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
boy0001/FastAsyncWorldedit
2,211
core/src/main/java/com/boydti/fawe/jnbt/anvil/MutableMCABackedBaseBlock.java
package com.boydti.fawe.jnbt.anvil; import com.boydti.fawe.FaweCache; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.blocks.BaseBlock; import javax.annotation.Nullable; /** * I'm aware this isn't OOP, but object creation is expensive */ public class MutableMCABackedBaseBlock extends BaseBlock { private MCAChunk chunk; private byte[] data; private byte[] ids; private int index; private int x; private int y; private int z; public MutableMCABackedBaseBlock() { super(0); } public void setChunk(MCAChunk chunk) { this.chunk = chunk; } public void setArrays(int layer) { ids = chunk.ids[layer]; data = chunk.data[layer]; } public MCAChunk getChunk() { return chunk; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setZ(int z) { this.z = z; } public void setIndex(int index) { this.index = index; } @Override public int getId() { return Byte.toUnsignedInt(ids[index]); } @Override public int getData() { if (!FaweCache.hasData(ids[index] & 0xFF)) { return 0; } else { int indexShift = index >> 1; if ((index & 1) == 0) { return data[indexShift] & 15; } else { return (data[indexShift] >> 4) & 15; } } } @Nullable @Override public CompoundTag getNbtData() { return chunk.getTile(x, y, z); } @Override public void setId(int id) { ids[index] = (byte) id; chunk.setModified(); } @Override public void setData(int value) { int indexShift = index >> 1; if ((index & 1) == 0) { data[indexShift] = (byte) (data[indexShift] & 240 | value & 15); } else { data[indexShift] = (byte) (data[indexShift] & 15 | (value & 15) << 4); } chunk.setModified(); } @Override public void setNbtData(@Nullable CompoundTag nbtData) { chunk.setTile(x, y, z, nbtData); chunk.setModified(); } }
0
0.873504
1
0.873504
game-dev
MEDIA
0.424889
game-dev
0.857366
1
0.857366
BOTLANNER/godot-gif
2,141
src/register_types.cpp
#include "register_types.h" #include "import_gif_to_animated_texture.h" #include "import_gif_to_sprite_frames.h" #include "gifmanager.h" #include "image_frames.h" #include <gdextension_interface.h> #include <godot_cpp/core/defs.hpp> #include <godot_cpp/core/class_db.hpp> #include <godot_cpp/classes/engine.hpp> #include <godot_cpp/classes/editor_plugin.hpp> #include <godot_cpp/godot.hpp> using namespace godot; static GifManager *GifMngrPtr; void register_gif_types(ModuleInitializationLevel p_level) { if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) { ClassDB::register_class<ImageFrames>(); ClassDB::register_class<GifManager>(); GifMngrPtr = memnew(GifManager); Engine::get_singleton()->register_singleton("GifManager", GifManager::get_singleton()); } if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) { ClassDB::register_class<GifToSpriteFramesImportPlugin>(); ClassDB::register_class<GifToSpriteFramesPlugin>(); EditorPlugins::add_by_type<GifToSpriteFramesPlugin>(); ClassDB::register_class<GifToAnimatedTextureImportPlugin>(); ClassDB::register_class<GifToAnimatedTexturePlugin>(); EditorPlugins::add_by_type<GifToAnimatedTexturePlugin>(); } } void unregister_gif_types(ModuleInitializationLevel p_level) { if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) { Engine::get_singleton()->unregister_singleton("GifManager"); memdelete(GifMngrPtr); } if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) { EditorPlugins::remove_by_type<GifToSpriteFramesPlugin>(); EditorPlugins::remove_by_type<GifToAnimatedTexturePlugin>(); } } extern "C" { // Initialization. GDExtensionBool GDE_EXPORT godot_gif_library_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, const GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization) { godot::GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization); init_obj.register_initializer(register_gif_types); init_obj.register_terminator(unregister_gif_types); init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE); return init_obj.init(); } }
0
0.906595
1
0.906595
game-dev
MEDIA
0.784845
game-dev
0.80138
1
0.80138
PowerNukkitX/PowerNukkitX
2,064
src/main/java/cn/nukkit/block/BlockTallGrass.java
package cn.nukkit.block; import cn.nukkit.block.property.CommonBlockProperties; import cn.nukkit.block.property.enums.DoublePlantType; import cn.nukkit.item.Item; import cn.nukkit.item.ItemID; import cn.nukkit.item.ItemTool; import cn.nukkit.item.enchantment.Enchantment; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; /** * @author Angelic47 (Nukkit Project) */ public class BlockTallGrass extends BlockDoublePlant { public static final BlockProperties PROPERTIES = new BlockProperties(TALL_GRASS, CommonBlockProperties.UPPER_BLOCK_BIT); @Override @NotNull public BlockProperties getProperties() { return PROPERTIES; } public BlockTallGrass() { this(PROPERTIES.getDefaultState()); } public BlockTallGrass(BlockState blockstate) { super(blockstate); } @Override public @NotNull DoublePlantType getDoublePlantType() { return DoublePlantType.GRASS; } @Override public String getName() { return "Tallgrass"; } @Override public int getBurnChance() { return 60; } @Override public int getBurnAbility() { return 100; } @Override public Item[] getDrops(Item item) { // https://minecraft.wiki/w/Fortune#Grass_and_ferns List<Item> drops = new ArrayList<>(2); if (item.isShears()) { drops.add(toItem()); } ThreadLocalRandom random = ThreadLocalRandom.current(); if (random.nextInt(8) == 0) { Enchantment fortune = item.getEnchantment(Enchantment.ID_FORTUNE_DIGGING); int fortuneLevel = fortune != null ? fortune.getLevel() : 0; int amount = fortuneLevel == 0 ? 1 : 1 + random.nextInt(fortuneLevel * 2); drops.add(Item.get(ItemID.WHEAT_SEEDS, 0, amount)); } return drops.toArray(Item.EMPTY_ARRAY); } @Override public int getToolType() { return ItemTool.TYPE_SHEARS; } }
0
0.906798
1
0.906798
game-dev
MEDIA
0.986416
game-dev
0.939327
1
0.939327
BananaFructa/Apec
1,598
src/main/java/Apec/Components/Gui/GuiIngame/GuiElements/GameModeText.java
package Apec.Components.Gui.GuiIngame.GuiElements; import Apec.ApecMain; import Apec.Components.Gui.GuiIngame.GUIComponent; import Apec.Components.Gui.GuiIngame.GUIComponentID; import Apec.DataInterpretation.DataExtractor; import Apec.Settings.SettingID; import Apec.Utils.ApecUtils; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.util.vector.Vector2f; public class GameModeText extends GUIComponent { private int StringWidth = 0; public GameModeText() { super(GUIComponentID.GAME_MODE_TEXT); } @Override public void draw(DataExtractor.PlayerStats ps, DataExtractor.ScoreBoardData sd, DataExtractor.OtherData od, ScaledResolution sr, boolean editingMode) { GlStateManager.pushMatrix(); GlStateManager.scale(scale, scale, scale); if (ApecMain.Instance.settingsManager.getSettingState(SettingID.USE_GAME_MODE_OUT_OF_BB) || editingMode) { Vector2f Pos = ApecUtils.scalarMultiply(this.getCurrentAnchorPoint(), oneOverScale); String s = sd.GameMode; StringWidth = mc.fontRendererObj.getStringWidth(s); ApecUtils.drawThiccBorderString(s, (int) (Pos.x) + 1, (int) (Pos.y) + 1, 0xffffffff); } GlStateManager.popMatrix(); } @Override public Vector2f getAnchorPointPosition() { return new Vector2f(g_sr.getScaledWidth() / 2f, g_sr.getScaledHeight() / 2f); } @Override public Vector2f getBoundingPoint() { return new Vector2f(StringWidth * scale, 11 * scale); } }
0
0.870406
1
0.870406
game-dev
MEDIA
0.732021
game-dev,graphics-rendering
0.938913
1
0.938913
DivineRPG/DivineRPG
1,531
src/main/java/divinerpg/loot_modifiers/JungleTempleChestModifier.java
package divinerpg.loot_modifiers; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import divinerpg.registries.*; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.neoforged.neoforge.common.loot.*; import org.jetbrains.annotations.NotNull; public class JungleTempleChestModifier extends LootModifier { public static final MapCodec<JungleTempleChestModifier> CODEC = RecordCodecBuilder.mapCodec(builder -> codecStart(builder).apply(builder, JungleTempleChestModifier::new)); protected JungleTempleChestModifier(LootItemCondition[] conditionsIn) { super(conditionsIn); } @Override @NotNull protected ObjectArrayList<ItemStack> doApply(ObjectArrayList<ItemStack> generatedLoot, LootContext context) { if(context.getRandom().nextFloat() <= .3){ ItemStack toAdd = new ItemStack(ItemRegistry.jungle_shards.get(), 1 + context.getRandom().nextInt(3)); generatedLoot.add(toAdd); } if(context.getRandom().nextFloat() <= .5){ ItemStack toAdd = new ItemStack(BlockRegistry.jungleSpiderPumpkin.asItem(), 1 + context.getRandom().nextInt(1)); generatedLoot.add(toAdd); } return generatedLoot; } @Override public MapCodec<? extends IGlobalLootModifier> codec() { return CODEC; } }
0
0.929374
1
0.929374
game-dev
MEDIA
0.997359
game-dev
0.958242
1
0.958242
OpenMITM/MuCuteRelay
3,112
Protocol/bedrock-codec/src/main/java/org/cloudburstmc/protocol/bedrock/packet/AddPlayerPacket.java
package org.cloudburstmc.protocol.bedrock.packet; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.cloudburstmc.math.vector.Vector3f; import org.cloudburstmc.protocol.bedrock.data.AbilityLayer; import org.cloudburstmc.protocol.bedrock.data.GameType; import org.cloudburstmc.protocol.bedrock.data.PlayerAbilityHolder; import org.cloudburstmc.protocol.bedrock.data.PlayerPermission; import org.cloudburstmc.protocol.bedrock.data.command.CommandPermission; import org.cloudburstmc.protocol.bedrock.data.entity.EntityDataMap; import org.cloudburstmc.protocol.bedrock.data.entity.EntityLinkData; import org.cloudburstmc.protocol.bedrock.data.entity.EntityProperties; import org.cloudburstmc.protocol.bedrock.data.inventory.ItemData; import org.cloudburstmc.protocol.common.PacketSignal; import java.util.List; import java.util.UUID; @Data @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class AddPlayerPacket implements BedrockPacket, PlayerAbilityHolder { private EntityDataMap metadata = new EntityDataMap(); private List<EntityLinkData> entityLinks = new ObjectArrayList<>(); private UUID uuid; private String username; private long uniqueEntityId; private long runtimeEntityId; private String platformChatId; private Vector3f position; private Vector3f motion; private Vector3f rotation; private ItemData hand; private AdventureSettingsPacket adventureSettings = new AdventureSettingsPacket(); private String deviceId; private int buildPlatform; private GameType gameType; /** * @since v534 */ private List<AbilityLayer> abilityLayers = new ObjectArrayList<>(); /** * @since v557 */ private final EntityProperties properties = new EntityProperties(); public void setUniqueEntityId(long uniqueEntityId) { this.uniqueEntityId = uniqueEntityId; this.adventureSettings.setUniqueEntityId(uniqueEntityId); } @Override public PlayerPermission getPlayerPermission() { return this.adventureSettings.getPlayerPermission(); } @Override public void setPlayerPermission(PlayerPermission playerPermission) { this.adventureSettings.setPlayerPermission(playerPermission); } @Override public CommandPermission getCommandPermission() { return this.adventureSettings.getCommandPermission(); } @Override public void setCommandPermission(CommandPermission commandPermission) { this.adventureSettings.setCommandPermission(commandPermission); } @Override public final PacketSignal handle(BedrockPacketHandler handler) { return handler.handle(this); } public BedrockPacketType getPacketType() { return BedrockPacketType.ADD_PLAYER; } @Override public AddPlayerPacket clone() { try { return (AddPlayerPacket) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } }
0
0.846011
1
0.846011
game-dev
MEDIA
0.815005
game-dev,networking
0.87664
1
0.87664
indiesoftby/defold-page-visibility
1,717
page_visibility/src/ext.hpp
#ifndef PAGE_VISIBILITY_EXTENSION_HPP #define PAGE_VISIBILITY_EXTENSION_HPP #include <dmsdk/sdk.h> // Lua headers #include <dmsdk/dlib/hashtable.h> namespace PageVisibilityExt { enum PageVisibilityState { STATE_UNKNOWN = -1, STATE_VISIBLE = 1, STATE_HIDDEN = 2, }; struct SetupLuaCallback { dmScript::LuaCallbackInfo* m_Callback; bool m_Once; SetupLuaCallback(dmScript::LuaCallbackInfo* callback, bool once) { if (!dmScript::IsCallbackValid(callback)) return; if (!dmScript::SetupCallback(callback)) { dmLogError("Failed to setup callback (has the calling script been destroyed?)"); dmScript::DestroyCallback(callback); return; } m_Callback = callback; m_Once = once; } bool Valid() { return m_Callback != NULL; } lua_State* GetLuaContext() { return dmScript::GetCallbackLuaContext(m_Callback); } void Call(lua_State* L, int nargs) { if (m_Callback) { dmScript::PCall(L, nargs + 1, 0); } else { lua_pop(L, nargs); } } ~SetupLuaCallback() { if (m_Callback) { dmScript::TeardownCallback(m_Callback); if (m_Once) { dmScript::DestroyCallback(m_Callback); } } } }; } // namespace PageVisibilityExt #endif // PAGE_VISIBILITY_EXTENSION_HPP
0
0.950548
1
0.950548
game-dev
MEDIA
0.61427
game-dev
0.907627
1
0.907627
mozeal/SDL_gui
3,778
SDL2/src/filesystem/cocoa/SDL_sysfilesystem.m
/* 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" #ifdef SDL_FILESYSTEM_COCOA /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* System dependent filesystem routines */ #include <Foundation/Foundation.h> #include <sys/stat.h> #include <sys/types.h> #include "SDL_error.h" #include "SDL_stdinc.h" #include "SDL_filesystem.h" char * SDL_GetBasePath(void) { @autoreleasepool { NSBundle *bundle = [NSBundle mainBundle]; const char* baseType = [[[bundle infoDictionary] objectForKey:@"SDL_FILESYSTEM_BASE_DIR_TYPE"] UTF8String]; const char *base = NULL; char *retval = NULL; if (baseType == NULL) { baseType = "resource"; } if (SDL_strcasecmp(baseType, "bundle")==0) { base = [[bundle bundlePath] fileSystemRepresentation]; } else if (SDL_strcasecmp(baseType, "parent")==0) { base = [[[bundle bundlePath] stringByDeletingLastPathComponent] fileSystemRepresentation]; } else { /* this returns the exedir for non-bundled and the resourceDir for bundled apps */ base = [[bundle resourcePath] fileSystemRepresentation]; } if (base) { const size_t len = SDL_strlen(base) + 2; retval = (char *) SDL_malloc(len); if (retval == NULL) { SDL_OutOfMemory(); } else { SDL_snprintf(retval, len, "%s/", base); } } return retval; }} char * SDL_GetPrefPath(const char *org, const char *app) { @autoreleasepool { if (!app) { SDL_InvalidParamError("app"); return NULL; } if (!org) { org = ""; } char *retval = NULL; NSArray *array = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); if ([array count] > 0) { /* we only want the first item in the list. */ NSString *str = [array objectAtIndex:0]; const char *base = [str fileSystemRepresentation]; if (base) { const size_t len = SDL_strlen(base) + SDL_strlen(org) + SDL_strlen(app) + 4; retval = (char *) SDL_malloc(len); if (retval == NULL) { SDL_OutOfMemory(); } else { char *ptr; if (*org) { SDL_snprintf(retval, len, "%s/%s/%s/", base, org, app); } else { SDL_snprintf(retval, len, "%s/%s/", base, app); } for (ptr = retval+1; *ptr; ptr++) { if (*ptr == '/') { *ptr = '\0'; mkdir(retval, 0700); *ptr = '/'; } } mkdir(retval, 0700); } } } return retval; }} #endif /* SDL_FILESYSTEM_COCOA */ /* vi: set ts=4 sw=4 expandtab: */
0
0.862925
1
0.862925
game-dev
MEDIA
0.52737
game-dev
0.824888
1
0.824888
jswigart/omni-bot
8,765
Installer/Files/dod/scripts/mapgoals/mapgoal_camp.gm
this.GoalType = "CAMP"; this.Version = 1; this.DefaultPriority = 0.5; this.MinRadius = 30; this.DefaultRenderRadius = 1024; this.MaxUsers_InUse(1); this.MaxUsers_InProgress(2); this.RolePriorityBonus = 0.01; ////////////////////////////////////////////////////////////////////////// // Couple callbacks to enforce additional constraints on property values. CheckMinCamp = function(var) { if(var <= this.MaxCampTime) { return true; } // returning any string is an error string return "MinCampTime must be <= MaxCampTime"; }; CheckMaxCamp = function(var) { if(var >= this.MinCampTime) { return true; } // returning any string is an error string return "MaxCampTime must be >= MinCampTime"; }; // Schema is a 'blueprint' of expected data that the goal needs to operate. // It is used for validating the expected fields and field values for correctness. this.Schema = Schema(); this.Schema.AimVectors = Validate.TableOf("vector3").Default({}); this.Schema.Weapons = Validate.TableOf("int").CheckValue(WEAPON).Default({}); this.Schema.Stance = Validate.Enum("stand","crouch","prone","peek").Default("stand"); this.Schema.MinCampTime = Validate.NumRange(0,9999).Default(10).CheckCallback(CheckMinCamp); this.Schema.MaxCampTime = Validate.NumRange(0,9999).Default(20).CheckCallback(CheckMaxCamp); ////////////////////////////////////////////////////////////////////////// this.InitNewGoal = function() { // the schema will initialize all fields with a default // so as long as everything has a default, we can let the schema // set up the data for us. this.Schema.Check(this); this.AimVectors[0] = GetLocalFacing(); localEnt = GetLocalEntity(); if (GetEntFlags(localEnt, ENTFLAG.CROUCHED)) { this.Stance = "crouch"; } else if (GetEntFlags(localEnt, ENTFLAG.PRONE)) { this.Stance = "prone"; } this.Radius = 32; this.DisableCM = 0; }; ////////////////////////////////////////////////////////////////////////// this.UpgradeVersion = function(Props) { if(Props.OldType=="attack" || Props.OldType=="defend" || Props.OldType=="snipe") { //Props.OldType = null; Props.Version = 1; Props.AimVectors = { ToVector(Props.Facing) }; this.Schema.Check(Props); // cs: can't do this since it is unreliable. constructable bridges for example //this.SetPosition( GroundPoint(this.GetPosition()) ); // offset instead this.SetPosition(this.GetPosition()); this.SetBounds(Vec3(-5,-5,0),Vec3(5,5,96)); return; } // version 0 is string,string key/values from the old waypoint format if(Props.Version==0) { // Version 1 Schema, upgrade from waypoint format Props.Version = 1; Props.AimVectors = { ToVector(Props.Facing) }; this.Schema.Check(Props); // cs: can't do this since it is unreliable. constructable bridges for example //this.SetPosition( GroundPoint(this.GetPosition()) ); this.SetBounds(Vec3(-5,-5,0),Vec3(5,5,96)); } else if(Props.Version == this.Version) { this.Schema.Check(Props); this.AimVectors = Props.AimVectors; this.Stance = Props.Stance; this.MinCampTime = Props.MinCampTime; this.MaxCampTime = Props.MaxCampTime; // convert from indexed table to weapon id keyed table this.Weapons = Props.Weapons; this.LimitToWeapon(this.Weapons); if ( tableCount(this.Weapons) > 0 ) { this.DefaultPriority += 0.2; } if ( Props.DisableCM ) { this.DisableCM = Props.DisableCM; } else { this.DisableCM = 0; } // detect 0 facing vectors if ( typeId(Props.AimVectors) == 6 ) { foreach(id and facing in Props.AimVectors ) { if ( facing.IsZero() ) { Props.AimVectors[id] = null; // clear it Util.MapDebugPrint(this.GetName() + " facing " + id + " is zero!", true); } } } if(!this.Schema.Check(this)) { this.DisableGoal(true); } } }; ////////////////////////////////////////////////////////////////////////// this.Render = function(editMode) { offset = Vector3(0,0,0); offset2 = Vector3(0,0,64); stanceOffset = Vector3(0,0,0); while(this.RenderGoal == true) { goalBasePos = this.GetPosition(); goalPos = goalBasePos + offset2; if(this.ExtraDebugText==null) { this.ExtraDebugText = ""; foreach(wpnId and b in this.Weapons) { if(this.ExtraDebugText != "") { this.ExtraDebugText += ","; } else { this.ExtraDebugText += "Weapon: "; } this.ExtraDebugText += Util.WeaponName(wpnId); } // newline if it wrote weapons if(tableCount(this.Weapons) > 0) { this.ExtraDebugText += "\n"; } this.ExtraDebugText += format("Stance: %s\n",this.Stance); this.ExtraDebugText += format("CampTime: %g to %g secs.\n",ToFloat(this.MinCampTime),ToFloat(this.MaxCampTime)); if ( this.DisableCM ) { this.ExtraDebugText += format("DisableCM: %d", this.DisableCM); } } if ( this.Stance == "crouch" ) { stanceOffset = Vector3(0,0,-24); } else if ( this.Stance == "prone" ) { stanceOffset = Vector3(0,0,-50); } this.RenderDefault(); if(this.IsDisabled()) { DrawLine(goalPos,goalBasePos,COLOR.RED,2); } else { DrawLine(goalPos,goalBasePos,COLOR.GREEN,2); } if ( typeId(this.AimVectors) == 6 ) { foreach ( id and face in this.AimVectors ) { DrawArrow(goalPos+stanceOffset,goalPos+stanceOffset+face*32,COLOR.BLUE,2); DrawText3d(goalPos+stanceOffset+face*32,ToString(id),COLOR.WHITE,2,512); } } sleep(2); } }; ////////////////////////////////////////////////////////////////////////// this.SaveToTable = function(SaveTable) { // save the goal specific properties SaveTable.AimVectors = this.AimVectors; SaveTable.Stance = this.Stance; SaveTable.MaxCampTime = this.MaxCampTime; SaveTable.MinCampTime = this.MinCampTime; SaveTable.Weapons = this.Weapons; SaveTable.DisableCM = this.DisableCM; }; ////////////////////////////////////////////////////////////////////////// this.Help = function() { print(this.GoalType,"goal, version",this.Version); print("Requires:"); print(" facing - Direction the bot should face"); print("Optional:"); print(" stance - stand, crouch, prone, peek"); print(" weapon - only this weapon is usable here, supports multiple"); print(" mincamptime - minimum time a bot should camp at the goal"); print(" maxcamptime - maximum time a bot should camp at the goal"); print(" disablecm - disable combat movement at this goal"); }; ////////////////////////////////////////////////////////////////////////// this.SetProperty = function(property, value) { proplower = property.Lower(0); switch(proplower) { case "facing": { if ( value == "clearall" || value == "clear" ) { tableClear(this.AimVectors); } else { i = ToInt(value); if ( typeId(i) == 1) { // make em add sequentially n = tableCount(this.AimVectors); if ( i < 0 || i > n ) { i = n; } playerFace = GetLocalFacing(); this.AimVectors[ i ] = playerFace; print("Facing",i,"set to",playerFace); } else { print(this.GoalType, ": Invalid facing index, expecting int"); } } } case "stance": // crouch, prone, default stand { this.Stance = value; } case "weapon": // limit to any number of weapons { if ( value == "clearall" || value == "clear" ) { tableClear(this.Weapons); } else { weap = Util.WeaponNameToId(value); if ( weap != -1 ) { // use the weapon id as the key this.Weapons[ weap ] = 1; } else { print(this.GoalType, ": Invalid Weapon Name" ); print( "Valid Weapon Names: "); Util.ListTableMembers(WEAPON); } } this.LimitToWeapon(this.Weapons); } case "snipe": { this.Weapons = Util.IndexedSniperWeapons; this.LimitToWeapon(this.Weapons); print("camp goal is now sniper weapon limited"); } case "mincamptime": { v = ToFloat(value); if(this.Schema.MinCampTime.CheckPrintErrors(this,v)) { this.MinCampTime = v; } } case "maxcamptime": { v = ToFloat(value); if(this.Schema.MaxCampTime.CheckPrintErrors(this,v)) { this.MaxCampTime = v; } } case "disablecm": { i = ToInt(value); if ( typeId(i) == 1) { this.DisableCM = i; } else { print("disablecm requires integer"); } } default: { print(this.GoalType, ": Invalid property:", property); return; } } // null the debug text so it will be rebuilt this.ExtraDebugText = null; }; ////////////////////////////////////////////////////////////////////////// global CreateGui = function(object, guidef) { }; ////////////////////////////////////////////////////////////////////////// this.HudDisplay = function(window) { // Create Gui elements to edit Schema properties this.CreateGuiFromSchema(this.Schema); };
0
0.816978
1
0.816978
game-dev
MEDIA
0.924572
game-dev
0.901287
1
0.901287
DK22Pac/plugin-sdk
2,317
plugin_vc/game_vc/CClumpModelInfo.h
/* Plugin-SDK (Grand Theft Auto Vice City) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CBaseModelInfo.h" #include "RenderWare.h" #include "RwObjectNameIdAssocation.h" #include "NodeName.h" struct FrameSearchData { char const *name; RwFrame *result; }; VALIDATE_SIZE(FrameSearchData, 8); class CClumpModelInfo : public CBaseModelInfo { public: RpClump *m_pClump; union { char *m_pszAnimFileName; int m_nAnimFileIndex; }; //vtable void SetClump(RpClump* clump); //funcs CClumpModelInfo(); CClumpModelInfo(plugin::dummy_func_t) {} static void FillFrameArray(RpClump* clump, RwFrame** frames); static RwFrame* FindFrameFromIdCB(RwFrame* frame, void* searchData); static RwFrame* FindFrameFromNameCB(RwFrame* frame, void* searchData); static RwFrame* FindFrameFromNameWithoutIdCB(RwFrame* frame, void* searchData); static RwFrame* GetFrameFromId(RpClump* clump, int id); static void SetAtomicRendererCB(RpAtomic* atomic, void* renderFunc); void SetFrameIds(RwObjectNameIdAssocation* data); static RwFrame* FindFrameFromNameCB_Fixed(RwFrame* frame, void* data) { auto searchData = reinterpret_cast<FrameSearchData *>(data); if (!_stricmp(GetFrameNodeName(frame), searchData->name)) { searchData->result = frame; return nullptr; } RwFrameForAllChildren(frame, FindFrameFromNameCB_Fixed, data); if (searchData->result) return nullptr; return frame; } static RwFrame *GetFrameFromName(RpClump *clump, char const *name) { FrameSearchData searchData; searchData.name = name; searchData.result = nullptr; RwFrameForAllChildren(reinterpret_cast<RwFrame *>(clump->object.parent), FindFrameFromNameCB_Fixed, &searchData); return searchData.result; } protected: CClumpModelInfo(const CClumpModelInfo &) {}; CClumpModelInfo &operator=(const CClumpModelInfo &) { return *this; }; }; VALIDATE_SIZE(CClumpModelInfo, 0x30); struct ClumpModelStore { unsigned int m_nCount; CClumpModelInfo m_sObject[5]; ~ClumpModelStore(); };
0
0.720343
1
0.720343
game-dev
MEDIA
0.521631
game-dev,graphics-rendering
0.635939
1
0.635939
openfl/openfl
41,740
src/openfl/events/Event.hx
package openfl.events; #if !flash import openfl.utils.Object; #if openfl_pool_events import openfl.utils.ObjectPool; #end /** The Event class is used as the base class for the creation of Event objects, which are passed as parameters to event listeners when an event occurs. The properties of the Event class carry basic information about an event, such as the event's type or whether the event's default behavior can be canceled. For many events, such as the events represented by the Event class constants, this basic information is sufficient. Other events, however, may require more detailed information. Events associated with a mouse click, for example, need to include additional information about the location of the click event and whether any keys were pressed during the click event. You can pass such additional information to event listeners by extending the Event class, which is what the MouseEvent class does. The OpenFL API defines several Event subclasses for common events that require additional information. Events associated with each of the Event subclasses are described in the documentation for each class. The methods of the Event class can be used in event listener functions to affect the behavior of the event object. Some events have an associated default behavior. For example, the `doubleClick` event has an associated default behavior that highlights the word under the mouse pointer at the time of the event. Your event listener can cancel this behavior by calling the `preventDefault()` method. You can also make the current event listener the last one to process an event by calling the `stopPropagation()` or `stopImmediatePropagation()` method. Other sources of information include: * A useful description about the timing of events, code execution, and rendering at runtime in Ted Patrick's blog entry: <a [Flash Player Mental Model - The Elastic Racetrack](http://tedpatrick.com/2005/07/19/flash-player-mental-model-the-elastic-racetrack/). * A blog entry by Johannes Tacskovics about the timing of frame events, such as ENTER_FRAME, EXIT_FRAME: [The MovieClip Lifecycle](http://web.archive.org/web/20110623195412/http://blog.johannest.com:80/2009/06/15/the-movieclip-life-cycle-revisited-from-event-added-to-event-removed_from_stage/). * An article by Trevor McCauley about the order of ActionScript operations: [Order of Operations in ActionScript](http://web.archive.org/web/20171009141202/http://www.senocular.com:80/flash/tutorials/orderofoperations/). * A blog entry by Matt Przybylski on creating custom events: [AS3: Custom Events](http://evolve.reintroducing.com/2007/10/23/as3/as3-custom-events/). @see [Basics of handling events](https://books.openfl.org/openfl-developers-guide/handling-events/basics-of-handling-events.html) @see [The event flow](https://books.openfl.org/openfl-developers-guide/handling-events/the-event-flow.html) @see [Event objects](https://books.openfl.org/openfl-developers-guide/handling-events/event-objects.html) @see [Event listeners](https://books.openfl.org/openfl-developers-guide/handling-events/event-listeners.html) @see [Handling events for display objects](https://books.openfl.org/openfl-developers-guide/display-programming/working-with-display-objects/handling-events-for-display-objects.html) **/ #if !openfl_debug @:fileXml('tags="haxe,release"') @:noDebug #end class Event { /** The `ACTIVATE` constant defines the value of the `type` property of an `activate` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to any potential targets, whether the target is on the display list or not. AIR for TV devices never automatically dispatch this event. You can, however, dispatch it manually. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any DisplayObject instance with a listener registered for the `activate` event. | **/ public static inline var ACTIVATE:EventType<Event> = "activate"; /** The `Event.ADDED` constant defines the value of the `type` property of an `added` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `true` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The DisplayObject instance being added to the display list. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var ADDED:EventType<Event> = "added"; /** The `Event.ADDED_TO_STAGE` constant defines the value of the `type` property of an `addedToStage` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The DisplayObject instance being added to the on stage display list, either directly or through the addition of a sub tree in which the DisplayObject instance is contained. If the DisplayObject instance is being directly added, the `added` event occurs before this event. | **/ public static inline var ADDED_TO_STAGE:EventType<Event> = "addedToStage"; // @:noCompletion @:dox(hide) @:require(flash15) public static var BROWSER_ZOOM_CHANGE:String; /** The `Event.CANCEL` constant defines the value of the `type` property of a `cancel` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | A reference to the object on which the operation is canceled. | **/ public static inline var CANCEL:EventType<Event> = "cancel"; /** The `Event.CHANGE` constant defines the value of the `type` property of a `change` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `true` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object that has had its value modified. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var CHANGE:EventType<Event> = "change"; // @:noCompletion @:dox(hide) public static var CHANNEL_MESSAGE:String; // @:noCompletion @:dox(hide) public static var CHANNEL_STATE:String; /** The `Event.CLEAR` constant defines the value of the `type` property of a `clear` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any InteractiveObject instance with a listener registered for the `clear` event. | **Note:** TextField objects do _not_ dispatch `clear`, `copy`, `cut`, `paste`, or `selectAll` events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands (or their keyboard equivalents) does not generate `clear`, `copy`, `cut`, `paste`, or `selectAll` events. However, other classes that extend the InteractiveObject class, including components built using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus. **/ public static inline var CLEAR:EventType<Event> = "clear"; /** The `Event.CLOSING` constant defines the value of the `type` property of a `closing` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `true`; canceling this event object stops the close operation. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object whose connection has been closed. | **/ public static inline var CLOSING:EventType<Event> = "closing"; /** The `Event.CLOSE` constant defines the value of the `type` property of a `close` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object whose connection has been closed. | **/ public static inline var CLOSE:EventType<Event> = "close"; /** The `Event.COMPLETE` constant defines the value of the `type` property of a `complete` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The network object that has completed loading. | **/ public static inline var COMPLETE:EventType<Event> = "complete"; /** The `Event.CONNECT` constant defines the value of the `type` property of a `connect` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The Socket or XMLSocket object that has established a network connection. | **/ public static inline var CONNECT:EventType<Event> = "connect"; /** The `Event.CONTEXT3D_CREATE` constant defines the value of the type property of a `context3Dcreate` event object. This event is raised only by Stage3D objects in response to either a call to `Stage3D.requestContext3D` or in response to an OS triggered reset of the Context3D bound to the Stage3D object. Inspect the `Stage3D.context3D` property to get the newly created Context3D object. **/ public static inline var CONTEXT3D_CREATE:EventType<Event> = "context3DCreate"; /** Defines the value of the `type` property of a `copy` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any InteractiveObject instance with a listener registered for the `copy` event. | **Note:** TextField objects do _not_ dispatch `clear`, `copy`, `cut`, `paste`, or `selectAll` events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands (or their keyboard equivalents) does not generate `clear`, `copy`, `cut`, `paste`, or `selectAll` events. However, other classes that extend the InteractiveObject class, including components built using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus. **/ public static inline var COPY:EventType<Event> = "copy"; /** Defines the value of the `type` property of a `cut` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any InteractiveObject instance with a listener registered for the `cut` event. | **Note:** TextField objects do _not_ dispatch `clear`, `copy`, `cut`, `paste`, or `selectAll` events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands (or their keyboard equivalents) does not generate `clear`, `copy`, `cut`, `paste`, or `selectAll` events. However, other classes that extend the InteractiveObject class, including components built using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus. **/ public static inline var CUT:EventType<Event> = "cut"; /** The `Event.DEACTIVATE` constant defines the value of the `type` property of a `deactivate` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to any potential targets, whether the target is on the display list or not. AIR for TV devices never automatically dispatch this event. You can, however, dispatch it manually. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any DisplayObject instance with a listener registered for the `deactivate` event. | **/ public static inline var DEACTIVATE:EventType<Event> = "deactivate"; /** The `Event.ENTER_FRAME` constant defines the value of the `type` property of an `enterFrame` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to any potential targets, whether the target is on the display list or not. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any DisplayObject instance with a listener registered for the `enterFrame` event. | **/ public static inline var ENTER_FRAME:EventType<Event> = "enterFrame"; /** The `Event.EXIT_FRAME` constant defines the value of the `type` property of an `exitFrame` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to any potential targets, whether the target is on the display list or not. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any DisplayObject instance with a listener registered for the `enterFrame` event. | **/ public static inline var EXIT_FRAME:EventType<Event> = "exitFrame"; /** The `Event.EXITING` constant defines the value of the `type` property of an `exiting` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `true`; canceling this event object stops the exit operation. | | `currentTarget` | The NativeApplication object. | | `target` | The NativeApplication object. | **/ public static inline var EXITING:EventType<Event> = "exiting"; /** The `Event.FRAME_CONSTRUCTED` constant defines the value of the `type` property of an `frameConstructed` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to any potential targets, whether the target is on the display list or not. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any DisplayObject instance with a listener registered for the `frameConstructed` event. | **/ public static inline var FRAME_CONSTRUCTED:EventType<Event> = "frameConstructed"; /** The `Event.FRAME_LABEL` constant defines the value of the type property of a `frameLabel` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to FrameLabel objects. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The FrameLabel object that is actively processing the Event object with an event listener. | | `target` | Any FrameLabel instance with a listener registered for the frameLabel event. | **/ public static inline var FRAME_LABEL:EventType<Event> = "frameLabel"; /** The `Event.FULL_SCREEN` constant defines the value of the `type` property of a `fullScreen` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The Stage object. | **/ public static inline var FULLSCREEN:EventType<Event> = "fullScreen"; /** The `Event.ID3` constant defines the value of the `type` property of an `id3` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The Sound object loading the MP3 for which ID3 data is now available. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var ID3:EventType<Event> = "id3"; /** The `Event.INIT` constant defines the value of the `type` property of an `init` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The LoaderInfo object associated with the SWF file being loaded. | **/ public static inline var INIT:EventType<Event> = "init"; /** The `Event.MOUSE_LEAVE` constant defines the value of the `type` property of a `mouseLeave` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The Stage object. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var MOUSE_LEAVE:EventType<Event> = "mouseLeave"; /** The `Event.OPEN` constant defines the value of the `type` property of an `open` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The network object that has opened a connection. | **/ public static inline var OPEN:EventType<Event> = "open"; /** The `Event.PASTE` constant defines the value of the `type` property of a `paste` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any InteractiveObject instance with a listener registered for the `paste` event. | **Note:** TextField objects do _not_ dispatch `clear`, `copy`, `cut`, `paste`, or `selectAll` events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands (or their keyboard equivalents) does not generate `clear`, `copy`, `cut`, `paste`, or `selectAll` events. However, other classes that extend the InteractiveObject class, including components built using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus. **/ public static inline var PASTE:EventType<Event> = "paste"; /** The `Event.REMOVED` constant defines the value of the `type` property of a `removed` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `true` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The DisplayObject instance to be removed from the display list. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var REMOVED:EventType<Event> = "removed"; /** The `Event.REMOVED_FROM_STAGE` constant defines the value of the `type` property of a `removedFromStage` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The DisplayObject instance being removed from the on stage display list, either directly or through the removal of a sub tree in which the DisplayObject instance is contained. If the DisplayObject instance is being directly removed, the `removed` event occurs before this event. | **/ public static inline var REMOVED_FROM_STAGE:EventType<Event> = "removedFromStage"; /** The `Event.RENDER` constant defines the value of the `type` property of a `render` event object. **Note:** This event has neither a "capture phase" nor a "bubble phase", which means that event listeners must be added directly to any potential targets, whether the target is on the display list or not. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; the default behavior cannot be canceled. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any DisplayObject instance with a listener registered for the `render` event. | **/ public static inline var RENDER:EventType<Event> = "render"; /** The `Event.RESIZE` constant defines the value of the `type` property of a `resize` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The Stage object. | **/ public static inline var RESIZE:EventType<Event> = "resize"; /** The `Event.SCROLL` constant defines the value of the `type` property of a `scroll` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The TextField object that has been scrolled. The `target` property is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var SCROLL:EventType<Event> = "scroll"; /** The `Event.SELECT` constant defines the value of the `type` property of a `select` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object on which an item has been selected. | **/ public static inline var SELECT:EventType<Event> = "select"; /** The `Event.SELECT_ALL` constant defines the value of the `type` property of a `selectAll` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | Any InteractiveObject instance with a listener registered for the `selectAll` event. | **Note:** TextField objects do _not_ dispatch `clear`, `copy`, `cut`, `paste`, or `selectAll` events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands (or their keyboard equivalents) does not generate `clear`, `copy`, `cut`, `paste`, or `selectAll` events. However, other classes that extend the InteractiveObject class, including components built using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus. **/ public static inline var SELECT_ALL:EventType<Event> = "selectAll"; /** The `Event.SOUND_COMPLETE` constant defines the value of the `type` property of a `soundComplete` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The SoundChannel object in which a sound has finished playing. | **/ public static inline var SOUND_COMPLETE:EventType<Event> = "soundComplete"; /** The `Event.TAB_CHILDREN_CHANGE` constant defines the value of the `type` property of a `tabChildrenChange` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `true` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object whose tabChildren flag has changed. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var TAB_CHILDREN_CHANGE:EventType<Event> = "tabChildrenChange"; /** The `Event.TAB_ENABLED_CHANGE` constant defines the value of the `type` property of a `tabEnabledChange` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `true` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The InteractiveObject whose tabEnabled flag has changed. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var TAB_ENABLED_CHANGE:EventType<Event> = "tabEnabledChange"; /** The `Event.TAB_INDEX_CHANGE` constant defines the value of the `type` property of a `tabIndexChange` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `true` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The object whose tabIndex has changed. The `target` is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ public static inline var TAB_INDEX_CHANGE:EventType<Event> = "tabIndexChange"; /** The `Event.TEXTURE_READY` constant defines the value of the type property of a `textureReady` event object. This event is dispatched by Texture and CubeTexture objects to signal the completion of an asynchronous upload. Request an asynchronous upload by using the `uploadCompressedTextureFromByteArray()` method on Texture or CubeTexture. This event neither bubbles nor is cancelable. **/ public static inline var TEXTURE_READY:EventType<Event> = "textureReady"; #if false /** The `Event.TEXT_INTERACTION_MODE_CHANGE` constant defines the value of the `type` property of a `interaction mode` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The TextField object whose interaction mode property is changed. For example on Android, one can change the interaction mode to SELECTION via context menu. The `target` property is not always the object in the display list that registered the event listener. Use the `currentTarget` property to access the object in the display list that is currently processing the event. | **/ // @:noCompletion @:dox(hide) @:require(flash11) public static var TEXT_INTERACTION_MODE_CHANGE:String; #end /** The `Event.UNLOAD` constant defines the value of the `type` property of an `unload` event object. This event has the following properties: | Property | Value | | --- | --- | | `bubbles` | `false` | | `cancelable` | `false`; there is no default behavior to cancel. | | `currentTarget` | The object that is actively processing the Event object with an event listener. | | `target` | The LoaderInfo object associated with the SWF file being unloaded or replaced. | **/ public static inline var UNLOAD:EventType<Event> = "unload"; // @:noCompletion @:dox(hide) public static var VIDEO_FRAME:String; // @:noCompletion @:dox(hide) public static var WORKER_STATE:String; /** Indicates whether an event is a bubbling event. If the event can bubble, this value is `true`; otherwise it is `false`. When an event occurs, it moves through the three phases of the event flow: the capture phase, which flows from the top of the display list hierarchy to the node just before the target node; the target phase, which comprises the target node; and the bubbling phase, which flows from the node subsequent to the target node back up the display list hierarchy. Some events, such as the `activate` and `unload` events, do not have a bubbling phase. The `bubbles` property has a value of `false` for events that do not have a bubbling phase. **/ public var bubbles(default, null):Bool; /** Indicates whether the behavior associated with the event can be prevented. If the behavior can be canceled, this value is `true`; otherwise it is `false`. **/ public var cancelable(default, null):Bool; /** The object that is actively processing the Event object with an event listener. For example, if a user clicks an OK button, the current target could be the node containing that button or one of its ancestors that has registered an event listener for that event. **/ public var currentTarget(default, null):Object; /** The current phase in the event flow. This property can contain the following numeric values: * The capture phase(`EventPhase.CAPTURING_PHASE`). * The target phase(`EventPhase.AT_TARGET`). * The bubbling phase(`EventPhase.BUBBLING_PHASE`). **/ public var eventPhase(default, null):EventPhase; /** The event target. This property contains the target node. For example, if a user clicks an OK button, the target node is the display list node containing that button. **/ public var target(default, null):Object; /** The type of event. The type is case-sensitive. **/ public var type(default, null):String; #if openfl_pool_events @:noCompletion private static var __pool:ObjectPool<Event> = new ObjectPool<Event>(function() return new Event(null), function(event) event.__init()); #end @:noCompletion private var __isCanceled:Bool; @:noCompletion private var __isCanceledNow:Bool; @:noCompletion private var __preventDefault:Bool; /** Creates an Event object to pass as a parameter to event listeners. @param type The type of the event, accessible as `Event.type`. @param bubbles Determines whether the Event object participates in the bubbling stage of the event flow. The default value is `false`. @param cancelable Determines whether the Event object can be canceled. The default values is `false`. **/ public function new(type:String, bubbles:Bool = false, cancelable:Bool = false) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; eventPhase = EventPhase.AT_TARGET; } /** Duplicates an instance of an Event subclass. Returns a new Event object that is a copy of the original instance of the Event object. You do not normally call `clone()`; the EventDispatcher class calls it automatically when you redispatch an event - that is, when you call `dispatchEvent(event)` from a handler that is handling `event`. The new Event object includes all the properties of the original. When creating your own custom Event class, you must override the inherited `Event.clone()` method in order for it to duplicate the properties of your custom class. If you do not set all the properties that you add in your event subclass, those properties will not have the correct values when listeners handle the redispatched event. In this example, `PingEvent` is a subclass of `Event` and therefore implements its own version of `clone()`. @return A new Event object that is identical to the original. **/ public function clone():Event { var event = new Event(type, bubbles, cancelable); event.eventPhase = eventPhase; event.target = target; event.currentTarget = currentTarget; return event; } /** A utility function for implementing the `toString()` method in custom OpenFL Event classes. Overriding the `toString()` method is recommended, but not required. ```haxe class PingEvent extends Event { var URL:String; public function new() { super(); } public override function toString():String { return formatToString("PingEvent", "type", "bubbles", "cancelable", "eventPhase", "URL"); } } ``` @param className The name of your custom Event class. In the previous example, the `className` parameter is `PingEvent`. @return The name of your custom Event class and the String value of your `...arguments` parameter. **/ public function formatToString(className:String, p1:String = null, p2:String = null, p3:String = null, p4:String = null, p5:String = null):String { var parameters:Array<String> = []; if (p1 != null) parameters.push(p1); if (p2 != null) parameters.push(p2); if (p3 != null) parameters.push(p3); if (p4 != null) parameters.push(p4); if (p5 != null) parameters.push(p5); return Reflect.callMethod(this, __formatToString, [className, parameters]); } /** Checks whether the `preventDefault()` method has been called on the event. If the `preventDefault()` method has been called, returns `true`; otherwise, returns `false`. @return If `preventDefault()` has been called, returns `true`; otherwise, returns `false`. **/ public function isDefaultPrevented():Bool { return __preventDefault; } /** Cancels an event's default behavior if that behavior can be canceled. Many events have associated behaviors that are carried out by default. For example, if a user types a character into a text field, the default behavior is that the character is displayed in the text field. Because the `TextEvent.TEXT_INPUT` event's default behavior can be canceled, you can use the `preventDefault()` method to prevent the character from appearing. An example of a behavior that is not cancelable is the default behavior associated with the Event.REMOVED event, which is generated whenever Flash Player is about to remove a display object from the display list. The default behavior (removing the element) cannot be canceled, so the `preventDefault()` method has no effect on this default behavior. You can use the `Event.cancelable` property to check whether you can prevent the default behavior associated with a particular event. If the value of `Event.cancelable` is true, then `preventDefault()` can be used to cancel the event; otherwise, `preventDefault()` has no effect. **/ public function preventDefault():Void { if (cancelable) { __preventDefault = true; } } /** Prevents processing of any event listeners in the current node and any subsequent nodes in the event flow. This method takes effect immediately, and it affects event listeners in the current node. In contrast, the `stopPropagation()` method doesn't take effect until all the event listeners in the current node finish processing. **Note:** This method does not cancel the behavior associated with this event; see `preventDefault()` for that functionality. **/ public function stopImmediatePropagation():Void { __isCanceled = true; __isCanceledNow = true; } /** Prevents processing of any event listeners in nodes subsequent to the current node in the event flow. This method does not affect any event listeners in the current node (`currentTarget`). In contrast, the `stopImmediatePropagation()` method prevents processing of event listeners in both the current node and subsequent nodes. Additional calls to this method have no effect. This method can be called in any phase of the event flow. **Note:** This method does not cancel the behavior associated with this event; see `preventDefault()` for that functionality. **/ public function stopPropagation():Void { __isCanceled = true; } /** Returns a string containing all the properties of the Event object. The string is in the following format: `[Event type=_value_ bubbles=_value_ cancelable=_value_]` @return A string containing all the properties of the Event object. **/ public function toString():String { return __formatToString("Event", ["type", "bubbles", "cancelable"]); } @:noCompletion private function __formatToString(className:String, parameters:Array<String>):String { // TODO: Make this a macro function, and handle at compile-time, with rest parameters? var output = '[$className'; var arg:Dynamic = null; for (param in parameters) { arg = Reflect.field(this, param); if ((arg is String)) { output += ' $param="$arg"'; } else { output += ' $param=$arg'; } } output += "]"; return output; } @:noCompletion private function __init():Void { // type = null; target = null; currentTarget = null; bubbles = false; cancelable = false; eventPhase = AT_TARGET; __isCanceled = false; __isCanceledNow = false; __preventDefault = false; } } #else typedef Event = flash.events.Event; #end
0
0.924211
1
0.924211
game-dev
MEDIA
0.581829
game-dev
0.789544
1
0.789544
magefree/mage
2,569
Mage.Sets/src/mage/cards/c/CrownHunterHireling.java
package mage.cards.c; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.RestrictionEffect; import mage.abilities.effects.common.BecomesMonarchSourceEffect; import mage.abilities.hint.common.MonarchHint; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; import mage.game.Game; import mage.game.permanent.Permanent; import java.util.UUID; /** * @author LevelX2 */ public final class CrownHunterHireling extends CardImpl { public CrownHunterHireling(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{R}"); this.subtype.add(SubType.OGRE); this.subtype.add(SubType.MERCENARY); this.power = new MageInt(4); this.toughness = new MageInt(4); // When Crown-Hunter Hireling enters the battlefield, you become the monarch. this.addAbility(new EntersBattlefieldTriggeredAbility(new BecomesMonarchSourceEffect()).addHint(MonarchHint.instance)); // Crown-Hunter Hireling can't attack unless defending player is the monarch. this.addAbility(new SimpleStaticAbility(new CrownHunterHirelingCantAttackEffect())); } private CrownHunterHireling(final CrownHunterHireling card) { super(card); } @Override public CrownHunterHireling copy() { return new CrownHunterHireling(this); } } class CrownHunterHirelingCantAttackEffect extends RestrictionEffect { CrownHunterHirelingCantAttackEffect() { super(Duration.WhileOnBattlefield); staticText = "{this} can't attack unless defending player is the monarch"; } private CrownHunterHirelingCantAttackEffect(final CrownHunterHirelingCantAttackEffect effect) { super(effect); } @Override public boolean applies(Permanent permanent, Ability source, Game game) { return permanent.getId().equals(source.getSourceId()); } @Override public boolean canAttack(Permanent attacker, UUID defenderId, Ability source, Game game, boolean canUseChooseDialogs) { if (defenderId == null) { return true; } return defenderId.equals(game.getMonarchId()); } @Override public CrownHunterHirelingCantAttackEffect copy() { return new CrownHunterHirelingCantAttackEffect(this); } }
0
0.778269
1
0.778269
game-dev
MEDIA
0.755987
game-dev
0.934449
1
0.934449
google/xrblocks
5,258
demos/gemini-xrobject/TriggerManager.js
import * as THREE from 'three'; import * as xb from 'xrblocks'; function easeInQuad(x) { return x * x; } function easeOutQuint(x) { return 1 - Math.pow(1 - x, 5); } export class TriggerManager extends xb.Script { constructor(onTrigger, { triggerDelay = 1000, triggerCooldownDuration = 5000, pulseAnimationDuration = 400, visualizerColor = 0x4970ff, visualizerRadius = 0.028, } = {}) { super(); this.onTrigger = onTrigger; this.triggerDelay = triggerDelay; this.triggerCooldownDuration = triggerCooldownDuration; this.pulseAnimationDuration = pulseAnimationDuration; this.visualizerColor = visualizerColor; this.visualizerRadius = visualizerRadius; this.triggerTimeout = null; this.lastTriggerTime = 0; this.isTriggerOnCooldown = false; this.activeHandedness = null; this.triggerStartTime = 0; this.isPulsing = false; this.pulseStartTime = 0; this.outerVisualizer = null; this.innerVisualizer = null; this.sphereGeometry = new THREE.SphereGeometry(this.visualizerRadius, 32, 32); this.outerMaterialOpacity = 0.3; this.outerMaterial = new THREE.MeshBasicMaterial({ color: this.visualizerColor, transparent: true, opacity: this.outerMaterialOpacity, depthWrite: false, }); this.innerMaterialOpacity = 0.6; this.innerMaterial = new THREE.MeshBasicMaterial({ color: this.visualizerColor, transparent: true, opacity: this.innerMaterialOpacity, depthWrite: false, }); } onSelectStart(event) { if (event.data && event.data.handedness) { this.activeHandedness = event.data.handedness; } else { console.warn('Could not determine handedness from onSelectStart event.'); this.activeHandedness = null; } } onSelecting(event) { if (this.isPulsing) { this.updateVisualizers(); return; } if (this.triggerTimeout === null) { if (this.isTriggerOnCooldown) return; if (!this.activeHandedness || !xb.core.input || !xb.core.input.hands) return; const handIndex = this.activeHandedness === 'right' ? 1 : 0; const hand = xb.core.input.hands[handIndex]; if (hand && hand.joints && hand.joints['index-finger-tip']) { const indexTip = hand.joints['index-finger-tip']; this.createVisualizers(indexTip); this.triggerStartTime = Date.now(); this.triggerTimeout = setTimeout(() => { this._triggerSelection(); }, this.triggerDelay); } } this.updateVisualizers(); } onSelectEnd(event) { this.removeVisualizers(); if (this.triggerTimeout) { clearTimeout(this.triggerTimeout); this.triggerTimeout = null; } this.activeHandedness = null; } _triggerSelection() { const currentTime = Date.now(); if (currentTime - this.lastTriggerTime < this.triggerCooldownDuration) { return; } this.lastTriggerTime = currentTime; this.isTriggerOnCooldown = true; setTimeout(() => { this.isTriggerOnCooldown = false; }, this.triggerCooldownDuration); setTimeout(() => { if (!this.outerVisualizer) return; xb.core.sound.soundSynthesizer.playPresetTone('ACTIVATE'); this.isPulsing = true; this.pulseStartTime = Date.now(); setTimeout(() => { this.removeVisualizers(); }, this.pulseAnimationDuration); }, 75); if (this.onTrigger) { this.onTrigger(); } } createVisualizers(parent) { this.removeVisualizers(); this.outerMaterial.opacity = this.outerMaterialOpacity; this.innerMaterial.opacity = this.innerMaterialOpacity; this.outerVisualizer = new THREE.Mesh(this.sphereGeometry, this.outerMaterial); parent.add(this.outerVisualizer); this.innerVisualizer = new THREE.Mesh(this.sphereGeometry, this.innerMaterial); this.innerVisualizer.scale.setScalar(0.01); parent.add(this.innerVisualizer); } updateVisualizers() { if (!this.innerVisualizer || this.triggerStartTime <= 0) return; const currentTime = Date.now(); if (this.isPulsing) { const pulseElapsed = currentTime - this.pulseStartTime; const pulseProgress = Math.min(pulseElapsed / this.pulseAnimationDuration, 1.0); const scaleProgress = easeOutQuint(pulseProgress); const pulseScale = 1.0 + scaleProgress * 0.20; this.innerVisualizer.scale.setScalar(pulseScale); const fadeProgress = pulseProgress; this.innerMaterial.opacity = 0.5 * (1 - fadeProgress); this.outerMaterial.opacity = 0.2 * (1 - fadeProgress); } else { const elapsed = currentTime - this.triggerStartTime; const progress = Math.min(elapsed / this.triggerDelay, 1.0); const easedProgress = easeInQuad(progress); this.innerVisualizer.scale.setScalar(easedProgress); } } removeVisualizers() { if (this.outerVisualizer) { this.outerVisualizer.removeFromParent(); this.outerVisualizer = null; } if (this.innerVisualizer) { this.innerVisualizer.removeFromParent(); this.innerVisualizer = null; } this.triggerStartTime = 0; this.isPulsing = false; this.pulseStartTime = 0; } }
0
0.947365
1
0.947365
game-dev
MEDIA
0.595696
game-dev,web-frontend
0.971351
1
0.971351
LambdAurora/LambdaBetterGrass
2,051
src/main/java/dev/lambdaurora/lambdabettergrass/gui/LBGOption.java
/* * Copyright © 2021 LambdAurora <email@lambdaurora.dev> * * This file is part of LambdaBetterGrass. * * Licensed under the Lambda License. For more information, * see the LICENSE file. */ package dev.lambdaurora.lambdabettergrass.gui; import com.mojang.datafixers.util.Unit; import com.mojang.serialization.Codec; import dev.lambdaurora.lambdabettergrass.LambdaBetterGrass; import net.minecraft.client.Minecraft; import net.minecraft.client.OptionInstance; import net.minecraft.client.Options; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Text; import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; /** * A dummy option to add a button leading to LambdaBetterGrass' settings. * * @author LambdAurora * @version 2.0.0 * @since 1.1.2 */ public final class LBGOption { private static final String KEY = LambdaBetterGrass.NAMESPACE; public static OptionInstance<Unit> getOption(Screen parent) { return new OptionInstance<>( KEY, OptionInstance.noTooltip(), (title, object) -> title, new DummyValueSet(parent), Unit.INSTANCE, unit -> { } ); } private record DummyValueSet(Screen parent) implements OptionInstance.ValueSet<Unit> { @Override public @NotNull Function<OptionInstance<Unit>, AbstractWidget> createButton( OptionInstance.TooltipSupplier<Unit> tooltipSupplier, Options options, int x, int y, int width, Consumer<Unit> consumer ) { return option -> Button.builder( Text.translatable(KEY), btn -> Minecraft.getInstance().setScreen(new SettingsScreen(this.parent)) ) .pos(x, y) .size(width, 20) .build(); } @Override public @NotNull Optional<Unit> validateValue(Unit value) { return Optional.of(Unit.INSTANCE); } @Override public @NotNull Codec<Unit> codec() { return Codec.EMPTY.codec(); } } }
0
0.715605
1
0.715605
game-dev
MEDIA
0.937611
game-dev
0.518897
1
0.518897
jjppof/goldensun_html5
8,906
base/windows/item/StatsCheckWithItemWindow.ts
import {TextObj, Window} from "../../Window"; import {Item, item_types} from "../../Item"; import {effect_types, effect_operators} from "../../Effect"; import {GoldenSun} from "../../GoldenSun"; import {ItemSlot, item_equip_slot, MainChar} from "../../MainChar"; import * as _ from "lodash"; import {main_stats} from "../../Player"; const BASE_WIN_WIDTH = 100; const BASE_WIN_HEIGHT = 92; const BASE_WIN_X = 0; const BASE_WIN_Y = 40; const ARROW_X = 53; const ARROW_Y_SHIFT = 2; const PREVIEW_TEXT_X = 94; type Arrows = { attack: Phaser.Sprite | TextObj; defense: Phaser.Sprite | TextObj; agility: Phaser.Sprite | TextObj; }; export class StatsCheckWithItemWindow { public game: Phaser.Game; public data: GoldenSun; public char: MainChar; public window_open: boolean; public x: number; public y: number; public base_window: Window; public avatar_group: Phaser.Group; public x_avatar: number; public y_avatar: number; public avatar: Phaser.Sprite; public up_arrows: Arrows; public down_arrows: Arrows; public preview_stats_texts: Arrows; public name_text: TextObj; public lv_text: TextObj; public attack_text: TextObj; public defense_text: TextObj; public agility_text: TextObj; public item: Item; public item_obj: ItemSlot; constructor(game, data) { this.game = game; this.data = data; this.char = null; this.window_open = false; this.x = BASE_WIN_X; this.y = BASE_WIN_Y; this.base_window = new Window(this.game, this.x, this.y, BASE_WIN_WIDTH, BASE_WIN_HEIGHT); this.base_window.set_canvas_update(); this.avatar_group = game.add.group(); this.base_window.add_sprite_to_window_group(this.avatar_group); this.x_avatar = 8; this.y_avatar = 8; this.avatar_group.x = this.x_avatar; this.avatar_group.y = this.y_avatar; this.avatar = null; this.up_arrows = { [effect_types.ATTACK]: this.base_window.create_at_group(ARROW_X, 48 - ARROW_Y_SHIFT, "menu", { frame: "up_arrow", }), [effect_types.DEFENSE]: this.base_window.create_at_group(ARROW_X, 64 - ARROW_Y_SHIFT, "menu", { frame: "up_arrow", }), [effect_types.AGILITY]: this.base_window.create_at_group(ARROW_X, 80 - ARROW_Y_SHIFT, "menu", { frame: "up_arrow", }), } as Arrows; this.down_arrows = { [effect_types.ATTACK]: this.base_window.create_at_group(ARROW_X, 48 - ARROW_Y_SHIFT, "menu", { frame: "down_arrow", }), [effect_types.DEFENSE]: this.base_window.create_at_group(ARROW_X, 64 - ARROW_Y_SHIFT, "menu", { frame: "down_arrow", }), [effect_types.AGILITY]: this.base_window.create_at_group(ARROW_X, 80 - ARROW_Y_SHIFT, "menu", { frame: "down_arrow", }), } as Arrows; this.preview_stats_texts = { [effect_types.ATTACK]: this.base_window.set_text_in_position("0", PREVIEW_TEXT_X, 48, {right_align: true}), [effect_types.DEFENSE]: this.base_window.set_text_in_position("0", PREVIEW_TEXT_X, 64, {right_align: true}), [effect_types.AGILITY]: this.base_window.set_text_in_position("0", PREVIEW_TEXT_X, 80, {right_align: true}), } as Arrows; this.hide_arrows(); this.base_window.set_text_in_position("Lv", 48, 24); this.base_window.set_text_in_position("Attack", 8, 40); this.base_window.set_text_in_position("Defense", 8, 56); this.base_window.set_text_in_position("Agility", 8, 72); this.name_text = this.base_window.set_text_in_position("0", 40, 8); this.lv_text = this.base_window.set_text_in_position("0", 80, 24); this.attack_text = this.base_window.set_text_in_position("0", 40, 48, {right_align: true}); this.defense_text = this.base_window.set_text_in_position("0", 40, 64, {right_align: true}); this.agility_text = this.base_window.set_text_in_position("0", 40, 80, {right_align: true}); } hide() { this.base_window.group.visible = false; } show() { if (!this.window_open) return; this.base_window.group.visible = true; } update_info(set_compare_arrows = true) { this.base_window.update_text(this.char.name, this.name_text); this.base_window.update_text(this.char.level.toString(), this.lv_text); this.base_window.update_text(this.char.atk.toString(), this.attack_text); this.base_window.update_text(this.char.def.toString(), this.defense_text); this.base_window.update_text(this.char.agi.toString(), this.agility_text); if (this.avatar) { this.avatar.destroy(); } this.avatar = this.avatar_group.create(0, 0, "avatars", this.char.key_name); if (set_compare_arrows) { this.compare_items(); } } set_compare_arrows(effect_type, equip_slot_property, current_stats_property, compare_removing) { let effect_obj = _.find(this.item.effects, {type: effect_type}); let preview_stats; if (effect_obj !== undefined) { const equip_slot_key_name = this.char.equip_slots[equip_slot_property] === null ? null : this.char.equip_slots[equip_slot_property].key_name; preview_stats = this.char.preview_stats_without_item_effect(effect_type, effect_obj, equip_slot_key_name); } if (this.char.equip_slots[equip_slot_property] === null) { if (effect_obj === undefined) { return; } } else { const equipped_effect_obj = _.find( this.data.info.items_list[this.char.equip_slots[equip_slot_property].key_name].effects, {type: effect_type} ); if (equipped_effect_obj === undefined && effect_obj === undefined) return; if (effect_obj === undefined || compare_removing) { effect_obj = { type: effect_type, quantity: 0, operator: effect_operators.PLUS, }; preview_stats = this.char.preview_stats_without_item_effect( effect_type, effect_obj, this.char.equip_slots[equip_slot_property].key_name ); } } const current_stats = this.char[current_stats_property]; if (preview_stats > current_stats) { this.up_arrows[effect_type].visible = true; } else if (preview_stats < current_stats) { this.down_arrows[effect_type].visible = true; } this.update_preview_text(preview_stats, effect_type); } update_preview_text(value, effect_type) { this.preview_stats_texts[effect_type].text.visible = true; this.preview_stats_texts[effect_type].shadow.visible = true; this.base_window.update_text(value.toString(), this.preview_stats_texts[effect_type]); } hide_arrows() { for (let key in this.up_arrows) { this.up_arrows[key].visible = false; this.down_arrows[key].visible = false; this.preview_stats_texts[key].text.visible = false; this.preview_stats_texts[key].shadow.visible = false; } } compare_items(compare_removing = false) { this.hide_arrows(); if (this.item_obj.equipped && !compare_removing) return; if (!this.item.equipable_chars.includes(this.char.key_name)) return; if (!(this.item.type in item_equip_slot)) return; this.set_compare_arrows( effect_types.ATTACK, item_equip_slot[this.item.type], main_stats.ATTACK, compare_removing ); this.set_compare_arrows( effect_types.DEFENSE, item_equip_slot[this.item.type], main_stats.DEFENSE, compare_removing ); this.set_compare_arrows( effect_types.AGILITY, item_equip_slot[this.item.type], main_stats.AGILITY, compare_removing ); } open(char, item, item_obj, callback?) { this.char = char; this.item = item; this.item_obj = item_obj; this.update_info(); this.base_window.show(() => { this.window_open = true; if (callback !== undefined) { callback(); } }, false); } close(callback?) { this.base_window.close(() => { this.window_open = false; if (callback !== undefined) { callback(); } }, false); } }
0
0.91649
1
0.91649
game-dev
MEDIA
0.964304
game-dev
0.97501
1
0.97501
MergHQ/CRYENGINE
3,283
Code/GameSDK/GameDll/CinematicInput.h
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Controls script variables coming from track view to add some control/feedback during cutscenes ------------------------------------------------------------------------- History: - 28:04:2010 Created by Benito Gangoso Rodriguez *************************************************************************/ #pragma once #ifndef _CINEMATIC_INPUT_H_ #define _CINEMATIC_INPUT_H_ #define CINEMATIC_INPUT_PC_MOUSE 1 class CWeapon; class CCinematicInput { struct SUpdateContext { SUpdateContext() : m_frameTime(0.0333f) , m_lookUpLimit(0.0f) , m_lookDownLimit(0.0f) , m_lookLeftLimit(0.0f) , m_lookRightLimit(0.0f) , m_recenter(true) { } float m_frameTime; float m_lookUpLimit; float m_lookDownLimit; float m_lookLeftLimit; float m_lookRightLimit; bool m_recenter; }; struct SCinematicWeapon { SCinematicWeapon() { Reset(); } void Reset() { m_weaponId = 0; m_parentId = 0; } EntityId m_weaponId; EntityId m_parentId; }; public: enum Weapon { eWeapon_Primary = 0, eWeapon_Secondary, eWeapon_ClassCount, }; CCinematicInput(); ~CCinematicInput(); void OnBeginCutScene(int cutSceneFlags); void OnEndCutScene(int cutSceneFlags); void Update(float frameTime); void SetUpWeapon( const CCinematicInput::Weapon& weaponClass, const IEntity* pEntity ); void OnAction( const EntityId actorId, const ActionId& actionId, int activationMode, float value); ILINE bool IsAnyCutSceneRunning() const { return (m_cutsceneRunningCount > 0); } ILINE bool IsPlayerNotActive() const { return (m_cutscenesNoPlayerRunningCount > 0); } void OnRayCastDataReceived(const QueuedRayID& rayID, const RayCastResult& result); private: void UpdateForceFeedback(IScriptSystem* pScriptSystem, float frameTime); void UpdateAdditiveCameraInput(IScriptSystem* pScriptSystem, float frameTime); void UpdateWeapons(); void UpdateWeaponOrientation( IEntity* pWeaponEntity, const Vec3& targetPosition ); Ang3 UpdateAdditiveCameraInputWithMouse(const CCinematicInput::SUpdateContext& updateCtx, const Ang3& rawMouseInput); Ang3 UpdateAdditiveCameraInputWithController(const CCinematicInput::SUpdateContext& updateCtx, const Ang3& rawMouseInput); void RefreshInputMethod(const bool isMouseInput); void ClearCutSceneVariables(); void DisablePlayerForCutscenes(); void ReEnablePlayerAfterCutscenes(); void TogglePlayerThirdPerson(bool bEnable); CWeapon* GetWeapon(const CCinematicInput::Weapon& weaponClass) const; Ang3 m_controllerAccumulatedAngles; int m_cutsceneRunningCount; int m_cutscenesNoPlayerRunningCount; bool m_bMutedAudioForCutscene; bool m_bPlayerIsThirdPerson; bool m_bPlayerWasInvisible; bool m_bCutsceneDisabledUISystem; int m_iHudState; SCinematicWeapon m_weapons[eWeapon_ClassCount]; QueuedRayID m_aimingRayID; float m_aimingDistance; #if CINEMATIC_INPUT_PC_MOUSE Ang3 m_mouseAccumulatedAngles; Ang3 m_mouseAccumulatedInput; float m_mouseRecenterTimeOut; bool m_lastUpdateWithMouse; #endif }; #endif
0
0.930819
1
0.930819
game-dev
MEDIA
0.936187
game-dev
0.571686
1
0.571686
onitama/OpenHSP
26,226
src/hsp3cnv/chsp3.cpp
// // HSP3 manager class // onion software/onitama 2008/4 // #include <stdio.h> #include <stdarg.h> #include <windows.h> #include "supio.h" #include "chsp3.h" #define DELCLASS(o) if (o) { delete (o); (o)=NULL; } /*------------------------------------------------------------*/ /* constructor */ /*------------------------------------------------------------*/ #include "../hspcmp/hspcmd.cpp" /*------------------------------------------------------------*/ /* constructor */ /*------------------------------------------------------------*/ CHsp3::CHsp3( void ) { buf = new CMemBuf; out = new CMemBuf; out2 = new CMemBuf; lb = new CLabel; lb->RegistList( hsp_prestr, "" ); mem_cs = NULL; mem_ds = NULL; mem_ot = NULL; dinfo = NULL; linfo = NULL; finfo = NULL; finfo2 = NULL; minfo = NULL; hpidat = NULL; ot_info = NULL; } CHsp3::~CHsp3( void ) { DeleteObjectHeader(); delete lb; delete out2; delete out; delete buf; } /*------------------------------------------------------------*/ /* interface */ /*------------------------------------------------------------*/ void CHsp3::DeleteObjectHeader( void ) { // HSPwb_[j // DELCLASS( mem_cs ); DELCLASS( mem_ds ); DELCLASS( mem_ot ); DELCLASS( dinfo ); DELCLASS( linfo ); DELCLASS( finfo ); DELCLASS( finfo2 ); DELCLASS( minfo ); DELCLASS( hpidat ); DELCLASS( ot_info ); } void CHsp3::NewObjectHeader( void ) { // VKHSPwb_[쐬 // hsphed = (HSPHED *)buf->GetBuffer(); mem_cs = new CMemBuf( 0x1000 ); mem_ds = new CMemBuf( 0x1000 ); mem_ot = new CMemBuf( 0x1000 ); dinfo = new CMemBuf( 0x1000 ); linfo = new CMemBuf( 0x1000 ); finfo = new CMemBuf( 0x1000 ); finfo2 = new CMemBuf( 0x1000 ); minfo = new CMemBuf( 0x1000 ); hpidat = new CMemBuf( 0x1000 ); orgname[0]=0; } int CHsp3::LoadObjectFile( char *fname ) { // axt@C[h // char *baseptr; if ( buf->PutFile( fname ) < 0 ) return -1; strcpy( orgname, fname ); hsphed = (HSPHED *)buf->GetBuffer(); baseptr = (char *)buf->GetBuffer(); if ((hsphed->h1!='H')||(hsphed->h2!='S')||(hsphed->h3!='P')||(hsphed->h4!='3')) { return -2; } //if ( hsphed->version < vercode ) { // return -3; //} mem_cs = new CMemBuf( 0x1000 ); mem_cs->PutData( baseptr+hsphed->pt_cs, hsphed->max_cs ); mem_ds = new CMemBuf( 0x1000 ); mem_ds->PutData( baseptr+hsphed->pt_ds, hsphed->max_ds ); mem_ot = new CMemBuf( 0x1000 ); mem_ot->PutData( baseptr+hsphed->pt_ot, hsphed->max_ot ); dinfo = new CMemBuf( 0x1000 ); dinfo->PutData( baseptr+hsphed->pt_dinfo, hsphed->max_dinfo ); linfo = new CMemBuf( 0x1000 ); linfo->PutData( baseptr+hsphed->pt_linfo, hsphed->max_linfo ); finfo = new CMemBuf( 0x1000 ); finfo->PutData( baseptr+hsphed->pt_finfo, hsphed->max_finfo ); finfo2 = new CMemBuf( 0x1000 ); finfo2->PutData( baseptr+hsphed->pt_finfo2, hsphed->max_finfo2 ); minfo = new CMemBuf( 0x1000 ); minfo->PutData( baseptr+hsphed->pt_minfo, hsphed->max_minfo ); hpidat = new CMemBuf( 0x1000 ); hpidat->PutData( baseptr+hsphed->pt_hpidat, hsphed->max_hpi ); UpdateValueName(); // ϐ̃fobO MakeOTInfo(); // OT // g[Xp̏ݒ // int i; initCS( mem_cs->GetBuffer() ); mcs_start = ( unsigned short * )( mem_cs->GetBuffer() ); mcs_end = ( unsigned short * )( mem_cs->GetBuffer() + hsphed->max_cs ); getCS(); exflag = 0; iflevel = 0; for( i=0;i<MAX_IFLEVEL;i++ ) { ifmode[i]=0; ifptr[i]=0; } SetIndent( 0 ); return 0; } void CHsp3::GetContext( MCSCONTEXT *ctx ) { // ReLXg擾 // (ctxɏ) // ctx->mcs = mcs; ctx->mcs_last = mcs_last; ctx->cstype = cstype; ctx->csval = csval; ctx->exflag = exflag; } void CHsp3::SetContext( MCSCONTEXT *ctx ) { // ReLXgݒ // (ctx̓eݒ) // mcs = ctx->mcs; mcs_last = ctx->mcs_last; cstype = ctx->cstype; csval = ctx->csval; exflag = ctx->exflag; } /*------------------------------------------------------------*/ LIBDAT *CHsp3::GetLInfo( int index ) { // linfol擾 // LIBDAT *baseptr; baseptr = (LIBDAT *)linfo->GetBuffer(); baseptr += index; return baseptr; } STRUCTDAT *CHsp3::GetFInfo( int index ) { // finfol擾 // STRUCTDAT *baseptr; baseptr = (STRUCTDAT *)finfo->GetBuffer(); baseptr += index; return baseptr; } STRUCTPRM *CHsp3::GetMInfo( int index ) { // minfol擾 // STRUCTPRM *baseptr; baseptr = (STRUCTPRM *)minfo->GetBuffer(); baseptr += index; return baseptr; } int CHsp3::GetOTCount( void ) { // OTindexʂ𓾂 // return ( mem_ot->GetSize() / sizeof( int ) ); } int CHsp3::GetLInfoCount( void ) { // linfoindexʂ𓾂 // return ( linfo->GetSize() / sizeof( LIBDAT ) ); } int CHsp3::GetFInfoCount( void ) { // finfoindexʂ𓾂 // return ( finfo->GetSize() / sizeof( STRUCTDAT ) ); } int CHsp3::GetMInfoCount( void ) { // minfoindexʂ𓾂 // return ( minfo->GetSize() / sizeof( STRUCTPRM ) ); } /*------------------------------------------------------------*/ int CHsp3::SaveOutBuf( char *fname ) { // o̓obt@Z[u // return ( out->SaveFile( fname ) ); } int CHsp3::SaveOutBuf2( char *fname ) { // o̓obt@2Z[u // return ( out2->SaveFile( fname ) ); } char *CHsp3::GetOutBuf( void ) { // o̓obt@̐擪|C^𓾂 // return ( out->GetBuffer() ); } void CHsp3::MakeObjectInfo( void ) { // ǂݍ񂾃IuWFNgt@C̏o(ʂ͏o̓obt@) // char mes[512]; sprintf( mes,"Original File : %s\n", orgname ); out->PutStr( mes ); sprintf( mes,"Code Segment Size : %d\n", mem_cs->GetSize() ); out->PutStr( mes ); sprintf( mes,"Data Segment Size : %d\n", mem_ds->GetSize() ); out->PutStr( mes ); sprintf( mes,"Object Temp Size : %d\n", mem_ot->GetSize() ); out->PutStr( mes ); sprintf( mes,"LibInfo(%d) FInfo(%d) MInfo(%d)\n", GetLInfoCount(), GetFInfoCount(), GetMInfoCount() ); out->PutStr( mes ); out->PutStr( "--------------------------------------------\n" ); { // LInfo̕\(DLLC|[g) int i,max; LIBDAT *lib; max = GetLInfoCount(); for(i=0;i<max;i++) { lib = GetLInfo(i); sprintf( mes,"LInfo#%d : flag=%x name=%s clsid=%x\n", i, lib->flag, GetDS(lib->nameidx), lib->clsid ); out->PutStr( mes ); } } { // FInfo̕\(gߏ) int i,max; STRUCTDAT *fnc; char *p; max = GetFInfoCount(); for(i=0;i<max;i++) { fnc = GetFInfo(i); if ( fnc->nameidx < 0 ) p = ""; else p = GetDS( fnc->nameidx ); sprintf( mes,"FInfo#%d : index=%d ot=%d subid=%d name=%s param=%d\n", i, fnc->index, fnc->otindex, fnc->subid, p, fnc->prmmax ); out->PutStr( mes ); } } /* { // Ot̕\(gp) int i,max,otv; max = GetOTCount(); for(i=0;i<max;i++) { otv = GetOT(i); sprintf( mes,"Ot#%d : value=%x\n", i, otv ); out->PutStr( mes ); } } */ /* { // MInfo̕\(gp) int i,max; MODDAT *mod; max = GetMInfoCount(); for(i=0;i<max;i++) { mod = GetMInfo(i); sprintf( mes,"MInfo#%d : flag=%x name=%s\n", i, mod->flag, mod->name ); out->PutStr( mes ); } } */ out->PutStr( "--------------------------------------------\n" ); } int CHsp3::UpdateValueName( void ) { // mem_di_valXV // unsigned char *mem_di; unsigned char ofs; int cl,a; mem_di_val = NULL; if ( dinfo->GetSize() == 0 ) { return -1; } mem_di = (unsigned char *)dinfo->GetBuffer(); if ( mem_di[0]==255) return -1; cl=0;a=0; while(1) { ofs=mem_di[a++]; switch( ofs ) { case 252: a+=2; break; case 253: mem_di_val=&mem_di[a-1]; return 0; case 254: cl=(mem_di[a+4]<<8)+mem_di[a+3]; a+=5; break; case 255: return -1; default: cl++; break; } } return cl; } char *CHsp3::GetHSPVarName( int varid ) { // ϐ擾 // int i; unsigned char *mm; if ( mem_di_val == NULL ) { // ϐ񂪂Ȃꍇ sprintf( hspvarmp, "_HspVar%d", varid ); return hspvarmp; } mm = mem_di_val + ( varid * 6 ); i = (mm[3]<<16)+(mm[2]<<8)+mm[1]; return GetDS( i ); } void CHsp3::MakeOTInfo( void ) { // ot_infoXV // (ot_infoɂFInfoID) // (ʏ탉x̏ꍇ́Aot_info-1ɂȂ) // int i,maxot; int *oi; int *ot; int maxfnc; STRUCTDAT *fnc; maxot = GetOTCount(); ot_info = new CMemBuf( maxot * sizeof(int) ); oi = (int *)ot_info->GetBuffer(); ot = (int *)mem_ot->GetBuffer(); for(i=0;i<maxot;i++) { oi[i]=-1; } maxfnc = GetFInfoCount(); for(i=0;i<maxfnc;i++) { fnc = GetFInfo(i); switch( fnc->index ) { case STRUCTDAT_INDEX_FUNC: // ` case STRUCTDAT_INDEX_CFUNC: // `֐ oi[fnc->otindex] = i; break; } } } int CHsp3::GetOTInfo( int index ) { int *oi; oi = (int *)ot_info->GetBuffer(); return oi[index]; } void CHsp3::OutMes( char *format, ... ) { // outbufɕo(printf݊)(OUTMES_BUFFER_MAX܂) // char textbf[OUTMES_BUFFER_MAX]; va_list args; va_start(args, format); vsprintf(textbf, format, args); va_end(args); out->PutStr( textbf ); } void CHsp3::OutLine( char *format, ... ) { // outbufɕo(printf݊)(OUTMES_BUFFER_MAX܂) // char textbf[OUTMES_BUFFER_MAX]; va_list args; va_start(args, format); vsprintf(textbf, format, args); va_end(args); for(int i=0;i<=indent;i++) { out->PutStr("\t"); } out->PutStr( textbf ); } void CHsp3::OutLineBuf( CMemBuf *outbuf, char *format, ... ) { // outbufɕo(printf݊)(OUTMES_BUFFER_MAX܂) // char textbf[OUTMES_BUFFER_MAX]; va_list args; va_start(args, format); vsprintf(textbf, format, args); va_end(args); for(int i=0;i<=indent;i++) { outbuf->PutStr("\t"); } outbuf->PutStr( textbf ); } void CHsp3::OutCR( void ) { out->PutCR(); } void CHsp3::SetIndent( int val ) { indent = val; } /*------------------------------------------------------------*/ void CHsp3::initCS( void *ptr ) { // ǂݎcs|C^ // mcs = (unsigned short *)ptr; } int CHsp3::getCS( void ) { // R}hP“ǂݎ // (ver3.0ȍ~p) // register unsigned short a; mcs_last=mcs; a=*mcs++; exflag = a & (EXFLG_1|EXFLG_2); cstype = a & CSTYPE; if ( a & 0x8000 ) { // 32bit val code // csval = (int)*((int *)mcs); mcs+=2; } else { // 16bit val code csval = (int)(*mcs++); } return csval; } int CHsp3::getEXFLG( void ) { // ̃R}hEXFLAGǂݎ // unsigned short a; a=*mcs; return (int)( a & (EXFLG_1|EXFLG_2)); } int CHsp3::getNextCS( int *type ) { // ̃R}hTYPE,VALǂݎ // unsigned short a; a=*mcs; *type = a & CSTYPE; if ( a & 0x8000 ) { // 32bit val code // return (int)*((int *)mcs); } // 16bit val code return (int)(mcs[1]); } char *CHsp3::GetDS_fmt( int offset ) { // DS當擾(tH[}bgςݕ) // MakeHspStyleString2( GetDS(offset), strtmp ); return strtmp; } char *CHsp3::GetDS( int offset ) { // DS當擾 // char *baseptr; baseptr = mem_ds->GetBuffer(); baseptr += offset; return baseptr; } double CHsp3::GetDSf( int offset ) { // DSdoublel擾 // char *ptr; ptr = GetDS( offset ); return *(double *)ptr; } int CHsp3::GetOT( int index ) { // OTl擾 // int *baseptr; baseptr = (int *)mem_ot->GetBuffer(); return baseptr[index]; } /*------------------------------------------------------------*/ char *CHsp3::GetHSPName( int type, int val ) { // type,valɑΉHSPo^𓾂 // int max,i; LABOBJ *lobj; max = lb->GetNumEntry(); for(i=0;i<max;i++) { lobj = lb->GetLabel(i); if ( lobj->type == type ) { if ( lobj->opt == val ) { return lobj->name; } } } switch( type ) { case TYPE_MODCMD: { STRUCTDAT *fnc; fnc = GetFInfo( val ); if ( fnc->index == STRUCTDAT_INDEX_FUNC ) return GetDS( fnc->nameidx ); if ( fnc->index == STRUCTDAT_INDEX_CFUNC ) return GetDS( fnc->nameidx ); break; } case TYPE_DLLFUNC: { STRUCTDAT *fnc; fnc = GetFInfo( val ); return GetDS( fnc->nameidx ); } default: break; } return ""; } char *CHsp3::GetHSPOperator( int val ) { // HSP̉Zq𕶎(L)ŕԂ // switch( val ) { case CALCCODE_ADD: return "+"; case CALCCODE_SUB: return "-"; case CALCCODE_MUL: return "*"; case CALCCODE_DIV: return "/"; case CALCCODE_MOD: return "%"; case CALCCODE_AND: return "&"; case CALCCODE_OR: return "|"; case CALCCODE_XOR: return "^"; case CALCCODE_EQ: return "="; case CALCCODE_NE: return "!="; case CALCCODE_GT: return ">"; case CALCCODE_LT: return "<"; case CALCCODE_GTEQ: return ">="; case CALCCODE_LTEQ: return "<="; case CALCCODE_RR: return ">>"; case CALCCODE_LR: return "<<"; } hspoptmp[0] = (char)val; hspoptmp[1] = 0; return hspoptmp; } char *CHsp3::GetHSPOperator2( int val ) { // HSP̉Zq𕶎(\bh)ŕԂ // switch( val ) { case CALCCODE_ADD: return "AddI"; case CALCCODE_SUB: return "SubI"; case CALCCODE_MUL: return "MulI"; case CALCCODE_DIV: return "DivI"; case CALCCODE_MOD: return "ModI"; case CALCCODE_AND: return "AndI"; case CALCCODE_OR: return "OrI"; case CALCCODE_XOR: return "XorI"; case CALCCODE_EQ: return "EqI"; case CALCCODE_NE: return "NeI"; case CALCCODE_GT: return "GtI"; case CALCCODE_LT: return "LtI"; case CALCCODE_GTEQ: return "GtEqI"; case CALCCODE_LTEQ: return "LtEqI"; case CALCCODE_RR: return "RrI"; case CALCCODE_LR: return "LrI"; } return ""; } char *CHsp3::GetHSPVarTypeName( int type ) { // HSP̃^Cvl𕶎ŕԂ // switch( type ) { case HSPVAR_FLAG_LABEL: return "label"; case HSPVAR_FLAG_STR: return "str"; case HSPVAR_FLAG_DOUBLE: return "double"; case HSPVAR_FLAG_INT: return "int"; case HSPVAR_FLAG_STRUCT: return "module"; case HSPVAR_FLAG_COMSTRUCT: return "comst"; } return ""; } char *CHsp3::GetHSPCmdTypeName( int type ) { // HSP̃R}h^Cvl𕶎ŕԂ // switch( type ) { case TYPE_MARK: return "Mark"; case TYPE_VAR: return "Var"; case TYPE_STRING: return "Str"; case TYPE_DNUM: return "Double"; case TYPE_INUM: return "Int"; case TYPE_STRUCT: return "Module"; case TYPE_XLABEL: return "Label"; case TYPE_LABEL: return "Label"; case TYPE_INTCMD: return "Intcmd"; case TYPE_EXTCMD: return "Extcmd"; case TYPE_EXTSYSVAR: return "Extvar"; case TYPE_CMPCMD: return "Cmp"; case TYPE_MODCMD: return "Modcmd"; case TYPE_INTFUNC: return "Intfunc"; case TYPE_SYSVAR: return "Sysvar"; case TYPE_PROGCMD: return "Prgcmd"; case TYPE_DLLFUNC: return "Dllfunc"; case TYPE_DLLCTRL: return "Dllctrl"; case TYPE_USERDEF: return "Usrfunc"; } return ""; } /*------------------------------------------------------------*/ void CHsp3::MakeProgramInfoFuncParam( int structid ) { // `߃p[^[̃eXg // structid : p[^[ID // char mes[256]; STRUCTDAT *fnc; STRUCTPRM *prm; int i,max; fnc = GetFInfo( structid ); switch( fnc->index ) { case STRUCTDAT_INDEX_FUNC: // ` out->PutStr( "#deffunc" ); break; case STRUCTDAT_INDEX_CFUNC: // `֐ out->PutStr( "#defcfunc" ); break; } sprintf( mes," %s ", GetDS(fnc->nameidx) ); out->PutStr( mes ); prm = GetMInfo( fnc->prmindex ); max = fnc->prmmax; for(i=0;i<max;i++) { if ( i ) out->PutStr( ", " ); switch( prm->mptype ) { case MPTYPE_VAR: out->PutStr( "var" ); break; case MPTYPE_STRING: case MPTYPE_LOCALSTRING: out->PutStr( "str" ); break; case MPTYPE_DNUM: out->PutStr( "double" ); break; case MPTYPE_INUM: out->PutStr( "int" ); break; case MPTYPE_LABEL: out->PutStr( "label" ); break; case MPTYPE_LOCALVAR: out->PutStr( "local" ); break; case MPTYPE_ARRAYVAR: out->PutStr( "array" ); break; case MPTYPE_SINGLEVAR: out->PutStr( "var" ); break; default: sprintf( mes, "???(%d)", prm->mptype ); out->PutStr( mes ); break; } sprintf( mes," _prm%d", fnc->prmindex + i ); out->PutStr( mes ); prm++; } out->PutCR(); } void CHsp3::MakeProgramInfoLabel( void ) { // x𐶐̃eXg // int otmax; char mes[256]; int labindex; int myot; otmax = GetOTCount(); if ( otmax == 0 ) return; myot = (int)(mcs_last - mcs_start); labindex = 0; while(1) { if ( labindex>=otmax ) break; if ( myot == GetOT( labindex ) ) { if ( GetOTInfo( labindex ) == -1 ) { sprintf( mes,"*L%04x\n", labindex ); out->PutStr( mes ); } else { MakeProgramInfoFuncParam( GetOTInfo( labindex ) ); } } labindex++; } } int CHsp3::GetHSPVarExpression( char *mes ) { // ϐɑp[^[(z)WJ // mes : zemesɏo // int i; int prm; if ( cstype == TYPE_MARK ) { if ( csval == '(' ) { CMemBuf arname; arname.PutStr( "(" ); getCS(); prm = 0; while(1) { if ( exflag & EXFLG_1) break; // p[^[I[ if ( mcs > mcs_end ) break; // f[^I[`FbN if ( prm ) arname.PutStr( ", " ); i = GetHSPExpression( &arname ); if ( i > 0 ) break; if ( i < -1 ) return i; prm++; } arname.PutStr( ")" ); if ( arname.GetSize() < VAREXP_BUFFER_MAX ) { strcpy( mes, arname.GetBuffer() ); } else { Alert( "CHsp3:Expression buffer overflow." ); *mes = 0; } getCS(); return 1; } } return 0; } int CHsp3::GetHSPExpression( CMemBuf *eout ) { // HSP̌vZtH[}bgŃp[^[WJ // eout : o͐ // int i; int op; int res; CsStack st; OPSTACK *stm1; OPSTACK *stm2; char mes[8192]; // WJ鎮̍ő啶 char mestmp[8192]; // WJ鎮̍ő啶 char mm[4096]; if (exflag&EXFLG_1) return 1; // p[^[I[ if (exflag&EXFLG_2) { // p[^[؂(ftHg) exflag^=EXFLG_2; return -1; } if ( cstype == TYPE_MARK ) { if ( csval == 63 ) { // p[^[ȗ('?') getCS(); exflag&=~EXFLG_2; return -1; } if ( csval == ')' ) { // ֐̃p[^[ȗ exflag&=~EXFLG_2; return 2; } } *mes = 0; res = 0; while(1) { if ( mcs > mcs_end ) return 1; // f[^I[`FbN switch(cstype) { case TYPE_MARK: // L(X^bNoĉZ) // if ( csval == ')' ) { // ̏I}[N exflag |= EXFLG_2; res = 2; break; } op = csval; stm1 = st.Peek2(); stm2 = st.Peek(); if ( stm1->type == -1 ) { // (?)+(result)̏ꍇ MakeImmidiateHSPName( mm, stm2->type, stm2->val, stm2->opt ); strcpy( mestmp, mes ); sprintf( mes,"(%s)%s%s", mestmp, GetHSPOperator(op), mm ); } else { if ( stm2->type == -1 ) { // (result)+(?)̏ꍇ MakeImmidiateHSPName( mm, stm1->type, stm1->val, stm1->opt ); strcat( mes, GetHSPOperator(op) ); strcat( mes, mm ); } else { // (?)+(?)̏ꍇ MakeImmidiateHSPName( mm, stm1->type, stm1->val, stm1->opt ); strcat( mes, mm ); strcat( mes, GetHSPOperator(op) ); MakeImmidiateHSPName( mm, stm2->type, stm2->val, stm2->opt ); strcat( mes, mm ); } } stm1->type = -1; st.Pop(); getCS(); break; case TYPE_VAR: // ϐX^bNɐς // stm1 = st.Push( cstype, csval ); getCS(); i = GetHSPVarExpression( mm ); if ( i ) st.SetExStr( stm1, mm ); break; case TYPE_INUM: case TYPE_STRING: case TYPE_DNUM: case TYPE_LABEL: // lX^bNɐς // st.Push( cstype, csval ); getCS(); break; case TYPE_STRUCT: // p[^[ // stm1 = st.Push( cstype, csval ); getCS(); i = GetHSPVarExpression( mm ); if ( i ) st.SetExStr( stm1, mm ); break; default: // ֐ƂēWJ // stm1 = st.Push( cstype, csval ); getCS(); i = GetHSPVarExpression( mm ); if ( i ) st.SetExStr( stm1, mm ); break; } if ( exflag ) { // p[^[I[`FbN exflag&=~EXFLG_2; break; } } if ( st.GetLevel() > 1 ) { eout->PutStr( "/*ERROR*/" ); Alert( "Invalid end stack" ); return -5; } if ( st.GetLevel() == 1 ) { stm1 = st.Peek(); if ( stm1->type != -1 ) { MakeImmidiateHSPName( mm, stm1->type, stm1->val, stm1->opt ); strcat( mes, mm ); } } eout->PutStr( mes ); return res; } int CHsp3::MakeImmidiateName( char *mes, int type, int val ) { // l(int,double,str)lj // (ljłȂ^̏ꍇ-1Ԃ) // switch( type ) { case TYPE_STRING: //sprintf( mes, "\"%s\"", GetDS( val ) ); sprintf( mes, "\"%s\"", GetDS_fmt( val ) ); break; case TYPE_DNUM: { double dval; dval = GetDSf(val); sprintf( mes, "%f", dval ); break; } case TYPE_INUM: sprintf( mes, "%d", val ); break; default: *mes = 0; return -1; } return 0; } int CHsp3::MakeImmidiateHSPName( char *mes, int type, int val, char *opt ) { // l(int,double,str)lj // (ljłȂ^̏ꍇ-1Ԃ) // int i; i = MakeImmidiateName( mes, type, val ); if ( i == 0 ) return 0; switch( type ) { case TYPE_VAR: sprintf( mes, "%s", GetHSPVarName(val) ); if ( opt != NULL ) strcat( mes, opt ); break; case TYPE_STRUCT: { STRUCTPRM *prm; prm = GetMInfo( val ); if ( prm->subid != STRUCTPRM_SUBID_STACK ) { sprintf( mes, "_modprm%d", val ); } else { sprintf( mes, "_prm%d", val ); } break; } case TYPE_LABEL: sprintf( mes, "*L%04x", val ); break; default: strcpy( mes, GetHSPName( type, val ) ); if ( opt != NULL ) strcat( mes, opt ); if ( *mes == 0 ) return -1; break; } return 0; } void CHsp3::MakeHspStyleString( char *str, CMemBuf *eout ) { // HSP̃GXP[vgp𐶐 // str : ̕ // eout : o͐ // char *p; char a1; p = str; eout->Put( (char)0x22 ); while(1) { a1 = *p++; if ( a1 == 0 ) break; if ( a1 == 13 ) { if ( *p==10 ) p++; eout->Put( '\\' ); a1='n'; } if ( a1 == '\t' ) { eout->Put( '\\' ); a1='t'; } if ( a1 == '\\' ) { eout->Put( '\\' ); } if ( a1 == 0x22 ) { eout->Put( '\\' ); a1 = 0x22; } eout->Put( a1 ); } eout->Put( (char)0x22 ); } void CHsp3::MakeHspStyleString2( char *str, char *dst ) { // HSP̃GXP[vgp𐶐 // str : ̕ // dst : o͐ // char *p; char *pdst; char a1; p = str; pdst = dst; while(1) { a1 = *p++; if ( a1 == 0 ) break; if ( a1 == 13 ) { if ( *p==10 ) p++; *pdst++ = '\\'; a1='n'; } if ( a1 == '\t' ) { *pdst++ = '\\'; a1='t'; } if ( a1 == '\\' ) { *pdst++ = '\\'; } if ( a1 == 0x22 ) { *pdst++ = '\\'; a1 = 0x22; } *pdst++ = a1; } *pdst++ = 0; } void CHsp3::MakeProgramInfoHSPName( bool putadr ) { // HSPlj(\) // putadr : AhX\ON/OFF // char mes[4096]; if ( putadr ) { sprintf( mes,"#%06x:", mcs - mcs_start ); out->PutStr( mes ); } else { out->PutStr( " " ); } switch( cstype ) { case TYPE_MARK: sprintf( mes, "Mark'%s'\n", GetHSPOperator( csval ) ); break; case TYPE_VAR: sprintf( mes, "VAR:%d(%s)\n", csval, GetHSPVarName(csval) ); break; case TYPE_STRING: sprintf( mes, "Str:%s\n", GetDS( csval ) ); break; case TYPE_DNUM: { double dval; dval = GetDSf(csval); sprintf( mes, "Double:%f\n", dval ); break; } case TYPE_INUM: sprintf( mes, "Int:%d\n", csval ); break; case TYPE_STRUCT: sprintf( mes, "Struct:%d\n", csval ); break; case TYPE_LABEL: sprintf( mes, "Label:%d\n", csval ); break; case TYPE_PROGCMD: case TYPE_INTCMD: case TYPE_EXTCMD: case TYPE_INTFUNC: char *p; p = GetHSPName( cstype, csval ); if ( *p == 0 ) { sprintf( mes, "cmd?:CSTYPE%d VAL%d\n", cstype, csval ); } else { sprintf( mes, "Cmd:%s\n", p ); } break; case TYPE_SYSVAR: sprintf( mes, "SysVar:%d\n", csval ); break; case TYPE_EXTSYSVAR: sprintf( mes, "ExtSysVar:%d\n", csval ); break; case TYPE_CMPCMD: sprintf( mes, "CMP:%d\n", csval ); break; case TYPE_MODCMD: sprintf( mes, "Module:%d\n", csval ); break; case TYPE_DLLFUNC: sprintf( mes, "DLLFUNC:%d\n", csval ); break; case TYPE_DLLCTRL: sprintf( mes, "DLLCTRL:%d\n", csval ); break; default: sprintf( mes, "???:CSTYPE%d VAL%d\n", cstype, csval ); break; } out->PutStr( mes ); } int CHsp3::MakeProgramInfoParam( void ) { // p[^[̃g[X // int prm; //char mes[4096]; prm = 0; while(1) { if ( mcs > mcs_end ) return -1; if ( exflag == EXFLG_1 ) break; // s if ( exflag & EXFLG_2 ) { if (prm) { // p[^[؂ out->PutStr( " ----\n" ); } } MakeProgramInfoHSPName( false ); //sprintf( mes, " CSTYPE%d VAL%d\n", cstype, csval ); //out->PutStr( mes ); prm++; getCS(); } return 0; } int CHsp3::MakeProgramInfoParam2( void ) { // p[^[̃g[X(WJ) // int i; int prm; // char mes[4096]; prm = 0; while(1) { // sprintf( mes,"---%04x:%x:CSTYPE%d VAL%d\n", mcs - mcs_start, exflag, cstype, csval ); // out->PutStr( mes ); if ( exflag & EXFLG_1) break; // p[^[I[ if ( mcs > mcs_end ) break; // f[^I[`FbN if ( prm ) out->PutStr( ", " ); i = GetHSPExpression( out ); if ( i > 0 ) break; if ( i < -1 ) return i; prm++; } out->PutCR(); return 0; } void CHsp3::MakeProgramInfo( void ) { // vÕg[XeXg // int i; int op; int cmdtype, cmdval; char mes[OUTMES_BUFFER_MAX]; char arbuf[VAREXP_BUFFER_MAX]; while(1) { if ( mcs > mcs_end ) break; // endif̃`FbN // if ( ifmode[iflevel]==2 ) { // if end if ( mcs_last>=ifptr[iflevel] ) { ifmode[iflevel] = 0; if ( iflevel == 0 ) { Alert( "Invalid endif." ); return; } iflevel--; out->PutStr( "endif\n" ); continue; } } // x`FbN // MakeProgramInfoLabel(); // s̃R[h // cmdtype = cstype; cmdval = csval; //MakeProgramInfoHSPName(); sprintf( mes,"#%06x:CSTYPE%d VAL%d\n", mcs_last - mcs_start, cstype, csval ); //Alert( mes ); out->PutStr( mes ); // p[^[ // switch( cmdtype ) { case TYPE_STRUCT: // ֕ϐ(struct) case TYPE_VAR: // ϐ MakeImmidiateHSPName( mes, cmdtype, cmdval ); out->PutStr( mes ); getCS(); i = GetHSPVarExpression( arbuf ); if ( i ) { out->PutStr( arbuf ); } if ( cstype == TYPE_MARK ) { if ( csval == CALCCODE_EQ ) { out->PutStr( "=" ); getCS(); MakeProgramInfoParam2(); break; } op = csval; getCS(); if ( exflag & EXFLG_1) { // ++ or -- out->PutStr( GetHSPOperator(op) ); out->PutStr( GetHSPOperator(op) ); MakeProgramInfoParam2(); break; } out->PutStr( GetHSPOperator(op) ); out->PutStr( "=" ); //getCS(); MakeProgramInfoParam2(); break; } Alert( "CHsp3:Var Syntax unknown." ); break; case TYPE_CMPCMD: // r if ( cmdval == 0 ) { out->PutStr( "if " ); iflevel++; if ( iflevel >= MAX_IFLEVEL ) { Alert( "Stack(If) overflow." ); return; } ifmode[iflevel] = 1; i = (int)*mcs; ifptr[iflevel] = mcs + i + 1; ifmode[iflevel]++; } else { out->PutStr( "} else {" ); ifmode[iflevel] = 3; i = (int)*mcs; ifptr[iflevel] = mcs + i + 1; } mcs++; getCS(); MakeProgramInfoParam2(); break; default: out->PutStr( GetHSPName( cstype, csval ) ); out->PutStr( " " ); getCS(); MakeProgramInfoParam2(); break; } } out->PutStr( "--------------------------------------------\n" ); } /*------------------------------------------------------------*/ int CHsp3::MakeSource( int option, void *ref ) { MakeObjectInfo(); MakeProgramInfo(); return 0; } int CHsp3::CheckExtLibrary( void ) { if ( GetLInfoCount() > 0 ) { return -1; } return 0; }
0
0.963598
1
0.963598
game-dev
MEDIA
0.235037
game-dev
0.975038
1
0.975038
Sandrem/FlyCasual
2,472
Assets/Scripts/Model/Content/SecondEdition/Standard/Upgrades/Astromech/R2Astromech.cs
using Upgrade; using UnityEngine; using Ship; using System; using System.Collections.Generic; using Tokens; using Content; namespace UpgradesList.SecondEdition { public class R2Astromech : GenericUpgrade { public R2Astromech() : base() { UpgradeInfo = new UpgradeCardInfo( "R2 Astromech", UpgradeType.Astromech, cost: 6, abilityType: typeof(Abilities.SecondEdition.R2AstromechAbility), charges: 2, seImageNumber: 53, legalityInfo: new List<Legality> { Legality.StandardBanned, Legality.ExtendedLegal } ); } } } namespace Abilities.SecondEdition { //After you reveal your dial, you may spend 1 charge and gain 1 disarm token to recover 1 shield. public class R2AstromechAbility : GenericAbility { public override void ActivateAbility() { HostShip.OnManeuverIsRevealed += PlanRegenShield; } public override void DeactivateAbility() { HostShip.OnManeuverIsRevealed -= PlanRegenShield; } private void PlanRegenShield(GenericShip host) { if (HostShip.State.ShieldsCurrent < HostShip.State.ShieldsMax && HostUpgrade.State.Charges > 0) { RegisterAbilityTrigger(TriggerTypes.OnManeuverIsRevealed, AskUseAbility); } } private void AskUseAbility(object sender, EventArgs e) { AskToUseAbility( HostUpgrade.UpgradeInfo.Name, NeverUseByDefault, RegenShield, descriptionLong: "Do you want to spend 1 Charge and gain 1 Disarm Token to recover 1 shield?", imageHolder: HostUpgrade ); } private void RegenShield(object sender, EventArgs e) { HostUpgrade.State.SpendCharge(); HostShip.Tokens.AssignToken(typeof(WeaponsDisabledToken), () => { if (HostShip.TryRegenShields()) { Sounds.PlayShipSound("R2D2-Proud"); Messages.ShowInfo(HostName + " causes " + HostShip.PilotInfo.PilotName + " to recover 1 shield and gain 1 disarm token"); } Triggers.FinishTrigger(); }); } } }
0
0.909885
1
0.909885
game-dev
MEDIA
0.97937
game-dev
0.754573
1
0.754573
ilpincy/argos3
36,983
src/plugins/simulator/physics_engines/dynamics3d/bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp
/* Bullet Continuous Collision Detection and Physics Library btConeTwistConstraint is Copyright (c) 2007 Starbreeze Studios 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. Written by: Marcus Hennix */ #include "btConeTwistConstraint.h" #include <argos3/plugins/simulator/physics_engines/dynamics3d/bullet/BulletDynamics/Dynamics/btRigidBody.h> #include <argos3/plugins/simulator/physics_engines/dynamics3d/bullet/LinearMath/btTransformUtil.h> #include <argos3/plugins/simulator/physics_engines/dynamics3d/bullet/LinearMath/btMinMax.h> #include <cmath> #include <new> //#define CONETWIST_USE_OBSOLETE_SOLVER true #define CONETWIST_USE_OBSOLETE_SOLVER false #define CONETWIST_DEF_FIX_THRESH btScalar(.05f) SIMD_FORCE_INLINE btScalar computeAngularImpulseDenominator(const btVector3& axis, const btMatrix3x3& invInertiaWorld) { btVector3 vec = axis * invInertiaWorld; return axis.dot(vec); } btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& rbAFrame, const btTransform& rbBFrame) : btTypedConstraint(CONETWIST_CONSTRAINT_TYPE, rbA, rbB), m_rbAFrame(rbAFrame), m_rbBFrame(rbBFrame), m_angularOnly(false), m_useSolveConstraintObsolete(CONETWIST_USE_OBSOLETE_SOLVER) { init(); } btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA, const btTransform& rbAFrame) : btTypedConstraint(CONETWIST_CONSTRAINT_TYPE, rbA), m_rbAFrame(rbAFrame), m_angularOnly(false), m_useSolveConstraintObsolete(CONETWIST_USE_OBSOLETE_SOLVER) { m_rbBFrame = m_rbAFrame; m_rbBFrame.setOrigin(btVector3(0., 0., 0.)); init(); } void btConeTwistConstraint::init() { m_angularOnly = false; m_solveTwistLimit = false; m_solveSwingLimit = false; m_bMotorEnabled = false; m_maxMotorImpulse = btScalar(-1); setLimit(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT)); m_damping = btScalar(0.01); m_fixThresh = CONETWIST_DEF_FIX_THRESH; m_flags = 0; m_linCFM = btScalar(0.f); m_linERP = btScalar(0.7f); m_angCFM = btScalar(0.f); } void btConeTwistConstraint::getInfo1(btConstraintInfo1* info) { if (m_useSolveConstraintObsolete) { info->m_numConstraintRows = 0; info->nub = 0; } else { info->m_numConstraintRows = 3; info->nub = 3; calcAngleInfo2(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform(), m_rbA.getInvInertiaTensorWorld(), m_rbB.getInvInertiaTensorWorld()); if (m_solveSwingLimit) { info->m_numConstraintRows++; info->nub--; if ((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh)) { info->m_numConstraintRows++; info->nub--; } } if (m_solveTwistLimit) { info->m_numConstraintRows++; info->nub--; } } } void btConeTwistConstraint::getInfo1NonVirtual(btConstraintInfo1* info) { //always reserve 6 rows: object transform is not available on SPU info->m_numConstraintRows = 6; info->nub = 0; } void btConeTwistConstraint::getInfo2(btConstraintInfo2* info) { getInfo2NonVirtual(info, m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform(), m_rbA.getInvInertiaTensorWorld(), m_rbB.getInvInertiaTensorWorld()); } void btConeTwistConstraint::getInfo2NonVirtual(btConstraintInfo2* info, const btTransform& transA, const btTransform& transB, const btMatrix3x3& invInertiaWorldA, const btMatrix3x3& invInertiaWorldB) { calcAngleInfo2(transA, transB, invInertiaWorldA, invInertiaWorldB); btAssert(!m_useSolveConstraintObsolete); // set jacobian info->m_J1linearAxis[0] = 1; info->m_J1linearAxis[info->rowskip + 1] = 1; info->m_J1linearAxis[2 * info->rowskip + 2] = 1; btVector3 a1 = transA.getBasis() * m_rbAFrame.getOrigin(); { btVector3* angular0 = (btVector3*)(info->m_J1angularAxis); btVector3* angular1 = (btVector3*)(info->m_J1angularAxis + info->rowskip); btVector3* angular2 = (btVector3*)(info->m_J1angularAxis + 2 * info->rowskip); btVector3 a1neg = -a1; a1neg.getSkewSymmetricMatrix(angular0, angular1, angular2); } info->m_J2linearAxis[0] = -1; info->m_J2linearAxis[info->rowskip + 1] = -1; info->m_J2linearAxis[2 * info->rowskip + 2] = -1; btVector3 a2 = transB.getBasis() * m_rbBFrame.getOrigin(); { btVector3* angular0 = (btVector3*)(info->m_J2angularAxis); btVector3* angular1 = (btVector3*)(info->m_J2angularAxis + info->rowskip); btVector3* angular2 = (btVector3*)(info->m_J2angularAxis + 2 * info->rowskip); a2.getSkewSymmetricMatrix(angular0, angular1, angular2); } // set right hand side btScalar linERP = (m_flags & BT_CONETWIST_FLAGS_LIN_ERP) ? m_linERP : info->erp; btScalar k = info->fps * linERP; int j; for (j = 0; j < 3; j++) { info->m_constraintError[j * info->rowskip] = k * (a2[j] + transB.getOrigin()[j] - a1[j] - transA.getOrigin()[j]); info->m_lowerLimit[j * info->rowskip] = -SIMD_INFINITY; info->m_upperLimit[j * info->rowskip] = SIMD_INFINITY; if (m_flags & BT_CONETWIST_FLAGS_LIN_CFM) { info->cfm[j * info->rowskip] = m_linCFM; } } int row = 3; int srow = row * info->rowskip; btVector3 ax1; // angular limits if (m_solveSwingLimit) { btScalar* J1 = info->m_J1angularAxis; btScalar* J2 = info->m_J2angularAxis; if ((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh)) { btTransform trA = transA * m_rbAFrame; btVector3 p = trA.getBasis().getColumn(1); btVector3 q = trA.getBasis().getColumn(2); int srow1 = srow + info->rowskip; J1[srow + 0] = p[0]; J1[srow + 1] = p[1]; J1[srow + 2] = p[2]; J1[srow1 + 0] = q[0]; J1[srow1 + 1] = q[1]; J1[srow1 + 2] = q[2]; J2[srow + 0] = -p[0]; J2[srow + 1] = -p[1]; J2[srow + 2] = -p[2]; J2[srow1 + 0] = -q[0]; J2[srow1 + 1] = -q[1]; J2[srow1 + 2] = -q[2]; btScalar fact = info->fps * m_relaxationFactor; info->m_constraintError[srow] = fact * m_swingAxis.dot(p); info->m_constraintError[srow1] = fact * m_swingAxis.dot(q); info->m_lowerLimit[srow] = -SIMD_INFINITY; info->m_upperLimit[srow] = SIMD_INFINITY; info->m_lowerLimit[srow1] = -SIMD_INFINITY; info->m_upperLimit[srow1] = SIMD_INFINITY; srow = srow1 + info->rowskip; } else { ax1 = m_swingAxis * m_relaxationFactor * m_relaxationFactor; J1[srow + 0] = ax1[0]; J1[srow + 1] = ax1[1]; J1[srow + 2] = ax1[2]; J2[srow + 0] = -ax1[0]; J2[srow + 1] = -ax1[1]; J2[srow + 2] = -ax1[2]; btScalar k = info->fps * m_biasFactor; info->m_constraintError[srow] = k * m_swingCorrection; if (m_flags & BT_CONETWIST_FLAGS_ANG_CFM) { info->cfm[srow] = m_angCFM; } // m_swingCorrection is always positive or 0 info->m_lowerLimit[srow] = 0; info->m_upperLimit[srow] = (m_bMotorEnabled && m_maxMotorImpulse >= 0.0f) ? m_maxMotorImpulse : SIMD_INFINITY; srow += info->rowskip; } } if (m_solveTwistLimit) { ax1 = m_twistAxis * m_relaxationFactor * m_relaxationFactor; btScalar* J1 = info->m_J1angularAxis; btScalar* J2 = info->m_J2angularAxis; J1[srow + 0] = ax1[0]; J1[srow + 1] = ax1[1]; J1[srow + 2] = ax1[2]; J2[srow + 0] = -ax1[0]; J2[srow + 1] = -ax1[1]; J2[srow + 2] = -ax1[2]; btScalar k = info->fps * m_biasFactor; info->m_constraintError[srow] = k * m_twistCorrection; if (m_flags & BT_CONETWIST_FLAGS_ANG_CFM) { info->cfm[srow] = m_angCFM; } if (m_twistSpan > 0.0f) { if (m_twistCorrection > 0.0f) { info->m_lowerLimit[srow] = 0; info->m_upperLimit[srow] = SIMD_INFINITY; } else { info->m_lowerLimit[srow] = -SIMD_INFINITY; info->m_upperLimit[srow] = 0; } } else { info->m_lowerLimit[srow] = -SIMD_INFINITY; info->m_upperLimit[srow] = SIMD_INFINITY; } srow += info->rowskip; } } void btConeTwistConstraint::buildJacobian() { if (m_useSolveConstraintObsolete) { m_appliedImpulse = btScalar(0.); m_accTwistLimitImpulse = btScalar(0.); m_accSwingLimitImpulse = btScalar(0.); m_accMotorImpulse = btVector3(0., 0., 0.); if (!m_angularOnly) { btVector3 pivotAInW = m_rbA.getCenterOfMassTransform() * m_rbAFrame.getOrigin(); btVector3 pivotBInW = m_rbB.getCenterOfMassTransform() * m_rbBFrame.getOrigin(); btVector3 relPos = pivotBInW - pivotAInW; btVector3 normal[3]; if (relPos.length2() > SIMD_EPSILON) { normal[0] = relPos.normalized(); } else { normal[0].setValue(btScalar(1.0), 0, 0); } btPlaneSpace1(normal[0], normal[1], normal[2]); for (int i = 0; i < 3; i++) { new (&m_jac[i]) btJacobianEntry( m_rbA.getCenterOfMassTransform().getBasis().transpose(), m_rbB.getCenterOfMassTransform().getBasis().transpose(), pivotAInW - m_rbA.getCenterOfMassPosition(), pivotBInW - m_rbB.getCenterOfMassPosition(), normal[i], m_rbA.getInvInertiaDiagLocal(), m_rbA.getInvMass(), m_rbB.getInvInertiaDiagLocal(), m_rbB.getInvMass()); } } calcAngleInfo2(m_rbA.getCenterOfMassTransform(), m_rbB.getCenterOfMassTransform(), m_rbA.getInvInertiaTensorWorld(), m_rbB.getInvInertiaTensorWorld()); } } void btConeTwistConstraint::solveConstraintObsolete(btSolverBody& bodyA, btSolverBody& bodyB, btScalar timeStep) { #ifndef __SPU__ if (m_useSolveConstraintObsolete) { btVector3 pivotAInW = m_rbA.getCenterOfMassTransform() * m_rbAFrame.getOrigin(); btVector3 pivotBInW = m_rbB.getCenterOfMassTransform() * m_rbBFrame.getOrigin(); btScalar tau = btScalar(0.3); //linear part if (!m_angularOnly) { btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); btVector3 vel1; bodyA.internalGetVelocityInLocalPointObsolete(rel_pos1, vel1); btVector3 vel2; bodyB.internalGetVelocityInLocalPointObsolete(rel_pos2, vel2); btVector3 vel = vel1 - vel2; for (int i = 0; i < 3; i++) { const btVector3& normal = m_jac[i].m_linearJointAxis; btScalar jacDiagABInv = btScalar(1.) / m_jac[i].getDiagonal(); btScalar rel_vel; rel_vel = normal.dot(vel); //positional error (zeroth order error) btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal btScalar impulse = depth * tau / timeStep * jacDiagABInv - rel_vel * jacDiagABInv; m_appliedImpulse += impulse; btVector3 ftorqueAxis1 = rel_pos1.cross(normal); btVector3 ftorqueAxis2 = rel_pos2.cross(normal); bodyA.internalApplyImpulse(normal * m_rbA.getInvMass(), m_rbA.getInvInertiaTensorWorld() * ftorqueAxis1, impulse); bodyB.internalApplyImpulse(normal * m_rbB.getInvMass(), m_rbB.getInvInertiaTensorWorld() * ftorqueAxis2, -impulse); } } // apply motor if (m_bMotorEnabled) { // compute current and predicted transforms btTransform trACur = m_rbA.getCenterOfMassTransform(); btTransform trBCur = m_rbB.getCenterOfMassTransform(); btVector3 omegaA; bodyA.internalGetAngularVelocity(omegaA); btVector3 omegaB; bodyB.internalGetAngularVelocity(omegaB); btTransform trAPred; trAPred.setIdentity(); btVector3 zerovec(0, 0, 0); btTransformUtil::integrateTransform( trACur, zerovec, omegaA, timeStep, trAPred); btTransform trBPred; trBPred.setIdentity(); btTransformUtil::integrateTransform( trBCur, zerovec, omegaB, timeStep, trBPred); // compute desired transforms in world btTransform trPose(m_qTarget); btTransform trABDes = m_rbBFrame * trPose * m_rbAFrame.inverse(); btTransform trADes = trBPred * trABDes; btTransform trBDes = trAPred * trABDes.inverse(); // compute desired omegas in world btVector3 omegaADes, omegaBDes; btTransformUtil::calculateVelocity(trACur, trADes, timeStep, zerovec, omegaADes); btTransformUtil::calculateVelocity(trBCur, trBDes, timeStep, zerovec, omegaBDes); // compute delta omegas btVector3 dOmegaA = omegaADes - omegaA; btVector3 dOmegaB = omegaBDes - omegaB; // compute weighted avg axis of dOmega (weighting based on inertias) btVector3 axisA, axisB; btScalar kAxisAInv = 0, kAxisBInv = 0; if (dOmegaA.length2() > SIMD_EPSILON) { axisA = dOmegaA.normalized(); kAxisAInv = getRigidBodyA().computeAngularImpulseDenominator(axisA); } if (dOmegaB.length2() > SIMD_EPSILON) { axisB = dOmegaB.normalized(); kAxisBInv = getRigidBodyB().computeAngularImpulseDenominator(axisB); } btVector3 avgAxis = kAxisAInv * axisA + kAxisBInv * axisB; static bool bDoTorque = true; if (bDoTorque && avgAxis.length2() > SIMD_EPSILON) { avgAxis.normalize(); kAxisAInv = getRigidBodyA().computeAngularImpulseDenominator(avgAxis); kAxisBInv = getRigidBodyB().computeAngularImpulseDenominator(avgAxis); btScalar kInvCombined = kAxisAInv + kAxisBInv; btVector3 impulse = (kAxisAInv * dOmegaA - kAxisBInv * dOmegaB) / (kInvCombined * kInvCombined); if (m_maxMotorImpulse >= 0) { btScalar fMaxImpulse = m_maxMotorImpulse; if (m_bNormalizedMotorStrength) fMaxImpulse = fMaxImpulse / kAxisAInv; btVector3 newUnclampedAccImpulse = m_accMotorImpulse + impulse; btScalar newUnclampedMag = newUnclampedAccImpulse.length(); if (newUnclampedMag > fMaxImpulse) { newUnclampedAccImpulse.normalize(); newUnclampedAccImpulse *= fMaxImpulse; impulse = newUnclampedAccImpulse - m_accMotorImpulse; } m_accMotorImpulse += impulse; } btScalar impulseMag = impulse.length(); btVector3 impulseAxis = impulse / impulseMag; bodyA.internalApplyImpulse(btVector3(0, 0, 0), m_rbA.getInvInertiaTensorWorld() * impulseAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0, 0, 0), m_rbB.getInvInertiaTensorWorld() * impulseAxis, -impulseMag); } } else if (m_damping > SIMD_EPSILON) // no motor: do a little damping { btVector3 angVelA; bodyA.internalGetAngularVelocity(angVelA); btVector3 angVelB; bodyB.internalGetAngularVelocity(angVelB); btVector3 relVel = angVelB - angVelA; if (relVel.length2() > SIMD_EPSILON) { btVector3 relVelAxis = relVel.normalized(); btScalar m_kDamping = btScalar(1.) / (getRigidBodyA().computeAngularImpulseDenominator(relVelAxis) + getRigidBodyB().computeAngularImpulseDenominator(relVelAxis)); btVector3 impulse = m_damping * m_kDamping * relVel; btScalar impulseMag = impulse.length(); btVector3 impulseAxis = impulse / impulseMag; bodyA.internalApplyImpulse(btVector3(0, 0, 0), m_rbA.getInvInertiaTensorWorld() * impulseAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0, 0, 0), m_rbB.getInvInertiaTensorWorld() * impulseAxis, -impulseMag); } } // joint limits { ///solve angular part btVector3 angVelA; bodyA.internalGetAngularVelocity(angVelA); btVector3 angVelB; bodyB.internalGetAngularVelocity(angVelB); // solve swing limit if (m_solveSwingLimit) { btScalar amplitude = m_swingLimitRatio * m_swingCorrection * m_biasFactor / timeStep; btScalar relSwingVel = (angVelB - angVelA).dot(m_swingAxis); if (relSwingVel > 0) amplitude += m_swingLimitRatio * relSwingVel * m_relaxationFactor; btScalar impulseMag = amplitude * m_kSwing; // Clamp the accumulated impulse btScalar temp = m_accSwingLimitImpulse; m_accSwingLimitImpulse = btMax(m_accSwingLimitImpulse + impulseMag, btScalar(0.0)); impulseMag = m_accSwingLimitImpulse - temp; btVector3 impulse = m_swingAxis * impulseMag; // don't let cone response affect twist // (this can happen since body A's twist doesn't match body B's AND we use an elliptical cone limit) { btVector3 impulseTwistCouple = impulse.dot(m_twistAxisA) * m_twistAxisA; btVector3 impulseNoTwistCouple = impulse - impulseTwistCouple; impulse = impulseNoTwistCouple; } impulseMag = impulse.length(); btVector3 noTwistSwingAxis = impulse / impulseMag; bodyA.internalApplyImpulse(btVector3(0, 0, 0), m_rbA.getInvInertiaTensorWorld() * noTwistSwingAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0, 0, 0), m_rbB.getInvInertiaTensorWorld() * noTwistSwingAxis, -impulseMag); } // solve twist limit if (m_solveTwistLimit) { btScalar amplitude = m_twistLimitRatio * m_twistCorrection * m_biasFactor / timeStep; btScalar relTwistVel = (angVelB - angVelA).dot(m_twistAxis); if (relTwistVel > 0) // only damp when moving towards limit (m_twistAxis flipping is important) amplitude += m_twistLimitRatio * relTwistVel * m_relaxationFactor; btScalar impulseMag = amplitude * m_kTwist; // Clamp the accumulated impulse btScalar temp = m_accTwistLimitImpulse; m_accTwistLimitImpulse = btMax(m_accTwistLimitImpulse + impulseMag, btScalar(0.0)); impulseMag = m_accTwistLimitImpulse - temp; // btVector3 impulse = m_twistAxis * impulseMag; bodyA.internalApplyImpulse(btVector3(0, 0, 0), m_rbA.getInvInertiaTensorWorld() * m_twistAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0, 0, 0), m_rbB.getInvInertiaTensorWorld() * m_twistAxis, -impulseMag); } } } #else btAssert(0); #endif //__SPU__ } void btConeTwistConstraint::updateRHS(btScalar timeStep) { (void)timeStep; } #ifndef __SPU__ void btConeTwistConstraint::calcAngleInfo() { m_swingCorrection = btScalar(0.); m_twistLimitSign = btScalar(0.); m_solveTwistLimit = false; m_solveSwingLimit = false; btVector3 b1Axis1(0, 0, 0), b1Axis2(0, 0, 0), b1Axis3(0, 0, 0); btVector3 b2Axis1(0, 0, 0), b2Axis2(0, 0, 0); b1Axis1 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(0); b2Axis1 = getRigidBodyB().getCenterOfMassTransform().getBasis() * this->m_rbBFrame.getBasis().getColumn(0); btScalar swing1 = btScalar(0.), swing2 = btScalar(0.); btScalar swx = btScalar(0.), swy = btScalar(0.); btScalar thresh = btScalar(10.); btScalar fact; // Get Frame into world space if (m_swingSpan1 >= btScalar(0.05f)) { b1Axis2 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(1); swx = b2Axis1.dot(b1Axis1); swy = b2Axis1.dot(b1Axis2); swing1 = btAtan2Fast(swy, swx); fact = (swy * swy + swx * swx) * thresh * thresh; fact = fact / (fact + btScalar(1.0)); swing1 *= fact; } if (m_swingSpan2 >= btScalar(0.05f)) { b1Axis3 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(2); swx = b2Axis1.dot(b1Axis1); swy = b2Axis1.dot(b1Axis3); swing2 = btAtan2Fast(swy, swx); fact = (swy * swy + swx * swx) * thresh * thresh; fact = fact / (fact + btScalar(1.0)); swing2 *= fact; } btScalar RMaxAngle1Sq = 1.0f / (m_swingSpan1 * m_swingSpan1); btScalar RMaxAngle2Sq = 1.0f / (m_swingSpan2 * m_swingSpan2); btScalar EllipseAngle = btFabs(swing1 * swing1) * RMaxAngle1Sq + btFabs(swing2 * swing2) * RMaxAngle2Sq; if (EllipseAngle > 1.0f) { m_swingCorrection = EllipseAngle - 1.0f; m_solveSwingLimit = true; // Calculate necessary axis & factors m_swingAxis = b2Axis1.cross(b1Axis2 * b2Axis1.dot(b1Axis2) + b1Axis3 * b2Axis1.dot(b1Axis3)); m_swingAxis.normalize(); btScalar swingAxisSign = (b2Axis1.dot(b1Axis1) >= 0.0f) ? 1.0f : -1.0f; m_swingAxis *= swingAxisSign; } // Twist limits if (m_twistSpan >= btScalar(0.)) { btVector3 b2Axis2 = getRigidBodyB().getCenterOfMassTransform().getBasis() * this->m_rbBFrame.getBasis().getColumn(1); btQuaternion rotationArc = shortestArcQuat(b2Axis1, b1Axis1); btVector3 TwistRef = quatRotate(rotationArc, b2Axis2); btScalar twist = btAtan2Fast(TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2)); m_twistAngle = twist; // btScalar lockedFreeFactor = (m_twistSpan > btScalar(0.05f)) ? m_limitSoftness : btScalar(0.); btScalar lockedFreeFactor = (m_twistSpan > btScalar(0.05f)) ? btScalar(1.0f) : btScalar(0.); if (twist <= -m_twistSpan * lockedFreeFactor) { m_twistCorrection = -(twist + m_twistSpan); m_solveTwistLimit = true; m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f; m_twistAxis.normalize(); m_twistAxis *= -1.0f; } else if (twist > m_twistSpan * lockedFreeFactor) { m_twistCorrection = (twist - m_twistSpan); m_solveTwistLimit = true; m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f; m_twistAxis.normalize(); } } } #endif //__SPU__ static btVector3 vTwist(1, 0, 0); // twist axis in constraint's space void btConeTwistConstraint::calcAngleInfo2(const btTransform& transA, const btTransform& transB, const btMatrix3x3& invInertiaWorldA, const btMatrix3x3& invInertiaWorldB) { m_swingCorrection = btScalar(0.); m_twistLimitSign = btScalar(0.); m_solveTwistLimit = false; m_solveSwingLimit = false; // compute rotation of A wrt B (in constraint space) if (m_bMotorEnabled && (!m_useSolveConstraintObsolete)) { // it is assumed that setMotorTarget() was alredy called // and motor target m_qTarget is within constraint limits // TODO : split rotation to pure swing and pure twist // compute desired transforms in world btTransform trPose(m_qTarget); btTransform trA = transA * m_rbAFrame; btTransform trB = transB * m_rbBFrame; btTransform trDeltaAB = trB * trPose * trA.inverse(); btQuaternion qDeltaAB = trDeltaAB.getRotation(); btVector3 swingAxis = btVector3(qDeltaAB.x(), qDeltaAB.y(), qDeltaAB.z()); btScalar swingAxisLen2 = swingAxis.length2(); if (btFuzzyZero(swingAxisLen2)) { return; } m_swingAxis = swingAxis; m_swingAxis.normalize(); m_swingCorrection = qDeltaAB.getAngle(); if (!btFuzzyZero(m_swingCorrection)) { m_solveSwingLimit = true; } return; } { // compute rotation of A wrt B (in constraint space) btQuaternion qA = transA.getRotation() * m_rbAFrame.getRotation(); btQuaternion qB = transB.getRotation() * m_rbBFrame.getRotation(); btQuaternion qAB = qB.inverse() * qA; // split rotation into cone and twist // (all this is done from B's perspective. Maybe I should be averaging axes...) btVector3 vConeNoTwist = quatRotate(qAB, vTwist); vConeNoTwist.normalize(); btQuaternion qABCone = shortestArcQuat(vTwist, vConeNoTwist); qABCone.normalize(); btQuaternion qABTwist = qABCone.inverse() * qAB; qABTwist.normalize(); if (m_swingSpan1 >= m_fixThresh && m_swingSpan2 >= m_fixThresh) { btScalar swingAngle, swingLimit = 0; btVector3 swingAxis; computeConeLimitInfo(qABCone, swingAngle, swingAxis, swingLimit); if (swingAngle > swingLimit * m_limitSoftness) { m_solveSwingLimit = true; // compute limit ratio: 0->1, where // 0 == beginning of soft limit // 1 == hard/real limit m_swingLimitRatio = 1.f; if (swingAngle < swingLimit && m_limitSoftness < 1.f - SIMD_EPSILON) { m_swingLimitRatio = (swingAngle - swingLimit * m_limitSoftness) / (swingLimit - swingLimit * m_limitSoftness); } // swing correction tries to get back to soft limit m_swingCorrection = swingAngle - (swingLimit * m_limitSoftness); // adjustment of swing axis (based on ellipse normal) adjustSwingAxisToUseEllipseNormal(swingAxis); // Calculate necessary axis & factors m_swingAxis = quatRotate(qB, -swingAxis); m_twistAxisA.setValue(0, 0, 0); m_kSwing = btScalar(1.) / (computeAngularImpulseDenominator(m_swingAxis, invInertiaWorldA) + computeAngularImpulseDenominator(m_swingAxis, invInertiaWorldB)); } } else { // you haven't set any limits; // or you're trying to set at least one of the swing limits too small. (if so, do you really want a conetwist constraint?) // anyway, we have either hinge or fixed joint btVector3 ivA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(0); btVector3 jvA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(1); btVector3 kvA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(2); btVector3 ivB = transB.getBasis() * m_rbBFrame.getBasis().getColumn(0); btVector3 target; btScalar x = ivB.dot(ivA); btScalar y = ivB.dot(jvA); btScalar z = ivB.dot(kvA); if ((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh)) { // fixed. We'll need to add one more row to constraint if ((!btFuzzyZero(y)) || (!(btFuzzyZero(z)))) { m_solveSwingLimit = true; m_swingAxis = -ivB.cross(ivA); } } else { if (m_swingSpan1 < m_fixThresh) { // hinge around Y axis // if(!(btFuzzyZero(y))) if ((!(btFuzzyZero(x))) || (!(btFuzzyZero(z)))) { m_solveSwingLimit = true; if (m_swingSpan2 >= m_fixThresh) { y = btScalar(0.f); btScalar span2 = btAtan2(z, x); if (span2 > m_swingSpan2) { x = btCos(m_swingSpan2); z = btSin(m_swingSpan2); } else if (span2 < -m_swingSpan2) { x = btCos(m_swingSpan2); z = -btSin(m_swingSpan2); } } } } else { // hinge around Z axis // if(!btFuzzyZero(z)) if ((!(btFuzzyZero(x))) || (!(btFuzzyZero(y)))) { m_solveSwingLimit = true; if (m_swingSpan1 >= m_fixThresh) { z = btScalar(0.f); btScalar span1 = btAtan2(y, x); if (span1 > m_swingSpan1) { x = btCos(m_swingSpan1); y = btSin(m_swingSpan1); } else if (span1 < -m_swingSpan1) { x = btCos(m_swingSpan1); y = -btSin(m_swingSpan1); } } } } target[0] = x * ivA[0] + y * jvA[0] + z * kvA[0]; target[1] = x * ivA[1] + y * jvA[1] + z * kvA[1]; target[2] = x * ivA[2] + y * jvA[2] + z * kvA[2]; target.normalize(); m_swingAxis = -ivB.cross(target); m_swingCorrection = m_swingAxis.length(); if (!btFuzzyZero(m_swingCorrection)) m_swingAxis.normalize(); } } if (m_twistSpan >= btScalar(0.f)) { btVector3 twistAxis; computeTwistLimitInfo(qABTwist, m_twistAngle, twistAxis); if (m_twistAngle > m_twistSpan * m_limitSoftness) { m_solveTwistLimit = true; m_twistLimitRatio = 1.f; if (m_twistAngle < m_twistSpan && m_limitSoftness < 1.f - SIMD_EPSILON) { m_twistLimitRatio = (m_twistAngle - m_twistSpan * m_limitSoftness) / (m_twistSpan - m_twistSpan * m_limitSoftness); } // twist correction tries to get back to soft limit m_twistCorrection = m_twistAngle - (m_twistSpan * m_limitSoftness); m_twistAxis = quatRotate(qB, -twistAxis); m_kTwist = btScalar(1.) / (computeAngularImpulseDenominator(m_twistAxis, invInertiaWorldA) + computeAngularImpulseDenominator(m_twistAxis, invInertiaWorldB)); } if (m_solveSwingLimit) m_twistAxisA = quatRotate(qA, -twistAxis); } else { m_twistAngle = btScalar(0.f); } } } // given a cone rotation in constraint space, (pre: twist must already be removed) // this method computes its corresponding swing angle and axis. // more interestingly, it computes the cone/swing limit (angle) for this cone "pose". void btConeTwistConstraint::computeConeLimitInfo(const btQuaternion& qCone, btScalar& swingAngle, // out btVector3& vSwingAxis, // out btScalar& swingLimit) // out { swingAngle = qCone.getAngle(); if (swingAngle > SIMD_EPSILON) { vSwingAxis = btVector3(qCone.x(), qCone.y(), qCone.z()); vSwingAxis.normalize(); #if 0 // non-zero twist?! this should never happen. btAssert(fabs(vSwingAxis.x()) <= SIMD_EPSILON)); #endif // Compute limit for given swing. tricky: // Given a swing axis, we're looking for the intersection with the bounding cone ellipse. // (Since we're dealing with angles, this ellipse is embedded on the surface of a sphere.) // For starters, compute the direction from center to surface of ellipse. // This is just the perpendicular (ie. rotate 2D vector by PI/2) of the swing axis. // (vSwingAxis is the cone rotation (in z,y); change vars and rotate to (x,y) coords.) btScalar xEllipse = vSwingAxis.y(); btScalar yEllipse = -vSwingAxis.z(); // Now, we use the slope of the vector (using x/yEllipse) and find the length // of the line that intersects the ellipse: // x^2 y^2 // --- + --- = 1, where a and b are semi-major axes 2 and 1 respectively (ie. the limits) // a^2 b^2 // Do the math and it should be clear. swingLimit = m_swingSpan1; // if xEllipse == 0, we have a pure vSwingAxis.z rotation: just use swingspan1 if (fabs(xEllipse) > SIMD_EPSILON) { btScalar surfaceSlope2 = (yEllipse * yEllipse) / (xEllipse * xEllipse); btScalar norm = 1 / (m_swingSpan2 * m_swingSpan2); norm += surfaceSlope2 / (m_swingSpan1 * m_swingSpan1); btScalar swingLimit2 = (1 + surfaceSlope2) / norm; swingLimit = std::sqrt(swingLimit2); } // test! /*swingLimit = m_swingSpan2; if (fabs(vSwingAxis.z()) > SIMD_EPSILON) { btScalar mag_2 = m_swingSpan1*m_swingSpan1 + m_swingSpan2*m_swingSpan2; btScalar sinphi = m_swingSpan2 / sqrt(mag_2); btScalar phi = asin(sinphi); btScalar theta = atan2(fabs(vSwingAxis.y()),fabs(vSwingAxis.z())); btScalar alpha = 3.14159f - theta - phi; btScalar sinalpha = sin(alpha); swingLimit = m_swingSpan1 * sinphi/sinalpha; }*/ } else if (swingAngle < 0) { // this should never happen! #if 0 btAssert(0); #endif } } btVector3 btConeTwistConstraint::GetPointForAngle(btScalar fAngleInRadians, btScalar fLength) const { // compute x/y in ellipse using cone angle (0 -> 2*PI along surface of cone) btScalar xEllipse = btCos(fAngleInRadians); btScalar yEllipse = btSin(fAngleInRadians); // Use the slope of the vector (using x/yEllipse) and find the length // of the line that intersects the ellipse: // x^2 y^2 // --- + --- = 1, where a and b are semi-major axes 2 and 1 respectively (ie. the limits) // a^2 b^2 // Do the math and it should be clear. btScalar swingLimit = m_swingSpan1; // if xEllipse == 0, just use axis b (1) if (fabs(xEllipse) > SIMD_EPSILON) { btScalar surfaceSlope2 = (yEllipse * yEllipse) / (xEllipse * xEllipse); btScalar norm = 1 / (m_swingSpan2 * m_swingSpan2); norm += surfaceSlope2 / (m_swingSpan1 * m_swingSpan1); btScalar swingLimit2 = (1 + surfaceSlope2) / norm; swingLimit = std::sqrt(swingLimit2); } // convert into point in constraint space: // note: twist is x-axis, swing 1 and 2 are along the z and y axes respectively btVector3 vSwingAxis(0, xEllipse, -yEllipse); btQuaternion qSwing(vSwingAxis, swingLimit); btVector3 vPointInConstraintSpace(fLength, 0, 0); return quatRotate(qSwing, vPointInConstraintSpace); } // given a twist rotation in constraint space, (pre: cone must already be removed) // this method computes its corresponding angle and axis. void btConeTwistConstraint::computeTwistLimitInfo(const btQuaternion& qTwist, btScalar& twistAngle, // out btVector3& vTwistAxis) // out { btQuaternion qMinTwist = qTwist; twistAngle = qTwist.getAngle(); if (twistAngle > SIMD_PI) // long way around. flip quat and recalculate. { qMinTwist = -(qTwist); twistAngle = qMinTwist.getAngle(); } if (twistAngle < 0) { // this should never happen #if 0 btAssert(0); #endif } vTwistAxis = btVector3(qMinTwist.x(), qMinTwist.y(), qMinTwist.z()); if (twistAngle > SIMD_EPSILON) vTwistAxis.normalize(); } void btConeTwistConstraint::adjustSwingAxisToUseEllipseNormal(btVector3& vSwingAxis) const { // the swing axis is computed as the "twist-free" cone rotation, // but the cone limit is not circular, but elliptical (if swingspan1 != swingspan2). // so, if we're outside the limits, the closest way back inside the cone isn't // along the vector back to the center. better (and more stable) to use the ellipse normal. // convert swing axis to direction from center to surface of ellipse // (ie. rotate 2D vector by PI/2) btScalar y = -vSwingAxis.z(); btScalar z = vSwingAxis.y(); // do the math... if (fabs(z) > SIMD_EPSILON) // avoid division by 0. and we don't need an update if z == 0. { // compute gradient/normal of ellipse surface at current "point" btScalar grad = y / z; grad *= m_swingSpan2 / m_swingSpan1; // adjust y/z to represent normal at point (instead of vector to point) if (y > 0) y = fabs(grad * z); else y = -fabs(grad * z); // convert ellipse direction back to swing axis vSwingAxis.setZ(-y); vSwingAxis.setY(z); vSwingAxis.normalize(); } } void btConeTwistConstraint::setMotorTarget(const btQuaternion& q) { //btTransform trACur = m_rbA.getCenterOfMassTransform(); //btTransform trBCur = m_rbB.getCenterOfMassTransform(); // btTransform trABCur = trBCur.inverse() * trACur; // btQuaternion qABCur = trABCur.getRotation(); // btTransform trConstraintCur = (trBCur * m_rbBFrame).inverse() * (trACur * m_rbAFrame); //btQuaternion qConstraintCur = trConstraintCur.getRotation(); btQuaternion qConstraint = m_rbBFrame.getRotation().inverse() * q * m_rbAFrame.getRotation(); setMotorTargetInConstraintSpace(qConstraint); } void btConeTwistConstraint::setMotorTargetInConstraintSpace(const btQuaternion& q) { m_qTarget = q; // clamp motor target to within limits { btScalar softness = 1.f; //m_limitSoftness; // split into twist and cone btVector3 vTwisted = quatRotate(m_qTarget, vTwist); btQuaternion qTargetCone = shortestArcQuat(vTwist, vTwisted); qTargetCone.normalize(); btQuaternion qTargetTwist = qTargetCone.inverse() * m_qTarget; qTargetTwist.normalize(); // clamp cone if (m_swingSpan1 >= btScalar(0.05f) && m_swingSpan2 >= btScalar(0.05f)) { btScalar swingAngle, swingLimit; btVector3 swingAxis; computeConeLimitInfo(qTargetCone, swingAngle, swingAxis, swingLimit); if (fabs(swingAngle) > SIMD_EPSILON) { if (swingAngle > swingLimit * softness) swingAngle = swingLimit * softness; else if (swingAngle < -swingLimit * softness) swingAngle = -swingLimit * softness; qTargetCone = btQuaternion(swingAxis, swingAngle); } } // clamp twist if (m_twistSpan >= btScalar(0.05f)) { btScalar twistAngle; btVector3 twistAxis; computeTwistLimitInfo(qTargetTwist, twistAngle, twistAxis); if (fabs(twistAngle) > SIMD_EPSILON) { // eddy todo: limitSoftness used here??? if (twistAngle > m_twistSpan * softness) twistAngle = m_twistSpan * softness; else if (twistAngle < -m_twistSpan * softness) twistAngle = -m_twistSpan * softness; qTargetTwist = btQuaternion(twistAxis, twistAngle); } } m_qTarget = qTargetCone * qTargetTwist; } } ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5). ///If no axis is provided, it uses the default axis for this constraint. void btConeTwistConstraint::setParam(int num, btScalar value, int axis) { switch (num) { case BT_CONSTRAINT_ERP: case BT_CONSTRAINT_STOP_ERP: if ((axis >= 0) && (axis < 3)) { m_linERP = value; m_flags |= BT_CONETWIST_FLAGS_LIN_ERP; } else { m_biasFactor = value; } break; case BT_CONSTRAINT_CFM: case BT_CONSTRAINT_STOP_CFM: if ((axis >= 0) && (axis < 3)) { m_linCFM = value; m_flags |= BT_CONETWIST_FLAGS_LIN_CFM; } else { m_angCFM = value; m_flags |= BT_CONETWIST_FLAGS_ANG_CFM; } break; default: btAssertConstrParams(0); break; } } ///return the local value of parameter btScalar btConeTwistConstraint::getParam(int num, int axis) const { btScalar retVal = 0; switch (num) { case BT_CONSTRAINT_ERP: case BT_CONSTRAINT_STOP_ERP: if ((axis >= 0) && (axis < 3)) { btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_LIN_ERP); retVal = m_linERP; } else if ((axis >= 3) && (axis < 6)) { retVal = m_biasFactor; } else { btAssertConstrParams(0); } break; case BT_CONSTRAINT_CFM: case BT_CONSTRAINT_STOP_CFM: if ((axis >= 0) && (axis < 3)) { btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_LIN_CFM); retVal = m_linCFM; } else if ((axis >= 3) && (axis < 6)) { btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_ANG_CFM); retVal = m_angCFM; } else { btAssertConstrParams(0); } break; default: btAssertConstrParams(0); } return retVal; } void btConeTwistConstraint::setFrames(const btTransform& frameA, const btTransform& frameB) { m_rbAFrame = frameA; m_rbBFrame = frameB; buildJacobian(); //calculateTransforms(); }
0
0.962357
1
0.962357
game-dev
MEDIA
0.969231
game-dev
0.988077
1
0.988077
EngineHub/WorldEdit
4,686
worldedit-cli/src/main/java/com/sk89q/worldedit/cli/CLIPlatform.java
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * 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 <https://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.cli; import com.google.common.collect.ImmutableSet; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.AbstractPlatform; import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Preference; import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.world.DataFixer; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.world.registry.Registries; import org.enginehub.piston.CommandManager; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import javax.annotation.Nullable; class CLIPlatform extends AbstractPlatform { private final CLIWorldEdit app; private int dataVersion = -1; private final List<World> worlds = new ArrayList<>(); private final Timer timer = new Timer(); private int lastTimerId = 0; CLIPlatform(CLIWorldEdit app) { this.app = app; } @Override public Registries getRegistries() { return CLIRegistries.getInstance(); } @Override public int getDataVersion() { return this.dataVersion; } public void setDataVersion(int dataVersion) { this.dataVersion = dataVersion; } @Override public DataFixer getDataFixer() { return null; } @Override public boolean isValidMobType(String type) { return EntityTypes.get(type) != null; } @Override public void reload() { getConfiguration().load(); super.reload(); } @Override public int schedule(long delay, long period, Runnable task) { this.timer.schedule(new TimerTask() { @Override public void run() { task.run(); if (period >= 0) { timer.schedule(this, period); } } }, delay); return this.lastTimerId++; } @Override public List<? extends World> getWorlds() { return this.worlds; } @Nullable @Override public Player matchPlayer(Player player) { return null; } @Nullable @Override public World matchWorld(World world) { return this.worlds.stream() .filter(w -> w.id().equals(world.id())) .findAny() .orElse(null); } @Override public void registerCommands(CommandManager manager) { } @Override public void setGameHooksEnabled(boolean enabled) { } @Override public CLIConfiguration getConfiguration() { return app.getConfig(); } @Override public String getVersion() { return app.getInternalVersion(); } @Override public String getPlatformName() { return "CLI-Official"; } @Override public String getPlatformVersion() { return app.getInternalVersion(); } @Override public String id() { return "enginehub:cli"; } @Override public Map<Capability, Preference> getCapabilities() { Map<Capability, Preference> capabilities = new EnumMap<>(Capability.class); capabilities.put(Capability.CONFIGURATION, Preference.PREFER_OTHERS); capabilities.put(Capability.GAME_HOOKS, Preference.NORMAL); capabilities.put(Capability.PERMISSIONS, Preference.NORMAL); capabilities.put(Capability.USER_COMMANDS, Preference.NORMAL); capabilities.put(Capability.WORLD_EDITING, Preference.PREFERRED); return capabilities; } @Override public Set<SideEffect> getSupportedSideEffects() { return ImmutableSet.of(); } public void addWorld(World world) { worlds.add(world); } }
0
0.670153
1
0.670153
game-dev
MEDIA
0.859241
game-dev
0.734244
1
0.734244
CleverRaven/Cataclysm-DDA
23,848
tests/bionics_test.cpp
#include <functional> #include <list> #include <memory> #include <optional> #include <set> #include <string> #include <vector> #include "avatar.h" #include "bionics.h" #include "cata_catch.h" #include "character.h" #include "character_attire.h" #include "debug.h" #include "enums.h" #include "item.h" #include "item_location.h" #include "pimpl.h" #include "player_helpers.h" #include "pocket_type.h" #include "ret_val.h" #include "type_id.h" #include "units.h" static const bionic_id bio_batteries( "bio_batteries" ); // Change to some other weapon CBM if bio_blade is ever removed static const bionic_id bio_blade( "bio_blade" ); static const bionic_id bio_cable( "bio_cable" ); static const bionic_id bio_earplugs( "bio_earplugs" ); static const bionic_id bio_ears( "bio_ears" ); static const bionic_id bio_fuel_cell_gasoline( "bio_fuel_cell_gasoline" ); static const bionic_id bio_fuel_wood( "bio_fuel_wood" ); static const bionic_id bio_power_storage( "bio_power_storage" ); // Change to some other weapon CBM if bio_surgical_razor is ever removed static const bionic_id bio_surgical_razor( "bio_surgical_razor" ); // Any item that can be wielded static const flag_id json_flag_PSEUDO( "PSEUDO" ); static const itype_id fuel_type_gasoline( "gasoline" ); static const itype_id itype_UPS_ON( "UPS_ON" ); static const itype_id itype_backpack( "backpack" ); static const itype_id itype_jumper_cable( "jumper_cable" ); static const itype_id itype_light_battery_cell( "light_battery_cell" ); static const itype_id itype_splinter( "splinter" ); static const itype_id itype_test_backpack( "test_backpack" ); TEST_CASE( "Bionic_power_capacity", "[bionics] [power]" ) { avatar &dummy = get_avatar(); GIVEN( "character starts without bionics and no bionic power" ) { clear_avatar(); REQUIRE( !dummy.has_max_power() ); WHEN( "a Power Storage CBM is installed" ) { dummy.add_bionic( bio_power_storage ); THEN( "their total bionic power capacity increases by the Power Storage capacity" ) { CHECK( dummy.get_max_power_level() == bio_power_storage->capacity ); } } } GIVEN( "character starts with 3 power storage bionics" ) { clear_avatar(); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); REQUIRE( dummy.has_max_power() ); units::energy current_max_power = dummy.get_max_power_level(); REQUIRE( !dummy.has_power() ); AND_GIVEN( "power level is twice the capacity of a power storage bionic (not maxed)" ) { dummy.set_power_level( bio_power_storage->capacity * 2 ); REQUIRE( dummy.get_power_level() == bio_power_storage->capacity * 2 ); WHEN( "a Power Storage CBM is uninstalled" ) { std::optional<bionic *> bio = dummy.find_bionic_by_type( bio_power_storage ); REQUIRE( bio ); dummy.remove_bionic( **bio ); THEN( "maximum power decreases by the Power Storage capacity without changing current power level" ) { CHECK( dummy.get_max_power_level() == current_max_power - bio_power_storage->capacity ); CHECK( dummy.get_power_level() == bio_power_storage->capacity * 2 ); } } } AND_GIVEN( "power level is maxed" ) { dummy.set_power_level( dummy.get_max_power_level() ); REQUIRE( dummy.is_max_power() ); WHEN( "a Power Storage CBM is uninstalled" ) { std::optional<bionic *> bio = dummy.find_bionic_by_type( bio_power_storage ); REQUIRE( bio ); dummy.remove_bionic( **bio ); THEN( "current power is reduced to fit the new capacity" ) { CHECK( dummy.get_power_level() == dummy.get_max_power_level() ); } } } } } TEST_CASE( "bionic_UIDs", "[bionics]" ) { avatar &dummy = get_avatar(); clear_avatar(); GIVEN( "character doesn't have any CBMs installed" ) { REQUIRE( dummy.get_bionics().empty() ); WHEN( "a new CBM is installed" ) { dummy.add_bionic( bio_power_storage ); THEN( "its UID is set" ) { CHECK( dummy.my_bionics->back().get_uid() ); } } } GIVEN( "character has multiple CBMs installed" ) { dummy.my_bionics->emplace_back( bio_power_storage, get_free_invlet( dummy ), 1000 ); dummy.my_bionics->emplace_back( bio_power_storage, get_free_invlet( dummy ), 1050 ); dummy.my_bionics->emplace_back( bio_power_storage, get_free_invlet( dummy ), 2000 ); dummy.update_last_bionic_uid(); bionic_uid expected_bionic_uid = dummy.generate_bionic_uid() + 1; REQUIRE( dummy.get_bionics().size() == 3 ); WHEN( "a new CBM is installed" ) { dummy.add_bionic( bio_power_storage ); THEN( "its UID is set to the next available UID" ) { CHECK( dummy.my_bionics->back().get_uid() == expected_bionic_uid ); } } } } TEST_CASE( "bionic_weapons", "[bionics] [weapon] [item]" ) { avatar &dummy = get_avatar(); clear_avatar(); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); dummy.set_power_level( dummy.get_max_power_level() ); REQUIRE( dummy.get_power_level() == 200_kJ ); REQUIRE( dummy.is_max_power() ); GIVEN( "character has two weapon CBM" ) { dummy.add_bionic( bio_surgical_razor ); bionic &bio2 = dummy.bionic_at_index( dummy.get_bionics().size() - 1 ); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_blade ); bionic &bio = dummy.bionic_at_index( dummy.get_bionics().size() - 1 ); REQUIRE_FALSE( dummy.get_bionics().empty() ); REQUIRE_FALSE( dummy.has_weapon() ); AND_GIVEN( "the weapon CBM is activated" ) { REQUIRE( dummy.activate_bionic( bio ) ); REQUIRE( dummy.has_weapon() ); THEN( "current CBM UID is stored and fake weapon is wielded by the character" ) { REQUIRE( dummy.is_using_bionic_weapon() ); CHECK( dummy.get_weapon_bionic_uid() == bio.get_uid() ); CHECK( dummy.get_wielded_item()->typeId() == bio.id->fake_weapon ); } WHEN( "the weapon CBM is deactivated" ) { REQUIRE( dummy.deactivate_bionic( bio ) ); THEN( "character doesn't have a weapon equipped anymore" ) { CHECK( !dummy.get_wielded_item() ); CHECK_FALSE( dummy.is_using_bionic_weapon() ); } } WHEN( "the second weapon CBM is activated next" ) { REQUIRE( dummy.get_wielded_item()->typeId() == bio.id->fake_weapon ); REQUIRE( dummy.activate_bionic( bio2 ) ); THEN( "current weapon bionic UID is stored and wielded weapon is replaced" ) { REQUIRE( dummy.is_using_bionic_weapon() ); CHECK( dummy.get_weapon_bionic_uid() == bio2.get_uid() ); CHECK( dummy.get_wielded_item()->typeId() == bio2.id->fake_weapon ); } } } // Test can't be executed because dispose_item creates a query window /* AND_GIVEN("character is wielding a regular item") { item real_item(itype_real_item); REQUIRE(dummy.can_wield(real_item).success()); dummy.wield(real_item); REQUIRE(dummy.get_wielded_item().typeId() == itype_real_item); WHEN("the weapon CBM is activated") { REQUIRE(dummy.activate_bionic(installed_index)); THEN("current CBM UID is stored and fake weapon is wielded by the character") { std::optional<int> cbm_index = dummy.active_bionic_weapon_index(); REQUIRE(cbm_index); CHECK(*cbm_index == installed_index); CHECK(dummy.get_wielded_item().typeId() == weapon_bionic->fake_weapon); } } }*/ } GIVEN( "character has a customizable weapon CBM" ) { bionic_id customizable_weapon_bionic_id( "bio_blade" ); dummy.add_bionic( customizable_weapon_bionic_id ); bionic &customizable_bionic = dummy.bionic_at_index( dummy.my_bionics->size() - 1 ); REQUIRE_FALSE( dummy.get_bionics().empty() ); REQUIRE_FALSE( dummy.has_weapon() ); item::FlagsSetType *allowed_flags = const_cast<item::FlagsSetType *> ( &customizable_weapon_bionic_id->installable_weapon_flags ); allowed_flags->insert( json_flag_PSEUDO ); GIVEN( "weapon bionic allows installation of new weapons" ) { REQUIRE( customizable_weapon_bionic_id->installable_weapon_flags.find( json_flag_PSEUDO ) != customizable_weapon_bionic_id->installable_weapon_flags.end() ); WHEN( "character tries uninstalls weapon installed in the customizable bionic" ) { std::optional<item> removed_weapon = customizable_bionic.uninstall_weapon(); THEN( "weapon is uninstalled and retrieved as an item" ) { REQUIRE( removed_weapon ); CHECK( removed_weapon->typeId() == customizable_bionic.id->fake_weapon ); } } } AND_GIVEN( "character is wielding a regular item" ) { item real_item( itype_test_backpack ); REQUIRE( dummy.can_wield( real_item ).success() ); dummy.wield( real_item ); item_location wielded_item = dummy.get_wielded_item(); REQUIRE( dummy.get_wielded_item()->typeId() == itype_test_backpack ); AND_GIVEN( "weapon bionic doesn't allow installation of new weapons" ) { allowed_flags->clear(); customizable_bionic.set_weapon( item() ); REQUIRE_FALSE( customizable_bionic.can_install_weapon() ); REQUIRE_FALSE( customizable_bionic.has_weapon() ); THEN( "character fails to install a new weapon on bionic" ) { capture_debugmsg_during( [&customizable_bionic, &wielded_item]() { CHECK_FALSE( customizable_bionic.install_weapon( *wielded_item ) ); } ); } } AND_GIVEN( "weapon bionic allows installation of new weapons" ) { REQUIRE( customizable_weapon_bionic_id->installable_weapon_flags.find( json_flag_PSEUDO ) != customizable_weapon_bionic_id->installable_weapon_flags.end() ); AND_GIVEN( "a weapon is already installed on bionic" ) { REQUIRE( customizable_bionic.has_weapon() ); THEN( "character fails to install a new weapon on bionic" ) { capture_debugmsg_during( [&customizable_bionic, &wielded_item]() { CHECK_FALSE( customizable_bionic.install_weapon( *wielded_item ) ); } ); } } AND_GIVEN( "bionic is powered" ) { customizable_bionic.powered = true; WHEN( "character tries to install a new weapon on bionic" ) { THEN( "installation fails" ) { capture_debugmsg_during( [&customizable_bionic, &wielded_item]() { CHECK_FALSE( customizable_bionic.install_weapon( *wielded_item ) ); } ); } } } AND_GIVEN( "bionic has no weapon installed" ) { customizable_bionic.set_weapon( item() ); REQUIRE_FALSE( customizable_bionic.has_weapon() ); AND_GIVEN( "item doesn't have valid flags for bionic installation" ) { wielded_item->unset_flag( json_flag_PSEUDO ); REQUIRE_FALSE( wielded_item->has_flag( json_flag_PSEUDO ) ); THEN( "character fails to install a new weapon on bionic" ) { capture_debugmsg_during( [&customizable_bionic, &wielded_item]() { CHECK_FALSE( customizable_bionic.install_weapon( *wielded_item ) ); } ); } } AND_GIVEN( "item has valid flags" ) { wielded_item->set_flag( json_flag_PSEUDO ); REQUIRE( wielded_item->has_flag( json_flag_PSEUDO ) ); REQUIRE( wielded_item->has_any_flag( customizable_weapon_bionic_id->installable_weapon_flags ) ); WHEN( "character tries to install a new weapon on bionic" ) { THEN( "installation succeeds" ) { CHECK( customizable_bionic.install_weapon( *wielded_item ) ); } } } } } } } GIVEN( "character has an activated weapon CBM with a breakable weapon" ) { dummy.add_bionic( bio_surgical_razor ); bionic &bio = dummy.bionic_at_index( dummy.get_bionics().size() - 1 ); bio.set_weapon( item( itype_test_backpack ) ); REQUIRE_FALSE( dummy.get_bionics().empty() ); REQUIRE_FALSE( dummy.has_weapon() ); REQUIRE( dummy.activate_bionic( bio ) ); REQUIRE( dummy.is_using_bionic_weapon() ); REQUIRE( dummy.get_weapon_bionic_uid() == bio.get_uid() ); REQUIRE( dummy.get_wielded_item()->typeId() == itype_test_backpack ); WHEN( "weapon breaks" ) { item_location weapon = dummy.get_wielded_item(); weapon->set_damage( weapon->max_damage() ); REQUIRE( dummy.handle_melee_wear( weapon, 100000 ) ); REQUIRE_FALSE( dummy.has_weapon() ); THEN( "weapon bionic is deactivated and its weapon is gone" ) { CHECK_FALSE( dummy.is_using_bionic_weapon() ); CHECK_FALSE( bio.has_weapon() ); CHECK_FALSE( bio.powered ); } } } } TEST_CASE( "included_bionics", "[bionics]" ) { avatar &dummy = get_avatar(); clear_avatar(); GIVEN( "character doesn't have any CBMs installed" ) { REQUIRE( dummy.get_bionics().empty() ); WHEN( "a CBM with included bionics is installed" ) { dummy.add_bionic( bio_ears ); bionic &parent_bio = dummy.bionic_at_index( dummy.num_bionics() - 2 ); bionic &included_bio = dummy.bionic_at_index( dummy.num_bionics() - 1 ); THEN( "the bionic and its included bionics are installed" ) { REQUIRE( dummy.num_bionics() > 1 ); REQUIRE( parent_bio.id == bio_ears ); REQUIRE( included_bio.id == bio_earplugs ); CHECK( included_bio.get_parent_uid() == parent_bio.get_uid() ); } WHEN( "the parent bionic is uninstalled" ) { REQUIRE( dummy.num_bionics() > 1 ); dummy.remove_bionic( parent_bio ); THEN( "the bionic is removed along with the included bionic" ) { CHECK( dummy.num_bionics() == 0 ); } } } } } TEST_CASE( "fueled_bionics", "[bionics] [item]" ) { avatar &dummy = get_avatar(); clear_avatar(); // 500kJ ought to be enough for everybody, make sure not to add any bionics in the // tests after taking reference to a bionic, if bionics vector is too small and gets // reallocated the references become invalid dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); dummy.add_bionic( bio_power_storage ); REQUIRE( !dummy.has_power() ); REQUIRE( dummy.has_max_power() ); SECTION( "bio_fuel_cell_gasoline" ) { bionic &bio = *dummy.find_bionic_by_uid( dummy.add_bionic( bio_fuel_cell_gasoline ) ).value(); item_location gasoline_tank = dummy.top_items_loc().front(); // There should be no fuel available, can't turn bionic on and no power is produced CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK( dummy.get_cable_ups().empty() ); CHECK( dummy.get_cable_solar().empty() ); CHECK( dummy.get_cable_vehicle().empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Add fuel. Now it turns on and generates power. item gasoline = item( fuel_type_gasoline ); gasoline.charges = 2; CHECK( gasoline_tank->can_reload_with( gasoline, true ) ); gasoline_tank->put_in( gasoline, pocket_type::CONTAINER ); REQUIRE( gasoline_tank->only_item().charges == 2 ); CHECK( dummy.activate_bionic( bio ) ); CHECK_FALSE( dummy.get_bionic_fuels( bio.id ).empty() ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 8550 ); CHECK( gasoline_tank->only_item().charges == 1 ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 17100 ); CHECK( gasoline_tank->empty_container() ); // Run out of fuel dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 17100 ); } SECTION( "bio_batteries" ) { bionic &bio = *dummy.find_bionic_by_uid( dummy.add_bionic( bio_batteries ) ).value(); item_location bat_compartment = dummy.top_items_loc().front(); // There should be no fuel available, can't turn bionic on and no power is produced REQUIRE( bat_compartment->ammo_remaining( ) == 0 ); CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK( dummy.get_cable_ups().empty() ); CHECK( dummy.get_cable_solar().empty() ); CHECK( dummy.get_cable_vehicle().empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Add empty battery. Still won't work item battery = item( itype_light_battery_cell ); CHECK( bat_compartment->can_reload_with( battery, true ) ); bat_compartment->put_in( battery, pocket_type::MAGAZINE_WELL ); REQUIRE( bat_compartment->ammo_remaining( ) == 0 ); CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK( dummy.get_cable_ups().empty() ); CHECK( dummy.get_cable_solar().empty() ); CHECK( dummy.get_cable_vehicle().empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Add fuel. Now it turns on and generates power. bat_compartment->magazine_current()->ammo_set( battery.ammo_default(), 2 ); REQUIRE( bat_compartment->ammo_remaining( ) == 2 ); CHECK( dummy.activate_bionic( bio ) ); CHECK_FALSE( dummy.get_bionic_fuels( bio.id ).empty() ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 1000 ); CHECK( bat_compartment->ammo_remaining( ) == 1 ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 2000 ); CHECK( bat_compartment->ammo_remaining( ) == 0 ); // Run out of ammo dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 2000 ); } SECTION( "bio_cable ups" ) { bionic &bio = *dummy.find_bionic_by_uid( dummy.add_bionic( bio_cable ) ).value(); // There should be no fuel available, can't turn bionic on and no power is produced CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK( dummy.get_cable_ups().empty() ); CHECK( dummy.get_cable_solar().empty() ); CHECK( dummy.get_cable_vehicle().empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Connect to empty ups. Bionic shouldn't work dummy.worn.wear_item( dummy, item( itype_backpack ), false, false ); item_location ups = dummy.i_add( item( itype_UPS_ON ) ); item_location cable = dummy.i_add( item( itype_jumper_cable ) ); cable->link().source = link_state::ups; cable->link().target = link_state::bio_cable; ups->set_var( "cable", "plugged_in" ); cable->active = true; REQUIRE( ups->ammo_remaining( ) == 0 ); CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK( dummy.get_cable_ups().empty() ); CHECK( dummy.get_cable_solar().empty() ); CHECK( dummy.get_cable_vehicle().empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Put empty battery into ups. Still does not work. item ups_mag( ups->magazine_default() ); ups->put_in( ups_mag, pocket_type::MAGAZINE_WELL ); REQUIRE( ups->ammo_remaining( ) == 0 ); CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Fill the battery. Works now. ups->magazine_current()->ammo_set( ups_mag.ammo_default(), 2 ); REQUIRE( ups->ammo_remaining( ) == 2 ); CHECK( dummy.activate_bionic( bio ) ); CHECK_FALSE( dummy.get_cable_ups().empty() ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 1000 ); CHECK( ups->ammo_remaining( ) == 1 ); dummy.suffer(); CHECK( ups->ammo_remaining( ) == 0 ); CHECK( units::to_joule( dummy.get_power_level() ) == 2000 ); // Run out of fuel dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 2000 ); } SECTION( "bio_wood_burner" ) { bionic &bio = *dummy.find_bionic_by_uid( dummy.add_bionic( bio_fuel_wood ) ).value(); item_location woodshed = dummy.top_items_loc().front(); // Turn safe fuel off since log produces too much energy bio.set_safe_fuel_thresh( -1.0f ); // There should be no fuel available, can't turn bionic on and no power is produced CHECK( dummy.get_bionic_fuels( bio.id ).empty() ); CHECK_FALSE( dummy.activate_bionic( bio ) ); dummy.suffer(); REQUIRE( !dummy.has_power() ); // Add two splints. Now it turns on and generates power. item wood = item( itype_splinter ); item wood_2 = item( itype_splinter ); REQUIRE_FALSE( wood.count_by_charges() ); woodshed->put_in( wood, pocket_type::CONTAINER ); woodshed->put_in( wood_2, pocket_type::CONTAINER ); REQUIRE( woodshed->all_items_ptr().size() == 2 ); CHECK( dummy.activate_bionic( bio ) ); CHECK_FALSE( dummy.get_bionic_fuels( bio.id ).empty() ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 62500 ); CHECK( woodshed->all_items_ptr().size() == 1 ); dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 125000 ); CHECK( woodshed->empty_container() ); // Run out of fuel dummy.suffer(); CHECK( units::to_joule( dummy.get_power_level() ) == 125000 ); } }
0
0.810771
1
0.810771
game-dev
MEDIA
0.853709
game-dev
0.566687
1
0.566687
bozimmerman/CoffeeMud
8,129
com/planet_ink/coffee_mud/Commands/Sheath.java
package com.planet_ink.coffee_mud.Commands; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2025 Bo Zimmerman Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 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. */ public class Sheath extends StdCommand { public Sheath() { } private final String[] access=I(new String[]{"SHEATH"}); @Override public String[] getAccessWords() { return access; } public final boolean canSheathIn(final Item I, final Container C, final Map<Container,int[]> sheaths) { if(C.canContain(I)) { final int[] capRem = sheaths.get(C); if((capRem!=null) &&(capRem[0] >= I.phyStats().weight())) { capRem[0] -= I.phyStats().weight(); return true; } } return false; } @Override public boolean execute(final MOB mob, final List<String> commands, final int metaFlags) throws java.io.IOException { boolean quiet=false; boolean noerrors=false; final Vector<String> origCmds=new XVector<String>(commands); if(((commands.size()>0)&&(commands.get(commands.size()-1).equalsIgnoreCase("QUIETLY"))) ||(CMath.bset(metaFlags, MUDCmdProcessor.METAFLAG_QUIETLY))) { commands.remove(commands.size()-1); quiet=true; } if((commands.size()>0)&&(commands.get(commands.size()-1).equalsIgnoreCase("IFPOSSIBLE"))) { commands.remove(commands.size()-1); noerrors=true; } Item item1=null; Item item2=null; if(commands.size()>0) commands.remove(0); final OrderedMap<Container,int[]> sheaths=new OrderedMap<Container,int[]>(); for(int i=0;i<mob.numItems();i++) { final Item I=mob.getItem(i); if(I != null) { if(!I.amWearingAt(Wearable.IN_INVENTORY)) { if(I instanceof Weapon) { if(I.amWearingAt(Wearable.WORN_WIELD)) item1=I; else if(I.amWearingAt(Wearable.WORN_HELD)) item2=I; } else if((I instanceof Container) &&(!(I instanceof Drink)) &&(((Container)I).capacity()>0) &&(((Container)I).containTypes()!=Container.CONTAIN_ANYTHING) &&(!sheaths.containsKey(I))) sheaths.put((Container)I, new int[] {((Container)I).capacity()}); } else { final Container C=I.container(); if((C != null) &&(!(C instanceof Drink)) &&(C.capacity()>0) &&(C.containTypes()!=Container.CONTAIN_ANYTHING)) { if(!sheaths.containsKey(C)) sheaths.put(C, new int[] {C.capacity()}); sheaths.get(C)[0] -= I.phyStats().weight(); } } } } if(commands.size()==0) { if((noerrors) &&(item1==null) &&(item2==null)) return false; } final OrderedMap<Item,Container> sheathMap=new OrderedMap<Item,Container>(); Item sheathable=null; if(commands.size()==0) { if(item2==item1) item2=null; for(final Iterator<Pair<Container,int[]>> p = sheaths.pairIterator();p.hasNext();) { final Pair<Container,int[]> sheathPair = p.next(); final Container sheath=sheathPair.first; if((item1!=null) &&(!sheathMap.containsKey(item1)) &&(canSheathIn(item1,sheath,sheaths))) sheathMap.put(item1, sheath); else if((item2!=null) &&(!sheathMap.containsKey(item2)) &&(canSheathIn(item2,sheath,sheaths))) sheathMap.put(item2, sheath); } if(item2!=null) { for(final Iterator<Pair<Container,int[]>> p = sheaths.pairIterator();p.hasNext();) { final Pair<Container,int[]> sheathPair = p.next(); final Container sheath=sheathPair.first; if((!sheathMap.containsKey(item2)) &&(canSheathIn(item2,sheath,sheaths))) sheathMap.put(item2, sheath); } } if(item1!=null) sheathable=item1; else if(item2!=null) sheathable=item2; } else { commands.add(0,"all"); final Container container=(Container)CMLib.english().parsePossibleContainer(mob,commands,false,Wearable.FILTER_WORNONLY); String thingToPut=CMParms.combine(commands,0); int addendum=1; String addendumStr=""; boolean allFlag=(commands.size()>0)?commands.get(0).equalsIgnoreCase("all"):false; if(thingToPut.toUpperCase().startsWith("ALL.")) { allFlag=true; thingToPut="ALL "+thingToPut.substring(4); } if(thingToPut.toUpperCase().endsWith(".ALL")) { allFlag=true; thingToPut="ALL "+thingToPut.substring(0,thingToPut.length()-4); } boolean doBugFix = true; while(doBugFix || allFlag) { doBugFix=false; final Item putThis=mob.fetchItem(null,Wearable.FILTER_WORNONLY,thingToPut+addendumStr); if(putThis==null) break; if(((putThis.amWearingAt(Wearable.WORN_WIELD)) ||(putThis.amWearingAt(Wearable.WORN_HELD))) &&(putThis instanceof Weapon)) { if(CMLib.flags().canBeSeenBy(putThis,mob) &&(!sheathMap.containsKey(putThis))) { sheathable=putThis; if((container!=null) &&(canSheathIn(putThis,container,sheaths))) sheathMap.put(putThis, container); else { for(final Iterator<Pair<Container,int[]>> p = sheaths.pairIterator();p.hasNext();) { final Pair<Container,int[]> sheathPair = p.next(); final Container sheath=sheathPair.first; if(canSheathIn(putThis,sheath,sheaths)) { sheathMap.put(putThis, sheath); break; } } } } } addendumStr="."+(++addendum); } } if(sheathMap.size()==0) { if(!noerrors) { if(sheaths.size()==0) CMLib.commands().postCommandFail(mob,origCmds,L("You are not wearing an appropriate sheath.")); else if(sheathable!=null) CMLib.commands().postCommandFail(mob,origCmds,L("You aren't wearing anything you can sheath @x1 in.",sheathable.name())); else if(commands.size()==0) CMLib.commands().postCommandFail(mob,origCmds,L("You don't seem to be wielding anything you can sheath.")); else CMLib.commands().postCommandFail(mob,origCmds,L("You don't seem to be wielding that.")); } } else for(final Iterator<Pair<Item,Container>> p=sheathMap.pairIterator();p.hasNext();) { final Pair<Item,Container> P=p.next(); final Item putThis=P.first; final Container container=P.second; if(CMLib.commands().postRemove(mob,putThis,true)) { final CMMsg putMsg=CMClass.getMsg(mob,container,putThis,CMMsg.MSG_PUT,((quiet?null:L("<S-NAME> sheath(s) <O-NAME> in <T-NAME>.")))); if(mob.location().okMessage(mob,putMsg)) mob.location().send(mob,putMsg); } } return false; } @Override public double actionsCost(final MOB mob, final List<String> cmds) { return CMProps.getCommandActionCost(ID(), CMath.div(CMProps.getIntVar(CMProps.Int.DEFCMDTIME),200.0)); } @Override public double combatActionsCost(final MOB mob, final List<String> cmds) { return CMProps.getCommandCombatActionCost(ID(), CMath.div(CMProps.getIntVar(CMProps.Int.DEFCOMCMDTIME),200.0)); } @Override public boolean canBeOrdered() { return true; } }
0
0.90229
1
0.90229
game-dev
MEDIA
0.984519
game-dev
0.947419
1
0.947419
cmangos/mangos-cata
6,201
src/game/AI/ScriptDevAI/scripts/northrend/naxxramas/boss_patchwerk.cpp
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * 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 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 */ /* ScriptData SDName: Boss_Patchwerk SD%Complete: 100 SDComment: SDCategory: Naxxramas EndScriptData */ #include "AI/ScriptDevAI/include/precompiled.h" #include "naxxramas.h" enum { SAY_AGGRO1 = -1533017, SAY_AGGRO2 = -1533018, SAY_SLAY = -1533019, SAY_DEATH = -1533020, EMOTE_GENERIC_BERSERK = -1000004, EMOTE_GENERIC_ENRAGED = -1000003, SPELL_HATEFULSTRIKE = 28308, SPELL_HATEFULSTRIKE_H = 59192, SPELL_ENRAGE = 28131, SPELL_BERSERK = 26662, SPELL_SLIMEBOLT = 32309 }; struct boss_patchwerkAI : public ScriptedAI { boss_patchwerkAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_naxxramas* m_pInstance; bool m_bIsRegularMode; uint32 m_uiHatefulStrikeTimer; uint32 m_uiBerserkTimer; uint32 m_uiSlimeboltTimer; bool m_bEnraged; bool m_bBerserk; void Reset() override { m_uiHatefulStrikeTimer = 1000; // 1 second m_uiBerserkTimer = MINUTE * 6 * IN_MILLISECONDS; // 6 minutes m_uiSlimeboltTimer = 10000; m_bEnraged = false; m_bBerserk = false; } void KilledUnit(Unit* /*pVictim*/) override { if (urand(0, 4)) return; DoScriptText(SAY_SLAY, m_creature); } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_PATCHWERK, DONE); } void Aggro(Unit* /*pWho*/) override { DoScriptText(urand(0, 1) ? SAY_AGGRO1 : SAY_AGGRO2, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_PATCHWERK, IN_PROGRESS); } void JustReachedHome() override { if (m_pInstance) m_pInstance->SetData(TYPE_PATCHWERK, FAIL); } void DoHatefulStrike() { // The ability is used on highest HP target choosen of the top 2 (3 heroic) targets on threat list being in melee range Unit* pTarget = NULL; uint32 uiHighestHP = 0; uint32 uiTargets = m_bIsRegularMode ? 1 : 2; ThreatList const& tList = m_creature->getThreatManager().getThreatList(); if (tList.size() > 1) // Check if more than two targets, and start loop with second-most aggro { ThreatList::const_iterator iter = tList.begin(); std::advance(iter, 1); for (; iter != tList.end(); ++iter) { if (!uiTargets) break; if (Unit* pTempTarget = m_creature->GetMap()->GetUnit((*iter)->getUnitGuid())) { if (m_creature->CanReachWithMeleeAttack(pTempTarget)) { if (pTempTarget->GetHealth() > uiHighestHP) { uiHighestHP = pTempTarget->GetHealth(); pTarget = pTempTarget; } --uiTargets; } } } } if (!pTarget) pTarget = m_creature->getVictim(); DoCastSpellIfCan(pTarget, m_bIsRegularMode ? SPELL_HATEFULSTRIKE : SPELL_HATEFULSTRIKE_H); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // Hateful Strike if (m_uiHatefulStrikeTimer < uiDiff) { DoHatefulStrike(); m_uiHatefulStrikeTimer = 1000; } else m_uiHatefulStrikeTimer -= uiDiff; // Soft Enrage at 5% if (!m_bEnraged) { if (m_creature->GetHealthPercent() < 5.0f) { if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK) { DoScriptText(EMOTE_GENERIC_ENRAGED, m_creature); m_bEnraged = true; } } } // Berserk after 6 minutes if (!m_bBerserk) { if (m_uiBerserkTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK) { DoScriptText(EMOTE_GENERIC_BERSERK, m_creature); m_bBerserk = true; } } else m_uiBerserkTimer -= uiDiff; } else { // Slimebolt - casted only while Berserking to prevent kiting if (m_uiSlimeboltTimer < uiDiff) { DoCastSpellIfCan(m_creature->getVictim(), SPELL_SLIMEBOLT); m_uiSlimeboltTimer = 5000; } else m_uiSlimeboltTimer -= uiDiff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_patchwerk(Creature* pCreature) { return new boss_patchwerkAI(pCreature); } void AddSC_boss_patchwerk() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_patchwerk"; pNewScript->GetAI = &GetAI_boss_patchwerk; pNewScript->RegisterSelf(); }
0
0.914531
1
0.914531
game-dev
MEDIA
0.960361
game-dev
0.953631
1
0.953631
Citadel-Station-13/Citadel-Station-13
2,275
code/modules/wiremod/components/hud/target_intercept.dm
/** * # Target Intercept Component * * When activated intercepts next click and outputs clicked atom. * Requires a BCI shell. */ /obj/item/circuit_component/target_intercept display_name = "Target Intercept" desc = "Requires a BCI shell. When activated, this component will allow user to target an object using their brain and will output the reference to said object." required_shells = list(/obj/item/organ/cyberimp/bci) var/datum/port/output/clicked_atom var/obj/item/organ/cyberimp/bci/bci var/intercept_cooldown = 1 SECONDS /obj/item/circuit_component/target_intercept/Initialize(mapload) . = ..() trigger_input = add_input_port("Activate", PORT_TYPE_SIGNAL) trigger_output = add_output_port("Triggered", PORT_TYPE_SIGNAL) clicked_atom = add_output_port("Targeted Object", PORT_TYPE_ATOM) /obj/item/circuit_component/target_intercept/register_shell(atom/movable/shell) if(istype(shell, /obj/item/organ/cyberimp/bci)) bci = shell RegisterSignal(shell, COMSIG_ORGAN_REMOVED, PROC_REF(on_organ_removed)) /obj/item/circuit_component/target_intercept/unregister_shell(atom/movable/shell) bci = null UnregisterSignal(shell, COMSIG_ORGAN_REMOVED) /obj/item/circuit_component/target_intercept/input_received(datum/port/input/port) . = ..() if(. || !bci) return var/mob/living/owner = bci.owner if(!owner || !istype(owner) || !owner.client) return if(TIMER_COOLDOWN_CHECK(parent, COOLDOWN_CIRCUIT_TARGET_INTERCEPT)) return to_chat(owner, "<B>Left-click to trigger target interceptor!</B>") owner.client.click_intercept = src /obj/item/circuit_component/target_intercept/proc/on_organ_removed(datum/source, mob/living/carbon/owner) SIGNAL_HANDLER if(owner.client && owner.client.click_intercept == src) owner.client.click_intercept = null /obj/item/circuit_component/target_intercept/proc/InterceptClickOn(mob/user, params, atom/object) user.client.click_intercept = null clicked_atom.set_output(object) trigger_output.set_output(COMPONENT_SIGNAL) TIMER_COOLDOWN_START(parent, COOLDOWN_CIRCUIT_TARGET_INTERCEPT, intercept_cooldown) /obj/item/circuit_component/target_intercept/get_ui_notices() . = ..() . += create_ui_notice("Target Interception Cooldown: [DisplayTimeText(intercept_cooldown)]", "orange", "stopwatch")
0
0.964951
1
0.964951
game-dev
MEDIA
0.193592
game-dev
0.935374
1
0.935374
BLACKujira/SekaiTools
2,529
SekaiTools/Assets/Scripts/UI/NCSPlayerInitialize/NCSPlayerInitialize.cs
using SekaiTools.UI.GenericInitializationParts; using SekaiTools.UI.NCSPlayer; using System; using System.Collections; using System.IO; using System.Windows.Forms; using UnityEngine; using UnityEngine.UI; namespace SekaiTools.UI.NCSPlayerInitialize { public class NCSPlayerInitialize : MonoBehaviour { public Window window; [Header("Components")] public InputField pathInputField; public Text textInfo; public GIP_NicknameCountData ncdArea; public GIP_CharLive2dPair l2dArea; public GIP_AudioData audioArea; [Header("Prefab")] public Window playerWindowPrefab; Count.Showcase.NicknameCountShowcase nicknameCountShowcase; public void LoadData() { OpenFileDialog openFileDialog = FileDialogFactory.GetOpenFileDialog(FileDialogFactory.FILTER_NCS); DialogResult dialogResult = openFileDialog.ShowDialog(); if (dialogResult != DialogResult.OK) return; string fileName = openFileDialog.FileName; nicknameCountShowcase = Count.Showcase.NicknameCountShowcase.LoadData(fileName,false); string audioDataPath = Path.ChangeExtension(fileName, ".aud"); if (File.Exists(audioDataPath)) throw new NotImplementedException(); //audioArea.Load(audioDataPath); l2dArea.Initialize(nicknameCountShowcase.charactersRequireL2d); ncdArea.Load(Path.GetDirectoryName(audioDataPath)); pathInputField.text = nicknameCountShowcase.SavePath; textInfo.text = $"包含{nicknameCountShowcase.scenes.Count}个场景"; } public void Apply() { NCSPlayer_Player.Settings settings = new NCSPlayer_Player.Settings(); settings.showcase = nicknameCountShowcase; settings.countData = ncdArea.NicknameCountData; settings.live2DModels = l2dArea.sekaiLive2DModels; AudioData audioData = new AudioData(); settings.audioData = audioData; NowLoadingTypeA nowLoadingTypeA = window.OpenWindow<NowLoadingTypeA>(WindowController.windowController.nowLoadingTypeAWindow); nowLoadingTypeA.OnFinish += () => { NCSPlayer.NCSPlayer nCSPlayer = window.OpenWindow<NCSPlayer.NCSPlayer>(playerWindowPrefab); nCSPlayer.Initialize(settings); }; nowLoadingTypeA.StartProcess(audioData.LoadFile(audioArea.SerializedAudioData)); } } }
0
0.638583
1
0.638583
game-dev
MEDIA
0.322332
game-dev
0.650335
1
0.650335
narknon/WukongB1
4,884
Plugins/UnrealJS/Source/V8/Private/JavascriptProfile.cpp
#include "JavascriptProfile.h" #include "Config.h" #include "Translator.h" #include "Helpers.h" #include "JavascriptLibrary.h" #include "V8PCH.h" using namespace v8; void UJavascriptProfile::BeginDestroy() { Super::BeginDestroy(); if (Profile) { reinterpret_cast<CpuProfile*>(Profile)->Delete(); Profile = nullptr; } } FJavascriptProfileNode UJavascriptProfile::GetTopDownRoot() { FJavascriptProfileNode out{ nullptr }; if (Profile) { out.Node = reinterpret_cast<CpuProfile*>(Profile)->GetTopDownRoot(); } return out; } int32 UJavascriptProfile::GetSamplesCount() { if (Profile) { return reinterpret_cast<CpuProfile*>(Profile)->GetSamplesCount(); } return 0; } FJavascriptProfileNode UJavascriptProfile::GetSample(int32 index) { FJavascriptProfileNode out{ nullptr }; if (Profile) { out.Node = reinterpret_cast<CpuProfile*>(Profile)->GetSample(index); } return out; } float UJavascriptProfile::GetSampleTimestamp(int32 index) { if (Profile) { return (float)reinterpret_cast<CpuProfile*>(Profile)->GetSampleTimestamp(index); } return -1; } FJavascriptCpuProfiler UJavascriptProfile::Start(const FString& Title, bool bRecordSamples) { auto isolate = Isolate::GetCurrent(); FIsolateHelper I(isolate); auto profiler = v8::CpuProfiler::New(isolate); profiler->StartProfiling(I.String(Title), bRecordSamples); FJavascriptCpuProfiler out { nullptr }; out.Profiler = profiler; return out; } UJavascriptProfile* UJavascriptProfile::Stop(const FJavascriptCpuProfiler& Profiler, const FString& Title) { auto isolate = Isolate::GetCurrent(); FIsolateHelper I(isolate); auto Profile = reinterpret_cast<CpuProfiler*>(Profiler.Profiler)->StopProfiling(I.String(Title)); auto instance = NewObject<UJavascriptProfile>(); instance->Profile = Profile; return instance; } void UJavascriptProfile::SetSamplingInterval(const FJavascriptCpuProfiler& Profiler, int32 us) { reinterpret_cast<CpuProfiler*>(Profiler.Profiler)->SetSamplingInterval(us); } void UJavascriptProfile::SetIdle(const FJavascriptCpuProfiler& Profiler, bool is_idle) { #if V8_MAJOR_VERSION < 9 reinterpret_cast<CpuProfiler*>(Profiler.Profiler)->SetIdle(is_idle); #else auto isolate = Isolate::GetCurrent(); isolate->SetIdle(is_idle); #endif } FString UJavascriptLibrary::GetFunctionName(FJavascriptProfileNode Node) { return StringFromV8(Isolate::GetCurrent(), reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetFunctionName()); } int32 UJavascriptLibrary::GetScriptId(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetScriptId(); } FString UJavascriptLibrary::GetScriptResourceName(FJavascriptProfileNode Node) { return StringFromV8(Isolate::GetCurrent(), reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetScriptResourceName()); } int32 UJavascriptLibrary::GetLineNumber(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetLineNumber(); } int32 UJavascriptLibrary::GetColumnNumber(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetColumnNumber(); } int32 UJavascriptLibrary::GetHitLineCount(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetHitLineCount(); } FString UJavascriptLibrary::GetBailoutReason(FJavascriptProfileNode Node) { return ANSI_TO_TCHAR(reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetBailoutReason()); } int32 UJavascriptLibrary::GetHitCount(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetHitCount(); } int32 UJavascriptLibrary::GetNodeId(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetNodeId(); } int32 UJavascriptLibrary::GetChildrenCount(FJavascriptProfileNode Node) { return reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetChildrenCount(); } FJavascriptProfileNode UJavascriptLibrary::GetChild(FJavascriptProfileNode Node, int32 index) { FJavascriptProfileNode out; out.Node = reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetChild(index); return out; } int32 UJavascriptLibrary::GetDeoptInfosCount(FJavascriptProfileNode Node, int32 index) { const auto& infos = reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetDeoptInfos(); return infos.size(); } FString UJavascriptLibrary::GetDeoptInfo_Reason(FJavascriptProfileNode Node, int32 index) { const auto& infos = reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetDeoptInfos(); return ANSI_TO_TCHAR(infos[index].deopt_reason); } FString UJavascriptLibrary::GetDeoptInfo_Stack(FJavascriptProfileNode Node, int32 index) { FString out; const auto& infos = reinterpret_cast<const CpuProfileNode*>(Node.Node)->GetDeoptInfos(); for (const auto& frame : infos[index].stack) { out.Append(FString::Printf(TEXT("%d:%d"), frame.script_id, frame.position)); } return out; }
0
0.716283
1
0.716283
game-dev
MEDIA
0.493909
game-dev
0.906985
1
0.906985
Admenri/urge
22,513
binding/mri/third_party/rgss/rgss3_patch.rb
if !defined? RPG WindowXP = Window TilemapXP = Tilemap Window = Window2 Tilemap = Tilemap2 module RPG class Map class Encounter def initialize @troop_id = 1 @weight = 10 @region_set = [] end attr_accessor :troop_id attr_accessor :weight attr_accessor :region_set end def initialize(width, height) @display_name = '' @tileset_id = 1 @width = width @height = height @scroll_type = 0 @specify_battleback = false @battleback_floor_name = '' @battleback_wall_name = '' @autoplay_bgm = false @bgm = BGM.new @autoplay_bgs = false @bgs = BGS.new('', 80) @disable_dashing = false @encounter_list = [] @encounter_step = 30 @parallax_name = '' @parallax_loop_x = false @parallax_loop_y = false @parallax_sx = 0 @parallax_sy = 0 @parallax_show = false @note = '' @data = Table.new(width, height, 4) @events = {} end attr_accessor :display_name attr_accessor :tileset_id attr_accessor :width attr_accessor :height attr_accessor :scroll_type attr_accessor :specify_battleback attr_accessor :battleback1_name attr_accessor :battleback2_name attr_accessor :autoplay_bgm attr_accessor :bgm attr_accessor :autoplay_bgs attr_accessor :bgs attr_accessor :disable_dashing attr_accessor :encounter_list attr_accessor :encounter_step attr_accessor :parallax_name attr_accessor :parallax_loop_x attr_accessor :parallax_loop_y attr_accessor :parallax_sx attr_accessor :parallax_sy attr_accessor :parallax_show attr_accessor :note attr_accessor :data attr_accessor :events end class MapInfo def initialize @name = '' @parent_id = 0 @order = 0 @expanded = false @scroll_x = 0 @scroll_y = 0 end attr_accessor :name attr_accessor :parent_id attr_accessor :order attr_accessor :expanded attr_accessor :scroll_x attr_accessor :scroll_y end class Event class Page class Condition def initialize @switch1_valid = false @switch2_valid = false @variable_valid = false @self_switch_valid = false @item_valid = false @actor_valid = false @switch1_id = 1 @switch2_id = 1 @variable_id = 1 @variable_value = 0 @self_switch_ch = 'A' @item_id = 1 @actor_id = 1 end attr_accessor :switch1_valid attr_accessor :switch2_valid attr_accessor :variable_valid attr_accessor :self_switch_valid attr_accessor :item_valid attr_accessor :actor_valid attr_accessor :switch1_id attr_accessor :switch2_id attr_accessor :variable_id attr_accessor :variable_value attr_accessor :self_switch_ch attr_accessor :item_id attr_accessor :actor_id end class Graphic def initialize @tile_id = 0 @character_name = '' @character_index = 0 @direction = 2 @pattern = 0 end attr_accessor :tile_id attr_accessor :character_name attr_accessor :character_index attr_accessor :direction attr_accessor :pattern end def initialize @condition = Condition.new @graphic = Graphic.new @move_type = 0 @move_speed = 3 @move_frequency = 3 @move_route = MoveRoute.new @walk_anime = true @step_anime = false @direction_fix = false @through = false @priority_type = 0 @trigger = 0 @list = [EventCommand.new] end attr_accessor :condition attr_accessor :graphic attr_accessor :move_type attr_accessor :move_speed attr_accessor :move_frequency attr_accessor :move_route attr_accessor :walk_anime attr_accessor :step_anime attr_accessor :direction_fix attr_accessor :through attr_accessor :priority_type attr_accessor :trigger attr_accessor :list end def initialize(x, y) @id = 0 @name = '' @x = x @y = y @pages = [Page.new] end attr_accessor :id attr_accessor :name attr_accessor :x attr_accessor :y attr_accessor :pages end class EventCommand def initialize(code = 0, indent = 0, parameters = []) @code = code @indent = indent @parameters = parameters end attr_accessor :code attr_accessor :indent attr_accessor :parameters end class MoveRoute def initialize @repeat = true @skippable = false @wait = false @list = [MoveCommand.new] end attr_accessor :repeat attr_accessor :skippable attr_accessor :wait attr_accessor :list end class MoveCommand def initialize(code = 0, parameters = []) @code = code @parameters = parameters end attr_accessor :code attr_accessor :parameters end class BaseItem class Feature def initialize(code = 0, data_id = 0, value = 0) @code = code @data_id = data_id @value = value end attr_accessor :code attr_accessor :data_id attr_accessor :value end def initialize @id = 0 @name = '' @icon_index = 0 @description = '' @features = [] @note = '' end attr_accessor :id attr_accessor :name attr_accessor :icon_index attr_accessor :description attr_accessor :features attr_accessor :note end class Actor < BaseItem def initialize super @nickname = '' @class_id = 1 @initial_level = 1 @max_level = 99 @character_name = '' @character_index = 0 @face_name = '' @face_index = 0 @equips = [0,0,0,0,0] end attr_accessor :nickname attr_accessor :class_id attr_accessor :initial_level attr_accessor :max_level attr_accessor :character_name attr_accessor :character_index attr_accessor :face_name attr_accessor :face_index attr_accessor :equips end class Class < BaseItem class Learning def initialize @level = 1 @skill_id = 1 @note = '' end attr_accessor :level attr_accessor :skill_id attr_accessor :note end def initialize super @exp_params = [30,20,30,30] @params = Table.new(8,100) (1..99).each do |i| @params[0,i] = 400+i*50 @params[1,i] = 80+i*10 (2..5).each {|j| @params[j,i] = 15+i*5/4 } (6..7).each {|j| @params[j,i] = 30+i*5/2 } end @learnings = [] @features.push(BaseItem::Feature.new(23, 0, 1)) @features.push(BaseItem::Feature.new(22, 0, 0.95)) @features.push(BaseItem::Feature.new(22, 1, 0.05)) @features.push(BaseItem::Feature.new(22, 2, 0.04)) @features.push(BaseItem::Feature.new(41, 1)) @features.push(BaseItem::Feature.new(51, 1)) @features.push(BaseItem::Feature.new(52, 1)) end def exp_for_level(level) lv = level.to_f basis = @exp_params[0].to_f extra = @exp_params[1].to_f acc_a = @exp_params[2].to_f acc_b = @exp_params[3].to_f return (basis*((lv-1)**(0.9+acc_a/250))*lv*(lv+1)/ (6+lv**2/50/acc_b)+(lv-1)*extra).round.to_i end attr_accessor :exp_params attr_accessor :params attr_accessor :learnings end class UsableItem < BaseItem class Damage def initialize @type = 0 @element_id = 0 @formula = '0' @variance = 20 @critical = false end def none? @type == 0 end def to_hp? [1,3,5].include?(@type) end def to_mp? [2,4,6].include?(@type) end def recover? [3,4].include?(@type) end def drain? [5,6].include?(@type) end def sign recover? ? -1 : 1 end def eval(a, b, v) [Kernel.eval(@formula), 0].max * sign rescue 0 end attr_accessor :type attr_accessor :element_id attr_accessor :formula attr_accessor :variance attr_accessor :critical end class Effect def initialize(code = 0, data_id = 0, value1 = 0, value2 = 0) @code = code @data_id = data_id @value1 = value1 @value2 = value2 end attr_accessor :code attr_accessor :data_id attr_accessor :value1 attr_accessor :value2 end def initialize super @scope = 0 @occasion = 0 @speed = 0 @success_rate = 100 @repeats = 1 @tp_gain = 0 @hit_type = 0 @animation_id = 0 @damage = Damage.new @effects = [] end def for_opponent? [1, 2, 3, 4, 5, 6].include?(@scope) end def for_friend? [7, 8, 9, 10, 11].include?(@scope) end def for_dead_friend? [9, 10].include?(@scope) end def for_user? @scope == 11 end def for_one? [1, 3, 7, 9, 11].include?(@scope) end def for_random? [3, 4, 5, 6].include?(@scope) end def number_of_targets for_random? ? @scope - 2 : 0 end def for_all? [2, 8, 10].include?(@scope) end def need_selection? [1, 7, 9].include?(@scope) end def battle_ok? [0, 1].include?(@occasion) end def menu_ok? [0, 2].include?(@occasion) end def certain? @hit_type == 0 end def physical? @hit_type == 1 end def magical? @hit_type == 2 end attr_accessor :scope attr_accessor :occasion attr_accessor :speed attr_accessor :animation_id attr_accessor :success_rate attr_accessor :repeats attr_accessor :tp_gain attr_accessor :hit_type attr_accessor :damage attr_accessor :effects end class Skill < UsableItem def initialize super @scope = 1 @stype_id = 1 @mp_cost = 0 @tp_cost = 0 @message1 = '' @message2 = '' @required_wtype_id1 = 0 @required_wtype_id2 = 0 end attr_accessor :stype_id attr_accessor :mp_cost attr_accessor :tp_cost attr_accessor :message1 attr_accessor :message2 attr_accessor :required_wtype_id1 attr_accessor :required_wtype_id2 end class Item < UsableItem def initialize super @scope = 7 @itype_id = 1 @price = 0 @consumable = true end def key_item? @itype_id == 2 end attr_accessor :itype_id attr_accessor :price attr_accessor :consumable end class EquipItem < BaseItem def initialize super @price = 0 @etype_id = 0 @params = [0] * 8 end attr_accessor :price attr_accessor :etype_id attr_accessor :params end class Weapon < EquipItem def initialize super @wtype_id = 0 @animation_id = 0 @features.push(BaseItem::Feature.new(31, 1, 0)) @features.push(BaseItem::Feature.new(22, 0, 0)) end def performance params[2] + params[4] + params.inject(0) {|r, v| r += v } end attr_accessor :wtype_id attr_accessor :animation_id end class Armor < EquipItem def initialize super @atype_id = 0 @etype_id = 1 @features.push(BaseItem::Feature.new(22, 1, 0)) end def performance params[3] + params[5] + params.inject(0) {|r, v| r += v } end attr_accessor :atype_id end class Enemy < BaseItem class DropItem def initialize @kind = 0 @data_id = 1 @denominator = 1 end attr_accessor :kind attr_accessor :data_id attr_accessor :denominator end class Action def initialize @skill_id = 1 @condition_type = 0 @condition_param1 = 0 @condition_param2 = 0 @rating = 5 end attr_accessor :skill_id attr_accessor :condition_type attr_accessor :condition_param1 attr_accessor :condition_param2 attr_accessor :rating end def initialize super @battler_name = '' @battler_hue = 0 @params = [100,0,10,10,10,10,10,10] @exp = 0 @gold = 0 @drop_items = Array.new(3) { DropItem.new } @actions = [Action.new] @features.push(BaseItem::Feature.new(22, 0, 0.95)) @features.push(BaseItem::Feature.new(22, 1, 0.05)) @features.push(BaseItem::Feature.new(31, 1, 0)) end attr_accessor :battler_name attr_accessor :battler_hue attr_accessor :params attr_accessor :exp attr_accessor :gold attr_accessor :drop_items attr_accessor :actions end class State < BaseItem def initialize super @restriction = 0 @priority = 50 @remove_at_battle_end = false @remove_by_restriction = false @auto_removal_timing = 0 @min_turns = 1 @max_turns = 1 @remove_by_damage = false @chance_by_damage = 100 @remove_by_walking = false @steps_to_remove = 100 @message1 = '' @message2 = '' @message3 = '' @message4 = '' end attr_accessor :restriction attr_accessor :priority attr_accessor :remove_at_battle_end attr_accessor :remove_by_restriction attr_accessor :auto_removal_timing attr_accessor :min_turns attr_accessor :max_turns attr_accessor :remove_by_damage attr_accessor :chance_by_damage attr_accessor :remove_by_walking attr_accessor :steps_to_remove attr_accessor :message1 attr_accessor :message2 attr_accessor :message3 attr_accessor :message4 end class Troop class Member def initialize @enemy_id = 1 @x = 0 @y = 0 @hidden = false end attr_accessor :enemy_id attr_accessor :x attr_accessor :y attr_accessor :hidden end class Page class Condition def initialize @turn_ending = false @turn_valid = false @enemy_valid = false @actor_valid = false @switch_valid = false @turn_a = 0 @turn_b = 0 @enemy_index = 0 @enemy_hp = 50 @actor_id = 1 @actor_hp = 50 @switch_id = 1 end attr_accessor :turn_ending attr_accessor :turn_valid attr_accessor :enemy_valid attr_accessor :actor_valid attr_accessor :switch_valid attr_accessor :turn_a attr_accessor :turn_b attr_accessor :enemy_index attr_accessor :enemy_hp attr_accessor :actor_id attr_accessor :actor_hp attr_accessor :switch_id end def initialize @condition = Condition.new @span = 0 @list = [EventCommand.new] end attr_accessor :condition attr_accessor :span attr_accessor :list end def initialize @id = 0 @name = '' @members = [] @pages = [Page.new] end attr_accessor :id attr_accessor :name attr_accessor :members attr_accessor :pages end class Animation class Frame def initialize @cell_max = 0 @cell_data = Table.new(0, 0) end attr_accessor :cell_max attr_accessor :cell_data end class Timing def initialize @frame = 0 @se = SE.new('', 80) @flash_scope = 0 @flash_color = Color.new(255,255,255,255) @flash_duration = 5 end attr_accessor :frame attr_accessor :se attr_accessor :flash_scope attr_accessor :flash_color attr_accessor :flash_duration end def initialize @id = 0 @name = '' @animation1_name = '' @animation1_hue = 0 @animation2_name = '' @animation2_hue = 0 @position = 1 @frame_max = 1 @frames = [Frame.new] @timings = [] end def to_screen? @position == 3 end attr_accessor :id attr_accessor :name attr_accessor :animation1_name attr_accessor :animation1_hue attr_accessor :animation2_name attr_accessor :animation2_hue attr_accessor :position attr_accessor :frame_max attr_accessor :frames attr_accessor :timings end class Tileset def initialize @id = 0 @mode = 1 @name = '' @tileset_names = Array.new(9).collect{''} @flags = Table.new(8192) @flags[0] = 0x0010 (2048..2815).each {|i| @flags[i] = 0x000F} (4352..8191).each {|i| @flags[i] = 0x000F} @note = '' end attr_accessor :id attr_accessor :mode attr_accessor :name attr_accessor :tileset_names attr_accessor :flags attr_accessor :note end class CommonEvent def initialize @id = 0 @name = '' @trigger = 0 @switch_id = 1 @list = [EventCommand.new] end def autorun? @trigger == 1 end def parallel? @trigger == 2 end attr_accessor :id attr_accessor :name attr_accessor :trigger attr_accessor :switch_id attr_accessor :list end class System class Vehicle def initialize @character_name = '' @character_index = 0 @bgm = BGM.new @start_map_id = 0 @start_x = 0 @start_y = 0 end attr_accessor :character_name attr_accessor :character_index attr_accessor :bgm attr_accessor :start_map_id attr_accessor :start_x attr_accessor :start_y end class Terms def initialize @basic = Array.new(8) {''} @params = Array.new(8) {''} @etypes = Array.new(5) {''} @commands = Array.new(23) {''} end attr_accessor :basic attr_accessor :params attr_accessor :etypes attr_accessor :commands end class TestBattler def initialize @actor_id = 1 @level = 1 @equips = [0,0,0,0,0] end attr_accessor :actor_id attr_accessor :level attr_accessor :equips end def initialize @game_title = '' @version_id = 0 @japanese = true @party_members = [1] @currency_unit = '' @elements = [nil, ''] @skill_types = [nil, ''] @weapon_types = [nil, ''] @armor_types = [nil, ''] @switches = [nil, ''] @variables = [nil, ''] @boat = Vehicle.new @ship = Vehicle.new @airship = Vehicle.new @title1_name = '' @title2_name = '' @opt_draw_title = true @opt_use_midi = false @opt_transparent = false @opt_followers = true @opt_slip_death = false @opt_floor_death = false @opt_display_tp = true @opt_extra_exp = false @window_tone = Tone.new(0,0,0) @title_bgm = BGM.new @battle_bgm = BGM.new @battle_end_me = ME.new @gameover_me = ME.new @sounds = Array.new(24) { SE.new } @test_battlers = [] @test_troop_id = 1 @start_map_id = 1 @start_x = 0 @start_y = 0 @terms = Terms.new @battleback1_name = '' @battleback2_name = '' @battler_name = '' @battler_hue = 0 @edit_map_id = 1 end attr_accessor :game_title attr_accessor :version_id attr_accessor :japanese attr_accessor :party_members attr_accessor :currency_unit attr_accessor :skill_types attr_accessor :weapon_types attr_accessor :armor_types attr_accessor :elements attr_accessor :switches attr_accessor :variables attr_accessor :boat attr_accessor :ship attr_accessor :airship attr_accessor :title1_name attr_accessor :title2_name attr_accessor :opt_draw_title attr_accessor :opt_use_midi attr_accessor :opt_transparent attr_accessor :opt_followers attr_accessor :opt_slip_death attr_accessor :opt_floor_death attr_accessor :opt_display_tp attr_accessor :opt_extra_exp attr_accessor :window_tone attr_accessor :title_bgm attr_accessor :battle_bgm attr_accessor :battle_end_me attr_accessor :gameover_me attr_accessor :sounds attr_accessor :test_battlers attr_accessor :test_troop_id attr_accessor :start_map_id attr_accessor :start_x attr_accessor :start_y attr_accessor :terms attr_accessor :battleback1_name attr_accessor :battleback2_name attr_accessor :battler_name attr_accessor :battler_hue attr_accessor :edit_map_id end class AudioFile def initialize(name = '', volume = 100, pitch = 100) @name = name @volume = volume @pitch = pitch end attr_accessor :name attr_accessor :volume attr_accessor :pitch end class BGM < AudioFile @@last = BGM.new def play(pos = 0) if @name.empty? Audio.bgm_stop @@last = BGM.new else Audio.bgm_play('Audio/BGM/' + @name, @volume, @pitch, pos) @@last = self.clone end end def replay play(@pos) end def self.stop Audio.bgm_stop @@last = BGM.new end def self.fade(time) Audio.bgm_fade(time) @@last = BGM.new end def self.last @@last.pos = Audio.bgm_pos @@last end attr_accessor :pos end class BGS < AudioFile @@last = BGS.new def play(pos = 0) if @name.empty? Audio.bgs_stop @@last = BGS.new else Audio.bgs_play('Audio/BGS/' + @name, @volume, @pitch, pos) @@last = self.clone end end def replay play(@pos) end def self.stop Audio.bgs_stop @@last = BGS.new end def self.fade(time) Audio.bgs_fade(time) @@last = BGS.new end def self.last @@last.pos = Audio.bgs_pos @@last end attr_accessor :pos end class ME < AudioFile def play if @name.empty? Audio.me_stop else Audio.me_play('Audio/ME/' + @name, @volume, @pitch) end end def self.stop Audio.me_stop end def self.fade(time) Audio.me_fade(time) end end class SE < AudioFile def play unless @name.empty? Audio.se_play('Audio/SE/' + @name, @volume, @pitch) end end def self.stop Audio.se_stop end end end end # RPG
0
0.967759
1
0.967759
game-dev
MEDIA
0.47106
game-dev
0.9532
1
0.9532
lllyasviel/YGOProUnity_V2
2,812
Assets/NGUI/Scripts/Interaction/UISavedOption.cs
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2015 Tasharen Entertainment //---------------------------------------------- using UnityEngine; /// <summary> /// Attach this script to a popup list, the parent of a group of toggles, or to a toggle itself to save its state. /// </summary> [AddComponentMenu("NGUI/Interaction/Saved Option")] public class UISavedOption : MonoBehaviour { /// <summary> /// PlayerPrefs-stored key for this option. /// </summary> public string keyName; string key { get { return (string.IsNullOrEmpty(keyName)) ? "NGUI State: " + name : keyName; } } UIPopupList mList; UIToggle mCheck; UIProgressBar mSlider; /// <summary> /// Cache the components and register a listener callback. /// </summary> void Awake () { mList = GetComponent<UIPopupList>(); mCheck = GetComponent<UIToggle>(); mSlider = GetComponent<UIProgressBar>(); } /// <summary> /// Load and set the state of the toggles. /// </summary> void OnEnable () { if (mList != null) { EventDelegate.Add(mList.onChange, SaveSelection); string s = PlayerPrefs.GetString(key); if (!string.IsNullOrEmpty(s)) mList.value = s; } else if (mCheck != null) { EventDelegate.Add(mCheck.onChange, SaveState); mCheck.value = (PlayerPrefs.GetInt(key, mCheck.startsActive ? 1 : 0) != 0); } else if (mSlider != null) { EventDelegate.Add(mSlider.onChange, SaveProgress); mSlider.value = PlayerPrefs.GetFloat(key, mSlider.value); } else { string s = PlayerPrefs.GetString(key); UIToggle[] toggles = GetComponentsInChildren<UIToggle>(true); for (int i = 0, imax = toggles.Length; i < imax; ++i) { UIToggle ch = toggles[i]; ch.value = (ch.name == s); } } } /// <summary> /// Save the state on destroy. /// </summary> void OnDisable () { if (mCheck != null) EventDelegate.Remove(mCheck.onChange, SaveState); else if (mList != null) EventDelegate.Remove(mList.onChange, SaveSelection); else if (mSlider != null) EventDelegate.Remove(mSlider.onChange, SaveProgress); else { UIToggle[] toggles = GetComponentsInChildren<UIToggle>(true); for (int i = 0, imax = toggles.Length; i < imax; ++i) { UIToggle ch = toggles[i]; if (ch.value) { PlayerPrefs.SetString(key, ch.name); break; } } } } /// <summary> /// Save the selection. /// </summary> public void SaveSelection () { PlayerPrefs.SetString(key, UIPopupList.current.value); } /// <summary> /// Save the state. /// </summary> public void SaveState () { PlayerPrefs.SetInt(key, UIToggle.current.value ? 1 : 0); } /// <summary> /// Save the current progress. /// </summary> public void SaveProgress () { PlayerPrefs.SetFloat(key, UIProgressBar.current.value); } }
0
0.932406
1
0.932406
game-dev
MEDIA
0.527312
game-dev,desktop-app
0.975565
1
0.975565
po-devs/pokemon-online
2,242
src/BattleServer/mechanicsbase.cpp
#include "mechanicsbase.h" BattleBase::TurnMemory & PureMechanicsBase::fturn(BattleBase &b, int player) { return b.turnMem(player); } BattleBase::context & PureMechanicsBase::poke(BattleBase &b, int player) { return b.pokeMemory(player); } BattleBase::BasicPokeInfo & PureMechanicsBase::fpoke(BattleBase &b, int player) { return b.fpoke(player); } BattleBase::context & PureMechanicsBase::turn(BattleBase &b, int player) { return b.turnMemory(player); } int PureMechanicsBase::type(BattleBase &b, int source) { return tmove(b, source).type; } int PureMechanicsBase::move(BattleBase &b, int source) { return tmove(b, source).attack; } BattleBase::BasicMoveInfo & PureMechanicsBase::tmove(BattleBase &b, int source) { return b.tmove(source); } void PureMechanicsBase::initMove(int num, Pokemon::gen gen, BattleBase::BasicMoveInfo &data) { /* Different steps: critical raise, number of times, ... */ data.critRaise = MoveInfo::CriticalRaise(num, gen); data.repeatMin = MoveInfo::RepeatMin(num, gen); data.repeatMax = MoveInfo::RepeatMax(num, gen); data.priority = MoveInfo::SpeedPriority(num, gen); data.flags = MoveInfo::Flags(num, gen); data.power = MoveInfo::Power(num, gen); data.zpower = MoveInfo::ZPower(num, gen); data.accuracy = MoveInfo::Acc(num, gen); data.type = MoveInfo::Type(num, gen); data.category = MoveInfo::Category(num, gen); data.rate = MoveInfo::EffectRate(num, gen); //(*this)["StatEffect"] = MoveInfo::Effect(num, gen); data.flinchRate = MoveInfo::FlinchRate(num, gen); data.recoil = MoveInfo::Recoil(num, gen); data.attack = num; data.targets = MoveInfo::Target(num, gen); data.healing = MoveInfo::Healing(num, gen); data.classification = MoveInfo::Classification(num, gen); data.status = MoveInfo::Status(num, gen); //data.statusKind = MoveInfo::StatusKind(num, gen); data.minTurns = MoveInfo::MinTurns(num, gen); data.maxTurns = MoveInfo::MaxTurns(num, gen); data.statAffected = MoveInfo::StatAffected(num, gen); data.boostOfStat = MoveInfo::BoostOfStat(num, gen); data.rateOfStat = MoveInfo::RateOfStat(num, gen); //data.kingRock = MoveInfo::FlinchByKingRock(num, gen); }
0
0.856054
1
0.856054
game-dev
MEDIA
0.935016
game-dev
0.948612
1
0.948612
soui3/soui
2,261
third-part/skia/src/utils/ios/SkOSFile_iOS.mm
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Foundation/Foundation.h> #include "SkOSFile.h" #include "SkString.h" struct SkFILE { NSData* fData; size_t fOffset; size_t fLength; }; SkFILE* sk_fopen(const char cpath[], SkFILE_Flags flags) { if (flags & kWrite_SkFILE_Flag) { return NULL; } SkString cname, csuffix; const char* start = strrchr(cpath, '/'); if (NULL == start) { start = cpath; } else { start += 1; } const char* stop = strrchr(cpath, '.'); if (NULL == stop) { return NULL; } else { stop += 1; } cname.set(start, stop - start - 1); csuffix.set(stop); NSBundle* bundle = [NSBundle mainBundle]; NSString* name = [NSString stringWithUTF8String:cname.c_str()]; NSString* suffix = [NSString stringWithUTF8String:csuffix.c_str()]; NSString* path = [bundle pathForResource:name ofType:suffix]; NSData* data = [NSData dataWithContentsOfMappedFile:path]; if (data) { [data retain]; SkFILE* rec = new SkFILE; rec->fData = data; rec->fOffset = 0; rec->fLength = [data length]; return reinterpret_cast<SkFILE*>(rec); } return NULL; } size_t sk_fgetsize(SkFILE* rec) { SkASSERT(rec); return rec->fLength; } bool sk_frewind(SkFILE* rec) { SkASSERT(rec); rec->fOffset = 0; return true; } size_t sk_fread(void* buffer, size_t byteCount, SkFILE* rec) { if (NULL == buffer) { return rec->fLength; } else { size_t remaining = rec->fLength - rec->fOffset; if (byteCount > remaining) { byteCount = remaining; } memcpy(buffer, (char*)[rec->fData bytes] + rec->fOffset, byteCount); rec->fOffset += byteCount; SkASSERT(rec->fOffset <= rec->fLength); return byteCount; } } size_t sk_fwrite(const void* buffer, size_t byteCount, SkFILE* f) { SkDEBUGFAIL("Not supported yet"); return 0; } void sk_fflush(SkFILE* f) { SkDEBUGFAIL("Not supported yet"); } void sk_fclose(SkFILE* rec) { SkASSERT(rec); [rec->fData release]; delete rec; }
0
0.89555
1
0.89555
game-dev
MEDIA
0.157147
game-dev
0.957107
1
0.957107
Cubed-Development/Modern-Warfare-Cubed
4,528
src/main/java/com/paneedah/weaponlib/ItemMagazine.java
package com.paneedah.weaponlib; import com.paneedah.mwc.instancing.PlayerItemInstanceFactory; import com.paneedah.mwc.instancing.PlayerMagazineInstance; import com.paneedah.mwc.instancing.Tags; import lombok.Getter; import net.minecraft.client.model.ModelBase; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.SoundEvent; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import java.util.ArrayList; import java.util.List; public class ItemMagazine extends ItemAttachment<Weapon> implements PlayerItemInstanceFactory<PlayerMagazineInstance, MagazineState>, Reloadable, Updatable, Part { public static final class Builder extends AttachmentBuilder<Weapon> { private int capacity; private final List<ItemBullet> compatibleBullets = new ArrayList<>(); private String reloadSound; private String unloadSound; public Builder withCapacity(int capacity) { this.capacity = capacity; return this; } public Builder withCompatibleBullet(ItemBullet compatibleBullet) { this.compatibleBullets.add(compatibleBullet); return this; } public Builder withUnloadSound(String unloadSound) { this.unloadSound = unloadSound; return this; } public Builder withReloadSound(String reloadSound) { this.reloadSound = reloadSound; return this; } @Override protected ItemAttachment<Weapon> createAttachment(ModContext modContext) { final ItemMagazine magazine = new ItemMagazine(getModel(), getTextureName(), capacity); magazine.compatibleBullets = compatibleBullets; if (reloadSound != null) { magazine.reloadSound = modContext.registerSound(reloadSound); } if (unloadSound != null) { magazine.unloadSound = modContext.registerSound(unloadSound); } magazine.modContext = modContext; informationProvider = stack -> TextFormatting.GREEN + "Ammunition: " + TextFormatting.GRAY + Tags.getAmmo(stack) + "/" + capacity; return magazine; } } private ModContext modContext; @Getter private final int capacity; @Getter private List<ItemBullet> compatibleBullets; @Getter private SoundEvent reloadSound; @Getter private SoundEvent unloadSound; ItemMagazine(ModelBase model, String textureName, int capacity) { this(model, textureName, capacity, null, null); } ItemMagazine(ModelBase model, String textureName, int capacity, ApplyHandler<Weapon> apply, ApplyHandler<Weapon> remove) { super(AttachmentCategory.MAGAZINE, model, textureName, apply, remove); this.capacity = capacity; setMaxStackSize(1); } public ItemStack create(int ammunition) { final ItemStack itemStack = new ItemStack(this); initializeTag(itemStack, ammunition); return itemStack; } public ItemStack create() { return this.create(capacity); } private void initializeTag(ItemStack itemStack, int initialAmmo) { if (itemStack.getTagCompound() == null) { itemStack.setTagCompound(new NBTTagCompound()); Tags.setAmmo(itemStack, initialAmmo); } } @Override public void onCreated(ItemStack stack, World world, EntityPlayer player) { initializeTag(stack, 0); } @Override public Part getRenderablePart() { return this; } @Override public PlayerMagazineInstance createItemInstance(final EntityLivingBase entityLivingBase, final ItemStack itemStack, final int slot) { final PlayerMagazineInstance instance = new PlayerMagazineInstance(slot, entityLivingBase, itemStack); instance.setState(MagazineState.READY); return instance; } @Override public void update(EntityPlayer player) { modContext.getMagazineReloadAspect().updateMainHeldItem(player); } @Override public void reloadMainHeldItemForPlayer(EntityPlayer player) { modContext.getMagazineReloadAspect().reloadMainHeldItem(player); } @Override public void unloadMainHeldItemForPlayer(EntityPlayer player) { modContext.getMagazineReloadAspect().unloadMainHeldItem(player); } }
0
0.833706
1
0.833706
game-dev
MEDIA
0.963181
game-dev
0.824775
1
0.824775
lwwhb/RoadToDotsTutorials
3,342
Assets/JobsTutorials/Lesson1/Scripts/DOD/AutoRotateAndMoveJob.cs
using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using Unity.Mathematics; using UnityEngine; using UnityEngine.Jobs; namespace Jobs.DOD { public struct AutoRotateAndMoveJob : IJobParallelForTransform { public float deltaTime; public float moveSpeed; public float rotateSpeed; public NativeArray<Vector3> randTargetPosArray; public void Execute(int index, TransformAccess transform) { Vector3 moveDir = (randTargetPosArray[index] - transform.position).normalized; transform.position += moveDir * moveSpeed * deltaTime; Vector3 localEulerAngles = transform.localRotation.eulerAngles; localEulerAngles.y += rotateSpeed * deltaTime; Quaternion localRotation = Quaternion.Euler(localEulerAngles); transform.localRotation = localRotation; } } [BurstCompile] public struct AutoRotateAndMoveJobOptimize0 : IJobParallelForTransform { public float deltaTime; public float moveSpeed; public float rotateSpeed; public NativeArray<Vector3> randTargetPosArray; public void Execute(int index, TransformAccess transform) { Vector3 moveDir = (randTargetPosArray[index] - transform.position).normalized; transform.position += moveDir * moveSpeed * deltaTime; Vector3 localEulerAngles = transform.localRotation.eulerAngles; localEulerAngles.y += rotateSpeed * deltaTime; Quaternion localRotation = Quaternion.Euler(localEulerAngles); transform.localRotation = localRotation; } } [BurstCompile] public struct AutoRotateAndMoveJobOptimize1 : IJobParallelForTransform { public float deltaTime; public float moveSpeed; public float rotateSpeed; [ReadOnly] public NativeArray<Vector3> randTargetPosArray; public void Execute(int index, TransformAccess transform) { Vector3 moveDir = (randTargetPosArray[index] - transform.position).normalized; transform.position += moveDir * moveSpeed * deltaTime; Vector3 localEulerAngles = transform.localRotation.eulerAngles; localEulerAngles.y += rotateSpeed * deltaTime; Quaternion localRotation = Quaternion.Euler(localEulerAngles); transform.localRotation = localRotation; } } [BurstCompile] public struct AutoRotateAndMoveJobOptimize2 : IJobParallelForTransform { public float deltaTime; public float moveSpeed; public float rotateSpeed; [ReadOnly] public NativeArray<float3> randTargetPosArray; public void Execute(int index, TransformAccess transform) { float3 moveDir = math.normalize(randTargetPosArray[index] - (float3)transform.position); float3 delta = moveDir * moveSpeed * deltaTime; transform.position += new Vector3(delta.x, delta.y, delta.z); Vector3 localEulerAngles = transform.localRotation.eulerAngles; localEulerAngles.y += rotateSpeed * deltaTime; Quaternion localRotation = Quaternion.Euler(localEulerAngles); transform.localRotation = localRotation; } } }
0
0.947369
1
0.947369
game-dev
MEDIA
0.95825
game-dev
0.966615
1
0.966615
minecraft-dotnet/Substrate
2,026
SubstrateCS/Source/Entities/EntityFallingSand.cs
using System; using System.Collections.Generic; using System.Text; namespace Substrate.Entities { using Substrate.Nbt; public class EntityFallingSand : TypedEntity { public static readonly SchemaNodeCompound FallingSandSchema = TypedEntity.Schema.MergeInto(new SchemaNodeCompound("") { new SchemaNodeString("id", TypeId), new SchemaNodeScaler("Tile", TagType.TAG_BYTE), }); public static string TypeId { get { return "FallingSand"; } } private byte _tile; public int Tile { get { return _tile; } set { _tile = (byte)value; } } protected EntityFallingSand (string id) : base(id) { } public EntityFallingSand () : this(TypeId) { } public EntityFallingSand (TypedEntity e) : base(e) { EntityFallingSand e2 = e as EntityFallingSand; if (e2 != null) { _tile = e2._tile; } } #region INBTObject<Entity> Members public override TypedEntity LoadTree (TagNode tree) { TagNodeCompound ctree = tree as TagNodeCompound; if (ctree == null || base.LoadTree(tree) == null) { return null; } _tile = ctree["Tile"].ToTagByte(); return this; } public override TagNode BuildTree () { TagNodeCompound tree = base.BuildTree() as TagNodeCompound; tree["Tile"] = new TagNodeByte(_tile); return tree; } public override bool ValidateTree (TagNode tree) { return new NbtVerifier(tree, FallingSandSchema).Verify(); } #endregion #region ICopyable<Entity> Members public override TypedEntity Copy () { return new EntityFallingSand(this); } #endregion } }
0
0.650334
1
0.650334
game-dev
MEDIA
0.831871
game-dev
0.804724
1
0.804724
chai3d/chai3d
5,738
modules/Bullet/externals/bullet/src/BulletDynamics/ConstraintSolver/btTypedConstraint.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 "btTypedConstraint.h" #include "BulletDynamics/Dynamics/btRigidBody.h" #include "LinearMath/btSerializer.h" #define DEFAULT_DEBUGDRAW_SIZE btScalar(0.3f) btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA) :btTypedObject(type), m_userConstraintType(-1), m_userConstraintPtr((void*)-1), m_breakingImpulseThreshold(SIMD_INFINITY), m_isEnabled(true), m_needsFeedback(false), m_overrideNumSolverIterations(-1), m_rbA(rbA), m_rbB(getFixedBody()), m_appliedImpulse(btScalar(0.)), m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE), m_jointFeedback(0) { } btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA,btRigidBody& rbB) :btTypedObject(type), m_userConstraintType(-1), m_userConstraintPtr((void*)-1), m_breakingImpulseThreshold(SIMD_INFINITY), m_isEnabled(true), m_needsFeedback(false), m_overrideNumSolverIterations(-1), m_rbA(rbA), m_rbB(rbB), m_appliedImpulse(btScalar(0.)), m_dbgDrawSize(DEFAULT_DEBUGDRAW_SIZE), m_jointFeedback(0) { } btScalar btTypedConstraint::getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact) { if(lowLim > uppLim) { return btScalar(1.0f); } else if(lowLim == uppLim) { return btScalar(0.0f); } btScalar lim_fact = btScalar(1.0f); btScalar delta_max = vel / timeFact; if(delta_max < btScalar(0.0f)) { if((pos >= lowLim) && (pos < (lowLim - delta_max))) { lim_fact = (lowLim - pos) / delta_max; } else if(pos < lowLim) { lim_fact = btScalar(0.0f); } else { lim_fact = btScalar(1.0f); } } else if(delta_max > btScalar(0.0f)) { if((pos <= uppLim) && (pos > (uppLim - delta_max))) { lim_fact = (uppLim - pos) / delta_max; } else if(pos > uppLim) { lim_fact = btScalar(0.0f); } else { lim_fact = btScalar(1.0f); } } else { lim_fact = btScalar(0.0f); } return lim_fact; } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btTypedConstraint::serialize(void* dataBuffer, btSerializer* serializer) const { btTypedConstraintData2* tcd = (btTypedConstraintData2*) dataBuffer; tcd->m_rbA = (btRigidBodyData*)serializer->getUniquePointer(&m_rbA); tcd->m_rbB = (btRigidBodyData*)serializer->getUniquePointer(&m_rbB); char* name = (char*) serializer->findNameForPointer(this); tcd->m_name = (char*)serializer->getUniquePointer(name); if (tcd->m_name) { serializer->serializeName(name); } tcd->m_objectType = m_objectType; tcd->m_needsFeedback = m_needsFeedback; tcd->m_overrideNumSolverIterations = m_overrideNumSolverIterations; tcd->m_breakingImpulseThreshold = m_breakingImpulseThreshold; tcd->m_isEnabled = m_isEnabled? 1: 0; tcd->m_userConstraintId =m_userConstraintId; tcd->m_userConstraintType =m_userConstraintType; tcd->m_appliedImpulse = m_appliedImpulse; tcd->m_dbgDrawSize = m_dbgDrawSize; tcd->m_disableCollisionsBetweenLinkedBodies = false; int i; for (i=0;i<m_rbA.getNumConstraintRefs();i++) if (m_rbA.getConstraintRef(i) == this) tcd->m_disableCollisionsBetweenLinkedBodies = true; for (i=0;i<m_rbB.getNumConstraintRefs();i++) if (m_rbB.getConstraintRef(i) == this) tcd->m_disableCollisionsBetweenLinkedBodies = true; return btTypedConstraintDataName; } btRigidBody& btTypedConstraint::getFixedBody() { static btRigidBody s_fixed(0, 0,0); s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.))); return s_fixed; } void btAngularLimit::set(btScalar low, btScalar high, btScalar _softness, btScalar _biasFactor, btScalar _relaxationFactor) { m_halfRange = (high - low) / 2.0f; m_center = btNormalizeAngle(low + m_halfRange); m_softness = _softness; m_biasFactor = _biasFactor; m_relaxationFactor = _relaxationFactor; } void btAngularLimit::test(const btScalar angle) { m_correction = 0.0f; m_sign = 0.0f; m_solveLimit = false; if (m_halfRange >= 0.0f) { btScalar deviation = btNormalizeAngle(angle - m_center); if (deviation < -m_halfRange) { m_solveLimit = true; m_correction = - (deviation + m_halfRange); m_sign = +1.0f; } else if (deviation > m_halfRange) { m_solveLimit = true; m_correction = m_halfRange - deviation; m_sign = -1.0f; } } } btScalar btAngularLimit::getError() const { return m_correction * m_sign; } void btAngularLimit::fit(btScalar& angle) const { if (m_halfRange > 0.0f) { btScalar relativeAngle = btNormalizeAngle(angle - m_center); if (!btEqual(relativeAngle, m_halfRange)) { if (relativeAngle > 0.0f) { angle = getHigh(); } else { angle = getLow(); } } } } btScalar btAngularLimit::getLow() const { return btNormalizeAngle(m_center - m_halfRange); } btScalar btAngularLimit::getHigh() const { return btNormalizeAngle(m_center + m_halfRange); }
0
0.880399
1
0.880399
game-dev
MEDIA
0.960852
game-dev
0.968478
1
0.968478
SebLague/Tiny-Chess-Bot-Challenge-Results
7,698
Bots/Bot_64.cs
namespace auto_Bot_64; using ChessChallenge.API; using System; public class Bot_64 : IChessBot { readonly int[] pieceValues = { 0, 1, 3, 3, 5, 9, 10 }; public Move Think(Board board, Timer timer) { Move[] moves = board.GetLegalMoves(); return GetBestMove(board, moves); } //returns move with best evaluation or specific move private Move GetBestMove(Board board, Move[] moves) { Move bestMove = moves[0]; float bestEvaluation = -100; foreach (Move move in moves) { float currentEvaluation = GetMoveEvaluation(board, move); //playes checkmante if (MoveIsCheckmate(board, move)) { return move; } //doesnt play move that allows checkmate if (MoveAllowsCheckmate(board, move)) { currentEvaluation = -100; } //doesnt play move that allows draw at an advantadge if (MoveAllowsDraw(board, move) && GetTeamPieceScoreDifference(board) > 8) { currentEvaluation = -50; } //plays move that forces checkmate in two if (OddsOfCheckmateInTwo(board, move) == 1) { currentEvaluation = 200; } //plays move that draws at a disavantage if (MoveIsDraw(board, move) && GetTeamPieceScoreDifference(board) <= 0) { currentEvaluation = 100; } if (currentEvaluation > bestEvaluation) { bestMove = move; bestEvaluation = currentEvaluation; } } //Debug.WriteLine(bestEvaluation); return bestMove; } private float GetMoveEvaluation(Board board, Move move) { Random rnd = new Random(); int thisPieceValue = GetPieceValue(move.MovePieceType); int capturedPieceValue = GetPieceValue(move.CapturePieceType); int promotionPieceValue = GetPieceValue(move.PromotionPieceType); float evaluation = 0; //prioritize pieces in danger evaluation += (board.SquareIsAttackedByOpponent(move.StartSquare) && !board.IsInCheck()) ? +thisPieceValue * 0.9f : 0; //halt pieces heading to danger evaluation += board.SquareIsAttackedByOpponent(move.TargetSquare) ? -thisPieceValue * 1f : 0; //reward protected squares evaluation += GetNPiecesProtectingSquareOnMove(board, move) * 0.02f; //reward check evaluation += MoveIsCheck(board, move) ? 0.03f : 0; //adds capured piece value evaluation += capturedPieceValue * 1; //adds promotion profit evaluation += promotionPieceValue * 4; //adds of checkmate in two evaluation += (float)Math.Pow(OddsOfCheckmateInTwo(board, move), 6) * 0.2f; if (thisPieceValue == 1 && move.TargetSquare.File > 0 && move.TargetSquare.File < 7) { evaluation += (board.IsWhiteToMove ? 0.7f / (7 - move.TargetSquare.File) : 0.7f / MathF.Abs(0 - move.TargetSquare.File)); } evaluation += rnd.Next(1) * 0.01f; return evaluation; } private int GetNPiecesProtectingSquareOnMove(Board board, Move move) { Move[] myMoves = board.GetLegalMoves(); int nPiecesProtectingSquare = 0; foreach (Move m in myMoves) { if (m == move) continue; if (m.TargetSquare == move.TargetSquare) { nPiecesProtectingSquare++; } } return nPiecesProtectingSquare; } private static bool MoveIsCheck(Board board, Move move) { board.MakeMove(move); bool isCheck = board.IsInCheck(); board.UndoMove(move); return isCheck; } private bool MoveIsCheckmate(Board board, Move move) { board.MakeMove(move); bool isMate = board.IsInCheckmate(); board.UndoMove(move); return isMate; } private bool MoveIsDraw(Board board, Move move) { board.MakeMove(move); bool isDraw = board.IsDraw(); board.UndoMove(move); return isDraw; } private bool MoveAllowsCheckmate(Board board, Move move) { board.MakeMove(move); Move[] adversaryMoves = board.GetLegalMoves(); foreach (Move ad in adversaryMoves) { board.MakeMove(ad); if (board.IsInCheckmate()) { board.UndoMove(ad); board.UndoMove(move); return true; } board.UndoMove(ad); } board.UndoMove(move); return false; } private bool MoveAllowsDraw(Board board, Move move) { board.MakeMove(move); Move[] adversaryMoves = board.GetLegalMoves(); foreach (Move ad in adversaryMoves) { board.MakeMove(ad); if (board.IsDraw()) { board.UndoMove(ad); board.UndoMove(move); return true; } board.UndoMove(ad); } board.UndoMove(move); return false; } private int GetTeamPieceTotalScore(Board board, bool isWhite) { PieceList[] boardPieceList = board.GetAllPieceLists(); int totalScore = 0; for (int i = 0; i < pieceValues.Length - 1; i++) { for (int j = 0; j < boardPieceList[i].Count; j++) { Piece currentPiece = boardPieceList[i][j]; if (currentPiece.IsWhite == isWhite) { totalScore += GetPieceValue(currentPiece.PieceType); } } } return totalScore; } //score difference, smaller is worse, < 0 is disavantage private int GetTeamPieceScoreDifference(Board board) { int ourTeamScore = GetTeamPieceTotalScore(board, board.IsWhiteToMove); int opponentTeamScore = GetTeamPieceTotalScore(board, !board.IsWhiteToMove); return ourTeamScore - opponentTeamScore; } //odds of move forcing a checkmate in two, 0-1 private float OddsOfCheckmateInTwo(Board board, Move move) { board.MakeMove(move); //get possible responses Move[] adversaryMoves = board.GetLegalMoves(); //array of possible chekmate on opponent move bool[] adversaryMovesAllowCheckmate = new bool[adversaryMoves.Length]; //loop through opponent moves for (int i = 0; i < adversaryMoves.Length; i++) { //do move board.MakeMove(adversaryMoves[i]); //get our possible responses Move[] ourNextMoves = board.GetLegalMoves(); for (int j = 0; j < ourNextMoves.Length; j++) { //allows a checkmate if (MoveIsCheckmate(board, ourNextMoves[j])) { adversaryMovesAllowCheckmate[i] = true; break; } } board.UndoMove(adversaryMoves[i]); } board.UndoMove(move); int nMovesAllowingCheckmate = 0; //check if checkmate is certain foreach (bool moveAllows in adversaryMovesAllowCheckmate) { if (moveAllows) nMovesAllowingCheckmate++; } if (adversaryMoves.Length == 0) return 1; return nMovesAllowingCheckmate / adversaryMoves.Length; } private int GetPieceValue(PieceType pieceType) { return pieceValues[(int)pieceType]; } }
0
0.87305
1
0.87305
game-dev
MEDIA
0.691372
game-dev
0.860116
1
0.860116
NBlood/NBlood
5,357
source/duke3d/src/input.cpp
//------------------------------------------------------------------------- /* Copyright (C) 2010 EDuke32 developers and contributors This file is part of EDuke32. EDuke32 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- #include "global.h" #include "game.h" #include "function.h" #include "keyboard.h" #include "mouse.h" #include "joystick.h" #include "control.h" #include "input.h" #include "menus.h" int32_t I_CheckAllInput(void) { return KB_KeyWaiting() || MOUSE_GetButtons() || JOYSTICK_GetButtons() #if defined EDUKE32_IOS || g_mouseClickState == MOUSE_PRESSED #endif ; } void I_ClearAllInput(void) { KB_FlushKeyboardQueue(); KB_ClearKeysDown(); MOUSE_ClearAllButtons(); JOYSTICK_ClearAllButtons(); CONTROL_ClearAllButtons(); mouseAdvanceClickState(); } void I_ClearLast(void) { CONTROL_ClearUserInput(nullptr); } int32_t I_TextSubmit(void) { // FIXME: this is needed because the menu code does some weird shit. // for some reason, if the mouse cursor is hidden, activating menu items is handled immediately on button press, // but if the mouse cursor is visible, activating menu items is handled on button release instead... // ...except for the right mouse button, which is handled immediately on button press in both cases. if (!MOUSEINACTIVECONDITIONAL(1) || !MOUSEACTIVECONDITIONAL(1)) MOUSE_ClearButton(M_LEFTBUTTON); return CONTROL_GetUserInput(nullptr)->b_advance; } int32_t I_ReturnTrigger(void) { return CONTROL_GetUserInput(nullptr)->b_return; } int32_t I_AdvanceTrigger(void) { return I_TextSubmit() || KB_KeyPressed(sc_Space); } void I_TextSubmitClear(void) { I_ClearAllInput(); } void I_AdvanceTriggerClear(void) { I_ClearLast(); KB_ClearKeyDown(sc_Space); } int32_t I_GeneralTrigger(void) { return I_AdvanceTrigger() || I_ReturnTrigger() || I_EscapeTrigger() #if !defined GEKKO || BUTTON(gamefunc_Open) # if !defined EDUKE32_TOUCH_DEVICES || MOUSEINACTIVECONDITIONAL(BUTTON(gamefunc_Fire)) # else || BUTTON(gamefunc_Fire) # endif #endif ; } void I_GeneralTriggerClear(void) { I_AdvanceTriggerClear(); // I_ReturnTriggerClear(); #if !defined GEKKO CONTROL_ClearButton(gamefunc_Open); CONTROL_ClearButton(gamefunc_Fire); #endif } int32_t I_EscapeTrigger(void) { return CONTROL_GetUserInput(nullptr)->b_escape; } int32_t I_MenuUp(void) { return CONTROL_GetUserInput(nullptr)->dir == dir_Up || BUTTON(gamefunc_Move_Forward); } int32_t I_MenuDown(void) { return CONTROL_GetUserInput(nullptr)->dir == dir_Down || BUTTON(gamefunc_Move_Backward); } int32_t I_MenuLeft(void) { return CONTROL_GetUserInput(nullptr)->dir == dir_Left || BUTTON(gamefunc_Turn_Left) || BUTTON(gamefunc_Strafe_Left); } int32_t I_MenuRight(void) { return CONTROL_GetUserInput(nullptr)->dir == dir_Right || BUTTON(gamefunc_Turn_Right) || BUTTON(gamefunc_Strafe_Right); } int32_t I_SliderLeft(void) { return I_MenuLeft() || /*MOUSEACTIVECONDITIONAL*/(MOUSE_GetButtons() & M_WHEELDOWN); } int32_t I_SliderRight(void) { return I_MenuRight() || /*MOUSEACTIVECONDITIONAL*/(MOUSE_GetButtons() & M_WHEELUP); } int32_t I_PanelUp(void) { return I_MenuUp() || I_MenuLeft() || KB_KeyPressed(sc_PgUp); } int32_t I_PanelDown(void) { return I_MenuDown() || I_MenuRight() || KB_KeyPressed(sc_PgDn); } void I_PanelUpClear(void) { I_ClearLast(); KB_ClearKeyDown(sc_PgUp); } void I_PanelDownClear(void) { I_ClearLast(); KB_ClearKeyDown(sc_PgDn); } int32_t I_EnterText(char *t, int32_t maxlength, int32_t flags) { char ch; int32_t inputloc = Bstrlen(typebuf); while ((ch = KB_GetCh()) != 0) { if (ch == asc_BackSpace) { if (inputloc > 0) { inputloc--; *(t+inputloc) = 0; } } else { if (ch == asc_Enter) { I_AdvanceTriggerClear(); return 1; } else if (ch == asc_Escape) { I_ReturnTriggerClear(); return -1; } else if (ch >= 32 && inputloc < maxlength && ch < 127) { if (!(flags & INPUT_NUMERIC) || (ch >= '0' && ch <= '9')) { // JBF 20040508: so we can have numeric only if we want *(t+inputloc) = ch; *(t+inputloc+1) = 0; inputloc++; } } } } if (I_TextSubmit()) { I_TextSubmitClear(); return 1; } if (I_ReturnTrigger()) { I_ReturnTriggerClear(); return -1; } return 0; }
0
0.926495
1
0.926495
game-dev
MEDIA
0.739789
game-dev
0.924791
1
0.924791
xBimTeam/XbimEssentials
1,712
Xbim.Ifc2x3/Interfaces/IFC4/IfcRelAssociatesLibrary.cs
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool Xbim.CodeGeneration // // Changes to this file may cause incorrect behaviour and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ using Xbim.Ifc4.Interfaces; using System.Collections.Generic; using System.Linq; using Xbim.Common; // ReSharper disable once CheckNamespace namespace Xbim.Ifc2x3.Kernel { public partial class @IfcRelAssociatesLibrary : IIfcRelAssociatesLibrary { [CrossSchemaAttribute(typeof(IIfcRelAssociatesLibrary), 6)] IIfcLibrarySelect IIfcRelAssociatesLibrary.RelatingLibrary { get { if (RelatingLibrary == null) return null; var ifclibraryreference = RelatingLibrary as ExternalReferenceResource.IfcLibraryReference; if (ifclibraryreference != null) return ifclibraryreference; var ifclibraryinformation = RelatingLibrary as ExternalReferenceResource.IfcLibraryInformation; if (ifclibraryinformation != null) return ifclibraryinformation; return null; } set { if (value == null) { RelatingLibrary = null; return; } var ifclibraryinformation = value as ExternalReferenceResource.IfcLibraryInformation; if (ifclibraryinformation != null) { RelatingLibrary = ifclibraryinformation; return; } var ifclibraryreference = value as ExternalReferenceResource.IfcLibraryReference; if (ifclibraryreference != null) { RelatingLibrary = ifclibraryreference; return; } } } //## Custom code //## } }
0
0.749491
1
0.749491
game-dev
MEDIA
0.099884
game-dev
0.721118
1
0.721118
OregonCore/OregonCore
16,454
src/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp
/* * This file is part of the OregonCore Project. See AUTHORS file for Copyright information * * 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 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, see <https://www.gnu.org/licenses/>. */ /* ScriptData SDName: Arcatraz SD%Complete: 60 SDComment: Warden Mellichar, event controller for Skyriss event. Millhouse Manastorm. @todo make better combatAI for Millhouse. SDCategory: Tempest Keep, The Arcatraz EndScriptData */ /* ContentData npc_millhouse_manastorm npc_warden_mellichar mob_zerekethvoidzone EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "arcatraz.h" /*##### # npc_millhouse_manastorm #####*/ #define SAY_INTRO_1 -1552010 #define SAY_INTRO_2 -1552011 #define SAY_WATER -1552012 #define SAY_BUFFS -1552013 #define SAY_DRINK -1552014 #define SAY_READY -1552015 #define SAY_KILL_1 -1552016 #define SAY_KILL_2 -1552017 #define SAY_PYRO -1552018 #define SAY_ICEBLOCK -1552019 #define SAY_LOWHP -1552020 #define SAY_DEATH -1552021 #define SAY_COMPLETE -1552022 #define SPELL_CONJURE_WATER 36879 #define SPELL_ARCANE_INTELLECT 36880 #define SPELL_ICE_ARMOR 36881 #define SPELL_ARCANE_MISSILES 33833 #define SPELL_CONE_OF_COLD 12611 #define SPELL_FIRE_BLAST 13341 #define SPELL_FIREBALL 14034 #define SPELL_FROSTBOLT 15497 #define SPELL_PYROBLAST 33975 struct npc_millhouse_manastormAI : public ScriptedAI { npc_millhouse_manastormAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; uint32 EventProgress_Timer; uint32 Phase; bool Init; bool LowHp; uint32 Pyroblast_Timer; uint32 Fireball_Timer; void Reset() { EventProgress_Timer = 2000; LowHp = false; Init = false; Phase = 1; Pyroblast_Timer = 1000; Fireball_Timer = 2500; if (pInstance) { if (pInstance->GetData(DATA_WARDEN_2) == DONE) Init = true; if (pInstance->GetData(DATA_HARBINGERSKYRISS) == DONE) DoScriptText(SAY_COMPLETE, me); } } void AttackStart(Unit* pWho) { if (me->Attack(pWho, true)) { me->AddThreat(pWho, 0.0f); me->SetInCombatWith(pWho); pWho->SetInCombatWith(me); me->GetMotionMaster()->MoveChase(pWho, 25.0f); } } void EnterCombat(Unit* /*who*/) { } void KilledUnit(Unit* /*victim*/) { switch (rand() % 2) { case 0: DoScriptText(SAY_KILL_1, me); break; case 1: DoScriptText(SAY_KILL_2, me); break; } } void JustDied(Unit* /*victim*/) { DoScriptText(SAY_DEATH, me); /*for questId 10886 (heroic mode only) if (pInstance && pInstance->GetData(DATA_HARBINGERSKYRISS) != DONE) ->FailQuest();*/ } void UpdateAI(const uint32 diff) { if (!Init) { if (EventProgress_Timer <= diff) { if (Phase < 8) { switch (Phase) { case 1: DoScriptText(SAY_INTRO_1, me); EventProgress_Timer = 18000; break; case 2: DoScriptText(SAY_INTRO_2, me); EventProgress_Timer = 18000; break; case 3: DoScriptText(SAY_WATER, me); DoCast(me, SPELL_CONJURE_WATER); EventProgress_Timer = 7000; break; case 4: DoScriptText(SAY_BUFFS, me); DoCast(me, SPELL_ICE_ARMOR); EventProgress_Timer = 7000; break; case 5: DoScriptText(SAY_DRINK, me); DoCast(me, SPELL_ARCANE_INTELLECT); EventProgress_Timer = 7000; break; case 6: DoScriptText(SAY_READY, me); EventProgress_Timer = 6000; break; case 7: if (pInstance) pInstance->SetData(DATA_WARDEN_2, DONE); Init = true; break; } ++Phase; } } else EventProgress_Timer -= diff; } if (!UpdateVictim()) return; if (!LowHp && HealthBelowPct(20)) { DoScriptText(SAY_LOWHP, me); LowHp = true; } if (Pyroblast_Timer <= diff) { if (me->IsNonMeleeSpellCast(false)) return; DoScriptText(SAY_PYRO, me); DoCastVictim(SPELL_PYROBLAST); Pyroblast_Timer = 40000; } else Pyroblast_Timer -= diff; if (Fireball_Timer <= diff) { DoCastVictim(SPELL_FIREBALL); Fireball_Timer = 4000; } else Fireball_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_npc_millhouse_manastorm(Creature* pCreature) { return new npc_millhouse_manastormAI (pCreature); } /*##### # npc_warden_mellichar #####*/ #define YELL_INTRO1 -1552023 #define YELL_INTRO2 -1552024 #define YELL_RELEASE1 -1552025 #define YELL_RELEASE2A -1552026 #define YELL_RELEASE2B -1552027 #define YELL_RELEASE3 -1552028 #define YELL_RELEASE4 -1552029 #define YELL_WELCOME -1552030 //phase 2(acid mobs) #define ENTRY_TRICKSTER 20905 #define ENTRY_PH_HUNTER 20906 //phase 3 #define ENTRY_MILLHOUSE 20977 //phase 4(acid mobs) #define ENTRY_AKKIRIS 20908 #define ENTRY_SULFURON 20909 //phase 5(acid mobs) #define ENTRY_TW_DRAK 20910 #define ENTRY_BL_DRAK 20911 //phase 6 #define ENTRY_SKYRISS 20912 //TARGET_SCRIPT #define SPELL_TARGET_ALPHA 36856 #define SPELL_TARGET_BETA 36854 #define SPELL_TARGET_DELTA 36857 #define SPELL_TARGET_GAMMA 36858 #define SPELL_TARGET_OMEGA 36852 #define SPELL_BUBBLE_VISUAL 36849 struct npc_warden_mellicharAI : public ScriptedAI { npc_warden_mellicharAI(Creature* c) : ScriptedAI(c) { pInstance = (ScriptedInstance*)c->GetInstanceData(); } ScriptedInstance* pInstance; bool IsRunning; bool CanSpawn; uint32 EventProgress_Timer; uint32 Phase; void Reset() { IsRunning = false; CanSpawn = false; EventProgress_Timer = 22000; Phase = 1; me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); DoCast(me, SPELL_TARGET_OMEGA); if (pInstance) pInstance->SetData(DATA_HARBINGERSKYRISS, NOT_STARTED); } void AttackStart(Unit* /*who*/) { } void MoveInLineOfSight(Unit* who) { if (IsRunning) return; if (!me->GetVictim() && who->isTargetableForAttack() && (me->IsHostileTo(who)) && who->isInAccessiblePlaceFor (me)) { if (!me->CanFly() && me->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE) return; if (who->GetTypeId() != TYPEID_PLAYER) return; float attackRadius = me->GetAttackDistance(who) / 10; if (me->IsWithinDistInMap(who, attackRadius) && me->IsWithinLOSInMap(who)) EnterCombat(who); } } void EnterCombat(Unit* /*who*/) { DoScriptText(YELL_INTRO1, me); DoCast(me, SPELL_BUBBLE_VISUAL); if (pInstance) { pInstance->SetData(DATA_HARBINGERSKYRISS, IN_PROGRESS); if (GameObject* Sphere = GameObject::GetGameObject(*me, pInstance->GetData64(DATA_SPHERE_SHIELD))) Sphere->SetGoState(GO_STATE_READY); IsRunning = true; } } bool CanProgress() { if (pInstance) { if (Phase == 7 && pInstance->GetData(DATA_WARDEN_4) == DONE) return true; if (Phase == 6 && pInstance->GetData(DATA_WARDEN_3) == DONE) return true; if (Phase == 5 && pInstance->GetData(DATA_WARDEN_2) == DONE) return true; if (Phase == 4) return true; if (Phase == 3 && pInstance->GetData(DATA_WARDEN_1) == DONE) return true; if (Phase == 2 && pInstance->GetData(DATA_HARBINGERSKYRISS) == IN_PROGRESS) return true; if (Phase == 1 && pInstance->GetData(DATA_HARBINGERSKYRISS) == IN_PROGRESS) return true; return false; } return false; } void DoPrepareForPhase() { if (pInstance) { me->InterruptNonMeleeSpells(true); me->RemoveSpellsCausingAura(SPELL_AURA_DUMMY); switch (Phase) { case 2: DoCast(me, SPELL_TARGET_ALPHA); pInstance->SetData(DATA_WARDEN_1, IN_PROGRESS); if (GameObject* Sphere = GameObject::GetGameObject(*me, pInstance->GetData64(DATA_SPHERE_SHIELD))) Sphere->SetGoState(GO_STATE_READY); break; case 3: DoCast(me, SPELL_TARGET_BETA); pInstance->SetData(DATA_WARDEN_2, IN_PROGRESS); break; case 5: DoCast(me, SPELL_TARGET_DELTA); pInstance->SetData(DATA_WARDEN_3, IN_PROGRESS); break; case 6: DoCast(me, SPELL_TARGET_GAMMA); pInstance->SetData(DATA_WARDEN_4, IN_PROGRESS); break; case 7: pInstance->SetData(DATA_WARDEN_5, IN_PROGRESS); break; } CanSpawn = true; } } void UpdateAI(const uint32 diff) { if (!IsRunning) return; if (EventProgress_Timer <= diff) { if (pInstance) { if (pInstance->GetData(DATA_HARBINGERSKYRISS) == FAIL) Reset(); } if (CanSpawn) { //continue beam omega pod, unless we are about to summon skyriss if (Phase != 7) DoCast(me, SPELL_TARGET_OMEGA); switch (Phase) { case 2: switch (rand() % 2) { case 0: me->SummonCreature(ENTRY_TRICKSTER, 478.326f, -148.505f, 42.56f, 3.19f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; case 1: me->SummonCreature(ENTRY_PH_HUNTER, 478.326f, -148.505f, 42.56f, 3.19f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; } break; case 3: me->SummonCreature(ENTRY_MILLHOUSE, 413.292f, -148.378f, 42.56f, 6.27f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; case 4: DoScriptText(YELL_RELEASE2B, me); break; case 5: switch (rand() % 2) { case 0: me->SummonCreature(ENTRY_AKKIRIS, 420.179f, -174.396f, 42.58f, 0.02f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; case 1: me->SummonCreature(ENTRY_SULFURON, 420.179f, -174.396f, 42.58f, 0.02f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; } break; case 6: switch (rand() % 2) { case 0: me->SummonCreature(ENTRY_TW_DRAK, 471.795f, -174.58f, 42.58f, 3.06f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; case 1: me->SummonCreature(ENTRY_BL_DRAK, 471.795f, -174.58f, 42.58f, 3.06f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); break; } break; case 7: me->SummonCreature(ENTRY_SKYRISS, 445.763f, -191.639f, 44.64f, 1.60f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000); DoScriptText(YELL_WELCOME, me); break; } CanSpawn = false; ++Phase; } if (CanProgress()) { switch (Phase) { case 1: DoScriptText(YELL_INTRO2, me); EventProgress_Timer = 10000; ++Phase; break; case 2: DoScriptText(YELL_RELEASE1, me); DoPrepareForPhase(); EventProgress_Timer = 7000; break; case 3: DoScriptText(YELL_RELEASE2A, me); DoPrepareForPhase(); EventProgress_Timer = 10000; break; case 4: DoPrepareForPhase(); EventProgress_Timer = 15000; break; case 5: DoScriptText(YELL_RELEASE3, me); DoPrepareForPhase(); EventProgress_Timer = 15000; break; case 6: DoScriptText(YELL_RELEASE4, me); DoPrepareForPhase(); EventProgress_Timer = 15000; break; case 7: DoPrepareForPhase(); EventProgress_Timer = 15000; break; } } } else EventProgress_Timer -= diff; } }; CreatureAI* GetAI_npc_warden_mellichar(Creature* pCreature) { return new npc_warden_mellicharAI (pCreature); } /*##### # mob_zerekethvoidzone (this script probably not needed in future -> `creature_template_addon`.`auras`='36120 0') #####*/ #define SPELL_VOID_ZONE_DAMAGE 36120 struct mob_zerekethvoidzoneAI : public ScriptedAI { mob_zerekethvoidzoneAI(Creature* c) : ScriptedAI(c) {} void Reset() { me->SetUInt32Value(UNIT_NPC_FLAGS, 0); me->SetFaction(16); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); DoCast(me, SPELL_VOID_ZONE_DAMAGE); } void EnterCombat(Unit* /*who*/) {} }; CreatureAI* GetAI_mob_zerekethvoidzoneAI(Creature* pCreature) { return new mob_zerekethvoidzoneAI (pCreature); } void AddSC_arcatraz() { Script* newscript; newscript = new Script; newscript->Name = "npc_millhouse_manastorm"; newscript->GetAI = &GetAI_npc_millhouse_manastorm; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_warden_mellichar"; newscript->GetAI = &GetAI_npc_warden_mellichar; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_zerekethvoidzone"; newscript->GetAI = &GetAI_mob_zerekethvoidzoneAI; newscript->RegisterSelf(); }
0
0.983815
1
0.983815
game-dev
MEDIA
0.97613
game-dev
0.984111
1
0.984111
StranikS-Scan/WorldOfTanks-Decompiled
2,398
source/res/scripts/client/gui/doc_loaders/event_settings_loader.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/doc_loaders/event_settings_loader.py import logging from collections import namedtuple import typing from ResMgr import DataSection from bonus_readers import readBonusSection, SUPPORTED_BONUSES from gui.server_events.bonuses import getNonQuestBonuses, splitBonuses import resource_helper from soft_exception import SoftException _logger = logging.getLogger(__name__) _EVENT_CONFIG_XML_PATH = 'gui/event_gui_settings.xml' _EVENT_SETTINGS = None _EventSettings = namedtuple('_EventSettings', ('vehicleCharacteristics',)) _VehicleCharacteristics = namedtuple('VehicleCharacteristics', ('pros', 'cons', 'role')) def _readEventSettings(): _, section = resource_helper.getRoot(_EVENT_CONFIG_XML_PATH) result = _EventSettings(_readVehicleCharacteristics(section['vehicleCharacteristics'])) resource_helper.purgeResource(_EVENT_CONFIG_XML_PATH) return result def _readVehicleCharacteristics(section): properties = frozenset(section['properties'].asString.split(' ')) result = {} for subsection in section['vehicles'].values(): vehicle = subsection['name'].asString result[vehicle] = _VehicleCharacteristics(_readProperties(subsection['pros'], properties), _readProperties(subsection['cons'], properties), role=subsection['role'].asString) return result def _readProperties(section, allProperties): properties = section.asString.split(' ') for prop in properties: if prop not in allProperties: raise SoftException('Incorrect vehicle property "%s" in the event settings' % prop) return properties def _readCollection(section): collection = [] for subsection in section.values(): bonuses = [] items = readBonusSection(SUPPORTED_BONUSES, subsection) for key, value in items.iteritems(): bonuses.extend(getNonQuestBonuses(key, value)) collection.extend(splitBonuses(bonuses)) return collection def getVehicleCharacteristics(): data = getEventSettings().vehicleCharacteristics if data is None: _logger.error('There is not vehicle characteristics') return {} else: return data def getEventSettings(): global _EVENT_SETTINGS if _EVENT_SETTINGS is None: _EVENT_SETTINGS = _readEventSettings() return _EVENT_SETTINGS
0
0.670862
1
0.670862
game-dev
MEDIA
0.506157
game-dev
0.892474
1
0.892474
opentk/opentk
11,609
src/Generator.Bind/Main.cs
/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos * See license.txt for license info */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Security; using System.Text.RegularExpressions; using Bind.CL; using Bind.ES; using Bind.GL2; namespace Bind { internal enum GeneratorMode { All = 0, Default = All, GL2, GL3, GL4, ES10, ES11, ES20, ES30, CL10, } internal static class MainClass { private static GeneratorMode mode = GeneratorMode.Default; static internal List<IBind> Generators = new List<IBind>(); private static Settings Settings = new Settings(); private static void Main(string[] arguments) { // These prevent us to accidently generate wrong code because of // locale dependent string functions. CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; Debug.AutoFlush = true; Trace.Listeners.Clear(); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.AutoFlush = true; Console.WriteLine("OpenGL binding generator {0} for OpenTK.", Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("For comments, bugs and suggestions visit http://github.com/opentk/opentk"); Console.WriteLine(); try { var split = new Regex(@"-\w+", RegexOptions.Compiled); foreach (var argument in arguments) { string a = argument.Replace("--", "-").Trim(); var match = split.Match(a); if (match.Success) { string opt = match.Value.Substring(1).Trim(); string val; if (a.Contains(":")) val = a.Substring(a.IndexOf(":") + 1).Trim(); else val = string.Empty; switch (opt) { case "?": case "help": ShowHelp(); return; case "in": case "input": Settings.InputPath = val; break; case "out": case "output": Settings.OutputPath = val; break; case "mode": { string arg = val.ToLower(); SetGeneratorMode(arg); break; } case "namespace": case "ns": Settings.OutputNamespace = val; break; case "class": Settings.OutputClass = val; break; case "gl": Settings.GLClass = val; break; case "legacy": case "o": case "option": { val = val.ToLower(); bool enable = !opt.StartsWith("-"); if (val.StartsWith("+") || val.StartsWith("-")) { val = val.Substring(1); } var settings = Settings.Legacy.None; switch (val) { case "tao": settings |= Settings.Legacy.Tao; break; case "simple_enums": settings |= Settings.Legacy.NoAdvancedEnumProcessing; break; case "safe": settings |= Settings.Legacy.NoPublicUnsafeFunctions; break; case "permutations": settings |= Settings.Legacy.GenerateAllPermutations; break; case "enums_in_class": settings |= Settings.Legacy.NestedEnums; break; case "nodocs": settings |= Settings.Legacy.NoDocumentation; break; case "keep_untyped_enums": settings |= Settings.Legacy.KeepUntypedEnums; break; } if (enable) { Settings.Compatibility |= settings; } else { Settings.Compatibility &= ~settings; } break; } default: throw new ArgumentException( String.Format("Argument not recognized. Use the '-help' switch for help.\n{0}", a) ); } } } } catch (NullReferenceException e) { Console.WriteLine("Argument error. Please use the '-help' switch for help.\n{0}", e.ToString()); return; } catch (ArgumentException e) { Console.WriteLine("Argument error. Please use the '-help' switch for help.\n{0}", e.ToString()); return; } try { switch (mode) { case GeneratorMode.All: Console.WriteLine("Using 'all' generator mode."); Console.WriteLine("Use '-mode:all/gl2/gl4/es10/es11/es20/es30/es31' to select a specific mode."); Generators.Add(new GL2Generator(Settings)); Generators.Add(new GL4Generator(Settings)); Generators.Add(new ESGenerator(Settings)); Generators.Add(new ES2Generator(Settings)); Generators.Add(new ES3Generator(Settings)); break; case GeneratorMode.GL2: Generators.Add(new GL2Generator(Settings)); break; case GeneratorMode.GL3: case GeneratorMode.GL4: Generators.Add(new GL4Generator(Settings)); break; case GeneratorMode.ES10: Generators.Add(new ESGenerator(Settings)); break; case GeneratorMode.ES11: Generators.Add(new ESGenerator(Settings)); break; case GeneratorMode.ES20: Generators.Add(new ES2Generator(Settings)); break; case GeneratorMode.ES30: Generators.Add(new ES3Generator(Settings)); break; case GeneratorMode.CL10: Generators.Add(new CLGenerator(Settings)); break; default: Console.WriteLine("Please specify a generator mode (use '-mode:gl2/gl4/es10/es11/es20/es30')"); return; } foreach (var generator in Generators) { long ticks = DateTime.Now.Ticks; generator.Process(); var writer = new CSharpSpecWriter(); writer.WriteBindings(generator); ticks = DateTime.Now.Ticks - ticks; Console.WriteLine(); Console.WriteLine("Bindings generated in {0} seconds.", ticks / (double)10000000.0); } Console.WriteLine(); if (Debugger.IsAttached) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } } catch (SecurityException e) { Console.WriteLine("Security violation \"{0}\" in method \"{1}\".", e.Message, e.Method); Console.WriteLine("This application does not have permission to take the requested actions."); } catch (NotImplementedException e) { Console.WriteLine(e.Message); Console.WriteLine("The requested functionality is not implemented yet."); } } private static void SetGeneratorMode(string arg) { switch (arg) { case "gl": case "gl2": mode = GeneratorMode.GL2; break; case "gl3": case "gl4": mode = GeneratorMode.GL4; break; case "es10": mode = GeneratorMode.ES10; break; case "es11": mode = GeneratorMode.ES11; break; case "es2": case "es20": mode = GeneratorMode.ES20; break; case "es3": case "es30": mode = GeneratorMode.ES30; break; case "cl": case "cl10": mode = GeneratorMode.CL10; break; default: throw new NotSupportedException(); } } private static void ShowHelp() { Console.WriteLine( @"Usage: bind [-in:path] [-out:path] [switches] Available switches: -in: Input directory (e.g. -in:../specs/) -out: Output directory (e.g. -out:out) -ns: Output namespace (e.g. -ns:OpenTK.Graphics). Default: OpenTK.Graphics.OpenGL -namespace: Same as -ns -class: Output class (e.g. -class:GL3). Default: GL/Wgl/Glu/Glx (depends on -mode) -mode: Generator mode (e.g. -mode:gl4). Default: all Accepted: all/gl2/gl4/es10/es11/es20 -o/-option: Set advanced option. Available options: -o:tao Tao compatibility mode. -o:enums Follow OpenGL instead .Net naming conventions. -o:safe Do not generate public unsafe functions. -o:enums_in_class Place enums in a nested class (i.e. GL.Enums) instead of a namespace (i.e. OpenTK.Graphics.OpenGL.Enums) "); } } }
0
0.821573
1
0.821573
game-dev
MEDIA
0.407329
game-dev
0.756114
1
0.756114
Avalon-Benchmark/avalon
10,840
avalon/datagen/world_creation/entities/doors/hinge_door.py
import math from typing import List import attr import numpy as np from godot_parser import Color from godot_parser import Node as GDNode from godot_parser import NodePath from scipy.spatial.transform import Rotation from avalon.common.utils import only from avalon.datagen.world_creation.entities.doors.door import Door from avalon.datagen.world_creation.entities.doors.locks.rotating_bar import RotatingBar from avalon.datagen.world_creation.entities.doors.locks.sliding_bar import SlidingBar from avalon.datagen.world_creation.entities.doors.types import HingeSide from avalon.datagen.world_creation.entities.doors.types import LatchingMechanics from avalon.datagen.world_creation.indoor.blocks import new_make_block_nodes from avalon.datagen.world_creation.indoor.utils import get_scaled_mesh_node from avalon.datagen.world_creation.types import GodotScene from avalon.datagen.world_creation.utils import make_transform @attr.s(auto_attribs=True, hash=True, collect_by_mro=True) class HingeDoor(Door): hinge_side: HingeSide = HingeSide.LEFT hinge_radius: float = 0.05 max_inwards_angle: float = 90.0 max_outwards_angle: float = 90.0 handle_size_proportion: float = 0.2 latching_mechanics: LatchingMechanics = LatchingMechanics.NO_LATCH def get_node(self, scene: GodotScene) -> GDNode: DOOR_BODY = "body" body_nodes = self._get_body_nodes(scene, DOOR_BODY) hinge_nodes = self._get_hinge_nodes(scene, DOOR_BODY) door_script = scene.add_ext_resource("res://entities/doors/hinge_door.gd", "Script") group_spatial_node = GDNode( f"hinge_door_{self.entity_id}", "Spatial", properties={ "transform": make_transform(self.rotation, self.position), "script": door_script.reference, "entity_id": self.entity_id, "is_latched": self.latching_mechanics != LatchingMechanics.NO_LATCH, }, ) for body_node in body_nodes: group_spatial_node.add_child(body_node) for hinge_node in hinge_nodes: group_spatial_node.add_child(hinge_node) body_node = only(body_nodes) door_body_width = self.size[0] door_body_size = np.array([door_body_width, self.size[1], self.size[2]]) body_x_offset = -door_body_width / 2 if self.hinge_side == HingeSide.RIGHT else door_body_width / 2 for i, lock in enumerate(self.locks): # if we have two locks of the same kind, their instance names will otherwise crash lock_with_id = attr.evolve(lock, entity_id=i) group_spatial_node.add_child(lock_with_id.get_node(scene)) offset_centroid = np.array([body_x_offset, 0, 0]) for body_addition in lock_with_id.get_additional_door_body_nodes(scene, door_body_size, offset_centroid): body_node.add_child(body_addition) return group_spatial_node def _get_body_nodes(self, scene: GodotScene, door_body_node_name: str) -> List[GDNode]: # The door body here also includes the handle, since PinJoints suck in Godot, so we can't have them separate :/ door_width, door_height, door_thickness = self.size if self.hinge_side == HingeSide.LEFT: body_offset = np.array([door_width / 2, 0, 0]) body_position = np.array([-door_width / 2 + self.hinge_radius, 0, 0]) else: body_offset = np.array([-door_width / 2, 0, 0]) body_position = np.array([door_width / 2 - self.hinge_radius, 0, 0]) body_children_nodes = new_make_block_nodes( scene, body_offset, self.size, make_parent=False, make_mesh=False, collision_shape_name=f"{door_body_node_name}_collision_shape", ) body_mesh_node = get_scaled_mesh_node( scene, "res://entities/doors/door_body.tscn", self.size, body_offset, mesh_name="body_mesh" ) body_children_nodes.append(body_mesh_node) handle_nodes = self._get_handle_nodes(scene) body_script = scene.add_ext_resource("res://entities/doors/door_body.gd", "Script") body_node = GDNode( door_body_node_name, type="RigidBody", properties={ "transform": make_transform(position=body_position), "mass": 100.0, "script": body_script.reference, "is_auto_latching": self.latching_mechanics == LatchingMechanics.AUTO_LATCH, "entity_id": 0, }, ) for node in body_children_nodes: body_node.add_child(node) for node in handle_nodes: body_node.add_child(node) return [body_node] def _get_handle_nodes(self, scene: GodotScene) -> List[GDNode]: DOOR_HANDLE = "handle" door_width, door_height, door_thickness = self.size handle_width = door_width * self.handle_size_proportion handle_height = door_height * (self.handle_size_proportion / 2) handle_thickness = 0.15 # We cap the handle height if there are locks that would get obstructed by it leeway = 0.05 bar_locks = [lock for lock in self.locks if isinstance(lock, (RotatingBar, SlidingBar))] if len(bar_locks) > 0: max_y = np.inf min_y = -np.inf for lock in bar_locks: if not isinstance(lock, (RotatingBar, SlidingBar)): continue if lock.position[1] > 0 and (lock_bottom := lock.position[1] - lock.size[1] / 2) < max_y: max_y = lock_bottom elif lock.position[1] < 0 and (lock_top := lock.position[1] + lock.size[1] / 2) > min_y: min_y = lock_top max_handle_height = min(abs(max_y), abs(min_y)) * 2 - leeway if handle_height > max_handle_height: handle_height = max_handle_height # We cap the handle width to ensure it doesn't prevent the door from opening inwards max_width = math.sqrt( (door_width - leeway) ** 2 - handle_thickness**2 ) # diagonal of handle can't exceed door width handle_width = min(max_width, handle_width) handle_size = np.array([handle_width, handle_height, handle_thickness]) handle_margin_skew = 25 # how many right-margins fit in the left margin handle_side_margin = (door_width - handle_width) / (1 + handle_margin_skew) * handle_margin_skew if self.hinge_side == HingeSide.LEFT: handle_x = handle_side_margin + handle_width / 2 else: handle_x = -(handle_side_margin + handle_width / 2) handle_offsets = 1, -1 handle_nodes = [] for i, handle_offset in enumerate(handle_offsets): handle_position = np.array( [ handle_x, 0, handle_offset * (handle_thickness / 2 + door_thickness / 2), ] ) handle_name = f"{DOOR_HANDLE}_{i}" handle_nodes.extend( new_make_block_nodes( scene, handle_position, handle_size, make_parent=False, make_mesh=False, collision_shape_name=f"{handle_name}_collision_shape", ) ) handle_mesh_node = get_scaled_mesh_node( scene, "res://entities/doors/door_handle_loop.tscn", handle_size, handle_position, mesh_name=f"{handle_name}_mesh", ) handle_nodes.append(handle_mesh_node) return handle_nodes def _get_hinge_nodes(self, scene: GodotScene, door_body_node_name: str) -> List[GDNode]: DOOR_HINGE = "hinge" door_width, door_height, door_thickness = self.size frame_width = door_width + 2 * self.hinge_radius hinge_height = door_height body_left_side = -frame_width / 2 + 2 * self.hinge_radius body_right_side = frame_width / 2 - 2 * self.hinge_radius if self.hinge_side == HingeSide.LEFT: hinge_x = -frame_width / 2 + self.hinge_radius else: hinge_x = frame_width / 2 - self.hinge_radius hinge_position = hinge_x, 0, 0 hinge_material = scene.add_sub_resource( "SpatialMaterial", albedo_color=Color(0.223529, 0.196078, 0.141176, 1), roughness=0.2, metallic=0.5 ) hinge_mesh_node = GDNode( "mesh", "MeshInstance", properties={ "transform": make_transform(), "mesh": scene.add_sub_resource( "CylinderMesh", material=hinge_material.reference, top_radius=self.hinge_radius, bottom_radius=self.hinge_radius, height=hinge_height, ).reference, }, ) hinge_collision_mesh_node = GDNode( "collision_shape", "CollisionShape", properties={ "shape": scene.add_sub_resource( "CylinderShape", radius=self.hinge_radius, height=hinge_height ).reference, "disabled": True, }, ) hinge_node = GDNode( DOOR_HINGE, "StaticBody", properties={ "transform": make_transform(position=hinge_position), }, ) hinge_node.add_child(hinge_mesh_node) hinge_node.add_child(hinge_collision_mesh_node) hinge_rotation_degrees = 90 if self.hinge_side == HingeSide.LEFT else -90 hinge_joint_position = body_left_side if self.hinge_side == HingeSide.LEFT else body_right_side, 0, 0 hinge_rotation = Rotation.from_euler("x", hinge_rotation_degrees, degrees=True).as_matrix().flatten() hinge_joint_node = GDNode( "hinge_joint", "HingeJoint", properties={ "transform": make_transform(position=hinge_joint_position, rotation=hinge_rotation), "nodes/node_a": NodePath(f"../{DOOR_HINGE}"), "nodes/node_b": NodePath(f"../{door_body_node_name}"), "params/bias": 0.99, "angular_limit/enable": True, "angular_limit/lower": -self.max_outwards_angle, "angular_limit/upper": self.max_inwards_angle, "angular_limit/bias": 0.99, "angular_limit/softness": 0.01, "angular_limit/relaxation": 0.01, }, ) return [hinge_node, hinge_joint_node]
0
0.921338
1
0.921338
game-dev
MEDIA
0.592449
game-dev,graphics-rendering
0.974328
1
0.974328
vinjn/pkg-doctor
15,458
AssetStudio/AssetStudio/SerializedFile.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace AssetStudio { public class SerializedFile { public AssetsManager assetsManager; public FileReader reader; public string fullName; public string originalPath; public string fileName; public int[] version = { 0, 0, 0, 0 }; public BuildType buildType; public List<Object> Objects; public Dictionary<long, Object> ObjectsDic; public SerializedFileHeader header; private byte m_FileEndianess; public string unityVersion = "2.5.0f5"; public BuildTarget m_TargetPlatform = BuildTarget.UnknownPlatform; private bool m_EnableTypeTree = true; public List<SerializedType> m_Types; public int bigIDEnabled = 0; public List<ObjectInfo> m_Objects; private List<LocalSerializedObjectIdentifier> m_ScriptTypes; public List<FileIdentifier> m_Externals; public List<SerializedType> m_RefTypes; public string userInformation; public SerializedFile(FileReader reader, AssetsManager assetsManager) { this.assetsManager = assetsManager; this.reader = reader; fullName = reader.FullPath; fileName = reader.FileName; // ReadHeader header = new SerializedFileHeader(); header.m_MetadataSize = reader.ReadUInt32(); header.m_FileSize = reader.ReadUInt32(); header.m_Version = (SerializedFileFormatVersion)reader.ReadUInt32(); header.m_DataOffset = reader.ReadUInt32(); if (header.m_Version >= SerializedFileFormatVersion.Unknown_9) { header.m_Endianess = reader.ReadByte(); header.m_Reserved = reader.ReadBytes(3); m_FileEndianess = header.m_Endianess; } else { reader.Position = header.m_FileSize - header.m_MetadataSize; m_FileEndianess = reader.ReadByte(); } if (header.m_Version >= SerializedFileFormatVersion.LargeFilesSupport) { header.m_MetadataSize = reader.ReadUInt32(); header.m_FileSize = reader.ReadInt64(); header.m_DataOffset = reader.ReadInt64(); reader.ReadInt64(); // unknown } // ReadMetadata if (m_FileEndianess == 0) { reader.Endian = EndianType.LittleEndian; } if (header.m_Version >= SerializedFileFormatVersion.Unknown_7) { unityVersion = reader.ReadStringToNull(); SetVersion(unityVersion); } if (header.m_Version >= SerializedFileFormatVersion.Unknown_8) { m_TargetPlatform = (BuildTarget)reader.ReadInt32(); if (!Enum.IsDefined(typeof(BuildTarget), m_TargetPlatform)) { m_TargetPlatform = BuildTarget.UnknownPlatform; } } if (header.m_Version >= SerializedFileFormatVersion.HasTypeTreeHashes) { m_EnableTypeTree = reader.ReadBoolean(); } // Read Types int typeCount = reader.ReadInt32(); m_Types = new List<SerializedType>(typeCount); for (int i = 0; i < typeCount; i++) { m_Types.Add(ReadSerializedType(false)); } if (header.m_Version >= SerializedFileFormatVersion.Unknown_7 && header.m_Version < SerializedFileFormatVersion.Unknown_14) { bigIDEnabled = reader.ReadInt32(); } // Read Objects int objectCount = reader.ReadInt32(); m_Objects = new List<ObjectInfo>(objectCount); Objects = new List<Object>(objectCount); ObjectsDic = new Dictionary<long, Object>(objectCount); for (int i = 0; i < objectCount; i++) { var objectInfo = new ObjectInfo(); if (bigIDEnabled != 0) { objectInfo.m_PathID = reader.ReadInt64(); } else if (header.m_Version < SerializedFileFormatVersion.Unknown_14) { objectInfo.m_PathID = reader.ReadInt32(); } else { reader.AlignStream(); objectInfo.m_PathID = reader.ReadInt64(); } if (header.m_Version >= SerializedFileFormatVersion.LargeFilesSupport) objectInfo.byteStart = reader.ReadInt64(); else objectInfo.byteStart = reader.ReadUInt32(); objectInfo.byteStart += header.m_DataOffset; objectInfo.byteSize = reader.ReadUInt32(); objectInfo.typeID = reader.ReadInt32(); if (header.m_Version < SerializedFileFormatVersion.RefactoredClassId) { objectInfo.classID = reader.ReadUInt16(); objectInfo.serializedType = m_Types.Find(x => x.classID == objectInfo.typeID); } else { var type = m_Types[objectInfo.typeID]; objectInfo.serializedType = type; objectInfo.classID = type.classID; } if (header.m_Version < SerializedFileFormatVersion.HasScriptTypeIndex) { objectInfo.isDestroyed = reader.ReadUInt16(); } if (header.m_Version >= SerializedFileFormatVersion.HasScriptTypeIndex && header.m_Version < SerializedFileFormatVersion.RefactorTypeData) { var m_ScriptTypeIndex = reader.ReadInt16(); if (objectInfo.serializedType != null) objectInfo.serializedType.m_ScriptTypeIndex = m_ScriptTypeIndex; } if (header.m_Version == SerializedFileFormatVersion.SupportsStrippedObject || header.m_Version == SerializedFileFormatVersion.RefactoredClassId) { objectInfo.stripped = reader.ReadByte(); } m_Objects.Add(objectInfo); } if (header.m_Version >= SerializedFileFormatVersion.HasScriptTypeIndex) { int scriptCount = reader.ReadInt32(); m_ScriptTypes = new List<LocalSerializedObjectIdentifier>(scriptCount); for (int i = 0; i < scriptCount; i++) { var m_ScriptType = new LocalSerializedObjectIdentifier(); m_ScriptType.localSerializedFileIndex = reader.ReadInt32(); if (header.m_Version < SerializedFileFormatVersion.Unknown_14) { m_ScriptType.localIdentifierInFile = reader.ReadInt32(); } else { reader.AlignStream(); m_ScriptType.localIdentifierInFile = reader.ReadInt64(); } m_ScriptTypes.Add(m_ScriptType); } } int externalsCount = reader.ReadInt32(); m_Externals = new List<FileIdentifier>(externalsCount); for (int i = 0; i < externalsCount; i++) { var m_External = new FileIdentifier(); if (header.m_Version >= SerializedFileFormatVersion.Unknown_6) { var tempEmpty = reader.ReadStringToNull(); } if (header.m_Version >= SerializedFileFormatVersion.Unknown_5) { m_External.guid = new Guid(reader.ReadBytes(16)); m_External.type = reader.ReadInt32(); } m_External.pathName = reader.ReadStringToNull(); m_External.fileName = Path.GetFileName(m_External.pathName); m_Externals.Add(m_External); } if (header.m_Version >= SerializedFileFormatVersion.SupportsRefObject) { int refTypesCount = reader.ReadInt32(); m_RefTypes = new List<SerializedType>(refTypesCount); for (int i = 0; i < refTypesCount; i++) { m_RefTypes.Add(ReadSerializedType(true)); } } if (header.m_Version >= SerializedFileFormatVersion.Unknown_5) { userInformation = reader.ReadStringToNull(); } //reader.AlignStream(16); } public void SetVersion(string stringVersion) { if (stringVersion != strippedVersion) { unityVersion = stringVersion; var buildSplit = Regex.Replace(stringVersion, @"\d", "").Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries); buildType = new BuildType(buildSplit[0]); var versionSplit = Regex.Replace(stringVersion, @"\D", ".").Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries); version = versionSplit.Select(int.Parse).ToArray(); } } private SerializedType ReadSerializedType(bool isRefType) { var type = new SerializedType(); type.classID = reader.ReadInt32(); if (header.m_Version >= SerializedFileFormatVersion.RefactoredClassId) { type.m_IsStrippedType = reader.ReadBoolean(); } if (header.m_Version >= SerializedFileFormatVersion.RefactorTypeData) { type.m_ScriptTypeIndex = reader.ReadInt16(); } if (header.m_Version >= SerializedFileFormatVersion.HasTypeTreeHashes) { if (isRefType && type.m_ScriptTypeIndex >= 0) { type.m_ScriptID = reader.ReadBytes(16); } else if ((header.m_Version < SerializedFileFormatVersion.RefactoredClassId && type.classID < 0) || (header.m_Version >= SerializedFileFormatVersion.RefactoredClassId && type.classID == 114)) { type.m_ScriptID = reader.ReadBytes(16); } type.m_OldTypeHash = reader.ReadBytes(16); } if (m_EnableTypeTree) { type.m_Type = new TypeTree(); type.m_Type.m_Nodes = new List<TypeTreeNode>(); if (header.m_Version >= SerializedFileFormatVersion.Unknown_12 || header.m_Version == SerializedFileFormatVersion.Unknown_10) { TypeTreeBlobRead(type.m_Type); } else { ReadTypeTree(type.m_Type); } if (header.m_Version >= SerializedFileFormatVersion.StoresTypeDependencies) { if (isRefType) { type.m_KlassName = reader.ReadStringToNull(); type.m_NameSpace = reader.ReadStringToNull(); type.m_AsmName = reader.ReadStringToNull(); } else { type.m_TypeDependencies = reader.ReadInt32Array(); } } } return type; } private void ReadTypeTree(TypeTree m_Type, int level = 0) { var typeTreeNode = new TypeTreeNode(); m_Type.m_Nodes.Add(typeTreeNode); typeTreeNode.m_Level = level; typeTreeNode.m_Type = reader.ReadStringToNull(); typeTreeNode.m_Name = reader.ReadStringToNull(); typeTreeNode.m_ByteSize = reader.ReadInt32(); if (header.m_Version == SerializedFileFormatVersion.Unknown_2) { var variableCount = reader.ReadInt32(); } if (header.m_Version != SerializedFileFormatVersion.Unknown_3) { typeTreeNode.m_Index = reader.ReadInt32(); } typeTreeNode.m_TypeFlags = reader.ReadInt32(); typeTreeNode.m_Version = reader.ReadInt32(); if (header.m_Version != SerializedFileFormatVersion.Unknown_3) { typeTreeNode.m_MetaFlag = reader.ReadInt32(); } int childrenCount = reader.ReadInt32(); for (int i = 0; i < childrenCount; i++) { ReadTypeTree(m_Type, level + 1); } } private void TypeTreeBlobRead(TypeTree m_Type) { int numberOfNodes = reader.ReadInt32(); int stringBufferSize = reader.ReadInt32(); for (int i = 0; i < numberOfNodes; i++) { var typeTreeNode = new TypeTreeNode(); m_Type.m_Nodes.Add(typeTreeNode); typeTreeNode.m_Version = reader.ReadUInt16(); typeTreeNode.m_Level = reader.ReadByte(); typeTreeNode.m_TypeFlags = reader.ReadByte(); typeTreeNode.m_TypeStrOffset = reader.ReadUInt32(); typeTreeNode.m_NameStrOffset = reader.ReadUInt32(); typeTreeNode.m_ByteSize = reader.ReadInt32(); typeTreeNode.m_Index = reader.ReadInt32(); typeTreeNode.m_MetaFlag = reader.ReadInt32(); if (header.m_Version >= SerializedFileFormatVersion.TypeTreeNodeWithTypeFlags) { typeTreeNode.m_RefTypeHash = reader.ReadUInt64(); } } m_Type.m_StringBuffer = reader.ReadBytes(stringBufferSize); using (var stringBufferReader = new BinaryReader(new MemoryStream(m_Type.m_StringBuffer))) { for (int i = 0; i < numberOfNodes; i++) { var m_Node = m_Type.m_Nodes[i]; m_Node.m_Type = ReadString(stringBufferReader, m_Node.m_TypeStrOffset); m_Node.m_Name = ReadString(stringBufferReader, m_Node.m_NameStrOffset); } } string ReadString(BinaryReader stringBufferReader, uint value) { var isOffset = (value & 0x80000000) == 0; if (isOffset) { stringBufferReader.BaseStream.Position = value; return stringBufferReader.ReadStringToNull(); } var offset = value & 0x7FFFFFFF; if (CommonString.StringBuffer.TryGetValue(offset, out var str)) { return str; } return offset.ToString(); } } public void AddObject(Object obj) { Objects.Add(obj); ObjectsDic.Add(obj.m_PathID, obj); } public bool IsVersionStripped => unityVersion == strippedVersion; private const string strippedVersion = "0.0.0"; } }
0
0.829365
1
0.829365
game-dev
MEDIA
0.420074
game-dev
0.930127
1
0.930127
kipr/opencv
6,577
samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java
package org.opencv.samples.puzzle15; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.core.Point; import android.util.Log; /** * This class is a controller for puzzle game. * It converts the image from Camera into the shuffled image */ public class Puzzle15Processor { private static final int GRID_SIZE = 4; private static final int GRID_AREA = GRID_SIZE * GRID_SIZE; private static final int GRID_EMPTY_INDEX = GRID_AREA - 1; private static final String TAG = "Puzzle15Processor"; private static final Scalar GRID_EMPTY_COLOR = new Scalar(0x33, 0x33, 0x33, 0xFF); private int[] mIndexes; private int[] mTextWidths; private int[] mTextHeights; private Mat mRgba15; private Mat[] mCells15; private boolean mShowTileNumbers = true; public Puzzle15Processor() { mTextWidths = new int[GRID_AREA]; mTextHeights = new int[GRID_AREA]; mIndexes = new int [GRID_AREA]; for (int i = 0; i < GRID_AREA; i++) mIndexes[i] = i; } /* this method is intended to make processor prepared for a new game */ public synchronized void prepareNewGame() { do { shuffle(mIndexes); } while (!isPuzzleSolvable()); } /* This method is to make the processor know the size of the frames that * will be delivered via puzzleFrame. * If the frames will be different size - then the result is unpredictable */ public synchronized void prepareGameSize(int width, int height) { mRgba15 = new Mat(height, width, CvType.CV_8UC4); mCells15 = new Mat[GRID_AREA]; for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { int k = i * GRID_SIZE + j; mCells15[k] = mRgba15.submat(i * height / GRID_SIZE, (i + 1) * height / GRID_SIZE, j * width / GRID_SIZE, (j + 1) * width / GRID_SIZE); } } for (int i = 0; i < GRID_AREA; i++) { Size s = Core.getTextSize(Integer.toString(i + 1), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null); mTextHeights[i] = (int) s.height; mTextWidths[i] = (int) s.width; } } /* this method to be called from the outside. it processes the frame and shuffles * the tiles as specified by mIndexes array */ public synchronized Mat puzzleFrame(Mat inputPicture) { Mat[] cells = new Mat[GRID_AREA]; int rows = inputPicture.rows(); int cols = inputPicture.cols(); rows = rows - rows%4; cols = cols - cols%4; for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { int k = i * GRID_SIZE + j; cells[k] = inputPicture.submat(i * inputPicture.rows() / GRID_SIZE, (i + 1) * inputPicture.rows() / GRID_SIZE, j * inputPicture.cols()/ GRID_SIZE, (j + 1) * inputPicture.cols() / GRID_SIZE); } } rows = rows - rows%4; cols = cols - cols%4; // copy shuffled tiles for (int i = 0; i < GRID_AREA; i++) { int idx = mIndexes[i]; if (idx == GRID_EMPTY_INDEX) mCells15[i].setTo(GRID_EMPTY_COLOR); else { cells[idx].copyTo(mCells15[i]); if (mShowTileNumbers) { Core.putText(mCells15[i], Integer.toString(1 + idx), new Point((cols / GRID_SIZE - mTextWidths[idx]) / 2, (rows / GRID_SIZE + mTextHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2); } } } for (int i = 0; i < GRID_AREA; i++) cells[i].release(); drawGrid(cols, rows, mRgba15); return mRgba15; } public void toggleTileNumbers() { mShowTileNumbers = !mShowTileNumbers; } public void deliverTouchEvent(int x, int y) { int rows = mRgba15.rows(); int cols = mRgba15.cols(); int row = (int) Math.floor(y * GRID_SIZE / rows); int col = (int) Math.floor(x * GRID_SIZE / cols); if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE) { Log.e(TAG, "It is not expected to get touch event outside of picture"); return ; } int idx = row * GRID_SIZE + col; int idxtoswap = -1; // left if (idxtoswap < 0 && col > 0) if (mIndexes[idx - 1] == GRID_EMPTY_INDEX) idxtoswap = idx - 1; // right if (idxtoswap < 0 && col < GRID_SIZE - 1) if (mIndexes[idx + 1] == GRID_EMPTY_INDEX) idxtoswap = idx + 1; // top if (idxtoswap < 0 && row > 0) if (mIndexes[idx - GRID_SIZE] == GRID_EMPTY_INDEX) idxtoswap = idx - GRID_SIZE; // bottom if (idxtoswap < 0 && row < GRID_SIZE - 1) if (mIndexes[idx + GRID_SIZE] == GRID_EMPTY_INDEX) idxtoswap = idx + GRID_SIZE; // swap if (idxtoswap >= 0) { synchronized (this) { int touched = mIndexes[idx]; mIndexes[idx] = mIndexes[idxtoswap]; mIndexes[idxtoswap] = touched; } } } private void drawGrid(int cols, int rows, Mat drawMat) { for (int i = 1; i < GRID_SIZE; i++) { Core.line(drawMat, new Point(0, i * rows / GRID_SIZE), new Point(cols, i * rows / GRID_SIZE), new Scalar(0, 255, 0, 255), 3); Core.line(drawMat, new Point(i * cols / GRID_SIZE, 0), new Point(i * cols / GRID_SIZE, rows), new Scalar(0, 255, 0, 255), 3); } } private static void shuffle(int[] array) { for (int i = array.length; i > 1; i--) { int temp = array[i - 1]; int randIx = (int) (Math.random() * i); array[i - 1] = array[randIx]; array[randIx] = temp; } } private boolean isPuzzleSolvable() { int sum = 0; for (int i = 0; i < GRID_AREA; i++) { if (mIndexes[i] == GRID_EMPTY_INDEX) sum += (i / GRID_SIZE) + 1; else { int smaller = 0; for (int j = i + 1; j < GRID_AREA; j++) { if (mIndexes[j] < mIndexes[i]) smaller++; } sum += smaller; } } return sum % 2 == 0; } }
0
0.861121
1
0.861121
game-dev
MEDIA
0.372124
game-dev,graphics-rendering
0.985347
1
0.985347
GregTechCEu/GregTech
8,455
src/main/java/gregtech/common/command/CommandHand.java
package gregtech.common.command; import gregtech.api.GregTechAPI; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.IElectricItem; import gregtech.api.items.toolitem.IGTTool; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.ore.OrePrefix; import gregtech.api.unification.stack.MaterialStack; import gregtech.api.util.ClipboardUtil; import gregtech.api.util.GTLog; import gregtech.integration.RecipeCompatUtil; import gregtech.modules.GregTechModules; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.*; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent.Action; import net.minecraft.util.text.event.HoverEvent; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fluids.capability.IFluidTankProperties; import org.jetbrains.annotations.NotNull; import java.util.Set; public class CommandHand extends CommandBase { @NotNull @Override public String getName() { return "hand"; } @NotNull @Override public String getUsage(@NotNull ICommandSender sender) { return "gregtech.command.hand.usage"; } @Override public void execute(@NotNull MinecraftServer server, @NotNull ICommandSender sender, @NotNull String[] args) throws CommandException { if (sender instanceof EntityPlayerMP) { EntityPlayerMP player = (EntityPlayerMP) sender; ItemStack stackInHand = player.getHeldItemMainhand(); if (stackInHand.isEmpty()) { stackInHand = player.getHeldItemOffhand(); if (stackInHand.isEmpty()) { throw new CommandException("gregtech.command.hand.no_item"); } } String registryName; ResourceLocation registryLocation = stackInHand.getItem().getRegistryName(); if (registryLocation != null) { registryName = registryLocation.toString(); } else { registryName = "ERROR"; GTLog.logger.warn("ItemStack {} has a null registry name", stackInHand.getTranslationKey()); } ClickEvent itemNameEvent = new ClickEvent(Action.OPEN_URL, registryName); player.sendMessage(new TextComponentTranslation("gregtech.command.hand.item_id", registryName, stackInHand.getItemDamage()) .setStyle(new Style().setClickEvent(itemNameEvent))); IElectricItem electricItem = stackInHand.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null); IFluidHandlerItem fluidHandlerItem = stackInHand .getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); if (electricItem != null) { player.sendMessage(new TextComponentTranslation("gregtech.command.hand.electric", electricItem.getCharge(), electricItem.getMaxCharge(), electricItem.getTier(), Boolean.toString(electricItem.canProvideChargeExternally()))); } if (fluidHandlerItem != null) { for (IFluidTankProperties properties : fluidHandlerItem.getTankProperties()) { FluidStack contents = properties.getContents(); String fluidName = contents == null ? "empty" : contents.getFluid().getName(); player.sendMessage(new TextComponentTranslation("gregtech.command.hand.fluid", contents == null ? 0 : contents.amount, properties.getCapacity(), Boolean.toString(properties.canFill()), Boolean.toString(properties.canDrain()))); if (contents != null) { player.sendMessage(new TextComponentTranslation("gregtech.command.hand.fluid2", fluidName) .appendSibling(new TextComponentString(" " + fluidName) .setStyle(new Style().setColor(TextFormatting.GREEN))) .setStyle(getCopyStyle("<liquid:" + fluidName + ">", false))); } } } String id = RecipeCompatUtil.getMetaItemId(stackInHand); if (id != null) { String ctId = "<metaitem:" + id + ">"; ClipboardUtil.copyToClipboard(player, ctId); player.sendMessage(new TextComponentTranslation("gregtech.command.hand.meta_item", id) .appendSibling( new TextComponentString(" " + id).setStyle(new Style().setColor(TextFormatting.GREEN))) .setStyle(getCopyStyle(ctId, true))); } // tool info if (stackInHand.getItem() instanceof IGTTool) { IGTTool tool = (IGTTool) stackInHand.getItem(); player.sendMessage(new TextComponentTranslation("gregtech.command.hand.tool_stats", tool.getToolClasses(stackInHand))); } // material info MaterialStack material = OreDictUnifier.getMaterial(stackInHand); if (material != null) { player.sendMessage(new TextComponentTranslation("gregtech.command.hand.material") .appendSibling(new TextComponentString(" " + material.material) .setStyle(new Style().setColor(TextFormatting.GREEN))) .setStyle(getCopyStyle("<material:" + material.material + ">", false))); } // ore prefix info OrePrefix orePrefix = OreDictUnifier.getPrefix(stackInHand); if (orePrefix != null) { player.sendMessage(new TextComponentTranslation("gregtech.command.hand.ore_prefix") .appendSibling(new TextComponentString(" " + orePrefix.name) .setStyle(new Style().setColor(TextFormatting.GREEN))) .setStyle(getCopyStyle(orePrefix.name, false))); } Set<String> oreDicts = OreDictUnifier.getOreDictionaryNames(stackInHand); if (!oreDicts.isEmpty()) { sender.sendMessage(new TextComponentTranslation("gregtech.command.hand.ore_dict_entries")); for (String oreName : oreDicts) { player.sendMessage(new TextComponentString(" \u00A7e- \u00A7b" + oreName) .setStyle(getCopyStyle("<ore:" + oreName + ">", false))); } } if (GregTechAPI.moduleManager.isModuleEnabled(GregTechModules.MODULE_GRS)) { sender.sendMessage(new TextComponentTranslation("gregtech.command.hand.groovy")); } } else { throw new CommandException("gregtech.command.hand.not_a_player"); } } public static Style getCopyStyle(String copyMessage, boolean alreadyCopied) { Style style = new Style(); ClickEvent click = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/gt copy " + copyMessage); style.setClickEvent(click); ITextComponent text = alreadyCopied ? new TextComponentString("") .appendSibling(new TextComponentString(copyMessage + " ") .setStyle(new Style().setColor(TextFormatting.GOLD))) .appendSibling(new TextComponentTranslation("gregtech.command.copy.copied_and_click")) : new TextComponentTranslation("gregtech.command.copy.click_to_copy") .appendSibling(new TextComponentString(" " + copyMessage) .setStyle(new Style().setColor(TextFormatting.GOLD))); style.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, text)); return style; } }
0
0.913865
1
0.913865
game-dev
MEDIA
0.969751
game-dev
0.982398
1
0.982398
mohsenheydari/three-fps
5,573
src/entities/NPC/CharacterFSM.js
import {FiniteStateMachine, State} from '../../FiniteStateMachine' import * as THREE from 'three' export default class CharacterFSM extends FiniteStateMachine{ constructor(proxy){ super(); this.proxy = proxy; this.Init(); } Init(){ this.AddState('idle', new IdleState(this)); this.AddState('patrol', new PatrolState(this)); this.AddState('chase', new ChaseState(this)); this.AddState('attack', new AttackState(this)); this.AddState('dead', new DeadState(this)); } } class IdleState extends State{ constructor(parent){ super(parent); this.maxWaitTime = 5.0; this.minWaitTime = 1.0; this.waitTime = 0.0; } get Name(){return 'idle'} get Animation(){return this.parent.proxy.animations['idle']; } Enter(prevState){ this.parent.proxy.canMove = false; const action = this.Animation.action; if(prevState){ action.time = 0.0; action.enabled = true; action.crossFadeFrom(prevState.Animation.action, 0.5, true); } action.play(); this.waitTime = Math.random() * (this.maxWaitTime - this.minWaitTime) + this.minWaitTime; } Update(t){ if(this.waitTime <= 0.0){ this.parent.SetState('patrol'); return; } this.waitTime -= t; if(this.parent.proxy.CanSeeThePlayer()){ this.parent.SetState('chase'); } } } class PatrolState extends State{ constructor(parent){ super(parent); } get Name(){return 'patrol'} get Animation(){return this.parent.proxy.animations['walk']; } PatrolEnd = ()=>{ this.parent.SetState('idle'); } Enter(prevState){ this.parent.proxy.canMove = true; const action = this.Animation.action; if(prevState){ action.time = 0.0; action.enabled = true; action.crossFadeFrom(prevState.Animation.action, 0.5, true); } action.play(); this.parent.proxy.NavigateToRandomPoint(); } Update(t){ if(this.parent.proxy.CanSeeThePlayer()){ this.parent.SetState('chase'); }else if(this.parent.proxy.path && this.parent.proxy.path.length == 0){ this.parent.SetState('idle'); } } } class ChaseState extends State{ constructor(parent){ super(parent); this.updateFrequency = 0.5; this.updateTimer = 0.0; this.attackDistance = 2.0; this.shouldRotate = false; this.switchDelay = 0.2; } get Name(){return 'chase'} get Animation(){return this.parent.proxy.animations['run']; } RunToPlayer(prevState){ this.parent.proxy.canMove = true; const action = this.Animation.action; this.updateTimer = 0.0; if(prevState){ action.time = 0.0; action.enabled = true; action.setEffectiveTimeScale(1.0); action.setEffectiveWeight(1.0); action.crossFadeFrom(prevState.Animation.action, 0.2, true); } action.timeScale = 1.5; action.play(); } Enter(prevState){ this.RunToPlayer(prevState); } Update(t){ if(this.updateTimer <= 0.0){ this.parent.proxy.NavigateToPlayer(); this.updateTimer = this.updateFrequency; } if(this.parent.proxy.IsCloseToPlayer){ if(this.switchDelay <= 0.0){ this.parent.SetState('attack'); } this.parent.proxy.ClearPath(); this.switchDelay -= t; }else{ this.switchDelay = 0.1; } this.updateTimer -= t; } } class AttackState extends State{ constructor(parent){ super(parent); this.attackTime = 0.0; this.canHit = true; } get Name(){return 'attack'} get Animation(){return this.parent.proxy.animations['attack']; } Enter(prevState){ this.parent.proxy.canMove = false; const action = this.Animation.action; this.attackTime = this.Animation.clip.duration; this.attackEvent = this.attackTime * 0.85; if(prevState){ action.time = 0.0; action.enabled = true; action.crossFadeFrom(prevState.Animation.action, 0.1, true); } action.play(); } Update(t){ this.parent.proxy.FacePlayer(t); if(!this.parent.proxy.IsCloseToPlayer && this.attackTime <= 0.0){ this.parent.SetState('chase'); return; } if(this.canHit && this.attackTime <= this.attackEvent && this.parent.proxy.IsPlayerInHitbox){ this.parent.proxy.HitPlayer(); this.canHit = false; } if(this.attackTime <= 0.0){ this.attackTime = this.Animation.clip.duration; this.canHit = true; } this.attackTime -= t; } } class DeadState extends State{ constructor(parent){ super(parent); } get Name(){return 'dead'} get Animation(){return this.parent.proxy.animations['die']; } Enter(prevState){ const action = this.Animation.action; action.setLoop(THREE.LoopOnce, 1); action.clampWhenFinished = true; if(prevState){ action.time = 0.0; action.enabled = true; action.crossFadeFrom(prevState.Animation.action, 0.1, true); } action.play(); } Update(t){} }
0
0.961637
1
0.961637
game-dev
MEDIA
0.971625
game-dev
0.996368
1
0.996368
LPGhatguy/lemur
1,046
lib/instances/ContextActionService.lua
local BaseInstance = import("./BaseInstance") local validateType = import("../validateType") local ContextActionService = BaseInstance:extend("ContextActionService") --[[ These action binding and unbinding functions mimic Roblox's validation of arguments, but are a little stricter about type expectations: * Roblox only throws errors on the 'actionName' parameter if it can't cast it to a string Additionally, Roblox does not throw error in either of these cases: * Binding a different action to the same name (overwrites existing action) * Unbinding actions that were never bound does not error ]] function ContextActionService.prototype:BindCoreAction(actionName, functionToBind, createTouchButton, ...) validateType("actionName", actionName, "string") validateType("functionToBind", functionToBind, "function") validateType("createTouchButton", createTouchButton, "boolean") end function ContextActionService.prototype:UnbindCoreAction(actionName) validateType("actionName", actionName, "string") end return ContextActionService
0
0.691169
1
0.691169
game-dev
MEDIA
0.474329
game-dev
0.59042
1
0.59042
Dark-Basic-Software-Limited/GameGuruRepo
5,991
GameGuru Core/SDK/BULLET/bullet-2.81-rev2613/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.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 <stdio.h> #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/CollisionShapes/btTriangleShape.h" #include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" #include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h" #include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include "btRaycastCallback.h" btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const btVector3& to, unsigned int flags) : m_from(from), m_to(to), //@BP Mod m_flags(flags), m_hitFraction(btScalar(1.)) { } void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, int triangleIndex) { const btVector3 &vert0=triangle[0]; const btVector3 &vert1=triangle[1]; const btVector3 &vert2=triangle[2]; btVector3 v10; v10 = vert1 - vert0 ; btVector3 v20; v20 = vert2 - vert0 ; btVector3 triangleNormal; triangleNormal = v10.cross( v20 ); const btScalar dist = vert0.dot(triangleNormal); btScalar dist_a = triangleNormal.dot(m_from) ; dist_a-= dist; btScalar dist_b = triangleNormal.dot(m_to); dist_b -= dist; if ( dist_a * dist_b >= btScalar(0.0) ) { return ; // same sign } if (((m_flags & kF_FilterBackfaces) != 0) && (dist_a <= btScalar(0.0))) { // Backface, skip check return; } const btScalar proj_length=dist_a-dist_b; const btScalar distance = (dist_a)/(proj_length); // Now we have the intersection point on the plane, we'll see if it's inside the triangle // Add an epsilon as a tolerance for the raycast, // in case the ray hits exacly on the edge of the triangle. // It must be scaled for the triangle size. if(distance < m_hitFraction) { btScalar edge_tolerance =triangleNormal.length2(); edge_tolerance *= btScalar(-0.0001); btVector3 point; point.setInterpolate3( m_from, m_to, distance); { btVector3 v0p; v0p = vert0 - point; btVector3 v1p; v1p = vert1 - point; btVector3 cp0; cp0 = v0p.cross( v1p ); if ( (btScalar)(cp0.dot(triangleNormal)) >=edge_tolerance) { btVector3 v2p; v2p = vert2 - point; btVector3 cp1; cp1 = v1p.cross( v2p); if ( (btScalar)(cp1.dot(triangleNormal)) >=edge_tolerance) { btVector3 cp2; cp2 = v2p.cross(v0p); if ( (btScalar)(cp2.dot(triangleNormal)) >=edge_tolerance) { //@BP Mod // Triangle normal isn't normalized triangleNormal.normalize(); //@BP Mod - Allow for unflipped normal when raycasting against backfaces if (((m_flags & kF_KeepUnflippedNormal) == 0) && (dist_a <= btScalar(0.0))) { m_hitFraction = reportHit(-triangleNormal,distance,partId,triangleIndex); } else { m_hitFraction = reportHit(triangleNormal,distance,partId,triangleIndex); } } } } } } } btTriangleConvexcastCallback::btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin) { m_convexShape = convexShape; m_convexShapeFrom = convexShapeFrom; m_convexShapeTo = convexShapeTo; m_triangleToWorld = triangleToWorld; m_hitFraction = 1.0f; m_triangleCollisionMargin = triangleCollisionMargin; m_allowedPenetration = 0.f; } void btTriangleConvexcastCallback::processTriangle (btVector3* triangle, int partId, int triangleIndex) { btTriangleShape triangleShape (triangle[0], triangle[1], triangle[2]); triangleShape.setMargin(m_triangleCollisionMargin); btVoronoiSimplexSolver simplexSolver; btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver; //#define USE_SUBSIMPLEX_CONVEX_CAST 1 //if you reenable USE_SUBSIMPLEX_CONVEX_CAST see commented out code below #ifdef USE_SUBSIMPLEX_CONVEX_CAST btSubsimplexConvexCast convexCaster(m_convexShape, &triangleShape, &simplexSolver); #else //btGjkConvexCast convexCaster(m_convexShape,&triangleShape,&simplexSolver); btContinuousConvexCollision convexCaster(m_convexShape,&triangleShape,&simplexSolver,&gjkEpaPenetrationSolver); #endif //#USE_SUBSIMPLEX_CONVEX_CAST btConvexCast::CastResult castResult; castResult.m_fraction = btScalar(1.); castResult.m_allowedPenetration = m_allowedPenetration; if (convexCaster.calcTimeOfImpact(m_convexShapeFrom,m_convexShapeTo,m_triangleToWorld, m_triangleToWorld, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < m_hitFraction) { /* btContinuousConvexCast's normal is already in world space */ /* #ifdef USE_SUBSIMPLEX_CONVEX_CAST //rotate normal into worldspace castResult.m_normal = m_convexShapeFrom.getBasis() * castResult.m_normal; #endif //USE_SUBSIMPLEX_CONVEX_CAST */ castResult.m_normal.normalize(); reportHit (castResult.m_normal, castResult.m_hitPoint, castResult.m_fraction, partId, triangleIndex); } } } }
0
0.969464
1
0.969464
game-dev
MEDIA
0.98402
game-dev
0.996157
1
0.996157
FrederoxDev/Amethyst
3,014
AmethystAPI/src/mc/src/common/world/actor/Actor.cpp
#include <amethyst/Memory.hpp> #include "mc/src/common/world/actor/Actor.hpp" #include "mc/src/common/world/level/dimension/Dimension.hpp" #include "mc/src/common/world/entity/components/ActorHeadRotationComponent.hpp" #include "mc/src/common/world/entity/components/ActorRotationComponent.hpp" #include "mc/src/common/world/entity/components/StateVectorComponent.hpp" #include "mc/src/common/world/entity/components/ActorGameTypeComponent.hpp" #include "mc/src/common/world/entity/components/ActorUniqueIDComponent.hpp" Vec3* Actor::getPosition() const { return &mBuiltInComponents.mStateVectorComponent->mPos; } Vec2* Actor::getHeadRot() const { return &mBuiltInComponents.mActorRotationComponent->mHeadRot; } void Actor::moveTo(const Vec3& a1, const Vec2& a2) { using function = decltype(&Actor::moveTo); static auto func = std::bit_cast<function>(SigScan("48 89 74 24 ? 48 89 7C 24 ? 41 56 48 83 EC ? 4C 8B B1 ? ? ? ? 48 8B FA")); return (this->*func)(a1, a2); } float Actor::distanceTo(const Vec3& other) const { return other.distance(*getPosition()); } const Dimension& Actor::getDimensionConst() const { return *mDimension.lock(); } const BlockSource& Actor::getDimensionBlockSourceConst() const { return *getDimensionConst().mBlockSource.get(); } BlockSource& Actor::getDimensionBlockSource() const { return *getDimensionConst().mBlockSource.get(); } bool Actor::hasDimension() const { return mDimension.lock() != nullptr; } void Actor::setDimension(WeakRef<Dimension> dimension) { using function = decltype(&Actor::setDimension); static auto func = std::bit_cast<function>(SigScan("48 89 5C 24 ? 55 56 57 48 83 EC ? 48 8B 05 ? ? ? ? 48 33 C4 48 89 44 24 ? 48 8B FA 48 8B E9 48 89 54 24 ? 0F 57 C9")); return (this->*func)(dimension); } //int Actor::load(const CompoundTag& actorData, DefaultDataLoadHelper& dataLoadHelper) //{ // using function = decltype(&Actor::load); // static auto func = std::bit_cast<function>(this->vtable[88]); // return (this->*func)(actorData, dataLoadHelper); //} void Actor::reload() { using function = decltype(&Actor::reload); static auto func = std::bit_cast<function>(SigScan("48 89 5C 24 ? 48 89 74 24 ? 55 57 41 54 41 56 41 57 48 8B EC 48 83 EC ? 48 8B 05 ? ? ? ? 48 33 C4 48 89 45 ? 48 8B F1 45 33 E4")); return (this->*func)(); } bool Actor::isClientSide() const { return mLevel->isClientSide(); } bool Actor::isCreative() const { const ActorGameTypeComponent* gameTypeComp = tryGetComponent<ActorGameTypeComponent>(); GameType ownType = gameTypeComp->mGameType; if (ownType == (GameType)-1) return false; GameType defaultType = mLevel->getDefaultGameType(); //return PlayerGameTypeUtility::isCreative(UnmappedGameType, v3); return ownType == GameType::Creative || (ownType == GameType::Default && defaultType == GameType::Creative); } ActorUniqueID Actor::getUniqueID() const { return tryGetComponent<ActorUniqueIDComponent>()->mActorUniqueID; }
0
0.703395
1
0.703395
game-dev
MEDIA
0.927419
game-dev
0.877269
1
0.877269
stijnwop/guidanceSteering
1,716
src/events/GuidanceStrategyChangedEvent.lua
-- -- GuidanceStrategyChangedEvent -- -- Guidance strategy event to sync guidance data with server. -- -- Copyright (c) Wopster, 2019 GuidanceStrategyChangedEvent = {} local GuidanceStrategyChangedEvent_mt = Class(GuidanceStrategyChangedEvent, Event) InitEventClass(GuidanceStrategyChangedEvent, "GuidanceStrategyChangedEvent") function GuidanceStrategyChangedEvent:emptyNew() local self = Event.new(GuidanceStrategyChangedEvent_mt) return self end function GuidanceStrategyChangedEvent:new(vehicle, method) local self = GuidanceStrategyChangedEvent:emptyNew() self.vehicle = vehicle self.method = method return self end function GuidanceStrategyChangedEvent:writeStream(streamId, connection) NetworkUtil.writeNodeObject(streamId, self.vehicle) streamWriteInt8(streamId, self.method + 1) end function GuidanceStrategyChangedEvent:readStream(streamId, connection) self.vehicle = NetworkUtil.readNodeObject(streamId) self.method = streamReadInt8(streamId) - 1 self:run(connection) end function GuidanceStrategyChangedEvent:run(connection) self.vehicle:setGuidanceStrategy(self.method, true) -- Send from server to all clients if not connection:getIsServer() then g_server:broadcastEvent(self, false, connection, self.vehicle) end end function GuidanceStrategyChangedEvent.sendEvent(object, method, noEventSend) if noEventSend == nil or not noEventSend then if g_server ~= nil then g_server:broadcastEvent(GuidanceStrategyChangedEvent:new(object, method), nil, nil, object) else g_client:getServerConnection():sendEvent(GuidanceStrategyChangedEvent:new(object, method)) end end end
0
0.778582
1
0.778582
game-dev
MEDIA
0.30093
game-dev
0.720053
1
0.720053
McJtyMods/RFTools
25,517
src/main/java/mcjty/rftools/blocks/spawner/SpawnerConfiguration.java
package mcjty.rftools.blocks.spawner; import mcjty.lib.varia.EntityTools; import mcjty.lib.varia.Logging; import net.minecraft.block.Block; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.monster.*; import net.minecraft.entity.passive.*; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SpawnerConfiguration { public static final String CATEGORY_SPAWNER = "spawner"; public static final String CATEGORY_MOBSPAWNAMOUNTS = "mobspawnamounts"; public static final String CATEGORY_MOBSPAWNRF = "mobspawnrf"; public static final String CATEGORY_LIVINGMATTER = "livingmatter"; public static final Map<String,Integer> mobSpawnRf = new HashMap<>(); public static int defaultMobSpawnRf; public static final Map<String,List<MobSpawnAmount>> mobSpawnAmounts = new HashMap<>(); public static final List<MobSpawnAmount> defaultSpawnAmounts = new ArrayList<>(); public static final Map<ResourceLocation,Float> livingMatter = new HashMap<>(); public static final int MATERIALTYPE_KEY = 0; public static final int MATERIALTYPE_BULK = 1; public static final int MATERIALTYPE_LIVING = 2; public static int SPAWNER_MAXENERGY = 200000; public static int SPAWNER_RECEIVEPERTICK = 2000; public static int BEAMER_MAXENERGY = 200000; public static int BEAMER_RECEIVEPERTICK = 1000; public static int beamRfPerObject = 2000; public static int beamBlocksPerSend = 1; public static int maxBeamDistance = 8; public static int maxMatterStorage = 64 * 100; // public static int maxEntitiesAroundSpawner = 300; public static void init(Configuration cfg) { cfg.addCustomCategoryComment(SpawnerConfiguration.CATEGORY_SPAWNER, "Settings for the spawner system"); cfg.addCustomCategoryComment(SpawnerConfiguration.CATEGORY_MOBSPAWNAMOUNTS, "Amount of materials needed to spawn mobs"); cfg.addCustomCategoryComment(SpawnerConfiguration.CATEGORY_MOBSPAWNRF, "Amount of RF needed to spawn mobs"); cfg.addCustomCategoryComment(SpawnerConfiguration.CATEGORY_LIVINGMATTER, "Blocks and items that are seen as living for the spawner"); SPAWNER_MAXENERGY = cfg.get(CATEGORY_SPAWNER, "spawnerMaxRF", SPAWNER_MAXENERGY, "Maximum RF storage that the spawner can hold").getInt(); SPAWNER_RECEIVEPERTICK = cfg.get(CATEGORY_SPAWNER, "spawnerRFPerTick", SPAWNER_RECEIVEPERTICK, "RF per tick that the spawner can receive").getInt(); BEAMER_MAXENERGY = cfg.get(CATEGORY_SPAWNER, "beamerMaxRF", BEAMER_MAXENERGY, "Maximum RF storage that the matter beamer can hold").getInt(); BEAMER_RECEIVEPERTICK = cfg.get(CATEGORY_SPAWNER, "beamerRFPerTick", BEAMER_RECEIVEPERTICK, "RF per tick that the matter beamer can receive").getInt(); beamRfPerObject = cfg.get(CATEGORY_SPAWNER, "beamerRfPerSend", beamRfPerObject, "RF per tick that the matter beamer will use for sending over a single object").getInt(); beamBlocksPerSend = cfg.get(CATEGORY_SPAWNER, "beamerBlocksPerSend", beamBlocksPerSend, "The amount of blocks that the matter beamer will use send in one operation (every 20 ticks)").getInt(); maxMatterStorage = cfg.get(CATEGORY_SPAWNER, "spawnerMaxMatterStorage", maxMatterStorage, "The maximum amount of energized matter that this spawner can store (per type)").getInt(); maxBeamDistance = cfg.get(CATEGORY_SPAWNER, "maxBeamDistance", maxBeamDistance, "The maximum distance that a laser can travel between the beamer and the spawner").getInt(); // maxEntitiesAroundSpawner = cfg.get(CATEGORY_SPAWNER, "maxEntitiesAroundSpawner", maxEntitiesAroundSpawner, // "If the number of entities around the spawner exceeds this number it will automatically stop spawning").getInt(); readLivingConfig(cfg); defaultMobSpawnRf = 10000; defaultSpawnAmounts.add(new MobSpawnAmount(new ItemStack(Items.DIAMOND), 1.0f)); defaultSpawnAmounts.add(new MobSpawnAmount(new ItemStack(Blocks.DIRT), 20)); defaultSpawnAmounts.add(new MobSpawnAmount(ItemStack.EMPTY, 120.0f)); if (cfg.getCategory(CATEGORY_MOBSPAWNAMOUNTS).isEmpty()) { setupInitialMobSpawnConfig(cfg); } } private static void readLivingConfig(Configuration cfg) { ConfigCategory category = cfg.getCategory(CATEGORY_LIVINGMATTER); if (category.isEmpty()) { setupInitialLivingConfig(cfg); } for (Map.Entry<String, Property> entry : category.entrySet()) { String[] value = entry.getValue().getStringList(); try { // value[0] is type and is no longer used String name = value[1]; Float factor = Float.parseFloat(value[2]); livingMatter.put(new ResourceLocation(name), factor); } catch (Exception e) { Logging.logError("Badly formatted 'livingmatter' configuration option!"); return; } } } private static void setupInitialLivingConfig(Configuration cfg) { int counter = 0; counter = addLiving(cfg, Blocks.LEAVES, counter, 0.5f); counter = addLiving(cfg, Blocks.LEAVES2, counter, 0.5f); counter = addLiving(cfg, Blocks.SAPLING, counter, 0.5f); counter = addLiving(cfg, Blocks.HAY_BLOCK, counter, 1.5f); counter = addLiving(cfg, Blocks.MELON_BLOCK, counter, 1.0f); counter = addLiving(cfg, Blocks.CACTUS, counter, 0.4f); counter = addLiving(cfg, Blocks.RED_FLOWER, counter, 0.3f); counter = addLiving(cfg, Blocks.YELLOW_FLOWER, counter, 0.3f); counter = addLiving(cfg, Blocks.CHORUS_FLOWER, counter, 1.1f); counter = addLiving(cfg, Blocks.BROWN_MUSHROOM, counter, 0.4f); counter = addLiving(cfg, Blocks.RED_MUSHROOM, counter, 0.4f); counter = addLiving(cfg, Blocks.PUMPKIN, counter, 0.9f); counter = addLiving(cfg, Blocks.VINE, counter, 0.4f); counter = addLiving(cfg, Blocks.WATERLILY, counter, 0.4f); counter = addLiving(cfg, Blocks.COCOA, counter, 0.8f); counter = addLiving(cfg, Items.APPLE, counter, 1.0f); counter = addLiving(cfg, Items.WHEAT, counter, 1.1f); counter = addLiving(cfg, Items.WHEAT_SEEDS, counter, 0.4f); counter = addLiving(cfg, Items.POTATO, counter, 1.5f); counter = addLiving(cfg, Items.CARROT, counter, 1.5f); counter = addLiving(cfg, Items.PUMPKIN_SEEDS, counter, 0.4f); counter = addLiving(cfg, Items.MELON_SEEDS, counter, 0.4f); counter = addLiving(cfg, Items.BEEF, counter, 1.5f); counter = addLiving(cfg, Items.PORKCHOP, counter, 1.5f); counter = addLiving(cfg, Items.MUTTON, counter, 1.5f); counter = addLiving(cfg, Items.CHICKEN, counter, 1.5f); counter = addLiving(cfg, Items.RABBIT, counter, 1.2f); counter = addLiving(cfg, Items.RABBIT_FOOT, counter, 1.0f); counter = addLiving(cfg, Items.RABBIT_HIDE, counter, 0.5f); counter = addLiving(cfg, Items.BEETROOT, counter, 0.8f); counter = addLiving(cfg, Items.BEETROOT_SEEDS, counter, 0.4f); counter = addLiving(cfg, Items.CHORUS_FRUIT, counter, 1.5f); counter = addLiving(cfg, Items.FISH, counter, 1.5f); counter = addLiving(cfg, Items.REEDS, counter, 1f); } private static int addLiving(Configuration cfg, Block block, int counter, float factor) { cfg.get(CATEGORY_LIVINGMATTER, "living." + counter, new String[] { "B", block.getRegistryName().toString(), Float.toString(factor) }); return counter+1; } private static int addLiving(Configuration cfg, Item item, int counter, float factor) { cfg.get(CATEGORY_LIVINGMATTER, "living." + counter, new String[] { "I", item.getRegistryName().toString(), Float.toString(factor) }); return counter+1; } public static void readMobSpawnAmountConfig(Configuration cfg) { ConfigCategory category = cfg.getCategory(CATEGORY_MOBSPAWNAMOUNTS); for (Map.Entry<String, Property> entry : category.entrySet()) { String key = entry.getKey(); String[] splitted = entry.getValue().getStringList(); int materialType; if (key.endsWith(".spawnamount.0")) { materialType = MATERIALTYPE_KEY; } else if (key.endsWith(".spawnamount.1")) { materialType = MATERIALTYPE_BULK; } else { materialType = MATERIALTYPE_LIVING; } String id = key.substring(0, key.indexOf(".spawnamount")); setSpawnAmounts(id, materialType, splitted); } category = cfg.getCategory(CATEGORY_MOBSPAWNRF); for (Map.Entry<String, Property> entry : category.entrySet()) { String key = entry.getKey(); int rf = entry.getValue().getInt(); mobSpawnRf.put(key, rf); } } private static void setupInitialMobSpawnConfig(Configuration cfg) { addMobSpawnRF(cfg, EntityBat.class, 100); addMobSpawnAmount(cfg, EntityBat.class, MATERIALTYPE_KEY, Items.FEATHER, 0, .1f); addMobSpawnAmount(cfg, EntityBat.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityBat.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntityBlaze.class, 1000); addMobSpawnAmount(cfg, EntityBlaze.class, MATERIALTYPE_KEY, Items.BLAZE_ROD, 0, 0.1f); addMobSpawnAmount(cfg, EntityBlaze.class, MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .5f); addMobSpawnAmount(cfg, EntityBlaze.class, MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, EntityCaveSpider.class, 500); addMobSpawnAmount(cfg, EntityCaveSpider.class, MATERIALTYPE_KEY, Items.STRING, 0, 0.1f); addMobSpawnAmount(cfg, EntityCaveSpider.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityCaveSpider.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntityChicken.class, 500); addMobSpawnAmount(cfg, EntityChicken.class, MATERIALTYPE_KEY, Items.FEATHER, 0, 0.1f); addMobSpawnAmount(cfg, EntityChicken.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityChicken.class, MATERIALTYPE_LIVING, null, 0, 15); addMobSpawnRF(cfg, EntityCow.class, 800); addMobSpawnAmount(cfg, EntityCow.class, MATERIALTYPE_KEY, Items.LEATHER, 0, 0.1f); addMobSpawnAmount(cfg, EntityCow.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityCow.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityCreeper.class, 800); addMobSpawnAmount(cfg, EntityCreeper.class, MATERIALTYPE_KEY, Items.GUNPOWDER, 0, 0.1f); addMobSpawnAmount(cfg, EntityCreeper.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .5f); addMobSpawnAmount(cfg, EntityCreeper.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityDragon.class, 100000); addMobSpawnAmount(cfg, EntityDragon.class, MATERIALTYPE_KEY, Items.EXPERIENCE_BOTTLE, 0, 0.1f); addMobSpawnAmount(cfg, EntityDragon.class, MATERIALTYPE_BULK, Blocks.END_STONE, 0, 100); addMobSpawnAmount(cfg, EntityDragon.class, MATERIALTYPE_LIVING, null, 0, 200); addMobSpawnRF(cfg, EntityEnderman.class, 2000); addMobSpawnAmount(cfg, EntityEnderman.class, MATERIALTYPE_KEY, Items.ENDER_PEARL, 0, 0.1f); addMobSpawnAmount(cfg, EntityEnderman.class, MATERIALTYPE_BULK, Blocks.END_STONE, 0, .5f); addMobSpawnAmount(cfg, EntityEnderman.class, MATERIALTYPE_LIVING, null, 0, 40); addMobSpawnRF(cfg, EntityGhast.class, 2000); addMobSpawnAmount(cfg, EntityGhast.class, MATERIALTYPE_KEY, Items.GHAST_TEAR, 0, 0.1f); addMobSpawnAmount(cfg, EntityGhast.class, MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, 1.0f); addMobSpawnAmount(cfg, EntityGhast.class, MATERIALTYPE_LIVING, null, 0, 50); addMobSpawnRF(cfg, EntityHorse.class, 1000); addMobSpawnAmount(cfg, EntityHorse.class, MATERIALTYPE_KEY, Items.LEATHER, 0, 0.1f); addMobSpawnAmount(cfg, EntityHorse.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .5f); addMobSpawnAmount(cfg, EntityHorse.class, MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, EntityIronGolem.class, 2000); addMobSpawnAmount(cfg, EntityIronGolem.class, MATERIALTYPE_KEY, Items.IRON_INGOT, 0, 0.1f); addMobSpawnAmount(cfg, EntityIronGolem.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, 6.0f); addMobSpawnAmount(cfg, EntityIronGolem.class, MATERIALTYPE_LIVING, Blocks.RED_FLOWER, 0, 0.5f); addMobSpawnRF(cfg, EntityMagmaCube.class, 600); addMobSpawnAmount(cfg, EntityMagmaCube.class, MATERIALTYPE_KEY, Items.MAGMA_CREAM, 0, 0.1f); addMobSpawnAmount(cfg, EntityMagmaCube.class, MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .2f); addMobSpawnAmount(cfg, EntityMagmaCube.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntityMooshroom.class, 800); addMobSpawnAmount(cfg, EntityMooshroom.class, MATERIALTYPE_KEY, Items.LEATHER, 0, 0.1f); addMobSpawnAmount(cfg, EntityMooshroom.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, 1.0f); addMobSpawnAmount(cfg, EntityMooshroom.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityOcelot.class, 800); addMobSpawnAmount(cfg, EntityOcelot.class, MATERIALTYPE_KEY, Items.FISH, 0, 0.1f); addMobSpawnAmount(cfg, EntityOcelot.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, 1.0f); addMobSpawnAmount(cfg, EntityOcelot.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityPig.class, 800); addMobSpawnAmount(cfg, EntityPig.class, MATERIALTYPE_KEY, Items.LEATHER, 0, 0.1f); addMobSpawnAmount(cfg, EntityPig.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityPig.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntitySheep.class, 800); addMobSpawnAmount(cfg, EntitySheep.class, MATERIALTYPE_KEY, Blocks.WOOL, 0, 0.1f); addMobSpawnAmount(cfg, EntitySheep.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntitySheep.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntitySkeleton.class, 800); addMobSpawnAmount(cfg, EntitySkeleton.class, MATERIALTYPE_KEY, Items.BONE, 0, 0.1f); addMobSpawnAmount(cfg, EntitySkeleton.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .5f); addMobSpawnAmount(cfg, EntitySkeleton.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntitySlime.class, 600); addMobSpawnAmount(cfg, EntitySlime.class, MATERIALTYPE_KEY, Items.SLIME_BALL, 0, 0.1f); addMobSpawnAmount(cfg, EntitySlime.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .5f); addMobSpawnAmount(cfg, EntitySlime.class, MATERIALTYPE_LIVING, null, 0, 15); addMobSpawnRF(cfg, EntitySnowman.class, 600); addMobSpawnAmount(cfg, EntitySnowman.class, MATERIALTYPE_KEY, Items.SNOWBALL, 0, 0.1f); addMobSpawnAmount(cfg, EntitySnowman.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, 1.0f); addMobSpawnAmount(cfg, EntitySnowman.class, MATERIALTYPE_LIVING, null, 0, 15); addMobSpawnRF(cfg, EntitySpider.class, 500); addMobSpawnAmount(cfg, EntitySpider.class, MATERIALTYPE_KEY, Items.STRING, 0, 0.1f); addMobSpawnAmount(cfg, EntitySpider.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntitySpider.class, MATERIALTYPE_LIVING, null, 0, 15); addMobSpawnRF(cfg, EntitySquid.class, 500); addMobSpawnAmount(cfg, EntitySquid.class, MATERIALTYPE_KEY, Items.DYE, 0, 0.1f); // Ink sac addMobSpawnAmount(cfg, EntitySquid.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .5f); addMobSpawnAmount(cfg, EntitySquid.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntityVillager.class, 2000); addMobSpawnAmount(cfg, EntityVillager.class, MATERIALTYPE_KEY, Items.BOOK, 0, 0.1f); addMobSpawnAmount(cfg, EntityVillager.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, 5.0f); addMobSpawnAmount(cfg, EntityVillager.class, MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, EntityWitch.class, 1200); addMobSpawnAmount(cfg, EntityWitch.class, MATERIALTYPE_KEY, Items.GLASS_BOTTLE, 0, 0.1f); addMobSpawnAmount(cfg, EntityWitch.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, 1.0f); addMobSpawnAmount(cfg, EntityWitch.class, MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, EntityWither.class, 20000); addMobSpawnAmount(cfg, EntityWither.class, MATERIALTYPE_KEY, Items.NETHER_STAR, 0, 0.1f); addMobSpawnAmount(cfg, EntityWither.class, MATERIALTYPE_BULK, Blocks.SOUL_SAND, 0, 0.5f); addMobSpawnAmount(cfg, EntityWither.class, MATERIALTYPE_LIVING, null, 0, 100); addMobSpawnRF(cfg, EntityWolf.class, 800); addMobSpawnAmount(cfg, EntityWolf.class, MATERIALTYPE_KEY, Items.BONE, 0, 0.1f); addMobSpawnAmount(cfg, EntityWolf.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .5f); addMobSpawnAmount(cfg, EntityWolf.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityPigZombie.class, 1200); addMobSpawnAmount(cfg, EntityPigZombie.class, MATERIALTYPE_KEY, Items.GOLD_NUGGET, 0, 0.1f); addMobSpawnAmount(cfg, EntityPigZombie.class, MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .5f); addMobSpawnAmount(cfg, EntityPigZombie.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityZombie.class, 800); addMobSpawnAmount(cfg, EntityZombie.class, MATERIALTYPE_KEY, Items.ROTTEN_FLESH, 0, 0.1f); addMobSpawnAmount(cfg, EntityZombie.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityZombie.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityGuardian.class, 1000); addMobSpawnAmount(cfg, EntityGuardian.class, MATERIALTYPE_KEY, Items.PRISMARINE_SHARD, 0, 0.1f); addMobSpawnAmount(cfg, EntityGuardian.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityGuardian.class, MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, EntityShulker.class, 600); addMobSpawnAmount(cfg, EntityShulker.class, MATERIALTYPE_KEY, Items.ENDER_PEARL, 0, 0.1f); addMobSpawnAmount(cfg, EntityShulker.class, MATERIALTYPE_BULK, Blocks.END_STONE, 0, .2f); addMobSpawnAmount(cfg, EntityShulker.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, EntityEndermite.class, 400); addMobSpawnAmount(cfg, EntityEndermite.class, MATERIALTYPE_KEY, Items.ENDER_PEARL, 0, 0.05f); addMobSpawnAmount(cfg, EntityEndermite.class, MATERIALTYPE_BULK, Blocks.END_STONE, 0, .2f); addMobSpawnAmount(cfg, EntityEndermite.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntitySilverfish.class, 400); addMobSpawnAmount(cfg, EntitySilverfish.class, MATERIALTYPE_KEY, Items.IRON_INGOT, 0, 0.05f); addMobSpawnAmount(cfg, EntitySilverfish.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntitySilverfish.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntityRabbit.class, 300); addMobSpawnAmount(cfg, EntityRabbit.class, MATERIALTYPE_KEY, Items.RABBIT_STEW, 0, 0.1f); addMobSpawnAmount(cfg, EntityRabbit.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityRabbit.class, MATERIALTYPE_LIVING, null, 0, 10); addMobSpawnRF(cfg, EntityPolarBear.class, 1500); addMobSpawnAmount(cfg, EntityPolarBear.class, MATERIALTYPE_KEY, Items.FISH, 0, 0.1f); addMobSpawnAmount(cfg, EntityPolarBear.class, MATERIALTYPE_BULK, Blocks.DIRT, 0, .2f); addMobSpawnAmount(cfg, EntityPolarBear.class, MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, "minecraft:wither_skeleton", 1500); addMobSpawnAmount(cfg, "minecraft:wither_skeleton", MATERIALTYPE_KEY, Items.BONE, 0, 0.1f); addMobSpawnAmount(cfg, "minecraft:wither_skeleton", MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .5f); addMobSpawnAmount(cfg, "minecraft:wither_skeleton", MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, "minecraft:stray", 800); addMobSpawnAmount(cfg, "minecraft:stray", MATERIALTYPE_KEY, Items.BONE, 0, 0.1f); addMobSpawnAmount(cfg, "minecraft:stray", MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .5f); addMobSpawnAmount(cfg, "minecraft:stray", MATERIALTYPE_LIVING, null, 0, 20); addMobSpawnRF(cfg, "WitherSkeleton", 1500); addMobSpawnAmount(cfg, "WitherSkeleton", MATERIALTYPE_KEY, Items.BONE, 0, 0.1f); addMobSpawnAmount(cfg, "WitherSkeleton", MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .5f); addMobSpawnAmount(cfg, "WitherSkeleton", MATERIALTYPE_LIVING, null, 0, 30); addMobSpawnRF(cfg, "StraySkeleton", 800); addMobSpawnAmount(cfg, "StraySkeleton", MATERIALTYPE_KEY, Items.BONE, 0, 0.1f); addMobSpawnAmount(cfg, "StraySkeleton", MATERIALTYPE_BULK, Blocks.NETHERRACK, 0, .5f); addMobSpawnAmount(cfg, "StraySkeleton", MATERIALTYPE_LIVING, null, 0, 20); } public static void addMobSpawnRF(Configuration cfg, Class<? extends EntityLiving> clazz, int rf) { String id = EntityTools.findEntityIdByClass(clazz); addMobSpawnRF(cfg, id, rf); } private static void addMobSpawnRF(Configuration cfg, String name, int rf) { cfg.get(CATEGORY_MOBSPAWNRF, name, rf); } public static void addMobSpawnAmount(Configuration cfg, Class<? extends EntityLiving> clazz, int materialType, Object object, int meta, float amount) { String id = EntityTools.findEntityIdByClass(clazz); addMobSpawnAmount(cfg, id, materialType, object, meta, amount); } private static void addMobSpawnAmount(Configuration cfg, String id, int materialType, Object object, int meta, float amount) { String type; ResourceLocation itemname; if (object instanceof Item) { type = "I"; itemname = Item.REGISTRY.getNameForObject((Item) object); } else if (object instanceof Block) { type = "B"; itemname = Block.REGISTRY.getNameForObject((Block) object); } else { type = "L"; itemname = null; } cfg.get(CATEGORY_MOBSPAWNAMOUNTS, id + ".spawnamount." + materialType, new String[] { type, itemname == null ? "" : itemname.toString(), Integer.toString(meta), Float.toString(amount) }); } private static void setSpawnAmounts(String id, int materialType, String[] splitted) { String type; ResourceLocation itemname; int meta; float amount; try { type = splitted[0]; String n = splitted[1]; if ("".equals(n)) { itemname = null; } else { itemname = new ResourceLocation(n); } meta = Integer.parseInt(splitted[2]); amount = Float.parseFloat(splitted[3]); } catch (NumberFormatException e) { Logging.logError("Something went wrong parsing the spawnamount setting for '" + id + "'!"); return; } ItemStack stack = ItemStack.EMPTY; if ("I".equals(type)) { Item item = Item.REGISTRY.getObject(itemname); stack = new ItemStack(item, 1, meta); } else if ("B".equals(type)) { Block block = Block.REGISTRY.getObject(itemname); stack = new ItemStack(block, 1, meta); } else if ("S".equals(type)) { } List<MobSpawnAmount> list = mobSpawnAmounts.get(id); if (list == null) { list = new ArrayList<>(3); list.add(null); list.add(null); list.add(null); mobSpawnAmounts.put(id, list); } list.set(materialType, new MobSpawnAmount(stack, amount)); } public static class MobSpawnAmount { private final ItemStack object; private final float amount; public MobSpawnAmount(ItemStack object, float amount) { this.object = object; this.amount = amount; } public ItemStack getObject() { return object; } public float getAmount() { return amount; } public Float match(ItemStack stack) { if (object.isEmpty()) { // Living? Item item = stack.getItem(); return livingMatter.get(item.getRegistryName()); } if (stack.isItemEqual(object)) { return 1.0f; } return null; } } }
0
0.659455
1
0.659455
game-dev
MEDIA
0.991265
game-dev
0.537003
1
0.537003
guanyuxin/baogame
3,771
game/ai/Path.js
var C = require('../../static/js/const.js'); //get All possible dest in one move from location [i,j] // return [y,x,distance,method] function getDest (map, i, j) { var res = []; var f = map.floor //move if (f[i][j] && f[i][j + 1]) { res.push([i, j + 1, 1, 'moveRight']); } if (f[i][j] && f[i][j - 1]) { res.push([i, j - 1, 1, 'moveLeft']); } //climb for (var pilla of map.pilla) { if (pilla.x > j && pilla.x < j + 1 && i >= pilla.y1 && i <= pilla.y2) { for (var k = pilla.y1; k <= pilla.y2; k++) { if (k > i) { res.push([k, j, k - i, 'climbUp']); } else { res.push([k, j, i - k, 'climbDown']); } } } } //jump on floor if (f[i][j]) { if (f[i][j - 1] && f[i][j + 3]) { res.push([i, j + 3, 4, 'jumpRight3']); } if (f[i][j + 1] && f[i][j - 3]) { res.push([i, j - 3, 4, 'jumpLeft3']); } if (f[i][j - 1] && f[i][j + 4]) { res.push([i, j + 4, 5, 'jumpRight4']); } if (f[i][j + 1] && f[i][j - 4]) { res.push([i, j - 4, 5, 'jumpLeft4']); } } //jump down if (!f[i][j - 1]) { for (var k = 1; k <= 2; k++) { if (f[i - k] && f[i - k][j - 1]) { res.push([i - k, j - 1, k + 1, 'jumpDownLeft']); break; } } for (var k = 3; k <= 4; k++) { if (f[i - k] && f[i - k][j - 2]) { res.push([i - k, j - 2, k + 1, 'jumpDownLeft']); break; } } for (var k = 5; k <= 7; k++) { if (f[i - k] && f[i - k][j - 3]) { res.push([i - k, j - 3, k + 1, 'jumpDownLeft']); break; } } } if (!f[i][j + 1]) { for (var k = 1; k < 2; k++) { if (f[i - k] && f[i - k][j + 1]) { res.push([i - k, j + 1, k + 1, 'jumpDownRight']); break; } } for (var k = 3; k <= 4; k++) { if (f[i - k] && f[i - k][j + 2]) { res.push([i - k, j + 2, k + 1, 'jumpDownRight']); break; } } for (var k = 5; k <= 7; k++) { if (f[i - k] && f[i - k][j + 3]) { res.push([i - k, j + 3, k + 1, 'jumpDownRight']); break; } } } return res; } function onPillar(map, i, j) { for (var pilla of map.pilla) { if (pilla.x > j && pilla.x < j + 1 && i >= pilla.y1 && i <= pilla.y2) { return true; } } return false; } function deepSearch (map, lengthMap, dirMap) { var t = 0; while (t < 1000) { var find = false; for (var i = 0; i < lengthMap.length; i++) { for (var j = 0; j < lengthMap[i].length; j++) { if (lengthMap[i][j] == -1) { continue; } dest = getDest(map, i, j); for (var k = 0; k < dest.length; k++) { if (lengthMap[dest[k][0]][dest[k][1]] == -1 || lengthMap[dest[k][0]][dest[k][1]] > lengthMap[i][j] + dest[k][2]) { lengthMap[dest[k][0]][dest[k][1]] = lengthMap[i][j] + dest[k][2]; dirMap[dest[k][0]][dest[k][1]] = dirMap[i][j] || dest[k][3]; find = true; } } } } t++; if (!find) { break; } } } function DR_MAP (dirMap) { console.log('\n\n'); for (var dd = 0; dd < dirMap.length; dd++){ console.log(dirMap[dd].join(' ')) } console.log('\n\n'); } var Path = function (map, P) { this.lengthMap = []; this.dirMap = []; //init var wc = P.w/C.TW; var hc = P.h/C.TH; for (var i = 0; i < hc; i++) { this.lengthMap[i] = []; this.dirMap[i] = []; for (var j = 0; j < wc; j++) { this.lengthMap[i][j] = []; this.dirMap[i][j] = []; if (!map.floor[i][j] && !onPillar(map, i, j)) { continue; } var lengthMap = []; var dirMap = []; for (var ix = 0; ix < hc; ix++) { lengthMap[ix] = []; dirMap[ix] = []; for (var jx = 0; jx < wc; jx++) { if (ix == i && jx == j) { lengthMap[ix][jx] = 0; } else { lengthMap[ix][jx] = -1; } dirMap[ix][jx] = ''; } } deepSearch(map, lengthMap, dirMap); this.lengthMap[i][j] = lengthMap; this.dirMap[i][j] = dirMap; } } } module.exports = Path;
0
0.629697
1
0.629697
game-dev
MEDIA
0.443722
game-dev
0.927972
1
0.927972
Vanilla-NetHack/NetHack-3.4.3
18,409
src/attrib.c
/* SCCS Id: @(#)attrib.c 3.4 2002/10/07 */ /* Copyright 1988, 1989, 1990, 1992, M. Stephenson */ /* NetHack may be freely redistributed. See license for details. */ /* attribute modification routines. */ #include "hack.h" /* #define DEBUG */ /* uncomment for debugging info */ #ifdef OVLB /* part of the output on gain or loss of attribute */ static const char * const plusattr[] = { "strong", "smart", "wise", "agile", "tough", "charismatic" }, * const minusattr[] = { "weak", "stupid", "foolish", "clumsy", "fragile", "repulsive" }; static const struct innate { schar ulevel; long *ability; const char *gainstr, *losestr; } arc_abil[] = { { 1, &(HStealth), "", "" }, { 1, &(HFast), "", "" }, { 10, &(HSearching), "perceptive", "" }, { 0, 0, 0, 0 } }, bar_abil[] = { { 1, &(HPoison_resistance), "", "" }, { 7, &(HFast), "quick", "slow" }, { 15, &(HStealth), "stealthy", "" }, { 0, 0, 0, 0 } }, cav_abil[] = { { 7, &(HFast), "quick", "slow" }, { 15, &(HWarning), "sensitive", "" }, { 0, 0, 0, 0 } }, hea_abil[] = { { 1, &(HPoison_resistance), "", "" }, { 15, &(HWarning), "sensitive", "" }, { 0, 0, 0, 0 } }, kni_abil[] = { { 7, &(HFast), "quick", "slow" }, { 0, 0, 0, 0 } }, mon_abil[] = { { 1, &(HFast), "", "" }, { 1, &(HSleep_resistance), "", "" }, { 1, &(HSee_invisible), "", "" }, { 3, &(HPoison_resistance), "healthy", "" }, { 5, &(HStealth), "stealthy", "" }, { 7, &(HWarning), "sensitive", "" }, { 9, &(HSearching), "perceptive", "unaware" }, { 11, &(HFire_resistance), "cool", "warmer" }, { 13, &(HCold_resistance), "warm", "cooler" }, { 15, &(HShock_resistance), "insulated", "conductive" }, { 17, &(HTeleport_control), "controlled","uncontrolled" }, { 0, 0, 0, 0 } }, pri_abil[] = { { 15, &(HWarning), "sensitive", "" }, { 20, &(HFire_resistance), "cool", "warmer" }, { 0, 0, 0, 0 } }, ran_abil[] = { { 1, &(HSearching), "", "" }, { 7, &(HStealth), "stealthy", "" }, { 15, &(HSee_invisible), "", "" }, { 0, 0, 0, 0 } }, rog_abil[] = { { 1, &(HStealth), "", "" }, { 10, &(HSearching), "perceptive", "" }, { 0, 0, 0, 0 } }, sam_abil[] = { { 1, &(HFast), "", "" }, { 15, &(HStealth), "stealthy", "" }, { 0, 0, 0, 0 } }, tou_abil[] = { { 10, &(HSearching), "perceptive", "" }, { 20, &(HPoison_resistance), "hardy", "" }, { 0, 0, 0, 0 } }, val_abil[] = { { 1, &(HCold_resistance), "", "" }, { 1, &(HStealth), "", "" }, { 7, &(HFast), "quick", "slow" }, { 0, 0, 0, 0 } }, wiz_abil[] = { { 15, &(HWarning), "sensitive", "" }, { 17, &(HTeleport_control), "controlled","uncontrolled" }, { 0, 0, 0, 0 } }, /* Intrinsics conferred by race */ elf_abil[] = { { 4, &(HSleep_resistance), "awake", "tired" }, { 0, 0, 0, 0 } }, orc_abil[] = { { 1, &(HPoison_resistance), "", "" }, { 0, 0, 0, 0 } }; static long next_check = 600L; /* arbitrary first setting */ STATIC_DCL void NDECL(exerper); STATIC_DCL void FDECL(postadjabil, (long *)); /* adjust an attribute; return TRUE if change is made, FALSE otherwise */ boolean adjattrib(ndx, incr, msgflg) int ndx, incr; int msgflg; /* positive => no message, zero => message, and */ { /* negative => conditional (msg if change made) */ if (Fixed_abil || !incr) return FALSE; if ((ndx == A_INT || ndx == A_WIS) && uarmh && uarmh->otyp == DUNCE_CAP) { if (msgflg == 0) Your("cap constricts briefly, then relaxes again."); return FALSE; } if (incr > 0) { if ((AMAX(ndx) >= ATTRMAX(ndx)) && (ACURR(ndx) >= AMAX(ndx))) { if (msgflg == 0 && flags.verbose) pline("You're already as %s as you can get.", plusattr[ndx]); ABASE(ndx) = AMAX(ndx) = ATTRMAX(ndx); /* just in case */ return FALSE; } ABASE(ndx) += incr; if(ABASE(ndx) > AMAX(ndx)) { incr = ABASE(ndx) - AMAX(ndx); AMAX(ndx) += incr; if(AMAX(ndx) > ATTRMAX(ndx)) AMAX(ndx) = ATTRMAX(ndx); ABASE(ndx) = AMAX(ndx); } } else { if (ABASE(ndx) <= ATTRMIN(ndx)) { if (msgflg == 0 && flags.verbose) pline("You're already as %s as you can get.", minusattr[ndx]); ABASE(ndx) = ATTRMIN(ndx); /* just in case */ return FALSE; } ABASE(ndx) += incr; if(ABASE(ndx) < ATTRMIN(ndx)) { incr = ABASE(ndx) - ATTRMIN(ndx); ABASE(ndx) = ATTRMIN(ndx); AMAX(ndx) += incr; if(AMAX(ndx) < ATTRMIN(ndx)) AMAX(ndx) = ATTRMIN(ndx); } } if (msgflg <= 0) You_feel("%s%s!", (incr > 1 || incr < -1) ? "very ": "", (incr > 0) ? plusattr[ndx] : minusattr[ndx]); flags.botl = 1; if (moves > 1 && (ndx == A_STR || ndx == A_CON)) (void)encumber_msg(); return TRUE; } void gainstr(otmp, incr) register struct obj *otmp; register int incr; { int num = 1; if(incr) num = incr; else { if(ABASE(A_STR) < 18) num = (rn2(4) ? 1 : rnd(6) ); else if (ABASE(A_STR) < STR18(85)) num = rnd(10); } (void) adjattrib(A_STR, (otmp && otmp->cursed) ? -num : num, TRUE); } void losestr(num) /* may kill you; cause may be poison or monster like 'a' */ register int num; { int ustr = ABASE(A_STR) - num; while(ustr < 3) { ++ustr; --num; if (Upolyd) { u.mh -= 6; u.mhmax -= 6; } else { u.uhp -= 6; u.uhpmax -= 6; } } (void) adjattrib(A_STR, -num, TRUE); } void change_luck(n) register schar n; { u.uluck += n; if (u.uluck < 0 && u.uluck < LUCKMIN) u.uluck = LUCKMIN; if (u.uluck > 0 && u.uluck > LUCKMAX) u.uluck = LUCKMAX; } int stone_luck(parameter) boolean parameter; /* So I can't think up of a good name. So sue me. --KAA */ { register struct obj *otmp; register long bonchance = 0; for (otmp = invent; otmp; otmp = otmp->nobj) if (confers_luck(otmp)) { if (otmp->cursed) bonchance -= otmp->quan; else if (otmp->blessed) bonchance += otmp->quan; else if (parameter) bonchance += otmp->quan; } return sgn((int)bonchance); } /* there has just been an inventory change affecting a luck-granting item */ void set_moreluck() { int luckbon = stone_luck(TRUE); if (!luckbon && !carrying(LUCKSTONE)) u.moreluck = 0; else if (luckbon >= 0) u.moreluck = LUCKADD; else u.moreluck = -LUCKADD; } #endif /* OVLB */ #ifdef OVL1 void restore_attrib() { int i; for(i = 0; i < A_MAX; i++) { /* all temporary losses/gains */ if(ATEMP(i) && ATIME(i)) { if(!(--(ATIME(i)))) { /* countdown for change */ ATEMP(i) += ATEMP(i) > 0 ? -1 : 1; if(ATEMP(i)) /* reset timer */ ATIME(i) = 100 / ACURR(A_CON); } } } (void)encumber_msg(); } #endif /* OVL1 */ #ifdef OVLB #define AVAL 50 /* tune value for exercise gains */ void exercise(i, inc_or_dec) int i; boolean inc_or_dec; { #ifdef DEBUG pline("Exercise:"); #endif if (i == A_INT || i == A_CHA) return; /* can't exercise these */ /* no physical exercise while polymorphed; the body's temporary */ if (Upolyd && i != A_WIS) return; if(abs(AEXE(i)) < AVAL) { /* * Law of diminishing returns (Part I): * * Gain is harder at higher attribute values. * 79% at "3" --> 0% at "18" * Loss is even at all levels (50%). * * Note: *YES* ACURR is the right one to use. */ AEXE(i) += (inc_or_dec) ? (rn2(19) > ACURR(i)) : -rn2(2); #ifdef DEBUG pline("%s, %s AEXE = %d", (i == A_STR) ? "Str" : (i == A_WIS) ? "Wis" : (i == A_DEX) ? "Dex" : "Con", (inc_or_dec) ? "inc" : "dec", AEXE(i)); #endif } if (moves > 0 && (i == A_STR || i == A_CON)) (void)encumber_msg(); } /* hunger values - from eat.c */ #define SATIATED 0 #define NOT_HUNGRY 1 #define HUNGRY 2 #define WEAK 3 #define FAINTING 4 #define FAINTED 5 #define STARVED 6 STATIC_OVL void exerper() { if(!(moves % 10)) { /* Hunger Checks */ int hs = (u.uhunger > 1000) ? SATIATED : (u.uhunger > 150) ? NOT_HUNGRY : (u.uhunger > 50) ? HUNGRY : (u.uhunger > 0) ? WEAK : FAINTING; #ifdef DEBUG pline("exerper: Hunger checks"); #endif switch (hs) { case SATIATED: exercise(A_DEX, FALSE); if (Role_if(PM_MONK)) exercise(A_WIS, FALSE); break; case NOT_HUNGRY: exercise(A_CON, TRUE); break; case WEAK: exercise(A_STR, FALSE); if (Role_if(PM_MONK)) /* fasting */ exercise(A_WIS, TRUE); break; case FAINTING: case FAINTED: exercise(A_CON, FALSE); break; } /* Encumberance Checks */ #ifdef DEBUG pline("exerper: Encumber checks"); #endif switch (near_capacity()) { case MOD_ENCUMBER: exercise(A_STR, TRUE); break; case HVY_ENCUMBER: exercise(A_STR, TRUE); exercise(A_DEX, FALSE); break; case EXT_ENCUMBER: exercise(A_DEX, FALSE); exercise(A_CON, FALSE); break; } } /* status checks */ if(!(moves % 5)) { #ifdef DEBUG pline("exerper: Status checks"); #endif if ((HClairvoyant & (INTRINSIC|TIMEOUT)) && !BClairvoyant) exercise(A_WIS, TRUE); if (HRegeneration) exercise(A_STR, TRUE); if(Sick || Vomiting) exercise(A_CON, FALSE); if(Confusion || Hallucination) exercise(A_WIS, FALSE); if((Wounded_legs #ifdef STEED && !u.usteed #endif ) || Fumbling || HStun) exercise(A_DEX, FALSE); } } void exerchk() { int i, mod_val; /* Check out the periodic accumulations */ exerper(); #ifdef DEBUG if(moves >= next_check) pline("exerchk: ready to test. multi = %d.", multi); #endif /* Are we ready for a test? */ if(moves >= next_check && !multi) { #ifdef DEBUG pline("exerchk: testing."); #endif /* * Law of diminishing returns (Part II): * * The effects of "exercise" and "abuse" wear * off over time. Even if you *don't* get an * increase/decrease, you lose some of the * accumulated effects. */ for(i = 0; i < A_MAX; AEXE(i++) /= 2) { if(ABASE(i) >= 18 || !AEXE(i)) continue; if(i == A_INT || i == A_CHA) continue;/* can't exercise these */ #ifdef DEBUG pline("exerchk: testing %s (%d).", (i == A_STR) ? "Str" : (i == A_WIS) ? "Wis" : (i == A_DEX) ? "Dex" : "Con", AEXE(i)); #endif /* * Law of diminishing returns (Part III): * * You don't *always* gain by exercising. * [MRS 92/10/28 - Treat Wisdom specially for balance.] */ if(rn2(AVAL) > ((i != A_WIS) ? abs(AEXE(i)*2/3) : abs(AEXE(i)))) continue; mod_val = sgn(AEXE(i)); #ifdef DEBUG pline("exerchk: changing %d.", i); #endif if(adjattrib(i, mod_val, -1)) { #ifdef DEBUG pline("exerchk: changed %d.", i); #endif /* if you actually changed an attrib - zero accumulation */ AEXE(i) = 0; /* then print an explanation */ switch(i) { case A_STR: You((mod_val >0) ? "must have been exercising." : "must have been abusing your body."); break; case A_WIS: You((mod_val >0) ? "must have been very observant." : "haven't been paying attention."); break; case A_DEX: You((mod_val >0) ? "must have been working on your reflexes." : "haven't been working on reflexes lately."); break; case A_CON: You((mod_val >0) ? "must be leading a healthy life-style." : "haven't been watching your health."); break; } } } next_check += rn1(200,800); #ifdef DEBUG pline("exerchk: next check at %ld.", next_check); #endif } } /* next_check will otherwise have its initial 600L after a game restore */ void reset_attribute_clock() { if (moves > 600L) next_check = moves + rn1(50,800); } void init_attr(np) register int np; { register int i, x, tryct; for(i = 0; i < A_MAX; i++) { ABASE(i) = AMAX(i) = urole.attrbase[i]; ATEMP(i) = ATIME(i) = 0; np -= urole.attrbase[i]; } tryct = 0; while(np > 0 && tryct < 100) { x = rn2(100); for (i = 0; (i < A_MAX) && ((x -= urole.attrdist[i]) > 0); i++) ; if(i >= A_MAX) continue; /* impossible */ if(ABASE(i) >= ATTRMAX(i)) { tryct++; continue; } tryct = 0; ABASE(i)++; AMAX(i)++; np--; } tryct = 0; while(np < 0 && tryct < 100) { /* for redistribution */ x = rn2(100); for (i = 0; (i < A_MAX) && ((x -= urole.attrdist[i]) > 0); i++) ; if(i >= A_MAX) continue; /* impossible */ if(ABASE(i) <= ATTRMIN(i)) { tryct++; continue; } tryct = 0; ABASE(i)--; AMAX(i)--; np++; } } void redist_attr() { register int i, tmp; for(i = 0; i < A_MAX; i++) { if (i==A_INT || i==A_WIS) continue; /* Polymorphing doesn't change your mind */ tmp = AMAX(i); AMAX(i) += (rn2(5)-2); if (AMAX(i) > ATTRMAX(i)) AMAX(i) = ATTRMAX(i); if (AMAX(i) < ATTRMIN(i)) AMAX(i) = ATTRMIN(i); ABASE(i) = ABASE(i) * AMAX(i) / tmp; /* ABASE(i) > ATTRMAX(i) is impossible */ if (ABASE(i) < ATTRMIN(i)) ABASE(i) = ATTRMIN(i); } (void)encumber_msg(); } STATIC_OVL void postadjabil(ability) long *ability; { if (!ability) return; if (ability == &(HWarning) || ability == &(HSee_invisible)) see_monsters(); } void adjabil(oldlevel,newlevel) int oldlevel, newlevel; { register const struct innate *abil, *rabil; long mask = FROMEXPER; switch (Role_switch) { case PM_ARCHEOLOGIST: abil = arc_abil; break; case PM_BARBARIAN: abil = bar_abil; break; case PM_CAVEMAN: abil = cav_abil; break; case PM_HEALER: abil = hea_abil; break; case PM_KNIGHT: abil = kni_abil; break; case PM_MONK: abil = mon_abil; break; case PM_PRIEST: abil = pri_abil; break; case PM_RANGER: abil = ran_abil; break; case PM_ROGUE: abil = rog_abil; break; case PM_SAMURAI: abil = sam_abil; break; #ifdef TOURIST case PM_TOURIST: abil = tou_abil; break; #endif case PM_VALKYRIE: abil = val_abil; break; case PM_WIZARD: abil = wiz_abil; break; default: abil = 0; break; } switch (Race_switch) { case PM_ELF: rabil = elf_abil; break; case PM_ORC: rabil = orc_abil; break; case PM_HUMAN: case PM_DWARF: case PM_GNOME: default: rabil = 0; break; } while (abil || rabil) { long prevabil; /* Have we finished with the intrinsics list? */ if (!abil || !abil->ability) { /* Try the race intrinsics */ if (!rabil || !rabil->ability) break; abil = rabil; rabil = 0; mask = FROMRACE; } prevabil = *(abil->ability); if(oldlevel < abil->ulevel && newlevel >= abil->ulevel) { /* Abilities gained at level 1 can never be lost * via level loss, only via means that remove _any_ * sort of ability. A "gain" of such an ability from * an outside source is devoid of meaning, so we set * FROMOUTSIDE to avoid such gains. */ if (abil->ulevel == 1) *(abil->ability) |= (mask|FROMOUTSIDE); else *(abil->ability) |= mask; if(!(*(abil->ability) & INTRINSIC & ~mask)) { if(*(abil->gainstr)) You_feel("%s!", abil->gainstr); } } else if (oldlevel >= abil->ulevel && newlevel < abil->ulevel) { *(abil->ability) &= ~mask; if(!(*(abil->ability) & INTRINSIC)) { if(*(abil->losestr)) You_feel("%s!", abil->losestr); else if(*(abil->gainstr)) You_feel("less %s!", abil->gainstr); } } if (prevabil != *(abil->ability)) /* it changed */ postadjabil(abil->ability); abil++; } if (oldlevel > 0) { if (newlevel > oldlevel) add_weapon_skill(newlevel - oldlevel); else lose_weapon_skill(oldlevel - newlevel); } } int newhp() { int hp, conplus; if (u.ulevel == 0) { /* Initialize hit points */ hp = urole.hpadv.infix + urace.hpadv.infix; if (urole.hpadv.inrnd > 0) hp += rnd(urole.hpadv.inrnd); if (urace.hpadv.inrnd > 0) hp += rnd(urace.hpadv.inrnd); /* Initialize alignment stuff */ u.ualign.type = aligns[flags.initalign].value; u.ualign.record = urole.initrecord; return hp; } else { if (u.ulevel < urole.xlev) { hp = urole.hpadv.lofix + urace.hpadv.lofix; if (urole.hpadv.lornd > 0) hp += rnd(urole.hpadv.lornd); if (urace.hpadv.lornd > 0) hp += rnd(urace.hpadv.lornd); } else { hp = urole.hpadv.hifix + urace.hpadv.hifix; if (urole.hpadv.hirnd > 0) hp += rnd(urole.hpadv.hirnd); if (urace.hpadv.hirnd > 0) hp += rnd(urace.hpadv.hirnd); } } if (ACURR(A_CON) <= 3) conplus = -2; else if (ACURR(A_CON) <= 6) conplus = -1; else if (ACURR(A_CON) <= 14) conplus = 0; else if (ACURR(A_CON) <= 16) conplus = 1; else if (ACURR(A_CON) == 17) conplus = 2; else if (ACURR(A_CON) == 18) conplus = 3; else conplus = 4; hp += conplus; return((hp <= 0) ? 1 : hp); } #endif /* OVLB */ #ifdef OVL0 schar acurr(x) int x; { register int tmp = (u.abon.a[x] + u.atemp.a[x] + u.acurr.a[x]); if (x == A_STR) { if (uarmg && uarmg->otyp == GAUNTLETS_OF_POWER) return(125); #ifdef WIN32_BUG else return(x=((tmp >= 125) ? 125 : (tmp <= 3) ? 3 : tmp)); #else else return((schar)((tmp >= 125) ? 125 : (tmp <= 3) ? 3 : tmp)); #endif } else if (x == A_CHA) { if (tmp < 18 && (youmonst.data->mlet == S_NYMPH || u.umonnum==PM_SUCCUBUS || u.umonnum == PM_INCUBUS)) return 18; } else if (x == A_INT || x == A_WIS) { /* yes, this may raise int/wis if player is sufficiently * stupid. there are lower levels of cognition than "dunce". */ if (uarmh && uarmh->otyp == DUNCE_CAP) return(6); } #ifdef WIN32_BUG return(x=((tmp >= 25) ? 25 : (tmp <= 3) ? 3 : tmp)); #else return((schar)((tmp >= 25) ? 25 : (tmp <= 3) ? 3 : tmp)); #endif } /* condense clumsy ACURR(A_STR) value into value that fits into game formulas */ schar acurrstr() { register int str = ACURR(A_STR); if (str <= 18) return((schar)str); if (str <= 121) return((schar)(19 + str / 50)); /* map to 19-21 */ else return((schar)(str - 100)); } #endif /* OVL0 */ #ifdef OVL2 /* avoid possible problems with alignment overflow, and provide a centralized * location for any future alignment limits */ void adjalign(n) register int n; { register int newalign = u.ualign.record + n; if(n < 0) { if(newalign < u.ualign.record) u.ualign.record = newalign; } else if(newalign > u.ualign.record) { u.ualign.record = newalign; if(u.ualign.record > ALIGNLIM) u.ualign.record = ALIGNLIM; } } #endif /* OVL2 */ /*attrib.c*/
0
0.917355
1
0.917355
game-dev
MEDIA
0.973624
game-dev
0.978943
1
0.978943
ima-games/ATD
2,036
Assets/Plugins/Behavior Designer/Runtime/Tasks/Unity/Animator/SetIntegerParameter.cs
using UnityEngine; using System.Collections; namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityAnimator { [TaskCategory("Unity/Animator")] [TaskDescription("Sets the int parameter on an animator. Returns Success.")] public class SetIntegerParameter : Action { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The name of the parameter")] public SharedString paramaterName; [Tooltip("The value of the int parameter")] public SharedInt intValue; [Tooltip("Should the value be reverted back to its original value after it has been set?")] public bool setOnce; private int hashID; private Animator animator; private GameObject prevGameObject; public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { animator = currentGameObject.GetComponent<Animator>(); prevGameObject = currentGameObject; } } public override TaskStatus OnUpdate() { if (animator == null) { Debug.LogWarning("Animator is null"); return TaskStatus.Failure; } hashID = UnityEngine.Animator.StringToHash(paramaterName.Value); int prevValue = animator.GetInteger(hashID); animator.SetInteger(hashID, intValue.Value); if (setOnce) { StartCoroutine(ResetValue(prevValue)); } return TaskStatus.Success; } public IEnumerator ResetValue(int origVale) { yield return null; animator.SetInteger(hashID, origVale); } public override void OnReset() { targetGameObject = null; paramaterName = ""; intValue = 0; } } }
0
0.731284
1
0.731284
game-dev
MEDIA
0.984631
game-dev
0.779376
1
0.779376
schombert/Project-Alice
2,166
src/military/military_templates.hpp
#pragma once #include "system_state.hpp" namespace military { template<typename T> auto province_is_blockaded(sys::state const& state, T ids) { return state.world.province_get_is_blockaded(ids); } template<typename T> auto province_is_under_siege(sys::state const& state, T ids) { return state.world.province_get_siege_progress(ids) > 0.0f; } template<typename T> auto battle_is_ongoing_in_province(sys::state const& state, T ids) { ve::apply( [&](dcon::province_id p) { auto battles = state.world.province_get_land_battle_location(p); return battles.begin() != battles.end(); }, ids); return false; } // Calculates whether province can support more regiments // Considers existing regiments and construction as well // Takes a filter function template to filter out which pops are eligible template<typename F> dcon::pop_id find_available_soldier(sys::state& state, dcon::province_id p, F&& filter) { float divisor = 0; if(state.world.province_get_is_colonial(p)) { divisor = state.defines.pop_size_per_regiment * state.defines.pop_min_size_for_regiment_colony_multiplier; } else if(!state.world.province_get_is_owner_core(p)) { divisor = state.defines.pop_size_per_regiment * state.defines.pop_min_size_for_regiment_noncore_multiplier; } else { divisor = state.defines.pop_size_per_regiment; } for(auto pop : state.world.province_get_pop_location(p)) { if(filter(state, pop.get_pop())) { if(can_pop_form_regiment(state, pop.get_pop(), divisor)) { return pop.get_pop().id; } } } return dcon::pop_id{}; } // Calculates whether province can support more regiments when parsing OOBs // Takes a filter function template to filter out which pops are eligible template<typename F> dcon::pop_id find_available_soldier_parsing(sys::state& state, dcon::province_id province_id, F&& filter) { float divisor = state.defines.pop_size_per_regiment; for(auto pop : state.world.province_get_pop_location(province_id)) { if(filter(state, pop.get_pop())) { if(can_pop_form_regiment(state, pop.get_pop(), divisor)) { return pop.get_pop().id; } } } return dcon::pop_id{ }; }; } // namespace military
0
0.844319
1
0.844319
game-dev
MEDIA
0.840059
game-dev
0.948593
1
0.948593
DominaeDev/ginger
6,560
source/src/Utility/EnumHelper.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Ginger { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class HideEnumAttribute : System.Attribute { } public static class EnumInfo<T> where T : struct, IConvertible { static EnumInfo() { Type type = typeof(T); UnderlyingType = Enum.GetUnderlyingType(type); var names = Enum.GetNames(type); var ignore = new HashSet<string>( names.Where(name => { var field = type.GetField(name); return field.GetCustomAttributes(typeof(HideEnumAttribute), false).Length > 0; })); ms_EnumToNameLookup = new Dictionary<T, string>(); foreach (var name in names.Except(ignore)) ms_EnumToNameLookup.TryAdd((T)Enum.Parse(type, name), name); ms_NameToEnumLookup = new Dictionary<string, T>(); foreach (var kvp in ms_EnumToNameLookup) ms_NameToEnumLookup.TryAdd(kvp.Value.ToLowerInvariant(), kvp.Key); // Values ms_Values = new ReadOnlyCollection<T>(Enum.GetValues(type).OfType<T>().Distinct().ToArray()); if (UnderlyingType == typeof(long)) // 64 bit bit enum { ms_ValueLookup = ms_Values .ToDictionary(x => (long)(object)x, x => x); } else if (UnderlyingType == typeof(int)) // 32 bit enum { ms_ValueLookup = ms_Values .ToDictionary(x => (long)(int)(object)x, x => x); } else if (UnderlyingType == typeof(short)) // 16 bit enum { ms_ValueLookup = ms_Values .ToDictionary(x => (long)(short)(object)x, x => x); } else if (UnderlyingType == typeof(byte)) // 8 bit enum { ms_ValueLookup = ms_Values .ToDictionary(x => (long)(byte)(object)x, x => x); } else { throw new ArgumentException("Unsupported underlying enum type."); } } // Static lookup tables private static readonly Dictionary<string, T> ms_NameToEnumLookup; private static readonly Dictionary<T, string> ms_EnumToNameLookup; private static readonly Dictionary<long, T> ms_ValueLookup; private static readonly ReadOnlyCollection<T> ms_Values; public static readonly Type UnderlyingType; public static bool Convert(string string_value, out T result) { if (ms_NameToEnumLookup.TryGetValue(string_value.ToLowerInvariant(), out result)) return true; return false; } public static bool Convert(StringHandle string_value, out T result) { if (ms_NameToEnumLookup.TryGetValue(string_value.ToString(), out result)) return true; return false; } public static bool Convert(long value, out T result) { return ms_ValueLookup.TryGetValue(value, out result); } public static string ToString(T value) { return GetName(value); } public static string GetName(T value) { string result; if (ms_EnumToNameLookup.TryGetValue(value, out result)) return result; return Enum.GetName(typeof(T), value); } public static ReadOnlyCollection<T> GetValues() { return ms_Values; } } public static class EnumHelper { public static string ToString<T>(T e) where T : struct, IConvertible { return EnumInfo<T>.ToString(e); } public static int ToInt(Enum e) { return Convert.ToInt32(e); } public static int ToInt<T>(T e) where T : struct, IConvertible { return Convert.ToInt32(e); } public static long ToLong<T>(Enum e) where T : struct, IConvertible { return Convert.ToInt64(e); } public static long ToLong<T>(T e) where T : struct, IConvertible { return Convert.ToInt64(e); } public static int Compare(Enum a, Enum b) { return Convert.ToInt32(a) - Convert.ToInt32(b); } public static T FromString<T>(string enumName, T default_value = default(T)) where T : struct, IConvertible { if (string.IsNullOrEmpty(enumName)) return default_value; T result; if (EnumInfo<T>.Convert(enumName, out result)) return result; return default_value; } public static T FromInt<T>(int enumValue, T default_value = default(T)) where T : struct, IConvertible { T result; if (EnumInfo<T>.Convert(enumValue, out result)) return result; if (Enum.TryParse(enumValue.ToString(), out result)) return result; return default_value; } public static T FromLong<T>(long enumValue, T default_value = default(T)) where T : struct, IConvertible { T result; if (EnumInfo<T>.Convert(enumValue, out result)) return result; return default_value; } public static bool Increment<T>(ref T enumValue, int increment, T enumMin, T enumMax) where T : struct, IConvertible { int iValue = (int)(object)enumValue + increment; // Clamp if ((int)(object)enumMin > iValue) { enumValue = enumMin; return true; } else if ((int)(object)enumMax < iValue) { enumValue = enumMax; return true; } T newEnumValue; if (EnumInfo<T>.Convert(iValue, out newEnumValue) == false) return false; enumValue = newEnumValue; return true; } public static T Increment<T>(T enumValue, int increment, T enumMin, T enumMax) where T : struct, IConvertible { int iValue = (int)(object)enumValue + increment; // Clamp if ((int)(object)enumMin > iValue) return enumMin; else if ((int)(object)enumMax < iValue) return enumMax; T newEnumValue; if (EnumInfo<T>.Convert(iValue, out newEnumValue) == false) return enumValue; return newEnumValue; } public static bool Contains<T>(T enumValue, T flag) where T : struct, IConvertible { try { Type underlyingType = EnumInfo<T>.UnderlyingType; if (underlyingType == typeof(ulong)) return (Convert.ToUInt64(enumValue) & Convert.ToUInt64(flag)) == Convert.ToUInt64(flag); if (underlyingType == typeof(uint)) return (Convert.ToUInt32(enumValue) & Convert.ToUInt32(flag)) == Convert.ToUInt32(flag); if (underlyingType == typeof(int)) return (Convert.ToInt32(enumValue) & Convert.ToInt32(flag)) == Convert.ToInt32(flag); if (underlyingType == typeof(Int64)) return (Convert.ToInt64(enumValue) & Convert.ToInt64(flag)) == Convert.ToInt64(flag); } catch { return false; } return false; } public static void Toggle<T>(ref T enumValue, T flag, bool toggled) where T : struct, IConvertible { if (toggled) enumValue = (T)Enum.Parse(typeof(T), (Convert.ToInt64(enumValue) | Convert.ToInt64(flag)).ToString()); else enumValue = (T)Enum.Parse(typeof(T), (Convert.ToInt64(enumValue) & ~Convert.ToInt64(flag)).ToString()); } } }
0
0.785996
1
0.785996
game-dev
MEDIA
0.220081
game-dev
0.97639
1
0.97639
OreCruncher/DynamicSurroundings
6,724
src/main/java/org/orecruncher/dsurround/client/weather/Weather.java
/* * This file is part of Dynamic Surroundings, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher, Abastro * * 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.orecruncher.dsurround.client.weather; import javax.annotation.Nonnull; import org.orecruncher.dsurround.ModInfo; import org.orecruncher.dsurround.ModOptions; import org.orecruncher.dsurround.capabilities.dimension.DimensionInfo; import org.orecruncher.dsurround.client.sound.Sounds; import org.orecruncher.dsurround.client.weather.tracker.ServerDrivenTracker; import org.orecruncher.dsurround.client.weather.tracker.SimulationTracker; import org.orecruncher.dsurround.client.weather.tracker.Tracker; import org.orecruncher.dsurround.event.WeatherUpdateEvent; import org.orecruncher.dsurround.registry.RegistryManager; import org.orecruncher.lib.math.MathStuff; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.world.World; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class Weather { private static final SoundEvent VANILLA_RAIN = RegistryManager.SOUND.getSound(new ResourceLocation("weather.rain")); public enum Properties { //@formatter:off VANILLA, NONE(0.0F, "calm"), CALM(0.125F, "calm"), LIGHT(0.25F, "light"), GENTLE(0.365F, "gentle"), MODERATE(0.5F, "moderate"), HEAVY(0.625F, "heavy"), STRONG(0.75F, "strong"), INTENSE(0.875F, "intense"), TORRENTIAL(1.0F, "torrential"); //@formatter:on private final float level; private final ResourceLocation rainTexture; private final ResourceLocation snowTexture; private final ResourceLocation dustTexture; Properties() { this.level = -10.0F; this.rainTexture = new ResourceLocation("textures/environment/rain.png"); this.snowTexture = new ResourceLocation("textures/environment/snow.png"); this.dustTexture = new ResourceLocation(ModInfo.RESOURCE_ID, "textures/environment/dust_calm.png"); } Properties(final float level, @Nonnull final String intensity) { this.level = level; this.rainTexture = new ResourceLocation(ModInfo.RESOURCE_ID, String.format("textures/environment/rain_%s.png", intensity)); this.snowTexture = new ResourceLocation(ModInfo.RESOURCE_ID, String.format("textures/environment/snow_%s.png", intensity)); this.dustTexture = new ResourceLocation(ModInfo.RESOURCE_ID, String.format("textures/environment/dust_%s.png", intensity)); } public float getLevel() { return this.level; } @Nonnull public ResourceLocation getRainTexture() { return this.rainTexture; } @Nonnull public ResourceLocation getDustTexture() { return this.dustTexture; } @Nonnull public ResourceLocation getSnowTexture() { return this.snowTexture; } @Nonnull public SoundEvent getStormSound() { return ModOptions.rain.useVanillaRainSound ? VANILLA_RAIN : Sounds.RAIN; } @Nonnull public SoundEvent getDustSound() { return Sounds.DUST; } public static Properties mapRainStrength(float str) { Properties result; // If the level is Vanilla it means that // the rainfall in the dimension is to be // that of Vanilla. if (str == Properties.VANILLA.getLevel()) { result = Properties.VANILLA; } else { str = MathStuff.clamp(str, DimensionInfo.MIN_INTENSITY, DimensionInfo.MAX_INTENSITY); result = Properties.NONE; for (int i = 0; i < Properties.values().length; i++) { final Properties p = Properties.values()[i]; if (str <= p.getLevel()) { result = p; break; } } } return result; } } // Start with the VANILLA storm tracker private static Tracker tracker = new SimulationTracker(); private static World getWorld() { return Minecraft.getMinecraft().world; } public static boolean isRaining() { return tracker.isRaining(); } public static boolean isThundering() { return tracker.isThundering(); } @Nonnull public static Properties getWeatherProperties() { return tracker.getWeatherProperties(); } public static float getIntensityLevel() { return tracker.getIntensityLevel(); } public static float getMaxIntensityLevel() { return tracker.getMaxIntensityLevel(); } public static int getNextRainChange() { return tracker.getNextRainChange(); } public static float getThunderStrength() { return tracker.getThunderStrength(); } public static int getNextThunderChange() { return tracker.getNextThunderChange(); } public static int getNextThunderEvent() { return tracker.getNextThunderEvent(); } public static float getCurrentVolume() { return tracker.getCurrentVolume(); } @Nonnull public static SoundEvent getCurrentStormSound() { return tracker.getCurrentStormSound(); } public static boolean notDoVanilla() { return !tracker.doVanilla(); } public static void update() { tracker.update(); } @SubscribeEvent public static void onWeatherUpdateEvent(@Nonnull final WeatherUpdateEvent event) { final World world = getWorld(); if (world == null || world.provider == null) return; if (world.provider.getDimension() != event.dimId) return; if (tracker instanceof ServerDrivenTracker) ((ServerDrivenTracker) tracker).update(event); } public static void register(final boolean serverAvailable) { if (serverAvailable) tracker = new ServerDrivenTracker(); } public static void unregister() { tracker = new SimulationTracker(); } @Nonnull public static String diagnostic() { return tracker.toString(); } }
0
0.931118
1
0.931118
game-dev
MEDIA
0.906517
game-dev
0.979947
1
0.979947
ProjectIgnis/CardScripts
3,377
unofficial/c511001202.lua
--スピード・キング☆スカル・フレイム (Anime) --Supersonic Skull Flame (Anime) local s,id=GetID() function s.initial_effect(c) --Special Summon this card local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) --Special Summon 1 "Skull Flame" from your Graveyard local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCost(s.spcost) e2:SetTarget(s.sptg) e2:SetOperation(s.spop) c:RegisterEffect(e2) --Inflict 400 damage for each "Burning Skull Head" in your Graveyard local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,1)) e3:SetCategory(CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetTarget(s.damtg) e3:SetOperation(s.damop) c:RegisterEffect(e3) end s.listed_names={99899504,26293219} function s.cfilter(c,tp) return c:IsCode(99899504) and c:IsAbleToRemoveAsCost() and aux.SpElimFilter(c,true) end function s.condition(e,c) if c==nil then return true end local tp=c:GetControler() local g=Duel.GetMatchingGroup(s.cfilter,tp,LOCATION_GRAVE|LOCATION_MZONE,0,nil,tp) return aux.SelectUnselectGroup(g,e,tp,1,1,aux.ChkfMMZ(1),0) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,c) local g=Duel.GetMatchingGroup(s.cfilter,tp,LOCATION_GRAVE|LOCATION_MZONE,0,nil,tp) local rg=aux.SelectUnselectGroup(g,e,tp,1,1,aux.ChkfMMZ(1),1,tp,HINTMSG_REMOVE,nil,nil,true) if #rg>0 then rg:KeepAlive() e:SetLabelObject(rg) return true end return false end function s.operation(e,tp,eg,ep,ev,re,r,rp,c) local rg=e:GetLabelObject() if not rg then return end Duel.Remove(rg,POS_FACEUP,REASON_COST) rg:DeleteGroup() end function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function s.spfilter(c,e,tp) return c:IsCode(99899504) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetMZoneCount(tp,e:GetHandler())>0 and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE) end function s.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) if #g>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsCode,tp,LOCATION_GRAVE,0,1,nil,26293219) end local dam=Duel.GetMatchingGroupCount(Card.IsCode,tp,LOCATION_GRAVE,0,nil,26293219)*400 Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(dam) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,dam) end function s.damop(e,tp,eg,ep,ev,re,r,rp) local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local d=Duel.GetMatchingGroupCount(Card.IsCode,tp,LOCATION_GRAVE,0,nil,26293219)*400 Duel.Damage(p,d,REASON_EFFECT) end
0
0.879397
1
0.879397
game-dev
MEDIA
0.995659
game-dev
0.957257
1
0.957257
PEAKModding/PEAKLib
3,203
src/PEAKLib.Core/ContentRegistry.cs
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace PEAKLib.Core; /// <summary> /// A content registry which can be used for finding out which mod content /// belong to which mod. /// </summary> public static class ContentRegistry { internal static readonly Dictionary<IContent, IRegisteredContent> s_RegisteredContent = []; /// <summary> /// Registers <typeparamref name="T"/> <paramref name="modContent"/> /// with <see cref="ContentRegistry"/>. /// </summary> /// <remarks> /// This doesn't register the content with the game. /// You should only use this if you are implementing a new <see cref="IContent"/> /// type for PEAKLib. /// </remarks> /// <typeparam name="T">The mod content type.</typeparam> /// <param name="modContent">The mod content.</param> /// <param name="owner">The owner of the content.</param> /// <returns>The registered <typeparamref name="T"/> representation.</returns> public static RegisteredContent<T> Register<T>(T modContent, ModDefinition owner) where T : IContent<T> => new(modContent, owner); /// <summary> /// Checks if <paramref name="modContent"/> is registered. /// </summary> /// <param name="modContent">The <see cref="IContent"/> to check for registration.</param> /// <returns>Whether or not <paramref name="modContent"/> is registered.</returns> public static bool IsRegistered(this IContent modContent) => s_RegisteredContent.ContainsKey(modContent.Resolve()); /// <summary> /// Tries to get the <see cref="RegisteredContent{T}"/> of /// <typeparamref name="T"/> <paramref name="modContent"/> /// if it has been registered. /// </summary> /// <inheritdoc cref="TryResolveAndGetRegisteredContent{T}(T, out IRegisteredContent?)"/> public static bool TryGetRegisteredContent<T>( this T modContent, [NotNullWhen(true)] out RegisteredContent<T>? registeredContent ) where T : IContent<T> { registeredContent = default; if (!s_RegisteredContent.TryGetValue(modContent, out var registered)) { return false; } registeredContent = (RegisteredContent<T>)registered; return true; } /// <summary> /// Tries to get the <see cref="IRegisteredContent"/> of /// <typeparamref name="T"/> <paramref name="modContent"/> /// if it has been registered. /// </summary> /// <typeparam name="T">The mod content type.</typeparam> /// <param name="modContent">The mod content.</param> /// <param name="registeredContent">The found registered mod content.</param> /// <returns>Whether or not <paramref name="modContent"/> was registered.</returns> public static bool TryResolveAndGetRegisteredContent<T>( this T modContent, [NotNullWhen(true)] out IRegisteredContent? registeredContent ) where T : IContent { registeredContent = default; if (!s_RegisteredContent.TryGetValue(modContent.Resolve(), out var registered)) { return false; } registeredContent = registered; return true; } }
0
0.517106
1
0.517106
game-dev
MEDIA
0.639247
game-dev
0.545935
1
0.545935
PixelGuy123/New-Baldis-Basics-Times
3,386
CustomContent/CustomItems/ITM_ToiletPaper.cs
using UnityEngine; using BBTimes.Extensions; using BBTimes.CustomComponents; using PixelInternalAPI.Classes; using PixelInternalAPI.Extensions; using BBTimes.Manager; namespace BBTimes.CustomContent.CustomItems { public class ITM_ToiletPaper : Item, IEntityTrigger, IItemPrefab { public void SetupPrefab() { var sprs = this.GetSpriteSheet(4, 2, 30f, "toiletpaper.png"); var renderer = ObjectCreationExtensions.CreateSpriteBillboard(sprs[0]); var rendererBase = renderer.transform; animComp = renderer.gameObject.AddComponent<AnimationComponent>(); animComp.animation = sprs; animComp.speed = 14.5f; animComp.renderers = [renderer]; rendererBase.SetParent(transform); rendererBase.localPosition = Vector3.zero; gameObject.layer = LayerStorage.standardEntities; entity = gameObject.CreateEntity(2f, 2f, rendererBase); entity.SetGrounded(false); audMan = gameObject.CreatePropagatedAudioManager(95, 115); audThrow = BBTimesManager.man.Get<SoundObject>("audGenericThrow"); audHit = BBTimesManager.man.Get<SoundObject>("audGenericPunch"); this.renderer = rendererBase; } public void SetupPrefabPost() { } public string Name { get; set; } public string TexturePath => this.GenerateDataPath("items", "Textures"); public string SoundPath => this.GenerateDataPath("items", "Audios"); public ItemObject ItmObj { get; set; } public override bool Use(PlayerManager pm) { owner = pm.gameObject; this.pm = pm; dir = Singleton<CoreGameManager>.Instance.GetCamera(pm.playerNumber).transform.forward; animComp.Initialize(pm.ec); entity.Initialize(pm.ec, pm.transform.position); ec = pm.ec; audMan.PlaySingle(audThrow); height = entity.BaseHeight; return true; } public void EntityTriggerEnter(Collider other) { if (other.gameObject == owner) return; if (other.isTrigger) { var e = other.GetComponent<Entity>(); if (e) { dir = (other.transform.position - transform.position).normalized; e.AddForce(new(dir, 35f, -20f)); speed *= 0.3f; velocityY = 0.7f * heightIncreaseFactor; heightIncreaseFactor *= 0.97f; heightDecreaseFactor *= 1.03f; audMan.PlaySingle(audHit); if (other.gameObject != pm.gameObject) pm.RuleBreak("Bullying", 2f, 0.8f); } } } public void EntityTriggerStay(Collider other) { } public void EntityTriggerExit(Collider other) { if (owner == other.gameObject) owner = null; // left owner's } void Update() { entity.UpdateInternalMovement(dir * ec.EnvironmentTimeScale * speed); velocityY -= heightDecreaseFactor * ec.EnvironmentTimeScale * Time.deltaTime; height += velocityY * 0.1f * Time.timeScale; if (height > 4f) { height = 4f; velocityY = 0f; } renderer.transform.localPosition = Vector3.up * height; if (height <= -4.9f) Destroy(gameObject); } GameObject owner; EnvironmentController ec; Vector3 dir; float speed = 35f; float height = 0f, heightDecreaseFactor = 1.015f, heightIncreaseFactor = 0.92f, velocityY = 0.03f; [SerializeField] internal PropagatedAudioManager audMan; [SerializeField] internal AnimationComponent animComp; [SerializeField] internal SoundObject audThrow, audHit; [SerializeField] internal Transform renderer; [SerializeField] internal Entity entity; } }
0
0.812482
1
0.812482
game-dev
MEDIA
0.979542
game-dev
0.96681
1
0.96681
panda3d/panda3d
1,770
panda/src/mathutil/finiteBoundingVolume.h
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file finiteBoundingVolume.h * @author drose * @date 1999-10-02 */ #ifndef FINITEBOUNDINGVOLUME_H #define FINITEBOUNDINGVOLUME_H #include "pandabase.h" #include "geometricBoundingVolume.h" /** * A special kind of GeometricBoundingVolume that is known to be finite. It * is possible to query this kind of volume for its minimum and maximum * extents. */ class EXPCL_PANDA_MATHUTIL FiniteBoundingVolume : public GeometricBoundingVolume { PUBLISHED: virtual LPoint3 get_min() const=0; virtual LPoint3 get_max() const=0; virtual PN_stdfloat get_volume() const; MAKE_PROPERTY(min, get_min); MAKE_PROPERTY(max, get_max); MAKE_PROPERTY(volume, get_volume); public: virtual const FiniteBoundingVolume *as_finite_bounding_volume() const; protected: virtual bool around_lines(const BoundingVolume **first, const BoundingVolume **last); virtual bool around_planes(const BoundingVolume **first, const BoundingVolume **last); public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { GeometricBoundingVolume::init_type(); register_type(_type_handle, "FiniteBoundingVolume", GeometricBoundingVolume::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() {init_type(); return get_class_type();} private: static TypeHandle _type_handle; }; #endif
0
0.889666
1
0.889666
game-dev
MEDIA
0.477434
game-dev
0.785798
1
0.785798
AK-Saigyouji/Procedural-Cave-Generator
3,940
Project/Scripts/CaveGeneration/Cave/Additional Structure/CollisionTester.cs
/* This class offers methods for testing whether objects will intersect the walls of a cave. Its primary purpose is to allow placing content at run-time without knowing ahead of time the structure of a cave. To this end it supports various tests for collision which are optimized to allow thousands of executions per frame. To achieve this performance, collisions use axis-aligned bounding boxes (AABB), represented in Unity by the Bounds struct. These are found on every mesh and collider, and can also be built independently, offering good flexibility and performance at the expense of some accuracy for objects not shaped like boxes parallel to the axes. Note that we use the efficient primitives from the FloorTester class as the basis behind the functionality in this class. */ using UnityEngine; using AKSaigyouji.MeshGeneration; namespace AKSaigyouji.CaveGeneration { public sealed class CollisionTester { FloorTester tester; internal CollisionTester(FloorTester tester) { this.tester = tester; } /// <summary> /// Will the box fit in the cave without intersecting any walls? Box is specified by its four coordinates. /// </summary> /// <param name="x1">Either the leftmost or rightmost x coordinate of the box.</param> /// <param name="x2">The other x coordinate of the box.</param> /// <param name="z1">Either the leftmost or rightmost z coordinate of the box.</param> /// <param name="z2">The other z coordinate of the box.</param> public bool CanFitBox(float x1, float x2, float z1, float z2) { return tester.CanFitBox(x1, x2, z1, z2); } /// <summary> /// Tests whether the object will fit within the walls of the cave at the given position, using the /// gameObject's MeshRenderer component. /// </summary> /// <param name="gameObject">The game object to be placed. Must have a MeshRenderer component.</param> /// <param name="position">The location for the object to be placed.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentException"></exception> public bool CanFitObject(GameObject gameObject, Vector3 position) { Bounds bounds = ExtractBounds(gameObject); return CanFitBoundingBox(bounds, position); } /// <summary> /// Can the bounding box fit within the walls at the given position? Uses the Bound's size, but not /// its center - uses the position instead. /// </summary> /// <param name="bounds">Specificies a bounding box.</param> /// <param name="position">Test position - will attempt to center the object at this position.</param> public bool CanFitBoundingBox(Bounds bounds, Vector3 position) { Vector3 extents = bounds.extents; float left = position.x - extents.x; float right = position.x + extents.x; float bot = position.z - extents.z; float top = position.z + extents.z; return CanFitBox(left, right, bot, top); } /// <summary> /// Does the cave have a floor at these coordinates? Out of range coordinates return false. /// </summary> public bool IsFloor(float x, float z) { return tester.IsFloor(x, z); } static Bounds ExtractBounds(GameObject gameObject) { if (gameObject == null) throw new System.ArgumentNullException("gameObject"); MeshRenderer meshRenderer = gameObject.GetComponent<MeshRenderer>(); if (meshRenderer == null) throw new System.ArgumentException("Must have MeshRenderer component.", "gameObject"); return meshRenderer.bounds; } } }
0
0.822951
1
0.822951
game-dev
MEDIA
0.863594
game-dev
0.766792
1
0.766792
cadaver/turso3d
2,630
Turso3D/Object/Event.h
// For conditions of distribution and use, see copyright notice in License.txt #pragma once #include "AutoPtr.h" #include "Ptr.h" #include <vector> class Event; /// Internal helper class for invoking event handler functions. class EventHandler { public: /// Construct with receiver object pointer. EventHandler(RefCounted* receiver); /// Destruct. virtual ~EventHandler(); /// Invoke the handler function. Implemented by subclasses. virtual void Invoke(Event& event) = 0; /// Return the receiver object. RefCounted* Receiver() const { return receiver; } protected: /// Receiver object. WeakPtr<RefCounted> receiver; }; /// Template implementation of the event handler invoke helper, stores a function pointer of specific class. template <class T, class U> class EventHandlerImpl : public EventHandler { public: typedef void (T::*HandlerFunctionPtr)(U&); /// Construct with receiver and function pointers. EventHandlerImpl(RefCounted* receiver_, HandlerFunctionPtr function_) : EventHandler(receiver_), function(function_) { assert(function); } /// Invoke the handler function. void Invoke(Event& event) override { T* typedReceiver = static_cast<T*>(receiver); U& typedEvent = static_cast<U&>(event); (typedReceiver->*function)(typedEvent); } private: /// Pointer to the event handler function. HandlerFunctionPtr function; }; /// Notification and data passing mechanism, to which objects can subscribe by specifying a handler function. Subclass to include event-specific data. class Event { public: /// Construct. Event(); /// Destruct. virtual ~Event(); /// Send the event. void Send(RefCounted* sender); /// Subscribe to the event. The event takes ownership of the handler data. If there is already handler data for the same receiver, it is overwritten. void Subscribe(EventHandler* handler); /// Unsubscribe from the event. void Unsubscribe(RefCounted* receiver); /// Return whether has at least one valid receiver. bool HasReceivers() const; /// Return whether has a specific receiver. bool HasReceiver(const RefCounted* receiver) const; /// Return current sender. RefCounted* Sender() const { return currentSender; } private: /// Prevent copy construction. Event(const Event& rhs); /// Prevent assignment. Event& operator = (const Event& rhs); /// Event handlers. std::vector<AutoPtr<EventHandler> > handlers; /// Current sender. WeakPtr<RefCounted> currentSender; };
0
0.847032
1
0.847032
game-dev
MEDIA
0.124111
game-dev
0.682939
1
0.682939
Dimbreath/AzurLaneData
2,275
zh-TW/view/activity/panels/ptawardwindow.lua
slot0 = class("PtAwardWindow") function slot0.Ctor(slot0, slot1, slot2) slot0._tf = slot1 slot0.binder = slot2 slot0.UIlist = UIItemList.New(slot0._tf:Find("window/panel/list"), slot0._tf:Find("window/panel/list/item")) slot0.ptTF = slot0._tf:Find("window/pt") slot0.totalTxt = slot0._tf:Find("window/pt/Text"):GetComponent(typeof(Text)) slot0.totalTitleTxt = slot0._tf:Find("window/pt/title"):GetComponent(typeof(Text)) slot0.closeBtn = slot0._tf:Find("window/top/btnBack") onButton(slot0.binder, slot0._tf, function () uv0:Hide() end, SFX_PANEL) onButton(slot0.binder, slot0.closeBtn, function () uv0:Hide() end, SFX_PANEL) end function slot1(slot0, slot1, slot2, slot3) slot0.UIlist:make(function (slot0, slot1, slot2) if slot0 == UIItemList.EventUpdate then slot3 = uv0[slot1 + 1] setText(slot2:Find("title/Text"), "PHASE " .. slot1 + 1) setText(slot2:Find("target/Text"), uv1[slot1 + 1]) setText(slot2:Find("target/title"), HXSet.hxLan(uv2.resTitle)) updateDrop(slot2:Find("award"), { type = slot3[1], id = slot3[2], count = slot3[3] }, { hideName = true }) onButton(uv2.binder, slot2:Find("award"), function () uv0.binder:emit(BaseUI.ON_DROP, uv1) end, SFX_PANEL) setActive(slot2:Find("award/mask"), slot1 + 1 <= uv3) end end) slot0.UIlist:align(#slot1) end function slot0.Show(slot0, slot1) slot2 = slot1.dropList slot3 = slot1.targets slot4 = slot1.level slot5 = slot1.count slot8 = slot1.type == 3 and "" or pg.item_data_statistics[id2ItemId(slot1.resId)].name if slot7 == 2 then slot0.cntTitle = i18n("pt_total_count", i18n("pt_cosume", slot8)) slot0.resTitle = i18n("pt_count", i18n("pt_cosume", slot8)) elseif slot7 == 3 then slot0.cntTitle = i18n("pt_ship_now") slot0.resTitle = i18n("pt_ship_goal") else slot0.cntTitle = i18n("pt_total_count", slot8) slot0.resTitle = i18n("pt_count", slot8) end uv0(slot0, slot2, slot3, slot4) slot0.totalTxt.text = slot5 slot0.totalTitleTxt.text = HXSet.hxLan(slot0.cntTitle) Canvas.ForceUpdateCanvases() setActive(slot0._tf, true) end function slot0.Hide(slot0) setActive(slot0._tf, false) end function slot0.Dispose(slot0) slot0:Hide() removeOnButton(slot0._tf) removeOnButton(slot0.closeBtn) end return slot0
0
0.534689
1
0.534689
game-dev
MEDIA
0.901396
game-dev
0.886356
1
0.886356
Neo-Mind/WARP
3,363
Scripts/Patches/AllowSpaceInGName.qjs
/**************************************************************************\ * * * Copyright (C) 2013-2024 Shakto * * * * This file is a part of WARP project (specific to RO clients) * * * * WARP 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/>. * * * * * |**************************************************************************| * * * Author(s) : Shakto * * Created Date : 2020-11-11 * * Last Modified : 2024-08-08 * * * \**************************************************************************/ /// /// \brief Make client Ignore the character check result of space in Guild names inside CGameMode::SendMsg /// AllowSpaceInGName = function(_) { $$(_, 1.1, `Find the character check`) let code = PUSH(0x20) //push 20h + PUSH_R //push regB + CALL(R32) //call regA; MSVCR#.strchr + ADD(ESP, 8) //add esp, 8 + TEST(EAX, EAX) //test eax, eax ; let addr = Exe.FindHex(code); if (addr < 0 && Exe.BuildDate > 20190000) { code = code.replace(CALL(R32), CALL(POS3WC)); //change to 'call <func#1>' which does the comparison addr = Exe.FindHex(code); } if (addr < 0) throw Error("Character check not found"); $$(_, 1.2, `Set addr to location after TEST`) addr += code.byteCount(); $$(_, 2, `Overwrite conditional jump after TEST (NOP out JNE / change JZ to JMP)`) const ins = Instr.FromAddr(addr); if (ins.Codes[0] === 0x74 || (ins.Codes[0] === 0x0F && ins.Codes[1] === 0x84)) { Exe.SetJMP(addr); //Change JE to JMP } else if (ins.Codes[0] === 0x75 || (ins.Codes[0] === 0x0F && ins.Codes[1] === 0x85)) { Exe.SetNOPs(addr, ins.Size); //NOP out the JNE } else { throw Error("No JMP formats found"); } return true; }; /// /// \brief Disable for old clients /// AllowSpaceInGName.validate = () => Exe.BuildDate >= 20120207;
0
0.753509
1
0.753509
game-dev
MEDIA
0.770443
game-dev
0.917092
1
0.917092
MergHQ/CRYENGINE
17,606
Code/CryEngine/CryAction/IActionMapManager.h
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Action Map Manager interfaces. ------------------------------------------------------------------------- History: - 8:9:2004 10:20 : Created by Mrcio Martins - 15:9:2010 12:30 : Revised by Dean Claassen *************************************************************************/ #ifndef __IACTIONMAPMANAGER_H__ #define __IACTIONMAPMANAGER_H__ #if _MSC_VER > 1000 #pragma once #endif #include <CryInput/IInput.h> #include <CryEntitySystem/IEntitySystem.h> #include <CryString/CryName.h> // CCryName #include <CryCore/smartptr.h> typedef CCryName ActionId; struct SInputEvent; // Summary // Enumeration all all the possible activation mode used for the actions enum EActionActivationMode // Value for onpress, onrelease, onhold must match EInputState { eAAM_Invalid = 0, eAAM_OnPress = BIT(0), // Used when the action key is pressed eAAM_OnRelease = BIT(1), // Used when the action key is released eAAM_OnHold = BIT(2), // Used when the action key is held eAAM_Always = BIT(3), // Special modifiers. eAAM_Retriggerable = BIT(4), eAAM_NoModifiers = BIT(5), eAAM_ConsoleCmd = BIT(6), eAAM_AnalogCompare = BIT(7), // Used when analog compare op succeeds }; // Summary // Input blocking action to perform when input is triggered enum EActionInputBlockType { eAIBT_None = 0, eAIBT_BlockInputs, eAIBT_Clear, }; struct SActionInputBlocker { // Summary: // Data used to block input symbol from firing event if matched SActionInputBlocker() : keyId(eKI_Unknown) { } SActionInputBlocker(const EKeyId keyId_) : keyId(keyId_) { } SActionInputBlocker& operator=(const SActionInputBlocker& rhs) { keyId = rhs.keyId; return *this; } EKeyId keyId; // External id for fast comparison. }; typedef DynArray<SActionInputBlocker> TActionInputBlockers; // Summary // Input blocking data struct SActionInputBlockData { SActionInputBlockData() : blockType(eAIBT_None) , fBlockDuration(0.0f) , activationMode(eAAM_Invalid) , deviceIndex(0) , bAllDeviceIndices(true) { } EActionInputBlockType blockType; TActionInputBlockers inputs; float fBlockDuration; int activationMode; uint8 deviceIndex; // Device index - controller 1/2 etc bool bAllDeviceIndices; // True to block all device indices of deviceID type, otherwise uses deviceIndex }; enum EActionFilterType { eAFT_ActionPass, eAFT_ActionFail, }; enum EActionInputDevice { eAID_Unknown = 0, eAID_KeyboardMouse = BIT(0), eAID_XboxPad = BIT(1), eAID_PS4Pad = BIT(2), eAID_OculusTouch = BIT(3), }; struct SActionInputDeviceData { SActionInputDeviceData(const EActionInputDevice type, const char* szTypeStr) : m_type(type) , m_typeStr(szTypeStr) { } EActionInputDevice m_type; CryFixedStringT<16> m_typeStr; }; //------------------------------------------------------------------------ struct IActionListener { virtual ~IActionListener(){} virtual void OnAction(const ActionId& action, int activationMode, float value) = 0; virtual void AfterAction() {}; }; typedef std::vector<IActionListener*> TActionListeners; // Blocking action listener (Improved, left old one to avoid huge refactor) //------------------------------------------------------------------------ struct IBlockingActionListener { virtual ~IBlockingActionListener(){} virtual bool OnAction(const ActionId& action, int activationMode, float value, const SInputEvent& inputEvent) = 0; virtual void AfterAction() {}; }; typedef std::shared_ptr<IBlockingActionListener> TBlockingActionListener; enum EActionAnalogCompareOperation { eAACO_None = 0, eAACO_Equals, eAACO_NotEquals, eAACO_GreaterThan, eAACO_LessThan, }; typedef CryFixedStringT<32> TActionInputString; struct SActionInput { SActionInput() : inputDevice(eAID_Unknown) , input("") , defaultInput("") , inputCRC(0) , fPressedTime(0.0f) , fPressTriggerDelay(0.0f) , fPressTriggerDelayRepeatOverride(-1.0f) , fLastRepeatTime(0.0f) , fAnalogCompareVal(0.0f) , fHoldTriggerDelay(0.0f) , fCurrentHoldValue(0.0f) , fReleaseTriggerThreshold(-1.0f) , fHoldRepeatDelay(0.0f) , fHoldTriggerDelayRepeatOverride(-1.0f) , activationMode(eAAM_Invalid) , iPressDelayPriority(0) , currentState(eIS_Unknown) , analogCompareOp(eAACO_None) , bHoldTriggerFired(false) , bAnalogConditionFulfilled(false) { } EActionInputDevice inputDevice; TActionInputString input; TActionInputString defaultInput; SActionInputBlockData inputBlockData; uint32 inputCRC; float fPressedTime; float fPressTriggerDelay; float fPressTriggerDelayRepeatOverride; float fLastRepeatTime; float fAnalogCompareVal; float fHoldTriggerDelay; float fCurrentHoldValue; // A normalized amount for the current hold before triggering at the hold delay. Is 1 when hold is hit, & it does not reset when repeating float fReleaseTriggerThreshold; float fHoldRepeatDelay; float fHoldTriggerDelayRepeatOverride; int activationMode; int iPressDelayPriority; // If priority is higher than the current EInputState currentState; EActionAnalogCompareOperation analogCompareOp; bool bHoldTriggerFired; bool bAnalogConditionFulfilled; void GetMemoryUsage(ICrySizer* pSizer) const { pSizer->AddObject(input); } }; //------------------------------------------------------------------------ struct IActionMapPopulateCallBack { virtual ~IActionMapPopulateCallBack(){} // Description: // Callback function to retrieve all action names // Use it in conjunction with IActionMapManager::EnumerateActions / IActionMapManager::GetActionsCount // Arguments: // pName - Name of one of the effects retrieved virtual void AddActionName(const char* const pName) = 0; }; struct IActionMapAction { virtual ~IActionMapAction(){} virtual void GetMemoryUsage(ICrySizer*) const = 0; virtual void Release() = 0; virtual int GetNumActionInputs() const = 0; virtual const SActionInput* FindActionInput(const char* szInput) const = 0; virtual const SActionInput* GetActionInput(const int iIndex) const = 0; virtual const SActionInput* GetActionInput(const EActionInputDevice device, const int iIndex) const = 0; virtual const ActionId& GetActionId() const = 0; virtual const char* GetTriggeredActionInput() const = 0; }; //------------------------------------------------------------------------ struct IActionMapActionIterator { virtual ~IActionMapActionIterator(){} virtual const IActionMapAction* Next() = 0; // Returns the same pointer every call, 0 if no more info available. virtual void AddRef() = 0; virtual void Release() = 0; }; typedef _smart_ptr<IActionMapActionIterator> IActionMapActionIteratorPtr; struct IActionMap { virtual ~IActionMap(){} virtual void GetMemoryUsage(ICrySizer*) const = 0; virtual void Release() = 0; virtual void Clear() = 0; virtual const IActionMapAction* GetAction(const ActionId& actionId) const = 0; virtual IActionMapAction* GetAction(const ActionId& actionId) = 0; virtual bool CreateAction(const ActionId& actionId) = 0; virtual bool RemoveAction(const ActionId& actionId) = 0; virtual int GetActionsCount() const = 0; virtual bool AddActionInput(const ActionId& actionId, const SActionInput& actionInput, const int iByDeviceIndex = -1) = 0; virtual bool AddAndBindActionInput(const ActionId& actionId, const SActionInput& actionInput) = 0; virtual bool RemoveActionInput(const ActionId& actionId, const char* szInput) = 0; virtual bool ReBindActionInput(const ActionId& actionId, const char* szCurrentInput, const char* szNewInput) = 0; virtual bool ReBindActionInput(const ActionId& actionId, const char* szNewInput, const EActionInputDevice device, const int iByDeviceIndex) = 0; virtual int GetNumRebindedInputs() = 0; virtual bool Reset() = 0; virtual bool LoadFromXML(const XmlNodeRef& actionMapNode) = 0; virtual bool LoadRebindingDataFromXML(const XmlNodeRef& actionMapNode) = 0; virtual bool SaveRebindingDataToXML(XmlNodeRef& actionMapNode) const = 0; virtual IActionMapActionIteratorPtr CreateActionIterator() = 0; virtual void SetActionListener(EntityId id) = 0; virtual EntityId GetActionListener() const = 0; virtual const char* GetName() = 0; virtual void Enable(bool enable) = 0; virtual bool Enabled() const = 0; }; //------------------------------------------------------------------------ struct IActionMapIterator { virtual ~IActionMapIterator(){} virtual IActionMap* Next() = 0; virtual void AddRef() = 0; virtual void Release() = 0; }; typedef _smart_ptr<IActionMapIterator> IActionMapIteratorPtr; //------------------------------------------------------------------------ struct IActionFilter { virtual ~IActionFilter(){} virtual void GetMemoryUsage(ICrySizer*) const = 0; virtual void Release() = 0; virtual void Filter(const ActionId& action) = 0; virtual bool SerializeXML(const XmlNodeRef& root, bool bLoading) = 0; virtual const char* GetName() = 0; virtual void Enable(bool enable) = 0; virtual bool Enabled() = 0; }; //------------------------------------------------------------------------ struct IActionFilterIterator { virtual ~IActionFilterIterator(){} virtual IActionFilter* Next() = 0; virtual void AddRef() = 0; virtual void Release() = 0; }; typedef _smart_ptr<IActionFilterIterator> IActionFilterIteratorPtr; struct SActionMapEvent { enum EActionMapManagerEvent { eActionMapManagerEvent_ActionMapsInitialized = 0, eActionMapManagerEvent_DefaultActionEntityChanged, eActionMapManagerEvent_FilterStatusChanged, eActionMapManagerEvent_ActionMapStatusChanged }; SActionMapEvent(EActionMapManagerEvent event, UINT_PTR wparam, UINT_PTR lparam = 0) : event(event), wparam(wparam), lparam(lparam) {} EActionMapManagerEvent event; UINT_PTR wparam; UINT_PTR lparam; }; struct IActionMapEventListener { virtual ~IActionMapEventListener() {}; virtual void OnActionMapEvent(const SActionMapEvent& event) = 0; }; //------------------------------------------------------------------------ struct IActionMapManager { virtual ~IActionMapManager(){} virtual void Update() = 0; virtual void Reset() = 0; virtual void Clear() = 0; virtual bool InitActionMaps(const char* filename) = 0; virtual void SetLoadFromXMLPath(const char* szPath) = 0; virtual const char* GetLoadFromXMLPath() const = 0; virtual bool LoadFromXML(const XmlNodeRef& node) = 0; virtual bool LoadRebindDataFromXML(const XmlNodeRef& node) = 0; virtual bool SaveRebindDataToXML(XmlNodeRef& node) = 0; virtual bool AddExtraActionListener(IActionListener* pExtraActionListener, const char* actionMap = NULL) = 0; virtual bool RemoveExtraActionListener(IActionListener* pExtraActionListener, const char* actionMap = NULL) = 0; virtual const TActionListeners& GetExtraActionListeners() const = 0; virtual void AddAlwaysActionListener(TBlockingActionListener pActionListener) = 0; virtual void RemoveAlwaysActionListener(TBlockingActionListener pActionListener) = 0; virtual void RemoveAllAlwaysActionListeners() = 0; virtual IActionMap* CreateActionMap(const char* name) = 0; virtual bool RemoveActionMap(const char* name) = 0; virtual void RemoveAllActionMaps() = 0; virtual IActionMap* GetActionMap(const char* name) = 0; virtual IActionFilter* CreateActionFilter(const char* name, EActionFilterType type) = 0; virtual IActionFilter* GetActionFilter(const char* name) = 0; virtual IActionMapIteratorPtr CreateActionMapIterator() = 0; virtual IActionFilterIteratorPtr CreateActionFilterIterator() = 0; virtual const SActionInput* GetActionInput(const char* actionMapName, const ActionId& actionId, const EActionInputDevice device, const int iByDeviceIndex) const = 0; virtual void Enable(const bool enable, const bool resetStateOnDisable = false) = 0; virtual void EnableActionMap(const char* name, bool enable) = 0; virtual void EnableFilter(const char* name, bool enable) = 0; virtual bool IsFilterEnabled(const char* name) = 0; virtual void ReleaseFilteredActions() = 0; virtual void ClearStoredCurrentInputData() = 0; virtual bool ReBindActionInput(const char* actionMapName, const ActionId& actionId, const char* szCurrentInput, const char* szNewInput) = 0; virtual int GetVersion() const = 0; virtual void SetVersion(int version) = 0; virtual void EnumerateActions(IActionMapPopulateCallBack* pCallBack) const = 0; virtual int GetActionsCount() const = 0; virtual int GetActionMapsCount() const = 0; virtual bool AddInputDeviceMapping(const EActionInputDevice deviceType, const char* szDeviceTypeStr) = 0; virtual bool RemoveInputDeviceMapping(const EActionInputDevice deviceType) = 0; virtual void ClearInputDevicesMappings() = 0; virtual int GetNumInputDeviceData() const = 0; virtual const SActionInputDeviceData* GetInputDeviceDataByIndex(const int iIndex) = 0; virtual const SActionInputDeviceData* GetInputDeviceDataByType(const EActionInputDevice deviceType) = 0; virtual const SActionInputDeviceData* GetInputDeviceDataByType(const char* szDeviceType) = 0; virtual void RemoveAllRefireData() = 0; virtual bool LoadControllerLayoutFile(const char* szLayoutKeyName) = 0; virtual EntityId GetDefaultActionEntity() const = 0; virtual void SetDefaultActionEntity(EntityId id, bool bUpdateAll = true) = 0; virtual void RegisterActionMapEventListener(IActionMapEventListener* pActionMapEventListener) = 0; virtual void UnregisterActionMapEventListener(IActionMapEventListener* pActionMapEventListener) = 0; }; template<class T> class TActionHandler { public: // Returns true if the action should also be forwarded to scripts typedef bool (T::* TOnActionHandler)(EntityId entityId, const ActionId& actionId, int activationMode, float value); // setup action handlers void AddHandler(const ActionId& actionId, TOnActionHandler fnHandler) { m_actionHandlers.insert(std::make_pair(actionId, fnHandler)); } size_t GetNumHandlers() const { return m_actionHandlers.size(); } // call action handler bool Dispatch(T* pThis, EntityId entityId, const ActionId& actionId, int activationMode, float value) { bool rVal = false; return Dispatch(pThis, entityId, actionId, activationMode, value, rVal); } // call action handler bool Dispatch(T* pThis, EntityId entityId, const ActionId& actionId, int activationMode, float value, bool& rVal) { rVal = false; TOnActionHandler fnHandler = GetHandler(actionId); if (fnHandler && pThis) { rVal = (pThis->*fnHandler)(entityId, actionId, activationMode, value); return true; } else return false; } // get action handler TOnActionHandler GetHandler(const ActionId& actionId) { typename TActionHandlerMap::iterator handler = m_actionHandlers.find(actionId); if (handler != m_actionHandlers.end()) { return handler->second; } return 0; } void Clear() { m_actionHandlers.clear(); } private: typedef std::multimap<ActionId, TOnActionHandler> TActionHandlerMap; TActionHandlerMap m_actionHandlers; }; #endif //__IACTIONMAPMANAGER_H__
0
0.941479
1
0.941479
game-dev
MEDIA
0.754647
game-dev
0.629773
1
0.629773
LiXizhi/NPLRuntime
9,165
Server/trunk/luabind-0.9/src/class.cpp
// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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. #define LUABIND_BUILDING #include <boost/foreach.hpp> #include <luabind/lua_include.hpp> #include <luabind/config.hpp> #include <luabind/class.hpp> #include <luabind/nil.hpp> #include <cstring> #include <iostream> namespace luabind { LUABIND_API detail::nil_type nil; } namespace luabind { namespace detail { namespace { struct cast_entry { cast_entry(class_id src, class_id target, cast_function cast) : src(src) , target(target) , cast(cast) {} class_id src; class_id target; cast_function cast; }; } // namespace unnamed struct class_registration : registration { class_registration(char const* name); void register_(lua_State* L) const; const char* m_name; mutable std::map<const char*, int, detail::ltstr> m_static_constants; typedef std::pair<type_id, cast_function> base_desc; mutable std::vector<base_desc> m_bases; type_id m_type; class_id m_id; class_id m_wrapper_id; type_id m_wrapper_type; std::vector<cast_entry> m_casts; scope m_scope; scope m_members; scope m_default_members; }; class_registration::class_registration(char const* name) { m_name = name; } void class_registration::register_(lua_State* L) const { LUABIND_CHECK_STACK(L); assert(lua_type(L, -1) == LUA_TTABLE); lua_pushstring(L, m_name); detail::class_rep* crep; detail::class_registry* r = detail::class_registry::get_registry(L); // create a class_rep structure for this class. // allocate it within lua to let lua collect it on // lua_close(). This is better than allocating it // as a static, since it will then be destructed // when the program exits instead. // warning: we assume that lua will not // move the userdata memory. lua_newuserdata(L, sizeof(detail::class_rep)); crep = reinterpret_cast<detail::class_rep*>(lua_touserdata(L, -1)); new(crep) detail::class_rep( m_type , m_name , L ); // register this new type in the class registry r->add_class(m_type, crep); lua_pushstring(L, "__luabind_class_map"); lua_rawget(L, LUA_REGISTRYINDEX); class_map& classes = *static_cast<class_map*>( lua_touserdata(L, -1)); lua_pop(L, 1); classes.put(m_id, crep); bool const has_wrapper = m_wrapper_id != registered_class<null_type>::id; if (has_wrapper) classes.put(m_wrapper_id, crep); crep->m_static_constants.swap(m_static_constants); detail::class_registry* registry = detail::class_registry::get_registry(L); crep->get_default_table(L); m_scope.register_(L); m_default_members.register_(L); lua_pop(L, 1); crep->get_table(L); m_members.register_(L); lua_pop(L, 1); lua_pushstring(L, "__luabind_cast_graph"); lua_gettable(L, LUA_REGISTRYINDEX); cast_graph* const casts = static_cast<cast_graph*>( lua_touserdata(L, -1)); lua_pop(L, 1); lua_pushstring(L, "__luabind_class_id_map"); lua_gettable(L, LUA_REGISTRYINDEX); class_id_map* const class_ids = static_cast<class_id_map*>( lua_touserdata(L, -1)); lua_pop(L, 1); class_ids->put(m_id, m_type); if (has_wrapper) class_ids->put(m_wrapper_id, m_wrapper_type); BOOST_FOREACH(cast_entry const& e, m_casts) { casts->insert(e.src, e.target, e.cast); } for (std::vector<base_desc>::iterator i = m_bases.begin(); i != m_bases.end(); ++i) { LUABIND_CHECK_STACK(L); // the baseclass' class_rep structure detail::class_rep* bcrep = registry->find_class(i->first); detail::class_rep::base_info base; base.pointer_offset = 0; base.base = bcrep; crep->add_base_class(base); // copy base class table crep->get_table(L); bcrep->get_table(L); lua_pushnil(L); while (lua_next(L, -2)) { lua_pushvalue(L, -2); // copy key lua_gettable(L, -5); if (!lua_isnil(L, -1)) { lua_pop(L, 2); continue; } lua_pop(L, 1); lua_pushvalue(L, -2); // copy key lua_insert(L, -2); lua_settable(L, -5); } lua_pop(L, 2); // copy base class detaults table crep->get_default_table(L); bcrep->get_default_table(L); lua_pushnil(L); while (lua_next(L, -2)) { lua_pushvalue(L, -2); // copy key lua_gettable(L, -5); if (!lua_isnil(L, -1)) { lua_pop(L, 2); continue; } lua_pop(L, 1); lua_pushvalue(L, -2); // copy key lua_insert(L, -2); lua_settable(L, -5); } lua_pop(L, 2); } lua_settable(L, -3); } // -- interface --------------------------------------------------------- class_base::class_base(char const* name) : scope(std::movable_auto_ptr<registration>( m_registration = new class_registration(name)) ) { } void class_base::init( type_id const& type_id_, class_id id , type_id const& wrapper_type, class_id wrapper_id) { m_registration->m_type = type_id_; m_registration->m_id = id; m_registration->m_wrapper_type = wrapper_type; m_registration->m_wrapper_id = wrapper_id; } void class_base::add_base(type_id const& base, cast_function cast) { m_registration->m_bases.push_back(std::make_pair(base, cast)); } void class_base::add_member(registration* member) { std::movable_auto_ptr<registration> ptr(member); m_registration->m_members.operator,(scope(ptr)); } void class_base::add_default_member(registration* member) { std::movable_auto_ptr<registration> ptr(member); m_registration->m_default_members.operator,(scope(ptr)); } const char* class_base::name() const { return m_registration->m_name; } void class_base::add_static_constant(const char* name, int val) { m_registration->m_static_constants[name] = val; } void class_base::add_inner_scope(scope& s) { m_registration->m_scope.operator,(s); } void class_base::add_cast( class_id src, class_id target, cast_function cast) { m_registration->m_casts.push_back(cast_entry(src, target, cast)); } void add_custom_name(type_id const& i, std::string& s) { s += " ["; s += i.name(); s += "]"; } std::string get_class_name(lua_State* L, type_id const& i) { std::string ret; assert(L); class_registry* r = class_registry::get_registry(L); class_rep* crep = r->find_class(i); if (crep == 0) { ret = "custom"; add_custom_name(i, ret); } else { /* TODO reimplement this? if (i == crep->holder_type()) { ret += "smart_ptr<"; ret += crep->name(); ret += ">"; } else if (i == crep->const_holder_type()) { ret += "smart_ptr<const "; ret += crep->name(); ret += ">"; } else*/ { ret += crep->name(); } } return ret; } }} // namespace luabind::detail
0
0.924107
1
0.924107
game-dev
MEDIA
0.387926
game-dev
0.841055
1
0.841055
qnpiiz/rich-2.0
5,918
src/main/java/net/minecraft/pathfinding/PathFinder.java
package net.minecraft.pathfinding; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import net.minecraft.entity.MobEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.Region; public class PathFinder { private final PathPoint[] pathOptions = new PathPoint[32]; private final int field_215751_d; private final NodeProcessor nodeProcessor; private final PathHeap path = new PathHeap(); public PathFinder(NodeProcessor p_i51280_1_, int p_i51280_2_) { this.nodeProcessor = p_i51280_1_; this.field_215751_d = p_i51280_2_; } @Nullable public Path func_227478_a_(Region p_227478_1_, MobEntity p_227478_2_, Set<BlockPos> p_227478_3_, float p_227478_4_, int p_227478_5_, float p_227478_6_) { this.path.clearPath(); this.nodeProcessor.func_225578_a_(p_227478_1_, p_227478_2_); PathPoint pathpoint = this.nodeProcessor.getStart(); Map<FlaggedPathPoint, BlockPos> map = p_227478_3_.stream().collect(Collectors.toMap((p_224782_1_) -> { return this.nodeProcessor.func_224768_a((double)p_224782_1_.getX(), (double)p_224782_1_.getY(), (double)p_224782_1_.getZ()); }, Function.identity())); Path path = this.func_227479_a_(pathpoint, map, p_227478_4_, p_227478_5_, p_227478_6_); this.nodeProcessor.postProcess(); return path; } @Nullable private Path func_227479_a_(PathPoint p_227479_1_, Map<FlaggedPathPoint, BlockPos> p_227479_2_, float p_227479_3_, int p_227479_4_, float p_227479_5_) { Set<FlaggedPathPoint> set = p_227479_2_.keySet(); p_227479_1_.totalPathDistance = 0.0F; p_227479_1_.distanceToNext = this.func_224776_a(p_227479_1_, set); p_227479_1_.distanceToTarget = p_227479_1_.distanceToNext; this.path.clearPath(); this.path.addPoint(p_227479_1_); Set<PathPoint> set1 = ImmutableSet.of(); int i = 0; Set<FlaggedPathPoint> set2 = Sets.newHashSetWithExpectedSize(set.size()); int j = (int)((float)this.field_215751_d * p_227479_5_); while (!this.path.isPathEmpty()) { ++i; if (i >= j) { break; } PathPoint pathpoint = this.path.dequeue(); pathpoint.visited = true; for (FlaggedPathPoint flaggedpathpoint : set) { if (pathpoint.func_224757_c(flaggedpathpoint) <= (float)p_227479_4_) { flaggedpathpoint.func_224764_e(); set2.add(flaggedpathpoint); } } if (!set2.isEmpty()) { break; } if (!(pathpoint.distanceTo(p_227479_1_) >= p_227479_3_)) { int k = this.nodeProcessor.func_222859_a(this.pathOptions, pathpoint); for (int l = 0; l < k; ++l) { PathPoint pathpoint1 = this.pathOptions[l]; float f = pathpoint.distanceTo(pathpoint1); pathpoint1.field_222861_j = pathpoint.field_222861_j + f; float f1 = pathpoint.totalPathDistance + f + pathpoint1.costMalus; if (pathpoint1.field_222861_j < p_227479_3_ && (!pathpoint1.isAssigned() || f1 < pathpoint1.totalPathDistance)) { pathpoint1.previous = pathpoint; pathpoint1.totalPathDistance = f1; pathpoint1.distanceToNext = this.func_224776_a(pathpoint1, set) * 1.5F; if (pathpoint1.isAssigned()) { this.path.changeDistance(pathpoint1, pathpoint1.totalPathDistance + pathpoint1.distanceToNext); } else { pathpoint1.distanceToTarget = pathpoint1.totalPathDistance + pathpoint1.distanceToNext; this.path.addPoint(pathpoint1); } } } } } Optional<Path> optional = !set2.isEmpty() ? set2.stream().map((p_224778_2_) -> { return this.func_224780_a(p_224778_2_.func_224763_d(), p_227479_2_.get(p_224778_2_), true); }).min(Comparator.comparingInt(Path::getCurrentPathLength)) : set.stream().map((p_224777_2_) -> { return this.func_224780_a(p_224777_2_.func_224763_d(), p_227479_2_.get(p_224777_2_), false); }).min(Comparator.comparingDouble(Path::func_224769_l).thenComparingInt(Path::getCurrentPathLength)); return !optional.isPresent() ? null : optional.get(); } private float func_224776_a(PathPoint p_224776_1_, Set<FlaggedPathPoint> p_224776_2_) { float f = Float.MAX_VALUE; for (FlaggedPathPoint flaggedpathpoint : p_224776_2_) { float f1 = p_224776_1_.distanceTo(flaggedpathpoint); flaggedpathpoint.func_224761_a(f1, p_224776_1_); f = Math.min(f1, f); } return f; } private Path func_224780_a(PathPoint p_224780_1_, BlockPos p_224780_2_, boolean p_224780_3_) { List<PathPoint> list = Lists.newArrayList(); PathPoint pathpoint = p_224780_1_; list.add(0, p_224780_1_); while (pathpoint.previous != null) { pathpoint = pathpoint.previous; list.add(0, pathpoint); } return new Path(list, p_224780_2_, p_224780_3_); } }
0
0.87071
1
0.87071
game-dev
MEDIA
0.511933
game-dev
0.90657
1
0.90657
Philos-Harak/nwn_content
3,477
PEPS WIP for Mobile v36/xx_pc_1_hb.nss
/*////////////////////////////////////////////////////////////////////////////// Script: xx_pc_1_hb Programmer: Philos //////////////////////////////////////////////////////////////////////////////// Player OnHeart beat script for PC AI; This will usually fire every 6 seconds (1 game round). */////////////////////////////////////////////////////////////////////////////// #include "0i_menus" void ai_ActionFollow(object oCreature, object oTarget) { if(!ai_GetAIMode(oCreature, AI_MODE_FOLLOW)) return; if(GetLocalInt(OBJECT_SELF, AI_CURRENT_ACTION_MODE) == AI_LAST_ACTION_MOVE) { float fDistance = GetDistanceBetween(oCreature, oTarget); float fFollowDistance = ai_GetFollowDistance(oCreature); if(fDistance > fFollowDistance && !ai_GetIsInCombat(oCreature)) { if(fDistance > fFollowDistance * 5.0) AssignCommand(oCreature, JumpToObject(oTarget)); else { ClearAllActions(); ActionMoveToObject(oTarget, TRUE, fFollowDistance); } } DelayCommand(1.0, ai_ActionFollow(oCreature, oTarget)); } } void main() { object oCreature = OBJECT_SELF; if(AI_DEBUG) ai_Debug("xx_pc_1_hb", "12", GetName(oCreature) + " heartbeat."); if(ai_GetIsBusy(oCreature) || ai_Disabled(oCreature)) return; if(ai_GetIsInCombat(oCreature)) { ai_DoAssociateCombatRound(oCreature); return; } if(ai_CheckForCombat(oCreature, FALSE)) return; if(IsInConversation(oCreature)) return; if(ai_TryHealing(oCreature, oCreature)) return; if(ai_CheckNearbyObjects(oCreature)) return; if(ai_GetAIMode(oCreature, AI_MODE_AGGRESSIVE_STEALTH)) { if(AI_DEBUG) ai_Debug("xx_ch_1_hb", "47", "Going into stealth mode!"); int nStealth = GetSkillRank(SKILL_HIDE, oCreature); nStealth += GetSkillRank(SKILL_MOVE_SILENTLY, oCreature); if(nStealth / 2 >= ai_GetCharacterLevels(oCreature)) { SetActionMode(oCreature, ACTION_MODE_STEALTH, TRUE); SetActionMode(oCreature, ACTION_MODE_DETECT, FALSE); } } else { SetActionMode(oCreature, ACTION_MODE_STEALTH, FALSE); if(ai_GetAIMode(oCreature, AI_MODE_AGGRESSIVE_SEARCH)) { if(AI_DEBUG) ai_Debug("xx_ch_1_hb", "61", "Going into search mode!"); SetActionMode(oCreature, ACTION_MODE_DETECT, TRUE); } else SetActionMode(oCreature, ACTION_MODE_DETECT, FALSE); } // Finally we check to make sure we are following. if(GetCurrentAction(oCreature) != ACTION_FOLLOW) { // Follow associate. object oAssociate = GetLocalObject(oCreature, AI_FOLLOW_TARGET); if(oAssociate == OBJECT_INVALID || GetMaster(oAssociate) != oCreature) return; if(GetDistanceBetween(oCreature, oAssociate) > ai_GetFollowDistance(oCreature)) { ai_ClearCreatureActions(); if(AI_DEBUG) ai_Debug("XX_pc_1_hb", "75", "Follow master: " + " Stealth: " + IntToString(ai_GetAIMode(oCreature, AI_MODE_AGGRESSIVE_STEALTH)) + " Search: " + IntToString(ai_GetAIMode(oCreature, AI_MODE_AGGRESSIVE_SEARCH))); SetLocalInt(oCreature, AI_CURRENT_ACTION_MODE, AI_LAST_ACTION_MOVE); ai_ActionFollow(oCreature, oAssociate); //ActionMoveToObject(oAssociate, TRUE, ai_GetFollowDistance(oCreature)); } } }
0
0.802926
1
0.802926
game-dev
MEDIA
0.980434
game-dev
0.948685
1
0.948685
FlameskyDexive/Legends-Of-Heroes
1,340
Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLinkBuilderConfig.cs
namespace DotRecast.Detour.Extras.Jumplink { public class JumpLinkBuilderConfig { public readonly float cellSize; public readonly float cellHeight; public readonly float agentClimb; public readonly float agentRadius; public readonly float groundTolerance; public readonly float agentHeight; public readonly float startDistance; public readonly float endDistance; public readonly float jumpHeight; public readonly float minHeight; public readonly float heightRange; public JumpLinkBuilderConfig(float cellSize, float cellHeight, float agentRadius, float agentHeight, float agentClimb, float groundTolerance, float startDistance, float endDistance, float minHeight, float maxHeight, float jumpHeight) { this.cellSize = cellSize; this.cellHeight = cellHeight; this.agentRadius = agentRadius; this.agentClimb = agentClimb; this.groundTolerance = groundTolerance; this.agentHeight = agentHeight; this.startDistance = startDistance; this.endDistance = endDistance; this.minHeight = minHeight; heightRange = maxHeight - minHeight; this.jumpHeight = jumpHeight; } } }
0
0.57769
1
0.57769
game-dev
MEDIA
0.874384
game-dev
0.900568
1
0.900568
dmm-com/vrlab-dvrsdk
4,687
DVRSDK/Assets/DVRSDK/Editor/PluginVersionChecker.cs
#if UNITY_EDITOR using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; namespace DVRSDK.Editor { [InitializeOnLoad] public class PluginVersionChecker : AssetPostprocessor { static PluginVersionChecker() { EditorApplication.wantsToQuit += Quit; UpdateDefineSymbols(); } private static List<string> InitializeSymbols() { var symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(';').ToList(); return symbols; } private static void UpdateDefineSymbols() { var symbols = InitializeSymbols(); var version = GetVRMVersion(); // Importer symbols.Remove("UNIVRM_0_68_IMPORTER"); symbols.Remove("UNIVRM_0_77_IMPORTER"); symbols.Remove("UNIVRM_0_78_1_IMPORTER"); symbols.Remove("UNIVRM_0_82_1_IMPORTER"); symbols.Remove("UNIVRM_LEGACY_IMPORTER"); symbols.Remove("UNIVRM_0_87_IMPORTER"); if (version.Value.major == 0 && version.Value.minor < 68) { symbols.Add("UNIVRM_LEGACY_IMPORTER"); } else if (version.Value.major == 0 && version.Value.minor < 77) { symbols.Add("UNIVRM_0_68_IMPORTER"); } else if (version.Value.major == 0 && version.Value.minor < 79 && version.Value.patch < 1) { symbols.Add("UNIVRM_0_77_IMPORTER"); } else if (version.Value.major == 0 && version.Value.minor < 83 && version.Value.patch < 1) { symbols.Add("UNIVRM_0_78_1_IMPORTER"); } else if (version.Value.major == 0 && version.Value.minor < 87) { symbols.Add("UNIVRM_0_82_1_IMPORTER"); } else { symbols.Add("UNIVRM_0_87_IMPORTER"); } // Exporter symbols.Remove("UNIVRM_0_71_EXPORTER"); symbols.Remove("UNIVRM_0_75_EXPORTER"); symbols.Remove("UNIVRM_0_79_EXPORTER"); symbols.Remove("UNIVRM_LEGACY_EXPORTER"); if (version.Value.major == 0 && version.Value.minor < 71) { symbols.Add("UNIVRM_LEGACY_EXPORTER"); } else if (version.Value.major == 0 && version.Value.minor < 75) { symbols.Add("UNIVRM_0_71_EXPORTER"); } else if (version.Value.major == 0 && version.Value.minor < 79) { symbols.Add("UNIVRM_0_75_EXPORTER"); } else { symbols.Add("UNIVRM_0_79_EXPORTER"); } PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", symbols)); EditorApplication.UnlockReloadAssemblies(); } private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string str in importedAssets) { if (str.Contains("VRMImporter")) { UpdateDefineSymbols(); } } } private static (int major, int minor, int patch)? GetVRMVersion() { var vrmVersionType = Type.GetType("VRM.VRMVersion"); if (vrmVersionType == null) vrmVersionType = Type.GetType("VRM.VRMVersion, VRM"); if (vrmVersionType != null) { int major = GetPublicConstantValue<int>(vrmVersionType, "MAJOR"); int minor = GetPublicConstantValue<int>(vrmVersionType, "MINOR"); int patch = GetPublicConstantValue<int>(vrmVersionType, "PATCH"); return (major, minor, patch); } else { return null; } } private static T GetPublicConstantValue<T>(Type type, string constantName) { return (T)type.GetField(constantName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).GetRawConstantValue(); } static bool Quit() { var symbols = InitializeSymbols(); PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", symbols)); return true; } } } #endif
0
0.802257
1
0.802257
game-dev
MEDIA
0.806035
game-dev
0.945399
1
0.945399
SammySemicolon/Malum-Mod
1,237
src/main/java/com/sammy/malum/core/handlers/enchantment/ReplenishingHandler.java
package com.sammy.malum.core.handlers.enchantment; import com.sammy.malum.registry.common.*; import com.sammy.malum.registry.common.enchantment.*; import net.minecraft.world.damagesource.*; import net.minecraft.world.entity.*; import net.minecraft.world.item.*; import team.lodestar.lodestone.registry.common.tag.*; import static com.sammy.malum.registry.common.enchantment.EnchantmentKeys.getEnchantmentLevel; public class ReplenishingHandler { public static void triggerReplenishing(DamageSource source, LivingEntity attacker, ItemStack stack) { if (!attacker.level().isClientSide) { if (source.is(LodestoneDamageTypeTags.CAN_TRIGGER_MAGIC)) { int level = getEnchantmentLevel(attacker.level(), EnchantmentKeys.REPLENISHING, stack); if (level > 0) { float chance = 0.4f * level; while (chance > 0) { if (chance >= 1 || attacker.getRandom().nextFloat() < chance) { attacker.getData(MalumAttachmentTypes.STAFF_ABILITIES).reduceStaffChargeDebt(attacker); } chance--; } } } } } }
0
0.791453
1
0.791453
game-dev
MEDIA
0.967735
game-dev
0.950453
1
0.950453
google/dawn
10,113
src/dawn/wire/client/EventManager.cpp
// Copyright 2023 The Dawn & Tint Authors // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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. #ifdef UNSAFE_BUFFERS_BUILD // TODO(crbug.com/439062058): Remove this and convert code to safer constructs. #pragma allow_unsafe_buffers #endif #include <map> #include <optional> #include <span> #include <utility> #include <vector> #include "dawn/wire/client/EventManager.h" #include "dawn/common/Log.h" #include "dawn/common/Time.h" #include "dawn/wire/client/Client.h" namespace dawn::wire::client { // TrackedEvent TrackedEvent::TrackedEvent(WGPUCallbackMode mode) : mMode(mode) {} TrackedEvent::~TrackedEvent() { DAWN_ASSERT(mEventState == EventState::Complete); } WGPUCallbackMode TrackedEvent::GetCallbackMode() const { return mMode; } bool TrackedEvent::IsReady() const { return mEventState == EventState::Ready; } void TrackedEvent::SetReady() { DAWN_ASSERT(mEventState != EventState::Complete); mEventState = EventState::Ready; } void TrackedEvent::Complete(FutureID futureID, EventCompletionType type) { // If the callback is already in a running state, that means that the std::call_once below is // already running on some thread. Normally |Complete| is not called re-entrantly, however, in // the case when a callback may drop the last reference to the Instance, because we only remove // the Event from the tracking list after the callback is completed, the teardown of the // EventManager will cause us to re-iterate all events and call |Complete| again on this one // with EventCompletionType::Shutdown. In that case, we don't want to call the std::call_once // below because it would cause a self-deadlock. During shutdown, it's not as important that // |Complete| waits until the callback completes, and instead we rely on the destructor's ASSERT // to ensure the invariant. if (type == EventCompletionType::Shutdown && mEventState == EventState::Running) { return; } std::call_once(mFlag, [&]() { mEventState = EventState::Running; CompleteImpl(futureID, type); mEventState = EventState::Complete; }); } // EventManager EventManager::EventManager(size_t timedWaitAnyMaxCount) : mTimedWaitAnyMaxCount(timedWaitAnyMaxCount) {} EventManager::~EventManager() { TransitionTo(State::ClientDropped); } std::pair<FutureID, bool> EventManager::TrackEvent(Ref<TrackedEvent>&& event) { if (!ValidateCallbackMode(event->GetCallbackMode())) { dawn::ErrorLog() << "Invalid callback mode: " << event->GetCallbackMode(); return {kNullFutureID, false}; } FutureID futureID = mNextFutureID++; switch (mState) { case State::InstanceDropped: { if (event->GetCallbackMode() != WGPUCallbackMode_AllowSpontaneous) { event->Complete(futureID, EventCompletionType::Shutdown); return {futureID, false}; } break; } case State::ClientDropped: { event->Complete(futureID, EventCompletionType::Shutdown); return {futureID, false}; } case State::Nominal: break; } mTrackedEvents.Use([&](auto trackedEvents) { auto [it, inserted] = trackedEvents->emplace(futureID, std::move(event)); DAWN_ASSERT(inserted); }); return {futureID, true}; } void EventManager::TransitionTo(EventManager::State state) { // If the client is disconnected, this becomes a no-op. if (mState == State::ClientDropped) { return; } // Only forward state transitions are allowed. DAWN_ASSERT(state > mState); mState = state; while (true) { EventMap events; switch (state) { case State::InstanceDropped: { mTrackedEvents.Use([&](auto trackedEvents) { for (auto it = trackedEvents->begin(); it != trackedEvents->end();) { auto& event = it->second; if (event->GetCallbackMode() != WGPUCallbackMode_AllowSpontaneous) { events.emplace(it->first, std::move(event)); it = trackedEvents->erase(it); } else { ++it; } } }); break; } case State::ClientDropped: { mTrackedEvents.Use([&](auto trackedEvents) { events = std::move(*trackedEvents); }); break; } case State::Nominal: // We always start in the nominal state so we should never be transitioning to it. DAWN_UNREACHABLE(); } if (events.empty()) { break; } for (auto& [futureID, event] : events) { event->Complete(futureID, EventCompletionType::Shutdown); } } } void EventManager::ProcessPollEvents() { std::vector<std::pair<FutureID, Ref<TrackedEvent>>> eventsToComplete; mTrackedEvents.ConstUse([&](auto trackedEvents) { for (auto& [futureID, event] : *trackedEvents) { WGPUCallbackMode callbackMode = event->GetCallbackMode(); if ((callbackMode == WGPUCallbackMode_AllowProcessEvents || callbackMode == WGPUCallbackMode_AllowSpontaneous) && event->IsReady()) { eventsToComplete.emplace_back(futureID, event); } } }); // Since events were initially stored and iterated from an ordered map, they must be ordered. for (auto& [futureID, event] : eventsToComplete) { event->Complete(futureID, EventCompletionType::Ready); } mTrackedEvents.Use([&](auto trackedEvents) { for (auto& [futureID, _] : eventsToComplete) { trackedEvents->erase(futureID); } }); } namespace { bool UpdateAnyCompletedOrReady(std::span<WGPUFutureWaitInfo> waitInfos, const EventManager::EventMap& allEvents, EventManager::EventMap* eventsToComplete) { DAWN_ASSERT(eventsToComplete->empty()); bool anyCompleted = false; for (auto& waitInfo : waitInfos) { auto it = allEvents.find(waitInfo.future.id); if (it == allEvents.end()) { waitInfo.completed = true; anyCompleted = true; continue; } auto& event = it->second; if (event->IsReady()) { waitInfo.completed = true; anyCompleted = true; eventsToComplete->emplace(it->first, event); } } DAWN_ASSERT(eventsToComplete->empty() || anyCompleted); return anyCompleted; } } // anonymous namespace WGPUWaitStatus EventManager::WaitAny(size_t count, WGPUFutureWaitInfo* infos, uint64_t timeoutNS) { if (timeoutNS > 0) { if (mTimedWaitAnyMaxCount == 0) { dawn::ErrorLog() << "Instance only supports timed wait anys if " "WGPUInstanceFeatureName_TimedWaitAny is enabled."; return WGPUWaitStatus_Error; } if (count > mTimedWaitAnyMaxCount) { dawn::ErrorLog() << "Instance only supports up to (" << mTimedWaitAnyMaxCount << ") timed wait anys."; return WGPUWaitStatus_Error; } } if (count == 0) { return WGPUWaitStatus_Success; } // Since the user can specify the FutureIDs in any order, we need to use another ordered map // here to ensure that the result is ordered for JS event ordering. auto waitInfos = std::span(infos, count); EventMap eventsToComplete; bool anyCompleted = mTrackedEvents.ConstUse([&](auto trackedEvents) { if (UpdateAnyCompletedOrReady(waitInfos, *trackedEvents, &eventsToComplete)) { return true; } if (timeoutNS > 0) { return trackedEvents.WaitFor(Nanoseconds(timeoutNS), [&](const EventMap& events) { return UpdateAnyCompletedOrReady(waitInfos, events, &eventsToComplete); }); } return false; }); for (auto& [futureID, event] : eventsToComplete) { // .completed has already been set to true (before the callback, per API contract). event->Complete(futureID, EventCompletionType::Ready); } mTrackedEvents.Use([&](auto trackedEvents) { for (auto& [futureID, _] : eventsToComplete) { trackedEvents->erase(futureID); } }); return anyCompleted ? WGPUWaitStatus_Success : WGPUWaitStatus_TimedOut; } } // namespace dawn::wire::client
0
0.971142
1
0.971142
game-dev
MEDIA
0.23568
game-dev
0.989371
1
0.989371
ForeignGods/Animated-Line-Renderer
4,986
Library/PackageCache/com.unity.render-pipelines.core@10.8.1/Editor/Volume/VolumeProfileFactory.cs
using UnityEngine; using UnityEditor.ProjectWindowCallback; using System.IO; using UnityEngine.Rendering; using UnityEngine.SceneManagement; namespace UnityEditor.Rendering { /// <summary> /// A utility class to create Volume Profiles and components. /// </summary> public static class VolumeProfileFactory { [MenuItem("Assets/Create/Volume Profile", priority = 201)] static void CreateVolumeProfile() { ProjectWindowUtil.StartNameEditingIfProjectWindowExists( 0, ScriptableObject.CreateInstance<DoCreatePostProcessProfile>(), "New Volume Profile.asset", null, null ); } /// <summary> /// Creates a <see cref="VolumeProfile"/> Asset and saves it at the given path. /// </summary> /// <param name="path">The path to save the Asset to, relative to the Project folder.</param> /// <returns>The newly created <see cref="VolumeProfile"/>.</returns> public static VolumeProfile CreateVolumeProfileAtPath(string path) { var profile = ScriptableObject.CreateInstance<VolumeProfile>(); profile.name = Path.GetFileName(path); AssetDatabase.CreateAsset(profile, path); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return profile; } /// <summary> /// Creates a <see cref="VolumeProfile"/> Asset and saves it in a folder next to the Scene. /// </summary> /// <param name="scene">The Scene to save the Profile next to.</param> /// <param name="targetName">A name to use for the Asset filename.</param> /// <returns>The newly created <see cref="VolumeProfile"/>.</returns> public static VolumeProfile CreateVolumeProfile(Scene scene, string targetName) { string path; if (string.IsNullOrEmpty(scene.path)) { path = "Assets/"; } else { var scenePath = Path.GetDirectoryName(scene.path); var extPath = scene.name; var profilePath = scenePath + Path.DirectorySeparatorChar + extPath; if (!AssetDatabase.IsValidFolder(profilePath)) { var directories = profilePath.Split(Path.DirectorySeparatorChar); string rootPath = ""; foreach (var directory in directories) { var newPath = rootPath + directory; if (!AssetDatabase.IsValidFolder(newPath)) AssetDatabase.CreateFolder(rootPath.TrimEnd(Path.DirectorySeparatorChar), directory); rootPath = newPath + Path.DirectorySeparatorChar; } } path = profilePath + Path.DirectorySeparatorChar; } path += targetName + " Profile.asset"; path = AssetDatabase.GenerateUniqueAssetPath(path); var profile = ScriptableObject.CreateInstance<VolumeProfile>(); AssetDatabase.CreateAsset(profile, path); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); return profile; } /// <summary> /// Creates a <see cref="VolumeComponent"/> in an existing <see cref="VolumeProfile"/>. /// </summary> /// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam> /// <param name="profile">The profile to store the new component in.</param> /// <param name="overrides">specifies whether to override the parameters in the component or not.</param> /// <param name="saveAsset">Specifies whether to save the Profile Asset or not. This is useful when you need to /// create several components in a row and only want to save the Profile Asset after adding the last one, /// because saving Assets to disk can be slow.</param> /// <returns></returns> public static T CreateVolumeComponent<T>(VolumeProfile profile, bool overrides = false, bool saveAsset = true) where T : VolumeComponent { var comp = profile.Add<T>(overrides); comp.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(comp, profile); if (saveAsset) { AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } return comp; } } class DoCreatePostProcessProfile : EndNameEditAction { public override void Action(int instanceId, string pathName, string resourceFile) { var profile = VolumeProfileFactory.CreateVolumeProfileAtPath(pathName); ProjectWindowUtil.ShowCreatedAsset(profile); } } }
0
0.872607
1
0.872607
game-dev
MEDIA
0.56475
game-dev
0.963822
1
0.963822
CrucibleMC/Crucible
1,430
patches/net/minecraftforge/common/ISpecialArmor.java.patch
--- ../src-base/minecraft/net/minecraftforge/common/ISpecialArmor.java +++ ../src-work/minecraft/net/minecraftforge/common/ISpecialArmor.java @@ -92,6 +92,11 @@ */ public static float ApplyArmor(EntityLivingBase entity, ItemStack[] inventory, DamageSource source, double damage) { + return ApplyArmor(entity, inventory, source, damage, true); + } + + public static float ApplyArmor(EntityLivingBase entity, ItemStack[] inventory, DamageSource source, double damage, boolean applyDamage) + { if (DEBUG) { System.out.println("Start: " + damage + " " + (damage * 25)); @@ -145,9 +150,12 @@ int itemDamage = (int)(absorb / 25D < 1 ? 1 : absorb / 25D); if (stack.getItem() instanceof ISpecialArmor) { - ((ISpecialArmor)stack.getItem()).damageArmor(entity, stack, source, itemDamage, prop.Slot); + if (applyDamage) + { + ((ISpecialArmor) stack.getItem()).damageArmor(entity, stack, source, itemDamage, prop.Slot); + } } - else + else if(applyDamage) { if (DEBUG) {
0
0.935934
1
0.935934
game-dev
MEDIA
0.993443
game-dev
0.787187
1
0.787187
Demonheadge/PokeScape
33,826
data/maps/Draynor_Manor_3F/scripts.inc
Draynor_Manor_3F_MapScripts:: map_script MAP_SCRIPT_ON_TRANSITION, Draynor_Manor_3F_MapScripts_MAP_SCRIPT_ON_TRANSITION .byte 0 Draynor_Manor_3F_MapScripts_MAP_SCRIPT_ON_TRANSITION: setvar VAR_EVOLUTION_MAP_STATE, 1 call DRAYNOR_MANOR_3F_STATE return DRAYNOR_MANOR_3F_STATE:: removeobject 6 removeobject 7 setflag FLAG_TEMP_18 setflag FLAG_TEMP_19 compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 4 goto_if_eq DRAYNOR_MANOR_3F_STATE_1 compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 6 goto_if_eq DRAYNOR_MANOR_3F_STATE_2 return DRAYNOR_MANOR_3F_STATE_1: addobject 6 clearflag FLAG_TEMP_18 setflag FLAG_TEMP_1D setflag FLAG_TEMP_1E setflag FLAG_TEMP_1F setflag FLAG_TEMP_1B removeobject 2 removeobject 3 removeobject 4 removeobject 5 return DRAYNOR_MANOR_3F_STATE_2: subquestmenu QUEST_MENU_CHECK_COMPLETE, QUEST_ERNEST_THE_CHICKEN, 3 compare VAR_RESULT, FALSE goto_if_eq DRAYNOR_MANOR_3F_STATE_5 return DRAYNOR_MANOR_3F_STATE_5: removeobject 5 setflag FLAG_TEMP_1B setobjectxyperm 6, 8, 17 addobject 6 clearflag FLAG_TEMP_18 return NPC_DraynorManor_Chicken_1:: lock faceplayer namebox NPC_DraynorManor_Chicken_1_Text_0 playmoncry SPECIES_ERNEST, 0 msgbox NPC_DraynorManor_Chicken_1_Text_1 waitmoncry hidenamebox closemessage namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Chicken_1_Text_3 hidenamebox closemessage release end NPC_DraynorManor_OddenstienLog:: msgbox NPC_DraynorManor_OddenstienLog_Text_0, MSGBOX_YESNO compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_OddenstienLog_2 NPC_DraynorManor_OddenstienLog_1: closemessage release end NPC_DraynorManor_OddenstienLog_2: msgbox NPC_DraynorManor_OddenstienLog_Text_1 msgbox NPC_DraynorManor_OddenstienLog_Text_2 msgbox NPC_DraynorManor_OddenstienLog_Text_3 msgbox NPC_DraynorManor_OddenstienLog_Text_4 msgbox NPC_DraynorManor_OddenstienLog_Text_5 msgbox NPC_DraynorManor_OddenstienLog_Text_6 msgbox NPC_DraynorManor_OddenstienLog_Text_7 msgbox NPC_DraynorManor_OddenstienLog_Text_8 goto NPC_DraynorManor_OddenstienLog_1 NPC_DraynorManor_Chicken_2:: lock faceplayer namebox NPC_DraynorManor_Chicken_1_Text_0 playmoncry SPECIES_ERNEST, 0 msgbox NPC_DraynorManor_Chicken_1_Text_1 waitmoncry hidenamebox closemessage compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 2 goto_if_eq NPC_DraynorManor_Chicken_2_2 NPC_DraynorManor_Chicken_2_1: release end NPC_DraynorManor_Chicken_2_2: msgbox NPC_DraynorManor_Chicken_2_Text_0 removeobject VAR_LAST_TALKED closemessage setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 3 goto NPC_DraynorManor_Chicken_2_1 ITEM_DRAYNORMANOR_FISHFOOD:: finditem ITEM_FISH_FOOD closemessage end ITEM_DRAYNORMANOR_OILCAN:: finditem ITEM_OIL_CAN closemessage subquestmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN, 0 end ITEM_DRAYNORMANOR_RUBBERTUBE:: finditem ITEM_RUBBER_TUBE closemessage subquestmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN, 1 end SCRIPT_DraynorManor_Poison:: msgbox SCRIPT_DraynorManor_Poison_Text_0 checkitem ITEM_FISH_FOOD, 1 compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Poison_2 closemessage end SCRIPT_DraynorManor_Poison_2: msgbox SCRIPT_DraynorManor_Poison_Text_1, MSGBOX_YESNO compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Poison_4 closemessage end SCRIPT_DraynorManor_Poison_4: msgbox SCRIPT_DraynorManor_Poison_Text_2 removeitem ITEM_FISH_FOOD giveitem ITEM_FISH_FOOD_POISONED closemessage call STORYMODE_STATE_DRAYNORMANOR_1F end SCRIPT_DraynorManor_Fountain:: compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 1 goto_if_eq SCRIPT_DraynorManor_Fountain_2 msgbox SCRIPT_DraynorManor_Fountain_Text_2 SCRIPT_DraynorManor_Fountain_1: closemessage checkitem ITEM_FISH_FOOD, 1 compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Fountain_6 checkitem ITEM_FISH_FOOD_POISONED, 1 compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Fountain_12 end SCRIPT_DraynorManor_Fountain_2: checkitem ITEM_PRESSURE_GAUGE, 1 compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Fountain_8 msgbox SCRIPT_DraynorManor_Fountain_Text_1 goto SCRIPT_DraynorManor_Fountain_1 SCRIPT_DraynorManor_Fountain_6: msgbox SCRIPT_DraynorManor_Fountain_Text_3, MSGBOX_YESNO compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Fountain_15 SCRIPT_DraynorManor_Fountain_14: closemessage release end SCRIPT_DraynorManor_Fountain_8: msgbox SCRIPT_DraynorManor_Fountain_Text_0 hidenamebox closemessage release end SCRIPT_DraynorManor_Fountain_12: msgbox SCRIPT_DraynorManor_Fountain_Text_6, MSGBOX_YESNO compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Fountain_17 closemessage end SCRIPT_DraynorManor_Fountain_15: msgbox SCRIPT_DraynorManor_Fountain_Text_4 msgbox SCRIPT_DraynorManor_Fountain_Text_5 goto SCRIPT_DraynorManor_Fountain_14 SCRIPT_DraynorManor_Fountain_17: msgbox SCRIPT_DraynorManor_Fountain_Text_4 removeitem ITEM_FISH_FOOD_POISONED finditem ITEM_PRESSURE_GAUGE closemessage subquestmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN, 2 end SCRIPT_DraynorManor_Gravestone:: msgbox SCRIPT_DraynorManor_Gravestone_Text_0 closemessage goto_if_unset FLAG_RECIEVED_EX_EX_PARROT, SCRIPT_DraynorManor_Gravestone_2 msgbox SCRIPT_DraynorManor_Gravestone_Text_6 closemessage end SCRIPT_DraynorManor_Gravestone_2: msgbox SCRIPT_DraynorManor_Gravestone_Text_1, MSGBOX_YESNO compare VAR_RESULT, TRUE goto_if_eq SCRIPT_DraynorManor_Gravestone_5 msgbox SCRIPT_DraynorManor_Gravestone_Text_5 closemessage end SCRIPT_DraynorManor_Gravestone_5: checkitem ITEM_MAGICAL_CAGE, 1 compare VAR_RESULT, 0 goto_if_ne SCRIPT_DraynorManor_Gravestone_8 msgbox SCRIPT_DraynorManor_Gravestone_Text_4 closemessage end SCRIPT_DraynorManor_Gravestone_8: msgbox SCRIPT_DraynorManor_Gravestone_Text_2 removeitem ITEM_MAGICAL_CAGE msgbox SCRIPT_DraynorManor_Gravestone_Text_3 call EventScript_DraynorManor_ExExParrot closemessage end SCRIPT_DraynorManor_FindCage:: msgbox SCRIPT_DraynorManor_FindCage_Text_0 goto_if_unset FLAG_RECIEVED_EX_EX_PARROT, SCRIPT_DraynorManor_FindCage_2 SCRIPT_DraynorManor_FindCage_1: msgbox SCRIPT_DraynorManor_FindCage_Text_1 closemessage end SCRIPT_DraynorManor_FindCage_2: checkitem ITEM_MAGICAL_CAGE, 1 compare VAR_RESULT, 0 goto_if_eq SCRIPT_DraynorManor_FindCage_4 goto SCRIPT_DraynorManor_FindCage_1 SCRIPT_DraynorManor_FindCage_4: closemessage giveitem ITEM_MAGICAL_CAGE, 1 closemessage end EventScript_DraynorManor_ExExParrot:: setvar VAR_TEMP_1, SPECIES_EXEXPARROT givemon SPECIES_EXEXPARROT, 5, ITEM_NONE compare VAR_RESULT, 0 goto_if_eq EventScript_DraynorManor_SendParty_ExExParrot compare VAR_RESULT, 1 goto_if_eq EventScript_DraynorManor_SendPC_ExExParrot goto Common_EventScript_NoMoreRoomForPokemon end EventScript_DraynorManor_SendParty_ExExParrot:: call EventScript_DraynorManor_ReceivedFanfare_ExExParrot msgbox EventScript_DraynorManor_SendParty_ExExParrot_Text_0, MSGBOX_YESNO compare VAR_RESULT, NO goto_if_eq EventScript_DraynorManor_Received_ExExParrot call Common_EventScript_GetGiftMonPartySlot call Common_EventScript_NameReceivedPartyMon goto EventScript_DraynorManor_Received_ExExParrot end EventScript_DraynorManor_SendPC_ExExParrot:: call EventScript_DraynorManor_ReceivedFanfare_ExExParrot msgbox EventScript_DraynorManor_SendParty_ExExParrot_Text_0, MSGBOX_YESNO compare VAR_RESULT, NO goto_if_eq EventScript_DraynorManor_TransferredToPC_ExExParrot call Common_EventScript_NameReceivedBoxMon goto EventScript_DraynorManor_TransferredToPC_ExExParrot end EventScript_DraynorManor_TransferredToPC_ExExParrot:: call Common_EventScript_TransferredToPC goto EventScript_DraynorManor_Received_ExExParrot end EventScript_DraynorManor_ReceivedFanfare_ExExParrot:: bufferspeciesname 1, SPECIES_EXEXPARROT playfanfare MUS_OBTAIN_ITEM msgbox EventScript_DraynorManor_ReceivedFanfare_ExExParrot_Text_0 waitmessage waitfanfare bufferspeciesname 0, SPECIES_EXEXPARROT return EventScript_DraynorManor_Received_ExExParrot:: subquestmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN, 4 setflag FLAG_RECIEVED_EX_EX_PARROT releaseall return NPC_DraynorManor_Oddenstein:: lock faceplayer switch VAR_POKESCAPE_ERNEST_QUEST_STATE case 0, NPC_DraynorManor_Oddenstein_2 case 1, NPC_DraynorManor_Oddenstein_3 case 2, NPC_DraynorManor_Oddenstein_4 case 3, NPC_DraynorManor_Oddenstein_5 case 4, NPC_DraynorManor_Oddenstein_6 case 5, NPC_DraynorManor_Oddenstein_7 case 6, NPC_DraynorManor_Oddenstein_8 return NPC_DraynorManor_Oddenstein_2: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_0 msgbox NPC_DraynorManor_Oddenstein_Text_1, MSGBOX_YESNO compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Oddenstein_9 msgbox NPC_DraynorManor_Oddenstein_Text_7 hidenamebox closemessage release end NPC_DraynorManor_Oddenstein_3: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_8, MSGBOX_YESNO compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Oddenstein_12 msgbox NPC_DraynorManor_Oddenstein_Text_7 hidenamebox release end NPC_DraynorManor_Oddenstein_4: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_13 hidenamebox closemessage release end NPC_DraynorManor_Oddenstein_5: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_14 closemessage hidenamebox fadenewbgm MUS_PS_KOUREND_CATACOMBS fadescreenswapbuffers FADE_TO_BLACK getplayerxy VAR_TEMP_1, VAR_TEMP_2 compare VAR_TEMP_2, 3 goto_if_eq NPC_DraynorManor_Oddenstein_16 compare VAR_TEMP_2, 4 goto_if_eq NPC_DraynorManor_Oddenstein_17 NPC_DraynorManor_Oddenstein_15: applymovement 1, movement_ENEREST_CHICKEN_QUEST_3 waitmovement 0 applymovement OBJ_EVENT_ID_PLAYER, movement_ENEREST_CHICKEN_QUEST_6 waitmovement OBJ_EVENT_ID_PLAYER setflag FLAG_TEMP_1D setflag FLAG_TEMP_1E setflag FLAG_TEMP_1F removeobject 2 removeobject 3 removeobject 4 removeobject 5 checkfollower compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Oddenstein_26 NPC_DraynorManor_Oddenstein_25: fadescreenswapbuffers FADE_FROM_BLACK special SpawnCameraObject applymovement OBJ_EVENT_ID_CAMERA, movement_ENEREST_CHICKEN_QUEST_5 waitmovement 0 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_15 closemessage hidenamebox applymovement 1, movement_ENEREST_CHICKEN_QUEST_7 waitmovement 0 addobject 7 clearflag FLAG_TEMP_19 delay 64 applymovement 1, movement_ENEREST_CHICKEN_QUEST_4 waitmovement 0 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_16 closemessage hidenamebox applymovement 1, movement_ENEREST_CHICKEN_QUEST_8 playse SE_BANG waitmovement 0 delay 10 applymovement 1, movement_ENEREST_CHICKEN_QUEST_8 playse SE_SELECT waitmovement 0 delay 10 applymovement 1, movement_ENEREST_CHICKEN_QUEST_8 playse SE_TRUCK_DOOR waitmovement 0 delay 30 applymovement 1, Movement_InteractFACEDOWN waitmovement 0 delay 64 fadeoutbgm 1 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_17 closemessage hidenamebox setvar VAR_0x8004, 1 @ vertical pan setvar VAR_0x8005, 1 @ horizontal pan setvar VAR_0x8006, 8 @ num shakes setvar VAR_0x8007, 3 @ shake delay special ShakeCamera waitstate setvar VAR_0x8004, 1 @ vertical pan setvar VAR_0x8005, 1 @ horizontal pan setvar VAR_0x8006, 8 @ num shakes setvar VAR_0x8007, 3 @ shake delay special ShakeCamera waitstate applymovement 7, movement_chickentransform delay 10 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_18 closemessage hidenamebox waitmovement 0 playse SE_ORB special DoOrbEffect delay 60 fadescreenswapbuffers FADE_TO_WHITE special FadeOutOrbEffect delay 120 setvar VAR_0x8004, 1 @ vertical pan setvar VAR_0x8005, 1 @ horizontal pan setvar VAR_0x8006, 8 @ num shakes setvar VAR_0x8007, 3 @ shake delay special ShakeCamera waitstate setvar VAR_0x8004, 1 @ vertical pan setvar VAR_0x8005, 1 @ horizontal pan setvar VAR_0x8006, 8 @ num shakes setvar VAR_0x8007, 3 @ shake delay special ShakeCamera waitstate delay 120 setflag FLAG_TEMP_19 clearflag FLAG_TEMP_18 addobject 6 removeobject 7 delay 32 fadescreenswapbuffers FADE_FROM_WHITE delay 30 applymovement 1, Movement_InteractFACELEFT waitmovement 0 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_19 closemessage hidenamebox applymovement OBJ_EVENT_ID_CAMERA, movement_ENEREST_CHICKEN_QUEST_9 waitmovement 0 special RemoveCameraObject fadeinbgm 1 setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 4 end NPC_DraynorManor_Oddenstein_6: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_20 closemessage hidenamebox release end NPC_DraynorManor_Oddenstein_7: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_21 questmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN hidenamebox giveitem ITEM_MINT_CAKE, 2 setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 6 closemessage hidenamebox namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_22 closemessage hidenamebox release end NPC_DraynorManor_Oddenstein_8: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_23 subquestmenu QUEST_MENU_CHECK_COMPLETE, QUEST_ERNEST_THE_CHICKEN, 4 compare VAR_RESULT, FALSE goto_if_eq NPC_DraynorManor_Oddenstein_21 compare VAR_RESULT, TRUE goto_if_eq NPC_DraynorManor_Oddenstein_22 NPC_DraynorManor_Oddenstein_20: hidenamebox closemessage release end NPC_DraynorManor_Oddenstein_9: hidenamebox startquest QUEST_ERNEST_THE_CHICKEN namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_3 msgbox NPC_DraynorManor_Oddenstein_Text_4 msgbox NPC_DraynorManor_Oddenstein_Text_5 msgbox NPC_DraynorManor_Oddenstein_Text_6 setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 1 hidenamebox closemessage release end NPC_DraynorManor_Oddenstein_12: msgbox NPC_DraynorManor_Oddenstein_Text_9 call CooksAssistant_Check_OilCan call CooksAssistant_Check_PressureGauge call CooksAssistant_Check_RubberTube namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_10 closemessage hidenamebox removeitem ITEM_OIL_CAN removeitem ITEM_PRESSURE_GAUGE removeitem ITEM_RUBBER_TUBE applymovement 1, MOVEMENT_DraynorManor_Oddenstein_1 waitmovement 0 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_11 closemessage hidenamebox applymovement 1, MOVEMENT_DraynorManor_Oddenstein_2 waitmovement 0 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox NPC_DraynorManor_Oddenstein_Text_12 closemessage hidenamebox hidenamebox closemessage setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 2 release end NPC_DraynorManor_Oddenstein_16: applymovement OBJ_EVENT_ID_PLAYER, movement_ENEREST_CHICKEN_QUEST_1 goto NPC_DraynorManor_Oddenstein_15 NPC_DraynorManor_Oddenstein_17: applymovement OBJ_EVENT_ID_PLAYER, movement_ENEREST_CHICKEN_QUEST_2 goto NPC_DraynorManor_Oddenstein_15 NPC_DraynorManor_Oddenstein_21: checkitem ITEM_MAGICAL_CAGE, 1 compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Oddenstein_28 msgbox NPC_DraynorManor_Oddenstein_Text_25 goto NPC_DraynorManor_Oddenstein_20 NPC_DraynorManor_Oddenstein_22: subquestmenu QUEST_MENU_CHECK_COMPLETE, QUEST_ERNEST_THE_CHICKEN, 3 compare VAR_RESULT, FALSE goto_if_eq NPC_DraynorManor_Oddenstein_32 subquestmenu QUEST_MENU_CHECK_COMPLETE, QUEST_ERNEST_THE_CHICKEN, 4 compare VAR_RESULT, TRUE goto_if_eq NPC_DraynorManor_Oddenstein_34 goto NPC_DraynorManor_Oddenstein_20 NPC_DraynorManor_Oddenstein_26: setobjectxy OBJ_EVENT_ID_FOLLOWER, 7, 3 applymovement OBJ_EVENT_ID_FOLLOWER, Movement_InteractFACEDOWN waitmovement 0 goto NPC_DraynorManor_Oddenstein_25 NPC_DraynorManor_Oddenstein_28: msgbox NPC_DraynorManor_Oddenstein_Text_24 goto NPC_DraynorManor_Oddenstein_20 NPC_DraynorManor_Oddenstein_32: msgbox NPC_DraynorManor_Oddenstein_Text_26 hidenamebox closemessage release end NPC_DraynorManor_Oddenstein_34: msgbox NPC_DraynorManor_Oddenstein_Text_27 goto NPC_DraynorManor_Oddenstein_20 EvilChickenBattleScript:: lock playmoncry SPECIES_EVILCHICKEN, 0 namebox EvilChickenBattleScript_Text_0 msgbox EvilChickenBattleScript_Text_1 waitmoncry closemessage setwildbattle SPECIES_EVILCHICKEN, 18, ITEM_NONE dowildbattle compare VAR_RESULT, B_OUTCOME_CAUGHT goto_if_eq EvilChickenBattleScript_2 EvilChickenBattleScript_1: compare VAR_RESULT, B_OUTCOME_WON goto_if_eq EvilChickenBattleScript_5 EvilChickenBattleScript_4: compare VAR_RESULT, B_OUTCOME_RAN goto_if_eq EvilChickenBattleScript_13 EvilChickenBattleScript_12: end EvilChickenBattleScript_2: fadescreenswapbuffers FADE_TO_BLACK removeobject VAR_LAST_TALKED compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 4 goto_if_eq EvilChickenBattleScript_8 compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 6 goto_if_eq EvilChickenBattleScript_9 EvilChickenBattleScript_7: fadescreenswapbuffers FADE_FROM_BLACK goto EvilChickenBattleScript_1 EvilChickenBattleScript_5: fadescreenswapbuffers FADE_TO_BLACK removeobject VAR_LAST_TALKED compare VAR_POKESCAPE_ERNEST_QUEST_STATE, 4 goto_if_eq EvilChickenBattleScript_16 EvilChickenBattleScript_15: fadescreenswapbuffers FADE_FROM_BLACK goto EvilChickenBattleScript_4 EvilChickenBattleScript_8: setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 5 subquestmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN, 3 goto EvilChickenBattleScript_7 EvilChickenBattleScript_9: subquestmenu QUEST_MENU_COMPLETE_QUEST, QUEST_ERNEST_THE_CHICKEN, 3 goto EvilChickenBattleScript_7 EvilChickenBattleScript_13: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox EvilChickenBattleScript_Text_2 closemessage hidenamebox release goto EvilChickenBattleScript_12 EvilChickenBattleScript_16: setvar VAR_POKESCAPE_ERNEST_QUEST_STATE, 5 goto EvilChickenBattleScript_15 movement_chickentransform: levitate face_left delay_16 delay_16 delay_16 delay_16 face_right delay_16 delay_16 delay_16 delay_16 face_down delay_16 delay_16 delay_16 delay_16 stop_levitate step_end MOVEMENT_DraynorManor_Oddenstein_1: walk_in_place_down walk_in_place_down walk_in_place_down step_end MOVEMENT_DraynorManor_Oddenstein_2: walk_in_place_down walk_in_place_down walk_in_place_down face_player step_end movement_ENEREST_CHICKEN_QUEST_1: face_down delay_16 delay_16 step_end movement_ENEREST_CHICKEN_QUEST_2: face_down lock_facing_direction walk_up unlock_facing_direction step_end movement_ENEREST_CHICKEN_QUEST_3: walk_left walk_left face_down face_down step_end movement_ENEREST_CHICKEN_QUEST_4: walk_right walk_right step_end movement_ENEREST_CHICKEN_QUEST_5: walk_slow_down walk_slow_down walk_slow_down step_end movement_ENEREST_CHICKEN_QUEST_6: delay_16 delay_16 walk_left walk_left walk_down step_end movement_ENEREST_CHICKEN_QUEST_7: walk_down walk_down step_end movement_ENEREST_CHICKEN_QUEST_8: walk_in_place_right step_end movement_ENEREST_CHICKEN_QUEST_9: walk_slow_up walk_slow_up walk_slow_up step_end CooksAssistant_Check_OilCan:: checkitem ITEM_OIL_CAN, 1 compare VAR_RESULT, 0 goto_if_eq CooksAssistant_Check_OilCan_1 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox CooksAssistant_Check_OilCan_Text_1 closemessage return CooksAssistant_Check_OilCan_1: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox CooksAssistant_Check_OilCan_Text_0 hidenamebox closemessage release end CooksAssistant_Check_PressureGauge:: checkitem ITEM_PRESSURE_GAUGE, 1 compare VAR_RESULT, 0 goto_if_eq CooksAssistant_Check_PressureGauge_1 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox CooksAssistant_Check_PressureGauge_Text_1 closemessage return CooksAssistant_Check_PressureGauge_1: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox CooksAssistant_Check_PressureGauge_Text_0 hidenamebox closemessage release end CooksAssistant_Check_RubberTube:: checkitem ITEM_RUBBER_TUBE, 1 compare VAR_RESULT, 0 goto_if_eq CooksAssistant_Check_RubberTube_1 namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox CooksAssistant_Check_RubberTube_Text_1 closemessage return CooksAssistant_Check_RubberTube_1: namebox NPC_DraynorManor_Chicken_1_Text_2 msgbox CooksAssistant_Check_RubberTube_Text_0 hidenamebox closemessage release end NPC_DraynorManor_Fisherman:: lock faceplayer namebox NPC_DraynorManor_Fisherman_Text_0 checkitem ITEM_PRESSURE_GAUGE, 1 compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Fisherman_2 checkitem ITEM_FISH_FOOD_POISONED, 1 compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Fisherman_5 checkitem ITEM_FISH_FOOD, 1 compare VAR_RESULT, 0 goto_if_ne NPC_DraynorManor_Fisherman_7 switch VAR_POKESCAPE_ERNEST_QUEST_STATE case 0, NPC_DraynorManor_Fisherman_11 case 1, NPC_DraynorManor_Fisherman_12 case 2, NPC_DraynorManor_Fisherman_13 case 3, NPC_DraynorManor_Fisherman_13 case 4, NPC_DraynorManor_Fisherman_13 return NPC_DraynorManor_Fisherman_2: msgbox NPC_DraynorManor_Fisherman_Text_1 hidenamebox closemessage release end NPC_DraynorManor_Fisherman_5: msgbox NPC_DraynorManor_Fisherman_Text_2 hidenamebox closemessage release end NPC_DraynorManor_Fisherman_7: msgbox NPC_DraynorManor_Fisherman_Text_3 hidenamebox closemessage release end NPC_DraynorManor_Fisherman_11: msgbox NPC_DraynorManor_Fisherman_Text_4 hidenamebox closemessage release end NPC_DraynorManor_Fisherman_12: msgbox NPC_DraynorManor_Fisherman_Text_5 hidenamebox closemessage release end NPC_DraynorManor_Fisherman_13: msgbox NPC_DraynorManor_Fisherman_Text_6 hidenamebox closemessage release end NPC_DraynorManor_Chicken_1_Text_0: .string "Chicken$" NPC_DraynorManor_Chicken_1_Text_1: .string "BWawkrk!$" NPC_DraynorManor_Chicken_1_Text_2: .string "Oddenstein$" NPC_DraynorManor_Chicken_1_Text_3: .string "I call that an Ernest Chicken!\p" .string "I named it this breed after its father.\p" .string "Basically I turned this guy called\n" .string "Ernest into a chicken, he laid some eggs\l" .string "and these chickens are what hatched\l" .string "from them.$" NPC_DraynorManor_OddenstienLog_Text_0: .string "It is Professor Oddenstien's Log book.\p" .string "Want to read it?$" NPC_DraynorManor_OddenstienLog_Text_1: .string "Log 1: I met a man named Ernest.\p" .string "This was perfect, before he could say a\n" .string "word I told him to be my assistant for\l" .string "my newest experiment.\p" .string "And it was a success I could now\n" .string "transform humans into chickens!\p" .string "With this I will never have a shortage\n" .string "of eggs for breakfast.$" NPC_DraynorManor_OddenstienLog_Text_2: .string "Log 2: Ernest seemed like he wanted to\n" .string "go outside so I opened a window.\p" .string "I wonder where he will go.$" NPC_DraynorManor_OddenstienLog_Text_3: .string "Log 3: An adventurer brought Ernest\n" .string "back to me and told me his fiancee\l" .string "wanted him turned back into a human.\p" .string "Does this mean I will no longer have\n" .string "eggs for breakfast?$" NPC_DraynorManor_OddenstienLog_Text_4: .string "Log 4: With Ernest gone only his eggs\n" .string "remain.\p" .string "I probably have enough supply for a\n" .string "week but I think I will need to find\l" .string "another assistant soon otherwise I will\l" .string "run out of eggs.$" NPC_DraynorManor_OddenstienLog_Text_5: .string "Log 5: Nooo!\p" .string "This is so unfortunate, the eggs have\n" .string "hatched!\p" .string "Now I must eat them before they hatch\n" .string "so I can have my breakfast.$" NPC_DraynorManor_OddenstienLog_Text_6: .string "Log 6: These are some weird-looking\n" .string "hybrid chickens.\p" .string "I think I will name them Ernest Chickens\n" .string "after thier father.$" NPC_DraynorManor_OddenstienLog_Text_7: .string "Log 7: I wonder what will happen if I\n" .string "turn these Ernest Chickens into\l" .string "humans…$" NPC_DraynorManor_OddenstienLog_Text_8: .string "End of log.$" NPC_DraynorManor_Chicken_2_Text_0: .string "You pick up the weird-looking chicken.$" SCRIPT_DraynorManor_Poison_Text_0: .string "You search the shelves…{PAUSE 15} …{PAUSE 15}\p" .string "You find a bunch of products labeled\n" .string "with a skull and bones.$" SCRIPT_DraynorManor_Poison_Text_1: .string "Would you like to mix it them with the\n" .string "Fish Food?$" SCRIPT_DraynorManor_Poison_Text_2: .string "You mix the poison in with the Fish\n" .string "Food.$" SCRIPT_DraynorManor_Fountain_Text_0: .string "There appears to be a lot of dead\n" .string "piranha in there.\p" .string "…{PAUSE 32}Oops.$" SCRIPT_DraynorManor_Fountain_Text_1: .string "You spot the Pressure Gauge among a\n" .string "school of piranhas.$" SCRIPT_DraynorManor_Fountain_Text_2: .string "There appears to be a lot of piranha in\n" .string "there.$" SCRIPT_DraynorManor_Fountain_Text_3: .string "Would you like to use FISH FOOD?$" SCRIPT_DraynorManor_Fountain_Text_4: .string "Seeing the piranhas in the fountain you\n" .string "throw the fish food into the fountain.$" SCRIPT_DraynorManor_Fountain_Text_5: .string "…{PAUSE 32}… They eat the food within seconds.\p" .string "Maybe something from the kitchen could\n" .string "help slow the piranhas down long enough\l" .string "to grab the pressure gauge.$" SCRIPT_DraynorManor_Fountain_Text_6: .string "Would you like to use FISH FOOD P++?$" SCRIPT_DraynorManor_Gravestone_Text_0: .string "It is a gravestone.\p" .string "It reads 'here lies Polly'.$" SCRIPT_DraynorManor_Gravestone_Text_1: .string "Would you like to dig up Polly?$" SCRIPT_DraynorManor_Gravestone_Text_2: .string "You dig up the corpse of an ex-parrot.\p" .string "You place the body in the cage.\p" .string "…{PAUSE 15} …{PAUSE 15} The cage begins to glow.$" SCRIPT_DraynorManor_Gravestone_Text_3: .string "The ex-parrot comes to life!$" SCRIPT_DraynorManor_Gravestone_Text_4: .string "You dig up the corpse of an ex-parrot.\p" .string "But have nowhere to put, so you bury it\n" .string "again.\p" .string "Maybe if you had a cage…$" SCRIPT_DraynorManor_Gravestone_Text_5: .string "You decide it is best to let Poly rest in\n" .string "peace.$" SCRIPT_DraynorManor_Gravestone_Text_6: .string "Looks like someone looted this grave.\p" .string "How could they…$" SCRIPT_DraynorManor_FindCage_Text_0: .string "You search through the shelves…$" SCRIPT_DraynorManor_FindCage_Text_1: .string "…{PAUSE 15}…{PAUSE 15} and find nothing!$" EventScript_DraynorManor_SendParty_ExExParrot_Text_0: .string "Would you like to give your monster a\n" .string "nickname?$" EventScript_DraynorManor_ReceivedFanfare_ExExParrot_Text_0: .string "{PLAYER} obtained a {STR_VAR_2}.$" NPC_DraynorManor_Oddenstein_Text_0: .string "Hello there, you seem to be an\n" .string "adventurer.\p" .string "You see, recently a human named Ernest\n" .string "was turned into a chicken.\p" .string "We managed to transform him back but\n" .string "not before he laid a bunch of eggs.\p" .string "Originally I thought nothing of it and\n" .string "was planning to have the eggs for\l" .string "breakfast tomorrow but they ended up\l" .string "hatching and now there are chicken all\l" .string "over the place.$" NPC_DraynorManor_Oddenstein_Text_1: .string "I've come up with a great idea involving\n" .string "the increasing number of chickens.\p" .string "But I need an assistant, can you help\n" .string "me with my experiment?$" NPC_DraynorManor_Oddenstein_Text_2: .string "I need a few items for my experiment to\n" .string "succeed can you go get me them?\p" .string "I need a Oil Can, Pressure Gauge and\n" .string "Rubber Tube.$" NPC_DraynorManor_Oddenstein_Text_3: .string "The Oil Can should be with Ava.\p" .string "She is in the room next to the living\n" .string "room.\p" .string "She loves puzzles so I'd imagine she\n" .string "would have hidden the door to her room\l" .string "behind a bookcase or something.$" NPC_DraynorManor_Oddenstein_Text_4: .string "I believe the last place I saw the\n" .string "Pressure Gauge being used was outside\l" .string "in the fountain.$" NPC_DraynorManor_Oddenstein_Text_5: .string "As I recall McBoneFace borrowed the\n" .string "Rubber Tube, he should be in his room.\p" .string "What he needed it for I have no idea.$" NPC_DraynorManor_Oddenstein_Text_6: .string "Alright off you go my assistant!\p" .string "I cannot do this experiment without\n" .string "those items!$" NPC_DraynorManor_Oddenstein_Text_7: .string "Shame.$" NPC_DraynorManor_Oddenstein_Text_8: .string "Have you found the parts?$" NPC_DraynorManor_Oddenstein_Text_9: .string "Let me check…$" NPC_DraynorManor_Oddenstein_Text_10: .string "It looks like you have everything!\p" .string "Allow me to take those off your hands.$" NPC_DraynorManor_Oddenstein_Text_11: .string "… {PAUSE 15}Just a few more adjustments…$" NPC_DraynorManor_Oddenstein_Text_12: .string "Done!\p" .string "Now all we need is one of those\n" .string "chickens.\p" .string "Can you go grab one for me.$" NPC_DraynorManor_Oddenstein_Text_13: .string "Don't be shy, I know they look weird but\n" .string "they are just chickens.\p" .string "Go pick one up and bring it over here to\n" .string "me.$" NPC_DraynorManor_Oddenstein_Text_14: .string "Perfect, thats an Ernest Chicken\n" .string "exactly what we needed!\p" .string "Stand back and let the experiment\n" .string "begin!$" NPC_DraynorManor_Oddenstein_Text_15: .string "Okay, first we place the chicken down.$" NPC_DraynorManor_Oddenstein_Text_16: .string "Then we press this button and fiddle\n" .string "with these doohickles…$" NPC_DraynorManor_Oddenstein_Text_17: .string "Wait!\n" .string "Something is wrong!$" NPC_DraynorManor_Oddenstein_Text_18: .string "Oh nooo!$" NPC_DraynorManor_Oddenstein_Text_19: .string "Drat my experiment has ended in\n" .string "failure!\p" .string "Let's call it there.\p" .string "Please dispose of the failed\n" .string "experiment.$" NPC_DraynorManor_Oddenstein_Text_20: .string "Please dispose of that chicken.$" NPC_DraynorManor_Oddenstein_Text_21: .string "Ah, thank you for disposing of that\n" .string "fowl creature.\p" .string "Despite my experiment ending in failure\n" .string "I would like you to have this.$" NPC_DraynorManor_Oddenstein_Text_22: .string "Thank you for your assistance with the\n" .string "experiment.$" NPC_DraynorManor_Oddenstein_Text_23: .string "Hello again {PLAYER}.$" NPC_DraynorManor_Oddenstein_Text_24: .string "Oh that's Polly's CAGE!\n" .string "I used to have a parrot named Polly.\p" .string "She loved that cage…\p" .string "She has sadly passed from this world\n" .string "and her grave now rests in the backyard\l" .string "of the manor…$" NPC_DraynorManor_Oddenstein_Text_25: .string "Oh by the way, have you seen a CAGE\n" .string "anywhere?\p" .string "I could have swore I left it in the room\n" .string "next to us somewhere but I haven't\l" .string "seen it in awhile.$" NPC_DraynorManor_Oddenstein_Text_26: .string "By the way, it appears that ever since\n" .string "we experimented on that chicken it\l" .string "appears to keep coming back.\p" .string "It would be great if you could get rid\n" .string "of it for me.$" NPC_DraynorManor_Oddenstein_Text_27: .string "OMFG I CANNOT BELIEVE THIS!\p" .string "SOMEONE DUG UP MY POOR POLLY!\p" .string "What kind of monster would disturb my\n" .string "poor Polly's rest!$" EvilChickenBattleScript_Text_0: .string "Evil Chicken$" EvilChickenBattleScript_Text_1: .string "BWAWWWK!\p" .string "BEGONE {PLAYER}!$" EvilChickenBattleScript_Text_2: .string "Don't listen to that failed experiment!\p" .string "Catch it or defeat it!\p" .string "Do something and get it out of my lab.$" CooksAssistant_Check_OilCan_Text_0: .string "You don't have the Oil Can.\p" .string "Check with Ava.\p" .string "She is in the room next to the living\n" .string "room.\p" .string "She loves puzzles so I'd imagine she\n" .string "would have hidden the door to her room\l" .string "behind a bookcase or something.$" CooksAssistant_Check_OilCan_Text_1: .string "You have the Oil Can!$" CooksAssistant_Check_PressureGauge_Text_0: .string "You don't have the Pressure Gauge.\p" .string "I believe the last place I saw that was\n" .string "outside in the fountain.$" CooksAssistant_Check_PressureGauge_Text_1: .string "You have the Pressure Gauge!$" CooksAssistant_Check_RubberTube_Text_0: .string "You don't have the Rubber Tube.\p" .string "As I recall McBoneFace borrowed it last.$" CooksAssistant_Check_RubberTube_Text_1: .string "You have the Rubber Tube!$" NPC_DraynorManor_Fisherman_Text_0: .string "Man$" NPC_DraynorManor_Fisherman_Text_1: .string "Why did you do that?\p" .string "I just wanted to fish for piranhas.$" NPC_DraynorManor_Fisherman_Text_2: .string "Hey, that fish food looks ominous.\p" .string "What are you planning to do?\p" .string "…{PAUSE 15}Murder the fish?$" NPC_DraynorManor_Fisherman_Text_3: .string "Where did you get that fish food from?\p" .string "Hopefully you didn't get it from the\n" .string "kitchen, there's a bunch of poisons in\l" .string "there.$" NPC_DraynorManor_Fisherman_Text_4: .string "Rumours say there is a rare fish called\n" .string "piranha in this fountain.$" NPC_DraynorManor_Fisherman_Text_5: .string "The fish are looking a bit hungry.\p" .string "I think I saw some fish food somewhere\n" .string "upstairs in that Manor.$" NPC_DraynorManor_Fisherman_Text_6: .string "The piranhas went extinct…$"
0
0.773271
1
0.773271
game-dev
MEDIA
0.928648
game-dev
0.684394
1
0.684394
GilbertoGojira/DOTS-Stackray
5,766
Packages/com.stackray.entities/Stackray.Entities.Editor/ComponentVisitor.cs
using System; using System.Linq; using System.Reflection; using Unity.Properties; using Unity.Properties.Adapters; using UnityEditor; namespace Stackray.Entities.Editor { class ComponentVisitor { interface IVisitor : IPropertyVisitorAdapter { void LoadValueMethod(MethodInfo method); void LoadClassMethod(MethodInfo method); void LoadClassMethodWithIndex(MethodInfo method); } class Visitor<T> : IVisitor, IVisit<T> { delegate void OnGUIDelegate(ref T value); delegate void OnGUIDelegateByClass(T value); delegate void OnGUIDelegateByClassWithIndex(T value, string index); OnGUIDelegate m_guiValueMethod; OnGUIDelegateByClass m_guiClassMethod; OnGUIDelegateByClassWithIndex m_guiClassMethodWithIndex; public void LoadValueMethod(MethodInfo method) { m_guiValueMethod = (OnGUIDelegate)Delegate.CreateDelegate(typeof(OnGUIDelegate), method); } public void LoadClassMethod(MethodInfo method) { m_guiClassMethod = (OnGUIDelegateByClass)Delegate.CreateDelegate(typeof(OnGUIDelegateByClass), null, method); } public void LoadClassMethodWithIndex(MethodInfo method) { m_guiClassMethodWithIndex = (OnGUIDelegateByClassWithIndex)Delegate.CreateDelegate(typeof(OnGUIDelegateByClassWithIndex), null, method); } public VisitStatus Visit<TContainer>(Property<TContainer, T> property, ref TContainer container, ref T value) { EditorGUI.BeginChangeCheck(); m_guiValueMethod?.Invoke(ref value); m_guiClassMethod?.Invoke(value); m_guiClassMethodWithIndex?.Invoke(value, property.Name); EditorGUI.EndChangeCheck(); return VisitStatus.Stop; } } public static bool TryGetAdapterForClass(Type componentType, out IPropertyVisitorAdapter visitor) { MethodInfo method = null; if (IsSubClassOfGeneric(componentType, typeof(BufferElementDataEditor<>))) method = componentType.GetMethods().SingleOrDefault( m => m.ReturnType == typeof(void) && m.Name == nameof(IComponentEditor<int>.OnInspectorGUI) && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType == typeof(string)); else method = componentType.GetMethods().SingleOrDefault( m => m.ReturnType == typeof(void) && m.Name == nameof(IComponentEditor<int>.OnInspectorGUI) && m.GetParameters().Length == 1); if (method != null) { var args = method.GetParameters(); var targetType = args[0].ParameterType; var result = (IVisitor)Activator.CreateInstance(typeof(Visitor<>).MakeGenericType(targetType)); if (args.Length == 1) result.LoadClassMethod(method); else if (args.Length == 2) result.LoadClassMethodWithIndex(method); visitor = result; return true; } visitor = null; return false; } public static bool TryGetAdapterForValue(Type componentType, out IPropertyVisitorAdapter visitor) { var method = componentType.GetMethod( nameof(IComponentEditor<int>.OnInspectorGUI), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (method != null && method.ReturnType == typeof(void)) { var args = method.GetParameters(); if (args.Length == 0) { var result = (IVisitor)Activator.CreateInstance(typeof(Visitor<>).MakeGenericType(componentType)); result.LoadValueMethod(method); visitor = result; return true; } } visitor = null; return false; } static bool IsSubClassOfGeneric(Type child, Type parent) { if (child == parent) return false; if (child.IsSubclassOf(parent)) return true; var parameters = parent.GetGenericArguments(); var isParameterLessGeneric = !(parameters != null && parameters.Length > 0 && ((parameters[0].Attributes & TypeAttributes.BeforeFieldInit) == TypeAttributes.BeforeFieldInit)); while (child != null && child != typeof(object)) { var cur = GetFullTypeDefinition(child); if (parent == cur || (isParameterLessGeneric && cur.GetInterfaces().Select(i => GetFullTypeDefinition(i)).Contains(GetFullTypeDefinition(parent)))) return true; else if (!isParameterLessGeneric) if (GetFullTypeDefinition(parent) == cur && !cur.IsInterface) { if (VerifyGenericArguments(GetFullTypeDefinition(parent), cur)) if (VerifyGenericArguments(parent, child)) return true; } else foreach (var item in child.GetInterfaces() .Where(i => GetFullTypeDefinition(parent) == GetFullTypeDefinition(i))) if (VerifyGenericArguments(parent, item)) return true; child = child.BaseType; } return false; } static Type GetFullTypeDefinition(Type type) { return type.IsGenericType ? type.GetGenericTypeDefinition() : type; } static bool VerifyGenericArguments(Type parent, Type child) { var childArguments = child.GetGenericArguments(); var parentArguments = parent.GetGenericArguments(); if (childArguments.Length == parentArguments.Length) for (var i = 0; i < childArguments.Length; i++) if (childArguments[i].Assembly != parentArguments[i].Assembly || childArguments[i].Name != parentArguments[i].Name || childArguments[i].Namespace != parentArguments[i].Namespace) if (!childArguments[i].IsSubclassOf(parentArguments[i])) return false; return true; } } }
0
0.960159
1
0.960159
game-dev
MEDIA
0.350077
game-dev
0.989498
1
0.989498
DOI-USGS/ISIS3
4,174
isis/tests/CameraFixtures.h
#ifndef CameraFixtures_h #define CameraFixtures_h #include "gtest/gtest.h" #include <memory> #include <QString> #include <nlohmann/json.hpp> #include "Cube.h" #include "Pvl.h" #include "TempFixtures.h" namespace Isis { class PushFramePair : public TempTestingFiles { protected: std::shared_ptr<Cube> evenCube; std::shared_ptr<Cube> oddCube; int numSamps; int numBands; int frameHeight; int numFrames; void SetUp() override; }; class FlippedPushFramePair : public TempTestingFiles { protected: std::shared_ptr<Cube> evenCube; std::shared_ptr<Cube> oddCube; int numSamps; int numBands; int frameHeight; int numFrames; void SetUp() override; }; class DefaultCube : public TempTestingFiles { protected: Cube *testCube; Cube *projTestCube; Pvl label; Pvl projLabel; nlohmann::json isd; void SetUp() override; void TearDown() override; void resizeCube(int samples, int lines, int bands); }; class LineScannerCube : public TempTestingFiles { protected: Cube *testCube; Cube *projTestCube; Pvl label; Pvl projLabel; nlohmann::json isd; void SetUp() override; void TearDown() override; }; class OffBodyCube : public TempTestingFiles { protected: Cube *testCube; void SetUp() override; void TearDown() override; }; class MiniRFCube : public TempTestingFiles { protected: Cube *testCube; void SetUp() override; void TearDown() override; }; class DemCube : public DefaultCube { protected: Cube *demCube; void SetUp() override; void TearDown() override; }; class MroCtxCube : public DefaultCube { protected: std::unique_ptr<Cube> testCube; void SetUp() override; void TearDown() override; }; class GalileoSsiCube : public DefaultCube { protected: void SetUp() override; void TearDown() override; }; class MgsMocCube : public DefaultCube { protected: std::unique_ptr<Cube> testCube; void SetUp() override; void TearDown() override; }; class MroHiriseCube : public DefaultCube { protected: QString ckPath = "data/mroKernels/mroCK.bc"; QString sclkPath = "data/mroKernels/mroSCLK.tsc"; QString lskPath = "data/mroKernels/mroLSK.tls"; Cube dejitteredCube; QString jitterPath; void SetUp() override; void setInstrument(QString ikid, QString instrumentId, QString spacecraftName); }; class NewHorizonsCube : public DefaultCube { protected: void setInstrument(QString ikid, QString instrumentId, QString spacecraftName); }; class OsirisRexOcamsCube : public DefaultCube { protected: void setInstrument(QString ikid, QString instrumentId); }; class OsirisRexTagcamsNAVCamCube : public DefaultCube { protected: void setInstrument(QString ikid, QString instrumentId); }; class OsirisRexTagcamsNFTCamCube : public DefaultCube { protected: void setInstrument(QString ikid, QString instrumentId); }; class ClipperWacFcCube : public DefaultCube { protected: Cube *wacFcCube; Pvl label; nlohmann::json isd; void SetUp() override; void TearDown() override; }; class ClipperNacRsCube : public DefaultCube { protected: void SetUp() override; void TearDown() override; }; class ClipperPbCube : public TempTestingFiles { protected: Cube *testCube; void setInstrument(QString instrumentId); }; class NearMsiCameraCube : public TempTestingFiles { protected: // Cube *testCube; std::unique_ptr<Cube> testCube; void SetUp() override; void TearDown() override; }; class OrexManyIsdCameraCubes : public TempTestingFiles { protected: QString m_sourcefile; nlohmann::json m_isd; Pvl m_label; const QString &source() const; Cube *make_cube( const QString &cubefile ); void SetUp() override; void TearDown() override; }; } #endif
0
0.667299
1
0.667299
game-dev
MEDIA
0.437059
game-dev
0.633803
1
0.633803
savchenkoaddev/TraffiLearn.WebApi
1,053
src/TraffiLearn.Application/UseCases/Regions/Mappers/CreateRegionCommandMapper.cs
using TraffiLearn.Application.Abstractions.Data; using TraffiLearn.Application.UseCases.Regions.Commands.Create; using TraffiLearn.Domain.Regions; using TraffiLearn.Domain.Regions.RegionNames; using TraffiLearn.SharedKernel.Shared; namespace TraffiLearn.Application.UseCases.Regions.Mappers { internal sealed class CreateRegionCommandMapper : Mapper<CreateRegionCommand, Result<Region>> { public override Result<Region> Map(CreateRegionCommand source) { var regionNameResult = RegionName.Create(source.RegionName); if (regionNameResult.IsFailure) { return Result.Failure<Region>(regionNameResult.Error); } var regionId = new RegionId(Guid.NewGuid()); var result = Region.Create( regionId, name: regionNameResult.Value); if (result.IsFailure) { return Result.Failure<Region>(result.Error); } return result.Value; } } }
0
0.543365
1
0.543365
game-dev
MEDIA
0.217372
game-dev
0.635098
1
0.635098
liquidapps-io/zeus-sdk
7,842
boxes/groups/sample/cardgame/contracts/eos/cardgame/gameplay.cpp
#include "cardgame.hpp" // Simple Pseudo Random Number Algorithm, randomly pick a number within 0 to n-1 int cardgame::random(const int range) { // Find the existing seed auto seed_iterator = _seed.begin(); // Initialize the seed with default value if it is not found if (seed_iterator == _seed.end()) { seed_iterator = _seed.emplace( _self, [&]( auto& seed ) { }); } // Generate new seed value using the existing seed value int prime = 65537; auto new_seed_value = (seed_iterator->value + eosio::current_time_point().sec_since_epoch()) % prime; // Store the updated seed value in the table _seed.modify( seed_iterator, _self, [&]( auto& s ) { s.value = new_seed_value; }); // Get the random result in desired range int random_result = new_seed_value % range; return random_result; } // Draw one card from the deck and assign it to the hand void cardgame::draw_one_card(vector<uint8_t>& deck, vector<uint8_t>& hand) { // Pick a random card from the deck int deck_card_idx = random(deck.size()); // Find the first empty slot in the hand int first_empty_slot = -1; for (int i = 0; i <= hand.size(); i++) { auto id = hand[i]; if (card_dict.at(id).type == EMPTY) { first_empty_slot = i; break; } } eosio::check(first_empty_slot != -1, "No empty slot in the player's hand"); // Assign the card to the first empty slot in the hand hand[first_empty_slot] = deck[deck_card_idx]; // Remove the card from the deck deck.erase(deck.begin() + deck_card_idx); } // Calculate the final attack point of a card after taking the elemental bonus into account int cardgame::calculate_attack_point(const card& card1, const card& card2) { int result = card1.attack_point; //Add elemental compatibility bonus of 1 if ((card1.type == FIRE && card2.type == WOOD) || (card1.type == WOOD && card2.type == WATER) || (card1.type == WATER && card2.type == FIRE)) { result++; } return result; } // AI Best Card Win Strategy int cardgame::ai_best_card_win_strategy(const int ai_attack_point, const int player_attack_point) { eosio::print("Best Card Wins"); if (ai_attack_point > player_attack_point) return 3; if (ai_attack_point < player_attack_point) return -2; return -1; } // AI Minimize Loss Strategy int cardgame::ai_min_loss_strategy(const int ai_attack_point, const int player_attack_point) { eosio::print("Minimum Losses"); if (ai_attack_point > player_attack_point) return 1; if (ai_attack_point < player_attack_point) return -4; return -1; } // AI Points Tally Strategy int cardgame::ai_points_tally_strategy(const int ai_attack_point, const int player_attack_point) { eosio::print("Points Tally"); return ai_attack_point - player_attack_point; } // AI Loss Prevention Strategy int cardgame::ai_loss_prevention_strategy(const int8_t life_ai, const int ai_attack_point, const int player_attack_point) { eosio::print("Loss Prevention"); if (life_ai + ai_attack_point - player_attack_point > 0) return 1; return 0; } // Calculate the score for the current ai card given the strategy and the player hand cards int cardgame::calculate_ai_card_score(const int strategy_idx, const int8_t life_ai, const card& ai_card, const vector<uint8_t> hand_player) { int card_score = 0; for (int i = 0; i < hand_player.size(); i++) { const auto player_card_id = hand_player[i]; const auto player_card = card_dict.at(player_card_id); int ai_attack_point = calculate_attack_point(ai_card, player_card); int player_attack_point = calculate_attack_point(player_card, ai_card); // Accumulate the card score based on the given strategy switch (strategy_idx) { case 0: { card_score += ai_best_card_win_strategy(ai_attack_point, player_attack_point); break; } case 1: { card_score += ai_min_loss_strategy(ai_attack_point, player_attack_point); break; } case 2: { card_score += ai_points_tally_strategy(ai_attack_point, player_attack_point); break; } default: { card_score += ai_loss_prevention_strategy(life_ai, ai_attack_point, player_attack_point); break; } } } return card_score; } // Chose a card from the AI's hand based on the current game data int cardgame::ai_choose_card(const game& game_data) { // The 4th strategy is only chosen in the dire situation int available_strategies = 4; if (game_data.life_ai > 2) available_strategies--; int strategy_idx = random(available_strategies); // Calculate the score of each card in the AI hand int chosen_card_idx = -1; int chosen_card_score = std::numeric_limits<int>::min(); for (int i = 0; i < game_data.hand_ai.size(); i++) { const auto ai_card_id = game_data.hand_ai[i]; const auto ai_card = card_dict.at(ai_card_id); // Ignore empty slot in the hand if (ai_card.type == EMPTY) continue; // Calculate the score for this AI card relative to the player's hand cards auto card_score = calculate_ai_card_score(strategy_idx, game_data.life_ai, ai_card, game_data.hand_player); // Keep track of the card that has the highest score if (card_score > chosen_card_score) { chosen_card_score = card_score; chosen_card_idx = i; } } return chosen_card_idx; } // Resolve selected cards and update the damage dealt void cardgame::resolve_selected_cards(game& game_data) { const auto player_card = card_dict.at(game_data.selected_card_player); const auto ai_card = card_dict.at(game_data.selected_card_ai); // For type VOID, we will skip any damage calculation if (player_card.type == VOID || ai_card.type == VOID) return; int player_attack_point = calculate_attack_point(player_card, ai_card); int ai_attack_point = calculate_attack_point(ai_card, player_card); // Damage calculation if (player_attack_point > ai_attack_point) { // Deal damage to the AI if the AI card's attack point is higher int diff = player_attack_point - ai_attack_point; game_data.life_lost_ai = diff; game_data.life_ai -= diff; } else if (ai_attack_point > player_attack_point) { // Deal damage to the player if the player card's attack point is higher int diff = ai_attack_point - player_attack_point; game_data.life_lost_player = diff; game_data.life_player -= diff; } } // Check the current game board and update the game status accordingly void cardgame::update_game_status(user_info& user) { game& game_data = user.game_data; if (game_data.life_ai <= 0) { // Check the AI's HP game_data.status = PLAYER_WON; } else if (game_data.life_player <= 0) { // Check the player's HP game_data.status = PLAYER_LOST; } else { // Neither player has their HP reduced to 0 // Check whether the game has finished (i.e., no more cards in both hands) const auto is_empty_slot = [&](const auto& id) { return card_dict.at(id).type == EMPTY; }; bool player_finished = std::all_of(game_data.hand_player.begin(), game_data.hand_player.end(), is_empty_slot); bool ai_finished = std::all_of(game_data.hand_ai.begin(), game_data.hand_ai.end(), is_empty_slot); // If one of them has run out of card, the other must have run out of card too if (player_finished || ai_finished) { if (game_data.life_player > game_data.life_ai) { game_data.status = PLAYER_WON; } else { game_data.status = PLAYER_LOST; } } } // Update the lost/ win count accordingly if (game_data.status == PLAYER_WON) { user.win_count++; } else if (game_data.status == PLAYER_LOST) { user.lost_count++; } }
0
0.556639
1
0.556639
game-dev
MEDIA
0.994483
game-dev
0.93661
1
0.93661
electronicarts/CnC_Generals_Zero_Hour
6,166
GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarOCLTimer.cpp
/* ** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts 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/>. */ //////////////////////////////////////////////////////////////////////////////// // // // (c) 2001-2003 Electronic Arts Inc. // // // //////////////////////////////////////////////////////////////////////////////// // FILE: ControlBarOCLTimer.cpp ////////////////////////////////////////////////////////// // Author: Colin Day, March 2002 // Desc: Methods specific to the control bar OCL Timer context /////////////////////////////////////////////////////////////////////////////////////////////////// // USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine #include "Common/NameKeyGenerator.h" #include "Common/ThingTemplate.h" #include "GameLogic/Object.h" #include "GameLogic/Module/OCLUpdate.h" #include "GameClient/Drawable.h" #include "GameClient/GameText.h" #include "GameClient/ControlBar.h" #include "GameClient/GameWindow.h" #include "GameClient/GameWindowManager.h" #include "GameClient/GadgetStaticText.h" #include "GameClient/GadgetProgressBar.h" //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- void ControlBar::updateOCLTimerTextDisplay( UnsignedInt totalSeconds, Real percent ) { UnicodeString text; static UnsignedInt descID = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:OCLTimerStaticText" ); GameWindow *descWindow = TheWindowManager->winGetWindowFromId( NULL, descID ); static UnsignedInt barID = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:OCLTimerProgressBar" ); GameWindow *barWindow = TheWindowManager->winGetWindowFromId( NULL, barID ); // santiy DEBUG_ASSERTCRASH( descWindow, ("Under construction window not found\n") ); Int minutes = totalSeconds / 60; Int seconds = totalSeconds - (minutes * 60); // format the message if( seconds < 10 ) text.format( TheGameText->fetch( "CONTROLBAR:OCLTimerDescWithPadding" ), minutes, seconds ); else text.format( TheGameText->fetch( "CONTROLBAR:OCLTimerDesc" ), minutes, seconds ); GadgetStaticTextSetText( descWindow, text ); GadgetProgressBarSetProgress(barWindow, (percent * 100)); // record this as the last time displayed m_displayedOCLTimerSeconds = totalSeconds; } // end updateOCLTimerTextDisplay //------------------------------------------------------------------------------------------------- /** Populate the interface for an OCL Timer context. */ //------------------------------------------------------------------------------------------------- void ControlBar::populateOCLTimer( Object *creatorObject ) { // sanity if( creatorObject == NULL ) return; // get our parent window GameWindow *parent = m_contextParent[ CP_OCL_TIMER ]; // set the sell button /// @todo srj -- remove hard-coding here, please NameKeyType id; id = TheNameKeyGenerator->nameToKey( "ControlBar.wnd:OCLTimerSellButton" ); GameWindow *win = TheWindowManager->winGetWindowFromId( parent, id ); if( !creatorObject->isKindOf(KINDOF_TECH_BUILDING) ) { // Surgical bug fix. srj is right, this is stupid. const CommandButton *commandButton = findCommandButton( "Command_Sell" ); setControlCommand( win, commandButton ); win->winSetStatus( WIN_STATUS_USE_OVERLAY_STATES ); } // Another last minute hack due to time constraint and feature creep else if( creatorObject->isKindOf(KINDOF_TECH_BUILDING) && creatorObject->isKindOf(KINDOF_AUTO_RALLYPOINT) ) { // This time we want a rally point button to show up instead of a sell button const CommandButton *commandButton = findCommandButton( "Command_SetRallyPoint" ); setControlCommand( win, commandButton ); win->winSetStatus( WIN_STATUS_USE_OVERLAY_STATES ); // // for objects that have a production exit interface, we may have a rally point set. // if we do, we want to show that rally point in the world // ExitInterface *exit = creatorObject->getObjectExitInterface(); if( exit ) { // // if a rally point is set, show the rally point, if we don't have it set hide any rally // point we might have visible // showRallyPoint( exit->getRallyPoint() ); } // end if } else { win->winHide(TRUE); } // set the text percent and bar of our timer we are displaying updateContextOCLTimer( ); // set the portrait for the thing being constructed setPortraitByObject( creatorObject ); } // end populateUnderConstruction //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- void ControlBar::updateContextOCLTimer( void ) { Object *obj = m_currentSelectedDrawable->getObject(); static const NameKeyType key_OCLUpdate = NAMEKEY( "OCLUpdate" ); OCLUpdate *update = (OCLUpdate*)obj->findUpdateModule( key_OCLUpdate ); UnsignedInt frames = update->getRemainingFrames(); UnsignedInt seconds = frames / LOGICFRAMES_PER_SECOND; Real percent = update->getCountdownPercent(); // if the time has changed since what was last shown to the user update the text if( m_displayedOCLTimerSeconds != seconds ) updateOCLTimerTextDisplay( seconds, percent ); } // end updatecontextUnderConstruction
0
0.914263
1
0.914263
game-dev
MEDIA
0.839292
game-dev
0.880446
1
0.880446
SkelletonX/DDTank4.1
16,538
Source Flash/scripts/civil/view/CivilRightView.as
package civil.view { import civil.CivilController; import civil.CivilEvent; import civil.CivilModel; import com.pickgliss.effect.EffectManager; import com.pickgliss.effect.EffectTypes; import com.pickgliss.effect.IEffect; import com.pickgliss.ui.ComponentFactory; import com.pickgliss.ui.controls.SelectedButton; import com.pickgliss.ui.controls.SelectedButtonGroup; import com.pickgliss.ui.controls.SimpleBitmapButton; import com.pickgliss.ui.controls.TextInput; import com.pickgliss.ui.controls.container.HBox; import com.pickgliss.ui.core.Disposeable; import com.pickgliss.ui.image.Scale9CornerImage; import com.pickgliss.ui.text.FilterFrameText; import com.pickgliss.utils.ObjectUtils; import ddt.manager.LanguageMgr; import ddt.manager.MessageTipManager; import ddt.manager.PlayerManager; import ddt.manager.SocketManager; import ddt.manager.SoundManager; import flash.display.Bitmap; import flash.display.Sprite; import flash.events.MouseEvent; import flash.geom.Point; import im.IMController; public class CivilRightView extends Sprite implements Disposeable { private var _bg:Scale9CornerImage; private var _rightViewBg:Bitmap; private var _nameTitle:Bitmap; private var _levelTitle:Bitmap; private var _stateTitle:Bitmap; private var _searchBG:Bitmap; private var _civilGenderContainer:HBox; private var _civilGenderGroup:SelectedButtonGroup; private var _maleBtn:SelectedButton; private var _femaleBtn:SelectedButton; private var _searchBtn:SimpleBitmapButton; private var _preBtn:SimpleBitmapButton; private var _nextBtn:SimpleBitmapButton; private var _registerBtn:SimpleBitmapButton; private var _addBigBtn:SimpleBitmapButton; private var _menberList:CivilPlayerInfoList; private var _controller:CivilController; private var _currentPage:int = 1; private var _model:CivilModel; private var _sex:Boolean; private var _searchTxt:TextInput; private var _pageTxt:FilterFrameText; private var _loadMember:Boolean = false; private var _registerEffect:IEffect; private var _seachKey:String = ""; private var _isBusy:Boolean; public function CivilRightView(param1:CivilController, param2:CivilModel) { this._model = param2; this._controller = param1; super(); this.init(); this.initButton(); this.initEvnet(); this._menberList.MemberList(this._model.civilPlayers); if(PlayerManager.Instance.Self.MarryInfoID <= 0 || !PlayerManager.Instance.Self.MarryInfoID) { SocketManager.Instance.out.sendRegisterInfo(PlayerManager.Instance.Self.ID,true,LanguageMgr.GetTranslation("civil.frame.CivilRegisterFrame.text")); } if(this._model.IsFirst) { this._registerEffect.play(); } } public function dispose() : void { this.removeEvent(); if(this._registerEffect) { EffectManager.Instance.removeEffect(this._registerEffect); this._registerEffect = null; } if(this._civilGenderContainer) { ObjectUtils.disposeObject(this._civilGenderContainer); this._civilGenderContainer = null; } if(this._preBtn) { this._preBtn.dispose(); } this._preBtn = null; if(this._preBtn) { this._preBtn.dispose(); } this._preBtn = null; if(this._nextBtn) { this._nextBtn.dispose(); } this._nextBtn = null; if(this._registerBtn) { this._registerBtn.dispose(); } this._registerBtn = null; if(this._addBigBtn) { this._addBigBtn.dispose(); } this._addBigBtn = null; if(this._searchBtn) { this._searchBtn.dispose(); } this._searchBtn = null; if(this._femaleBtn) { this._femaleBtn.dispose(); } this._femaleBtn = null; if(this._maleBtn) { this._maleBtn.dispose(); } this._maleBtn = null; if(this._rightViewBg) { ObjectUtils.disposeObject(this._rightViewBg); this._rightViewBg = null; } if(this._bg) { ObjectUtils.disposeObject(this._bg); this._bg = null; } if(this._nameTitle) { ObjectUtils.disposeObject(this._nameTitle); this._nameTitle = null; } if(this._levelTitle) { ObjectUtils.disposeObject(this._levelTitle); this._levelTitle = null; } if(this._stateTitle) { ObjectUtils.disposeObject(this._stateTitle); this._stateTitle = null; } if(this._searchBG) { ObjectUtils.disposeObject(this._searchBG); this._searchBG = null; } if(this._searchTxt) { ObjectUtils.disposeObject(this._searchTxt); this._searchTxt = null; } if(this._pageTxt) { ObjectUtils.disposeObject(this._pageTxt); this._pageTxt = null; } if(this._menberList) { ObjectUtils.disposeObject(this._menberList); this._menberList = null; } } public function init() : void { this._bg = ComponentFactory.Instance.creatComponentByStylename("asset.civil.RightViewFirstBG"); addChild(this._bg); this._rightViewBg = ComponentFactory.Instance.creatBitmap("asset.civil.rightViewBgAsset"); addChild(this._rightViewBg); this._nameTitle = ComponentFactory.Instance.creatBitmap("asset.civil.name2Title"); addChild(this._nameTitle); this._levelTitle = ComponentFactory.Instance.creatBitmap("asset.civil.levelTitle"); addChild(this._levelTitle); this._stateTitle = ComponentFactory.Instance.creatBitmap("asset.civil.stateTitle"); addChild(this._stateTitle); this._searchBG = ComponentFactory.Instance.creatBitmap("asset.civil.search_bgAsset"); addChild(this._searchBG); this._searchTxt = ComponentFactory.Instance.creat("civil.searchText"); this._searchTxt.text = LanguageMgr.GetTranslation("academy.view.AcademyMemberListView.searchTxt"); addChild(this._searchTxt); this._pageTxt = ComponentFactory.Instance.creat("civil.page"); addChild(this._pageTxt); this._menberList = ComponentFactory.Instance.creatCustomObject("civil.view.CivilPlayerInfoList"); this._menberList.model = this._model; addChild(this._menberList); } private function initButton() : void { this._civilGenderGroup = new SelectedButtonGroup(); this._searchBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.searchBtn"); addChild(this._searchBtn); this._preBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.preBtn"); addChild(this._preBtn); this._nextBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.nextBtn"); addChild(this._nextBtn); this._registerBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.registerBtn"); addChild(this._registerBtn); this._addBigBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.addBigBtn"); addChild(this._addBigBtn); this._civilGenderContainer = ComponentFactory.Instance.creatComponentByStylename("civil.GenderBtnContainer"); this._maleBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.maleButton"); this._femaleBtn = ComponentFactory.Instance.creatComponentByStylename("asset.civil.femaleButton"); this._civilGenderContainer.addChild(this._maleBtn); this._civilGenderContainer.addChild(this._femaleBtn); this._civilGenderGroup.addSelectItem(this._maleBtn); this._civilGenderGroup.addSelectItem(this._femaleBtn); addChild(this._civilGenderContainer); var _loc1_:Point = ComponentFactory.Instance.creatCustomObject("civil.register.RegisterPos"); this._registerEffect = EffectManager.Instance.creatEffect(EffectTypes.ADD_MOVIE_EFFECT,this._registerBtn,"asset.civil.registerGlowAsset",_loc1_); } private function initEvnet() : void { this._preBtn.addEventListener(MouseEvent.CLICK,this.__leafBtnClick); this._nextBtn.addEventListener(MouseEvent.CLICK,this.__leafBtnClick); this._searchBtn.addEventListener(MouseEvent.CLICK,this.__leafBtnClick); this._maleBtn.addEventListener(MouseEvent.CLICK,this.__sexBtnClick); this._femaleBtn.addEventListener(MouseEvent.CLICK,this.__sexBtnClick); this._registerBtn.addEventListener(MouseEvent.CLICK,this.__btnClick); this._addBigBtn.addEventListener(MouseEvent.CLICK,this.__addBtnClick); this._searchTxt.addEventListener(MouseEvent.CLICK,this.__searchTxtClick); this._menberList.addEventListener(CivilEvent.SELECTED_CHANGE,this.__memberSelectedChange); this._model.addEventListener(CivilEvent.CIVIL_PLAYERINFO_ARRAY_CHANGE,this.__updateView); this._model.addEventListener(CivilEvent.REGISTER_CHANGE,this.__onRegisterChange); } private function removeEvent() : void { this._preBtn.removeEventListener(MouseEvent.CLICK,this.__leafBtnClick); this._nextBtn.removeEventListener(MouseEvent.CLICK,this.__leafBtnClick); this._searchBtn.removeEventListener(MouseEvent.CLICK,this.__leafBtnClick); this._maleBtn.removeEventListener(MouseEvent.CLICK,this.__sexBtnClick); this._femaleBtn.removeEventListener(MouseEvent.CLICK,this.__sexBtnClick); this._searchTxt.removeEventListener(MouseEvent.CLICK,this.__searchTxtClick); this._menberList.removeEventListener(CivilEvent.SELECTED_CHANGE,this.__memberSelectedChange); this._registerBtn.removeEventListener(MouseEvent.CLICK,this.__btnClick); this._addBigBtn.removeEventListener(MouseEvent.CLICK,this.__addBtnClick); this._model.removeEventListener(CivilEvent.CIVIL_PLAYERINFO_ARRAY_CHANGE,this.__updateView); this._model.removeEventListener(CivilEvent.REGISTER_CHANGE,this.__onRegisterChange); } private function __onRegisterChange(param1:CivilEvent) : void { if(!this._model.registed) { this._registerEffect.play(); } else { this._registerEffect.stop(); } } private function __btnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._controller.Register(); } private function __addBtnClick(param1:MouseEvent) : void { if(this._controller.currentcivilInfo && this._controller.currentcivilInfo.info) { SoundManager.instance.play("008"); IMController.Instance.addFriend(this._controller.currentcivilInfo.info.NickName); } } private function __sexBtnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); this._currentPage = 1; if(param1.currentTarget == this._femaleBtn) { this._sex = false; if(this._sex == this._model.sex) { return; } this._model.sex = false; } else { this._sex = true; if(this._sex == this._model.sex) { return; } this._model.sex = true; } this._sex = this._model.sex; this._controller.loadCivilMemberList(this._currentPage,this._model.sex); if(this._searchTxt.text != LanguageMgr.GetTranslation("academy.view.AcademyMemberListView.searchTxt")) { this._searchTxt.text = ""; } else { this._searchTxt.text = LanguageMgr.GetTranslation("academy.view.AcademyMemberListView.searchTxt"); } this._seachKey = ""; } private function __leafBtnClick(param1:MouseEvent) : void { SoundManager.instance.play("008"); if(this._loadMember) { return; } if(this._isBusy) { return; } switch(param1.currentTarget) { case this._preBtn: this._currentPage = --this._currentPage; break; case this._nextBtn: this._currentPage = ++this._currentPage; break; case this._searchBtn: if(this._searchTxt.text == "" || this._searchTxt.text == LanguageMgr.GetTranslation("academy.view.AcademyMemberListView.searchTxt")) { MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("civil.view.CivilRightView.info")); } else { this._seachKey = this._searchTxt.text; this._currentPage = 1; this._controller.loadCivilMemberList(this._currentPage,this._sex,this._seachKey); this._loadMember = true; } return; } this._isBusy = true; this._controller.loadCivilMemberList(this._currentPage,this._sex,this._seachKey); } private function __searchTxtClick(param1:MouseEvent) : void { if(this._searchTxt.text == LanguageMgr.GetTranslation("academy.view.AcademyMemberListView.searchTxt")) { this._searchTxt.text = ""; } } private function __memberSelectedChange(param1:CivilEvent) : void { if(param1.data) { this._addBigBtn.enable = this._menberList.selectedItem.info.UserId == PlayerManager.Instance.Self.ID?Boolean(false):Boolean(true); } } private function updateButton() : void { if(this._model.TotalPage == 1) { this.setButtonState(false,false); } else if(this._model.TotalPage == 0) { this.setButtonState(false,false); } else if(this._currentPage == 1) { this.setButtonState(false,true); } else if(this._currentPage == this._model.TotalPage && this._currentPage != 0) { this.setButtonState(true,false); } else { this.setButtonState(true,true); } if(!this._model.TotalPage) { this._pageTxt.text = String(1) + " / " + String(1); } else { this._pageTxt.text = String(this._currentPage) + " / " + String(this._model.TotalPage); } this._addBigBtn.enable = this._addBigBtn.enable && this._model.civilPlayers.length > 0?Boolean(true):Boolean(false); this.updateSex(); } private function updateSex() : void { if(this._model.sex) { this._civilGenderGroup.selectIndex = 0; } else { this._civilGenderGroup.selectIndex = 1; } this._sex = this._model.sex; } private function __updateRegisterGlow(param1:CivilEvent) : void { } private function setButtonState(param1:Boolean, param2:Boolean) : void { this._preBtn.mouseChildren = param1; this._preBtn.enable = param1; this._nextBtn.mouseChildren = param2; this._nextBtn.enable = param2; } private function __updateView(param1:CivilEvent) : void { this._isBusy = false; this.updateButton(); this._loadMember = false; } } }
0
0.819001
1
0.819001
game-dev
MEDIA
0.894956
game-dev
0.933551
1
0.933551
lukewasthefish/AutomatonLung
2,463
Assets/Cinema Suite/Cinema Director/Cutscene Items/Global Items/GameObject/DisableGameObjectGlobal.cs
// Cinema Suite using CinemaDirector.Helpers; using UnityEngine; namespace CinemaDirector { /// <summary> /// A simple event for Disabling a Game Object. /// </summary> [CutsceneItemAttribute("Game Object", "Disable Game Object", CutsceneItemGenre.GlobalItem)] public class DisableGameObjectGlobal : CinemaGlobalEvent, IRevertable { // The target Game Object public GameObject target; // Options for reverting in editor. [SerializeField] private RevertMode editorRevertMode = RevertMode.Revert; // Options for reverting during runtime. [SerializeField] private RevertMode runtimeRevertMode = RevertMode.Revert; // Keep track of the GameObject's previous state when calling Trigger. private bool previousState; /// <summary> /// Cache the initial state of the target GameObject's active state. /// </summary> /// <returns>The Info necessary to revert this event.</returns> public RevertInfo[] CacheState() { if (target != null) return new RevertInfo[] { new RevertInfo(this, target, "SetActive", target.activeInHierarchy) }; return null; } /// <summary> /// Trigger this event and set the given GameObject to disabled. /// </summary> public override void Trigger() { if (target != null) { previousState = target.activeInHierarchy; target.SetActive(false); } } /// <summary> /// Reverse this Event and put the GameObject into its' previous state. /// </summary> public override void Reverse() { if (target != null) { target.SetActive(previousState); } } /// <summary> /// Option for choosing when this Event will Revert to initial state in Editor. /// </summary> public RevertMode EditorRevertMode { get { return editorRevertMode; } set { editorRevertMode = value; } } /// <summary> /// Option for choosing when this Event will Revert to initial state in Runtime. /// </summary> public RevertMode RuntimeRevertMode { get { return runtimeRevertMode; } set { runtimeRevertMode = value; } } } }
0
0.931001
1
0.931001
game-dev
MEDIA
0.969054
game-dev
0.934072
1
0.934072
rciworks/RCi.Tutorials.Csgo.Cheat.External
8,237
Tutorial 011 - Global Hook/Features/AimBot.cs
using System; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.DirectX; using RCi.Tutorials.Csgo.Cheat.External.Data; using RCi.Tutorials.Csgo.Cheat.External.Gfx.Math; using RCi.Tutorials.Csgo.Cheat.External.Sys; using RCi.Tutorials.Csgo.Cheat.External.Sys.Data; using RCi.Tutorials.Csgo.Cheat.External.Utils; using Point = System.Drawing.Point; namespace RCi.Tutorials.Csgo.Cheat.External.Features { /// <summary> /// Aim bot. Aims towards enemy when active. /// </summary> public class AimBot : ThreadedComponent { #region // storage /// <summary> /// Moving mouse one pixel will give this much of view angle change (in radians). /// </summary> private double AnglePerPixel { get; set; } = 0.00057596609244744; /// <summary> /// Bone id to aim for, 8 = head. /// </summary> private const int AimBoneId = 8; /// <inheritdoc /> protected override string ThreadName => nameof(AimBot); /// <inheritdoc cref="GameProcess"/> private GameProcess GameProcess { get; set; } /// <inheritdoc cref="GameData"/> private GameData GameData { get; set; } /// <summary> /// Global mouse hook. /// </summary> private GlobalHook MouseHook { get; set; } #endregion #region // ctor /// <summary /> public AimBot(GameProcess gameProcess, GameData gameData) { GameProcess = gameProcess; GameData = gameData; MouseHook = new GlobalHook(HookType.WH_MOUSE_LL, MouseHookCallback); } /// <inheritdoc /> public override void Dispose() { base.Dispose(); MouseHook.Dispose(); MouseHook = default; GameData = default; GameProcess = default; } #endregion #region // routines /// <inheritdoc cref="HookProc"/> private IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { var mouseMessage = (MouseMessage)wParam; var mouseInput = Marshal.PtrToStructure<MouseInput>(lParam); Console.WriteLine($"{mouseMessage} x={mouseInput.dx} y={mouseInput.dy}"); } return User32.CallNextHookEx(MouseHook.HookHandle, nCode, wParam, lParam); } /// <inheritdoc /> protected override void FrameAction() { if (!GameProcess.IsValid) { return; } if (IsCalibrateHotKeyDown()) { Calibrate(); return; } if (!WindowsVirtualKey.VK_LBUTTON.IsKeyDown()) { // no mouse left down return; } // get and validate aim target if (!GetAimTarget(out var aimAngles)) { return; } // get pixels to move GetAimPixels(aimAngles, out var aimPixels); // try to move mouse on a target var wait = TryMouseMove(aimPixels); // give time for csgo to process simulated input if (wait) { // arbitrary amount of wait Thread.Sleep(20); } } /// <summary> /// Get aim target. /// </summary> /// <param name="aimAngles">Euler angles to aim target (in radians).</param> /// <returns> /// <see langword="true"/> if aim target was found. /// </returns> private bool GetAimTarget(out Vector2 aimAngles) { var minAngleSize = float.MaxValue; aimAngles = new Vector2((float)Math.PI, (float)Math.PI); var targetFound = false; foreach (var entity in GameData.Entities) { // validate if (!entity.IsAlive() || entity.AddressBase == GameData.Player.AddressBase) { continue; } // get angle to bone GetAimAngles(entity.BonesPos[AimBoneId], out var angleToBoneSize, out var anglesToBone); // check if it's closer if (angleToBoneSize < minAngleSize) { minAngleSize = angleToBoneSize; aimAngles = anglesToBone; targetFound = true; } } return targetFound; } /// <summary> /// Get aim angle to a point. /// </summary> /// <param name="pointWorld">A point (in world) to which aim angles are calculated.</param> /// <param name="angleSize">Angle size (in radians) between aim direction and desired aim direction (direction to <see cref="pointWorld"/>).</param> /// <param name="aimAngles">Euler angles to aim target (in radians).</param> private void GetAimAngles(Vector3 pointWorld, out float angleSize, out Vector2 aimAngles) { var aimDirection = GameData.Player.AimDirection; var aimDirectionDesired = (pointWorld - GameData.Player.EyePosition).Normalized(); angleSize = aimDirection.AngleTo(aimDirectionDesired); aimAngles = new Vector2 ( aimDirectionDesired.AngleToSigned(aimDirection, new Vector3(0, 0, 1)), aimDirectionDesired.AngleToSigned(aimDirection, aimDirectionDesired.Cross(new Vector3(0, 0, 1)).Normalized()) ); } /// <summary> /// Get pixels to move in a screen (from aim angles). /// </summary> private void GetAimPixels(Vector2 aimAngles, out Point aimPixels) { var fovRatio = 90.0 / GameData.Player.Fov; aimPixels = new Point ( (int)Math.Round(aimAngles.X / AnglePerPixel * fovRatio), (int)Math.Round(aimAngles.Y / AnglePerPixel * fovRatio) ); } /// <summary> /// Try to simulate mouse move. /// </summary> private bool TryMouseMove(Point aimPixels) { if (aimPixels.X == 0 && aimPixels.Y == 0) { return false; } U.MouseMove(aimPixels.X, aimPixels.Y); return true; } #endregion #region // calibration /// <summary> /// Is calibration hot key down? /// </summary> private static bool IsCalibrateHotKeyDown() { return WindowsVirtualKey.VK_F11.IsKeyDown() && WindowsVirtualKey.VK_F12.IsKeyDown(); } /// <summary> /// Calibrate <see cref="AnglePerPixel"/>. /// </summary> private void Calibrate() { AnglePerPixel = new[] { CalibrationMeasureAnglePerPixel(100), CalibrationMeasureAnglePerPixel(-200), CalibrationMeasureAnglePerPixel(300), CalibrationMeasureAnglePerPixel(-400), CalibrationMeasureAnglePerPixel(200), }.Average(); Console.WriteLine($"{nameof(AnglePerPixel)} = {AnglePerPixel}"); } /// <summary> /// Simulate horizontal mouse move, measure angle difference and get angle per pixel ratio (in radians). /// </summary> private double CalibrationMeasureAnglePerPixel(int deltaPixels) { // measure starting angle Thread.Sleep(100); var eyeDirectionStart = GameData.Player.EyeDirection; eyeDirectionStart.Z = 0; // rotate U.MouseMove(deltaPixels, 0); // measure end angle Thread.Sleep(100); var eyeDirectionEnd = GameData.Player.EyeDirection; eyeDirectionEnd.Z = 0; // get angle and divide by number of pixels return eyeDirectionEnd.AngleTo(eyeDirectionStart) / Math.Abs(deltaPixels); } #endregion } }
0
0.836082
1
0.836082
game-dev
MEDIA
0.659259
game-dev,graphics-rendering
0.837873
1
0.837873
lukasmonk/lucaschess
10,797
Engines/Windows/pawny/src/see.c
/*-------------------------------------------------------------------------- Pawny 0.3.1, chess engine (source code). Copyright (C) 2009 - 2011 by Mincho Georgiev. 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/>. contact: pawnychess@gmail.com web: http://www.pawny.netii.net/ ----------------------------------------------------------------------------*/ #include "data.h" #define SEE_P_VALUE 100 #define SEE_N_VALUE 321 #define SEE_B_VALUE 325 #define SEE_R_VALUE 500 #define SEE_Q_VALUE 950 #define SEE_K_VALUE 1000 static const int see_pval[16] = { 0, SEE_P_VALUE, SEE_N_VALUE, SEE_B_VALUE, SEE_R_VALUE, SEE_Q_VALUE, SEE_K_VALUE, 0, 0, SEE_P_VALUE, SEE_N_VALUE, SEE_B_VALUE, SEE_R_VALUE, SEE_Q_VALUE, SEE_K_VALUE, 0 }; int see(move_t m) { int i,v,sq,delta; int dest; //delta leads to sq. int from; //source square int to; //target (dest) square int victim; //captured piece value; int score[32]; //results of capturing int nscore; //score count int side; //side to "move" int attackers[2][16];//attackers squares int atk_count[2];//total count of attackers per side int smallest; //the smallest attacker value int sm_index; //the index of the smallest atk int sm_sq; //the smallest attacker square attack_t *a; bool pinned; bool discovery; int ksq[2]; bitboard_t played = 0; //already "played" attackers //see() handles only captures: if(!(m.type & CAP) || (m.promoted) || (m.type & EP)) return m.score; //init data: from = m.from; to = m.to; for(i = 0, v = 16; i < 16; i++,v++) attackers[0][i] = attackers[1][i] = \ score[i] = score[v] = 0; atk_count[W] = atk_count[B] = 0; nscore = 0; side = board->side;//initial side to move: a = &attack_vector[to][0]; //white pawns if(PieceType(to-15) == WP && from != (to-15)) { attackers[W][atk_count[W]] = (to-15); atk_count[W]++; } if(PieceType(to-17) == WP && from != (to-17)) { attackers[W][atk_count[W]] = (to-17); atk_count[W]++; } //black pawns: if(PieceType(to+15) == BP && from != (to+15)) { attackers[B][atk_count[B]] = (to+15); atk_count[B]++; } if(PieceType(to + 17) == BP && from != (to+17)) { attackers[B][atk_count[B]] = (to+17); atk_count[B]++; } //white queens: for(sq = PLS(WQ); sq <= H8; sq = PLN(sq)) { if(sq != from && (a[sq].flags & R_ATK || a[sq].flags & B_ATK)) { delta = a[sq].delta; for(dest = sq + delta; IsEmpty(dest);dest += delta); if(dest == to) { attackers[W][atk_count[W]] = sq; atk_count[W]++; } } } //black queens: for(sq = PLS(BQ); sq <= H8; sq = PLN(sq)) { if(sq != from && (a[sq].flags & R_ATK || a[sq].flags & B_ATK)) { delta = a[sq].delta; for(dest = sq + delta; IsEmpty(dest);dest += delta); if(dest == to) { attackers[B][atk_count[B]] = sq; atk_count[B]++; } } } //white rooks: for(sq = PLS(WR); sq <= H8; sq = PLN(sq)) { if(sq != from && a[sq].flags & R_ATK) { delta = a[sq].delta; for(dest = sq + delta; IsEmpty(dest);dest += delta); if(dest == to) { attackers[W][atk_count[W]] = sq; atk_count[W]++; } } } //black rooks: for(sq = PLS(BR); sq <= H8; sq = PLN(sq)) { if(sq != from && a[sq].flags & R_ATK) { delta = a[sq].delta; for(dest = sq + delta; IsEmpty(dest);dest += delta); if(dest == to) { attackers[B][atk_count[B]] = sq; atk_count[B]++; } } } //white bishops: for(sq = PLS(WB); sq <= H8; sq = PLN(sq)) { if(sq != from && a[sq].flags & B_ATK) { delta = a[sq].delta; for(dest = sq + delta; IsEmpty(dest);dest += delta); if(dest == to) { attackers[W][atk_count[W]] = sq; atk_count[W]++; } } } //black bishops: for(sq = PLS(BB); sq <= H8; sq = PLN(sq)) { if(sq != from && a[sq].flags & B_ATK) { delta = a[sq].delta; for(dest = sq + delta; IsEmpty(dest);dest += delta); if(dest == to) { attackers[B][atk_count[B]] = sq; atk_count[B]++; } } } //white knights: for(sq = PLS(WN); sq <= H8; sq = PLN(sq)) { if(sq != from && a[sq].flags & N_ATK) { if(sq + a[sq].delta == to) { attackers[W][atk_count[W]] = sq; atk_count[W]++; } } } //black knights: for(sq = PLS(BN); sq <= H8; sq = PLN(sq)) { if(sq != from && a[sq].flags & N_ATK) { if(sq + a[sq].delta == to) { attackers[B][atk_count[B]] = sq; atk_count[B]++; } } } //whether the king is trying to capture onto an attacked square: if((GetType(PieceType(m.from)) == KING) && atk_count[side^1]) return -INF; //white king: ksq[W] = King_Square(W); if(ksq[W] != from && (a[ksq[W]].flags & R_ATK || a[ksq[W]].flags & B_ATK)) { if(ksq[W] + a[ksq[W]].delta == to) { attackers[W][atk_count[W]] = ksq[W]; atk_count[W]++; } } //black king: ksq[B] = King_Square(B); if(ksq[B] != from && (a[ksq[B]].flags & R_ATK || a[ksq[B]].flags & B_ATK)) { if(ksq[B] + a[ksq[B]].delta == to) { attackers[B][atk_count[B]] = ksq[B]; atk_count[B]++; } } //hidden attacker (slider) behind the initial one: if(direction[to][from]) { i = direction[to][from]; for(dest = from + i; IsEmpty(dest);dest += i); if(!IsOutside(dest)) { if(a[dest].flags & atk_masks[PieceType(dest)]) { attackers[side][atk_count[side]] = dest; atk_count[side]++; } } } //testing whether the initial piece is pinned for the king, //these tests (along with king attacking protected square) are necessary, //since pseudo-legal move generator is used. if(direction[ksq[side]][from]) { i = direction[ksq[side]][from]; for(dest = ksq[side] + i; IsEmpty(dest) ; dest += i); if(dest == from) //there is no piece between the king and this one! { pinned = false; for(dest = from + i; !IsOutside(dest); dest += i) { if(!IsEmpty(dest)) { //we reach a friendly piece?: if(GetColor(PieceType(dest)) == (side)) break; else//enemy piece { if((dest != m.to) && (attack_vector[dest][ksq[side]].flags & atk_masks[PieceType(dest)])) pinned = true; break; } } } if(pinned == true) return -INF; } } //excluding the initial attacker: played = (1ULL << rsz[from]); discovery = false; if(direction[ksq[side^1]][from]) { i = direction[ksq[side^1]][from]; for(dest = ksq[side^1] + i;IsEmpty(dest) || (((1ULL << rsz[dest]) & played) != 0); dest += i); if(!IsOutside(dest)) { if(GetColor(PieceType(dest)) == side) { if(attack_vector[dest][ksq[side^1]].flags & atk_masks[PieceType(dest)]) discovery = true; } } } //initial capture: score[0] = see_pval[square[m.to]]; nscore++; victim = see_pval[PieceType(from)]; side ^= 1; //capture sequence: while(atk_count[side]) { //preparing data. smallest = SEE_K_VALUE + 1; sm_index = 0; sm_sq = 0; //find smallest attacker for 'side' for(i = 0; i < atk_count[side]; i++) { v = see_pval[PieceType(attackers[side][i])]; if(v < smallest) { smallest = v; sm_index = i; } } //if king is exposed and it's not able to capture on the square: if(discovery) { if(distance_table[ksq[side]][to] != 1) break; if(atk_count[side^1]) break; score[nscore] = -score[nscore-1] + victim; nscore ++; break; } //if the only attacker left is the king, //is the square still attacked?: if(smallest == SEE_K_VALUE) { if(atk_count[side^1]) break; else { score[nscore] = -score[nscore-1] + victim; nscore ++; break; } } sm_sq = attackers[side][sm_index]; //pinned?: if(direction[ksq[side]][sm_sq]) { i = direction[ksq[side]][sm_sq]; for(dest = ksq[side] + i;IsEmpty(dest) || (((1ULL << rsz[dest]) & played) != 0); dest += i); if(!IsOutside(dest)) { if(dest == sm_sq) //there is no piece between the king and this one! { pinned = false; for(dest = sm_sq + i;!IsOutside(dest);dest += i) { if(!IsEmpty(dest) && GetColor(PieceType(dest)) == (side^1)) { //exclude if already played: if(((1ULL << rsz[dest]) & played) != 0) continue; //friendly piece?: if(GetColor(PieceType(dest)) == (side)) break; else { //is the found piece able to attack king and it's not a pice that gets re-captured: if((dest != m.to) && (attack_vector[dest][ksq[side]].flags & atk_masks[PieceType(dest)])) pinned = true; break; } } }//break the main loop if pinned: if(pinned == true) break; } } } //excluding the piece now: played |= (1ULL << rsz[sm_sq]); //discovery check? discovery = false; if(direction[ksq[side^1]][sm_sq]) { i = direction[ksq[side^1]][sm_sq]; for(dest = ksq[side^1] + i; IsEmpty(dest) || (((1ULL << rsz[dest]) & played) != 0); dest += i); if(!IsOutside(dest)) { if(GetColor(PieceType(dest)) == side) { if(attack_vector[dest][ksq[side^1]].flags & atk_masks[PieceType(dest)]) discovery = true; } } } attackers[side][sm_index] = attackers[side][--atk_count[side]]; attackers[side][atk_count[side]] = sm_sq;//swap //now,if we have sliding direction 'target<->sm_sq'. //continue and find the next hidden attacker (slider or pawn): if(direction[to][sm_sq]) { i = direction[to][sm_sq]; for(dest = sm_sq + i;IsEmpty(dest);dest += i); if(!IsOutside(dest)) { if(a[dest].flags & atk_masks[PieceType(dest)]) { attackers[side][atk_count[side]] = dest; atk_count[side]++; } } } score[nscore] = -score[nscore-1] + victim; nscore++; victim = smallest; side ^= 1; } while(--nscore) score[nscore - 1] = min(-score[nscore], score[nscore-1]); return (score[0]); }
0
0.969675
1
0.969675
game-dev
MEDIA
0.805471
game-dev
0.993893
1
0.993893
chsami/Microbot-Hub
22,859
src/main/java/net/runelite/client/plugins/microbot/mixology/MixologyScript.java
package net.runelite.client.plugins.microbot.mixology; import net.runelite.api.DynamicObject; import net.runelite.api.GameObject; import net.runelite.api.gameval.ItemID; import net.runelite.api.gameval.ObjectID; import net.runelite.api.coords.WorldPoint; import net.runelite.client.plugins.microbot.Microbot; import net.runelite.client.plugins.microbot.Script; import net.runelite.client.plugins.microbot.mixology.enums.AlchemyObject; import net.runelite.client.plugins.microbot.mixology.enums.MixologyState; import net.runelite.client.plugins.microbot.mixology.enums.PotionComponent; import net.runelite.client.plugins.microbot.mixology.enums.PotionModifier; import net.runelite.client.plugins.microbot.util.antiban.Rs2AntibanSettings; import net.runelite.client.plugins.microbot.util.bank.Rs2Bank; import net.runelite.client.plugins.microbot.util.gameobject.Rs2GameObject; import net.runelite.client.plugins.microbot.util.inventory.Rs2Inventory; import net.runelite.client.plugins.microbot.util.math.Rs2Random; import net.runelite.client.plugins.microbot.util.player.Rs2Player; import net.runelite.client.plugins.microbot.util.walker.Rs2Walker; import net.runelite.client.plugins.microbot.util.widget.Rs2Widget; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static net.runelite.client.plugins.microbot.mixology.enums.AlchemyObject.MIXING_VESSEL; public class MixologyScript extends Script { private static final Integer DIGWEED = ItemID.MM_LAB_SPECIAL_HERB; public java.util.List<PotionOrder> potionOrders = Collections.emptyList(); public static MixologyState mixologyState = MixologyState.IDLE; public static int lyePasteAmount, agaPasteAmount, moxPasteAmount = 0; public static int startLyePoints, startAgaPoints, startMoxPoints = 0; public static int currentLyePoints, currentAgaPoints, currentMoxPoints = 0; public int agitatorQuickActionTicks = 0; public int alembicQuickActionTicks = 0; public AlchemyObject digweed; public int leverRetries = 0; public List<PotionModifier> customOrder = Arrays.asList( PotionModifier.CRYSTALISED, PotionModifier.CONCENTRATED, PotionModifier.HOMOGENOUS ); public boolean run(MixologyConfig config) { Microbot.enableAutoRunOn = false; currentMoxPoints = 0; currentAgaPoints = 0; currentLyePoints = 0; leverRetries = 0; if (!Rs2AntibanSettings.naturalMouse) { Microbot.log("Hey! Did you know this script works really well with natural mouse? Feel free to enable it in the antiban settings."); } mainScheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> { try { if (!Microbot.isLoggedIn()) return; if (!super.run()) return; long startTime = System.currentTimeMillis(); if (leverRetries >= 20) { Microbot.log("Failed to create a potion. Please do this step manually and restart the script."); return; } boolean isInMinigame = Rs2Widget.getWidget(882, 2) != null; if (!isInMinigame && mixologyState != MixologyState.REFINER) { Rs2Walker.walkTo(1395, 9322, 0, 2); return; } if (isInMinigame) { if (startLyePoints == 0 && startAgaPoints == 0 && startMoxPoints == 0) { startMoxPoints = getMoxPoints(); startAgaPoints = getAgaPoints(); startLyePoints = getLyePoints(); } if (digweed != null && !Rs2Player.isAnimating() && !Rs2Inventory.hasItem(DIGWEED) && config.pickDigWeed()) { Rs2GameObject.interact(digweed.coordinate()); Rs2Player.waitForWalking(); Rs2Player.waitForAnimation(); return; } if (Rs2Inventory.hasItem(DIGWEED) && !Rs2Player.isAnimating()) { Optional<Integer> potionItemId = potionOrders .stream() .filter(x -> !x.fulfilled() && Rs2Inventory.hasItem(x.potionType().itemId())) .map(x -> x.potionType().itemId()) .findFirst(); if (potionItemId.isPresent()) { Rs2Inventory.interact(DIGWEED, "use"); Rs2Inventory.interact(potionItemId.get(), "use"); Rs2Player.waitForAnimation(); return; } } moxPasteAmount = Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[8].getText()) + Rs2Inventory.itemQuantity(ItemID.MM_MOX_PASTE); agaPasteAmount = Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[11].getText()) + Rs2Inventory.itemQuantity(ItemID.MM_AGA_PASTE); lyePasteAmount = Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[14].getText()) + Rs2Inventory.itemQuantity(ItemID.MM_LYE_PASTE); if (mixologyState != MixologyState.REFINER && (moxPasteAmount < 100 || agaPasteAmount < 100 || lyePasteAmount < 100)) { mixologyState = MixologyState.REFINER; } else if (Rs2Inventory.hasItem(ItemID.MM_MOX_PASTE) || Rs2Inventory.hasItem(ItemID.MM_LYE_PASTE) || Rs2Inventory.hasItem(ItemID.MM_AGA_PASTE)) { if (Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[8].getText()) >= 3000 && Rs2Inventory.hasItem(ItemID.MM_MOX_PASTE)) { mixologyState = MixologyState.BANK; } else if (Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[11].getText()) >= 3000 && Rs2Inventory.hasItem(ItemID.MM_AGA_PASTE)) { mixologyState = MixologyState.BANK; } else if (Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[14].getText()) >= 3000 && Rs2Inventory.hasItem(ItemID.MM_LYE_PASTE)) { mixologyState = MixologyState.BANK; } else { mixologyState = MixologyState.DEPOSIT_HOPPER; } } } if (mixologyState == MixologyState.IDLE) { mixologyState = MixologyState.MIX_POTION_STAGE_1; } if (hasAllFulFilledItems()) { mixologyState = MixologyState.CONVEYER_BELT; } switch (mixologyState) { case BANK: if (Rs2Inventory.hasItem("paste")) { if (Rs2Bank.openBank()) { Rs2Bank.depositAll(); } return; } mixologyState = MixologyState.MIX_POTION_STAGE_1; break; case REFINER: String herb = ""; WorldPoint bankLocation = new WorldPoint(1398, 9313, 0); if (Rs2Player.getWorldLocation().distanceTo(bankLocation) > 10) { Rs2Walker.walkTo(bankLocation); return; } if (Rs2Inventory.hasItem(config.agaHerb().toString()) || Rs2Inventory.hasItem(config.lyeHerb().toString()) || Rs2Inventory.hasItem(config.moxHerb().toString())) { Rs2GameObject.interact(ObjectID.MM_LAB_MILL); Rs2Player.waitForAnimation(); sleepGaussian(450, 150); if (!config.useQuickActionRefiner()) { sleepUntil(() -> !Microbot.isGainingExp, 30000); } return; } if (Rs2Bank.openBank()) { sleepUntil(Rs2Bank::isOpen); moxPasteAmount = Rs2Bank.count(ItemID.MM_MOX_PASTE); lyePasteAmount = Rs2Bank.count(ItemID.MM_LYE_PASTE); agaPasteAmount = Rs2Bank.count(ItemID.MM_AGA_PASTE); if (moxPasteAmount < config.amtMoxHerb()) { herb = config.moxHerb().toString(); } else if (lyePasteAmount < config.amtLyeHerb()) { herb = config.lyeHerb().toString(); } else if (agaPasteAmount < config.amtAgaHerb()) { herb = config.agaHerb().toString(); } else { if (Rs2Bank.openBank()) { Rs2Bank.depositAll(); Rs2Bank.withdrawAll(ItemID.MM_MOX_PASTE); Rs2Bank.withdrawAll(ItemID.MM_LYE_PASTE); Rs2Bank.withdrawAll(ItemID.MM_AGA_PASTE); mixologyState = MixologyState.DEPOSIT_HOPPER; return; } } Rs2Bank.depositAll(); if (!Rs2Bank.hasItem(herb, true)) { Microbot.showMessage("Failed to find " + herb + " in your bank. Shutting down script..."); shutdown(); return; } Rs2Bank.withdrawAll(herb, true); Rs2Bank.closeBank(); sleepGaussian(600, 150); } break; case DEPOSIT_HOPPER: if (Rs2GameObject.interact(ObjectID.MM_LAB_HOPPER)) { Rs2Player.waitForWalking(); Rs2Inventory.waitForInventoryChanges(10000); mixologyState = MixologyState.MIX_POTION_STAGE_1; } break; case MIX_POTION_STAGE_1: Map<Integer, Integer> itemsToCheck = new HashMap<>(); PotionOrder potionToMake = null; for (PotionOrder _potionOrder : potionOrders) { int key = _potionOrder.potionType().itemId(); int value = itemsToCheck.getOrDefault(key, 0); itemsToCheck.put(key, value + 1); } for (int itemId : itemsToCheck.keySet()) { PotionOrder _potionOrder = potionOrders .stream() .filter(x -> x.potionType().itemId() == itemId) .findFirst() .orElse(null); if (_potionOrder == null) continue; int itemAmount = itemsToCheck.getOrDefault(itemId, 1); if (!Rs2Inventory.hasItemAmount(itemId, itemAmount)) { potionToMake = _potionOrder; } } if (potionToMake == null) { mixologyState = MixologyState.MIX_POTION_STAGE_2; return; } if (canCreatePotion(potionToMake)) { mixologyState = MixologyState.TAKE_FROM_MIXIN_VESSEL; leverRetries = 0; } else { createPotion(potionToMake, config); } break; case TAKE_FROM_MIXIN_VESSEL: Rs2GameObject.interact(MIXING_VESSEL.objectId()); boolean result = Rs2Inventory.waitForInventoryChanges(5000); if (result) { mixologyState = MixologyState.MIX_POTION_STAGE_1; } break; case MIX_POTION_STAGE_2: // Sort using a custom comparator List<PotionOrder> nonFulfilledPotions = potionOrders .stream() .filter(x -> !x.fulfilled()) .sorted(Comparator.comparingInt(customOrder::indexOf)) .collect(Collectors.toList()); if (nonFulfilledPotions.isEmpty()) { mixologyState = MixologyState.CONVEYER_BELT; return; } PotionOrder nonFulfilledPotion = nonFulfilledPotions.get(0); if (Rs2Player.isAnimating()) { if (agitatorQuickActionTicks > 0 && config.useQuickActionOnAgitator()) { int clicks = Rs2AntibanSettings.naturalMouse ? Rs2Random.between(4, 6) : Rs2Random.between(6, 10); for (int i = 0; i < clicks; i++) { quickActionProcessPotion(nonFulfilledPotion); } agitatorQuickActionTicks = 0; } else if (alembicQuickActionTicks > 0 && config.useQuickActionOnAlembic()) { quickActionProcessPotion(nonFulfilledPotion); alembicQuickActionTicks = 0; } if (nonFulfilledPotion.potionModifier().alchemyObject() == AlchemyObject.RETORT && config.useQuickActionOnRetort()&&Microbot.getVarbitValue(11327)<15&&Microbot.getVarbitValue(11327)!=0) { quickActionProcessPotion(nonFulfilledPotion); sleep(350, 400); } return; } if (nonFulfilledPotion == null || !Rs2Inventory.hasItem(nonFulfilledPotion.potionType().itemId())) { mixologyState = MixologyState.MIX_POTION_STAGE_1; return; } processPotion(nonFulfilledPotion); sleepUntil(Rs2Player::isAnimating); break; case CONVEYER_BELT: if (potionOrders.stream().noneMatch(x -> Rs2Inventory.hasItem(x.potionType().getFulfilledItemId()))) { mixologyState = MixologyState.MIX_POTION_STAGE_1; return; } if (Rs2GameObject.interact(AlchemyObject.CONVEYOR_BELT.objectId())) { Rs2Inventory.waitForInventoryChanges(5000); currentAgaPoints = getAgaPoints(); currentLyePoints = getLyePoints(); currentMoxPoints = getMoxPoints(); } break; } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Total time for loop " + totalTime); } catch (Exception ex) { System.out.println(ex.getMessage()); } }, 0, 100, TimeUnit.MILLISECONDS); return true; } private boolean hasAllFulFilledItems() { Map<Integer, Integer> itemsToCheck = new HashMap<>(); boolean hasAllFulFilledItems = true; for (PotionOrder _potionOrder : potionOrders) { int key = _potionOrder.potionType().getFulfilledItemId(); int value = itemsToCheck.getOrDefault(key, 0); itemsToCheck.put(key, value + 1); } for (int itemId : itemsToCheck.keySet()) { PotionOrder _potionOrder = potionOrders .stream() .filter(x -> x.potionType().getFulfilledItemId() == itemId) .findFirst() .orElse(null); if (_potionOrder == null) continue; int itemAmount = itemsToCheck.getOrDefault(itemId, 1); if (!Rs2Inventory.hasItemAmount(itemId, itemAmount)) { hasAllFulFilledItems = false; } } return hasAllFulFilledItems; } private static void processPotion(PotionOrder nonFulfilledPotion) { switch (nonFulfilledPotion.potionModifier()) { case HOMOGENOUS: GameObject agitator = (GameObject) Rs2GameObject.findObjectById(AlchemyObject.AGITATOR.objectId()); if (agitator != null && (((DynamicObject) agitator.getRenderable()).getAnimation().getId() == 11633 || ((DynamicObject) agitator.getRenderable()).getAnimation().getId() == 11632)) { Rs2GameObject.interact(AlchemyObject.AGITATOR.objectId()); } else { Rs2Inventory.useItemOnObject(nonFulfilledPotion.potionType().itemId(), AlchemyObject.AGITATOR.objectId()); } break; case CONCENTRATED: GameObject retort = (GameObject) Rs2GameObject.findObjectById(AlchemyObject.RETORT.objectId()); if (retort != null && (((DynamicObject) retort.getRenderable()).getAnimation().getId() == 11643 || ((DynamicObject) retort.getRenderable()).getAnimation().getId() == 11642)) { Rs2GameObject.interact(AlchemyObject.RETORT.objectId()); } else { Rs2Inventory.useItemOnObject(nonFulfilledPotion.potionType().itemId(), AlchemyObject.RETORT.objectId()); } break; case CRYSTALISED: GameObject alembic = (GameObject) Rs2GameObject.findObjectById(AlchemyObject.ALEMBIC.objectId()); if (alembic != null && (((DynamicObject) alembic.getRenderable()).getAnimation().getId() == 11638 || ((DynamicObject) alembic.getRenderable()).getAnimation().getId() == 11637)) { Rs2GameObject.interact(AlchemyObject.ALEMBIC.objectId()); } else { Rs2Inventory.useItemOnObject(nonFulfilledPotion.potionType().itemId(), AlchemyObject.ALEMBIC.objectId()); } break; } } private static void quickActionProcessPotion(PotionOrder nonFulfilledPotion) { switch (nonFulfilledPotion.potionModifier()) { case HOMOGENOUS: Rs2GameObject.interact(AlchemyObject.AGITATOR.objectId()); break; case CONCENTRATED: Rs2GameObject.interact(AlchemyObject.RETORT.objectId()); break; case CRYSTALISED: Rs2GameObject.interact(AlchemyObject.ALEMBIC.objectId()); break; } } private void createPotion(PotionOrder potionOrder, MixologyConfig config) { for (PotionComponent component : potionOrder.potionType().components()) { if (canCreatePotion(potionOrder)) break; if (component.character() == 'A') { Rs2GameObject.interact(AlchemyObject.AGA_LEVER.objectId()); } else if (component.character() == 'L') { Rs2GameObject.interact(AlchemyObject.LYE_LEVER.objectId()); } else if (component.character() == 'M') { Rs2GameObject.interact(AlchemyObject.MOX_LEVER.objectId()); } if (config.useQuickActionLever()) { Rs2Player.waitForAnimation(); } else { sleepUntil(Rs2Player::isAnimating); final int sleep = Rs2Random.between(300, 600); sleepGaussian(sleep, sleep / 4); } leverRetries++; } } private boolean canCreatePotion(PotionOrder potionOrder) { // Get the mixer game objects GameObject[] mixers = { (GameObject) Rs2GameObject.findObjectById(ObjectID.MM_LAB_MIXER_03), // mixer3 (GameObject) Rs2GameObject.findObjectById(ObjectID.MM_LAB_MIXER_02), // mixer2 (GameObject) Rs2GameObject.findObjectById(ObjectID.MM_LAB_MIXER_01) // mixer1 }; // Check if any mixers are missing if (Arrays.stream(mixers).anyMatch(Objects::isNull)) { return false; } // Get animations in correct order int[] currentAnimations = Arrays.stream(mixers) .map(mixer -> ((DynamicObject) mixer.getRenderable()).getAnimation().getId()) .mapToInt(Integer::intValue) .toArray(); // Map components to their valid animations Map<Character, int[]> componentAnimations = Map.of( 'A', new int[]{11615, 11609, 11612}, // AGA animations 'M', new int[]{11617, 11614, 11607}, // MOX animations 'L', new int[]{11608, 11611, 11618} // LYE animations ); // Check each position for (int i = 0; i < potionOrder.potionType().components().length; i++) { char expectedComponent = potionOrder.potionType().components()[i].character(); int currentAnimation = currentAnimations[i]; boolean isValid = Arrays.stream(componentAnimations.get(expectedComponent)) .anyMatch(validAnim -> validAnim == currentAnimation); if (!isValid) { return false; } } return true; } private int getMoxPoints() { return Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[16].getText()); } private int getAgaPoints() { return Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[17].getText()); } private int getLyePoints() { return Integer.parseInt(Rs2Widget.getWidget(882, 2).getDynamicChildren()[18].getText()); } @Override public void shutdown() { super.shutdown(); } }
0
0.9182
1
0.9182
game-dev
MEDIA
0.600625
game-dev
0.961921
1
0.961921
Ayfri/Kore
6,090
kore/src/main/kotlin/io/github/ayfri/kore/features/tags/Tag.kt
package io.github.ayfri.kore.features.tags import io.github.ayfri.kore.DataPack import io.github.ayfri.kore.Generator import io.github.ayfri.kore.arguments.types.ResourceLocationArgument import io.github.ayfri.kore.arguments.types.TaggedResourceLocationArgument import io.github.ayfri.kore.utils.resolve import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.descriptors.element import kotlinx.serialization.encoding.* import kotlinx.io.files.Path import kotlin.reflect.KClass import kotlin.reflect.full.companionObject import kotlin.reflect.full.companionObjectInstance import kotlin.reflect.full.memberFunctions /** * Data-driven tag definition for Minecraft Java Edition. * * A tag is a JSON structure used in data packs to group items, blocks, entities, etc. * It can be used in commands, loot tables, advancements, and other data-driven features * to filter or trigger actions based on game state. * * Minecraft Wiki: https://minecraft.wiki/w/Tag */ @Serializable(with = Tag.Companion.TagSerializer::class) data class Tag<out T : TaggedResourceLocationArgument>( @Transient override var fileName: String = "tag", @Transient var type: String = "", var replace: Boolean = false, var values: List<TagEntry> = emptyList(), ) : Generator("tags") { @Transient @PublishedApi internal var tagClass: KClass<out TaggedResourceLocationArgument> = TaggedResourceLocationArgument::class @PublishedApi internal val invokeFunction get() = tagClass.companionObject!!.memberFunctions.first { it.name == "invoke" } override fun generateJson(dataPack: DataPack) = dataPack.jsonEncoder.encodeToString(TagSerializer, this) override fun getPathFromDataDir(dir: Path, namespace: String): Path { return dir.resolve(namespace, resourceFolder, type, "$fileName.json") } operator fun plusAssign(value: TagEntry) { values += value } operator fun plusAssign(value: String) { values += TagEntry(value) } operator fun plusAssign(value: Pair<String, Boolean>) { values += TagEntry(value.first, value.second) } operator fun plusAssign(value: ResourceLocationArgument) { values += TagEntry(value.asString()) } fun add( name: String, namespace: String = "minecraft", tag: Boolean = false, required: Boolean? = null, ) { values += TagEntry("${if (tag) "#" else ""}$namespace:$name", required) } fun add(value: String, required: Boolean? = null) { values += TagEntry(value, required) } fun add(value: ResourceLocationArgument, required: Boolean? = null) { values += TagEntry(value.asString(), required) } companion object { data object TagSerializer : KSerializer<Tag<*>> { override val descriptor = buildClassSerialDescriptor("Tag") { element<Boolean>("replace") element<List<TagEntry>>("values") } override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) { var replace = false var values = emptyList<TagEntry>() while (true) { when (val index = decodeElementIndex(descriptor)) { 0 -> replace = decodeBooleanElement(descriptor, 0) 1 -> values = decodeSerializableElement(descriptor, 1, ListSerializer(TagEntry.serializer())) CompositeDecoder.DECODE_DONE -> break else -> error("Unexpected index: $index") } } Tag<TaggedResourceLocationArgument>(replace = replace, values = values) } override fun serialize(encoder: Encoder, value: Tag<*>) = encoder.encodeStructure(descriptor) { encodeBooleanElement(descriptor, 0, value.replace) encodeSerializableElement(descriptor, 1, ListSerializer(TagEntry.serializer()), value.values) } } } } /** * Create and register a tag in this [DataPack]. The type parameter [T] selects the tag registry * (e.g. `BlockTagArgument`, `ItemTagArgument`, etc.). * * Produces `data/<namespace>/tags/<type>/<fileName>.json`. * * Minecraft Wiki: https://minecraft.wiki/w/Tag */ inline fun <reified T : TaggedResourceLocationArgument> DataPack.tag( fileName: String = "tag", type: String = "", namespace: String = name, replace: Boolean = false, block: Tag<T>.() -> Unit = {}, ): T { val tag = Tag<T>(fileName = fileName, type = type, replace = replace).apply { this.namespace = namespace tagClass = T::class block() } tags += tag return tag.invokeFunction.call(tag.tagClass.companionObjectInstance, fileName, tag.namespace ?: namespace) as T } @JvmName("tagUntyped") /** * Create and register a tag in this [DataPack]. * * Untyped variant of [tag] when the registry type is decided at call site. * * Produces `data/<namespace>/tags/<type>/<fileName>.json`. */ inline fun DataPack.tag( fileName: String = "tag", type: String = "", namespace: String = name, replace: Boolean = false, block: Tag<TaggedResourceLocationArgument>.() -> Unit = {}, ) = tag<TaggedResourceLocationArgument>(fileName, type, namespace, replace, block) /** * Add entries to an existing tag, or create it if missing. */ inline fun <reified T : TaggedResourceLocationArgument> DataPack.addToTag( fileName: String = "tag", type: String = "", namespace: String = name, block: Tag<T>.() -> Unit = {}, ): T { val tag = tags.find { it.fileName == fileName && it.type == type && it.namespace == namespace && it.tagClass == T::class } as Tag<T>? ?: Tag<T>(fileName = fileName, type = type).also { it.namespace = namespace it.tagClass = T::class tags += it } tag.apply(block) return tag.invokeFunction.call(tag.tagClass.companionObjectInstance, fileName, tag.namespace ?: namespace) as T } @JvmName("addToTagUntyped") /** * Untyped variant of [addToTag]. * * Produces `data/<namespace>/tags/<type>/<fileName>.json`. */ inline fun DataPack.addToTag( fileName: String = "tag", type: String = "", namespace: String = name, block: Tag<TaggedResourceLocationArgument>.() -> Unit = {}, ) = addToTag<TaggedResourceLocationArgument>(fileName, type, namespace, block)
0
0.853749
1
0.853749
game-dev
MEDIA
0.935246
game-dev
0.88508
1
0.88508
DeltaV-Station/Delta-v
4,438
Content.Client/_DV/VendingMachines/ShopVendorSystem.cs
using Content.Shared._DV.VendingMachines; using Content.Shared.VendingMachines; using Robust.Client.Animations; using Robust.Client.GameObjects; namespace Content.Client._DV.VendingMachines; public sealed class ShopVendorSystem : SharedShopVendorSystem { [Dependency] private readonly AnimationPlayerSystem _animationPlayer = default!; [Dependency] private readonly AppearanceSystem _appearance = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<ShopVendorComponent, AppearanceChangeEvent>(OnAppearanceChange); SubscribeLocalEvent<ShopVendorComponent, AnimationCompletedEvent>(OnAnimationCompleted); } // copied from vending machines because its not reusable in other systems :) private void OnAnimationCompleted(Entity<ShopVendorComponent> ent, ref AnimationCompletedEvent args) { UpdateAppearance((ent, ent.Comp)); } private void OnAppearanceChange(Entity<ShopVendorComponent> ent, ref AppearanceChangeEvent args) { UpdateAppearance((ent, ent.Comp, args.Sprite)); } private void UpdateAppearance(Entity<ShopVendorComponent, SpriteComponent?> ent) { if (!Resolve(ent, ref ent.Comp2)) return; if (!_appearance.TryGetData<VendingMachineVisualState>(ent, VendingMachineVisuals.VisualState, out var state)) state = VendingMachineVisualState.Normal; var sprite = ent.Comp2; SetLayerState(VendingMachineVisualLayers.Base, ent.Comp1.OffState, sprite); SetLayerState(VendingMachineVisualLayers.Screen, ent.Comp1.ScreenState, sprite); switch (state) { case VendingMachineVisualState.Normal: SetLayerState(VendingMachineVisualLayers.BaseUnshaded, ent.Comp1.NormalState, sprite); break; case VendingMachineVisualState.Deny: if (ent.Comp1.LoopDenyAnimation) SetLayerState(VendingMachineVisualLayers.BaseUnshaded, ent.Comp1.DenyState, sprite); else PlayAnimation(ent, VendingMachineVisualLayers.BaseUnshaded, ent.Comp1.DenyState, ent.Comp1.DenyDelay, sprite); break; case VendingMachineVisualState.Eject: PlayAnimation(ent, VendingMachineVisualLayers.BaseUnshaded, ent.Comp1.EjectState, ent.Comp1.EjectDelay, sprite); break; case VendingMachineVisualState.Broken: HideLayers(sprite); SetLayerState(VendingMachineVisualLayers.Base, ent.Comp1.BrokenState, sprite); break; case VendingMachineVisualState.Off: HideLayers(sprite); break; } } private static void SetLayerState(VendingMachineVisualLayers layer, string? state, SpriteComponent sprite) { if (state == null) return; sprite.LayerSetVisible(layer, true); sprite.LayerSetAutoAnimated(layer, true); sprite.LayerSetState(layer, state); } private void PlayAnimation(EntityUid uid, VendingMachineVisualLayers layer, string? state, TimeSpan time, SpriteComponent sprite) { if (state == null || _animationPlayer.HasRunningAnimation(uid, state)) return; var animation = GetAnimation(layer, state, time); sprite.LayerSetVisible(layer, true); _animationPlayer.Play(uid, animation, state); } private static Animation GetAnimation(VendingMachineVisualLayers layer, string state, TimeSpan time) { return new Animation { Length = time, AnimationTracks = { new AnimationTrackSpriteFlick { LayerKey = layer, KeyFrames = { new AnimationTrackSpriteFlick.KeyFrame(state, 0f) } } } }; } private static void HideLayers(SpriteComponent sprite) { HideLayer(VendingMachineVisualLayers.BaseUnshaded, sprite); HideLayer(VendingMachineVisualLayers.Screen, sprite); } private static void HideLayer(VendingMachineVisualLayers layer, SpriteComponent sprite) { if (!sprite.LayerMapTryGet(layer, out var actualLayer)) return; sprite.LayerSetVisible(actualLayer, false); } }
0
0.697824
1
0.697824
game-dev
MEDIA
0.979176
game-dev
0.743597
1
0.743597
Eaglercraft-Archive/EaglercraftX-1.8-workspace
11,420
src/game/java/net/minecraft/block/BlockLever.java
package net.minecraft.block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; /**+ * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. * * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * * EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) 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. * */ public class BlockLever extends Block { public static PropertyEnum<BlockLever.EnumOrientation> FACING; public static final PropertyBool POWERED = PropertyBool.create("powered"); protected BlockLever() { super(Material.circuits); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, BlockLever.EnumOrientation.NORTH) .withProperty(POWERED, Boolean.valueOf(false))); this.setCreativeTab(CreativeTabs.tabRedstone); } public static void bootstrapStates() { FACING = PropertyEnum.<BlockLever.EnumOrientation>create("facing", BlockLever.EnumOrientation.class); } public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { return null; } /**+ * Used to determine ambient occlusion and culling when * rebuilding chunks for render */ public boolean isOpaqueCube() { return false; } public boolean isFullCube() { return false; } /**+ * Check whether this Block can be placed on the given side */ public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { return func_181090_a(world, blockpos, enumfacing.getOpposite()); } public boolean canPlaceBlockAt(World world, BlockPos blockpos) { EnumFacing[] facings = EnumFacing._VALUES; for (int i = 0; i < facings.length; ++i) { EnumFacing enumfacing = facings[i]; if (func_181090_a(world, blockpos, enumfacing)) { return true; } } return false; } protected static boolean func_181090_a(World parWorld, BlockPos parBlockPos, EnumFacing parEnumFacing) { return BlockButton.func_181088_a(parWorld, parBlockPos, parEnumFacing); } /**+ * Called by ItemBlocks just before a block is actually set in * the world, to allow for adjustments to the IBlockstate */ public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, float var6, int var7, EntityLivingBase entitylivingbase) { IBlockState iblockstate = this.getDefaultState().withProperty(POWERED, Boolean.valueOf(false)); if (func_181090_a(world, blockpos, enumfacing.getOpposite())) { return iblockstate.withProperty(FACING, BlockLever.EnumOrientation.forFacings(enumfacing, entitylivingbase.getHorizontalFacing())); } else { EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; for (int i = 0; i < facings.length; ++i) { EnumFacing enumfacing1 = facings[i]; if (enumfacing1 != enumfacing && func_181090_a(world, blockpos, enumfacing1.getOpposite())) { return iblockstate.withProperty(FACING, BlockLever.EnumOrientation.forFacings(enumfacing1, entitylivingbase.getHorizontalFacing())); } } if (World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { return iblockstate.withProperty(FACING, BlockLever.EnumOrientation.forFacings(EnumFacing.UP, entitylivingbase.getHorizontalFacing())); } else { return iblockstate; } } } public static int getMetadataForFacing(EnumFacing facing) { switch (facing) { case DOWN: return 0; case UP: return 5; case NORTH: return 4; case SOUTH: return 3; case WEST: return 2; case EAST: return 1; default: return -1; } } /**+ * Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { if (this.func_181091_e(world, blockpos, iblockstate) && !func_181090_a(world, blockpos, ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing().getOpposite())) { this.dropBlockAsItem(world, blockpos, iblockstate, 0); world.setBlockToAir(blockpos); } } private boolean func_181091_e(World parWorld, BlockPos parBlockPos, IBlockState parIBlockState) { if (this.canPlaceBlockAt(parWorld, parBlockPos)) { return true; } else { this.dropBlockAsItem(parWorld, parBlockPos, parIBlockState, 0); parWorld.setBlockToAir(parBlockPos); return false; } } public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { float f = 0.1875F; switch ((BlockLever.EnumOrientation) iblockaccess.getBlockState(blockpos).getValue(FACING)) { case EAST: this.setBlockBounds(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); break; case WEST: this.setBlockBounds(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); break; case SOUTH: this.setBlockBounds(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); break; case NORTH: this.setBlockBounds(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); break; case UP_Z: case UP_X: f = 0.25F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); break; case DOWN_X: case DOWN_Z: f = 0.25F; this.setBlockBounds(0.5F - f, 0.4F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); } } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, EnumFacing var5, float var6, float var7, float var8) { if (world.isRemote) { return true; } else { iblockstate = iblockstate.cycleProperty(POWERED); world.setBlockState(blockpos, iblockstate, 3); world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0.6F : 0.5F); world.notifyNeighborsOfStateChange(blockpos, this); EnumFacing enumfacing = ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing(); world.notifyNeighborsOfStateChange(blockpos.offset(enumfacing.getOpposite()), this); return true; } } public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { world.notifyNeighborsOfStateChange(blockpos, this); EnumFacing enumfacing = ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing(); world.notifyNeighborsOfStateChange(blockpos.offset(enumfacing.getOpposite()), this); } super.breakBlock(world, blockpos, iblockstate); } public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; } public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 : (((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing() == enumfacing ? 15 : 0); } /**+ * Can this block provide power. Only wire currently seems to * have this change based on its state. */ public boolean canProvidePower() { return true; } /**+ * Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int i) { return this.getDefaultState().withProperty(FACING, BlockLever.EnumOrientation.byMetadata(i & 7)) .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); } /**+ * Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; i = i | ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getMetadata(); if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { i |= 8; } return i; } protected BlockState createBlockState() { return new BlockState(this, new IProperty[] { FACING, POWERED }); } public static enum EnumOrientation implements IStringSerializable { DOWN_X(0, "down_x", EnumFacing.DOWN), EAST(1, "east", EnumFacing.EAST), WEST(2, "west", EnumFacing.WEST), SOUTH(3, "south", EnumFacing.SOUTH), NORTH(4, "north", EnumFacing.NORTH), UP_Z(5, "up_z", EnumFacing.UP), UP_X(6, "up_x", EnumFacing.UP), DOWN_Z(7, "down_z", EnumFacing.DOWN); private static final BlockLever.EnumOrientation[] META_LOOKUP = new BlockLever.EnumOrientation[8]; private final int meta; private final String name; private final EnumFacing facing; private EnumOrientation(int meta, String name, EnumFacing facing) { this.meta = meta; this.name = name; this.facing = facing; } public int getMetadata() { return this.meta; } public EnumFacing getFacing() { return this.facing; } public String toString() { return this.name; } public static BlockLever.EnumOrientation byMetadata(int meta) { if (meta < 0 || meta >= META_LOOKUP.length) { meta = 0; } return META_LOOKUP[meta]; } public static BlockLever.EnumOrientation forFacings(EnumFacing clickedSide, EnumFacing entityFacing) { switch (clickedSide) { case DOWN: switch (entityFacing.getAxis()) { case X: return DOWN_X; case Z: return DOWN_Z; default: throw new IllegalArgumentException( "Invalid entityFacing " + entityFacing + " for facing " + clickedSide); } case UP: switch (entityFacing.getAxis()) { case X: return UP_X; case Z: return UP_Z; default: throw new IllegalArgumentException( "Invalid entityFacing " + entityFacing + " for facing " + clickedSide); } case NORTH: return NORTH; case SOUTH: return SOUTH; case WEST: return WEST; case EAST: return EAST; default: throw new IllegalArgumentException("Invalid facing: " + clickedSide); } } public String getName() { return this.name; } static { BlockLever.EnumOrientation[] orientations = values(); for (int i = 0; i < orientations.length; ++i) { META_LOOKUP[orientations[i].getMetadata()] = orientations[i]; } } } }
0
0.961779
1
0.961779
game-dev
MEDIA
0.959062
game-dev
0.982178
1
0.982178
emawind84/SelacoVR
5,675
src/p_tick.cpp
//----------------------------------------------------------------------------- // // Copyright 1993-1996 id Software // Copyright 1999-2016 Randy Heit // Copyright 2002-2016 Christoph Oelckers // // 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/ // //----------------------------------------------------------------------------- // // DESCRIPTION: // Ticker. // //----------------------------------------------------------------------------- #include "p_local.h" #include "p_effect.h" #include "c_console.h" #include "b_bot.h" #include "doomstat.h" #include "sbar.h" #include "r_data/r_interpolate.h" #include "d_player.h" #include "r_utility.h" #include "p_spec.h" #include "g_levellocals.h" #include "events.h" #include "actorinlines.h" #include "g_game.h" #include "i_interface.h" extern gamestate_t wipegamestate; extern uint8_t globalfreeze, globalchangefreeze; //========================================================================== // // P_CheckTickerPaused // // Returns true if the ticker should be paused. In that case, it also // pauses sound effects and possibly music. If the ticker should not be // paused, then it returns false but does not unpause anything. // //========================================================================== bool P_CheckTickerPaused () { // pause if in menu or console and at least one tic has been run if ( !netgame && gamestate != GS_TITLELEVEL && ((menuactive != MENU_Off && menuactive != MENU_OnNoPause) || ConsoleState == c_down || ConsoleState == c_falling) && !demoplayback && !demorecording && players[consoleplayer].viewz != NO_VALUE && wipegamestate == gamestate) { // Only the current UI level's settings are relevant for sound. S_PauseSound (!(primaryLevel->flags2 & LEVEL2_PAUSE_MUSIC_IN_MENUS), false); return true; } return false; } // // P_Ticker // void P_Ticker (void) { int i; for (auto Level : AllLevels()) { Level->interpolator.UpdateInterpolations(); } r_NoInterpolate = true; if (!demoplayback) { // This is a separate slot from the wipe in D_Display(), because this // is delayed slightly due to latency. (Even on a singleplayer game!) // GSnd->SetSfxPaused(!!playerswiping, 2); } // run the tic if (paused || P_CheckTickerPaused()) { // This must run even when the game is paused to catch changes from netevents before the frame is rendered. for (auto Level : AllLevels()) { auto it = Level->GetThinkerIterator<AActor>(); AActor* ac; while ((ac = it.Next())) { if (ac->flags8 & MF8_RECREATELIGHTS) { ac->flags8 &= ~MF8_RECREATELIGHTS; ac->SetDynamicLights(); } } } return; } DPSprite::NewTick(); // [RH] Frozen mode is only changed every 4 tics, to make it work with A_Tracer(). // This may not be perfect but it is not really relevant for sublevels that tracer homing behavior is preserved. if ((primaryLevel->maptime & 3) == 0) { if (globalchangefreeze) { globalfreeze ^= 1; globalchangefreeze = 0; for (auto Level : AllLevels()) { Level->frozenstate = (Level->frozenstate & ~2) | (2 * globalfreeze); } } } // [BC] Do a quick check to see if anyone has the freeze time power. If they do, // then don't resume the sound, since one of the effects of that power is to shut // off the music. for (i = 0; i < MAXPLAYERS; i++ ) { if (playeringame[i] && players[i].timefreezer != 0) break; } if ( i == MAXPLAYERS ) S_ResumeSound (false); P_ResetSightCounters (false); R_ClearInterpolationPath(); // Since things will be moving, it's okay to interpolate them in the renderer. r_NoInterpolate = false; // Reset all actor interpolations on all levels before the current thinking turn so that indirect actor movement gets properly interpolated. for (auto Level : AllLevels()) { // todo: set up a sandbox for secondary levels here. auto it = Level->GetThinkerIterator<AActor>(); AActor *ac; while ((ac = it.Next())) { ac->ClearInterpolation(); ac->ClearFOVInterpolation(); } P_ThinkParticles(Level); // [RH] make the particles think for (i = 0; i < MAXPLAYERS; i++) if (Level->PlayerInGame(i)) P_PlayerThink(Level->Players[i]); // [ZZ] call the WorldTick hook Level->localEventManager->WorldTick(); Level->Tick(); // [RH] let the level tick Level->Thinkers.RunThinkers(Level); P_ThinkDefinedParticles(Level); // Run after the world tick so we get proper moving sector heights //if added by MC: Freeze mode. if (!Level->isFrozen()) { P_UpdateSpecials(Level); } // for par times Level->time++; Level->maptime++; Level->totaltime++; } if (players[consoleplayer].mo != NULL) { if (players[consoleplayer].mo->Vel.Length() > primaryLevel->max_velocity) { primaryLevel->max_velocity = players[consoleplayer].mo->Vel.Length(); } primaryLevel->avg_velocity += (players[consoleplayer].mo->Vel.Length() - primaryLevel->avg_velocity) / primaryLevel->maptime; } StatusBar->CallTick(); // Status bar should tick AFTER the thinkers to properly reflect the level's state at this time. }
0
0.862421
1
0.862421
game-dev
MEDIA
0.958878
game-dev
0.960191
1
0.960191
ParadiseSS13/Paradise
83,352
code/datums/mind.dm
/* Note from Carnie: The way datum/mind stuff works has been changed a lot. Minds now represent IC characters rather than following a client around constantly. Guidelines for using minds properly: - Never mind.transfer_to(ghost). The var/current and var/original of a mind must always be of type mob/living! ghost.mind is however used as a reference to the ghost's corpse - When creating a new mob for an existing IC character (e.g. cloning a dead guy or borging a brain of a human) the existing mind of the old mob should be transfered to the new mob like so: mind.transfer_to(new_mob) - You must not assign key= or ckey= after transfer_to() since the transfer_to transfers the client for you. By setting key or ckey explicitly after transfering the mind with transfer_to you will cause bugs like DCing the player. - IMPORTANT NOTE 2, if you want a player to become a ghost, use mob.ghostize() It does all the hard work for you. - When creating a new mob which will be a new IC character (e.g. putting a shade in a construct or randomly selecting a ghost to become a xeno during an event). Simply assign the key or ckey like you've always done. new_mob.key = key The Login proc will handle making a new mob for that mobtype (including setting up stuff like mind.name). Simple! However if you want that mind to have any special properties like being a traitor etc you will have to do that yourself. */ /datum/mind var/key var/name //replaces mob/var/original_name var/mob/living/current /// A serialized copy of this mind's body when it was destroyed, for admin respawn usage. var/destroyed_body_json /// The original mob's UID. Used for example to see if a silicon with antag status is actually malf. Or just an antag put in a borg var/original_mob_UID /// The original mob's name. Used in Dchat messages var/original_mob_name var/active = FALSE var/memory var/assigned_role //assigned role is what job you're assigned to when you join the station. var/playtime_role //if set, overrides your assigned_role for the purpose of playtime awards. Set by IDcomputer when your ID is changed. var/special_role //special roles are typically reserved for antags or roles like ERT. If you want to avoid a character being automatically announced by the AI, on arrival (becuase they're an off station character or something); ensure that special_role and assigned_role are equal. var/offstation_role = FALSE //set to true for ERT, deathsquad, abductors, etc, that can go from and to CC at will and shouldn't be antag targets var/list/restricted_roles = list() var/list/spell_list = list() // Wizard mode & "Give Spell" badmin button. var/datum/martial_art/martial_art var/list/known_martial_arts = list() var/role_alt_title var/datum/objective_holder/objective_holder ///a list of objectives that a player with this job could complete for space credit rewards var/list/job_objectives = list() var/list/datum/objective/special_verbs = list() var/list/targets = list() /// Tracks if this mind has been a rev or not var/has_been_rev = FALSE var/miming = 0 // Mime's vow of silence /// A list of all the antagonist datums that the player is (does not include undatumized antags) var/list/antag_datums /// A lazy list of all teams the player is part of but doesnt have an antag role for, (i.e. a custom admin team) var/list/teams var/antag_hud_icon_state = null //this mind's ANTAG_HUD should have this icon_state var/datum/atom_hud/antag/antag_hud = null //this mind's antag HUD var/datum/mindslaves/som //stands for slave or master...hush.. var/isblessed = FALSE // is this person blessed by a chaplain? var/num_blessed = 0 // for prayers var/suicided = FALSE //put this here for easier tracking ingame var/datum/money_account/initial_account //zealot_master is a reference to the mob that converted them into a zealot (for ease of investigation and such) var/mob/living/carbon/human/zealot_master = null var/list/learned_recipes //List of learned recipe TYPES. /datum/mind/New(new_key) key = new_key objective_holder = new(src) /datum/mind/Destroy() SSticker.minds -= src remove_all_antag_datums() qdel(objective_holder) unbind() return ..() /datum/mind/proc/set_original_mob(mob/original) original_mob_name = original.real_name original_mob_UID = original.UID() /datum/mind/proc/is_original_mob(mob/M) return original_mob_UID == M.UID() // Do not use for admin related things as this can hide the mob's ckey /datum/mind/proc/get_display_key() // Lets try find a client so we can check their prefs var/client/C = null var/cannonical_key = ckey(key) if(current?.client) // Active client C = current.client else if(cannonical_key in GLOB.directory) // Do a directory lookup on the last ckey this mind had // If theyre online we can grab them still and check prefs C = GLOB.directory[cannonical_key] // Ok we found a client, be it their active or their last // Now we see if we need to respect their privacy var/out_ckey if(C) if(C.prefs.toggles2 & PREFTOGGLE_2_ANON) out_ckey = "(Anon)" else out_ckey = C.ckey else // No client. Just mark as DC'd. out_ckey = "(Disconnected)" return out_ckey /datum/mind/proc/archive_deleted_body() SIGNAL_HANDLER // COMSIG_PARENT_QDELETING if(isliving(current)) destroyed_body_json = json_encode(current.serialize()) /datum/mind/proc/bind_to(mob/living/new_character) current = new_character new_character.mind = src RegisterSignal(current, COMSIG_PARENT_QDELETING, PROC_REF(archive_deleted_body), override = TRUE) /datum/mind/proc/unbind() if(isnull(current)) return UnregisterSignal(current, COMSIG_PARENT_QDELETING) if(current.mind == src) current.mind = null current = null /datum/mind/proc/transfer_to(mob/living/new_character) var/datum/atom_hud/antag/hud_to_transfer = antag_hud //we need this because leave_hud() will clear this list var/mob/living/old_current = current if(!istype(new_character)) stack_trace("transfer_to(): Some idiot has tried to transfer_to() a non mob/living mob.") if(current) //remove ourself from our old body's mind variable if(isliving(current)) current.med_hud_set_status() leave_all_huds() //leave all the huds in the old body, so it won't get huds if somebody else enters it SStgui.on_transfer(current, new_character) new_character.job = current.job //transfer our job over to the new body unbind() if(new_character.mind) //remove any mind currently in our new body's mind variable new_character.mind.unbind() bind_to(new_character) for(var/a in antag_datums) //Makes sure all antag datums effects are applied in the new body var/datum/antagonist/A = a A.on_body_transfer(old_current, current) transfer_antag_huds(hud_to_transfer) //inherit the antag HUD transfer_actions(new_character) if(martial_art) for(var/datum/martial_art/MA in known_martial_arts) MA.reset_combos(old_current) // Clear combos on old body if(MA.temporary) MA.remove(current) else MA.remove(current) MA.teach(current) if(active) new_character.key = key //now transfer the key to link the client to our new body SEND_SIGNAL(src, COMSIG_MIND_TRANSER_TO, new_character) SEND_SIGNAL(new_character, COMSIG_BODY_TRANSFER_TO) if(ishuman(new_character)) var/mob/living/carbon/human/H = new_character if(H.mind in SSticker.mode.syndicates) SSticker.mode.update_synd_icons_added(H.mind) /datum/mind/proc/store_memory(new_text) memory += "[new_text]<br>" /datum/mind/proc/wipe_memory() memory = null /datum/mind/proc/show_memory(mob/recipient, window = 1) if(!recipient) recipient = current var/list/output = list() output.Add("<!DOCTYPE html><meta charset='UTF-8'><b>[current.real_name]'s Memories:</b><hr>") output.Add(memory) for(var/datum/antagonist/A in antag_datums) output.Add(A.antag_memory) if(has_objectives()) output.Add("<HR><B>Objectives:</B>") output.Add(gen_objective_text()) if(LAZYLEN(job_objectives)) output.Add("<HR><B>Job Objectives:</B><UL>") var/obj_count = 1 for(var/datum/job_objective/objective in job_objectives) output.Add("<LI><B>Task #[obj_count]</B>: [objective.description]</LI>") obj_count++ output.Add("</UL>") output = output.Join("<br>") if(window) recipient << browse(output, "window=memory") else to_chat(recipient, "<i>[output]</i>") /datum/mind/proc/gen_objective_text(admin = FALSE) if(!has_objectives()) return "<b>No Objectives.</b><br>" var/list/text = list() var/obj_count = 1 // If they don't have any objectives, "" will be returned. for(var/datum/objective/objective in get_all_objectives()) text.Add("<b>Objective #[obj_count++]</b>: [objective.explanation_text][admin ? get_admin_objective_edit(objective) : ""]") return text.Join("<br>") /datum/mind/proc/get_admin_objective_edit(datum/objective/objective) return " <a href='byond://?src=[UID()];obj_edit=\ref[objective]'>Edit</a> \ <a href='byond://?src=[UID()];obj_delete=\ref[objective]'>Delete</a> \ <a href='byond://?src=[UID()];obj_completed=\ref[objective]'>\ <font color=[objective.completed ? "green" : "red"]>Toggle Completion</font></a>" /** * A quicker version of get_all_objectives() but only for seeing if they have any objectives at all */ /datum/mind/proc/has_objectives(include_team = TRUE) if(objective_holder.has_objectives()) return TRUE for(var/datum/antagonist/A as anything in antag_datums) if(A.has_antag_objectives(include_team)) // this checks teams also return TRUE // For custom non-antag role teams if(include_team && LAZYLEN(teams)) for(var/datum/team/team as anything in teams) if(team.objective_holder.has_objectives()) return TRUE return FALSE /** * Gets every objective this mind owns, including all of those from any antag datums and teams they have, and returns them as a list. */ /datum/mind/proc/get_all_objectives(include_team = TRUE) var/list/all_objectives = list() all_objectives += objective_holder.get_objectives() // Get their personal objectives for(var/datum/antagonist/A as anything in antag_datums) all_objectives += A.get_antag_objectives(include_team) // Add all antag datum objectives, and possibly antag team objectives // For custom non-antag role teams if(include_team && LAZYLEN(teams)) for(var/datum/team/team as anything in teams) all_objectives += team.objective_holder.get_objectives() return all_objectives /** * Add an objective to the mind */ /datum/mind/proc/add_mind_objective(datum/objective/O, _explanation_text, mob/target_override) if(ispath(O)) O = new O() if(O.owner) stack_trace("[O], [O.type] was assigned as an objective to [src] (mind), but already had an owner: [O.owner] (mind). Overriding.") O.owner = src return objective_holder.add_objective(O, _explanation_text, target_override) /** * Completely remove the given objective from the mind, and include antagdatums/teams if remove_from_everything is true */ /datum/mind/proc/remove_mind_objective(datum/objective/O, remove_from_everything) . = objective_holder.remove_objective(O) if(!remove_from_everything) return for(var/datum/antagonist/A as anything in antag_datums) A.remove_antag_objective(O) var/datum/team/team = A.get_team() team?.objective_holder.remove_objective(O) /datum/mind/proc/_memory_edit_header(gamemode, list/alt) . = gamemode if(SSticker.mode.config_tag == gamemode || (LAZYLEN(alt) && (SSticker.mode.config_tag in alt))) . = uppertext(.) . = "<i><b>[.]</b></i>: " /datum/mind/proc/_memory_edit_role_enabled(role) . = "|Disabled in Prefs" if(current && current.client && (role in current.client.prefs.be_special)) . = "|Enabled in Prefs" /datum/mind/proc/memory_edit_implant(mob/living/carbon/human/H) if(ismindshielded(H)) . = "Mindshield Bio-chip:<a href='byond://?src=[UID()];implant=remove'>Remove</a>|<b><font color='green'>Implanted</font></b></br>" else . = "Mindshield Bio-chip:<b>No Bio-chip</b>|<a href='byond://?src=[UID()];implant=add'>Bio-chip [H.p_them()]!</a></br>" /datum/mind/proc/memory_edit_revolution(mob/living/carbon/human/H) . = _memory_edit_header("revolution") var/datum/antagonist/rev = has_antag_datum(/datum/antagonist/rev) if(ismindshielded(H)) . += "<b>NO</b>|headrev|rev" else if(istype(rev, /datum/antagonist/rev/head)) . += "<a href='byond://?src=[UID()];revolution=clear'>no</a>|<b><font color='red'>HEADREV</font></b>|<a href='byond://?src=[UID()];revolution=rev'>rev</a>" . += "<br>Flash: <a href='byond://?src=[UID()];revolution=flash'>give</a>" var/list/L = current.get_contents() var/obj/item/flash/flash = locate() in L if(flash) if(!flash.broken) . += "|<a href='byond://?src=[UID()];revolution=takeflash'>take</a>." else . += "|<a href='byond://?src=[UID()];revolution=takeflash'>take</a>|<a href='byond://?src=[UID()];revolution=repairflash'>repair</a>." else . += "." . += " <a href='byond://?src=[UID()];revolution=reequip'>Reequip</a> (gives flash/cham sec hud)." if(!rev.has_antag_objectives()) // if theres anything missing here, we want it to runtime. There should never be a rev without a rev team . += "<br>Objectives are empty! Unless theres no command, this is likely a bug, please report it! <a href='byond://?src=[UID()];revolution=autoobjectives'>Set to kill all heads</a>." else if(rev) . += "<a href='byond://?src=[UID()];revolution=clear'>no</a>|<a href='byond://?src=[UID()];revolution=headrev'>headrev</a>|<b><font color='red'>REV</font></b>" else . += "<b>NO</b>|<a href='byond://?src=[UID()];revolution=headrev'>headrev</a>|<a href='byond://?src=[UID()];revolution=rev'>rev</a>" . += _memory_edit_role_enabled(ROLE_REV) /datum/mind/proc/memory_edit_cult(mob/living/carbon/human/H) . = _memory_edit_header("cult") if(has_antag_datum(/datum/antagonist/cultist)) . += "<a href='byond://?src=[UID()];cult=clear'>no</a>|<b><font color='red'>CULTIST</font></b>" . += "<br>Give <a href='byond://?src=[UID()];cult=dagger'>dagger</a>|<a href='byond://?src=[UID()];cult=runedmetal'>runedmetal</a>." else . += "<b>NO</b>|<a href='byond://?src=[UID()];cult=cultist'>cultist</a>" . += _memory_edit_role_enabled(ROLE_CULTIST) /datum/mind/proc/memory_edit_wizard(mob/living/carbon/human/H) . = _memory_edit_header("wizard") if(has_antag_datum(/datum/antagonist/wizard)) . += "<b><font color='red'>WIZARD</font></b>|<a href='byond://?src=[UID()];wizard=clear'>no</a>" . += "<br><a href='byond://?src=[UID()];wizard=lair'>To lair</a>, <a href='byond://?src=[UID()];common=undress'>undress</a>, <a href='byond://?src=[UID()];wizard=dressup'>dress up</a>, <a href='byond://?src=[UID()];wizard=name'>let choose name</a>." else . += "<a href='byond://?src=[UID()];wizard=wizard'>wizard</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_WIZARD) /datum/mind/proc/memory_edit_changeling(mob/living/carbon/human/H) . = _memory_edit_header("changeling", list("traitorchan")) var/datum/antagonist/changeling/cling = has_antag_datum(/datum/antagonist/changeling) if(cling) . += "<b><font color='red'>CHANGELING</font></b>|<a href='byond://?src=[UID()];changeling=clear'>no</a>" if(!cling.has_antag_objectives()) . += "<br>Objectives are empty! <a href='byond://?src=[UID()];changeling=autoobjectives'>Randomize!</a>" if(length(cling.absorbed_dna)) var/datum/dna/DNA = cling.absorbed_dna[1] if(current.real_name != DNA.real_name) . += "<br><a href='byond://?src=[UID()];changeling=initialdna'>Transform to initial appearance.</a>" else . += "<a href='byond://?src=[UID()];changeling=changeling'>changeling</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_CHANGELING) /datum/mind/proc/memory_edit_vampire(mob/living/carbon/human/H) . = _memory_edit_header("vampire", list("traitorvamp")) var/datum/antagonist/vampire/vamp = has_antag_datum(/datum/antagonist/vampire) if(vamp) . += "<b><font color='red'>VAMPIRE</font></b>|<a href='byond://?src=[UID()];vampire=clear'>no</a>" . += "<br>Usable blood: <a href='byond://?src=[UID()];vampire=edit_usable_blood'>[vamp.bloodusable]</a>" . += " | Total blood: <a href='byond://?src=[UID()];vampire=edit_total_blood'>[vamp.bloodtotal]</a>" var/has_subclass = !QDELETED(vamp.subclass) . += "<br>Subclass: <a href='byond://?src=[UID()];vampire=change_subclass'>[has_subclass ? capitalize(vamp.subclass.name) : "None"]</a>" if(has_subclass) . += " | Force full power: <a href='byond://?src=[UID()];vampire=full_power_override'>[vamp.subclass.full_power_override ? "Yes" : "No"]</a>" if(!vamp.has_antag_objectives()) . += "<br>Objectives are empty! <a href='byond://?src=[UID()];vampire=autoobjectives'>Randomize!</a>" else . += "<a href='byond://?src=[UID()];vampire=vampire'>vampire</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_VAMPIRE) /** Enthralled ***/ . += "<br><b><i>enthralled</i></b>: " if(has_antag_datum(/datum/antagonist/mindslave/thrall)) . += "<b><font color='red'>THRALL</font></b>|<a href='byond://?src=[UID()];vampthrall=clear'>no</a>" else . += "thrall|<b>NO</b>" /datum/mind/proc/memory_edit_mind_flayer(mob/living/carbon/human/H) . = _memory_edit_header("mind_flayer") var/datum/antagonist/mindflayer/flayer = has_antag_datum(/datum/antagonist/mindflayer) if(flayer) . += "<b><font color='red'>MINDFLAYER</font></b>|<a href='byond://?src=[UID()];mind_flayer=clear'>no</a>" . += " | Usable swarms: <a href='byond://?src=[UID()];mind_flayer=edit_total_swarms'>[flayer.usable_swarms]</a>" . += " | Total swarms gathered: [flayer.total_swarms_gathered]" . += " | List of purchased powers: [json_encode(flayer.powers)]" if(!flayer.has_antag_objectives()) . += "<br>Objectives are empty! <a href='byond://?src=[UID()];mind_flayer=autoobjectives'>Randomize!</a>" else . += "<a href='byond://?src=[UID()];mind_flayer=mind_flayer'>mind_flayer</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_MIND_FLAYER) /datum/mind/proc/memory_edit_nuclear(mob/living/carbon/human/H) . = _memory_edit_header("nuclear") if(src in SSticker.mode.syndicates) . += "<b><font color='red'>OPERATIVE</b></font>|<a href='byond://?src=[UID()];nuclear=clear'>no</a>" . += "<br><a href='byond://?src=[UID()];nuclear=lair'>To shuttle</a>, <a href='byond://?src=[UID()];common=undress'>undress</a>, <a href='byond://?src=[UID()];nuclear=dressup'>dress up</a>." var/code for(var/obj/machinery/nuclearbomb/bombue in SSmachines.get_by_type(/obj/machinery/nuclearbomb)) if(length(bombue.r_code) <= 5 && bombue.r_code != "LOLNO" && bombue.r_code != "ADMIN") code = bombue.r_code break if(code) . += " Code is [code]. <a href='byond://?src=[UID()];nuclear=tellcode'>tell the code.</a>" else . += "<a href='byond://?src=[UID()];nuclear=nuclear'>operative</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_OPERATIVE) /datum/mind/proc/memory_edit_abductor(mob/living/carbon/human/H) . = _memory_edit_header("abductor") if(has_antag_datum(/datum/antagonist/abductor)) . += "<b><font color='red'>ABDUCTOR</font></b>|<a href='byond://?src=[UID()];abductor=clear'>no</a>" else . += "<a href='byond://?src=[UID()];abductor=abductor'>abductor</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_ABDUCTOR) /datum/mind/proc/memory_edit_zombie(mob/living/H) . = _memory_edit_header("zombie", list()) if(has_antag_datum(/datum/antagonist/zombie)) . += "<a href='byond://?src=[UID()];zombie=clear'>no</a>|<b><font color='red'>ZOMBIE</font></b>" return if(current.HasDisease(/datum/disease/zombie)) . += "<b>NO</b>|<a href='byond://?src=[UID()];zombie=zombie'>zombie</a>|<a href='byond://?src=[UID()];zombie=zombievirusno'><font color='red'>dis-infect</font></a>" else . += "<b>NO</b>|<a href='byond://?src=[UID()];zombie=zombie'>zombie</a>|<a href='byond://?src=[UID()];zombie=zombievirus'>infect</a>" /datum/mind/proc/memory_edit_eventmisc(mob/living/H) . = _memory_edit_header("event", list()) if(has_antag_datum(/datum/antagonist/eventmisc)) . += "<b>YES</b>|<a href='byond://?src=[UID()];eventmisc=clear'>no</a>" else . += "<a href='byond://?src=[UID()];eventmisc=eventmisc'>Event Role</a>|<b>NO</b>" /datum/mind/proc/memory_edit_traitor() . = _memory_edit_header("traitor", list("traitorchan", "traitorvamp")) if(has_antag_datum(/datum/antagonist/traitor)) . += "<b><font color='red'>TRAITOR</font></b>|<a href='byond://?src=[UID()];traitor=clear'>no</a>" var/datum/antagonist/traitor/T = has_antag_datum(/datum/antagonist/traitor) if(!T.has_antag_objectives()) . += "<br>Objectives are empty! <a href='byond://?src=[UID()];traitor=autoobjectives'>Randomize!</a>" else . += "<a href='byond://?src=[UID()];traitor=traitor'>traitor</a>|<b>NO</b>" . += _memory_edit_role_enabled(ROLE_TRAITOR) // Contractor . += "<br><b><i>contractor</i></b>: " var/datum/contractor_hub/H = LAZYACCESS(GLOB.contractors, src) if(H) . += "<b><font color='red'>CONTRACTOR</font></b>" // List all their contracts . += "<br><b>Contracts:</b>" if(H.contracts) var/count = 1 for(var/co in H.contracts) var/datum/syndicate_contract/CO = co . += "<br><B>Contract #[count++]</B>: " . += "<a href='byond://?src=[UID()];cuid=[CO.UID()];contractor=target'><b>[CO.contract.target?.name || "Invalid target!"]</b></a>|" . += "<a href='byond://?src=[UID()];cuid=[CO.UID()];contractor=locations'>locations</a>|" . += "<a href='byond://?src=[UID()];cuid=[CO.UID()];contractor=other'>more</a>|" switch(CO.status) if(CONTRACT_STATUS_INVALID) . += "<b>INVALID</b>" if(CONTRACT_STATUS_INACTIVE) . += "inactive" if(CONTRACT_STATUS_ACTIVE) . += "<b><font color='orange'>ACTIVE</font></b>|" . += "<a href='byond://?src=[UID()];cuid=[CO.UID()];contractor=interrupt'>interrupt</a>|" . += "<a href='byond://?src=[UID()];cuid=[CO.UID()];contractor=fail'>fail</a>" if(CONTRACT_STATUS_COMPLETED) . += "<font color='green'>COMPLETED</font>" if(CONTRACT_STATUS_FAILED) . += "<font color='red'>FAILED</font>" . += "<br>" . += "<a href='byond://?src=[UID()];contractor=add'>Add Contract</a><br>" . += "Claimable TC: <a href='byond://?src=[UID()];contractor=tc'>[H.reward_tc_available]</a><br>" . += "Available Rep: <a href='byond://?src=[UID()];contractor=rep'>[H.rep]</a><br>" else . += "<br>" . += "<i>Has not logged in to contractor uplink</i>" else . += "<b>NO</b>" // Mindslave . += "<br><b><i>mindslaved</i></b>: " if(has_antag_datum(/datum/antagonist/mindslave, FALSE)) . += "<b><font color='red'>MINDSLAVE</font></b>|<a href='byond://?src=[UID()];mindslave=clear'>no</a>" else . += "mindslave|<b>NO</b>" /datum/mind/proc/memory_edit_silicon() . = "<i><b>Silicon</b></i>: " var/mob/living/silicon/robot/robot = current if(istype(robot) && robot.emagged) . += "<br>Cyborg: <b><font color='red'>Is emagged!</font></b> <a href='byond://?src=[UID()];silicon=unemag'>Unemag!</a><br>0th law: [robot.laws.zeroth_law]" var/mob/living/silicon/ai/ai = current if(istype(ai) && length(ai.connected_robots)) var/n_e_robots = 0 for(var/mob/living/silicon/robot/R in ai.connected_robots) if(R.emagged) n_e_robots++ . += "<br>[n_e_robots] of [length(ai.connected_robots)] slaved cyborgs are emagged. <a href='byond://?src=[UID()];silicon=unemagcyborgs'>Unemag</a>" /datum/mind/proc/memory_edit_uplink() . = "" if(ishuman(current) && ((has_antag_datum(/datum/antagonist/traitor)) || \ (src in SSticker.mode.syndicates))) . = "Uplink: <a href='byond://?src=[UID()];common=uplink'>give</a>" var/obj/item/uplink/hidden/suplink = find_syndicate_uplink() var/crystals if(suplink) crystals = suplink.uses if(suplink) . += "|<a href='byond://?src=[UID()];common=takeuplink'>take</a>" if(usr.client.holder.rights & (R_SERVER|R_EVENT)) . += ", <a href='byond://?src=[UID()];common=crystals'>[crystals]</a> crystals" else . += ", [crystals] crystals" . += "." //hiel grammar // ^ whoever left this comment is literally a grammar nazi. stalin better. in russia grammar correct you. /datum/mind/proc/edit_memory() if(SSticker.current_state < GAME_STATE_PLAYING) alert("Not before round-start!", "Alert") return var/list/out = list("<html><meta charset='UTF-8'><head><title>[name]</title></head><body><b>[name]</b>[(current && (current.real_name != name))?" (as [current.real_name])" : ""]") out.Add("Mind currently owned by key: [key] [active ? "(synced)" : "(not synced)"]") out.Add("Assigned role: [assigned_role]. <a href='byond://?src=[UID()];role_edit=1'>Edit</a>") out.Add("Factions and special roles:") var/list/sections = list( "implant", "revolution", "cult", "wizard", "changeling", "vampire", // "traitorvamp", "mind_flayer", "nuclear", "traitor", // "traitorchan", ) var/mob/living/carbon/human/H = current if(ishuman(current)) /** Impanted**/ sections["implant"] = memory_edit_implant(H) /** REVOLUTION ***/ sections["revolution"] = memory_edit_revolution(H) /** WIZARD ***/ sections["wizard"] = memory_edit_wizard(H) /** CHANGELING ***/ sections["changeling"] = memory_edit_changeling(H) /** VAMPIRE ***/ sections["vampire"] = memory_edit_vampire(H) /** MINDFLAYER ***/ sections["mind_flayer"] = memory_edit_mind_flayer(H) /** NUCLEAR ***/ sections["nuclear"] = memory_edit_nuclear(H) /** Abductors **/ sections["abductor"] = memory_edit_abductor(H) /** Zombies **/ sections["zombie"] = memory_edit_zombie(H) sections["eventmisc"] = memory_edit_eventmisc(H) /** TRAITOR ***/ sections["traitor"] = memory_edit_traitor() if(!issilicon(current)) /** CULT ***/ sections["cult"] = memory_edit_cult(H) /** SILICON ***/ if(issilicon(current)) sections["silicon"] = memory_edit_silicon() /* This prioritizes antags relevant to the current round to make them appear at the top of the panel. Traitorchan and traitorvamp are snowflaked in because they have multiple sections. */ if(SSticker.mode.config_tag == "traitorchan") if(sections["traitor"]) out.Add(sections["traitor"]) if(sections["changeling"]) out.Add(sections["changeling"]) sections -= "traitor" sections -= "changeling" // Elif technically unnecessary but it makes the following else look better else if(SSticker.mode.config_tag == "traitorvamp") if(sections["traitor"]) out.Add(sections["traitor"]) if(sections["vampire"]) out.Add(sections["vampire"]) sections -= "traitor" sections -= "vampire" else if(sections[SSticker.mode.config_tag]) out.Add(sections[SSticker.mode.config_tag]) sections -= SSticker.mode.config_tag for(var/i in sections) if(sections[i]) out.Add(sections[i]) out.Add("<b>Organization:</b> ") for(var/datum/antagonist/D in antag_datums) if(D.organization) out.Add("[D.organization.name]") out.Add(memory_edit_uplink()) out.Add("<b>Memory:</b>") out.Add(memory) out.Add("<a href='byond://?src=[UID()];memory_edit=1'>Edit memory</a><br>") out.Add("Objectives:") out.Add(gen_objective_text(admin = TRUE)) out.Add("<a href='byond://?src=[UID()];obj_add=1'>Add objective</a><br>") out.Add("<a href='byond://?src=[UID()];obj_announce=1'>Announce objectives</a><br>") out.Add("</body></html>") usr << browse(out.Join("<br>"), "window=edit_memory[src];size=500x500") /datum/mind/Topic(href, href_list) if(!check_rights(R_ADMIN)) return if(href_list["role_edit"]) var/new_role = input("Select new role", "Assigned role", assigned_role) as null|anything in GLOB.joblist if(!new_role) return assigned_role = new_role log_admin("[key_name(usr)] has changed [key_name(current)]'s assigned role to [assigned_role]") message_admins("[key_name_admin(usr)] has changed [key_name_admin(current)]'s assigned role to [assigned_role]") else if(href_list["memory_edit"]) var/messageinput = input("Write new memory", "Memory", memory) as null|message if(isnull(messageinput)) return var/new_memo = copytext(messageinput, 1,MAX_MESSAGE_LEN) var/confirmed = alert(usr, "Are you sure you want to edit their memory? It will wipe out their original memory!", "Edit Memory", "Yes", "No") if(confirmed == "Yes") // Because it is too easy to accidentally wipe someone's memory memory = new_memo log_admin("[key_name(usr)] has edited [key_name(current)]'s memory") message_admins("[key_name_admin(usr)] has edited [key_name_admin(current)]'s memory") else if(href_list["obj_edit"] || href_list["obj_add"]) var/datum/objective/objective var/def_value if(href_list["obj_edit"]) objective = locate(href_list["obj_edit"]) if(!objective) return //Text strings are easy to manipulate. Revised for simplicity. var/temp_obj_type = "[objective.type]"//Convert path into a text string. def_value = copytext(temp_obj_type, 18)//Convert last part of path into an objective keyword. if(!def_value)//If it's a custom objective, it will be an empty string. def_value = "custom" var/new_obj_type = input("Select objective type:", "Objective type", def_value) as null|anything in list( "assassinate", "assassinateonce", "blood", "debrain", "protect", "prevent", "hijack", "escape", "survive", "steal", "nuclear", "absorb", "destroy", "maroon", "identity theft", "custom") if(!new_obj_type) return var/datum/objective/new_objective = null switch(new_obj_type) if("assassinate", "assassinateonce", "protect","debrain", "maroon") var/list/possible_targets = list() var/list/possible_targets_random = list() for(var/datum/mind/possible_target in SSticker.minds) if((possible_target != src) && ishuman(possible_target.current)) possible_targets += possible_target.current // Allows for admins to pick off station roles if(!is_invalid_target(possible_target)) possible_targets_random += possible_target.current // For random picking, only valid targets var/mob/def_target = null var/objective_list[] = list(/datum/objective/assassinate, /datum/objective/assassinateonce, /datum/objective/protect, /datum/objective/debrain) if(objective&&(objective.type in objective_list) && objective:target) def_target = objective.target.current possible_targets = sortAtom(possible_targets) var/new_target if(length(possible_targets)) if(alert(usr, "Do you want to pick the objective yourself? No will randomise it", "Pick objective", "Yes", "No") == "Yes") possible_targets += "Free objective" new_target = input("Select target:", "Objective target", def_target) as null|anything in possible_targets else if(!length(possible_targets_random)) to_chat(usr, "<span class='warning'>No random target found. Pick one manually.</span>") return new_target = pick(possible_targets_random) if(!new_target) return else to_chat(usr, "<span class='warning'>No possible target found. Defaulting to a Free objective.</span>") new_target = "Free objective" var/objective_path = text2path("/datum/objective/[new_obj_type]") if(new_target == "Free objective") new_objective = new objective_path new_objective:target = null new_objective.update_explanation_text() else new_objective = new objective_path new_objective:target = new_target:mind new_objective.update_explanation_text() if("destroy") var/list/possible_targets = active_ais(1) if(length(possible_targets)) var/mob/new_target = input("Select target:", "Objective target") as null|anything in possible_targets new_objective = new /datum/objective/destroy new_objective.target = new_target.mind new_objective.update_explanation_text() else to_chat(usr, "No active AIs with minds") if("prevent") new_objective = /datum/objective/block // we can place paths here because they will be created as needed in the objective holder if("hijack") new_objective = /datum/objective/hijack if("escape") new_objective = /datum/objective/escape if("survive") new_objective = /datum/objective/survive if("nuclear") new_objective = /datum/objective/nuclear if("steal") if(!istype(objective, /datum/objective/steal)) new_objective = new /datum/objective/steal else new_objective = objective var/datum/objective/steal/steal = new_objective if(!steal.select_target()) return if("absorb", "blood") var/def_num if(objective&&objective.type==text2path("/datum/objective/[new_obj_type]")) def_num = objective.target_amount var/target_number = input("Input target number:", "Objective", def_num) as num|null if(isnull(target_number))//Ordinarily, you wouldn't need isnull. In this case, the value may already exist. return switch(new_obj_type) if("absorb") new_objective = new /datum/objective/absorb if("blood") new_objective = new /datum/objective/blood new_objective.target_amount = target_number new_objective.update_explanation_text() if("identity theft") var/list/possible_targets = list() for(var/datum/mind/possible_target in SSticker.minds) if((possible_target != src) && ishuman(possible_target.current)) possible_targets += possible_target possible_targets = sortAtom(possible_targets) possible_targets += "Free objective" var/new_target = input("Select target:", "Objective target") as null|anything in possible_targets if(!new_target) return var/datum/mind/targ = new_target if(!istype(targ)) CRASH("Invalid target for identity theft objective, cancelling") new_objective = new /datum/objective/escape/escape_with_identity new_objective.target = new_target new_objective.update_explanation_text() var/datum/objective/escape/escape_with_identity/O = new_objective O.target_real_name = new_objective.target.current.real_name if("custom") var/expl = sanitize(copytext_char(input("Custom objective:", "Objective", objective ? objective.explanation_text : "") as text|null, 1, MAX_MESSAGE_LEN)) if(!expl) return new_objective = new /datum/objective new_objective.explanation_text = expl new_objective.needs_target = FALSE if(!new_objective) return if(objective) objective.holder.replace_objective(objective, new_objective) // replace it in its old holder else add_mind_objective(new_objective) log_admin("[key_name(usr)] has updated [key_name(current)]'s objectives: [new_objective]") message_admins("[key_name_admin(usr)] has updated [key_name_admin(current)]'s objectives: [new_objective]") else if(href_list["obj_delete"]) var/datum/objective/objective = locate(href_list["obj_delete"]) if(!istype(objective)) return log_admin("[key_name(usr)] has removed one of [key_name(current)]'s objectives: [objective]") message_admins("[key_name_admin(usr)] has removed one of [key_name_admin(current)]'s objectives: [objective]") remove_mind_objective(objective, TRUE) else if(href_list["obj_completed"]) var/datum/objective/objective = locate(href_list["obj_completed"]) if(!istype(objective)) return objective.completed = !objective.completed log_admin("[key_name(usr)] has toggled the completion of one of [key_name(current)]'s objectives") message_admins("[key_name_admin(usr)] has toggled the completion of one of [key_name_admin(current)]'s objectives") else if(href_list["implant"]) var/mob/living/carbon/human/H = current switch(href_list["implant"]) if("remove") for(var/obj/item/bio_chip/mindshield/I in H.contents) if(I && I.implanted) qdel(I) to_chat(H, "<span class='notice'><font size='3'><b>Your mindshield bio-chip has been deactivated.</b></font></span>") log_admin("[key_name(usr)] has deactivated [key_name(current)]'s mindshield bio-chip") message_admins("[key_name_admin(usr)] has deactivated [key_name_admin(current)]'s mindshield bio-chip") if("add") var/obj/item/bio_chip/mindshield/L = new/obj/item/bio_chip/mindshield(H) L.implant(H) log_admin("[key_name(usr)] has given [key_name(current)] a mindshield bio-chip") message_admins("[key_name_admin(usr)] has given [key_name_admin(current)] a mindshield bio-chip") to_chat(H, "<span class='userdanger'>You somehow have become the recipient of a mindshield transplant, and it just activated!</span>") var/datum/antagonist/rev/has_rev = has_antag_datum(/datum/antagonist/rev) if(has_rev) remove_antag_datum(/datum/antagonist/rev, silent_removal = TRUE) // we have some custom text, lets make the removal silent to_chat(H, "<span class='userdanger'>The nanobots in the mindshield implant remove all thoughts about being a revolutionary. Get back to work!</span>") else if(href_list["revolution"]) switch(href_list["revolution"]) if("clear") var/datum/antagonist/rev/has_rev = has_antag_datum(/datum/antagonist/rev) if(has_rev) remove_antag_datum(/datum/antagonist/rev) log_admin("[key_name(usr)] has de-rev'd [key_name(current)]") message_admins("[key_name_admin(usr)] has de-rev'd [key_name_admin(current)]") if("rev") var/datum/antagonist/rev/head/is_headrev = has_antag_datum(/datum/antagonist/rev/head) if(is_headrev) is_headrev.demote() log_admin("[key_name(usr)] has demoted [key_name(current)] from headrev to rev") message_admins("[key_name(usr)] has demoted [key_name(current)] from headrev to rev") edit_memory() // so it updates... return if(has_antag_datum(/datum/antagonist/rev)) return add_antag_datum(/datum/antagonist/rev) log_admin("[key_name(usr)] has rev'd [key_name(current)]") message_admins("[key_name_admin(usr)] has rev'd [key_name_admin(current)]") current.create_log(MISC_LOG, "[current] was made into a revolutionary by [key_name_admin(usr)]") if("headrev") if(has_antag_datum(/datum/antagonist/rev/head)) return var/datum/antagonist/rev/has_rev = has_antag_datum(/datum/antagonist/rev) if(has_rev) has_rev.promote() log_admin("[key_name(usr)] has promoted [key_name(current)] from rev to headrev (auto-equipped flash/hud)") message_admins("[key_name(usr)] has promoted [key_name(current)] from rev to headrev (auto-equipped flash/hud)") edit_memory() // so it updates... return var/datum/antagonist/rev/head/head_rev = new() head_rev.should_equip = FALSE add_antag_datum(head_rev) log_admin("[key_name(usr)] has head-rev'd [key_name(current)]") message_admins("[key_name_admin(usr)] has head-rev'd [key_name_admin(current)]") if("autoobjectives") var/datum/team/revolution/the_rev_team = SSticker.mode.get_rev_team() the_rev_team.update_team_objectives() log_admin("[key_name(usr)] has updated revolutionary objectives for [key_name(current)]") message_admins("[key_name_admin(usr)] has updated revolutionary objectives for [key_name_admin(current)]") if("flash") var/datum/antagonist/rev/head/headrev = has_antag_datum(/datum/antagonist/rev/head) if(!headrev.equip_revolutionary(TRUE, FALSE)) to_chat(usr, "<span class='warning'>Spawning flash failed!</span>") log_admin("[key_name(usr)] has given [key_name(current)] a flash") message_admins("[key_name_admin(usr)] has given [key_name_admin(current)] a flash") if("takeflash") var/list/L = current.get_contents() var/obj/item/flash/flash = locate() in L if(!flash) to_chat(usr, "<span class='warning'>Deleting flash failed!</span>") qdel(flash) log_admin("[key_name(usr)] has taken [key_name(current)]'s flash") message_admins("[key_name_admin(usr)] has taken [key_name_admin(current)]'s flash") if("repairflash") var/list/L = current.get_contents() var/obj/item/flash/flash = locate() in L if(!flash) to_chat(usr, "<span class='warning'>Repairing flash failed!</span>") else flash.broken = FALSE log_admin("[key_name(usr)] has repaired [key_name(current)]'s flash") message_admins("[key_name_admin(usr)] has repaired [key_name_admin(current)]'s flash") if("reequip") var/list/L = current.get_contents() var/obj/item/flash/flash = locate() in L qdel(flash) take_uplink() var/datum/antagonist/rev/head/headrev = has_antag_datum(/datum/antagonist/rev/head) if(!headrev.equip_revolutionary()) to_chat(usr, "<span class='warning'>Reequipping revolutionary went wrong!</span>") return log_admin("[key_name(usr)] has equipped [key_name(current)] as a revolutionary") message_admins("[key_name_admin(usr)] has equipped [key_name_admin(current)] as a revolutionary") else if(href_list["cult"]) switch(href_list["cult"]) if("clear") if(has_antag_datum(/datum/antagonist/cultist)) remove_antag_datum(/datum/antagonist/cultist) log_admin("[key_name(usr)] has de-culted [key_name(current)]") message_admins("[key_name_admin(usr)] has de-culted [key_name_admin(current)]") if("cultist") if(!has_antag_datum(/datum/antagonist/cultist)) add_antag_datum(/datum/antagonist/cultist) to_chat(current, "<span class='cultitalic'>Assist your new compatriots in their dark dealings. Their goal is yours, and yours is theirs. You serve [GET_CULT_DATA(entity_title2, "your god")] above all else. Bring It back.</span>") log_and_message_admins("has culted [key_name(current)]") if("dagger") var/datum/antagonist/cultist/cultist = has_antag_datum(/datum/antagonist/cultist) if(!cultist.cult_give_item(/obj/item/melee/cultblade/dagger)) to_chat(usr, "<span class='warning'>Spawning dagger failed!</span>") log_and_message_admins("has equipped [key_name(current)] with a cult dagger") if("runedmetal") var/datum/antagonist/cultist/cultist = has_antag_datum(/datum/antagonist/cultist) if(!cultist.cult_give_item(/obj/item/stack/sheet/runed_metal/ten)) to_chat(usr, "<span class='warning'>Spawning runed metal failed!</span>") log_and_message_admins("has equipped [key_name(current)] with 10 runed metal sheets") else if(href_list["wizard"]) switch(href_list["wizard"]) if("clear") if(has_antag_datum(/datum/antagonist/wizard)) remove_antag_datum(/datum/antagonist/wizard) log_admin("[key_name(usr)] has de-wizarded [key_name(current)]") message_admins("[key_name_admin(usr)] has de-wizarded [key_name_admin(current)]") if("wizard") if(!has_antag_datum(/datum/antagonist/wizard)) var/datum/antagonist/wizard/wizard = new /datum/antagonist/wizard() wizard.should_equip_wizard = FALSE wizard.should_name_pick = FALSE add_antag_datum(wizard) log_admin("[key_name(usr)] has wizarded [key_name(current)]") message_admins("[key_name_admin(usr)] has wizarded [key_name_admin(current)]") current.create_log(MISC_LOG, "[current] was made into a wizard by [key_name_admin(usr)]") if("lair") current.forceMove(pick(GLOB.wizardstart)) log_admin("[key_name(usr)] has moved [key_name(current)] to the wizard's lair") message_admins("[key_name_admin(usr)] has moved [key_name_admin(current)] to the wizard's lair") if("dressup") var/datum/antagonist/wizard/wizard = has_antag_datum(/datum/antagonist/wizard) var/list/text_result = wizard.equip_wizard() to_chat(current, chat_box_red(text_result.Join("<br>"))) log_admin("[key_name(usr)] has equipped [key_name(current)] as a wizard") message_admins("[key_name_admin(usr)] has equipped [key_name_admin(current)] as a wizard") if("name") var/datum/antagonist/wizard/wizard = has_antag_datum(/datum/antagonist/wizard) if(!istype(wizard)) return wizard.name_wizard() log_admin("[key_name(usr)] has allowed wizard [key_name(current)] to name themselves") message_admins("[key_name_admin(usr)] has allowed wizard [key_name_admin(current)] to name themselves") else if(href_list["changeling"]) switch(href_list["changeling"]) if("clear") if(IS_CHANGELING(current)) remove_antag_datum(/datum/antagonist/changeling) log_admin("[key_name(usr)] has de-changelinged [key_name(current)]") message_admins("[key_name_admin(usr)] has de-changelinged [key_name_admin(current)]") if("changeling") if(!IS_CHANGELING(current)) add_antag_datum(/datum/antagonist/changeling) to_chat(current, "<span class='biggerdanger'>Your powers have awoken. A flash of memory returns to us... We are a changeling!</span>") log_admin("[key_name(usr)] has changelinged [key_name(current)]") message_admins("[key_name_admin(usr)] has changelinged [key_name_admin(current)]") if("autoobjectives") var/datum/antagonist/changeling/cling = has_antag_datum(/datum/antagonist/changeling) cling.give_objectives() to_chat(usr, "<span class='notice'>The objectives for changeling [key] have been generated. You can edit them and announce manually.</span>") log_admin("[key_name(usr)] has automatically forged objectives for [key_name(current)]") message_admins("[key_name_admin(usr)] has automatically forged objectives for [key_name_admin(current)]") if("initialdna") var/datum/antagonist/changeling/cling = has_antag_datum(/datum/antagonist/changeling) if(!cling || !length(cling.absorbed_dna)) to_chat(usr, "<span class='warning'>Resetting DNA failed!</span>") else current.dna = cling.absorbed_dna[1] current.real_name = current.dna.real_name current.UpdateAppearance() domutcheck(current) log_admin("[key_name(usr)] has reset [key_name(current)]'s DNA") message_admins("[key_name_admin(usr)] has reset [key_name_admin(current)]'s DNA") else if(href_list["vampire"]) switch(href_list["vampire"]) if("clear") if(has_antag_datum(/datum/antagonist/vampire)) remove_antag_datum(/datum/antagonist/vampire) to_chat(current, "<FONT color='red' size = 3><B>You grow weak and lose your powers! You are no longer a vampire and are stuck in your current form!</B></FONT>") log_admin("[key_name(usr)] has de-vampired [key_name(current)]") message_admins("[key_name_admin(usr)] has de-vampired [key_name_admin(current)]") if("vampire") if(!has_antag_datum(/datum/antagonist/vampire)) add_antag_datum(/datum/antagonist/vampire) to_chat(current, "<B><font color='red'>Your powers have awoken. Your lust for blood grows... You are a Vampire!</font></B>") log_admin("[key_name(usr)] has vampired [key_name(current)]") message_admins("[key_name_admin(usr)] has vampired [key_name_admin(current)]") if("edit_usable_blood") var/new_usable = input(usr, "Select a new value:", "Modify usable blood") as null|num if(isnull(new_usable) || new_usable < 0) return var/datum/antagonist/vampire/vamp = has_antag_datum(/datum/antagonist/vampire) vamp.bloodusable = new_usable current.update_action_buttons_icon() log_admin("[key_name(usr)] has set [key_name(current)]'s usable blood to [new_usable].") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s usable blood to [new_usable].") if("edit_total_blood") var/new_total = input(usr, "Select a new value:", "Modify total blood") as null|num if(isnull(new_total) || new_total < 0) return var/datum/antagonist/vampire/vamp = has_antag_datum(/datum/antagonist/vampire) if(new_total < vamp.bloodtotal) if(alert(usr, "Note that reducing the vampire's total blood may remove some active powers. Continue?", "Confirm New Total", "Yes", "No") == "No") return vamp.remove_all_powers() vamp.bloodtotal = new_total vamp.check_vampire_upgrade() log_admin("[key_name(usr)] has set [key_name(current)]'s total blood to [new_total].") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s total blood to [new_total].") if("change_subclass") var/list/subclass_selection = list() for(var/subtype in subtypesof(/datum/vampire_subclass)) var/datum/vampire_subclass/subclass = subtype subclass_selection[capitalize(initial(subclass.name))] = subtype subclass_selection["Let them choose (remove current subclass)"] = NONE var/new_subclass_name = input(usr, "Choose a new subclass:", "Change Vampire Subclass") as null|anything in subclass_selection if(!new_subclass_name) return var/datum/antagonist/vampire/vamp = has_antag_datum(/datum/antagonist/vampire) var/subclass_type = subclass_selection[new_subclass_name] if(subclass_type == NONE) vamp.clear_subclass() log_admin("[key_name(usr)] has removed [key_name(current)]'s vampire subclass.") message_admins("[key_name_admin(usr)] has removed [key_name_admin(current)]'s vampire subclass.") else vamp.upgrade_tiers -= /datum/spell/vampire/self/specialize vamp.change_subclass(subclass_type) log_admin("[key_name(usr)] has removed [key_name(current)]'s vampire subclass.") message_admins("[key_name_admin(usr)] has removed [key_name_admin(current)]'s vampire subclass.") if("full_power_override") var/datum/antagonist/vampire/vamp = has_antag_datum(/datum/antagonist/vampire) if(vamp.subclass.full_power_override) vamp.subclass.full_power_override = FALSE for(var/power in vamp.powers) if(!is_type_in_list(power, vamp.subclass.fully_powered_abilities)) continue vamp.remove_ability(power) else vamp.subclass.full_power_override = TRUE vamp.check_full_power_upgrade() log_admin("[key_name(usr)] set [key_name(current)]'s vampire 'full_power_overide' to [vamp.subclass.full_power_override].") message_admins("[key_name_admin(usr)] set [key_name_admin(current)]'s vampire 'full_power_overide' to [vamp.subclass.full_power_override].") if("autoobjectives") var/datum/antagonist/vampire/V = has_antag_datum(/datum/antagonist/vampire) V.give_objectives() to_chat(usr, "<span class='notice'>The objectives for vampire [key] have been generated. You can edit them and announce manually.</span>") log_admin("[key_name(usr)] has automatically forged objectives for [key_name(current)]") message_admins("[key_name_admin(usr)] has automatically forged objectives for [key_name_admin(current)]") else if(href_list["vampthrall"]) switch(href_list["vampthrall"]) if("clear") if(has_antag_datum(/datum/antagonist/mindslave/thrall)) remove_antag_datum(/datum/antagonist/mindslave/thrall) log_admin("[key_name(usr)] has de-vampthralled [key_name(current)]") message_admins("[key_name_admin(usr)] has de-vampthralled [key_name_admin(current)]") else if(href_list["mind_flayer"]) switch(href_list["mind_flayer"]) if("clear") if(has_antag_datum(/datum/antagonist/mindflayer)) remove_antag_datum(/datum/antagonist/mindflayer) log_admin("[key_name(usr)] has de-flayer'd [key_name(current)].") message_admins("[key_name(usr)] has de-flayer'd [key_name(current)].") if("mind_flayer") make_mind_flayer() log_admin("[key_name(usr)] has flayer'd [key_name(current)].") to_chat(current, "<b><font color='red'>You feel an entity stirring inside your chassis... You are a Mindflayer!</font></b>") message_admins("[key_name(usr)] has flayer'd [key_name(current)].") if("edit_total_swarms") var/new_swarms = input(usr, "Select a new value:", "Modify swarms") as null|num if(isnull(new_swarms) || new_swarms < 0) return var/datum/antagonist/mindflayer/MF = has_antag_datum(/datum/antagonist/mindflayer) MF.set_swarms(new_swarms) log_admin("[key_name(usr)] has set [key_name(current)]'s current swarms to [new_swarms].") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s current swarms to [new_swarms].") else if(href_list["nuclear"]) var/mob/living/carbon/human/H = current switch(href_list["nuclear"]) if("clear") if(src in SSticker.mode.syndicates) SSticker.mode.syndicates -= src SSticker.mode.update_synd_icons_removed(src) special_role = null objective_holder.clear(/datum/objective/nuclear) to_chat(current, "<span class='warning'><font size='3'><b>You have been brainwashed! You are no longer a Syndicate operative!</b></font></span>") log_admin("[key_name(usr)] has de-nuke op'd [key_name(current)]") message_admins("[key_name_admin(usr)] has de-nuke op'd [key_name_admin(current)]") if("nuclear") if(!(src in SSticker.mode.syndicates)) SSticker.mode.syndicates += src SSticker.mode.update_synd_icons_added(src) if(length(SSticker.mode.syndicates) == 1) SSticker.mode.prepare_syndicate_leader(src) else current.real_name = "[syndicate_name()] Operative #[length(SSticker.mode.syndicates) - 1]" special_role = SPECIAL_ROLE_NUKEOPS to_chat(current, "<span class='notice'>You are a [syndicate_name()] agent!</span>") SSticker.mode.forge_syndicate_objectives(src) SSticker.mode.greet_syndicate(src, FALSE) // False to fix the agent message appearing twice log_admin("[key_name(usr)] has nuke op'd [key_name(current)]") message_admins("[key_name_admin(usr)] has nuke op'd [key_name_admin(current)]") if("lair") current.forceMove(get_turf(locate("landmark*Syndicate-Spawn"))) log_admin("[key_name(usr)] has moved [key_name(current)] to the nuclear operative spawn") message_admins("[key_name_admin(usr)] has moved [key_name_admin(current)] to the nuclear operative spawn") if("dressup") qdel(H.belt) qdel(H.back) qdel(H.l_ear) qdel(H.r_ear) qdel(H.gloves) qdel(H.head) qdel(H.shoes) qdel(H.wear_id) qdel(H.wear_pda) qdel(H.wear_suit) qdel(H.w_uniform) if(!SSticker.mode.equip_syndicate(current)) to_chat(usr, "<span class='warning'>Equipping a Syndicate failed!</span>") return SSticker.mode.update_syndicate_id(current.mind, length(SSticker.mode.syndicates) == 1) log_admin("[key_name(usr)] has equipped [key_name(current)] as a nuclear operative") message_admins("[key_name_admin(usr)] has equipped [key_name_admin(current)] as a nuclear operative") if("tellcode") var/code for(var/obj/machinery/nuclearbomb/bombue in SSmachines.get_by_type(/obj/machinery/nuclearbomb)) if(length(bombue.r_code) <= 5 && bombue.r_code != "LOLNO" && bombue.r_code != "ADMIN") code = bombue.r_code break if(code) store_memory("<B>Syndicate Nuclear Bomb Code</B>: [code]", 0, 0) to_chat(current, "The nuclear authorization code is: <B>[code]</B>") log_admin("[key_name(usr)] has given [key_name(current)] the nuclear authorization code") message_admins("[key_name_admin(usr)] has given [key_name_admin(current)] the nuclear authorization code") else to_chat(usr, "<span class='warning'>No valid nuke found!</span>") else if(href_list["eventmisc"]) switch(href_list["eventmisc"]) if("clear") if(!has_antag_datum(/datum/antagonist/eventmisc)) return remove_antag_datum(/datum/antagonist/eventmisc) message_admins("[key_name_admin(usr)] has de-eventantag'ed [current].") log_admin("[key_name(usr)] has de-eventantag'ed [current].") if("eventmisc") if(has_antag_datum(/datum/antagonist/eventmisc)) to_chat(usr, "[current] is already an event antag!") return add_antag_datum(/datum/antagonist/eventmisc) message_admins("[key_name_admin(usr)] has eventantag'ed [current].") log_admin("[key_name(usr)] has eventantag'ed [current].") current.create_log(MISC_LOG, "[current] was made into an event antagonist by [key_name_admin(usr)]") else if(href_list["zombie"]) switch(href_list["zombie"]) if("clear") if(!has_antag_datum(/datum/antagonist/zombie)) return remove_antag_datum(/datum/antagonist/zombie) for(var/datum/disease/zombie/D in current.viruses) D.cure() if(ishuman(current)) var/mob/living/carbon/human/human_current = current for(var/obj/item/organ/limb as anything in human_current.bodyparts) if(limb.status & ORGAN_DEAD && !limb.is_robotic()) limb.status &= ~ORGAN_DEAD human_current.update_body() message_admins("[key_name_admin(usr)] has de-zombied'ed [key_name(current)].") log_admin("[key_name(usr)] has de-zombied'ed [key_name(current)].") if("zombie") if(has_antag_datum(/datum/antagonist/zombie)) return add_antag_datum(/datum/antagonist/zombie) message_admins("[key_name_admin(usr)] has zombie'ed [key_name(current)].") log_admin("[key_name(usr)] has zombie'ed [key_name(current)].") current.create_log(MISC_LOG, "[key_name(current)] was made into an zombie by [key_name_admin(usr)]") if("zombievirus") if(has_antag_datum(/datum/antagonist/zombie) || !ishuman(current)) return current.AddDisease(new /datum/disease/zombie) message_admins("[key_name_admin(usr)] has given a zombie virus to [key_name(current)].") log_admin("[key_name(usr)] has given a zombie virus to [key_name(current)].") current.create_log(MISC_LOG, "[key_name(current)] was admin-infected with a zombie virus by [key_name_admin(usr)]") if("zombievirusno") if(has_antag_datum(/datum/antagonist/zombie)) return for(var/datum/disease/zombie/D in current.viruses) D.cure() message_admins("[key_name_admin(usr)] has removed the zombie virus from [key_name(current)].") log_admin("[key_name(usr)] has removed the zombie virus from [key_name(current)].") current.create_log(MISC_LOG, "[key_name(current)] had their zombie virus admin-removed by [key_name_admin(usr)]") else if(href_list["traitor"]) switch(href_list["traitor"]) if("clear") if(has_antag_datum(/datum/antagonist/traitor)) remove_antag_datum(/datum/antagonist/traitor) log_admin("[key_name(usr)] has de-traitored [key_name(current)]") message_admins("[key_name_admin(usr)] has de-traitored [key_name_admin(current)]") if("traitor") if(!(has_antag_datum(/datum/antagonist/traitor))) add_antag_datum(/datum/antagonist/traitor) log_admin("[key_name(usr)] has traitored [key_name(current)]") message_admins("[key_name_admin(usr)] has traitored [key_name_admin(current)]") if("autoobjectives") var/datum/antagonist/traitor/T = has_antag_datum(/datum/antagonist/traitor) T.give_objectives() to_chat(usr, "<span class='notice'>The objectives for traitor [key] have been generated. You can edit them and announce manually.</span>") log_admin("[key_name(usr)] has automatically forged objectives for [key_name(current)]") message_admins("[key_name_admin(usr)] has automatically forged objectives for [key_name_admin(current)]") else if(href_list["contractor"]) var/datum/contractor_hub/H = LAZYACCESS(GLOB.contractors, src) switch(href_list["contractor"]) if("add") if(!H) return var/list/possible_targets = list() for(var/foo in SSticker.minds) var/datum/mind/possible_target = foo if(src == possible_target || !possible_target.current || !possible_target.key) continue possible_targets[possible_target.name] = possible_target var/choice = input(usr, "Select the contract target:", "Add Contract") as null|anything in possible_targets var/datum/mind/target = possible_targets[choice] if(!target || !target.current || !target.key) return var/datum/syndicate_contract/new_contract = new(H, src, list(), target) new_contract.reward_tc = list(0, 0, 0) H.contracts += new_contract for(var/difficulty in EXTRACTION_DIFFICULTY_EASY to EXTRACTION_DIFFICULTY_HARD) var/amount_tc = H.calculate_tc_reward(length(H.contracts), difficulty) new_contract.reward_tc[difficulty] = amount_tc SStgui.update_uis(H) log_admin("[key_name(usr)] has given a new contract to [key_name(current)] with [target.current] as the target") message_admins("[key_name_admin(usr)] has given a new contract to [key_name_admin(current)] with [target.current] as the target") if("tc") if(!H) return var/new_tc = input(usr, "Enter the new amount of TC:", "Set Claimable TC", H.reward_tc_available) as num|null new_tc = text2num(new_tc) if(isnull(new_tc) || new_tc < 0) return H.reward_tc_available = new_tc SStgui.update_uis(H) log_admin("[key_name(usr)] has set [key_name(current)]'s claimable TC to [new_tc]") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s claimable TC to [new_tc]") if("rep") if(!H) return var/new_rep = input(usr, "Enter the new amount of Rep:", "Set Available Rep", H.rep) as num|null new_rep = text2num(new_rep) if(isnull(new_rep) || new_rep < 0) return H.rep = new_rep SStgui.update_uis(H) log_admin("[key_name(usr)] has set [key_name(current)]'s contractor Rep to [new_rep]") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s contractor Rep to [new_rep]") // Contract specific actions if("target") if(!H) return var/datum/syndicate_contract/CO = locateUID(href_list["cuid"]) if(!istype(CO)) return var/list/possible_targets = list() for(var/foo in SSticker.minds) var/datum/mind/possible_target = foo if(src == possible_target || !possible_target.current || !possible_target.key) continue possible_targets[possible_target.name] = possible_target var/choice = input(usr, "Select the new contract target:", "Set Contract Target") as null|anything in possible_targets var/datum/mind/target = possible_targets[choice] if(!target || !target.current || !target.key) return // Update var/datum/data/record/R = find_record("name", target.name, GLOB.data_core.general) var/name = R?.fields["name"] || target.name || "Unknown" var/rank = R?.fields["rank"] || target.assigned_role || "Unknown" CO.contract.target = target CO.target_name = "[name], the [rank]" if(R?.fields["photo"]) var/icon/temp = new('icons/turf/floors.dmi', pick("floor", "wood", "darkfull", "stairs")) temp.Blend(R.fields["photo"], ICON_OVERLAY) CO.target_photo = temp // Notify SStgui.update_uis(H) log_admin("[key_name(usr)] has set [key_name(current)]'s contract target to [target.current]") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s contract target to [target.current]") if("locations") if(!H) return var/datum/syndicate_contract/CO = locateUID(href_list["cuid"]) if(!istype(CO)) return var/list/difficulty_choices = list() for(var/diff in EXTRACTION_DIFFICULTY_EASY to EXTRACTION_DIFFICULTY_HARD) var/area/A = CO.contract.candidate_zones[diff] difficulty_choices["[A.name] ([CO.reward_tc[diff]] TC)"] = diff var/choice_diff = input(usr, "Select the location to change:", "Set Contract Location") as null|anything in difficulty_choices var/difficulty = difficulty_choices[choice_diff] if(!difficulty) return var/list/area_choices = list() for(var/a in return_sorted_areas()) var/area/A = a if(A.outdoors || !is_station_level(A.z)) continue area_choices += A var/new_area = input(usr, "Select the new location:", "Set Contract Location", CO.contract.candidate_zones[difficulty]) in area_choices if(!new_area) return var/new_reward = input(usr, "Enter the new amount of rewarded TC:", "Set Contract Location", CO.reward_tc[difficulty]) as num|null new_reward = text2num(new_reward) if(isnull(new_reward) || new_reward < 0) return CO.contract.candidate_zones[difficulty] = new_area CO.reward_tc[difficulty] = new_reward SStgui.update_uis(H) log_admin("[key_name(usr)] has set [key_name(current)]'s contract location to [new_area] with [new_reward] TC as reward") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s contract location to [new_area] with [new_reward] TC as reward") if("other") if(!H) return var/datum/syndicate_contract/CO = locateUID(href_list["cuid"]) if(!istype(CO)) return var/choice = input(usr, "Select an action to take:", "Other Contract Actions") in list("Edit Fluff Message", "Edit Prison Time", "Edit Credits Reward", "Delete Contract", "Cancel") if(!choice) return switch(choice) if("Edit Fluff Message") var/new_message = input(usr, "Enter the new fluff message:", "Edit Fluff Message", CO.fluff_message) as message|null if(!new_message) return CO.fluff_message = new_message log_admin("[key_name(usr)] has edited [key_name(current)]'s contract fluff message") message_admins("[key_name_admin(usr)] has edited [key_name_admin(current)]'s contract fluff message") if("Edit Prison Time") var/new_time = input(usr, "Enter the new prison time in seconds:", "Edit Prison Time", CO.prison_time / 10) as num|null if(!new_time || new_time < 0) return CO.prison_time = new_time SECONDS log_admin("[key_name(usr)] has edited [key_name(current)]'s contract prison time to [new_time] seconds") message_admins("[key_name_admin(usr)] has edited [key_name_admin(current)]'s contract prison time to [new_time] seconds") if("Edit Credits Reward") var/new_creds = input(usr, "Enter the new credits reward:", "Edit Credits Reward", CO.reward_credits) as num|null if(!new_creds || new_creds < 0) return CO.reward_credits = new_creds log_admin("[key_name(usr)] has edited [key_name(current)]'s contract reward credits to [new_creds]") message_admins("[key_name_admin(usr)] has edited [key_name_admin(current)]'s contract reward credits to [new_creds]") if("Delete Contract") if(CO.status == CONTRACT_STATUS_ACTIVE) CO.fail("Contract interrupted forcibly.") H.contracts -= CO log_admin("[key_name(usr)] has deleted [key_name(current)]'s contract") message_admins("[key_name_admin(usr)] has deleted [key_name_admin(current)]'s contract") else return SStgui.update_uis(H) if("interrupt") if(!H) return var/datum/syndicate_contract/CO = locateUID(href_list["cuid"]) if(!istype(CO) || CO.status != CONTRACT_STATUS_ACTIVE) return H.current_contract = null CO.contract.extraction_zone = null CO.status = CONTRACT_STATUS_INACTIVE CO.clean_up() log_admin("[key_name(usr)] has interrupted [key_name(current)]'s contract") message_admins("[key_name_admin(usr)] has interrupted [key_name_admin(current)]'s contract") if("fail") if(!H) return var/datum/syndicate_contract/CO = locateUID(href_list["cuid"]) if(!istype(CO) || CO.status != CONTRACT_STATUS_ACTIVE) return var/fail_reason = sanitize(input(usr, "Enter the fail reason:", "Fail Contract") as text|null) if(!fail_reason || CO.status != CONTRACT_STATUS_ACTIVE) return CO.fail(fail_reason) SStgui.update_uis(H) log_admin("[key_name(usr)] has failed [key_name(current)]'s contract with reason: [fail_reason]") message_admins("[key_name_admin(usr)] has failed [key_name_admin(current)]'s contract with reason: [fail_reason]") else if(href_list["mindslave"]) switch(href_list["mindslave"]) if("clear") if(has_antag_datum(/datum/antagonist/mindslave, FALSE)) var/mob/living/carbon/human/H = current for(var/i in H.contents) if(istype(i, /obj/item/bio_chip/traitor)) qdel(i) break remove_antag_datum(/datum/antagonist/mindslave) log_admin("[key_name(usr)] has de-mindslaved [key_name(current)]") message_admins("[key_name_admin(usr)] has de-mindslaved [key_name_admin(current)]") else if(href_list["abductor"]) switch(href_list["abductor"]) if("clear") to_chat(usr, "<span class='userdanger'>This will probably never be implemented. Sorry!</span>") if("abductor") if(!ishuman(current)) to_chat(usr, "<span class='warning'>This only works on humans!</span>") return make_Abductor() log_admin("[key_name(usr)] turned [current] into an abductor.") message_admins("[key_name_admin(usr)] turned [key_name_admin(current)] into an abductor.") current.create_log(MISC_LOG, "[current] was made into an abductor by [key_name_admin(usr)]") else if(href_list["silicon"]) switch(href_list["silicon"]) if("unemag") var/mob/living/silicon/robot/R = current if(!istype(R)) return R.unemag() log_admin("[key_name(usr)] has un-emagged [key_name(current)]") message_admins("[key_name_admin(usr)] has un-emagged [key_name_admin(current)]") if("unemagcyborgs") if(!is_ai(current)) return var/mob/living/silicon/ai/ai = current for(var/mob/living/silicon/robot/R in ai.connected_robots) R.unemag(R) log_admin("[key_name(usr)] has unemagged [key_name(ai)]'s cyborgs") message_admins("[key_name_admin(usr)] has unemagged [key_name_admin(ai)]'s cyborgs") else if(href_list["common"]) switch(href_list["common"]) if("undress") for(var/obj/item/I in current) current.drop_item_to_ground(I, force = TRUE) log_admin("[key_name(usr)] has unequipped [key_name(current)]") message_admins("[key_name_admin(usr)] has unequipped [key_name_admin(current)]") if("takeuplink") take_uplink() var/datum/antagonist/traitor/T = has_antag_datum(/datum/antagonist/traitor) T.antag_memory = "" //Remove any antag memory they may have had (uplink codes, code phrases) log_admin("[key_name(usr)] has taken [key_name(current)]'s uplink") message_admins("[key_name_admin(usr)] has taken [key_name_admin(current)]'s uplink") if("crystals") if(usr.client.holder.rights & (R_SERVER|R_EVENT)) var/obj/item/uplink/hidden/suplink = find_syndicate_uplink() var/crystals if(suplink) crystals = suplink.uses crystals = input("Amount of telecrystals for [key]","Syndicate uplink", crystals) as null|num if(!isnull(crystals)) if(suplink) suplink.uses = crystals log_admin("[key_name(usr)] has set [key_name(current)]'s telecrystals to [crystals]") message_admins("[key_name_admin(usr)] has set [key_name_admin(current)]'s telecrystals to [crystals]") if("uplink") if(has_antag_datum(/datum/antagonist/traitor)) var/datum/antagonist/traitor/T = has_antag_datum(/datum/antagonist/traitor) if(!T.give_uplink()) to_chat(usr, "<span class='warning'>Equipping a Syndicate failed!</span>") return log_admin("[key_name(usr)] has given [key_name(current)] an uplink") message_admins("[key_name_admin(usr)] has given [key_name_admin(current)] an uplink") else if(href_list["obj_announce"]) var/list/messages = prepare_announce_objectives() to_chat(current, chat_box_red(messages.Join("<br>"))) SEND_SOUND(current, sound('sound/ambience/alarm4.ogg')) log_admin("[key_name(usr)] has announced [key_name(current)]'s objectives") message_admins("[key_name_admin(usr)] has announced [key_name_admin(current)]'s objectives") edit_memory() /** * Create and/or add the `datum_type_or_instance` antag datum to the src mind. * * Arguments: * * antag_datum - an antag datum typepath or instance. If it's a typepath, it will create a new antag datum * * datum/team/team - the antag team that the src mind should join, if any */ /datum/mind/proc/add_antag_datum(datum_type_or_instance, datum/team/team) var/datum/antagonist/antag_datum if(!ispath(datum_type_or_instance)) antag_datum = datum_type_or_instance if(!istype(antag_datum)) return else antag_datum = new datum_type_or_instance() if(!antag_datum.can_be_owned(src)) qdel(antag_datum) return antag_datum.owner = src LAZYADD(antag_datums, antag_datum) antag_datum.create_team(team) var/datum/team/antag_team = antag_datum.get_team() if(antag_team) antag_team.add_member(src) ASSERT(antag_datum.owner && antag_datum.owner.current) antag_datum.on_gain() return antag_datum /** * Remove the specified `datum_type` antag datum from the src mind. * * Arguments: * * datum_type - an antag datum typepath */ /datum/mind/proc/remove_antag_datum(datum_type, check_subtypes = TRUE, silent_removal = FALSE) var/datum/antagonist/A = has_antag_datum(datum_type, check_subtypes) if(A) A.silent |= silent_removal qdel(A) /** * Removes all antag datums from the src mind. * * Use this over doing `QDEL_LIST_CONTENTS(antag_datums)`. */ /datum/mind/proc/remove_all_antag_datums(handle_target_cryo = FALSE) // This is not `QDEL_LIST_CONTENTS(antag_datums)`because it's possible for the `antag_datums` list to be set to null during deletion of an antag datum. // Then `QDEL_LIST` would runtime because it would be doing `null.Cut()`. for(var/datum/antagonist/A as anything in antag_datums) if(handle_target_cryo) A.on_cryo() qdel(A) antag_datums?.Cut() antag_datums = null /// This proc sets the hijack speed for a mob. If greater than zero, they can hijack. Outputs in seconds. /datum/mind/proc/get_hijack_speed() var/hijack_speed = 0 if(special_role) hijack_speed = 15 SECONDS if(locate(/datum/objective/hijack) in get_all_objectives()) hijack_speed = 10 SECONDS return hijack_speed /** * Returns an antag datum instance if the src mind has the specified `datum_type`. Returns `null` otherwise. * * Arguments: * * datum_type - an antag datum typepath * * check_subtypes - TRUE if this proc will consider subtypes of `datum_type` as valid. FALSE if only the exact same type should be considered. */ /datum/mind/proc/has_antag_datum(datum_type, check_subtypes = TRUE) for(var/datum/antagonist/A as anything in antag_datums) if(check_subtypes && istype(A, datum_type)) return A else if(A.type == datum_type) return A /datum/mind/proc/prepare_announce_objectives(title = TRUE) if(!current) return var/list/text = list() if(title) text.Add("<span class='notice'>Your current objectives:</span>") text.Add(gen_objective_text()) return text /datum/mind/proc/find_syndicate_uplink() var/list/L = current.get_contents() for(var/obj/item/I in L) if(I.hidden_uplink) return I.hidden_uplink return null /datum/mind/proc/take_uplink() var/obj/item/uplink/hidden/H = find_syndicate_uplink() if(H) qdel(H) /datum/mind/proc/make_Traitor() if(!has_antag_datum(/datum/antagonist/traitor)) add_antag_datum(/datum/antagonist/traitor) /datum/mind/proc/make_Nuke() if(!(src in SSticker.mode.syndicates)) SSticker.mode.syndicates += src SSticker.mode.update_synd_icons_added(src) if(length(SSticker.mode.syndicates) == 1) SSticker.mode.prepare_syndicate_leader(src) else current.real_name = "[syndicate_name()] Operative #[length(SSticker.mode.syndicates) - 1]" special_role = SPECIAL_ROLE_NUKEOPS assigned_role = SPECIAL_ROLE_NUKEOPS to_chat(current, "<span class='notice'>You are a [syndicate_name()] agent!</span>") SSticker.mode.forge_syndicate_objectives(src) SSticker.mode.greet_syndicate(src, FALSE) // False to fix the agent message appearing twice current.loc = get_turf(locate("landmark*Syndicate-Spawn")) var/mob/living/carbon/human/H = current qdel(H.belt) qdel(H.back) qdel(H.l_ear) qdel(H.r_ear) qdel(H.gloves) qdel(H.head) qdel(H.shoes) qdel(H.wear_id) qdel(H.wear_pda) qdel(H.wear_suit) qdel(H.w_uniform) SSticker.mode.equip_syndicate(current) /datum/mind/proc/make_vampire() if(!has_antag_datum(/datum/antagonist/vampire)) add_antag_datum(/datum/antagonist/vampire) /datum/mind/proc/make_Overmind() if(!(src in SSticker.mode.blob_overminds)) SSticker.mode.blob_overminds += src special_role = SPECIAL_ROLE_BLOB_OVERMIND /datum/mind/proc/make_mind_flayer() if(!has_antag_datum(/datum/antagonist/mindflayer)) add_antag_datum(/datum/antagonist/mindflayer) SSticker.mode.mindflayers |= src /datum/mind/proc/make_Abductor() if(alert(usr, "Are you sure you want to turn this person into an abductor? This can't be undone!", "New Abductor?", "Yes", "No") != "Yes") return for(var/datum/team/abductor/team in SSticker.mode.actual_abductor_teams) if(length(team.members) < 2) team.add_member(src) team.create_agent() team.create_scientist() return var/role = alert("Abductor Role?", "Role", "Agent", "Scientist", "Cancel") if(!role || role == "Cancel") return var/datum/team/abductor/team = new /datum/team/abductor(list(src)) if(role == "Agent") team.create_agent() else team.create_scientist() /datum/mind/proc/AddSpell(datum/spell/S) spell_list += S S.action.Grant(current) /datum/mind/proc/RemoveSpell(datum/spell/spell) //To remove a specific spell from a mind if(!spell) return for(var/datum/spell/S in spell_list) if(istype(S, spell)) qdel(S) spell_list -= S /datum/mind/proc/transfer_actions(mob/living/new_character) if(current && current.actions) for(var/datum/action/A in current.actions) A.Grant(new_character) transfer_mindbound_actions(new_character) /datum/mind/proc/transfer_mindbound_actions(mob/living/new_character) for(var/X in spell_list) var/datum/spell/S = X if(!S.on_mind_transfer(new_character)) current.RemoveSpell(S) continue S.action.Grant(new_character) /datum/mind/proc/get_ghost(even_if_they_cant_reenter) for(var/mob/dead/observer/ghost in GLOB.dead_mob_list) if(ghost.mind == src && ghost.mind.key == ghost.key) if(ghost.ghost_flags & GHOST_CAN_REENTER || even_if_they_cant_reenter) return ghost return /datum/mind/proc/check_ghost_client() var/mob/dead/observer/G = get_ghost() if(G?.client) return TRUE /datum/mind/proc/grab_ghost(force) var/mob/dead/observer/G = get_ghost(even_if_they_cant_reenter = force) . = G if(G) G.reenter_corpse() /datum/mind/proc/make_zealot(mob/living/carbon/human/missionary, convert_duration = 10 MINUTES, team_color = "red") zealot_master = missionary // Give the new zealot their mindslave datum with a custom greeting. var/greeting = "You're now a loyal zealot of [missionary.name]!</B> You now must lay down your life to protect [missionary.p_them()] and assist in [missionary.p_their()] goals at any cost." add_antag_datum(new /datum/antagonist/mindslave(missionary.mind, greeting)) var/obj/item/clothing/under/jumpsuit = null if(ishuman(current)) //only bother with the jumpsuit stuff if we are a human type, since we won't have the slot otherwise var/mob/living/carbon/human/H = current if(H.w_uniform) jumpsuit = H.w_uniform jumpsuit.color = team_color H.update_inv_w_uniform() add_attack_logs(missionary, current, "Converted to a zealot for [convert_duration/600] minutes") addtimer(CALLBACK(src, PROC_REF(remove_zealot), jumpsuit), convert_duration) //deconverts after the timer expires return TRUE /datum/mind/proc/remove_zealot(obj/item/clothing/under/jumpsuit = null) if(!zealot_master) //if they aren't a zealot, we can't remove their zealot status, obviously. don't bother with the rest so we don't confuse them with the messages return remove_antag_datum(/datum/antagonist/mindslave) add_attack_logs(zealot_master, current, "Lost control of zealot") zealot_master = null if(jumpsuit) jumpsuit.color = initial(jumpsuit.color) //reset the jumpsuit no matter where our mind is if(ishuman(current)) //but only try updating us if we are still a human type since it is a human proc var/mob/living/carbon/human/H = current H.update_inv_w_uniform() to_chat(current, "<span class='warning'><b>You seem to have forgotten the events of the past 10 minutes or so, and your head aches a bit as if someone beat it savagely with a stick.</b></span>") to_chat(current, "<span class='warning'><b>This means you don't remember who you were working for or what you were doing.</b></span>") /datum/mind/proc/has_normal_assigned_role() if(!assigned_role) return FALSE if(assigned_role == special_role) // nukie, ninjas, wizards, whatever return FALSE if(assigned_role == "Assistant") // because the default assigned role is assistant :P for(var/list/L in list(GLOB.data_core.general)) for(var/datum/data/record/R in L) if(R.fields["name"] == name) return TRUE return FALSE return TRUE /datum/mind/proc/get_assigned_role_asset() //Used in asset generation for Orbiting var/job_icons = GLOB.joblist var/centcom = get_all_centcom_jobs() + SPECIAL_ROLE_ERT + SPECIAL_ROLE_DEATHSQUAD var/solgov = get_all_solgov_jobs() var/soviet = get_all_soviet_jobs() if(assigned_role in centcom) //Return with the NT logo if it is a Centcom job return "centcom" if(assigned_role in solgov) //Return with the SolGov logo if it is a SolGov job return "solgov" if(assigned_role in soviet) //Return with the U.S.S.P logo if it is a Soviet job return "soviet" if(assigned_role in job_icons) //Check if the job has a hud icon return assigned_role return "unknown" //Initialisation procs /mob/proc/mind_initialize() SHOULD_CALL_PARENT(TRUE) if(mind) mind.key = key else mind = new /datum/mind(key) if(SSticker) SSticker.minds += mind else error("mind_initialize(): No ticker ready yet! Please inform Carn") if(!mind.name) mind.name = real_name mind.bind_to(src) SEND_SIGNAL(src, COMSIG_MIND_INITIALIZE) //HUMAN /mob/living/carbon/human/mind_initialize() ..() if(!mind.assigned_role) mind.assigned_role = "Assistant" //default /mob/proc/sync_mind() mind_initialize() //updates the mind (or creates and initializes one if one doesn't exist) mind.active = TRUE //indicates that the mind is currently synced with a client client.persistent.minds |= mind //slime /mob/living/simple_animal/slime/mind_initialize() ..() mind.assigned_role = "slime" //XENO /mob/living/carbon/alien/mind_initialize() ..() mind.assigned_role = "Alien" //XENO HUMANOID /mob/living/carbon/alien/humanoid/queen/mind_initialize() ..() mind.special_role = SPECIAL_ROLE_XENOMORPH_QUEEN /mob/living/carbon/alien/humanoid/hunter/mind_initialize() ..() mind.special_role = SPECIAL_ROLE_XENOMORPH_HUNTER /mob/living/carbon/alien/humanoid/drone/mind_initialize() ..() mind.special_role = SPECIAL_ROLE_XENOMORPH_DRONE /mob/living/carbon/alien/humanoid/sentinel/mind_initialize() ..() mind.special_role = SPECIAL_ROLE_XENOMORPH_SENTINEL //XENO LARVA /mob/living/carbon/alien/larva/mind_initialize() ..() mind.special_role = SPECIAL_ROLE_XENOMORPH_LARVA //AI /mob/living/silicon/ai/mind_initialize() ..() mind.assigned_role = "AI" //BORG /mob/living/silicon/robot/mind_initialize() ..() mind.assigned_role = "Cyborg" //PAI /mob/living/silicon/pai/mind_initialize() ..() mind.assigned_role = "pAI" mind.special_role = null //BLOB /mob/camera/overmind/mind_initialize() ..() mind.special_role = SPECIAL_ROLE_BLOB //Animals /mob/living/simple_animal/mind_initialize() ..() mind.assigned_role = "Animal" /mob/living/simple_animal/pet/dog/corgi/mind_initialize() ..() mind.assigned_role = "Corgi" /mob/living/simple_animal/shade/mind_initialize() ..() mind.assigned_role = "Shade" /mob/living/simple_animal/hostile/construct/builder/mind_initialize() ..() mind.assigned_role = "Artificer" mind.special_role = SPECIAL_ROLE_CULTIST /mob/living/simple_animal/hostile/construct/wraith/mind_initialize() ..() mind.assigned_role = "Wraith" mind.special_role = SPECIAL_ROLE_CULTIST /mob/living/simple_animal/hostile/construct/armoured/mind_initialize() ..() mind.assigned_role = "Juggernaut" mind.special_role = SPECIAL_ROLE_CULTIST
0
0.838527
1
0.838527
game-dev
MEDIA
0.80743
game-dev
0.972755
1
0.972755
Dreaming381/Latios-Framework-Add-Ons
1,825
AddOns/FlowFieldNavigation/Types/Flow.cs
using Latios; using Latios.Transforms; using Unity.Burst; using Unity.Collections; using Unity.Jobs; using Unity.Mathematics; namespace Latios.FlowFieldNavigation { [BurstCompile] public struct Flow : INativeDisposable { public bool IsCreated {get; private set;} internal NativeReference<TransformQvvs> Transform; internal NativeHashSet<int2> GoalCells; internal NativeArray<float> Costs; internal NativeArray<float2> DirectionMap; internal FlowSettings Settings; public Flow(in Field field, FlowSettings settings, AllocatorManager.AllocatorHandle allocator) { this.Settings = settings; Transform = field.Transform; var length = field.Width * field.Height; Costs = CollectionHelper.CreateNativeArray<float>(length, allocator); DirectionMap = CollectionHelper.CreateNativeArray<float2>(length, allocator); GoalCells = new NativeHashSet<int2>(FlowSettings.MaxFootprintSize, allocator); IsCreated = true; } public void Dispose() { IsCreated = false; Settings = default; if (Costs.IsCreated) Costs.Dispose(); if (GoalCells.IsCreated) GoalCells.Dispose(); if (DirectionMap.IsCreated) DirectionMap.Dispose(); } public JobHandle Dispose(JobHandle inputDeps) { IsCreated = false; Settings = default; return CollectionsExtensions.CombineDependencies(stackalloc JobHandle[] { Costs.Dispose(inputDeps), GoalCells.Dispose(inputDeps), DirectionMap.Dispose(inputDeps), }); } } }
0
0.870098
1
0.870098
game-dev
MEDIA
0.73155
game-dev
0.97628
1
0.97628
Pico-Developer/XR-Profiling-Toolkit
6,707
Packages/XRProfilingToolKit/Samples~/CyberAlleyVRSampleScene/External/DOTween/Modules/DOTweenModuleEPOOutline.cs
using UnityEngine; #if false || EPO_DOTWEEN // MODULE_MARKER using EPOOutline; using DG.Tweening.Plugins.Options; using DG.Tweening; using DG.Tweening.Core; namespace DG.Tweening { public static class DOTweenModuleEPOOutline { public static int DOKill(this SerializedPass target, bool complete) { return DOTween.Kill(target, complete); } public static TweenerCore<float, float, FloatOptions> DOFloat(this SerializedPass target, string propertyName, float endValue, float duration) { var tweener = DOTween.To(() => target.GetFloat(propertyName), x => target.SetFloat(propertyName, x), endValue, duration); tweener.SetOptions(true).SetTarget(target); return tweener; } public static TweenerCore<Color, Color, ColorOptions> DOFade(this SerializedPass target, string propertyName, float endValue, float duration) { var tweener = DOTween.ToAlpha(() => target.GetColor(propertyName), x => target.SetColor(propertyName, x), endValue, duration); tweener.SetOptions(true).SetTarget(target); return tweener; } public static TweenerCore<Color, Color, ColorOptions> DOColor(this SerializedPass target, string propertyName, Color endValue, float duration) { var tweener = DOTween.To(() => target.GetColor(propertyName), x => target.SetColor(propertyName, x), endValue, duration); tweener.SetOptions(false).SetTarget(target); return tweener; } public static TweenerCore<Vector4, Vector4, VectorOptions> DOVector(this SerializedPass target, string propertyName, Vector4 endValue, float duration) { var tweener = DOTween.To(() => target.GetVector(propertyName), x => target.SetVector(propertyName, x), endValue, duration); tweener.SetOptions(false).SetTarget(target); return tweener; } public static TweenerCore<float, float, FloatOptions> DOFloat(this SerializedPass target, int propertyId, float endValue, float duration) { var tweener = DOTween.To(() => target.GetFloat(propertyId), x => target.SetFloat(propertyId, x), endValue, duration); tweener.SetOptions(true).SetTarget(target); return tweener; } public static TweenerCore<Color, Color, ColorOptions> DOFade(this SerializedPass target, int propertyId, float endValue, float duration) { var tweener = DOTween.ToAlpha(() => target.GetColor(propertyId), x => target.SetColor(propertyId, x), endValue, duration); tweener.SetOptions(true).SetTarget(target); return tweener; } public static TweenerCore<Color, Color, ColorOptions> DOColor(this SerializedPass target, int propertyId, Color endValue, float duration) { var tweener = DOTween.To(() => target.GetColor(propertyId), x => target.SetColor(propertyId, x), endValue, duration); tweener.SetOptions(false).SetTarget(target); return tweener; } public static TweenerCore<Vector4, Vector4, VectorOptions> DOVector(this SerializedPass target, int propertyId, Vector4 endValue, float duration) { var tweener = DOTween.To(() => target.GetVector(propertyId), x => target.SetVector(propertyId, x), endValue, duration); tweener.SetOptions(false).SetTarget(target); return tweener; } public static int DOKill(this Outlinable.OutlineProperties target, bool complete = false) { return DOTween.Kill(target, complete); } public static int DOKill(this Outliner target, bool complete = false) { return DOTween.Kill(target, complete); } /// <summary> /// Controls the alpha (transparency) of the outline /// </summary> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Outlinable.OutlineProperties target, float endValue, float duration) { var tweener = DOTween.ToAlpha(() => target.Color, x => target.Color = x, endValue, duration); tweener.SetOptions(true).SetTarget(target); return tweener; } /// <summary> /// Controls the color of the outline /// </summary> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Outlinable.OutlineProperties target, Color endValue, float duration) { var tweener = DOTween.To(() => target.Color, x => target.Color = x, endValue, duration); tweener.SetOptions(false).SetTarget(target); return tweener; } /// <summary> /// Controls the amount of blur applied to the outline /// </summary> public static TweenerCore<float, float, FloatOptions> DOBlurShift(this Outlinable.OutlineProperties target, float endValue, float duration, bool snapping = false) { var tweener = DOTween.To(() => target.BlurShift, x => target.BlurShift = x, endValue, duration); tweener.SetOptions(snapping).SetTarget(target); return tweener; } /// <summary> /// Controls the amount of blur applied to the outline /// </summary> public static TweenerCore<float, float, FloatOptions> DOBlurShift(this Outliner target, float endValue, float duration, bool snapping = false) { var tweener = DOTween.To(() => target.BlurShift, x => target.BlurShift = x, endValue, duration); tweener.SetOptions(snapping).SetTarget(target); return tweener; } /// <summary> /// Controls the amount of dilation applied to the outline /// </summary> public static TweenerCore<float, float, FloatOptions> DODilateShift(this Outlinable.OutlineProperties target, float endValue, float duration, bool snapping = false) { var tweener = DOTween.To(() => target.DilateShift, x => target.DilateShift = x, endValue, duration); tweener.SetOptions(snapping).SetTarget(target); return tweener; } /// <summary> /// Controls the amount of dilation applied to the outline /// </summary> public static TweenerCore<float, float, FloatOptions> DODilateShift(this Outliner target, float endValue, float duration, bool snapping = false) { var tweener = DOTween.To(() => target.DilateShift, x => target.DilateShift = x, endValue, duration); tweener.SetOptions(snapping).SetTarget(target); return tweener; } } } #endif
0
0.900414
1
0.900414
game-dev
MEDIA
0.638306
game-dev
0.930019
1
0.930019
CryptoMorin/KingdomsX
2,797
resources/languages/ru/guis/item-editor/main.yml
title: "{$sep}-=( {$p}Item Editor {$sep})=-" rows: 3 sound: BLOCK_LEVER_CLICK options: item: # Will be replaced by the actual item material: STONE interaction: FREE slot: 15 name: posx: 1 posy: 1 material: NAME_TAG name: '{$p}Name' lore: "%item_name%" flags: posx: 2 posy: 1 material: BLACK_BANNER name: '{$p}Flags' lore: | {$sep}Click to modify {$dot} {$p}Hide Attributes{$colon} %item_flag_hide_attributes% {$dot} {$p}Hide Destroys{$colon} %item_flag_hide_destroys% {$dot} {$p}Hide Dye{$colon} %item_flag_hide_dye% {$dot} {$p}Hide Enchants{$colon} %item_flag_hide_enchants% {$dot} {$p}Hide Placed On{$colon} %item_flag_hide_placed_on% {$dot} {$p}Hide Unbreakable{$colon} %item_flag_hide_unbreakable% attributes: posx: 3 posy: 1 material: DIAMOND_SWORD name: '{$p}Attributes' decoration: slots: [ 4, 5, 6, 7, 8, 13, 14, 16, 17, 22, 23, 24, 25, 26 ] material: BLACK_STAINED_GLASS_PANE name: '' lore: posx: 1 posy: 2 material: BOOK name: '{$p}Lore' # The lore is automatically set by the plugin for this option enchantments: posx: 2 posy: 2 material: ENCHANTED_BOOK name: '{$p}Enchantments' lore: [ "{$sep}Click to modify" ] # The lore is modified by the plugin to add set enchants unbreakable: isUnbreakable: condition: item_unbreakable name: '{$p}Unbreakable' glow: true else: name: '{$e}Breakable' posx: 3 posy: 2 material: BEDROCK lore: | {$sep}If an item is unbreakable, it'll not decrease its durability when you use it. nbt: posx: 4 posy: 2 material: BOOKSHELF name: '{$p}NBT Viewer' amount: posx: 1 posy: 3 material: SLIME_BALL name: '{$p}Amount{$colon} {$s}%item_amount%' lore: | {$sep}Maximum amount would be {$p}64 {$sep}while you can technically set up to {$p}127 {$sep}it will cause issues in rare situations. For example, the GUI isn't able to show this change and when it's being transferred to your inventory, it might not keep its amount. custom-model-data: posx: 2 posy: 3 material: FIREWORK_STAR name: '{$p}Custom Model Data{$colon} {$s}%item_custom_model_data%' lore: | {$sep}This is used for resource packs that are made for 1.14+ to add new items to the game. This is basically just a reskin of the same item type. This is what plugins like ItemsAdder use to add new items to the game. material: posx: 3 posy: 3 material: STONE # This is a template material, the actual material is taken from the placed item name: '{$p}Material{$colon} {$s}%item_material%'
0
0.95918
1
0.95918
game-dev
MEDIA
0.991082
game-dev
0.577132
1
0.577132
TaiyitistMC/Taiyitist
2,402
modules/taiyitist-server/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java
package org.bukkit.help; import com.google.common.base.Joiner; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.jetbrains.annotations.NotNull; /** * Lacking an alternative, the help system will create instances of * GenericCommandHelpTopic for each command in the server's CommandMap. You * can use this class as a base class for custom help topics, or as an example * for how to write your own. */ public class GenericCommandHelpTopic extends HelpTopic { protected Command command; public GenericCommandHelpTopic(@NotNull Command command) { this.command = command; if (command.getLabel().startsWith("/")) { name = command.getLabel(); } else { name = "/" + command.getLabel(); } // The short text is the first line of the description int i = command.getDescription().indexOf('\n'); if (i > 1) { shortText = command.getDescription().substring(0, i - 1); } else { shortText = command.getDescription(); } // Build full text StringBuilder sb = new StringBuilder(); sb.append(ChatColor.GOLD); sb.append("Description: "); sb.append(ChatColor.WHITE); sb.append(command.getDescription()); sb.append("\n"); sb.append(ChatColor.GOLD); sb.append("Usage: "); sb.append(ChatColor.WHITE); sb.append(command.getUsage().replace("<command>", name.substring(1))); if (command.getAliases().size() > 0) { sb.append("\n"); sb.append(ChatColor.GOLD); sb.append("Aliases: "); sb.append(ChatColor.WHITE); sb.append(Joiner.on(", ").join(command.getAliases())); } fullText = sb.toString(); } @Override public boolean canSee(@NotNull CommandSender sender) { if (!command.isRegistered()) { // Unregistered commands should not show up in the help return false; } if (sender instanceof ConsoleCommandSender) { return true; } if (amendedPermission != null) { return sender.hasPermission(amendedPermission); } else { return command.testPermissionSilent(sender); } } }
0
0.737383
1
0.737383
game-dev
MEDIA
0.656547
game-dev,cli-devtools
0.86179
1
0.86179
libsdl-org/SDL-1.2
2,903
src/joystick/SDL_sysjoystick.h
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga This library is SDL_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; either version 2.1 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" /* This is the system specific header for the SDL joystick API */ #include "SDL_joystick.h" /* The SDL joystick structure */ struct _SDL_Joystick { Uint8 index; /* Device index */ const char *name; /* Joystick name - system dependent */ int naxes; /* Number of axis controls on the joystick */ Sint16 *axes; /* Current axis states */ int nhats; /* Number of hats on the joystick */ Uint8 *hats; /* Current hat states */ int nballs; /* Number of trackballs on the joystick */ struct balldelta { int dx; int dy; } *balls; /* Current ball motion deltas */ int nbuttons; /* Number of buttons on the joystick */ Uint8 *buttons; /* Current button states */ struct joystick_hwdata *hwdata; /* Driver dependent information */ int ref_count; /* Reference count for multiple opens */ }; /* Function to scan the system for joysticks. * Joystick 0 should be the system default joystick. * This function should return the number of available joysticks, or -1 * on an unrecoverable fatal error. */ extern int SDL_SYS_JoystickInit(void); /* Function to get the device-dependent name of a joystick */ extern const char *SDL_SYS_JoystickName(int index); /* Function to open a joystick for use. The joystick to open is specified by the index field of the joystick. This should fill the nbuttons and naxes fields of the joystick structure. It returns 0, or -1 if there is an error. */ extern int SDL_SYS_JoystickOpen(SDL_Joystick *joystick); /* Function to update the state of a joystick - called as a device poll. * This function shouldn't update the joystick structure directly, * but instead should call SDL_PrivateJoystick*() to deliver events * and update joystick device state. */ extern void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick); /* Function to close a joystick after use */ extern void SDL_SYS_JoystickClose(SDL_Joystick *joystick); /* Function to perform any system-specific joystick related cleanup */ extern void SDL_SYS_JoystickQuit(void);
0
0.605401
1
0.605401
game-dev
MEDIA
0.895501
game-dev,drivers
0.561852
1
0.561852
AtomicStryker/atomicstrykers-minecraft-mods
7,774
Minions/src/main/java/atomicstryker/minions/common/jobmanager/TreeScanner.java
package atomicstryker.minions.common.jobmanager; import java.util.ArrayList; import atomicstryker.minions.common.MinionsCore; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; /** * Minion Mod Runnable Tree Scanner class. Finds Trees in a certain area around * a first given Tree, returns a List once done. * * * @author AtomicStryker */ public class TreeScanner implements Runnable { private Minion_Job_TreeHarvest boss; private World world; private int foundTreeCount; private int currentX; private int currentZ; private int currentMaxX; private int currentMaxZ; private Block treeBlockID; private final ArrayList<ChunkPos> skippableCoords; public TreeScanner(Minion_Job_TreeHarvest creator) { boss = creator; skippableCoords = new ArrayList<ChunkPos>(); foundTreeCount = 0; currentMaxX = 0; currentMaxZ = 0; } public void setup(BlockPos coords, World worldObj) { currentX = coords.getX(); currentZ = coords.getZ(); this.world = worldObj; } @Override public void run() { // System.out.println("AS_TreeScanner starting to run at // ["+currentX+"|"+currentZ+"]"); boolean otherDirection = false; while (foundTreeCount < 16 && currentMaxX < 64) { // iterate length X int nextXStop = currentX + (otherDirection ? currentMaxX * -1 : currentMaxX); while (currentX != nextXStop) { checkForTreeAtCoords(); if (otherDirection) { currentX--; } else { currentX++; } } // iterate length Z int nextZStop = currentZ + (otherDirection ? currentMaxZ * -1 : currentMaxZ); while (currentZ != nextZStop) { checkForTreeAtCoords(); if (otherDirection) { currentZ--; } else { currentZ++; } } // change movement direction as per search algorithm otherDirection = !otherDirection; // expand lengths for next run currentMaxX++; currentMaxZ++; } MinionsCore.debugPrint("AS_TreeScanner finished work, found: " + foundTreeCount + "; checked length: " + currentMaxX); boss.onDoneFindingTrees(); } private void checkForTreeAtCoords() { if (skippableCoords.contains(new ChunkPos(currentX, currentZ))) // to // fix // more-than-1-block-thick // trees { return; } // System.out.println("checkForTreeAtCoords // ["+currentX+"|"+currentZ+"]"); BlockPos y = this.world.getTopSolidOrLiquidBlock(new BlockPos(currentX, 0, currentZ)); if (y.getY() != -1) { BlockPos pos = new BlockPos(currentX, y.getY() - 1, currentZ); IBlockState is = this.world.getBlockState(pos); Block ID = is.getBlock(); if (MinionsCore.instance.foundTreeBlocks.contains(ID) || ID.isWood(world, pos)) { IBlockState newState; Block newID; for (y = y.down();; y = y.down()) { newState = world.getBlockState(y); newID = newState.getBlock(); if (newID != ID) { break; } } if (newID == Blocks.AIR || newState.getMaterial() == Material.LEAVES || newID.isLeaves(is, world, y)) { return; } else { onFoundTreeBase(currentX, y.getY() + 1, currentZ); } } } Thread.yield(); } private void onFoundTreeBase(int ix, int iy, int iz) { for (int jx = -1; jx <= 1; jx++) { for (int jz = -1; jz <= 1; jz++) { ChunkPos excludeCoords = new ChunkPos(ix + jx, iz + jz); if (!skippableCoords.contains(excludeCoords)) { skippableCoords.add(excludeCoords); } } } ArrayList<BlockPos> treeBlockList = new ArrayList<BlockPos>(); ArrayList<BlockPos> leaveBlockList = new ArrayList<BlockPos>(); treeBlockID = this.world.getBlockState(new BlockPos(ix, iy, iz)).getBlock(); indexTargetTree(ix, iy, iz, treeBlockList, leaveBlockList); if (treeBlockList.size() > 3) { foundTreeCount++; boss.onFoundTreeBase(ix, iy, iz, treeBlockList, leaveBlockList); } } private void indexTargetTree(int ix, int iy, int iz, ArrayList<BlockPos> treeBlockList, ArrayList<BlockPos> leaveBlockList) { indexTreeBlockRecursive(ix, iy, iz, treeBlockList, leaveBlockList); } private void indexTreeBlockRecursive(int ix, int iy, int iz, ArrayList<BlockPos> treeBlockList, ArrayList<BlockPos> leaveBlockList) { byte one = 1; for (int xIter = -one; xIter <= one; xIter++) { for (int zIter = -one; zIter <= one; zIter++) { for (int yIter = 0; yIter <= one; yIter++) { if (world.getBlockState(new BlockPos(ix + xIter, iy + yIter, iz + zIter)).getBlock() == treeBlockID) { BlockPos coords = new BlockPos(ix + xIter, iy + yIter, iz + zIter); if (!treeBlockList.contains(coords)) { treeBlockList.add(coords); findLeavesRecursive(ix + xIter, iy + yIter, iz + zIter, 0, leaveBlockList); indexTreeBlockRecursive(ix + xIter, iy + yIter, iz + zIter, treeBlockList, leaveBlockList); } } } } } } private void findLeavesRecursive(int ix, int iy, int iz, int fromStem, ArrayList<BlockPos> leaveBlockList) { for (int xIter = -1; xIter <= 1; xIter++) { for (int zIter = -1; zIter <= 1; zIter++) { for (int yIter = 0; yIter <= 1; yIter++) { final BlockPos coords = new BlockPos(ix + xIter, iy + yIter, iz + zIter); final IBlockState is = world.getBlockState(coords); final Block b = is.getBlock(); if (is.getMaterial() == Material.LEAVES || b.isLeaves(is, world, coords)) { if (fromStem < 4) { if (!leaveBlockList.contains(coords)) { leaveBlockList.add(coords); findLeavesRecursive(ix + xIter, iy + yIter, iz + zIter, fromStem + 1, leaveBlockList); } } } } } } } }
0
0.951531
1
0.951531
game-dev
MEDIA
0.943485
game-dev
0.977557
1
0.977557
PacktPublishing/Mastering-Cpp-Game-Development
14,374
Chapter08/Include/bullet/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.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. */ //#define DISABLE_BVH #include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h" #include "BulletCollision/CollisionShapes/btOptimizedBvh.h" #include "LinearMath/btSerializer.h" ///Bvh Concave triangle mesh is a static-triangle mesh shape with Bounding Volume Hierarchy optimization. ///Uses an interface to access the triangles to allow for sharing graphics/physics triangles. btBvhTriangleMeshShape::btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh) :btTriangleMeshShape(meshInterface), m_bvh(0), m_triangleInfoMap(0), m_useQuantizedAabbCompression(useQuantizedAabbCompression), m_ownsBvh(false) { m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE; //construct bvh from meshInterface #ifndef DISABLE_BVH if (buildBvh) { buildOptimizedBvh(); } #endif //DISABLE_BVH } btBvhTriangleMeshShape::btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,bool buildBvh) :btTriangleMeshShape(meshInterface), m_bvh(0), m_triangleInfoMap(0), m_useQuantizedAabbCompression(useQuantizedAabbCompression), m_ownsBvh(false) { m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE; //construct bvh from meshInterface #ifndef DISABLE_BVH if (buildBvh) { void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); m_bvh = new (mem) btOptimizedBvh(); m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax); m_ownsBvh = true; } #endif //DISABLE_BVH } void btBvhTriangleMeshShape::partialRefitTree(const btVector3& aabbMin,const btVector3& aabbMax) { m_bvh->refitPartial( m_meshInterface,aabbMin,aabbMax ); m_localAabbMin.setMin(aabbMin); m_localAabbMax.setMax(aabbMax); } void btBvhTriangleMeshShape::refitTree(const btVector3& aabbMin,const btVector3& aabbMax) { m_bvh->refit( m_meshInterface, aabbMin,aabbMax ); recalcLocalAabb(); } btBvhTriangleMeshShape::~btBvhTriangleMeshShape() { if (m_ownsBvh) { m_bvh->~btOptimizedBvh(); btAlignedFree(m_bvh); } } void btBvhTriangleMeshShape::performRaycast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget) { struct MyNodeOverlapCallback : public btNodeOverlapCallback { btStridingMeshInterface* m_meshInterface; btTriangleCallback* m_callback; MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) :m_meshInterface(meshInterface), m_callback(callback) { } virtual void processNode(int nodeSubPart, int nodeTriangleIndex) { btVector3 m_triangle[3]; const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart); unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; if (type == PHY_FLOAT) { float* graphicsbase = (float*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); } else { double* graphicsbase = (double*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(btScalar(graphicsbase[0])*meshScaling.getX(),btScalar(graphicsbase[1])*meshScaling.getY(),btScalar(graphicsbase[2])*meshScaling.getZ()); } } /* Perform ray vs. triangle collision here */ m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } }; MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); m_bvh->reportRayOverlappingNodex(&myNodeCallback,raySource,rayTarget); } void btBvhTriangleMeshShape::performConvexcast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax) { struct MyNodeOverlapCallback : public btNodeOverlapCallback { btStridingMeshInterface* m_meshInterface; btTriangleCallback* m_callback; MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) :m_meshInterface(meshInterface), m_callback(callback) { } virtual void processNode(int nodeSubPart, int nodeTriangleIndex) { btVector3 m_triangle[3]; const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart); unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; if (type == PHY_FLOAT) { float* graphicsbase = (float*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); } else { double* graphicsbase = (double*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(btScalar(graphicsbase[0])*meshScaling.getX(),btScalar(graphicsbase[1])*meshScaling.getY(),btScalar(graphicsbase[2])*meshScaling.getZ()); } } /* Perform ray vs. triangle collision here */ m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } }; MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); m_bvh->reportBoxCastOverlappingNodex (&myNodeCallback, raySource, rayTarget, aabbMin, aabbMax); } //perform bvh tree traversal and report overlapping triangles to 'callback' void btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const { #ifdef DISABLE_BVH //brute force traverse all triangles btTriangleMeshShape::processAllTriangles(callback,aabbMin,aabbMax); #else //first get all the nodes struct MyNodeOverlapCallback : public btNodeOverlapCallback { btStridingMeshInterface* m_meshInterface; btTriangleCallback* m_callback; btVector3 m_triangle[3]; MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) :m_meshInterface(meshInterface), m_callback(callback) { } virtual void processNode(int nodeSubPart, int nodeTriangleIndex) { const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart); unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT||indicestype==PHY_UCHAR); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:indicestype==PHY_INTEGER?gfxbase[j]:((unsigned char*)gfxbase)[j]; #ifdef DEBUG_TRIANGLE_MESH printf("%d ,",graphicsindex); #endif //DEBUG_TRIANGLE_MESH if (type == PHY_FLOAT) { float* graphicsbase = (float*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3( graphicsbase[0]*meshScaling.getX(), graphicsbase[1]*meshScaling.getY(), graphicsbase[2]*meshScaling.getZ()); } else { double* graphicsbase = (double*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3( btScalar(graphicsbase[0])*meshScaling.getX(), btScalar(graphicsbase[1])*meshScaling.getY(), btScalar(graphicsbase[2])*meshScaling.getZ()); } #ifdef DEBUG_TRIANGLE_MESH printf("triangle vertices:%f,%f,%f\n",triangle[j].x(),triangle[j].y(),triangle[j].z()); #endif //DEBUG_TRIANGLE_MESH } m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } }; MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); m_bvh->reportAabbOverlappingNodex(&myNodeCallback,aabbMin,aabbMax); #endif//DISABLE_BVH } void btBvhTriangleMeshShape::setLocalScaling(const btVector3& scaling) { if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) { btTriangleMeshShape::setLocalScaling(scaling); buildOptimizedBvh(); } } void btBvhTriangleMeshShape::buildOptimizedBvh() { if (m_ownsBvh) { m_bvh->~btOptimizedBvh(); btAlignedFree(m_bvh); } ///m_localAabbMin/m_localAabbMax is already re-calculated in btTriangleMeshShape. We could just scale aabb, but this needs some more work void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); m_bvh = new(mem) btOptimizedBvh(); //rebuild the bvh... m_bvh->build(m_meshInterface,m_useQuantizedAabbCompression,m_localAabbMin,m_localAabbMax); m_ownsBvh = true; } void btBvhTriangleMeshShape::setOptimizedBvh(btOptimizedBvh* bvh, const btVector3& scaling) { btAssert(!m_bvh); btAssert(!m_ownsBvh); m_bvh = bvh; m_ownsBvh = false; // update the scaling without rebuilding the bvh if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) { btTriangleMeshShape::setLocalScaling(scaling); } } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btBvhTriangleMeshShape::serialize(void* dataBuffer, btSerializer* serializer) const { btTriangleMeshShapeData* trimeshData = (btTriangleMeshShapeData*) dataBuffer; btCollisionShape::serialize(&trimeshData->m_collisionShapeData,serializer); m_meshInterface->serialize(&trimeshData->m_meshInterface, serializer); trimeshData->m_collisionMargin = float(m_collisionMargin); if (m_bvh && !(serializer->getSerializationFlags()&BT_SERIALIZE_NO_BVH)) { void* chunk = serializer->findPointer(m_bvh); if (chunk) { #ifdef BT_USE_DOUBLE_PRECISION trimeshData->m_quantizedDoubleBvh = (btQuantizedBvhData*)chunk; trimeshData->m_quantizedFloatBvh = 0; #else trimeshData->m_quantizedFloatBvh = (btQuantizedBvhData*)chunk; trimeshData->m_quantizedDoubleBvh= 0; #endif //BT_USE_DOUBLE_PRECISION } else { #ifdef BT_USE_DOUBLE_PRECISION trimeshData->m_quantizedDoubleBvh = (btQuantizedBvhData*)serializer->getUniquePointer(m_bvh); trimeshData->m_quantizedFloatBvh = 0; #else trimeshData->m_quantizedFloatBvh = (btQuantizedBvhData*)serializer->getUniquePointer(m_bvh); trimeshData->m_quantizedDoubleBvh= 0; #endif //BT_USE_DOUBLE_PRECISION int sz = m_bvh->calculateSerializeBufferSizeNew(); btChunk* chunk = serializer->allocate(sz,1); const char* structType = m_bvh->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_QUANTIZED_BVH_CODE,m_bvh); } } else { trimeshData->m_quantizedFloatBvh = 0; trimeshData->m_quantizedDoubleBvh = 0; } if (m_triangleInfoMap && !(serializer->getSerializationFlags()&BT_SERIALIZE_NO_TRIANGLEINFOMAP)) { void* chunk = serializer->findPointer(m_triangleInfoMap); if (chunk) { trimeshData->m_triangleInfoMap = (btTriangleInfoMapData*)chunk; } else { trimeshData->m_triangleInfoMap = (btTriangleInfoMapData*)serializer->getUniquePointer(m_triangleInfoMap); int sz = m_triangleInfoMap->calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(sz,1); const char* structType = m_triangleInfoMap->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_TRIANLGE_INFO_MAP,m_triangleInfoMap); } } else { trimeshData->m_triangleInfoMap = 0; } return "btTriangleMeshShapeData"; } void btBvhTriangleMeshShape::serializeSingleBvh(btSerializer* serializer) const { if (m_bvh) { int len = m_bvh->calculateSerializeBufferSizeNew(); //make sure not to use calculateSerializeBufferSize because it is used for in-place btChunk* chunk = serializer->allocate(len,1); const char* structType = m_bvh->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_QUANTIZED_BVH_CODE,(void*)m_bvh); } } void btBvhTriangleMeshShape::serializeSingleTriangleInfoMap(btSerializer* serializer) const { if (m_triangleInfoMap) { int len = m_triangleInfoMap->calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(len,1); const char* structType = m_triangleInfoMap->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_TRIANLGE_INFO_MAP,(void*)m_triangleInfoMap); } }
0
0.972979
1
0.972979
game-dev
MEDIA
0.78118
game-dev,graphics-rendering
0.988464
1
0.988464
cmangos/mangos-cata
7,616
src/game/AI/ScriptDevAI/scripts/northrend/azjol-nerub/ahnkahet/boss_nadox.cpp
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * 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 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 */ /* ScriptData SDName: Boss_Nadox SD%Complete: 90% SDComment: Some adjustment may be required SDCategory: Ahn'kahet EndScriptData */ #include "AI/ScriptDevAI/include/precompiled.h" #include "ahnkahet.h" enum { SAY_AGGRO = -1619000, SAY_SUMMON_EGG_1 = -1619001, SAY_SUMMON_EGG_2 = -1619002, SAY_SLAY_1 = -1619003, SAY_SLAY_2 = -1619004, SAY_SLAY_3 = -1619005, SAY_DEATH = -1619006, EMOTE_HATCH = -1619007, SPELL_BROOD_PLAGUE = 56130, SPELL_BROOD_PLAGUE_H = 59467, SPELL_BERSERK = 26662, SPELL_BROOD_RAGE = 59465, SPELL_GUARDIAN_AURA = 56151, // JustSummoned is not called for spell summoned creatures SPELL_SUMMON_SWARM_GUARDIAN = 56120, SPELL_SUMMON_SWARMERS = 56119, NPC_AHNKAHAR_GUARDIAN = 30176, NPC_AHNKAHAR_SWARMER = 30178 }; /*###### ## mob_ahnkahat_egg ######*/ struct mob_ahnkahar_eggAI : public ScriptedAI { mob_ahnkahar_eggAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; void Reset() override {} void MoveInLineOfSight(Unit* /*pWho*/) override {} void AttackStart(Unit* /*pWho*/) override {} void JustSummoned(Creature* pSummoned) override { if (pSummoned->GetEntry() == NPC_AHNKAHAR_GUARDIAN) { pSummoned->CastSpell(pSummoned, SPELL_GUARDIAN_AURA, TRIGGERED_OLD_TRIGGERED); DoScriptText(EMOTE_HATCH, m_creature); } if (m_pInstance) { if (Creature* pElderNadox = m_pInstance->GetSingleCreatureFromStorage(NPC_ELDER_NADOX)) { float fPosX, fPosY, fPosZ; pElderNadox->GetPosition(fPosX, fPosY, fPosZ); pSummoned->SetWalk(false); pSummoned->GetMotionMaster()->MovePoint(0, fPosX, fPosY, fPosZ); } } } void SummonedCreatureJustDied(Creature* pSummoned) override { // If the Guardian is killed set the achiev criteria to false if (pSummoned->GetEntry() == NPC_AHNKAHAR_GUARDIAN) { if (m_pInstance) m_pInstance->SetData(TYPE_NADOX, SPECIAL); } } }; CreatureAI* GetAI_mob_ahnkahar_egg(Creature* pCreature) { return new mob_ahnkahar_eggAI(pCreature); } /*###### ## boss_nadox ######*/ struct boss_nadoxAI : public ScriptedAI { boss_nadoxAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (instance_ahnkahet*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); Reset(); } instance_ahnkahet* m_pInstance; bool m_bIsRegularMode; bool m_bBerserk; bool m_bGuardianSummoned; uint32 m_uiBroodPlagueTimer; uint32 m_uiBroodRageTimer; uint32 m_uiSummonTimer; void Reset() override { m_bBerserk = false; m_bGuardianSummoned = false; m_uiSummonTimer = 5000; m_uiBroodPlagueTimer = 15000; m_uiBroodRageTimer = 20000; } void Aggro(Unit* /*pWho*/) override { DoScriptText(SAY_AGGRO, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_NADOX, IN_PROGRESS); } void JustReachedHome() override { if (m_pInstance) m_pInstance->SetData(TYPE_NADOX, FAIL); } void KilledUnit(Unit* /*pVictim*/) override { switch (urand(0, 2)) { case 0: DoScriptText(SAY_SLAY_1, m_creature); break; case 1: DoScriptText(SAY_SLAY_2, m_creature); break; case 2: DoScriptText(SAY_SLAY_3, m_creature); break; } } void JustDied(Unit* /*pKiller*/) override { DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_NADOX, DONE); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (!m_bGuardianSummoned && m_creature->GetHealthPercent() < 50.0f) { // guardian is summoned at 50% of boss HP if (m_pInstance) { if (Creature* pGuardianEgg = m_creature->GetMap()->GetCreature(m_pInstance->SelectRandomGuardianEggGuid())) pGuardianEgg->CastSpell(pGuardianEgg, SPELL_SUMMON_SWARM_GUARDIAN, TRIGGERED_NONE); m_bGuardianSummoned = true; } } if (m_uiSummonTimer < uiDiff) { if (roll_chance_i(50)) DoScriptText(urand(0, 1) ? SAY_SUMMON_EGG_1 : SAY_SUMMON_EGG_2, m_creature); if (m_pInstance) { // There are 2 Swarmers summoned at a timer if (Creature* pSwarmerEgg = m_creature->GetMap()->GetCreature(m_pInstance->SelectRandomSwarmerEggGuid())) { for (uint8 i = 0; i < 2; ++i) pSwarmerEgg->CastSpell(pSwarmerEgg, SPELL_SUMMON_SWARMERS, TRIGGERED_NONE); } } m_uiSummonTimer = urand(5000, 10000); } else m_uiSummonTimer -= uiDiff; if (m_uiBroodPlagueTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) DoCastSpellIfCan(pTarget, m_bIsRegularMode ? SPELL_BROOD_PLAGUE : SPELL_BROOD_PLAGUE_H); m_uiBroodPlagueTimer = 20000; } else m_uiBroodPlagueTimer -= uiDiff; if (!m_bIsRegularMode) { if (m_uiBroodRageTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BROOD_RAGE) == CAST_OK) m_uiBroodRageTimer = 20000; } else m_uiBroodRageTimer -= uiDiff; } if (!m_bBerserk && m_creature->GetPositionZ() < 24.0) { if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK) m_bBerserk = true; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_nadox(Creature* pCreature) { return new boss_nadoxAI(pCreature); } void AddSC_boss_nadox() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_nadox"; pNewScript->GetAI = &GetAI_boss_nadox; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_ahnkahar_egg"; pNewScript->GetAI = &GetAI_mob_ahnkahar_egg; pNewScript->RegisterSelf(); }
0
0.908057
1
0.908057
game-dev
MEDIA
0.976451
game-dev
0.994228
1
0.994228
AddstarMC/Prism-Bukkit
10,209
Prism/src/main/java/me/botsko/prism/actions/GenericAction.java
package me.botsko.prism.actions; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.botsko.prism.Prism; import me.botsko.prism.actionlibs.ActionTypeImpl; import me.botsko.prism.api.ChangeResult; import me.botsko.prism.api.PrismParameters; import me.botsko.prism.api.actions.ActionType; import me.botsko.prism.api.actions.Handler; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.data.BlockData; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; import java.text.SimpleDateFormat; import java.util.UUID; public abstract class GenericAction implements Handler { private static final SimpleDateFormat date = new SimpleDateFormat("yy/MM/dd"); private static final SimpleDateFormat time = new SimpleDateFormat("hh:mm:ssa"); private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private boolean canceled = false; private ActionType type; private long id; private long epoch; private String sourceName; private UUID playerUuid; private Location location; private Material material = Material.AIR; private BlockData blockData; private Material oldBlock = Material.AIR; private BlockData oldBlockData; private int aggregateCount = 0; public GenericAction() { epoch = System.currentTimeMillis() / 1000; } protected static Gson gson() { return GenericAction.gson; } @Override public String getCustomDesc() { return null; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getId() */ @Override public long getId() { return id; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#setId(int) */ @Override public void setId(long id) { this.id = id; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getActionTime() */ @Override public long getUnixEpoch() { return epoch; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#setDisplayDate(java.lang.String) */ @Override public void setUnixEpoch(long epoch) { this.epoch = epoch; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getDisplayDate() */ @Override public String getDisplayDate() { return date.format(epoch * 1000); } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getDisplayTime() */ @Override public String getDisplayTime() { return time.format(epoch * 1000); } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getTimeSince() */ @Override public String getTimeSince() { long diffInSeconds = System.currentTimeMillis() / 1000 - epoch; if (diffInSeconds < 60) { return "just now"; } long period = 24 * 60 * 60; final long[] diff = { diffInSeconds / period, (diffInSeconds / (period /= 24)) % 24, (diffInSeconds / (period /= 60)) % 60 }; StringBuilder timeAgo = new StringBuilder(); if (diff[0] > 0) { timeAgo.append(diff[0]).append('d'); } if (diff[1] > 0) { timeAgo.append(diff[1]).append('h'); } if (diff[2] > 0) { timeAgo.append(diff[2]).append('m'); } // 'time_ago' will have something at this point, because if all 'diff's // were 0, the first if check would have caught and returned "just now" return timeAgo.append(" ago").toString(); } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getType() */ @Override public ActionType getActionType() { return type; } /** * Set Action Type from a String. * * @param actionType String */ public void setActionType(String actionType) { if (actionType != null) { setActionType(Prism.getActionRegistry().getAction(actionType)); } } /** * Set the Action Type. * * @param type {@link ActionTypeImpl} */ @Override public void setActionType(ActionType type) { this.type = type; } private void createWorldIfNull() { if (location == null) { location = Bukkit.getWorlds().get(0).getSpawnLocation(); } } /** * Set the player. * * @param player OfflinePlayer */ public void setPlayer(AnimalTamer player) { if (player != null) { setUuid(player.getUniqueId()); this.sourceName = player.getName(); } } /** * {@inheritDoc} */ @Override public @Nullable String getSourceName() { if (sourceName != null) { return sourceName; } return Bukkit.getOfflinePlayer(playerUuid).getName(); } /** * {@inheritDoc} */ @Override public void setSourceName(String sourceName) { this.sourceName = sourceName; this.playerUuid = null; } /** * {@inheritDoc} */ @Override public UUID getUuid() { return playerUuid; } /** * {@inheritDoc} */ @Override public void setUuid(UUID uuid) { this.playerUuid = uuid; this.sourceName = null; } /** * {@inheritDoc} */ @Override public void setX(double x) { createWorldIfNull(); location.setX(x); } /** * {@inheritDoc} */ @Override public void setY(double y) { createWorldIfNull(); location.setY(y); } /** * {@inheritDoc} */ @Override public void setZ(double z) { createWorldIfNull(); location.setZ(z); } /** * Get World. * * @return World */ public World getWorld() { if (location != null) { return location.getWorld(); } return null; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#setWorld(org.bukkit.World) */ @Override public void setWorld(World world) { createWorldIfNull(); location.setWorld(world); } /** * Get Location. * * @return Location */ public Location getLoc() { return location; } /** * Set Location. * * @param loc Location */ public void setLoc(Location loc) { if (loc != null) { location = loc.clone(); } else { location = null; } } @Override public Material getMaterial() { return material; } @Override public void setMaterial(Material material) { this.material = material; } /* * (non-Javadoc) * * @see me.botsko.prism.actions.Handler#getBlockSubId() */ @Override public BlockData getBlockData() { return blockData; } /** * {@inheritDoc} */ @Override public void setBlockData(BlockData data) { this.blockData = data; } @Override public short getDurability() { return 0; } @Override public void setDurability(short durability) { } @Override public Material getOldMaterial() { return oldBlock; } @Override public void setOldMaterial(Material material) { this.oldBlock = material; } /** * {@inheritDoc} */ @Override public BlockData getOldBlockData() { return oldBlockData; } /** * {@inheritDoc} */ @Override public void setOldBlockData(BlockData data) { this.oldBlockData = data; } /** * {@inheritDoc} */ @Override public short getOldDurability() { return 0; } /** * {@inheritDoc} */ @Override public void setOldDurability(short durability) { } /** * {@inheritDoc} */ @Override public int getAggregateCount() { return aggregateCount; } /** * {@inheritDoc} */ @Override public void setAggregateCount(int aggregateCount) { this.aggregateCount = aggregateCount; } /** * {@inheritDoc} */ @Override public boolean isCanceled() { return canceled; } @Override public void setCanceled(boolean cancel) { this.canceled = cancel; } /** * Currently these methods are not made available in the api. As they perform world * changes. This can be reviewed later. * * @param player Player * @param parameters PrismParameters * @param isPreview boolean * @return ChangeResult */ public ChangeResult applyRollback(Player player, PrismParameters parameters, boolean isPreview) { return null; } /** * See above. * * @see GenericAction#applyRollback(Player, PrismParameters, boolean) * @param player Player * @param parameters PrismParameters * @param isPreview boolean * @return ChangeResult */ public ChangeResult applyRestore(Player player, PrismParameters parameters, boolean isPreview) { return null; } /** * See above. * * @see GenericAction#applyRollback(Player, PrismParameters, boolean) * @param player Player * @param parameters PrismParameters * @param isPreview boolean * @return ChangeResult */ public ChangeResult applyUndo(Player player, PrismParameters parameters, boolean isPreview) { return null; } /** * See above. * * @see GenericAction#applyRollback(Player, PrismParameters, boolean) * @param player Player * @param parameters PrismParameters * @param isPreview boolean * @return ChangeResult */ public ChangeResult applyDeferred(Player player, PrismParameters parameters, boolean isPreview) { return null; } }
0
0.774824
1
0.774824
game-dev
MEDIA
0.283064
game-dev
0.891113
1
0.891113
yigao/NFShmXFrame
3,627
game/MMO/NFLogicComm/DescStore/FestivalMuban_contrecharge_dayDesc.cpp
#include "FestivalMuban_contrecharge_dayDesc.h" #include "NFComm/NFPluginModule/NFCheck.h" FestivalMuban_contrecharge_dayDesc::FestivalMuban_contrecharge_dayDesc() { if (EN_OBJ_MODE_INIT == NFShmMgr::Instance()->GetCreateMode()) { CreateInit(); } else { ResumeInit(); } } FestivalMuban_contrecharge_dayDesc::~FestivalMuban_contrecharge_dayDesc() { } int FestivalMuban_contrecharge_dayDesc::CreateInit() { return 0; } int FestivalMuban_contrecharge_dayDesc::ResumeInit() { return 0; } int FestivalMuban_contrecharge_dayDesc::Load(NFResDB *pDB) { NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--begin--"); CHECK_EXPR(pDB != NULL, -1, "pDB == NULL"); NFLogTrace(NF_LOG_SYSTEMLOG, 0, "FestivalMuban_contrecharge_dayDesc::Load() strFileName = {}", GetFileName()); proto_ff::Sheet_FestivalMuban_contrecharge_day table; NFResTable* pResTable = pDB->GetTable(GetFileName()); CHECK_EXPR(pResTable != NULL, -1, "pTable == NULL, GetTable:{} Error", GetFileName()); int iRet = 0; iRet = pResTable->FindAllRecord(GetDBName(), &table); CHECK_EXPR(iRet == 0, -1, "FindAllRecord Error:{}", GetFileName()); //NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", table.Utf8DebugString()); if ((table.e_festivalmuban_contrecharge_day_list_size() < 0) || (table.e_festivalmuban_contrecharge_day_list_size() > (int)(m_astDescMap.max_size()))) { NFLogError(NF_LOG_SYSTEMLOG, 0, "Invalid TotalNum:{}", table.e_festivalmuban_contrecharge_day_list_size()); return -2; } m_minId = INVALID_ID; for (int i = 0; i < (int)table.e_festivalmuban_contrecharge_day_list_size(); i++) { const proto_ff::E_FestivalMuban_contrecharge_day& desc = table.e_festivalmuban_contrecharge_day_list(i); if (desc.has_m_id() == false && desc.ByteSize() == 0) { NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc no value, {}", desc.Utf8DebugString()); continue; } if (m_minId == INVALID_ID) { m_minId = desc.m_id(); } else { if (desc.m_id() < m_minId) { m_minId = desc.m_id(); } } //NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", desc.Utf8DebugString()); if (m_astDescMap.find(desc.m_id()) != m_astDescMap.end()) { if (IsReloading()) { auto pDesc = GetDesc(desc.m_id()); NF_ASSERT_MSG(pDesc, "the desc:{} Reload, GetDesc Failed!, id:{}", GetClassName(), desc.m_id()); pDesc->read_from_pbmsg(desc); } else { NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc:{} id:{} exist", GetClassName(), desc.m_id()); } continue; } CHECK_EXPR_ASSERT(m_astDescMap.size() < m_astDescMap.max_size(), -1, "m_astDescMap Space Not Enough"); auto pDesc = &m_astDescMap[desc.m_id()]; CHECK_EXPR_ASSERT(pDesc, -1, "m_astDescMap Insert Failed desc.id:{}", desc.m_id()); pDesc->read_from_pbmsg(desc); CHECK_EXPR_ASSERT(GetDesc(desc.m_id()) == pDesc, -1, "GetDesc != pDesc, id:{}", desc.m_id()); } for(int i = 0; i < (int)m_astDescIndex.size(); i++) { m_astDescIndex[i] = INVALID_ID; } for(auto iter = m_astDescMap.begin(); iter != m_astDescMap.end(); iter++) { int64_t index = (int64_t)iter->first - (int64_t)m_minId; if (index >= 0 && index < (int64_t)m_astDescIndex.size()) { m_astDescIndex[index] = iter.m_curNode->m_self; CHECK_EXPR_ASSERT(iter == m_astDescMap.get_iterator(m_astDescIndex[index]), -1, "index error"); CHECK_EXPR_ASSERT(GetDesc(iter->first) == &iter->second, -1, "GetDesc != iter->second, id:{}", iter->first); } } NFLogTrace(NF_LOG_SYSTEMLOG, 0, "load {}, num={}", iRet, table.e_festivalmuban_contrecharge_day_list_size()); NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--end--"); return 0; } int FestivalMuban_contrecharge_dayDesc::CheckWhenAllDataLoaded() { return 0; }
0
0.982275
1
0.982275
game-dev
MEDIA
0.475738
game-dev
0.993711
1
0.993711