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
pret/pmd-red
17,265
src/world_map.c
#include "global.h" #include "globaldata.h" #include "bg_control.h" #include "bg_palette_buffer.h" #include "code_8004AA0.h" #include "code_800558C.h" #include "graphics_memory.h" #include "code_800C9CC.h" #include "code_800D090.h" #include "music_util.h" #include "world_map_sound.h" #include "decompress_at.h" #include "decompress_sir.h" #include "def_filearchives.h" #include "dungeon_info.h" #include "friend_area.h" #include "game_options.h" #include "input.h" #include "math.h" #include "play_time.h" #include "pokemon.h" #include "sprite.h" #include "string_format.h" #include "text_1.h" #include "text_2.h" #include "text_3.h" #include "world_map.h" extern void WaitForNextFrameAndAdvanceRNG(void); static EWRAM_INIT struct WorldMap *sWorldMapPtr = NULL; static EWRAM_INIT WindowTemplates sWorldMapWindows = { .id = { [0] = { .type = WINDOW_TYPE_NORMAL, .pos = {2, 10}, .width = 26, .height = 9, .unk10 = 9, }, [1] = { .type = WINDOW_TYPE_NORMAL, .pos = {23, 6}, .width = 5, .height = 3, .unk10 = 3, }, [2] = WIN_TEMPLATE_DUMMY, [3] = WIN_TEMPLATE_DUMMY, } }; static void ClearWindows(void); static void AnimateSprites(bool8 a0); static bool8 FadeScreen(void); static void nullsub_24(void); static void WorldMap_RunFrameActions(void); static void UpdateMonSpritePosition(void); static void UpdateBg(void); static void sub_8010494(struct WorldMapInfo *r9); static void AnimateMonPath_Async(u8 id1, u8 id2); static void sub_801059C(void); static bool8 PlayerEnterDungeonPrompt_Async(u8 *str); static void PrintDialogueMessage_Async(const u8 *text); static void FadeFromWorldMap_Async(void); static void CloseFiles(void); static void PrintDungeonName(DungeonLocation *dungLocation); // Code is very similar to the functions in friend_areas_map_util.c void ShowWorldMap_Async(struct WorldMapSetupStruct *setupPtr) { s32 i, speciesId, dungeonEnter; u8 text[1000]; sWorldMapPtr = setupPtr->worldMap; gUnknown_2026E4E = 2566; sub_80095CC(0, 0x14); UpdateFadeInTile(2); sub_801059C(); sub_8010494(&setupPtr->info); PlayWorldMapBGM(); // 60 frame delay for (i = 0; i < 60; i++) WorldMap_RunFrameActions(); AnimateMonPath_Async(setupPtr->info.startLocation.id, setupPtr->info.unk4.unk0.id); PrintDungeonName(&setupPtr->info.unk4.unk0); // 60 frame delay for (i = 0; i < 60; i++) WorldMap_RunFrameActions(); if (setupPtr->info.unk4.unkC) { speciesId = setupPtr->info.mon.speciesNum; ASM_MATCH_TRICK(speciesId); } else { speciesId = 0; } dungeonEnter = BufferDungeonRequirementsText(setupPtr->info.unk4.unk0.id, speciesId, text, setupPtr->info.unk6C, FALSE); if (dungeonEnter == DUNGEON_REQUIREMENTS_PASS) { setupPtr->dungeonEntered = TRUE; } else if (dungeonEnter == DUNGEON_REQUIREMENTS_FAIL) { PrintDialogueMessage_Async(text); setupPtr->dungeonEntered = FALSE; } else if (dungeonEnter == DUNGEON_REQUIREMENTS_ASK) { if (PlayerEnterDungeonPrompt_Async(text)) { setupPtr->dungeonEntered = TRUE; } else { setupPtr->dungeonEntered = FALSE; } } FadeFromWorldMap_Async(); CloseFiles(); nullsub_16(); } static const DungeonPos gDungeonCoordinates[] = { [DUNGEON_TINY_WOODS] = {172, 174}, [DUNGEON_THUNDERWAVE_CAVE] = {171, 111}, [DUNGEON_MT_STEEL] = {242, 126}, [DUNGEON_SINISTER_WOODS] = {232, 181}, [DUNGEON_SILENT_CHASM] = {263, 155}, [DUNGEON_MT_THUNDER] = {298, 159}, [DUNGEON_MT_THUNDER_PEAK] = {299, 142}, [DUNGEON_GREAT_CANYON] = {203, 255}, [DUNGEON_LAPIS_CAVE] = {385, 166}, [DUNGEON_MT_BLAZE] = {388, 126}, [DUNGEON_MT_BLAZE_PEAK] = {389, 109}, [DUNGEON_FROSTY_FOREST] = {417, 112}, [DUNGEON_FROSTY_GROTTO] = {422, 101}, [DUNGEON_MT_FREEZE] = {432, 85}, [DUNGEON_MT_FREEZE_PEAK] = {436, 69}, [DUNGEON_MAGMA_CAVERN] = {442, 150}, [DUNGEON_MAGMA_CAVERN_PIT] = {446, 163}, [DUNGEON_SKY_TOWER] = {365, 27}, [DUNGEON_SKY_TOWER_SUMMIT] = {352, 12}, [DUNGEON_STORMY_SEA] = {133, 238}, [DUNGEON_SILVER_TRENCH] = {129, 143}, [DUNGEON_METEOR_CAVE] = {344, 105}, [DUNGEON_MT_FREEZE_PEAK_2] = {427, 62}, [DUNGEON_WESTERN_CAVE] = {27, 211}, [DUNGEON_BOSS_3] = {246, 315}, [DUNGEON_BOSS_4] = {443, 6}, [DUNGEON_WISH_CAVE] = {32, 279}, [DUNGEON_BURIED_RELIC] = {404, 262}, [DUNGEON_PITFALL_VALLEY] = {194, 63}, [DUNGEON_NORTHERN_RANGE] = {159, 46}, [DUNGEON_BOSS_9] = {441, 310}, [DUNGEON_DESERT_REGION] = {231, 235}, [DUNGEON_SOUTHERN_CAVERN] = {169, 287}, [DUNGEON_WYVERN_HILL] = {441, 273}, [DUNGEON_FIERY_FIELD] = {64, 87}, [DUNGEON_NORTHWIND_FIELD] = {80, 54}, [DUNGEON_SOLAR_CAVE] = {431, 225}, [DUNGEON_LIGHTNING_FIELD] = {27, 94}, [DUNGEON_DARKNIGHT_RELIC] = {354, 298}, [DUNGEON_WONDROUS_SEA] = {336, 253}, [DUNGEON_MURKY_CAVE] = {287, 222}, [DUNGEON_GRAND_SEA] = {63, 163}, [DUNGEON_UPROAR_FOREST] = {275, 111}, [DUNGEON_ODDITY_CAVE] = {202, 232}, [DUNGEON_REMAINS_ISLAND] = {268, 302}, [DUNGEON_MARVELOUS_SEA] = {336, 260}, [DUNGEON_FANTASY_STRAIT] = {110, 79}, [DUNGEON_ROCK_PATH] = {225, 314}, [DUNGEON_SNOW_PATH] = {206, 314}, [DUNGEON_AUTOPILOT] = {11, 307}, [DUNGEON_D50] = {472, 25}, [DUNGEON_D51] = {250, 8}, [DUNGEON_NORMAL_MAZE] = {187, 190}, [DUNGEON_HOWLING_FOREST] = {205, 111}, [DUNGEON_D54] = {474, 6}, [DUNGEON_POISON_MAZE] = {183, 9}, [DUNGEON_WATERFALL_POND] = {367, 214}, [DUNGEON_UNOWN_RELIC] = {278, 273}, [DUNGEON_JOYOUS_TOWER] = {68, 305}, [DUNGEON_FAR_OFF_SEA] = {270, 33}, [DUNGEON_MT_FARAWAY] = {33, 39}, [DUNGEON_D61] = {217, 8}, [DUNGEON_PURITY_FOREST] = {69, 280}, [DUNGEON_OUT_ON_RESCUE] = {192, 183}, }; // Heavy math function. static void AnimateMonPath_Async(u8 id1, u8 id2) { s32 i, valMax, r3; PixelPos pixelPos; DungeonPos pos1 = gDungeonCoordinates[id1]; DungeonPos pos2 = gDungeonCoordinates[id2]; valMax = max(abs(pos2.x - pos1.x), abs(pos2.y - pos1.y)); valMax /= 2; pixelPos.x = pos1.x - pos2.x; pixelPos.y = pos2.y - pos1.y; r3 = Atan2_4096(&pixelPos) - 1024; if (r3 < 0) { r3 += 511; } r3 >>= 9; r3 &= 7; AxResInitFile(&sWorldMapPtr->monAxSprite, sWorldMapPtr->unk1100[3], 0, r3, 0, 0, TRUE); for (i = 0; i < valMax; i++) { sWorldMapPtr->monSpritePos.x = ((((pos2.x - pos1.x) * (i << 8)) / valMax) / 256) + pos1.x; sWorldMapPtr->monSpritePos.y = ((((pos2.y - pos1.y) * (i << 8)) / valMax) / 256) + pos1.y; UpdateMonSpritePosition(); UpdateBg(); WorldMap_RunFrameActions(); if (gRealInputs.pressed & A_BUTTON) break; if (gRealInputs.pressed & B_BUTTON) break; } sWorldMapPtr->monSpritePos = pos2; UpdateMonSpritePosition(); UpdateBg(); WorldMap_RunFrameActions(); } static void sub_8010494(struct WorldMapInfo *info) { s32 i; for (i = 0; i < 64; i++) { struct UnkStruct_Sub1 *structPtr = &sWorldMapPtr->unk0[i]; u8 r0; if (i < WORLD_MAP_UNK_6D_COUNT) { r0 = info->unk6D[i]; } else { r0 = 1; } if (r0) { structPtr->unk0 = 1; AxResInitFile(&structPtr->unk8, sWorldMapPtr->unk1100[2], (i == WORLD_MAP_UNK_6D_COUNT) ? 12 : 1, 0, 0x40, 0, 1); structPtr->unk4 = gDungeonCoordinates[i]; } else { structPtr->unk0 = 0; } } AxResInitFile(&sWorldMapPtr->monAxSprite, sWorldMapPtr->unk1100[3], 0, 0, 0, 0, TRUE); sWorldMapPtr->monSpritePos = gDungeonCoordinates[info->startLocation.id]; sWorldMapPtr->bgPos.x = sWorldMapPtr->monSpritePos.x - 120; sWorldMapPtr->bgPos.y = sWorldMapPtr->monSpritePos.y - 80; UpdateMonSpritePosition(); UpdateBg(); } static char *const gUnknown_80D4014[] = { "wmp2font", "wmp2mcc", "wmp2cani", "wmp2pal", "wmp2fon1", // Maybe blue uses this? }; static void sub_801059C(void) { u8 filename[0xC]; s32 i, size; Pokemon *pokeStruct = GetPlayerPokemonStruct(); OpenedFile *file = OpenFileAndGetFileDataPtr(gUnknown_80D4014[0], &gTitleMenuFileArchive); OpenedFile *file2 = OpenFileAndGetFileDataPtr(gUnknown_80D4014[1], &gTitleMenuFileArchive); sprintf(filename, "ax%03d", pokeStruct->speciesNum); sWorldMapPtr->unk1100[3] = OpenFileAndGetFileDataPtr(filename, &gMonsterFileArchive); sWorldMapPtr->unk1100[2] = OpenFileAndGetFileDataPtr("wmapspr", &gTitleMenuFileArchive); sWorldMapPtr->unk1100[4] = OpenFileAndGetFileDataPtr(gUnknown_80D4014[2], &gTitleMenuFileArchive); sWorldMapPtr->unk1100[1] = OpenFileAndGetFileDataPtr("palet", &gMonsterFileArchive); sWorldMapPtr->unk1100[0] = OpenFileAndGetFileDataPtr(gUnknown_80D4014[3], &gTitleMenuFileArchive); sWorldMapPtr->unk52D4 = GetPokemonOverworldPalette(pokeStruct->speciesNum, FALSE); sub_8005610(sWorldMapPtr->unk1100[2], 0x40, 0x1F, 0); DecompressATGlobalFile((u32 *)(VRAM + 0x8000), 0x0, file); sub_8004AA4(sWorldMapPtr->unk5150, sWorldMapPtr->unk1100[4], 0x10); size = 0x4000; DecompressATFile(&sWorldMapPtr->unk1114, size, file2); sWorldMapPtr->brightness = 0; sWorldMapPtr->bgPos.x = 0; sWorldMapPtr->bgPos.y = 0; for (i = 0; i < UNK_WORLD_MAP_52E0_COUNT; i++) { sWorldMapPtr->unk52E0[i] = 0xFFFF; sWorldMapPtr->unk5E98[i] = 0; } CloseFile(file); CloseFile(file2); ShowWindows(NULL, 1, 1); } static void CloseFiles(void) { CloseFile(sWorldMapPtr->unk1100[4]); CloseFile(sWorldMapPtr->unk1100[3]); CloseFile(sWorldMapPtr->unk1100[2]); CloseFile(sWorldMapPtr->unk1100[0]); CloseFile(sWorldMapPtr->unk1100[1]); } static void UpdateMonSpritePosition(void) { if (sWorldMapPtr->monSpritePos.x - sWorldMapPtr->bgPos.x < 48) { sWorldMapPtr->bgPos.x = sWorldMapPtr->monSpritePos.x - 48; } else if (sWorldMapPtr->monSpritePos.x - sWorldMapPtr->bgPos.x > 192) { sWorldMapPtr->bgPos.x = sWorldMapPtr->monSpritePos.x - 192; } if (sWorldMapPtr->monSpritePos.y - sWorldMapPtr->bgPos.y < 48) { sWorldMapPtr->bgPos.y = sWorldMapPtr->monSpritePos.y - 48; } else if (sWorldMapPtr->monSpritePos.y - sWorldMapPtr->bgPos.y > 112) { sWorldMapPtr->bgPos.y = sWorldMapPtr->monSpritePos.y - 112; } if (sWorldMapPtr->bgPos.x < 0) { sWorldMapPtr->bgPos.x = 0; } if (sWorldMapPtr->bgPos.y < 0) { sWorldMapPtr->bgPos.y = 0; } if (sWorldMapPtr->bgPos.x >= 240) { sWorldMapPtr->bgPos.x = 240; } if (sWorldMapPtr->bgPos.y >= 160) { sWorldMapPtr->bgPos.y = 160; } } static void UpdateBg(void) { s32 i, j; s32 y1 = sWorldMapPtr->bgPos.y >> 3; s32 y2 = y1; for (i = 0; i < 21; i++) { s32 x1 = sWorldMapPtr->bgPos.x >> 3; s32 x2 = x1; for (j = 0; j < 31; j++) { x1 &= 0x1F; y1 &= 0x1F; gBgTilemaps[2][y1][x1] = sWorldMapPtr->unk3114[y2][x2]; gBgTilemaps[3][y1][x1] = sWorldMapPtr->unk1114[y2][x2]; x2++; x1++; } y2++; y1++; } ScheduleBgTilemapCopy(2); ScheduleBgTilemapCopy(3); } static void nullsub_24(void) { } static void FadeFromWorldMap_Async(void) { s32 i; ClearWindows(); FadeOutWorldMapBGM(); for (i = 0; i < 60; i++) { sWorldMapPtr->brightness -= 2; WorldMap_RunFrameActions(); } } static void ClearWindows(void) { ShowWindows(NULL, TRUE, TRUE); } static void WorldMap_RunFrameActions(void) { SetBG2RegOffsets(sWorldMapPtr->bgPos.x, sWorldMapPtr->bgPos.y); SetBG3RegOffsets(sWorldMapPtr->bgPos.x, sWorldMapPtr->bgPos.y); AnimateSprites(TRUE); FadeScreen(); sub_8005838(NULL, 0); nullsub_8(gGameOptionsRef->touchScreen); sub_8005180(); sub_80060EC(); IncrementPlayTime(gPlayTimeRef); WaitForNextFrameAndAdvanceRNG(); LoadBufferedInputs(); CopySpritesToOam(); sub_8005304(); TransferBGPaletteBuffer(); xxx_call_update_bg_vram(); nullsub_24(); DoScheduledMemCopies(); xxx_call_update_bg_sound_input(); UpdateSoundEffectCounters(); ResetSprites(FALSE); } static bool8 FadeScreen(void) { bool8 ret = FALSE; if (sWorldMapPtr->brightness < 31) { s32 i; RGB *color = (void *) sWorldMapPtr->unk1100[0]->data; if (++sWorldMapPtr->brightness >= 31) { sWorldMapPtr->brightness = 31; } for (i = 0; i < 224; color++, i++) { SetBGPaletteBufferColorRGB(i, color, sWorldMapPtr->brightness, NULL); } color = (void *) sWorldMapPtr->unk1100[1]->data; for (i = 0; i < 240; color++, i++) { SetBGPaletteBufferColorRGB(i + 256, color, sWorldMapPtr->brightness, NULL); } ret = TRUE; } return ret; } static void AnimateSprites(bool8 a0) { s32 i; unkStruct_2039DB0 var_2C; DungeonPos pos; sub_8004E8C(&var_2C); var_2C.unk4 = 0xF3FF; var_2C.unkA = 0x800; pos = sWorldMapPtr->bgPos; RunAxAnimationFrame(&sWorldMapPtr->monAxSprite); if (a0) { DoAxFrame_800558C(&sWorldMapPtr->monAxSprite, sWorldMapPtr->monSpritePos.x - pos.x, sWorldMapPtr->monSpritePos.y - pos.y, 3, sWorldMapPtr->unk52D4, &var_2C); } for (i = 0; i < 64; i++) { struct UnkStruct_Sub1 *structPtr = &sWorldMapPtr->unk0[i]; if (structPtr->unk0) { axdata *axPtr = &structPtr->unk8; RunAxAnimationFrame(axPtr); if (a0) { DoAxFrame_800558C(axPtr, structPtr->unk4.x - pos.x, structPtr->unk4.y - pos.y, 1, 0, &var_2C); } } } } static void PrintDungeonName(DungeonLocation *dungLocation) { WindowTemplates windows = { .id = { [0] = { .type = WINDOW_TYPE_NORMAL, .pos = {12, 2}, .width = 16, .height = 2, .unk10 = 2, }, [1] = WIN_TEMPLATE_DUMMY, [2] = WIN_TEMPLATE_DUMMY, [3] = WIN_TEMPLATE_DUMMY, } }; if (sWorldMapPtr->monSpritePos.y - sWorldMapPtr->bgPos.y <= 80) { windows.id[0].pos.y = 17; } else { windows.id[0].pos.y = 1; } ShowWindows(&windows, TRUE, TRUE); sub_80073B8(0); CopyDungeonName1toBuffer(gFormatBuffer_Monsters[0], dungLocation); PrintFormattedStringOnWindow(12, 2, _("{CENTER_ALIGN}{POKEMON_0}"), 0, '\0'); sub_80073E0(0); } static void PrintDialogueMessage_Async(const u8 *text) { s32 i, a; CreateMenuDialogueBoxAndPortrait(text, NULL, 0, NULL, NULL, 3, 0, NULL, 0x301); do { DrawDialogueBoxString(); WorldMap_RunFrameActions(); } while (sub_80144A4(&a) != 0); for (i = 0; i < 10; i++) WorldMap_RunFrameActions(); } static bool8 PlayerEnterDungeonPrompt_Async(u8 *str) { s32 height, i; MenuInputStruct menuInput; height = 0; for (i = 0; str[i] != '\0'; i++) { if (str[i] == '\n') height += 12; } height += 11; height /= 8; sWorldMapWindows.id[0].pos.y = 19 - height; sWorldMapWindows.id[0].unk10 = height; sWorldMapWindows.id[0].height = height; sWorldMapWindows.id[1].pos.y = 14 - height; ShowWindows(&sWorldMapWindows, TRUE, TRUE); sub_80073B8(0); PrintFormattedStringOnWindow(4, 0, str, 0, '\0'); sub_80073E0(0); sub_80073B8(1); PrintFormattedStringOnWindow(10, 0, "Yes", 1, '\0'); PrintFormattedStringOnWindow(10, 12, "No", 1, '\0'); sub_80073E0(1); menuInput.menuIndex = 1; menuInput.currPageEntries = 2; menuInput.entriesPerPage = 2; menuInput.currPage = 0; menuInput.pagesCount = 0; menuInput.unk4 = 0; menuInput.firstEntryY = 0; menuInput.windowId = 1; menuInput.leftRightArrowsPos.x = 0; menuInput.leftRightArrowsPos.y = 0; menuInput.unk14.x = 0; menuInput.unk14.y = 0; menuInput.cursorArrowPos.x = 8; menuInput.cursorArrowPos.y = 8; sub_80137B0(&menuInput, 24); ResetTouchScreenMenuInput(&menuInput.touchScreen); while (TRUE) { AddMenuCursorSprite(&menuInput); WorldMap_RunFrameActions(); if (gRealInputs.repeated & DPAD_DOWN) { MoveMenuCursorDown(&menuInput); PlayCursorUpDownSoundEffect(); } if (gRealInputs.repeated & DPAD_UP) { MoveMenuCursorUp(&menuInput); PlayCursorUpDownSoundEffect(); } if ((gRealInputs.pressed & A_BUTTON) || menuInput.touchScreen.a_button) { PlayAcceptSoundEffect(); break; } } if (menuInput.menuIndex == 0) return TRUE; // Yes return FALSE; } static UNUSED void GetDungeonCoords(u8 id, DungeonPos *pos) { pos->x = gDungeonCoordinates[id].x; pos->y = gDungeonCoordinates[id].y; }
412
0.958268
1
0.958268
game-dev
MEDIA
0.963417
game-dev
0.913453
1
0.913453
dilmerv/UnityVisionOS2DAndVR
1,376
Assets/Samples/XR Interaction Toolkit/2.5.3/Starter Assets/DemoSceneAssets/Scripts/IncrementUIText.cs
using UnityEngine.UI; namespace UnityEngine.XR.Interaction.Toolkit.Samples.StarterAssets { /// <summary> /// Add this component to a GameObject and call the <see cref="IncrementText"/> method /// in response to a Unity Event to update a text display to count up with each event. /// </summary> public class IncrementUIText : MonoBehaviour { [SerializeField] [Tooltip("The Text component this behavior uses to display the incremented value.")] Text m_Text; /// <summary> /// The Text component this behavior uses to display the incremented value. /// </summary> public Text text { get => m_Text; set => m_Text = value; } int m_Count; /// <summary> /// See <see cref="MonoBehaviour"/>. /// </summary> protected void Awake() { if (m_Text == null) Debug.LogWarning("Missing required Text component reference. Use the Inspector window to assign which Text component to increment.", this); } /// <summary> /// Increment the string message of the Text component. /// </summary> public void IncrementText() { m_Count += 1; if (m_Text != null) m_Text.text = m_Count.ToString(); } } }
412
0.628726
1
0.628726
game-dev
MEDIA
0.700061
game-dev
0.698864
1
0.698864
microsoft/kiota-dotnet
6,080
src/abstractions/serialization/IParseNode.cs
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ using System; using System.Collections.Generic; #if NET5_0_OR_GREATER using System.Diagnostics.CodeAnalysis; #endif namespace Microsoft.Kiota.Abstractions.Serialization { /// <summary> /// Interface for a deserialization node in a parse tree. This interace provides an abstraction layer over serialiation formats, libararies and implementations. /// </summary> public interface IParseNode { /// <summary> /// Gets the string value of the node. /// </summary> /// <returns>The string value of the node.</returns> string? GetStringValue(); /// <summary> /// Gets a new parse node for the given identifier. /// </summary> /// <param name="identifier">The identifier.</param> /// <returns>The new parse node.</returns> IParseNode? GetChildNode(string identifier); /// <summary> /// Gets the boolean value of the node. /// </summary> /// <returns>The boolean value of the node.</returns> bool? GetBoolValue(); /// <summary> /// Gets the byte value of the node. /// </summary> /// <returns>The byte value of the node.</returns> byte? GetByteValue(); /// <summary> /// Gets the sbyte value of the node. /// </summary> /// <returns>The sbyte value of the node.</returns> sbyte? GetSbyteValue(); /// <summary> /// Gets the integer value of the node. /// </summary> /// <returns>The integer value of the node.</returns> int? GetIntValue(); /// <summary> /// Gets the float value of the node. /// </summary> /// <returns>The float value of the node.</returns> float? GetFloatValue(); /// <summary> /// Gets the long value of the node. /// </summary> /// <returns>The long value of the node.</returns> long? GetLongValue(); /// <summary> /// Gets the double value of the node. /// </summary> /// <returns>The double value of the node.</returns> double? GetDoubleValue(); /// <summary> /// Gets the decimal value of the node. /// </summary> /// <returns>The decimal value of the node.</returns> decimal? GetDecimalValue(); /// <summary> /// Gets the GUID value of the node. /// </summary> /// <returns>The GUID value of the node.</returns> Guid? GetGuidValue(); /// <summary> /// Gets the DateTimeOffset value of the node. /// </summary> /// <returns>The DateTimeOffset value of the node.</returns> DateTimeOffset? GetDateTimeOffsetValue(); /// <summary> /// Gets the TimeSpan value of the node. /// </summary> /// <returns>The TimeSpan value of the node.</returns> TimeSpan? GetTimeSpanValue(); /// <summary> /// Gets the Date value of the node. /// </summary> /// <returns>The Date value of the node.</returns> Date? GetDateValue(); /// <summary> /// Gets the Time value of the node. /// </summary> /// <returns>The Time value of the node.</returns> Time? GetTimeValue(); /// <summary> /// Gets the collection of primitive values of the node. /// </summary> /// <returns>The collection of primitive values.</returns> #if NET5_0_OR_GREATER IEnumerable<T> GetCollectionOfPrimitiveValues<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>(); #else IEnumerable<T> GetCollectionOfPrimitiveValues<T>(); #endif /// <summary> /// Gets the collection of enum values of the node. /// </summary> /// <returns>The collection of enum values.</returns> #if NET5_0_OR_GREATER IEnumerable<T?> GetCollectionOfEnumValues<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>() where T : struct, Enum; #else IEnumerable<T?> GetCollectionOfEnumValues<T>() where T : struct, Enum; #endif /// <summary> /// Gets the collection of model objects values of the node. /// </summary> /// <param name="factory">The factory to use to create the model object.</param> /// <returns>The collection of model objects values.</returns> IEnumerable<T> GetCollectionOfObjectValues<T>(ParsableFactory<T> factory) where T : IParsable; /// <summary> /// Gets the enum value of the node. /// </summary> /// <returns>The enum value of the node.</returns> #if NET5_0_OR_GREATER T? GetEnumValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>() where T : struct, Enum; #else T? GetEnumValue<T>() where T : struct, Enum; #endif /// <summary> /// Gets the model object value of the node. /// </summary> /// <param name="factory">The factory to use to create the model object.</param> /// <returns>The model object value of the node.</returns> T GetObjectValue<T>(ParsableFactory<T> factory) where T : IParsable; /// <summary> /// Callback called before the node is deserialized. /// </summary> Action<IParsable>? OnBeforeAssignFieldValues { get; set; } /// <summary> /// Callback called after the node is deserialized. /// </summary> Action<IParsable>? OnAfterAssignFieldValues { get; set; } /// <summary> /// Gets the byte array value of the node. /// </summary> /// <returns>The byte array value of the node.</returns> byte[]? GetByteArrayValue(); } }
412
0.746235
1
0.746235
game-dev
MEDIA
0.20469
game-dev
0.637268
1
0.637268
FlightGear/flightgear
4,535
src/Network/opengc.hxx
//// opengc.hxx - Network interface program to send sim data onto a LAN // // Created by: J. Wojnaroski -- castle@mminternet.com // Date: 21 Nov 2001 // // // Adapted from original network code developed by C. Olson // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef _FG_OPENGC_HXX #define _FG_OPENGC_HXX #include <simgear/compiler.h> #include <string> #include <Main/fg_props.hxx> #include "protocol.hxx" #include "opengc_data.hxx" class FlightProperties; class FGOpenGC : public FGProtocol { ogcFGData buf; FlightProperties* fdm; // Environment SGPropertyNode_ptr press_node; SGPropertyNode_ptr temp_node; SGPropertyNode_ptr wind_dir_node; SGPropertyNode_ptr wind_speed_node; SGPropertyNode_ptr magvar_node; // Position on the Geod SGPropertyNode_ptr p_latitude; SGPropertyNode_ptr p_longitude; SGPropertyNode_ptr p_elev_node; //SGPropertyNode_ptr p_altitude; SGPropertyNode_ptr p_altitude_agl; // Orientation SGPropertyNode_ptr p_pitch; SGPropertyNode_ptr p_bank; SGPropertyNode_ptr p_heading; SGPropertyNode_ptr p_yaw; SGPropertyNode_ptr p_yaw_rate; // Flight Parameters SGPropertyNode_ptr vel_kcas; SGPropertyNode_ptr p_vvi; SGPropertyNode_ptr p_mach; // Control surfaces SGPropertyNode_ptr p_left_aileron; SGPropertyNode_ptr p_right_aileron; SGPropertyNode_ptr p_elevator; SGPropertyNode_ptr p_elevator_trim; SGPropertyNode_ptr p_rudder; SGPropertyNode_ptr p_flaps; SGPropertyNode_ptr p_flaps_cmd; // GEAR System SGPropertyNode_ptr p_park_brake; // Engines SGPropertyNode_ptr egt0_node; SGPropertyNode_ptr egt1_node; SGPropertyNode_ptr egt2_node; SGPropertyNode_ptr egt3_node; SGPropertyNode_ptr epr0_node; SGPropertyNode_ptr epr1_node; SGPropertyNode_ptr epr2_node; SGPropertyNode_ptr epr3_node; SGPropertyNode_ptr n10_node; SGPropertyNode_ptr n11_node; SGPropertyNode_ptr n12_node; SGPropertyNode_ptr n13_node; SGPropertyNode_ptr n20_node; SGPropertyNode_ptr n21_node; SGPropertyNode_ptr n22_node; SGPropertyNode_ptr n23_node; SGPropertyNode_ptr oil_temp0; SGPropertyNode_ptr oil_temp1; SGPropertyNode_ptr oil_temp2; SGPropertyNode_ptr oil_temp3; // Fuel System SGPropertyNode_ptr tank0_node; SGPropertyNode_ptr tank1_node; SGPropertyNode_ptr tank2_node; SGPropertyNode_ptr tank3_node; SGPropertyNode_ptr tank4_node; SGPropertyNode_ptr tank5_node; SGPropertyNode_ptr tank6_node; SGPropertyNode_ptr tank7_node; // Boost pumps; Center tank has only override pumps; boosts are in the // four main wing tanks 1->4 // SGPropertyNode_ptr boost1_node; // SGPropertyNode_ptr boost2_node; // SGPropertyNode_ptr boost3_node; // SGPropertyNode_ptr boost4_node; // SGPropertyNode_ptr boost5_node; // SGPropertyNode_ptr boost6_node; // SGPropertyNode_ptr boost7_node; // SGPropertyNode_ptr boost8_node; // Override pumps // SGPropertyNode_ptr ovride0_node; // SGPropertyNode_ptr ovride1_node; // SGPropertyNode_ptr ovride2_node; // SGPropertyNode_ptr ovride3_node; // SGPropertyNode_ptr ovride4_node; // SGPropertyNode_ptr ovride5_node; // X_Feed valves // SGPropertyNode_ptr x_feed0_node; // SGPropertyNode_ptr x_feed1_node; // SGPropertyNode_ptr x_feed2_node; // SGPropertyNode_ptr x_feed3_node; // Aero numbers SGPropertyNode_ptr p_alphadot; SGPropertyNode_ptr p_betadot; public: FGOpenGC(); ~FGOpenGC(); // open hailing frequencies bool open(); // process work for this port bool process(); // close the channel bool close(); void collect_data(ogcFGData *data ); }; #endif // _FG_OPENGC_HXX
412
0.736668
1
0.736668
game-dev
MEDIA
0.16003
game-dev
0.570008
1
0.570008
AberFray/how-to-make-game-cheats-and-anticheats
3,479
1. Introduction/GetQuakeHandle.cpp
#include <iostream> // For general input and output #include <Windows.h> // Windows API for interacting with windows processes #include <TlHelp32.h> // For getting snapshots int main() { /* Get the process ID to attach later */ DWORD gameProcID = -1; // Variable to hold the process ID, has to be a DWORD because the windows API wants it that way. Starts as -1 (which is invald) so it is known if the process wasn't found HANDLE procSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS , 0); // Creates a "snapshot" of the current processes (Essentially a list of the processes) // Creates a placeholder process entry, that will hold each process for checking PROCESSENTRY32 currentProc; currentProc.dwSize = sizeof(PROCESSENTRY32); // Has to have it's "sizeof" member set, or else the loop fails. // Loops through each process in the snapshot until it finds Winquake.exe if (Process32First(procSnap, &currentProc)) { // Starts by getting the first process do { if (!_wcsicmp(currentProc.szExeFile, L"Winquake.exe")) { // Checks if the process is Winquake, using a Wide Character String Compare function // If found, update the variable and break out the loop gameProcID = currentProc.th32ProcessID; break; } } while (Process32Next(procSnap, &currentProc)); // While there are still more processes, keep checking } CloseHandle(procSnap); // Close the snapshot. Good memory management :) // If it can't find the process, print and then close if (gameProcID == -1) { std::cout << "Couldn't find process" << std::endl; exit(1); } /* Get the module inside the found process (Quite similar to finding the process) */ uintptr_t gameBaseAddr = -1; // Variable to hold the base memory address of the module we want to find, Starts as -1 (which is invalid) so it is known if the module wasn't found HANDLE modSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, gameProcID); // Creates a snapshot of all the modules inside the process // Creates a placeholder module entry, that will hold each module for checking MODULEENTRY32 currentMod; currentMod.dwSize = sizeof(currentMod); // Has to have it's "sizeof" member set, or else the loop fails. // Loops through each module in the snapshot until it finds Winquake.exe if (Module32First(modSnap, &currentMod)) { // Starts by getting the first module do { if (!_wcsicmp(currentMod.szModule, L"Winquake.exe")) { // Checks if the module is Winquake, using a Wide Character String Compare fucntion // If found, update the variable and break out the loop gameBaseAddr = (uintptr_t)currentMod.modBaseAddr; } } while (Module32Next(modSnap, &currentMod)); // While there are still more modules, keep checking } CloseHandle(modSnap); // Close the snapshot. Good memory management // If it can't find the module, print and then close if (gameBaseAddr == -1) { std::cout << "Couldn't find module inside game. Perhaps you have the wrong 'Winquake.exe' executable" << std::endl; exit(1); } // The final handle for the game process HANDLE gameProc = OpenProcess(PROCESS_ALL_ACCESS, NULL, gameProcID); // Opens a handle to attach to the Winquake process and module. With full access rights }
412
0.736717
1
0.736717
game-dev
MEDIA
0.390099
game-dev
0.657674
1
0.657674
GregTechCEu/GregTech
4,085
src/main/java/gregtech/common/gui/impl/FakeModularUIContainerClipboard.java
package gregtech.common.gui.impl; import gregtech.api.GregTechAPI; import gregtech.api.gui.ModularUI; import gregtech.api.gui.Widget; import gregtech.api.gui.impl.FakeModularGuiContainer; import gregtech.common.metatileentities.MetaTileEntityClipboard; import gregtech.core.network.packets.PacketClipboardUIWidgetUpdate; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Tuple; import io.netty.buffer.Unpooled; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import static gregtech.api.capability.GregtechDataCodes.UPDATE_UI; public class FakeModularUIContainerClipboard extends FakeModularGuiContainer { private final List<ItemStack> inventoryItemStacks = new ArrayList<>(); public final List<Slot> inventorySlots = new ArrayList<>(); public int windowId; public MetaTileEntityClipboard clipboard; public FakeModularUIContainerClipboard(ModularUI modularUI, MetaTileEntityClipboard clipboard) { super(modularUI); this.clipboard = clipboard; } protected void addSlotToContainer(Slot slotIn) { slotIn.slotNumber = this.inventorySlots.size(); this.inventorySlots.add(slotIn); this.inventoryItemStacks.add(ItemStack.EMPTY); } public void handleSlotUpdate(PacketBuffer updateData) { try { int size = updateData.readVarInt(); for (int i = 0; i < size; i++) { inventorySlots.get(updateData.readVarInt()).putStack(updateData.readItemStack()); } } catch (Exception ignored) { } } public void handleClientAction(PacketBuffer buffer) { int windowId = buffer.readVarInt(); if (windowId == this.windowId) { Widget widget = modularUI.guiWidgets.get(buffer.readVarInt()); if (widget != null) { widget.handleClientAction(buffer.readVarInt(), buffer); } } } @Override public boolean detectSyncedPacket(PacketBuffer buffer) { return this.windowId == buffer.readVarInt(); } public void detectAndSendChanges() { List<Tuple<Integer, ItemStack>> toUpdate = new ArrayList<>(); for (int i = 0; i < this.inventorySlots.size(); ++i) { ItemStack real = this.inventorySlots.get(i).getStack(); ItemStack fake = this.inventoryItemStacks.get(i); if (!ItemStack.areItemStacksEqual(fake, real)) { boolean clientStackChanged = !ItemStack.areItemStacksEqualUsingNBTShareTag(fake, real); fake = real.isEmpty() ? ItemStack.EMPTY : real.copy(); this.inventoryItemStacks.set(i, fake); if (clientStackChanged) { toUpdate.add(new Tuple<>(i, fake)); } } } modularUI.guiWidgets.values().forEach(Widget::detectAndSendChanges); } @Override public void writeClientAction(Widget widget, int updateId, Consumer<PacketBuffer> payloadWriter) { int widgetId = modularUI.guiWidgets.inverse().get(widget); PacketBuffer packetBuffer = new PacketBuffer(Unpooled.buffer()); packetBuffer.writeVarInt(windowId); packetBuffer.writeVarInt(widgetId); packetBuffer.writeVarInt(updateId); payloadWriter.accept(packetBuffer); GregTechAPI.networkHandler.sendToServer(new PacketClipboardUIWidgetUpdate( this.clipboard.getWorld().provider.getDimension(), this.clipboard.getPos(), updateId, packetBuffer)); } @Override public void writeUpdateInfo(Widget widget, int updateId, Consumer<PacketBuffer> payloadWriter) { this.clipboard.writeCustomData(UPDATE_UI + modularUI.guiWidgets.inverse().get(widget), buf -> { buf.writeVarInt(windowId); buf.writeVarInt(modularUI.guiWidgets.inverse().get(widget)); buf.writeVarInt(updateId); payloadWriter.accept(buf); }); } }
412
0.700535
1
0.700535
game-dev
MEDIA
0.767029
game-dev
0.703908
1
0.703908
Kampfkarren/zombie-strike
1,992
src/mission/ServerScriptService/BossLocalScripts/Samurai/SwordSpin.client.ts
import { CollectionService, Players, RunService, SoundService } from "@rbxts/services" import * as BossLocalScriptUtil from "mission/ReplicatedStorage/Libraries/BossLocalScriptUtil" import WarningRange from "mission/ReplicatedStorage/Libraries/WarningRange" const RANGE_OFFSET = 5 const SWORD_SPIN_RANGE = 15 const SWORD_SPIN_RATE = 12 const SWORD_SPIN_DELAY_PHASE1 = 2.5 const SWORD_SPIN_DELAY_PHASE2 = 1.8 const SwordSpin = BossLocalScriptUtil.WaitForBossRemote("SwordSpin") let swordSpinTick = 0 SwordSpin.OnClientEvent.Connect((swordPoints: Attachment[]) => { swordSpinTick += 1 const spinTick = swordSpinTick const boss = CollectionService.GetTagged("Boss")[0] as Model & { CurrentPhase: NumberValue, } const primaryPart = boss.PrimaryPart! const angle = primaryPart.CFrame.sub(primaryPart.Position) let touched = false const warningRange = WarningRange(primaryPart.Position.sub( new Vector3(0, RANGE_OFFSET, 0) ), SWORD_SPIN_RANGE) warningRange.Touched.Connect((part) => { const character = Players.LocalPlayer.Character if (character !== undefined && part.IsDescendantOf(character) && !touched) { touched = true SwordSpin.FireServer() } }) let angleTotal = 0 for (const swordPoint of swordPoints) { touched = false const initial = primaryPart.Position const goal = new Vector3(swordPoint.WorldPosition.X, initial.Y, swordPoint.WorldPosition.Z) let total = 0 const spinDelay = boss.CurrentPhase.Value === 1 ? SWORD_SPIN_DELAY_PHASE2 : SWORD_SPIN_DELAY_PHASE1 while (total < spinDelay && swordSpinTick === spinTick) { const delta = RunService.Heartbeat.Wait()[0] total += delta angleTotal += delta const centerPosition = initial.Lerp(goal, total / spinDelay) boss.SetPrimaryPartCFrame( new CFrame(centerPosition) .mul(angle) .mul(CFrame.Angles(0, angleTotal * SWORD_SPIN_RATE, 0)), ) warningRange.Position = centerPosition.sub(new Vector3(0, RANGE_OFFSET, 0)) } } warningRange.Destroy() })
412
0.878174
1
0.878174
game-dev
MEDIA
0.903514
game-dev
0.942428
1
0.942428
ProjectIgnis/CardScripts
1,196
official/c29947751.lua
--D・マグネンU --Morphtronic Magnen local s,id=GetID() function s.initial_effect(c) --atk local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET) e1:SetCondition(s.cona) e1:SetValue(s.vala) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_DIRECT_ATTACK) e2:SetCondition(s.cona) c:RegisterEffect(e2) --def local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetRange(LOCATION_MZONE) e3:SetTargetRange(0,LOCATION_MZONE) e3:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET) e3:SetCondition(s.cond) e3:SetValue(s.atlimit) c:RegisterEffect(e3) end function s.cona(e) return e:GetHandler():IsAttackPos() and Duel.IsExistingMatchingCard(Card.IsFaceup,e:GetHandler():GetControler(),0,LOCATION_MZONE,1,nil) end function s.filter(c,atk) return c:IsFaceup() and c:GetAttack()>atk end function s.vala(e,c) if c:IsFaceup() then return Duel.IsExistingMatchingCard(s.filter,c:GetControler(),LOCATION_MZONE,0,1,c,c:GetAttack()) else return true end end function s.cond(e) return e:GetHandler():IsDefensePos() end function s.atlimit(e,c) return c~=e:GetHandler() end
412
0.804335
1
0.804335
game-dev
MEDIA
0.970075
game-dev
0.920821
1
0.920821
opentibiabr/otservbr-global
5,776
data/npc/ortheus.lua
local internalNpcName = "Ortheus" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 153, lookHead = 40, lookBody = 121, lookLegs = 121, lookFeet = 116, lookAddons = 0 } npcConfig.flags = { floorchange = false } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end local BloodBrothers = Storage.Quest.U8_4.BloodBrothers local function creatureSayCallback(npc, creature, type, message) local player = Player(creature) local playerId = player:getId() if message == "cookie" then if player:getStorageValue(BloodBrothers.Mission02) == 1 and player:getItemCount(8199) > 0 and player:getStorageValue(BloodBrothers.Cookies.Ortheus) < 0 then npcHandler:say("A cookie? Well... I have to admit I haven't had one for ages. Can I have it?", npc, creature) npcHandler:setTopic(playerId, 1) else npcHandler:say("It'd be better for you to leave now.", npc, creature) end elseif message == "yes" then if npcHandler:getTopic(playerId) == 1 and player:removeItem(8199, 1) then -- garlic cookie npcHandler:say("Well thanks, it looks tasty, I'll just take a bi - COUGH! Are you trying to poison me?? Get out of here before I forget myself!", npc, creature) player:setStorageValue(BloodBrothers.Cookies.Ortheus, 1) npcHandler:setTopic(playerId, 0) elseif npcHandler:getTopic(playerId) == 2 then if player:removeItem(2880, 17) then -- mug of tea npcHandler:say("Wow. These polite young adventurers nowadays. Thank you.", npc, creature) npcHandler:setTopic(playerId, 0) else npcHandler:say("Hmmm, you don't have tea with you.", npc, creature) npcHandler:setTopic(playerId, 0) end end elseif message == "tea" then npcHandler:say("Have you actually brought me a mug of tea??", npc, creature) npcHandler:setTopic(playerId, 2) elseif message == "no" then if npcHandler:getTopic(playerId) == 2 then npcHandler:say("What a pity.", npc, creature) npcHandler:setTopic(playerId, 0) end end end --Basic keywordHandler:addKeyword({"magicians"}, StdModule.say, {npcHandler = npcHandler, text = "I can't imagine a better place to live."}) keywordHandler:addKeyword({"live"}, StdModule.say, {npcHandler = npcHandler, text = "Though the city has seen better days, the quality of life is still much better than in most other cities."}) keywordHandler:addKeyword({"job"}, StdModule.say, {npcHandler = npcHandler, text = "Hm, good question. Maybe old, wise man?"}) keywordHandler:addKeyword({"name"}, StdModule.say, {npcHandler = npcHandler, text = "I'm used to being called old man. Simple as that."}) keywordHandler:addKeyword({"vampire"}, StdModule.say, {npcHandler = npcHandler, text = "I don't know what you're talking about."}) keywordHandler:addKeyword({"blood"}, StdModule.say, {npcHandler = npcHandler, text = "Yes, it's a bit messy down there. Sorry."}) keywordHandler:addKeyword({"julius"}, StdModule.say, {npcHandler = npcHandler, text = "Doesn't ring a bell."}) keywordHandler:addKeyword({"armenius"}, StdModule.say, {npcHandler = npcHandler, text = "He rarely comes here."}) keywordHandler:addKeyword({"maris"}, StdModule.say, {npcHandler = npcHandler, text = "A man of the seas."}) keywordHandler:addKeyword({"lisander"}, StdModule.say, {npcHandler = npcHandler, text = "He used to visit me for a chat, but ever since that new tavern opened I haven't seen him much anymore."}) keywordHandler:addKeyword({"serafin"}, StdModule.say, {npcHandler = npcHandler, text = "He sometimes delivers fruit and vegetables to this quarter."}) keywordHandler:addKeyword({"yalahar"}, StdModule.say, {npcHandler = npcHandler, text = "Though the city has seen better days, the quality of life is still much better than in most other cities."}) keywordHandler:addKeyword({"quarter"}, StdModule.say, {npcHandler = npcHandler, text = "I can't imagine a better place to live"}) keywordHandler:addKeyword({"alori mort"}, StdModule.say, {npcHandler = npcHandler, text = "Whatever that's supposed to mean."}, function(player) return player:getStorageValue(BloodBrothers.Mission03) == 1 end) keywordHandler:addKeyword({"reward"}, StdModule.say, {npcHandler = npcHandler, text = "I don't have anything that I could give you as a reward. Guess you aren't so selfless after all, huh?"}) keywordHandler:addKeyword({"augur"}, StdModule.say, {npcHandler = npcHandler, text = "They try to protect the city and do a decent job. Well - no, a poor job, I mean a poor job."}) keywordHandler:addKeyword({"mission"}, StdModule.say, {npcHandler = npcHandler, text = "You can bring me a mug of tea if you want to."}) keywordHandler:addAliasKeyword({"quest"}) npcHandler:setMessage(MESSAGE_GREET, "What's your business here with the {magicians}, |PLAYERNAME|?") npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) -- npcType registering the npcConfig table npcType:register(npcConfig)
412
0.852356
1
0.852356
game-dev
MEDIA
0.956083
game-dev
0.914404
1
0.914404
SourMesen/Mesen2
1,642
Core/Shared/Movies/MovieManager.cpp
#include "pch.h" #include <algorithm> #include "Utilities/FolderUtilities.h" #include "Utilities/VirtualFile.h" #include "Utilities/ZipReader.h" #include "Shared/Emulator.h" #include "Shared/Movies/MovieManager.h" #include "Shared/Movies/MesenMovie.h" #include "Shared/Movies/MovieRecorder.h" MovieManager::MovieManager(Emulator* emu) { _emu = emu; } void MovieManager::Record(RecordMovieOptions options) { //Stop any active recording/playback before starting playback for this movie Stop(); shared_ptr<MovieRecorder> recorder(new MovieRecorder(_emu)); if(recorder->Record(options)) { _recorder.reset(recorder); } } void MovieManager::Play(VirtualFile file, bool forTest) { vector<uint8_t> fileData; if(file.IsValid() && file.ReadFile(fileData)) { shared_ptr<IMovie> player; if(memcmp(fileData.data(), "PK", 2) == 0) { //Mesen movie ZipReader reader; reader.LoadArchive(fileData); vector<string> files = reader.GetFileList(); if(std::find(files.begin(), files.end(), "GameSettings.txt") != files.end()) { player.reset(new MesenMovie(_emu, forTest)); } } //Stop any active recording/playback before starting playback for this movie Stop(); if(player && player->Play(file)) { _player.reset(player); if(!forTest) { MessageManager::DisplayMessage("Movies", "MoviePlaying", file.GetFileName()); } } } } void MovieManager::Stop() { shared_ptr<IMovie> player = _player.lock(); if(player) { player->Stop(); } _player.reset(); _recorder.reset(); } bool MovieManager::Playing() { return _player != nullptr; } bool MovieManager::Recording() { return _recorder != nullptr; }
412
0.66253
1
0.66253
game-dev
MEDIA
0.762187
game-dev
0.709654
1
0.709654
nesrak1/AssetsTools.NET
32,974
AssetTools.NET/Standard/AssetsBundleFileFormat/AssetBundleFile.cs
using AssetsTools.NET.Extra; using AssetsTools.NET.Extra.Decompressors.LZ4; using LZ4ps; using SevenZip.Compression.LZMA; using System; using System.Collections.Generic; using System.IO; namespace AssetsTools.NET { public class AssetBundleFile { /// <summary> /// Bundle header. Contains bundle engine version. /// </summary> public AssetBundleHeader Header { get; set; } /// <summary> /// List of compression blocks and file info (file names, address in file, etc.) /// </summary> public AssetBundleBlockAndDirInfo BlockAndDirInfo { get; set; } /// <summary> /// Reader for data block of bundle /// </summary> public AssetsFileReader DataReader { get; set; } /// <summary> /// Is data reader reading compressed data? Only LZMA bundles set this to true. /// </summary> public bool DataIsCompressed { get; set; } public AssetsFileReader Reader; /// <summary> /// Closes the reader. /// </summary> public void Close() { Reader.Close(); DataReader.Close(); } /// <summary> /// Read the <see cref="AssetBundleFile"/> with the provided reader. /// </summary> /// <param name="reader">The reader to use.</param> public void Read(AssetsFileReader reader) { Reader = reader; Reader.Position = 0; Reader.BigEndian = true; string magic = reader.ReadNullTerminated(); // skipped and read by header uint version = reader.ReadUInt32(); if (version >= 6 || version <= 8) { Reader.Position = 0; Header = new AssetBundleHeader(); Header.Read(reader); if (Header.Version >= 7) { reader.Align16(); } if (Header.Signature == "UnityFS") { UnpackInfoOnly(); } else { new NotImplementedException("Non UnityFS bundles are not supported yet."); } } else { new NotImplementedException($"Version {version} bundles are not supported yet."); } } /// <summary> /// Write the <see cref="AssetBundleFile"/> with the provided writer. /// </summary> /// <param name="writer">The writer to use.</param> /// <param name="filePos">Where in the stream to start writing. Use -1 to start writing at the current stream position.</param> public void Write(AssetsFileWriter writer, long filePos = 0) { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); if (Header.Signature != "UnityFS") throw new NotImplementedException("Non UnityFS bundles are not supported yet."); if (DataIsCompressed) throw new Exception("Bundles must be decompressed before writing."); long writeStart = filePos; if (filePos == -1) writeStart = writer.Position; else writer.Position = filePos; List<AssetBundleDirectoryInfo> directoryInfos = BlockAndDirInfo.DirectoryInfos; Header.Write(writer); if (Header.Version >= 7) { writer.Align16(); } long blockDataLength = 0; int blockDataCount = 1; foreach (AssetBundleDirectoryInfo dirInfo in directoryInfos) { if (dirInfo.Replacer != null) { blockDataLength += dirInfo.Replacer.GetSize(); } else { blockDataLength += dirInfo.DecompressedSize; } while (blockDataLength >= uint.MaxValue) { blockDataLength -= uint.MaxValue; blockDataCount++; } } AssetBundleBlockAndDirInfo newBundleInf = new AssetBundleBlockAndDirInfo() { Hash = new Hash128(), BlockInfos = new AssetBundleBlockInfo[blockDataCount] }; for (int i = 0; i < blockDataCount; i++) { newBundleInf.BlockInfos[i] = new AssetBundleBlockInfo { CompressedSize = 0, DecompressedSize = 0, Flags = 0x40 }; } List<AssetBundleDirectoryInfo> dirInfos = new List<AssetBundleDirectoryInfo>(); // write all original file infos and skip those to be removed int dirCount = directoryInfos.Count; for (int i = 0; i < dirCount; i++) { AssetBundleDirectoryInfo dirInfo = directoryInfos[i]; ContentReplacerType replacerType = dirInfo.ReplacerType; if (replacerType == ContentReplacerType.Remove) continue; dirInfos.Add(new AssetBundleDirectoryInfo() { // offset and size to be edited later Offset = dirInfo.Offset, DecompressedSize = dirInfo.DecompressedSize, Flags = dirInfo.Flags, Name = dirInfo.Name, Replacer = dirInfo.Replacer, }); } // write the listings long bundleInfPos = writer.Position; // this is only here to allocate enough space so it's fine if it's inaccurate newBundleInf.DirectoryInfos = dirInfos; newBundleInf.Write(writer); if ((Header.FileStreamHeader.Flags & AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart) != 0) { writer.Align16(); } long assetDataPos = writer.Position; // write the updated directory infos for (int i = 0; i < dirInfos.Count; i++) { AssetBundleDirectoryInfo dirInfo = dirInfos[i]; long startPosition = writer.Position; long newOffset = startPosition - assetDataPos; ContentReplacerType replacerType = dirInfo.ReplacerType; if (replacerType == ContentReplacerType.AddOrModify) { dirInfo.Replacer.Write(writer, true); } else { DataReader.Position = dirInfo.Offset; DataReader.BaseStream.CopyToCompat(writer.BaseStream, dirInfo.DecompressedSize); } dirInfo.Offset = newOffset; dirInfo.DecompressedSize = writer.Position - startPosition; } // now that we know what the sizes are of the written files, let's go back and fix them long finalSize = writer.Position; long assetSize = finalSize - assetDataPos; // is it okay to have blocks of zero size in case we overshoot? long remainingAssetSize = assetSize; for (int i = 0; i < newBundleInf.BlockInfos.Length; i++) { AssetBundleBlockInfo blockInfo = newBundleInf.BlockInfos[i]; uint take = (uint)Math.Min(remainingAssetSize, uint.MaxValue); blockInfo.DecompressedSize = take; blockInfo.CompressedSize = take; remainingAssetSize -= take; } newBundleInf.DirectoryInfos = dirInfos; writer.Position = bundleInfPos; newBundleInf.Write(writer); uint infoSize = (uint)(assetDataPos - bundleInfPos); writer.Position = writeStart; AssetBundleHeader newBundleHeader = new AssetBundleHeader { Signature = Header.Signature, Version = Header.Version, GenerationVersion = Header.GenerationVersion, EngineVersion = Header.EngineVersion, FileStreamHeader = new AssetBundleFSHeader { TotalFileSize = finalSize, CompressedSize = infoSize, DecompressedSize = infoSize, // unset "info at end" flag and compression value Flags = Header.FileStreamHeader.Flags & ~AssetBundleFSHeaderFlags.BlockAndDirAtEnd & ~AssetBundleFSHeaderFlags.CompressionMask } }; newBundleHeader.Write(writer); } /// <summary> /// Unpack and write the uncompressed <see cref="AssetBundleFile"/> with the provided writer. <br/> /// You must write to a new file or stream when calling this method. /// </summary> /// <param name="writer">The writer to use.</param> public void Unpack(AssetsFileWriter writer) { if (Header == null) new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); if (Header.Signature != "UnityFS") new NotImplementedException("Non UnityFS bundles are not supported yet."); AssetBundleFSHeader fsHeader = Header.FileStreamHeader; AssetsFileReader reader = DataReader; AssetBundleBlockInfo[] blockInfos = BlockAndDirInfo.BlockInfos; List<AssetBundleDirectoryInfo> directoryInfos = BlockAndDirInfo.DirectoryInfos; AssetBundleHeader newBundleHeader = new AssetBundleHeader() { Signature = Header.Signature, Version = Header.Version, GenerationVersion = Header.GenerationVersion, EngineVersion = Header.EngineVersion, FileStreamHeader = new AssetBundleFSHeader { TotalFileSize = 0, CompressedSize = fsHeader.DecompressedSize, DecompressedSize = fsHeader.DecompressedSize, Flags = AssetBundleFSHeaderFlags.HasDirectoryInfo | ( (fsHeader.Flags & AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart) != AssetBundleFSHeaderFlags.None ? AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart : AssetBundleFSHeaderFlags.None ) } }; long fileSize = newBundleHeader.GetFileDataOffset(); for (int i = 0; i < blockInfos.Length; i++) { fileSize += blockInfos[i].DecompressedSize; } newBundleHeader.FileStreamHeader.TotalFileSize = fileSize; AssetBundleBlockAndDirInfo newBundleInf = new AssetBundleBlockAndDirInfo() { Hash = new Hash128(), BlockInfos = new AssetBundleBlockInfo[blockInfos.Length], DirectoryInfos = new List<AssetBundleDirectoryInfo>(directoryInfos.Count) }; // todo: we should just use one block here for (int i = 0; i < blockInfos.Length; i++) { newBundleInf.BlockInfos[i] = new AssetBundleBlockInfo() { CompressedSize = blockInfos[i].DecompressedSize, DecompressedSize = blockInfos[i].DecompressedSize, // Set compression to none Flags = (ushort)(blockInfos[i].Flags & (~0x3f)) }; } for (int i = 0; i < directoryInfos.Count; i++) { newBundleInf.DirectoryInfos.Add(new AssetBundleDirectoryInfo() { Offset = directoryInfos[i].Offset, DecompressedSize = directoryInfos[i].DecompressedSize, Flags = directoryInfos[i].Flags, Name = directoryInfos[i].Name }); } newBundleHeader.Write(writer); if (newBundleHeader.Version >= 7) { writer.Align16(); } newBundleInf.Write(writer); if ((newBundleHeader.FileStreamHeader.Flags & AssetBundleFSHeaderFlags.BlockInfoNeedPaddingAtStart) != 0) { writer.Align16(); } reader.Position = 0; if (DataIsCompressed) { for (int i = 0; i < newBundleInf.BlockInfos.Length; i++) { AssetBundleBlockInfo info = blockInfos[i]; switch (info.GetCompressionType()) { case 0: { reader.BaseStream.CopyToCompat(writer.BaseStream, info.CompressedSize); break; } case 1: { SevenZipHelper.StreamDecompress(reader.BaseStream, writer.BaseStream, info.CompressedSize, info.DecompressedSize); break; } case 2: case 3: { using (MemoryStream tempMs = new MemoryStream()) { reader.BaseStream.CopyToCompat(tempMs, info.CompressedSize); tempMs.Position = 0; using (Lz4DecoderStream decoder = new Lz4DecoderStream(tempMs)) { decoder.CopyToCompat(writer.BaseStream, info.DecompressedSize); } } break; } } } } else { for (int i = 0; i < newBundleInf.BlockInfos.Length; i++) { AssetBundleBlockInfo info = blockInfos[i]; reader.BaseStream.CopyToCompat(writer.BaseStream, info.DecompressedSize); } } } /// <summary> /// Pack and write the compressed <see cref="AssetBundleFile"/> with the provided writer. <br/> /// You must write to a new file or stream when calling this method. /// </summary> /// <param name="writer">The writer to use.</param> /// <param name="compType">The compression type to use. LZ4 compresses worse but faster, LZMA compresses better but slower.</param> /// <param name="blockDirAtEnd">Put block and directory list at end? This skips creating temporary files, but is not officially used.</param> /// <param name="progress">Optional callback for compression progress.</param> public void Pack(AssetsFileWriter writer, AssetBundleCompressionType compType, bool blockDirAtEnd = true, IAssetBundleCompressProgress progress = null) { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); if (Header.Signature != "UnityFS") throw new NotImplementedException("Non UnityFS bundles are not supported yet."); if (DataIsCompressed) throw new Exception("Bundles must be decompressed before writing."); Reader.Position = 0; writer.Position = 0; AssetBundleFSHeader newFsHeader = new AssetBundleFSHeader { TotalFileSize = 0, CompressedSize = 0, DecompressedSize = 0, Flags = AssetBundleFSHeaderFlags.LZ4HCCompressed | AssetBundleFSHeaderFlags.HasDirectoryInfo | (blockDirAtEnd ? AssetBundleFSHeaderFlags.BlockAndDirAtEnd : AssetBundleFSHeaderFlags.None) }; AssetBundleHeader newHeader = new AssetBundleHeader() { Signature = Header.Signature, Version = Header.Version, GenerationVersion = Header.GenerationVersion, EngineVersion = Header.EngineVersion, FileStreamHeader = newFsHeader }; AssetBundleBlockAndDirInfo newBlockAndDirList = new AssetBundleBlockAndDirInfo() { Hash = new Hash128(), BlockInfos = null, DirectoryInfos = BlockAndDirInfo.DirectoryInfos }; // write header now and overwrite it later long startPos = writer.Position; newHeader.Write(writer); if (newHeader.Version >= 7) writer.Align16(); int headerSize = (int)(writer.Position - startPos); long totalCompressedSize = 0; List<AssetBundleBlockInfo> newBlocks = new List<AssetBundleBlockInfo>(); List<Stream> newStreams = new List<Stream>(); // used if blockDirAtEnd == false Stream bundleDataStream = DataReader.BaseStream; bundleDataStream.Position = 0; int fileDataLength = (int)bundleDataStream.Length; switch (compType) { case AssetBundleCompressionType.LZMA: { // write to one large lzma block Stream writeStream; if (blockDirAtEnd) writeStream = writer.BaseStream; else writeStream = GetTempFileStream(); var lzmaProgress = new AssetBundleLZMAProgress(progress, bundleDataStream.Length); long writeStreamStart = writeStream.Position; SevenZipHelper.Compress(bundleDataStream, writeStream, lzmaProgress); uint writeStreamLength = (uint)(writeStream.Position - writeStreamStart); AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo() { CompressedSize = writeStreamLength, DecompressedSize = (uint)fileDataLength, Flags = 0x41 }; totalCompressedSize += blockInfo.CompressedSize; newBlocks.Add(blockInfo); if (!blockDirAtEnd) newStreams.Add(writeStream); if (progress != null) { progress.SetProgress(1.0f); } break; } case AssetBundleCompressionType.LZ4: case AssetBundleCompressionType.LZ4Fast: { // compress into 0x20000 blocks BinaryReader bundleDataReader = new BinaryReader(bundleDataStream); Stream writeStream; if (blockDirAtEnd) writeStream = writer.BaseStream; else writeStream = GetTempFileStream(); byte[] uncompressedBlock = bundleDataReader.ReadBytes(0x20000); while (uncompressedBlock.Length != 0) { byte[] compressedBlock = compType == AssetBundleCompressionType.LZ4Fast ? LZ4Codec.Encode32(uncompressedBlock, 0, uncompressedBlock.Length) : LZ4Codec.Encode32HC(uncompressedBlock, 0, uncompressedBlock.Length); if (progress != null) { progress.SetProgress((float)bundleDataReader.BaseStream.Position / bundleDataReader.BaseStream.Length); } if (compressedBlock.Length > uncompressedBlock.Length) { writeStream.Write(uncompressedBlock, 0, uncompressedBlock.Length); AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo() { CompressedSize = (uint)uncompressedBlock.Length, DecompressedSize = (uint)uncompressedBlock.Length, Flags = 0x00 }; totalCompressedSize += blockInfo.CompressedSize; newBlocks.Add(blockInfo); } else { writeStream.Write(compressedBlock, 0, compressedBlock.Length); AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo() { CompressedSize = (uint)compressedBlock.Length, DecompressedSize = (uint)uncompressedBlock.Length, Flags = 0x03 }; totalCompressedSize += blockInfo.CompressedSize; newBlocks.Add(blockInfo); } uncompressedBlock = bundleDataReader.ReadBytes(0x20000); } if (!blockDirAtEnd) newStreams.Add(writeStream); if (progress != null) { progress.SetProgress(1.0f); } break; } case AssetBundleCompressionType.None: { AssetBundleBlockInfo blockInfo = new AssetBundleBlockInfo() { CompressedSize = (uint)fileDataLength, DecompressedSize = (uint)fileDataLength, Flags = 0x00 }; totalCompressedSize += blockInfo.CompressedSize; newBlocks.Add(blockInfo); if (blockDirAtEnd) bundleDataStream.CopyToCompat(writer.BaseStream); else newStreams.Add(bundleDataStream); break; } } newBlockAndDirList.BlockInfos = newBlocks.ToArray(); byte[] bundleInfoBytes; using (MemoryStream memStream = new MemoryStream()) { AssetsFileWriter infoWriter = new AssetsFileWriter(memStream); infoWriter.BigEndian = writer.BigEndian; newBlockAndDirList.Write(infoWriter); bundleInfoBytes = memStream.ToArray(); } // listing is usually lz4 even if the data blocks are lzma byte[] bundleInfoBytesCom = compType == AssetBundleCompressionType.LZ4Fast ? LZ4Codec.Encode32(bundleInfoBytes, 0, bundleInfoBytes.Length) : LZ4Codec.Encode32HC(bundleInfoBytes, 0, bundleInfoBytes.Length); long totalFileSize = headerSize + bundleInfoBytesCom.Length + totalCompressedSize; newFsHeader.TotalFileSize = totalFileSize; newFsHeader.DecompressedSize = (uint)bundleInfoBytes.Length; newFsHeader.CompressedSize = (uint)bundleInfoBytesCom.Length; if (!blockDirAtEnd) { writer.Write(bundleInfoBytesCom); foreach (Stream newStream in newStreams) { newStream.Position = 0; newStream.CopyToCompat(writer.BaseStream); newStream.Close(); } } else { writer.Write(bundleInfoBytesCom); } writer.Position = 0; newHeader.Write(writer); if (newHeader.Version >= 7) writer.Align16(); } private void UnpackInfoOnly() { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); MemoryStream blocksInfoStream; AssetsFileReader memReader; Reader.Position = Header.GetBundleInfoOffset(); if (Header.GetCompressionType() == 0) { BlockAndDirInfo = new AssetBundleBlockAndDirInfo(); BlockAndDirInfo.Read(Reader); } else { int compressedSize = (int)Header.FileStreamHeader.CompressedSize; int decompressedSize = (int)Header.FileStreamHeader.DecompressedSize; switch (Header.GetCompressionType()) { case 1: { using (MemoryStream mstream = new MemoryStream(Reader.ReadBytes(compressedSize))) { blocksInfoStream = new MemoryStream(); SevenZipHelper.StreamDecompress(mstream, blocksInfoStream, compressedSize, decompressedSize); } break; } case 2: case 3: { byte[] uncompressedBytes = new byte[Header.FileStreamHeader.DecompressedSize]; using (MemoryStream mstream = new MemoryStream(Reader.ReadBytes(compressedSize))) { var decoder = new Lz4DecoderStream(mstream); decoder.Read(uncompressedBytes, 0, (int)Header.FileStreamHeader.DecompressedSize); decoder.Dispose(); } blocksInfoStream = new MemoryStream(uncompressedBytes); break; } default: { blocksInfoStream = null; break; } } using (memReader = new AssetsFileReader(blocksInfoStream)) { memReader.Position = 0; memReader.BigEndian = Reader.BigEndian; BlockAndDirInfo = new AssetBundleBlockAndDirInfo(); BlockAndDirInfo.Read(memReader); } } // it hasn't been seen but it's possible we // find mixed lz4 and lzma. if so, that's bad news. switch (GetCompressionType()) { case AssetBundleCompressionType.None: { SegmentStream dataStream = new SegmentStream(Reader.BaseStream, Header.GetFileDataOffset()); DataReader = new AssetsFileReader(dataStream); DataIsCompressed = false; break; } case AssetBundleCompressionType.LZMA: { SegmentStream dataStream = new SegmentStream(Reader.BaseStream, Header.GetFileDataOffset()); DataReader = new AssetsFileReader(dataStream); DataIsCompressed = true; break; } case AssetBundleCompressionType.LZ4: { LZ4BlockStream dataStream = new LZ4BlockStream(Reader.BaseStream, Header.GetFileDataOffset(), BlockAndDirInfo.BlockInfos); DataReader = new AssetsFileReader(dataStream); DataIsCompressed = false; break; } } } /// <summary> /// Returns the main compression type the bundle uses (the first uncompressed block type). /// </summary> /// <returns>The compression type</returns> public AssetBundleCompressionType GetCompressionType() { AssetBundleBlockInfo[] blockInfos = BlockAndDirInfo.BlockInfos; for (int i = 0; i < blockInfos.Length; i++) { byte compType = blockInfos[i].GetCompressionType(); if (compType == 2 || compType == 3) { return AssetBundleCompressionType.LZ4; } else if (compType == 1) { return AssetBundleCompressionType.LZMA; } } return AssetBundleCompressionType.None; } /// <summary> /// Is the file at the index an <see cref="AssetsFile"/>? /// Note: this checks by reading the first bit of the file instead of reading the directory flag. /// </summary> /// <param name="index">Index of the file in the directory info list.</param> /// <returns>True if the file at the index is an <see cref="AssetsFile"/>.</returns> public bool IsAssetsFile(int index) { GetFileRange(index, out long offset, out long length); return AssetsFile.IsAssetsFile(DataReader, offset, length); } /// <summary> /// Returns the index of the file in the directory list with the given name. /// </summary> /// <param name="name">The name to search for.</param> /// <returns>The index of the file in the directory list or -1 if no file is found.</returns> public int GetFileIndex(string name) { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); for (int i = 0; i < BlockAndDirInfo.DirectoryInfos.Count; i++) { if (BlockAndDirInfo.DirectoryInfos[i].Name == name) return i; } return -1; } /// <summary> /// Returns the name of the file at the index in the directory list. /// </summary> /// <param name="index">The index to look at.</param> /// <returns>The name of the file in the directory list or null if the index is out of bounds.</returns> public string GetFileName(int index) { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); if (index < 0 || index >= BlockAndDirInfo.DirectoryInfos.Count) return null; return BlockAndDirInfo.DirectoryInfos[index].Name; } /// <summary> /// Returns the file range of a file. /// Use <see cref="DataReader"/> instead of <see cref="Reader"/> to read data. /// </summary> /// <param name="index">The index to look at.</param> /// <param name="offset">The offset in the data stream, or -1 if the index is out of bounds.</param> /// <param name="length">The length of the file, or 0 if the index is out of bounds.</param> public void GetFileRange(int index, out long offset, out long length) { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); if (index < 0 || index >= BlockAndDirInfo.DirectoryInfos.Count) { offset = -1; length = 0; return; } AssetBundleDirectoryInfo entry = BlockAndDirInfo.DirectoryInfos[index]; offset = entry.Offset; length = entry.DecompressedSize; } /// <summary> /// Returns a list of file names in the bundle. /// </summary> /// <returns>The file names in the bundle.</returns> public List<string> GetAllFileNames() { if (Header == null) throw new Exception("Header must be loaded! (Did you forget to call bundle.Read?)"); List<string> names = new List<string>(); List<AssetBundleDirectoryInfo> dirInfos = BlockAndDirInfo.DirectoryInfos; foreach (AssetBundleDirectoryInfo dirInfo in dirInfos) { names.Add(dirInfo.Name); } return names; } private FileStream GetTempFileStream() { string tempFilePath = Path.GetTempFileName(); FileStream tempFileStream = new FileStream(tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); return tempFileStream; } } public enum AssetBundleCompressionType { None, LZMA, LZ4, LZ4Fast } }
412
0.964341
1
0.964341
game-dev
MEDIA
0.331573
game-dev
0.978671
1
0.978671
FlintMC/FlintMC
3,463
mcapi/src/v1_15_2/java/net/flintmc/mcapi/v1_15_2/world/generator/flat/VersionedFlatWorldPresetRegistry.java
/* * FlintMC * Copyright (C) 2020-2021 LabyMedia GmbH and contributors * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package net.flintmc.mcapi.v1_15_2.world.generator.flat; import com.google.inject.Inject; import com.google.inject.Singleton; import net.flintmc.framework.inject.implement.Implement; import net.flintmc.mcapi.chat.builder.ComponentBuilder; import net.flintmc.mcapi.chat.component.ChatComponent; import net.flintmc.mcapi.items.ItemStack; import net.flintmc.mcapi.items.mapper.MinecraftItemMapper; import net.flintmc.mcapi.world.generator.WorldGeneratorMapper; import net.flintmc.mcapi.world.generator.flat.FlatWorldGeneratorSettings; import net.flintmc.mcapi.world.generator.flat.FlatWorldGeneratorSettingsSerializer; import net.flintmc.mcapi.world.generator.flat.presets.FlatWorldPreset; import net.flintmc.mcapi.world.generator.flat.presets.FlatWorldPresetRegistry; import net.flintmc.util.mappings.ClassMappingProvider; import net.minecraft.client.gui.screen.FlatPresetsScreen; import net.minecraft.world.gen.FlatGenerationSettings; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Singleton @Implement(FlatWorldPresetRegistry.class) public class VersionedFlatWorldPresetRegistry implements FlatWorldPresetRegistry { private final Collection<FlatWorldPreset> presets; @Inject private VersionedFlatWorldPresetRegistry( FlatWorldGeneratorSettingsSerializer serializer, ComponentBuilder.Factory componentBuilderFactory, MinecraftItemMapper itemMapper, FlatWorldPreset.Factory presetFactory, ClassMappingProvider mappingProvider) throws ReflectiveOperationException { this.presets = new ArrayList<>(); Object value = mappingProvider .get(FlatPresetsScreen.class.getName()) .getField("FLAT_WORLD_PRESETS") .getValue(null); List<?> list = (List<?>) value; for (Object o : list) { FlatPresetsLayerShadow layer = (FlatPresetsLayerShadow) o; ChatComponent displayName = componentBuilderFactory.text().text(layer.getName()).build(); ItemStack icon = itemMapper.fromMinecraft(layer.getIcon().getDefaultInstance()); FlatWorldGeneratorSettings settings = serializer.deserialize(layer.getGeneratorInfo()); this.addPreset(presetFactory.create(displayName, icon, settings)); } } /** * {@inheritDoc} */ @Override public Collection<FlatWorldPreset> getPresets() { return this.presets; } /** * {@inheritDoc} */ @Override public void addPreset(FlatWorldPreset preset) { this.presets.add(preset); } /** * {@inheritDoc} */ @Override public void removePreset(FlatWorldPreset preset) { this.presets.remove(preset); } }
412
0.673143
1
0.673143
game-dev
MEDIA
0.844648
game-dev
0.774246
1
0.774246
Lyall/FF7RemakeFix
8,815
src/SDK/EB0003_12_HelicopterTurks_MoveControl_AI_classes.hpp
#pragma once /* * SDK generated by Dumper-7 * * https://github.com/Encryqed/Dumper-7 */ // Package: EB0003_12_HelicopterTurks_MoveControl_AI #include "Basic.hpp" #include "Engine_structs.hpp" #include "CoreUObject_structs.hpp" #include "EndGame_structs.hpp" #include "EB0003_12_HelicopterTurks_Standard_AI_classes.hpp" namespace SDK { // BlueprintGeneratedClass EB0003_12_HelicopterTurks_MoveControl_AI.EB0003_12_HelicopterTurks_MoveControl_AI_C // 0x0138 (0x23F8 - 0x22C0) class AEB0003_12_HelicopterTurks_MoveControl_AI_C final : public AEB0003_12_HelicopterTurks_Standard_AI_C { public: struct FPointerToUberGraphFrame UberGraphFrame_EB0003_12_HelicopterTurks_MoveControl_AI_C; // 0x22C0(0x0008)(Transient, DuplicateTransient) class UEndAITimerComponent* StayTimer; // 0x22C8(0x0008)(BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor, HasGetValueTypeHash) class UEndBattleAIOverlapComponent* EndBattleAIOverlap_0; // 0x22D0(0x0008)(BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor, HasGetValueTypeHash) class UEndAITimerComponent* EndAITimer_0; // 0x22D8(0x0008)(BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor, HasGetValueTypeHash) class UEndAITimerComponent* EndAITimerSet_0; // 0x22E0(0x0008)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FVector centerPos_0; // 0x22E8(0x000C)(Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) bool Wait_0; // 0x22F4(0x0001)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor) uint8 Pad_22F5[0x3]; // 0x22F5(0x0003)(Fixing Size After Last Property [ Dumper-7 ]) class FName Situation; // 0x22F8(0x0008)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FEndBattleHelicopterSpec HeliStay; // 0x2300(0x0028)(Edit, BlueprintVisible, DisableEditOnInstance, NoDestructor) struct FEndBattleHelicopterSpec HeliMove; // 0x2328(0x0028)(Edit, BlueprintVisible, DisableEditOnInstance, NoDestructor) struct FEndBattleHelicopterSpec HeliAtk; // 0x2350(0x0028)(Edit, BlueprintVisible, DisableEditOnInstance, NoDestructor) TMap<class FName, int32> GoalPoint; // 0x2378(0x0050)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) struct FEndBattleHelicopterSpec NewVar_0_0; // 0x23C8(0x0028)(Edit, BlueprintVisible, DisableEditOnInstance, NoDestructor) bool FinReserve; // 0x23F0(0x0001)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor) bool FinFix; // 0x23F1(0x0001)(Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor) public: void ExecuteUbergraph_EB0003_12_HelicopterTurks_MoveControl_AI(int32 EntryPoint); void OnEndCutScene(const class FName& CutsceneID); void OnMetaMessageAboutCharacter(class AEndCharacter* InChara, const class FString& InMessage); void OnFirstUpdate(EEndAiBattleRole InRole, int32 InStep); void OnMotionMessage(class FName InMotionName, class FName InName, int32 InIntValue, float InFloatValue); void OnTakeDamage(int32 Damage, class AEndCharacter* InChara, class FName InName, EEndBattleAbilityCommandType InCommandType, bool InBind, bool InGuard, bool InDodge, class FName InBoneName, bool InAttributeWeak, class FName InDmgSrcID, EEndBattleAttributeType InDmgSrcAttribute, float justHitRotYaw, const struct FVector& hitPosition, bool InHeal, bool InCounter, const struct FEndDataTableBattleDamageSource& dataTableBattleDamageSource, bool useAbilityUCPC); void CustomEvent_1(class AEndNavModifierVolume* InVolume); void CustomEvent(class AEndNavModifierVolume* InVolume); void OnKilled(int32 Damage, class AEndCharacter* InTarget, class FName InName, bool InBind); void OnCutSceneMessage(const class FName& Message); void ReceiveTick(float DeltaSeconds); void OnUpdate(EEndAiBattleRole InRole, int32 InStep, float DeltaTime); void InpActEvt_NumPadOne_K2Node_InputKeyEvent_1(const struct FKey& Key); void InpActEvt_NumPadTwo_K2Node_InputKeyEvent_0(const struct FKey& Key); void NextSituation(); void OnChangePhase(int32 InNew, int32 InOld); void OnEntryBattleScene(); void OnMetaMessage(const class FString& InMessage); void ReceiveBeginPlay(); void stay(class FName InName); void UserConstructionScript(); public: static class UClass* StaticClass() { return StaticBPGeneratedClassImpl<"EB0003_12_HelicopterTurks_MoveControl_AI_C">(); } static class AEB0003_12_HelicopterTurks_MoveControl_AI_C* GetDefaultObj() { return GetDefaultObjImpl<AEB0003_12_HelicopterTurks_MoveControl_AI_C>(); } }; static_assert(alignof(AEB0003_12_HelicopterTurks_MoveControl_AI_C) == 0x000008, "Wrong alignment on AEB0003_12_HelicopterTurks_MoveControl_AI_C"); static_assert(sizeof(AEB0003_12_HelicopterTurks_MoveControl_AI_C) == 0x0023F8, "Wrong size on AEB0003_12_HelicopterTurks_MoveControl_AI_C"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, UberGraphFrame_EB0003_12_HelicopterTurks_MoveControl_AI_C) == 0x0022C0, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::UberGraphFrame_EB0003_12_HelicopterTurks_MoveControl_AI_C' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, StayTimer) == 0x0022C8, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::StayTimer' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, EndBattleAIOverlap_0) == 0x0022D0, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::EndBattleAIOverlap_0' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, EndAITimer_0) == 0x0022D8, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::EndAITimer_0' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, EndAITimerSet_0) == 0x0022E0, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::EndAITimerSet_0' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, centerPos_0) == 0x0022E8, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::centerPos_0' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, Wait_0) == 0x0022F4, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::Wait_0' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, Situation) == 0x0022F8, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::Situation' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, HeliStay) == 0x002300, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::HeliStay' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, HeliMove) == 0x002328, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::HeliMove' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, HeliAtk) == 0x002350, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::HeliAtk' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, GoalPoint) == 0x002378, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::GoalPoint' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, NewVar_0_0) == 0x0023C8, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::NewVar_0_0' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, FinReserve) == 0x0023F0, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::FinReserve' has a wrong offset!"); static_assert(offsetof(AEB0003_12_HelicopterTurks_MoveControl_AI_C, FinFix) == 0x0023F1, "Member 'AEB0003_12_HelicopterTurks_MoveControl_AI_C::FinFix' has a wrong offset!"); }
412
0.715546
1
0.715546
game-dev
MEDIA
0.986767
game-dev
0.94273
1
0.94273
OGSR/OGSR-Engine
6,967
ogsr_engine/xrGame/BlackGraviArtifact.cpp
/////////////////////////////////////////////////////////////// // BlackGraviArtifact.cpp // BlackGraviArtefact - гравитационный артефакт, // такой же как и обычный, но при получении хита /////////////////////////////////////////////////////////////// #include "stdafx.h" #include "BlackGraviArtifact.h" #include "PhysicsShell.h" #include "entity_alive.h" #include "ParticlesObject.h" #include "phmovementcontrol.h" #include "xrmessages.h" #include "physicsshellholder.h" #include "explosive.h" #include "../xr_3da/NET_Server_Trash/net_utils.h" #include "PHWorld.h" #include "CharacterPhysicsSupport.h" extern CPHWorld* ph_world; CBlackGraviArtefact::CBlackGraviArtefact(void) { m_fImpulseThreshold = 10.f; m_fRadius = 10.f; m_fStrikeImpulse = 50.f; m_bStrike = false; } CBlackGraviArtefact::~CBlackGraviArtefact(void) { m_GameObjectList.clear(); } void CBlackGraviArtefact::Load(LPCSTR section) { inherited::Load(section); m_fImpulseThreshold = pSettings->r_float(section, "impulse_threshold"); m_fRadius = pSettings->r_float(section, "radius"); m_fStrikeImpulse = pSettings->r_float(section, "strike_impulse"); m_sParticleName = pSettings->r_string(section, "particle"); } BOOL CBlackGraviArtefact::net_Spawn(CSE_Abstract* DC) { if (!inherited::net_Spawn(DC)) return FALSE; CParticlesObject* pStaticPG; pStaticPG = CParticlesObject::Create("anomaly\\galantine", FALSE); Fmatrix pos; // pos.rotateY(1.57); // pos.mulA(pos); pos.scale(0.7f, 0.7f, 0.7f); pos.translate_over(XFORM().c); Fvector vel; vel.set(0, 0, 0); pStaticPG->UpdateParent(pos, vel); pStaticPG->Play(); return TRUE; } struct SRP { const CPhysicsShellHolder* obj; SRP(const CPhysicsShellHolder* O) { obj = O; } bool operator()(CPhysicsShellHolder* O) const { return obj == O; } }; void CBlackGraviArtefact::net_Relcase(CObject* O) { inherited::net_Relcase(O); // for vector GAME_OBJECT_LIST_it I = std::remove_if(m_GameObjectList.begin(), m_GameObjectList.end(), SRP(smart_cast<CPhysicsShellHolder*>(O))); m_GameObjectList.erase(I, m_GameObjectList.end()); // for list // m_GameObjectList.remove_if(SRP(smart_cast<CPhysicsShellHolder*>(O))); } void CBlackGraviArtefact::UpdateCLChild() { VERIFY(!ph_world->Processing()); inherited::UpdateCLChild(); if (getVisible() && m_pPhysicsShell) { if (m_bStrike) { Fvector P; P.set(Position()); feel_touch_update(P, m_fRadius); GraviStrike(); CParticlesObject* pStaticPG; pStaticPG = CParticlesObject::Create(*m_sParticleName, TRUE); Fmatrix pos; pos.set(XFORM()); Fvector vel; // vel.sub(Position(),ps_Element(0).vPosition); // vel.div((Level().timeServer()-ps_Element(0).dwTime)/1000.f); vel.set(0, 0, 0); pStaticPG->UpdateParent(pos, vel); pStaticPG->Play(); m_bStrike = false; } } else if (H_Parent()) XFORM().set(H_Parent()->XFORM()); } // void CBlackGraviArtefact::Hit(float P, Fvector &dir, // CObject* who, s16 element, // Fvector position_in_object_space, // float impulse, // ALife::EHitType hit_type) void CBlackGraviArtefact::Hit(SHit* pHDS) { SHit HDS = *pHDS; if (HDS.impulse > m_fImpulseThreshold) { m_bStrike = true; //чтоб выстрел не повлиял на траекторию полета артефакта HDS.impulse = 0; } // inherited::Hit(P, dir, who, element, position_in_object_space, impulse, hit_type); inherited::Hit(&HDS); } void CBlackGraviArtefact::feel_touch_new(CObject* O) { CPhysicsShellHolder* pGameObject = smart_cast<CPhysicsShellHolder*>(O); CArtefact* pArtefact = smart_cast<CArtefact*>(O); if (pGameObject && !pArtefact) { m_GameObjectList.push_back(pGameObject); } } void CBlackGraviArtefact::feel_touch_delete(CObject* O) { CGameObject* pGameObject = static_cast<CGameObject*>(O); CArtefact* pArtefact = smart_cast<CArtefact*>(O); if (pGameObject && !pArtefact) { m_GameObjectList.erase(std::find(m_GameObjectList.begin(), m_GameObjectList.end(), pGameObject)); } } BOOL CBlackGraviArtefact::feel_touch_contact(CObject* O) { CGameObject* pGameObject = static_cast<CGameObject*>(O); if (pGameObject) return TRUE; else return FALSE; } void CBlackGraviArtefact::GraviStrike() { xr_list<s16> elements_list; xr_list<Fvector> bone_position_list; Fvector object_pos; Fvector strike_dir; rq_storage.r_clear(); for (GAME_OBJECT_LIST_it it = m_GameObjectList.begin(); m_GameObjectList.end() != it; ++it) { CPhysicsShellHolder* pGameObject = *it; if (pGameObject->Visual()) pGameObject->Center(object_pos); else object_pos.set(pGameObject->Position()); strike_dir.sub(object_pos, Position()); float distance = strike_dir.magnitude(); float impulse = 100.f * m_fStrikeImpulse * (1.f - (distance / m_fRadius) * (distance / m_fRadius)); if (impulse > .001f) { //? BOOL enabled = getEnabled(); //? setEnabled (FALSE); impulse *= CExplosive::ExplosionEffect(rq_storage, NULL, pGameObject, Position(), m_fRadius); //? setEnabled (enabled); } float hit_power; CEntityAlive* pEntityAlive = smart_cast<CEntityAlive*>(pGameObject); if (pGameObject->m_pPhysicsShell) hit_power = 0; else if (pEntityAlive && pEntityAlive->g_Alive() && pEntityAlive->character_physics_support()->movement()->CharacterExist()) hit_power = 0; else hit_power = impulse; if (impulse > .001f) { while (!elements_list.empty()) { s16 element = elements_list.front(); Fvector bone_pos = bone_position_list.front(); NET_Packet P; SHit HS; HS.GenHeader(GE_HIT, pGameObject->ID()); // u_EventGen (P,GE_HIT, pGameObject->ID()); HS.whoID = ID(); // P.w_u16 (ID()); HS.weaponID = ID(); // P.w_u16 (ID()); HS.dir = strike_dir; // P.w_dir (strike_dir); HS.power = hit_power; // P.w_float (hit_power); HS.boneID = element; // P.w_s16 (element); HS.p_in_bone_space = bone_pos; // P.w_vec3 (bone_pos); HS.impulse = impulse; // P.w_float (impulse); HS.hit_type = (ALife::eHitTypeWound); // P.w_u16 (u16(ALife::eHitTypeWound)); HS.Write_Packet(P); u_EventSend(P); elements_list.pop_front(); bone_position_list.pop_front(); } } } }
412
0.976585
1
0.976585
game-dev
MEDIA
0.950119
game-dev
0.956113
1
0.956113
shit-ware/IW4
436,040
maps/_utility.gsc
#include common_scripts\utility; #include animscripts\utility; #include maps\_utility_code; /* ============= ///ScriptDocBegin "Name: is_coop()" "Summary: returns true if co-op is in use" "Module: Utility" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_coop() { if ( IsSplitScreen() || ( GetDvar( "coop" ) == "1" ) ) { AssertEx( IsDefined( level.player2 ), "In co-op mode but level.player2 is undefined. IsSplitScreen=" + IsSplitScreen() + " coop dvar=" + GetDvar( "coop" ) ); return true; } return false; } /* ============= ///ScriptDocBegin "Name: is_coop_online()" "Summary: Returns true if co-op is in use and the game is online." "Module: Utility" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_coop_online() { if ( issplitscreen() ) return false; if ( !is_coop() ) return false; return true; } /* ============= ///ScriptDocBegin "Name: is_player_down( <player> )" "Summary: Returns true if a co-op player is in last stand mode." "Module: Entity" "CallOn: A player" "MandatoryArg: <player>: The player you want to check." "Example: return is_player_down( level.player );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_player_down( player ) { assertex( isdefined( player ) && isplayer( player ), "player_coop_is_down() requires a valid player to test." ); if ( !is_coop() ) return false; if ( !isdefined( player.laststand ) ) return false; return player.laststand; } /* ============= ///ScriptDocBegin "Name: is_player_down_and_out( <player> )" "Summary: Returns true if a co-op player is in last stand mode AND been knocked into "out" mode... where they have no weapon." "Module: Entity" "CallOn: A player" "MandatoryArg: <player>: " "Example: return is_player_down_and_out( leve.player );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_player_down_and_out( player ) { assertex( isdefined( player ) && isplayer( player ), "player_coop_is_down_and_out() requires a valid player to test." ); if ( !is_coop() ) return false; if ( !isdefined( player.down_part2_proc_ran ) ) return false; return player.down_part2_proc_ran; } /* ============= ///ScriptDocBegin "Name: clear_custom_eog_summary()" "Summary: Clears all dvars for custom end-of-game summary for special ops" "Module: Utility" "SPMP: singleplayer" ///ScriptDocEnd ============= */ clear_custom_eog_summary() { for ( i = 1; i < 7; i++ ) { SetDvar( "ui_eog_r" + i + "c1_player1", "" ); SetDvar( "ui_eog_r" + i + "c1_player2", "" ); } for ( i = 1; i < 7; i++ ) { SetDvar( "ui_eog_r" + i + "c2_player1", "" ); SetDvar( "ui_eog_r" + i + "c2_player2", "" ); } SetDvar( "ui_eog_success_heading_player1", "" ); SetDvar( "ui_eog_success_heading_player2", "" ); } /* ============= ///ScriptDocBegin "Name: set_custom_eog_summary( <int row>, <int col >, <string data> )" "Summary: Called on player to set custom end-of-game summary for special ops" "Module: Utility" "MandatoryArg: <int row>: Row number to set the data in. Currently row is between 1 to 6." "MandatoryArg: <int col>: Column number to set the data in. Currently column is between 1 to 2." "MandatoryArg: <string data>: Data to be set in string." "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_custom_eog_summary( row, col, data ) { AssertEx( IsDefined( self ) && IsPlayer( self ), "set_custom_eog_summary() Must be called on a Player entity!" ); AssertEx( IsDefined( level.eog_summary_callback ), "Setting custom eog display data when callback function is not set. level.ego_summary_callback function pointer is undefined." ); level.custom_eog_summary = true; r = Int( row ); c = Int( col ); AssertEx( r >= 1 && r <= 6, "Row: " + r + " is out of bound, row = 1->6." ); AssertEx( c >= 1 && c <= 2, "Column: " + c + " is out of bound, column = 1->2." ); eog_dvar = ""; if ( level.players.size > 1 ) { if ( self == level.player ) eog_dvar = "ui_eog_r" + r + "c" + c + "_player1"; else if ( self == level.player2 ) eog_dvar = "ui_eog_r" + r + "c" + c + "_player2"; else AssertEx( true, "set_custom_eog_summary() Must be called on a Player entity!" ); } else { eog_dvar = "ui_eog_r" + r + "c" + c + "_player1"; } SetDvar( eog_dvar, data ); } /* ============= ///ScriptDocBegin "Name: add_custom_eog_summary_line( <eog_title> , <eog_value> , <eog_line_override> )" "Summary: Compressed way to add a line to the eog summary. By default will add itself in the order it was added." "Module: Utility" "CallOn: A player" "MandatoryArg: <eog_title>: The title message to display in the left column." "MandatoryArg: <eog_value>: The value to display in the right column." "OptionalArg: <eog_line_override>: Optional value to override the line the summary is going to display on." "Example: add_custom_eog_summary_line( "@SPECIAL_OP_KILLS", player.kill_count );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_custom_eog_summary_line( eog_title, eog_value, eog_line_override ) { assertex( isdefined( eog_title ), "so_add_eog_summary_line() requires a valid eog_title." ); assertex( isdefined( eog_value ), "so_add_eog_summary_line() requires a valid eog_title." ); assertex( isdefined( self ) && isplayer( self ), "so_add_eog_summary_line() must be called on a player." ); if ( !isdefined( self.eog_line ) ) self.eog_line = 0; eog_line = undefined; if ( isdefined( eog_line_override ) ) { eog_line = eog_line_override; } else { self.eog_line++; eog_line = self.eog_line; } self set_custom_eog_summary( eog_line, 1, eog_title ); self set_custom_eog_summary( eog_line, 2, eog_value ); } /* ============= ///ScriptDocBegin "Name: add_custom_eog_summary_line_blank( <add_custom_eog_summary_line_blank> )" "Summary: Simple function that auto-advances the line that the EOG summary is drawing on. Useful to clearly show what the EOG summary is doing." "Module: Utility" "Example: add_custom_eog_summary_line_blank();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_custom_eog_summary_line_blank() { if ( !isdefined( self.eog_line ) ) self.eog_line = 0; self.eog_line++; } /* ============= ///ScriptDocBegin "Name: set_eog_success_heading( <string data> )" "Summary: Sets mission sucess custom heading end-of-game summary for special ops" "Module: Utility" "MandatoryArg: <string data>: Title to be set in string." "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_eog_success_heading( title ) { AssertEx( IsDefined( self ) && IsPlayer( self ), "set_custom_eog_summary() Must be called on a Player entity!" ); AssertEx( IsDefined( level.eog_summary_callback ), "Setting custom eog display data when callback function is not set. level.ego_summary_callback function pointer is undefined." ); level.custom_eog_summary = true; eog_dvar = ""; if ( level.players.size > 1 ) { if ( self == level.player ) eog_dvar = "ui_eog_success_heading_player1"; else if ( self == level.player2 ) eog_dvar = "ui_eog_success_heading_player2"; else AssertEx( true, "set_eog_success_heading() Must be called on a Player entity!" ); } else { eog_dvar = "ui_eog_success_heading_player1"; } SetDvar( eog_dvar, title ); } /* ============= ///ScriptDocBegin "Name: is_specialop()" "Summary: returns true if map is in Special Op mode." "Module: Utility" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_specialop() { return GetDvar( "specialops" ) == "1"; } /* ============= ///ScriptDocBegin "Name: convert_to_time_string( <timer>, <show_tenths> )" "Summary: Takes a number and returns a string in Minutes:Seconds format." "Module: Utility" "MandatoryArg: <timer>: The number you want to convert." "MandatoryArg: <show_tenths>: Option to add an additional .0 to the end of the timer." "Example: time_string = convert_to_time_string( time_value );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ convert_to_time_string( timer, show_tenths ) { string = ""; if ( timer < 0 ) string += "-"; timer_clipped = timer * 100; timer_clipped = int( timer_clipped ); timer_clipped = abs( timer_clipped ); minutes = timer_clipped / 6000; minutes = int( minutes ); string += minutes; seconds = timer_clipped / 100; seconds = int( seconds ); seconds -= minutes * 60; if ( seconds < 10 ) string += ":0" + seconds; else string += ":" + seconds; if ( IsDefined( show_tenths ) && show_tenths ) { tenths = timer_clipped; tenths -= minutes * 6000; tenths -= seconds * 100; tenths = int( tenths ); if ( tenths < 10 ) string += ".0" + tenths; else string += "." + tenths; } return string; } /* ============= ///ScriptDocBegin "Name: set_vision_set( <visionset> , <transition_time> )" "Summary: Sets the vision set over time" "Module: Utility" "MandatoryArg: <visionset>: Visionset file to use" "OptionalArg: <transition_time>: Time to transition to the new vision set. Defaults to 1 second." "Example: set_vision_set( "blackout_darkness", 0.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_vision_set( visionset, transition_time ) { if ( init_vision_set( visionset ) ) return; if ( !isdefined( transition_time ) ) transition_time = 1; //iprintlnbold( visionset ); VisionSetNaked( visionset, transition_time ); SetDvar( "vision_set_current", visionset ); } /* ============= ///ScriptDocBegin "Name: set_vision_set_player( <visionset> , <transition_time> )" "Summary: Sets the vision set over time for a specific player in coop" "Module: Utility" "MandatoryArg: <visionset>: Visionset file to use" "OptionalArg: <transition_time>: Time to transition to the new vision set. Defaults to 1 second." "Example: level.player2 set_vision_set_player( "blackout_darkness", 0.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_vision_set_player( visionset, transition_time ) { if ( init_vision_set( visionset ) ) return; Assert( IsDefined( self ) ); Assert( level != self ); if ( !isdefined( transition_time ) ) transition_time = 1; self VisionSetNakedForPlayer( visionset, transition_time ); } /* ============= ///ScriptDocBegin "Name: set_nvg_vision( <visionset> , <transition_time> )" "Summary: Sets the night vision set over time" "Module: Utility" "MandatoryArg: <visionset>: Visionset file to use" "OptionalArg: <transition_time>: Time to transition to the new vision set. Defaults to 1 second." "Example: set_nvg_vision( "blackout_darkness", 0.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_nvg_vision( visionset, transition_time ) { // init_vision_set( visionset ); if ( !isdefined( transition_time ) ) transition_time = 1; VisionSetNight( visionset, transition_time ); } /* ============= ///ScriptDocBegin "Name: sun_light_fade( <startSunColor>, <endSunColor>, <fTime> )" "Summary: Fade to a given sunlight RGB value over the specified time" "Module: Utility" "MandatoryArg: <startSunColor> : Starting RGB values (use whatever the current sun is set to)" "MandatoryArg: <endSunColor> : Target RGB values the sun colors should change to" "MandatoryArg: <fTime> : Time in seconds for the fade to occur" "Example: thread sun_light_fade( (.5,.8,.75), (3.5,3.5,3.5), 2 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ sun_light_fade( startSunColor, endSunColor, fTime ) { fTime = Int( fTime * 20 ); // determine difference btwn starting and target sun RGBs increment = []; for ( i = 0; i < 3; i++ ) increment[ i ] = ( startSunColor[ i ] - endSunColor[ i ] ) / fTime; // change gradually to new sun color over time newSunColor = []; for ( i = 0; i < fTime; i++ ) { wait( 0.05 ); for ( j = 0; j < 3; j++ ) newSunColor[ j ] = startSunColor[ j ] - ( increment[ j ] * i ); SetSunLight( newSunColor[ 0 ], newSunColor[ 1 ], newSunColor[ 2 ] ); } //set sunlight to new target values to account for rounding off decimal places SetSunLight( endSunColor[ 0 ], endSunColor[ 1 ], endSunColor[ 2 ] ); } /* ============= ///ScriptDocBegin "Name: ent_flag_wait( <flagname> )" "Summary: Waits until the specified flag is set on self. Even handles some default flags for ai such as 'goal' and 'damage'" "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to wait on" "Example: enemy ent_flag_wait( "goal" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_wait( msg ) { AssertEx( ( !IsSentient( self ) && IsDefined( self ) ) || IsAlive( self ), "Attempt to check a flag on entity that is not alive or removed" ); while ( IsDefined( self ) && !self.ent_flag[ msg ] ) self waittill( msg ); } /* ============= ///ScriptDocBegin "Name: ent_flag_wait_either( <flagname1> , <flagname2> )" "Summary: Waits until either of the the specified flags are set on self. Even handles some default flags for ai such as 'goal' and 'damage'" "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname1> : name of one flag to wait on" "MandatoryArg: <flagname2> : name of the other flag to wait on" "Example: enemy ent_flag_wait( "goal", "damage" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_wait_either( flag1, flag2 ) { AssertEx( ( !IsSentient( self ) && IsDefined( self ) ) || IsAlive( self ), "Attempt to check a flag on entity that is not alive or removed" ); while ( IsDefined( self ) ) { if ( ent_flag( flag1 ) ) return; if ( ent_flag( flag2 ) ) return; self waittill_either( flag1, flag2 ); } } /* ============= ///ScriptDocBegin "Name: ent_flag_wait_or_timeout( <flagname> , <timer> )" "Summary: Waits until either the flag gets set on self or the timer elapses. Even handles some default flags for ai such as 'goal' and 'damage'" "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname1: Name of one flag to wait on" "MandatoryArg: <timer> : Amount of time to wait before continuing regardless of flag." "Example: ent_flag_wait_or_timeout( "time_to_go", 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_wait_or_timeout( flagname, timer ) { AssertEx( ( !IsSentient( self ) && IsDefined( self ) ) || IsAlive( self ), "Attempt to check a flag on entity that is not alive or removed" ); start_time = GetTime(); while ( IsDefined( self ) ) { if ( self.ent_flag[ flagname ] ) break; if ( GetTime() >= start_time + timer * 1000 ) break; self ent_wait_for_flag_or_time_elapses( flagname, timer ); } } /* ============= ///ScriptDocBegin "Name: ent_flag_waitopen( <msg> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_waitopen( msg ) { AssertEx( ( !IsSentient( self ) && IsDefined( self ) ) || IsAlive( self ), "Attempt to check a flag on entity that is not alive or removed" ); while ( IsDefined( self ) && self.ent_flag[ msg ] ) self waittill( msg ); } ent_flag_assert( msg ) { AssertEx( !self ent_flag( msg ), "Flag " + msg + " set too soon on entity" ); } /* ============= ///ScriptDocBegin "Name: ent_flag_waitopen_either( <flagname1> , <flagname2> )" "Summary: Waits until either of the the specified flags are open on self. Even handles some default flags for ai such as 'goal' and 'damage'" "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname1> : name of one flag to waitopen on" "MandatoryArg: <flagname2> : name of the other flag to waitopen on" "Example: enemy ent_flag_waitopen_either( "goal", "damage" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_waitopen_either( flag1, flag2 ) { AssertEx( ( !IsSentient( self ) && IsDefined( self ) ) || IsAlive( self ), "Attempt to check a flag on entity that is not alive or removed" ); while ( IsDefined( self ) ) { if ( !ent_flag( flag1 ) ) return; if ( !ent_flag( flag2 ) ) return; self waittill_either( flag1, flag2 ); } } /* ============= ///ScriptDocBegin "Name: ent_flag_init( <flagname> )" "Summary: Initialize a flag to be used. All flags must be initialized before using ent_flag_set or ent_flag_wait. Some flags for ai are set by default such as 'goal', 'death', and 'damage'" "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to create" "Example: enemy ent_flag_init( "hq_cleared" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_init( message ) { if ( !isDefined( self.ent_flag ) ) { self.ent_flag = []; self.ent_flags_lock = []; } /# if ( IsDefined( level.first_frame ) && level.first_frame == -1 ) AssertEx( !isDefined( self.ent_flag[ message ] ), "Attempt to reinitialize existing message: " + message + " on entity." ); #/ self.ent_flag[ message ] = false; /# self.ent_flags_lock[ message ] = false; #/ } /* ============= ///ScriptDocBegin "Name: ent_flag_exist( <flagname> )" "Summary: checks to see if a flag exists" "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to check" "Example: if( enemy ent_flag_exist( "hq_cleared" ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_exist( message ) { if ( IsDefined( self.ent_flag ) && IsDefined( self.ent_flag[ message ] ) ) return true; return false; } /* ============= ///ScriptDocBegin "Name: ent_flag_set_delayed( <flagname> , <delay> )" "Summary: Sets the specified flag after waiting the delay time on self, all scripts using ent_flag_wait on self will now continue." "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to set" "MandatoryArg: <delay> : time to wait before setting the flag" "Example: entity flag_set_delayed( "hq_cleared", 2.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_set_delayed( message, delay ) { self endon( "death" ); wait( delay ); self ent_flag_set( message ); } /* ============= ///ScriptDocBegin "Name: ent_flag_set( <flagname> )" "Summary: Sets the specified flag on self, all scripts using ent_flag_wait on self will now continue." "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to set" "Example: enemy ent_flag_set( "hq_cleared" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_set( message ) { /# AssertEx( IsDefined( self ), "Attempt to set a flag on entity that is not defined" ); AssertEx( IsDefined( self.ent_flag[ message ] ), "Attempt to set a flag before calling flag_init: " + message + " on entity." ); Assert( self.ent_flag[ message ] == self.ent_flags_lock[ message ] ); self.ent_flags_lock[ message ] = true; #/ self.ent_flag[ message ] = true; self notify( message ); } /* ============= ///ScriptDocBegin "Name: ent_flag_clear( <flagname> )" "Summary: Clears the specified flag on self." "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to clear" "Example: enemy ent_flag_clear( "hq_cleared" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_clear( message ) { /# AssertEx( IsDefined( self ), "Attempt to clear a flag on entity that is not defined" ); AssertEx( IsDefined( self.ent_flag[ message ] ), "Attempt to set a flag before calling flag_init: " + message + " on entity." ); Assert( self.ent_flag[ message ] == self.ent_flags_lock[ message ] ); self.ent_flags_lock[ message ] = false; #/ //do this check so we don't unneccessarily send a notify if ( self.ent_flag[ message ] ) { self.ent_flag[ message ] = false; self notify( message ); } } /* ============= ///ScriptDocBegin "Name: ent_flag_clear_delayed( <message> , <delay> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag_clear_delayed( message, delay ) { wait( delay ); self ent_flag_clear( message ); } /* ============= ///ScriptDocBegin "Name: ent_flag( <flagname> )" "Summary: Checks if the flag is set on self. Returns true or false." "Module: Flag" "CallOn: Any entity (script_origin, script_struct, ai, script_model, script_brushmodel, player)" "MandatoryArg: <flagname> : name of the flag to check" "Example: enemy ent_flag( "death" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ ent_flag( message ) { AssertEx( IsDefined( message ), "Tried to check flag but the flag was not defined." ); AssertEx( IsDefined( self.ent_flag[ message ] ), "Tried to check flag " + message + " but the flag was not initialized." ); return self.ent_flag[ message ]; } /* ============= ///ScriptDocBegin "Name: get_closest_to_player_view( <array>, <player>, <use_eye> )" "Summary: Returns array member closest to player's view" "Module: " "CallOn: Variable" "MandatoryArg: <array>: The array of items to test against" "OptionalArg: <player>: Player to test against. If undefined defaults to level.player" "OptionalArg: <use_eye>: Check from the player's eye point. If undefined uses the player's origin." "Example: enemy get_closest_to_player_view( enemies, level.player2, true );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_to_player_view( array, player, use_eye, min_dot ) { if ( !array.size ) return; if ( !isdefined( player ) ) player = level.player; if ( !isdefined( min_dot ) ) min_dot = -1; player_origin = player.origin; if ( IsDefined( use_eye ) && use_eye ) player_origin = player GetEye(); ent = undefined; player_angles = player GetPlayerAngles(); player_forward = AnglesToForward( player_angles ); dot = -1; foreach ( array_item in array ) { angles = VectorToAngles( array_item.origin - player_origin ); forward = AnglesToForward( angles ); newdot = VectorDot( player_forward, forward ); if ( newdot < dot ) continue; if ( newdot < min_dot ) continue; dot = newdot; ent = array_item; } return ent; } /* ============= ///ScriptDocBegin "Name: get_closest_index_to_player_view( <array>, <player>, <use_eye> )" "Summary: Returns array index of item closest to player's view" "Module: " "CallOn: Variable" "MandatoryArg: <array>: The array of items to test against" "OptionalArg: <player>: Player to test against. If undefined defaults to level.player" "OptionalArg: <use_eye>: Check from the player's eye point. If undefined uses the player's origin." "OptionalArg: <return_index>: If true, will return the index within the array rather than the actual array element." "Example: enemy get_closest_index_to_player_view( enemies, level.player2, true );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_index_to_player_view( array, player, use_eye ) { if ( !array.size ) return; if ( !isdefined( player ) ) player = level.player; player_origin = player.origin; if ( IsDefined( use_eye ) && use_eye ) player_origin = player GetEye(); index = undefined; player_angles = player GetPlayerAngles(); player_forward = AnglesToForward( player_angles ); dot = -1; for ( i = 0; i < array.size; i++ ) { angles = VectorToAngles( array[ i ].origin - player_origin ); forward = AnglesToForward( angles ); newdot = VectorDot( player_forward, forward ); if ( newdot < dot ) continue; dot = newdot; index = i; } return index; } flag_trigger_init( message, trigger, continuous ) { flag_init( message ); if ( !isDefined( continuous ) ) continuous = false; Assert( IsSubStr( trigger.classname, "trigger" ) ); trigger thread _flag_wait_trigger( message, continuous ); return trigger; } flag_triggers_init( message, triggers, all ) { flag_init( message ); if ( !isDefined( all ) ) all = false; for ( index = 0; index < triggers.size; index++ ) { Assert( IsSubStr( triggers[ index ].classname, "trigger" ) ); triggers[ index ] thread _flag_wait_trigger( message, false ); } return triggers; } /* ============= ///ScriptDocBegin "Name: flag_set_delayed( <flagname> , <delay> )" "Summary: Sets the specified flag after waiting the delay time, all scripts using flag_wait will now continue." "Module: Flag" "CallOn: " "MandatoryArg: <flagname> : name of the flag to set" "MandatoryArg: <delay> : time to wait before setting the flag" "Example: flag_set_delayed( "hq_cleared", 2.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ flag_set_delayed( message, delay ) { wait( delay ); flag_set( message ); } /* ============= ///ScriptDocBegin "Name: flag_clear_delayed( <flagname> , <delay> )" "Summary: Clears the specified flag after waiting the delay time, all scripts using flag_waitopen will now continue." "Module: Flag" "CallOn: " "MandatoryArg: <flagname> : name of the flag to clear" "MandatoryArg: <delay> : time to wait before clearing the flag" "Example: flag_clear_delayed( "hq_cleared", 2.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ flag_clear_delayed( message, delay ) { wait( delay ); flag_clear( message ); } _flag_wait_trigger( message, continuous ) { self endon( "death" ); for ( ;; ) { self waittill( "trigger", other ); flag_set( message ); if ( !continuous ) return; while ( other IsTouching( self ) ) wait( 0.05 ); flag_clear( message ); } } level_end_save() { if ( arcadeMode() ) return; if ( level.MissionFailed ) return; if ( flag( "game_saving" ) ) return; for ( i = 0; i < level.players.size; i++ ) { player = level.players[ i ]; if ( !isAlive( player ) ) return; } flag_set( "game_saving" ); imagename = "levelshots / autosave / autosave_" + level.script + "end"; // string not found for AUTOSAVE_AUTOSAVE SaveGame( "levelend", &"AUTOSAVE_AUTOSAVE", imagename, true );// does not print "Checkpoint Reached" flag_clear( "game_saving" ); } /* ============= ///ScriptDocBegin "Name: add_extra_autosave_check( <name> , <func> , <msg> )" "Summary: Adds an extra autosave check that must pass for an autosave to happen" "Module: Utility" "CallOn: An entity" "MandatoryArg: <name>: identify the index, of this autosave check ( so you can overwrite it )" "MandatoryArg: <func>: function should return true for the check to pass" "MandatoryArg: <msg>: this is what will print to the console when this check fails" "Example: add_extra_autosave_check( "boat_check_trailing" , ::autosave_boat_check_trailing , "trailing too far behind the enemy boat." );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_extra_autosave_check( name, func, msg ) { level._extra_autosave_checks[ name ] = []; level._extra_autosave_checks[ name ][ "func" ] = func; level._extra_autosave_checks[ name ][ "msg" ] = msg; } /* ============= ///ScriptDocBegin "Name: remove_extra_autosave_check( <name> )" "Summary: removes the extra autosave game condtions added by add_extra_autosave_check" "Module: Utility" "CallOn: An entity" "MandatoryArg: <param1>: Name" "Example: add_extra_autosave_check( "boat_check_trailing" ); " "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_extra_autosave_check( name ) { level._extra_autosave_checks[ name ] = undefined; } /* ============= ///ScriptDocBegin "Name: autosave_stealth()" "Summary: autosave the game if it's 'safe' to do so in a stealth level, internally threaded and handles any 'dangerous' situations that we wouldn't want to save at during stealth gameplay" "Module: Autosave" "CallOn: " "Example: autosave_stealth();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_stealth() { thread autosave_by_name_thread( "autosave_stealth", 8, true ); } /* ============= ///ScriptDocBegin "Name: autosave_tactical()" "Summary: autosave the game if it's 'safe' during tactical gameplay...meaning don't autosave if the player has any current enemies or has thrown a grenade. ( internally threaded )" "Module: Autosave" "CallOn: " "Example: autosave_tactical();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_tactical() { autosave_tactical_setup(); thread autosave_tactical_proc(); } /* ============= ///ScriptDocBegin "Name: autosave_by_name( <savename> )" "Summary: autosave the game with the specified save name" "Module: Autosave" "CallOn: " "MandatoryArg: <savename> : name of the save file to create" "Example: thread autosave_by_name( "building2_cleared" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_by_name( name ) { thread autosave_by_name_thread( name ); } /* ============= ///ScriptDocBegin "Name: autosave_by_name_silent( <savename> )" "Summary: autosave the game with the specified save name without printing a checkpoint msg" "Module: Autosave" "CallOn: " "MandatoryArg: <savename> : name of the save file to create" "Example: thread autosave_by_name_silent( "building2_cleared" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_by_name_silent( name ) { thread autosave_by_name_thread( name, undefined, undefined, true ); } autosave_by_name_thread( name, timeout, doStealthChecks, suppress_hint ) { if ( !isDefined( level.curAutoSave ) ) level.curAutoSave = 1; // nate - sorry auto style guide makes this ugly.. fixing it is complicated and this doesn't hurt things imageName = "levelshots / autosave / autosave_" + level.script + level.curAutoSave; result = level maps\_autosave::tryAutoSave( level.curAutoSave, "autosave", imagename, timeout, doStealthChecks, suppress_hint ); if ( IsDefined( result ) && result ) level.curAutoSave++; } /* ============= ///ScriptDocBegin "Name: autosave_or_timeout( <name> , <timeout> )" "Summary: Autosaves with the specified name but times out if the time elapses" "Module: Autosave" "MandatoryArg: <name>: The name" "MandatoryArg: <timeout>: The timeout" "Example: autosave_or_timeout( "thename", 3.5 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_or_timeout( name, timeout ) { thread autosave_by_name_thread( name, timeout ); } /* ============= ///ScriptDocBegin "Name: debug_message( <message> , <origin>, <duration>, <entity> )" "Summary: Prints 3d debug text at the specified location for a duration of time." "Module: Debug" "MandatoryArg: <message>: String to print" "MandatoryArg: <origin>: Location of string ( x, y, z )" "OptionalArg: <duration>: Time to keep the string on screen. Defaults to 5 seconds." "OptionalArg: <entity>: Overrides any origin value so that message can print on a moving entity" "Example: debug_message( "I am the enemy", enemy.origin, 3.0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ debug_message( message, origin, duration, entity ) { if ( !isDefined( duration ) ) duration = 5; if ( IsDefined( entity ) ) { entity endon( "death" ); origin = entity.origin; } for ( time = 0; time < ( duration * 20 ); time++ ) { if ( !isdefined( entity ) ) Print3d( ( origin + ( 0, 0, 45 ) ), message, ( 0.48, 9.4, 0.76 ), 0.85 ); else Print3d( entity.origin, message, ( 0.48, 9.4, 0.76 ), 0.85 ); wait 0.05; } } /* ============= ///ScriptDocBegin "Name: debug_message_ai( <message>, <duration> )" "Summary: Prints 3d debug text at the ai's origin and follows the ai that passed the function." "Module: Debug" "CallOn: An AI" "MandatoryArg: <message>: String to print" "OptionalArg: <duration>: Time to keep the string on screen. Defaults to 5 seconds." "Example: debug_message_ai( "I am the enemy", 3.0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ debug_message_ai( message, duration ) { self notify( "debug_message_ai" ); self endon( "debug_message_ai" ); self endon( "death" ); if ( !isDefined( duration ) ) duration = 5; for ( time = 0; time < ( duration * 20 ); time++ ) { Print3d( ( self.origin + ( 0, 0, 45 ) ), message, ( 0.48, 9.4, 0.76 ), 0.85 ); wait 0.05; } } /* ============= ///ScriptDocBegin "Name: debug_message_clear( <message> , <origin>, <duration>, <extraEndon> )" "Summary: Prints 3d debug text at the specified location for a duration of time, but can be cleared before the normal time has passed if a notify occurs." "Module: Debug" "MandatoryArg: <message>: String to print" "MandatoryArg: <origin>: Location of string ( x, y, z )" "OptionalArg: <duration>: Time to keep the string on screen. Defaults to 5 seconds." "OptionalArg: <extraEndon>: Level notify string that will make this text go away before the time expires." "Example: debug_message( "I am the enemy", enemy.origin, 3.0, "enemy died" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ debug_message_clear( message, origin, duration, extraEndon ) { if ( IsDefined( extraEndon ) ) { level notify( message + extraEndon ); level endon( message + extraEndon ); } else { level notify( message ); level endon( message ); } if ( !isDefined( duration ) ) duration = 5; for ( time = 0; time < ( duration * 20 ); time++ ) { Print3d( ( origin + ( 0, 0, 45 ) ), message, ( 0.48, 9.4, 0.76 ), 0.85 ); wait 0.05; } } chain_off( chain ) { trigs = GetEntArray( "trigger_friendlychain", "classname" ); for ( i = 0; i < trigs.size; i++ ) if ( ( IsDefined( trigs[ i ].script_chain ) ) && ( trigs[ i ].script_chain == chain ) ) { if ( IsDefined( trigs[ i ].oldorigin ) ) trigs[ i ].origin = trigs[ i ].oldorigin; else trigs[ i ].oldorigin = trigs[ i ].origin; trigs[ i ].origin = trigs[ i ].origin + ( 0, 0, -5000 ); } } chain_on( chain ) { trigs = GetEntArray( "trigger_friendlychain", "classname" ); for ( i = 0; i < trigs.size; i++ ) if ( ( IsDefined( trigs[ i ].script_chain ) ) && ( trigs[ i ].script_chain == chain ) ) { if ( IsDefined( trigs[ i ].oldorigin ) ) trigs[ i ].origin = trigs[ i ].oldorigin; } } precache( model ) { ent = Spawn( "script_model", ( 0, 0, 0 ) ); ent.origin = level.player GetOrigin(); ent SetModel( model ); ent Delete(); } closerFunc( dist1, dist2 ) { return dist1 >= dist2; } fartherFunc( dist1, dist2 ) { return dist1 <= dist2; } /* ============= ///ScriptDocBegin "Name: getClosest( <org> , <array> , <dist> )" "Summary: Returns the closest entity in < array > to location < org > " "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of entities to check distance on" "OptionalArg: <maxdist> : Minimum distance to check" "Example: friendly = getClosest( level.player.origin, allies );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getClosest( org, array, maxdist ) { if ( !IsDefined( maxdist ) ) maxdist = 500000; // twice the size of the grid ent = undefined; foreach ( item in array ) { newdist = Distance( item.origin, org ); if ( newdist >= maxdist ) continue; maxdist = newdist; ent = item; } return ent; } /* ============= ///ScriptDocBegin "Name: getFarthest( <org> , <array> , <dist> )" "Summary: Returns the farthest entity in < array > to location < org > " "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be farthest from." "MandatoryArg: <array> : Array of entities to check distance on" "OptionalArg: <maxdist> : Maximum distance to check" "Example: target = getFarthest( level.player.origin, targets );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getFarthest( org, array, maxdist ) { if ( !IsDefined( maxdist ) ) maxdist = 500000; // twice the size of the grid dist = 0; ent = undefined; foreach ( item in array ) { newdist = Distance( item.origin, org ); if ( newdist <= dist || newdist >= maxdist ) continue; dist = newdist; ent = item; } return ent; } /* ============= ///ScriptDocBegin "Name: getClosestFx( <org> , <fxarray> , <dist> )" "Summary: Returns the closest fx struct created by createfx in < fxarray > to location < org > " "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of createfx structs to check distance on. These are obtained with getfxarraybyID( <fxid> )" "OptionalArg: <dist> : Minimum distance to check" "Example: fxstruct = getClosestFx( hallway_tv, fxarray );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getClosestFx( org, fxarray, dist ) { return compareSizesFx( org, fxarray, dist, ::closerFunc ); } /* ============= ///ScriptDocBegin "Name: get_closest_point( <origin> , <points> , <maxDist> )" "Summary: Returns the closest point from array < points > from location < origin > " "Module: Distance" "CallOn: " "MandatoryArg: <origin> : Origin to be closest to." "MandatoryArg: <points> : Array of points to check distance on" "OptionalArg: <maxDist> : Maximum distance to check" "Example: target = getFarthest( level.player.origin, targets );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_point( origin, points, maxDist ) { Assert( points.size ); closestPoint = points[ 0 ]; dist = Distance( origin, closestPoint ); for ( index = 0; index < points.size; index++ ) { testDist = Distance( origin, points[ index ] ); if ( testDist >= dist ) continue; dist = testDist; closestPoint = points[ index ]; } if ( !isDefined( maxDist ) || dist <= maxDist ) return closestPoint; return undefined; } /* ============= ///ScriptDocBegin "Name: get_farthest_ent( <origin> , <array> )" "Summary: Returns the farthest entity in <array> from location < origin > " "Module: Distance" "CallOn: " "MandatoryArg: <origin> : Origin to be farthest from." "MandatoryArg: <array> : Array of entities to choose from" "Example: dude = get_farthest_ent( level.player.origin, aFriendlies );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_farthest_ent( org, array ) { if ( array.size < 1 ) return; dist = Distance( array[ 0 ] GetOrigin(), org ); ent = array[ 0 ]; for ( i = 0; i < array.size; i++ ) { newdist = Distance( array[ i ] GetOrigin(), org ); if ( newdist < dist ) continue; dist = newdist; ent = array[ i ]; } return ent; } /* ============= ///ScriptDocBegin "Name: get_within_range( <org> , <array> , <dist> )" "Summary: Returns all elements from the array that are within DIST range to ORG." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of entities to check distance on" "OptionalArg: <dist> : Maximum distance to check" "Example: close_ai = get_within_range( level.player.origin, ai, 500 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_within_range( org, array, dist ) { guys = []; for ( i = 0; i < array.size; i++ ) { if ( Distance( array[ i ].origin, org ) <= dist ) guys[ guys.size ] = array[ i ]; } return guys; } /* ============= ///ScriptDocBegin "Name: get_outside_range( <org> , <array> , <dist> )" "Summary: Returns all elements from the array that are outside DIST range to ORG." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of entities to check distance on" "OptionalArg: <dist> : Maximum distance to check" "Example: close_ai = get_outside_range( level.player.origin, ai, 500 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_outside_range( org, array, dist ) { guys = []; for ( i = 0; i < array.size; i++ ) { if ( Distance( array[ i ].origin, org ) > dist ) guys[ guys.size ] = array[ i ]; } return guys; } /* ============= ///ScriptDocBegin "Name: get_closest_living( <org> , <array> , <dist> )" "Summary: Returns the closest living entity from the array from the origin" "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of entities to check distance on" "OptionalArg: <dist> : Maximum distance to check" "Example: kicker = get_closest_living( node.origin, ai );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_living( org, array, dist ) { if ( !isdefined( dist ) ) dist = 9999999; if ( array.size < 1 ) return; ent = undefined; for ( i = 0; i < array.size; i++ ) { if ( !isalive( array[ i ] ) ) continue; newdist = Distance( array[ i ].origin, org ); if ( newdist >= dist ) continue; dist = newdist; ent = array[ i ]; } return ent; } /* ============= ///ScriptDocBegin "Name: get_highest_dot( <start> , <end> , <array> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_highest_dot( start, end, array ) { if ( !array.size ) return; ent = undefined; angles = VectorToAngles( end - start ); dotforward = AnglesToForward( angles ); dot = -1; foreach ( member in array ) { angles = VectorToAngles( member.origin - start ); forward = AnglesToForward( angles ); newdot = VectorDot( dotforward, forward ); if ( newdot < dot ) continue; dot = newdot; ent = member; } return ent; } /* ============= ///ScriptDocBegin "Name: get_closest_index( <org> , <array> , <dist> )" "Summary: same as getClosest but returns the closest entity's array index instead of the actual entity." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of entities to check distance on." "OptionalArg: <dist> : Maximum distance to check" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_index( org, array, dist ) { if ( !isdefined( dist ) ) dist = 9999999; if ( array.size < 1 ) return; index = undefined; foreach ( i, ent in array ) { newdist = Distance( ent.origin, org ); if ( newdist >= dist ) continue; dist = newdist; index = i; } return index; } /* ============= ///ScriptDocBegin "Name: get_closest_exclude( <org> , <ents> , <excluders> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_exclude( org, ents, excluders ) { if ( !isdefined( ents ) ) return undefined; range = 0; if ( IsDefined( excluders ) && excluders.size ) { exclude = []; for ( i = 0; i < ents.size; i++ ) exclude[ i ] = false; for ( i = 0; i < ents.size; i++ ) for ( p = 0; p < excluders.size; p++ ) if ( ents[ i ] == excluders[ p ] ) exclude[ i ] = true; found_unexcluded = false; for ( i = 0; i < ents.size; i++ ) if ( ( !exclude[ i ] ) && ( IsDefined( ents[ i ] ) ) ) { found_unexcluded = true; range = Distance( org, ents[ i ].origin ); ent = i; i = ents.size + 1; } if ( !found_unexcluded ) return( undefined ); } else { for ( i = 0; i < ents.size; i++ ) if ( IsDefined( ents[ i ] ) ) { range = Distance( org, ents[ 0 ].origin ); ent = i; i = ents.size + 1; } } ent = undefined; for ( i = 0; i < ents.size; i++ ) if ( IsDefined( ents[ i ] ) ) { exclude = false; if ( IsDefined( excluders ) ) { for ( p = 0; p < excluders.size; p++ ) if ( ents[ i ] == excluders[ p ] ) exclude = true; } if ( !exclude ) { newrange = Distance( org, ents[ i ].origin ); if ( newrange <= range ) { range = newrange; ent = i; } } } if ( IsDefined( ent ) ) return ents[ ent ]; else return undefined; } /* ============= ///ScriptDocBegin "Name: get_closest_player( <org> )" "Summary: Returns the closest coop player to the specified origin." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "Example: player = get_closest_player( tank.origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_player( org ) { if ( level.players.size == 1 ) return level.player; player = getClosest( org, level.players ); return player; } /* ============= ///ScriptDocBegin "Name: get_closest_player_healthy( <org> )" "Summary: Returns the closest coop player that is not bleeding out (.coop_downed) to the specified origin." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "Example: player = get_closest_player_healthy( tank.origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_player_healthy( org ) { if ( level.players.size == 1 ) return level.player; healthyPlayers = []; foreach ( player in level.players ) { if ( player ent_flag( "coop_downed" ) ) continue; // Checking player.coop_downed is unreliable due to it being set in more than _coop.gsc (see dog_combat.gsc). // We need to go through everything and make the use of player.coop_downed and // ent_flag( "coop_downed" ) consistent and not maintain both. /* if ( IsDefined( player.coop_downed ) && ( player.coop_downed ) ) continue;*/ healthyPlayers[ healthyPlayers.size ] = player; } /# assertex( healthyPlayers.size > 0, "get_closest_player_healthy() was unable to find a healthy player. This should never be possible." ); #/ player = getClosest( org, healthyPlayers ); return player; } /* ============= ///ScriptDocBegin "Name: get_closest_ai( <org> , <team> )" "Summary: Returns the closest AI of the specified team to the specified origin." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <team> : Team to use. Can be "allies", "axis", or "both"." "Example: friendly = get_closest_ai( level.player.origin, "allies" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_ai( org, team, excluders ) { if ( IsDefined( team ) ) ents = GetAIArray( team ); else ents = GetAIArray(); if ( ents.size == 0 ) return undefined; if ( IsDefined( excluders ) ) { Assert( excluders.size > 0 ); ents = array_remove_array( ents, excluders ); } return getClosest( org, ents ); } /* ============= ///ScriptDocBegin "Name: get_array_of_farthest( <org> , <array> , <excluders> , <max>, <maxdist>, <mindist> )" "Summary: Returns an array of all the entities in < array > sorted in order of farthest to closest." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be farthest from." "MandatoryArg: <array> : Array of entities to check distance on." "OptionalArg: <excluders> : Array of entities to exclude from the check." "OptionalArg: <max> : Max size of the array to return" "OptionalArg: <maxdist> : Max distance from the origin to return acceptable entities" "OptionalArg: <mindist> : Min distance from the origin to return acceptable entities" "Example: allies_sort = get_array_of_closest( originFC1.origin, allies );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_array_of_farthest( org, array, excluders, max, maxdist, mindist ) { aArray = get_array_of_closest( org, array, excluders, max, maxdist, mindist ); aArray = array_reverse( aArray ); return aArray; } /* ============= ///ScriptDocBegin "Name: get_array_of_closest( <org> , <array> , <excluders> , <max>, <maxdist>, <mindist> )" "Summary: Returns an array of all the entities in < array > sorted in order of closest to farthest." "Module: Distance" "CallOn: " "MandatoryArg: <org> : Origin to be closest to." "MandatoryArg: <array> : Array of entities to check distance on." "OptionalArg: <excluders> : Array of entities to exclude from the check." "OptionalArg: <max> : Max size of the array to return" "OptionalArg: <maxdist> : Max distance from the origin to return acceptable entities" "OptionalArg: <mindist> : Min distance from the origin to return acceptable entities" "Example: allies_sort = get_array_of_closest( originFC1.origin, allies );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_array_of_closest( org, array, excluders, max, maxdist, mindist ) { // pass an array of entities to this function and it will return them in the order of closest // to the origin you pass, you can also set max to limit how many ents get returned if ( !isdefined( max ) ) max = array.size; if ( !isdefined( excluders ) ) excluders = []; maxdist2rd = undefined; if ( IsDefined( maxdist ) ) maxdist2rd = maxdist * maxdist; mindist2rd = 0; if ( IsDefined( mindist ) ) mindist2rd = mindist * mindist; // optimize the common case of a simple sort if ( excluders.size == 0 && max >= array.size && mindist2rd == 0 && !isdefined( maxdist2rd ) ) return SortByDistance( array, org ); newArray = []; foreach ( ent in array ) { excluded = false; foreach ( excluder in excluders ) { if ( ent == excluder ) { excluded = true; break; } } if ( excluded ) continue; dist2rd = DistanceSquared( org, ent.origin ); if ( IsDefined( maxdist2rd ) && dist2rd > maxdist2rd ) continue; if ( dist2rd < mindist2rd ) continue; newArray[ newArray.size ] = ent; } newArray = SortByDistance( newArray, org ); if ( max >= newArray.size ) return newArray; finalArray = []; for ( i = 0; i < max; i++ ) finalArray[ i ] = newArray[ i ]; return finalArray; } /* ============= ///ScriptDocBegin "Name: get_closest_ai_exclude( <org> , <team> , <excluders> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_ai_exclude( org, team, excluders ) { if ( IsDefined( team ) ) ents = GetAIArray( team ); else ents = GetAIArray(); if ( ents.size == 0 ) return undefined; return get_closest_exclude( org, ents, excluders ); } /* ============= ///ScriptDocBegin "Name: can_see_origin( <origin>, <test_characters> )" "Summary: Checks to see if the specified point is within the player's view." "Module: Sentient" "CallOn: An AI or player" "MandatoryArg: <origin>: Origin you wish to see whether the player or AI can see." "OptionalArg: <test_characters>: Set to determine whether the sight trace should check against characters." "Example: level.player can_see_origin( entity.origin, true );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ can_see_origin( origin, test_characters ) { AssertEx( IsDefined( origin ), "can_see_origin() requires a valid origin to be passed in." ); AssertEx( IsPlayer( self ) || IsAI( self ), "can_see_origin() can only be called on a player or AI." ); if ( !isdefined( test_characters ) ) test_characters = true; // if not in FOV, return false if ( !self point_in_fov( origin ) ) { return false; } // if in FOV but sight trace fails, return false if ( !SightTracePassed( self GetEye(), origin, test_characters, self ) ) { return false; } // if in FOV with successful trace, return true return true; } /* ============= ///ScriptDocBegin "Name: point_in_fov( <origin> )" "Summary: Checks to see if the point is within a standard player view FOV." "Module: Entity" "CallOn: An entity" "MandatoryArg: <origin>: The point to check if it is within view." "Example: level.player point_in_fov( weapon_respawn.origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ point_in_fov( origin ) { forward = AnglesToForward( self.angles ); normalVec = VectorNormalize( origin - self.origin ); dot = VectorDot( forward, normalVec ); return dot > 0.766;// fov = 80 } /* ============= ///ScriptDocBegin "Name: stop_magic_bullet_shield()" "Summary: Stops magic bullet shield on an AI, setting his health back to a normal value and making him vulnerable to death." "Module: AI" "CallOn: AI" "Example: friendly stop_magic_bullet_shield();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ stop_magic_bullet_shield() { self notify( "stop_magic_bullet_shield" ); AssertEx( IsDefined( self.magic_bullet_shield ) && self.magic_bullet_shield, "Tried to stop magic bullet shield on a guy without magic bulletshield" ); if ( IsAI( self ) ) self.attackeraccuracy = 1; self.magic_bullet_shield = undefined; self.damageShield = false; self notify( "internal_stop_magic_bullet_shield" ); } // For future projects we should distinguish between "death" and "deletion" // Since we currently do not, bulletshield has to be turned off before deleting characters, or you will get the 2nd assert below magic_bullet_death_detection() { /# self endon( "internal_stop_magic_bullet_shield" ); export = self.export; entnum = self GetEntNum(); self waittill( "death" ); if ( IsDefined( self ) ) AssertEx( 0, "Magic bullet shield guy with export " + export + " died some how." ); else AssertEx( 0, "Magic bullet shield guy with export " + export + " died, most likely deleted from spawning guys." ); export = export;// extra line so you can get this info in the debugger without a breakpoint. #/ } /* ============= ///ScriptDocBegin "Name: magic_bullet_shield( <no_death_detection> )" "Summary: Makes an AI invulnerable to death. When he gets shot, he is ignored by enemies for < time > seconds and his health is regenerated." "Module: AI" "CallOn: AI" "OptionalArg: <no_death_detection> : Set this to make the AI not script error on death, like if you want the guy to be deletable." "Example: friendly thread magic_bullet_shield();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ magic_bullet_shield( no_death_detection ) { if ( IsAI( self ) )// AI only { AssertEx( IsAlive( self ), "Tried to do magic_bullet_shield on a dead or undefined guy." ); AssertEx( !self.delayedDeath, "Tried to do magic_bullet_shield on a guy about to die." ); AssertEx( !isDefined( self.Melee ), "Trying to turn on magic_bullet_shield while melee in progress (might be about to die)." ); } else { self.health = 100000; } self endon( "internal_stop_magic_bullet_shield" ); AssertEx( !isdefined( self.magic_bullet_shield ), "Can't call magic bullet shield on a character twice. Use make_hero and remove_heroes_from_array so that you don't end up with shielded guys in your logic." ); if ( IsAI( self ) )// AI only self.attackeraccuracy = 0.1; /# if ( !isdefined( no_death_detection ) ) thread magic_bullet_death_detection(); else AssertEx( no_death_detection, "no_death_detection must be undefined or true" ); #/ self.magic_bullet_shield = true; self.damageShield = true; } /* ============= ///ScriptDocBegin "Name: disable_long_death( )" "Summary: Disables long death on Self" "Module: Utility" "CallOn: An enemy AI" "Example: level.zakhaev disable_long_death(0" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_long_death() { AssertEx( IsAlive( self ), "Tried to disable long death on a non living thing" ); self.a.disableLongDeath = true; } /* ============= ///ScriptDocBegin "Name: enable_long_death( )" "Summary: Enables long death on Self" "Module: Utility" "CallOn: An enemy AI" "Example: level.zakhaev enable_long_death(0" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_long_death() { AssertEx( IsAlive( self ), "Tried to enable long death on a non living thing" ); self.a.disableLongDeath = false; } /* ============= ///ScriptDocBegin "Name: enable_blood_pool( <enable_blood_pool> )" "Summary: enables blood pools on AI deaths( on by default )" "Module: AI" "CallOn: An AI" "Example: ai enable_blood_pool()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_blood_pool() { self.skipBloodPool = undefined; } /* ============= ///ScriptDocBegin "Name: disable_blood_pool( <enable_blood_pool> )" "Summary: disables blood pools on AI deaths( on by default )" "Module: AI" "CallOn: An AI" "Example: ai disable_blood_pool()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_blood_pool() { self.skipBloodPool = true; } /* ============= ///ScriptDocBegin "Name: deletable_magic_bullet_shield()" "Summary: A version of magic bullet shield that does not error if the AI dies. Useful for guys that can be deleted but you want them to have aspects of MBS." "Module: AI" "CallOn: AI" "Example: friendly thread magic_bullet_shield();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ deletable_magic_bullet_shield() { magic_bullet_shield( true ); } /* ============= ///ScriptDocBegin "Name: get_ignoreme( <get_ignoreme> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_ignoreme() { return self.ignoreme; } /* ============= ///ScriptDocBegin "Name: set_ignoreme( <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_ignoreme( val ) { AssertEx( IsSentient( self ), "Non ai tried to set ignoreme" ); self.ignoreme = val; } /* ============= ///ScriptDocBegin "Name: set_ignoreall( <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_ignoreall( val ) { AssertEx( IsSentient( self ), "Non ai tried to set ignoraell" ); self.ignoreall = val; } /* ============= ///ScriptDocBegin "Name: set_favoriteenemy( <enemy> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_favoriteenemy( enemy ) { self.favoriteenemy = enemy; } /* ============= ///ScriptDocBegin "Name: get_pacifist( <get_pacifist> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_pacifist() { return self.pacifist; } /* ============= ///ScriptDocBegin "Name: set_pacifist( <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_pacifist( val ) { AssertEx( IsSentient( self ), "Non ai tried to set pacifist" ); self.pacifist = val; } ignore_me_timer( time ) { self notify( "new_ignore_me_timer" ); self endon( "new_ignore_me_timer" ); self endon( "death" ); if ( !isdefined( self.ignore_me_timer_prev_value ) ) self.ignore_me_timer_prev_value = self.ignoreme; ai = GetAIArray( "bad_guys" ); foreach ( guy in ai ) { if ( !isalive( guy.enemy ) ) continue; if ( guy.enemy != self ) continue; guy ClearEnemy(); } self.ignoreme = true; wait( time ); self.ignoreme = self.ignore_me_timer_prev_value; self.ignore_me_timer_prev_value = undefined; } /* ============= ///ScriptDocBegin "Name: array_randomize( <array> )" "Summary: Randomizes the array and returns the new array." "Module: Array" "CallOn: " "MandatoryArg: <array> : Array to be randomized." "Example: roof_nodes = array_randomize( roof_nodes );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_randomize( array ) { for ( i = 0; i < array.size; i++ ) { j = RandomInt( array.size ); temp = array[ i ]; array[ i ] = array[ j ]; array[ j ] = temp; } return array; } /* ============= ///ScriptDocBegin "Name: array_reverse( <array> )" "Summary: Reverses the order of the array and returns the new array." "Module: Array" "CallOn: " "MandatoryArg: <array> : Array to be reversed." "Example: patrol_nodes = array_reverse( patrol_nodes );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_reverse( array ) { array2 = []; for ( i = array.size - 1; i >= 0; i-- ) array2[ array2.size ] = array[ i ]; return array2; } /* ============= ///ScriptDocBegin "Name: delete_exploder( <num> )" "Summary: deletes an exploder and its brushes forever." "Module: Level" "CallOn: Level" "MandatoryArg: <num>: number of the exploder that you want to delete" "Example: delete_exploder( 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ delete_exploder( num ) { num += ""; prof_begin( "delete_exploder" ); for ( i = 0; i < level.createFXent.size; i++ ) { ent = level.createFXent[ i ]; if ( !isdefined( ent ) ) continue; if ( ent.v[ "type" ] != "exploder" ) continue; // make the exploder actually removed the array instead? if ( !isdefined( ent.v[ "exploder" ] ) ) continue; if ( ent.v[ "exploder" ] + "" != num ) continue; if ( IsDefined( ent.model ) ) ent.model Delete(); } //ends trigger threads. level notify( "killexplodertridgers" + num ); prof_end( "delete_exploder" ); } /* ============= ///ScriptDocBegin "Name: hide_exploder_models( <num> )" "Summary: Hides the models for an exploder." "Module: Level" "CallOn: Level" "MandatoryArg: <num>: number of the exploder that you want to hide" "Example: hide_exploder_models( 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hide_exploder_models( num ) { num += ""; prof_begin( "hide_exploder" ); for ( i = 0; i < level.createFXent.size; i++ ) { ent = level.createFXent[ i ]; if ( !isdefined( ent ) ) continue; if ( ent.v[ "type" ] != "exploder" ) continue; // make the exploder actually removed the array instead? if ( !isdefined( ent.v[ "exploder" ] ) ) continue; if ( ent.v[ "exploder" ] + "" != num ) continue; if ( IsDefined( ent.model ) ) ent.model Hide(); } prof_end( "hide_exploder" ); } /* ============= ///ScriptDocBegin "Name: show_exploder_models( <num> )" "Summary: shows the models for an exploder." "Module: Level" "CallOn: Level" "MandatoryArg: <num>: number of the exploder that you want to hide" "Example: show_exploder_models( 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ show_exploder_models( num ) { num += ""; prof_begin( "hide_exploder" ); for ( i = 0; i < level.createFXent.size; i++ ) { ent = level.createFXent[ i ]; if ( !isdefined( ent ) ) continue; if ( ent.v[ "type" ] != "exploder" ) continue; // make the exploder actually removed the array instead? if ( !isdefined( ent.v[ "exploder" ] ) ) continue; if ( ent.v[ "exploder" ] + "" != num ) continue; if ( IsDefined( ent.model ) ) { //pre exploded geo. don't worry about deleted exploder geo.. if ( ! exploder_model_starts_hidden( ent.model ) && ! exploder_model_is_damaged_model( ent.model ) && !exploder_model_is_chunk( ent.model ) ) { ent.model Show(); } //exploded geo and should be shown if ( IsDefined( ent.brush_shown ) ) ent.model Show(); } } prof_end( "hide_exploder" ); } exploder_model_is_damaged_model( ent ) { return( IsDefined( ent.targetname ) ) && ( ent.targetname == "exploder" ); } exploder_model_starts_hidden( ent ) { return( ent.model == "fx" ) && ( ( !isdefined( ent.targetname ) ) || ( ent.targetname != "exploderchunk" ) ); } exploder_model_is_chunk( ent ) { return( IsDefined( ent.targetname ) ) && ( ent.targetname == "exploderchunk" ); } /* ============= ///ScriptDocBegin "Name: stop_exploder( <num> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ stop_exploder( num ) { num += ""; for ( i = 0; i < level.createFXent.size; i++ ) { ent = level.createFXent[ i ]; if ( !isdefined( ent ) ) continue; if ( ent.v[ "type" ] != "exploder" ) continue; // make the exploder actually removed the array instead? if ( !isdefined( ent.v[ "exploder" ] ) ) continue; if ( ent.v[ "exploder" ] + "" != num ) continue; if ( !isdefined( ent.looper ) ) continue; ent.looper Delete(); } } /* ============= ///ScriptDocBegin "Name: get_exploder_array( <msg> )" "Summary: Return an array of exploders" "Module: Utility" "MandatoryArg: <msg>: Exploder num/name" "Example: exploders = get_exploder_array( "boom" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_exploder_array( msg ) { msg += ""; array = []; foreach ( ent in level.createFXent ) { if ( ent.v[ "type" ] != "exploder" ) continue; // make the exploder actually removed the array instead? if ( !isdefined( ent.v[ "exploder" ] ) ) continue; if ( ent.v[ "exploder" ] + "" != msg ) continue; array[ array.size ] = ent; } return array; } flood_spawn( spawners ) { maps\_spawner::flood_spawner_scripted( spawners ); } /* ============= ///ScriptDocBegin "Name: set_ambient( <track> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_ambient( track ) { maps\_ambient::activateAmbient( track ); } /* ============= ///ScriptDocBegin "Name: force_crawling_death( <angle> , <num_crawls> , <array> , <nofallanim> )" "Summary: Force an AI to crawl" "Module: Utility" "CallOn: An AI" "MandatoryArg: <angle>: The angle to crawl" "MandatoryArg: <num_crawls>: How many times to crawl" "OptionalArg: <array>: Sets self.a.custom_crawling_death_array" "OptionalArg: <nofallanim>: Sets self.nofallanim" "Example: self force_crawling_death( self.angles[ 1 ], 2, level.scr_anim[ "crawl_death_1" ], 1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ force_crawling_death( angle, num_crawls, array, nofallanim ) { if ( !isdefined( num_crawls ) ) num_crawls = 4; self thread force_crawling_death_proc( angle, num_crawls, array, nofallanim ); } #using_animtree( "generic_human" ); override_crawl_death_anims() { if ( IsDefined( self.a.custom_crawling_death_array ) ) { self.a.array[ "crawl" ] = self.a.custom_crawling_death_array[ "crawl" ]; self.a.array[ "death" ] = self.a.custom_crawling_death_array[ "death" ]; self.a.crawl_fx_rate = self.a.custom_crawling_death_array[ "blood_fx_rate" ]; if( isdefined( self.a.custom_crawling_death_array[ "blood_fx" ] ) ) self.a.crawl_fx = self.a.custom_crawling_death_array[ "blood_fx" ]; } self.a.array[ "stand_2_crawl" ] = []; self.a.array[ "stand_2_crawl" ][ 0 ] = %dying_stand_2_crawl_v3; if ( IsDefined( self.nofallanim ) ) self.a.pose = "prone"; self OrientMode( "face angle", self.a.force_crawl_angle ); self.a.force_crawl_angle = undefined; } force_crawling_death_proc( angle, num_crawls, array, nofallanim ) { self.forceLongDeath = true; self.a.force_num_crawls = num_crawls; self.noragdoll = true; self.nofallanim = nofallanim; self.a.custom_crawling_death_array = array; self.crawlingPainAnimOverrideFunc = ::override_crawl_death_anims; self.maxhealth = 100000; self.health = 100000; self enable_long_death(); if ( !isdefined( nofallanim ) || nofallanim == false ) self.a.force_crawl_angle = angle + 181.02; else { self.a.force_crawl_angle = angle; self thread animscripts\shared::noteTrackPoseCrawl(); } } get_friendly_chain_node( chainstring ) { chain = undefined; trigger = GetEntArray( "trigger_friendlychain", "classname" ); for ( i = 0; i < trigger.size; i++ ) { if ( ( IsDefined( trigger[ i ].script_chain ) ) && ( trigger[ i ].script_chain == chainstring ) ) { chain = trigger[ i ]; break; } } if ( !isdefined( chain ) ) { /# error( "Tried to get chain " + chainstring + " which does not exist with script_chain on a trigger." ); #/ return undefined; } node = GetNode( chain.target, "targetname" ); return node; } shock_ondeath() { Assert( IsPlayer( self ) ); PreCacheShellShock( "default" ); self waittill( "death" ); if ( IsDefined( self.specialDeath ) ) return; if ( GetDvar( "r_texturebits" ) == "16" ) return; self ShellShock( "default", 3 ); } /* ============= ///ScriptDocBegin "Name: delete_on_death_wait_sound( <ent> , <sounddone> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ delete_on_death_wait_sound( ent, sounddone ) { ent endon( "death" ); self waittill( "death" ); if ( IsDefined( ent ) ) { if ( ent IsWaitingOnSound() ) ent waittill( sounddone ); ent Delete(); } } is_dead_sentient() { return IsSentient( self ) && !isalive( self ); } /* ============= ///ScriptDocBegin "Name: play_sound_on_tag( <alias> , <tag>, <ends_on_death> )" "Summary: Play the specified sound alias on a tag of an entity" "Module: Sound" "CallOn: An entity" "MandatoryArg: <alias> : Sound alias to play" "OptionalArg: <tag> : Tag on the entity to play sound on. If no tag is specified the entities origin will be used." "OptionalArg: <ends_on_death> : The sound will be cut short if the entity dies. Defaults to false." "OptionalArg: <op_notify_string> : Optional notify string on sound done." "Example: vehicle thread play_sound_on_tag( "horn_honk", "tag_engine" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ play_sound_on_tag( alias, tag, ends_on_death, op_notify_string, radio_dialog ) { if ( is_dead_sentient() ) return; org = Spawn( "script_origin", ( 0, 0, 0 ) ); org endon( "death" ); thread delete_on_death_wait_sound( org, "sounddone" ); if ( IsDefined( tag ) ) org LinkTo( self, tag, ( 0, 0, 0 ), ( 0, 0, 0 ) ); else { org.origin = self.origin; org.angles = self.angles; org LinkTo( self ); } /# if ( IsDefined( level.player_radio_emitter ) && ( self == level.player_radio_emitter ) ) PrintLn( "**dialog alias playing radio: " + alias ); #/ org PlaySound( alias, "sounddone" ); if ( IsDefined( ends_on_death ) ) { AssertEx( ends_on_death, "ends_on_death must be true or undefined" ); if ( !isdefined( wait_for_sounddone_or_death( org ) ) ) org StopSounds(); // don't call StopSounds (redundantly) when the sound stopped since this can cut off sounds in SO for the non host wait( 0.05 );// stopsounds doesnt work if the org is deleted same frame } else { org waittill( "sounddone" ); } if ( IsDefined( op_notify_string ) ) self notify( op_notify_string ); org Delete(); } /* ============= ///ScriptDocBegin "Name: play_sound_on_tag_endon_death( <alias>, <tag> )" "Summary: Play the specified sound alias on a tag of an entity but gets cut short if the entity dies" "Module: Sound" "CallOn: An entity" "MandatoryArg: <alias> : Sound alias to play" "OptionalArg: <tag> : Tag on the entity to play sound on. If no tag is specified the entities origin will be used." "Example: vehicle thread play_sound_on_tag_endon_death( "horn_honk", "tag_engine" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ play_sound_on_tag_endon_death( alias, tag ) { play_sound_on_tag( alias, tag, true ); } /* ============= ///ScriptDocBegin "Name: play_sound_on_entity( <alias> , <op_notify_string> )" "Summary: Play the specified sound alias on an entity at it's origin" "Module: Sound" "CallOn: An entity" "MandatoryArg: <alias> : Sound alias to play" "OptionalArg: <op_notify_string> : Optional notify string on sound done." "Example: level.player play_sound_on_entity( "breathing_better" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ play_sound_on_entity( alias, op_notify_string ) { AssertEx( !isSpawner( self ), "Spawner tried to play a sound" ); play_sound_on_tag( alias, undefined, undefined, op_notify_string ); } /* ============= ///ScriptDocBegin "Name: play_loop_sound_on_tag( <alias> , <tag>, bStopSoundOnDeath )" "Summary: Play the specified looping sound alias on a tag of an entity" "Module: Sound" "CallOn: An entity" "MandatoryArg: <alias> : Sound alias to loop" "OptionalArg: <tag> : Tag on the entity to play sound on. If no tag is specified the entities origin will be used." "OptionalArg: <bStopSoundOnDeath> : Defaults to true. If true, will stop the looping sound when self dies" "Example: vehicle thread play_loop_sound_on_tag( "engine_belt_run", "tag_engine" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ play_loop_sound_on_tag( alias, tag, bStopSoundOnDeath ) { org = Spawn( "script_origin", ( 0, 0, 0 ) ); org endon( "death" ); if ( !isdefined( bStopSoundOnDeath ) ) bStopSoundOnDeath = true; if ( bStopSoundOnDeath ) thread delete_on_death( org ); if ( IsDefined( tag ) ) org LinkTo( self, tag, ( 0, 0, 0 ), ( 0, 0, 0 ) ); else { org.origin = self.origin; org.angles = self.angles; org LinkTo( self ); } // org endon( "death" ); org PlayLoopSound( alias ); // PrintLn( "playing loop sound ", alias, " on entity at origin ", self.origin, " at ORIGIN ", org.origin ); self waittill( "stop sound" + alias ); org StopLoopSound( alias ); org Delete(); } save_friendlies() { ai = GetAIArray( "allies" ); game_characters = 0; for ( i = 0; i < ai.size; i++ ) { if ( IsDefined( ai[ i ].script_friendname ) ) continue; // attachsize = // PrintLn( "attachSize = ", self GetAttachSize() ); game[ "character" + game_characters ] = ai[ i ] codescripts\character::save(); game_characters++; } game[ "total characters" ] = game_characters; } /* ============= ///ScriptDocBegin "Name: spawn_failed( <spawn> )" "Summary: Checks to see if the spawned AI spawned correctly or had errors. Also waits until all spawn initialization is complete. Returns true or false." "Module: AI" "CallOn: " "MandatoryArg: <spawn> : The actor that just spawned" "Example: spawn_failed( level.price );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ spawn_failed( spawn ) { if ( !isalive( spawn ) ) return true; if ( !isdefined( spawn.finished_spawning ) ) spawn waittill( "finished spawning" ); if ( IsAlive( spawn ) ) return false; return true; } spawn_setcharacter( data ) { codescripts\character::precache( data ); self waittill( "spawned", spawn ); if ( maps\_utility::spawn_failed( spawn ) ) return; PrintLn( "Size is ", data[ "attach" ].size ); spawn codescripts\character::new(); spawn codescripts\character::load( data ); } key_hint_print( message, binding ) { // Note that this will insert only the first bound key for the action IPrintLnBold( message, binding[ "key1" ] ); } view_tag( tag ) { self endon( "death" ); for ( ;; ) { maps\_debug::drawTag( tag ); wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: assign_animtree( <animname> )" "Summary: Assigns the level.scr_animtree for the given animname to self." "Module: _Anim" "OptionalArg: <animname> : You can optionally assign the animname for self at this juncture." "Example: model = assign_animtree( "whatever" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ assign_animtree( animname ) { if ( IsDefined( animname ) ) self.animname = animname; AssertEx( IsDefined( level.scr_animtree[ self.animname ] ), "There is no level.scr_animtree for animname " + self.animname ); self UseAnimTree( level.scr_animtree[ self.animname ] ); } /* ============= ///ScriptDocBegin "Name: assign_model( <assign_model> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ assign_model() { AssertEx( IsDefined( level.scr_model[ self.animname ] ), "There is no level.scr_model for animname " + self.animname ); if ( IsArray( level.scr_model[ self.animname ] ) ) { randIndex = RandomInt( level.scr_model[ self.animname ].size ); self SetModel( level.scr_model[ self.animname ][ randIndex ] ); } else self SetModel( level.scr_model[ self.animname ] ); } /* ============= ///ScriptDocBegin "Name: spawn_anim_model( <animname>, <origin> )" "Summary: Spawns a script model and gives it the animtree and model associated with that animname" "Module: _Anim" "MandatoryArg: <animname> : Name of the animname from this map_anim.gsc." "OptionalArg: <origin> : Optional origin." "Example: model = spawn_anim_model( "player_rappel" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ spawn_anim_model( animname, origin ) { if ( !isdefined( origin ) ) origin = ( 0, 0, 0 ); model = Spawn( "script_model", origin ); model.animname = animname; model assign_animtree(); model assign_model(); return model; } /* ============= ///ScriptDocBegin "Name: trigger_wait( <strName> , <strKey> )" "Summary: Waits until a trigger with the specified key / value is triggered" "Module: Trigger" "CallOn: " "MandatoryArg: <strName> : Name of the key on this trigger" "MandatoryArg: <strKey> : Key on the trigger to use, example: "targetname" or "script_noteworthy"" "Example: trigger_wait( "player_in_building1", "targetname" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ trigger_wait( strName, strKey ) { eTrigger = GetEnt( strName, strKey ); if ( !isdefined( eTrigger ) ) { AssertMsg( "trigger not found: " + strName + " key: " + strKey ); return; } eTrigger waittill( "trigger", eOther ); level notify( strName, eOther ); return eOther; } /* ============= ///ScriptDocBegin "Name: trigger_wait_targetname( <strName> )" "Summary: Waits until a trigger with the specified key / value is triggered" "Module: Trigger" "CallOn: " "MandatoryArg: <strKey> : targetname key to waitfor" "Example: trigger_wait_targetname( "player_in_building1" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ trigger_wait_targetname( strName ) { eTrigger = GetEnt( strName, "targetname" ); if ( !isdefined( eTrigger ) ) { AssertMsg( "trigger not found: " + strName + " targetname " ); return; } eTrigger waittill( "trigger", eOther ); level notify( strName, eOther ); return eOther; } /* ============= ///ScriptDocBegin "Name: set_flag_on_dead( <spawners> , <strFlag> )" "Summary: the function will set the flag <strFlag> after the actors from <spawners> have spawned and then died " "Module: AI" "CallOn: " "MandatoryArg: <spawners>: the array of spawners" "MandatoryArg: <strFlag>: the flag to set" "Example: set_flag_on_dead( spawners, "base_guys_dead" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_flag_on_dead( spawners, strFlag ) { thread set_flag_on_func_wait_proc( spawners, strFlag, ::waittill_dead, "set_flag_on_dead" ); } /* ============= ///ScriptDocBegin "Name: set_flag_on_dead_or_dying( <spawners> , <strFlag> )" "Summary: the function will set the flag <strFlag> after the actors from <spawners> have spawned and then are dead or dying ( long death )." "Module: AI" "CallOn: " "MandatoryArg: <spawners>: the array of spawners" "MandatoryArg: <strFlag>: the flag to set" "Example: set_flag_on_dead_or_dying( spawners, "base_guys_dead" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_flag_on_dead_or_dying( spawners, strFlag ) { thread set_flag_on_func_wait_proc( spawners, strFlag, ::waittill_dead_or_dying, "set_flag_on_dead_or_dying" ); } /* ============= ///ScriptDocBegin "Name: set_flag_on_spawned( <spawners> , <strFlag> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_flag_on_spawned( spawners, strFlag ) { thread set_flag_on_func_wait_proc( spawners, strFlag, ::empty_func, "set_flag_on_spawned" ); } empty_func( var ) { return; } set_flag_on_spawned_ai_proc( system, internal_flag ) { self waittill( "spawned", guy ); if ( maps\_utility::spawn_failed( guy ) ) return; system.ai[ system.ai.size ] = guy; self ent_flag_set( internal_flag ); } set_flag_on_func_wait_proc( spawners, strFlag, waitfunc, internal_flag ) { system = SpawnStruct(); system.ai = []; AssertEx( spawners.size, "spawners is empty" ); foreach ( key, spawn in spawners ) spawn ent_flag_init( internal_flag ); array_thread( spawners, ::set_flag_on_spawned_ai_proc, system, internal_flag ); foreach ( key, spawn in spawners ) spawn ent_flag_wait( internal_flag ); [[ waitfunc ]]( system.ai ); flag_set( strFlag ); } /* ============= ///ScriptDocBegin "Name: set_flag_on_trigger( <eTrigger> , <strFlag> )" "Summary: Calls flag_set to set the specified flag when the trigger is triggered" "Module: Trigger" "CallOn: " "MandatoryArg: <eTrigger> : trigger entity to use" "MandatoryArg: <strFlag> : name of the flag to set" "Example: set_flag_on_trigger( trig, "player_is_outside" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_flag_on_trigger( eTrigger, strFlag ) { if ( !flag( strFlag ) ) { eTrigger waittill( "trigger", eOther ); flag_set( strFlag ); return eOther; } } /* ============= ///ScriptDocBegin "Name: set_flag_on_targetname_trigger( <flag> )" "Summary: Sets the specified flag when a trigger with targetname < flag > is triggered." "Module: Trigger" "CallOn: " "MandatoryArg: <flag> : name of the flag to set, and also the targetname of the trigger to use" "Example: set_flag_on_targetname_trigger( "player_is_outside" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_flag_on_targetname_trigger( msg ) { Assert( IsDefined( level.flag[ msg ] ) ); if ( flag( msg ) ) return; trigger = GetEnt( msg, "targetname" ); trigger waittill( "trigger" ); flag_set( msg ); } /* ============= ///ScriptDocBegin "Name: is_in_array( <aeCollection> , <eFindee> )" "Summary: Returns true if < eFindee > is an entity in array < aeCollection > . False if it is not. " "Module: Array" "CallOn: " "MandatoryArg: <aeCollection> : array of entities to search through" "MandatoryArg: <eFindee> : entity to check if it's in the array" "Example: qBool = is_in_array( eTargets, vehicle1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_in_array( aeCollection, eFindee ) { for ( i = 0; i < aeCollection.size; i++ ) { if ( aeCollection[ i ] == eFindee ) return( true ); } return( false ); } /* ============= ///ScriptDocBegin "Name: waittill_dead( <guys> , <num> , <timeoutLength> )" "Summary: Waits until all the AI in array < guys > are dead." "Module: AI" "CallOn: " "MandatoryArg: <guys> : Array of actors to wait until dead" "OptionalArg: <num> : Number of guys that must die for this function to continue" "OptionalArg: <timeoutLength> : Number of seconds before this function times out and continues" "Example: waittill_dead( GetAIArray( "axis" ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_dead( guys, num, timeoutLength ) { // verify the living - ness of the ai /# allAlive = true; foreach ( member in guys ) { if ( IsAlive( member ) ) continue; allAlive = false; break; } AssertEx( allAlive, "Waittill_Dead was called with dead or removed AI in the array, meaning it will never pass." ); if ( !allAlive ) { newArray = []; foreach ( member in guys ) { if ( IsAlive( member ) ) newArray[ newArray.size ] = member; } guys = newArray; } #/ ent = SpawnStruct(); if ( IsDefined( timeoutLength ) ) { ent endon( "thread_timed_out" ); ent thread waittill_dead_timeout( timeoutLength ); } ent.count = guys.size; if ( IsDefined( num ) && num < ent.count ) ent.count = num; array_thread( guys, ::waittill_dead_thread, ent ); while ( ent.count > 0 ) ent waittill( "waittill_dead guy died" ); } /* ============= ///ScriptDocBegin "Name: waittill_dead_or_dying( <guys> , <num> , <timeoutLength> )" "Summary: Similar to waittill_dead(). Waits until all the AI in array < guys > are dead OR dying (long deaths)." "Module: AI" "CallOn: " "MandatoryArg: <guys> : Array of actors to wait until dead or dying" "OptionalArg: <num> : Number of guys that must die or be dying for this function to continue" "OptionalArg: <timeoutLength> : Number of seconds before this function times out and continues" "Example: waittill_dead_or_dying( GetAIArray( "axis" ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_dead_or_dying( guys, num, timeoutLength ) { // verify the living - ness and healthy - ness of the ai newArray = []; foreach ( member in guys ) { if ( IsAlive( member ) && !member.ignoreForFixedNodeSafeCheck ) newArray[ newArray.size ] = member; } guys = newArray; ent = SpawnStruct(); if ( IsDefined( timeoutLength ) ) { ent endon( "thread_timed_out" ); ent thread waittill_dead_timeout( timeoutLength ); } ent.count = guys.size; // optional override on count if ( IsDefined( num ) && num < ent.count ) ent.count = num; array_thread( guys, ::waittill_dead_or_dying_thread, ent ); while ( ent.count > 0 ) ent waittill( "waittill_dead_guy_dead_or_dying" ); } waittill_dead_thread( ent ) { self waittill( "death" ); ent.count--; ent notify( "waittill_dead guy died" ); } waittill_dead_or_dying_thread( ent ) { self waittill_either( "death", "pain_death" ); ent.count--; ent notify( "waittill_dead_guy_dead_or_dying" ); } waittill_dead_timeout( timeoutLength ) { wait( timeoutLength ); self notify( "thread_timed_out" ); } waittill_aigroupcleared( aigroup ) { while ( level._ai_group[ aigroup ].spawnercount || level._ai_group[ aigroup ].aicount ) wait( 0.25 ); } waittill_aigroupcount( aigroup, count ) { while ( level._ai_group[ aigroup ].spawnercount + level._ai_group[ aigroup ].aicount > count ) wait( 0.25 ); } get_ai_group_count( aigroup ) { return( level._ai_group[ aigroup ].spawnercount + level._ai_group[ aigroup ].aicount ); } get_ai_group_sentient_count( aigroup ) { return( level._ai_group[ aigroup ].aicount ); } get_ai_group_ai( aigroup ) { aiSet = []; for ( index = 0; index < level._ai_group[ aigroup ].ai.size; index++ ) { if ( !isAlive( level._ai_group[ aigroup ].ai[ index ] ) ) continue; aiSet[ aiSet.size ] = level._ai_group[ aigroup ].ai[ index ]; } return( aiSet ); } /* ============= ///ScriptDocBegin "Name: waittill_notetrack_or_damage( <notetrack> )" "Summary: Waits until the entity hits a certain notetrack or is damaged or killed" "Module: AI" "CallOn: An AI" "MandatoryArg: <notetrack> : the notetrack to wait for" "Example: self waittill_notetrack_or_damage( "bodyfall large" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_notetrack_or_damage( notetrack ) { self endon( "damage" ); self endon( "death" ); self waittillmatch( "single anim", notetrack ); } /* ============= ///ScriptDocBegin "Name: get_living_ai( <name> , <type> )" "Summary: Returns single spawned ai in the level of <name> and <type>. Error if used on more than one ai with same name and type " "Module: AI" "CallOn: " "MandatoryArg: <name> : the value of the targetname or script_noteworthy of the ai" "MandatoryArg: <type> : valid types are targetname and script_noteworthy" "Example: patroller = get_living_ai( "patrol", "script_noteworthy" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_living_ai( name, type ) { array = get_living_ai_array( name, type ); if ( array.size > 1 ) { AssertMsg( "get_living_ai used for more than one living ai of type " + type + " called " + name + "." ); return undefined; } return array[ 0 ]; } /* ============= ///ScriptDocBegin "Name: get_living_ai_array( <name> , <type> )" "Summary: Returns array of spawned ai in the level of <name> and <type> " "Module: AI" "CallOn: " "MandatoryArg: <name> : the value of the targetname or script_noteworthy of the ai" "MandatoryArg: <type> : valid types are targetname and script_noteworthy" "Example: patrollers = get_living_ai_array( "patrol", "script_noteworthy" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_living_ai_array( name, type ) { ai = GetAISpeciesArray( "all", "all" ); array = []; foreach ( actor in ai ) { if ( !isalive( actor ) ) continue; switch( type ) { case "targetname":{ if ( IsDefined( actor.targetname ) && actor.targetname == name ) array[ array.size ] = actor; }break; case "script_noteworthy":{ if ( IsDefined( actor.script_noteworthy ) && actor.script_noteworthy == name ) array[ array.size ] = actor; }break; } } return array; } /* ============= ///ScriptDocBegin "Name: get_vehicle( <name> , <type> )" "Summary: Returns the vehicle spawned from the SHIFT-V radient menu of <name> and <type> " "Module: Vehicle" "CallOn: " "MandatoryArg: <name> : the value of the targetname or script_noteworthy of the vehicle" "MandatoryArg: <type> : valid types are targetname and script_noteworthy" "Example: patrollers = get_vehicle( "heli_1", "script_noteworthy" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_vehicle( name, type ) { Assert( IsDefined( name ) ); Assert( IsDefined( type ) ); array = get_vehicle_array( name, type ); if ( !array.size ) return undefined; AssertEx( array.size == 1, "tried to get_vehicle() on vehicles with key-pair: " + name + "," + type ); return array[ 0 ]; } /* ============= ///ScriptDocBegin "Name: get_vehicle_array( <name> , <type> )" "Summary: Returns the vehicles spawned from the SHIFT-V radient menu of <name> and <type> " "Module: Vehicle" "CallOn: " "MandatoryArg: <name> : the value of the targetname or script_noteworthy of the vehicle" "MandatoryArg: <type> : valid types are targetname and script_noteworthy" "Example: helis = get_vehicle_array( "tower_helis", "script_noteworthy" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_vehicle_array( name, type ) { array = GetEntArray( name, type ); vehicle = []; merge_array = []; foreach ( object in array ) { if ( object.code_classname != "script_vehicle" ) continue; merge_array[ 0 ] = object; //since vehicles lose their targetname return the last vehicle spawned from the spawner. if ( IsSpawner( object ) ) { if ( IsDefined( object.last_spawned_vehicle ) ) { merge_array[ 0 ] = object.last_spawned_vehicle; vehicle = array_merge( vehicle, merge_array );// least tricky way for me to do this. } continue; } vehicle = array_merge( vehicle, merge_array );// least tricky way for me to do this. } return vehicle; } /* ============= ///ScriptDocBegin "Name: get_living_aispecies( <name> , <type>, <breed> )" "Summary: Returns single spawned ai in the level of <name> and <type>. Error if used on more than one ai with same name and type " "Module: AI" "CallOn: " "MandatoryArg: <name> : the value of the targetname or script_noteworthy of the ai" "MandatoryArg: <type> : valid types are targetname and script_noteworthy" "OptionalArg: <bread> : the breadof spieces, if none is given, defaults to 'all' " "Example: patroller = get_living_aispecies( "patrol", "script_noteworthy", "dog" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_living_aispecies( name, type, breed ) { array = get_living_ai_array( name, type, breed ); if ( array.size > 1 ) { AssertMsg( "get_living_aispecies used for more than one living ai of type " + type + " called " + name + "." ); return undefined; } return array[ 0 ]; } /* ============= ///ScriptDocBegin "Name: get_living_aispecies_array( <name> , <type>, <breed> )" "Summary: Returns array of spawned ai of any speices in the level of <name>, <type>, and <breed> " "Module: AI" "CallOn: " "MandatoryArg: <name> : the value of the targetname or script_noteworthy of the ai" "MandatoryArg: <type> : valid types are targetname and script_noteworthy" "OptionalArg: <bread> : the breadof spieces, if none is given, defaults to 'all' " "Example: patrollers = get_living_aispecies_array( "patrol", "script_noteworthy", "dog" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_living_aispecies_array( name, type, breed ) { if ( !isdefined( breed ) ) breed = "all"; ai = GetAISpeciesArray( "allies", breed ); ai = array_combine( ai, GetAISpeciesArray( "axis", breed ) ); array = []; for ( i = 0; i < ai.size; i++ ) { switch( type ) { case "targetname":{ if ( IsDefined( ai[ i ].targetname ) && ai[ i ].targetname == name ) array[ array.size ] = ai[ i ]; }break; case "script_noteworthy":{ if ( IsDefined( ai[ i ].script_noteworthy ) && ai[ i ].script_noteworthy == name ) array[ array.size ] = ai[ i ]; }break; } } return array; } // Creates an event based on this message if none exists, and sets it to true after the delay. gather_delay_proc( msg, delay ) { if ( IsDefined( level.gather_delay[ msg ] ) ) { if ( level.gather_delay[ msg ] ) { wait( 0.05 ); if ( IsAlive( self ) ) self notify( "gather_delay_finished" + msg + delay ); return; } level waittill( msg ); if ( IsAlive( self ) ) self notify( "gather_delay_finished" + msg + delay ); return; } level.gather_delay[ msg ] = false; wait( delay ); level.gather_delay[ msg ] = true; level notify( msg ); if ( IsAlive( self ) ) self notify( "gather_delay_finished" + msg + delay ); } gather_delay( msg, delay ) { thread gather_delay_proc( msg, delay ); self waittill( "gather_delay_finished" + msg + delay ); } set_environment( env ) { animscripts\utility::setEnv( env ); } death_waiter( notifyString ) { self waittill( "death" ); level notify( notifyString ); } getchar( num ) { if ( num == 0 ) return "0"; if ( num == 1 ) return "1"; if ( num == 2 ) return "2"; if ( num == 3 ) return "3"; if ( num == 4 ) return "4"; if ( num == 5 ) return "5"; if ( num == 6 ) return "6"; if ( num == 7 ) return "7"; if ( num == 8 ) return "8"; if ( num == 9 ) return "9"; } /* ============= ///ScriptDocBegin "Name: player_god_on()" "Summary: Puts the player in god mode. Player takes damage but will never die." "Module: Player" "CallOn: " "Example: thread player_god_on();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_god_on() { thread player_god_on_thread(); } player_god_on_thread() { self endon( "godoff" ); self.oldhealth = self.health; for ( ;; ) { self waittill( "damage" ); self.health = 10000; } } /* ============= ///ScriptDocBegin "Name: player_god_off()" "Summary: Remove god mode from player. Player will be vulnerable to death again." "Module: Player" "CallOn: " "Example: thread player_god_off();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_god_off() { self notify( "godoff" ); Assert( IsDefined( self.oldhealth ) ); self.health = self.oldhealth; } getlinks_array( array, linkMap )// don't pass stuff through as an array of struct.linkname[] but only linkMap[] { ents = []; for ( j = 0; j < array.size; j++ ) { node = array[ j ]; script_linkname = node.script_linkname; if ( !isdefined( script_linkname ) ) continue; if ( !isdefined( linkMap[ script_linkname ] ) ) continue; ents[ ents.size ] = node; } return ents; } // Adds only things that are new to the array. // Requires the arrays to be of node with script_linkname defined. /* ============= ///ScriptDocBegin "Name: array_merge_links( <array1> , <array2> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_merge_links( array1, array2 ) { if ( !array1.size ) return array2; if ( !array2.size ) return array1; linkMap = []; for ( i = 0; i < array1.size; i++ ) { node = array1[ i ]; linkMap[ node.script_linkName ] = true; } for ( i = 0; i < array2.size; i++ ) { node = array2[ i ]; if ( IsDefined( linkMap[ node.script_linkName ] ) ) continue; linkMap[ node.script_linkName ] = true; array1[ array1.size ] = node; } return array1; } /* ============= ///ScriptDocBegin "Name: array_merge( <array1> , <array2> )" "Summary: Combines the two arrays and returns the resulting array. Adds only things that are new to the array, no duplicates." "Module: Array" "CallOn: " "MandatoryArg: <array1> : first array" "MandatoryArg: <array2> : second array" "Example: combinedArray = array_merge( array1, array2 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_merge( array1, array2 )// adds only things that are new to the array { if ( array1.size == 0 ) return array2; if ( array2.size == 0 ) return array1; newarray = array1; foreach ( array2_ent in array2 ) { foundmatch = false; foreach ( array1_ent in array1 ) { if ( array1_ent == array2_ent ) { foundmatch = true; break; } } if ( foundmatch ) continue; else newarray[ newarray.size ] = array2_ent; } return newarray; } /* ============= ///ScriptDocBegin "Name: array_exclude( <array> , <arrayExclude> )" "Summary: Returns an array excluding all members of < arrayExclude > " "Module: Array" "CallOn: " "MandatoryArg: <array> : Array containing all items" "MandatoryArg: <arrayExclude> : Arary containing all items to remove" "Example: newArray = array_exclude( array1, array2 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_exclude( array, arrayExclude )// returns "array" minus all members of arrayExclude { newarray = array; for ( i = 0; i < arrayExclude.size; i++ ) { if ( is_in_array( array, arrayExclude[ i ] ) ) newarray = array_remove( newarray, arrayExclude[ i ] ); } return newarray; } /* ============= ///ScriptDocBegin "Name: array_compare( <array1> , <array2> )" "Summary: checks whether 2 arrays are equal. Returns true if they are, false if they are not" "Module: Array" "CallOn: " "MandatoryArg: <array1>: the first array to compare " "MandatoryArg: <array2>: the second array to compare " "Example: if( array_compare( array1, array2 ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_compare( array1, array2 ) { if ( array1.size != array2.size ) return false; foreach ( key, member in array1 ) { if ( !isdefined( array2[ key ] ) ) return false; member2 = array2[ key ]; if ( member2 != member ) return false; } return true; } /* ============= ///ScriptDocBegin "Name: array_contains( <array> , <compare> )" "Summary: Checks whether an item is in the array or not." "Module: Array" "CallOn: " "MandatoryArg: <array>: The array to search." "MandatoryArg: <compare>: The item to see if it exists in the array" "Example: if( arrray_contains( array, important_item ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_contains( array, compare ) { if ( array.size <= 0 ) return false; foreach ( member in array ) { if ( member == compare ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: getLinkedVehicleNodes()" "Summary: Returns an array of vehicle nodes that SELF is linked to" "Module: Utility" "CallOn: An entity that links to vehicle nodes" "Example: spawners = heli get_linked_ents()" "SPMP: both" ///ScriptDocEnd ============= */ getLinkedVehicleNodes() { array = []; if ( IsDefined( self.script_linkTo ) ) { linknames = get_links(); foreach ( name in linknames ) { entities = GetVehicleNodeArray( name, "script_linkname" ); array = array_combine( array, entities ); } } return array; } /* ============= ///ScriptDocBegin "Name: draw_line( <org1> , <org2> , <r> , <g> , <b> )" "Summary: Draws a line from < org1 > to < org2 > in the specified color forever" "Module: Debug" "CallOn: " "MandatoryArg: <org1> : starting origin for the line" "MandatoryArg: <org2> : ending origin for the line" "MandatoryArg: <r> : red color value( 0 to 1 )" "MandatoryArg: <g> : green color value( 0 to 1 )" "MandatoryArg: <b> : blue color value( 0 to 1 )" "Example: thread draw_line( level.player.origin, vehicle.origin, 1, 0, 0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_line( org1, org2, r, g, b ) { while ( 1 ) { Line( org1, org2, ( r, g, b ), 1 ); wait .05; } } /* ============= ///ScriptDocBegin "Name: draw_line_to_ent_for_time( <org1> , <ent> , <r> , <g> , <b> , <timer> )" "Summary: Draws a line from < org1 > to < ent > origin in the specified color for the specified duration. Updates to the entities origin each frame." "Module: Debug" "CallOn: " "MandatoryArg: <org1> : starting origin for the line" "MandatoryArg: <ent> : entity to draw line to" "MandatoryArg: <r> : red color value( 0 to 1 )" "MandatoryArg: <g> : green color value( 0 to 1 )" "MandatoryArg: <b> : blue color value( 0 to 1 )" "MandatoryArg: <timer> : time in seconds the line should last" "Example: thread draw_line_to_ent_for_time( level.player.origin, vehicle, 1, 0, 0, 10.0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_line_to_ent_for_time( org1, ent, r, g, b, timer ) { timer = GetTime() + ( timer * 1000 ); while ( GetTime() < timer ) { Line( org1, ent.origin, ( r, g, b ), 1 ); wait .05; if ( !isdefined( ent ) || !isdefined( ent.origin ) ) return; } } /* ============= ///ScriptDocBegin "Name: draw_line_from_ent_for_time( <ent> , <org> , <r> , <g> , <b> , <timer> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_line_from_ent_for_time( ent, org, r, g, b, timer ) { draw_line_to_ent_for_time( org, ent, r, g, b, timer ); } /* ============= ///ScriptDocBegin "Name: draw_line_from_ent_to_ent_for_time( <ent1> , <ent2> , <r> , <g> , <b> , <timer> )" "Summary: Draws a line from one entity origin to another entity origin in the specified color for the specified duration. Updates to the entities origin each frame." "Module: Debug" "CallOn: " "MandatoryArg: <ent1> : entity to draw line from" "MandatoryArg: <ent2> : entity to draw line to" "MandatoryArg: <r> : red color value( 0 to 1 )" "MandatoryArg: <g> : green color value( 0 to 1 )" "MandatoryArg: <b> : blue color value( 0 to 1 )" "MandatoryArg: <timer> : time in seconds the line should last" "Example: thread draw_line_from_ent_to_ent_for_time( level.player, vehicle, 1, 0, 0, 10.0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_line_from_ent_to_ent_for_time( ent1, ent2, r, g, b, timer ) { ent1 endon( "death" ); ent2 endon( "death" ); timer = GetTime() + ( timer * 1000 ); while ( GetTime() < timer ) { Line( ent1.origin, ent2.origin, ( r, g, b ), 1 ); wait .05; } } /* ============= ///ScriptDocBegin "Name: draw_line_from_ent_to_ent_until_notify( <ent1> , <ent2> , <r> , <g> , <b> , <notifyEnt> , <notifyString> )" "Summary: Draws a line from one entity origin to another entity origin in the specified color until < notifyEnt > is notified < notifyString > . Updates to the entities origin each frame." "Module: Debug" "CallOn: " "MandatoryArg: <ent1> : entity to draw line from" "MandatoryArg: <ent2> : entity to draw line to" "MandatoryArg: <r> : red color value( 0 to 1 )" "MandatoryArg: <g> : green color value( 0 to 1 )" "MandatoryArg: <b> : blue color value( 0 to 1 )" "MandatoryArg: <notifyEnt> : entity that waits for the notify" "MandatoryArg: <notifyString> : notify string that will make the line stop being drawn" "Example: thread draw_line_from_ent_to_ent_until_notify( level.player, guy, 1, 0, 0, guy, "anim_on_tag_done" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_line_from_ent_to_ent_until_notify( ent1, ent2, r, g, b, notifyEnt, notifyString ) { Assert( IsDefined( notifyEnt ) ); Assert( IsDefined( notifyString ) ); ent1 endon( "death" ); ent2 endon( "death" ); notifyEnt endon( notifyString ); while ( 1 ) { Line( ent1.origin, ent2.origin, ( r, g, b ), 0.05 ); wait .05; } } /* ============= ///ScriptDocBegin "Name: draw_line_until_notify( <org1> , <org2> , <r> , <g> , <b> , <notifyEnt> , <notifyString> )" "Summary: Draws a line from < org1 > to < org2 > in the specified color until < notifyEnt > is notified < notifyString > " "Module: Debug" "CallOn: " "MandatoryArg: <org1> : starting origin for the line" "MandatoryArg: <org2> : ending origin for the line" "MandatoryArg: <r> : red color value( 0 to 1 )" "MandatoryArg: <g> : green color value( 0 to 1 )" "MandatoryArg: <b> : blue color value( 0 to 1 )" "MandatoryArg: <notifyEnt> : entity that waits for the notify" "MandatoryArg: <notifyString> : notify string that will make the line stop being drawn" "Example: thread draw_line_until_notify( self.origin, targetLoc, 1, 0, 0, self, "stop_drawing_line" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_line_until_notify( org1, org2, r, g, b, notifyEnt, notifyString ) { Assert( IsDefined( notifyEnt ) ); Assert( IsDefined( notifyString ) ); notifyEnt endon( notifyString ); while ( 1 ) { draw_line_for_time( org1, org2, r, g, b, 0.05 ); } } /* ============= ///ScriptDocBegin "Name: draw_circle_until_notify( <center> , <radius> , <r> , <g> , <b> , <notifyEnt> , <notifyString> )" "Summary: Draws a circle at < center > with < radius > in the specified color until < notifyEnt > is notified < notifyString > " "Module: Debug" "CallOn: " "MandatoryArg: <center> : origin center of the circle" "MandatoryArg: <radius> : radius of the circle to draw" "MandatoryArg: <r> : red color value( 0 to 1 )" "MandatoryArg: <g> : green color value( 0 to 1 )" "MandatoryArg: <b> : blue color value( 0 to 1 )" "MandatoryArg: <notifyEnt> : entity that waits for the notify" "MandatoryArg: <notifyString> : notify string that will make the line stop being drawn" "Example: thread draw_circle_until_notify( self.origin, self.radius, 1, 0, 0, self, "stop_drawing_circle" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ draw_circle_until_notify( center, radius, r, g, b, notifyEnt, notifyString ) { circle_sides = 16; angleFrac = 360 / circle_sides; // Z circle circlepoints = []; for ( i = 0; i < circle_sides; i++ ) { angle = ( angleFrac * i ); xAdd = Cos( angle ) * radius; yAdd = Sin( angle ) * radius; x = center[ 0 ] + xAdd; y = center[ 1 ] + yAdd; z = center[ 2 ]; circlepoints[ circlepoints.size ] = ( x, y, z ); } thread draw_circle_lines_until_notify( circlepoints, r, g, b, notifyEnt, notifyString ); /* // X circle circlepoints = []; for ( i = 0 ; i < circle_sides ; i++ ) { angle = ( angleFrac * i ); xAdd = Cos( angle ) * radius; yAdd = Sin( angle ) * radius; x = center[ 0 ]; y = center[ 1 ] + xAdd; z = center[ 2 ] + yAdd; circlepoints[ circlepoints.size ] = ( x, y, z ); } thread debug_circle_drawlines( circlepoints, 5.0, ( 1, 0, 0 ), center ); // Y circle circlepoints = []; for ( i = 0 ; i < circle_sides ; i++ ) { angle = ( angleFrac * i ); xAdd = Cos( angle ) * radius; yAdd = Sin( angle ) * radius; x = center[ 0 ] + yAdd; y = center[ 1 ]; z = center[ 2 ] + xAdd; circlepoints[ circlepoints.size ] = ( x, y, z ); } thread debug_circle_drawlines( circlepoints, 5.0, ( 1, 0, 0 ), center ); */ } draw_circle_lines_until_notify( circlepoints, r, g, b, notifyEnt, notifyString ) { for ( i = 0; i < circlepoints.size; i++ ) { start = circlepoints[ i ]; if ( i + 1 >= circlepoints.size ) end = circlepoints[ 0 ]; else end = circlepoints[ i + 1 ]; thread draw_line_until_notify( start, end, r, g, b, notifyEnt, notifyString ); } } clear_enemy_passthrough() { self notify( "enemy" ); self ClearEnemy(); } /* ============= ///ScriptDocBegin "Name: battlechatter_off( <team> )" "Summary: Disable battlechatter for the specified team" "Module: Battlechatter" "CallOn: " "MandatoryArg: <team> : team to disable battlechatter on" "Example: battlechatter_off( "allies" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ battlechatter_off( team ) { level notify( "battlechatter_off_thread" ); animscripts\battlechatter::bcs_setup_chatter_toggle_array(); if ( IsDefined( team ) ) { set_battlechatter_variable( team, false ); soldiers = GetAIArray( team ); } else { foreach ( team in anim.teams ) { set_battlechatter_variable( team, false ); } soldiers = GetAIArray(); } if ( !isDefined( anim.chatInitialized ) || !anim.chatInitialized ) return; for ( index = 0; index < soldiers.size; index++ ) soldiers[ index ].battlechatter = false; for ( index = 0; index < soldiers.size; index++ ) { soldier = soldiers[ index ]; if ( !isalive( soldier ) ) continue; if ( !soldier.chatInitialized ) continue; if ( !soldier.isSpeaking ) continue; soldier wait_until_done_speaking(); } speakDiff = GetTime() - anim.lastTeamSpeakTime[ "allies" ]; if ( speakDiff < 1500 ) wait( speakDiff / 1000 ); if ( IsDefined( team ) ) level notify( team + " done speaking" ); else level notify( "done speaking" ); } /* ============= ///ScriptDocBegin "Name: battlechatter_on( <team> )" "Summary: Enable battlechatter for the specified team" "Module: Battlechatter" "CallOn: " "MandatoryArg: <team> : team to enable battlechatter on" "Example: battlechatter_on( "allies" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ battlechatter_on( team ) { thread battlechatter_on_thread( team ); } battlechatter_on_thread( team ) { level endon( "battlechatter_off_thread" ); animscripts\battlechatter::bcs_setup_chatter_toggle_array(); while ( !IsDefined( anim.chatInitialized ) ) { wait( 0.05 ); } flag_set( "battlechatter_on_thread_waiting" ); // buffer time wait( 1.5 ); flag_clear( "battlechatter_on_thread_waiting" ); if ( IsDefined( team ) ) { set_battlechatter_variable( team, true ); soldiers = GetAIArray( team ); } else { foreach ( team in anim.teams ) { set_battlechatter_variable( team, true ); } soldiers = GetAIArray(); } for ( index = 0; index < soldiers.size; index++ ) soldiers[ index ] set_battlechatter( true ); } /* ============= ///ScriptDocBegin "Name: set_battlechatter( <state> )" "Summary: Turns an AI's battlechatter on/off. Will be overridden if a spawner's .script_bcdialog is set to 0." "Module: Battlechatter" "CallOn: An AI" "MandatoryArg: <state>: True/false, describes whether battlechatter should be on or off for this AI" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_battlechatter( state ) { if ( !anim.chatInitialized ) return; if ( self.type == "dog" ) return; if ( state ) { if ( IsDefined( self.script_bcdialog ) && !self.script_bcdialog ) self.battlechatter = false; else self.battlechatter = true; } else { self.battlechatter = false; if ( IsDefined( self.isSpeaking ) && self.isSpeaking ) self waittill( "done speaking" ); } } /* ============= ///ScriptDocBegin "Name: flavorbursts_on( <team> )" "Summary: Gives all the AIs on a team the ability to play flavor burst transmissions. (Only US allies can use FBTs.) Note: if the battlechatter system is not working, the flavorbursts will not work even if the AIs have this set on them." "Module: Battlechatter" "CallOn: " "OptionalArg: <team>: which team? Usually, only allies have flavorbursts." "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ flavorbursts_on( team ) { thread set_flavorbursts_team_state( true, team ); } /* ============= ///ScriptDocBegin "Name: flavorbursts_off( <team> )" "Summary: Removes the ability to play flavor burst transmissions from all AIs on a team. (Only US allies can use FBTs.)" "Module: Battlechatter" "CallOn: " "OptionalArg: <team>: which team? Usually, only allies have flavorbursts." "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ flavorbursts_off( team ) { thread set_flavorbursts_team_state( false, team ); } set_flavorbursts_team_state( state, team ) { if ( !IsDefined( team ) ) { team = "allies"; } if ( !anim.chatInitialized ) { return; } // buffer time wait( 1.5 ); level.flavorbursts[ team ] = state; guys = []; guys = GetAIArray( team ); array_thread( guys, ::set_flavorbursts, state ); } /* ============= ///ScriptDocBegin "Name: set_flavorbursts( <state> )" "Summary: Turns battlechatter flavor burst transmissions for an AI on or off" "Module: Entity" "CallOn: An AI" "MandatoryArg: <state> " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_flavorbursts( state ) { self.flavorbursts = state; } /* ============= ///ScriptDocBegin "Name: friendlyfire_warnings_off()" "Summary: Disables player-originated friendly fire warnings for all allied AI." "Module: Entity" "SPMP: singleplayer" ///ScriptDocEnd ============= */ friendlyfire_warnings_off() { ais = GetAiArray( "allies" ); foreach( guy in ais ) { if( IsAlive( guy ) ) { guy set_friendlyfire_warnings( false ); } } level.friendlyfire_warnings = false; } /* ============= ///ScriptDocBegin "Name: friendlyfire_warnings_on()" "Summary: Enables player-originated friendly fire warnings for all allied AI." "Module: Entity" "SPMP: singleplayer" ///ScriptDocEnd ============= */ friendlyfire_warnings_on() { ais = GetAiArray( "allies" ); foreach( guy in ais ) { if( IsAlive( guy ) ) { guy set_friendlyfire_warnings( true ); } } level.friendlyfire_warnings = true; } /* ============= ///ScriptDocBegin "Name: set_friendlyfire_warnings( <state> )" "Summary: Turns player-originated friendly fire warnings for an AI on or off" "Module: Entity" "CallOn: An AI" "MandatoryArg: <state> " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_friendlyfire_warnings( state ) { if( state ) { self.friendlyfire_warnings_disable = undefined; } else { self.friendlyfire_warnings_disable = true; } } // // This is for scripted sequence guys that the LD has setup to not // get interrupted in route. // set_friendly_chain_wrapper( node ) { level.player SetFriendlyChain( node ); level notify( "newFriendlyChain", node.script_noteworthy ); } // Newvillers objective management /* level.currentObjective = "obj1";// disables non obj1 friendly chains if you're using newvillers style friendlychains objEvent = get_obj_event( "center_house" );// a trigger with targetname objective_event and a script_deathchain value objEvent waittill_objectiveEvent();// this waits until the AI with the event's script_deathchain are dead, then waits for trigger from the player. If it targets a friendly chain then it'll make the friendlies go to the chain. */ get_obj_origin( msg ) { objOrigins = GetEntArray( "objective", "targetname" ); for ( i = 0; i < objOrigins.size; i++ ) { if ( objOrigins[ i ].script_noteworthy == msg ) return objOrigins[ i ].origin; } } get_obj_event( msg ) { objEvents = GetEntArray( "objective_event", "targetname" ); for ( i = 0; i < objEvents.size; i++ ) { if ( objEvents[ i ].script_noteworthy == msg ) return objEvents[ i ]; } } waittill_objective_event() { waittill_objective_event_proc( true ); } waittill_objective_event_notrigger() { waittill_objective_event_proc( false ); } obj_set_chain_and_enemies() { objChain = GetNode( self.target, "targetname" ); objEnemies = GetEntArray( self.target, "targetname" ); flood_and_secure_scripted( objEnemies ); // array_thread(, ::flood_begin ); level notify( "new_friendly_trigger" ); level.player set_friendly_chain_wrapper( objChain ); } flood_begin() { self notify( "flood_begin" ); } flood_and_secure_scripted( spawners, instantRespawn ) { /* The "scripted" version acts as if it had been player triggered. Spawns AI that run to a spot then get a big goal radius. They stop spawning when auto delete kicks in, then start again when they are retriggered or the player gets close. trigger targetname flood_and_secure ai spawn and run to goal with small goalradius then get large goalradius spawner starts with a notify from any flood_and_secure trigger that triggers it spawner stops when an AI from it is deleted to make space for a new AI or when count is depleted spawners with count of 1 only make 1 guy. Spawners with count of more than 1 only deplete in count when the player kills the AI. spawner can target another spawner. When first spawner's ai dies from death( not deletion ), second spawner activates. */ if ( !isdefined( instantRespawn ) ) instantRespawn = false; if ( !isdefined( level.spawnerWave ) ) level.spawnerWave = []; array_thread( spawners, maps\_spawner::flood_and_secure_spawner, instantRespawn ); for ( i = 0; i < spawners.size; i++ ) { spawners[ i ].playerTriggered = true; spawners[ i ] notify( "flood_begin" ); } } debugorigin() { // self endon( "killanimscript" ); self notify( "Debug origin" ); self endon( "Debug origin" ); self endon( "death" ); for ( ;; ) { forward = AnglesToForward( self.angles ); forwardFar = vector_multiply( forward, 30 ); forwardClose = vector_multiply( forward, 20 ); right = AnglesToRight( self.angles ); left = vector_multiply( right, -10 ); right = vector_multiply( right, 10 ); Line( self.origin, self.origin + forwardFar, ( 0.9, 0.7, 0.6 ), 0.9 ); Line( self.origin + forwardFar, self.origin + forwardClose + right, ( 0.9, 0.7, 0.6 ), 0.9 ); Line( self.origin + forwardFar, self.origin + forwardClose + left, ( 0.9, 0.7, 0.6 ), 0.9 ); wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: get_linked_structs()" "Summary: Returns an array of entities that SELF is linked to" "Module: Utility" "CallOn: An entity that links to other entities" "Example: spawners = heli get_linked_structs()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_linked_structs() { array = []; if ( IsDefined( self.script_linkTo ) ) { linknames = get_links(); for ( i = 0; i < linknames.size; i++ ) { ent = getstruct( linknames[ i ], "script_linkname" ); if ( IsDefined( ent ) ) { array[ array.size ] = ent; } } } return array; } /* ============= ///ScriptDocBegin "Name: get_last_ent_in_chain( <sEntityType> )" "Summary: Get the last entity/node/vehiclenode in a chain of targeted entities" "Module: Entity" "CallOn: Any entity that targets a chain of linked nodes, vehiclenodes or other entities like script_origin" "MandatoryArg: <sEntityType>: needs to be specified as 'vehiclenode', 'pathnode', 'ent' or 'struct'" "Example: eLastNode = eVehicle get_last_ent_in_chain( "vehiclenode" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_last_ent_in_chain( sEntityType ) { ePathpoint = self; while ( IsDefined( ePathpoint.target ) ) { wait( 0.05 ); if ( IsDefined( ePathpoint.target ) ) { switch( sEntityType ) { case "vehiclenode": ePathpoint = GetVehicleNode( ePathpoint.target, "targetname" ); break; case "pathnode": ePathpoint = GetNode( ePathpoint.target, "targetname" ); break; case "ent": ePathpoint = GetEnt( ePathpoint.target, "targetname" ); break; case "struct": ePathpoint = getstruct( ePathpoint.target, "targetname" ); break; default: AssertMsg( "sEntityType needs to be 'vehiclenode', 'pathnode', 'ent' or 'struct'" ); } } else break; } ePathend = ePathpoint; return ePathend; } player_seek( timeout ) { goalent = Spawn( "script_origin", level.player.origin ); goalent LinkTo( level.player ); if ( IsDefined( timeout ) ) self thread timeout( timeout ); self SetGoalEntity( goalent ); if ( !isdefined( self.oldgoalradius ) ) self.oldgoalradius = self.goalradius; self.goalradius = 300; self waittill_any( "goal", "timeout" ); if ( IsDefined( self.oldgoalradius ) ) { self.goalradius = self.oldgoalradius; self.oldgoalradius = undefined; } goalent Delete(); } timeout( timeout ) { self endon( "death" ); wait( timeout ); self notify( "timeout" ); } /* ============= ///ScriptDocBegin "Name: set_forcegoal( <set_forcegoal> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_forcegoal() { if ( IsDefined( self.set_forcedgoal ) ) return; self.oldfightdist = self.pathenemyfightdist; self.oldmaxdist = self.pathenemylookahead; self.oldmaxsight = self.maxsightdistsqrd; self.pathenemyfightdist = 8; self.pathenemylookahead = 8; self.maxsightdistsqrd = 1; self.set_forcedgoal = true; } /* ============= ///ScriptDocBegin "Name: unset_forcegoal( <unset_forcegoal> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ unset_forcegoal() { if ( !isdefined( self.set_forcedgoal ) ) return; self.pathenemyfightdist = self.oldfightdist; self.pathenemylookahead = self.oldmaxdist; self.maxsightdistsqrd = self.oldmaxsight; self.set_forcedgoal = undefined; } /* ============= ///ScriptDocBegin "Name: array_add( <array> , <ent> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_add( array, ent ) { array[ array.size ] = ent; return array; } /* ============= ///ScriptDocBegin "Name: array_removeDead_keepkeys( <array> )" "Summary: Remove dead from an array but keep keys intact" "Module: Utility" "CallOn: An array" "MandatoryArg: <array>: The array " "Example: array = array_removeDead_keepkeys( <array> );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_removeDead_keepkeys( array ) { newArray = []; keys = GetArrayKeys( array ); for ( i = 0; i < keys.size; i++ ) { key = keys[ i ]; if ( !isalive( array[ key ] ) ) continue; newArray[ key ] = array[ key ]; } return newArray; } /* ============= ///ScriptDocBegin "Name: array_removeDead( <array> )" "Summary: Returns a new array of < array > minus the dead entities" "Module: Array" "CallOn: " "MandatoryArg: <array> : The array to search for dead entities in." "Example: friendlies = array_removeDead( friendlies );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_removeDead( array ) { newArray = []; foreach ( member in array ) { if ( !isalive( member ) ) continue; newArray[ newArray.size ] = member; } return newArray; } /* ============= ///ScriptDocBegin "Name: array_removeDead_or_dying( <array> )" "Summary: Returns a new array of < array > minus the dead or dying ai" "Module: Array" "CallOn: " "MandatoryArg: <array> : The array to search for dead ai in." "Example: friendlies = array_removeDead_or_dying( friendlies );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_removeDead_or_dying( array ) { newArray = []; foreach ( member in array ) { if ( !isalive( member ) ) continue; if ( member doingLongDeath() ) continue; newArray[ newArray.size ] = member; } return newArray; } /* ============= ///ScriptDocBegin "Name: array_insert( <array> , <object> , <index> )" "Summary: Returns a new array of < array > plus < object > at the specified index" "Module: Array" "CallOn: " "MandatoryArg: <array> : The array to add to." "MandatoryArg: <object> : The entity to add" "MandatoryArg: <index> : The index position < object > should be added to." "Example: ai = array_insert( ai, spawned, 0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_insert( array, object, index ) { if ( index == array.size ) { temp = array; temp[ temp.size ] = object; return temp; } temp = []; offset = 0; for ( i = 0; i < array.size; i++ ) { if ( i == index ) { temp[ i ] = object; offset = 1; } temp[ i + offset ] = array[ i ]; } return temp; } /* ============= ///ScriptDocBegin "Name: array_remove_nokeys( <ents> , <remover> )" "Summary: array_remove used on non keyed arrays doesn't flip the array " "Module: Utility" "CallOn: Level" "MandatoryArg: <ents>: array to remove from" "MandatoryArg: <remover>: thing to remove from the array" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_remove_nokeys( ents, remover ) { newents = []; for ( i = 0; i < ents.size; i++ ) if ( ents[ i ] != remover ) newents[ newents.size ] = ents[ i ]; return newents; } /* ============= ///ScriptDocBegin "Name: array_remove_index( <array> , <index> )" "Summary: Removes the element in the array with this index, resulting array order is intact." "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_remove_index( array, index ) { for ( i = 0; i < array.size - 1; i++ ) { if ( i == index ) { array[ i ] = array[ i + 1 ]; index++; } } array[ array.size - 1 ] = undefined; return array; } /* ============= ///ScriptDocBegin "Name: array_notify( <ents> , <notifier> )" "Summary: notify this array of entities with <notifier>" "Module: Array" "CallOn: array of entities" "MandatoryArg: <ents>: " "MandatoryArg: <notifier>: " "Example: array_notify( enemies, "time_to_dance" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_notify( ents, notifier, match ) { foreach ( key, value in ents ) value notify( notifier, match ); } // fancy quicker struct array handling, assumes array elements are objects with which an index can be asigned to( IE: can't do 5.struct_array_index ) // also have to be sure that objects can't be a part of another structarray setup as the index position is asigned to the object struct_arrayspawn() { struct = SpawnStruct(); struct.array = []; struct.lastindex = 0; return struct; } /* structarray_add( struct, object ) { struct.array[ struct.lastindex ] = SpawnStruct(); struct.array[ struct.lastindex ].object = object; struct.array[ struct.lastindex ].struct_array_index = struct.lastindex; struct.lastindex ++ ; } */ structarray_add( struct, object ) { Assert( !isdefined( object.struct_array_index ) );// can't have elements of two structarrays on these. can add that later if it's needed struct.array[ struct.lastindex ] = object; object.struct_array_index = struct.lastindex; struct.lastindex++; } /* ============= ///ScriptDocBegin "Name: structarray_remove( <struct> , <object )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1> : " "OptionalArg: <param2> : " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ structarray_remove( struct, object ) { structarray_swaptolast( struct, object ); struct.array[ struct.lastindex - 1 ] = undefined; struct.lastindex--; } structarray_remove_index( struct, index ) { // overwrite the index to remove with the last in the array struct.array[ index ] = struct.array[ struct.lastindex - 1 ]; struct.array[ index ].struct_array_index = index; // remove the last from the array since it's now at position 'index' struct.array[ struct.lastindex - 1 ] = undefined; struct.lastindex = struct.array.size; } structarray_remove_undefined( struct ) { // remove undefined ents from array newArray = []; foreach( object in struct.array ) { if ( !isdefined( object ) ) continue; newArray[ newArray.size ] = object; } struct.array = newArray; // reassign all the index vars foreach( i, object in struct.array ) { object.struct_array_index = i; } struct.lastindex = struct.array.size; } structarray_swaptolast( struct, object ) { struct structarray_swap( struct.array[ struct.lastindex - 1 ], object ); } structarray_shuffle( struct, shuffle ) { for ( i = 0; i < shuffle; i++ ) struct structarray_swap( struct.array[ i ], struct.array[ RandomInt( struct.lastindex ) ] ); } // starts this ambient track set_ambient_alias( ambient, alias ) { // change the meaning of this ambience so that the ambience can change over the course of the level level.ambient_modifier[ ambient ] = alias; // if the ambient being aliased is the current ambience then restart it so it gets the new track if ( level.ambient == ambient ) maps\_ambient::activateAmbient( ambient ); } /* ============= ///ScriptDocBegin "Name: get_use_key( <get_use_key> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_use_key() { if ( level.console ) return " + usereload"; else return " + activate"; } doom() { // send somebody far away then delete them self Teleport( ( 0, 0, -15000 ) ); self Kill( ( 0, 0, 0 ) ); } /* ============= ///ScriptDocBegin "Name: custom_battlechatter( <phrase> )" "Summary: Call this on an AI to get him to use the battlechatter system to say a specific kind of phrase. AIs who have battlechatter turned off won't be able to say the phrase. Returns false if it couldn't do the custom battlechatter for some reason (will output to console or assert with errors, depending on severity)." "Module: Battlechatter" "CallOn: An AI" "MandatoryArg: <phrase>: the string ID for the phrase that the AI will try to say. Legit phrases are: "order_move_combat", "order_move_noncombat", "order_action_coverme", "inform_reloading"" "Example: level.sarge custom_battlechatter( "move_combat" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ custom_battlechatter( phrase ) { return self animscripts\battlechatter_ai::custom_battlechatter_internal( phrase ); } /* ============= ///ScriptDocBegin "Name: get_stop_watch( <time> , <othertime> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_stop_watch( time, othertime ) { watch = NewHudElem(); if ( level.console ) { watch.x = 68; watch.y = 35; } else { watch.x = 58; watch.y = 95; } watch.alignx = "center"; watch.aligny = "middle"; watch.horzAlign = "left"; watch.vertAlign = "middle"; if ( IsDefined( othertime ) ) timer = othertime; else timer = level.explosiveplanttime; watch SetClock( timer, time, "hudStopwatch", 64, 64 );// count down for level.explosiveplanttime of 60 seconds, size is 64x64 return watch; } objective_is_active( msg ) { active = false; // objective must be active for this trigger to hit for ( i = 0; i < level.active_objective.size; i++ ) { if ( level.active_objective[ i ] != msg ) continue; active = true; break; } return( active ); } objective_is_inactive( msg ) { inactive = false; // objective must be active for this trigger to hit for ( i = 0; i < level.inactive_objective.size; i++ ) { if ( level.inactive_objective[ i ] != msg ) continue; inactive = true; break; } return( inactive ); } set_objective_inactive( msg ) { // remove the objective from the active list array = []; for ( i = 0; i < level.active_objective.size; i++ ) { if ( level.active_objective[ i ] == msg ) continue; array[ array.size ] = level.active_objective[ i ]; } level.active_objective = array; // add it to the inactive list exists = false; for ( i = 0; i < level.inactive_objective.size; i++ ) { if ( level.inactive_objective[ i ] != msg ) continue; exists = true; } if ( !exists ) level.inactive_objective[ level.inactive_objective.size ] = msg; /# // assert that each objective is only on one list for ( i = 0; i < level.active_objective.size; i++ ) { for ( p = 0; p < level.inactive_objective.size; p++ ) AssertEx( level.active_objective[ i ] != level.inactive_objective[ p ], "Objective is both inactive and active" ); } #/ } set_objective_active( msg ) { // remove the objective from the inactive list array = []; for ( i = 0; i < level.inactive_objective.size; i++ ) { if ( level.inactive_objective[ i ] == msg ) continue; array[ array.size ] = level.inactive_objective[ i ]; } level.inactive_objective = array; // add it to the active list exists = false; for ( i = 0; i < level.active_objective.size; i++ ) { if ( level.active_objective[ i ] != msg ) continue; exists = true; } if ( !exists ) level.active_objective[ level.active_objective.size ] = msg; /# // assert that each objective is only on one list for ( i = 0; i < level.active_objective.size; i++ ) { for ( p = 0; p < level.inactive_objective.size; p++ ) AssertEx( level.active_objective[ i ] != level.inactive_objective[ p ], "Objective is both inactive and active" ); } #/ } /* ============= ///ScriptDocBegin "Name: detect_friendly_fire( <detect_friendly_fire> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ detect_friendly_fire() { level thread maps\_friendlyfire::detectFriendlyFireOnEntity( self ); } /* ============= ///ScriptDocBegin "Name: missionFailedWrapper( <missionFailedWrapper> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ missionFailedWrapper() { if ( level.MissionFailed ) return; if ( IsDefined( level.nextmission ) ) return;// don't fail the mission while the game is on it's way to the next mission. /* // will return in the next game /# if ( IsGodMode( level.player ) ) { PrintLn( GetDvar( "ui_deadquote" ) ); return; } #/ */ level.MissionFailed = true; flag_set( "missionfailed" ); if ( arcadeMode() ) return; if ( GetDvar( "failure_disabled" ) == "1" ) return; if ( is_specialop() ) { thread maps\_specialops_code::failure_summary_display(); return; } MissionFailed(); } /* ============= ///ScriptDocBegin "Name: script_delay( <script_delay> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ script_delay() { if ( IsDefined( self.script_delay ) ) { wait( self.script_delay ); return true; } else if ( IsDefined( self.script_delay_min ) && IsDefined( self.script_delay_max ) ) { wait( RandomFloatRange( self.script_delay_min, self.script_delay_max ) ); return true; } return false; } /* ============= ///ScriptDocBegin "Name: script_wait( <script_wait> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ script_wait() { startTime = GetTime(); if ( IsDefined( self.script_wait ) ) { wait( self.script_wait ); if ( IsDefined( self.script_wait_add ) ) self.script_wait += self.script_wait_add; } else if ( IsDefined( self.script_wait_min ) && IsDefined( self.script_wait_max ) ) { wait( RandomFloatRange( self.script_wait_min, self.script_wait_max ) ); if ( IsDefined( self.script_wait_add ) ) { self.script_wait_min += self.script_wait_add; self.script_wait_max += self.script_wait_add; } } return( GetTime() - startTime ); } /* ============= ///ScriptDocBegin "Name: guy_enter_vehicle( <guy> )" "Summary: Makes a guy get in a vehicle" "Module: Utility" "CallOn: A vehicle" "MandatoryArg: <guy>: The guy getting in" "Example: tank guy_enter_vehicle( guy );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ guy_enter_vehicle( guy ) { self maps\_vehicle_aianim::guy_enter( guy ); } /* ============= ///ScriptDocBegin "Name: guy_runtovehicle_load( <guy> , <vehicle> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ guy_runtovehicle_load( guy, vehicle ) { maps\_vehicle_aianim::guy_runtovehicle( guy, vehicle ); } get_force_color_guys( team, color ) { ai = GetAIArray( team ); guys = []; for ( i = 0; i < ai.size; i++ ) { guy = ai[ i ]; if ( !isdefined( guy.script_forcecolor ) ) continue; if ( guy.script_forcecolor != color ) continue; guys[ guys.size ] = guy; } return guys; } get_all_force_color_friendlies() { ai = GetAIArray( "allies" ); guys = []; for ( i = 0; i < ai.size; i++ ) { guy = ai[ i ]; if ( !isdefined( guy.script_forcecolor ) ) continue; guys[ guys.size ] = guy; } return guys; } /* ============= ///ScriptDocBegin "Name: get_all_target_ents( <target> )" "Summary: Returns array of targetted ent, structs, nodes" "Module: Utility" "OptionalArg: <target>: Optional target override" "Example: node = guy get_target_ent();" "SPMP: both" ///ScriptDocEnd ============= */ get_all_target_ents( target ) { if ( !isdefined( target ) ) target = self.target; AssertEx( IsDefined( target ), "Self had no target!" ); array = []; ents = GetEntArray( target, "targetname" ); array = array_combine( array, ents ); ents = GetNodeArray( target, "targetname" ); array = array_combine( array, ents ); ents = getstructarray( target, "targetname" ); array = array_combine( array, ents ); ents = GetVehicleNodeArray( target, "targetname" ); array = array_combine( array, ents ); return array; } /* ============= ///ScriptDocBegin "Name: enable_ai_color( )" "Summary: Enables color movement system on an AI" "Module: Entity" "CallOn: An entity" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_ai_color() { if ( IsDefined( self.script_forcecolor ) ) return; if ( !isdefined( self.old_forceColor ) ) return; set_force_color( self.old_forcecolor ); self.old_forceColor = undefined; } /* ============= ///ScriptDocBegin "Name: enable_ai_color_dontmove( )" "Summary: Enables color movement system on an AI, but wont cause them to move to that color until another order is given by script or trigger" "Module: Entity" "CallOn: An entity" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_ai_color_dontmove() { self.dontColorMove = true; self enable_ai_color(); } /* ============= ///ScriptDocBegin "Name: disable_ai_color( <disable_ai_color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_ai_color() { if ( IsDefined( self.new_force_color_being_set ) ) { self endon( "death" ); // setting force color happens after waittillframeend so we need to wait until it finishes // setting before we disable it, so a set followed by a disable will send the guy to a node. self waittill( "done_setting_new_color" ); } self ClearFixedNodeSafeVolume(); // any color on this guy? if ( !isdefined( self.script_forcecolor ) ) { return; } AssertEx( !isdefined( self.old_forcecolor ), "Tried to disable forcecolor on a guy that somehow had a old_forcecolor already. Investigate!!!" ); self.old_forceColor = self.script_forceColor; // first remove the guy from the force color array he used to belong to level.arrays_of_colorForced_ai[ self maps\_colors::get_team() ][ self.script_forcecolor ] = array_remove( level.arrays_of_colorForced_ai[ self maps\_colors::get_team() ][ self.script_forcecolor ], self ); // self maps\_colors::removeAIFromColorNumberArray(); maps\_colors::left_color_node(); self.script_forcecolor = undefined; self.currentColorCode = undefined; /# update_debug_friendlycolor( self.unique_id ); #/ } /* ============= ///ScriptDocBegin "Name: clear_force_color( <clear_force_color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ clear_force_color() { disable_ai_color(); } /* ============= ///ScriptDocBegin "Name: check_force_color( <_color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ check_force_color( _color ) { color = level.colorCheckList[ ToLower( _color ) ]; if ( IsDefined( self.script_forcecolor ) && color == self.script_forcecolor ) return true; else return false; } /* ============= ///ScriptDocBegin "Name: get_force_color( <get_force_color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_force_color() { color = self.script_forceColor; return color; } shortenColor( color ) { AssertEx( IsDefined( level.colorCheckList[ ToLower( color ) ] ), "Tried to set force color on an undefined color: " + color ); return level.colorCheckList[ ToLower( color ) ]; } /* ============= ///ScriptDocBegin "Name: set_force_color( <_color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_force_color( _color ) { // shorten and lowercase the ai's forcecolor to a single letter color = shortenColor( _color ); AssertEx( maps\_colors::colorIsLegit( color ), "Tried to set force color on an undefined color: " + color ); if ( !isAI( self ) ) { set_force_color_spawner( color ); return; } AssertEx( IsAlive( self ), "Tried to set force color on a dead / undefined entity." ); /* /# thread insure_player_does_not_set_forcecolor_twice_in_one_frame(); #/ */ if ( self.team == "allies" ) { // enable fixed node mode. self.fixednode = true; self.fixednodesaferadius = 64; self.pathenemyfightdist = 0; self.pathenemylookahead = 0; } // maps\_colors::removeAIFromColorNumberArray(); self.script_color_axis = undefined; self.script_color_allies = undefined; self.old_forcecolor = undefined; team = maps\_colors::get_team(); if ( IsDefined( self.script_forcecolor ) ) { // first remove the guy from the force color array he used to belong to level.arrays_of_colorForced_ai[ team ][ self.script_forcecolor ] = array_remove( level.arrays_of_colorForced_ai[ team ][ self.script_forcecolor ], self ); } self.script_forcecolor = color; // get added to the new array of AI that are forced to this color level.arrays_of_colorForced_ai[ team ][ color ] = array_removeDead( level.arrays_of_colorForced_ai[ team ][ color ] ); level.arrays_of_colorForced_ai[ team ][ self.script_forcecolor ] = array_add( level.arrays_of_colorForced_ai[ team ][ self.script_forcecolor ], self ); // set it here so that he continues in script as the correct color thread new_color_being_set( color ); } set_force_color_spawner( color ) { /* team = undefined; colorTeam = undefined; if( IsSubStr( self.classname, "axis" ) ) { colorTeam = self.script_color_axis; team = "axis"; } if( IsSubStr( self.classname, "ally" ) ) { colorTeam = self.script_color_allies; team = "allies"; } maps\_colors::removeSpawnerFromColorNumberArray(); */ self.script_forcecolor = color; // self.script_color_axis = undefined; // self.script_color_allies = undefined; self.old_forceColor = undefined; // thread maps\_colors::spawner_processes_colorCoded_ai(); } issue_color_orders( color_team, team ) { colorCodes = StrTok( color_team, " " ); colors = []; colorCodesByColorIndex = []; for ( i = 0; i < colorCodes.size; i++ ) { color = undefined; if ( IsSubStr( colorCodes[ i ], "r" ) ) color = "r"; else if ( IsSubStr( colorCodes[ i ], "b" ) ) color = "b"; else if ( IsSubStr( colorCodes[ i ], "y" ) ) color = "y"; else if ( IsSubStr( colorCodes[ i ], "c" ) ) color = "c"; else if ( IsSubStr( colorCodes[ i ], "g" ) ) color = "g"; else if ( IsSubStr( colorCodes[ i ], "p" ) ) color = "p"; else if ( IsSubStr( colorCodes[ i ], "o" ) ) color = "o"; else AssertEx( 0, "Trigger at origin " + self GetOrigin() + " had strange color index " + colorCodes[ i ] ); colorCodesByColorIndex[ color ] = colorCodes[ i ]; colors[ colors.size ] = color; } Assert( colors.size == colorCodes.size ); for ( i = 0; i < colorCodes.size; i++ ) { // remove deleted spawners level.arrays_of_colorCoded_spawners[ team ][ colorCodes[ i ] ] = array_removeUndefined( level.arrays_of_colorCoded_spawners[ team ][ colorCodes[ i ] ] ); AssertEx( IsDefined( level.arrays_of_colorCoded_spawners[ team ][ colorCodes[ i ] ] ), "Trigger refer to a color# that does not exist in any node for this team." ); // set the .currentColorCode on each appropriate spawner for ( p = 0; p < level.arrays_of_colorCoded_spawners[ team ][ colorCodes[ i ] ].size; p++ ) level.arrays_of_colorCoded_spawners[ team ][ colorCodes[ i ] ][ p ].currentColorCode = colorCodes[ i ]; } for ( i = 0; i < colors.size; i++ ) { // remove the dead from the color forced ai level.arrays_of_colorForced_ai[ team ][ colors[ i ] ] = array_removeDead( level.arrays_of_colorForced_ai[ team ][ colors[ i ] ] ); // set the destination of the color forced spawners level.currentColorForced[ team ][ colors[ i ] ] = colorCodesByColorIndex[ colors[ i ] ]; } for ( i = 0; i < colorCodes.size; i++ ) self thread maps\_colors::issue_color_order_to_ai( colorCodes[ i ], colors[ i ], team ); } // TODO: Non - hacky rumble. flashRumbleLoop( duration ) { Assert( IsPlayer( self ) ); goalTime = GetTime() + duration * 1000; while ( GetTime() < goalTime ) { self PlayRumbleOnEntity( "damage_heavy" ); wait( 0.05 ); } } flashMonitorEnableHealthShield( time ) { self endon( "death" ); self endon( "flashed" ); wait 0.2; self EnableHealthShield( false ); wait time + 2; self EnableHealthShield( true ); } flashMonitor() { Assert( IsPlayer( self ) ); self endon( "death" ); for ( ;; ) { self waittill( "flashbang", origin, percent_distance, percent_angle, attacker, team ); if ( "1" == GetDvar( "noflash" ) ) continue; if ( isdefined( self.coop_downed ) ) continue; // PrintLn( "Flashed by a grenade from team '", team, "'." ); // if it's close enough, angle doesn't matter so much frac = ( percent_distance - 0.85 ) / ( 1 - 0.85 ); if ( frac > percent_angle ) percent_angle = frac; if ( percent_angle < 0.25 ) percent_angle = 0.25; // at 300 or less of the full range of 1000 units, get the full effect minamountdist = 0.3; if ( percent_distance > 1 - minamountdist ) percent_distance = 1.0; else percent_distance = percent_distance / ( 1 - minamountdist ); if ( team != self.team ) seconds = percent_distance * percent_angle * 6.0; else seconds = percent_distance * percent_angle * 3.0; if ( seconds < 0.25 ) continue; if ( IsDefined( self.maxflashedseconds ) && seconds > self.maxflashedseconds ) seconds = self.maxflashedseconds; self.flashingTeam = team; self notify( "flashed" ); self.flashendtime = GetTime() + seconds * 1000;// player is flashed if flashDoneTime > GetTime() self ShellShock( "flashbang", seconds ); flag_set( "player_flashed" ); thread unflash_flag( seconds ); if ( percent_distance * percent_angle > 0.5 ) self thread flashMonitorEnableHealthShield( seconds ); if ( seconds > 2 ) thread flashRumbleLoop( 0.75 ); else thread flashRumbleLoop( 0.25 ); // if it's an enemy's flash grenade, // flash nearby allies so they can't take out enemies going after the player if ( team != "allies" ) self thread flashNearbyAllies( seconds, team ); } } flashNearbyAllies( baseDuration, team ) { Assert( IsPlayer( self ) ); wait .05; allies = GetAIArray( "allies" ); for ( i = 0; i < allies.size; i++ ) { if ( DistanceSquared( allies[ i ].origin, self.origin ) < 350 * 350 ) { duration = baseDuration + RandomFloatRange( -1000, 1500 ); if ( duration > 4.5 ) duration = 4.5; else if ( duration < 0.25 ) continue; newendtime = GetTime() + duration * 1000; if ( !isdefined( allies[ i ].flashendtime ) || allies[ i ].flashendtime < newendtime ) { allies[ i ].flashingTeam = team; allies[ i ] flashBangStart( duration ); } } } } /* ============= ///ScriptDocBegin "Name: restartEffect( <restartEffect> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ restartEffect() { self common_scripts\_createfx::restart_fx_looper(); } /* ============= ///ScriptDocBegin "Name: pauseExploder( <num> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ pauseExploder( num ) { num += ""; foreach ( fx in level.createFXent ) { if ( !isdefined( fx.v[ "exploder" ] ) ) continue; if ( fx.v[ "exploder" ] != num ) continue; fx pauseEffect(); } } /* ============= ///ScriptDocBegin "Name: restartExploder( <num> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ restartExploder( num ) { num += ""; foreach ( fx in level.createFXent ) { if ( !isdefined( fx.v[ "exploder" ] ) ) continue; if ( fx.v[ "exploder" ] != num ) continue; fx restartEffect(); } } /* ============= ///ScriptDocBegin "Name: getfxarraybyID( <fxid> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getfxarraybyID( fxid ) { array = []; for ( i = 0; i < level.createFXent.size; i++ ) { if ( level.createFXent[ i ].v[ "fxid" ] == fxid ) array[ array.size ] = level.createFXent[ i ]; } return array; } ignoreAllEnemies( qTrue ) { self notify( "ignoreAllEnemies_threaded" ); self endon( "ignoreAllEnemies_threaded" ); if ( qTrue ) { // put the ai in a threat bias group that ignores all the other groups so he // doesnt get distracted and go into exposed while his goal radius is too small self.old_threat_bias_group = self GetThreatBiasGroup(); num = undefined; /# num = self GetEntNum(); PrintLn( "entity: " + num + "ignoreAllEnemies TRUE" ); PrintLn( "entity: " + num + " threatbiasgroup is " + self.old_threat_bias_group ); #/ CreateThreatBiasGroup( "ignore_everybody" ); /# PrintLn( "entity: " + num + "ignoreAllEnemies TRUE" ); PrintLn( "entity: " + num + " SetThreatBiasGroup( ignore_everybody )" ); #/ self SetThreatBiasGroup( "ignore_everybody" ); teams = []; teams[ "axis" ] = "allies"; teams[ "allies" ] = "axis"; AssertEx( self.team != "neutral", "Why are you making a guy have team neutral? And also, why is he doing anim_reach?" ); ai = GetAIArray( teams[ self.team ] ); groups = []; for ( i = 0; i < ai.size; i++ ) groups[ ai[ i ] GetThreatBiasGroup() ] = true; keys = GetArrayKeys( groups ); for ( i = 0; i < keys.size; i++ ) { /# PrintLn( "entity: " + num + "ignoreAllEnemies TRUE" ); PrintLn( "entity: " + num + " SetThreatBias( " + keys[ i ] + ", ignore_everybody, 0 )" ); #/ SetThreatBias( keys[ i ], "ignore_everybody", 0 ); } // should now be impossible for this guy to attack anybody on the other team } else { num = undefined; AssertEx( IsDefined( self.old_threat_bias_group ), "You can't use ignoreAllEnemies( false ) on an AI that has never ran ignoreAllEnemies( true )" ); /# num = self GetEntNum(); PrintLn( "entity: " + num + "ignoreAllEnemies FALSE" ); PrintLn( "entity: " + num + " self.old_threat_bias_group is " + self.old_threat_bias_group ); #/ if ( self.old_threat_bias_group != "" ) { /# PrintLn( "entity: " + num + "ignoreAllEnemies FALSE" ); PrintLn( "entity: " + num + " SetThreatBiasGroup( " + self.old_threat_bias_group + " )" ); #/ self SetThreatBiasGroup( self.old_threat_bias_group ); } self.old_threat_bias_group = undefined; } } /* ============= ///ScriptDocBegin "Name: vehicle_detachfrompath( <vehicle_detachfrompath> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ vehicle_detachfrompath() { maps\_vehicle::vehicle_pathdetach(); } /* ============= ///ScriptDocBegin "Name: vehicle_resumepath()" "Summary: will resume to the last path a vehicle was on. Only used for helicopters, ground vehicles don't ever deviate." "Module: Vehicle" "CallOn: An entity" "Example: helicopter vehicle_resumepath();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ vehicle_resumepath() { thread maps\_vehicle::vehicle_resumepathvehicle(); } /* ============= ///ScriptDocBegin "Name: vehicle_land( <neargoaldist>)" "Summary: lands a vehicle on the ground, _vehicle scripts take care of offsets and determining where the ground is relative to the origin. Returns when land is complete" "Module: Vehicle" "CallOn: An entity" "OptionalArg: <neargoaldist>: neargoal distance for notifying near_goal" "Example: helicopter vehicle_land();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ vehicle_land( neargoaldist ) { maps\_vehicle::vehicle_landvehicle( neargoaldist ); } /* ============= ///ScriptDocBegin "Name: vehicle_liftoff( <height> )" "Summary: make a vehicle lift of to the specified height. if the vehicle was on a path and went through vehicle_land, this will resume that path" "Module: Entity" "CallOn: An entity" "OptionalArg: <height>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ vehicle_liftoff( height ) { maps\_vehicle::vehicle_liftoffvehicle( height ); } /* ============= ///ScriptDocBegin "Name: vehicle_dynamicpath( <node> , <bwaitforstart> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ vehicle_dynamicpath( node, bwaitforstart ) { maps\_vehicle::vehicle_paths( node, bwaitforstart ); } /* ============= ///ScriptDocBegin "Name: groundpos( <origin> )" "Summary: bullettraces to the ground and returns the position that it hit." "Module: Utility" "CallOn: An entity" "MandatoryArg: <origin> : " "Example: groundposition = helicopter groundpos( helicopter.origin ); " "SPMP: singleplayer" ///ScriptDocEnd ============= */ groundpos( origin ) { return BulletTrace( origin, ( origin + ( 0, 0, -100000 ) ), 0, self )[ "position" ]; } change_player_health_packets( num ) { Assert( IsPlayer( self ) ); self.player_health_packets += num; self notify( "update_health_packets" ); if ( self.player_health_packets >= 3 ) self.player_health_packets = 3; // if( self.player_health_packets <= 0 ) // self Kill(); } /* ============= ///ScriptDocBegin "Name: getvehiclespawner( <targetname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getvehiclespawner( targetname ) { spawners = getvehiclespawnerarray( targetname ); Assert( spawners.size == 1 ); return spawners[ 0 ]; } /* ============= ///ScriptDocBegin "Name: getvehiclespawnerarray( <targetname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getvehiclespawnerarray( targetname ) { return maps\_vehicle::_getvehiclespawnerarray( targetname ); } /* ============= ///ScriptDocBegin "Name: player_fudge_moveto( <dest> , <moverate> )" "Summary: this function is to fudge move the player. Use this as a placeholder for an actual animation. returns when finished" "Module: Player" "CallOn: Level" "MandatoryArg: <dest> : origin to move the player to" "OptionalArg: <moverate> : Units per second to move the player. defaults to 200" "Example: player_fudge_moveto( carexitorg );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_fudge_moveto( dest, moverate ) { // moverate = units / persecond if ( !isdefined( moverate ) ) moverate = 200; // this function is to fudge move the player. I'm using this as a placeholder for an actual animation org = Spawn( "script_origin", level.player.origin ); org.origin = level.player.origin; level.player LinkTo( org ); dist = Distance( level.player.origin, dest ); movetime = dist / moverate; org MoveTo( dest, dist / moverate, .05, .05 ); wait movetime; level.player Unlink(); } /* ============= ///ScriptDocBegin "Name: add_start( <msg> , <func> , <loc_string> , <optional_func> )" "Summary: add start with a string" "Module: Utility" "CallOn: Level" "MandatoryArg: <msg>: string to identify the start" "MandatoryArg: <func>: thread to start when this start is initialized" "OptionalArg: <loc_string>: Localizated string to display, this became a requirement when loc_warnings were turned on." "OptionalArg: <Optional_func>: The main logic function associated with this start point, will run in the order of the start points when a previous function completes." "Example: add_start( "first_hind", ::start_first_hind, &"STARTS_FIRSTHIND" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_start( msg, func, loc_string, optional_func ) { AssertEx( !isdefined( level._loadStarted ), "Can't create starts after _load" ); if ( !isdefined( level.start_functions ) ) level.start_functions = []; // AssertEx( IsDefined( loc_string ), "Starts now require a localize string" ); msg = ToLower( msg ); /# if ( IsDefined( loc_string ) ) { PreCacheString( loc_string ); level.start_loc_string[ msg ] = loc_string; } #/ array = []; array[ "name" ] = msg; array[ "start_func" ] = func; array[ "logic_func" ] = optional_func; level.start_functions[ level.start_functions.size ] = array; level.start_arrays[ msg ] = array; } level_has_start_points() { // account for no_game start point return level.start_functions.size > 1; } /* ============= ///ScriptDocBegin "Name: set_default_start( <start> )" "Summary: Set the default start point by name." "Module: Utility" "MandatoryArg: <start>: Which start to use as the default start." "Example: set_default_start( "ride" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_default_start( start ) { level.default_start_override = start; } /* ============= ///ScriptDocBegin "Name: default_start( <func> )" "Summary: " "Module: Utility" "CallOn: Level" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ default_start( func ) { level.default_start = func; } linetime( start, end, color, timer ) { thread linetime_proc( start, end, color, timer ); } /* ============= ///ScriptDocBegin "Name: within_fov( <start_origin> , <start_angles> , <end_origin> , <fov> )" "Summary: Returns true if < end_origin > is within the players field of view, otherwise returns false." "Module: Vector" "CallOn: " "MandatoryArg: <start_origin> : starting origin for FOV check( usually the players origin )" "MandatoryArg: <start_angles> : angles to specify facing direction( usually the players angles )" "MandatoryArg: <end_origin> : origin to check if it's in the FOV" "MandatoryArg: <fov> : cosine of the FOV angle to use" "Example: qBool = within_fov( level.player.origin, level.player.angles, target1.origin, Cos( 45 ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ within_fov( start_origin, start_angles, end_origin, fov ) { normal = VectorNormalize( end_origin - start_origin ); forward = AnglesToForward( start_angles ); dot = VectorDot( forward, normal ); return dot >= fov; } /* ============= ///ScriptDocBegin "Name: within_fov_2d( <start_origin> , <start_angles> , <end_origin> , <fov> )" "Summary: Returns true if < end_origin > is within the players field of view, otherwise returns false. Compares in 2d only." "Module: Vector" "CallOn: " "MandatoryArg: <start_origin> : starting origin for FOV check( usually the players origin )" "MandatoryArg: <start_angles> : angles to specify facing direction( usually the players angles )" "MandatoryArg: <end_origin> : origin to check if it's in the FOV" "MandatoryArg: <fov> : cosine of the FOV angle to use" "Example: qBool = within_fov_2d( level.player.origin, level.player.angles, target1.origin, Cos( 45 ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ within_fov_2d( start_origin, start_angles, end_origin, fov ) { start_origin = set_z( start_origin, 0 ); end_origin = set_z( end_origin, 0 ); start_angles = ( 0, start_angles[ 1 ], 0 ); normal = VectorNormalize( end_origin - start_origin ); forward = AnglesToForward( start_angles ); dot = VectorDot( forward, normal ); return dot >= fov; } /* ============= ///ScriptDocBegin "Name: get_dot( <start_origin> , <start_angles> , <end_origin> )" "Summary: Returns the dot product." "Module: Vector" "CallOn: " "MandatoryArg: <start_origin> : starting origin for FOV check( usually the players origin )" "MandatoryArg: <start_angles> : angles to specify facing direction( usually the players angles )" "MandatoryArg: <end_origin> : origin to check if it's in the FOV" "Example: fov = get_dot( level.player.origin, level.player.angles, target1.origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_dot( start_origin, start_angles, end_origin ) { normal = VectorNormalize( end_origin - start_origin ); forward = AnglesToForward( start_angles ); dot = VectorDot( forward, normal ); return dot; } /* ============= ///ScriptDocBegin "Name: within_fov_of_players( <end_origin> , <fov> )" "Summary: Returns true if < end_origin > is within the all of the players field of view (single or coop), otherwise returns false. Start origin and start angles are of the individual players in the map (single or coop)" "Module: Vector" "CallOn: " "MandatoryArg: <end_origin> : origin to check if it's in the FOV" "MandatoryArg: <fov> : cosine of the FOV angle to use" "Example: qBool = within_fov_of_players( target1.origin, Cos( 45 ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ within_fov_of_players( end_origin, fov ) { bDestInFOV = undefined; for ( i = 0; i < level.players.size; i++ ) { playerEye = level.players[ i ] GetEye(); bDestInFOV = within_fov( playerEye, level.players[ i ] GetPlayerAngles(), end_origin, fov ); if ( !bDestInFOV ) return false; } return true; } waitSpread( start, end ) { if ( !isdefined( end ) ) { end = start; start = 0; } AssertEx( IsDefined( start ) && IsDefined( end ), "Waitspread was called without defining amount of time" ); // temporarily disabling waitspread until I have time to fix it properly wait( RandomFloatRange( start, end ) ); if ( 1 ) return; personal_wait_index = undefined; if ( !isdefined( level.active_wait_spread ) ) { // the first guy sets it up and runs the master logic. Thread it off in case he dies level.active_wait_spread = true; level.wait_spreaders = 0; personal_wait_index = level.wait_spreaders; level.wait_spreaders++; thread waitSpread_code( start, end ); } else { personal_wait_index = level.wait_spreaders; level.wait_spreaders++; waittillframeend;// give every other waitspreader in this frame a chance to increment wait_spreaders } waittillframeend;// wait for the logic to setup the waits wait( level.wait_spreader_allotment[ personal_wait_index ] ); } /* ============= ///ScriptDocBegin "Name: wait_for_buffer_time_to_pass( <start_time> , <buffer_time> )" "Summary: Wait until the current time is equal or greater than the start_time (in ms) + buffer_time (in seconds)" "Module: Utility" "MandatoryArg: <start_time>: The GetTime() at the start of the scene." "MandatoryArg: <buffer_time>: The amount of time you want to insure has passed since start_time." "Example: wait_for_buffer_time_to_pass( level.last_time_we_checked, 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_buffer_time_to_pass( last_queue_time, buffer_time ) { timer = buffer_time * 1000 - ( GetTime() - last_queue_time ); timer *= 0.001; if ( timer > 0 ) { // 500ms buffer time between radio or dialogue sounds wait( timer ); } } bcs_scripted_dialogue_start() { anim.scriptedDialogueStartTime = GetTime(); } /* ============= ///ScriptDocBegin "Name: dialogue_queue( <msg> )" "Summary: Plays an anim_single_queue on the guy, with the guy as the actor" "Module: Utility" "CallOn: An ai" "MandatoryArg: <msg>: The dialogue scene, defined as level.scr_sound[ guys.animname ][ "scene" ] " "Example: level.price dialogue_queue( "nice_find_macgregor" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ dialogue_queue( msg ) { bcs_scripted_dialogue_start(); self maps\_anim::anim_single_queue( self, msg ); } /* ============= ///ScriptDocBegin "Name: generic_dialogue_queue( <msg>, <timeout> )" "Summary: Plays an anim_generic_queue on the guy, with the guy as the actor" "Module: Utility" "CallOn: An ai" "MandatoryArg: <msg>: The dialogue scene, defined as level.scr_sound[ "generic" ][ "scene" ] " "OptionalArg: <timeout>: optional timeout to forget the radio dialogue if it's been in the queue for longer than this many seconds" "Example: level.price dialogue_queue( "nice_find_macgregor" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ generic_dialogue_queue( msg, timeout ) { bcs_scripted_dialogue_start(); self maps\_anim::anim_generic_queue( self, msg, undefined, undefined, timeout ); } /* ============= ///ScriptDocBegin "Name: radio_dialogue( <msg> )" "Summary: puts radio dialogue into a queue. Dialogue plays when it gets it's turn in the queue." "Module: Utility" "MandatoryArg: <msg>: the radio dialogue alias to play" "OptionalArg: <timeout>: optional timeout to forget the radio dialogue if it's been in the queue for longer than this many seconds" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ radio_dialogue( msg, timeout ) { AssertEx( IsDefined( level.scr_radio[ msg ] ), "Tried to play radio dialogue " + msg + " that did not exist! Add it to level.scr_radio" ); //this is so we have a universal entity to stack radio dialogue on without worrying about //any other scripts dirtying up the stack with functions not related to radio_dialogue if ( !isdefined( level.player_radio_emitter ) ) { ent = Spawn( "script_origin", ( 0, 0, 0 ) ); ent LinkTo( level.player, "", ( 0, 0, 0 ), ( 0, 0, 0 ) ); level.player_radio_emitter = ent; } bcs_scripted_dialogue_start(); success = false; if ( !IsDefined( timeout ) ) { success = level.player_radio_emitter function_stack( ::play_sound_on_tag, level.scr_radio[ msg ], undefined, true ); } else { success = level.player_radio_emitter function_stack_timeout( timeout, ::play_sound_on_tag, level.scr_radio[ msg ], undefined, true ); } return success; } /* ============= ///ScriptDocBegin "Name: radio_dialogue_overlap( <msg> )" "Summary: Play a radio dialogue sound on top of whatever radio dialogue is currently playing (overlapping)." "Module: Utility" "MandatoryArg: <msg>: The dialogue alias" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ radio_dialogue_overlap( msg ) { AssertEx( IsDefined( level.scr_radio[ msg ] ), "Tried to play radio dialogue " + msg + " that did not exist! Add it to level.scr_radio" ); AssertEx( IsDefined( level.player_radio_emitter ), "Tried to overlap dialogue but no radio dialogue was playing, use radio_dialogue." ); level.player_radio_emitter play_sound_on_tag( level.scr_radio[ msg ], undefined, true ); } /* ============= ///ScriptDocBegin "Name: radio_dialogue_stop()" "Summary: Stops any radio dialogue currently playing and Stops any further radio dialogue queued up from playing ( removes those requests from the queue )" "Module: Utility" "Example: radio_dialogue_stop();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ radio_dialogue_stop() { if ( !isdefined( level.player_radio_emitter ) ) return; //level.player_radio_emitter function_stack_clear(); ->don't need it - kills the funciton stack already level.player_radio_emitter Delete(); } /* ============= ///ScriptDocBegin "Name: radio_dialogue_clear_stack()" "Summary: Stops any further radio dialogue queued up from playing ( removes those requests from the queue )" "Module: Utility" "Example: radio_dialogue_clear_stack();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ radio_dialogue_clear_stack() { if ( !isdefined( level.player_radio_emitter ) ) return; level.player_radio_emitter function_stack_clear(); } /* ============= ///ScriptDocBegin "Name: radio_dialogue_interupt( <msg> )" "Summary: plays a radio dialogue line and oversteps any previous radio dialogue being played (doesn't stop any previous dialogue being played )" "Module: Utility" "MandatoryArg: <msg>: the radio dialogue alias to play" "Example: radio_dialogue_interupt( "shutup" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ radio_dialogue_interupt( msg ) { AssertEx( IsDefined( level.scr_radio[ msg ] ), "Tried to play radio dialogue " + msg + " that did not exist! Add it to level.scr_radio" ); if ( !isdefined( level.player_radio_emitter ) ) { ent = Spawn( "script_origin", ( 0, 0, 0 ) ); ent LinkTo( level.player, "", ( 0, 0, 0 ), ( 0, 0, 0 ) ); level.player_radio_emitter = ent; } level.player_radio_emitter play_sound_on_tag( level.scr_radio[ msg ], undefined, true ); } /* ============= ///ScriptDocBegin "Name: radio_dialogue_safe( <msg> )" "Summary: trys to play a radio dialogue line - only plays if there is no other radio dialogue playing" "Module: Utility" "MandatoryArg: <msg>: the radio dialogue alias to play" "Example: radio_dialogue_interupt( "shutup_please" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ radio_dialogue_safe( msg ) { return radio_dialogue( msg, .05 ); } /////////////////////// DELETE ME //////////////////////// radio_dialogue_queue( msg ) { radio_dialogue( msg ); } // HUD ELEMENT STUFF hint_create( text, background, backgroundAlpha ) { struct = SpawnStruct(); if ( IsDefined( background ) && background == true ) struct.bg = NewHudElem(); struct.elm = NewHudElem(); struct hint_position_internal( backgroundAlpha ); // elm.label = struct.text; // elm.debugtext = struct.text; struct.elm SetText( text ); return struct; } hint_delete() { self notify( "death" ); if ( IsDefined( self.elm ) ) self.elm Destroy(); if ( IsDefined( self.bg ) ) self.bg Destroy(); } hint_position_internal( bgAlpha ) { if ( level.console ) self.elm.fontScale = 2; else self.elm.fontScale = 1.6; self.elm.x = 0; self.elm.y = -40; self.elm.alignX = "center"; self.elm.alignY = "bottom"; self.elm.horzAlign = "center"; self.elm.vertAlign = "middle"; self.elm.sort = 1; self.elm.alpha = 0.8; if ( !isdefined( self.bg ) ) return; self.bg.x = 0; self.bg.y = -40; self.bg.alignX = "center"; self.bg.alignY = "middle"; self.bg.horzAlign = "center"; self.bg.vertAlign = "middle"; self.bg.sort = -1; if ( level.console ) self.bg SetShader( "popmenu_bg", 650, 52 ); else self.bg SetShader( "popmenu_bg", 650, 42 ); if ( !isdefined( bgAlpha ) ) bgAlpha = 0.5; self.bg.alpha = bgAlpha; } /* ============= ///ScriptDocBegin "Name: string( <num> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ string( num ) { return( "" + num ); } ignoreEachOther( group1, group2 ) { // these threatbias groups ignore each other AssertEx( ThreatBiasGroupExists( group1 ), "Tried to make threatbias group " + group1 + " ignore " + group2 + " but " + group1 + " does not exist!" ); AssertEx( ThreatBiasGroupExists( group2 ), "Tried to make threatbias group " + group2 + " ignore " + group1 + " but " + group2 + " does not exist!" ); SetIgnoreMeGroup( group1, group2 ); SetIgnoreMeGroup( group2, group1 ); } /* ============= ///ScriptDocBegin "Name: add_global_spawn_function( <team> , <func> , <param1> , <param2> , <param3> )" "Summary: All spawners of this team will run this function on spawn." "Module: Utility" "MandatoryArg: <team> : The team of the spawners that will run this function." "MandatoryArg: <func> : The function to run." "OptionalArg: <param1> : An optional parameter." "OptionalArg: <param2> : An optional parameter." "OptionalArg: <param3> : An optional parameter." "Example: add_global_spawn_function( "axis", ::do_the_amazing_thing, some_amazing_parameter );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_global_spawn_function( team, function, param1, param2, param3 ) { AssertEx( IsDefined( level.spawn_funcs ), "Tried to add_global_spawn_function before calling _load" ); func = []; func[ "function" ] = function; func[ "param1" ] = param1; func[ "param2" ] = param2; func[ "param3" ] = param3; level.spawn_funcs[ team ][ level.spawn_funcs[ team ].size ] = func; } /* ============= ///ScriptDocBegin "Name: remove_global_spawn_function( <team> , <func> )" "Summary: Remove this function from the global spawn functions for this team." "Module: Utility" "MandatoryArg: <team> : The team of the spawners that will no longer run this function." "MandatoryArg: <func> : The function to remove." "Example: remove_global_spawn_function( "allies", ::do_the_amazing_thing );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_global_spawn_function( team, function ) { AssertEx( IsDefined( level.spawn_funcs ), "Tried to remove_global_spawn_function before calling _load" ); array = []; for ( i = 0; i < level.spawn_funcs[ team ].size; i++ ) { if ( level.spawn_funcs[ team ][ i ][ "function" ] != function ) { array[ array.size ] = level.spawn_funcs[ team ][ i ]; } } //assertEx( level.spawn_funcs[ team ].size != array.size, "Tried to remove a function from level.spawn_funcs, but that function didn't exist!" ); level.spawn_funcs[ team ] = array; } /* ============= ///ScriptDocBegin "Name: exists_global_spawn_function( <team> , <func> )" "Summary: Check if thisfunction from the global spawn functions for this team exists. Returns true or false." "Module: Utility" "MandatoryArg: <team> : The team of the spawners that will no longer run this function." "MandatoryArg: <func> : The function to remove." "Example: if ( exists_global_spawn_function( "allies", ::do_the_amazing_thing ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ exists_global_spawn_function( team, function ) { if ( !isdefined( level.spawn_funcs ) ) return false; for ( i = 0; i < level.spawn_funcs[ team ].size; i++ ) { if ( level.spawn_funcs[ team ][ i ][ "function" ] == function ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: remove_spawn_function( <func> )" "Summary: Remove this spawn function from this spawner." "Module: Utility" "MandatoryArg: <func1> : The function to remove." "Example: spawner remove_spawn_function( ::do_the_amazing_thing );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_spawn_function( function ) { AssertEx( !isalive( self ), "Tried to remove_spawn_function to a living guy." ); AssertEx( IsSpawner( self ), "Tried to remove_spawn_function to something that isn't a spawner." ); AssertEx( IsDefined( self.spawn_functions ), "Tried to remove_spawn_function before calling _load" ); new_spawn_functions = []; foreach ( func_array in self.spawn_functions ) { if ( func_array[ "function" ] == function ) continue; new_spawn_functions[ new_spawn_functions.size ] = func_array; } self.spawn_functions = new_spawn_functions; } /* ============= ///ScriptDocBegin "Name: add_spawn_function( <func> , <param1> , <param2> , <param3>, <param4>, <param5> )" "Summary: Anything that spawns from this spawner will run this function. Anything." "Module: Utility" "MandatoryArg: <func1> : The function to run." "OptionalArg: <param1> : An optional parameter." "OptionalArg: <param2> : An optional parameter." "OptionalArg: <param3> : An optional parameter." "OptionalArg: <param4> : An optional parameter." "OptionalArg: <param5> : An optional parameter." "Example: spawner add_spawn_function( ::do_the_amazing_thing, some_amazing_parameter );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_spawn_function( function, param1, param2, param3, param4, param5 ) { AssertEx( !isalive( self ), "Tried to add_spawn_function to a living guy." ); AssertEx( IsSpawner( self ), "Tried to add_spawn_function to something that isn't a spawner." ); AssertEx( IsDefined( self.spawn_functions ), "Tried to add_spawn_function before calling _load" ); foreach ( func_array in self.spawn_functions ) { if ( func_array[ "function" ] == function ) return; } func = []; func[ "function" ] = function; func[ "param1" ] = param1; func[ "param2" ] = param2; func[ "param3" ] = param3; func[ "param4" ] = param4; func[ "param5" ] = param5; self.spawn_functions[ self.spawn_functions.size ] = func; } /* ============= ///ScriptDocBegin "Name: array_delete( <array> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_delete( array ) { for ( i = 0; i < array.size; i++ ) { array[ i ] Delete(); } } ignore_triggers( timer ) { // ignore triggers for awhile so others can trigger the trigger we're in. self endon( "death" ); self.ignoreTriggers = true; if ( IsDefined( timer ) ) { wait( timer ); } else { wait( 0.5 ); } self.ignoreTriggers = false; } /* ============= ///ScriptDocBegin "Name: activate_trigger_with_targetname( <name> )" "Summary: Notifies a trigger of 'trigger'" "Module: Trigger" "MandatoryArg: <name>: string get the entity that has a targetname of <name>" "Example: activate_trigger_with_targetname( "red_team1" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ activate_trigger_with_targetname( msg ) { trigger = GetEnt( msg, "targetname" ); trigger activate_trigger(); } /* ============= ///ScriptDocBegin "Name: activate_trigger_with_noteworthy( <name> )" "Summary: Notifies a trigger of 'trigger'" "Module: Trigger" "MandatoryArg: <name>: string get the entity that has a script_noteworthy of <name>" "Example: activate_trigger_with_noteworthy( "red_team1" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ activate_trigger_with_noteworthy( msg ) { trigger = GetEnt( msg, "script_noteworthy" ); trigger activate_trigger(); } /* ============= ///ScriptDocBegin "Name: disable_trigger_with_targetname( <name> )" "Summary: calls trigger_off() on a trigger with targetname of <name>" "Module: Trigger" "MandatoryArg: <name>: string get the entity that has a targetname of <name>" "Example: disable_trigger_with_targetname( "red_team1" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_trigger_with_targetname( msg ) { trigger = GetEnt( msg, "targetname" ); trigger trigger_off(); } /* ============= ///ScriptDocBegin "Name: disable_trigger_with_noteworthy( <name> )" "Summary: calls trigger_off() on a trigger with script_noteworthy of <name>" "Module: Trigger" "MandatoryArg: <name>: string get the entity that has a script_noteworthy of <name>" "Example: disable_trigger_with_noteworthy( "red_team1" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_trigger_with_noteworthy( msg ) { trigger = GetEnt( msg, "script_noteworthy" ); trigger trigger_off(); } /* ============= ///ScriptDocBegin "Name: is_hero()" "Summary: check to see if AI is a hero" "Module: AI" "Example: level.price ishero()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_hero() { return IsDefined( level.hero_list[ get_ai_number() ] ); } /* ============= ///ScriptDocBegin "Name: get_ai_number()" "Summary: gets an AI's ai number" "Module: AI" "Example: num = level.price get_ai_number()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_ai_number() { if ( !isdefined( self.unique_id ) ) { set_ai_number(); } return self.unique_id; } /* ============= ///ScriptDocBegin "Name: set_ai_number( <set_ai_number> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_ai_number() { self.unique_id = "ai" + level.ai_number; level.ai_number++; } /* ============= ///ScriptDocBegin "Name: make_hero()" "Summary: makes an AI a hero" "Module: AI" "Example: level.price make_hero()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ make_hero() { level.hero_list[ self.unique_id ] = true; } /* ============= ///ScriptDocBegin "Name: unmake_hero()" "Summary: makes an AI not a hero" "Module: " "Example: level.price unmake_hero()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ unmake_hero() { level.hero_list[ self.unique_id ] = undefined; } /* ============= ///ScriptDocBegin "Name: get_heroes()" "Summary: returns an array of hero AI" "Module: " "Example: level.heros = get_heroes()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_heroes() { array = []; ai = GetAIArray( "allies" ); for ( i = 0; i < ai.size; i++ ) { if ( ai[ i ] is_hero() ) array[ array.size ] = ai[ i ]; } return array; } /* ============= ///ScriptDocBegin "Name: set_team_pacifist( <team> , <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_team_pacifist( team, val ) { ai = GetAIArray( team ); for ( i = 0; i < ai.size; i++ ) { ai[ i ].pacifist = val; } } /* ============= ///ScriptDocBegin "Name: replace_on_death()" "Summary: Color friendlies that run this will be replaced when they die" "Module: Utility" "CallOn: A friendly" "Example: red_shirt thread replace_on_death(); // poor guy" "SPMP: singleplayer" ///ScriptDocEnd ============= */ replace_on_death() { // kill with either: // level notify( "kill_color_replacements" ); // or // self notify( "_disable_reinforcement" ); maps\_colors::colorNode_replace_on_death(); } spawn_reinforcement( classname, color ) { maps\_colors::colorNode_spawn_reinforcement( classname, color ); } clear_promotion_order() { level.current_color_order = []; } set_promotion_order( deadguy, replacer ) { if ( !isdefined( level.current_color_order ) ) { level.current_color_order = []; } deadguy = shortenColor( deadguy ); replacer = shortenColor( replacer ); level.current_color_order[ deadguy ] = replacer; // if there is no color order for the replacing color than // let script assume that it is meant to be replaced by // respawning guys if ( !isdefined( level.current_color_order[ replacer ] ) ) set_empty_promotion_order( replacer ); } set_empty_promotion_order( deadguy ) { if ( !isdefined( level.current_color_order ) ) { level.current_color_order = []; } level.current_color_order[ deadguy ] = "none"; } /* ============= ///ScriptDocBegin "Name: remove_dead_from_array( <array> )" "Summary: remove_dead_from_array" "Module: " "Example: array = remove_dead_from_array( array )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_dead_from_array( array ) { newarray = []; foreach ( item in array ) { if ( !isalive( item ) ) continue; newarray[ newarray.size ] = item; } return newarray; } /* ============= ///ScriptDocBegin "Name: remove_heroes_from_array( <array> )" "Summary: remove_heroes_from_array" "Module: " "Example: array = remove_heroes_from_array( array )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_heroes_from_array( array ) { newarray = []; for ( i = 0; i < array.size; i++ ) { if ( array[ i ] is_hero() ) continue; newarray[ newarray.size ] = array[ i ]; } return newarray; } /* ============= ///ScriptDocBegin "Name: remove_all_animnamed_guys_from_array( <array> )" "Summary: remove_all_animnamed_guys_from_array" "Module: " "Example: array = remove_all_animnamed_guys_from_array( array )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_all_animnamed_guys_from_array( array ) { newarray = []; for ( i = 0; i < array.size; i++ ) { if ( IsDefined( array[ i ].animname ) ) continue; newarray[ newarray.size ] = array[ i ]; } return newarray; } /* ============= ///ScriptDocBegin "Name: remove_color_from_array( <array> , <color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_color_from_array( array, color ) { newarray = []; for ( i = 0; i < array.size; i++ ) { guy = array[ i ]; if ( !isdefined( guy.script_forcecolor ) ) continue; if ( guy.script_forcecolor == color ) continue; newarray[ newarray.size ] = guy; } return newarray; } /* ============= ///ScriptDocBegin "Name: remove_noteworthy_from_array( <array> , <noteworthy> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_noteworthy_from_array( array, noteworthy ) { newarray = []; for ( i = 0; i < array.size; i++ ) { guy = array[ i ]; if ( !isdefined( guy.script_noteworthy ) ) continue; if ( guy.script_noteworthy == noteworthy ) continue; newarray[ newarray.size ] = guy; } return newarray; } /* ============= ///ScriptDocBegin "Name: get_closest_colored_friendly( <color> , <origin> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_colored_friendly( color, origin ) { allies = get_force_color_guys( "allies", color ); allies = remove_heroes_from_array( allies ); if ( !isdefined( origin ) ) friendly_origin = level.player.origin; else friendly_origin = origin; return getClosest( friendly_origin, allies ); } /* ============= ///ScriptDocBegin "Name: remove_without_classname( <array> , <classname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_without_classname( array, classname ) { newarray = []; for ( i = 0; i < array.size; i++ ) { if ( !issubstr( array[ i ].classname, classname ) ) continue; newarray[ newarray.size ] = array[ i ]; } return newarray; } /* ============= ///ScriptDocBegin "Name: remove_without_model( <array> , <model> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_without_model( array, model ) { newarray = []; for ( i = 0; i < array.size; i++ ) { if ( !issubstr( array[ i ].model, model ) ) continue; newarray[ newarray.size ] = array[ i ]; } return newarray; } /* ============= ///ScriptDocBegin "Name: get_closest_colored_friendly_with_classname( <color> , <classname> , <origin> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_closest_colored_friendly_with_classname( color, classname, origin ) { allies = get_force_color_guys( "allies", color ); allies = remove_heroes_from_array( allies ); if ( !isdefined( origin ) ) friendly_origin = level.player.origin; else friendly_origin = origin; allies = remove_without_classname( allies, classname ); return getClosest( friendly_origin, allies ); } /* ============= ///ScriptDocBegin "Name: promote_nearest_friendly( <colorFrom> , <colorTo> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ promote_nearest_friendly( colorFrom, colorTo ) { for ( ;; ) { friendly = get_closest_colored_friendly( colorFrom ); if ( !isalive( friendly ) ) { wait( 1 ); continue; } friendly set_force_color( colorTo ); return; } } /* ============= ///ScriptDocBegin "Name: instantly_promote_nearest_friendly( <colorFrom> , <colorTo> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ instantly_promote_nearest_friendly( colorFrom, colorTo ) { for ( ;; ) { friendly = get_closest_colored_friendly( colorFrom ); if ( !isalive( friendly ) ) { AssertEx( 0, "Instant promotion from " + colorFrom + " to " + colorTo + " failed!" ); return; } friendly set_force_color( colorTo ); return; } } /* ============= ///ScriptDocBegin "Name: instantly_promote_nearest_friendly_with_classname( <colorFrom> , <colorTo> , <classname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ instantly_promote_nearest_friendly_with_classname( colorFrom, colorTo, classname ) { for ( ;; ) { friendly = get_closest_colored_friendly_with_classname( colorFrom, classname ); if ( !isalive( friendly ) ) { AssertEx( 0, "Instant promotion from " + colorFrom + " to " + colorTo + " failed!" ); return; } friendly set_force_color( colorTo ); return; } } /* ============= ///ScriptDocBegin "Name: promote_nearest_friendly_with_classname( <colorFrom> , <colorTo> , <classname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ promote_nearest_friendly_with_classname( colorFrom, colorTo, classname ) { for ( ;; ) { friendly = get_closest_colored_friendly_with_classname( colorFrom, classname ); if ( !isalive( friendly ) ) { wait( 1 ); continue; } friendly set_force_color( colorTo ); return; } } /* ============= ///ScriptDocBegin "Name: riotshield_lock_orientation( <yaw_angle> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ riotshield_lock_orientation( yaw_angle ) { self OrientMode( "face angle", yaw_angle ); self.lockOrientation = true; } /* ============= ///ScriptDocBegin "Name: riotshield_unlock_orientation( <riotshield_unlock_orientation> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ riotshield_unlock_orientation() { self.lockOrientation = false; } /* ============= ///ScriptDocBegin "Name: instantly_set_color_from_array_with_classname( <array> , <color> , <classname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ instantly_set_color_from_array_with_classname( array, color, classname ) { // the guy is removed from the array so the function can be run on the array again foundGuy = false; newArray = []; for ( i = 0; i < array.size; i++ ) { guy = array[ i ]; if ( foundGuy || !isSubstr( guy.classname, classname ) ) { newArray[ newArray.size ] = guy; continue; } foundGuy = true; guy set_force_color( color ); } return newArray; } /* ============= ///ScriptDocBegin "Name: instantly_set_color_from_array( <array> , <color> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ instantly_set_color_from_array( array, color ) { // the guy is removed from the array so the function can be run on the array again foundGuy = false; newArray = []; for ( i = 0; i < array.size; i++ ) { guy = array[ i ]; if ( foundGuy ) { newArray[ newArray.size ] = guy; continue; } foundGuy = true; guy set_force_color( color ); } return newArray; } /* ============= ///ScriptDocBegin "Name: wait_for_script_noteworthy_trigger( <msg> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_script_noteworthy_trigger( msg ) { wait_for_trigger( msg, "script_noteworthy" ); } /* ============= ///ScriptDocBegin "Name: wait_for_targetname_trigger( <msg> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_targetname_trigger( msg ) { wait_for_trigger( msg, "targetname" ); } /* ============= ///ScriptDocBegin "Name: wait_for_flag_or_timeout( <msg> , <timer> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_flag_or_timeout( msg, timer ) { if ( flag( msg ) ) return; ent = SpawnStruct(); ent thread ent_waits_for_level_notify( msg ); ent thread ent_times_out( timer ); ent waittill( "done" ); } /* ============= ///ScriptDocBegin "Name: wait_for_notify_or_timeout( <msg> , <timer> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_notify_or_timeout( msg, timer ) { ent = SpawnStruct(); ent thread ent_waits_for_notify( self, msg ); ent thread ent_times_out( timer ); ent waittill( "done" ); } /* ============= ///ScriptDocBegin "Name: wait_for_trigger_or_timeout( <timer> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_trigger_or_timeout( timer ) { ent = SpawnStruct(); ent thread ent_waits_for_trigger( self ); ent thread ent_times_out( timer ); ent waittill( "done" ); } /* ============= ///ScriptDocBegin "Name: wait_for_either_trigger( <msg1> , <msg2> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ wait_for_either_trigger( msg1, msg2 ) { ent = SpawnStruct(); array = []; array = array_combine( array, GetEntArray( msg1, "targetname" ) ); array = array_combine( array, GetEntArray( msg2, "targetname" ) ); for ( i = 0; i < array.size; i++ ) { ent thread ent_waits_for_trigger( array[ i ] ); } ent waittill( "done" ); } /* ============= ///ScriptDocBegin "Name: dronespawn_bodyonly( <spawner> )" "Summary: Create a drone body, doesn't take damage, die, etc." "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ dronespawn_bodyonly( spawner ) { drone = maps\_spawner::spawner_dronespawn( spawner ); Assert( IsDefined( drone ) ); return drone; } /* ============= ///ScriptDocBegin "Name: dronespawn( <spawner> )" "Summary: Create a drone, make it behave like AI" "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ dronespawn( spawner ) { if ( !isdefined( spawner ) ) spawner = self; drone = maps\_spawner::spawner_dronespawn( spawner ); Assert( IsDefined( drone ) ); AssertEx( IsDefined( level.drone_spawn_func ), "You need to put maps\_drone_civilian::init(); OR maps\_drone_ai::init(); in your level script! Use the civilian version if your drone is a civilian and the _ai version if it's a friendly or enemy." ); drone [[ level.drone_spawn_func ]](); drone.spawn_funcs = spawner.spawn_functions; drone thread maps\_spawner::run_spawn_functions(); return drone; } /* ============= ///ScriptDocBegin "Name: makerealai( <drone> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ makerealai( drone ) { return maps\_spawner::spawner_makerealai( drone ); } /* ============= ///ScriptDocBegin "Name: get_trigger_flag( <get_trigger_flag> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_trigger_flag() { if ( IsDefined( self.script_flag ) ) { return self.script_flag; } if ( IsDefined( self.script_noteworthy ) ) { return self.script_noteworthy; } AssertEx( 0, "Flag trigger at " + self.origin + " has no script_flag set." ); } set_default_pathenemy_settings() { self.pathenemylookahead = 192; self.pathenemyfightdist = 192; } /* ============= ///ScriptDocBegin "Name: cqb_walk( <on_or_off> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ cqb_walk( on_or_off )// ( deprecated ) { if ( on_or_off == "on" ) { self enable_cqbwalk(); } else { Assert( on_or_off == "off" ); self disable_cqbwalk(); } } /* ============= ///ScriptDocBegin "Name: enable_cqbwalk( <autoEnabled> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_cqbwalk( autoEnabled ) { if ( !isdefined( autoEnabled ) ) self.cqbEnabled = true; self.cqbwalking = true; self.turnRate = 0.2; level thread animscripts\cqb::findCQBPointsOfInterest(); /# self thread animscripts\cqb::CQBDebug(); #/ } /* ============= ///ScriptDocBegin "Name: disable_cqbwalk( <disable_cqbwalk> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_cqbwalk() { self.cqbwalking = undefined; self.cqbEnabled = undefined; self.turnRate = 0.3; self.cqb_point_of_interest = undefined; /# self notify( "end_cqb_debug" ); #/ } /* ============= ///ScriptDocBegin "Name: cqb_aim( <the_target> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ cqb_aim( the_target ) { if ( !isdefined( the_target ) ) { self.cqb_target = undefined; } else { self.cqb_target = the_target; if ( !isdefined( the_target.origin ) ) AssertMsg( "target passed into cqb_aim does not have an origin!" ); } } /* ============= ///ScriptDocBegin "Name: set_force_cover( <val> )" "Summary: true to be suppressed, false to turn off "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_force_cover( val ) { AssertEx( !isdefined( val ) || val == false || val == true, "invalid force cover set on guy" ); AssertEx( IsAlive( self ), "Tried to set force cover on a dead guy" ); if ( IsDefined( val ) && val ) self.forceSuppression = true; else self.forceSuppression = undefined; } /* ============= ///ScriptDocBegin "Name: do_in_order( <func1> , <param1> , <func2> , <param2> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ do_in_order( func1, param1, func2, param2 ) { if ( IsDefined( param1 ) ) [[ func1 ]]( param1 ); else [[ func1 ]](); if ( IsDefined( param2 ) ) [[ func2 ]]( param2 ); else [[ func2 ]](); } scrub() { // sets an AI to default settings, ignoring the .script_ values on him. self maps\_spawner::scrub_guy(); } /* ============= ///ScriptDocBegin "Name: send_notify( <msg> , <optional_param> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ send_notify( msg, optional_param ) { // functionalized so it can be function pointer'd if ( IsDefined( optional_param ) ) self notify( msg, optional_param ); else self notify( msg ); } /* ============= ///ScriptDocBegin "Name: waittill_match_or_timeout( <msg> , <match>, <timer> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_match_or_timeout( msg, match, timer ) { ent = SpawnStruct(); ent endon( "complete" ); ent delayThread( timer, ::send_notify, "complete" ); self waittillmatch( msg, match ); } deleteEnt( ent ) { // created so entities can be deleted using array_thread ent notify( "deleted" ); ent Delete(); } /* ============= ///ScriptDocBegin "Name: first_touch( <ent> )" "Summary: Returns true the first time this check is run against an entity." "Module: Utility" "CallOn: An entity that notifies trigger to a trigger." "MandatoryArg: <ent>: The ent that caused trigger to be notified " "Example: if ( first_touch( guy ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ first_touch( ent ) { if ( !isdefined( self.touched ) ) self.touched = []; AssertEx( IsDefined( ent ), "Ent is not defined!" ); AssertEx( IsDefined( ent.unique_id ), "Ent has no unique_id" ); if ( IsDefined( self.touched[ ent.unique_id ] ) ) return false; self.touched[ ent.unique_id ] = true; return true; } /* ============= ///ScriptDocBegin "Name: getanim( <anime> )" "Summary: Gets the animation referenced by the string for the animname of the caller" "Module: Animation" "CallOn: An entity that has an animname." "MandatoryArg: <anime> The animation scene. " "Example: animation = guy getanim( "run" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getanim( anime ) { AssertEx( IsDefined( self.animname ), "Called getanim on a guy with no animname" ); AssertEx( IsDefined( level.scr_anim[ self.animname ][ anime ] ), "Called getanim on an inexistent anim" ); return level.scr_anim[ self.animname ][ anime ]; } /* ============= ///ScriptDocBegin "Name: hasanim( <anime> )" "Summary: Returns whether a guy has the animation referenced by the string for the animname of the caller." "Module: Animation" "CallOn: An entity that has an animname." "MandatoryArg: <anime> The animation scene. " "Example: if( guy hasanim( "run" ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hasanim( anime ) { AssertEx( IsDefined( self.animname ), "Called getanim on a guy with no animname" ); return IsDefined( level.scr_anim[ self.animname ][ anime ] ); } /* ============= ///ScriptDocBegin "Name: getanim_from_animname( <anime> , <animname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getanim_from_animname( anime, animname ) { AssertEx( IsDefined( animname ), "Must supply an animname" ); AssertEx( IsDefined( level.scr_anim[ animname ][ anime ] ), "Called getanim on an inexistent anim" ); return level.scr_anim[ animname ][ anime ]; } /* ============= ///ScriptDocBegin "Name: getanim_generic( <anime> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getanim_generic( anime ) { AssertEx( IsDefined( level.scr_anim[ "generic" ][ anime ] ), "Called getanim_generic on an inexistent anim" ); return level.scr_anim[ "generic" ][ anime ]; } /* ============= ///ScriptDocBegin "Name: add_hint_string( <name> , <string> , <optionalFunc> )" "Summary: Adds a hint string that will be displayed with display_hint. The hint runs until the function returns true" "Module: Hint" "MandatoryArg: <name>: Name of the hint" "MandatoryArg: <string>: String to display for the hint" "MandatoryArg: <optionalFunc>: Draw the string until this function returns true." // Press^3 [{+actionslot 1}] ^7to disable Night Vision Goggles. "Example: add_hint_string( "disable_nvg", &"SCRIPT_NIGHTVISION_STOP_USE", maps\_nightvision::should_break_disable_nvg_print );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_hint_string( name, string, optionalFunc ) { if ( !isdefined( level.trigger_hint_string ) ) { level.trigger_hint_string = []; level.trigger_hint_func = []; } AssertEx( IsDefined( name ), "Set a name for the hint string. This should be the same as the script_hint on the trigger_hint." ); AssertEx( IsDefined( string ), "Set a string for the hint string. This is the string you want to appear when the trigger is hit." ); AssertEx( !isdefined( level.trigger_hint_string[ name ] ), "Tried to redefine hint " + name ); level.trigger_hint_string[ name ] = string; PreCacheString( string ); if ( IsDefined( optionalFunc ) ) { level.trigger_hint_func[ name ] = optionalFunc; } } show_hint( struct ) { AssertEx( IsDefined( struct.string ), "Need a localized string associated with the hint" ); thread ShowHintPrint_struct( struct ); } hide_hint( struct ) { struct.timeout = true; } fire_radius( origin, radius ) { /# if ( level.createFX_enabled ) return; #/ trigger = Spawn( "trigger_radius", origin, 0, radius, 48 ); for ( ;; ) { trigger waittill( "trigger", other ); AssertEx( IsPlayer( other ), "Tried to burn a non player in a fire" ); level.player DoDamage( 5, origin ); } } clearThreatBias( group1, group2 ) { SetThreatBias( group1, group2, 0 ); SetThreatBias( group2, group1, 0 ); } scr_println( msg ) { // so println can be called from a function pointer PrintLn( msg ); } // use in moderation! ThrowGrenadeAtPlayerASAP() { animscripts\combat_utility::ThrowGrenadeAtPlayerASAP_combat_utility(); } /* ============= ///ScriptDocBegin "Name: array_combine_keys( <array1> , <keys> , <keys> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_combine_keys( array1, array2 )// mashes them in. array 2 will overwrite like keys, this works for what I'm using it for - Nate. { if ( !array1.size ) return array2; keys = GetArrayKeys( array2 ); for ( i = 0; i < keys.size; i++ ) array1[ keys[ i ] ] = array2[ keys[ i ] ]; return array1; } /* ============= ///ScriptDocBegin "Name: set_ignoreSuppression( <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_ignoreSuppression( val ) { self.ignoreSuppression = val; } /* ============= ///ScriptDocBegin "Name: set_goalradius( <radius> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goalradius( radius ) { self.goalradius = radius; } try_forever_spawn() { export = self.export; for ( ;; ) { AssertEx( IsDefined( self ), "Spawner with export " + export + " was deleted." ); guy = self DoSpawn(); if ( spawn_failed( guy ) ) { wait( 1 ); continue; } return guy; } } /* ============= ///ScriptDocBegin "Name: set_allowdeath( <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_allowdeath( val ) { self.allowdeath = val; } /* ============= ///ScriptDocBegin "Name: set_run_anim( <anime> , <alwaysRunForward> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_run_anim( anime, alwaysRunForward ) { AssertEx( IsDefined( anime ), "Tried to set run anim but didn't specify which animation to ues" ); AssertEx( IsDefined( self.animname ), "Tried to set run anim on a guy that had no anim name" ); AssertEx( IsDefined( level.scr_anim[ self.animname ][ anime ] ), "Tried to set run anim but the anim was not defined in the maps _anim file" ); //this is good for slower run animations like patrol walks if ( IsDefined( alwaysRunForward ) ) self.alwaysRunForward = alwaysRunForward; else self.alwaysRunForward = true; self disable_turnAnims(); self.run_overrideanim = level.scr_anim[ self.animname ][ anime ]; self.walk_overrideanim = self.run_overrideanim; } /* ============= ///ScriptDocBegin "Name: set_dog_walk_anim( <set_dog_walk_anim> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_dog_walk_anim() { AssertEx( self.type == "dog" ); self.a.movement = "walk"; self.disablearrivals = true; self.disableexits = true; self.script_nobark = 1; } /* ============= ///ScriptDocBegin "Name: set_combat_stand_animset( <fire>, <aim_straight>, <idle>, <reload> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_combat_stand_animset( fire_anim, aim_straight, idle_anim, reload_anim ) { self animscripts\animset::init_animset_custom_stand( fire_anim, aim_straight, idle_anim, reload_anim ); } /* ============= ///ScriptDocBegin "Name: set_move_animset( <move_mode>, <move_anim>, <sprint_anim> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_move_animset( move_mode, move_anim, sprint_anim ) { AssertEx( IsDefined( anim.animsets.move[ move_mode ] ), "Default anim set is not defined" ); // init with defaults animset = anim.animsets.move[ move_mode ]; if ( IsArray( move_anim ) ) { Assert( move_anim.size == 4 ); animset[ "straight" ] = move_anim[ 0 ]; animset[ "move_f" ] = move_anim[ 0 ]; animset[ "move_l" ] = move_anim[ 1 ]; animset[ "move_r" ] = move_anim[ 2 ]; animset[ "move_b" ] = move_anim[ 3 ]; } else { animset[ "straight" ] = move_anim; animset[ "move_f" ] = move_anim; } if ( IsDefined( sprint_anim ) ) animset[ "sprint" ] = sprint_anim; self.customMoveAnimSet[ move_mode ] = animset; } /* ============= ///ScriptDocBegin "Name: set_generic_idle_anim( <anime> )" "Summary: Sets the override idle anim, needs to be set each time he idles" "Module: Utility" "CallOn: An ai" "MandatoryArg: <anime>: The idle scene " "Example: guy set_idle_anim( "yay" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_generic_idle_anim( anime ) { AssertEx( IsDefined( anime ), "Tried to set generic idle but didn't specify which animation to ues" ); AssertEx( IsDefined( level.scr_anim[ "generic" ][ anime ] ), "Tried to set generic run anim but the anim was not defined in the maps _anim file" ); idleAnim = level.scr_anim[ "generic" ][ anime ]; if ( IsArray( idleAnim ) ) self.specialIdleAnim = idleAnim; else self.specialIdleAnim[ 0 ] = idleAnim; } /* ============= ///ScriptDocBegin "Name: set_idle_anim( <anime> )" "Summary: Sets the override idle anim, needs to be set each time he idles" "Module: Utility" "CallOn: An ai" "MandatoryArg: <anime>: The idle scene " "Example: guy set_idle_anim( "yay" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_idle_anim( anime ) { AssertEx( IsDefined( self.animname ), "No animname!" ); AssertEx( IsDefined( anime ), "Tried to set idle anim but didn't specify which animation to ues" ); AssertEx( IsDefined( level.scr_anim[ self.animname ][ anime ] ), "Tried to set generic run anim but the anim was not defined in the maps _anim file" ); idleAnim = level.scr_anim[ self.animname ][ anime ]; if ( IsArray( idleAnim ) ) self.specialIdleAnim = idleAnim; else self.specialIdleAnim[ 0 ] = idleAnim; } /* ============= ///ScriptDocBegin "Name: clear_generic_idle_anim()" "Summary: " "Module: Entity" "CallOn: An entity" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ clear_generic_idle_anim() { self.specialIdleAnim = undefined; self notify( "stop_specialidle" ); } /* ============= ///ScriptDocBegin "Name: set_generic_run_anim( <anime> , <alwaysRunForward> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_generic_run_anim( anime, alwaysRunForward ) { AssertEx( IsDefined( anime ), "Tried to set generic run anim but didn't specify which animation to ues" ); AssertEx( IsDefined( level.scr_anim[ "generic" ][ anime ] ), "Tried to set generic run anim but the anim was not defined in the maps _anim file" ); self notify( "movemode" ); //this is good for slower run animations like patrol walks if ( !isdefined( alwaysRunForward ) || alwaysRunForward ) self.alwaysRunForward = true; else self.alwaysRunForward = undefined; self disable_turnAnims(); self.run_overrideanim = level.scr_anim[ "generic" ][ anime ]; self.walk_overrideanim = self.run_overrideanim; } /* ============= ///ScriptDocBegin "Name: set_generic_run_anim_array( <array>, <weights>, <alwaysRunForward> )" "Summary: " "Module: AI" "CallOn: An AI" "MandatoryArg: <string anime>: index to an array of run cycles (run cycle and twitches) to pass" "OptionalArg: <string weights>: relative weights of animation variations, if not specified, all are equal" "OptionalArg: <alwaysRunForward>: bool to always face in the direction of motion or not" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_generic_run_anim_array( anime, weights, alwaysRunForward ) { AssertEx( IsDefined( anime ), "Tried to set generic run anim but didn't specify which animation to ues" ); AssertEx( IsDefined( level.scr_anim[ "generic" ][ anime ] ), "Tried to set generic run anim but the anim was not defined in the maps _anim file" ); self notify( "movemode" ); //this is good for slower run animations like patrol walks if ( !isdefined( alwaysRunForward ) || alwaysRunForward ) self.alwaysRunForward = true; else self.alwaysRunForward = undefined; self disable_turnAnims(); self.run_overrideanim = level.scr_anim[ "generic" ][ anime ]; self.walk_overrideanim = self.run_overrideanim; if ( IsDefined( weights ) ) { self.run_override_weights = level.scr_anim[ "generic" ][ weights ]; self.walk_override_weights = self.run_override_weights; } else { self.run_override_weights = undefined; self.walk_override_weights = undefined; } } /* ============= ///ScriptDocBegin "Name: set_run_anim_array( <array>, <weights>, <alwaysRunForward> )" "Summary: " "Module: AI" "CallOn: An AI" "MandatoryArg: <string anime>: index to an array of run cycles (run cycle and twitches) to pass" "OptionalArg: <string weights>: relative weights of animation variations, if not specified, all are equal" "OptionalArg: <alwaysRunForward>: bool to always face in the direction of motion or not" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_run_anim_array( anime, weights, alwaysRunForward ) { AssertEx( IsDefined( anime ), "Tried to set generic run anim but didn't specify which animation to ues" ); AssertEx( IsDefined( self.animname ), "Tried to set run anim on a guy that had no anim name" ); AssertEx( IsDefined( level.scr_anim[ self.animname ][ anime ] ), "Tried to set run anim but the anim was not defined in the maps _anim file" ); self notify( "movemode" ); //this is good for slower run animations like patrol walks if ( !isdefined( alwaysRunForward ) || alwaysRunForward ) self.alwaysRunForward = true; else self.alwaysRunForward = undefined; self disable_turnAnims(); self.run_overrideanim = level.scr_anim[ self.animname ][ anime ]; self.walk_overrideanim = self.run_overrideanim; if ( IsDefined( weights ) ) { self.run_override_weights = level.scr_anim[ self.animname ][ weights ]; self.walk_override_weights = self.run_override_weights; } else { self.run_override_weights = undefined; self.walk_override_weights = undefined; } } /* ============= ///ScriptDocBegin "Name: clear_run_anim( <clear_run_anim> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ clear_run_anim() { self notify( "clear_run_anim" ); self notify( "movemode" ); if ( self.type == "dog" ) { self.a.movement = "run"; self.disablearrivals = false; self.disableexits = false; self.script_nobark = undefined; return; } if ( !isdefined( self.casual_killer ) ) self enable_turnAnims(); self.alwaysRunForward = undefined; self.run_overrideanim = undefined; self.walk_overrideanim = undefined; self.run_override_weights = undefined; self.walk_override_weights = undefined; } debugvar( msg, timer ) { SetDvarIfUninitialized( msg, timer ); return GetDvarFloat( msg ); } physicsjolt_proximity( outer_radius, inner_radius, force ) { // Usage: <entity > thread physicjolt_proximity( 400, 256, ( 0, 0, 0.1 ) ); self endon( "death" ); self endon( "stop_physicsjolt" ); if ( !isdefined( outer_radius ) || !isdefined( inner_radius ) || !isdefined( force ) ) { outer_radius = 400; inner_radius = 256; force = ( 0, 0, 0.075 ); // no direction on this one. } fade_distance = outer_radius * outer_radius; fade_speed = 3; base_force = force; while ( true ) { wait 0.1; force = base_force; if ( self.code_classname == "script_vehicle" ) { speed = self Vehicle_GetSpeed(); if ( speed < fade_speed ) { scale = speed / fade_speed; force = vector_multiply( base_force, scale ); } } dist = DistanceSquared( self.origin, level.player.origin ); scale = fade_distance / dist; if ( scale > 1 ) scale = 1; force = vector_multiply( force, scale ); total_force = force[ 0 ] + force[ 1 ] + force[ 2 ]; if ( total_force > 0.025 ) PhysicsJitter( self.origin, outer_radius, inner_radius, force[ 2 ], force[ 2 ] * 2.0 ); } } /* ============= ///ScriptDocBegin "Name: set_goal_entity( <ent> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goal_entity( ent ) { self SetGoalEntity( ent ); } /* ============= ///ScriptDocBegin "Name: activate_trigger( <name> , <type> )" "Summary: Notifies a trigger of 'trigger'" "Module: Trigger" "MandatoryArg: <name>: string to get the entity with" "MandatoryArg: <type>: type that string refers to (ie. targetname, script_noteworthy, target )" "Example: activate_trigger( "red_team1", "targetname" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ activate_trigger( name, type, triggeringEnt ) { if ( !isdefined( name ) ) self activate_trigger_process( triggeringEnt ); else array_thread( GetEntArray( name, type ), ::activate_trigger_process, triggeringEnt ); } activate_trigger_process( triggeringEnt ) { AssertEx( !isdefined( self.trigger_off ), "Tried to activate trigger that is OFF( either from trigger_off or from flags set on it through shift - G menu" ); if ( IsDefined( self.script_color_allies ) ) { // so we don't run activate_color_trigger twice, we set this var self.activated_color_trigger = true; maps\_colors::activate_color_trigger( "allies" ); } if ( IsDefined( self.script_color_axis ) ) { // so we don't run activate_color_trigger twice, we set this var self.activated_color_trigger = true; maps\_colors::activate_color_trigger( "axis" ); } self notify( "trigger", triggeringEnt ); /* if ( self.classname != "trigger_friendlychain" ) return; node = GetNode( self.target, "targetname" ); AssertEx( IsDefined( node ), "Trigger_friendlychain at " + self.origin + " doesn't target a node" ); level.player SetFriendlyChain( node ); */ } /* ============= ///ScriptDocBegin "Name: self_delete()" "Summary: Just calls the Delete() script command on self. Reason for this is so that we can use array_thread to delete entities" "Module: Entity" "CallOn: An entity" "Example: ai[ 0 ] thread self_delete();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ self_delete() { self Delete(); } remove_noColor_from_array( ai ) { newarray = []; for ( i = 0; i < ai.size; i++ ) { guy = ai[ i ]; if ( guy has_color() ) newarray[ newarray.size ] = guy; } return newarray; } has_color() { // can lose color during the waittillframeend in left_color_node if ( self maps\_colors::get_team() == "axis" ) { return IsDefined( self.script_color_axis ) || IsDefined( self.script_forcecolor ); } return IsDefined( self.script_color_allies ) || IsDefined( self.script_forcecolor ); } clear_colors() { clear_team_colors( "axis" ); clear_team_colors( "allies" ); } clear_team_colors( team ) { level.currentColorForced[ team ][ "r" ] = undefined; level.currentColorForced[ team ][ "b" ] = undefined; level.currentColorForced[ team ][ "c" ] = undefined; level.currentColorForced[ team ][ "y" ] = undefined; level.currentColorForced[ team ][ "p" ] = undefined; level.currentColorForced[ team ][ "o" ] = undefined; level.currentColorForced[ team ][ "g" ] = undefined; } /* ============= ///ScriptDocBegin "Name: get_script_palette( <get_script_palette> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_script_palette() { rgb = []; rgb[ "r" ] = ( 1, 0, 0 ); rgb[ "o" ] = ( 1, 0.5, 0 ); rgb[ "y" ] = ( 1, 1, 0 ); rgb[ "g" ] = ( 0, 1, 0 ); rgb[ "c" ] = ( 0, 1, 1 ); rgb[ "b" ] = ( 0, 0, 1 ); rgb[ "p" ] = ( 1, 0, 1 ); return rgb; } /* ============= ///ScriptDocBegin "Name: notify_delay( <notify_string> , <delay> )" "Summary: Notifies self the string after waiting the specified delay time" "Module: Entity" "CallOn: An entity" "MandatoryArg: <notify_string> : The string to notify" "MandatoryArg: <delay> : Time to wait( in seconds ) before sending the notify." "Example: vehicle notify_delay( "start_to_smoke", 3.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ notify_delay( sNotifyString, fDelay ) { Assert( IsDefined( self ) ); Assert( IsDefined( sNotifyString ) ); Assert( IsDefined( fDelay ) ); self endon( "death" ); if ( fDelay > 0 ) wait fDelay; if ( !isdefined( self ) ) return; self notify( sNotifyString ); } /* ============= ///ScriptDocBegin "Name: gun_remove()" "Summary: Removed the gun from the given AI. Often used for scripted sequences where you dont want the AI to carry a weapon." "Module: AI" "CallOn: An AI" "Example: level.price gun_remove();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ gun_remove() { if ( IsAI( self ) ) // regular AI self animscripts\shared::placeWeaponOn( self.weapon, "none" ); else // Drone self Detach( GetWeaponModel( self.weapon ), "tag_weapon_right" ); } /* ============= ///ScriptDocBegin "Name: gun_recall()" "Summary: Give the AI his gun back." "Module: AI" "CallOn: An AI" "Example: level.price gun_recall();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ gun_recall() { if ( IsAI( self ) ) // regular AI self animscripts\shared::placeWeaponOn( self.weapon, "right" ); else // Drone self Attach( GetWeaponModel( self.weapon ), "tag_weapon_right" ); } /* ============= ///ScriptDocBegin "Name: place_weapon_on( <weapon>, <location> )" "Summary: Equip a wepaon on an AI." "Module: AI" "CallOn: An AI" "MandatoryArg: <weapon> : The name of the weapon to equip" "MandatoryArg: <> : Slot to store the weapon in. 'right', 'left', 'chest', or 'back'." "Example: level.price place_weapon_on( "at4", "back" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ place_weapon_on( weapon, location ) { Assert( IsAI( self ) ); if ( !AIHasWeapon( weapon ) ) animscripts\init::initWeapon( weapon ); animscripts\shared::placeWeaponOn( weapon, location ); } /* ============= ///ScriptDocBegin "Name: forceUseWeapon( <newWeapon>, <targetSlot> )" "Summary: Forces the AI to switch to a specified weapon." "Module: AI" "CallOn: An AI" "MandatoryArg: <newWeapon> : The name of the weapon to use/give" "MandatoryArg: <target slot> : Slot to store the weapon in. primary, secondary or sidearm." "Example: level.price forceUseWeapon( "glock", "sidearm" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ forceUseWeapon( newWeapon, targetSlot ) { Assert( IsDefined( newWeapon ) ); Assert( newWeapon != "none" ); Assert( IsDefined( targetSlot ) ); AssertEx( ( targetSlot == "primary" ) || ( targetSlot == "secondary" ) || ( targetSlot == "sidearm" ), "Target slot is either primary, secondary or sidearm." ); // Setup the weaponInfo if it wasn't already done if ( !animscripts\init::isWeaponInitialized( newWeapon ) ) animscripts\init::initWeapon( newWeapon ); // Figure out whether the current and target weapons are side arms, and which slot to go to hasWeapon = ( self.weapon != "none" ); isCurrentSideArm = usingSidearm(); isNewSideArm = ( targetSlot == "sidearm" ); isNewSecondary = ( targetSlot == "secondary" ); // If we have a weapon and we're not replacing it with one of the same "type", we need to hoslter it first if ( hasWeapon && ( isCurrentSideArm != isNewSideArm ) ) { Assert( self.weapon != newWeapon ); // Based on the current weapon - Hide side arms completely, and holster based on the new target otherwise if ( isCurrentSideArm ) holsterTarget = "none"; else if ( isNewSecondary ) holsterTarget = "back"; else holsterTarget = "chest"; animscripts\shared::placeWeaponOn( self.weapon, holsterTarget ); // Remember we switched out of that weapon self.lastWeapon = self.weapon; } else { // We didn't have a weapon before, or we're going to loose the one we had, so reset the lastWeapon. self.lastWeapon = newWeapon; } // Put the new weapon in hand animscripts\shared::placeWeaponOn( newWeapon, "right" ); // Replace the equipped weapon slot of the same type with the new weapon ( could stay the same, too ) // If the AI was using a secondary, replace that slot instead of primary if ( isNewSideArm ) self.sideArm = newWeapon; else if ( isNewSecondary ) self.secondaryweapon = newWeapon; else self.primaryweapon = newWeapon; // Set our current weapon to the new one self.weapon = newWeapon; self.bulletsinclip = WeaponClipSize( self.weapon ); self notify( "weapon_switch_done" ); } /* ============= ///ScriptDocBegin "Name: lerp_player_view_to_tag( <player>, <tag> , <lerptime> , <fraction> , <right_arc> , <left_arc> , <top_arc> , <bottom_arc> )" "Summary: Lerps the player's view to the tag on the entity that calls the function.." "Module: Utility" "CallOn: An entity you want to lerp the player's view to." "MandatoryArg: <player> : Player to do the lerp on" "MandatoryArg: <tag> : Tag on the entity that you're lerping to." "MandatoryArg: <lerptime> : Time to lerp over." "OptionalArg: <fraction> : 0 to 1 amount that the rotation of the player's view should be effected by the entity. If you set it less than 1 then the player's view will not get all the way to the final angle." "OptionalArg: <arcs> : Various arcs that limit how far the player can change his view." "Example: car lerp_player_view_to_tag( "tag_windshield", 1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_player_view_to_tag( player, tag, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc ) { lerp_player_view_to_tag_internal( player, tag, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc, false ); } /* ============= ///ScriptDocBegin "Name: lerp_player_view_to_tag_and_hit_geo( <player>, <tag> , <lerptime> , <fraction> , <right_arc> , <left_arc> , <top_arc> , <bottom_arc> )" "Summary: Lerps the player's view to the tag on the entity that calls the function. Geo will block the player." "Module: Utility" "CallOn: An entity you want to lerp the player's view to." "MandatoryArg: <player> : Player to do the lerp on" "MandatoryArg: <tag> : Tag on the entity that you're lerping to." "MandatoryArg: <lerptime> : Time to lerp over." "OptionalArg: <fraction> : 0 to 1 amount that the rotation of the player's view should be effected by the entity. If you set it less than 1 then the player's view will not get all the way to the final angle." "OptionalArg: <arcs> : Various arcs that limit how far the player can change his view." "Example: car lerp_player_view_to_tag_and_hit_geo( "tag_windshield", 1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_player_view_to_tag_and_hit_geo( player, tag, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc ) { lerp_player_view_to_tag_internal( player, tag, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc, true ); } /* ============= ///ScriptDocBegin "Name: lerp_player_view_to_position( <origin> , <angles> , <lerptime> , <fraction> , <right_arc> , <left_arc> , <top_arc> , <bottom_arc>, <hit_geo> )" "Summary: Lerps the player's view to an origin and angles. See lerp_player_view_to_tag." "Module: Utility" "CallOn: A player (optional. If not cvalled on player, will default to level.player)" "MandatoryArg: <origin> : The origin you're lerping to." "MandatoryArg: <angles> : The angles you're lerping to." "MandatoryArg: <lerptime> : Time to lerp over." "OptionalArg: <fraction> : 0 to 1 amount that the rotation of the player's view should be effected by the destination angles. If you set it less than 1 then the player's view will not get all the way to the final angle." "OptionalArg: <arcs> : Various arcs that limit how far the player can change his view." "OptionalArg: <hit_geo> : Sets if the player will hit geo." "Example: lerp_player_view_to_position( org.origin, org.angles );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_player_view_to_position( origin, angles, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc, hit_geo, player ) { player = get_player_from_self(); linker = Spawn( "script_origin", ( 0, 0, 0 ) ); linker.origin = player.origin; linker.angles = player GetPlayerAngles(); if ( IsDefined( hit_geo ) && hit_geo ) { player PlayerLinkTo( linker, "", fraction, right_arc, left_arc, top_arc, bottom_arc, hit_geo ); } else if ( IsDefined( right_arc ) ) { player PlayerLinkTo( linker, "", fraction, right_arc, left_arc, top_arc, bottom_arc ); } else if ( IsDefined( fraction ) ) { player PlayerLinkTo( linker, "", fraction ); } else { player PlayerLinkTo( linker ); } linker MoveTo( origin, lerptime, lerptime * 0.25 ); linker RotateTo( angles, lerptime, lerptime * 0.25 ); wait( lerptime ); linker Delete(); } /* ============= ///ScriptDocBegin "Name: lerp_player_view_to_tag_oldstyle( <player>, <tag> , <lerptime> , <fraction> , <right_arc> , <left_arc> , <top_arc> , <bottom_arc> )" "Summary: Lerps the player's view to the tag on the entity that calls the function, using the oldstyle link which moves the player's view when the tag rotates." "Module: Utility" "CallOn: An entity you want to lerp the player's view to." "MandatoryArg: <player> : Which player." "MandatoryArg: <tag> : Tag on the entity that you're lerping to." "MandatoryArg: <lerptime> : Time to lerp over." "OptionalArg: <fraction> : 0 to 1 amount that the rotation of the player's view should be effected by the entity. If you set it less than 1 then the player's view will not get all the way to the final angle." "OptionalArg: <arcs> : Various arcs that limit how far the player can change his view." "Example: car lerp_player_view_to_tag_oldstyle( "tag_windshield", 1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_player_view_to_tag_oldstyle( player, tag, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc ) { lerp_player_view_to_tag_oldstyle_internal( player, tag, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc, false ); } /* ============= ///ScriptDocBegin "Name: lerp_player_view_to_position_oldstyle( <origin> , <angles> , <lerptime> , <fraction> , <right_arc> , <left_arc> , <top_arc> , <bottom_arc>, <hit_geo> )" "Summary: Lerps the player's view to an origin and angles. See lerp_player_view_to_tag_oldstyle. Oldstyle means that you're going to move to the point where the player's feet would be, rather than directly below the point where the view would be." "Module: Utility" "MandatoryArg: <origin> : The origin you're lerping to." "MandatoryArg: <angles> : The angles you're lerping to." "MandatoryArg: <lerptime> : Time to lerp over." "OptionalArg: <fraction> : 0 to 1 amount that the rotation of the player's view should be effected by the destination angles. If you set it less than 1 then the player's view will not get all the way to the final angle." "OptionalArg: <arcs> : Various arcs that limit how far the player can change his view." "OptionalArg: <hit_geo> : Sets if the player will hit geo." "Example: lerp_player_view_to_position_oldstyle( org.origin, org.angles );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_player_view_to_position_oldstyle( origin, angles, lerptime, fraction, right_arc, left_arc, top_arc, bottom_arc, hit_geo ) { player = get_player_from_self(); linker = Spawn( "script_origin", ( 0, 0, 0 ) ); linker.origin = player get_player_feet_from_view(); linker.angles = player GetPlayerAngles(); if ( IsDefined( hit_geo ) ) { player PlayerLinkToDelta( linker, "", fraction, right_arc, left_arc, top_arc, bottom_arc, hit_geo ); } else if ( IsDefined( right_arc ) ) { player PlayerLinkToDelta( linker, "", fraction, right_arc, left_arc, top_arc, bottom_arc ); } else if ( IsDefined( fraction ) ) { player PlayerLinkToDelta( linker, "", fraction ); } else { player PlayerLinkToDelta( linker ); } linker MoveTo( origin, lerptime, lerptime * 0.25 ); linker RotateTo( angles, lerptime, lerptime * 0.25 ); wait( lerptime ); linker Delete(); } // can't make a function pointer out of a code command timer( time ) { wait( time ); } /* ============= ///ScriptDocBegin "Name: player_moves( <dist> )" "Summary: Returns when the player has moved < dist > distance." "Module: Utility" "MandatoryArg: <dist> : The distance the player must move for the function to return." "Example: player_moves( 500 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_moves( dist ) { org = level.player.origin; for ( ;; ) { if ( Distance( org, level.player.origin ) > dist ) break; wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: waittill_either_function( <func1> , <parm1> , <func2> , <parm2> )" "Summary: Returns when either func1 or func2 have returned." "Module: Utility" "MandatoryArg: <func1> : A function pointer to a function that may return at some point." "MandatoryArg: <func2> : Another function pointer to a function that may return at some point." "OptionalArg: <parm1> : An optional parameter for func1." "OptionalArg: <parm2> : An optional parameter for func2." "Example: player_moves( 500 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_either_function( func1, parm1, func2, parm2 ) { ent = SpawnStruct(); thread waittill_either_function_internal( ent, func1, parm1 ); thread waittill_either_function_internal( ent, func2, parm2 ); ent waittill( "done" ); } /* ============= ///ScriptDocBegin "Name: waittill_msg( <msg> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_msg( msg ) { self waittill( msg ); } /* ============= ///ScriptDocBegin "Name: display_hint( <hint> )" "Summary: Displays a hint created with add_hint_string." "Module: Utility" "MandatoryArg: <hint> : The hint reference created with add_hint_string." "Example: display_hint( "huzzah" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ display_hint( hint, parm1, parm2, parm3 ) { player = get_player_from_self(); // hint triggers have an optional function they can boolean off of to determine if the hint will occur // such as not doing the NVG hint if the player is using NVGs already if ( IsDefined( level.trigger_hint_func[ hint ] ) ) { if ( player [[ level.trigger_hint_func[ hint ] ]]() ) return; player thread HintPrint( level.trigger_hint_string[ hint ], level.trigger_hint_func[ hint ], parm1, parm2, parm3, 30 ); } else { player thread HintPrint( level.trigger_hint_string[ hint ], undefined, undefined, undefined, undefined, 30 ); } } /* ============= ///ScriptDocBegin "Name: display_hint_timeout( <hint> )" "Summary: Displays a hint created with add_hint_string." "Module: Utility" "MandatoryArg: <hint> : The hint reference created with add_hint_string." "Example: display_hint( "huzzah" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ display_hint_timeout( hint, timeout, parm1, parm2, parm3 ) { player = get_player_from_self(); AssertEx( IsDefined( level.trigger_hint_func[ hint ] ), "Can't have a hint with a timeout if is has no break function, because hints without break functions display for a set period of time." ); // hint triggers have an optional function they can boolean off of to determine if the hint will occur // such as not doing the NVG hint if the player is using NVGs already if ( player [[ level.trigger_hint_func[ hint ] ]]() ) return; player thread HintPrint( level.trigger_hint_string[ hint ], level.trigger_hint_func[ hint ], parm1, parm2, parm3, timeout ); } /* ============= ///ScriptDocBegin "Name: getGenericAnim( <anime> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getGenericAnim( anime ) { AssertEx( IsDefined( level.scr_anim[ "generic" ][ anime ] ), "Generic anim " + anime + " was not defined in your _anim file." ); return level.scr_anim[ "generic" ][ anime ]; } /* ============= ///ScriptDocBegin "Name: enable_careful()" "Summary: Makes an AI not advance into his fixednode safe radius if an enemy enters it." "Module: AI" "Example: guy enable_careful()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_careful() { AssertEx( IsAI( self ), "Tried to make an ai careful but it wasn't called on an AI" ); self.script_careful = true; } /* ============= ///ScriptDocBegin "Name: disable_careful()" "Summary: Turns off careful mode for this AI." "Module: AI" "Example: guy disable_careful()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_careful() { AssertEx( IsAI( self ), "Tried to unmake an ai careful but it wasn't called on an AI" ); self.script_careful = false; self notify( "stop_being_careful" ); } /* ============= ///ScriptDocBegin "Name: enable_sprint()" "Summary: Force an ai to sprint." "Module: AI" "Example: guy enable_sprint()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_sprint() { AssertEx( IsAI( self ), "Tried to make an ai sprint but it wasn't called on an AI" ); self.sprint = true; } /* ============= ///ScriptDocBegin "Name: disable_sprint()" "Summary: Disable forced sprinting." "Module: AI" "Example: guy disable_sprint()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_sprint() { AssertEx( IsAI( self ), "Tried to unmake an ai sprint but it wasn't called on an AI" ); self.sprint = undefined; } /* ============= ///ScriptDocBegin "Name: disable_bulletwhizbyreaction()" "Summary: disables the bulletwhizby reactions by ai" "Module: AI" "CallOn: An AI" "Example: level.price disable_bulletwhizbyreaction();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_bulletwhizbyreaction() { self.disableBulletWhizbyReaction = true; } /* ============= ///ScriptDocBegin "Name: enable_bulletwhizbyreaction()" "Summary: renables the bulletwhizby reactions by ai" "Module: AI" "CallOn: An AI" "Example: level.price enable_bulletwhizbyreaction();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_bulletwhizbyreaction() { self.disableBulletWhizbyReaction = undefined; } clear_dvar( msg ) { SetDvar( msg, "" ); } /* ============= ///ScriptDocBegin "Name: mission( <name> )" "Summary: Returns true if name is the current mission" "Module: Utility" "MandatoryArg: <name>: Name of the mission to test" "Example: if ( mission( "bog_a" ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ mission( name ) { return level.script == name; } /* ============= ///ScriptDocBegin "Name: set_fixednode_true( <set_fixednode_true> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_fixednode_true() { self.fixednode = true; } /* ============= ///ScriptDocBegin "Name: set_fixednode_false( <set_fixednode_false> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_fixednode_false() { self.fixednode = false; } /* ============= ///ScriptDocBegin "Name: spawn_ai( <bForceSpawn> )" "Summary: Spawns the AI spawner and returns the alive AI" "Module: Entity" "CallOn: An entity" "OptionalArg: <bForceSpawn>: Set to true to force spawn the AI" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ spawn_ai( bForceSpawn ) { if ( IsDefined( self.script_delay_spawn ) ) { self endon( "death" ); wait( self.script_delay_spawn ); } spawnedGuy = undefined; dontShareEnemyInfo = ( IsDefined( self.script_stealth ) && flag( "_stealth_enabled" ) && !flag( "_stealth_spotted" ) ); if ( ( IsDefined( self.script_forcespawn ) ) || ( IsDefined( bForceSpawn ) ) ) { if ( !isdefined( self.script_drone ) ) spawnedGuy = self StalingradSpawn( dontShareEnemyInfo ); else spawnedGuy = dronespawn( self ); } else { if ( !isdefined( self.script_drone ) ) spawnedGuy = self DoSpawn( dontShareEnemyInfo ); else spawnedGuy = dronespawn( self ); } if ( !isdefined( self.script_drone ) ) spawn_failed( spawnedGuy ); //this assert should still be here - but the functions calling this (pyramid spawner for example ) don't care if //the guy is actually spawned or not...seems to be more of an issue with pyramid spawner ( why is trying to spawn guys ) //and not caring about the consiquences...tracked it down to this function being called twice on the same spawner in the same frame //in bog B, maybe further evaluation should be taken of pyramid spawner and why it's trying to do that - but for now - just commenting out //the assert and assuming we don't care why we can't spawn 2 guys in the same frame... -MO //assert( IsDefined( spawnedGuy ) ); return spawnedGuy; } /* ============= ///ScriptDocBegin "Name: function_stack( <function>, <param1>, <param2>, <param3>, <param4>, <param5> )" "Summary: function stack is used to thread off multiple functions one after another an insure that they get called in the order you sent them in (like a FIFO queue or stack). function_stack will wait for the function to finish before continuing the next line of code, but since it internally threads the function off, the function will not end if the parent function which called function_stack() ends. function_stack is also local to the entity that called it, if you call it on nothing it will use level and all functions sent to the stack will wait on the previous one sent to level. The same works for entities. This way you can have 2 AI's that thread off multiple functions but those functions are in individual stacks for each ai" "Module: Utility" "CallOn: level or an entity." "MandatoryArg: <function> : the function to send to the stack" "OptionalArg: <param1> : An optional parameter for <function>." "OptionalArg: <param2> : An optional parameter for <function>." "OptionalArg: <param3> : An optional parameter for <function>." "OptionalArg: <param4> : An optional parameter for <function>." "OptionalArg: <param5> : An optional parameter for <function>." "Example: level thread function_stack(::radio_dialogue, "scoutsniper_mcm_okgo" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ function_stack( func, param1, param2, param3, param4, param5 ) { //self might die - but if we endon( "death" ) this function will return without a bool, which is bad. //self endon( "death" ); localentity = SpawnStruct(); localentity thread function_stack_proc( self, func, param1, param2, param3, param4, param5 ); return self function_stack_wait_finish( localentity ); } /* ============= ///ScriptDocBegin "Name: function_stack_timeout( <timeout> , <func> , <param1> , <param2> , <param3> , <param4> )" "Summary: function stack is used to thread off multiple functions one after another an insure that they get called in the order you sent them in (like a FIFO queue or stack). function_stack will wait for the function to finish before continuing the next line of code, but since it internally threads the function off, the function will not end if the parent function which called function_stack() ends. function_stack is also local to the entity that called it, if you call it on nothing it will use level and all functions sent to the stack will wait on the previous one sent to level. The same works for entities. This way you can have 2 AI's that thread off multiple functions but those functions are in individual stacks for each ai" "Module: Utility" "CallOn: level or an entity." "MandatoryArg: <timeout> : number of seconds before this function times out of the stack" "MandatoryArg: <function> : the function to send to the stack" "OptionalArg: <param1> : An optional parameter for <function>." "OptionalArg: <param2> : An optional parameter for <function>." "OptionalArg: <param3> : An optional parameter for <function>." "OptionalArg: <param4> : An optional parameter for <function>." "OptionalArg: <param5> : An optional parameter for <function>." "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ function_stack_timeout( timeout, func, param1, param2, param3, param4, param5 ) { //self might die - but if we endon( "death" ) this function will return without a bool, which is bad. //self endon( "death" ); localentity = SpawnStruct(); localentity thread function_stack_proc( self, func, param1, param2, param3, param4, param5 ); if ( IsDefined( localentity.function_stack_func_begun ) || ( localentity waittill_any_timeout( timeout, "function_stack_func_begun" ) != "timeout" ) ) { return self function_stack_wait_finish( localentity ); } else { localentity notify( "death" ); return false; } } /* ============= ///ScriptDocBegin "Name: function_stack_clear()" "Summary: kills the stack of funcitons waiting to run" "Module: Utility" "CallOn: level or entity" "Example: level function_stack_clear();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ function_stack_clear() { newstack = []; if ( IsDefined( self.function_stack[ 0 ] ) && IsDefined( self.function_stack[ 0 ].function_stack_func_begun ) ) newstack[ 0 ] = self.function_stack[ 0 ]; //clear the stack and stop further processes self.function_stack = undefined; self notify( "clear_function_stack" ); //the notify ends a function in the stack process waiting it's turn...it checks to //see if there is a function_stack on self to either run the function or just quit //in rare cases if you clear the stack and start piling stuff onto a new one, you'll //create the new stack before the process has a chance to check if the stack is undefined //and then all your functions run at once instead of being actually cleared...this //waittillframeend makes sure that doesn't happen waittillframeend; if ( !newstack.size ) return; if ( !newstack[ 0 ].function_stack_func_begun ) return; self.function_stack = newstack; } /* ============= ///ScriptDocBegin "Name: geo_off( <geo_off> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ geo_off() { if ( IsDefined( self.geo_off ) ) return; self.realorigin = self GetOrigin(); self MoveTo( self.realorigin + ( 0, 0, -10000 ), .2 ); self.geo_off = true; } /* ============= ///ScriptDocBegin "Name: geo_on( <geo_on> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ geo_on() { if ( !isDefined( self.geo_off ) ) return; self MoveTo( self.realorigin, .2 ); self waittill( "movedone" ); self.geo_off = undefined; } /* ============= ///ScriptDocBegin "Name: disable_exits( <value> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_exits() { self.disableexits = true; } /* ============= ///ScriptDocBegin "Name: enable_exits( <enable_exits> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_exits() { self.disableexits = undefined; } /* ============= ///ScriptDocBegin "Name: disable_turnAnims( <disable_turnAnims> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_turnAnims() { self.noTurnAnims = true; } /* ============= ///ScriptDocBegin "Name: enable_turnAnims()" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_turnAnims() { self.noTurnAnims = undefined; } /* ============= ///ScriptDocBegin "Name: disable_arrivals()" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_arrivals() { self.disablearrivals = true; } /* ============= ///ScriptDocBegin "Name: enable_arrivals()" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_arrivals() { self endon( "death" ); // wait until after anim_reach has turned arrivals off waittillframeend; self.disablearrivals = undefined; } /* ============= ///ScriptDocBegin "Name: set_blur( <magnitude>, <transition time> )" "Summary: calls script command SetBlur( <magnitude>, <transition time> )" "Module: Utility" "CallOn: " "MandatoryArg: <magnitude> : amount of blur to transition to" "MandatoryArg: <transition time> : time in seconds to transition to desired blur amount" "Example: set_blur( 8, 3.1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_blur( magnitude, time ) { SetBlur( magnitude, time ); } /* ============= ///ScriptDocBegin "Name: set_goal_radius( <radius> )" "Summary: sets .goalradius parameter on ai to <radius>" "Module: AI" "CallOn: AI" "MandatoryArg: <radius> : radius to set ai's .goalradius to" "Example: guy set_goal_radius( 128 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goal_radius( radius ) { self.goalradius = radius; } /* ============= ///ScriptDocBegin "Name: set_goal_node( <node> )" "Summary: calls script command SetGoalNode( <node> ), but also sets self.last_set_goalnode to <node>" "Module: AI" "CallOn: AI" "MandatoryArg: <node> : node to send the ai to" "Example: guy set_goal_node( node );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goal_node( node ) { self.last_set_goalnode = node; self.last_set_goalpos = undefined; self.last_set_goalent = undefined; self SetGoalNode( node ); } /* ============= ///ScriptDocBegin "Name: set_goal_node_targetname( <targetname> )" "Summary: gets the node with the spedified targetname then calls script command SetGoalNode( <node> ), but also sets self.last_set_goalnode to <node>" "Module: AI" "CallOn: AI" "MandatoryArg: <targetname> : node targetname to send the ai to" "Example: guy set_goal_node( "first_node" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goal_node_targetname( targetname ) { Assert( IsDefined( targetname ) ); node = GetNode( targetname, "targetname" ); Assert( IsDefined( node ) ); self set_goal_node( node ); } /* ============= ///ScriptDocBegin "Name: set_goal_pos( <origin> )" "Summary: calls script command SetGoalPos( <origin> ), but also sets self.last_set_goalpos to <origin>" "Module: AI" "CallOn: AI" "MandatoryArg: <origin> : origin to send the ai to" "Example: guy set_goal_pos( vector );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goal_pos( origin ) { self.last_set_goalnode = undefined; self.last_set_goalpos = origin; self.last_set_goalent = undefined; self SetGoalPos( origin ); } /* ============= ///ScriptDocBegin "Name: set_goal_ent( <entity> )" "Summary: calls script command SetGoalPos( <entity>.origin ), but also sets self.last_set_goalent to <origin>" "Module: AI" "CallOn: AI" "MandatoryArg: <entity> : entity with .origin variable to send the ai to" "Example: guy set_goal_ent( script_origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_goal_ent( target ) { set_goal_pos( target.origin ); self.last_set_goalent = target; } /* ============= ///ScriptDocBegin "Name: objective_complete( <obj> )" "Summary: Sets an objective to DONE" "Module: Entity" "CallOn: An entity" "MandatoryArg: <obj>: The objective index" "Example: objective_complete( 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ objective_complete( obj ) { Objective_State( obj, "done" ); level notify( "objective_complete" + obj ); } /* ============= ///ScriptDocBegin "Name: handsignal( <xanim> , <ender> , <waiter> )" "Summary: Makes an AI do a handsignal" "Module: Utility" "CallOn: An ai" "MandatoryArg: <xanim>: The string name of the animation. Options are 'moveout', 'moveup', 'stop', 'onme', 'enemy', 'go'." "OptionalArg: <wait anim done>: if true, wait till animation is over. Defaults to false." "OptionalArg: <ender>: An optional ender " "OptionalArg: <waiter>: An optional string to wait for level notify on " "Example: level.price handsignal( "go" );" "SPMP: singleplayer" ///ScriptDocEnd ============= Add this to your _anim script: level.scr_anim[ "generic" ][ "signal_onme" ] = %CQB_stand_wave_on_me; level.scr_anim[ "generic" ][ "signal_go" ] = %CQB_stand_wave_go_v1; level.scr_anim[ "generic" ][ "signal_stop" ] = %CQB_stand_signal_stop; */ handsignal( xanim, waitAnimDone, ender, waiter ) { returnImmediate = true; if ( IsDefined( waitAnimDone ) ) returnImmediate = !waitAnimDone; if ( IsDefined( ender ) ) level endon( ender ); if ( IsDefined( waiter ) ) level waittill( waiter ); animName = "signal_" + xanim; if ( self.a.pose == "crouch" ) animName = animName + "_crouch"; else if ( self.script == "cover_right" ) animName = animName + "_coverR"; else if ( self isCQBWalking() ) animName = animName + "_cqb"; if ( returnImmediate ) self SetAnimRestart( getGenericAnim( animName ), 1, 0, 1.1 ); else self maps\_anim::anim_generic( self, animName ); } /* ============= ///ScriptDocBegin "Name: get_guy_with_script_noteworthy_from_spawner( <script_noteworthy> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_guy_with_script_noteworthy_from_spawner( script_noteworthy ) { spawner = GetEntArray( script_noteworthy, "script_noteworthy" ); AssertEx( spawner.size == 1, "Tried to get guy from spawner but there were zero or multiple spawners" ); guys = array_spawn( spawner ); return guys[ 0 ]; } /* ============= ///ScriptDocBegin "Name: get_guy_with_targetname_from_spawner( <targetname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_guy_with_targetname_from_spawner( targetname ) { spawner = GetEntArray( targetname, "targetname" ); AssertEx( spawner.size == 1, "Tried to get guy from spawner but there were zero or multiple spawners" ); guys = array_spawn( spawner ); return guys[ 0 ]; } /* ============= ///ScriptDocBegin "Name: get_guys_with_targetname_from_spawner( <targetname> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_guys_with_targetname_from_spawner( targetname ) { spawners = GetEntArray( targetname, "targetname" ); AssertEx( spawners.size > 0, "Tried to get guy from spawner but there were zero spawners" ); return array_spawn( spawners ); } /* ============= ///ScriptDocBegin "Name: array_spawn( <spawners>, <bForceSpawn> )" "Summary: spawns every spawner in the array and then returns an array of the alive AI that were spawned" "Module: Utility" "CallOn: An array of spawners" "MandatoryArg: <spawners>: The spawners" "OptionalArg: <bForceSpawn>: use stalingradspawn to force spawn the AI" "Example: guys = array_spawn( hooligans );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_spawn( spawners, bForceSpawn ) { guys = []; foreach ( spawner in spawners ) { spawner.count = 1; if ( GetSubStr( spawner.classname, 7, 10 ) == "veh" ) { guy = spawner spawn_vehicle(); /# if ( IsDefined( spawner.export ) ) AssertEx( IsAlive( guy ), "Vehicle with export " + spawner.export + " failed to spawn." ); else AssertEx( IsAlive( guy ), "Vehicle at " + spawner.origin + " failed to spawn." ); #/ if ( IsDefined( guy.target ) ) guy thread maps\_vehicle::gopath(); guys[ guys.size ] = guy; } else { guy = spawner spawn_ai( bForceSpawn ); AssertEx( IsAlive( guy ), "Guy with export " + spawner.export + " failed to spawn." ); guys[ guys.size ] = guy; } } AssertEx( guys.size == spawners.size, "Didnt spawn correct number of guys" ); return guys; } /* ============= ///ScriptDocBegin "Name: array_spawn_targetname( <targetname> )" "Summary: Spawn guys with this targetname" "Module: Utility" "MandatoryArg: <targetname>: The targetname " "Example: array_spawn_targetname( "badguy_spawner" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_spawn_targetname( targetname ) { spawners = GetEntArray( targetname, "targetname" ); AssertEx( spawners.size, "Tried to spawn spawners with targetname " + targetname + " but there are no spawners" ); return array_spawn( spawners ); } /* ============= ///ScriptDocBegin "Name: array_spawn_noteworthy( <noteworthy> )" "Summary: Spawn guys with this noteworthy" "Module: Utility" "MandatoryArg: <noteworthy>: The noteworthy " "Example: array_spawn_noteworthy( "badguy_spawner" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_spawn_noteworthy( noteworthy ) { spawners = GetEntArray( noteworthy, "script_noteworthy" ); AssertEx( spawners.size, "Tried to spawn spawners with targetname " + noteworthy + " but there are no spawners" ); return array_spawn( spawners ); } /* ============= ///ScriptDocBegin "Name: spawn_script_noteworthy( <script_noteworthy> )" "Summary: Spawns an AI spawner with a specific script_noteworthy" "Module: Utility" "MandatoryArg: <script_noteworthy>: The script_noteworthy of the spawner" "Example: level.price = spawn_script_noteworthy( "friendly_price" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ spawn_script_noteworthy( script_noteworthy, bForceSpawn ) { spawner = GetEnt( script_noteworthy, "script_noteworthy" ); AssertEx( IsDefined( spawner ), "Spawner with script_noteworthy " + script_noteworthy + " does not exist." ); guy = spawner spawn_ai( bForceSpawn ); return guy; } /* ============= ///ScriptDocBegin "Name: spawn_targetname( <targetname> )" "Summary: Spawns an AI spawner with a specific targetname" "Module: Utility" "MandatoryArg: <targetname>: The targetname of the spawner" "OptionalArg: <bForcespawn>: make this spawn with stalingradspawn" "Example: level.price = targetname( "targetname" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ spawn_targetname( targetname, bForceSpawn ) { spawner = GetEnt( targetname, "targetname" ); AssertEx( IsDefined( spawner ), "Spawner with targetname " + targetname + " does not exist." ); guy = spawner spawn_ai( bForceSpawn ); return guy; } /* ============= ///ScriptDocBegin "Name: add_dialogue_line( <name> , <msg>, <name_color> )" "Summary: Prints temp dialogue on the screen in lieu of a sound alias." "Module: Utility" "MandatoryArg: <name>: The character." "MandatoryArg: <msg>: The dialogue." "OptionalArg: <name_color>: An optional string of a color to give the name (makes different names delivering dialogue easier to follow...colors red, green, yellow, blue, cyan, purple, white, black " "Example: thread add_dialogue_line( "MacMillan", "Put me down over there on the slope by the mattress." );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_dialogue_line( name, msg, name_color ) { if ( GetDvarInt( "loc_warnings", 0 ) ) return;// I'm not localizing your damn temp dialog lines - Nate. if ( !isdefined( level.dialogue_huds ) ) { level.dialogue_huds = []; } for ( index = 0; ; index++ ) { if ( !isdefined( level.dialogue_huds[ index ] ) ) break; } color = "^3"; if ( IsDefined( name_color ) ) { switch( name_color ) { case "r": case "red": color = "^1"; break; case "g": case "green": color = "^2"; break; case "y": case "yellow": color = "^3"; break; case "b": case "blue": color = "^4"; break; case "c": case "cyan": color = "^5"; break; case "p": case "purple": color = "^6"; break; case "w": case "white": color = "^7"; break; case "bl": case "black": color = "^8"; break; } } level.dialogue_huds[ index ] = true; hudelem = maps\_hud_util::createFontString( "default", 1.5 ); hudelem.location = 0; hudelem.alignX = "left"; hudelem.alignY = "top"; hudelem.foreground = 1; hudelem.sort = 20; hudelem.alpha = 0; hudelem FadeOverTime( 0.5 ); hudelem.alpha = 1; hudelem.x = 40; hudelem.y = 260 + index * 18; hudelem.label = " " + color + "< " + name + " > ^7" + msg; hudelem.color = ( 1, 1, 1 ); wait( 2 ); timer = 2 * 20; hudelem FadeOverTime( 6 ); hudelem.alpha = 0; for ( i = 0; i < timer; i++ ) { hudelem.color = ( 1, 1, 0 / ( timer - i ) ); wait( 0.05 ); } wait( 4 ); hudelem Destroy(); level.dialogue_huds[ index ] = undefined; } /* ============= ///ScriptDocBegin "Name: destructible_disable_explosion()" "Summary: Disables a destructibles ( ie destructible vehicle ) ability to explode. It will catch fire, take window damage etc but not explode." "Module: Destructibles" "CallOn: Destructible" "Example: car thread destructible_disable_explosion();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ destructible_disable_explosion() { self common_scripts\_destructible::disable_explosion(); } /* ============= ///ScriptDocBegin "Name: destructible_force_explosion()" "Summary: Forces a destructible ( ie destructible vehicle ) to explode immediately." "Module: Destructibles" "CallOn: Destructible" "Example: car thread destructible_force_explosion();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ destructible_force_explosion() { self common_scripts\_destructible::force_explosion(); } set_grenadeammo( count ) { self.grenadeammo = count; } /* ============= ///ScriptDocBegin "Name: get_player_feet_from_view( <get_player_feet_from_view> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_player_feet_from_view() { Assert( IsPlayer( self ) ); tagorigin = self.origin; upvec = AnglesToUp( self GetPlayerAngles() ); height = self GetPlayerViewHeight(); player_eye = tagorigin + ( 0, 0, height ); player_eye_fake = tagorigin + vector_multiply( upvec, height ); diff_vec = player_eye - player_eye_fake; fake_origin = tagorigin + diff_vec; return fake_origin; } /* ============= ///ScriptDocBegin "Name: set_baseaccuracy( <val> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_baseaccuracy( val ) { self.baseaccuracy = val; } /* ============= ///ScriptDocBegin "Name: set_console_status( <set_console_status> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_console_status() { if ( !isdefined( level.Console ) ) level.Console = GetDvar( "consoleGame" ) == "true"; else AssertEx( level.Console == ( GetDvar( "consoleGame" ) == "true" ), "Level.console got set incorrectly." ); if ( !isdefined( level.xenon ) ) level.xenon = GetDvar( "xenonGame" ) == "true"; else AssertEx( level.xenon == ( GetDvar( "xenonGame" ) == "true" ), "Level.xenon got set incorrectly." ); if ( !isdefined( level.ps3 ) ) level.ps3 = GetDvar( "ps3Game" ) == "true"; else AssertEx( level.ps3 == ( GetDvar( "ps3Game" ) == "true" ), "Level.ps3 got set incorrectly." ); } /* ============= ///ScriptDocBegin "Name: autosave_now( <suppress_print> )" "Summary: " "Module: Utility" "CallOn: Level" "OptionalArg: <suppress_print>: " "Example: thread autosave_now();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_now( suppress_print ) { return maps\_autosave::_autosave_game_now( suppress_print ); } /* ============= ///ScriptDocBegin "Name: autosave_now_silent()" "Summary: No checkpoint msg" "Module: Utility" "CallOn: Level" "OptionalArg: <suppress_print>: " "Example: thread autosave_now_silent();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ autosave_now_silent() { return maps\_autosave::_autosave_game_now( true ); } /* ============= ///ScriptDocBegin "Name: set_generic_deathanim( <deathanim> )" "Summary: Sets a deathanim for a generic guy" "Module: Utility" "CallOn: AI" "MandatoryArg: <deathanim>: The death animation reference" "Example: guy set_generic_deathanim( "explosive_death" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_generic_deathanim( deathanim ) { self.deathanim = getGenericAnim( deathanim ); } /* ============= ///ScriptDocBegin "Name: set_deathanim( <deathanim> )" "Summary: Sets the deathanim on an AI" "Module: Utility" "CallOn: AI" "MandatoryArg: <deathanim>: The death animation reference" "Example: guy set_deathanim( "death" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_deathanim( deathanim ) { self.deathanim = getanim( deathanim ); } /* ============= ///ScriptDocBegin "Name: clear_deathanim( <clear_deathanim> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ clear_deathanim() { self.deathanim = undefined; } /* ============= ///ScriptDocBegin "Name: hunted_style_door_open( <soundalias> )" "Summary: Animates the door/gate/whatever in the style of Hunted's cool price door opening." "Module: Utility" "CallOn: A door or gate calls it" "OptionalArg: <Soundalias>: A soundalias to play " "Example: door hunted_style_door_open( "door_wood_slow_creaky_open" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hunted_style_door_open( soundalias ) { wait( 1.75 ); if ( IsDefined( soundalias ) ) self PlaySound( soundalias ); else self PlaySound( "door_wood_slow_open" ); self RotateTo( self.angles + ( 0, 70, 0 ), 2, .5, 0 ); self ConnectPaths(); self waittill( "rotatedone" ); self RotateTo( self.angles + ( 0, 40, 0 ), 2, 0, 2 ); } /* ============= ///ScriptDocBegin "Name: palm_style_door_open( <soundalias> )" "Summary: Animates the door/gate/whatever in the style of Hunted's cool price door opening but with the palm instead of door knob." "Module: Utility" "CallOn: A door or gate calls it" "OptionalArg: <Soundalias>: A soundalias to play " "Example: door palm_style_door_open( "door_wood_slow_creaky_open" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ palm_style_door_open( soundalias ) { wait( 1.35 ); if ( IsDefined( soundalias ) ) self PlaySound( soundalias ); else self PlaySound( "door_wood_slow_open" ); self RotateTo( self.angles + ( 0, 70, 0 ), 2, .5, 0 ); self ConnectPaths(); self waittill( "rotatedone" ); self RotateTo( self.angles + ( 0, 40, 0 ), 2, 0, 2 ); } /* ============= ///ScriptDocBegin "Name: lerp_fov_overtime( <time> , <destfov> )" "Summary: lerps from the current cg_fov value to the destfov value linearly over time" "Module: Player" "CallOn: Level" "MandatoryArg: <time>: time to lerp" "OptionalArg: <destfov>: field of view to go to" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_fov_overtime( time, destfov ) { basefov = GetDvarFloat( "cg_fov" ); incs = Int( time / .05 ); incfov = ( destfov - basefov ) / incs ; currentfov = basefov; for ( i = 0; i < incs; i++ ) { currentfov += incfov; SetSavedDvar( "cg_fov", currentfov ); wait .05; } //fix up the little bit of rounding error. not that it matters much .002, heh SetSavedDvar( "cg_fov", destfov ); } /* ============= ///ScriptDocBegin "Name: lerp_fovscale_overtime( <time> , <destfovscale> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_fovscale_overtime( time, destfovscale ) { basefov = GetDvarFloat( "cg_fovscale" ); incs = Int( time / .05 ); incfov = ( destfovscale - basefov ) / incs ; currentfov = basefov; for ( i = 0; i < incs; i++ ) { currentfov += incfov; SetSavedDvar( "cg_fovscale", currentfov ); wait .05; } SetSavedDvar( "cg_fovscale", destfovscale ); } /* ============= ///ScriptDocBegin "Name: putGunAway()" "Summary: Puts the AI's weapon away" "Module: Utility" "CallOn: An ai" "Example: level.price putGunAaway();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ putGunAway() { animscripts\shared::placeWeaponOn( self.weapon, "none" ); self.weapon = "none"; } /* ============= ///ScriptDocBegin "Name: apply_fog()" "Summary: Applies the "start" fog settings for this trigger" "Module: Utility" "CallOn: A trigger_fog" "Example: trigger_fog apply_fog()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ apply_fog() { maps\_load::set_fog_progress( 0 ); } /* ============= ///ScriptDocBegin "Name: apply_end_fog()" "Summary: Applies the "end" fog settings for this trigger" "Module: Utility" "CallOn: A trigger_fog" "Example: trigger_fog apply_end_fog()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ apply_end_fog() { maps\_load::set_fog_progress( 1 ); } /* ============= ///ScriptDocBegin "Name: anim_stopanimscripted()" "Summary: " "Module: Entity" "CallOn: An entity" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ anim_stopanimscripted() { self StopAnimScripted(); self notify( "stop_loop" );// default ender. self notify( "single anim", "end" ); self notify( "looping anim", "end" ); } /* ============= ///ScriptDocBegin "Name: disable_pain()" "Summary: Disables pain on the AI" "Module: Utility" "CallOn: An ai" "Example: level.zakhaev disable_pain();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_pain() { AssertEx( IsAI( self ), "Tried to disable pain on a non ai" ); self.a.disablePain = true; self.allowPain = false; } /* ============= ///ScriptDocBegin "Name: enable_pain()" "Summary: Enables pain on the AI" "Module: Utility" "CallOn: An ai" "Example: level.zakhaev enable_pain();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_pain() { AssertEx( IsAI( self ), "Tried to enable pain on a non ai" ); self.a.disablePain = false; self.allowPain = true; } /* ============= ///ScriptDocBegin "Name: _delete( <_delete> )" "Summary: " "Module: Code Wrappers" "CallOn: An entity" "Example: pointer = ::_delete" "SPMP: singleplayer" ///ScriptDocEnd ============= */ _delete() { self Delete(); } /* ============= ///ScriptDocBegin "Name: _kill( <_kill> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _kill() { self Kill(); } /* ============= ///ScriptDocBegin "Name: kill_wrapper( <kill_wrapper> )" "Summary: Wrapper to safely handle killing entities. Does special checks to ensure stability when killing players in Special Ops. Returns true or false depending on whether it actually killed the player." "Module: Entity" "CallOn: An entity" "Example: level.player kill_wrapper();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ kill_wrapper() { // Only do special checking in special ops for now, and only on players. // Players are put into invulnerable states that are unpredictable in co-op Special Ops which can result in // attempts to call kill() directly to assert. If the special op has already terminated just exit out. If the // player is downed force invulnerability off so the kill will be able to succeed. if ( isplayer( self ) && is_coop() ) { if ( flag( "special_op_terminated" ) ) { return false; } if ( is_player_down( self ) ) { self disableinvulnerability(); } } self Kill(); return true; } /* ============= ///ScriptDocBegin "Name: _setentitytarget( <target> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _setentitytarget( target ) { self SetEntityTarget( target ); } /* ============= ///ScriptDocBegin "Name: _ClearEntityTarget()" "Summary: " "Module: Code Wrappers" "CallOn: An entity" "Example: pointer = ::_ClearEntityTarget" "SPMP: singleplayer" ///ScriptDocEnd ============= */ _ClearEntityTarget() { self ClearEntityTarget(); } /* ============= ///ScriptDocBegin "Name: _unlink()" "Summary: " "Module: Code Wrappers" "CallOn: An entity" "Example: pointer = ::_unlink" "SPMP: singleplayer" ///ScriptDocEnd ============= */ _unlink() { self Unlink(); } /* ============= ///ScriptDocBegin "Name: disable_oneshotfx_with_noteworthy( <noteworthy> )" "Summary: Disables _global_fx that have the given noteworthy on them" "Module: Utility" "MandatoryArg: <noteworthy>: The script_noteworthy" "Example: disable_oneshotfx_with_noteworthy( "blackout_spotlight_fx" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_oneshotfx_with_noteworthy( noteworthy ) { AssertEx( IsDefined( level._global_fx_ents[ noteworthy ] ), "No _global_fx ents have noteworthy " + noteworthy ); keys = GetArrayKeys( level._global_fx_ents[ noteworthy ] ); for ( i = 0; i < keys.size; i++ ) { level._global_fx_ents[ noteworthy ][ keys[ i ] ].looper Delete(); level._global_fx_ents[ noteworthy ][ keys[ i ] ] = undefined; } } /* ============= ///ScriptDocBegin "Name: _setLightIntensity( <val> )" "Summary: function pointer to code command SetLightIntensity()" "Module: Code Wrappers" "CallOn: An entity" "MandatoryArg: <val>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _setLightIntensity( val ) { self SetLightIntensity( val ); } /* ============= ///ScriptDocBegin "Name: _linkto( <targ> , <tag> , <org> , <angles> )" "Summary: wrapper for linkto "Module: Code Wrappers" "CallOn: An entity" "MandatoryArg: <targ>: " "OptionalArg: <tag>: " "OptionalArg: <org>: " "OptionalArg: <angles>: " "Example: array_thread( guys, ::_linkto, blackhawk, "tag_detach" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ _linkto( targ, tag, org, angles ) { if ( IsDefined( angles ) ) { self LinkTo( targ, tag, org, angles ); return; } if ( IsDefined( org ) ) { self LinkTo( targ, tag, org ); return; } if ( IsDefined( tag ) ) { self LinkTo( targ, tag ); return; } self LinkTo( targ ); } /* ============= ///ScriptDocBegin "Name: array_wait( <array>, <msg>, <timeout> )" "Summary: waits for every entry in the <array> to recieve the <msg> notify, die, or timeout" "Module: Utility" "MandatoryArg: <array>: the array of entities to wait on" "MandatoryArg: <msg>: the msg each array entity will wait on" "OptionalArg: <timeout>: timeout to kill the wait prematurely" "Example: array_wait( guys, "at the hq" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_wait( array, msg, timeout ) { keys = GetArrayKeys( array ); structs = []; for ( i = 0; i < keys.size; i++ ) { key = keys[ i ]; } for ( i = 0; i < keys.size; i++ ) { key = keys[ i ]; structs[ key ] = SpawnStruct(); structs[ key ]._array_wait = true; structs[ key ] thread array_waitlogic1( array[ key ], msg, timeout ); } for ( i = 0; i < keys.size; i++ ) { key = keys[ i ]; if ( IsDefined( array[ key ] ) && structs[ key ]._array_wait ) structs[ key ] waittill( "_array_wait" ); } } /* ============= ///ScriptDocBegin "Name: die()" "Summary: The entity does damage to itself of > health value" "Module: Utility" "CallOn: An entity" "Example: enemy die();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ die() { self Kill( ( 0, 0, 0 ) ); } /* ============= ///ScriptDocBegin "Name: getmodel( <model> )" "Summary: Returns the level.scr_model[ model ]" "Module: Utility" "MandatoryArg: <model>: The string index into level.scr_model" "Example: SetModel( getmodel( "zakhaevs arm" ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getmodel( str ) { AssertEx( IsDefined( level.scr_model[ str ] ), "Tried to getmodel on model " + str + " but level.scr_model[ " + str + " was not defined." ); return level.scr_model[ str ]; } /* ============= ///ScriptDocBegin "Name: isADS()" "Summary: Returns true if the player is more than 50% ads" "Module: Utility" "Example: player_is_ads = isADS();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ isADS() { Assert( IsPlayer( self ) ); return( self PlayerAds() > 0.5 ); } /* ============= ///ScriptDocBegin "Name: enable_auto_adjust_threatbias()" "Summary: Allows auto adjust to change the player threatbias. Defaults to on" "Module: Utility" "Example: enable_auto_adjust_threatbias();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_auto_adjust_threatbias() { // this needs to be made to work again, broke when coop difficulty was done // (sorry) level.auto_adjust_threatbias = true; if ( level.gameskill >= 2 ) { // hard and vet use locked values level.player.threatbias = Int( maps\_gameskill::get_locked_difficulty_val_player( "threatbias", 1 ) ); return; } // set the threatbias based on the current difficulty frac level.auto_adjust_difficulty_frac = GetDvarInt( "autodifficulty_frac" ); current_frac = level.auto_adjust_difficulty_frac * 0.01; level.player.threatbias = Int( maps\_gameskill::get_blended_difficulty( "threatbias", current_frac ) ); } /* ============= ///ScriptDocBegin "Name: disable_auto_adjust_threatbias()" "Summary: Disallows auto adjust to change the player threatbias. Defaults to on" "Module: Utility" "Example: disable_auto_adjust_threatbias();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_auto_adjust_threatbias() { level.auto_adjust_threatbias = false; } /* ============= ///ScriptDocBegin "Name: disable_replace_on_death()" "Summary: Disables replace on death" "Module: Color" "CallOn: An AI" "Example: guy disable_replace_on_death();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_replace_on_death() { self.replace_on_death = undefined; self notify( "_disable_reinforcement" ); } /* ============= ///ScriptDocBegin "Name: waittill_player_lookat( <dot>, <timer>, <dot_only>, <timeout> )" "Summary: Waits until the player is looking at this entity." "Module: Utility" "CallOn: An AI or entity" "OptionalArg: <dot>: Overwrite the default dot of .92 " "OptionalArg: <timer>: Optional parameter to control how long you have to look before it triggers" "OptionalArg: <dot_only>: Set to false if the player must trace to the entity to pass" "OptionalArg: <timeout>: Time to pass before this function will timeout and give up" "OptionalArg: <player>: When specified, is the player you want to detect is doing the looking." "Example: level.price waittill_player_lookat();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_player_lookat( dot, timer, dot_only, timeout, ignore_ent, player ) { if ( !isdefined( player ) ) player = level.player; timeoutEnt = SpawnStruct(); if ( IsDefined( timeout ) ) timeoutEnt thread notify_delay( "timeout", timeout ); timeoutEnt endon( "timeout" ); if ( !isdefined( dot ) ) dot = 0.92; if ( !isdefined( timer ) ) timer = 0; base_time = Int( timer * 20 ); count = base_time; self endon( "death" ); ai_guy = IsAI( self ); org = undefined; for ( ;; ) { if ( ai_guy ) org = self GetEye(); else org = self.origin; if ( player player_looking_at( org, dot, dot_only, ignore_ent ) ) { count--; if ( count <= 0 ) return true; } else { count = base_time; } wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: waittill_player_lookat_for_time( <timer> , <dot> )" "Summary: Wait until the player is looking at this entity for x time" "Module: Utility" "CallOn: An AI" "MandatoryArg: <timer>: How long the player must look before the timer passes " "OptionalArg: <dot>: Optional override dot" "OptionalArg: <dot_only>: If true, it will only check FOV and not tracepassed" "Example: self waittill_player_lookat_for_time( 0.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_player_lookat_for_time( timer, dot, dot_only, ignore_ent ) { AssertEx( IsDefined( timer ), "Tried to do waittill_player_lookat_for_time with no time parm." ); waittill_player_lookat( dot, timer, dot_only, undefined, ignore_ent ); } /* ============= ///ScriptDocBegin "Name: player_looking_at( <org>, <dot> )" "Summary: Checks to see if the player can dot and trace to a point" "Module: Utility" "MandatoryArg: <org>: The position you're checking if the player is looking at" "OptionalArg: <dot>: Optional override dot" "OptionalArg: <dot_only>: If true, it will only check FOV and not tracepassed" "Example: if ( player_looking_at( org.origin ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_looking_at( start, dot, dot_only, ignore_ent ) { if ( !isdefined( dot ) ) dot = 0.8; player = get_player_from_self(); end = player GetEye(); angles = VectorToAngles( start - end ); forward = AnglesToForward( angles ); player_angles = player GetPlayerAngles(); player_forward = AnglesToForward( player_angles ); new_dot = VectorDot( forward, player_forward ); if ( new_dot < dot ) { return false; } if ( IsDefined( dot_only ) ) { AssertEx( dot_only, "dot_only must be true or undefined" ); return true; } trace = BulletTrace( start, end, false, ignore_ent ); return trace[ "fraction" ] == 1; } /* ============= ///ScriptDocBegin "Name: players_looking_at( <org>, <dot>, <dot_only> )" "Summary: Checks to see if all players can dot and trace to a point" "Module: Utility" "MandatoryArg: <org>: The position you're checking if the players are all looking at" "OptionalArg: <dot>: Optional override dot" "OptionalArg: <dot_only>: If true, it will only check FOV and not tracepassed" "Example: if ( players_looking_at( org.origin ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ players_looking_at( org, dot, dot_only, ignore_ent ) { for ( i = 0; i < level.players.size; i++ ) { if ( !level.players[ i ] player_looking_at( org, dot, dot_only, ignore_ent ) ) return false; } return true; } /* ============= ///ScriptDocBegin "Name: either_player_looking_at( <org>, <dot>, <dot_only> )" "Summary: returns true when either of the two players can trace and/or dot to a point" "Module: Utility" "MandatoryArg: <org>: The position you're checking if a player is looking at" "OptionalArg: <dot>: Optional override dot" "OptionalArg: <dot_only>: If true, it will only check FOV and not tracepassed" "Example: if ( either_player_looking_at( org.origin ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ either_player_looking_at( org, dot, dot_only, ignore_ent ) { for ( i = 0; i < level.players.size; i++ ) { if ( level.players[ i ] player_looking_at( org, dot, dot_only, ignore_ent ) ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: player_can_see_ai( <ai> )" "Summary: Rough method to test if an AI is in view of the player - only checks three points on the AI (low, mid, high)." "Module: Utility" "MandatoryArg: <ai>: The AI whom you're testing if the player can see." "Example: if( player_can_see_ai( ambushGuy ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_can_see_ai( ai ) { feetOrigin = ai.origin; if ( player_can_see_origin( feetOrigin ) ) return true; midOrigin = ai GetTagOrigin( "J_SpineLower" ); if ( player_can_see_origin( midOrigin ) ) return true; eyeOrigin = ai GetEye(); if ( player_can_see_origin( eyeOrigin ) ) return true; return false; } player_can_see_origin( origin ) { // if not in FOV, return false if ( !level.player animscripts\battlechatter::pointInFov( origin ) ) { return false; } // if in FOV but sight trace fails, return false if ( !SightTracePassed( level.player GetEye(), origin, true, level.player ) ) { return false; } // if in FOV with successful trace, return true return true; } /* ============= ///ScriptDocBegin "Name: players_within_distance( <fDist>, <org> )" "Summary: Determines if any players are within a distance of a certain point. Returns false if any players are within the distance" "Module: Utility" "MandatoryArg: <fDist>: The distance away from the <org>" "MandatoryArg: <org>: The location in space we are checking distance from" "Example: if ( players_within_distance( 1024, enemy.origin ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ players_within_distance( fDist, org ) { fDistSquared = fDist * fDist; for ( i = 0; i < level.players.size; i++ ) { if ( DistanceSquared( org, level.players[ i ].origin ) < fDistSquared ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: AI_delete_when_out_of_sight( <aAI_to_delete>, <fDist> )" "Summary: Deletes all of the AI in the array passed as players reach a certain distance away (and are not looking at them)" "Module: Utility" "MandatoryArg: <aAI_to_delete>: The array of AI to delete" "MandatoryArg: <fDist>: The distance away from the players the AI will be deleted" "Example: thread AI_delete_when_out_of_sight( aEnemies, 2048 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ AI_delete_when_out_of_sight( aAI_to_delete, fDist ) { if ( !isdefined( aAI_to_delete ) ) return; off_screen_dot = 0.75; if ( IsSplitScreen() ) { off_screen_dot = 0.65; } while ( aAI_to_delete.size > 0 ) { wait( 1 ); for ( i = 0; i < aAI_to_delete.size; i++ ) { /*----------------------- KEEP LOOPING AND REMOVE ENEMY IF DEAD/DELETED -------------------------*/ if ( ( !isdefined( aAI_to_delete[ i ] ) ) || ( !isalive( aAI_to_delete[ i ] ) ) ) { aAI_to_delete = array_remove( aAI_to_delete, aAI_to_delete[ i ] ); continue; } /*----------------------- KEEP LOOPING IF ANY PLAYERS TOO CLOSE OR IS FACING THE AI -------------------------*/ if ( players_within_distance( fDist, aAI_to_delete[ i ].origin ) ) continue; if ( either_player_looking_at( aAI_to_delete[ i ].origin + ( 0, 0, 48 ), off_screen_dot, true ) ) continue; /*----------------------- ALL TESTS PASSED, DELETE THE BASTARD -------------------------*/ if ( IsDefined( aAI_to_delete[ i ].magic_bullet_shield ) ) aAI_to_delete[ i ] stop_magic_bullet_shield(); aAI_to_delete[ i ] Delete(); aAI_to_delete = array_remove( aAI_to_delete, aAI_to_delete[ i ] ); } } } /* ============= ///ScriptDocBegin "Name: add_wait( <func> , <parm1> , <parm2> , <parm3> )" "Summary: Adds a function that you want to wait for completion on. Self of the function will be whatever add_wait is called on. Make sure you call add_wait before any wait, since the functions are stored globally." "Module: Utility" "MandatoryArg: <func>: The function." "OptionalArg: <parm1>: Optional parameter" "OptionalArg: <parm2>: Optional parameter" "OptionalArg: <parm3>: Optional parameter" "Example: add_wait( ::waittill_player_lookat );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_wait( func, parm1, parm2, parm3 ) { /# thread add_wait_asserter(); #/ ent = SpawnStruct(); ent.caller = self; ent.func = func; ent.parms = []; if ( IsDefined( parm1 ) ) { ent.parms[ ent.parms.size ] = parm1; } if ( IsDefined( parm2 ) ) { ent.parms[ ent.parms.size ] = parm2; } if ( IsDefined( parm3 ) ) { ent.parms[ ent.parms.size ] = parm3; } level.wait_any_func_array[ level.wait_any_func_array.size ] = ent; } /* ============= ///ScriptDocBegin "Name: add_abort( <func> , <parm1> , <parm2> , <parm3> )" "Summary: Adds a function that when completed aborts both the do_wait and any add_funcs added to the system." "Module: Utility" "MandatoryArg: <func>: The function." "OptionalArg: <parm1>: Optional parameter" "OptionalArg: <parm2>: Optional parameter" "OptionalArg: <parm3>: Optional parameter" "Example: add_abort( ::flag_wait, "shazam" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_abort( func, parm1, parm2, parm3 ) { /# thread add_wait_asserter(); #/ ent = SpawnStruct(); ent.caller = self; ent.func = func; ent.parms = []; if ( IsDefined( parm1 ) ) { ent.parms[ ent.parms.size ] = parm1; } if ( IsDefined( parm2 ) ) { ent.parms[ ent.parms.size ] = parm2; } if ( IsDefined( parm3 ) ) { ent.parms[ ent.parms.size ] = parm3; } level.abort_wait_any_func_array[ level.abort_wait_any_func_array.size ] = ent; } /* ============= ///ScriptDocBegin "Name: add_func( <func> , <parm1> , <parm2> , <parm3> )" "Summary: Adds a function that runs after an add_wait/do_wait completes." "Module: Utility" "MandatoryArg: <func>: The function." "OptionalArg: <parm1>: Optional parameter" "OptionalArg: <parm2>: Optional parameter" "OptionalArg: <parm3>: Optional parameter" "Example: add_func( ::waittill_player_lookat );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_func( func, parm1, parm2, parm3, parm4, parm5 ) { /# thread add_wait_asserter(); #/ ent = SpawnStruct(); ent.caller = self; ent.func = func; ent.parms = []; if ( IsDefined( parm1 ) ) { ent.parms[ ent.parms.size ] = parm1; } if ( IsDefined( parm2 ) ) { ent.parms[ ent.parms.size ] = parm2; } if ( IsDefined( parm3 ) ) { ent.parms[ ent.parms.size ] = parm3; } if ( IsDefined( parm4 ) ) { ent.parms[ ent.parms.size ] = parm4; } if ( IsDefined( parm5 ) ) { ent.parms[ ent.parms.size ] = parm5; } level.run_func_after_wait_array[ level.run_func_after_wait_array.size ] = ent; } /* ============= ///ScriptDocBegin "Name: add_call( <func> , <parm1> , <parm2> , <parm3> )" "Summary: Adds a code function call that runs after an add_wait/do_wait completes." "Module: Utility" "MandatoryArg: <func>: The function." "OptionalArg: <parm1>: Optional parameter" "OptionalArg: <parm2>: Optional parameter" "OptionalArg: <parm3>: Optional parameter" "Example: level.player add_call( ::playerlinktodelta, node );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_call( func, parm1, parm2, parm3, parm4, parm5 ) { /# thread add_wait_asserter(); #/ ent = SpawnStruct(); ent.caller = self; ent.func = func; ent.parms = []; if ( IsDefined( parm1 ) ) { ent.parms[ ent.parms.size ] = parm1; } if ( IsDefined( parm2 ) ) { ent.parms[ ent.parms.size ] = parm2; } if ( IsDefined( parm3 ) ) { ent.parms[ ent.parms.size ] = parm3; } if ( IsDefined( parm4 ) ) { ent.parms[ ent.parms.size ] = parm4; } if ( IsDefined( parm5 ) ) { ent.parms[ ent.parms.size ] = parm5; } level.run_call_after_wait_array[ level.run_call_after_wait_array.size ] = ent; } /* ============= ///ScriptDocBegin "Name: add_noself_call( <func> , <parm1> , <parm2> , <parm3> )" "Summary: Adds a code function call that runs after an add_wait/do_wait completes." "Module: Utility" "MandatoryArg: <func>: The function." "OptionalArg: <parm1>: Optional parameter" "OptionalArg: <parm2>: Optional parameter" "OptionalArg: <parm3>: Optional parameter" "Example: add_noself_call( ::earthquake, blah, blah, blah );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_noself_call( func, parm1, parm2, parm3, parm4, parm5 ) { /# thread add_wait_asserter(); #/ ent = SpawnStruct(); ent.func = func; ent.parms = []; if ( IsDefined( parm1 ) ) { ent.parms[ ent.parms.size ] = parm1; } if ( IsDefined( parm2 ) ) { ent.parms[ ent.parms.size ] = parm2; } if ( IsDefined( parm3 ) ) { ent.parms[ ent.parms.size ] = parm3; } if ( IsDefined( parm4 ) ) { ent.parms[ ent.parms.size ] = parm4; } if ( IsDefined( parm5 ) ) { ent.parms[ ent.parms.size ] = parm5; } level.run_noself_call_after_wait_array[ level.run_noself_call_after_wait_array.size ] = ent; } /* ============= ///ScriptDocBegin "Name: add_endon( <endon> )" "Summary: Adds an endon that will kill a do_wait. Threads can't acquire a parent's endons so this is a way to force an endon in cases where a do_wait could be killed, otherwise it'll cause a thread leak." "Module: Utility" "MandatoryArg: <endon>: The endon." "Example: level.price add_endon( "shazam" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_endon( name ) { /# thread add_wait_asserter(); #/ ent = SpawnStruct(); ent.caller = self; ent.ender = name; level.do_wait_endons_array[ level.do_wait_endons_array.size ] = ent; } /* ============= ///ScriptDocBegin "Name: do_wait_any()" "Summary: Waits until any of functions defined by add_wait complete. Clears the global variable where the functions were being stored." "Module: Utility" "Example: do_wait_any();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ do_wait_any() { AssertEx( IsDefined( level.wait_any_func_array ), "Tried to do a do_wait without addings funcs first" ); AssertEx( level.wait_any_func_array.size > 0, "Tried to do a do_wait without addings funcs first" ); do_wait( level.wait_any_func_array.size - 1 ); } /* ============= ///ScriptDocBegin "Name: do_wait()" "Summary: Waits until all of the functions defined by add_wait complete. Clears the global variable where the functions were being stored." "Module: Utility" "Example: do_wait();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ do_wait( count_to_reach ) { if ( !isdefined( count_to_reach ) ) count_to_reach = 0; /# level notify( "kill_add_wait_asserter" ); #/ AssertEx( IsDefined( level.wait_any_func_array ), "Tried to do a do_wait without addings funcs first" ); ent = SpawnStruct(); array = level.wait_any_func_array; endons = level.do_wait_endons_array; after_array = level.run_func_after_wait_array; call_array = level.run_call_after_wait_array; nscall_array = level.run_noself_call_after_wait_array; abort_array = level.abort_wait_any_func_array; level.wait_any_func_array = []; level.run_func_after_wait_array = []; level.do_wait_endons_array = []; level.abort_wait_any_func_array = []; level.run_call_after_wait_array = []; level.run_noself_call_after_wait_array = []; ent.count = array.size; ent array_levelthread( array, ::waittill_func_ends, endons ); ent thread do_abort( abort_array ); ent endon( "any_funcs_aborted" ); for ( ;; ) { if ( ent.count <= count_to_reach ) break; ent waittill( "func_ended" ); } ent notify( "all_funcs_ended" ); array_levelthread( after_array, ::exec_func, [] ); array_levelthread( call_array, ::exec_call ); array_levelthread( nscall_array, ::exec_call_noself ); } /* ============= ///ScriptDocBegin "Name: do_funcs()" "Summary: Calls a series of add_funcs in order. When one finishes, the next starts. Etc." "Module: Utility" "Example: thread do_funcs();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ do_funcs() { /# level notify( "kill_add_wait_asserter" ); #/ AssertEx( IsDefined( level.wait_any_func_array ), "Tried to do a do_wait without addings funcs first" ); ent = SpawnStruct(); AssertEx( !level.wait_any_func_array.size, "Don't use add_wait and do_funcs together." ); AssertEx( !level.do_wait_endons_array.size, "Don't use add_endon and do_funcs together." ); AssertEx( !level.run_call_after_wait_array.size, "Don't use add_call and do_funcs together." ); AssertEx( !level.run_noself_call_after_wait_array.size, "Don't use add_call and do_funcs together." ); AssertEx( !level.abort_wait_any_func_array.size, "Do_funcs doesn't support add_abort." ); after_array = level.run_func_after_wait_array; level.run_func_after_wait_array = []; foreach ( func_struct in after_array ) { level exec_func( func_struct, [] ); } ent notify( "all_funcs_ended" ); } /* ============= ///ScriptDocBegin "Name: is_default_start()" "Summary: Returns true if you're playing from the default start" "Module: Utility" "Example: if ( is_default_start() )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_default_start() { if ( IsDefined( level.default_start_override ) && level.default_start_override == level.start_point ) return true; if ( IsDefined( level.default_start ) ) return level.start_point == "default"; if ( level_has_start_points() ) return level.start_point == level.start_functions[ 0 ][ "name" ]; return level.start_point == "default"; } /* ============= ///ScriptDocBegin "Name: is_first_start()" "Summary: Returns true if it is the first start point in the list of starts." "Module: Utility" "Example: if ( is_first_start() )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_first_start() { if ( !level_has_start_points() ) return true; return level.start_point == level.start_functions[ 0 ][ "name" ]; } /* ============= ///ScriptDocBegin "Name: _Earthquake( <scale> , <duration> , <source> , <radius> )" "Summary: Wrapper for earthquake command" "Module: Code Wrappers" "CallOn: Level" "MandatoryArg: <scale>: " "MandatoryArg: <duration>: " "MandatoryArg: <source>: " "MandatoryArg: <radius>: " "Example: delayThread( 0.1, ::_Earthquake, 0.4, 1.2, ent.origin, 6000 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ _Earthquake( scale, duration, source, radius ) { Earthquake( scale, duration, source, radius ); } /* ============= ///ScriptDocBegin "Name: waterfx( <endflag> )" "Summary: Makes AI have trails in water. Can be used on the player as well, so you're not a vampire." "Module: Utility" "CallOn: An AI or player" "OptionalArg: <endflag>: A flag to end on " "Example: level.price thread waterfx();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waterfx( endflag ) { // currently using these devraw fx: // level._effect[ "water_stop" ] = LoadFX( "misc/parabolic_water_stand" ); // level._effect[ "water_movement" ] = LoadFX( "misc/parabolic_water_movement" ); self endon( "death" ); if ( IsDefined( endflag ) ) { flag_assert( endflag ); level endon( endflag ); } for ( ;; ) { wait( RandomFloatRange( 0.15, 0.3 ) ); start = self.origin + ( 0, 0, 150 ); end = self.origin - ( 0, 0, 150 ); trace = BulletTrace( start, end, false, undefined ); if ( trace[ "surfacetype" ] != "water" ) continue; fx = "water_movement"; if ( IsPlayer( self ) ) { if ( Distance( self GetVelocity(), ( 0, 0, 0 ) ) < 5 ) { fx = "water_stop"; } } else if ( IsDefined( level._effect[ "water_" + self.a.movement ] ) ) { fx = "water_" + self.a.movement; } water_fx = getfx( fx ); start = trace[ "position" ]; //angles = vectortoangles( trace[ "normal" ] ); angles = (0,self.angles[1],0); forward = anglestoforward( angles ); up = anglestoup( angles ); PlayFX( water_fx, start, up, forward ); } } /* ============= ///ScriptDocBegin "Name: playerSnowFootsteps( <endflag> )" "Summary: Make the player have footstep fx in snow" "Module: Utility" "CallOn: player" "OptionalArg: <endflag>: A flag to end on " "Example: level.player thread playerSnowFootsteps();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ playerSnowFootsteps( endflag ) { // currently using these devraw fx: // level._effect[ "footstep_snow_small" ] = LoadFX( "impacts/footstep_snow_small" ); // level._effect[ "footstep_snow" ] = LoadFX( "impacts/footstep_snow" ); if ( IsDefined( endflag ) ) { flag_assert( endflag ); level endon( endflag ); } for ( ;; ) { wait( RandomFloatRange( 0.25, .5 ) ); start = self.origin + ( 0, 0, 0 ); end = self.origin - ( 0, 0, 5 ); trace = BulletTrace( start, end, false, undefined ); forward = AnglesToForward( self.angles ); mydistance = Distance( self GetVelocity(), ( 0, 0, 0 ) ); if ( IsDefined( self.vehicle ) ) continue; if ( trace[ "surfacetype" ] != "snow" ) continue; if ( mydistance <= 10 ) continue; fx = "snow_movement"; //iprintlnbold( "Moved" + mydistance ); if ( Distance( self GetVelocity(), ( 0, 0, 0 ) ) <= 154 ) { PlayFX( getfx( "footstep_snow_small" ), trace[ "position" ], trace[ "normal" ], forward ); } if ( Distance( self GetVelocity(), ( 0, 0, 0 ) ) > 154 ) { PlayFX( getfx( "footstep_snow" ), trace[ "position" ], trace[ "normal" ], forward ); } } } /* ============= ///ScriptDocBegin "Name: mix_up( <sound> )" "Summary: Used to blend sounds on a script model vehicle. See maps\sniperescape_code::seaknight_sound()" "Module: Utility" "CallOn: A sound blend entity" "OptionalArg: <Sound>: The sound alias to blend, blends with the _off version of the alias. " "Example: maps\sniperescape_code::seaknight_sound();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ mix_up( sound ) { timer = 3 * 20; for ( i = 0; i < timer; i++ ) { self SetSoundBlend( sound, sound + "_off", ( timer - i ) / timer ); wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: mix_down( <sound> )" "Summary: Used to blend sounds on a script model vehicle. See maps\sniperescape_code::seaknight_sound()" "Module: Utility" "CallOn: A sound blend entity" "OptionalArg: <Sound>: The sound alias to blend, blends with the _off version of the alias. " "Example: maps\sniperescape_code::seaknight_sound();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ mix_down( sound ) { timer = 3 * 20; for ( i = 0; i < timer; i++ ) { self SetSoundBlend( sound, sound + "_off", i / timer ); wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: manual_linkto( <entity> , <offset> )" "Summary: Sets an entity to the origin of another entity every server frame, for entity types that don't support linkto" "Module: Utility" "CallOn: An entity that doesn't support linkto, like soundblend entities." "MandatoryArg: <entity>: The entity to link to " "OptionalArg: <offset>: The offset to use " "Example: flyblend thread manual_linkto( self, (0,0,0) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ manual_linkto( entity, offset ) { entity endon( "death" ); self endon( "death" ); // for entities that don't support linkto, like soundblend entities if ( !isdefined( offset ) ) { offset = ( 0, 0, 0 ); } for ( ;; ) { self.origin = entity.origin + offset; self.angles = entity.angles; wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: nextmission()" "Summary: Sends level to nextmission via _endmission script, one place for handling transitions" "Module: Code Wrappers" "CallOn: Level" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ nextmission() { maps\_endmission::_nextmission(); } /* ============= ///ScriptDocBegin "Name: make_array( <index1> , <index2> , <index3> , <index4> , <index5> )" "Summary: make an array with the stuff. (up to 5 things) " "Module: Utility" "CallOn: An entity" "MandatoryArg: <index1>: " "OptionalArg: <index2>: " "OptionalArg: <index3>: " "OptionalArg: <index4>: " "OptionalArg: <index5>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ make_array( index1, index2, index3, index4, index5 ) { AssertEx( IsDefined( index1 ), "Need to define index 1 at least" ); array = []; array[ array.size ] = index1; if ( IsDefined( index2 ) ) { array[ array.size ] = index2; } if ( IsDefined( index3 ) ) { array[ array.size ] = index3; } if ( IsDefined( index4 ) ) { array[ array.size ] = index4; } if ( IsDefined( index5 ) ) { array[ array.size ] = index5; } return array; } /* ============= ///ScriptDocBegin "Name: fail_on_friendly_fire()" "Summary: If this is run, the player will fail the mission if he kills a friendly" "Module: Utility" "Example: fail_on_friendly_fire();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ fail_on_friendly_fire() { level.failOnFriendlyFire = true; } /* ============= ///ScriptDocBegin "Name: normal_friendly_fire_penalty()" "Summary: Returns friendly fire penalty to normal" "Module: Utility" "Example: normal_friendly_fire_penalty();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ normal_friendly_fire_penalty() { level.failOnFriendlyFire = false; } /* ============= ///ScriptDocBegin "Name: getPlayerClaymores()" "Summary: Returns the number of claymores the player has" "Module: Utility" "Example: count = getPlayerClaymores();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getPlayerClaymores() { Assert( IsPlayer( self ) ); heldweapons = self GetWeaponsListAll(); stored_ammo = []; for ( i = 0; i < heldweapons.size; i++ ) { weapon = heldweapons[ i ]; stored_ammo[ weapon ] = self GetWeaponAmmoClip( weapon ); } claymoreCount = 0; if ( IsDefined( stored_ammo[ "claymore" ] ) && stored_ammo[ "claymore" ] > 0 ) { claymoreCount = stored_ammo[ "claymore" ]; } return claymoreCount; } /* ============= ///ScriptDocBegin "Name: getPlayerC4()" "Summary: Returns the number of c4 the player has" "Module: Utility" "Example: count = getPlayerC4();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getPlayerC4() { Assert( IsPlayer( self ) ); heldweapons = self GetWeaponsListAll(); stored_ammo = []; for ( i = 0; i < heldweapons.size; i++ ) { weapon = heldweapons[ i ]; stored_ammo[ weapon ] = self GetWeaponAmmoClip( weapon ); } c4Count = 0; if ( IsDefined( stored_ammo[ "c4" ] ) && stored_ammo[ "c4" ] > 0 ) { c4Count = stored_ammo[ "c4" ]; } return c4Count; } /* ============= ///ScriptDocBegin "Name: _wait( <timer> )" "Summary: wrapper for wait command" "Module: Code Wrappers" "CallOn: An entity" "MandatoryArg: <timer>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _wait( timer ) { wait( timer ); } /* ============= ///ScriptDocBegin "Name: _waittillmatch( <msg> , <match> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _waittillmatch( msg, match ) { self waittillmatch( msg, match ); } /* ============= ///ScriptDocBegin "Name: _setsaveddvar( <var> , <val> )" "Summary: code wrapper for setsaveddvar" "Module: Code Wrappers" "CallOn: Level" "MandatoryArg: <var>: dvar" "OptionalArg: <val>: value to set" "Example: delayThread( 9, ::_setsaveddvar, "g_friendlynamedist", level.friendlynamedist );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ _setsaveddvar( var, val ) { SetSavedDvar( var, val ); } /* ============= ///ScriptDocBegin "Name: lerp_savedDvar( <name> , <value> , <time> )" "Summary: lerps a saveddvar float setting over time" "Module: dvar" "CallOn: " "MandatoryArg: <name>: the name of the dvar" "MandatoryArg: <value>: the value to set it to" "MandatoryArg: <time>: the time to blend to the new value" "Example: thread lerp_savedDvar( "r_lightGridIntensity", .695, .75 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ lerp_savedDvar( name, value, time ) { curr = GetDvarFloat( name ); range = value - curr; interval = .05; count = Int( time / interval ); delta = range / count; while ( count ) { curr += delta; SetSavedDvar( name, curr ); wait interval; count--; } SetSavedDvar( name, value ); } /* ============= ///ScriptDocBegin "Name: giveachievement_wrapper( <achievement> )" "Summary: Gives achievement to all players. Only does so if the player isn't cheating and hasn't cheated." "Module: Code Wrappers" "MandatoryArg: <achievement>: " "Example: giveachievement_wrapper( "RESCUE_ROYCEWICZ" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ giveachievement_wrapper( achievement ) { if( level.script == "ending" && isdefined( level.level_mode ) && level.level_mode == "free" )//char museum return; foreach ( player in level.players ) { player GiveAchievement( achievement ); } /# println( "ACHIEVEMENT: " + achievement ); #/ } /* ============= ///ScriptDocBegin "Name: player_giveachievement_wrapper( <achievement> )" "Summary: Gives achievement to a specific player. Only does so if the player isn't cheating and hasn't cheated." "Module: Code Wrappers" "CallOn: Player" "MandatoryArg: <achievement>: " "Example: player giveachievement_wrapper( "RESCUE_ROYCEWICZ" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_giveachievement_wrapper( achievement ) { if( level.script == "ending" && isdefined( level.level_mode ) && level.level_mode == "free" )//char museum return; self GiveAchievement( achievement ); /# println( "ACHIEVEMENT: " + achievement ); #/ } /* ============= ///ScriptDocBegin "Name: add_jav_glow( <optional_glow_delete_flag> )" "Summary: Adds glow to the Javelin." "Module: Utility" "CallOn: A Javelin weapon" "OptionalArg: <optional_glow_delete_flag>: Flag to disable the glow. " "Example: jav thread add_jav_glow( "overpass_baddies_flee" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_jav_glow( optional_glow_delete_flag ) { jav_glow = Spawn( "script_model", ( 0, 0, 0 ) ); jav_glow SetContents( 0 ); jav_glow SetModel( "weapon_javelin_obj" ); jav_glow.origin = self.origin; jav_glow.angles = self.angles; self add_wait( ::delete_on_not_defined ); if ( IsDefined( optional_glow_delete_flag ) ) { flag_assert( optional_glow_delete_flag ); add_wait( ::flag_wait, optional_glow_delete_flag ); } do_wait_any(); jav_glow Delete(); } /* ============= ///ScriptDocBegin "Name: add_c4_glow( <optional_glow_delete_flag> )" "Summary: Adds glow to the C4." "Module: Utility" "CallOn: A C4 weapon" "OptionalArg: <optional_glow_delete_flag>: Flag to disable the glow. " "Example: c4 thread add_c4_glow( "overpass_baddies_flee" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_c4_glow( optional_glow_delete_flag ) { c4_glow = Spawn( "script_model", ( 0, 0, 0 ) ); c4_glow SetContents( 0 ); c4_glow SetModel( "weapon_c4_obj" ); c4_glow.origin = self.origin; c4_glow.angles = self.angles; self add_wait( ::delete_on_not_defined ); if ( IsDefined( optional_glow_delete_flag ) ) { flag_assert( optional_glow_delete_flag ); add_wait( ::flag_wait, optional_glow_delete_flag ); } do_wait_any(); c4_glow Delete(); } /* ============= ///ScriptDocBegin "Name: delete_on_not_defined()" "Summary: Weapons don't seem to notify death when they're picked up." "Module: Utility" "CallOn: An entity" "Example: javelin delete_on_not_defined()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ delete_on_not_defined() { for ( ;; ) { if ( !isdefined( self ) ) return; wait( 0.05 ); } } /* ============= ///ScriptDocBegin "Name: slowmo_start( <slowmo_start> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_start() { } /* ============= ///ScriptDocBegin "Name: slowmo_end( <slowmo_end> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_end() { } /* ============= ///ScriptDocBegin "Name: slowmo_setspeed_slow( <speed> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_setspeed_slow( speed ) { level.slowmo.speed_slow = speed; } /* ============= ///ScriptDocBegin "Name: slowmo_setspeed_norm( <speed> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_setspeed_norm( speed ) { level.slowmo.speed_norm = speed; } /* ============= ///ScriptDocBegin "Name: slowmo_setlerptime_in( <time> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_setlerptime_in( time ) { level.slowmo.lerp_time_in = time; } /* ============= ///ScriptDocBegin "Name: slowmo_setlerptime_out( <time> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_setlerptime_out( time ) { level.slowmo.lerp_time_out = time; } /* ============= ///ScriptDocBegin "Name: slowmo_lerp_in( <slowmo_lerp_in> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_lerp_in() { SetSlowMotion( level.slowmo.speed_norm, level.slowmo.speed_slow, level.slowmo.lerp_time_in ); //setslowmotionview( level.slowmo.speed_norm, level.slowmo.speed_slow, level.slowmo.lerp_time_in ); //changed for slomo breach } /* ============= ///ScriptDocBegin "Name: slowmo_lerp_out( <slowmo_lerp_out> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ slowmo_lerp_out() { setslowmotion( level.slowmo.speed_slow, level.slowmo.speed_norm, level.slowmo.lerp_time_out ); } /* ============= ///ScriptDocBegin "Name: add_earthquake( <name> , <mag> , <duration> , <radius> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_earthquake( name, mag, duration, radius ) { level.earthquake[ name ][ "magnitude" ] = mag; level.earthquake[ name ][ "duration" ] = duration; level.earthquake[ name ][ "radius" ] = radius; } /* ============= ///ScriptDocBegin "Name: arcadeMode_kill( <origin> , <damage_type> , <amount> )" "Summary: Rewards points for a kill in arcade mode." "Module: ArcadeMode" "MandatoryArg: <origin>: Location of kill" "MandatoryArg: <damage_type>: explosive, pistol, rifle, or melee" "MandatoryArg: <amount>: Amount of points rewarded" "Example: arcadeMode_kill( self.origin, "explosive", 500 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ arcadeMode_kill( origin, damage_type, amount ) { if ( GetDvar( "arcademode" ) != "1" ) return; thread maps\_arcademode::arcadeMode_add_points( origin, true, damage_type, amount ); } /* ============= ///ScriptDocBegin "Name: arcadeMode_damage( <origin> , <damage_type> , <amount> )" "Summary: Rewards points for a kill in arcade mode." "Module: ArcadeMode" "MandatoryArg: <origin>: Location of kill" "MandatoryArg: <damage_type>: explosive, pistol, rifle, or melee" "MandatoryArg: <amount>: Amount of points rewarded" "Example: arcadeMode_damage( self.origin, "explosive", 500 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ arcadeMode_damage( origin, damage_type, amount ) { if ( GetDvar( "arcademode" ) != "1" ) return; thread maps\_arcademode::arcadeMode_add_points( origin, false, damage_type, amount ); } /* ============= ///ScriptDocBegin "Name: arcademode_checkpoint( <minutes_remaining> )" "Summary: Gives a checkpoint in Arcademode and sets a new remaining time." "Module: ArcadeMode" "MandatoryArg: <minutes_remaining>: The time the player has until they fail or reach the next checkpoint or win " "Example: arcademode_checkpoint( 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ arcademode_checkpoint( time_remaining, unique_id ) { if ( 1 ) return; if ( GetDvar( "arcademode" ) != "1" ) return; id = maps\_arcadeMode::arcademode_checkpoint_getid( unique_id ); if ( !isdefined( id ) ) { id = level.arcadeMode_checkpoint_dvars.size; // add the unique_id to the list if it doesn't exist yet level.arcadeMode_checkpoint_dvars[ level.arcadeMode_checkpoint_dvars.size ] = unique_id; AssertEx( level.arcadeMode_checkpoint_dvars.size <= level.arcadeMode_checkpoint_max, "Exceeded max number of arcademode checkpoints." ); } // make sure we don't do the same checkpoint twice if ( GetDvar( "arcademode_checkpoint_" + id ) == "1" ) return; SetDvar( "arcademode_checkpoint_" + id, "1" ); if ( GetDvar( "arcademode_full" ) == "1" ) { if ( level.gameskill == 2 ) time_remaining *= 2.0; if ( level.gameskill == 3 ) time_remaining *= 2.5; } // save the remaining time to add it back on at the end // then set the remaining time to the new time_remaining remaining_time = GetDvarInt( "arcademode_time" ); stored_time = GetDvarInt( "arcademode_stored_time" ); stored_time += remaining_time; SetDvar( "arcademode_stored_time", stored_time ); SetDvar( "arcademode_time", time_remaining * 60 ); start_offset = 800; movetime = 0.8; level.player thread play_sound_in_space( "arcademode_checkpoint", level.player GetEye() ); thread maps\_arcademode::draw_checkpoint( start_offset, movetime, 1 ); thread maps\_arcademode::draw_checkpoint( start_offset, movetime, -1 ); } /* ============= ///ScriptDocBegin "Name: arcadeMode()" "Summary: returns true if arcade mode is on" "Module: Utility" "CallOn: Level" "Example: if(arcademode){ dothestuf(); }" "SPMP: singleplayer" ///ScriptDocEnd ============= */ arcadeMode() { return GetDvar( "arcademode" ) == "1"; } /* ============= ///ScriptDocBegin "Name: arcadeMode_stop_timer()" "Summary: Stops the countdown timer in arcademode, for missions that have non-competitive ending sequences." "Module: ArcadeMode" "Example: arcadeMode_stop_timer();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ arcadeMode_stop_timer() { if ( !isdefined( level.arcadeMode_hud_timer ) ) return; level notify( "arcadeMode_remove_timer" ); level.arcademode_stoptime = GetTime(); level.arcadeMode_hud_timer Destroy(); level.arcadeMode_hud_timer = undefined; } /* ============= ///ScriptDocBegin "Name: MusicPlayWrapper( <song> , <timescale> , <overrideCheat> )" "Summary: wrapper for music play for arcade mode stuff." "Module: Code Wrappers" "CallOn: Level" "MandatoryArg: <song>: song to play" "OptionalArg: <timescale>: timescale param to pass to musicplay" "OptionalArg: <overrideCheat>: overrideCheat param to pass to musicplay" "Example: MusicPlayWrapper( "credits_bog_victory" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ MusicPlayWrapper( song, timescale, overrideCheat ) { level.last_song = song; if ( !arcadeMode() || !flag( "arcadeMode_multiplier_maxed" ) ) { if ( !isdefined( timescale ) ) timescale = true; if ( !isdefined( overrideCheat ) ) overrideCheat = false; MusicStop( 0 ); MusicPlay( song, timescale, overrideCheat ); } } /* ============= ///ScriptDocBegin "Name: music_loop( <name> , <time>, <fade_time> )" "Summary: stops any previously playing music, and plays a track of music that loops." "Module: Utility" "CallOn: " "MandatoryArg: <name>: the name of the music track" "MandatoryArg: <time>: The amount of time to wait between loops. If > 10, will be ignored." "OptionalArg: <fade_time>: optional fade time IN SECONDS to fade out any previously playing music...if undefined, previously playing music will end immediately" "Example: music_loop( 'ICBM_tension_music', 112 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ music_loop( name, time, fade_time, timescale, overrideCheat ) { thread music_loop_internal( name, time, fade_time, timescale, overrideCheat ); } /* ============= ///ScriptDocBegin "Name: music_loop_stealth( <name> , <length>, <fade_time> )" "Summary: stops any previously playing music, and plays a track of music that loops. The music will automatically pause on stealth_spotted and resume on stealth_hidden." "Module: Utility" "CallOn: " "MandatoryArg: <name>: the name of the music track" "MandatoryArg: <length>: the length of the music track IN SECONDS (if short, the song will end and loop early )" "OptionalArg: <fade_time>: optional fade time IN SECONDS to fade out any previously playing music...if undefined, previously playing music will end immediately" "Example: music_loop_stealth( 'ICBM_tension_music', 112 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ music_loop_stealth( name, length, fade_time, timescale, overrideCheat ) { thread music_loop_internal( name, length, fade_time, timescale, overrideCheat, true ); } /* ============= ///ScriptDocBegin "Name: music_play( <name> , <fade_time> )" "Summary: stops any previously playing music, and plays a new piece of music." "Module: Utility" "CallOn: " "MandatoryArg: <name>: the name of the music track" "OptionalArg: <fade_time>: optional fade time IN SECONDS to fade out any previously playing music...if undefined, previously playing music will end immediately" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ music_play( name, fade_time, timescale, overrideCheat ) { if ( IsDefined( fade_time ) && fade_time > 0 ) { thread music_play_internal_stop_with_fade_then_call( name, fade_time, timescale, overrideCheat ); return; } music_stop(); MusicPlayWrapper( name, timescale, overrideCheat ); } /* ============= ///ScriptDocBegin "Name: music_stop( <fade_time> )" "Summary: stops any currently playing music, including loops" "Module: Entity" "CallOn: An entity" "OptionalArg: <fade_time>: the time IN SECONDS to stop the currently playing music" "Example: music_stop( 3 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ music_stop( fade_time ) { if ( !isdefined( fade_time ) || fade_time <= 0 ) MusicStop(); else MusicStop( fade_time ); level notify( "stop_music" ); } /* ============= ///ScriptDocBegin "Name: player_is_near_live_grenade()" "Summary: Returns true if player(s) is near a live grenade" "Module: Utility" "CallOn: Level" "Example: if( player_is_near_live_grenade() )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_is_near_live_grenade() { grenades = GetEntArray( "grenade", "classname" ); for ( i = 0; i < grenades.size; i++ ) { grenade = grenades[ i ]; if ( grenade.model == "weapon_claymore" ) continue; for ( playerIndex = 0; playerIndex < level.players.size; playerIndex++ ) { player = level.players[ playerIndex ]; if ( DistanceSquared( grenade.origin, player.origin ) < ( 275 * 275 ) )// grenade radius is 256 { /# maps\_autosave::AutoSavePrint( "autosave failed: live grenade too close to player" ); #/ return true; } } } return false; } /* ============= ///ScriptDocBegin "Name: player_died_recently()" "Summary: check the player_died_recently dvar" "Module: Utility" "CallOn: Level" "Example: if(player_died_recently())" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_died_recently() { return GetDvarInt( "player_died_recently", "0" ) > 0; } /* ============= ///ScriptDocBegin "Name: all_players_istouching( eVolume )" "Summary: Returns true/false if all coop players are currently touching eVolume. Does IsTouching() code function on all coop players (or just single player if no coop enabled)." "Module: Player" "MandatoryArg: <eVolume>: The volume you are checking to see that the players are touching." "Example: while ( coop_players_touching( eRoomVolume ) )....<do something>" "SPMP: singleplayer" ///ScriptDocEnd ============= */ all_players_istouching( eVolume ) { AssertEx( IsDefined( eVolume ), "eVolume parameter not defined" ); foreach ( player in level.players ) { if ( !player IsTouching( eVolume ) ) return false; } return true; } /* ============= ///ScriptDocBegin "Name: any_players_istouching( eVolume )" "Summary: Returns true/false if any coop players are currently touching eVolume. Does IsTouching() code function on all coop players (or just single player if no coop enabled)." "Module: Player" "MandatoryArg: <eVolume>: The volume you are checking to see that the players are touching." "Example: while ( coop_players_touching( eRoomVolume ) )....<do something>" "SPMP: singleplayer" ///ScriptDocEnd ============= */ any_players_istouching( eVolume ) { AssertEx( IsDefined( eVolume ), "eVolume parameter not defined" ); foreach ( player in level.players ) { if ( player IsTouching( eVolume ) ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: get_ent_closest_to_flag_trig( sFlagName, aEnts )" "Summary: Returns the entity that is closest to a given flag trigger" "Module: Distance" "MandatoryArg: <sFlagName>: The script_flag value of the trigger in question." "MandatoryArg: <aEnts>: Array of entities you want to check." "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_ent_closest_to_flag_trig( sFlagName, aEnts ) { AssertEx( IsDefined( sFlagName ), "You need to specify the name of the script_flag key for this function" ); AssertEx( IsDefined( aEnts ), "You need to specify the array of entities you want to check" ); AssertEx( aEnts.size > 0, "The array passed is empty" ); if ( aEnts.size == 1 ) return aEnts[ 0 ]; flag_trig = undefined; eEnt = undefined; trigs = GetEntArray( "trigger_multiple", "classname" ); for ( i = 0; i < trigs.size; i++ ) { if ( ( IsDefined( trigs[ i ].script_flag ) ) && ( trigs[ i ].script_flag == sFlagName ) ) { flag_trig = trigs[ i ]; break; } } AssertEx( IsDefined( flag_trig ), "Cannot find a flag trigger with the script_flag name of :" + sFlagName ); eEnt = getClosest( flag_trig.origin, aEnts ); AssertEx( IsDefined( eEnt ), "Could not determine which entity was closest to flag trigger " + sFlagName ); return eEnt; } is_legacy_map() { return level.is_legacy_map; } /* ============= ///ScriptDocBegin "Name: getDifficulty( <getDifficulty> )" "Summary: Returns level difficulty in "easy","medium", "hard", or "fu" format." "Module: Utility" "CallOn: Level" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ getDifficulty() { Assert( IsDefined( level.gameskill ) ); if ( level.gameskill < 1 ) return "easy"; if ( level.gameskill < 2 ) return "medium"; if ( level.gameskill < 3 ) return "hard"; return "fu"; } /* ============= ///ScriptDocBegin "Name: hide_players( <qBool> )" "Summary: Hides the player models." "Module: Utility" "MandatoryArg: <qBool>: True/false to hide/unhide the players." "SPMP: singleplayer" ///ScriptDocEnd ============= */ hide_players( qBool ) { for ( i = 0; i < level.players.size; i++ ) { if ( qBool == true ) level.players[ i ] Hide(); else level.players[ i ] Show(); } } /* ============= ///ScriptDocBegin "Name: SetModelFunc( <modelFunc> )" "Summary: Runs the model setting function on a player, to set a player's 3rd person model." "Module: Utility" "CallOn: A player" "MandatoryArg: <modelFunc>: The function to run on the player " "Example: self SetModelFunc( ::so_body_ranger_player1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ SetModelFunc( modelFunc, starts_off ) { if ( !isdefined( starts_off ) ) starts_off = false; thread maps\_loadout::UpdateModel( modelFunc ); } /* ============= ///ScriptDocBegin "Name: isPlayerDown()" "Summary: Returns whether the player is dead or waiting to be revived." "Module: Flag" "CallOn: A player" "Example: player isPlayerDown()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ isPlayerDown() { Assert( IsPlayer( self ) ); if ( is_coop() && flag( "coop_revive" ) ) { if ( self ent_flag( "coop_downed" ) ) return true; } return !isAlive( self ); } /* ============= ///ScriptDocBegin "Name: getAveragePlayerOrigin()" "Summary: Returns the average player origin of level.players array." "Module: Utility" "CallOn: " "Example: org = getAveragePlayerOrigin();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getAveragePlayerOrigin() { averageOrigin_x = 0; averageOrigin_y = 0; averageOrigin_z = 0; foreach ( player in level.players ) { averageOrigin_x += player.origin[ 0 ]; averageOrigin_y += player.origin[ 1 ]; averageOrigin_z += player.origin[ 2 ]; } averageOrigin_x = averageOrigin_x / level.players.size; averageOrigin_y = averageOrigin_y / level.players.size; averageOrigin_z = averageOrigin_z / level.players.size; return( averageOrigin_x, averageOrigin_y, averageOrigin_z ); } /* ============= ///ScriptDocBegin "Name: get_average_origin( <array> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_average_origin( array ) { origin = ( 0, 0, 0 ); foreach ( member in array ) origin += member.origin; return vector_multiply( origin, ( 1.0 / array.size ) ); } /* ============= ///ScriptDocBegin "Name: add_damage_function( <func> )" "Summary: Adds a damage function to an AI. It is called when the AI takes damage. The AI function must have all 7 of the required parameters." "Module: Spawner" "CallOn: An AI" "MandatoryArg: <func > The function to be run when the AI takes damage. " "Example: ai add_damage_function( ::got_hurt );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_damage_function( func ) { self.damage_functions[ self.damage_functions.size ] = func; } /* ============= ///ScriptDocBegin "Name: remove_damage_function( <func> )" "Summary: Removes a damage function that was added with add_damage_function." "Module: Spawner" "CallOn: An AI" "MandatoryArg: <func > The function to be removed. " "Example: ai remove_damage_function( ::got_hurt );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ remove_damage_function( damage_func ) { new_array = []; foreach ( func in self.damage_functions ) { if ( func == damage_func ) continue; new_array[ new_array.size ] = func; } self.damage_functions = new_array; } /* ============= ///ScriptDocBegin "Name: giveXp( <type>, <value> )" "Summary: Gives a player XP either by predefined <type> or customized <value>, single player XP gain feature must be enabled to use this." "Module: Spawner" "CallOn: A Player" "MandatoryArg: <type> String name of type of XP given. Does not need to be an existing type, can be any label for the XP reward." "OptionalArg: <value> Int value of XP given. If not defined, type's XP reward will be awarded. If type does not exist, default 'kill' type XP will be awarded." "Example: level.player giveXp( "assist" ); level.player2 giveXp( "pwn", 10000 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ giveXp( type, value ) { self maps\_rank::updatePlayerScore( type, value ); } /* ============= ///ScriptDocBegin "Name: giveMoney( <type>, <amount> )" "Summary: Gives a player money either by predefined <type> or customized <value>, single player money gain feature must be enabled to use this." "Module: Spawner" "CallOn: A Player" "MandatoryArg: <type> String name of type of money given. Does not need to be an existing type, can be any label for the money reward." "OptionalArg: <value> Int value of money given. If not defined, type's money reward will be awarded. If type does not exist, default 'kill' type money will be awarded." "Example: level.player giveMoney( "assist" ); level.player2 giveXp( "pwn", 1000 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ giveMoney( type, amount, attacker ) { self maps\_money::updatePlayerMoney( type, amount, attacker ); } /* ============= ///ScriptDocBegin "Name: playLocalSoundWrapper( <soundalias> )" "Summary: Calls playLocalSound on self. This function was made so it can be used in array_thread" "Module: Player" "CallOn: A Player" "MandatoryArg: <soundalias> Soundalias to played." "Example: level.player playLocalSoundWrapper( "mission_complete_sound" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ playLocalSoundWrapper( alias ) { Assert( IsDefined( alias ) ); self PlayLocalSound( alias ); } /* ============= ///ScriptDocBegin "Name: enablePlayerWeapons( <bool> )" "Summary: enables or disables weapons on single all players (singleplayer or coop)" "Module: Player" "MandatoryArg: <bool> True or false to enable or disable weapons" "Example: enablePlayerWeapons( false );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enablePlayerWeapons( bool ) { AssertEx( IsDefined( bool ), "Need to pass either 'true' or 'false' to enable/disable weapons" ); if ( level.players.size < 1 ) return; foreach ( player in level.players ) { if ( bool == true ) player EnableWeapons(); else player DisableWeapons(); } } /* ============= ///ScriptDocBegin "Name: teleport_players( aNodes )" "Summary: Teleports coop players to an array of nodes" "Module: Player" "MandatoryArg: <aNodes> An array of exactly 2 nodes (to account for the possibility of a second player)" "Example: teleport_players( aPlayerNodes, true );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ teleport_players( aNodes ) { //->not supporting coop in SP anymore //assertEx( aNodes.size == 2, "An array of exactly 2 nodes is required to teleport 2 coop players" ); player1node = undefined; player2node = undefined; eNode = undefined; foreach ( node in aNodes ) { if ( ( IsDefined( node.script_noteworthy ) ) && ( node.script_noteworthy == "player1" ) ) player1node = node; else if ( ( IsDefined( node.script_noteworthy ) ) && ( node.script_noteworthy == "player2" ) ) player2node = node; else { if ( !isdefined( player1node ) ) player1node = node; if ( !isdefined( player2node ) ) player2node = node; } } foreach ( player in level.players ) { if ( player == level.player ) eNode = player1node; else if ( player == level.player2 ) eNode = player2node; player SetOrigin( eNode.origin ); player SetPlayerAngles( eNode.angles ); } } /* ============= ///ScriptDocBegin "Name: teleport_player( <object> )" "Summary: move the player to the origin and angles of the specified object" "Module: Player" "CallOn: A Player" "MandatoryArg: <param1>: " "Example: level.player teleport_player( getstruct("start_surprized_parachute_moment","script_noteworthy" ) );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ teleport_player( object ) { level.player SetOrigin( object.origin ); level.player SetPlayerAngles( object.angles ); } /* ============= ///ScriptDocBegin "Name: hide_player_model()" "Summary: Hide the players model." "Module: Utility" "CallOn: A player" "Example: level.players[0] hide_player_model(); " "SPMP: singleplayer" ///ScriptDocEnd ============= */ hide_player_model() { if ( !is_coop() ) return; self.is_hidden = true; AssertEx( IsDefined( self.last_modelfunc ), "can't Hide player model on a player that hasn't been through maps\_loadout::UpdateModel()" ); thread maps\_loadout::UpdateModel( undefined ); } /* ============= ///ScriptDocBegin "Name: show_player_model()" "Summary: Show the players model." "Module: Utility" "CallOn: A player" "Example: level.players[0] show_player_model(); " "SPMP: singleplayer" ///ScriptDocEnd ============= */ show_player_model() { if ( !is_coop() ) return; self.is_hidden = false; AssertEx( IsDefined( self.last_modelfunc ), "can't Show player model on a player that hasn't been through maps\_loadout::UpdateModel()" ); thread maps\_loadout::UpdateModel( self.last_modelfunc ); } /* ============= ///ScriptDocBegin "Name: translate_local()" "Summary: Translates an entity in space" "Module: Utility" "CallOn: A spawnstruct" "MandatoryArg: <.entity>: Member variable on spawnstruct that sets the entity that will be moved" "OptionalArg: <.entities>: Member variable on spawnstruct that sets an array of entities to be moved" "OptionalArg: <.forward>: Member variable on spawnstruct that determines how far forward the entity will move" "OptionalArg: <.right>: Member variable on spawnstruct that determines how far right the entity will move" "OptionalArg: <.up>: Member variable on spawnstruct that determines how far up the entity will move" "OptionalArg: <.yaw>: Member variable on spawnstruct that determines how much to rotate the yaw" "OptionalArg: <.pitch>: Member variable on spawnstruct that determines how much to rotate the pitch" "OptionalArg: <.roll>: Member variable on spawnstruct that determines how much to rotate the roll" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ translate_local() { entities = []; if ( IsDefined( self.entities ) ) entities = self.entities; if ( IsDefined( self.entity ) ) entities[ entities.size ] = self.entity; AssertEx( entities.size > 0, "Tried to do translate_local without any entities" ); array_levelthread( entities, ::translate_local_on_ent ); } /* ============= ///ScriptDocBegin "Name: open_up_fov( <time> , <player_rig> , <tag> , <arcRight> , <arcLeft> , <arcTop> , <arcBottom> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ open_up_fov( time, player_rig, tag, arcRight, arcLeft, arcTop, arcBottom ) { level.player endon( "stop_opening_fov" ); wait( time ); level.player PlayerLinkToDelta( player_rig, tag, 1, arcRight, arcLeft, arcTop, arcBottom, true ); } /* ============= ///ScriptDocBegin "Name: get_ai_touching_volume( sTeam, species )" "Summary: Returns an array of all ai touching a specified info_volume" "Module: Utility" "CallOn: An info_volume" "OptionalArg: <sTeam>: 'axis' or 'allies'. Left blank the function will return an array containing all ai of all teams." "OptionalArg: <species>: 'human', 'dog', 'civilians'. Left blank the function will return an array containing all ai of all species." "Example: aEnemies = eRoomVolume get_ai_touching_volume( team )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_ai_touching_volume( sTeam, species, bGetDrones ) { if ( !isdefined( sTeam ) ) sTeam = "all"; if ( !isdefined( species ) ) species = "all"; aTeam = GetAISpeciesArray( sTeam, species ); aGuysTouchingVolume = []; foreach ( guy in aTeam ) { AssertEx( IsAlive( guy ), "Got ai array yet got a dead guy!" ); if ( guy IsTouching( self ) ) aGuysTouchingVolume[ aGuysTouchingVolume.size ] = guy; } return aGuysTouchingVolume; } /* ============= ///ScriptDocBegin "Name: get_drones_touching_volume( sTeam )" "Summary: Returns an array of all ai touching a specified info_volume" "Module: Utility" "CallOn: An info_volume" "OptionalArg: <sTeam>: 'axis', 'allies' or 'neutral. Left blank the function will return an array containing all ai of all teams." "Example: aDrones = eRoomVolume get_drones_touching_volume( "axis" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_drones_touching_volume( sTeam ) { if ( !isdefined( sTeam ) ) sTeam = "all"; aDrones = []; if ( sTeam == "all" ) { aDrones = array_merge( level.drones[ "allies" ].array, level.drones[ "axis" ].array ); aDrones = array_merge( aDrones, level.drones[ "neutral" ].array ); } else aDrones = level.drones[ sTeam ].array; aDronesToReturn = []; foreach ( drone in aDrones ) { if ( !isdefined( drone ) ) continue; if ( drone IsTouching( self ) ) aDronesToReturn[ aDronesToReturn.size ] = drone; } return aDronesToReturn; } /* ============= ///ScriptDocBegin "Name: get_drones_with_targetname( sTargetname )" "Summary: Returns an array of all live drones with the specified targetname" "Module: Utility" "MandatoryArg: <"MandatoryArg>: Targetname of the drones you want." "Example: aDrones = get_drones_with_targetname( bunker_drones )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_drones_with_targetname( sTargetname ) { aDrones = array_merge( level.drones[ "allies" ].array, level.drones[ "axis" ].array ); aDrones = array_merge( aDrones, level.drones[ "neutral" ].array ); aDronesToReturn = []; foreach ( drone in aDrones ) { if ( !isdefined( drone ) ) continue; if ( ( IsDefined( drone.targetname ) ) && ( drone.targetname == sTargetname ) ) aDronesToReturn[ aDronesToReturn.size ] = drone; } return aDronesToReturn; } /* ============= ///ScriptDocBegin "Name: get_other_player( <player> )" "Summary: Gets the other player in Coop." "Module: Utility" "MandatoryArg: <player>: A player. The function will return the other player in coop" "Example: other_player = get_other_player( player );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_other_player( player ) { Assert( is_coop() ); Assert( isdefined( player ) && isplayer( player ) ); foreach ( other_player in level.players ) { if ( player == other_player ) continue; return other_player; } AssertMsg( "get_other_player() tried to get other player but there is no other player." ); } /* ============= ///ScriptDocBegin "Name: is_other_player_downed( <player> )" "Summary: Checks if other player in downed in Coop." "Module: Utility" "MandatoryArg: <player>: A player. The function will check if the other player in downed in coop" "Example: if ( is_other_player_downed( player ); )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_other_player_downed( player ) { Assert( is_coop() ); Assert( isdefined( player ) && isplayer( player ) ); other_player = get_other_player( player ); Assert( IsDefined( other_player ) ); return( other_player ent_flag_exist( "coop_downed" ) && other_player ent_flag( "coop_downed" ) ); } /* ============= ///ScriptDocBegin "Name: set_count( <count> )" "Summary: Set the count of a spawner" "Module: Utility" "CallOn: A spawner" "MandatoryArg: <Count>: The count to set to" "Example: spawner set_count( 3 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_count( count ) { /# AssertEx( IsDefined( self ), "Spawner wasn't defined!" ); AssertEx( !isalive( self ), "Spawner was alive!" ); #/ self.count = count; }/* ============= ///ScriptDocBegin "Name: follow_path( <node>, <require_player_dist>, <arrived_at_node_func> )" "Summary: Set's the AI on a path of nodes, script_structs, or script_origins. Internally uses maps\_spawner::go_to_node which has the following attributes: - if the node has .script_requires_player set, then the AI will stop at that node until the player catches up. - if the node has .script_delay set, then the AI will stop at that node for the amount of delay" - the function will return once all nodes are traversed, and will notify self 'path_end_reached'. - follow_path stops maps\_spawner::go_to_node from exploding the AI's goal_radius after the last node is reached." "Module: Utility" "CallOn: AI" "MandatoryArg: <node>: a node, script_struct, or script_origin that starts the path" "OptionalArg: <require_player_dist>: The distance the player must be to the AI before the AI will move on from a node with .script_requires_player set, defaults to 300." "OptionalArg: <arrived_at_node_func>: Optional function to run every time the AI reaches his goal." "Example: other_player = get_other_player( player );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ follow_path( node, require_player_dist, arrived_at_node_func ) { self notify( "_utility::follow_path" ); self endon( "_utility::follow_path" ); self endon( "death" ); goal_type = undefined; //only nodes and structs dont have classnames - ents do if ( !isdefined( node.classname ) ) { //only structs don't have types, nodes do if ( !isdefined( node.type ) ) goal_type = "struct"; else goal_type = "node"; } else goal_type = "entity"; if ( !isdefined( require_player_dist ) ) require_player_dist = 300; //set this so the radius doesn't explode. oldforcegoal = self.script_forcegoal; self.script_forcegoal = 1; self maps\_spawner::go_to_node( node, goal_type, arrived_at_node_func, require_player_dist ); self.script_forcegoal = oldforcegoal; } /* ============= ///ScriptDocBegin "Name: enable_dynamic_run_speed( <pushdist> , <sprintdist> , <stopdist> , <jogdist> , <group> , <dontChangeMovePlaybackRate> )" "Summary: Turns on dynamic speed system for an AI, where the AI will run faster or slower based on average position of players. make sure to call maps\_dynamic_run_speed::main(); after maps\_load::main(). maps\_dynamic_run_speed::main() takes an optional parameter which is an array of dialogue lines the for the AI to say when they are stopped and want the player to catch up" "Module: _dynamic_run_speed.gsc" "CallOn: AI" "OptionalArg: <pushdist>: The max distance from the player to the AI that the AI will go from a jog/walk to a run, at twice this distance the ai will stop. DEFAULTS to 250." "OptionalArg: <sprintdist>: The min distance from the player to the AI where the AI will start sprinting. DEFAULTS to 125." "Example: level.price enable_dynamic_run_speed();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_dynamic_run_speed( pushdist, sprintdist, stopdist, jogdist, group, dontChangeMovePlaybackRate ) { AssertEx( IsDefined( level.scr_anim[ "generic" ][ "DRS_sprint" ] ), " - -- -- -- -- -- -- add this line: 'maps\_dynamic_run_speed::main();' AFTER maps\\\_load::main(); -- -- -- -- -- -- - " ); if ( !isdefined( pushdist ) ) pushdist = 250; if ( !isdefined( sprintdist ) ) sprintdist = 100; if ( !isdefined( stopdist ) ) stopdist = pushdist * 2; if ( !isdefined( jogdist ) ) jogdist = pushdist * 1.25; if ( !isdefined( dontChangeMovePlaybackRate ) ) dontChangeMovePlaybackRate = false; self.dontChangeMovePlaybackRate = dontChangeMovePlaybackRate; self thread dynamic_run_speed_proc( pushdist, sprintdist, stopdist, jogdist, group ); } /* ============= ///ScriptDocBegin "Name: disable_dynamic_run_speed()" "Summary: Stops Dynamic run speed logic on an AI." "Module: _dynamic_run_speed.gsc" "CallOn: AI" "OptionalArg: <pushdist>: The max distance from the player to the AI that the AI will go from a jog/walk to a run, at twice this distance the ai will stop. DEFAULTS to 250." "OptionalArg: <sprintdist>: The min distance from the player to the AI where the AI will start sprinting. DEFAULTS to 125." "Example: level.price disable_dynamic_run_speed();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_dynamic_run_speed() { self notify( "stop_dynamic_run_speed" ); } /* ============= ///ScriptDocBegin "Name: player_seek_enable()" "Summary: Makes an enemy AI seek out the closest player." "Module: AI" "CallOn: AI" "Example: enemy thread player_seek_enable();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_seek_enable() { self endon( "death" ); self endon( "stop_player_seek" ); g_radius = 1200; if ( self has_shotgun() ) g_radius = 250; newGoalRadius = Distance( self.origin, level.player.origin ); for ( ;; ) { wait 2; self.goalradius = newGoalRadius; player = get_closest_player( self.origin ); self SetGoalEntity( player ); newGoalRadius -= 175; if ( newGoalRadius < g_radius ) { newGoalRadius = g_radius; return; } } } /* ============= ///ScriptDocBegin "Name: player_seek_disable()" "Summary: Makes an enemy AI stop seeking out the closest player. Disables behavior caused by funtion player_seek_enable()" "Module: AI" "CallOn: AI" "Example: enemy thread player_seek_disable();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_seek_disable() { self notify( "stop_player_seek" ); } /* ============= ///ScriptDocBegin "Name: waittill_entity_in_range_or_timeout( <entity>, <range>, <timeout> )" "Summary: waits until a given entity is within range of the calling entity or timeout time passes" "Module: Entity" "CallOn: An entity" "MandatoryArg: <entity>: entity whose origin is checked to see if it is within range of the calling entity " "OptionalArg: <range>: distance in units to check" "OptionalArg: <timeout>: time in seconds to wait defaults to 5" "Example: level.player waittill_entity_in_range_or_timeout( level.enemyHeli, 2048, 10 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_entity_in_range_or_timeout( entity, range, timeout ) { self endon( "death" ); entity endon( "death" ); if ( !isdefined( timeout ) ) timeout = 5; timeout_time = GetTime() + ( timeout * 1000 ); while ( IsDefined( entity ) ) { if ( Distance( entity.origin, self.origin ) <= range ) break; if ( GetTime() > timeout_time ) break; wait .1; } } /* ============= ///ScriptDocBegin "Name: waittill_entity_in_range( <entity>, <range> )" "Summary: waits until a given entity is within range of the calling entity" "Module: Entity" "CallOn: An entity" "MandatoryArg: <entity>: entity whose origin is checked to see if it is within range of the calling entity " "OptionalArg: <range>: distance in units to check" "Example: level.player waittill_entity_in_range( level.enemyHeli, 2048 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_entity_in_range( entity, range ) { self endon( "death" ); entity endon( "death" ); while ( IsDefined( entity ) ) { if ( Distance( entity.origin, self.origin ) <= range ) break; wait .1; } } /* ============= ///ScriptDocBegin "Name: waittill_entity_out_of_range( <entity>, <range> )" "Summary: waits until a given entity is out of range of the calling entity" "Module: Entity" "CallOn: An entity" "MandatoryArg: <entity>: entity whose origin is checked" "OptionalArg: <range>: distance in units to check" "Example: level.player waittill_entity_out_of_range( level.enemyHeli, 2048 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_entity_out_of_range( entity, range ) { self endon( "death" ); entity endon( "death" ); while ( IsDefined( entity ) ) { if ( Distance( entity.origin, self.origin ) > range ) break; wait .1; } } /* ============= ///ScriptDocBegin "Name: has_shotgun()" "Summary: returns true/false if AI has a shotgun" "Module: AI" "CallOn: AI" "Example: self has_shotgun()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ has_shotgun() { self endon( "death" ); if ( !isdefined( self.weapon ) ) return false; if ( self.weapon == "winchester1200" || self.weapon == "m1014" || self.weapon == "striker" || self.weapon == "ranger" || self.weapon == "aa12" ) return true; else return false; } /* ============= ///ScriptDocBegin "Name: player_has_thermal()" "Summary: returns true/false if player has a weapon with a thermal scope" "Module: Player" "CallOn: Player" "Example: if ( level.player player_has_thermal() )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_has_thermal() { weapons = self GetWeaponsListAll(); if ( !isdefined( weapons ) ) return false; foreach ( weapon in weapons ) { if ( IsSubStr( weapon, "thermal" ) ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: waittill_true_goal( <origin> , <radius> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_true_goal( origin, radius ) { self endon( "death" ); if ( !isdefined( radius ) ) radius = self.goalradius; while ( 1 ) { self waittill( "goal" ); if ( Distance( self.origin, origin ) < radius + 10 )// give a little leeway break; } } /* ============= ///ScriptDocBegin "Name: player_speed_percent( <percent> , <time> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_speed_percent( percent, time ) { currspeed = Int( GetDvar( "g_speed" ) ); if ( !isdefined( level.player.g_speed ) ) level.player.g_speed = currspeed; goalspeed = Int( level.player.g_speed * percent * .01 ); level.player player_speed_set( goalspeed, time ); } /* ============= ///ScriptDocBegin "Name: blend_movespeedscale_percent( <percent> , <time> )" "Summary: blends the player's speed percentage using setMoveSpeedScale over time" "Module: player" "CallOn: player" "MandatoryArg: <percent>: percentage > 0 to scale to" "OptionalArg: <time>: time in seconds to lerp over if none - set speed instantly" "Example: level.player blend_movespeedscale_percent( 1.2, 3 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ blend_movespeedscale_percent( percent, time ) { player = self; if ( !isplayer( player ) ) player = level.player; if ( !isdefined( player.movespeedscale ) ) player.movespeedscale = 1.0; goalscale = percent * .01; player blend_movespeedscale( goalscale, time ); } /* ============= ///ScriptDocBegin "Name: player_speed_set( <speed> , <time> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_speed_set( speed, time ) { currspeed = Int( GetDvar( "g_speed" ) ); if ( !isdefined( level.player.g_speed ) ) level.player.g_speed = currspeed; get_func = ::g_speed_get_func; set_func = ::g_speed_set_func; level.player thread player_speed_proc( speed, time, get_func, set_func, "player_speed_set" ); } /* ============= ///ScriptDocBegin "Name: blend_movespeedscale( <scale> , <time> )" "Summary: blends the player's speed scaler using setMoveSpeedScale over time" "Module: player" "CallOn: player" "MandatoryArg: <scale>: scale > 0 to scale to" "OptionalArg: <time>: time in seconds to lerp over if none - set speed instantly" "Example: level.player blend_movespeedscale( 1.2, 3 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ blend_movespeedscale( scale, time ) { player = self; if ( !isplayer( player ) ) player = level.player; if ( !isdefined( player.movespeedscale ) ) player.movespeedscale = 1.0; get_func = ::movespeed_get_func; set_func = ::movespeed_set_func; player thread player_speed_proc( scale, time, get_func, set_func, "blend_movespeedscale" ); } player_speed_proc( speed, time, get_func, set_func, ender ) { self notify( ender ); self endon( ender ); currspeed = [[ get_func ]](); goalspeed = speed; if ( IsDefined( time ) ) { range = goalspeed - currspeed; interval = .05; numcycles = time / interval; fraction = range / numcycles; while ( abs( goalspeed - currspeed ) > abs( fraction * 1.1 ) ) { currspeed += fraction; [[ set_func ]]( currspeed ); wait interval; } } [[ set_func ]]( goalspeed ); } /* ============= ///ScriptDocBegin "Name: player_speed_default( <time> )" "Summary: blends the level.player's speed back to default using the dvar g_speed over time" "Module: player" "CallOn: " "OptionalArg: <time>: the time to blend over, if none - then set speed instantly" "Example: player_speed_default( 2 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_speed_default( time ) { if ( !isdefined( level.player.g_speed ) ) return; level.player player_speed_set( level.player.g_speed, time ); waittillframeend; level.player.g_speed = undefined; } /* ============= ///ScriptDocBegin "Name: blend_movespeedscale_default( <time> )" "Summary: blends the player's speed scale back to default using setmovespeedscale over time" "Module: player" "CallOn: player" "OptionalArg: <time>: the time to blend over, if none - then set speed instantly" "Example: level.player blend_movespeedscale_default( 2 )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ blend_movespeedscale_default( time ) { player = self; if ( !isplayer( player ) ) player = level.player; if ( !isdefined( player.movespeedscale ) ) return; player blend_movespeedscale( 1.0, time ); waittillframeend; player.movespeedscale = undefined; } /* ============= ///ScriptDocBegin "Name: drop_to_ground( <pos> )" "Summary: Return the ground point for this origin" "Module: Utility" "MandatoryArg: <pos>: The origin you want to find the ground point for" "OptionalArg: <updist>: Optional height to drop the point from" "OptionalArg: <downdist>: Optional height to drop the point to" "Example: ground_org = drop_to_ground( origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ drop_to_ground( pos, updist, downdist ) { if ( !isdefined( updist ) ) updist = 1500; if ( !isdefined( downdist ) ) downdist = -12000; return PhysicsTrace( pos + ( 0, 0, updist ), pos + ( 0, 0, downdist ) ); } /* ============= ///ScriptDocBegin "Name: teleport_ent( <ent> )" "Summary: Teleport self to an ent" "Module: Utility" "CallOn: An entity you want to teleport" "MandatoryArg: <ent>: The entity to teleport to" "Example: level.player teleport_ent( player_start_ent );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ teleport_ent( ent ) { if ( IsPlayer( self ) ) { self SetOrigin( ent.origin ); self SetPlayerAngles( ent.angles ); } else { self ForceTeleport( ent.origin, ent.angles ); } } /* ============= ///ScriptDocBegin "Name: teleport_ai( <eNode> )" "Summary: Force teleport of an AI to a given node and set its goalpos and goalnode to the node" "Module: Utility" "CallOn: An AI you want to teleport" "MandatoryArg: <eNode>: The node to teleport to" "Example: level.price teleport_ai( eNode );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ teleport_ai( eNode ) { AssertEx( IsAI( self ), "Function teleport_ai can only be called on an AI entity" ); AssertEx( IsDefined( eNode ), "Need to pass a node entity to function teleport_ai" ); self ForceTeleport( eNode.origin, eNode.angles ); self SetGoalPos( self.origin ); self SetGoalNode( eNode ); } /* ============= ///ScriptDocBegin "Name: move_all_fx( <vec> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ move_all_fx( vec ) { foreach ( fx in level.createFXent ) { fx.v[ "origin" ] += vec; } } /* ============= ///ScriptDocBegin "Name: IsSliding( <IsSliding> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ IsSliding() { return IsDefined( self.slideModel ); } /* ============= ///ScriptDocBegin "Name: BeginSliding( <velocity> , <allowedAcceleration> , <dampening> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ BeginSliding( velocity, allowedAcceleration, dampening ) { Assert( IsPlayer( self ) ); player = self; player thread play_sound_on_entity( "foot_slide_plr_start" ); player thread play_loop_sound_on_tag( "foot_slide_plr_loop" ); override_link_method = IsDefined( level.custom_linkto_slide ); if ( !isDefined( velocity ) ) velocity = player GetVelocity() + ( 0, 0, -10 ); if ( !isDefined( allowedAcceleration ) ) allowedAcceleration = 10; if ( !isDefined( dampening ) ) dampening = .035; Assert( !isDefined( player.slideModel ) ); // in the future, slideModel will actually be a script_model of legs slideModel = Spawn( "script_origin", player.origin ); slideModel.angles = player.angles; player.slideModel = slideModel; slideModel MoveSlide( ( 0, 0, 15 ), 15, velocity ); if ( override_link_method ) { player PlayerLinkToBlend( slideModel, undefined, 1 ); } else { player PlayerLinkTo( slideModel ); } player DisableWeapons(); player AllowProne( false ); player AllowCrouch( true ); player AllowStand( false ); player thread DoSlide( slideModel, allowedAcceleration, dampening ); } /* ============= ///ScriptDocBegin "Name: EndSliding( <EndSliding> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ EndSliding() { Assert( IsPlayer( self ) ); player = self; Assert( IsDefined( player.slideModel ) ); player notify( "stop sound" + "foot_slide_plr_loop" ); player thread play_sound_on_entity( "foot_slide_plr_end" ); player Unlink(); player SetVelocity( player.slidemodel.slideVelocity ); player.slideModel Delete(); player EnableWeapons(); player AllowProne( true ); player AllowCrouch( true ); player AllowStand( true ); player notify( "stop_sliding" ); } /* ============= ///ScriptDocBegin "Name: spawn_vehicle( <spawn_vehicle> )" "Summary: Self is a vehicle spawner" "Module: Vehicle" LevelOn: A vehicle spawner" "Example: vehicle = spawner spawn_vehicle();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ spawn_vehicle() { /# // dev comments so we can catch the local variable in the debugger vehicle = maps\_vehicle::vehicle_spawn( self ); return vehicle; #/ // to conform with the style that AI are spawned; return maps\_vehicle::vehicle_spawn( self ); } /* ============= ///ScriptDocBegin "Name: getEntWithFlag( <flag> )" "Summary: Returns an entity that has the flag" "Module: Utility" "MandatoryArg: <flag>: The flag " "Example: flagEnt = getEntWithFlag( "give_c4_obj" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getEntWithFlag( flag ) { trigger_classes = maps\_load::get_load_trigger_classes(); triggers = []; foreach ( class, _ in trigger_classes ) { if ( !IsSubStr( class, "flag" ) ) continue; other_triggers = GetEntArray( class, "classname" ); triggers = array_combine( triggers, other_triggers ); } trigger_funcs = maps\_load::get_load_trigger_funcs(); foreach ( func, _ in trigger_funcs ) { if ( !IsSubStr( func, "flag" ) ) continue; other_triggers = GetEntArray( func, "targetname" ); triggers = array_combine( triggers, other_triggers ); } found_trigger = undefined; /# foreach ( trigger in triggers ) { AssertEx( IsDefined( trigger.script_flag ), "Flag trigger at " + trigger.origin + " has no script_flag" ); if ( trigger.script_flag == flag ) { AssertEx( !isdefined( found_trigger ), "Did getEntWithFlag on flag " + flag + " but found multiple entities with that flag" ); found_trigger = trigger; } } //AssertEx( IsDefined( found_trigger ), "Tried to find entity with flag " + flag + " but found none" ); //if ( 1 ) return found_trigger; #/ foreach ( trigger in triggers ) { if ( trigger.script_flag == flag ) { return trigger; } } } /* ============= ///ScriptDocBegin "Name: getEntArrayWithFlag( <flag> )" "Summary: Returns an array of entities that have the flag" "Module: Utility" "MandatoryArg: <flag>: The flag " "Example: flagEnt = getEntArrayWithFlag( "give_c4_obj" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getEntArrayWithFlag( flag ) { trigger_classes = maps\_load::get_load_trigger_classes(); triggers = []; foreach ( class, _ in trigger_classes ) { if ( !IsSubStr( class, "flag" ) ) continue; other_triggers = GetEntArray( class, "classname" ); triggers = array_combine( triggers, other_triggers ); } trigger_funcs = maps\_load::get_load_trigger_funcs(); foreach ( func, _ in trigger_funcs ) { if ( !IsSubStr( func, "flag" ) ) continue; other_triggers = GetEntArray( func, "targetname" ); triggers = array_combine( triggers, other_triggers ); } found_triggers = []; /# foreach ( trigger in triggers ) { AssertEx( IsDefined( trigger.script_flag ), "Flag trigger at " + trigger.origin + " has no script_flag" ); if ( trigger.script_flag == flag ) { found_triggers[ found_triggers.size ] = trigger; } } AssertEx( found_triggers.size, "Tried to find entity with flag " + flag + " but found none" ); if ( 1 ) return found_triggers; #/ foreach ( trigger in triggers ) { if ( trigger.script_flag == flag ) { found_triggers[ found_triggers.size ] = trigger; } } return found_triggers; } /* ============= ///ScriptDocBegin "Name: set_z( <vec> , <z> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_z( vec, z ) { return( vec[ 0 ], vec[ 1 ], z ); } /* ============= ///ScriptDocBegin "Name: set_y( <vec> , <y> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_y( vec, y ) { return( vec[ 0 ], y, vec[ 2 ] ); } /* ============= ///ScriptDocBegin "Name: set_x( <vec> , <x> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_x( vec, x ) { return( x, vec[ 1 ], vec[ 2 ] ); } /* ============= ///ScriptDocBegin "Name: player_using_missile()" "Summary: detect whether player has a missile weapon equipped as his current weapon (AT4, RPG, Stinger)" "Module: Utility" "CallOn: Player" "Example: if ( player_using_missile() )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_using_missile() { weapon = self GetCurrentWeapon(); if ( !isdefined( weapon ) ) return false; if ( IsSubStr( ToLower( weapon ), "rpg" ) ) return true; if ( IsSubStr( ToLower( weapon ), "stinger" ) ) return true; if ( IsSubStr( ToLower( weapon ), "at4" ) ) return true; if ( IsSubStr( ToLower( weapon ), "javelin" ) ) return true; return false; } /* ============= ///ScriptDocBegin "Name: doingLongDeath( <longDeath> )" "Summary: Returns if an AI is doing long death" "Module: Utility" "CallOn: An AI" "Example: if ( guy longDeath() )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ doingLongDeath() { Assert( IsAI( self ) ); return IsDefined( self.a.doingLongDeath ); } /* ============= ///ScriptDocBegin "Name: get_rumble_ent( <rumble> )" "Summary: Create an entity to do rumble on. Set .intensity to change the rumble intensity or use blend commands below." "Module: Rumble" "OptionalArg: <rumble>: The rumble to use, if not specified steady_rumble is used. " "Example: ent = get_rumble_ent();" "NoteLine: don't forget to add PreCacheRumble( "steady_rumble" ) or whatever rumble you decide to use to your script. " "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_rumble_ent( rumble ) { if ( is_coop() ) PrintLn( "^3Warning! Using get_rumble_ent will cause the same rumbles to apply to all of the coop players!" ); player = get_player_from_self(); if ( !IsDefined( rumble ) ) rumble = "steady_rumble"; ent = Spawn( "script_origin", player.origin ); ent.intensity = 1; ent PlayRumbleLoopOnEntity( rumble ); ent thread update_rumble_intensity( player ); return ent; } set_rumble_intensity( intensity ) { AssertEx( intensity >= 0 && intensity <= 1, "Intensity must be between 0 and 1" ); self.intensity = intensity; } /* ============= ///ScriptDocBegin "Name: rumble_ramp_on( <time> )" "Summary: Ramp rumble to 1 on entity" "Module: Rumble" "CallOn: A rumble entity created with get_rumble_ent()" "MandatoryArg: <time>: Time in seconds over which to ramp " "Example: rumble_ent rumble_ramp_on( 2 )";" "SPMP: singleplayer" ///ScriptDocEnd ============= */ rumble_ramp_on( time ) { thread rumble_ramp_to( 1, time ); } /* ============= ///ScriptDocBegin "Name: rumble_ramp_off( <time> )" "Summary: Ramp rumble to 0 on entity" "Module: Rumble" "CallOn: A rumble entity created with get_rumble_ent()" "MandatoryArg: <time>: Time in seconds over which to ramp " "Example: rumble_ent rumble_ramp_off( 2 )";" "SPMP: singleplayer" ///ScriptDocEnd ============= */ rumble_ramp_off( time ) { thread rumble_ramp_to( 0, time ); } /* ============= ///ScriptDocBegin "Name: rumble_ramp_to( <dest> , <time> )" "Summary: Ramp rumble to dest on entity" "Module: Rumble" "CallOn: A rumble entity created with get_rumble_ent()" "MandatoryArg: <dest>: Value to blend rumble to " "MandatoryArg: <time>: Time in seconds over which to ramp " "Example: rumble_ent rumble_ramp_to( 1, 2 )";" "SPMP: singleplayer" ///ScriptDocEnd ============= */ rumble_ramp_to( dest, time ) { self notify( "new_ramp" ); self endon( "new_ramp" ); self endon( "death" ); frames = time * 20; dif = dest - self.intensity; slice = dif / frames; for ( i = 0; i < frames; i++ ) { self.intensity += slice; wait( 0.05 ); } self.intensity = dest; } /* ============= ///ScriptDocBegin "Name: get_player_from_self()" "Summary: Returns a player, and if self is a player then it returns that player." "Module: Utility" "Example: player = get_player_from_self();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_player_from_self() { if ( IsDefined( self ) ) { if ( !is_in_array( level.players, self ) ) return level.player; else return self; } else return level.player; } /* ============= ///ScriptDocBegin "Name: get_player_gameskill( <get_player_gameskill> )" "Summary: Returns the gameskill for a player based on the dvar." "Module: Entity" "CallOn: A player" "Example: player get_player_gameskill()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_player_gameskill() { AssertEx( IsPlayer( self ), "get_player_gameskill() can only be called on a player." ); return Int( self GetPlayerSetting( "gameskill" ) ); } /* ============= ///ScriptDocBegin "Name: glow( <model> )" "Summary: Makes a model glow with" "Module: Utility" "CallOn: An entity that should glow" "OptionalArg: <Model>: A glow model to use. If not specified then _obj is appended to the current model, which is how it should normally work anyway. " "Example: keyboard glow();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ glow( model ) { if ( IsDefined( self.non_glow_model ) ) return; self.non_glow_model = self.model; if ( !isdefined( model ) ) model = self.model + "_obj"; self SetModel( model ); } /* ============= ///ScriptDocBegin "Name: stopGlow( <model> )" "Summary: Stops a model from glowing." "Module: Utility" "CallOn: An entity that is glowing" "Example: keyboard stopGlow();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ stopGlow( model ) { if ( !isdefined( self.non_glow_model ) ) return; self SetModel( self.non_glow_model ); self.non_glow_model = undefined; } /* ============= ///ScriptDocBegin "Name: array_delete_evenly( <array> , <delete_size>, <set_size> )" "Summary: Evenly remove entries from an array. For example delete 3 out of every 4 entries in an array." "Module: Entity" "CallOn: An entity" "MandatoryArg: <array>: The array, order of the array determines the order stuff is removed." "MandatoryArg: <delete_size>: The ratio of entries to delete." "MandatoryArg: <set_size>: The size of each set." "Example: array = array_delete_evenly( array, 1, 3 ); // Delete 1 out of every 3 entries in the array" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_delete_evenly( array, delete_size, set_size ) { AssertEx( delete_size > 0, "Save size must be at least 1" ); AssertEx( set_size > 0, "Removal size must be at least 1" ); AssertEx( delete_size < set_size, "Save size must be less than removal size" ); removal = []; delete_size = set_size - delete_size; foreach ( entry in array ) { removal[ removal.size ] = entry; if ( removal.size == set_size ) { // remove 2 of every 3 entrys removal = array_randomize( removal ); for ( i = delete_size; i < removal.size; i++ ) { removal[ i ] Delete(); } removal = []; } } new_array = []; foreach ( entry in array ) { if ( !isdefined( entry ) ) continue; new_array[ new_array.size ] = entry; } return new_array; } /* ============= ///ScriptDocBegin "Name: waittill_in_range( <origin> , <range> )" "Summary: Wait until and entity is within range or a given origin." "Module: Entity" "CallOn: An entity" "MandatoryArg: <origin>: wait until entity is within range of this position." "MandatoryArg: <range>: wait until entity is within this distance to the given position." "Example: array = array_delete_evenly( array, 1, 3 ); // Delete 1 out of every 3 entries in the array" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_in_range( origin, range ) { self endon( "death" ); while ( IsDefined( self ) ) { if ( Distance( origin, self.origin ) <= range ) break; wait .5; } } /* ============= ///ScriptDocBegin "Name: add_trace_fx( <name> )" "Summary: Adds FX that play off a trace from a tag. See _climb.gsc for examples." "Module: Utility" "MandatoryArg: <name>: Name the tracefx." "Example: add_trace_fx( "ice_pick" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_trace_fx( name ) { ent = SpawnStruct(); ent thread add_trace_fx_proc( name ); return ent; } /* ============= ///ScriptDocBegin "Name: traceFX_on_tag( <fx_name> , <tag> , <trace_depth> )" "Summary: Plays a traceFX on the specified tag." "Module: Utility" "CallOn: An entity with a tag." "MandatoryArg: <fx_name>: The name of the tracefx, created with add_trace_fx." "MandatoryArg: <tag>: The tag to play the fx on." "MandatoryArg: <trace_depth>: How far to trace to find a surface." "Example: car traceFX_on_tag( "player_ice_pick", "tag_origin", 10 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ traceFX_on_tag( fx_name, tag, trace_depth ) { origin = self GetTagOrigin( tag ); angles = self GetTagAngles( tag ); traceFx( fx_name, origin, angles, trace_depth ); } /* ============= ///ScriptDocBegin "Name: traceFx( <fx_name> , <origin> , <angles> , <trace_depth> )" "Summary: Trace from org/ang and then play an fx where it hits" "Module: Utility" "MandatoryArg: <fx_name>: The TraceFX name, added with add_trace_fx. " "MandatoryArg: <origin>: The origin to trace from. " "MandatoryArg: <angles>: The angles to trace from. " "MandatoryArg: <trace_depth>: The depth to trace for a surface. " "Example: traceFx( fx_name, origin, angles, trace_depth );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ traceFx( fx_name, origin, angles, trace_depth ) { // plays an effect based off surface type then deletes the tag that called it AssertEx( IsDefined( level.trace_fx[ fx_name ] ), "No level.trace_fx with name " + fx_name ); AssertEx( IsDefined( level.trace_fx[ fx_name ][ "default" ] ), "No default fx defined for " + fx_name ); forward = AnglesToForward( angles ); trace = BulletTrace( origin, origin + forward * trace_depth, false, undefined ); if ( trace[ "fraction" ] >= 1 ) { /# if ( GetDvarInt( "debug_tracefx" ) ) Line( origin, origin + forward * trace_depth, ( 1, 0, 0 ), 1, 0, 500 ); #/ // didn't hit anything return; } surface = trace[ "surfacetype" ]; if ( !isdefined( level.trace_fx[ fx_name ][ surface ] ) ) surface = "default"; fx_info = level.trace_fx[ fx_name ][ surface ]; if ( IsDefined( fx_info[ "fx" ] ) ) { PlayFX( fx_info[ "fx" ], trace[ "position" ], trace[ "normal" ] ); } if ( IsDefined( fx_info[ "fx_array" ] ) ) { foreach ( fx in fx_info[ "fx_array" ] ) { PlayFX( fx, trace[ "position" ], trace[ "normal" ] ); } } if ( IsDefined( fx_info[ "sound" ] ) ) { level thread play_sound_in_space( fx_info[ "sound" ], trace[ "position" ] ); } if ( IsDefined( fx_info[ "rumble" ] ) ) { player = get_player_from_self(); player PlayRumbleOnEntity( fx_info[ "rumble" ] ); } } /* ============= ///ScriptDocBegin "Name: disable_surprise()" "Summary: Disables AI surprise" "Module: AI" "CallOn: An AI" "Example: guy disable_surprise();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_surprise() { self.newEnemyReactionDistSq = 0; } /* ============= ///ScriptDocBegin "Name: enable_surprise()" "Summary: reenables AI surprise" "Module: AI" "CallOn: An AI" "Example: guy enable_surprise();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_surprise() { self.newEnemyReactionDistSq = squared( 512 ); } /* ============= ///ScriptDocBegin "Name: enable_heat_behavior( <shoot_while_moving> )" "Summary: Enables heat behavior" "Module: AI" "CallOn: An AI" "OptionalArg: <shoot_while_moving>: do regular AI shoot behavior while moving. Defaults to false" "Example: guy enable_heat_behavior();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_heat_behavior( shoot_while_moving ) { self.heat = true; self.no_pistol_switch = true; self.useCombatScriptAtCover = true; if ( !isdefined( shoot_while_moving ) || !shoot_while_moving ) { self.dontshootwhilemoving = true; self.maxfaceenemydist = 64; self.pathenemylookahead = 2048; self disable_surprise(); } self.specialReloadAnimFunc = animscripts\animset::heat_reload_anim; self.customMoveAnimSet[ "run" ] = anim.animsets.move[ "heat_run" ]; } /* ============= ///ScriptDocBegin "Name: disable_heat_behavior()" "Summary: Disables heat behavior" "Module: AI" "CallOn: An AI" "Example: guy disable_heat_behavior();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_heat_behavior() { self.heat = undefined; self.no_pistol_switch = undefined; self.dontshootwhilemoving = undefined; self.useCombatScriptAtCover = false; self.maxfaceenemydist = 512; self.specialReloadAnimFunc = undefined; self.customMoveAnimSet = undefined; } /* ============= ///ScriptDocBegin "Name: getVehicleArray()" "Summary: Returns Vehicle_GetArray();" "Module: Utility" "Example: vehicles = getVehicleArray()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getVehicleArray() { return Vehicle_GetArray(); } /* ============= ///ScriptDocBegin "Name: hint( string, timeOut )" "Summary: Creates a simple white text string at the center of the screen;" "Module: Utility" "Example: thread hint( &"OILRIG_HINT_C4_SWITCH" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hint( string, timeOut, zoffset ) { if ( !isdefined( zoffset ) ) zoffset = 0; hintfade = 0.5; level endon( "clearing_hints" ); if ( IsDefined( level.hintElement ) ) level.hintElement maps\_hud_util::destroyElem(); level.hintElement = maps\_hud_util::createFontString( "default", 1.5 ); level.hintElement maps\_hud_util::setPoint( "MIDDLE", undefined, 0, 30 + zoffset ); level.hintElement.color = ( 1, 1, 1 ); level.hintElement SetText( string ); level.hintElement.alpha = 0; level.hintElement FadeOverTime( 0.5 ); level.hintElement.alpha = 1; wait( 0.5 ); level.hintElement endon( "death" ); if ( IsDefined( timeOut ) ) wait( timeOut ); else return; level.hintElement FadeOverTime( hintfade ); level.hintElement.alpha = 0; wait( hintfade ); level.hintElement maps\_hud_util::destroyElem(); } /* ============= ///ScriptDocBegin "Name: hint_fade()" "Summary: Fades out a text hint created with the hint() function" "Module: Utility" "Example: thread hint( &"OILRIG_HINT_C4_SWITCH" )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hint_fade() { hintfade = 1; if ( IsDefined( level.hintElement ) ) { level notify( "clearing_hints" ); level.hintElement FadeOverTime( hintfade ); level.hintElement.alpha = 0; wait( hintfade ); } } /* ============= ///ScriptDocBegin "Name: kill_deathflag( <theFlag>, <time> )" "Summary: Kill everything associated with a deathflag" "Module: Utility" "MandatoryArg: <theFlag>: The flag to kill on " "OptionalArg: <time>: random amount of time to wait before death " "Example: kill_deathflag( "tower_cleared" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ kill_deathflag( theFlag, time ) { //assertex( IsDefined( level.flag[ theFlag ] ), "Tried to kill_deathFlag on a flag " + theFlag + " which does not exist." ); if ( !isdefined( level.flag[ theFlag ] ) ) return; if ( !isdefined( time ) ) time = 0; foreach ( deathTypes in level.deathFlags[ theFlag ] ) { foreach ( element in deathTypes ) { if ( IsAlive( element ) ) { element thread kill_deathflag_proc( time ); } else { element Delete(); } } } } /* ============= ///ScriptDocBegin "Name: get_player_view_controller( <model> , <tag>, <originoffset> )" "Summary: Returns a turret that you can link the player to. Link the player to tag_aim." "Module: Utility" "MandatoryArg: <model>: The model to link to." "MandatoryArg: <tag>: The tag to link to." "OptionalArg: <originoffset>: Optional offset from the tag." "Example: player_view_controller = get_player_view_controller( level.player_heli, "tag_guy2" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_player_view_controller( model, tag, originoffset ) { if ( !isdefined( originoffset ) ) originoffset = ( 0, 0, 0 ); origin = model GetTagOrigin( tag ); player_view_controller = SpawnTurret( "misc_turret", origin, "player_view_controller" ); player_view_controller.angles = model GetTagAngles( tag ); player_view_controller SetModel( "tag_turret" ); player_view_controller LinkTo( model, tag, originoffset, ( 0, 0, 0 ) ); player_view_controller MakeUnusable(); player_view_controller Hide(); player_view_controller SetMode( "manual" ); /* player_view_controller thread maps\_debug::drawTagForever( "tag_origin" ); player_view_controller thread maps\_debug::drawTagForever( "TAG_player", (1,0,0) ); player_view_controller thread maps\_debug::drawTagForever( "TAG_Weapon", (0,1,0) ); player_view_controller thread maps\_debug::drawTagForever( "tag_flash", (1,0,1) ); model thread maps\_debug::drawTagForever( tag ); player_view_controller thread maps\_debug::drawTagForever( "TAG_aim", (0,0,1) ); */ return player_view_controller; } /* ============= ///ScriptDocBegin "Name: blend_dof( <start> , <end> , <time> )" "Summary: Blend DOF from start to end over time" "Module: Utility" "MandatoryArg: <start>: Starting dof values, usually level.dofDefault" "MandatoryArg: <end>: Values you want to blend to" "MandatoryArg: <time>: Amount of time to blend over" "Example: blend_dof( start, end, 14 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ blend_dof( start, end, time ) { blend = level create_blend( ::blend_default_dof, start, end ); blend.time = time; } /* ============= ///ScriptDocBegin "Name: create_blend( <func> , <var1> , <var2> , <var3> )" "Summary: Creates a spawnstruct that blends values over time, using a function you create (see blend_dof)" "Module: Utility" "MandatoryArg: <func>: The function that will blend the values " "OptionalArg: <var1>: Optional var to use." "OptionalArg: <var2>: Optional var to use." "OptionalArg: <var3>: Optional var to use." "Example: blend = create_blend( ::blend_dof, start, end ); blend.time = 14;" "SPMP: singleplayer" ///ScriptDocEnd ============= */ create_blend( func, var1, var2, var3 ) { ent = SpawnStruct(); ent childthread process_blend( func, self, var1, var2, var3 ); return ent; } /* ============= ///ScriptDocBegin "Name: store_players_weapons( <scene> )" "Summary: Store the player's inventory to a variable that you can recall later" "Module: Utility" "CallOn: A player" "MandatoryArg: <scene>: String to store the inventory to." "Example: level.player store_players_weapons( "c4_scene" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ store_players_weapons( scene ) { if ( !isdefined( self.stored_weapons ) ) { self.stored_weapons = []; } array = []; weapons = self GetWeaponsListAll(); foreach ( weapon in weapons ) { array[ weapon ] = []; array[ weapon ][ "clip_left" ] = self GetWeaponAmmoClip( weapon, "left" ); array[ weapon ][ "clip_right" ] = self GetWeaponAmmoClip( weapon, "right" ); array[ weapon ][ "stock" ] = self GetWeaponAmmoStock( weapon ); } if ( !isdefined( scene ) ) scene = "default"; self.stored_weapons[ scene ] = []; self.stored_weapons[ scene ][ "current_weapon" ] = self GetCurrentWeapon(); self.stored_weapons[ scene ][ "inventory" ] = array; } /* ============= ///ScriptDocBegin "Name: restore_players_weapons( <scene> )" "Summary: Restore the player's inventory from a variable that you stored earlier." "Module: Utility" "MandatoryArg: <scene>: String to store the inventory to." "Example: level.player restore_players_weapons( "c4_scene" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ restore_players_weapons( scene ) { if ( !isdefined( scene ) ) scene = "default"; if ( !isdefined( self.stored_weapons ) || !isdefined( self.stored_weapons[ scene ] ) ) { PrintLn( "^3Warning! Tried to restore weapons for scene " + scene + " but they weren't stored" ); return; } self TakeAllWeapons(); foreach ( weapon, array in self.stored_weapons[ scene ][ "inventory" ] ) { // We cannot give "alt-fire" weapons if ( WeaponInventoryType( weapon ) != "altmode" ) { self GiveWeapon( weapon ); } self SetWeaponAmmoClip( weapon, array[ "clip_left" ], "left" ); self SetWeaponAmmoClip( weapon, array[ "clip_right" ], "right" ); self SetWeaponAmmoStock( weapon, array[ "stock" ] ); } current_weapon = self.stored_weapons[ scene ][ "current_weapon" ]; if ( current_weapon != "none" ) self SwitchToWeapon( current_weapon ); } /* ============= ///ScriptDocBegin "Name: hide_entity()" "Summary: Used to hide large groups of ents when you are unsure of the exact classname. Will use appropriate functions for turning off triggers, connecting paths in brushmodels, etc. if appropriate." "Module: Utility" "CallOn: An entity" "Example: array_thread( group_of_misc_entities,::hide_entity );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hide_entity() { switch( self.code_classname ) { case "light_spot": case "script_vehicle": case "script_model": self Hide(); break; case "script_brushmodel": self Hide(); self NotSolid(); if ( self.spawnflags & 1 ) self ConnectPaths(); break; case "trigger_radius": case "trigger_multiple": case "trigger_use": case "trigger_use_touch": case "trigger_multiple_flag_set": case "trigger_multiple_breachIcon": case "trigger_multiple_flag_lookat": case "trigger_multiple_flag_looking": self trigger_off(); break; default: AssertMsg( "Unable to hide entity at " + self.origin + ". Need to define a method for handling entities of classname " + self.code_classname ); } } /* ============= ///ScriptDocBegin "Name: show_entity()" "Summary: Used to show large groups of hidden ents when you are unsure of the exact classname. Will use appropriate functions for turning off triggers, disconnecting paths in brushmodels, etc. if appropriate." "Module: Utility" "CallOn: An entity" "Example: array_thread( group_of_misc_entities,::show_entity );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ show_entity() { switch( self.code_classname ) { case "light_spot": case"script_vehicle": case"script_model": self Show(); break; case "script_brushmodel": self Show(); self Solid(); if ( self.spawnflags & 1 ) self DisconnectPaths(); break; case "trigger_radius": case "trigger_multiple": case "trigger_use": case "trigger_use_touch": case "trigger_multiple_flag_set": case "trigger_multiple_breachIcon": case "trigger_multiple_flag_lookat": case "trigger_multiple_flag_looking": self trigger_on(); break; default: AssertMsg( "Unable to show entity at " + self.origin + ". Need to define a method for handling entities of classname " + self.code_classname ); } } /* ============= ///ScriptDocBegin "Name: _rotateyaw( <yaw_angle> , <time> , <time> , <time> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _rotateyaw( yaw_angle, time, acc_time, dec_time ) { if ( IsDefined( dec_time ) ) self RotateYaw( yaw_angle, time, acc_time, dec_time ); else if ( IsDefined( acc_time ) ) self RotateYaw( yaw_angle, time, acc_time ); else self RotateYaw( yaw_angle, time ); } /* ============= ///ScriptDocBegin "Name: set_moveplaybackrate( <rate>, <time> )" "Summary: set an AI's .moveplaybackrate over time" "Module: AI" "CallOn: AI" "MandatoryArg: <rate>: the speed of the playbackrate ( default rate is 1 )" "OptionalArg: <time>: time to lerp the rate in - if no time then set instantly" "Example: level.price set_moveplaybackrate( 1.1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_moveplaybackrate( rate, time ) { self notify( "set_moveplaybackrate" ); self endon( "set_moveplaybackrate" ); if ( IsDefined( time ) ) { range = rate - self.moveplaybackrate; interval = .05; numcycles = time / interval; fraction = range / numcycles; while ( abs( rate - self.moveplaybackrate ) > abs( fraction * 1.1 ) ) { self.moveplaybackrate += fraction; wait interval; } } self.moveplaybackrate = rate; } /* ============= ///ScriptDocBegin "Name: array_spawn_function( <array> , <func>, param1, param2, param3, param4 )" "Summary: Adds a spawn function to an array of spawners" "Module: Utility" "MandatoryArg: <array>: Array of spawners" "MandatoryArg: <func>: Function to run on the guy when he spawns" "OptionalArg: <param1> : An optional parameter." "OptionalArg: <param2> : An optional parameter." "OptionalArg: <param3> : An optional parameter." "OptionalArg: <param4> : An optional parameter." "Example: array_spawn_function( spawners, ::do_it, do_it_parameter );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_spawn_function( array, func, param1, param2, param3, param4 ) { AssertEx( IsDefined( array ), "That isn't an array!" ); AssertEx( IsArray( array ), "That isn't an array!" ); AssertEx( array.size, "That array is empty!" ); foreach ( spawner in array ) { AssertEx( IsSpawner( spawner ), "This isn't a spawner!" ); spawner thread add_spawn_function( func, param1, param2, param3, param4 ); } } /* ============= ///ScriptDocBegin "Name: array_spawn_function_targetname( <key> , <func>, param1, param2, param3, param4 )" "Summary: Gets spawners with the specified targetname and adds a spawn function to them" "Module: Utility" "MandatoryArg: <key>: targetname of spawners" "MandatoryArg: <func>: Function to run on the guys when they spawn" "OptionalArg: <param1> : An optional parameter." "OptionalArg: <param2> : An optional parameter." "OptionalArg: <param3> : An optional parameter." "OptionalArg: <param4> : An optional parameter." "Example: array_spawn_function_targetname( "specialguy", ::do_it );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_spawn_function_targetname( key, func, param1, param2, param3, param4 ) { array = GetEntArray( key, "targetname" ); array_spawn_function( array, func, param1, param2, param3, param4 ); } /* ============= ///ScriptDocBegin "Name: array_spawn_function_noteworthy( <key> , <func>, param1, param2, param3, param4 )" "Summary: Gets spawners with the specified noteworthy and adds a spawn function to them" "Module: Utility" "MandatoryArg: <key>: noteworthy of spawners" "MandatoryArg: <func>: Function to run on the guys when they spawn" "OptionalArg: <param1> : An optional parameter." "OptionalArg: <param2> : An optional parameter." "OptionalArg: <param3> : An optional parameter." "OptionalArg: <param4> : An optional parameter." "Example: array_spawn_function_noteworthy( "specialguy", ::do_it );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_spawn_function_noteworthy( key, func, param1, param2, param3, param4 ) { array = GetEntArray( key, "script_noteworthy" ); array_spawn_function( array, func, param1, param2, param3, param4 ); } /* ============= ///ScriptDocBegin "Name: enable_dontevershoot( <enable_dontevershoot> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_dontevershoot() { self.dontEverShoot = true; } /* ============= ///ScriptDocBegin "Name: disable_dontevershoot( <disable_dontevershoot> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_dontevershoot() { self.dontEverShoot = undefined; } /* ============= ///ScriptDocBegin "Name: create_vision_set_fog( <fogset> )" "Summary: Stores fog settings that get executed automatically with trigger_multiple_visionset" "Module: Utility" "MandatoryArg: <fogset>: Name, must be the same as the vision set it works with. " "Example: ent = create_vision_set_fog( "gulag" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ create_vision_set_fog( fogset ) { if ( !isdefined( level.vision_set_fog ) ) level.vision_set_fog = []; ent = SpawnStruct(); ent.name = fogset; level.vision_set_fog[ fogset ] = ent; return ent; } /* ============= ///ScriptDocBegin "Name: get_vision_set_fog( <fogset> )" "Summary: Get vision set fog defined by create_vision_set_fog( fogset ). Returns Undefined if doesn't exist." "Module: Utility" "MandatoryArg: <fogset>: Unique vision set name" "Example: ent = get_vision_set_fog( "contingency_bridge" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_vision_set_fog( fogset ) { if ( !isdefined( level.vision_set_fog ) ) level.vision_set_fog = []; ent = level.vision_set_fog[ fogset ]; //assertex( IsDefined( ent ), "visiont set fog: " + fogset + "does not exist, use create_vision_set_fog( " + fogset + " ) in your level_fog.gsc." ); return ent; } /* ============= ///ScriptDocBegin "Name: create_fog( <fogset> )" "Summary: Stores fog settings that get executed automatically with trigger_multiple_fog" "Module: Utility" "MandatoryArg: <fogset>: Unique fog setting name" "Example: ent = create_fog( "contingency_bridge" );" "NoteLine: Here are some values you might set on the ent:" "NoteLine: ent.startDist" "NoteLine: ent.halfwayDist" "NoteLine: ent.red" "NoteLine: ent.green" "NoteLine: ent.blue" "NoteLine: ent.maxOpacity" "NoteLine: ent.sunRed" "NoteLine: ent.sunGreen" "NoteLine: ent.sunBlue" "NoteLine: ent.sunDir" "NoteLine: ent.sunBeginFadeAngle" "NoteLine: ent.sunEndFadeAngle" "NoteLine: ent.normalFogScale" "SPMP: singleplayer" ///ScriptDocEnd ============= */ create_fog( fogset ) { if ( !isdefined( level.fog_set ) ) level.fog_set = []; ent = SpawnStruct(); ent.name = fogset; level.fog_set[ fogset ] = ent; return ent; } /* ============= ///ScriptDocBegin "Name: get_fog( <fogset> )" "Summary: Get fog defined by create_fog( fogset ). Returns Undefined if doesn't exist." "Module: Utility" "MandatoryArg: <fogset>: Unique fog setting name" "Example: ent = get_fog( "contingency_fog_forest" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_fog( fogset ) { if ( !isdefined( level.fog_set ) ) level.fog_set = []; ent = level.fog_set[ fogset ]; //assertex( IsDefined( ent ), "fog set: " + fogset + "does not exist, use create_fog( " + fogset + " ) in your level_fog.gsc." ); return ent; } /* ============= ///ScriptDocBegin "Name: fog_set_changes( <fog_set> , <transition_time> )" "Summary: Switches to a fog set over a transition time." "Module: Utility" "MandatoryArg: <fog_set>: The fog set name, defined by create_fog( name )" "MandatoryArg: <transition_time>: How long to transition for" "Example: fog_set_changes( "contingency_fog_forest", 10 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ fog_set_changes( fog_set, transition_time ) { if ( !isdefined( level.fog_transition_ent ) ) { level.fog_transition_ent = SpawnStruct(); level.fog_transition_ent.fogset = ""; level.fog_transition_ent.time = 0; } if ( !isdefined( level.fog_set ) ) level.fog_set = []; ent = level.fog_set[ fog_set ]; if ( !isdefined( ent ) ) { AssertEx( IsDefined( level.vision_set_fog ), "Fog set:" + fog_set + " does not exist, use create_fog( " + fog_set + " ) or create_vision_set_fog( " + fog_set + " ); in your /createart/level_fog.gsc" ); ent = level.vision_set_fog[ fog_set ]; } AssertEx( IsDefined( ent ), "Fog set:" + fog_set + " does not exist, use create_fog( " + fog_set + " ) or create_vision_set_fog( " + fog_set + " ); in your /createart/level_fog.gsc" ); //if ( !isdefined( ent ) ) // return; // transition time override if ( !isdefined( transition_time ) ) transition_time = ent.transitiontime; AssertEx( IsDefined( transition_time ), "Fog set: " + fog_set + " does not have a transition_time defined and a time was not specified in the function call." ); // this the same fog set we're already doing? if ( level.fog_transition_ent.fogset == fog_set && level.fog_transition_ent.time == transition_time ) return; if ( IsDefined( ent.sunRed ) ) { SetExpFog( ent.startDist, ent.halfwayDist, ent.red, ent.green, ent.blue, ent.maxOpacity, transition_time, ent.sunRed, ent.sunGreen, ent.sunBlue, ent.sunDir, ent.sunBeginFadeAngle, ent.sunEndFadeAngle, ent.normalFogScale ); } else { SetExpFog( ent.startDist, ent.halfwayDist, ent.red, ent.green, ent.blue, ent.maxOpacity, transition_time ); } level.fog_transition_ent.fogset = fog_set; level.fog_transition_ent.time = transition_time; } /* ============= ///ScriptDocBegin "Name: vision_set_fog_changes( <vision_set> , <transition_time> )" "Summary: Switches to a vision set over a transition time and changes fog, safely overwriting other calls to the same function. " "Module: Utility" "MandatoryArg: <vision_set>: The vision set file" "MandatoryArg: <transition_time>: How long to transition for" "Example: vision_set_fog_changes( "gulag_flying", 10 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ vision_set_fog_changes( vision_set, transition_time ) { do_fog = vision_set_changes( vision_set, transition_time ); if ( do_fog && IsDefined( get_vision_set_fog( vision_set ) ) ) fog_set_changes( vision_set, transition_time ); } /* ============= ///ScriptDocBegin "Name: vision_set_changes( <vision_set> , <transition_time> )" "Summary: Switches to a vision set over a transition time, safely overwriting other calls to the same function. " "Module: Utility" "MandatoryArg: <vision_set>: The vision set file" "MandatoryArg: <transition_time>: How long to transition for" "Example: vision_set_changes( "gulag_flying", 10 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ vision_set_changes( vision_set, transition_time ) { if ( !isdefined( level.vision_set_transition_ent ) ) { level.vision_set_transition_ent = SpawnStruct(); level.vision_set_transition_ent.vision_set = ""; level.vision_set_transition_ent.time = 0; } // this the same vision set we're already doing? if ( level.vision_set_transition_ent.vision_set == vision_set && level.vision_set_transition_ent.time == transition_time ) return false;// no fog level.vision_set_transition_ent.vision_set = vision_set; level.vision_set_transition_ent.time = transition_time; VisionSetNaked( vision_set, transition_time ); //iprintlnbold( vision_set ); SetDvar( "vision_set_current", vision_set ); return true;// do fog } /* ============= ///ScriptDocBegin "Name: enable_teamflashbangImmunity( <enable_teamflashbangImmunity> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_teamflashbangImmunity() { self thread enable_teamflashbangImmunity_proc(); } enable_teamflashbangImmunity_proc() { self endon( "death" ); while ( 1 ) { self.teamFlashbangImmunity = true; wait .05; } } /* ============= ///ScriptDocBegin "Name: disable_teamflashbangImmunity( <disable_teamflashbangImmunity> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_teamflashbangImmunity() { self.teamFlashbangImmunity = undefined; } /* ============= ///ScriptDocBegin "Name: _radiusdamage( <origin> , <range> , <maxdamage> , <mindamage> , <attacker> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ _radiusdamage( origin, range, maxdamage, mindamage, attacker ) { if ( !isdefined( attacker ) ) RadiusDamage( origin, range, maxdamage, mindamage ); else RadiusDamage( origin, range, maxdamage, mindamage, attacker ); } /* ============= ///ScriptDocBegin "Name: mask_interactives_in_volumes( <volumes> )" "Summary: Masks interactive tvs in volumes so they don't use entities. Must be done before _load." "Module: Utility" "MandatoryArg: <volumes>: Array of volumes to hide interactive objects in" "Example: mask_interactives_in_volumes( volumes );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ mask_interactives_in_volumes( volumes ) { tvs = GetEntArray( "interactive_tv", "targetname" ); foreach ( volume in volumes ) { volume.interactives = []; } foreach ( tv in tvs ) { foreach ( volume in volumes ) { if ( !volume IsTouching( tv ) ) continue; volume put_interactive_in_volume( tv ); break; } } } /* ============= ///ScriptDocBegin "Name: activate_interactives_in_volume()" "Summary: Activates masked interactive tvs in a volume" "Module: Utility" "CallOn: A masking volume" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: volume activate_interactives_in_volume();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ activate_interactives_in_volume() { if ( !isdefined( self.interactives ) ) return; foreach ( ent in self.interactives ) { toy = Spawn( "script_model", ( 0, 0, 0 ) ); toy SetModel( ent.toy_model ); toy.origin = ent.origin; toy.angles = ent.angles; toy.script_noteworthy = ent.script_noteworthy; toy.target = ent.target; toy.targetname = ent.targetname; toy thread maps\_interactive_objects::tv_logic(); } self.interactives = []; } /* ============= ///ScriptDocBegin "Name: mask_destructibles_in_volumes( <volumes> )" "Summary: Masks destructibles in an array of volumes so they dont use entities. Must be done before _load."" "Module: Utility" "MandatoryArg: <volumes>: Array of volumes " "Example: mask_destructibles_in_volumes( vols );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ mask_destructibles_in_volumes( volumes ) { destructible_toy = GetEntArray( "destructible_toy", "targetname" ); foreach ( volume in volumes ) { volume.destructibles = []; } foreach ( toy in destructible_toy ) { foreach ( volume in volumes ) { if ( !volume IsTouching( toy ) ) continue; volume put_toy_in_volume( toy ); break; } } } /* ============= ///ScriptDocBegin "Name: activate_destructibles_in_volume()" "Summary: Activate destructibles in a masked volume." "Module: Utility" "CallOn: A mask volume" "Example: vol activate_destructibles_in_volume();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ activate_destructibles_in_volume() { if ( !isdefined( self.destructibles ) ) return; foreach ( ent in self.destructibles ) { toy = Spawn( "script_model", ( 0, 0, 0 ) ); toy SetModel( ent.toy_model ); toy.origin = ent.origin; toy.angles = ent.angles; toy.script_noteworthy = ent.script_noteworthy; toy.target = ent.target; toy.destructible_type = ent.destructible_type; toy.script_noflip = ent.script_noflip; toy common_scripts\_destructible::setup_destructibles( true );// true meaning don't precache } self.destructibles = []; } /* ============= ///ScriptDocBegin "Name: setFlashbangImmunity( <immune> )" "Summary: " "Module: Entity" "CallOn: An entity" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ setFlashbangImmunity( immune ) { self.flashBangImmunity = immune; } /* ============= ///ScriptDocBegin "Name: flashBangGetTimeLeftSec()" "Summary: " "Module: Entity" "CallOn: An entity" "Example: duration = flashBangGetTimeLeftSec();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ flashBangGetTimeLeftSec() { Assert( IsDefined( self ) ); Assert( IsDefined( self.flashEndTime ) ); // duration is the flash time left durationMs = self.flashEndTime - GetTime(); if ( durationMs < 0 ) return 0; // return the duration in seconds return( durationMs * 0.001 ); } /* ============= ///ScriptDocBegin "Name: flashBangIsActive()" "Summary: " "Module: Entity" "CallOn: An entity" "Example: active = flashBangIsActive();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ flashBangIsActive() { return( flashBangGetTimeLeftSec() > 0 ); } /* ============= ///ScriptDocBegin "Name: flashBangStart( <duration> )" "Summary: I'm guessing it makes a guy get flash banged, maybe somebody could FILL IN THE FREAKING DOCS" "Module: Entity" "CallOn: An entity" "Example: actor flashBangStart( 4.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ flashBangStart( duration ) { Assert( IsDefined( self ) ); Assert( IsDefined( duration ) ); if ( IsDefined( self.flashBangImmunity ) && self.flashbangImmunity ) return; // If we're alreayd flashing, update the time to the one that would last the longest newFlashEndTime = GetTime() + ( duration * 1000.0 ); if ( IsDefined( self.flashendtime ) ) self.flashEndTime = max( self.flashendtime, newFlashEndTime ); else self.flashendtime = newFlashEndTime; self notify( "flashed" ); self SetFlashBanged( true ); } /* ============= ///ScriptDocBegin "Name: waittill_volume_dead()" "Summary: Waits for all the guys in a volume to die." "Module: Utility" "CallOn: A volume" "Example: volume waittill_volume_dead()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_volume_dead() { for ( ;; ) { ai = GetAISpeciesArray( "axis", "all" ); found_guy = false; foreach ( guy in ai ) { if ( !isalive( guy ) ) continue; if ( guy IsTouching( self ) ) { found_guy = true; break; } // check all the time, 4 guys per frame wait( 0.0125 ); } if ( !found_guy ) { // do one more complete check aHostiles = self get_ai_touching_volume( "axis" ); if ( !aHostiles.size ) break; } wait( 0.05 ); //aHostiles = self get_ai_touching_volume( "axis" ); //if ( !aHostiles.size ) // break; //wait( //waittill_dead( aHostiles ); } } /* ============= ///ScriptDocBegin "Name: waittill_volume_dead_or_dying()" "Summary: Waits for all the guys in a volume to die or do long death." "Module: Utility" "CallOn: A volume" "Example: volume waittill_volume_dead_or_dying()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_volume_dead_or_dying() { ever_found_guy = false; for ( ;; ) { ai = GetAISpeciesArray( "axis", "all" ); found_guy = false; foreach ( guy in ai ) { if ( !isalive( guy ) ) continue; if ( guy IsTouching( self ) ) { if ( guy doingLongDeath() ) continue; found_guy = true; ever_found_guy = true; break; } // check all the time, 4 guys per frame wait( 0.0125 ); } if ( !found_guy ) { // do one more complete check aHostiles = self get_ai_touching_volume( "axis" ); if ( !aHostiles.size ) { break; } else { ever_found_guy = true; } } wait( 0.05 ); //aHostiles = self get_ai_touching_volume( "axis" ); //if ( !aHostiles.size ) // break; //wait( //waittill_dead( aHostiles ); } return ever_found_guy; } /* ============= ///ScriptDocBegin "Name: waittill_volume_dead_then_set_flag( <sFlag> )" "Summary: Read the function name." "Module: Utility" "CallOn: A volume" "MandatoryArg: <param1>: " "OptionalArg: <param2>: " "Example: volume waittill_volume_dead_then_set_flag( "some_flag" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_volume_dead_then_set_flag( sFlag ) { self waittill_volume_dead(); flag_set( sFlag ); } /* ============= ///ScriptDocBegin "Name: waittill_targetname_volume_dead_then_set_flag( <targetname> , <msg> )" "Summary: Read the function name." "Module: Utility" "MandatoryArg: <targetname>: The targetname " "OptionalArg: <msg>: The flag " "Example: waittill_targetname_volume_dead_then_set_flag( "some_targetname", "some_flag" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ waittill_targetname_volume_dead_then_set_flag( targetname, msg ) { volume = GetEnt( targetname, "targetname" ); AssertEx( IsDefined( volume ), "No volume for targetname " + targetname ); volume waittill_volume_dead_then_set_flag( msg ); } /* ============= ///ScriptDocBegin "Name: player_can_be_shot()" "Summary: The player gets correct attackeraccuracy again." "Module: Utility" "Example: player_can_be_shot();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_can_be_shot() { level.player ent_flag_clear( "player_zero_attacker_accuracy" ); level.player.IgnoreRandomBulletDamage = false; level.player maps\_gameskill::update_player_attacker_accuracy(); } /* ============= ///ScriptDocBegin "Name: player_cant_be_shot()" "Summary: The player gets 0 attackeraccuracy and won't get his attackeraccuracy overwritten by _gameskill." "Module: Utility" "Example: player_cant_be_shot();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_cant_be_shot() { level.player ent_flag_set( "player_zero_attacker_accuracy" ); level.player.attackeraccuracy = 0; level.player.IgnoreRandomBulletDamage = true; } /* ============= ///ScriptDocBegin "Name: set_player_attacker_accuracy( <val> )" "Summary: Sets the player's attacker accuracy correctly so _gameskill won't overwrite it" "Module: Utility" "CallOn: A player" "MandatoryArg: <val>: The attacker accuracy" "Example: level.player set_player_attacker_accuracy( 0.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_player_attacker_accuracy( val ) { // sets player attackeraccuracy player = get_player_from_self(); player.gs.player_attacker_accuracy = val; player maps\_gameskill::update_player_attacker_accuracy(); } /* ============= ///ScriptDocBegin "Name: array_index_by_parameters( <array> )" "Summary: Indexes and array by its script_parameter values and returns the array" "Module: Utility" "MandatoryArg: <array>: The array of entities that all have script_parameters " "Example: orgs = array_index_by_parameters( friendly_escape_orgs );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_index_by_parameters( old_array ) { array = []; foreach ( item in old_array ) { array[ item.script_parameters ] = item; } return array; } /* ============= ///ScriptDocBegin "Name: array_index_by_classname( <array> )" "Summary: Indexes and array by its classname values and returns the array" "Module: Utility" "MandatoryArg: <array>: The array of entities that all have classnames " "Example: orgs = array_index_by_classname( friendly_escape_orgs );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_index_by_classname( old_array ) { array = []; foreach ( item in old_array ) { array[ item.classname ] = item; } return array; } /* ============= ///ScriptDocBegin "Name: array_index_by_script_index( <array> )" "Summary: Indexes and array by its script_index values and returns the array" "Module: Utility" "MandatoryArg: <array>: The array of entities that all have script_indexs " "Example: orgs = array_index_by_script_index( friendly_escape_orgs );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ array_index_by_script_index( array ) { // sort ents by order of script_index newarray = []; foreach ( ent in array ) { index = ent.script_index; if ( IsDefined( index ) ) { AssertEx( !isdefined( newarray[ index ] ), "Multiple ents had the same script_index of " + index ); newarray[ index ] = ent; } } return newarray; } /* ============= ///ScriptDocBegin "Name: add_target_pivot()" "Summary: Adds a .pivot to an entity, from the entity's .target." "Module: Utility" "CallOn: An entity that is going to rotate around a pivot point." "OptionalArg: <ent>: Optional override ent" "Example: evac_rock add_target_pivot();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ add_target_pivot( ent ) { if ( IsDefined( ent ) ) { self.pivot = ent; } else { AssertEx( IsDefined( self.target ), "Tried to add pivot to an entity but it has no target." ); self.pivot = GetEnt( self.target, "targetname" ); AssertEx( IsDefined( self.pivot ), "Tried to add pivot but there was no pivot entity. Must be a script mover, like a script_origin not script_struct." ); } self LinkTo( self.pivot ); } /* ============= ///ScriptDocBegin "Name: get_color_volume_from_trigger()" "Summary: Gets the color volume from a trigger that has only one color code" "Module: Color" "CallOn: A color trigger" "Example: volume = trigger get_color_volume_from_trigger();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_color_volume_from_trigger() { info = self get_color_info_from_trigger(); team = info[ "team" ]; foreach ( code in info[ "codes" ] ) { volume = level.arrays_of_colorCoded_volumes[ team ][ code ]; if ( IsDefined( volume ) ) return volume; } return undefined; } /* ============= ///ScriptDocBegin "Name: get_color_nodes_from_trigger()" "Summary: Gets the color nodes from a trigger that has only one color code" "Module: Color" "CallOn: A color trigger" "Example: nodes = trigger get_color_nodes_from_trigger();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_color_nodes_from_trigger() { info = self get_color_info_from_trigger(); team = info[ "team" ]; foreach ( code in info[ "codes" ] ) { nodes = level.arrays_of_colorCoded_nodes[ team ][ code ]; if ( IsDefined( nodes ) ) return nodes; } return undefined; } /* ============= ///ScriptDocBegin "Name: flashBangStop()" "Summary: " "Module: Entity" "CallOn: An entity" "Example: actor flashBangStop();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ flashBangStop() { self.flashendtime = undefined; self SetFlashBanged( false ); } /* ============= ///ScriptDocBegin "Name: getent_or_struct( param1, param2 )" "Summary: " "Module: Entity" "MandatoryArg: <param1>: first param of a key/value pair, such as 'self.target'" "MandatoryArg: <param2>: second param of a key/value pair, such as 'targetname'" "Example: nextNode = getent_or_struct( self.target, "targetname" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ getent_or_struct( param1, param2 ) { ent = GetEnt( param1, param2 ); if ( IsDefined( ent ) ) return ent; return getstruct( param1, param2 ); } grenade_earthQuake() { // grenades die when they explode so we wait until the end of the frame before killing the thread. // not doing so would kill the thread before the fx could happen. self thread endOnDeath(); self endon( "end_explode" ); self waittill( "explode", position ); dirt_on_screen_from_position( position ); } /* ============= ///ScriptDocBegin "Name: dirt_on_screen_from_position( <position> )" "Summary: Self explanatory" "Module: Utility" "MandatoryArg: <position>: origin of explosion" "Example: dirt_on_screen_from_position( from_on_high );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ dirt_on_screen_from_position( position ) { PlayRumbleOnPosition( "grenade_rumble", position ); Earthquake( 0.3, 0.5, position, 400 ); foreach ( player in level.players ) { if ( Distance( position, player.origin ) > 600 ) continue; if ( player DamageConeTrace( position ) ) player thread dirtEffect( position ); } } /* ============= ///ScriptDocBegin "Name: player_rides_shotgun_in_humvee( <right> , <left> , <up> , <down> )" "Summary: Makes the player pop into the humvee's shotgun seat. Returns the org used to dismount the player" "Module: Utility" "CallOn: The humvee" "OptionalArg: <directions> FOV limits for the player " "Example: org = humvee player_rides_shotgun_in_humvee( 45,45,45,45 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_rides_shotgun_in_humvee( right, left, up, down ) { level.player AllowCrouch( false ); level.player AllowProne( false ); level.player DisableWeapons(); org = spawn_tag_origin(); org LinkTo( self, "tag_passenger", ( -5, 10, -34 ), ( 0, 0, 0 ) ); org.player_dismount = spawn_tag_origin(); org.player_dismount LinkTo( self, "tag_body", ( -8, -90, -12.6 ), ( 0, 0, 0 ) ); //org.player_dismount thread maps\_debug::drawOrgForever( (1, 0, 0 )); if ( !isdefined( right ) ) right = 90; if ( !isdefined( left ) ) left = 90; if ( !isdefined( up ) ) up = 40; if ( !isdefined( down ) ) down = 40; level.player DisableWeapons(); level.player PlayerLinkTo( org, "tag_origin", 0.8, right, left, up, down ); return org; } player_leaves_humvee() { self Unlink(); move_time = 0.6; self MoveTo( self.player_dismount.origin, move_time, move_time * 0.5, move_time * 0.5 ); wait( move_time ); level.player Unlink(); level.player EnableWeapons(); level.player AllowCrouch( true ); level.player AllowProne( true ); self.player_dismount Delete(); self Delete(); } endOnDeath() { self waittill( "death" ); waittillframeend; self notify( "end_explode" ); } /* ============= ///ScriptDocBegin "Name: dirtEffect( <position> )" "Summary: plays a grenade dirt effect on the screen" "Module: player" "CallOn: player" "MandatoryArg: <position>: the position of the event that causes the effect" "Example: level.player dirtEffect( fx.origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ dirtEffect( position ) { forwardVec = VectorNormalize( AnglesToForward( self.angles ) ); rightVec = VectorNormalize( AnglesToRight( self.angles ) ); grenadeVec = VectorNormalize( position - self.origin ); fDot = VectorDot( grenadeVec, forwardVec ); rDot = VectorDot( grenadeVec, rightVec ); dirt_effects = []; if ( fDot > 0 && fDot > 0.5 && self GetCurrentWeapon() != "riotshield" ) dirt_effects[ "bottom_b" ] = true; if ( abs( fDot ) < 0.866 ) { if ( rDot > 0 ) dirt_effects[ "right" ] = true; else dirt_effects[ "left" ] = true; } foreach ( type, _ in dirt_effects ) { self thread maps\_gameskill::grenade_dirt_on_screen( type ); } } /* ============= ///ScriptDocBegin "Name: pathrandompercent_set( <value> )" "Summary: sets self.pathrandompercent to the value" "Module: AI" "CallOn: An AI" "MandatoryArg: <value>: the value of self.pathrandompercent" "Example: level.price pathrandompercent_set( 0 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ pathrandompercent_set( value ) { if ( !isdefined( self.old_pathrandompercent ) ) self.old_pathrandompercent = self.pathrandompercent; self.pathrandompercent = value; } /* ============= ///ScriptDocBegin "Name: pathrandompercent_zero()" "Summary: sets self.pathrandompercent to 0" "Module: AI" "CallOn: An AI" "Example: level.price pathrandompercent_zero();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ pathrandompercent_zero() { if ( IsDefined( self.old_pathrandompercent ) ) return; self.old_pathrandompercent = self.pathrandompercent; self.pathrandompercent = 0; } /* ============= ///ScriptDocBegin "Name: pathrandompercent_reset()" "Summary: resets self.pathrandompercent ( see pathrandompercent_zero )" "Module: AI" "CallOn: An AI" "Example: level.price pathrandompercent_reset();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ pathrandompercent_reset() { Assert( IsDefined( self.old_pathrandompercent ) ); self.pathrandompercent = self.old_pathrandompercent; self.old_pathrandompercent = undefined; } /* ============= ///ScriptDocBegin "Name: walkdist_zero()" "Summary: sets self.walkdist and self.old_walkDistFacingMotion to 0" "Module: AI" "CallOn: An AI" "Example: level.price walkdist_zero();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ walkdist_zero() { if ( IsDefined( self.old_walkDistFacingMotion ) ) return; self.old_walkDist = self.walkDist; self.old_walkDistFacingMotion = self.walkDistFacingMotion; self.walkdist = 0; self.walkDistFacingMotion = 0; } /* ============= ///ScriptDocBegin "Name: walkdist_reset()" "Summary: resets self.walkdist and self.old_walkDistFacingMotion ( see walkdist_zero )" "Module: AI" "CallOn: An AI" "Example: level.price walkdist_reset();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ walkdist_reset() { Assert( IsDefined( self.old_walkDist ) ); Assert( IsDefined( self.old_walkDistFacingMotion ) ); self.walkdist = self.old_walkDist; self.walkDistFacingMotion = self.old_walkDistFacingMotion; self.old_walkDist = undefined; self.old_walkDistFacingMotion = undefined; } /* ============= ///ScriptDocBegin "Name: enable_ignorerandombulletdamage_drone()" "Summary: effectively has the same effect as .IgnoreRandomBulletDamage on AI, but for drones" "Module: Entity" "CallOn: An a drone" "Example: guy enable_ignorerandombulletdamage_drone()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_ignorerandombulletdamage_drone() { //threading internally so script doesn't stop here...most our enable/disable utility code doesn't stop script. self thread ignorerandombulletdamage_drone_proc(); } ignorerandombulletdamage_drone_proc() { AssertEx( !IsSentient( self ), "AI tried to run enable_ignorerandombulletdamage_drone" ); self endon( "disable_ignorerandombulletdamage_drone" ); self endon( "death" ); //just an easy variable we can check for debugging - doesn't actually do anything in code. self.IgnoreRandomBulletDamage = true; self.fakehealth = self.health; self.health = 1000000; while ( 1 ) { self waittill( "damage", damage, attacker ); if ( !isplayer( attacker ) && IsSentient( attacker ) ) { if ( IsDefined( attacker.enemy ) && attacker.enemy != self ) continue; } self.fakehealth -= damage; if ( self.fakehealth <= 0 ) break; } self Kill(); } /* ============= ///ScriptDocBegin "Name: hide_notsolid( <hide_notsolid> )" "Summary: Hide an entity and make it truly notsolid via setContents" "Module: Utility" "CallOn: An entity" "Example: model hide_notsolid();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ hide_notsolid() { if ( !isdefined( self.oldContents ) ) { self.oldContents = self SetContents( 0 ); } self Hide(); } /* ============= ///ScriptDocBegin "Name: show_solid( <hide_notsolid> )" "Summary: Show an entity and retrieve its prior contents." "Module: Utility" "CallOn: An entity" "Example: model show_solid();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ show_solid() { if ( !isai( self ) ) self Solid(); if ( IsDefined( self.oldContents ) ) { self SetContents( self.oldContents ); } self Show(); } /* ============= ///ScriptDocBegin "Name: set_brakes( <num> )" "Summary: Sets the brakes on the vehicle" "Module: Utility" "CallOn: A vehicle" "MandatoryArg: <num>: The brakes, 0 to 1. " "Example: vehicle set_brakes( 0.5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_brakes( num ) { self.veh_brake = num; } /* ============= ///ScriptDocBegin "Name: disable_ignorerandombulletdamage_drone()" "Summary: stops ignoring random bullet damage" "Module: Entity" "CallOn: An a drone" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_ignorerandombulletdamage_drone() { if ( !isalive( self ) ) return; if ( !isdefined( self.IgnoreRandomBulletDamage ) ) return; self notify( "disable_ignorerandombulletdamage_drone" ); self.IgnoreRandomBulletDamage = undefined; self.health = self.fakehealth; } timeOutEnt( timeOut ) { ent = SpawnStruct(); ent delayThread( timeOut, ::send_notify, "timeout" ); return ent; } /* ============= ///ScriptDocBegin "Name: delayThread( <delay>, <function>, <arg1>, <arg2>, <arg3>, <arg4> )" "Summary: Delaythread is cool! It saves you from having to write extra script for once off commands. Note you dont have to thread it off. Delaythread is that smart!" "Module: Utility" "MandatoryArg: <delay> : The delay before the function occurs" "MandatoryArg: <delay> : The function to run." "OptionalArg: <arg1> : parameter 1 to pass to the process" "OptionalArg: <arg2> : parameter 2 to pass to the process" "OptionalArg: <arg3> : parameter 3 to pass to the process" "OptionalArg: <arg4> : parameter 4 to pass to the process" "OptionalArg: <arg5> : parameter 5 to pass to the process" "Example: delayThread( 3, ::flag_set, "player_can_rappel" ); "SPMP: both" ///ScriptDocEnd ============= */ delayThread( timer, func, param1, param2, param3, param4, param5 ) { // to thread it off thread delayThread_proc( func, timer, param1, param2, param3, param4, param5 ); } /* ============= ///ScriptDocBegin "Name: enable_danger_react( <duration_seconds> )" "Summary: if nearby teammate is shot, makes AI stop at current position, find nearby cover if available, and fight." "Module: AI" "CallOn: An AI" "MandatoryArg: <duration_seconds>: how long to stop and fight" "Example: self enable_danger_react( 10 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_danger_react( duration ) { duration *= 1000; Assert( IsAI( self ) ); self.doDangerReact = true; self.dangerReactDuration = duration; self.neverSprintForVariation = undefined; } /* ============= ///ScriptDocBegin "Name: disable_danger_react()" "Summary: disable danger reaction. See enable_danger_react" "Module: AI" "CallOn: An AI" "Example: self disable_danger_react();" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_danger_react() { Assert( IsAI( self ) ); self.doDangerReact = false; self.neverSprintForVariation = true; } /* ============= ///ScriptDocBegin "Name: set_group_advance_to_enemy_parameters( <interval> <group size> )" "Summary: sets how often and group size for AI advancing directly toward their enemy" "Module: AI" "CallOn: level" "MandatoryArg: <interval millisec>: how often" "MandatoryArg: <group size>: how many" "Example: self set_group_advance_to_enemy_parameters( 30000, 5 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_group_advance_to_enemy_parameters( interval, group_size ) { level.advanceToEnemyInterval = interval; // how often AI will try to run directly to their enemy if the enemy is not visible level.advanceToEnemyGroupMax = group_size; // group size for AI running to their enemy } /* ============= ///ScriptDocBegin "Name: reset_group_advance_to_enemy_timer( <team> )" "Summary: reset the advance-to-enemy time for a team. Useful when player advances to a new section of a level" "Module: AI" "CallOn: level" "MandatoryArg: <team>: team to reset the timer for" "Example: self reset_group_advance_to_enemy_timer( "team3" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ reset_group_advance_to_enemy_timer( team ) { Assert( IsDefined( level.lastAdvanceToEnemyTime[ team ] ) ); level.lastAdvanceToEnemyTime[ team ] = GetTime(); } /* ============= ///ScriptDocBegin "Name: set_custom_gameskill_func( <func> )" "Summary: Sets a custom func to run at the end of _gameskill::setskill(), so you can change difficulty settings." "Module: Utility" "MandatoryArg: <func>: The function to call after _gameskill::setskill()" "Example: set_custom_gameskill_func( maps\_gameskill::solo_player_in_coop_gameskill_settings );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_custom_gameskill_func( func ) { Assert( IsDefined( func ) ); level.custom_gameskill_func = func; // reset so it takes effect thread maps\_gameskill::resetSkill(); } /* ============= ///ScriptDocBegin "Name: clear_custom_gameskill_func()" "Summary: Sets a custom func to run at the end of _gameskill::setskill(), so you can change difficulty settings." "Module: Utility" "MandatoryArg: <func>: The function to call after _gameskill::setskill()" "Example: set_custom_gameskill_func( maps\_gameskill::solo_player_in_coop_gameskill_settings );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ clear_custom_gameskill_func() { level.custom_gameskill_func = undefined; // reset so it takes effect thread maps\_gameskill::resetSkill(); } /* ============= ///ScriptDocBegin "Name: set_wind( <weight>, <rate>, <variance> )" "Summary: sets the blend weight,rate on the strong wind animation for animated trees. defaults at 1 and .4." "Module: Level" "CallOn: The Level" "MandatoryArg: <weight>: the weight of the animation" "MandatoryArg: <rate>: the weight of the animation" "OptionalArg: <variance>: How much random speed is added to the rate for each loop of the animation. " "Example: set_wind( 100,6 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ set_wind( weight, rate, variance ) { Assert( IsDefined( weight ) ); Assert( IsDefined( rate ) ); maps\_animatedmodels::init_wind_if_uninitialized(); if ( IsDefined( variance ) ) level.wind.variance = variance; level.wind.rate = rate; level.wind.weight = weight; level notify( "windchange", "strong" ); } /* ============= ///ScriptDocBegin "Name: string_is_single_digit_integer( <str> )" "Summary: Tests whether a string is a single digit integer. Helpful for situations like parsing strings for indexes, etc." "Module: Utility" "CallOn: the level" "MandatoryArg: <str>: the string you want to test." "Example: bIsInt = string_is_single_digit_integer( "1" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ string_is_single_digit_integer( str ) { if ( str.size > 1 ) { return false; } arr = []; arr[ "0" ] = true; arr[ "1" ] = true; arr[ "2" ] = true; arr[ "3" ] = true; arr[ "4" ] = true; arr[ "5" ] = true; arr[ "6" ] = true; arr[ "7" ] = true; arr[ "8" ] = true; arr[ "9" ] = true; if ( IsDefined( arr[ str ] ) ) { return true; } return false; } set_battlechatter_variable( team, val ) { // used internally level.battlechatter[ team ] = val; update_battlechatter_hud(); } /* ============= ///ScriptDocBegin "Name: objective_clearAdditionalPositions( <objective_number> )" "Summary: Clears the positions for this objective" "Module: Utility" "MandatoryArg: <objective_number>: The index for the objective" "Example: objective_clearAdditionalPositions( objective_index );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ objective_clearAdditionalPositions( objective_number ) { // can have up to 8 positions, so clear them all for ( i = 0; i < 8; i++ ) { objective_additionalposition( objective_number, i, (0,0,0) ); } } /* ============= ///ScriptDocBegin "Name: get_minutes_and_seconds( <milliseconds> )" "Summary: Returns how many minutes and seconds are in the milliseconds provided. Returns array with index "minutes" and index "seconds"." "Module: Utility" "CallOn: the level" "MandatoryArg: <milliseconds>: Number of milliseconds to check" "Example: time = get_minutes_and_seconds( GetTime() ); minutes = time[ "minutes" ]; seconds = time[ "seconds" ];" "SPMP: singleplayer" ///ScriptDocEnd ============= */ get_minutes_and_seconds( milliseconds ) { time = []; time[ "minutes" ] = 0; time[ "seconds" ] = Int( milliseconds / 1000 ); while ( time[ "seconds" ] >= 60 ) { time[ "minutes" ]++; time[ "seconds" ] -= 60; } if ( time[ "seconds" ] < 10 ) time[ "seconds" ] = "0" + time[ "seconds" ]; return time; } /* ============= ///ScriptDocBegin "Name: player_has_weapon( <weap> )" "Summary: Returns true if the player has the wepaon." "Module: Utility" "MandatoryArg: <weap>: The weapon" "Example: if ( player_has_weapon( "riotshield" ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_has_weapon( weap ) { weaponList = level.player GetWeaponsListPrimaries(); foreach ( weapon in weaponList ) { if ( weapon == weap ) return true; } return false; } /* ============= ///ScriptDocBegin "Name: obj( <msg> )" "Summary: A simple script macro for translating objective strings into indices" "Module: Utility" "MandatoryArg: <msg>: The string to refer to the objective" "Example: Objective_Add( obj( "exfil" ), "current", &"ROADKILL_OBJECTIVE_REPORT", struct.origin );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ obj( msg ) { if ( !isdefined( level.obj_array ) ) { level.obj_array = []; } if ( !isdefined( level.obj_array[ msg ] ) ) { level.obj_array[ msg ] = level.obj_array.size + 1; // cause objs start at 1 not 0 } return level.obj_array[ msg ]; } /* ============= ///ScriptDocBegin "Name: MusicLoop( <alias> , <minutes> , <seconds> )" "Summary: Loop a music alias" "Module: Utility" "MandatoryArg: <alias>: The alias for the music " "MandatoryArg: <minutes>: The number of minutes between loops " "MandatoryArg: <seconds>: The number of seconds between loops " "Example: thread MusicLoop( "roadkill_armored_and_combat", 8, 24 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ MusicLoop( alias, delay_between_tracks ) { if ( !isdefined( delay_between_tracks ) ) delay_between_tracks = 0; time = musicLength( alias ); assertex( time + delay_between_tracks > 0, "No time for delay" ); level notify( "stop_music" ); level endon( "stop_music" ); for ( ;; ) { MusicPlayWrapper( alias ); wait time; wait delay_between_tracks; } } /* ============= ///ScriptDocBegin "Name: player_mount_vehicle( <vehicle> )" "Summary: Makes player drive the specified vehicle" "Module: Player" "CallOn: A player" "MandatoryArg: <vehicle>: the vehicle for the player to ride" "Example: level.player player_mount_vehicle( snowmobile );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_mount_vehicle( vehicle ) { assert( isplayer( self ) ); self MountVehicle( vehicle ); self.drivingVehicle = vehicle; } /* ============= ///ScriptDocBegin "Name: player_dismount_vehicle()" "Summary: Makes player stop driving the vehicle" "Module: Player" "CallOn: A player" "Example: " "SPMP: singleplayer" ///ScriptDocEnd ============= */ player_dismount_vehicle() { assert( isplayer( self ) ); self DismountVehicle(); self.drivingVehicle = undefined; } /* ============= ///ScriptDocBegin "Name: graph_position( <v> , <min_x> , <min_y> , <max_x> , <max_y> )" "Summary: Input graph parameters and variable, returns the result." "Module: Utility" "MandatoryArg: <v>: The variable to plot on the graph" "MandatoryArg: <min_x>: The first x value on the graph" "MandatoryArg: <min_y>: The first y value on the graph" "MandatoryArg: <max_x>: The last x value on the graph" "MandatoryArg: <max_y>: The last y value on the graph" "Example: x = graph_position( val, 0, 0, 1, 1 );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ graph_position( v, min_x, min_y, max_x, max_y ) { rise = max_y - min_y; run = max_x - min_x; assertex( run != 0, "max and min x must be different, or you havent defined any graph space." ); slope = rise / run; v -= max_x; v = slope * v; v += max_y; return v; } /* ============= ///ScriptDocBegin "Name: enable_achievement_harder_they_fall()" "Summary: enables this AI's death to count towards the achievement THE HARDER THEY FALL" "Module: AI" "CallOn: An AI" "Example: repeller enable_achievement_harder_they_fall()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ enable_achievement_harder_they_fall() { self.rappeller = true; } /* ============= ///ScriptDocBegin "Name: disable_achievement_harder_they_fall()" "Summary: disables this AI's death to count towards the achievement THE HARDER THEY FALL" "Module: AI" "CallOn: An AI" "Example: repeller disable_achievement_harder_they_fall()" "SPMP: singleplayer" ///ScriptDocEnd ============= */ disable_achievement_harder_they_fall() { self.rappeller = undefined; } enable_achievement_harder_they_fall_guy( guy ) { guy enable_achievement_harder_they_fall(); } disable_achievement_harder_they_fall_guy( guy ) { guy disable_achievement_harder_they_fall(); } /* ============= ///ScriptDocBegin "Name: musicLength( <alias> )" "Summary: Returns the length of a music alias, from main/sound/soundlength.csv, which is auto generated on convert." "Module: Utility" "MandatoryArg: <alias>: The music alias" "Example: time = musicLength( "gulag_ending_music" );" "SPMP: singleplayer" ///ScriptDocEnd ============= */ musicLength( alias ) { time = TableLookup( "sound/soundlength.csv", 0, alias, 1 ); if ( !isdefined( time ) ) { assertmsg( "No time stored in sound/soundlength.csv for " + alias ); return -1; } time = int( time ); assertex( time > 0, "Music alias " + alias + " had zero time." ); time *= 0.001; return time; } /* ============= ///ScriptDocBegin "Name: is_command_bound( <cmd> )" "Summary: Returns the amount of keys bound to the given command." "Module: Utility" "MandatoryArg: <cmd>: The command to check if it is bound, ie: "+attack", "+toggleads_throw"" "Example: if ( is_command_bound( "+toggleads_throw" ) )" "SPMP: singleplayer" ///ScriptDocEnd ============= */ is_command_bound( cmd ) { binding = GetKeyBinding( cmd ); return binding[ "count" ]; }
412
0.867921
1
0.867921
game-dev
MEDIA
0.660177
game-dev,web-backend
0.971752
1
0.971752
liquidbounceplusreborn/LiquidbouncePlus-Reborn
1,726
src/main/java/net/ccbluex/liquidbounce/injection/forge/mixins/network/MixinNetworkPlayerInfo.java
/* * LiquidBounce+ Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge. * https://github.com/WYSI-Foundation/LiquidBouncePlus/ */ package net.ccbluex.liquidbounce.injection.forge.mixins.network; import com.mojang.authlib.GameProfile; import net.ccbluex.liquidbounce.LiquidBounce; import net.ccbluex.liquidbounce.features.module.modules.client.NameProtect; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.util.ResourceLocation; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.Objects; @Mixin(NetworkPlayerInfo.class) public class MixinNetworkPlayerInfo { @Shadow @Final private GameProfile gameProfile; @Inject(method = "getLocationSkin", cancellable = true, at = @At("HEAD")) private void injectSkinProtect(CallbackInfoReturnable<ResourceLocation> cir) { NameProtect nameProtect = LiquidBounce.moduleManager.getModule(NameProtect.class); if (nameProtect.getState() && nameProtect.getSkinProtectValue().get()) { if (nameProtect.getAllPlayersValue().get() || Objects.equals(gameProfile.getId(), Minecraft.getMinecraft().getSession().getProfile().getId())) { cir.setReturnValue(DefaultPlayerSkin.getDefaultSkin(this.gameProfile.getId())); cir.cancel(); } } } }
412
0.915844
1
0.915844
game-dev
MEDIA
0.922567
game-dev
0.704665
1
0.704665
DerKoun/bsnes-hd
1,166
hiro/core/widget/frame.cpp
#if defined(Hiro_Frame) auto mFrame::allocate() -> pObject* { return new pFrame(*this); } auto mFrame::destruct() -> void { if(auto& sizable = state.sizable) sizable->destruct(); mWidget::destruct(); } // auto mFrame::append(sSizable sizable) -> type& { if(auto& sizable = state.sizable) remove(sizable); state.sizable = sizable; sizable->setParent(this, 0); signal(append, sizable); return *this; } auto mFrame::remove(sSizable sizable) -> type& { signal(remove, sizable); sizable->setParent(); state.sizable.reset(); return *this; } auto mFrame::reset() -> type& { if(auto& sizable = state.sizable) remove(sizable); return *this; } auto mFrame::setParent(mObject* object, int offset) -> type& { if(auto& sizable = state.sizable) sizable->destruct(); mObject::setParent(object, offset); if(auto& sizable = state.sizable) sizable->setParent(this, 0); return *this; } auto mFrame::setText(const string& text) -> type& { state.text = text; signal(setText, text); return *this; } auto mFrame::sizable() const -> Sizable { return state.sizable; } auto mFrame::text() const -> string { return state.text; } #endif
412
0.878903
1
0.878903
game-dev
MEDIA
0.516808
game-dev
0.892229
1
0.892229
ProjectSkyfire/SkyFire_548
85,684
src/server/game/Handlers/MiscHandler.cpp
/* * This file is part of Project SkyFire https://www.projectskyfire.org. * See LICENSE.md file for Copyright information */ #include "AccountMgr.h" #include "AccountMgr.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Battleground.h" #include "BattlegroundMgr.h" #include "BigNumber.h" #include "CellImpl.h" #include "CharacterBoost.h" #include "Chat.h" #include "Common.h" #include "CreatureAI.h" #include "DatabaseEnv.h" #include "DB2Stores.h" #include "DBCEnums.h" #include "GameObjectAI.h" #include "GossipDef.h" #include "Group.h" #include "GuildMgr.h" #include "InstanceScript.h" #include "Language.h" #include "Log.h" #include "LootMgr.h" #include "MapManager.h" #include "Object.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "OutdoorPvP.h" #include "Pet.h" #include "Player.h" #include "ScriptMgr.h" #include "SocialMgr.h" #include "Spell.h" #include "UpdateData.h" #include "Vehicle.h" #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" #include "zlib.h" void WorldSession::HandleRepopRequestOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Recvd CMSG_REPOP_REQUEST Message"); recvData.read_skip<uint8>(); if (GetPlayer()->IsAlive() || GetPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) return; if (GetPlayer()->HasAuraType(SPELL_AURA_PREVENT_RESURRECTION)) return; // silently return, client should display the error by itself // the world update order is sessions, players, creatures // the netcode runs in parallel with all of these // creatures can kill players // so if the server is lagging enough the player can // release spirit after he's killed but before he is updated if (GetPlayer()->getDeathState() == DeathState::JUST_DIED) { SF_LOG_DEBUG("network", "HandleRepopRequestOpcode: got request after player %s(%d) was killed and before he was updated", GetPlayer()->GetName().c_str(), GetPlayer()->GetGUIDLow()); GetPlayer()->KillPlayer(); } //this is spirit release confirm? GetPlayer()->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); GetPlayer()->BuildPlayerRepop(); GetPlayer()->RepopAtGraveyard(); } void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_GOSSIP_SELECT_OPTION"); ObjectGuid guid; uint32 gossipListId; uint32 menuId; uint8 boxTextLength = 0; std::string code = ""; recvData >> gossipListId >> menuId; guid[3] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); boxTextLength = recvData.ReadBits(8); guid[2] = recvData.ReadBit(); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[5]); if (_player->PlayerTalkClass->IsGossipOptionCoded(gossipListId)) code = recvData.ReadString(boxTextLength); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[1]); Creature* unit = NULL; GameObject* go = NULL; if (IS_CRE_OR_VEH_GUID(guid)) { unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE); if (!unit) { SF_LOG_DEBUG("network", "WORLD: HandleGossipSelectOptionOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); return; } } else if (IS_GAMEOBJECT_GUID(guid)) { go = _player->GetMap()->GetGameObject(guid); if (!go) { SF_LOG_DEBUG("network", "WORLD: HandleGossipSelectOptionOpcode - GameObject (GUID: %u) not found.", uint32(GUID_LOPART(guid))); return; } } else { SF_LOG_DEBUG("network", "WORLD: HandleGossipSelectOptionOpcode - unsupported GUID type for highguid %u. lowpart %u.", uint32(GUID_HIPART(guid)), uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); if ((unit && unit->GetCreatureTemplate()->ScriptID != unit->LastUsedScriptID) || (go && go->GetGOInfo()->ScriptId != go->LastUsedScriptID)) { SF_LOG_DEBUG("network", "WORLD: HandleGossipSelectOptionOpcode - Script reloaded while in use, ignoring and set new scipt id"); if (unit) unit->LastUsedScriptID = unit->GetCreatureTemplate()->ScriptID; if (go) go->LastUsedScriptID = go->GetGOInfo()->ScriptId; _player->PlayerTalkClass->SendCloseGossip(); return; } if (!code.empty()) { if (unit) { unit->AI()->sGossipSelectCode(_player, menuId, gossipListId, code.c_str()); if (!sScriptMgr->OnGossipSelectCode(_player, unit, _player->PlayerTalkClass->GetGossipOptionSender(gossipListId), _player->PlayerTalkClass->GetGossipOptionAction(gossipListId), code.c_str())) _player->OnGossipSelect(unit, gossipListId, menuId); } else { go->AI()->GossipSelectCode(_player, menuId, gossipListId, code.c_str()); sScriptMgr->OnGossipSelectCode(_player, go, _player->PlayerTalkClass->GetGossipOptionSender(gossipListId), _player->PlayerTalkClass->GetGossipOptionAction(gossipListId), code.c_str()); } } else { if (unit) { unit->AI()->sGossipSelect(_player, menuId, gossipListId); if (!sScriptMgr->OnGossipSelect(_player, unit, _player->PlayerTalkClass->GetGossipOptionSender(gossipListId), _player->PlayerTalkClass->GetGossipOptionAction(gossipListId))) _player->OnGossipSelect(unit, gossipListId, menuId); } else { go->AI()->GossipSelect(_player, menuId, gossipListId); if (!sScriptMgr->OnGossipSelect(_player, go, _player->PlayerTalkClass->GetGossipOptionSender(gossipListId), _player->PlayerTalkClass->GetGossipOptionAction(gossipListId))) _player->OnGossipSelect(go, gossipListId, menuId); } } } void WorldSession::HandleWhoOpcode(WorldPacket& recvData) { //CMSG_WHO SF_LOG_DEBUG("network", "WORLD: Recvd CMSG_WHO Message"); time_t now = time(NULL); if (now - timeLastWhoCommand < 5) return; else timeLastWhoCommand = now; uint32 levelMin, levelMax, raceMask, classMask, zonesCount, wordCount; uint32 zoneIds[10]; // 10 is client limit bool requestServerInfo, showEnemies, showArenaPlayers, exactName; uint8 playerLen, guildLen, realmNameLen, guildRealmNameLen; std::string playerName, guildName, realmName, guildRealmName; recvData >> classMask; // race mask recvData >> raceMask; // minimal player level, default 100 (MAX_LEVEL) recvData >> levelMax; // maximal player level, default 0 recvData >> levelMin; // class mask showEnemies = recvData.ReadBit(); exactName = recvData.ReadBit(); requestServerInfo = recvData.ReadBit(); guildRealmNameLen = recvData.ReadBits(9); showArenaPlayers = recvData.ReadBit(); playerLen = recvData.ReadBits(6); zonesCount = recvData.ReadBits(4); // zones count, client limit = 10 (2.0.10) if (zonesCount > 10) // can't be received from real client or broken packet return; realmNameLen = recvData.ReadBits(9); guildLen = recvData.ReadBits(7); wordCount = recvData.ReadBits(3); if (wordCount > 4) return; // can't be received from real client or broken packet uint8* wordLens = new uint8[wordCount]; std::string* words = new std::string[wordCount]; for (uint8 i = 0; i < wordCount; i++) wordLens[i] = recvData.ReadBits(7); std::wstring wWords[4]; for (uint32 i = 0; i < wordCount; ++i) { std::string temp; recvData >> temp; // user entered string, it used as universal search pattern(guild+player name)? if (!Utf8toWStr(temp, wWords[i])) continue; wstrToLower(wWords[i]); SF_LOG_DEBUG("network", "String %u: %s", i, temp.c_str()); } guildRealmName = recvData.ReadString(guildRealmNameLen); for (uint32 i = 0; i < zonesCount; ++i) { recvData >> zoneIds[i]; // zone id, 0 if zone is unknown... SF_LOG_DEBUG("network", "Zone %u: %u", i, zoneIds[i]); } // NYI playerName = recvData.ReadString(playerLen); realmName = recvData.ReadString(realmNameLen); guildName = recvData.ReadString(guildLen); uint32 virtualRealmAddress = 0; int32 faction = 0, locale = 0; if (requestServerInfo) { recvData >> locale; recvData >> virtualRealmAddress; recvData >> faction; } SF_LOG_DEBUG("network", "Minlvl %u, maxlvl %u, name %s, guild %s, racemask %u, classmask %u, zones %u, strings %u", levelMin, levelMax, playerName.c_str(), guildName.c_str(), raceMask, classMask, zonesCount, wordCount); std::wstring wPlayerName, wGuildName; if (!(Utf8toWStr(playerName, wPlayerName) && Utf8toWStr(guildName, wGuildName))) return; wstrToLower(wPlayerName); wstrToLower(wGuildName); // SMSG_WHO // client send in case not set max level value 100 but Skyfire supports 255 max level, // update it to show GMs with characters after 100 level if (levelMax >= MAX_LEVEL) levelMax = STRONG_MAX_LEVEL; uint32 team = _player->GetTeam(); //bool allowTwoSideWhoList = sWorld->GetBoolConfig(CONFIG_ALLOW_TWO_SIDE_WHO_LIST); uint32 gmLevelInWhoList = sWorld->getIntConfig(WorldIntConfigs::CONFIG_GM_LEVEL_IN_WHO_LIST); uint8 displaycount = 0, matchcount = 0; ByteBuffer bytesData; WorldPacket data(SMSG_WHO); size_t pos = data.bitwpos(); data.WriteBits(displaycount, 6); SF_SHARED_GUARD readGuard(*HashMapHolder<Player>::GetLock()); HashMapHolder<Player>::MapType const& m = sObjectAccessor->GetPlayers(); for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { Player* target = itr->second; // player can see member of other team only if CONFIG_ALLOW_TWO_SIDE_WHO_LIST if (target->GetTeam() != team && !HasPermission(rbac::RBAC_PERM_TWO_SIDE_WHO_LIST)) continue; // player can see MODERATOR, GAME MASTER, ADMINISTRATOR only if CONFIG_GM_IN_WHO_LIST if (!HasPermission(rbac::RBAC_PERM_WHO_SEE_ALL_SEC_LEVELS) && target->GetSession()->GetSecurity() > AccountTypes(gmLevelInWhoList)) continue; // do not process players which are not in world if (!target->IsInWorld()) continue; // check if target is globally visible for player if (!target->IsVisibleGloballyFor(_player)) continue; // check if target's level is in level range uint8 level = target->getLevel(); if (level < levelMin || level > levelMax) continue; // check if class matches classmask uint8 class_ = target->getClass(); if (!(classMask & (1 << class_))) continue; // check if race matches racemask uint32 race = target->getRace(); if (!(raceMask & (1 << race))) continue; uint32 zoneId = target->GetZoneId(); uint8 gender = target->getGender(); bool z_show = true; for (uint32 i = 0; i < zonesCount; ++i) { if (zoneIds[i] == zoneId) { z_show = true; break; } z_show = false; } if (!z_show) continue; std::string pname = target->GetName(); std::wstring wpname; if (!Utf8toWStr(pname, wpname)) continue; wstrToLower(wpname); if (!(wPlayerName.empty() || wpname.find(wPlayerName) != std::wstring::npos)) continue; std::string gname = sGuildMgr->GetGuildNameById(target->GetGuildId()); std::wstring wgname; if (!Utf8toWStr(gname, wgname)) continue; wstrToLower(wgname); if (!(wGuildName.empty() || wgname.find(wGuildName) != std::wstring::npos)) continue; std::string aname; if (AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(zoneId)) aname = areaEntry->m_AreaName[GetSessionDbcLocale()]; bool s_show = true; for (uint32 i = 0; i < wordCount; ++i) { if (!wWords[i].empty()) { if (wgname.find(wWords[i]) != std::wstring::npos || wpname.find(wWords[i]) != std::wstring::npos || Utf8FitTo(aname, wWords[i])) { s_show = true; break; } s_show = false; } } if (!s_show) continue; // 49 is maximum player count sent to client - can be overridden // through config, but is unstable if ((matchcount++) >= sWorld->getIntConfig(WorldIntConfigs::CONFIG_MAX_WHO)) continue; ObjectGuid playerGuid = target->GetGUID(); ObjectGuid accountId = target->GetSession()->GetAccountId(); ObjectGuid guildGuid = target->GetGuild() ? target->GetGuild()->GetGUID() : 0; data.WriteBit(accountId[2]); data.WriteBit(playerGuid[2]); data.WriteBit(accountId[7]); data.WriteBit(guildGuid[5]); data.WriteBits(gname.size(), 7); data.WriteBit(accountId[1]); data.WriteBit(accountId[5]); data.WriteBit(guildGuid[7]); data.WriteBit(playerGuid[5]); data.WriteBit(false); data.WriteBit(guildGuid[1]); data.WriteBit(playerGuid[6]); data.WriteBit(guildGuid[2]); data.WriteBit(playerGuid[4]); data.WriteBit(guildGuid[0]); data.WriteBit(guildGuid[3]); data.WriteBit(accountId[6]); data.WriteBit(false); data.WriteBit(playerGuid[1]); data.WriteBit(guildGuid[4]); data.WriteBit(accountId[0]); if (DeclinedName const* names = itr->second->GetDeclinedNames()) { for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i) data.WriteBits(names->name[i].size(), 14); } else { for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i) data.WriteBits(0, 7); } data.WriteBit(playerGuid[3]); data.WriteBit(guildGuid[6]); data.WriteBit(playerGuid[0]); data.WriteBit(accountId[4]); data.WriteBit(accountId[3]); data.WriteBit(playerGuid[7]); data.WriteBits(pname.size(), 6); bytesData.WriteByteSeq(playerGuid[1]); bytesData << uint32(target->GetSession()->GetVirtualRealmID()); bytesData.WriteByteSeq(playerGuid[7]); bytesData << uint32(realmID); // NYI. guild creation virtual realm id. bytesData.WriteByteSeq(playerGuid[4]); bytesData.WriteString(pname); bytesData.WriteByteSeq(guildGuid[1]); bytesData.WriteByteSeq(playerGuid[0]); bytesData.WriteByteSeq(guildGuid[2]); bytesData.WriteByteSeq(guildGuid[0]); bytesData.WriteByteSeq(guildGuid[4]); bytesData.WriteByteSeq(playerGuid[3]); bytesData.WriteByteSeq(guildGuid[6]); bytesData << uint32(target->GetSession()->GetAccountId()); bytesData.WriteString(gname); bytesData.WriteByteSeq(guildGuid[3]); bytesData.WriteByteSeq(accountId[4]); bytesData << uint8(class_); bytesData.WriteByteSeq(accountId[7]); bytesData.WriteByteSeq(playerGuid[6]); bytesData.WriteByteSeq(playerGuid[2]); if (DeclinedName const* names = itr->second->GetDeclinedNames()) for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i) bytesData.WriteString(names->name[i]); bytesData.WriteByteSeq(accountId[2]); bytesData.WriteByteSeq(accountId[3]); bytesData << uint8(race); bytesData.WriteByteSeq(guildGuid[7]); bytesData.WriteByteSeq(accountId[1]); bytesData.WriteByteSeq(accountId[5]); bytesData.WriteByteSeq(accountId[6]); bytesData.WriteByteSeq(playerGuid[5]); bytesData.WriteByteSeq(accountId[0]); bytesData << uint8(gender); bytesData.WriteByteSeq(guildGuid[5]); bytesData << uint8(level); bytesData << int32(zoneId); ++displaycount; } data.FlushBits(); data.PutBits(pos, displaycount, 6); data.append(bytesData); SendPacket(&data); delete[] words; delete[] wordLens; SF_LOG_DEBUG("network", "WORLD: Send SMSG_WHO Message"); } void WorldSession::HandleLogoutRequestOpcode(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: Recvd CMSG_LOGOUT_REQUEST Message, security - %u", uint8(GetSecurity())); if (uint64 lguid = GetPlayer()->GetLootGUID()) DoLootRelease(lguid); bool instantLogout = (GetPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && !GetPlayer()->IsInCombat()) || GetPlayer()->IsInFlight() || HasPermission(rbac::RBAC_PERM_INSTANT_LOGOUT); /// TODO: Possibly add RBAC permission to log out in combat bool canLogoutInCombat = GetPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING); uint32 reason = 0; if (GetPlayer()->IsInCombat() && !canLogoutInCombat) reason = 1; else if (GetPlayer()->IsFalling()) reason = 3; // is jumping or falling else if (GetPlayer()->duel || GetPlayer()->HasAura(9454)) // is dueling or frozen by GM via freeze command reason = 2; // FIXME - Need the correct value WorldPacket data(SMSG_LOGOUT_RESPONSE, 1 + 4); data << uint32(reason); data.WriteBit(instantLogout); data.FlushBits(); SendPacket(&data); if (reason) { LogoutRequest(0); return; } // instant logout in taverns/cities or on taxi or for admins, gm's, mod's if its enabled in worldserver.conf if (instantLogout) { LogoutPlayer(true); return; } // not set flags if player can't free move to prevent lost state at logout cancel if (GetPlayer()->CanFreeMove()) { GetPlayer()->SetStandState(UNIT_STAND_STATE_SIT); GetPlayer()->SetRooted(true); GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } LogoutRequest(time(NULL)); } void WorldSession::HandlePlayerLogoutOpcode(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: Recvd CMSG_PLAYER_LOGOUT Message"); } void WorldSession::HandleLogoutCancelOpcode(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: Recvd CMSG_LOGOUT_CANCEL Message"); // Player have already logged out serverside, too late to cancel if (!GetPlayer()) return; LogoutRequest(0); WorldPacket data(SMSG_LOGOUT_CANCEL_ACK, 0); SendPacket(&data); // not remove flags if can't free move - its not set in Logout request code. if (GetPlayer()->CanFreeMove()) { //!we can move again GetPlayer()->SetRooted(false); //! Stand Up GetPlayer()->SetStandState(UNIT_STAND_STATE_STAND); //! DISABLE_ROTATE GetPlayer()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } SF_LOG_DEBUG("network", "WORLD: Sent SMSG_LOGOUT_CANCEL_ACK Message"); } void WorldSession::HandleSetPvP(WorldPacket& recvData) { if (recvData.size() == 1) { bool newPvPStatus; newPvPStatus = recvData.ReadBit(); GetPlayer()->ApplyModFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP, newPvPStatus); GetPlayer()->ApplyModFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_PVP_TIMER, !newPvPStatus); } } void WorldSession::HandleTogglePvP(WorldPacket& /*recvData*/) { GetPlayer()->ToggleFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP); GetPlayer()->ToggleFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_PVP_TIMER); if (GetPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP)) { if (!GetPlayer()->IsPvP() || GetPlayer()->pvpInfo.EndTimer) GetPlayer()->UpdatePvP(true, true); } else { if (!GetPlayer()->pvpInfo.IsHostile && GetPlayer()->IsPvP()) GetPlayer()->pvpInfo.EndTimer = time(NULL); // start toggle-off } //if (OutdoorPvP* pvp = _player->GetOutdoorPvP()) // pvp->HandlePlayerActivityChanged(_player); } void WorldSession::HandleZoneUpdateOpcode(WorldPacket& recvData) { uint32 newZone; recvData >> newZone; SF_LOG_DEBUG("network", "WORLD: Recvd ZONE_UPDATE: %u", newZone); // use server size data uint32 newzone, newarea; GetPlayer()->GetZoneAndAreaId(newzone, newarea); GetPlayer()->UpdateZone(newzone, newarea); //GetPlayer()->SendInitWorldStates(true, newZone); } void WorldSession::HandleReturnToGraveyard(WorldPacket& /*recvPacket*/) { if (GetPlayer()->IsAlive() || !GetPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) return; GetPlayer()->RepopAtGraveyard(); } void WorldSession::HandleRequestCemeteryList(WorldPacket& /*recvPacket*/) { uint32 zoneId = _player->GetZoneId(); uint32 team = _player->GetTeam(); std::vector<uint32> GraveyardIds; GraveYardContainer::const_iterator it; std::pair<GraveYardContainer::const_iterator, GraveYardContainer::const_iterator> range; range = sObjectMgr->GraveYardStore.equal_range(zoneId); for (it = range.first; it != range.second && GraveyardIds.size() < 16; ++it) // client max { if (it->second.team == 0 || it->second.team == team) GraveyardIds.push_back(it->first); } if (GraveyardIds.empty()) { SF_LOG_DEBUG("network", "No graveyards found for zone %u for %u (team %u) in CMSG_REQUEST_CEMETERY_LIST", zoneId, m_GUIDLow, team); return; } bool IsGossipTriggered = false; WorldPacket data(SMSG_REQUEST_CEMETERY_LIST_RESPONSE, 4 + 4 * GraveyardIds.size()); data.WriteBits(GraveyardIds.size(), 22); data << IsGossipTriggered; for (uint32 i = 0; i < GraveyardIds.size(); ++i) data << uint32(GraveyardIds[i]); SendPacket(&data); } void WorldSession::HandleSetSelectionOpcode(WorldPacket& recvData) { ObjectGuid guid; guid[7] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[2]); _player->SetSelection(guid); } void WorldSession::HandleStandStateChangeOpcode(WorldPacket& recvData) { // SF_LOG_DEBUG("network", "WORLD: Received CMSG_STAND_STATE_CHANGE"); -- too many spam in log at lags/debug stop uint32 animstate; recvData >> animstate; _player->SetStandState(animstate); } void WorldSession::HandleContactListOpcode(WorldPacket& recvData) { recvData.read_skip<uint32>(); // always 1 SF_LOG_DEBUG("network", "WORLD: Received CMSG_CONTACT_LIST"); _player->GetSocial()->SendSocialList(_player); } void WorldSession::HandleAddFriendOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_ADD_FRIEND"); std::string friendName = GetSkyFireString(LANG_FRIEND_IGNORE_UNKNOWN); std::string friendNote; recvData >> friendName; recvData >> friendNote; friendName = friendName.substr(0, friendName.find("-")); if (!normalizePlayerName(friendName)) return; SF_LOG_DEBUG("network", "WORLD: %s asked to add friend : '%s'", GetPlayer()->GetName().c_str(), friendName.c_str()); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_RACE_ACC_BY_NAME); stmt->setString(0, friendName); _addFriendCallback.SetParam(friendNote); _addFriendCallback.SetFutureResult(CharacterDatabase.AsyncQuery(stmt)); } void WorldSession::HandleAddFriendOpcodeCallBack(PreparedQueryResult result, std::string const& friendNote) { if (!GetPlayer()) return; uint64 friendGuid; uint32 friendAccountId; uint32 team; FriendsResult friendResult; friendResult = FRIEND_NOT_FOUND; friendGuid = 0; if (result) { Field* fields = result->Fetch(); friendGuid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER); team = Player::TeamForRace(fields[1].GetUInt8()); friendAccountId = fields[2].GetUInt32(); if (HasPermission(rbac::RBAC_PERM_ALLOW_GM_FRIEND) || AccountMgr::IsPlayerAccount(AccountMgr::GetSecurity(friendAccountId, GetVirtualRealmID()))) { if (friendGuid) { if (friendGuid == GetPlayer()->GetGUID()) friendResult = FRIEND_SELF; else if (GetPlayer()->GetTeam() != team && !HasPermission(rbac::RBAC_PERM_TWO_SIDE_ADD_FRIEND)) friendResult = FRIEND_ENEMY; else if (GetPlayer()->GetSocial()->HasFriend(GUID_LOPART(friendGuid))) friendResult = FRIEND_ALREADY; else { Player* pFriend = ObjectAccessor::FindPlayer(friendGuid); if (pFriend && pFriend->IsInWorld() && pFriend->IsVisibleGloballyFor(GetPlayer())) friendResult = FRIEND_ADDED_ONLINE; else friendResult = FRIEND_ADDED_OFFLINE; if (!GetPlayer()->GetSocial()->AddToSocialList(GUID_LOPART(friendGuid), false)) { friendResult = FRIEND_LIST_FULL; SF_LOG_DEBUG("network", "WORLD: %s's friend list is full.", GetPlayer()->GetName().c_str()); } } GetPlayer()->GetSocial()->SetFriendNote(GUID_LOPART(friendGuid), friendNote); } } } sSocialMgr->SendFriendStatus(GetPlayer(), friendResult, GUID_LOPART(friendGuid), false); SF_LOG_DEBUG("network", "WORLD: Sent (SMSG_FRIEND_STATUS)"); } void WorldSession::HandleDelFriendOpcode(WorldPacket& recvData) { uint64 FriendGUID; SF_LOG_DEBUG("network", "WORLD: Received CMSG_DEL_FRIEND"); recvData >> FriendGUID; _player->GetSocial()->RemoveFromSocialList(GUID_LOPART(FriendGUID), false); sSocialMgr->SendFriendStatus(GetPlayer(), FRIEND_REMOVED, GUID_LOPART(FriendGUID), false); SF_LOG_DEBUG("network", "WORLD: Sent motd (SMSG_FRIEND_STATUS)"); } void WorldSession::HandleAddIgnoreOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_ADD_IGNORE"); std::string ignoreName = GetSkyFireString(LANG_FRIEND_IGNORE_UNKNOWN); recvData >> ignoreName; if (!normalizePlayerName(ignoreName)) return; SF_LOG_DEBUG("network", "WORLD: %s asked to Ignore: '%s'", GetPlayer()->GetName().c_str(), ignoreName.c_str()); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_BY_NAME); stmt->setString(0, ignoreName); _addIgnoreCallback = CharacterDatabase.AsyncQuery(stmt); } void WorldSession::HandleAddIgnoreOpcodeCallBack(PreparedQueryResult result) { if (!GetPlayer()) return; uint64 IgnoreGuid; FriendsResult ignoreResult; ignoreResult = FRIEND_IGNORE_NOT_FOUND; IgnoreGuid = 0; if (result) { IgnoreGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER); if (IgnoreGuid) { if (IgnoreGuid == GetPlayer()->GetGUID()) //not add yourself ignoreResult = FRIEND_IGNORE_SELF; else if (GetPlayer()->GetSocial()->HasIgnore(GUID_LOPART(IgnoreGuid))) ignoreResult = FRIEND_IGNORE_ALREADY; else { ignoreResult = FRIEND_IGNORE_ADDED; // ignore list full if (!GetPlayer()->GetSocial()->AddToSocialList(GUID_LOPART(IgnoreGuid), true)) ignoreResult = FRIEND_IGNORE_FULL; } } } sSocialMgr->SendFriendStatus(GetPlayer(), ignoreResult, GUID_LOPART(IgnoreGuid), false); SF_LOG_DEBUG("network", "WORLD: Sent (SMSG_FRIEND_STATUS)"); } void WorldSession::HandleDelIgnoreOpcode(WorldPacket& recvData) { uint64 IgnoreGUID; SF_LOG_DEBUG("network", "WORLD: Received CMSG_DEL_IGNORE"); recvData >> IgnoreGUID; _player->GetSocial()->RemoveFromSocialList(GUID_LOPART(IgnoreGUID), true); sSocialMgr->SendFriendStatus(GetPlayer(), FRIEND_IGNORE_REMOVED, GUID_LOPART(IgnoreGUID), false); SF_LOG_DEBUG("network", "WORLD: Sent motd (SMSG_FRIEND_STATUS)"); } void WorldSession::HandleSetContactNotesOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "CMSG_SET_CONTACT_NOTES"); uint64 guid; std::string note; recvData >> guid >> note; _player->GetSocial()->SetFriendNote(GUID_LOPART(guid), note); } void WorldSession::HandleBugOpcode(WorldPacket& recvData) { uint32 suggestion, contentlen, typelen; std::string content, type; recvData >> suggestion >> contentlen; content = recvData.ReadString(contentlen); recvData >> typelen; type = recvData.ReadString(typelen); if (suggestion == 0) SF_LOG_DEBUG("network", "WORLD: Received CMSG_BUG [Bug Report]"); else SF_LOG_DEBUG("network", "WORLD: Received CMSG_BUG [Suggestion]"); SF_LOG_DEBUG("network", "%s", type.c_str()); SF_LOG_DEBUG("network", "%s", content.c_str()); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BUG_REPORT); stmt->setString(0, type); stmt->setString(1, content); CharacterDatabase.Execute(stmt); } void WorldSession::HandleReclaimCorpseOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_RECLAIM_CORPSE"); ObjectGuid guid; guid[1] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[3]); if (GetPlayer()->IsAlive()) return; // do not allow corpse reclaim in arena if (GetPlayer()->InArena()) return; // body not released yet if (!GetPlayer()->HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) return; Corpse* corpse = GetPlayer()->GetCorpse(); if (!corpse) return; // prevent resurrect before 30-sec delay after body release not finished if (time_t(corpse->GetGhostTime() + GetPlayer()->GetCorpseReclaimDelay(corpse->GetType() == CorpseType::CORPSE_RESURRECTABLE_PVP)) > time_t(time(NULL))) return; if (!corpse->IsWithinDistInMap(GetPlayer(), CORPSE_RECLAIM_RADIUS, true)) return; // resurrect GetPlayer()->ResurrectPlayer(GetPlayer()->InBattleground() ? 1.0f : 0.5f); // spawn bones GetPlayer()->SpawnCorpseBones(); } void WorldSession::HandleResurrectResponseOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_RESURRECT_RESPONSE"); ObjectGuid guid; uint32 status; recvData >> status; guid[3] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[5]); if (GetPlayer()->IsAlive()) return; if (status == 1) { GetPlayer()->ClearResurrectRequestData(); // reject return; } if (!GetPlayer()->IsRessurectRequestedBy(guid)) return; GetPlayer()->ResurectUsingRequestData(); } void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) { uint32 triggerId; uint8 unk1, unk2; recvData >> triggerId; unk1 = recvData.ReadBit(); unk2 = recvData.ReadBit(); SF_LOG_DEBUG("network", "CMSG_AREATRIGGER. Trigger ID: %u, Unk1: %u, Unk2: %u", triggerId, unk1, unk2); Player* player = GetPlayer(); if (player->IsInFlight()) { SF_LOG_DEBUG("network", "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) in flight, ignore Area Trigger ID:%u, unk1: %u, unk2: %u", player->GetName().c_str(), player->GetGUIDLow(), triggerId, unk1, unk2); return; } AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(triggerId); if (!atEntry) { SF_LOG_DEBUG("network", "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) send unknown (by DBC) Area Trigger ID:%u, unk1: %u, unk2: %u", player->GetName().c_str(), player->GetGUIDLow(), triggerId, unk1, unk2); return; } if (player->GetMapId() != atEntry->mapid) { SF_LOG_DEBUG("network", "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) too far (trigger map: %u player map: %u), ignore Area Trigger ID: %u, unk1: %u, unk2: %u", player->GetName().c_str(), atEntry->mapid, player->GetMapId(), player->GetGUIDLow(), triggerId, unk1, unk2); return; } // delta is safe radius const float delta = 5.0f; if (atEntry->radius > 0) { // if we have radius check it float dist = player->GetDistance(atEntry->x, atEntry->y, atEntry->z); if (dist > atEntry->radius + delta) { SF_LOG_DEBUG("network", "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) too far (radius: %f distance: %f), ignore Area Trigger ID: %u, unk1: %u, unk2: %u", player->GetName().c_str(), player->GetGUIDLow(), atEntry->radius, dist, triggerId, unk1, unk2); return; } } else { // we have only extent // rotate the players position instead of rotating the whole cube, that way we can make a simplified // is-in-cube check and we have to calculate only one point instead of 4 // 2PI = 360°, keep in mind that ingame orientation is counter-clockwise double rotation = 2 * M_PI - atEntry->box_orientation; double sinVal = std::sin(rotation); double cosVal = std::cos(rotation); float playerBoxDistX = player->GetPositionX() - atEntry->x; float playerBoxDistY = player->GetPositionY() - atEntry->y; float rotPlayerX = float(atEntry->x + playerBoxDistX * cosVal - playerBoxDistY * sinVal); float rotPlayerY = float(atEntry->y + playerBoxDistY * cosVal + playerBoxDistX * sinVal); // box edges are parallel to coordiante axis, so we can treat every dimension independently :D float dz = player->GetPositionZ() - atEntry->z; float dx = rotPlayerX - atEntry->x; float dy = rotPlayerY - atEntry->y; if ((fabs(dx) > atEntry->box_x / 2 + delta) || (fabs(dy) > atEntry->box_y / 2 + delta) || (fabs(dz) > atEntry->box_z / 2 + delta)) { SF_LOG_DEBUG("network", "HandleAreaTriggerOpcode: Player '%s' (GUID: %u) too far (1/2 box X: %f 1/2 box Y: %f 1/2 box Z: %f rotatedPlayerX: %f rotatedPlayerY: %f dZ:%f), ignore Area Trigger ID: %u, unk1: %u, unk2: %u", player->GetName().c_str(), player->GetGUIDLow(), atEntry->box_x / 2, atEntry->box_y / 2, atEntry->box_z / 2, rotPlayerX, rotPlayerY, dz, triggerId, unk1, unk2); return; } } if (player->isDebugAreaTriggers) ChatHandler(player->GetSession()).PSendSysMessage(LANG_DEBUG_AREATRIGGER_REACHED, triggerId); if (sScriptMgr->OnAreaTrigger(player, atEntry)) return; if (player->IsAlive()) if (uint32 questId = sObjectMgr->GetQuestForAreaTrigger(triggerId)) if (player->GetQuestStatus(questId) == QUEST_STATUS_INCOMPLETE) player->AreaExploredOrEventHappens(questId); if (sObjectMgr->IsTavernAreaTrigger(triggerId)) { // set resting flag we are in the inn player->SetFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING); player->InnEnter(time(NULL), atEntry->mapid, atEntry->x, atEntry->y, atEntry->z); player->SetRestType(REST_TYPE_IN_TAVERN); if (sWorld->IsFFAPvPRealm()) player->RemoveByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP); return; } if (Battleground* bg = player->GetBattleground()) if (bg->GetStatus() == STATUS_IN_PROGRESS) { bg->HandleAreaTrigger(player, triggerId); return; } if (OutdoorPvP* pvp = player->GetOutdoorPvP()) if (pvp->HandleAreaTrigger(_player, triggerId)) return; AreaTriggerStruct const* at = sObjectMgr->GetAreaTrigger(triggerId); if (!at) return; bool teleported = false; if (player->GetMapId() != at->target_mapId) { if (!sMapMgr->CanPlayerEnter(at->target_mapId, player, false)) return; if (Group* group = player->GetGroup()) if (group->isLFGGroup() && player->GetMap()->IsInstance()) teleported = player->TeleportToBGEntryPoint(); } if (!teleported) player->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, at->target_Orientation, TELE_TO_NOT_LEAVE_TRANSPORT); } void WorldSession::HandleUpdateAccountData(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_UPDATE_ACCOUNT_DATA"); uint32 timestamp = 0, decompressedSize = 0, compCount = 0; uint8 type = 0; recvData >> decompressedSize >> timestamp >> compCount; if (decompressedSize == 0) // erase { SetAccountData(AccountDataType(type), 0, ""); WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA_COMPLETE, 4 + 4); type = recvData.ReadBits(3); data << uint32(type); data << uint32(0); SendPacket(&data); return; } if (decompressedSize > 0xFFFF) { recvData.rfinish(); // unneeded warning spam in this case SF_LOG_DEBUG("network", "UAD: Account data packet too big, size %u", decompressedSize); return; } ByteBuffer dest; dest.resize(decompressedSize); uLongf realSize = decompressedSize; if (uncompress(const_cast<uint8*>(dest.contents()), &realSize, const_cast<uint8*>(recvData.contents() + recvData.rpos()), compCount) != Z_OK) { recvData.rfinish(); // unneeded warning spam in this case SF_LOG_DEBUG("network", "UAD: Failed to decompress account data"); return; } recvData.rpos(recvData.rpos() + compCount); type = recvData.ReadBits(3); AccountDataType UADType = AccountDataType(type); if (UADType >= AccountDataType::NUM_ACCOUNT_DATA_TYPES) { SF_LOG_DEBUG("network", "UAD: Unknown account data type: %u", type); return; } std::string adata; dest >> adata; SetAccountData(UADType, timestamp, adata); WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA_COMPLETE, 4 + 4); data << uint32(UADType); data << uint32(0); SendPacket(&data); } void WorldSession::HandleRequestAccountData(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_REQUEST_ACCOUNT_DATA"); uint32 type = recvData.ReadBits(3); SF_LOG_DEBUG("network", "RAD: type %u", type); AccountDataType RADType = AccountDataType(type); if (RADType >= AccountDataType::NUM_ACCOUNT_DATA_TYPES) { SF_LOG_DEBUG("network", "RAD: Unknown account data type: %u", type); return; } AccountData* adata = GetAccountData(RADType); uint32 size = adata->Data.size(); uLongf destSize = compressBound(size); ByteBuffer dest; dest.resize(destSize); if (size && compress(dest.contents(), &destSize, (uint8 const*)adata->Data.c_str(), size) != Z_OK) { SF_LOG_DEBUG("network", "RAD: Failed to compress account data"); return; } dest.resize(destSize); WorldPacket data(SMSG_UPDATE_ACCOUNT_DATA, 8 + 4 + 4 + 4 + destSize); ObjectGuid guid; data.WriteBits(type, 3); // type (0-7) data.WriteBit(guid[5]); data.WriteBit(guid[1]); data.WriteBit(guid[3]); data.WriteBit(guid[7]); data.WriteBit(guid[0]); data.WriteBit(guid[4]); data.WriteBit(guid[2]); data.WriteBit(guid[6]); data.WriteByteSeq(guid[3]); data.WriteByteSeq(guid[1]); data.WriteByteSeq(guid[5]); data << uint32(size); // decompressed length data << uint32(destSize); data.append(dest); data.WriteByteSeq(guid[7]); data.WriteByteSeq(guid[4]); data.WriteByteSeq(guid[0]); data.WriteByteSeq(guid[6]); data.WriteByteSeq(guid[2]); data << uint32(adata->Time); // unix time SendPacket(&data); } int32 WorldSession::HandleEnableNagleAlgorithm() { // Instructs the server we wish to receive few amounts of large packets (SMSG_MULTIPLE_PACKETS?) // instead of large amount of small packets return 0; } void WorldSession::HandleSetActionButtonOpcode(WorldPacket& recvData) { ObjectGuid buttonStream; uint8 slotId; recvData >> slotId; recvData.ReadGuidMask(buttonStream, 7, 0, 5, 2, 1, 6, 3, 4); recvData.ReadGuidBytes(buttonStream, 6, 7, 3, 5, 2, 1, 4, 0); ActionButtonPACKET* button = reinterpret_cast<ActionButtonPACKET*>(&buttonStream); button->id = ACTION_BUTTON_ACTION(buttonStream); button->unk = ACTION_BUTTON_TYPE(buttonStream); SF_LOG_DEBUG("network", "CMSG_SET_ACTION_BUTTON slotId: %u actionId: %u buttontype: %u", slotId, button->id, button->unk); if (!button->id) GetPlayer()->removeActionButton(slotId); else GetPlayer()->addActionButton(slotId, button->id, ActionButtonType(button->unk)); } void WorldSession::HandleCompleteCinematic(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_COMPLETE_CINEMATIC"); // If player has sight bound to visual waypoint NPC we should remove it GetPlayer()->StopCinematic(); } void WorldSession::HandleNextCinematicCamera(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_NEXT_CINEMATIC_CAMERA"); } void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: Received CMSG_MOVE_TIME_SKIPPED"); ObjectGuid guid; uint32 time; recvData >> time; guid[5] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[4]); //TODO! /* GetPlayer()->ModifyLastMoveTime(-int32(time_skipped)); */ } void WorldSession::HandleFeatherFallAck(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_MOVE_FEATHER_FALL_ACK"); // no used recvData.rfinish(); // prevent warnings spam } void WorldSession::HandleMoveUnRootAck(WorldPacket& recvData) { // no used recvData.rfinish(); // prevent warnings spam /* uint64 guid; recvData >> guid; // now can skip not our packet if (_player->GetGUID() != guid) { recvData.rfinish(); // prevent warnings spam return; } SF_LOG_DEBUG("network", "WORLD: CMSG_FORCE_MOVE_UNROOT_ACK"); recvData.read_skip<uint32>(); // unk MovementInfo movementInfo; movementInfo.guid = guid; ReadMovementInfo(recvData, &movementInfo); recvData.read_skip<float>(); // unk2 */ } void WorldSession::HandleMoveRootAck(WorldPacket& recvData) { // no used recvData.rfinish(); // prevent warnings spam /* uint64 guid; recvData >> guid; // now can skip not our packet if (_player->GetGUID() != guid) { recvData.rfinish(); // prevent warnings spam return; } SF_LOG_DEBUG("network", "WORLD: CMSG_FORCE_MOVE_ROOT_ACK"); recvData.read_skip<uint32>(); // unk MovementInfo movementInfo; ReadMovementInfo(recvData, &movementInfo); */ } void WorldSession::HandleMoveGravityAck(WorldPacket& recvData) { // not used recvData.rfinish(); // prevent warnings spam } void WorldSession::HandleSetActionBarToggles(WorldPacket& recvData) { uint8 actionBar; recvData >> actionBar; if (!GetPlayer()) // ignore until not logged (check needed because STATUS_AUTHED) { if (actionBar != 0) SF_LOG_ERROR("network", "WorldSession::HandleSetActionBarToggles in not logged state with value: %u, ignored", uint32(actionBar)); return; } GetPlayer()->SetByteValue(PLAYER_FIELD_LIFETIME_MAX_RANK, 2, actionBar); } void WorldSession::HandlePlayedTime(WorldPacket& recvData) { uint8 unk1; recvData >> unk1; // 0 or 1 expected WorldPacket data(SMSG_PLAYED_TIME, 4 + 4 + 1); data << uint32(_player->GetTotalPlayedTime()); data << uint32(_player->GetLevelPlayedTime()); data << uint8(unk1); // 0 - will not show in chat frame SendPacket(&data); } void WorldSession::HandleInspectOpcode(WorldPacket& recvData) { ObjectGuid guid; guid[0] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[7]); SF_LOG_DEBUG("network", "WORLD: Received CMSG_INSPECT"); Player* player = ObjectAccessor::FindPlayer(guid); if (!player) { SF_LOG_DEBUG("network", "CMSG_INSPECT: No player found from GUID: " UI64FMTD, (uint64)guid); return; } _player->SendInspectResult(player); } void WorldSession::HandleInspectHonorStatsOpcode(WorldPacket& recvData) { ObjectGuid guid; recvData.ReadGuidMask(guid, 4, 3, 6, 1, 0, 2, 5, 7); recvData.ReadGuidBytes(guid, 0, 5, 1, 4, 2, 6, 7, 3); Player* player = ObjectAccessor::FindPlayer(guid); if (!player) { SF_LOG_DEBUG("network", "CMSG_INSPECT_HONOR_STATS: No player found from GUID: " UI64FMTD, (uint64)guid); return; } ObjectGuid playerGuid = player->GetGUID(); WorldPacket data(SMSG_INSPECT_HONOR_STATS, 8 + 1 + 4 + 4); data << uint32(player->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS)); data << uint16(player->GetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 1)); // yesterday kills data << uint16(player->GetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 0)); // today kills data << uint8(0); // rank data.WriteBit(playerGuid[2]); data.WriteBit(playerGuid[1]); data.WriteBit(playerGuid[6]); data.WriteBit(playerGuid[4]); data.WriteBit(playerGuid[5]); data.WriteBit(playerGuid[3]); data.WriteBit(playerGuid[7]); data.WriteBit(playerGuid[0]); data.WriteByteSeq(playerGuid[1]); data.WriteByteSeq(playerGuid[3]); data.WriteByteSeq(playerGuid[6]); data.WriteByteSeq(playerGuid[7]); data.WriteByteSeq(playerGuid[2]); data.WriteByteSeq(playerGuid[4]); data.WriteByteSeq(playerGuid[5]); data.WriteByteSeq(playerGuid[0]); SendPacket(&data); } void WorldSession::HandleWorldTeleportOpcode(WorldPacket& recvData) { uint32 time; uint32 mapid; float PositionX; float PositionY; float PositionZ; float Orientation; recvData >> time; // time in m.sec. recvData >> mapid; recvData >> PositionX; recvData >> PositionY; recvData >> PositionZ; recvData >> Orientation; // o (3.141593 = 180 degrees) SF_LOG_DEBUG("network", "WORLD: Received CMSG_WORLD_TELEPORT"); if (GetPlayer()->IsInFlight()) { SF_LOG_DEBUG("network", "Player '%s' (GUID: %u) in flight, ignore worldport command.", GetPlayer()->GetName().c_str(), GetPlayer()->GetGUIDLow()); return; } SF_LOG_DEBUG("network", "CMSG_WORLD_TELEPORT: Player = %s, Time = %u, map = %u, x = %f, y = %f, z = %f, o = %f", GetPlayer()->GetName().c_str(), time, mapid, PositionX, PositionY, PositionZ, Orientation); if (HasPermission(rbac::RBAC_PERM_OPCODE_WORLD_TELEPORT)) GetPlayer()->TeleportTo(mapid, PositionX, PositionY, PositionZ, Orientation); else SendNotification(LANG_YOU_NOT_HAVE_PERMISSION); } void WorldSession::HandleWhoisOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "Received opcode CMSG_WHOIS"); std::string charname; recvData >> charname; if (!HasPermission(rbac::RBAC_PERM_OPCODE_WHOIS)) { SendNotification(LANG_YOU_NOT_HAVE_PERMISSION); return; } if (charname.empty() || !normalizePlayerName(charname)) { SendNotification(LANG_NEED_CHARACTER_NAME); return; } Player* player = sObjectAccessor->FindPlayerByName(charname); if (!player) { SendNotification(LANG_PLAYER_NOT_EXIST_OR_OFFLINE, charname.c_str()); return; } uint32 accid = player->GetSession()->GetAccountId(); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_WHOIS); stmt->setUInt32(0, accid); PreparedQueryResult result = LoginDatabase.Query(stmt); if (!result) { SendNotification(LANG_ACCOUNT_FOR_PLAYER_NOT_FOUND, charname.c_str()); return; } Field* fields = result->Fetch(); std::string acc = fields[0].GetString(); if (acc.empty()) acc = "Unknown"; std::string email = fields[1].GetString(); if (email.empty()) email = "Unknown"; std::string lastip = fields[2].GetString(); if (lastip.empty()) lastip = "Unknown"; std::string msg = charname + "'s " + "account is " + acc + ", e-mail: " + email + ", last ip: " + lastip; WorldPacket data(SMSG_WHOIS, msg.size() + 1); data.WriteBits(msg.size(), 11); data.FlushBits(); if (msg.size()) data.WriteString(msg); SendPacket(&data); SF_LOG_DEBUG("network", "Received whois command from player %s for character %s", GetPlayer()->GetName().c_str(), charname.c_str()); } void WorldSession::HandleComplainOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_COMPLAIN"); uint8 spam_type; // 0 - mail, 1 - chat uint64 spammer_guid; uint32 unk1 = 0; uint32 unk2 = 0; uint32 unk3 = 0; uint32 unk4 = 0; std::string description = ""; recvData >> spam_type; // unk 0x01 const, may be spam type (mail/chat) recvData >> spammer_guid; // player guid switch (spam_type) { case 0: recvData >> unk1; // const 0 recvData >> unk2; // probably mail id recvData >> unk3; // const 0 break; case 1: recvData >> unk1; // probably language recvData >> unk2; // message type? recvData >> unk3; // probably channel id recvData >> unk4; // time recvData >> description; // spam description string (messagetype, channel name, player name, message) break; } // NOTE: all chat messages from this spammer automatically ignored by spam reporter until logout in case chat spam. // if it's mail spam - ALL mails from this spammer automatically removed by client // Complaint Received message WorldPacket data(SMSG_COMPLAIN_RESULT, 2); data << uint8(0); // value 1 resets CGChat::m_complaintsSystemStatus in client. (unused?) data << uint8(0); // value 0xC generates a "CalendarError" in client. SendPacket(&data); SF_LOG_DEBUG("network", "REPORT SPAM: type %u, guid %u, unk1 %u, unk2 %u, unk3 %u, unk4 %u, message %s", spam_type, GUID_LOPART(spammer_guid), unk1, unk2, unk3, unk4, description.c_str()); } void WorldSession::HandleRealmSplitOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "CMSG_REALM_SPLIT"); uint32 unk; std::string split_date = "01/01/01"; recvData >> unk; WorldPacket data(SMSG_REALM_SPLIT, 4 + 4 + split_date.size() + 1); data << unk; data << uint32(0x00000000); // realm split state // split states: // 0x0 realm normal // 0x1 realm split // 0x2 realm split pending data.WriteBits(split_date.size(), 7); data.WriteString(split_date); SendPacket(&data); //SF_LOG_DEBUG("response sent %u", unk); } void WorldSession::HandleFarSightOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_FAR_SIGHT"); bool apply = recvData.ReadBit(); if (apply) { SF_LOG_DEBUG("network", "Added FarSight " UI64FMTD " to player %u", _player->GetUInt64Value(PLAYER_FIELD_FARSIGHT_OBJECT), _player->GetGUIDLow()); if (WorldObject* target = _player->GetViewpoint()) _player->SetSeer(target); else SF_LOG_ERROR("network", "Player %s (GUID: %u) requests non-existing seer " UI64FMTD, _player->GetName().c_str(), GUID_LOPART(_player->GetGUID()), _player->GetUInt64Value(PLAYER_FIELD_FARSIGHT_OBJECT)); } else { SF_LOG_DEBUG("network", "Player %u set vision to self", _player->GetGUIDLow()); _player->SetSeer(_player); } GetPlayer()->UpdateVisibilityForPlayer(); } void WorldSession::HandleSetTitleOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "CMSG_SET_TITLE"); int32 title; recvData >> title; // -1 at none if (title > 0 && title < MAX_TITLE_INDEX) { if (!GetPlayer()->HasTitle(title)) return; } else title = 0; GetPlayer()->SetUInt32Value(PLAYER_FIELD_PLAYER_TITLE, title); } void WorldSession::SendTitleEarned(uint32 TitleIndex) { WorldPacket data(SMSG_TITLE_EARNED, 4); data << uint32(TitleIndex); SendPacket(&data); } void WorldSession::SendTitleLost(uint32 TitleIndex) { WorldPacket data(SMSG_TITLE_LOST, 4); data << uint32(TitleIndex); SendPacket(&data); } void WorldSession::HandleTimeSyncResp(WorldPacket& recvData) { SF_LOG_DEBUG("network", "CMSG_TIME_SYNC_RESPONSE"); uint32 counter, clientTicks; recvData >> counter >> clientTicks; if (counter != _player->m_timeSyncQueue.front()) SF_LOG_ERROR("network", "Wrong time sync counter from player %s (cheater?)", _player->GetName().c_str()); SF_LOG_DEBUG("network", "Time sync received: counter %u, client ticks %u, time since last sync %u", counter, clientTicks, clientTicks - _player->m_timeSyncClient); uint32 ourTicks = clientTicks + (getMSTime() - _player->m_timeSyncServer); // diff should be small SF_LOG_DEBUG("network", "Our ticks: %u, diff %u, latency %u", ourTicks, ourTicks - clientTicks, GetLatency()); _player->m_timeSyncClient = clientTicks; _player->m_timeSyncQueue.pop(); } void WorldSession::HandleResetInstancesOpcode(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: CMSG_RESET_INSTANCES"); if (Group* group = _player->GetGroup()) { if (group->IsLeader(_player->GetGUID())) group->ResetInstances(InstanceResetMethod::INSTANCE_RESET_ALL, false, _player); } else _player->ResetInstances(InstanceResetMethod::INSTANCE_RESET_ALL, false); } void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "Received: CMSG_SET_DUNGEON_DIFFICULTY"); uint32 Difficulty; recvData >> Difficulty; DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(Difficulty); if (!difficultyEntry) { SF_LOG_DEBUG("network", "%d sent an invalid instance mode %u!", _player->GetGUIDLow(), Difficulty); return; } if (difficultyEntry->maptype != MAP_DUNGEON) { SF_LOG_DEBUG("network", "%d sent an non-dungeon instance mode %d!", _player->GetGUIDLow(), difficultyEntry->DiffID); return; } DifficultyID difficulty = DifficultyID(difficultyEntry->DiffID); if (difficulty == _player->GetDungeonDifficulty()) return; // cannot reset while in an instance Map* map = _player->FindMap(); if (map && map->IsNonRaidInstance()) { SF_LOG_DEBUG("network", "player (Name: %s, GUID: %u) tried to reset the instance while player is inside!", _player->GetName().c_str(), _player->GetGUIDLow()); return; } Group* group = _player->GetGroup(); if (group) { if (group->IsLeader(_player->GetGUID())) { for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* groupGuy = itr->GetSource(); if (!groupGuy) continue; if (!groupGuy->IsInMap(groupGuy)) return; if (groupGuy->GetMap()->IsNonRaidInstance()) { SF_LOG_DEBUG("network", "player %d tried to reset the instance while group member (Name: %s, GUID: %u) is inside!", _player->GetGUIDLow(), groupGuy->GetName().c_str(), groupGuy->GetGUIDLow()); return; } } // the difficulty is set even if the instances can't be reset //_player->SendDungeonDifficulty(true); group->ResetInstances(InstanceResetMethod::INSTANCE_RESET_CHANGE_DIFFICULTY, false, _player); group->SetDungeonDifficulty(DifficultyID(difficulty)); } } else { _player->ResetInstances(InstanceResetMethod::INSTANCE_RESET_CHANGE_DIFFICULTY, false); _player->SetDungeonDifficulty(DifficultyID(difficulty)); _player->SendDungeonDifficulty(); } } void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "Received: CMSG_SET_RAID_DIFFICULTY"); uint32 Difficulty; recvData >> Difficulty; DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(Difficulty); if (!difficultyEntry) { SF_LOG_DEBUG("network", "%d sent an invalid instance mode %u!", _player->GetGUIDLow(), Difficulty); return; } if (difficultyEntry->maptype != MAP_RAID) { SF_LOG_DEBUG("network", "%d sent an non-raid instance mode %u!", _player->GetGUIDLow(), difficultyEntry->DiffID); return; } DifficultyID difficulty = DifficultyID(difficultyEntry->DiffID); if (difficulty == _player->GetRaidDifficulty()) return; // cannot reset while in an instance Map* map = _player->FindMap(); if (map && map->IsRaid()) { SF_LOG_DEBUG("network", "player %d tried to reset the raid while inside!", _player->GetGUIDLow()); return; } Group* group = _player->GetGroup(); if (group) { if (group->IsLeader(_player->GetGUID())) { for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* groupGuy = itr->GetSource(); if (!groupGuy) continue; if (!groupGuy->IsInMap(groupGuy)) return; if (groupGuy->GetMap()->IsRaid()) { SF_LOG_DEBUG("network", "player %d tried to reset the raid while inside!", _player->GetGUIDLow()); return; } } // the difficulty is set even if the instances can't be reset //_player->SendDungeonDifficulty(true); group->ResetInstances(InstanceResetMethod::INSTANCE_RESET_CHANGE_DIFFICULTY, true, _player); group->SetRaidDifficulty(DifficultyID(difficulty)); } } else { _player->ResetInstances(InstanceResetMethod::INSTANCE_RESET_CHANGE_DIFFICULTY, true); _player->SetRaidDifficulty(DifficultyID(difficulty)); _player->SendRaidDifficulty(); } } void WorldSession::HandleCancelMountAuraOpcode(WorldPacket& /*recvData*/) { SF_LOG_DEBUG("network", "WORLD: CMSG_CANCEL_MOUNT_AURA"); //If player is not mounted, so go out :) if (!_player->IsMounted()) // not blizz like; no any messages on blizz { ChatHandler(this).SendSysMessage(LANG_CHAR_NON_MOUNTED); return; } if (_player->IsInFlight()) // not blizz like; no any messages on blizz { ChatHandler(this).SendSysMessage(LANG_YOU_IN_FLIGHT); return; } _player->RemoveAurasByType(SPELL_AURA_MOUNTED); // Calls Dismount() } void WorldSession::HandleRequestPetInfoOpcode(WorldPacket& /*recvData */) { if (_player->GetVehicle()) _player->VehicleSpellInitialize(); else if (Unit* minion = _player->GetFirstControlled()) { if (minion->IsPet()) _player->PetSpellInitialize(); else if (minion->HasUnitTypeMask(UNIT_MASK_CONTROLABLE_GUARDIAN)) _player->CharmSpellInitialize(); } } void WorldSession::HandleSetTaxiBenchmarkOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_SET_TAXI_BENCHMARK_MODE"); uint8 mode; recvData >> mode; mode ? _player->SetFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_TAXI_BENCHMARK) : _player->RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_TAXI_BENCHMARK); SF_LOG_DEBUG("network", "Client used \"/timetest %d\" command", mode); } void WorldSession::HandleQueryInspectAchievements(WorldPacket& recvData) { ObjectGuid guid; guid[2] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[5] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[5]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[3]); Player* player = ObjectAccessor::FindPlayer(guid); if (!player) { SF_LOG_DEBUG("network", "CMSG_QUERY_INSPECT_ACHIEVEMENTS: Inspected Player " UI64FMTD, (uint64)guid); return; } player->SendRespondInspectAchievements(_player); } void WorldSession::HandleGuildAchievementProgressQuery(WorldPacket& recvData) { uint32 achievementId; recvData >> achievementId; if (Guild* guild = sGuildMgr->GetGuildById(_player->GetGuildId())) guild->GetAchievementMgr().SendAchievementInfo(_player, achievementId); } void WorldSession::HandleWorldStateUITimerUpdate(WorldPacket& /*recvData*/) { // empty opcode SF_LOG_DEBUG("network", "WORLD: CMSG_WORLD_STATE_UI_TIMER_UPDATE"); WorldPacket data(SMSG_UI_TIME, 4); data << uint32(time(NULL)); SendPacket(&data); } void WorldSession::HandleReadyForAccountDataTimes(WorldPacket& /*recvData*/) { // empty opcode SF_LOG_DEBUG("network", "WORLD: CMSG_READY_FOR_ACCOUNT_DATA_TIMES"); SendAccountDataTimes(GLOBAL_CACHE_MASK); } void WorldSession::SendSetPhaseShift(std::set<uint32> const& phaseIds, std::set<uint32> const& terrainswaps, std::set<uint32> const& worldMapAreas) { ObjectGuid guid = _player->GetGUID(); WorldPacket data(SMSG_PHASE_SHIFT_CHANGE, 1 + 8 + 2 * phaseIds.size() + 4 + 2 * worldMapAreas.size() + 2 * terrainswaps.size() + 4); data.WriteBit(guid[0]); data.WriteBit(guid[3]); data.WriteBit(guid[1]); data.WriteBit(guid[4]); data.WriteBit(guid[6]); data.WriteBit(guid[2]); data.WriteBit(guid[7]); data.WriteBit(guid[5]); data.WriteByteSeq(guid[4]); data.WriteByteSeq(guid[3]); data.WriteByteSeq(guid[2]); data << uint32(phaseIds.size()) * 2; // Phase.dbc ids for (std::set<uint32>::const_iterator itr = phaseIds.begin(); itr != phaseIds.end(); ++itr) data << uint16(*itr); data.WriteByteSeq(guid[0]); data.WriteByteSeq(guid[6]); data << uint32(0); // Inactive terrain swaps //for (uint8 i = 0; i < inactiveSwapsCount; ++i) // data << uint16(0); data.WriteByteSeq(guid[1]); data.WriteByteSeq(guid[7]); data << uint32(worldMapAreas.size()) * 2; // WorldMapArea.dbc id (controls map display) for (std::set<uint32>::const_iterator itr = worldMapAreas.begin(); itr != worldMapAreas.end(); ++itr) data << uint16(*itr); data << uint32(terrainswaps.size()) * 2; // Active terrain swaps for (std::set<uint32>::const_iterator itr = terrainswaps.begin(); itr != terrainswaps.end(); ++itr) data << uint16(*itr); data.WriteByteSeq(guid[5]); data << uint32(phaseIds.size() ? 0 : 8); // flags (not phasemask) SendPacket(&data); } // Battlefield and Battleground void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_AREA_SPIRIT_HEALER_QUERY"); Battleground* bg = _player->GetBattleground(); ObjectGuid guid; recvData.ReadGuidMask(guid, 5, 6, 0, 4, 1, 2, 7, 3); recvData.ReadGuidBytes(guid, 0, 2, 6, 7, 1, 5, 3, 4); Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); if (!unit) return; if (!unit->IsSpiritService()) // it's not spirit service return; if (bg) sBattlegroundMgr->SendAreaSpiritHealerQueryOpcode(_player, bg, guid); if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(_player->GetZoneId())) bf->SendAreaSpiritHealerQueryOpcode(_player, guid); } void WorldSession::HandleAreaSpiritHealerQueueOpcode(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_AREA_SPIRIT_HEALER_QUEUE"); ObjectGuid guid; Battleground* bg = _player->GetBattleground(); guid[5] = recvData.ReadBit(); guid[4] = recvData.ReadBit(); guid[0] = recvData.ReadBit(); guid[2] = recvData.ReadBit(); guid[7] = recvData.ReadBit(); guid[1] = recvData.ReadBit(); guid[6] = recvData.ReadBit(); guid[3] = recvData.ReadBit(); recvData.ReadByteSeq(guid[1]); recvData.ReadByteSeq(guid[7]); recvData.ReadByteSeq(guid[6]); recvData.ReadByteSeq(guid[2]); recvData.ReadByteSeq(guid[4]); recvData.ReadByteSeq(guid[3]); recvData.ReadByteSeq(guid[0]); recvData.ReadByteSeq(guid[5]); Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); if (!unit) return; if (!unit->IsSpiritService()) // it's not spirit service return; if (bg) bg->AddPlayerToResurrectQueue(guid, _player->GetGUID()); if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(_player->GetZoneId())) bf->AddPlayerToResurrectQueue(guid, _player->GetGUID()); } void WorldSession::HandleHearthAndResurrect(WorldPacket& /*recvData*/) { if (_player->IsInFlight()) return; if (/*Battlefield* bf = */sBattlefieldMgr->GetBattlefieldToZoneId(_player->GetZoneId())) { // bf->PlayerAskToLeave(_player); FIXME return; } AreaTableEntry const* atEntry = sAreaStore.LookupEntry(_player->GetAreaId()); if (!atEntry || !(atEntry->m_flags & AREA_FLAG_WINTERGRASP_2)) return; _player->BuildPlayerRepop(); _player->ResurrectPlayer(100); _player->TeleportTo(_player->m_homebindMapId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ, _player->GetOrientation()); } void WorldSession::HandleInstanceLockResponse(WorldPacket& recvPacket) { bool AcceptLock = recvPacket.ReadBit(); if (!_player->HasPendingBind()) { SF_LOG_INFO("network", "InstanceLockResponse: Player %s (guid %u) tried to bind himself/teleport to graveyard without a pending bind!", _player->GetName().c_str(), _player->GetGUIDLow()); return; } if (AcceptLock) _player->BindToInstance(); else _player->RepopAtGraveyard(); _player->SetPendingBind(0, 0); } void WorldSession::HandleRequestHotfix(WorldPacket& recvPacket) { uint32 type, count; recvPacket >> type; DB2StorageBase const* store = GetDB2Storage(type); if (!store) { SF_LOG_ERROR("network", "CMSG_REQUEST_HOTFIX: Received unknown hotfix type: %u", type); recvPacket.rfinish(); return; } count = recvPacket.ReadBits(21); ObjectGuid* guids = new ObjectGuid[count]; for (uint32 i = 0; i < count; ++i) { recvPacket.ReadGuidMask(guids[i], 6, 3, 0, 1, 4, 5, 7, 2); } uint32 entry; for (uint32 i = 0; i < count; ++i) { recvPacket.ReadByteSeq(guids[i][1]); recvPacket >> entry; recvPacket.ReadGuidBytes(guids[i], 0, 5, 6, 4, 7, 2, 3); // temp: this should be moved once broadcast text is properly implemented if (type == DB2_REPLY_BROADCASTTEXT) { SendBroadcastText(entry); continue; } if (!store->HasRecord(entry)) continue; ByteBuffer record; store->WriteRecord(entry, (uint32)GetSessionDbcLocale(), record); WorldPacket data(SMSG_DB_REPLY); data << uint32(entry); data << uint32(time(NULL)); data << uint32(type); data << uint32(record.size()); data.append(record); SendPacket(&data); SF_LOG_DEBUG("network", "SMSG_DB_REPLY: Sent hotfix entry: %u type: %u", entry, type); } delete[] guids; } void WorldSession::SendBroadcastText(uint32 entry) { /* * This is a hack fix! Still uses Gossip Id's instead of Broadcast Id's. * Major database changed required at some point. */ ByteBuffer buffer; std::string defaultText = "Greetings, $n"; GossipText const* pGossip = sObjectMgr->GetGossipText(entry); uint16 nrmTextLength = pGossip ? pGossip->Options[0].Text_0.length() : defaultText.length(); uint16 altTextLength = pGossip ? pGossip->Options[0].Text_1.length() : defaultText.length(); buffer << uint32(entry); buffer << uint32(pGossip ? pGossip->Options[0].Language : 0); buffer << uint16(nrmTextLength); if (nrmTextLength) buffer << std::string(pGossip ? pGossip->Options[0].Text_0 : defaultText); buffer << uint16(altTextLength); if (altTextLength) buffer << std::string(pGossip ? pGossip->Options[0].Text_1 : defaultText); for (int i = 0; i < MAX_GOSSIP_TEXT_OPTIONS; i++) buffer << uint32(0); buffer << uint32(1); WorldPacket data(SMSG_DB_REPLY); data << uint32(entry); data << uint32(time(NULL)); data << uint32(DB2_REPLY_BROADCASTTEXT); data << uint32(buffer.size()); data.append(buffer); SendPacket(&data); } void WorldSession::HandleUpdateMissileTrajectory(WorldPacket& recvPacket) { SF_LOG_DEBUG("network", "WORLD: CMSG_UPDATE_MISSILE_TRAJECTORY"); uint64 guid; uint32 spellId; float elevation, speed; float curX, curY, curZ; float targetX, targetY, targetZ; uint8 moveStop; recvPacket >> guid >> spellId >> elevation >> speed; recvPacket >> curX >> curY >> curZ; recvPacket >> targetX >> targetY >> targetZ; recvPacket >> moveStop; Unit* caster = ObjectAccessor::GetUnit(*_player, guid); Spell* spell = caster ? caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) : NULL; if (!spell || spell->m_spellInfo->Id != spellId || !spell->m_targets.HasDst() || !spell->m_targets.HasSrc()) { recvPacket.rfinish(); return; } Position pos = *spell->m_targets.GetSrcPos(); pos.Relocate(curX, curY, curZ); spell->m_targets.ModSrc(pos); pos = *spell->m_targets.GetDstPos(); pos.Relocate(targetX, targetY, targetZ); spell->m_targets.ModDst(pos); spell->m_targets.SetElevation(elevation); spell->m_targets.SetSpeed(speed); if (moveStop) { uint32 opcode; recvPacket >> opcode; recvPacket.SetOpcode(MSG_MOVE_STOP); // always set to MSG_MOVE_STOP in client SetOpcode HandleMovementOpcodes(recvPacket); } } void WorldSession::HandleViolenceLevel(WorldPacket& recvPacket) { uint8 violenceLevel; recvPacket >> violenceLevel; // do something? } void WorldSession::HandleObjectUpdateFailedOpcode(WorldPacket& recvPacket) { ObjectGuid guid; guid[3] = recvPacket.ReadBit(); guid[5] = recvPacket.ReadBit(); guid[6] = recvPacket.ReadBit(); guid[0] = recvPacket.ReadBit(); guid[1] = recvPacket.ReadBit(); guid[2] = recvPacket.ReadBit(); guid[7] = recvPacket.ReadBit(); guid[4] = recvPacket.ReadBit(); recvPacket.ReadByteSeq(guid[0]); recvPacket.ReadByteSeq(guid[6]); recvPacket.ReadByteSeq(guid[5]); recvPacket.ReadByteSeq(guid[7]); recvPacket.ReadByteSeq(guid[2]); recvPacket.ReadByteSeq(guid[1]); recvPacket.ReadByteSeq(guid[3]); recvPacket.ReadByteSeq(guid[4]); WorldObject* obj = ObjectAccessor::GetWorldObject(*GetPlayer(), guid); SF_LOG_ERROR("network", "Object update failed for object " UI64FMTD " (%s) for player %s (%u)", uint64(guid), obj ? obj->GetName().c_str() : "object-not-found", GetPlayerName().c_str(), GetGuidLow()); // If create object failed for current player then client will be stuck on loading screen //if (_player->GetGUID() == guid) //{ // LogoutPlayer(true); // return; //} // Pretend we've never seen this object //_player->m_clientGUIDs.erase(guid); } void WorldSession::HandleSaveCUFProfiles(WorldPacket& recvPacket) { SF_LOG_DEBUG("network", "WORLD: CMSG_SAVE_CUF_PROFILES"); uint8 count = (uint8)recvPacket.ReadBits(19); if (count > MAX_CUF_PROFILES) { SF_LOG_ERROR("entities.player", "HandleSaveCUFProfiles - %s tried to save more than %i CUF profiles. Hacking attempt?", GetPlayerName().c_str(), MAX_CUF_PROFILES); recvPacket.rfinish(); return; } CUFProfile* profiles[MAX_CUF_PROFILES]; uint8 strlens[MAX_CUF_PROFILES]; for (uint8 i = 0; i < count; ++i) { profiles[i] = new CUFProfile; profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_SPEC_2, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_MAIN_TANK_AND_ASSIST, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_POWER_BAR, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_10_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_3_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_UNK_156, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_40_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_2_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_KEEP_GROUPS_TOGETHER, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_USE_CLASS_COLORS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_25_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_UNK_145, recvPacket.ReadBit()); strlens[i] = (uint8)recvPacket.ReadBits(7); profiles[i]->BoolOptions.set(CUF_DISPLAY_PETS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_PVP, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_ONLY_DISPELLABLE_DEBUFFS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_NON_BOSS_DEBUFFS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_15_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_UNK_157, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_BORDER, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_HORIZONTAL_GROUPS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_SPEC_1, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_5_PLAYERS, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_PVE, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_HEAL_PREDICTION, recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_DISPLAY_AGGRO_HIGHLIGHT, recvPacket.ReadBit()); } for (uint8 i = 0; i < count; ++i) { recvPacket >> profiles[i]->FrameHeight; recvPacket >> profiles[i]->Unk146; recvPacket >> profiles[i]->HealthText; recvPacket >> profiles[i]->FrameWidth; recvPacket >> profiles[i]->Unk148; recvPacket >> profiles[i]->SortBy; recvPacket >> profiles[i]->Unk150; profiles[i]->ProfileName = recvPacket.ReadString(strlens[i]); recvPacket >> profiles[i]->Unk147; recvPacket >> profiles[i]->Unk152; recvPacket >> profiles[i]->Unk154; GetPlayer()->SaveCUFProfile(i, profiles[i]); } for (uint8 i = count; i < MAX_CUF_PROFILES; ++i) GetPlayer()->SaveCUFProfile(i, NULL); } void WorldSession::SendLoadCUFProfiles() { Player* player = GetPlayer(); uint8 count = player->GetCUFProfilesCount(); ByteBuffer byteBuffer(25 * count); WorldPacket data(SMSG_LOAD_CUF_PROFILES, 5 * count + 25 * count); data.WriteBits(count, 20); for (uint8 i = 0; i < MAX_CUF_PROFILES; ++i) { CUFProfile* profile = player->GetCUFProfile(i); if (!profile) continue; data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_SPEC_1]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_3_PLAYERS]); data.WriteBit(profile->BoolOptions[CUF_UNK_157]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_10_PLAYERS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_40_PLAYERS]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_BORDER]); data.WriteBit(profile->BoolOptions[CUF_USE_CLASS_COLORS]); data.WriteBit(profile->BoolOptions[CUF_KEEP_GROUPS_TOGETHER]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_POWER_BAR]); data.WriteBits(profile->ProfileName.size(), 8); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_PETS]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_AGGRO_HIGHLIGHT]); data.WriteBit(profile->BoolOptions[CUF_UNK_145]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_PVP]); data.WriteBit(profile->BoolOptions[CUF_UNK_156]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_MAIN_TANK_AND_ASSIST]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_NON_BOSS_DEBUFFS]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_HORIZONTAL_GROUPS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_SPEC_2]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_HEAL_PREDICTION]); data.WriteBit(profile->BoolOptions[CUF_DISPLAY_ONLY_DISPELLABLE_DEBUFFS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_25_PLAYERS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_PVE]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_5_PLAYERS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_15_PLAYERS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_2_PLAYERS]); byteBuffer << uint16(profile->Unk152); byteBuffer << uint16(profile->Unk154); byteBuffer << uint8(profile->HealthText); byteBuffer.WriteString(profile->ProfileName); byteBuffer << uint8(profile->Unk147); byteBuffer << uint8(profile->Unk146); byteBuffer << uint16(profile->FrameHeight); byteBuffer << uint8(profile->Unk148); byteBuffer << uint8(profile->SortBy); byteBuffer << uint16(profile->FrameWidth); byteBuffer << uint16(profile->Unk150); } data.FlushBits(); data.append(byteBuffer); SendPacket(&data); } #define JOIN_THE_ALLIANCE 1 #define JOIN_THE_HORDE 0 void WorldSession::HandleSelectFactionOpcode(WorldPacket& recvPacket) { uint32 choice = recvPacket.read<uint32>(); if (_player->getRace() != RACE_PANDAREN_NEUTRAL) return; if (choice == JOIN_THE_HORDE) { _player->SetByteValue(UNIT_FIELD_SEX, 0, RACE_PANDAREN_HORDE); _player->setFactionForRace(RACE_PANDAREN_HORDE); _player->SaveToDB(); WorldLocation location(1, 1357.62f, -4373.55f, 26.13f, 0.13f); _player->TeleportTo(location); _player->SetHomebind(location, 363); _player->learnSpell(669, false); // Language Orcish _player->learnSpell(108127, false); // Language Pandaren } else if (choice == JOIN_THE_ALLIANCE) { _player->SetByteValue(UNIT_FIELD_SEX, 0, RACE_PANDAREN_ALLIANCE); _player->setFactionForRace(RACE_PANDAREN_ALLIANCE); _player->SaveToDB(); WorldLocation location(0, -8960.02f, 516.10f, 96.36f, 0.67f); _player->TeleportTo(location); _player->SetHomebind(location, 9); _player->learnSpell(668, false); // Language Common _player->learnSpell(108127, false); // Language Pandaren } if (_player->GetQuestStatus(31450) == QUEST_STATUS_INCOMPLETE) _player->KilledMonsterCredit(64594); _player->SendMovieStart(116); } void WorldSession::HandleDiscardedTimeSyncAcks(WorldPacket& recvData) { SF_LOG_DEBUG("network", "WORLD: CMSG_DISCARDED_TIME_SYNC_ACKS"); bool hasInfo = !recvData.ReadBit(); if (hasInfo) recvData.read_skip<uint32>(); } void WorldSession::SendPlayMusic(uint32 SoundKitID) { WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(SoundKitID); SendPacket(&data); } void WorldSession::SendPageText(ObjectGuid GameObjectGUID) { WorldPacket data(SMSG_PAGETEXT, 8); data.WriteGuidMask(GameObjectGUID, 0, 3, 2, 6, 5, 1, 7, 4); data.WriteGuidBytes(GameObjectGUID, 6, 2, 7, 0, 5, 3, 1, 4); _player->SendDirectMessage(&data); } void WorldSession::HandleSceneCompleted(WorldPacket& recvPacket) { SF_LOG_ERROR("network", "recv CMSG_SCENE_COMPLETED"); uint32 unk = 0; uint8 unkbit = 0; unkbit = recvPacket.ReadBit(); if (unkbit) unk = recvPacket.read<uint32>(); SF_LOG_ERROR("network", "hasData %u", unkbit); } void WorldSession::SendCrossedInebriationThreshold(ObjectGuid guid, uint32 ItemID, DrunkenState drunkenState) { WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8 + 4 + 4)); data.WriteGuidMask(guid, 0, 4, 2, 6, 5, 1, 3, 7); data.WriteGuidBytes(guid, 3); data << ItemID; data << uint32(drunkenState); data.WriteGuidBytes(guid, 4, 6, 7, 0, 2, 5, 1); _player->SendMessageToSet(&data, true); }
412
0.96401
1
0.96401
game-dev
MEDIA
0.668556
game-dev
0.974579
1
0.974579
bepu/bepuphysics1
12,024
BEPUik/IKJoint.cs
using System; using BEPUutilities; namespace BEPUik { /// <summary> /// Connects two bones together. /// </summary> public abstract class IKJoint : IKConstraint { /// <summary> /// Gets the first bone connected by this joint. /// </summary> public Bone ConnectionA { get; private set; } /// <summary> /// Gets the second bone connected by this joint. /// </summary> public Bone ConnectionB { get; private set; } /// <summary> /// Gets whether or not the joint is a member of the active set as determined by the last IK solver execution. /// </summary> public bool IsActive { get; internal set; } bool enabled; /// <summary> /// Gets or sets whether or not this joint is enabled. If set to true, this joint will be a part of /// the joint graph and will undergo solving. If set to false, this joint will be removed from the connected bones and will no longer be traversable. /// </summary> public bool Enabled { get { return enabled; } set { //The bones must know which joints they are associated with so that the bone-joint graph can be traversed. if (enabled && !value) { ConnectionA.joints.Remove(this); ConnectionB.joints.Remove(this); } else if (!enabled && value) { ConnectionA.joints.Add(this); ConnectionB.joints.Add(this); } enabled = value; } } protected IKJoint(Bone connectionA, Bone connectionB) { ConnectionA = connectionA; ConnectionB = connectionB; Enabled = true; } internal Vector3 velocityBias; internal Matrix3x3 linearJacobianA; internal Matrix3x3 angularJacobianA; internal Matrix3x3 linearJacobianB; internal Matrix3x3 angularJacobianB; internal Matrix3x3 effectiveMass; internal Vector3 accumulatedImpulse; protected internal override void ComputeEffectiveMass() { //For all constraints, the effective mass matrix is 1 / (J * M^-1 * JT). //For two bone constraints, J has 4 3x3 matrices. M^-1 (W below) is a 12x12 matrix with 4 3x3 block diagonal matrices. //To compute the whole denominator, Matrix3x3 linearW; Matrix3x3 linearA, angularA, linearB, angularB; if (!ConnectionA.Pinned) { Matrix3x3.CreateScale(ConnectionA.inverseMass, out linearW); Matrix3x3.Multiply(ref linearJacobianA, ref linearW, out linearA); //Compute J * M^-1 for linear component Matrix3x3.MultiplyByTransposed(ref linearA, ref linearJacobianA, out linearA); //Compute (J * M^-1) * JT for linear component Matrix3x3.Multiply(ref angularJacobianA, ref ConnectionA.inertiaTensorInverse, out angularA); //Compute J * M^-1 for angular component Matrix3x3.MultiplyByTransposed(ref angularA, ref angularJacobianA, out angularA); //Compute (J * M^-1) * JT for angular component } else { //Treat pinned bones as if they have infinite inertia. linearA = new Matrix3x3(); angularA = new Matrix3x3(); } if (!ConnectionB.Pinned) { Matrix3x3.CreateScale(ConnectionB.inverseMass, out linearW); Matrix3x3.Multiply(ref linearJacobianB, ref linearW, out linearB); //Compute J * M^-1 for linear component Matrix3x3.MultiplyByTransposed(ref linearB, ref linearJacobianB, out linearB); //Compute (J * M^-1) * JT for linear component Matrix3x3.Multiply(ref angularJacobianB, ref ConnectionB.inertiaTensorInverse, out angularB); //Compute J * M^-1 for angular component Matrix3x3.MultiplyByTransposed(ref angularB, ref angularJacobianB, out angularB); //Compute (J * M^-1) * JT for angular component } else { //Treat pinned bones as if they have infinite inertia. linearB = new Matrix3x3(); angularB = new Matrix3x3(); } //A nice side effect of the block diagonal nature of M^-1 is that the above separated components are now combined into the complete denominator matrix by addition! Matrix3x3.Add(ref linearA, ref angularA, out effectiveMass); Matrix3x3.Add(ref effectiveMass, ref linearB, out effectiveMass); Matrix3x3.Add(ref effectiveMass, ref angularB, out effectiveMass); //Incorporate the constraint softness into the effective mass denominator. This pushes the matrix away from singularity. //Softness will also be incorporated into the velocity solve iterations to complete the implementation. if (effectiveMass.M11 != 0) effectiveMass.M11 += softness; if (effectiveMass.M22 != 0) effectiveMass.M22 += softness; if (effectiveMass.M33 != 0) effectiveMass.M33 += softness; //Invert! Takes us from J * M^-1 * JT to 1 / (J * M^-1 * JT). Matrix3x3.AdaptiveInvert(ref effectiveMass, out effectiveMass); } protected internal override void WarmStart() { //Take the accumulated impulse and transform it into world space impulses using the jacobians by P = JT * lambda //(where P is the impulse, JT is the transposed jacobian matrix, and lambda is the accumulated impulse). //Recall the jacobian takes impulses from world space into constraint space, and transpose takes them from constraint space into world space. Vector3 impulse; if (!ConnectionA.Pinned) //Treat pinned elements as if they have infinite inertia. { //Compute and apply linear impulse for A. Matrix3x3.Transform(ref accumulatedImpulse, ref linearJacobianA, out impulse); ConnectionA.ApplyLinearImpulse(ref impulse); //Compute and apply angular impulse for A. Matrix3x3.Transform(ref accumulatedImpulse, ref angularJacobianA, out impulse); ConnectionA.ApplyAngularImpulse(ref impulse); } if (!ConnectionB.Pinned) //Treat pinned elements as if they have infinite inertia. { //Compute and apply linear impulse for B. Matrix3x3.Transform(ref accumulatedImpulse, ref linearJacobianB, out impulse); ConnectionB.ApplyLinearImpulse(ref impulse); //Compute and apply angular impulse for B. Matrix3x3.Transform(ref accumulatedImpulse, ref angularJacobianB, out impulse); ConnectionB.ApplyAngularImpulse(ref impulse); } } protected internal override void SolveVelocityIteration() { //Compute the 'relative' linear and angular velocities. For single bone constraints, it's based entirely on the one bone's velocities! //They have to be pulled into constraint space first to compute the necessary impulse, though. Vector3 linearContributionA; Matrix3x3.TransformTranspose(ref ConnectionA.linearVelocity, ref linearJacobianA, out linearContributionA); Vector3 angularContributionA; Matrix3x3.TransformTranspose(ref ConnectionA.angularVelocity, ref angularJacobianA, out angularContributionA); Vector3 linearContributionB; Matrix3x3.TransformTranspose(ref ConnectionB.linearVelocity, ref linearJacobianB, out linearContributionB); Vector3 angularContributionB; Matrix3x3.TransformTranspose(ref ConnectionB.angularVelocity, ref angularJacobianB, out angularContributionB); //The constraint velocity error will be the velocity we try to remove. Vector3 constraintVelocityError; Vector3.Add(ref linearContributionA, ref angularContributionA, out constraintVelocityError); Vector3.Add(ref constraintVelocityError, ref linearContributionB, out constraintVelocityError); Vector3.Add(ref constraintVelocityError, ref angularContributionB, out constraintVelocityError); //However, we need to take into account two extra sources of velocities which modify our target velocity away from zero. //First, the velocity bias from position correction: Vector3.Subtract(ref constraintVelocityError, ref velocityBias, out constraintVelocityError); //And second, the bias from softness: Vector3 softnessBias; Vector3.Multiply(ref accumulatedImpulse, -softness, out softnessBias); Vector3.Subtract(ref constraintVelocityError, ref softnessBias, out constraintVelocityError); //By now, the constraint velocity error contains all the velocity we want to get rid of. //Convert it into an impulse using the effective mass matrix. Vector3 constraintSpaceImpulse; Matrix3x3.Transform(ref constraintVelocityError, ref effectiveMass, out constraintSpaceImpulse); Vector3.Negate(ref constraintSpaceImpulse, out constraintSpaceImpulse); //Add the constraint space impulse to the accumulated impulse so that warm starting and softness work properly. Vector3 preadd = accumulatedImpulse; Vector3.Add(ref constraintSpaceImpulse, ref accumulatedImpulse, out accumulatedImpulse); //But wait! The accumulated impulse may exceed this constraint's capacity! Check to make sure! float impulseSquared = accumulatedImpulse.LengthSquared(); if (impulseSquared > maximumImpulseSquared) { //Oops! Clamp that down. Vector3.Multiply(ref accumulatedImpulse, maximumImpulse / (float)Math.Sqrt(impulseSquared), out accumulatedImpulse); //Update the impulse based upon the clamped accumulated impulse and the original, pre-add accumulated impulse. Vector3.Subtract(ref accumulatedImpulse, ref preadd, out constraintSpaceImpulse); } //The constraint space impulse now represents the impulse we want to apply to the bone... but in constraint space. //Bring it out to world space using the transposed jacobian. if (!ConnectionA.Pinned)//Treat pinned elements as if they have infinite inertia. { Vector3 linearImpulseA; Matrix3x3.Transform(ref constraintSpaceImpulse, ref linearJacobianA, out linearImpulseA); Vector3 angularImpulseA; Matrix3x3.Transform(ref constraintSpaceImpulse, ref angularJacobianA, out angularImpulseA); //Apply them! ConnectionA.ApplyLinearImpulse(ref linearImpulseA); ConnectionA.ApplyAngularImpulse(ref angularImpulseA); } if (!ConnectionB.Pinned)//Treat pinned elements as if they have infinite inertia. { Vector3 linearImpulseB; Matrix3x3.Transform(ref constraintSpaceImpulse, ref linearJacobianB, out linearImpulseB); Vector3 angularImpulseB; Matrix3x3.Transform(ref constraintSpaceImpulse, ref angularJacobianB, out angularImpulseB); //Apply them! ConnectionB.ApplyLinearImpulse(ref linearImpulseB); ConnectionB.ApplyAngularImpulse(ref angularImpulseB); } } protected internal override void ClearAccumulatedImpulses() { accumulatedImpulse = new Vector3(); } } }
412
0.927351
1
0.927351
game-dev
MEDIA
0.612986
game-dev
0.984811
1
0.984811
RibirX/Ribir
6,968
core/src/scheduler.rs
use std::{ cell::RefCell, future::Future, pin::Pin, task::{Context, RawWaker, RawWakerVTable, Waker}, }; use pin_project_lite::pin_project; use tokio::task::LocalSet; use tokio_run_until_stalled::*; cfg_if::cfg_if! { if #[cfg(target_arch = "wasm32")] { mod wasm_scheduler; pub type RibirScheduler = wasm_scheduler::WasmScheduler; } else { mod tokio_scheduler; pub type RibirScheduler = tokio_scheduler::TokioScheduler; } } #[cfg(not(target_arch = "wasm32"))] pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; #[cfg(target_arch = "wasm32")] pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>; #[derive(Default)] enum LocalPoolState { #[default] Empty, WaitToRun(LocalSet), Running, } impl LocalPoolState { fn spawn_local(&mut self, fut: impl Future<Output = ()> + 'static) { match self { LocalPoolState::Empty => { let local_set = LocalSet::new(); local_set.spawn_local(fut); *self = LocalPoolState::WaitToRun(local_set); } LocalPoolState::WaitToRun(local_set) => { local_set.spawn_local(fut); } LocalPoolState::Running => { tokio::task::spawn_local(fut); } } } fn take_to_run(&mut self) -> Option<LocalSet> { match std::mem::replace(self, LocalPoolState::Running) { LocalPoolState::WaitToRun(local_set) => Some(local_set), LocalPoolState::Empty => Some(LocalSet::new()), _ => None, } } fn is_empty(&self) -> bool { matches!(self, LocalPoolState::Empty) } fn is_running(&self) -> bool { matches!(self, LocalPoolState::Running) } fn reset(&mut self) -> &mut Self { *self = LocalPoolState::Empty; self } fn add_local_set(&mut self, local_set: LocalSet) { match self { LocalPoolState::Empty => *self = LocalPoolState::WaitToRun(local_set), LocalPoolState::WaitToRun(runtime) => { runtime.spawn_local(local_set); } LocalPoolState::Running => { tokio::task::spawn_local(local_set); } } } } pub trait RuntimeWaker { fn clone_box(&self) -> Box<dyn RuntimeWaker + Send>; fn wake(&self); } impl Clone for Box<dyn RuntimeWaker + Send> { fn clone(&self) -> Self { self.clone_box() } } pin_project! { struct WakerFuture<F> { #[pin] fut: F, waker: Box<dyn RuntimeWaker + Send>, } } impl<F> WakerFuture<F> where F: Future, { fn local_waker(&self, cx: &std::task::Context<'_>) -> Waker { type RawLocalWaker = (std::task::Waker, Box<dyn RuntimeWaker + Send>); fn clone(this: *const ()) -> RawWaker { let waker = this as *const RawLocalWaker; let (w, cb) = unsafe { &*waker }; let data = Box::new((w.clone(), cb.clone())); let raw = Box::leak(data) as *const RawLocalWaker; RawWaker::new(raw as *const (), &VTABLE) } unsafe fn wake(this: *const ()) { let waker = this as *mut RawLocalWaker; let (w, ribir_waker) = unsafe { &*waker }; w.wake_by_ref(); ribir_waker.wake(); unsafe { drop(this) }; } unsafe fn wake_by_ref(this: *const ()) { let waker = this as *mut RawLocalWaker; let (w, ribir_waker) = unsafe { &*waker }; w.wake_by_ref(); ribir_waker.wake(); } unsafe fn drop(this: *const ()) { let waker = this as *mut RawLocalWaker; let _ = unsafe { Box::from_raw(waker) }; } static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop); let old_waker = cx.waker().clone(); let data = Box::new((old_waker, self.waker.clone())); let raw = RawWaker::new(Box::leak(data) as *const RawLocalWaker as *const (), &VTABLE); unsafe { Waker::from_raw(raw) } } } impl<F> Future for WakerFuture<F> where F: Future, { type Output = F::Output; fn poll( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { let waker = self.local_waker(cx); let mut cx = Context::from_waker(&waker); let this = self.project(); this.fut.poll(&mut cx) } } #[derive(Default)] pub struct LocalPool { local_set: RefCell<LocalPoolState>, } impl LocalPool { pub fn spawn_local(&self, fut: impl Future<Output = ()> + 'static) { self.local_set.borrow_mut().spawn_local(fut); } pub fn run_until_stalled(&self, runtime_waker: Option<Box<dyn RuntimeWaker + Send>>) { if self.local_set.borrow().is_empty() { return; } if self.local_set.borrow().is_running() { panic!("Local pool is already running"); } let local_set = self.local_set.borrow_mut().take_to_run().unwrap(); let fut = local_set.run_until_stalled(); let local_set = if let Some(waker) = runtime_waker { self .run_non_block(WakerFuture { fut, waker }) .into_local_set() } else { self.run_non_block(fut).into_local_set() }; self.local_set.borrow_mut().reset(); if let Some(local_set) = local_set { self .local_set .borrow_mut() .add_local_set(local_set); } } #[cfg(not(target_arch = "wasm32"))] fn run_until<F: Future>(&self, fut: F, rt: &tokio::runtime::Runtime) -> F::Output { if self.local_set.borrow().is_running() { panic!("Local pool is already running"); } let local_set = self.local_set.borrow_mut().take_to_run().unwrap(); let res = rt.block_on(local_set.run_until(fut)); self .local_set .borrow_mut() .reset() .add_local_set(local_set); res } #[cfg(not(target_arch = "wasm32"))] fn run(&self, rt: &tokio::runtime::Runtime) { if self.local_set.borrow().is_empty() { return; } if self.local_set.borrow().is_running() { panic!("Local pool is already running"); } let local_set = self.local_set.borrow_mut().take_to_run().unwrap(); rt.block_on(local_set); self.local_set.borrow_mut().reset(); } pub fn is_empty(&self) -> bool { self.local_set.borrow().is_empty() } #[allow(unused_mut)] fn run_non_block<F: Future + Unpin>(&self, mut fut: F) -> F::Output { cfg_if::cfg_if! { if #[cfg(not(target_arch = "wasm32"))] { crate::scheduler::tokio_scheduler::RUNTIME.block_on(fut) } else { fn mock_waker() -> Waker { fn clone(_: *const ()) -> RawWaker { RawWaker::new(std::ptr::null(), &VTABLE) } unsafe fn wake(_: *const ()) {} unsafe fn wake_by_ref(_: *const ()) {} unsafe fn drop(_: *const ()) {} static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop); let raw = RawWaker::new(std::ptr::null(), &VTABLE); unsafe { Waker::from_raw(raw) } } let waker = mock_waker(); let mut cx = Context::from_waker(&waker); match Pin::new(&mut fut).poll(&mut cx) { std::task::Poll::Ready(res) => res, std::task::Poll::Pending => unreachable!(), } } } } }
412
0.880229
1
0.880229
game-dev
MEDIA
0.73607
game-dev
0.965402
1
0.965402
ufcpp/UfcppSample
2,384
Demo/2017/BitOperations/BitOperations/Bits_T.cs
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace BitOperations { // Bits<T> should be a ref-like type (https://github.com/dotnet/csharplang/blob/master/meetings/2016/LDM-2016-11-01.md) // Type parameter T should be blittabl (https://github.com/dotnet/csharplang/issues/187) public unsafe struct Bits<T, TOperator> : IBits where T : struct where TOperator : SBitOperator<T> { // This should use ByReference<T> (https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/ByReference.cs) if possible void* _ptr; public Bits(ref T x) => _ptr = Unsafe.AsPointer(ref x); /// <summary> /// get/set a <paramref name="index"/>-th bit。 /// </summary> /// <remarks> /// It depends on <see cref="TOperator"/>'s implementaion whether order of bits is ascending or descending。 /// </remarks> public bool this[int index] { get => default(TOperator).GetBit(ref Unsafe.AsRef<T>(_ptr), index); set => default(TOperator).SetBit(ref Unsafe.AsRef<T>(_ptr), index, value); } /// <summary> /// bit counts. /// </summary> public int Count => default(TOperator).Size; Enumerator GetEnumerator() => new Enumerator(Unsafe.AsRef<T>(_ptr)); IEnumerator<bool> IEnumerable<bool>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); bool IReadOnlyList<bool>.this[int index] => this[index]; public struct Enumerator : IEnumerator<bool> { int _i; T _x; public Enumerator(T x) => (_x, _i) = (x, 0); public bool Current => default(TOperator).GetBit(ref _x, 0); object IEnumerator.Current => Current; void IDisposable.Dispose() { } public bool MoveNext() { if (_i == 0) { ++_i; return true; } if (_i >= default(TOperator).Size) return false; ++_i; _x = default(TOperator).RightShift(_x); return true; } public void Reset() => throw new NotImplementedException(); } } }
412
0.900399
1
0.900399
game-dev
MEDIA
0.187825
game-dev
0.970473
1
0.970473
osgcc/no-one-lives-forever
12,291
NOLF/ClientShellDLL/NetInfo.cpp
/**************************************************************************** ; ; MODULE: NetInfo (.CPP) ; ; PURPOSE: Network game info ; ; HISTORY: 07/05/98 [blg] This file was created ; ; COMMENT: Copyright (c) 1998, Monolith Productions Inc. ; ****************************************************************************/ // Includes... #include "stdafx.h" #include "NetInfo.h" #include "Sparam.h" // Statics... char s_sNameWithPing[256]; // Functions... /* *********************************************************************** */ /* CNinfoMgr */ // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::Init // // PURPOSE: Initialization // // ----------------------------------------------------------------------- // BOOL CNinfoMgr::Init() { // All done... return(TRUE); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::Term // // PURPOSE: Termination // // ----------------------------------------------------------------------- // void CNinfoMgr::Term() { RemoveGames(); Clear(); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::GetGame // // PURPOSE: Gets the game object has the given net session handle // // ----------------------------------------------------------------------- // CNinfoGame* CNinfoMgr::GetGame(NetSession* pNetSession) { // Sanity checks... if (!pNetSession) return(NULL); // Look for a game object with this net session handle... CNinfoGame* pGame = GetFirstGame(); while (pGame) { if (pGame->GetSessionPointer() == pNetSession) { return(pGame); } pGame = GetNextGame(); } // If we get here, we didn't find a match... return(NULL); } CNinfoGame* CNinfoMgr::GetGame(DWORD dwCRC) { // Look for a game object with this CRC... CNinfoGame* pGame = GetFirstGame(); while (pGame) { if (pGame->GetCRC() == dwCRC) { return(pGame); } pGame = GetNextGame(); } // If we get here, we didn't find a match... return(NULL); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::AddGame // // PURPOSE: Adds a new game object // // ----------------------------------------------------------------------- // CNinfoGame* CNinfoMgr::AddGame(const char* sInfo, NetSession* pNetSession, DWORD dwNumDPlayPlayers) { // Sanity checks... if (!sInfo) return(NULL); if (!pNetSession) return(NULL); // Get the name of this game session... char sName[NML_NAME]; if (!Sparam_Get(sName, sInfo, NST_GAMENAME)) { return(NULL); } // Get the host of this game session... char sHost[NML_HOST]; if (!Sparam_Get(sHost, sInfo, NST_GAMEHOST)) { return(NULL); } // Get the level of this game... char sLevel[NML_LEVEL]; char sBuf[NML_LEVEL]; if (!Sparam_Get(sBuf, sInfo, NST_GAMELEVEL)) { return(NULL); } int nLen = strlen(sBuf); int nIndex = 0; for (int i = nLen-2; i > 0; i--) { if (sBuf[i] == '\\' || sBuf[i] == '/') { nIndex = i+1; i = 0; } } if (nIndex < 0) nIndex = 0; if (nIndex >= nLen) nIndex = 0; strcpy(sLevel, &sBuf[nIndex]); // Get the type of this game... char sTemp[NML_NAME]; int nType; if (!Sparam_Get(sTemp, sInfo, NST_GAMETYPE)) { return(NULL); } nType = atoi(sTemp); // Create a new game object... CNinfoGame* pGame = debug_new(CNinfoGame); if (!pGame) return(NULL); // Init the new game object... if (!pGame->Init(sName, sHost, sLevel, nType, pNetSession, dwNumDPlayPlayers, pNetSession->m_HostIP, pNetSession->m_HostPort)) { debug_delete(pGame); return(NULL); } // Add each player in this game... int count = 0; if (Sparam_Get(sTemp, sInfo, NST_PLRCOUNT)) { count = atoi(sTemp); } for (i = 1; i <= count; i++) { char sBase[32]; wsprintf(sBase, "%s%i", NST_PLRNAME_BASE, i); if (Sparam_Get(sName, sInfo, sBase)) { wsprintf(sBase, "%s%i", NST_PLRFRAG_BASE, i); if (Sparam_Get(sTemp, sInfo, sBase)) { pGame->AddPlayer(sName, atoi(sTemp)); } } } // Add the game to our internal collection... if (!AddGame(pGame)) { debug_delete(pGame); return(NULL); } // All done... return(pGame); } BOOL CNinfoMgr::AddGame(CNinfoGame* pGame) { // Sanity checks... if (!pGame) return(FALSE); if (m_cGames >= NML_GAMES) return(FALSE); // Add the game to our internal collection... m_aGames[m_cGames] = pGame; m_cGames++; // All done... return(TRUE); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::GetFirstGame // // PURPOSE: Gets the first game in our internal collection // // ----------------------------------------------------------------------- // CNinfoGame* CNinfoMgr::GetFirstGame() { // Sanity checks... if (m_cGames == 0) return(NULL); // Get the first game and prepare for iterating... m_iGame = 0; return(m_aGames[m_iGame]); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::GetNextGame // // PURPOSE: Gets the next game in our internal collection // // WARNING: You must call GetFirstGame() before calling this function // // ----------------------------------------------------------------------- // CNinfoGame* CNinfoMgr::GetNextGame() { // Sanity checks... if (m_iGame+1 >= m_cGames) return(NULL); // Get the first game and prepare for iterating... m_iGame++; return(m_aGames[m_iGame]); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::RemoveGames // // PURPOSE: Removes all the games in our internal collection // // ----------------------------------------------------------------------- // void CNinfoMgr::RemoveGames() { // Remove each game in our internal collection... for (int i = 0; i < m_cGames; i++) { CNinfoGame* pGame = m_aGames[i]; _ASSERT(pGame && pGame->IsValid()); if (pGame) debug_delete(pGame); } // Reset our internal collection... m_cGames = 0; } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoMgr::CreateSessionString // // PURPOSE: Static function to fill in a string with all the given // game info. // // ----------------------------------------------------------------------- // BOOL CNinfoMgr::CreateSessionString(char* sString, char* sName, char* sHost, char* sLevel, int nType) { // Sanity checks... if (!sString) return(FALSE); if (!sName) return(FALSE); // Set the name info... Sparam_Add(sString, NST_GAMENAME, sName); Sparam_Add(sString, NST_GAMEHOST, sHost); Sparam_Add(sString, NST_GAMELEVEL, sLevel); Sparam_Add(sString, NST_GAMETYPE, nType); Sparam_Add(sString, NST_GAMETIME, 0); // All done... return(TRUE); } /* *********************************************************************** */ /* CNinfoGame */ // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::Init // // PURPOSE: Initialization // // ----------------------------------------------------------------------- // BOOL CNinfoGame::Init(char* sName, char* sHost, char* sLevel, int nType, NetSession* pNetSession, DWORD dwNumDPlayPlayers, char *pHostIP, DWORD hostPort) { // Sanity checks... if (!sName) return(FALSE); if (!sLevel) return(FALSE); if (!pNetSession) return(FALSE); // Set simple members... Clear(); strcpy(m_sName, sName); strcpy(m_sHost, sHost); strcpy(m_sLevel, sLevel); SAFE_STRCPY(m_sHostIP, pHostIP); m_dwHostPort = hostPort; m_nType = nType; m_pNetSession = pNetSession; m_cDPlayPlayers = dwNumDPlayPlayers; m_nPing = pNetSession->m_Ping; if (m_cDPlayPlayers > 0) m_cDPlayPlayers--; // don't count the server player // Set string helper members... const char* pGameType = GameTypeToString((GameType)m_nType); strcpy(m_sType, pGameType ? pGameType : "Unknown"); // Calculate a CRC value... m_dwCRC = m_pNetSession->m_guidInst.a; // All done... return(TRUE); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::Term // // PURPOSE: Termination // // ----------------------------------------------------------------------- // void CNinfoGame::Term() { RemovePlayers(); Clear(); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::AddPlayer // // PURPOSE: Adds a new player object // // ----------------------------------------------------------------------- // CNinfoPlayer* CNinfoGame::AddPlayer(char* sName, int nFrags) { // Sanity checks... if (!sName) return(NULL); // Create a new player object... CNinfoPlayer* pPlayer = debug_new(CNinfoPlayer); if (!pPlayer) return(NULL); // Init the new player object... if (!pPlayer->Init(sName, nFrags)) { debug_delete(pPlayer); return(NULL); } // Add the game to our internal collection... if (!AddPlayer(pPlayer)) { debug_delete(pPlayer); return(NULL); } // All done... return(pPlayer); } BOOL CNinfoGame::AddPlayer(CNinfoPlayer* pPlayer) { // Sanity checks... if (!pPlayer) return(FALSE); if (m_cPlayers >= NML_PLAYERS) return(FALSE); // Add the Player to our internal collection... m_aPlayers[m_cPlayers] = pPlayer; m_cPlayers++; // All done... return(TRUE); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::GetFirstPlayer // // PURPOSE: Gets the first Player in our internal collection // // ----------------------------------------------------------------------- // CNinfoPlayer* CNinfoGame::GetFirstPlayer() { // Sanity checks... if (m_cPlayers == 0) return(NULL); // Get the first Player and prepare for iterating... m_iPlayer = 0; return(m_aPlayers[m_iPlayer]); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::GetNextPlayer // // PURPOSE: Gets the next Player in our internal collection // // WARNING: You must call GetFirstPlayer() before calling this function // // ----------------------------------------------------------------------- // CNinfoPlayer* CNinfoGame::GetNextPlayer() { // Sanity checks... if (m_iPlayer+1 >= m_cPlayers) return(NULL); // Get the first Player and prepare for iterating... m_iPlayer++; return(m_aPlayers[m_iPlayer]); } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::RemovePlayers // // PURPOSE: Removes all the Players in our internal collection // // ----------------------------------------------------------------------- // void CNinfoGame::RemovePlayers() { // Remove each Player in our internal collection... for (int i = 0; i < m_cPlayers; i++) { CNinfoPlayer* pPlayer = m_aPlayers[i]; _ASSERT(pPlayer); if (pPlayer) debug_delete(pPlayer); } // Reset our internal collection... m_cPlayers = 0; } // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoGame::GetNameWithPing // // PURPOSE: Gets the name and ping time if available // // ----------------------------------------------------------------------- // char* CNinfoGame::GetNameWithPing() { // Build the string to use... if(m_nPing <= 0) wsprintf(s_sNameWithPing, "[-] %s [%s:%d]", GetName(), GetHostIP(), GetHostPort()); else wsprintf(s_sNameWithPing, "[%i] %s [%s:%d]", GetPing(), GetName(), GetHostIP(), GetHostPort()); // All done... return(s_sNameWithPing); } /* *********************************************************************** */ /* CNinfoPlayer */ // ----------------------------------------------------------------------- // // // ROUTINE: CNinfoPlayer::Init // // PURPOSE: Initialization // // ----------------------------------------------------------------------- // BOOL CNinfoPlayer::Init(char* sName, int nFrags) { // Sanity checks... if (!sName) return(FALSE); // Set simple members... Clear(); strcpy(m_sName, sName); m_nFrags = nFrags; // All done... return(TRUE); }
412
0.706029
1
0.706029
game-dev
MEDIA
0.840136
game-dev
0.867419
1
0.867419
Fluorohydride/ygopro-scripts
3,050
c35187185.lua
--夢魔鏡の天魔-ネイロス function c35187185.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcFunRep(c,c35187185.ffilter,2,true) --attribute local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_ADD_ATTRIBUTE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetValue(ATTRIBUTE_DARK) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(35187185,0)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_RELEASE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,35187185) e2:SetCondition(c35187185.descon) e2:SetTarget(c35187185.destg) e2:SetOperation(c35187185.desop) c:RegisterEffect(e2) --spsummon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(35187185,1)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_DESTROYED) e3:SetProperty(EFFECT_FLAG_DELAY) e3:SetCountLimit(1,35187186) e3:SetCondition(c35187185.spcon) e3:SetTarget(c35187185.sptg) e3:SetOperation(c35187185.spop) c:RegisterEffect(e3) end function c35187185.ffilter(c,fc,sub,mg,sg) return c:IsFusionSetCard(0x131) and (not sg or not sg:IsExists(Card.IsFusionAttribute,1,c,c:GetFusionAttribute())) end function c35187185.cfilter(c,tp) return c:IsPreviousLocation(LOCATION_MZONE) and c:IsPreviousControler(tp) end function c35187185.descon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c35187185.cfilter,1,e:GetHandler(),tp) end function c35187185.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() end if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c35187185.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end function c35187185.spfilter(c,e,tp) return c:IsSetCard(0x131) and not c:IsCode(35187185) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c35187185.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousControler(tp) and rp==1-tp end function c35187185.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c35187185.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE) end function c35187185.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,aux.NecroValleyFilter(c35187185.spfilter),tp,LOCATION_GRAVE,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
412
0.953936
1
0.953936
game-dev
MEDIA
0.977338
game-dev
0.97416
1
0.97416
pe3ep/Trident
5,050
src/main/kotlin/cc/pe3epwithyou/trident/client/listeners/KillChatListener.kt
package cc.pe3epwithyou.trident.client.listeners import cc.pe3epwithyou.trident.client.events.KillEvents import cc.pe3epwithyou.trident.config.Config import cc.pe3epwithyou.trident.feature.killfeed.DeathMessages import cc.pe3epwithyou.trident.feature.killfeed.KillMethod import cc.pe3epwithyou.trident.feature.questing.EliminatedCriteria import cc.pe3epwithyou.trident.feature.questing.IncrementContext import cc.pe3epwithyou.trident.feature.questing.QuestCriteria import cc.pe3epwithyou.trident.feature.questing.QuestStorage import cc.pe3epwithyou.trident.interfaces.killfeed.KillFeedDialog import cc.pe3epwithyou.trident.interfaces.killfeed.widgets.KillWidget import cc.pe3epwithyou.trident.state.Game import cc.pe3epwithyou.trident.state.MCCIState import com.noxcrew.sheeplib.util.opacity import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents import net.minecraft.Util import net.minecraft.client.Minecraft import net.minecraft.network.chat.Component object KillChatListener { private val fallbackColor = 0xFFFFFF opacity 128 val streaks = hashMapOf<String, Int>() fun resetStreaks() { streaks.clear() } fun register() { ClientReceiveMessageEvents.ALLOW_GAME.register allowGame@{ message, _ -> if (!MCCIState.isOnIsland()) return@allowGame true DeathMessages.entries.forEach { deathMessage -> if (deathMessage.regex.matches(message.string)) { return@allowGame handleKill(message, deathMessage.method) } } return@allowGame true } } private fun handleKill(message: Component, method: KillMethod): Boolean { val players = cleanupComponent(message) if (players.isEmpty()) return true val victim = players[0] val attacker = players.getOrNull(1) var killMethod = method if (method == KillMethod.MAGIC) { if ("Splash Potion" in message.string) killMethod = KillMethod.POTION if ("Orb" in message.string) killMethod = KillMethod.ORB } /* Call the event for external use */ KillEvents.KILL.invoker().onKill( KillEvents.KillEventPlayer( victim.string, victim.style.color?.value ?: fallbackColor ), if (attacker == null) null else KillEvents.KillEventPlayer( attacker.string, attacker.style.color?.value ?: fallbackColor ), killMethod ) if (MCCIState.game !in listOf(Game.BATTLE_BOX, Game.DYNABALL, Game.SKY_BATTLE)) return true if (attacker != null) { // Questing val self = Minecraft.getInstance().player ?: return true if (attacker.string == self.name.string) { val game = MCCIState.game val ctx = EliminatedCriteria.get(game, sourceTag = "kill") ?: return true QuestStorage.applyIncrement(ctx, true) if (killMethod == KillMethod.RANGE && game == Game.BATTLE_BOX) { QuestStorage.applyIncrement( IncrementContext( Game.BATTLE_BOX, QuestCriteria.BATTLE_BOX_QUADS_RANGED_KILLS, 1, "bb_ranged_kill" ), true ) } } // Streaks streaks[attacker.string] = (streaks[attacker.string] ?: 0) + 1 KillFeedDialog.addKill( KillWidget( victim.string, killMethod, attacker.string, getColors(victim, attacker), streak = streaks[attacker.string]!! // This should never fail ) ) } else { val victimColor = victim.style.color?.value?.opacity(128) ?: fallbackColor KillFeedDialog.addKill( KillWidget( victim.string, killMethod, killColors = Pair(0x606060 opacity 128, victimColor) ) ) } return !Config.KillFeed.hideKills } private fun getColors(victim: Component, attacker: Component): Pair<Int, Int> { val attackerColor = attacker.style.color?.value?.opacity(128) ?: fallbackColor val victimColor = victim.style.color?.value?.opacity(128) ?: fallbackColor return Pair(attackerColor, victimColor) } private fun cleanupComponent(c: Component): List<Component> { val rawList = c.toFlatList() val socialManager = Minecraft.getInstance().playerSocialManager val components: MutableList<Component> = mutableListOf() rawList.forEach { if (it.string.length in 1..2) return@forEach if ("[" in it.string) return@forEach val uuid = socialManager.getDiscoveredUUID(it.string) if (uuid == Util.NIL_UUID) return@forEach components.add(it) if (components.size == 2) return components } return components } }
412
0.93125
1
0.93125
game-dev
MEDIA
0.906642
game-dev
0.965319
1
0.965319
mirror-engine/the-mirror
1,288
mirror-godot-app/creator/selection/inspector/primitive/inspector_line_edit_field.gd
@tool extends "inspector_property_base.gd" signal value_changed(new_value: String) @export var reset_value: String = "" @export var current_value: String = "": get: return _line_edit_node.text set(value): _line_edit_node.text = value @export var enabled: bool = true: set(value): enabled = value if _line_edit_node: _line_edit_node.editable = value @onready var _line_edit_node: LineEdit = $LineEditHolder/LineEdit func _ready() -> void: super() if reset_value != "": _update_reset_visibility(current_value != reset_value) _line_edit_node.editable = enabled func _on_text_changed(new_text: String) -> void: if reset_value != "": _update_reset_visibility(new_text != reset_value) value_changed.emit(new_text) func _on_value_dropped(value) -> void: current_value = type_convert(value, TYPE_STRING) _on_text_changed(current_value) func _on_focus_entered() -> void: await get_tree().process_frame # This is done declaratively by LineEdit.select_all_on_focus = true # _line_edit_node.select_all() GameUI.instance.grab_input_lock(self) func _on_focus_exited() -> void: GameUI.instance.release_input_lock(self) func _on_reset_button_pressed() -> void: current_value = reset_value _update_reset_visibility(false) value_changed.emit(current_value)
412
0.898132
1
0.898132
game-dev
MEDIA
0.390446
game-dev
0.955456
1
0.955456
hannibal002/SkyHanni
2,595
src/main/java/at/hannibal2/skyhanni/features/gifting/UniqueGiftCounter.kt
package at.hannibal2.skyhanni.features.gifting import at.hannibal2.skyhanni.SkyHanniMod import at.hannibal2.skyhanni.api.event.HandleEvent import at.hannibal2.skyhanni.data.ProfileStorageData import at.hannibal2.skyhanni.data.WinterApi import at.hannibal2.skyhanni.events.GuiRenderEvent import at.hannibal2.skyhanni.events.InventoryFullyOpenedEvent import at.hannibal2.skyhanni.events.IslandChangeEvent import at.hannibal2.skyhanni.skyhannimodule.SkyHanniModule import at.hannibal2.skyhanni.utils.InventoryUtils import at.hannibal2.skyhanni.utils.ItemUtils.getLore import at.hannibal2.skyhanni.utils.NumberUtil.formatInt import at.hannibal2.skyhanni.utils.RegexUtils.firstMatcher import at.hannibal2.skyhanni.utils.RenderUtils.renderString import at.hannibal2.skyhanni.utils.SkyBlockUtils import at.hannibal2.skyhanni.utils.repopatterns.RepoPattern @SkyHanniModule object UniqueGiftCounter { private val config get() = SkyHanniMod.feature.event.gifting.uniqueGiftCounter private val storage get() = ProfileStorageData.playerSpecific?.winter private val giftedAmountPattern by RepoPattern.pattern( "event.winter.uniqugifts.counter.amount", "§7Unique Players Gifted: §a(?<amount>.*)", ) private var display = "" @HandleEvent fun onInventoryFullyOpened(event: InventoryFullyOpenedEvent) { if (event.inventoryName != "Generow") return val item = event.inventoryItems[40] ?: return val storage = storage ?: return giftedAmountPattern.firstMatcher(item.getLore()) { val amount = group("amount").formatInt() storage.amountGifted = amount update() } } @HandleEvent fun onIslandChange(event: IslandChangeEvent) { update() } fun addUniqueGift() { val storage = storage ?: return storage.amountGifted++ update() } private fun update() { val storage = storage ?: return val amountGifted = storage.amountGifted val max = 600 val hasMax = amountGifted >= max val color = if (hasMax) "§a" else "§e" display = "§7Unique Players Gifted: $color$amountGifted/$max" } @HandleEvent fun onRenderOverlay(event: GuiRenderEvent.GuiOverlayRenderEvent) { if (!isEnabled()) return config.position.renderString( display, posLabel = "Unique Gift Counter", ) } private fun isEnabled() = SkyBlockUtils.inSkyBlock && config.enabled && WinterApi.isDecember() && InventoryUtils.itemInHandId.endsWith("_GIFT") }
412
0.792588
1
0.792588
game-dev
MEDIA
0.819212
game-dev
0.867947
1
0.867947
SR5-FoundryVTT/SR5-FoundryVTT
3,175
src/module/rolls/SR5Roll.ts
import {SR} from "../constants"; import ModList = Shadowrun.ModList; // TODO: Data for casting actor / item (uuid) // TODO: maybe copy of the action data from the casting item / actor export type ShadowrunRollData = { limit: number; threshold: number; parts: ModList<number>; // TODO: Is this useful? explodeSixes: boolean; [key: string]: number | boolean | ModList<number>; } /** * Apply Shadowrun 5 rules to a FoundryVTT Roll. * * TODO: This class should create a basic Success Test template and be extended * for further Test templates (versus, action, weapon?, spell?) * * TODO: A chat message should contain all data needed to cast resulting actions. */ export class SR5Roll extends Roll<ShadowrunRollData> { // toJSON(): any { // // TODO: Check if data includes custom ShadowrunRollData // const data = super.toJSON(); // // add class Roll to the json so dice-so-nice works // // TODO: Check if this is still necessary. // // data.class = 'Roll'; // return data; // } get sides(): number[] { // 0.7.x foundryVTT if (this.terms) { //@ts-expect-error return this.terms[0].results.map(result => result.result); } //@ts-expect-error // 0.6.x foundryVTT return this.parts[0].rolls.map(roll => roll.roll); } get limit(): number { return this.data.limit; } get threshold(): number { return this.data.threshold; } get parts(): ModList<number> { return this.data.parts; } // TODO: Not needed anymore with complex Formula of SuccessTest get explodeSixes(): boolean { return this.data.explodeSixes; } count(side: number): number { return this.sides.reduce((counted, result) => result === side ? counted + 1 : counted, 0); } // TODO: Rework this to work with the complex formula of SuccessTest.formula (total counts all cs and cf) get hits(): number { return this.sides.reduce((hits, result) => SR.die.success.includes(result) ? hits + 1 : hits, 0); } get glitches(): number { return this.sides.reduce((glitches, result) => SR.die.glitch.includes(result) ? glitches + 1 : glitches, 0); } /** * The amount of dice going into the throw (the pool used). * * NOTE: this can be different from the amount of dice actually thrown. * Use SR5Roll#diceThrown instead */ get pool(): number { // 0.7.x > FoundryVTT if (this.terms) { return this.dice[0].number!; } //@ts-expect-error // till 0.6.x FoundryVTT return this.parts[0].rolls.length; } /** * The amount of dice actually thrown after all dice explosions have been resolved. */ get poolThrown(): number { return this.sides.length; } get glitched(): boolean { return this.glitches > Math.floor(this.pool / 2); } override get total(): number { return this.hits; } }
412
0.846592
1
0.846592
game-dev
MEDIA
0.694866
game-dev
0.957061
1
0.957061
chai3d/chai3d
3,705
modules/Bullet/externals/bullet/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h
/* 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. */ #ifndef BT_POLYHEDRAL_CONVEX_SHAPE_H #define BT_POLYHEDRAL_CONVEX_SHAPE_H #include "LinearMath/btMatrix3x3.h" #include "btConvexInternalShape.h" class btConvexPolyhedron; ///The btPolyhedralConvexShape is an internal interface class for polyhedral convex shapes. ATTRIBUTE_ALIGNED16(class) btPolyhedralConvexShape : public btConvexInternalShape { protected: btConvexPolyhedron* m_polyhedron; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btPolyhedralConvexShape(); virtual ~btPolyhedralConvexShape(); ///optional method mainly used to generate multiple contact points by clipping polyhedral features (faces/edges) ///experimental/work-in-progress virtual bool initializePolyhedralFeatures(int shiftVerticesByMargin=0); const btConvexPolyhedron* getConvexPolyhedron() const { return m_polyhedron; } //brute force implementations virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual int getNumVertices() const = 0 ; virtual int getNumEdges() const = 0; virtual void getEdge(int i,btVector3& pa,btVector3& pb) const = 0; virtual void getVertex(int i,btVector3& vtx) const = 0; virtual int getNumPlanes() const = 0; virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i ) const = 0; // virtual int getIndex(int i) const = 0 ; virtual bool isInside(const btVector3& pt,btScalar tolerance) const = 0; }; ///The btPolyhedralConvexAabbCachingShape adds aabb caching to the btPolyhedralConvexShape class btPolyhedralConvexAabbCachingShape : public btPolyhedralConvexShape { btVector3 m_localAabbMin; btVector3 m_localAabbMax; bool m_isLocalAabbValid; protected: void setCachedLocalAabb (const btVector3& aabbMin, const btVector3& aabbMax) { m_isLocalAabbValid = true; m_localAabbMin = aabbMin; m_localAabbMax = aabbMax; } inline void getCachedLocalAabb (btVector3& aabbMin, btVector3& aabbMax) const { btAssert(m_isLocalAabbValid); aabbMin = m_localAabbMin; aabbMax = m_localAabbMax; } public: btPolyhedralConvexAabbCachingShape(); inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const { //lazy evaluation of local aabb btAssert(m_isLocalAabbValid); btTransformAabb(m_localAabbMin,m_localAabbMax,margin,trans,aabbMin,aabbMax); } virtual void setLocalScaling(const btVector3& scaling); virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; void recalcLocalAabb(); }; #endif //BT_POLYHEDRAL_CONVEX_SHAPE_H
412
0.856891
1
0.856891
game-dev
MEDIA
0.986554
game-dev
0.827771
1
0.827771
maxioriv/HB_4.16
1,296
Routines/DefaultRoutine/Silverfish/cards/110ICC冰封王座的骑士/Sim_ICC_086.cs
using System; using System.Collections.Generic; using System.Text; namespace HREngine.Bots { class Sim_ICC_086: SimTemplate //* Glacial Mysteries { // Put one of each Secret from your deck into the battlefield. public override void onCardPlay(Playfield p, bool ownplay, Minion target, int choice) { if (ownplay) { List<CardDB.cardIDEnum> secrets = new List<CardDB.cardIDEnum>(); CardDB.Card c; foreach (KeyValuePair<CardDB.cardIDEnum, int> cid in p.prozis.turnDeck) { c = CardDB.Instance.getCardDataFromID(cid.Key); if (c.Secret) secrets.Add(cid.Key); } foreach (CardDB.cardIDEnum cId in secrets) { if (p.ownSecretsIDList.Count < 5 && !p.ownSecretsIDList.Contains(cId)) p.ownSecretsIDList.Add(cId); } } else { for (int i = p.enemySecretCount; i < 5; i++) { p.enemySecretCount++; p.enemySecretList.Add(Probabilitymaker.Instance.getNewSecretGuessedItem(p.getNextEntity(), p.enemyHeroStartClass)); } } } } }
412
0.973398
1
0.973398
game-dev
MEDIA
0.974853
game-dev
0.868049
1
0.868049
sh-akira/VirtualMotionCapture
86,906
Assets/Scripts/Avatar/Calibrator.cs
using RootMotion; using RootMotion.FinalIK; using System.Collections; using UnityEngine; using static RootMotion.FinalIK.VRIKCalibrator; namespace VMC { public class Calibrator { public static float pelvisOffsetDivide = 4f; public static Transform pelvisOffsetTransform; public static float pelvisOffsetHeight = 0f; /* /// <summary> /// Calibrates VRIK to the specified trackers using the VRIKTrackerCalibrator.Settings. /// </summary> /// <param name="ik">Reference to the VRIK component.</param> /// <param name="settings">Calibration settings.</param> /// <param name="HMDTransform">The HMD.</param> /// <param name="PelvisTransform">(Optional) A tracker placed anywhere on the body of the player, preferrably close to the pelvis, on the belt area.</param> /// <param name="LeftHandTransform">(Optional) A tracker or hand controller device placed anywhere on or in the player's left hand.</param> /// <param name="RightHandTransform">(Optional) A tracker or hand controller device placed anywhere on or in the player's right hand.</param> /// <param name="LeftFootTransform">(Optional) A tracker placed anywhere on the ankle or toes of the player's left leg.</param> /// <param name="RightFootTransform">(Optional) A tracker placed anywhere on the ankle or toes of the player's right leg.</param> public static void Calibrate(VRIK ik, Settings settings, Transform HMDTransform, Transform PelvisTransform = null, Transform LeftHandTransform = null, Transform RightHandTransform = null, Transform LeftFootTransform = null, Transform RightFootTransform = null) { if (!ik.solver.initiated) { Debug.LogError("[Calib Fail] Can not calibrate before VRIK has initiated."); return; } if (HMDTransform == null) { Debug.LogError("[Calib Fail] Can not calibrate VRIK without the head tracker."); return; } //TrackingWatcherを初期化する GameObject.Find("HandTrackerRoot").GetComponent<sh_akira.OVRTracking.TrackerHandler>().ClearTrackingWatcher(); // Head Transform hmdAdjusterTransform = ik.solver.spine.headTarget == null ? (new GameObject("hmdAdjuster")).transform : ik.solver.spine.headTarget; hmdAdjusterTransform.parent = HMDTransform; hmdAdjusterTransform.position = HMDTransform.position + HMDTransform.rotation * Quaternion.LookRotation(settings.headTrackerForward, settings.headTrackerUp) * settings.headOffset; hmdAdjusterTransform.rotation = ik.references.head.rotation; ik.solver.spine.headTarget = hmdAdjusterTransform; //TrackingWatcherにWeight設定用アクションを設定 Debug.Log("### Set"); HMDTransform.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); // Size float sizeF = hmdAdjusterTransform.position.y / ik.references.head.position.y; ik.references.root.localScale = Vector3.one * sizeF; // Root position and rotation ik.references.root.position = new Vector3(hmdAdjusterTransform.position.x, ik.references.root.position.y, hmdAdjusterTransform.position.z); Vector3 hmdForwardAngle = HMDTransform.rotation * settings.headTrackerForward; hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); // Body if (PelvisTransform != null) { Transform pelvisAdjusterTransform = ik.solver.spine.pelvisTarget == null ? (new GameObject("pelvisAdjuster")).transform : ik.solver.spine.pelvisTarget; pelvisAdjusterTransform.parent = PelvisTransform; pelvisAdjusterTransform.position = ik.references.pelvis.position; pelvisAdjusterTransform.rotation = ik.references.pelvis.rotation; ik.solver.spine.pelvisTarget = pelvisAdjusterTransform; ik.solver.spine.pelvisPositionWeight = 1f; ik.solver.spine.pelvisRotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 PelvisTransform.GetComponentInChildren<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.spine.pelvisPositionWeight = weight; ik.solver.spine.pelvisRotationWeight = weight; }); ik.solver.plantFeet = false; ik.solver.spine.neckStiffness = 0f; ik.solver.spine.maxRootAngle = 180f; } else if (LeftFootTransform != null && RightFootTransform != null) { ik.solver.spine.maxRootAngle = 0f; } // Left Hand if (LeftHandTransform != null) { Transform leftHandAdjusterTransform = ik.solver.leftArm.target == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.target; leftHandAdjusterTransform.parent = LeftHandTransform; leftHandAdjusterTransform.position = LeftHandTransform.position + LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = Vector3.Cross(ik.solver.leftArm.wristToPalmAxis, ik.solver.leftArm.palmToThumbAxis); leftHandAdjusterTransform.rotation = QuaTools.MatchRotation(LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.target = leftHandAdjusterTransform; ik.solver.leftArm.positionWeight = 1f; ik.solver.leftArm.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 LeftHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.positionWeight = weight; ik.solver.leftArm.rotationWeight = weight; }); } else { ik.solver.leftArm.positionWeight = 0f; ik.solver.leftArm.rotationWeight = 0f; } // Right Hand if (RightHandTransform != null) { Transform rightHandAdjusterTransform = ik.solver.rightArm.target == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.target; rightHandAdjusterTransform.parent = RightHandTransform; rightHandAdjusterTransform.position = RightHandTransform.position + RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = -Vector3.Cross(ik.solver.rightArm.wristToPalmAxis, ik.solver.rightArm.palmToThumbAxis); rightHandAdjusterTransform.rotation = QuaTools.MatchRotation(RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.target = rightHandAdjusterTransform; ik.solver.rightArm.positionWeight = 1f; ik.solver.rightArm.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 RightHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.positionWeight = weight; ik.solver.rightArm.rotationWeight = weight; }); } else { ik.solver.rightArm.positionWeight = 0f; ik.solver.rightArm.rotationWeight = 0f; } // Legs if (LeftFootTransform != null) CalibrateLeg(settings, LeftFootTransform, ik.solver.leftLeg, (ik.references.leftToes != null ? ik.references.leftToes : ik.references.leftFoot), hmdForwardAngle, ik.references.root.forward, true); if (RightFootTransform != null) CalibrateLeg(settings, RightFootTransform, ik.solver.rightLeg, (ik.references.rightToes != null ? ik.references.rightToes : ik.references.rightFoot), hmdForwardAngle, ik.references.root.forward, false); // Root controller bool addRootController = PelvisTransform != null || (LeftFootTransform != null && RightFootTransform != null); var rootController = ik.references.root.GetComponent<VRIKRootController>(); if (addRootController) { if (rootController == null) rootController = ik.references.root.gameObject.AddComponent<VRIKRootController>(); //rootController.pelvisTarget = ik.solver.spine.pelvisTarget; //rootController.leftFootTarget = ik.solver.leftLeg.target; //rootController.rightFootTarget = ik.solver.rightLeg.target; rootController.Calibrate(); } else { if (rootController != null) GameObject.Destroy(rootController); } // Additional solver settings ik.solver.spine.minHeadHeight = 0f; ik.solver.locomotion.weight = PelvisTransform == null && LeftFootTransform == null && RightFootTransform == null ? 1f : 0f; } */ private static Transform CalibrateLeg(VRIKCalibrator.Settings settings, Transform FootTransform, IKSolverVR.Leg leg, Transform lastBone, Vector3 hmdForwardAngle, Vector3 rootForward, bool isLeft) { Transform footAdjusterTransform = leg.target == null ? new GameObject(isLeft ? "leftFootAdjuster" : "rightFootAdjuster").transform : leg.target; footAdjusterTransform.parent = FootTransform; // Space of the tracker heading Quaternion frontQuaternion = Quaternion.LookRotation(hmdForwardAngle); // Target position //float inwardOffset = isLeft ? settings.footInwardOffset : -settings.footInwardOffset; //footAdjusterTransform.position = FootTransform.position + frontQuaternion * new Vector3(inwardOffset, 0f, settings.footForwardOffset); //footAdjusterTransform.position = new Vector3(footAdjusterTransform.position.x, lastBone.position.y, footAdjusterTransform.position.z); footAdjusterTransform.position = lastBone.position; // Target rotation footAdjusterTransform.rotation = lastBone.rotation; // Rotate target forward towards tracker forward Vector3 footForward = AxisTools.GetAxisVectorToDirection(lastBone, rootForward); if (Vector3.Dot(lastBone.rotation * footForward, rootForward) < 0f) footForward = -footForward; Vector3 fLocal = Quaternion.Inverse(Quaternion.LookRotation(footAdjusterTransform.rotation * footForward)) * hmdForwardAngle; float angle = Mathf.Atan2(fLocal.x, fLocal.z) * Mathf.Rad2Deg; float headingOffset = isLeft ? settings.footHeadingOffset : -settings.footHeadingOffset; footAdjusterTransform.rotation = Quaternion.AngleAxis(angle + headingOffset, Vector3.up) * footAdjusterTransform.rotation; leg.target = footAdjusterTransform; leg.positionWeight = 1f; leg.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 FootTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { leg.positionWeight = weight; leg.rotationWeight = weight; }); // Bend goal Transform bendGoal = leg.bendGoal == null ? (new GameObject(isLeft ? "leftFootBendGoal" : "rightFootBendGoal")).transform : leg.bendGoal; bendGoal.position = lastBone.position + frontQuaternion * Vector3.forward + frontQuaternion * Vector3.up;// * 0.5f; bendGoal.parent = FootTransform; return bendGoal; //leg.bendGoal = null; //leg.bendGoalWeight = 0f; } public static IEnumerator CalibrateScaled(Transform handTrackerRoot, Transform footTrackerRoot, VRIK ik, VRIKCalibrator.Settings settings, Vector3 LeftHandOffset, Vector3 RightHandOffset, TrackingPoint HMDTrackingPoint, TrackingPoint PelvisTrackingPoint = null, TrackingPoint LeftHandTrackingPoint = null, TrackingPoint RightHandTrackingPoint = null, TrackingPoint LeftFootTrackingPoint = null, TrackingPoint RightFootTrackingPoint = null, TrackingPoint LeftElbowTrackingPoint = null, TrackingPoint RightElbowTrackingPoint = null, TrackingPoint LeftKneeTrackingPoint = null, TrackingPoint RightKneeTrackingPoint = null, TrackingPoint ChestTrackingPoint = null) { Transform HMDTransform = HMDTrackingPoint?.TargetTransform; Transform PelvisTransform = PelvisTrackingPoint?.TargetTransform; Transform LeftHandTransform = LeftHandTrackingPoint?.TargetTransform; Transform RightHandTransform = RightHandTrackingPoint?.TargetTransform; Transform LeftFootTransform = LeftFootTrackingPoint?.TargetTransform; Transform RightFootTransform = RightFootTrackingPoint?.TargetTransform; Transform LeftElbowTransform = LeftElbowTrackingPoint?.TargetTransform; Transform RightElbowTransform = RightElbowTrackingPoint?.TargetTransform; Transform LeftKneeTransform = LeftKneeTrackingPoint?.TargetTransform; Transform RightKneeTransform = RightKneeTrackingPoint?.TargetTransform; Transform ChestTransform = ChestTrackingPoint?.TargetTransform; if (!ik.solver.initiated) { Debug.LogError("[Calib Fail] Can not calibrate before VRIK has initiated."); yield break; } if (HMDTransform == null) { Debug.LogError("[Calib Fail] Can not calibrate VRIK without the head tracker."); yield break; } //トラッカーのルートスケールを初期値に戻す handTrackerRoot.localScale = new Vector3(1.0f, 1.0f, 1.0f); footTrackerRoot.localScale = new Vector3(1.0f, 1.0f, 1.0f); handTrackerRoot.position = Vector3.zero; footTrackerRoot.position = Vector3.zero; //腰トラ下げ用空Object var pelvisOffsetAdjuster = new GameObject("PelvisOffsetAdjuster").transform; pelvisOffsetAdjuster.parent = footTrackerRoot; //それぞれのトラッカーを正しいルートに移動 if (HMDTransform != null) HMDTransform.parent = handTrackerRoot; if (LeftHandTransform != null) LeftHandTransform.parent = handTrackerRoot; if (RightHandTransform != null) RightHandTransform.parent = handTrackerRoot; if (PelvisTransform != null) PelvisTransform.parent = pelvisOffsetAdjuster; if (LeftFootTransform != null) LeftFootTransform.parent = footTrackerRoot; if (RightFootTransform != null) RightFootTransform.parent = footTrackerRoot; if (LeftElbowTransform != null) LeftElbowTransform.parent = handTrackerRoot; if (RightElbowTransform != null) RightElbowTransform.parent = handTrackerRoot; if (LeftKneeTransform != null) LeftKneeTransform.parent = footTrackerRoot; if (RightKneeTransform != null) RightKneeTransform.parent = footTrackerRoot; if (ChestTransform != null) ChestTransform.parent = handTrackerRoot; HandSwapManagerScript handSwapManagerScript = GameObject.Find("HandSwapManager").GetComponent<HandSwapManagerScript>(); handSwapManagerScript.WPFLeftHandTransform = LeftHandTransform; //左手登録 handSwapManagerScript.WPFRightHandTransform = RightHandTransform; //右手登録 //コントローラーの場合手首までのオフセットを追加 if (LeftHandOffset == Vector3.zero) { var offset = new GameObject("LeftWristOffset"); offset.transform.parent = LeftHandTransform; offset.transform.localPosition = new Vector3(-0.04f, 0.04f, -0.15f); offset.transform.localRotation = Quaternion.Euler(60, 0, 90); offset.transform.localScale = Vector3.one; LeftHandTransform = offset.transform; } if (RightHandOffset == Vector3.zero) { var offset = new GameObject("RightWristOffset"); offset.transform.parent = RightHandTransform; offset.transform.localPosition = new Vector3(0.04f, 0.04f, -0.15f); offset.transform.localRotation = Quaternion.Euler(60, 0, -90); offset.transform.localScale = Vector3.one; RightHandTransform = offset.transform; } //モデルの体の中心を取っておく var modelcenterposition = Vector3.Lerp(ik.references.leftHand.position, ik.references.rightHand.position, 0.5f); modelcenterposition = new Vector3(modelcenterposition.x, ik.references.root.position.y, modelcenterposition.z); var modelcenterdistance = Vector3.Distance(ik.references.root.position, modelcenterposition); // モデルのポジションを手と手の中心位置に移動 var centerposition = Vector3.Lerp(LeftHandTransform.position, RightHandTransform.position, 0.5f); ik.references.root.position = new Vector3(centerposition.x, ik.references.root.position.y, centerposition.z); yield return new WaitForEndOfFrame(); //それぞれのトラッカーに手のオフセットを適用 //トラッカーの角度は 0,-90,-90 が正位置(手の甲に付けてLED部を外側に向けたとき) //トラッカー zをマイナス方向に動かすとトラッカーの底面に向かって進む //角度補正LookAt(左手なら右のトラッカーに向けた)後 zを+方向は体中心(左手なら右手の方向)に向かって進む //xを-方向は体の正面に向かって進む //先にトラッカー底面に向かってのオフセットを両手に適用する var leftWrist = new GameObject("LeftWristOffset").transform; leftWrist.parent = LeftHandTransform; leftWrist.localPosition = new Vector3(0, 0, -LeftHandOffset.y); leftWrist.localRotation = Quaternion.Euler(Vector3.zero); var rightWrist = new GameObject("RightWristOffset").transform; rightWrist.parent = RightHandTransform; rightWrist.localPosition = new Vector3(0, 0, -RightHandOffset.y); rightWrist.localRotation = Quaternion.Euler(Vector3.zero); //お互いのトラッカー同士を向き合わせてオフセットを適用する leftWrist.LookAt(rightWrist ?? RightHandTransform); leftWrist.localPosition += leftWrist.localRotation * new Vector3(0, 0, LeftHandOffset.z); rightWrist.LookAt(leftWrist ?? LeftHandTransform); rightWrist.localPosition += rightWrist.localRotation * new Vector3(0, 0, RightHandOffset.z); //両手のxをマイナス方向が正面なので体を回転させる Vector3 hmdForwardAngle = leftWrist.rotation * new Vector3(-1, 0, 0); hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); //回転した分トラッカーも回転させる if (LeftHandOffset != Vector3.zero) // Vector3 (IsEnable, ToTrackerBottom, ToBodySide) { leftWrist.eulerAngles = new Vector3(0, -90, 90); //トラッカー補正後の角度 leftWrist.RotateAround(leftWrist.position, Vector3.up, ik.references.root.rotation.eulerAngles.y); //体の回転分を引く LeftHandTransform = leftWrist; } if (RightHandOffset != Vector3.zero) // Vector3 (IsEnable, ToTrackerBottom, ToBodySide) { rightWrist.eulerAngles = new Vector3(180, -90, 90); //トラッカー補正後の角度 rightWrist.RotateAround(rightWrist.position, Vector3.up, ik.references.root.rotation.eulerAngles.y); //体の回転分を引く RightHandTransform = rightWrist; } yield return new WaitForEndOfFrame(); //モデルを手の高さで比較してスケールアップさせる //なるべく現実の身長に近づけて現実のコントローラー座標とのずれをなくす //ずれが大きいとexternalcamera.cfgとの合成時に手がずれすぎておかしくなる var modelHandHeight = (ik.references.leftHand.position.y + ik.references.rightHand.position.y) / 2f; var realHandHeight = (LeftHandTransform.position.y + RightHandTransform.position.y) / 2f; var hscale = realHandHeight / modelHandHeight; ik.references.root.localScale = new Vector3(hscale, hscale, hscale); // 手のトラッカー全体のスケールを手の位置に合わせる var modelHandDistance = Vector3.Distance(ik.references.leftHand.position, ik.references.rightHand.position); var realHandDistance = Vector3.Distance(LeftHandTransform.position, RightHandTransform.position); var wscale = modelHandDistance / realHandDistance; modelHandHeight = (ik.references.leftHand.position.y + ik.references.rightHand.position.y) / 2f; realHandHeight = (LeftHandTransform.position.y + RightHandTransform.position.y) / 2f; hscale = modelHandHeight / realHandHeight; handTrackerRoot.localScale = new Vector3(wscale, hscale, wscale); // モデルのポジションを再度手と手の中心位置に移動 centerposition = Vector3.Lerp(LeftHandTransform.position, RightHandTransform.position, 0.5f); ik.references.root.position = new Vector3(centerposition.x, ik.references.root.position.y, centerposition.z) + ik.references.root.forward * modelcenterdistance + ik.references.root.forward * 0.1f; //hmdForwardAngle = HMDTransform.rotation * settings.headTrackerForward; //hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); // 腰のトラッカー全体のスケールを腰の位置に合わせる if (PelvisTransform != null) { var modelPelvisHeight = ik.references.pelvis.position.y; var realPelvisHeight = PelvisTransform.position.y; var pelvisHscale = modelPelvisHeight / realPelvisHeight; footTrackerRoot.localScale = new Vector3(wscale, pelvisHscale, wscale); } yield return new WaitForEndOfFrame(); //yield break; // Head Transform hmdAdjusterTransform = ik.solver.spine.headTarget == null ? (new GameObject("hmdAdjuster")).transform : ik.solver.spine.headTarget; hmdAdjusterTransform.parent = HMDTransform; hmdAdjusterTransform.position = ik.references.head.position; //HMDTransform.position + HMDTransform.rotation * Quaternion.LookRotation(settings.headTrackerForward, settings.headTrackerUp) * settings.headOffset; //hmdAdjusterTransform.localPosition = new Vector3(0, hmdAdjusterTransform.localPosition.y, -0.15f); hmdAdjusterTransform.rotation = ik.references.head.rotation; ik.solver.spine.headTarget = hmdAdjusterTransform; ik.solver.spine.headClampWeight = 0.38f; //TrackingWatcherにWeight設定用アクションを設定 HMDTransform.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); // Body if (PelvisTransform != null) { Transform pelvisAdjusterTransform = ik.solver.spine.pelvisTarget == null ? (new GameObject("pelvisAdjuster")).transform : ik.solver.spine.pelvisTarget; pelvisAdjusterTransform.parent = PelvisTransform; pelvisAdjusterTransform.position = ik.references.pelvis.position; pelvisAdjusterTransform.rotation = ik.references.pelvis.rotation; ik.solver.spine.pelvisTarget = pelvisAdjusterTransform; ik.solver.spine.pelvisPositionWeight = 1f; ik.solver.spine.pelvisRotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 PelvisTransform.GetComponentInChildren<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.spine.pelvisPositionWeight = weight; ik.solver.spine.pelvisRotationWeight = weight; }); ik.solver.plantFeet = false; ik.solver.spine.neckStiffness = 0f; ik.solver.spine.maxRootAngle = 180f; } else if (LeftFootTransform != null && RightFootTransform != null) { ik.solver.plantFeet = false; ik.solver.spine.maxRootAngle = 0f; } ik.solver.spine.maintainPelvisPosition = 0.0f; yield return new WaitForEndOfFrame(); // Chest if (ChestTransform != null && ik.references.chest != null) { var chestBone = ik.references.chest; var bendGoal = new GameObject("ChestBendGoal").transform; bendGoal.parent = ChestTransform; bendGoal.position = chestBone.position + ik.references.root.forward * 0.5f; ik.solver.spine.chestGoal = bendGoal; ik.solver.spine.chestGoalWeight = 1.0f; ik.solver.spine.chestClampWeight = 0f; } // Left Hand if (LeftHandTransform != null) { Transform leftHandAdjusterTransform = ik.solver.leftArm.target == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.target; leftHandAdjusterTransform.parent = LeftHandTransform; leftHandAdjusterTransform.position = LeftHandTransform.position + LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = new Vector3(0, 1, 0); leftHandAdjusterTransform.rotation = QuaTools.MatchRotation(LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.target = leftHandAdjusterTransform; ik.solver.leftArm.positionWeight = 1f; ik.solver.leftArm.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 LeftHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.positionWeight = weight; ik.solver.leftArm.rotationWeight = weight; }); } else { ik.solver.leftArm.positionWeight = 0f; ik.solver.leftArm.rotationWeight = 0f; } // Right Hand if (RightHandTransform != null) { Transform rightHandAdjusterTransform = ik.solver.rightArm.target == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.target; rightHandAdjusterTransform.parent = RightHandTransform; rightHandAdjusterTransform.position = RightHandTransform.position + RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = new Vector3(0, 1, 0); rightHandAdjusterTransform.rotation = QuaTools.MatchRotation(RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.target = rightHandAdjusterTransform; ik.solver.rightArm.positionWeight = 1f; ik.solver.rightArm.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 RightHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.positionWeight = weight; ik.solver.rightArm.rotationWeight = weight; }); } else { ik.solver.rightArm.positionWeight = 0f; ik.solver.rightArm.rotationWeight = 0f; } // Left Elbow if (LeftElbowTransform != null) { Transform leftElbowAdjusterTransform = ik.solver.leftArm.bendGoal == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.bendGoal; leftElbowAdjusterTransform.parent = LeftElbowTransform; leftElbowAdjusterTransform.position = LeftElbowTransform.position + LeftElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = new Vector3(0, 1, 0); leftElbowAdjusterTransform.rotation = QuaTools.MatchRotation(LeftElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.bendGoal = leftElbowAdjusterTransform; ik.solver.leftArm.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftElbowTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.bendGoalWeight = weight; }); } else { ik.solver.leftArm.bendGoalWeight = 0.0f; } // Right Elbow if (RightElbowTransform != null) { Transform rightElbowAdjusterTransform = ik.solver.rightArm.bendGoal == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.bendGoal; rightElbowAdjusterTransform.parent = RightElbowTransform; rightElbowAdjusterTransform.position = RightElbowTransform.position + RightElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = new Vector3(0, 1, 0); rightElbowAdjusterTransform.rotation = QuaTools.MatchRotation(RightElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.bendGoal = rightElbowAdjusterTransform; ik.solver.rightArm.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 RightElbowTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.bendGoalWeight = weight; }); } else { ik.solver.rightArm.bendGoalWeight = 0.0f; } // Legs ik.solver.leftLeg.bendGoalWeight = 0.0f; if (LeftFootTransform != null) { var leftBendGoalTarget = CalibrateLeg(settings, LeftFootTransform, ik.solver.leftLeg, (ik.references.leftToes != null ? ik.references.leftToes : ik.references.leftFoot), hmdForwardAngle, ik.references.root.forward, true); ik.solver.leftLeg.bendGoal = leftBendGoalTarget; ik.solver.leftLeg.bendGoalWeight = 0.0f; } if (LeftKneeTransform != null) { Transform leftKneeAdjusterTransform = ik.solver.leftLeg.bendGoal == null ? (new GameObject("leftKneeAdjuster")).transform : ik.solver.leftLeg.bendGoal; leftKneeAdjusterTransform.parent = LeftKneeTransform; leftKneeAdjusterTransform.position = ik.references.leftCalf.position;// LeftKneeTransform.position + LeftKneeTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; leftKneeAdjusterTransform.transform.localPosition += new Vector3(0, -0.3f, 1f); //正面1m 下に30cm (膝より上にBendGoalが来ると計算が反転して膝が下向いてしまう) //Vector3 leftHandUp = Vector3.Cross(GuessFootToKneeAxis(ik.references.leftCalf,ik.references.leftThigh), ik.solver.leftLeg.palmToThumbAxis); leftKneeAdjusterTransform.rotation = ik.references.leftCalf.rotation;// QuaTools.MatchRotation(LeftKneeTransform.rotation * Quaternion.LookRotation(settings.footTrackerForward, settings.footTrackerUp), settings.footTrackerForward, settings.footTrackerUp, Vector3.zero, leftHandUp); ik.solver.leftLeg.bendGoal = leftKneeAdjusterTransform; ik.solver.leftLeg.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftKneeTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftLeg.bendGoalWeight = weight; }); } ik.solver.rightLeg.bendGoalWeight = 0.0f; if (RightFootTransform != null) { var rightBendGoalTarget = CalibrateLeg(settings, RightFootTransform, ik.solver.rightLeg, (ik.references.rightToes != null ? ik.references.rightToes : ik.references.rightFoot), hmdForwardAngle, ik.references.root.forward, false); ik.solver.rightLeg.bendGoal = rightBendGoalTarget; ik.solver.rightLeg.bendGoalWeight = 0.0f; } if (RightKneeTransform != null) { Transform rightKneeAdjusterTransform = ik.solver.rightLeg.bendGoal == null ? (new GameObject("rightKneeAdjuster")).transform : ik.solver.rightLeg.bendGoal; rightKneeAdjusterTransform.parent = RightKneeTransform; rightKneeAdjusterTransform.position = ik.references.rightCalf.position;// RightKneeTransform.position + RightKneeTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; rightKneeAdjusterTransform.transform.localPosition += new Vector3(0, -0.3f, 1f); //正面1m 下に30cm (膝より上にBendGoalが来ると計算が反転して膝が下向いてしまう) //Vector3 rightHandUp = Vector3.Cross(GuessFootToKneeAxis(ik.references.rightCalf,ik.references.rightThigh), ik.solver.rightLeg.palmToThumbAxis); rightKneeAdjusterTransform.rotation = ik.references.rightCalf.rotation;// QuaTools.MatchRotation(RightKneeTransform.rotation * Quaternion.LookRotation(settings.footTrackerForward, settings.footTrackerUp), settings.footTrackerForward, settings.footTrackerUp, Vector3.zero, rightHandUp); ik.solver.rightLeg.bendGoal = rightKneeAdjusterTransform; ik.solver.rightLeg.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 RightKneeTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightLeg.bendGoalWeight = weight; }); } // Root controller bool addRootController = PelvisTransform != null || (LeftFootTransform != null && RightFootTransform != null); var rootController = ik.references.root.GetComponent<VRIKRootController>(); if (addRootController) { if (rootController == null) rootController = ik.references.root.gameObject.AddComponent<VRIKRootController>(); //rootController.pelvisTarget = ik.solver.spine.pelvisTarget; //rootController.leftFootTarget = ik.solver.leftLeg.target; //rootController.rightFootTarget = ik.solver.rightLeg.target; rootController.Calibrate(); } else { if (rootController != null) GameObject.Destroy(rootController); } if (PelvisTransform != null) { pelvisOffsetHeight = ik.references.pelvis.position.y; pelvisOffsetTransform = pelvisOffsetAdjuster; if (LeftFootTransform != null && RightFootTransform != null) { pelvisOffsetAdjuster.localPosition = new Vector3(0, pelvisOffsetDivide == 0 ? 0 : -(ik.references.pelvis.position.y / pelvisOffsetDivide), 0); } } // Additional solver settings ik.solver.spine.minHeadHeight = 0f; ik.solver.locomotion.weight = PelvisTransform == null && LeftFootTransform == null && RightFootTransform == null ? 1f : 0f; } public static IEnumerator CalibrateFixedHand(Transform handTrackerRoot, Transform footTrackerRoot, VRIK ik, VRIKCalibrator.Settings settings, Vector3 LeftHandOffset, Vector3 RightHandOffset, TrackingPoint HMDTrackingPoint, TrackingPoint PelvisTrackingPoint = null, TrackingPoint LeftHandTrackingPoint = null, TrackingPoint RightHandTrackingPoint = null, TrackingPoint LeftFootTrackingPoint = null, TrackingPoint RightFootTrackingPoint = null, TrackingPoint LeftElbowTrackingPoint = null, TrackingPoint RightElbowTrackingPoint = null, TrackingPoint LeftKneeTrackingPoint = null, TrackingPoint RightKneeTrackingPoint = null, TrackingPoint ChestTrackingPoint = null) { Transform HMDTransform = HMDTrackingPoint?.TargetTransform; Transform PelvisTransform = PelvisTrackingPoint?.TargetTransform; Transform LeftHandTransform = LeftHandTrackingPoint?.TargetTransform; Transform RightHandTransform = RightHandTrackingPoint?.TargetTransform; Transform LeftFootTransform = LeftFootTrackingPoint?.TargetTransform; Transform RightFootTransform = RightFootTrackingPoint?.TargetTransform; Transform LeftElbowTransform = LeftElbowTrackingPoint?.TargetTransform; Transform RightElbowTransform = RightElbowTrackingPoint?.TargetTransform; Transform LeftKneeTransform = LeftKneeTrackingPoint?.TargetTransform; Transform RightKneeTransform = RightKneeTrackingPoint?.TargetTransform; Transform ChestTransform = ChestTrackingPoint?.TargetTransform; if (!ik.solver.initiated) { Debug.LogError("[Calib Fail] Can not calibrate before VRIK has initiated."); yield break; } if (HMDTransform == null) { Debug.LogError("[Calib Fail] Can not calibrate VRIK without the head tracker."); yield break; } //トラッカーのルートスケールを初期値に戻す handTrackerRoot.localScale = new Vector3(1.0f, 1.0f, 1.0f); footTrackerRoot.localScale = new Vector3(1.0f, 1.0f, 1.0f); handTrackerRoot.position = Vector3.zero; footTrackerRoot.position = Vector3.zero; //腰トラ下げ用空Object var pelvisOffsetAdjuster = new GameObject("PelvisOffsetAdjuster").transform; pelvisOffsetAdjuster.parent = footTrackerRoot; HandSwapManagerScript handSwapManagerScript = GameObject.Find("HandSwapManager").GetComponent<HandSwapManagerScript>(); handSwapManagerScript.WPFLeftHandTransform = LeftHandTransform; //左手登録 handSwapManagerScript.WPFRightHandTransform = RightHandTransform; //右手登録 //それぞれのトラッカーを正しいルートに移動 if (HMDTransform != null) HMDTransform.parent = handTrackerRoot; if (LeftHandTransform != null) LeftHandTransform.parent = handTrackerRoot; if (RightHandTransform != null) RightHandTransform.parent = handTrackerRoot; if (PelvisTransform != null) PelvisTransform.parent = pelvisOffsetAdjuster; if (LeftFootTransform != null) LeftFootTransform.parent = footTrackerRoot; if (RightFootTransform != null) RightFootTransform.parent = footTrackerRoot; if (LeftElbowTransform != null) LeftElbowTransform.parent = handTrackerRoot; if (RightElbowTransform != null) RightElbowTransform.parent = handTrackerRoot; if (LeftKneeTransform != null) LeftKneeTransform.parent = footTrackerRoot; if (RightKneeTransform != null) RightKneeTransform.parent = footTrackerRoot; if (ChestTransform != null) ChestTransform.parent = handTrackerRoot; //コントローラーの場合手首までのオフセットを追加 if (LeftHandOffset == Vector3.zero) { var offset = new GameObject("LeftWristOffset"); offset.transform.parent = LeftHandTransform; offset.transform.localPosition = new Vector3(-0.04f, 0.04f, -0.15f); offset.transform.localRotation = Quaternion.Euler(60, 0, 90); offset.transform.localScale = Vector3.one; LeftHandTransform = offset.transform; } if (RightHandOffset == Vector3.zero) { var offset = new GameObject("RightWristOffset"); offset.transform.parent = RightHandTransform; offset.transform.localPosition = new Vector3(0.04f, 0.04f, -0.15f); offset.transform.localRotation = Quaternion.Euler(60, 0, -90); offset.transform.localScale = Vector3.one; RightHandTransform = offset.transform; } //モデルの体の中心を取っておく var modelcenterposition = Vector3.Lerp(ik.references.leftHand.position, ik.references.rightHand.position, 0.5f); modelcenterposition = new Vector3(modelcenterposition.x, ik.references.root.position.y, modelcenterposition.z); var modelcenterdistance = Vector3.Distance(ik.references.root.position, modelcenterposition); // モデルのポジションを手と手の中心位置に移動 var centerposition = Vector3.Lerp(LeftHandTransform.position, RightHandTransform.position, 0.5f); ik.references.root.position = new Vector3(centerposition.x, ik.references.root.position.y, centerposition.z); yield return new WaitForEndOfFrame(); //それぞれのトラッカーに手のオフセットを適用 //トラッカーの角度は 0,-90,-90 が正位置(手の甲に付けてLED部を外側に向けたとき) //トラッカー zをマイナス方向に動かすとトラッカーの底面に向かって進む //角度補正LookAt(左手なら右のトラッカーに向けた)後 zを+方向は体中心(左手なら右手の方向)に向かって進む //xを-方向は体の正面に向かって進む //先にトラッカー底面に向かってのオフセットを両手に適用する var leftWrist = new GameObject("LeftWristOffset").transform; leftWrist.parent = LeftHandTransform; leftWrist.localPosition = new Vector3(0, 0, -LeftHandOffset.y); leftWrist.localRotation = Quaternion.Euler(Vector3.zero); var rightWrist = new GameObject("RightWristOffset").transform; rightWrist.parent = RightHandTransform; rightWrist.localPosition = new Vector3(0, 0, -RightHandOffset.y); rightWrist.localRotation = Quaternion.Euler(Vector3.zero); //お互いのトラッカー同士を向き合わせてオフセットを適用する leftWrist.LookAt(rightWrist ?? RightHandTransform); leftWrist.localPosition += leftWrist.localRotation * new Vector3(0, 0, LeftHandOffset.z); rightWrist.LookAt(leftWrist ?? LeftHandTransform); rightWrist.localPosition += rightWrist.localRotation * new Vector3(0, 0, RightHandOffset.z); //両手のxをマイナス方向が正面なので体を回転させる Vector3 hmdForwardAngle = leftWrist.rotation * new Vector3(-1, 0, 0); hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); //回転した分トラッカーも回転させる if (LeftHandOffset != Vector3.zero) // Vector3 (IsEnable, ToTrackerBottom, ToBodySide) { leftWrist.eulerAngles = new Vector3(0, -90, 90); //トラッカー補正後の角度 leftWrist.RotateAround(leftWrist.position, Vector3.up, ik.references.root.rotation.eulerAngles.y); //体の回転分を引く LeftHandTransform = leftWrist; } if (RightHandOffset != Vector3.zero) // Vector3 (IsEnable, ToTrackerBottom, ToBodySide) { rightWrist.eulerAngles = new Vector3(180, -90, 90); //トラッカー補正後の角度 rightWrist.RotateAround(rightWrist.position, Vector3.up, ik.references.root.rotation.eulerAngles.y); //体の回転分を引く RightHandTransform = rightWrist; } yield return new WaitForEndOfFrame(); // 手のトラッカー全体のスケールを手の位置に合わせる var modelHandDistance = Vector3.Distance(ik.references.leftHand.position, ik.references.rightHand.position); var realHandDistance = Vector3.Distance(LeftHandTransform.position, RightHandTransform.position); var wscale = modelHandDistance / realHandDistance; handTrackerRoot.localScale = new Vector3(wscale, wscale, wscale); // モデルのポジションを再度手と手の中心位置に移動 centerposition = Vector3.Lerp(LeftHandTransform.position, RightHandTransform.position, 0.5f); ik.references.root.position = new Vector3(centerposition.x, ik.references.root.position.y, centerposition.z) + ik.references.root.forward * modelcenterdistance; //hmdForwardAngle = HMDTransform.rotation * settings.headTrackerForward; //hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); // 腰のトラッカー全体のスケール footTrackerRoot.localScale = new Vector3(wscale, wscale, wscale); yield return new WaitForEndOfFrame(); //トラッカー全体を手の高さにオフセット var modelHandHeight = (ik.references.leftHand.position.y + ik.references.rightHand.position.y) / 2f; var realHandHeight = (LeftHandTransform.position.y + RightHandTransform.position.y) / 2f; var hoffset = new Vector3(0, modelHandHeight - realHandHeight, 0); handTrackerRoot.position = hoffset; footTrackerRoot.position = hoffset; yield return new WaitForEndOfFrame(); //yield break; // Head Transform hmdAdjusterTransform = ik.solver.spine.headTarget == null ? (new GameObject("hmdAdjuster")).transform : ik.solver.spine.headTarget; hmdAdjusterTransform.parent = HMDTransform; hmdAdjusterTransform.position = ik.references.head.position; //HMDTransform.position + HMDTransform.rotation * Quaternion.LookRotation(settings.headTrackerForward, settings.headTrackerUp) * settings.headOffset; //hmdAdjusterTransform.localPosition = new Vector3(0, hmdAdjusterTransform.localPosition.y, -0.15f); hmdAdjusterTransform.rotation = ik.references.head.rotation; ik.solver.spine.headTarget = hmdAdjusterTransform; ik.solver.spine.headClampWeight = 0.38f; //TrackingWatcherにWeight設定用アクションを設定 HMDTransform.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); // Body if (PelvisTransform != null) { Transform pelvisAdjusterTransform = ik.solver.spine.pelvisTarget == null ? (new GameObject("pelvisAdjuster")).transform : ik.solver.spine.pelvisTarget; pelvisAdjusterTransform.parent = PelvisTransform; pelvisAdjusterTransform.position = ik.references.pelvis.position; pelvisAdjusterTransform.rotation = ik.references.pelvis.rotation; ik.solver.spine.pelvisTarget = pelvisAdjusterTransform; ik.solver.spine.pelvisPositionWeight = 1f; ik.solver.spine.pelvisRotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 PelvisTransform.GetComponentInChildren<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.spine.pelvisPositionWeight = weight; ik.solver.spine.pelvisRotationWeight = weight; }); ik.solver.plantFeet = false; ik.solver.spine.neckStiffness = 0f; ik.solver.spine.maxRootAngle = 180f; } else if (LeftFootTransform != null && RightFootTransform != null) { ik.solver.plantFeet = false; ik.solver.spine.maxRootAngle = 0f; } ik.solver.spine.maintainPelvisPosition = 0.0f; yield return new WaitForEndOfFrame(); // Chest if (ChestTransform != null && ik.references.chest != null) { var chestBone = ik.references.chest; var bendGoal = new GameObject("ChestBendGoal").transform; bendGoal.parent = ChestTransform; bendGoal.position = chestBone.position + ik.references.root.forward * 0.5f; ik.solver.spine.chestGoal = bendGoal; ik.solver.spine.chestGoalWeight = 1.0f; ik.solver.spine.chestClampWeight = 0f; } // Left Hand if (LeftHandTransform != null) { Transform leftHandAdjusterTransform = ik.solver.leftArm.target == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.target; leftHandAdjusterTransform.parent = LeftHandTransform; leftHandAdjusterTransform.position = LeftHandTransform.position + LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = new Vector3(0, 1, 0); leftHandAdjusterTransform.rotation = QuaTools.MatchRotation(LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.target = leftHandAdjusterTransform; ik.solver.leftArm.positionWeight = 1f; ik.solver.leftArm.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 LeftHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.positionWeight = weight; ik.solver.leftArm.rotationWeight = weight; }); } else { ik.solver.leftArm.positionWeight = 0f; ik.solver.leftArm.rotationWeight = 0f; } // Right Hand if (RightHandTransform != null) { Transform rightHandAdjusterTransform = ik.solver.rightArm.target == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.target; rightHandAdjusterTransform.parent = RightHandTransform; rightHandAdjusterTransform.position = RightHandTransform.position + RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = new Vector3(0, 1, 0); rightHandAdjusterTransform.rotation = QuaTools.MatchRotation(RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.target = rightHandAdjusterTransform; ik.solver.rightArm.positionWeight = 1f; ik.solver.rightArm.rotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 RightHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.positionWeight = weight; ik.solver.rightArm.rotationWeight = weight; }); } else { ik.solver.rightArm.positionWeight = 0f; ik.solver.rightArm.rotationWeight = 0f; } // Left Elbow if (LeftElbowTransform != null) { Transform leftElbowAdjusterTransform = ik.solver.leftArm.bendGoal == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.bendGoal; leftElbowAdjusterTransform.parent = LeftElbowTransform; leftElbowAdjusterTransform.position = LeftElbowTransform.position + LeftElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = Vector3.Cross(ik.solver.leftArm.wristToPalmAxis, ik.solver.leftArm.palmToThumbAxis); leftElbowAdjusterTransform.rotation = QuaTools.MatchRotation(LeftElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.bendGoal = leftElbowAdjusterTransform; ik.solver.leftArm.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftElbowTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.bendGoalWeight = weight; }); } else { ik.solver.leftArm.bendGoalWeight = 0.0f; } // Right Elbow if (RightElbowTransform != null) { Transform rightElbowAdjusterTransform = ik.solver.rightArm.bendGoal == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.bendGoal; rightElbowAdjusterTransform.parent = RightElbowTransform; rightElbowAdjusterTransform.position = RightElbowTransform.position + RightElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = Vector3.Cross(ik.solver.rightArm.wristToPalmAxis, ik.solver.rightArm.palmToThumbAxis); rightElbowAdjusterTransform.rotation = QuaTools.MatchRotation(RightElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.bendGoal = rightElbowAdjusterTransform; ik.solver.rightArm.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 RightElbowTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.bendGoalWeight = weight; }); } else { ik.solver.rightArm.bendGoalWeight = 0.0f; } // Legs ik.solver.leftLeg.bendGoalWeight = 0.0f; if (LeftFootTransform != null) { var leftBendGoalTarget = CalibrateLeg(settings, LeftFootTransform, ik.solver.leftLeg, (ik.references.leftToes != null ? ik.references.leftToes : ik.references.leftFoot), hmdForwardAngle, ik.references.root.forward, true); ik.solver.leftLeg.bendGoal = leftBendGoalTarget; ik.solver.leftLeg.bendGoalWeight = 0.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftFootTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); } if (LeftKneeTransform != null) { Transform leftKneeAdjusterTransform = ik.solver.leftLeg.bendGoal == null ? (new GameObject("leftKneeAdjuster")).transform : ik.solver.leftLeg.bendGoal; leftKneeAdjusterTransform.parent = LeftKneeTransform; leftKneeAdjusterTransform.position = ik.references.leftCalf.position;// LeftKneeTransform.position + LeftKneeTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; leftKneeAdjusterTransform.transform.localPosition += new Vector3(0, -0.3f, 1f); //正面1m 下に30cm (膝より上にBendGoalが来ると計算が反転して膝が下向いてしまう) //Vector3 leftHandUp = Vector3.Cross(GuessFootToKneeAxis(ik.references.leftCalf,ik.references.leftThigh), ik.solver.leftLeg.palmToThumbAxis); leftKneeAdjusterTransform.rotation = ik.references.leftCalf.rotation;// QuaTools.MatchRotation(LeftKneeTransform.rotation * Quaternion.LookRotation(settings.footTrackerForward, settings.footTrackerUp), settings.footTrackerForward, settings.footTrackerUp, Vector3.zero, leftHandUp); ik.solver.leftLeg.bendGoal = leftKneeAdjusterTransform; ik.solver.leftLeg.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftKneeTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftLeg.bendGoalWeight = weight; }); } ik.solver.rightLeg.bendGoalWeight = 0.0f; if (RightFootTransform != null) { var rightBendGoalTarget = CalibrateLeg(settings, RightFootTransform, ik.solver.rightLeg, (ik.references.rightToes != null ? ik.references.rightToes : ik.references.rightFoot), hmdForwardAngle, ik.references.root.forward, false); ik.solver.rightLeg.bendGoal = rightBendGoalTarget; ik.solver.rightLeg.bendGoalWeight = 0.0f; //TrackingWatcherにWeight設定用アクションを設定 RightFootTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); } if (RightKneeTransform != null) { Transform rightKneeAdjusterTransform = ik.solver.rightLeg.bendGoal == null ? (new GameObject("rightKneeAdjuster")).transform : ik.solver.rightLeg.bendGoal; rightKneeAdjusterTransform.parent = RightKneeTransform; rightKneeAdjusterTransform.position = ik.references.rightCalf.position;// RightKneeTransform.position + RightKneeTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; rightKneeAdjusterTransform.transform.localPosition += new Vector3(0, -0.3f, 1f); //正面1m 下に30cm (膝より上にBendGoalが来ると計算が反転して膝が下向いてしまう) //Vector3 rightHandUp = Vector3.Cross(GuessFootToKneeAxis(ik.references.rightCalf,ik.references.rightThigh), ik.solver.rightLeg.palmToThumbAxis); rightKneeAdjusterTransform.rotation = ik.references.rightCalf.rotation;// QuaTools.MatchRotation(RightKneeTransform.rotation * Quaternion.LookRotation(settings.footTrackerForward, settings.footTrackerUp), settings.footTrackerForward, settings.footTrackerUp, Vector3.zero, rightHandUp); ik.solver.rightLeg.bendGoal = rightKneeAdjusterTransform; ik.solver.rightLeg.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 RightKneeTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightLeg.bendGoalWeight = weight; }); } // Root controller bool addRootController = PelvisTransform != null || (LeftFootTransform != null && RightFootTransform != null); var rootController = ik.references.root.GetComponent<VRIKRootController>(); if (addRootController) { if (rootController == null) rootController = ik.references.root.gameObject.AddComponent<VRIKRootController>(); //rootController.pelvisTarget = ik.solver.spine.pelvisTarget; //rootController.leftFootTarget = ik.solver.leftLeg.target; //rootController.rightFootTarget = ik.solver.rightLeg.target; rootController.Calibrate(); } else { if (rootController != null) GameObject.Destroy(rootController); } if (PelvisTransform != null) { pelvisOffsetHeight = ik.references.pelvis.position.y; pelvisOffsetTransform = pelvisOffsetAdjuster; if (LeftFootTransform != null && RightFootTransform != null) { pelvisOffsetAdjuster.localPosition = new Vector3(0, pelvisOffsetDivide == 0 ? 0 : -(ik.references.pelvis.position.y / pelvisOffsetDivide), 0); } } // Additional solver settings ik.solver.spine.minHeadHeight = 0f; ik.solver.locomotion.weight = PelvisTransform == null && LeftFootTransform == null && RightFootTransform == null ? 1f : 0f; } public static IEnumerator CalibrateFixedHandWithGround(Transform handTrackerRoot, Transform footTrackerRoot, VRIK ik, VRIKCalibrator.Settings settings, Vector3 LeftHandOffset, Vector3 RightHandOffset, TrackingPoint HMDTrackingPoint, TrackingPoint PelvisTrackingPoint = null, TrackingPoint LeftHandTrackingPoint = null, TrackingPoint RightHandTrackingPoint = null, TrackingPoint LeftFootTrackingPoint = null, TrackingPoint RightFootTrackingPoint = null, TrackingPoint LeftElbowTrackingPoint = null, TrackingPoint RightElbowTrackingPoint = null, TrackingPoint LeftKneeTrackingPoint = null, TrackingPoint RightKneeTrackingPoint = null, TrackingPoint ChestTrackingPoint = null) { Transform HMDTransform = HMDTrackingPoint?.TargetTransform; Transform PelvisTransform = PelvisTrackingPoint?.TargetTransform; Transform LeftHandTransform = LeftHandTrackingPoint?.TargetTransform; Transform RightHandTransform = RightHandTrackingPoint?.TargetTransform; Transform LeftFootTransform = LeftFootTrackingPoint?.TargetTransform; Transform RightFootTransform = RightFootTrackingPoint?.TargetTransform; Transform LeftElbowTransform = LeftElbowTrackingPoint?.TargetTransform; Transform RightElbowTransform = RightElbowTrackingPoint?.TargetTransform; Transform LeftKneeTransform = LeftKneeTrackingPoint?.TargetTransform; Transform RightKneeTransform = RightKneeTrackingPoint?.TargetTransform; Transform ChestTransform = ChestTrackingPoint?.TargetTransform; if (!ik.solver.initiated) { Debug.LogError("[Calib Fail] Can not calibrate before VRIK has initiated."); yield break; } if (HMDTransform == null) { Debug.LogError("[Calib Fail] Can not calibrate VRIK without the head tracker."); yield break; } //トラッカーのルートスケールを初期値に戻す handTrackerRoot.localScale = new Vector3(1.0f, 1.0f, 1.0f); footTrackerRoot.localScale = new Vector3(1.0f, 1.0f, 1.0f); handTrackerRoot.position = Vector3.zero; footTrackerRoot.position = Vector3.zero; //腰トラ下げ用空Object var pelvisOffsetAdjuster = new GameObject("PelvisOffsetAdjuster").transform; pelvisOffsetAdjuster.parent = footTrackerRoot; HandSwapManagerScript handSwapManagerScript = GameObject.Find("HandSwapManager").GetComponent<HandSwapManagerScript>(); handSwapManagerScript.WPFLeftHandTransform = LeftHandTransform; //左手登録 handSwapManagerScript.WPFRightHandTransform = RightHandTransform; //右手登録 //それぞれのトラッカーを正しいルートに移動 if (HMDTransform != null) HMDTransform.parent = handTrackerRoot; if (LeftHandTransform != null) LeftHandTransform.parent = handTrackerRoot; if (RightHandTransform != null) RightHandTransform.parent = handTrackerRoot; if (PelvisTransform != null) PelvisTransform.parent = pelvisOffsetAdjuster; if (LeftFootTransform != null) LeftFootTransform.parent = footTrackerRoot; if (RightFootTransform != null) RightFootTransform.parent = footTrackerRoot; if (LeftElbowTransform != null) LeftElbowTransform.parent = handTrackerRoot; if (RightElbowTransform != null) RightElbowTransform.parent = handTrackerRoot; if (LeftKneeTransform != null) LeftKneeTransform.parent = footTrackerRoot; if (RightKneeTransform != null) RightKneeTransform.parent = footTrackerRoot; if (ChestTransform != null) ChestTransform.parent = handTrackerRoot; //コントローラーの場合手首までのオフセットを追加 if (LeftHandOffset == Vector3.zero) { var offset = new GameObject("LeftWristOffset"); offset.transform.parent = LeftHandTransform; offset.transform.localPosition = new Vector3(-0.04f, 0.04f, -0.15f); offset.transform.localRotation = Quaternion.Euler(60, 0, 90); offset.transform.localScale = Vector3.one; LeftHandTransform = offset.transform; } if (RightHandOffset == Vector3.zero) { var offset = new GameObject("RightWristOffset"); offset.transform.parent = RightHandTransform; offset.transform.localPosition = new Vector3(0.04f, 0.04f, -0.15f); offset.transform.localRotation = Quaternion.Euler(60, 0, -90); offset.transform.localScale = Vector3.one; RightHandTransform = offset.transform; } //モデルの体の中心を取っておく var modelcenterposition = Vector3.Lerp(ik.references.leftHand.position, ik.references.rightHand.position, 0.5f); modelcenterposition = new Vector3(modelcenterposition.x, ik.references.root.position.y, modelcenterposition.z); var modelcenterdistance = Vector3.Distance(ik.references.root.position, modelcenterposition); // モデルのポジションを手と手の中心位置に移動 var centerposition = Vector3.Lerp(LeftHandTransform.position, RightHandTransform.position, 0.5f); ik.references.root.position = new Vector3(centerposition.x, ik.references.root.position.y, centerposition.z); yield return new WaitForEndOfFrame(); //それぞれのトラッカーに手のオフセットを適用 //トラッカーの角度は 0,-90,-90 が正位置(手の甲に付けてLED部を外側に向けたとき) //トラッカー zをマイナス方向に動かすとトラッカーの底面に向かって進む //角度補正LookAt(左手なら右のトラッカーに向けた)後 zを+方向は体中心(左手なら右手の方向)に向かって進む //xを-方向は体の正面に向かって進む //先にトラッカー底面に向かってのオフセットを両手に適用する var leftWrist = new GameObject("LeftWristOffset").transform; leftWrist.parent = LeftHandTransform; leftWrist.localPosition = new Vector3(0, 0, -LeftHandOffset.y); leftWrist.localRotation = Quaternion.Euler(Vector3.zero); var rightWrist = new GameObject("RightWristOffset").transform; rightWrist.parent = RightHandTransform; rightWrist.localPosition = new Vector3(0, 0, -RightHandOffset.y); rightWrist.localRotation = Quaternion.Euler(Vector3.zero); //お互いのトラッカー同士を向き合わせてオフセットを適用する leftWrist.LookAt(rightWrist ?? RightHandTransform); leftWrist.localPosition += leftWrist.localRotation * new Vector3(0, 0, LeftHandOffset.z); rightWrist.LookAt(leftWrist ?? LeftHandTransform); rightWrist.localPosition += rightWrist.localRotation * new Vector3(0, 0, RightHandOffset.z); //両手のxをマイナス方向が正面なので体を回転させる Vector3 hmdForwardAngle = leftWrist.rotation * new Vector3(-1, 0, 0); hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); //回転した分トラッカーも回転させる if (LeftHandOffset != Vector3.zero) // Vector3 (IsEnable, ToTrackerBottom, ToBodySide) { leftWrist.eulerAngles = new Vector3(0, -90, 90); //トラッカー補正後の角度 leftWrist.RotateAround(leftWrist.position, Vector3.up, ik.references.root.rotation.eulerAngles.y); //体の回転分を引く LeftHandTransform = leftWrist; } if (RightHandOffset != Vector3.zero) // Vector3 (IsEnable, ToTrackerBottom, ToBodySide) { rightWrist.eulerAngles = new Vector3(180, -90, 90); //トラッカー補正後の角度 rightWrist.RotateAround(rightWrist.position, Vector3.up, ik.references.root.rotation.eulerAngles.y); //体の回転分を引く RightHandTransform = rightWrist; } yield return new WaitForEndOfFrame(); // 手のトラッカー全体のスケールを手の位置に合わせる var modelHandDistance = Vector3.Distance(ik.references.leftHand.position, ik.references.rightHand.position); var realHandDistance = Vector3.Distance(LeftHandTransform.position, RightHandTransform.position); var wscale = modelHandDistance / realHandDistance; handTrackerRoot.localScale = new Vector3(wscale, wscale, wscale); // モデルのポジションを再度手と手の中心位置に移動 centerposition = Vector3.Lerp(LeftHandTransform.position, RightHandTransform.position, 0.5f); ik.references.root.position = new Vector3(centerposition.x, ik.references.root.position.y, centerposition.z) + ik.references.root.forward * modelcenterdistance; //hmdForwardAngle = HMDTransform.rotation * settings.headTrackerForward; //hmdForwardAngle.y = 0f; ik.references.root.rotation = Quaternion.LookRotation(hmdForwardAngle); // 腰のトラッカー全体のスケール footTrackerRoot.localScale = new Vector3(wscale, wscale, wscale); yield return new WaitForEndOfFrame(); //トラッカー全体を手の高さにオフセット var modelHandHeight = (ik.references.leftHand.position.y + ik.references.rightHand.position.y) / 2f; var realHandHeight = (LeftHandTransform.position.y + RightHandTransform.position.y) / 2f; var hoffset = new Vector3(0, modelHandHeight - realHandHeight, 0); handTrackerRoot.position = hoffset; footTrackerRoot.position = hoffset; yield return new WaitForEndOfFrame(); //yield break; // Head Transform hmdAdjusterTransform = ik.solver.spine.headTarget == null ? (new GameObject("hmdAdjuster")).transform : ik.solver.spine.headTarget; hmdAdjusterTransform.parent = HMDTransform; hmdAdjusterTransform.position = ik.references.head.position; //HMDTransform.position + HMDTransform.rotation * Quaternion.LookRotation(settings.headTrackerForward, settings.headTrackerUp) * settings.headOffset; //hmdAdjusterTransform.localPosition = new Vector3(0, hmdAdjusterTransform.localPosition.y, -0.15f); hmdAdjusterTransform.rotation = ik.references.head.rotation; ik.solver.spine.headTarget = hmdAdjusterTransform; ik.solver.spine.headClampWeight = 0.38f; //TrackingWatcherにWeight設定用アクションを設定 HMDTransform.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); // Body if (PelvisTransform != null) { Transform pelvisAdjusterTransform = ik.solver.spine.pelvisTarget == null ? (new GameObject("pelvisAdjuster")).transform : ik.solver.spine.pelvisTarget; pelvisAdjusterTransform.parent = PelvisTransform; pelvisAdjusterTransform.position = ik.references.pelvis.position; pelvisAdjusterTransform.rotation = ik.references.pelvis.rotation; ik.solver.spine.pelvisTarget = pelvisAdjusterTransform; ik.solver.spine.pelvisPositionWeight = 1f; ik.solver.spine.pelvisRotationWeight = 1f; //TrackingWatcherにWeight設定用アクションを設定 PelvisTransform.GetComponentInChildren<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.spine.pelvisPositionWeight = weight; ik.solver.spine.pelvisRotationWeight = weight; }); ik.solver.plantFeet = false; ik.solver.spine.neckStiffness = 0f; ik.solver.spine.maxRootAngle = 180f; } else if (LeftFootTransform != null && RightFootTransform != null) { ik.solver.plantFeet = false; ik.solver.spine.maxRootAngle = 0f; } ik.solver.spine.maintainPelvisPosition = 0.0f; yield return new WaitForEndOfFrame(); // Chest if (ChestTransform != null && ik.references.chest != null) { var chestBone = ik.references.chest; var bendGoal = new GameObject("ChestBendGoal").transform; bendGoal.parent = ChestTransform; bendGoal.position = chestBone.position + ik.references.root.forward * 0.5f; ik.solver.spine.chestGoal = bendGoal; ik.solver.spine.chestGoalWeight = 1.0f; ik.solver.spine.chestClampWeight = 0f; } // Left Hand if (LeftHandTransform != null) { Transform leftHandAdjusterTransform = ik.solver.leftArm.target == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.target; leftHandAdjusterTransform.parent = LeftHandTransform; leftHandAdjusterTransform.position = LeftHandTransform.position + LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = new Vector3(0, 1, 0); leftHandAdjusterTransform.rotation = QuaTools.MatchRotation(LeftHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.target = leftHandAdjusterTransform; //TrackingWatcherにWeight設定用アクションを設定 LeftHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.positionWeight = weight; ik.solver.leftArm.rotationWeight = weight; }); } else { ik.solver.leftArm.positionWeight = 0f; ik.solver.leftArm.rotationWeight = 0f; } // Right Hand if (RightHandTransform != null) { Transform rightHandAdjusterTransform = ik.solver.rightArm.target == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.target; rightHandAdjusterTransform.parent = RightHandTransform; rightHandAdjusterTransform.position = RightHandTransform.position + RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = new Vector3(0, 1, 0); rightHandAdjusterTransform.rotation = QuaTools.MatchRotation(RightHandTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.target = rightHandAdjusterTransform; //TrackingWatcherにWeight設定用アクションを設定 RightHandTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.positionWeight = weight; ik.solver.rightArm.rotationWeight = weight; }); } else { ik.solver.rightArm.positionWeight = 0f; ik.solver.rightArm.rotationWeight = 0f; } // Left Elbow if (LeftElbowTransform != null) { Transform leftElbowAdjusterTransform = ik.solver.leftArm.bendGoal == null ? (new GameObject("leftHandAdjuster")).transform : ik.solver.leftArm.bendGoal; leftElbowAdjusterTransform.parent = LeftElbowTransform; leftElbowAdjusterTransform.position = LeftElbowTransform.position + LeftElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 leftHandUp = new Vector3(0, 1, 0); leftElbowAdjusterTransform.rotation = QuaTools.MatchRotation(LeftElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.leftArm.wristToPalmAxis, leftHandUp); ik.solver.leftArm.bendGoal = leftElbowAdjusterTransform; ik.solver.leftArm.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftElbowTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftArm.bendGoalWeight = weight; }); } else { ik.solver.leftArm.bendGoalWeight = 0.0f; } // Right Elbow if (RightElbowTransform != null) { Transform rightElbowAdjusterTransform = ik.solver.rightArm.bendGoal == null ? (new GameObject("rightHandAdjuster")).transform : ik.solver.rightArm.bendGoal; rightElbowAdjusterTransform.parent = RightElbowTransform; rightElbowAdjusterTransform.position = RightElbowTransform.position + RightElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; Vector3 rightHandUp = new Vector3(0, 1, 0); rightElbowAdjusterTransform.rotation = QuaTools.MatchRotation(RightElbowTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp), settings.handTrackerForward, settings.handTrackerUp, ik.solver.rightArm.wristToPalmAxis, rightHandUp); ik.solver.rightArm.bendGoal = rightElbowAdjusterTransform; ik.solver.rightArm.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 RightElbowTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightArm.bendGoalWeight = weight; }); } else { ik.solver.rightArm.bendGoalWeight = 0.0f; } // Legs ik.solver.leftLeg.bendGoalWeight = 0.0f; if (LeftFootTransform != null) { var leftBendGoalTarget = CalibrateLeg(settings, LeftFootTransform, ik.solver.leftLeg, (ik.references.leftToes != null ? ik.references.leftToes : ik.references.leftFoot), hmdForwardAngle, ik.references.root.forward, true); ik.solver.leftLeg.bendGoal = leftBendGoalTarget; ik.solver.leftLeg.bendGoalWeight = 0.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftFootTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); } if (LeftKneeTransform != null) { Transform leftKneeAdjusterTransform = ik.solver.leftLeg.bendGoal == null ? (new GameObject("leftKneeAdjuster")).transform : ik.solver.leftLeg.bendGoal; leftKneeAdjusterTransform.parent = LeftKneeTransform; leftKneeAdjusterTransform.position = ik.references.leftCalf.position;// LeftKneeTransform.position + LeftKneeTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; leftKneeAdjusterTransform.transform.localPosition += new Vector3(0, -0.3f, 1f); //正面1m 下に30cm (膝より上にBendGoalが来ると計算が反転して膝が下向いてしまう) //Vector3 leftHandUp = Vector3.Cross(GuessFootToKneeAxis(ik.references.leftCalf,ik.references.leftThigh), ik.solver.leftLeg.palmToThumbAxis); leftKneeAdjusterTransform.rotation = ik.references.leftCalf.rotation;// QuaTools.MatchRotation(LeftKneeTransform.rotation * Quaternion.LookRotation(settings.footTrackerForward, settings.footTrackerUp), settings.footTrackerForward, settings.footTrackerUp, Vector3.zero, leftHandUp); ik.solver.leftLeg.bendGoal = leftKneeAdjusterTransform; ik.solver.leftLeg.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 LeftKneeTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.leftLeg.bendGoalWeight = weight; }); } ik.solver.rightLeg.bendGoalWeight = 0.0f; if (RightFootTransform != null) { var rightBendGoalTarget = CalibrateLeg(settings, RightFootTransform, ik.solver.rightLeg, (ik.references.rightToes != null ? ik.references.rightToes : ik.references.rightFoot), hmdForwardAngle, ik.references.root.forward, false); ik.solver.rightLeg.bendGoal = rightBendGoalTarget; ik.solver.rightLeg.bendGoalWeight = 0.0f; RightFootTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { //Do noting }); } if (RightKneeTransform != null) { Transform rightKneeAdjusterTransform = ik.solver.rightLeg.bendGoal == null ? (new GameObject("rightKneeAdjuster")).transform : ik.solver.rightLeg.bendGoal; rightKneeAdjusterTransform.parent = RightKneeTransform; rightKneeAdjusterTransform.position = ik.references.rightCalf.position;// RightKneeTransform.position + RightKneeTransform.rotation * Quaternion.LookRotation(settings.handTrackerForward, settings.handTrackerUp) * settings.handOffset; rightKneeAdjusterTransform.transform.localPosition += new Vector3(0, -0.3f, 1f); //正面1m 下に30cm (膝より上にBendGoalが来ると計算が反転して膝が下向いてしまう) //Vector3 rightHandUp = Vector3.Cross(GuessFootToKneeAxis(ik.references.rightCalf,ik.references.rightThigh), ik.solver.rightLeg.palmToThumbAxis); rightKneeAdjusterTransform.rotation = ik.references.rightCalf.rotation;// QuaTools.MatchRotation(RightKneeTransform.rotation * Quaternion.LookRotation(settings.footTrackerForward, settings.footTrackerUp), settings.footTrackerForward, settings.footTrackerUp, Vector3.zero, rightHandUp); ik.solver.rightLeg.bendGoal = rightKneeAdjusterTransform; ik.solver.rightLeg.bendGoalWeight = 1.0f; //TrackingWatcherにWeight設定用アクションを設定 RightKneeTransform.parent.GetComponent<TrackingWatcher>()?.SetActionOfSetWeight((float weight) => { ik.solver.rightLeg.bendGoalWeight = weight; }); } // Root controller bool addRootController = PelvisTransform != null || (LeftFootTransform != null && RightFootTransform != null); var rootController = ik.references.root.GetComponent<VRIKRootController>(); if (addRootController) { if (rootController == null) rootController = ik.references.root.gameObject.AddComponent<VRIKRootController>(); //rootController.pelvisTarget = ik.solver.spine.pelvisTarget; //rootController.leftFootTarget = ik.solver.leftLeg.target; //rootController.rightFootTarget = ik.solver.rightLeg.target; rootController.Calibrate(); } else { if (rootController != null) GameObject.Destroy(rootController); } if (hoffset.y > 0) { handTrackerRoot.position = Vector3.zero; } if (PelvisTransform != null) { pelvisOffsetHeight = ik.references.pelvis.position.y; pelvisOffsetTransform = pelvisOffsetAdjuster; if (LeftFootTransform != null && RightFootTransform != null) { pelvisOffsetAdjuster.localPosition = new Vector3(0, pelvisOffsetDivide == 0 ? 0 : -(ik.references.pelvis.position.y / pelvisOffsetDivide), 0); } } // Additional solver settings ik.solver.spine.minHeadHeight = 0f; ik.solver.locomotion.weight = PelvisTransform == null && LeftFootTransform == null && RightFootTransform == null ? 1f : 0f; } private static Vector3 GuessFootToKneeAxis(Transform Foot, Transform Knee) { Vector3 toKnee = Knee.position - Foot.position; Vector3 axis = AxisTools.ToVector3(AxisTools.GetAxisToDirection(Foot, toKnee)); if (Vector3.Dot(toKnee, Foot.rotation * axis) > 0f) axis = -axis; return axis; } } }
412
0.90354
1
0.90354
game-dev
MEDIA
0.571041
game-dev
0.9881
1
0.9881
candybox2/candybox
14,471
scripts/castleKeep.js
var castleKeep = { // Variables size : 30, // The size here must be higher than the size of the biggest room realSize : 0, // This is the real size of the current room, in term of things roomSize : 0, // Real size of the room in term of ascii floorPosition : 0, // Where the floor is located in the current room firstCharacterPosition : 0, // Where the character is located when he enters the room lastCharacterPosition : 0, // Where the character can exit the room text : [], roomNumber : 0, // The current room number. Increase by one each room. mobsAreMoving : false, // If true, in the current room, mobs should move toward the player maxRoom : 6, // Functions onload : function(){ land.addLand("Castle's keep", this.size, 5, this.load.bind(this), this.getText.bind(this), this.move.bind(this)); }, move : function(){ // We get the character's index var index = quest.getCharacterIndex(); var characterThing = quest.things[index]; // If the mobs should move, we make them move if(this.mobsAreMoving){ for(var i = 0; i < quest.things.length; i++){ if(quest.things[i].type == "mob" && quest.things[i-1].type == "none"){ quest.things[i-1] = quest.things[i]; quest.things[i] = quest.makeNoneThing(); } } } // If the character is just after the exit of the room, we create a new room and put him in it if(index == this.lastCharacterPosition - this.firstCharacterPosition + 1){ this.roomNumber += 1; // We increment the room number // If we aren't yet arrived at the room x if(this.roomNumber <= this.maxRoom){ quest.things = quest.fillWithNoneThings(); // Remove all the things this.createNewRoom(); // Create a new room quest.things[0] = characterThing; // Put the character at the beginning of the room } // Else, we end the quest else{ quest.things[this.size-1] = quest.things[index]; quest.things[index] = quest.makeFakeCharacter(); } } // If we just killed the dragon if(this.roomNumber == 6 && index == 16 && quest.things[17].type == "none"){ // We reload the room without the dragon this.text = []; this.createRoomStructure(); this.createDoorHere(this.firstCharacterPosition); } }, load : function(){ this.roomNumber = 0; // We reset the room number this.createNewRoom(); }, getText : function(){ var lines = []; lines = this.text.slice(0); // It will store the lines of the castle keep // We add things for(var i = 0; i < this.realSize; i++){ if(quest.things[i].type != "none"){ lines[this.floorPosition] = lines[this.floorPosition].replaceAt(1 + this.firstCharacterPosition*3 + i*3, quest.things[i].text); } } // We return the lines around the player return lines.join(""); }, createRoomStructure : function(){ var line; // Create the roof line = "__"; for(var i = 0; i < this.roomSize; i++){ line += "___"; } line += "\n"; this.text.push(line); // Create the inside line = "|"; for(var i = 0; i < this.roomSize; i++){ line += " "; } line += "|\n"; for(var i = 0; i < this.floorPosition - 1; i++){ this.text.push(line); } // Create the floor line = "|"; for(var i = 0; i < this.roomSize; i++){ line += "___"; } line += "|\n"; this.text.push(line); }, addDragonInRoom : function(){ var line = ""; // Add a line (to store the tail of the dragon) for(var i = 0; i < this.roomSize; i++){ line += " "; } this.text.push(line); for(var i = 0; i < this.asciiDragon.length; i++){ this.text[i + 1] = this.text[i + 1].replaceAt(54, this.asciiDragon[i]); } }, createNewRoom : function(){ this.text = []; // If we're not yet at the boss room, we make a random-sized room if(this.roomNumber < this.maxRoom){ // Set the size and stuff this.realSize = 16 + random.getRandomIntUpTo(10); this.firstCharacterPosition = random.getRandomIntUpTo(2); this.lastCharacterPosition = this.firstCharacterPosition + this.realSize - 1; this.floorPosition = 5 + random.getRandomIntUpTo(6); this.roomSize = this.realSize + this.firstCharacterPosition + random.getRandomIntUpTo(2); this.createRoomStructure(); // We add the doors at the character's first and last position this.createDoorHere(this.firstCharacterPosition); this.createDoorHere(this.lastCharacterPosition); } // Else, it's the boss room else{ // Set the size and stuff this.realSize = 26; this.firstCharacterPosition = 1; this.lastCharacterPosition = 21; this.floorPosition = 16; this.roomSize = this.realSize + this.firstCharacterPosition + 1; this.createRoomStructure(); this.addDragonInRoom(); // We add the doors at the character's first and last position this.createDoorHere(this.firstCharacterPosition); } // By default, mobs are not moving this.mobsAreMoving = false; // We add roomNumber specific stuff switch(this.roomNumber){ // Room 0 : we put some guards case 0: for(var i = 2; i < this.realSize - 1; i+=3){ quest.things[i] = castleEntrance.makeGuard(); } this.mobsAreMoving = true; break; // Rooms 1 to 4 : we put some random ennemies case 1: case 2: case 3: case 4: switch(random.getRandomIntUpTo(7)){ // Knights room case 0: for(var i = 2; i < this.realSize - 1; i++){ if(random.oneChanceOutOf(4)){ quest.things[i] = castleEntrance.makeKnight(); } } this.mobsAreMoving = true; break; // Animals room case 1: for(var i = 2; i < this.realSize - 1; i++){ if(random.oneChanceOutOf(4)){ switch(random.getRandomIntUpTo(6)){ case 0: quest.things[i] = castleKeep.makeKomodoDragon(); break; case 1: quest.things[i] = castleKeep.makeRhinoceros(); break; case 2: quest.things[i] = castleKeep.makeGaur(); break; case 3: quest.things[i] = castleKeep.makeDromornisStirtoni(); break; case 4: quest.things[i] = castleKeep.makeGorilla(); break; case 5: quest.things[i] = castleKeep.makeCapybara(); break; case 6: quest.things[i] = castleKeep.makeDoedicurus(); break; } } } break; // Ghosts room case 2: for(var i = 4; i < this.realSize - 1; i++){ if(random.oneChanceOutOf(5)){ quest.things[i] = castleStairs.makeGhost(); } } this.mobsAreMoving = true; break; // Walled off zombie warrior room case 3: // We add the walls for(var i = 1; i < this.floorPosition; i++){ this.text[i] = this.text[i].replaceAt(1 + this.firstCharacterPosition*3 + 7*3, "WAL"); this.text[i] = this.text[i].replaceAt(1 + this.firstCharacterPosition*3 + 9*3, "WAL"); } // We add the mobs (walls and walled off zombie warrior) quest.things[7] = this.makeStoneWall(); quest.things[9] = this.makeStoneWall(); quest.things[8] = this.makeWalledOffZombieWarrior(); break; // Fireball room case 4: for(var i = this.realSize - 8; i < this.realSize - 1; i++){ if(random.flipACoin()){ quest.things[i] = this.makeFireball(); } } this.mobsAreMoving = true; break; // Fake door room case 5: this.createDoorHere(this.firstCharacterPosition + 8); quest.things[8] = this.makeFakeDoorMonster(); break; // Unicorn room case 6: quest.things[2 + random.getRandomIntUpTo(this.realSize - 4)] = this.makeCharlieTheUnicorn(); quest.things[2 + random.getRandomIntUpTo(this.realSize - 4)] = this.makeUnicorn(); quest.things[2 + random.getRandomIntUpTo(this.realSize - 4)] = this.makeUnicorn(); this.mobsAreMoving = true; break; // Troll room case 7: quest.things[6 + random.getRandomIntUpTo(this.realSize - 8)] = this.makeTroll(); this.mobsAreMoving = true; break; } break; // The chests room case 5: for(var i = 1; i < this.realSize - 1; i++){ if(random.oneChanceOutOf(3)){ quest.things[i] = quest.makeOpenChest(); } } this.mobsAreMoving = false; break; // Boss room case 6: quest.things[17] = this.makeDragon(); break; } }, createDoorHere : function(position){ this.text[this.floorPosition-2] = this.text[this.floorPosition-2].replaceAt(1 + position*3, " _ "); this.text[this.floorPosition-1] = this.text[this.floorPosition-1].replaceAt(1 + position*3, "|.|"); this.text[this.floorPosition] = this.text[this.floorPosition].replaceAt(1 + position*3, "| |"); }, makeKomodoDragon : function(){ return land.createMob("KOM", 5, 5, "foots and tail", "A Komodo dragon. Did you heard about island gigantism ?", []); }, makeRhinoceros : function(){ return land.createMob("RHI", 160, 160, "horn", "A " + random.pickRandomly(["white", "black", "indian", "javan", "sumatran"]) + " rhinoceros. Watch out for his horn !", []); }, makeGaur : function(){ return land.createMob("GAU", 80, 80, "horns", "A Gaur. This large bovine looks like a bison.", []); }, makeDromornisStirtoni : function(){ return land.createMob("DST", 70, 70, "giant beak", "A Dromornis Stirtoni ! A 400kg flightless bird !", []); }, makeGorilla : function(){ return land.createMob("GOR", 50, 50, "its fists", "A Gorilla. Gorillas occasionally engage in homosexual interactions.", []); }, makeCapybara : function(){ return land.createMob("CPY", 20, 20, "its teeth", "A capybara : the largest rodent in the world !", []); }, makeDoedicurus : function(){ return land.createMob("DOE", 120, 120, "spiky tail", "A Doedicurus : your favorite glyptodont !", []); }, makeStoneWall : function(){ return land.createMob("WAL", 300, 300, "stone", "A stone wall.", []); }, makeWalledOffZombieWarrior : function(){ var hp = 150 + random.getRandomIntUpTo(10) * 10; return land.createMob("WZW", hp, hp, "cursed sword", "A walled off zombie warrior. He probably did something bad to end up here.", [drops.createDrop("candies", random.getRandomIntUpTo(1) * 4000), drops.createDrop("object", "oldAmulet", true)]); }, makeFireball : function(){ return land.createMob("FBL", 1, 1, "itself", "A fireball !! Watch out !", []); }, makeFakeDoorMonster : function(){ return land.createMob("| |", 70, 70, "sharp teeth", "It's not a door ! It's a monster ! (an ugly one)", []); }, makeUnicorn : function(){ return land.createMob("UNI", 100, 100, "magical horn", "A unicorn !! They exist !", []); }, makeCharlieTheUnicorn : function(){ return land.createMob("UNI", 100, 100, "magical horn", "A unicorn !! It has no kidney.", [drops.createDrop("object", "magicalHorn", true)]); }, makeTroll : function(){ return land.createMob("TRL", 250, 250, "enormous fist", "A troll. It is huge, but it lacks precision.", []); }, makeDragon : function(){ return land.createMob(",((", 1000, 1000, "flames", "A dragon !! Kill him and the castle will be yours.", []); }, asciiDragon : [ " _///_,", " / ` \' \'>", " o\' __/_\'>", " / _/ )_\\\'>", "\"__/ /_/\\_>", " ____/_/_/_/", " /,---, _/ /", "\"\" /_/_/_/", " /_(_(_(_ \\", " ( \\_\\_\\\\_ )\\", " \\\'__\\_\\_\\_\\__ ).\\", " //____|___\\__) )_/", " | _ \\\'___\'_( /\'", " \\_ (-\'\\\'___\'_\\ __,\'_\'", " __) \\ \\\\___(_ __/.__,\'", "_,((,-,__\\__\'\", __\\_/. __,\'", " \'\"./_._._-\'" ] };
412
0.546478
1
0.546478
game-dev
MEDIA
0.898642
game-dev
0.907269
1
0.907269
Retera/WarsmashModEngine
11,925
core/src/com/etheller/warsmash/parsers/fdf/frames/ScrollBarFrame.java
package com.etheller.warsmash.parsers.fdf.frames; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.utils.viewport.Viewport; import com.etheller.warsmash.parsers.fdf.GameUI; import com.etheller.warsmash.parsers.fdf.datamodel.FramePoint; import com.etheller.warsmash.viewer5.handlers.w3x.ui.command.ClickableFrame; public class ScrollBarFrame extends AbstractRenderableFrame implements ClickableFrame { private final boolean vertical; private UIFrame controlBackdrop; private UIFrame incButtonFrame; private UIFrame decButtonFrame; private UIFrame thumbButtonFrame; private int scrollValuePercent = 50; private ScrollBarChangeListener changeListener = ScrollBarChangeListener.DO_NOTHING; private int minValue = 0; private int maxValue = 100; private int stepSize = 10; public ScrollBarFrame(final String name, final UIFrame parent, final boolean vertical) { super(name, parent); this.vertical = vertical; } public void setControlBackdrop(final UIFrame controlBackdrop) { this.controlBackdrop = controlBackdrop; } public void setIncButtonFrame(final UIFrame incButtonFrame) { this.incButtonFrame = incButtonFrame; ((GlueButtonFrame) incButtonFrame).setButtonListener(new GlueButtonFrame.ButtonListener() { @Override public void mouseDown(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseUp(final GameUI gameUI, final Viewport uiViewport) { setValue(gameUI, uiViewport, ScrollBarFrame.this.scrollValuePercent + ScrollBarFrame.this.stepSize); } @Override public void mouseDragged(final GameUI rootFrame, final Viewport uiViewport, final float x, final float y) { } }); } public void setDecButtonFrame(final UIFrame decButtonFrame) { this.decButtonFrame = decButtonFrame; ((GlueButtonFrame) decButtonFrame).setButtonListener(new GlueButtonFrame.ButtonListener() { @Override public void mouseDown(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseUp(final GameUI gameUI, final Viewport uiViewport) { setValue(gameUI, uiViewport, ScrollBarFrame.this.scrollValuePercent - ScrollBarFrame.this.stepSize); } @Override public void mouseDragged(final GameUI rootFrame, final Viewport uiViewport, final float x, final float y) { } }); } public void setThumbButtonFrame(final UIFrame thumbButtonFrame) { if (this.thumbButtonFrame instanceof GlueButtonFrame) { ((GlueButtonFrame) this.thumbButtonFrame).setButtonListener(GlueButtonFrame.ButtonListener.DO_NOTHING); } this.thumbButtonFrame = thumbButtonFrame; if (thumbButtonFrame instanceof GlueButtonFrame) { final GlueButtonFrame frame = (GlueButtonFrame) thumbButtonFrame; frame.setButtonListener(new GlueButtonFrame.ButtonListener() { @Override public void mouseDown(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseUp(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseDragged(final GameUI rootFrame, final Viewport uiViewport, final float x, final float y) { ScrollBarFrame.this.mouseDragged(rootFrame, uiViewport, x, y); } }); } } public void setMinValue(final int minValue) { this.minValue = minValue; } public void setMaxValue(final int maxValue) { this.maxValue = maxValue; } public void setStepSize(final int stepSize) { this.stepSize = stepSize; } private float getMaxThumbButtonTravelDistance() { if (this.vertical) { final float incButtonFrameHeight = this.incButtonFrame == null ? 0 : this.incButtonFrame.getAssignedHeight(); final float decButtonFrameHeight = this.decButtonFrame == null ? 0 : this.decButtonFrame.getAssignedHeight(); return this.renderBounds.height - this.thumbButtonFrame.getAssignedHeight() - incButtonFrameHeight - decButtonFrameHeight; } else { final float incButtonFrameWidth = this.incButtonFrame == null ? 0 : this.incButtonFrame.getAssignedWidth(); final float decButtonFrameWidth = this.decButtonFrame == null ? 0 : this.decButtonFrame.getAssignedWidth(); return this.renderBounds.width - this.thumbButtonFrame.getAssignedWidth() - incButtonFrameWidth - decButtonFrameWidth; } } public void setValue(final GameUI gameUI, final Viewport uiViewport, final int percent) { this.scrollValuePercent = Math.min(this.maxValue, Math.max(this.minValue, percent)); updateThumbButtonPoint(); this.changeListener.onChange(gameUI, uiViewport, this.scrollValuePercent); positionBounds(gameUI, uiViewport); } public int getValue() { return this.scrollValuePercent; } public void updateThumbButtonPoint() { if (this.vertical) { final float newYValue = (this.scrollValuePercent / (float) this.maxValue) * getMaxThumbButtonTravelDistance(); if (this.decButtonFrame != null) { this.thumbButtonFrame.addSetPoint( new SetPoint(FramePoint.BOTTOM, this.decButtonFrame, FramePoint.TOP, 0, newYValue)); } else { this.thumbButtonFrame .addSetPoint(new SetPoint(FramePoint.BOTTOM, this, FramePoint.BOTTOM, 0, newYValue)); } } else { final float newXValue = (this.scrollValuePercent / (float) this.maxValue) * getMaxThumbButtonTravelDistance(); if (this.decButtonFrame != null) { this.thumbButtonFrame.addSetPoint( new SetPoint(FramePoint.LEFT, this.decButtonFrame, FramePoint.RIGHT, 0, newXValue)); } else { this.thumbButtonFrame.addSetPoint(new SetPoint(FramePoint.LEFT, this, FramePoint.LEFT, newXValue, 0)); } } } @Override protected void innerPositionBounds(final GameUI gameUI, final Viewport viewport) { if (this.controlBackdrop != null) { this.controlBackdrop.positionBounds(gameUI, viewport); } if (this.incButtonFrame != null) { this.incButtonFrame.positionBounds(gameUI, viewport); } if (this.decButtonFrame != null) { this.decButtonFrame.positionBounds(gameUI, viewport); } updateThumbButtonPoint(); if (this.thumbButtonFrame != null) { this.thumbButtonFrame.positionBounds(gameUI, viewport); } } @Override protected void internalRender(final SpriteBatch batch, final BitmapFont baseFont, final GlyphLayout glyphLayout) { if (this.controlBackdrop != null) { this.controlBackdrop.render(batch, baseFont, glyphLayout); } if (this.incButtonFrame != null) { this.incButtonFrame.render(batch, baseFont, glyphLayout); } if (this.decButtonFrame != null) { this.decButtonFrame.render(batch, baseFont, glyphLayout); } if (this.thumbButtonFrame != null) { this.thumbButtonFrame.render(batch, baseFont, glyphLayout); } } @Override public void mouseDown(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseUp(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseEnter(final GameUI gameUI, final Viewport uiViewport) { } @Override public void mouseExit(final GameUI gameUI, final Viewport uiViewport) { } @Override public void onClick(final int button) { } @Override public void mouseDragged(final GameUI rootFrame, final Viewport uiViewport, final float x, final float y) { final float maxThumbButtonTravelDistance = getMaxThumbButtonTravelDistance(); final int newScrollValuePercent; if (this.vertical) { final float decFrameHeight = this.decButtonFrame == null ? 0 : this.decButtonFrame.getAssignedHeight(); newScrollValuePercent = Math.min(this.maxValue, Math.max(this.minValue, Math .round(((y - this.renderBounds.y - decFrameHeight - (this.thumbButtonFrame.getAssignedHeight() / 2)) / maxThumbButtonTravelDistance) * this.maxValue))); } else { final float decFrameWidth = this.decButtonFrame == null ? 0 : this.decButtonFrame.getAssignedWidth(); newScrollValuePercent = Math.min(this.maxValue, Math.max(this.minValue, Math.round( ((x - this.renderBounds.x - decFrameWidth - (this.thumbButtonFrame.getAssignedWidth() / 2)) / maxThumbButtonTravelDistance) * this.maxValue))); } if (newScrollValuePercent != this.scrollValuePercent) { setValue(rootFrame, uiViewport, newScrollValuePercent); positionBounds(rootFrame, uiViewport); } } @Override public UIFrame touchUp(final float screenX, final float screenY, final int button) { if (isVisible() && this.renderBounds.contains(screenX, screenY)) { UIFrame frameChildUnderMouse = this.thumbButtonFrame.touchUp(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } if (this.incButtonFrame != null) { frameChildUnderMouse = this.incButtonFrame.touchUp(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } if (this.decButtonFrame != null) { frameChildUnderMouse = this.decButtonFrame.touchUp(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } if (this.controlBackdrop != null) { frameChildUnderMouse = this.controlBackdrop.touchUp(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } return this; } return super.touchUp(screenX, screenY, button); } @Override public UIFrame touchDown(final float screenX, final float screenY, final int button) { if (isVisible() && this.renderBounds.contains(screenX, screenY)) { UIFrame frameChildUnderMouse = this.thumbButtonFrame.touchDown(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } if (this.incButtonFrame != null) { frameChildUnderMouse = this.incButtonFrame.touchDown(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } if (this.decButtonFrame != null) { frameChildUnderMouse = this.decButtonFrame.touchDown(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } if (this.controlBackdrop != null) { frameChildUnderMouse = this.controlBackdrop.touchDown(screenX, screenY, button); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } return this; } return super.touchDown(screenX, screenY, button); } @Override public UIFrame getFrameChildUnderMouse(final float screenX, final float screenY) { if (isVisible() && this.renderBounds.contains(screenX, screenY)) { UIFrame frameChildUnderMouse = this.thumbButtonFrame.getFrameChildUnderMouse(screenX, screenY); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } if (this.incButtonFrame != null) { frameChildUnderMouse = this.incButtonFrame.getFrameChildUnderMouse(screenX, screenY); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } if (this.decButtonFrame != null) { frameChildUnderMouse = this.decButtonFrame.getFrameChildUnderMouse(screenX, screenY); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } if (this.controlBackdrop != null) { frameChildUnderMouse = this.controlBackdrop.getFrameChildUnderMouse(screenX, screenY); if (frameChildUnderMouse != null) { return frameChildUnderMouse; } } return this; } return super.getFrameChildUnderMouse(screenX, screenY); } public void setChangeListener(final ScrollBarChangeListener changeListener) { this.changeListener = changeListener; } public interface ScrollBarChangeListener { void onChange(GameUI gameUI, Viewport uiViewport, int newValue); ScrollBarChangeListener DO_NOTHING = new ScrollBarChangeListener() { @Override public void onChange(final GameUI gameUI, final Viewport uiViewport, final int newValue) { } }; } @Override public String getSoundKey() { return SOUND_KEY_MENU_BUTTON_CLICK; } }
412
0.871859
1
0.871859
game-dev
MEDIA
0.671188
game-dev,desktop-app
0.92425
1
0.92425
MaximumADHD/Roblox-Client-Tracker
10,410
scripts/CoreScripts/Modules/VR/VRHub.lua
--!nonstrict --Modules/VR/VRHub.lua --Handles all global VR state that isn't built into a specific module. --Written by 0xBAADF00D (Kyle) on 6/10/16 local StarterGui = game:GetService("StarterGui") local VRService = game:GetService("VRService") local RunService = game:GetService("RunService") local HttpService = game:GetService("HttpService") local CoreGui = game:GetService("CoreGui") local StarterGui = game:GetService("StarterGui") local UserInputService = game:GetService("UserInputService") local ContextActionService = game:GetService("ContextActionService") local CorePackages = game:GetService("CorePackages") local RobloxGui = CoreGui.RobloxGui local Create = require(CorePackages.Workspace.Packages.AppCommonLib).Create local LaserPointer = require(CorePackages.Workspace.Packages.VrCommon).LaserPointer local VRControllerModel = require(CorePackages.Workspace.Packages.VrCommon).VRControllerModel local SplashScreenManager = require(CorePackages.Workspace.Packages.SplashScreenManager).SplashScreenManager local SafetyBubble = require(script.Parent.SafetyBubble) local VRHub = {} local RegisteredModules = {} local OpenModules = {} --VR Setup local vrUpdateRenderstepName = HttpService:GenerateGUID(true) VRHub.LaserPointer = nil VRHub.ControllerModelsEnabled = false VRHub.LeftControllerModel = nil VRHub.RightControllerModel = nil VRHub.isFPSAtTarget = SplashScreenManager.isFPSAtTarget() VRHub.SafetyBubble = nil -- TODO: AvatarGestures cannot be turned on until this is implemented VRHub.IsFirstPerson = false StarterGui:RegisterSetCore("VRLaserPointerMode", function(mode) if not VRHub.LaserPointer then return end if not mode or not tostring(mode) then return end VRHub.LaserPointer:setMode(LaserPointer.Mode[tostring(mode)] or LaserPointer.Mode.Disabled) end) local function enableControllerModels(enabled) if enabled ~= VRHub.ControllerModelsEnabled then VRHub.ControllerModelsEnabled = enabled if enabled then if not VRHub.LeftControllerModel then VRHub.LeftControllerModel = VRControllerModel.new(Enum.UserCFrame.LeftHand) end VRHub.LeftControllerModel:setEnabled(true) if not VRHub.RightControllerModel then VRHub.RightControllerModel = VRControllerModel.new(Enum.UserCFrame.RightHand) end VRHub.RightControllerModel:setEnabled(true) else if VRHub.LeftControllerModel then VRHub.LeftControllerModel:setEnabled(false) end if VRHub.RightControllerModel then VRHub.RightControllerModel:setEnabled(false) end end end end -- This function exists to support the deprecated lua API -- game.StarterGui:SetCore("VREnableControllerModels", "<value>") -- Any usage of these old APIs should redirect to the newer -- VRService.ControllerModels = Enum.VRControllerModelMode.<Value> StarterGui:RegisterSetCore("VREnableControllerModels", function(enabled) if enabled then VRService.ControllerModels = Enum.VRControllerModelMode.Transparent else VRService.ControllerModels = Enum.VRControllerModelMode.Disabled end end) VRService:GetPropertyChangedSignal("ControllerModels"):Connect(function() enableControllerModels(VRService.ControllerModels == Enum.VRControllerModelMode.Transparent) end) local start = tick() local function onRenderSteppedLast() local now = tick() local dt = now - start start = now if VRHub.LaserPointer then VRHub.LaserPointer:update(dt) end if VRHub.LeftControllerModel then VRHub.LeftControllerModel:update(dt) end if VRHub.RightControllerModel then VRHub.RightControllerModel:update(dt) end if VRHub.SafetyBubble then VRHub.SafetyBubble:update(dt) end end local function onCameraCFrameChanged() -- We normally update the position of the controllers and laser pointer in RenderStepped. -- If a developer moves the camera after that, for example using TweenService, the controllers and pointer -- will always be a frame behind and the user will notice a severe jitter. This can be fixed by -- calling the update functions again after the camera moves, passing in a deltaTime of zero. if VRHub.LaserPointer then VRHub.LaserPointer:update(0) end if VRHub.LeftControllerModel then VRHub.LeftControllerModel:update(0) end if VRHub.RightControllerModel then VRHub.RightControllerModel:update(0) end end local cameraCFrameChangedConn = nil local function onCurrentCameraChanged() if cameraCFrameChangedConn then cameraCFrameChangedConn:disconnect() end if workspace.CurrentCamera then cameraCFrameChangedConn = (workspace.CurrentCamera :: Camera):GetPropertyChangedSignal("CFrame"):Connect(onCameraCFrameChanged) end end workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(onCurrentCameraChanged) onCurrentCameraChanged() local function onVREnabledChanged() if VRService.VREnabled then UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter UserInputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.ForceHide if not VRHub.LaserPointer then VRHub.LaserPointer = LaserPointer.new() end --Check again in case creating the laser pointer gracefully failed if VRHub.LaserPointer then if VRHub.isFPSAtTarget then VRHub.LaserPointer:setMode(LaserPointer.Mode.Navigation) else VRHub.LaserPointer:setMode(LaserPointer.Mode.Disabled) end end enableControllerModels(VRService.ControllerModels == Enum.VRControllerModelMode.Transparent) RunService:BindToRenderStep(vrUpdateRenderstepName, Enum.RenderPriority.Last.Value, onRenderSteppedLast) if VRHub.LaserPointer then VRHub.LaserPointer:setForcePointer(true) end UserInputService.OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.ForceHide VRHub.SafetyBubble = SafetyBubble.new() -- this is the equivalent of MouseButton1 in VR ContextActionService:BindCoreActivate(Enum.UserInputType.Gamepad1, Enum.KeyCode.ButtonR2) else if VRHub.LaserPointer then VRHub.LaserPointer:setMode(LaserPointer.Mode.Disabled) end RunService:UnbindFromRenderStep(vrUpdateRenderstepName) end end local function onVREnabled(property) if property ~= "VREnabled" then return end onVREnabledChanged() end local function onVRSessionStateChanged() if VRService.VRSessionState == Enum.VRSessionState.Focused then if VRHub.LaserPointer and VRHub.LaserPointer.Mode.Disabled then VRHub.LaserPointer:setMode(LaserPointer.Mode.Navigation) enableControllerModels(VRService.ControllerModels == Enum.VRControllerModelMode.Transparent) end if not VRHub.ControllerModelsEnabled then enableControllerModels(VRService.ControllerModels == Enum.VRControllerModelMode.Transparent) end else if VRHub.LaserPointer and VRHub.LaserPointer.Mode.Navigation then VRHub.LaserPointer:setMode(LaserPointer.Mode.Disabled) end if VRHub.ControllerModelsEnabled then enableControllerModels(false) end end end local function onVRPropertyChanged(property) if property == "VREnabled" then onVREnabledChanged() elseif property == "VRSessionState" then onVRSessionStateChanged() end end onVREnabledChanged() VRService.Changed:connect(onVRPropertyChanged) --VRHub API function VRHub:RegisterModule(module) RegisteredModules[module.ModuleName] = module end function VRHub:GetModule(moduleName) return RegisteredModules[moduleName] end function VRHub:IsModuleOpened(moduleName) return OpenModules[moduleName] ~= nil end function VRHub:GetOpenedModules() local result = {} for _, openModule in pairs(OpenModules) do table.insert(result, openModule) end return result end VRHub.ModuleOpened = Create("BindableEvent")({ Name = "VRModuleOpened", }) --Wrapper function to document the arguments to the event function VRHub:FireModuleOpened(moduleName) if not RegisteredModules[moduleName] then error("Tried to open module that is not registered: " .. moduleName) end if OpenModules[moduleName] ~= RegisteredModules[moduleName] then OpenModules[moduleName] = RegisteredModules[moduleName] VRHub.ModuleOpened:Fire(moduleName) end end VRHub.ModuleClosed = Create("BindableEvent")({ Name = "VRModuleClosed", }) --Wrapper function to document the arguments to the event function VRHub:FireModuleClosed(moduleName) if not RegisteredModules[moduleName] then error("Tried to close module that is not registered: " .. moduleName) end if OpenModules[moduleName] ~= nil then OpenModules[moduleName] = nil VRHub.ModuleClosed:Fire(moduleName) end end function VRHub:KeepVRTopbarOpen() for moduleName, openModule in pairs(OpenModules) do if openModule.KeepVRTopbarOpen then return true end end return false end VRHub.ShowHighlightedLeaveGameIcon = false VRHub.ShowHighlightedLeaveGameIconToggled = Create("BindableEvent")({ Name = "ShowHighlightedLeaveGameIconToggled", }) function VRHub:SetShowHighlightedLeaveGameIconToggled(showHighlightedLeaveGameIcon) if VRHub.ShowHighlightedLeaveGameIcon ~= showHighlightedLeaveGameIcon then VRHub.ShowHighlightedLeaveGameIcon = showHighlightedLeaveGameIcon VRHub.ShowHighlightedLeaveGameIconToggled:Fire() end end VRHub.ShowTopBar = true VRHub.ShowMoreMenu = false VRHub.ShowTopBarChanged = Create("BindableEvent")({ Name = "ShowTopBarChanged", }) VRHub.ShowMoreMenuChanged = Create("BindableEvent")({ Name = "ShowMoreMenuChanged", }) function VRHub:SetShowTopBar(showTopBar) if VRHub.ShowTopBar ~= showTopBar then VRHub.ShowTopBar = showTopBar VRHub.ShowTopBarChanged:Fire() end end function VRHub:SetShowMoreMenu(showMoreMenu) if VRHub.ShowMoreMenu ~= showMoreMenu then VRHub.ShowMoreMenu = showMoreMenu VRHub.ShowMoreMenuChanged:Fire() end end function VRHub:ToggleSafetyBubble() if VRHub.SafetyBubble then VRHub.SafetyBubble:ToggleEnabled() end end function VRHub:GetControllerModel(userCFrame) if userCFrame == Enum.UserCFrame.LeftHand then return VRHub.LeftControllerModel elseif userCFrame == Enum.UserCFrame.RightHand then return VRHub.RightControllerModel else return nil end end function VRHub:GetControllerButtonPosition(keyCode) local leftControllerButtonPos = VRHub.LeftControllerModel and VRHub.LeftControllerModel:getButtonPosition(keyCode) local rightControllerButtonPos = VRHub.RightControllerModel and VRHub.RightControllerModel:getButtonPosition(keyCode) return leftControllerButtonPos, rightControllerButtonPos end SplashScreenManager.addStatusChangeListener(function(isFPSAtTarget) VRHub.isFPSAtTarget = isFPSAtTarget onVREnabledChanged() end) return VRHub
412
0.898146
1
0.898146
game-dev
MEDIA
0.739331
game-dev
0.917149
1
0.917149
TaiyitistMC/Taiyitist
1,138
modules/taiyitist-server/src/main/java/org/bukkit/craftbukkit/block/data/type/CraftTrialSpawner.java
package org.bukkit.craftbukkit.block.data.type; import org.bukkit.block.data.type.TrialSpawner; import org.bukkit.craftbukkit.block.data.CraftBlockData; public abstract class CraftTrialSpawner extends CraftBlockData implements TrialSpawner { private static final net.minecraft.world.level.block.state.properties.EnumProperty<?> TRIAL_SPAWNER_STATE = getEnum("trial_spawner_state"); private static final net.minecraft.world.level.block.state.properties.BooleanProperty OMINOUS = getBoolean("ominous"); @Override public org.bukkit.block.data.type.TrialSpawner.State getTrialSpawnerState() { return this.get(CraftTrialSpawner.TRIAL_SPAWNER_STATE, org.bukkit.block.data.type.TrialSpawner.State.class); } @Override public void setTrialSpawnerState(org.bukkit.block.data.type.TrialSpawner.State state) { this.set(CraftTrialSpawner.TRIAL_SPAWNER_STATE, state); } @Override public boolean isOminous() { return this.get(CraftTrialSpawner.OMINOUS); } @Override public void setOminous(boolean ominous) { this.set(CraftTrialSpawner.OMINOUS, ominous); } }
412
0.865741
1
0.865741
game-dev
MEDIA
0.967057
game-dev
0.835951
1
0.835951
emscripten-core/emscripten
5,844
test/third_party/bullet/src/BulletCollision/CollisionShapes/btCapsuleShape.h
/* 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. */ #ifndef BT_CAPSULE_SHAPE_H #define BT_CAPSULE_SHAPE_H #include "btConvexInternalShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types ///The btCapsuleShape represents a capsule around the Y axis, there is also the btCapsuleShapeX aligned around the X axis and btCapsuleShapeZ around the Z axis. ///The total height is height+2*radius, so the height is just the height between the center of each 'sphere' of the capsule caps. ///The btCapsuleShape is a convex hull of two spheres. The btMultiSphereShape is a more general collision shape that takes the convex hull of multiple sphere, so it can also represent a capsule when just using two spheres. class btCapsuleShape : public btConvexInternalShape { protected: int m_upAxis; protected: ///only used for btCapsuleShapeZ and btCapsuleShapeX subclasses. btCapsuleShape() : btConvexInternalShape() {m_shapeType = CAPSULE_SHAPE_PROXYTYPE;}; public: btCapsuleShape(btScalar radius,btScalar height); ///CollisionShape Interface virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; /// btConvexShape Interface virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void setMargin(btScalar collisionMargin) { //correct the m_implicitShapeDimensions for the margin btVector3 oldMargin(getMargin(),getMargin(),getMargin()); btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin; btConvexInternalShape::setMargin(collisionMargin); btVector3 newMargin(getMargin(),getMargin(),getMargin()); m_implicitShapeDimensions = implicitShapeDimensionsWithMargin - newMargin; } virtual void getAabb (const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const { btVector3 halfExtents(getRadius(),getRadius(),getRadius()); halfExtents[m_upAxis] = getRadius() + getHalfHeight(); halfExtents += btVector3(getMargin(),getMargin(),getMargin()); btMatrix3x3 abs_b = t.getBasis().absolute(); btVector3 center = t.getOrigin(); btVector3 extent = btVector3(abs_b[0].dot(halfExtents),abs_b[1].dot(halfExtents),abs_b[2].dot(halfExtents)); aabbMin = center - extent; aabbMax = center + extent; } virtual const char* getName()const { return "CapsuleShape"; } int getUpAxis() const { return m_upAxis; } btScalar getRadius() const { int radiusAxis = (m_upAxis+2)%3; return m_implicitShapeDimensions[radiusAxis]; } btScalar getHalfHeight() const { return m_implicitShapeDimensions[m_upAxis]; } virtual void setLocalScaling(const btVector3& scaling) { btVector3 oldMargin(getMargin(),getMargin(),getMargin()); btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin; btVector3 unScaledImplicitShapeDimensionsWithMargin = implicitShapeDimensionsWithMargin / m_localScaling; btConvexInternalShape::setLocalScaling(scaling); m_implicitShapeDimensions = (unScaledImplicitShapeDimensionsWithMargin * m_localScaling) - oldMargin; } virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; ///btCapsuleShapeX represents a capsule around the Z axis ///the total height is height+2*radius, so the height is just the height between the center of each 'sphere' of the capsule caps. class btCapsuleShapeX : public btCapsuleShape { public: btCapsuleShapeX(btScalar radius,btScalar height); //debugging virtual const char* getName()const { return "CapsuleX"; } }; ///btCapsuleShapeZ represents a capsule around the Z axis ///the total height is height+2*radius, so the height is just the height between the center of each 'sphere' of the capsule caps. class btCapsuleShapeZ : public btCapsuleShape { public: btCapsuleShapeZ(btScalar radius,btScalar height); //debugging virtual const char* getName()const { return "CapsuleZ"; } }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btCapsuleShapeData { btConvexInternalShapeData m_convexInternalShapeData; int m_upAxis; char m_padding[4]; }; SIMD_FORCE_INLINE int btCapsuleShape::calculateSerializeBufferSize() const { return sizeof(btCapsuleShapeData); } ///fills the dataBuffer and returns the struct name (and 0 on failure) SIMD_FORCE_INLINE const char* btCapsuleShape::serialize(void* dataBuffer, btSerializer* serializer) const { btCapsuleShapeData* shapeData = (btCapsuleShapeData*) dataBuffer; btConvexInternalShape::serialize(&shapeData->m_convexInternalShapeData,serializer); shapeData->m_upAxis = m_upAxis; return "btCapsuleShapeData"; } #endif //BT_CAPSULE_SHAPE_H
412
0.956658
1
0.956658
game-dev
MEDIA
0.984049
game-dev
0.948063
1
0.948063
TheBlckbird/sandy-factry
2,946
src/content/items.rs
use bevy::prelude::*; use bevy_ecs_tilemap::prelude::*; use serde::{Deserialize, Serialize}; use strum_macros::Display; // TODO: Fix items skipping one in loops // - add flag to item if it has already moved // - check before moving #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize, Display)] pub enum ItemType { #[strum(to_string = "Coal")] Coal, #[strum(to_string = "Raw Copper")] RawCopper, #[strum(to_string = "Raw Iron")] RawIron, #[strum(to_string = "Copper Ingot")] CopperIngot, #[strum(to_string = "Iron Ingot")] IronIngot, #[strum(to_string = "Gear")] Gear, #[strum(to_string = "Steel")] Steel, #[strum(to_string = "Wire")] Wire, #[strum(to_string = "Reinforced Steel")] ReinforcedSteel, #[strum(to_string = "Electrical Circuit")] ElectricalCircuit, #[strum(to_string = "Micro Processor")] MicroProcessor, #[strum(to_string = "Rotor Blade")] RotorBlade, #[strum(to_string = "Propeller")] Propeller, #[strum(to_string = "Big Propeller")] BigPropeller, #[strum(to_string = "Hull")] Hull, #[strum(to_string = "Motor")] Motor, #[strum(to_string = "Battery")] Battery, #[strum(to_string = "Control Module")] ControlModule, #[strum(to_string = "Helicopter Frame")] HelicopterFrame, #[strum(to_string = "Engine")] Engine, #[strum(to_string = "Helicopter")] Helicopter, } impl ItemType { pub fn ends_game(&self) -> bool { *self == Self::Helicopter } } impl From<ItemType> for TileTextureIndex { fn from(value: ItemType) -> Self { TileTextureIndex(match value { ItemType::Coal => 0, ItemType::RawCopper => 1, ItemType::RawIron => 2, ItemType::CopperIngot => 3, ItemType::IronIngot => 4, ItemType::Gear => 5, ItemType::Steel => 6, ItemType::Wire => 7, ItemType::ReinforcedSteel => 8, ItemType::ElectricalCircuit => 9, ItemType::MicroProcessor => 10, ItemType::RotorBlade => 11, ItemType::Propeller => 12, ItemType::BigPropeller => 13, ItemType::Hull => 14, ItemType::Motor => 15, ItemType::Battery => 16, ItemType::ControlModule => 17, ItemType::HelicopterFrame => 18, ItemType::Engine => 19, ItemType::Helicopter => 20, }) } } /// The Item struct stores the item type and whether the item has been moved this tick #[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Deref)] pub struct Item { pub has_moved: bool, #[deref] pub item_type: ItemType, } impl From<ItemType> for Item { fn from(value: ItemType) -> Self { Self { has_moved: false, item_type: value, } } }
412
0.743525
1
0.743525
game-dev
MEDIA
0.982659
game-dev
0.775791
1
0.775791
bloodmc/GriefDefender
10,074
bukkit/src/main/java/com/griefdefender/command/CommandClaimAbandonWorld.java
/* * This file is part of GriefDefender, licensed under the MIT License (MIT). * * Copyright (c) bloodmc * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.griefdefender.command; import co.aikar.commands.BaseCommand; import co.aikar.commands.annotation.CommandAlias; import co.aikar.commands.annotation.CommandCompletion; import co.aikar.commands.annotation.CommandPermission; import co.aikar.commands.annotation.Description; import co.aikar.commands.annotation.Optional; import co.aikar.commands.annotation.Subcommand; import co.aikar.commands.annotation.Syntax; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.reflect.TypeToken; import com.griefdefender.GDPlayerData; import com.griefdefender.GriefDefenderPlugin; import com.griefdefender.api.GriefDefender; import com.griefdefender.api.claim.Claim; import com.griefdefender.api.permission.option.Options; import com.griefdefender.cache.MessageCache; import com.griefdefender.claim.GDClaimManager; import com.griefdefender.configuration.MessageStorage; import com.griefdefender.event.GDCauseStackManager; import com.griefdefender.event.GDRemoveClaimEvent; import com.griefdefender.permission.GDPermissionManager; import com.griefdefender.permission.GDPermissionUser; import com.griefdefender.permission.GDPermissions; import com.griefdefender.text.action.GDCallbackHolder; import net.kyori.text.Component; import net.kyori.text.TextComponent; import net.kyori.text.adapter.bukkit.TextAdapter; import net.kyori.text.event.ClickEvent; import net.kyori.text.event.HoverEvent; import net.kyori.text.format.TextColor; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @CommandAlias("%griefdefender") @CommandPermission(GDPermissions.COMMAND_ABANDON_WORLD_CLAIMS) public class CommandClaimAbandonWorld extends BaseCommand { @CommandCompletion("@gdworlds @gddummy") @CommandAlias("abandonworld") @Description("%abandon-world") @Subcommand("abandon world") @Syntax("[<world>]") public void execute(Player player, @Optional String worldName) { World world = player.getWorld(); if (worldName != null) { world = Bukkit.getWorld(worldName); if (world == null) { TextAdapter.sendComponent(player, MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.COMMAND_WORLD_NOT_FOUND, ImmutableMap.of("world", worldName))); return; } } final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(player.getWorld().getUID()); if (claimWorldManager.getWorldClaims().size() == 0) { try { throw new CommandException(MessageCache.getInstance().CLAIM_NO_CLAIMS); } catch (CommandException e) { TextAdapter.sendComponent(player, e.getText()); return; } } final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ABANDON_WORLD_WARNING, ImmutableMap.of( "world", TextComponent.of(world.getName()))); final Component confirmationText = TextComponent.builder() .append(message) .append(TextComponent.builder() .append("\n[") .append(MessageCache.getInstance().LABEL_CONFIRM.color(TextColor.GREEN)) .append("]\n") .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(player, createConfirmationConsumer(player, world), true))) .hoverEvent(HoverEvent.showText(MessageCache.getInstance().UI_CLICK_CONFIRM)).build()) .build(); TextAdapter.sendComponent(player, confirmationText); } private static Consumer<CommandSender> createConfirmationConsumer(Player source, World world) { return confirm -> { final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(world.getUID()); for (GDPlayerData playerData : claimWorldManager.getPlayerDataMap().values()) { final GDPermissionUser user = playerData.getSubject(); if (user == null) { continue; } if (playerData.playerID.equals(GriefDefenderPlugin.ADMIN_USER_UUID)) { continue; } if (playerData.playerID.equals(GriefDefenderPlugin.PUBLIC_UUID)) { continue; } if (playerData.playerID.equals(GriefDefenderPlugin.WORLD_USER_UUID)) { continue; } Set<Claim> allowedClaims = new HashSet<>(); final Player player = user.getOnlinePlayer(); for (Claim claim : playerData.getInternalClaims()) { if (!claim.getWorldUniqueId().equals(world.getUID())) { continue; } allowedClaims.add(claim); } if (!allowedClaims.isEmpty()) { GDCauseStackManager.getInstance().pushCause(user); GDRemoveClaimEvent.Abandon event = new GDRemoveClaimEvent.Abandon(ImmutableList.copyOf(allowedClaims)); GriefDefender.getEventManager().post(event); GDCauseStackManager.getInstance().popCause(); if (event.cancelled()) { TextAdapter.sendComponent(source, event.getMessage().orElse(MessageCache.getInstance().PLUGIN_EVENT_CANCEL).color(TextColor.RED)); return; } double refund = 0; // adjust claim blocks for (Claim claim : allowedClaims) { if (claim.isSubdivision() || claim.isAdminClaim() || claim.isWilderness()) { continue; } final double abandonReturnRatio = GDPermissionManager.getInstance().getInternalOptionValue(TypeToken.of(Double.class), user, Options.ABANDON_RETURN_RATIO, claim); if (GriefDefenderPlugin.getInstance().isEconomyModeEnabled()) { refund += claim.getClaimBlocks() * abandonReturnRatio; } else { playerData.setAccruedClaimBlocks(playerData.getAccruedClaimBlocks() - ((int) Math.ceil(claim.getClaimBlocks() * (1 - abandonReturnRatio)))); } } //playerData.useRestoreSchematic = event.isRestoring(); GriefDefenderPlugin.getInstance().dataStore.abandonClaimsForPlayer(user, allowedClaims); //playerData.useRestoreSchematic = false; playerData.onClaimDelete(); if (GriefDefenderPlugin.getInstance().isEconomyModeEnabled()) { final Economy economy = GriefDefenderPlugin.getInstance().getVaultProvider().getApi(); if (!economy.hasAccount(user.getOfflinePlayer())) { continue; } final EconomyResponse result = economy.depositPlayer(user.getOfflinePlayer(), refund); if (result.transactionSuccess() && player != null) { final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ECONOMY_CLAIM_ABANDON_SUCCESS_WORLD, ImmutableMap.of( "world", world.getName(), "amount", TextComponent.of(String.valueOf(refund)))); TextAdapter.sendComponent(player, message); } } else if (player != null) { int remainingBlocks = playerData.getRemainingClaimBlocks(); final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ABANDON_SUCCESS_WORLD, ImmutableMap.of( "world", world.getName(), "amount", remainingBlocks)); TextAdapter.sendComponent(player, message); } } } final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ABANDON_WORLD_SUCCESS, ImmutableMap.of( "world", world.getName())); TextAdapter.sendComponent(source, message); }; } }
412
0.974026
1
0.974026
game-dev
MEDIA
0.648252
game-dev,web-backend
0.993787
1
0.993787
CleanroomMC/GroovyScript
3,955
src/main/java/com/cleanroommc/groovyscript/compat/mods/ic2/exp/FluidGenerator.java
package com.cleanroommc.groovyscript.compat.mods.ic2.exp; import com.cleanroommc.groovyscript.api.GroovyLog; import com.cleanroommc.groovyscript.core.mixin.ic2.SemiFluidFuelManagerAccessor; import com.cleanroommc.groovyscript.helper.Alias; import com.cleanroommc.groovyscript.helper.SimpleObjectStream; import com.cleanroommc.groovyscript.helper.ingredient.IngredientHelper; import com.cleanroommc.groovyscript.registry.VirtualizedRegistry; import ic2.api.recipe.ISemiFluidFuelManager; import ic2.api.recipe.Recipes; import net.minecraftforge.fluids.FluidStack; import org.apache.commons.lang3.tuple.Pair; import java.util.Map; public class FluidGenerator extends VirtualizedRegistry<Pair<String, ISemiFluidFuelManager.FuelProperty>> { public FluidGenerator() { super(Alias.generateOfClassAnd(FluidGenerator.class, "SemiFluidGenerator")); } @Override public void onReload() { Map<String, ISemiFluidFuelManager.FuelProperty> fluidMap = ((SemiFluidFuelManagerAccessor) Recipes.semiFluidGenerator).getFuelProperties(); removeScripted().forEach(pair -> fluidMap.remove(pair.getKey())); restoreFromBackup().forEach(pair -> fluidMap.put(pair.getKey(), pair.getValue())); } public Pair<String, ISemiFluidFuelManager.FuelProperty> add(FluidStack input, long energyPerMb, long energyPerTick) { if (GroovyLog.msg("Error adding Industrialcraft 2 Semi Fluid Generator recipe") .add(IngredientHelper.isEmpty(input), () -> "input must not be empty") .add(energyPerMb <= 0, () -> "energy per mb must be higher than zero") .add(energyPerTick <= 0, () -> "energy per tick must be higher than zero") .error() .postIfNotEmpty()) { return null; } Pair<String, ISemiFluidFuelManager.FuelProperty> pair = Pair.of(input.getFluid().getName(), new ISemiFluidFuelManager.FuelProperty(energyPerMb, energyPerTick)); Recipes.semiFluidGenerator.addFluid(input.getFluid().getName(), energyPerMb, energyPerTick); addScripted(pair); return pair; } public Pair<String, ISemiFluidFuelManager.FuelProperty> add(String name, ISemiFluidFuelManager.FuelProperty recipe) { Map<String, ISemiFluidFuelManager.FuelProperty> fluidMap = ((SemiFluidFuelManagerAccessor) Recipes.semiFluidGenerator).getFuelProperties(); Pair<String, ISemiFluidFuelManager.FuelProperty> pair = Pair.of(name, recipe); fluidMap.put(name, recipe); addScripted(pair); return pair; } public SimpleObjectStream<Map.Entry<String, ISemiFluidFuelManager.FuelProperty>> streamRecipes() { return new SimpleObjectStream<>(Recipes.semiFluidGenerator.getFuelProperties().entrySet()).setRemover(r -> remove(r.getKey())); } public boolean remove(FluidStack input) { if (IngredientHelper.isEmpty(input)) { GroovyLog.msg("Error removing Industrialcraft 2 Semi Fluid Generator recipe") .add("input must not be empty") .error() .post(); return false; } return remove(input.getFluid().getName()); } public void removeAll() { Map<String, ISemiFluidFuelManager.FuelProperty> fluidMap = ((SemiFluidFuelManagerAccessor) Recipes.semiFluidGenerator).getFuelProperties(); for (String fluid : fluidMap.keySet()) { addBackup(Pair.of(fluid, fluidMap.get(fluid))); fluidMap.remove(fluid); } } public boolean remove(String name) { Map<String, ISemiFluidFuelManager.FuelProperty> fluidMap = ((SemiFluidFuelManagerAccessor) Recipes.semiFluidGenerator).getFuelProperties(); ISemiFluidFuelManager.FuelProperty property = fluidMap.remove(name); if (property != null) { addBackup(Pair.of(name, property)); return true; } return false; } }
412
0.754293
1
0.754293
game-dev
MEDIA
0.356822
game-dev
0.904903
1
0.904903
Darkrp-community/OpenKeep
2,010
code/modules/jobs/job_types/roguetown/adventurer/types/combat/monk.dm
/datum/advclass/combat/monk name = "Monk" allowed_sexes = list(MALE, FEMALE) tutorial = "A traveling monk of the God Ravox, unmatched in unarmed combat and with an unwavering devotion to Justice." allowed_races = list( "Humen", "Elf", "Half-Elf", "Dwarf", "Aasimar" ) outfit = /datum/outfit/job/roguetown/adventurer/monk min_pq = 0 category_tags = list(CTAG_ADVENTURER) vampcompat = FALSE /datum/outfit/job/roguetown/adventurer/monk allowed_patrons = list(/datum/patron/divine/ravox) /datum/outfit/job/roguetown/adventurer/monk/pre_equip(mob/living/carbon/human/H) ..() head = /obj/item/clothing/head/roguetown/roguehood/brown neck = /obj/item/clothing/neck/roguetown/psycross/silver/ravox cloak = /obj/item/clothing/cloak/raincloak/furcloak/brown wrists = /obj/item/clothing/wrists/roguetown/bracers/leather armor = /obj/item/clothing/suit/roguetown/shirt/robe/plain belt = /obj/item/storage/belt/rogue/leather/rope beltr = /obj/item/storage/belt/rogue/pouch/coins/poor shoes = /obj/item/clothing/shoes/roguetown/shortboots backl = /obj/item/storage/backpack/rogue/backpack backr = /obj/item/rogueweapon/polearm/woodstaff if(H.mind) H.mind.adjust_skillrank(/datum/skill/misc/reading, 3, TRUE) H.mind.adjust_skillrank(/datum/skill/combat/unarmed, 5, TRUE) H.mind.adjust_skillrank(/datum/skill/combat/wrestling, 4, TRUE) H.mind.adjust_skillrank(/datum/skill/combat/polearms, pick(1,1,2), TRUE) // Wood staff H.mind.adjust_skillrank(/datum/skill/misc/sewing, 2, TRUE) H.mind.adjust_skillrank(/datum/skill/misc/medicine, 1, TRUE) H.mind.adjust_skillrank(/datum/skill/misc/climbing, 4, TRUE) H.mind.adjust_skillrank(/datum/skill/misc/athletics, pick(2,2,3), TRUE) H.change_stat("strength", 3) H.change_stat("constitution", 2) H.change_stat("endurance", 2) H.change_stat("perception", -1) H.change_stat("speed", 1) ADD_TRAIT(H, TRAIT_DODGEEXPERT, TRAIT_GENERIC) if(H.patron != /datum/patron/divine/ravox) H.set_patron(/datum/patron/divine/ravox)
412
0.722905
1
0.722905
game-dev
MEDIA
0.756874
game-dev
0.828426
1
0.828426
DragonRuby/dragonruby-game-toolkit-contrib
2,812
samples/04_physics_and_collisions/14_hookes_law_coulombs_law/app/main.rb
# Sample app demonstrates how to use Hooke's Law and Columb's Law # to render things to the screen without things overlapping def boot args args.state = {} end def tick args args.state.center_screen ||= { x: 640, y: 360 } args.state.particles ||= 10.map do { x: Numeric.rand(500..800), y: Numeric.rand(200..400), w: 16, h: 16, dx: Numeric.rand(-1.0..1.0), dy: Numeric.rand(-1.0..1.0), r: 128 * rand, g: 128 * rand, b: 128 * rand, path: :solid } end if args.inputs.mouse.click args.state.particles.push_back({ x: args.inputs.mouse.x - 8, y: args.inputs.mouse.y - 8, w: 16, h: 16, dx: Numeric.rand(-1.0..1.0), dy: Numeric.rand(-1.0..1.0), r: 128 * rand, g: 128 * rand, b: 128 * rand, path: :solid }) end args.state.particles.each do |p1| hookes_law! p1, args.state.center_screen args.state.particles.each do |p2| next if p1 == p2 coulombs_law! p1, p2 end end args.state.particles.each do |p1| p1.dx = p1.dx.clamp(-2.5, 2.5) p1.dy = p1.dy.clamp(-2.5, 2.5) p1.x += p1.dx p1.y += p1.dy collide_edge! p1 end collisions = false Geometry.each_intersect_rect(args.state.particles, args.state.particles) do |p1, p2| collisions = true end if !collisions args.state.particles.each do |p1| p1.dx *= 0.95 p1.dy *= 0.95 end end args.outputs.sprites << args.state.particles args.outputs.labels << { x: 640, y: 360, text: "Click to add particles", anchor_x: 0.5, anchor_y: 0.5 } end def hookes_law! p1, p2 dx = p2.x - p1.x dy = p2.y - p1.y distance = Math.sqrt(dx * dx + dy * dy) force = (distance - 100) / 100.0 * 0.01 if distance > 0 p1.dx += (dx / distance) * force p1.dy += (dy / distance) * force end end def coulombs_law! p1, p2 dx = p2.x - p1.x dy = p2.y - p1.y distance = Math.sqrt(dx * dx + dy * dy) return if distance < 1 force = 20 / (distance * distance) dx_force = (dx / distance) * force dy_force = (dy / distance) * force p1.dx -= dx_force p1.dy -= dy_force p2.dx += dx_force p2.dy += dy_force end def collide_edge! p1 if p1.x < 0 p1.x = 0 p1.dx *= -1 elsif p1.x > 1280 - p1.w p1.x = 1280 - p1.w p1.dx *= -1 end if p1.y < 0 p1.y = 0 p1.dy *= -1 elsif p1.y > 720 - p1.h p1.y = 720 - p1.h p1.dy *= -1 end end
412
0.913018
1
0.913018
game-dev
MEDIA
0.672983
game-dev
0.992118
1
0.992118
schrum2/GameGAN
5,468
src/competition/cig/robinbaumgarten/astar/sprites/Mushroom.java
package competition.cig.robinbaumgarten.astar.sprites; import competition.cig.robinbaumgarten.astar.LevelScene; public class Mushroom extends Sprite { private static float GROUND_INERTIA = 0.89f; private static float AIR_INERTIA = 0.89f; private float runTime; private boolean onGround = false; /*private boolean mayJump = false; private int jumpTime = 0; private float xJumpSpeed; private float yJumpSpeed;*/ private int width = 4; int height = 24; private LevelScene world; public int facing; public boolean avoidCliffs = false; private int life; public Mushroom(LevelScene world, int x, int y) { kind = 91; this.x = x; this.y = y; this.world = world; height = 12; facing = 1; life = 0; } public void collideCheck() { float xMarioD = world.mario.x - x; float yMarioD = world.mario.y - y; if (xMarioD > -16 && xMarioD < 16) { if (yMarioD > -height && yMarioD < world.mario.height) { world.mario.getMushroom(); spriteContext.removeSprite(this); } } } public void move() { if (life<9) { layer = 0; y--; life++; return; } float sideWaysSpeed = 1.75f; layer = 1; // float sideWaysSpeed = onGround ? 2.5f : 1.2f; if (xa > 2) { facing = 1; } if (xa < -2) { facing = -1; } xa = facing * sideWaysSpeed; runTime += (Math.abs(xa)) + 5; if (!move(xa, 0)) facing = -facing; onGround = false; move(0, ya); ya *= 0.85f; if (onGround) { xa *= GROUND_INERTIA; } else { xa *= AIR_INERTIA; } if (!onGround) { ya += 2; } } private boolean move(float xa, float ya) { while (xa > 8) { if (!move(8, 0)) return false; xa -= 8; } while (xa < -8) { if (!move(-8, 0)) return false; xa += 8; } while (ya > 8) { if (!move(0, 8)) return false; ya -= 8; } while (ya < -8) { if (!move(0, -8)) return false; ya += 8; } boolean collide = false; if (ya > 0) { if (isBlocking(x + xa - width, y + ya, xa, 0)) collide = true; else if (isBlocking(x + xa + width, y + ya, xa, 0)) collide = true; else if (isBlocking(x + xa - width, y + ya + 1, xa, ya)) collide = true; else if (isBlocking(x + xa + width, y + ya + 1, xa, ya)) collide = true; } if (ya < 0) { if (isBlocking(x + xa, y + ya - height, xa, ya)) collide = true; else if (collide || isBlocking(x + xa - width, y + ya - height, xa, ya)) collide = true; else if (collide || isBlocking(x + xa + width, y + ya - height, xa, ya)) collide = true; } if (xa > 0) { if (isBlocking(x + xa + width, y + ya - height, xa, ya)) collide = true; if (isBlocking(x + xa + width, y + ya - height / 2, xa, ya)) collide = true; if (isBlocking(x + xa + width, y + ya, xa, ya)) collide = true; if (avoidCliffs && onGround && !world.level.isBlocking((int) ((x + xa + width) / 16), (int) ((y) / 16 + 1), xa, 1)) collide = true; } if (xa < 0) { if (isBlocking(x + xa - width, y + ya - height, xa, ya)) collide = true; if (isBlocking(x + xa - width, y + ya - height / 2, xa, ya)) collide = true; if (isBlocking(x + xa - width, y + ya, xa, ya)) collide = true; if (avoidCliffs && onGround && !world.level.isBlocking((int) ((x + xa - width) / 16), (int) ((y) / 16 + 1), xa, 1)) collide = true; } if (collide) { if (xa < 0) { x = (int) ((x - width) / 16) * 16 + width; this.xa = 0; } if (xa > 0) { x = (int) ((x + width) / 16 + 1) * 16 - width - 1; this.xa = 0; } if (ya < 0) { y = (int) ((y - height) / 16) * 16 + height; //jumpTime = 0; this.ya = 0; } if (ya > 0) { y = (int) (y / 16 + 1) * 16 - 1; onGround = true; } return false; } else { x += xa; y += ya; return true; } } private boolean isBlocking(float _x, float _y, float xa, float ya) { int x = (int) (_x / 16); int y = (int) (_y / 16); if (x == (int) (this.x / 16) && y == (int) (this.y / 16)) return false; boolean blocking = world.level.isBlocking(x, y, xa, ya); //byte block = world.level.getBlock(x, y); return blocking; } public void bumpCheck(int xTile, int yTile) { if (x + width > xTile * 16 && x - width < xTile * 16 + 16 && yTile==(int)((y-1)/16)) { facing = -world.mario.facing; ya = -10; } } }
412
0.771269
1
0.771269
game-dev
MEDIA
0.471936
game-dev
0.980475
1
0.980475
Mauler125/scripts_r5
12,265
vscripts/weapons/sh_titancore_utility.gnut
#if SERVER untyped #endif global function MpTitanabilityFusionCore_Init global function OnAbilityCharge_TitanCore global function OnAbilityStart_TitanCore #if SERVER global function OnAbilityEnd_TitanCore global function OnAbilityChargeEnd_TitanCore global function SoulTitanCore_SetNextAvailableTime global function SoulTitanCore_SetExpireTime #endif global function SoulTitanCore_GetNextAvailableTime global function SoulTitanCore_GetExpireTime global function IsTitanCoreFiring global function CheckCoreAvailable global function IsCoreAvailable global function IsCoreChargeAvailable global function CoreChargeBegin #if SERVER global function CoreChargeEnd global function CoreActivate global function CoreDeactivate global function CoreBegin global function CoreEnd #endif const EMP_BLAST_EFFECT = $"P_titan_core_atlas_blast" const EMP_BLAST_CHARGE_EFFECT = $"P_titan_core_atlas_charge" #if SERVER global function SetUsedCoreCallback global function CreateDefaultChargeEffect global function SetCoreEffect global function CreateCoreEffect global function CleanupCoreEffect global function HideTitanCoreFX global function OnAbilityStart_DashCore global function OnAbilityEnd_DashCore global function LowerEnemyAccuracy #endif #if SERVER struct { void functionref( entity, entity ) usedCoreCallback } file #endif void function MpTitanabilityFusionCore_Init() { PrecacheParticleSystem( EMP_BLAST_CHARGE_EFFECT ) PrecacheParticleSystem( EMP_BLAST_EFFECT ) // //#if TITANS_CLASSIC_GAMEPLAY // Shift_Core_Init() // LaserCannon_Init() // FlightCore_Init() // SalvoCore_Init() // UpgradeCore_Init() // Stealth_Core_Init() //#endif RegisterSignal( "CoreActivated" ) RegisterSignal( "CoreBegin" ) RegisterSignal( "CoreEnd" ) #if SERVER AddCallback_OnPlayerKilled( TitanCore_PlayerKilledCleanup ) AddDamageCallback( "player", TitanCore_OnDamage ) #endif } #if SERVER void function SetUsedCoreCallback( void functionref( entity, entity ) func ) { file.usedCoreCallback = func } void function TitanCore_OnDamage( entity ent, var damageInfo ) { } #endif bool function IsTitanCoreFiring( entity titan ) { if ( !titan.IsTitan() ) return false entity soul = titan.GetTitanSoul() float time = Time() return time >= soul.GetCoreChargeStartTime() && time <= soul.GetCoreChargeExpireTime() } bool function OnAbilityCharge_TitanCore( entity weapon ) { if ( !CheckCoreAvailable( weapon ) ) return false entity player = weapon.GetWeaponOwner() #if CLIENT if ( !InPrediction() || IsFirstTimePredicted() ) { #endif // printt( "chargebegin" ) #if SERVER CoreActivate( player ) #endif CoreChargeBegin( player, player, weapon ) #if CLIENT } #endif player.Signal( "CoreActivated" ) return true } bool function OnAbilityStart_TitanCore( entity weapon ) { entity titan = weapon.GetWeaponOwner() // printt( "abilitybegin" ) titan.Signal( "CoreBegin" ) #if SERVER CoreBegin( titan, titan, weapon ) #endif if ( titan.IsPlayer() ) { PlayerUsedOffhand( titan, weapon ) } return true } #if SERVER void function OnAbilityChargeEnd_TitanCore( entity weapon ) { // printt( "chargeend" ) entity titan = weapon.GetWeaponOwner() if ( titan == null ) return CoreChargeEnd( titan, weapon ) } void function OnAbilityEnd_TitanCore( entity weapon ) { // printt( "abilityend" ) entity titan = weapon.GetWeaponOwner() if ( titan == null ) return CoreDeactivate( titan, weapon ) CoreEnd( titan, titan, weapon ) } #endif bool function CheckCoreAvailable( entity weapon ) { return false } #if SERVER void function CoreActivate( entity player ) { // printt( "activate" ) entity soul = player.GetTitanSoul() if ( IsValid( soul ) && !player.ContextAction_IsMeleeExecution() ) { if ( TitanDamageRewardsTitanCoreTime() ) SoulTitanCore_SetNextAvailableTime( soul, 0.0 ) else SoulTitanCore_SetNextAvailableTime( soul, Time() + 1000 ) } } void function CoreDeactivate( entity player, entity weapon ) { // printt( "deactivate" ) Assert( player.IsTitan() ) entity soul = player.GetTitanSoul() if ( IsValid( soul ) && !player.ContextAction_IsMeleeExecution() ) { if ( IsValid( player ) ) { SoulTitanCore_SetNextAvailableTime( soul, Time() + GetTitanCoreBuildTimeFromWeapon( weapon ) ) } } } bool function CoreBegin( entity player, entity titan, entity weapon ) { entity soul = titan.GetTitanSoul() bool marathon = false if ( !IsAlive( titan ) ) return false if ( !titan.IsTitan() ) return false if ( player.IsPlayer() ) { BlastScreenShake( titan ) var passive = GetPassiveFromWeapon( weapon ) if ( passive != null ) GivePassive( soul, expect int( passive ) ) PIN_AddToPlayerCountStat( player, "titan_cores" ) } if ( marathon ) EmitSoundOnEntity( titan, "Titan_CoreAbility_Sustain_Long" ) else EmitSoundOnEntity( titan, "Titan_CoreAbility_Sustain" ) SetCoreEffect( titan, CreateCoreEffect, EMP_BLAST_EFFECT ) if ( file.usedCoreCallback != null ) file.usedCoreCallback( titan, weapon ) return true } void function LowerEnemyAccuracy( entity titan, float duration ) { Assert( titan.IsPlayer() ) titan.EndSignal( "OnDeath" ) titan.EndSignal( "TitanEjectionStarted" ) titan.EndSignal( "CoreEnd" ) titan.EndSignal( "DisembarkingTitan" ) titan.EndSignal( "OnSyncedMelee" ) OnThreadEnd( function() : ( titan ) { if ( IsValid( titan ) ) { print( "Making player titan Shootable\n" ) titan.kv.EnemyAccuracyMultiplier = 1.0 } } ) titan.kv.EnemyAccuracyMultiplier = 0.3 wait duration } void function CoreEnd( entity player, entity titan, entity weapon ) { entity soul = titan.GetTitanSoul() if ( soul != null ) { var passive = GetPassiveFromWeapon( weapon ) if ( passive != null ) TakePassive( soul, expect int( passive ) ) CleanupCoreEffect( soul ) if ( IsValid( titan ) ) { StopSoundOnEntity( titan, "Titan_CoreAbility_Sustain_Long" ) StopSoundOnEntity( titan, "Titan_CoreAbility_Sustain" ) } } if ( IsValid( player ) ) player.Signal( "CoreEnd" ) } #endif // #if SERVER bool function CoreChargeBegin( entity player, entity titan, entity weapon ) { entity soul = titan.GetTitanSoul() #if CLIENT thread CoreActivatedVO( player ) #if HAS_BOSS_AI if ( titan.IsPlayer() ) { BossTitanPlayerUsedCoreAbility( titan, GetTitanCurrentRegenTab( titan ) ) } #endif #endif #if SERVER float coreWaitTime = GetTitanCoreDurationFromWeapon( weapon ) + GetTitanCoreChargeTimeFromWeapon( weapon ) SoulTitanCore_SetExpireTime( soul, Time() + coreWaitTime ) soul.SetCoreChargeStartTime( Time() ) soul.SetCoreUseDuration( coreWaitTime ) #if HAS_BOSS_AI if ( titan.IsNPC() && BossTitanVDUEnabled( titan ) ) { entity p = titan.GetEnemy() if ( p.IsPlayer() ) Remote_CallFunction_NonReplay( p, "ServerCallback_BossTitanUseCoreAbility", titan.GetEncodedEHandle(), GetTitanCurrentRegenTab( titan ) ) } #endif #endif // #else // #if CLIENT return true } #if SERVER void function CoreChargeEnd( entity titan, entity weapon ) { if ( IsValid( titan ) ) { entity soul = titan.GetTitanSoul() if ( soul != null ) CleanupCoreEffect( soul ) } } #endif // #if SERVER bool function IsCoreChargeAvailable( entity player, entity soul ) { if ( soul == null ) return false if ( TitanDamageRewardsTitanCoreTime() ) return SoulTitanCore_GetNextAvailableTime( soul ) >= 1.0 if ( Time() >= SoulTitanCore_GetNextAvailableTime( soul ) && IsCoreAvailable( player ) ) return true return false } bool function IsCoreAvailable( entity player ) { entity coreWeapon = player.GetOffhandWeapon( OFFHAND_EQUIPMENT ) if ( coreWeapon == null ) return false return ( GetDoomedState( player ) == false || CoreAvailableDuringDoomState() ) } var function GetPassiveFromWeapon( entity weapon ) { var passiveName = weapon.GetWeaponInfoFileKeyField( "passive" ) if ( passiveName == null ) return null switch ( passiveName ) { } return null } #if SERVER void functionref( entity ) function PROTO_CoreStringToFunction( string funcName ) { return null } void functionref( entity ) function GetFuncFromWeaponEntry( string weaponName, string field ) { var funcName = GetWeaponInfoFileKeyField_Global( weaponName, field ) if ( funcName == null ) return null expect string( funcName ) return PROTO_CoreStringToFunction( funcName ) } //////////////////////////////////////////////////////////////////////// // Core-start effect functions //////////////////////////////////////////////////////////////////////// void function CreateDefaultChargeEffect( entity titan ) { SetCoreEffect( titan, CreateCoreEffect, EMP_BLAST_CHARGE_EFFECT ) } void function BlastScreenShake( entity titan ) { // Screen shake float amplitude = 16.0 float frequency = 5.0 float duration = 2.0 float radius = 1500.0 entity shake = CreateShake( titan.GetOrigin(), amplitude, frequency, duration, radius ) shake.SetParent( titan, "CHESTFOCUS" ) shake.Kill_Deprecated_UseDestroyInstead( 3.0 ) } void function TitanCore_PlayerKilledCleanup( entity player, entity attacker, var damageInfo ) { ForceTitanSustainedDischargeEnd( player ) } void function CleanupCoreEffect( entity soul ) { if ( "coreEffect" in soul.s && IsValid( soul.s.coreEffect.ent ) ) { soul.s.coreEffect.ent.Destroy() } if ( "coreEffect" in soul.s ) delete soul.s.coreEffect } void function SetCoreEffect( entity titan, entity functionref(entity,asset) func, asset effectName ) { Assert( IsAlive( titan ) ) Assert( titan.IsTitan() ) entity soul = titan.GetTitanSoul() entity chargeEffect = func( titan, effectName ) if ( "coreEffect" in soul.s ) { soul.s.coreEffect.ent.Kill_Deprecated_UseDestroyInstead() } else { soul.s.coreEffect <- null } soul.s.coreEffect = { parameter = effectName, ent = chargeEffect, func = func } } //////////////////////////////////////////////////////////////////////// // core fx and color correction //////////////////////////////////////////////////////////////////////// entity function CreateCoreEffect( entity player, asset effectName ) { Assert( player.IsTitan() ) int index = player.LookupAttachment( "hijack" ) entity chargeEffect = StartParticleEffectOnEntity_ReturnEntity( player, GetParticleSystemIndex( effectName ), FX_PATTACH_POINT_FOLLOW, index ) chargeEffect.kv.VisibilityFlags = (ENTITY_VISIBLE_TO_FRIENDLY | ENTITY_VISIBLE_TO_ENEMY) // everyone but owner chargeEffect.SetOwner( player ) return chargeEffect } void function HideTitanCoreFX( entity titan, float duration ) { titan.EndSignal( "OnDestroy" ) CleanupCoreEffect( titan.GetTitanSoul() ) wait duration CreateDefaultChargeEffect( titan ) } //////////////////////////////////////////////////////////////////////// // R1 core functions //////////////////////////////////////////////////////////////////////// void function OnAbilityEnd_DashCore( entity player ) { player.SetDodgePowerDelayScale( 1.0 ) player.SetPowerRegenRateScale( 1.0 ) } void function OnAbilityStart_DashCore( entity player ) { // Dash recharges fast player.SetDodgePowerDelayScale( 0.05 ) player.SetPowerRegenRateScale( 16.0 ) } //PAS_SHIELDED_CORE void function ShieldedCore( entity soul, float coreDuration ) { soul.EndSignal( "OnDestroy" ) soul.EndSignal( "OnTitanDeath" ) int health = soul.GetShieldHealthMax() soul.SetShieldHealth( health ) OnThreadEnd( function() : ( soul ) { if ( IsValid( soul ) ) soul.SetShieldHealth( 0 ) } ) wait max( 3.0, coreDuration ) } void function SoulTitanCore_SetNextAvailableTime( entity soul, float time ) { soul.SetTitanSoulNetFloat( "coreAvailableFrac", min( time, 1.0 ) ) soul.SetNextCoreChargeAvailable( time ) } void function SoulTitanCore_SetExpireTime( entity soul, float expireTime ) { if ( expireTime - Time() > 0 ) { soul.SetTitanSoulNetFloat( "coreExpireFrac", 1.0 ) soul.SetTitanSoulNetFloatOverTime( "coreExpireFrac", 0.0, expireTime - Time() ) } else { soul.SetTitanSoulNetFloat( "coreExpireFrac", 0.0 ) } soul.SetCoreChargeExpireTime( expireTime ) } #endif // SERVER float function SoulTitanCore_GetNextAvailableTime( entity soul ) { return soul.GetNextCoreChargeAvailable() } float function SoulTitanCore_GetExpireTime( entity soul ) { return soul.GetCoreChargeExpireTime() }
412
0.856062
1
0.856062
game-dev
MEDIA
0.97235
game-dev
0.86115
1
0.86115
R2NorthstarTools/NorthstarProton
9,435
lsteamclient/steamworks_sdk_155/steam_api_common.h
//====== Copyright Valve Corporation, All rights reserved. ==================== // // Steamworks SDK minimal include // // Defines the minimal set of things we need to use any single interface // or register for any callback. // //============================================================================= #ifndef STEAM_API_COMMON_H #define STEAM_API_COMMON_H #ifdef _WIN32 #pragma once #endif #include "steamtypes.h" #include "steamclientpublic.h" // S_API defines the linkage and calling conventions for steam_api.dll exports #if defined( _WIN32 ) && !defined( _X360 ) #if defined( STEAM_API_EXPORTS ) #define S_API extern "C" __declspec( dllexport ) #elif defined( STEAM_API_NODLL ) #define S_API extern "C" #else #define S_API extern "C" __declspec( dllimport ) #endif // STEAM_API_EXPORTS #elif defined( GNUC ) #if defined( STEAM_API_EXPORTS ) #define S_API extern "C" __attribute__ ((visibility("default"))) #else #define S_API extern "C" #endif // STEAM_API_EXPORTS #else // !WIN32 #if defined( STEAM_API_EXPORTS ) #define S_API extern "C" #else #define S_API extern "C" #endif // STEAM_API_EXPORTS #endif #if ( defined(STEAM_API_EXPORTS) || defined(STEAM_API_NODLL) ) && !defined(API_GEN) #define STEAM_PRIVATE_API( ... ) __VA_ARGS__ #elif defined(STEAM_API_EXPORTS) && defined(API_GEN) #define STEAM_PRIVATE_API( ... ) #else #define STEAM_PRIVATE_API( ... ) protected: __VA_ARGS__ public: #endif // handle to a communication pipe to the Steam client typedef int32 HSteamPipe; // handle to single instance of a steam user typedef int32 HSteamUser; // function prototype #if defined( POSIX ) #define __cdecl #endif extern "C" typedef void (__cdecl *SteamAPIWarningMessageHook_t)(int, const char *); extern "C" typedef uint32 ( *SteamAPI_CheckCallbackRegistered_t )( int iCallbackNum ); #if defined( __SNC__ ) #pragma diag_suppress=1700 // warning 1700: class "%s" has virtual functions but non-virtual destructor #endif //----------------------------------------------------------------------------------------------------------------------------------------------------------// // steam callback and call-result helpers // // The following macros and classes are used to register your application for // callbacks and call-results, which are delivered in a predictable manner. // // STEAM_CALLBACK macros are meant for use inside of a C++ class definition. // They map a Steam notification callback directly to a class member function // which is automatically prototyped as "void func( callback_type *pParam )". // // CCallResult is used with specific Steam APIs that return "result handles". // The handle can be passed to a CCallResult object's Set function, along with // an object pointer and member-function pointer. The member function will // be executed once the results of the Steam API call are available. // // CCallback and CCallbackManual classes can be used instead of STEAM_CALLBACK // macros if you require finer control over registration and unregistration. // // Callbacks and call-results are queued automatically and are only // delivered/executed when your application calls SteamAPI_RunCallbacks(). // // Note that there is an alternative, lower level callback dispatch mechanism. // See SteamAPI_ManualDispatch_Init //----------------------------------------------------------------------------------------------------------------------------------------------------------// // Dispatch all queued Steamworks callbacks. // // This is safe to call from multiple threads simultaneously, // but if you choose to do this, callback code could be executed on any thread. // One alternative is to call SteamAPI_RunCallbacks from the main thread only, // and call SteamAPI_ReleaseCurrentThreadMemory regularly on other threads. S_API void S_CALLTYPE SteamAPI_RunCallbacks(); // Declares a callback member function plus a helper member variable which // registers the callback on object creation and unregisters on destruction. // The optional fourth 'var' param exists only for backwards-compatibility // and can be ignored. #define STEAM_CALLBACK( thisclass, func, .../*callback_type, [deprecated] var*/ ) \ _STEAM_CALLBACK_SELECT( ( __VA_ARGS__, 4, 3 ), ( /**/, thisclass, func, __VA_ARGS__ ) ) // Declares a callback function and a named CCallbackManual variable which // has Register and Unregister functions instead of automatic registration. #define STEAM_CALLBACK_MANUAL( thisclass, func, callback_type, var ) \ CCallbackManual< thisclass, callback_type > var; void func( callback_type *pParam ) // Dispatch callbacks relevant to the gameserver client and interfaces. // To register for these, you need to use STEAM_GAMESERVER_CALLBACK. // (Or call SetGameserverFlag on your CCallbackBase object.) S_API void S_CALLTYPE SteamGameServer_RunCallbacks(); // Same as STEAM_CALLBACK, but for callbacks on the gameserver interface. // These will be dispatched during SteamGameServer_RunCallbacks #define STEAM_GAMESERVER_CALLBACK( thisclass, func, /*callback_type, [deprecated] var*/... ) \ _STEAM_CALLBACK_SELECT( ( __VA_ARGS__, GS, 3 ), ( this->SetGameserverFlag();, thisclass, func, __VA_ARGS__ ) ) #define STEAM_GAMESERVER_CALLBACK_MANUAL( thisclass, func, callback_type, var ) \ CCallbackManual< thisclass, callback_type, true > var; void func( callback_type *pParam ) //----------------------------------------------------------------------------- // Purpose: base for callbacks and call results - internal implementation detail //----------------------------------------------------------------------------- class CCallbackBase { public: CCallbackBase() { m_nCallbackFlags = 0; m_iCallback = 0; } // don't add a virtual destructor because we export this binary interface across dll's virtual void Run( void *pvParam ) = 0; virtual void Run( void *pvParam, bool bIOFailure, SteamAPICall_t hSteamAPICall ) = 0; int GetICallback() { return m_iCallback; } virtual int GetCallbackSizeBytes() = 0; protected: enum { k_ECallbackFlagsRegistered = 0x01, k_ECallbackFlagsGameServer = 0x02 }; uint8 m_nCallbackFlags; int m_iCallback; friend class CCallbackMgr; private: CCallbackBase( const CCallbackBase& ); CCallbackBase& operator=( const CCallbackBase& ); }; //----------------------------------------------------------------------------- // Purpose: templated base for callbacks - internal implementation detail //----------------------------------------------------------------------------- template< int sizeof_P > class CCallbackImpl : protected CCallbackBase { public: virtual ~CCallbackImpl() { if ( m_nCallbackFlags & k_ECallbackFlagsRegistered ) SteamAPI_UnregisterCallback( this ); } void SetGameserverFlag() { m_nCallbackFlags |= k_ECallbackFlagsGameServer; } protected: friend class CCallbackMgr; virtual void Run( void *pvParam ) = 0; virtual void Run( void *pvParam, bool /*bIOFailure*/, SteamAPICall_t /*hSteamAPICall*/ ) { Run( pvParam ); } virtual int GetCallbackSizeBytes() { return sizeof_P; } }; //----------------------------------------------------------------------------- // Purpose: maps a steam async call result to a class member function // template params: T = local class, P = parameter struct //----------------------------------------------------------------------------- template< class T, class P > class CCallResult : private CCallbackBase { public: typedef void (T::*func_t)( P*, bool ); CCallResult(); ~CCallResult(); void Set( SteamAPICall_t hAPICall, T *p, func_t func ); bool IsActive() const; void Cancel(); void SetGameserverFlag() { m_nCallbackFlags |= k_ECallbackFlagsGameServer; } private: virtual void Run( void *pvParam ); virtual void Run( void *pvParam, bool bIOFailure, SteamAPICall_t hSteamAPICall ); virtual int GetCallbackSizeBytes() { return sizeof( P ); } SteamAPICall_t m_hAPICall; T *m_pObj; func_t m_Func; }; //----------------------------------------------------------------------------- // Purpose: maps a steam callback to a class member function // template params: T = local class, P = parameter struct, // bGameserver = listen for gameserver callbacks instead of client callbacks //----------------------------------------------------------------------------- template< class T, class P, bool bGameserver = false > class CCallback : public CCallbackImpl< sizeof( P ) > { public: typedef void (T::*func_t)(P*); // NOTE: If you can't provide the correct parameters at construction time, you should // use the CCallbackManual callback object (STEAM_CALLBACK_MANUAL macro) instead. CCallback( T *pObj, func_t func ); void Register( T *pObj, func_t func ); void Unregister(); protected: virtual void Run( void *pvParam ); T *m_pObj; func_t m_Func; }; //----------------------------------------------------------------------------- // Purpose: subclass of CCallback which allows default-construction in // an unregistered state; you must call Register manually //----------------------------------------------------------------------------- template< class T, class P, bool bGameServer = false > class CCallbackManual : public CCallback< T, P, bGameServer > { public: CCallbackManual() : CCallback< T, P, bGameServer >( nullptr, nullptr ) {} // Inherits public Register and Unregister functions from base class }; // Internal implementation details for all of the above #include "steam_api_internal.h" #endif // STEAM_API_COMMON_H
412
0.910141
1
0.910141
game-dev
MEDIA
0.94551
game-dev
0.67626
1
0.67626
JasonXuDeveloper/Nino
5,519
src/Nino.Unity/Assets/ThirdParty/Mongo/MongoDB.Bson/IO/InputBufferChunkSource.cs
/* Copyright 2013-present MongoDB Inc. * * 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. */ using System; namespace MongoDB.Bson.IO { /// <summary> /// Represents a source of chunks optimized for input buffers. /// </summary> public sealed class InputBufferChunkSource : IBsonChunkSource { // constants const int DefaultMaxChunkSize = 1 * 1024 * 1024; const int DefaultMaxUnpooledChunkSize = 4 * 1024; const int DefaultMinChunkSize = 16 * 1024; // fields private readonly IBsonChunkSource _baseSource; private bool _disposed; private readonly int _maxChunkSize; private readonly int _maxUnpooledChunkSize; private readonly int _minChunkSize; // constructors /// <summary> /// Initializes a new instance of the <see cref="InputBufferChunkSource"/> class. /// </summary> /// <param name="baseSource">The chunk source.</param> /// <param name="maxUnpooledChunkSize">The maximum size of an unpooled chunk.</param> /// <param name="minChunkSize">The minimum size of a chunk.</param> /// <param name="maxChunkSize">The maximum size of a chunk.</param> public InputBufferChunkSource( IBsonChunkSource baseSource, int maxUnpooledChunkSize = DefaultMaxUnpooledChunkSize, int minChunkSize = DefaultMinChunkSize, int maxChunkSize = DefaultMaxChunkSize) { if (baseSource == null) { throw new ArgumentNullException("baseSource"); } if (maxUnpooledChunkSize < 0) { throw new ArgumentOutOfRangeException("maxUnpooledChunkSize"); } if (minChunkSize <= 0) { throw new ArgumentOutOfRangeException("minChunkSize"); } if (maxChunkSize <= 0) { throw new ArgumentOutOfRangeException("maxChunkSize"); } if (!PowerOf2.IsPowerOf2(minChunkSize)) { throw new ArgumentException("minChunkSize is not a power of 2.", "minChunkSize"); } if (!PowerOf2.IsPowerOf2(maxChunkSize)) { throw new ArgumentException("maxChunkSize is not a power of 2.", "maxChunkSize"); } if (maxChunkSize < minChunkSize) { throw new ArgumentException("maxChunkSize is less than minChunkSize", "maxChunkSize"); } _baseSource = baseSource; _maxUnpooledChunkSize = maxUnpooledChunkSize; _minChunkSize = minChunkSize; _maxChunkSize = maxChunkSize; } // properties /// <summary> /// Gets the base source. /// </summary> /// <value> /// The base source. /// </value> public IBsonChunkSource BaseSource { get { ThrowIfDisposed(); return _baseSource; } } /// <summary> /// Gets the maximum size of a chunk. /// </summary> /// <value> /// The maximum size of a chunk. /// </value> public int MaxChunkSize { get { return _maxChunkSize; } } /// <summary> /// Gets the minimum size of a chunk. /// </summary> /// <value> /// The minimum size of a chunk. /// </value> public int MinChunkSize { get { return _minChunkSize; } } /// <summary> /// Gets the maximum size of an unpooled chunk. /// </summary> /// <value> /// The maximum size of an unpooled chunk. /// </value> public int MaxUnpooledChunkSize { get { return _maxUnpooledChunkSize; } } // methods /// <inheritdoc/> public void Dispose() { _disposed = true; } /// <inheritdoc/> public IBsonChunk GetChunk(int requestedSize) { if (requestedSize <= 0) { throw new ArgumentOutOfRangeException("requestedSize"); } ThrowIfDisposed(); if (requestedSize <= _maxUnpooledChunkSize) { return new ByteArrayChunk(requestedSize); } var powerOf2Size = PowerOf2.RoundUpToPowerOf2(requestedSize); if (powerOf2Size - requestedSize > _minChunkSize) { powerOf2Size = powerOf2Size / 2; } var chunkSize = Math.Max(Math.Min(powerOf2Size, _maxChunkSize), _minChunkSize); return _baseSource.GetChunk(chunkSize); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } } }
412
0.685095
1
0.685095
game-dev
MEDIA
0.4989
game-dev
0.888038
1
0.888038
TeamMidnightDust/MidnightControls
1,202
common/src/main/java/eu/midnightdust/midnightcontrols/client/mixin/InGameHudMixin.java
package eu.midnightdust.midnightcontrols.client.mixin; import eu.midnightdust.midnightcontrols.client.gui.MidnightControlsHud; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.hud.InGameHud; import net.minecraft.client.render.RenderTickCounter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(InGameHud.class) public class InGameHudMixin { @Inject(method = "<init>", at = @At("TAIL")) private static void midnightcontrols$initHud(MinecraftClient client, CallbackInfo ci) { MidnightControlsHud.getInstance().init(); } @Inject(method = "renderMainHud", at = @At("HEAD")) public void midnightcontrols$renderHud(DrawContext context, RenderTickCounter tickCounter, CallbackInfo ci) { MidnightControlsHud.getInstance().render(context, tickCounter); } @Inject(method = "tick()V", at = @At("HEAD")) public void midnightcontrols$tickHud(CallbackInfo ci) { MidnightControlsHud.getInstance().tick(); } }
412
0.779924
1
0.779924
game-dev
MEDIA
0.876845
game-dev,graphics-rendering
0.844288
1
0.844288
Team-8-bit/2024-Sonic
1,689
robot/src/main/kotlin/org/team9432/robot/commands/shooter/Subwoofer.kt
package org.team9432.robot.commands.shooter import org.team9432.lib.commandbased.commands.* import org.team9432.robot.LEDState import org.team9432.robot.MechanismSide import org.team9432.robot.RobotState import org.team9432.robot.RobotState.NotePosition import org.team9432.robot.commands.hopper.MoveToPosition import org.team9432.robot.oi.Controls import org.team9432.robot.subsystems.Shooter import org.team9432.robot.subsystems.Superstructure /** Runs the shooter and at the speeds required to shoot from the subwoofer. This doesn't use aim or use the hood and is only used if something is broken. */ fun Subwoofer() = ParallelDeadlineCommand( Shooter.Commands.runAtSpeeds(3000.0, 2500.0), deadline = SequentialCommand( ParallelCommand( // Move the note to the speaker side of the hopper MoveToPosition(NotePosition.SPEAKER_HOPPER), SequentialCommand( WaitCommand(0.1), WaitUntilCommand { Shooter.atSetpoint() } ) ), InstantCommand { LEDState.speakerShooterReady = true }, // Keep aiming while waiting for confirmation WaitUntilCommand { Controls.readyToShootSpeaker }, // Wait for driver confirmation InstantCommand { LEDState.speakerShooterReady = false }, ParallelDeadlineCommand( // Shoot the note Superstructure.Commands.runLoad(MechanismSide.SPEAKER), // Do this until the note is no longer in the beam break, plus a little bit deadline = WaitCommand(0.75) ), // Update the note position InstantCommand { RobotState.notePosition = NotePosition.NONE }, ) )
412
0.901181
1
0.901181
game-dev
MEDIA
0.826122
game-dev
0.648939
1
0.648939
MightyPirates/OpenComputers
1,316
src/main/scala/li/cil/oc/integration/bluepower/RedstoneDevice.scala
package li.cil.oc.integration.bluepower import com.bluepowermod.api.BPApi import com.bluepowermod.api.connect.ConnectionType import com.bluepowermod.api.connect.IConnectionCache import com.bluepowermod.api.wire.redstone.IRedstoneDevice import li.cil.oc.common.tileentity.traits.RedstoneAware import net.minecraft.world.World import net.minecraftforge.common.util.ForgeDirection class RedstoneDevice(val tileEntity: RedstoneAware) extends IRedstoneDevice { lazy val cache = BPApi.getInstance.getRedstoneApi.createRedstoneConnectionCache(this) override def getX: Int = tileEntity.x override def getY: Int = tileEntity.y override def getZ: Int = tileEntity.z override def getWorld: World = tileEntity.world override def canConnect(side: ForgeDirection, dev: IRedstoneDevice, connectionType: ConnectionType): Boolean = tileEntity.isOutputEnabled override def isNormalFace(side: ForgeDirection): Boolean = true override def getRedstoneConnectionCache: IConnectionCache[_ <: IRedstoneDevice] = cache override def getRedstonePower(side: ForgeDirection): Byte = tileEntity.getOutput(side).toByte override def setRedstonePower(side: ForgeDirection, power: Byte): Unit = tileEntity.setInput(side, power & 0xFF) override def onRedstoneUpdate(): Unit = tileEntity.checkRedstoneInputChanged() }
412
0.776784
1
0.776784
game-dev
MEDIA
0.985506
game-dev
0.769238
1
0.769238
hlrs-vis/covise
3,248
src/OpenCOVER/PluginUtil/coVR3DGizmo.cpp
#include "coVR3DGizmo.h" #include "coVR3DTransGizmo.h" #include "coVR3DRotGizmo.h" #include "coVR3DScaleGizmo.h" #include <exception> #include <cover/coVRPluginSupport.h> using namespace opencover; coVR3DGizmo::coVR3DGizmo(GIZMO_TYPE gizmotype,bool translate, bool rotate, bool scale, osg::Matrix m, float s, vrui::coInteraction::InteractionType type, const char *iconName, const char *interactorName, vrui::coInteraction::InteractionPriority priority) :_translate(translate),_rotate(rotate),_scale(scale) { _type = gizmotype; if(gizmotype == GIZMO_TYPE::ROTATE) _gizmo.reset(new coVR3DRotGizmo(m, s, type, iconName, interactorName, priority, this)); else if(gizmotype == GIZMO_TYPE::TRANSLATE) _gizmo.reset(new coVR3DTransGizmo(m, s, type, iconName, interactorName, priority, this)); else if(gizmotype == GIZMO_TYPE::SCALE) _gizmo.reset(new coVR3DScaleGizmo(m, s, type, iconName, interactorName, priority, this)); _gizmo->enableIntersection(); _gizmo->show(); } coVR3DGizmo::~coVR3DGizmo() { } void coVR3DGizmo::changeGizmoType() { float _interSize = cover->getSceneSize() / 50 ; osg::Matrix matrix = _gizmo->getMatrix(); try{ if(dynamic_cast<coVR3DRotGizmo*>(_gizmo.get()) != nullptr) { if(_translate) { _gizmo.reset(new coVR3DTransGizmo(matrix, _interSize, vrui::coInteraction::ButtonA, "hand", "coVR3DTransGizmo", vrui::coInteraction::Medium, this)); _type = GIZMO_TYPE::TRANSLATE; } else if(_scale) { _gizmo.reset(new coVR3DScaleGizmo(matrix, _interSize, vrui::coInteraction::ButtonA, "hand", "coVR3DScaleGizmo", vrui::coInteraction::Medium, this)); _type = GIZMO_TYPE::SCALE; } } else if(dynamic_cast<coVR3DTransGizmo*>(_gizmo.get()) != nullptr) { if(_scale) { _gizmo.reset(new coVR3DScaleGizmo(matrix, _interSize, vrui::coInteraction::ButtonA, "hand", "coVR3DScaleGizmo", vrui::coInteraction::Medium, this)); _type = GIZMO_TYPE::SCALE; } else if(_rotate) { _gizmo.reset(new coVR3DRotGizmo(matrix, _interSize, vrui::coInteraction::ButtonA, "hand", "coVR3DRotateGizmo", vrui::coInteraction::Medium, this)); _type = GIZMO_TYPE::ROTATE; } } else if(dynamic_cast<coVR3DScaleGizmo*>(_gizmo.get()) != nullptr) { if(_rotate) { _gizmo.reset(new coVR3DRotGizmo(matrix, _interSize, vrui::coInteraction::ButtonA, "hand", "coVR3DRotGizmo", vrui::coInteraction::Medium, this)); _type = GIZMO_TYPE::ROTATE; } else if(_translate) { _gizmo.reset(new coVR3DTransGizmo(matrix, _interSize, vrui::coInteraction::ButtonA, "hand", "coVR3DTransGizmo", vrui::coInteraction::Medium, this)); _type = GIZMO_TYPE::TRANSLATE; } } }catch (std::exception& e) {std::cout << "Exception: " << e.what();} _gizmo->enableIntersection(); _gizmo->show(); std::cout<<_translate<<_rotate<<_scale<<std::endl; } void coVR3DGizmo::setGizmoTypes(bool translate, bool rotate, bool scale) { _translate = translate; _rotate = rotate; _scale = scale; }
412
0.859141
1
0.859141
game-dev
MEDIA
0.579253
game-dev
0.883565
1
0.883565
MehVahdJukaar/Supplementaries
2,652
common/src/main/java/net/mehvahdjukaar/supplementaries/client/particles/DrippingLiquidParticle.java
package net.mehvahdjukaar.supplementaries.client.particles; import net.mehvahdjukaar.supplementaries.reg.ModParticles; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.*; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.SimpleParticleType; import net.minecraft.world.level.material.FluidState; public class DrippingLiquidParticle extends TextureSheetParticle { private DrippingLiquidParticle(ClientLevel world, double x, double y, double z) { super(world, x, y, z); this.setSize(0.01F, 0.01F); this.gravity = 0.06F; this.gravity *= 0.02F; this.lifetime = 40; } @Override public void tick() { this.xo = this.x; this.yo = this.y; this.zo = this.z; this.ageParticle(); if (!this.removed) { this.yd -= this.gravity; this.move(this.xd, this.yd, this.zd); this.updateMotion(); if (!this.removed) { this.xd *= 0.98F; this.yd *= 0.98F; this.zd *= 0.98F; BlockPos blockpos = BlockPos.containing(this.x, this.y, this.z); FluidState fluidstate = this.level.getFluidState(blockpos); if (!fluidstate.isEmpty() && this.y < ( blockpos.getY() + fluidstate.getHeight(this.level, blockpos))) { this.remove(); } } } } protected void ageParticle() { if (this.lifetime-- <= 0) { this.remove(); this.level.addParticle(ModParticles.FALLING_LIQUID.get(), this.x, this.y, this.z, this.rCol, this.gCol, this.bCol); } } public ParticleRenderType getRenderType() { return ParticleRenderType.PARTICLE_SHEET_OPAQUE; } protected void updateMotion() { this.xd *= 0.02D; this.yd *= 0.02D; this.zd *= 0.02D; } public static class Factory implements ParticleProvider<SimpleParticleType> { protected final SpriteSet spriteSet; public Factory(SpriteSet spriteSet) { this.spriteSet = spriteSet; } @Override public Particle createParticle(SimpleParticleType typeIn, ClientLevel worldIn, double x, double y, double z, double r, double g, double b) { DrippingLiquidParticle drippingLiquidParticle = new DrippingLiquidParticle(worldIn, x, y, z); drippingLiquidParticle.setColor((float) r, (float) g, (float) b); drippingLiquidParticle.pickSprite(this.spriteSet); return drippingLiquidParticle; } } }
412
0.743493
1
0.743493
game-dev
MEDIA
0.947678
game-dev
0.850423
1
0.850423
JDKDigital/productive-bees
1,452
src/main/java/cy/jdkdigital/productivebees/init/ModParticles.java
package cy.jdkdigital.productivebees.init; import cy.jdkdigital.productivebees.ProductiveBees; import cy.jdkdigital.productivebees.client.particle.NectarParticleType; import net.minecraft.core.particles.ParticleType; import net.minecraft.core.registries.Registries; import net.neoforged.neoforge.registries.DeferredHolder; import net.neoforged.neoforge.registries.DeferredRegister; import javax.annotation.Nonnull; public class ModParticles { public static final DeferredRegister<ParticleType<?>> PARTICLE_TYPES = DeferredRegister.create(Registries.PARTICLE_TYPE, ProductiveBees.MODID); public static final DeferredHolder<ParticleType<?>, NectarParticleType> COLORED_FALLING_NECTAR = register("colored_falling_nectar"); public static final DeferredHolder<ParticleType<?>, NectarParticleType> COLORED_RISING_NECTAR = register("colored_rising_nectar"); public static final DeferredHolder<ParticleType<?>, NectarParticleType> COLORED_LAVA_NECTAR = register("colored_lava_nectar"); public static final DeferredHolder<ParticleType<?>, NectarParticleType> COLORED_POPPING_NECTAR = register("colored_popping_nectar"); public static final DeferredHolder<ParticleType<?>, NectarParticleType> COLORED_PORTAL_NECTAR = register("colored_portal_nectar"); private static DeferredHolder<ParticleType<?>, NectarParticleType> register(@Nonnull String key) { return PARTICLE_TYPES.register(key, NectarParticleType::new); } }
412
0.638061
1
0.638061
game-dev
MEDIA
0.871822
game-dev
0.66625
1
0.66625
kidagine/Darklings-FightingGame
5,361
Assets/_Project/Scripts/PlayerScripts/PlayerMovement.cs
using UnityEngine; public class PlayerMovement : MonoBehaviour { private Player _player; private Audio _audio; private DemonVector2 _velocity; private int _knockbackFrame; public DemonicsPhysics Physics { get; private set; } public bool HasJumped { get; set; } public bool HasDoubleJumped { get; set; } public bool HasAirDashed { get; set; } public DemonFloat MovementSpeed { get; set; } public bool IsGrounded { get; set; } = true; public bool IsInHitstop { get; private set; } public bool IsInCorner => Physics.OnWall; private InputBuffer inputBuffer; void Awake() { _player = GetComponent<Player>(); Physics = GetComponent<DemonicsPhysics>(); _audio = GetComponent<Audio>(); inputBuffer = GetComponent<InputBuffer>(); } void Start() { MovementSpeed = _player.playerStats.SpeedWalk; } void FixedUpdate() { CheckKnockback(); } public void SetPosition(DemonVector2 position) { Vector2Int fixedPosition = new Vector2Int((int)(position.x * 1) / 1, (int)(position.y * 1) / 1); Physics.SetPositionWithRender(new DemonVector2((DemonFloat)position.x, (DemonFloat)position.y)); } public void TravelDistance(DemonVector2 travelDistance) { Physics.Velocity = new DemonVector2((DemonFloat)travelDistance.x, (DemonFloat)travelDistance.y); } public void Knockback(Vector2 knockbackForce, int knockbackDuration, int direction, int arc = 0, bool instant = false, bool ground = false, bool ignoreX = false) { if (knockbackDuration > 0) { if (_knockbackDuration > 0) { StopKnockback(); Physics.SetFreeze(true); } DemonFloat endPositionY = (DemonFloat)0; if (arc > 0) { endPositionY = DemonicsPhysics.GROUND_POINT; } if (instant) { _startPosition = Physics.Position; _endPosition = new DemonVector2(Physics.Position.x + ((DemonFloat)knockbackForce.x * direction), Physics.Position.y + endPositionY); _knockbackDuration = knockbackDuration; _arc = (DemonFloat)arc; } else { _player.hitstopEvent.AddListener(() => { _ignoreX = ignoreX; _startPosition = Physics.Position; if (!ground) { _endPosition = new DemonVector2(Physics.Position.x + ((DemonFloat)knockbackForce.x * direction), Physics.Position.y + endPositionY); } else { _endPosition = new DemonVector2(Physics.Position.x + ((DemonFloat)knockbackForce.x * direction), DemonicsPhysics.GROUND_POINT - 0.5); } _knockbackDuration = knockbackDuration; _arc = (DemonFloat)arc; }); } } } public void StopKnockback() { _knockbackDuration = 0; _knockbackFrame = 0; } private bool _ignoreX; private DemonFloat _arc; private int _knockbackDuration; DemonVector2 _startPosition; DemonVector2 _endPosition; private void CheckKnockback() { if (_knockbackDuration > 0 && !IsInHitstop) { DemonFloat ratio = (DemonFloat)_knockbackFrame / (DemonFloat)_knockbackDuration; DemonFloat distance = _endPosition.x - _startPosition.x; DemonFloat nextX = DemonFloat.Lerp(_startPosition.x, _endPosition.x, ratio); DemonFloat baseY = DemonFloat.Lerp(_startPosition.y, _endPosition.y, (nextX - _startPosition.x) / distance); DemonFloat arc = _arc * (nextX - _startPosition.x) * (nextX - _endPosition.x) / ((DemonFloat)(-0.25) * distance * distance); DemonVector2 nextPosition; if (arc == (DemonFloat)0) { nextPosition = new DemonVector2(nextX, Physics.Position.y); } else { nextPosition = new DemonVector2(nextX, baseY + arc); } if (_ignoreX) { nextPosition = new DemonVector2(Physics.Position.x, nextPosition.y); } Physics.SetPositionWithRender(nextPosition); _knockbackFrame++; if (_knockbackFrame == _knockbackDuration) { Physics.Velocity = DemonVector2.Zero; StopKnockback(); } } } public void ResetToWalkSpeed() { if (MovementSpeed == _player.playerStats.SpeedRun) { _audio.Sound("Run").Stop(); MovementSpeed = _player.playerStats.SpeedWalk; } } public void EnterHitstop() { if (!IsInHitstop) { _velocity = Physics.Velocity; IsInHitstop = true; Physics.SetFreeze(true); } } public void ExitHitstop() { if (IsInHitstop) { IsInHitstop = false; Physics.SetFreeze(false); Physics.Velocity = new DemonVector2(_velocity.x, Physics.Velocity.y); } } }
412
0.757226
1
0.757226
game-dev
MEDIA
0.99742
game-dev
0.995506
1
0.995506
tcltk/tcllib
1,523
modules/debug/heartbeat.tcl
# -*- tcl -* # Debug -- Heartbeat. Track operation of Tcl's eventloop. # -- Colin McCormack / originally Wub server utilities # # ## ### ##### ######## ############# ##################### ## Requisites package require Tcl 8.5 9 package require debug namespace eval ::debug { namespace export heartbeat namespace ensemble create } # # ## ### ##### ######## ############# ##################### ## API & Implementation proc ::debug::heartbeat {{delta 500}} { variable duration $delta variable timer if {$duration > 0} { # stop a previous heartbeat before starting the next catch { after cancel $timer } on heartbeat ::debug::every $duration { debug.heartbeat {[::debug::pulse]} } } else { catch { after cancel $timer } off heartbeat } } proc ::debug::every {ms body} { eval $body variable timer [after $ms [info level 0]] return } proc ::debug::pulse {} { variable duration variable hbtimer variable heartbeat set now [::tcl::clock::milliseconds] set diff [expr {$now - $hbtimer - $duration}] set hbtimer $now return [list [incr heartbeat] $diff] } # # ## ### ##### ######## ############# ##################### namespace eval ::debug { variable duration 0 ; # milliseconds between heart-beats variable heartbeat 0 ; # beat counter variable hbtimer [::tcl::clock::milliseconds] variable timer } # # ## ### ##### ######## ############# ##################### ## Ready package provide debug::heartbeat 1.0.2 return
412
0.705759
1
0.705759
game-dev
MEDIA
0.23774
game-dev
0.781961
1
0.781961
dougdonohoe/ddpoker
62,464
code/poker/src/main/java/com/donohoedigital/games/poker/TournamentProfileDialog.java
/* * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * DD Poker - Source Code * Copyright (c) 2003-2025 Doug Donohoe * * 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. * * For the full License text, please see the LICENSE.txt file * in the root directory of this project. * * The "DD Poker" and "Donohoe Digital" names and logos, as well as any images, * graphics, text, and documentation found in this repository (including but not * limited to written documentation, website content, and marketing materials) * are licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives * 4.0 International License (CC BY-NC-ND 4.0). You may not use these assets * without explicit written permission for any uses not covered by this License. * For the full License text, please see the LICENSE-CREATIVE-COMMONS.txt file * in the root directory of this project. * * For inquiries regarding commercial licensing of this source code or * the use of names, logos, images, text, or other assets, please contact * doug [at] donohoe [dot] info. * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ /* * TournamentProfileDialog.java * * Created on January 27, 2003, 3:49 AM */ package com.donohoedigital.games.poker; import com.donohoedigital.base.*; import com.donohoedigital.comms.*; import com.donohoedigital.config.*; import com.donohoedigital.games.config.*; import com.donohoedigital.games.engine.*; import com.donohoedigital.games.poker.ai.gui.*; import com.donohoedigital.games.poker.engine.*; import com.donohoedigital.games.poker.model.*; import com.donohoedigital.gui.*; import org.apache.logging.log4j.*; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.*; import static com.donohoedigital.config.DebugConfig.*; /** * @author Doug Donohoe */ public class TournamentProfileDialog extends OptionMenuDialog implements PropertyChangeListener, ActionListener, FocusListener { static Logger logger = LogManager.getLogger(TournamentProfileDialog.class); static com.donohoedigital.base.Format fPerc = new com.donohoedigital.base.Format("%1.3f"); private javax.swing.border.Border empty_ = null; private TournamentProfile profile_; private PokerGame game_; // used when editing during a tournament private TypedHashMap dummy_ = new TypedHashMap(); private TypedHashMap labelignore_ = new TypedHashMap(); private TypedHashMap orig_; private ArrayList rebuyOptions_ = new ArrayList(); private ArrayList addonOptions_ = new ArrayList(); private DDPanel base_; private DDTextField name_; private DDNumberSpinner numPlayers_; private DDNumberSpinner buyinCost_; private DDCheckBox rebuys_; private DDCheckBox addons_; private DDLabelBorder payout_; private DDNumberSpinner houseAmount_; private DDNumberSpinner spotPerc_; private DDNumberSpinner spotAmount_; private DDRadioButton buttonAuto_, buttonPerc_, buttonAmount_; private DDRadioButton buttonSatellite_; private boolean bDetailsTabReady_ = false; private SpotPanel spots_[] = new SpotPanel[TournamentProfile.MAX_SPOTS]; private String saveA_[] = new String[TournamentProfile.MAX_SPOTS]; private String saveP_[] = new String[TournamentProfile.MAX_SPOTS]; private int nNumSpots_ = 0; private DDRadioButton buttonSelected_; private DDButton clear_; private ButtonGroup buttonGroup_; private DDPanel spotsParent_; private JScrollPane spotscroll_; private DDLabel total_; private boolean bUpdating_ = false; private DDTabbedPane tabs_; private OpponentMixPanel oppmix_; private LevelsTab leveltab_; /** * help text area */ protected int getTextPreferredHeight() { return 55; } /** * create ui */ public JComponent getOptions() { TournamentProfile profile = (TournamentProfile) gamephase_.getObject(ProfileList.PARAM_PROFILE); ApplicationError.assertNotNull(profile, "No 'profile' in params"); // usually null, unless editing in-tournament game_ = (PokerGame) context_.getGame(); return getOptions(profile, STYLE); } /** * Get options using a specified profile */ public JComponent getOptions(TournamentProfile profile, String sStyle) { STYLE = sStyle; profile_ = profile; // save starting values for use during reset orig_ = new DMTypedHashMap(); orig_.putAll(profile_.getMap()); // init pool so it accepts changes in user input profile.setPrizePool(-1, false); // need opponent mix for okay processing oppmix_ = new OpponentMixPanel(profile_); leveltab_ = new LevelsTab(); base_ = new DDPanel(GuiManager.DEFAULT, STYLE); // used for colors in Sep // tabs ImageIcon error = ImageConfig.getImageIcon("taberror"); ImageIcon icon = ImageConfig.getImageIcon("ddlogo20"); tabs_ = new DDTabbedPane(STYLE, null, JTabbedPane.TOP); tabs_.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); tabs_.addTab("msg.description", icon, error, new DescTab()); tabs_.addTab("msg.levels", icon, error, leveltab_); tabs_.addTab("msg.tourdetails", icon, error, new DetailsTab()); tabs_.addTab("msg.opponentmix", icon, error, oppmix_); tabs_.addTab("msg.online", icon, error, new OnlineTab()); // return our base return tabs_; } /** * Base class for tabs which use options */ private abstract class OptionTab extends DDTabPanel { private ArrayList localOptions = new ArrayList(); OptionTab() { setPreferredSize(new Dimension(700, 420)); } protected void createUI() { createUILocal(); processUI(); } protected void processUI() { localOptions.clear(); GuiUtils.getDDOptions(this, localOptions); TournamentProfileDialog.this.doMapLoad(localOptions, true); TournamentProfileDialog.this.addListeners(localOptions); } protected void cleanUI() { localOptions.clear(); GuiUtils.getDDOptions(this, localOptions); TournamentProfileDialog.this.removeListeners(localOptions); } protected abstract void createUILocal(); } /** * set map on each option to actual tournament map */ private void doMapLoad(ArrayList options, boolean bResetToMap) { DDOption opt; for (int i = 0; i < options.size(); i++) { opt = ((DDOption) options.get(i)); opt.setMap(profile_.getMap()); if (bResetToMap) opt.resetToMap(); else opt.saveToMap(); } } /** * Description tab */ private class DescTab extends OptionTab { /** * create UI at start since this is the initial panel */ DescTab() { createUI(); } protected void createUILocal() { setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 5, VerticalFlowLayout.LEFT)); OptionText ot = new OptionText(null, "tournamentname", STYLE, dummy_, 30, "^.+$", 200, true); add(ot); name_ = ot.getTextField(); name_.addPropertyChangeListener("value", TournamentProfileDialog.this); name_.setText(profile_.getName()); add(new OptionTextArea(null, TournamentProfile.PARAM_DESC, STYLE, null, dummy_, 500, null, 12, 450)); add(new OptionTextArea(null, TournamentProfile.PARAM_GREETING, STYLE, null, dummy_, 500, null, 5, 450)); GuiUtils.setDDOptionLabelWidths(this); // after fixing widths, // don't add to option list so we don't reset/set map // we do this because profile name not stored in a // map (its a member of BaseProfile) ot.setIgnored(true); } /** * subclass can chime in on validity */ protected boolean isValidCheck() { return name_.isValidData(); } } /** * Levels tab */ private class LevelsTab extends OptionTab { protected void createUILocal() { add(new LevelsPanel(this), BorderLayout.WEST); } public void reset() { cleanUI(); removeAll(); if (isSelectedTab()) createUI(); repaint(); } } /** * Online tab */ private class OnlineTab extends OptionTab { protected void createUILocal() { DDPanel left = new DDPanel(); left.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 5, VerticalFlowLayout.LEFT)); add(left, BorderLayout.WEST); DDLabelBorder players = new DDLabelBorder("players", STYLE); players.setLayout(new GridLayout(0, 1, 0, -4)); left.add(players); GlassButton invitees = new GlassButton("invitees", "Glass"); invitees.setBorderGap(2, 4, 2, 4); invitees.setPreferredSize(new Dimension(75, 15)); invitees.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { TypedHashMap params = new TypedHashMap(); params.setObject(PlayerListDialog.PARAM_PLAYER_LIST, profile_.getInvitees()); context_.processPhaseNow("InvitedPlayerList", params); } }); OptionBoolean obs = new OptionBoolean(null, TournamentProfile.PARAM_INVITE_OBS, STYLE, dummy_, true); Dimension pref = obs.getPreferredSize(); pref.height = 15; obs.setPreferredSize(pref); OptionDummy db = new OptionDummy(invitees, obs); db.setBorder(BorderFactory.createEmptyBorder(2, 5, 3, 0)); db.setBorderLayoutGap(0, 10); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_INVITE_ONLY, STYLE, dummy_, true, db), players); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_ALLOW_DASH, STYLE, dummy_, true), players); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_ALLOW_ADVISOR, STYLE, dummy_, true), players); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_FILL_COMPUTER, STYLE, dummy_, true), players); OptionBoolean ob = OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_ALLOW_DEMO, STYLE, dummy_, true), players); // if running demo, don't let them shut out other demo users if (engine_.isDemo()) ob.setEnabled(false); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_ONLINE_ACTIVATED_ONLY, STYLE, dummy_, true), players); DDLabelBorder observers = new DDLabelBorder("observers", STYLE); left.add(observers); int nMin = (game_ != null && game_.isOnlineGame()) ? Math.max(game_.getNumObservers(), 0) : 0; OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_MAX_OBSERVERS, STYLE, dummy_, null, nMin, TournamentProfile.MAX_OBSERVERS, 50, true), observers); DDLabelBorder timeout = new DDLabelBorder("timeout", STYLE); left.add(timeout); DDPanel base = new DDPanel(); base.setLayout(new GridLayout(0, 1, 0, 4)); timeout.add(base, BorderLayout.CENTER); OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_TIMEOUT, STYLE, dummy_, null, TournamentProfile.MIN_TIMEOUT, TournamentProfile.MAX_TIMEOUT, 50, true), base); OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_THINKBANK, STYLE, dummy_, null, 0, TournamentProfile.MAX_THINKBANK, 50, true), base); /// /// boot disconnect/sitout /// DDLabelBorder bootbase = createBootControls(STYLE, dummy_, null); left.add(bootbase); } } /** * Boot controls labelborder. Static for use from GameInfoDialog (case where profile is non-null, to allow * changing of profile in-game) */ public static DDLabelBorder createBootControls(String STYLE, TypedHashMap dummy, TournamentProfile profile) { DDLabelBorder bootbase = new DDLabelBorder("boot", STYLE); bootbase.setLayout(new GridLayout(0, 1, 0, -4)); Dimension size; OptionBoolean disconnect, sitout; // disconnect OptionInteger disconnectCount = new OptionInteger(null, TournamentProfile.PARAM_BOOT_DISCONNECT_COUNT, STYLE, dummy, null, TournamentProfile.MIN_BOOT_HANDS, TournamentProfile.MAX_BOOT_HANDS, 60); disconnectCount.setEditable(true); disconnect = OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_BOOT_DISCONNECT, STYLE, dummy, true, disconnectCount), bootbase); if (profile != null) { disconnectCount.setMap(profile.getMap()); disconnectCount.resetToMap(); disconnect.setMap(profile.getMap()); disconnect.resetToMap(); } // sitout OptionInteger sitoutCount = new OptionInteger(null, TournamentProfile.PARAM_BOOT_SITOUT_COUNT, STYLE, dummy, null, TournamentProfile.MIN_BOOT_HANDS, TournamentProfile.MAX_BOOT_HANDS, 60); sitoutCount.setEditable(true); sitout = OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_BOOT_SITOUT, STYLE, dummy, true, sitoutCount), bootbase); if (profile != null) { sitoutCount.setMap(profile.getMap()); sitoutCount.resetToMap(); sitout.setMap(profile.getMap()); sitout.resetToMap(); } // size to same size = disconnect.getCheckBox().getPreferredSize(); size.width += 10; sitout.getCheckBox().setPreferredSize(size); disconnect.getCheckBox().setPreferredSize(size); return bootbase; } /** * money tab */ private class DetailsTab extends OptionTab { protected void createUI() { super.createUI(); // handle checkbox values checkBox(rebuys_); checkBox(addons_); // we are ready bDetailsTabReady_ = true; displayPrizePool(); checkButtons(); } protected void createUILocal() { DDPanel left = new DDPanel(); left.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 5, VerticalFlowLayout.LEFT)); add(left, BorderLayout.WEST); // num players / max at table DDPanel quantity = new DDPanel(); left.add(quantity); quantity.setBorderLayoutGap(0, 10); // num players int nMax = (game_ != null && game_.isOnlineGame()) ? TournamentProfile.MAX_ONLINE_PLAYERS : TournamentProfile.MAX_PLAYERS; int nMin = (game_ != null && game_.isOnlineGame()) ? Math.max(game_.getNumPlayers(), 2) : 2; OptionInteger oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_NUM_PLAYERS, STYLE, dummy_, null, nMin, nMax, 75, true), quantity, BorderLayout.WEST); oi.getSpinner().setUseBigStep(true); numPlayers_ = oi.getSpinner(); if (engine_.isDemo() && !TESTING(EngineConstants.TESTING_DEMO)) numPlayers_.setEnabled(false); // max at table oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_TABLE_SEATS, STYLE, dummy_, null, 2, PokerConstants.SEATS, 40, true), quantity, BorderLayout.CENTER); // buyin DDLabelBorder buyin = new DDLabelBorder("buyin", STYLE); left.add(buyin); buyin.add(createBuyIn(), BorderLayout.CENTER); // rebuy DDLabelBorder rebuy = new DDLabelBorder("rebuys", STYLE); left.add(rebuy); rebuy.add(createRebuy(), BorderLayout.CENTER); // addon DDLabelBorder addon = new DDLabelBorder("addons", STYLE); left.add(addon); addon.add(createAddon(), BorderLayout.CENTER); // payout/alloc DDPanel payalloc = new DDPanel(); payalloc.setBorderLayoutGap(10, 0); left.add(payalloc); // payout payout_ = new DDLabelBorder("payout", STYLE); payalloc.add(payout_, BorderLayout.NORTH); payout_.add(createPayout(), BorderLayout.CENTER); // adjust size based on payout Dimension ps = rebuy.getPreferredSize(); payout_.setPreferredWidth(ps.width); buyin.setPreferredWidth(ps.width); rebuy.setPreferredWidth(ps.width); addon.setPreferredWidth(ps.width); // allocation DDPanel format = new DDPanel(); format.setBorder(BorderFactory.createEmptyBorder(0, 0, 13, 0)); DDLabelBorder alloc = new DDLabelBorder("alloc", STYLE); add(format, BorderLayout.CENTER); format.add(alloc, BorderLayout.CENTER); alloc.add(createAlloc(), BorderLayout.CENTER); } /** * subclass can chime in on validity */ protected boolean isValidCheck() { return isTotalCorrect(getTotal()); } } /** * create levels */ private class LevelsPanel extends DDPanel implements ListSelectionListener, ActionListener { private GlassButton insertlevel; private GlassButton insertbreak; private GlassButton delete; private GlassButton verify; private ListPanel levelsList; private LevelsTab tab; public LevelsPanel(LevelsTab tab) { DDPanel base = this; this.tab = tab; base.setBorderLayoutGap(0, 20); // controls DDPanel controls = new DDPanel(); controls.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 10, VerticalFlowLayout.LEFT)); base.add(controls, BorderLayout.WEST); // game type OptionCombo combo = new OptionCombo(null, TournamentProfile.PARAM_GAMETYPE_DEFAULT, TournamentProfile.DATA_ELEMENT_GAMETYPE, STYLE, dummy_, 80, true); controls.add(combo); // minutes per level OptionInteger integer = new OptionInteger(null, TournamentProfile.PARAM_MINPERLEVEL_DEFAULT, STYLE, dummy_, null, 1, TournamentProfile.MAX_MINUTES, 50, true, true); controls.add(integer); // max raises integer = new OptionInteger(null, TournamentProfile.PARAM_MAXRAISES, STYLE, dummy_, null, 1, TournamentProfile.MAX_MAX_RAISES, 35, true, true); controls.add(integer); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_MAXRAISES_NONE_HEADSUP, STYLE, dummy_, true), controls); GuiUtils.setDDOptionLabelWidths(controls); // levels DDPanel levels = new DDPanel(); levels.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); levels.setBorderLayoutGap(5, 0); base.add(levels, BorderLayout.CENTER); // header LevelPanel llp; llp = new LevelPanel(null, new LevelListItem(TournamentProfileDialog.this, -1, false), STYLE); levels.add(llp, BorderLayout.NORTH); levels.setPreferredWidth(llp.getPreferredSize().width + 12); // panel with profile info levelsList = new ListPanel(LevelPanel.class, STYLE); levelsList.setFocusable(false); levelsList.addListSelectionListener(this); levels.add(levelsList, BorderLayout.CENTER); // add levels createLevels(); // bottom - buttons/double checkbox DDPanel bottompanel = new DDPanel(); bottompanel.setBorderLayoutGap(5, 0); levels.add(bottompanel, BorderLayout.SOUTH); // double at end DDPanel doublepanel = DDPanel.CENTER(); bottompanel.add(doublepanel, BorderLayout.NORTH); OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_DOUBLE, STYLE, dummy_, true), doublepanel, null); // control buttons DDPanel buttonpanel = new DDPanel(); buttonpanel.setLayout(new GridLayout(1, 0, 5, 0)); bottompanel.add(GuiUtils.CENTER(buttonpanel), BorderLayout.CENTER); insertlevel = new GlassButton("insertlevel", "Glass"); insertlevel.addActionListener(this); buttonpanel.add(insertlevel); insertbreak = new GlassButton("insertbreak", "Glass"); insertbreak.addActionListener(this); buttonpanel.add(insertbreak); delete = new GlassButton("deletelevel", "Glass"); delete.addActionListener(this); buttonpanel.add(delete); verify = new GlassButton("verify", "Glass"); verify.addActionListener(this); buttonpanel.add(verify); // init display levelsList.setSelectedIndex(0); checkButtons(); } private void createLevels() { ArrayList levelitems = new ArrayList(); for (int i = 0; i < profile_.getLastLevel(); i++) { levelitems.add(new LevelListItem(TournamentProfileDialog.this, i, profile_.isBreak(i + 1))); } levelsList.setItems(levelitems); } public void valueChanged(ListSelectionEvent e) { checkButtons(); } private void checkButtons() { LevelPanel selected = (LevelPanel) levelsList.getSelectedPanel(); int nIndex = levelsList.getSelectedIndex(); int size = levelsList.getItems().size(); insertlevel.setEnabled(selected != null && (selected.canDelete() || nIndex == (size - 1)) && size < TournamentProfile.MAX_LEVELS); insertbreak.setEnabled(selected != null && (selected.canDelete() || nIndex == (size - 1)) && size < TournamentProfile.MAX_LEVELS); delete.setEnabled(selected != null && selected.canDelete() && size > 1); } public void actionPerformed(ActionEvent e) { Object button = e.getSource(); if (button == insertlevel) insertLevel(); else if (button == insertbreak) insertBreak(); else if (button == delete) delete(); else if (button == verify) verify(); } private void insertLevel() { insertLevel(false); } private void insertBreak() { insertLevel(true); } private void insertLevel(boolean bBreak) { int index = levelsList.getSelectedIndex() + 1; LevelListItem item = new LevelListItem(TournamentProfileDialog.this, // use index at end to avoid // over-writing data. Will // get reset when update() called levelsList.getItems().size(), bBreak); levelsList.insertItem(index, item); LevelPanel lp = (LevelPanel) levelsList.getSelectedPanel(); if (bBreak) lp.minutes.requestFocus(); else lp.ante.requestFocus(); if (bBreak) profile_.setBreak(item.index + 1, 15); // load from map for new break level to get the minutes // for regular level, we save blank values to map to // init ArrayList newOptions = new ArrayList(); GuiUtils.getDDOptions(lp, newOptions); doMapLoad(newOptions, bBreak); TournamentProfileDialog.this.addListeners(newOptions); } private void delete() { // set dummy map so we won't get storage from focus lost LevelPanel panel = (LevelPanel) levelsList.getSelectedPanel(); ArrayList options = new ArrayList(); GuiUtils.getDDOptions(panel, options); DDOption dd; for (int i = 0; i < options.size(); i++) { dd = ((DDOption) options.get(i)); dd.setMap(dummy_); } // remove listeners too TournamentProfileDialog.this.removeListeners(options); // remove item int index = levelsList.getSelectedIndex(); levelsList.removeItem(index); // need to remove last item from map profile_.clearLevel(levelsList.getItems().size() + 1); } private void verify() { int nOldSelectedIndex = levelsList.getSelectedIndex(); profile_.fixLevels(); tab.cleanUI(); createLevels(); if (nOldSelectedIndex >= levelsList.getItems().size()) { nOldSelectedIndex = levelsList.getItems().size() - 1; } levelsList.setSelectedIndex(nOldSelectedIndex); tab.processUI(); repaint(); } } /** * track level for use with ListPanel/ListItemPanel support */ private class LevelListItem { public int index; public TournamentProfileDialog dialog; public boolean bBreak; public LevelListItem(TournamentProfileDialog dialog, int level, boolean bBreak) { this.dialog = dialog; this.index = level; this.bBreak = bBreak; } } /** * LevelPanel */ public static class LevelPanel extends ListItemPanel { DDLabel label; DDTextField ante, small, big, minutes; OptionText otAnte, otSmall, otBig, otMinutes; OptionCombo ocGame; DDOption dd; boolean canDelete = true; public boolean canDelete() { return canDelete; } public LevelPanel(ListPanel panel, Object item, String sStyle) { super(panel, item, sStyle); LevelListItem levelitem = (LevelListItem) item; int i = levelitem.index; boolean bBreak = levelitem.bBreak; TournamentProfileDialog dialog = levelitem.dialog; int nNum = i + 1; // if in-game, need to set display-only those levels that have passed TypedHashMap map = dialog.profile_.getMap(); boolean bDisplayOnly = false; if (nNum > 0 && dialog.game_ != null && dialog.game_.getLevel() > nNum && !(map.getString(TournamentProfile.PARAM_ANTE + nNum, "").length() == 0 && map.getString(TournamentProfile.PARAM_SMALL + nNum, "").length() == 0 && map.getString(TournamentProfile.PARAM_BIG + nNum, "").length() == 0) ) { bDisplayOnly = true; canDelete = false; } // negative i means label if (i < 0) { sStyle = "OptionsDialogInfo"; setDisplayOnly(true); } // layout setLayout(new HorizontalFlowLayout(HorizontalFlowLayout.LEFT, 5, 0, HorizontalFlowLayout.CENTER)); // label label = new DDLabel("level", sStyle); if (i >= 0) { label.setText(Integer.toString(nNum)); label.setPreferredSize(new Dimension(20, 20)); } else label.setPreferredSize(new Dimension(25, 12)); add(label); // NOTE: we ignore ante/small/big for a break since // we don't care about those values - this has effect of not // setting profile_'s map to these values // ante otAnte = dialog.createText(TournamentProfile.PARAM_ANTE, sStyle, 6, 60, i, "msg.header.ante", bBreak ? ".*" : "^[0-9]*$"); ante = otAnte.getTextField(); ante.addFocusListener(dialog); add(otAnte); if (bDisplayOnly || bBreak) { otAnte.setDisplayOnly(true); ante.setBorder(dialog.empty_); } if (bBreak) ante.setText(PropertyConfig.getMessage("msg.break.edit")); if (bBreak || i < 0) otAnte.setIgnored(true); // small otSmall = dialog.createText(TournamentProfile.PARAM_SMALL, sStyle, 7, 82, i, "msg.header.small", "^[0-9]*$"); small = otSmall.getTextField(); small.addFocusListener(dialog); add(otSmall); if (bDisplayOnly || bBreak) { otSmall.setDisplayOnly(true); small.setBorder(dialog.empty_); } if (bBreak || i < 0) otSmall.setIgnored(true); // big otBig = dialog.createText(TournamentProfile.PARAM_BIG, sStyle, 7, 82, i, "msg.header.big", "^[0-9]*$"); big = otBig.getTextField(); big.addFocusListener(dialog); add(otBig); if (bDisplayOnly || bBreak) { otBig.setDisplayOnly(true); big.setBorder(dialog.empty_); } if (bBreak || i < 0) otBig.setIgnored(true); // time otMinutes = dialog.createText(TournamentProfile.PARAM_MINUTES, sStyle, 3, 60, i, "msg.header.time", "^[0-9]*$"); minutes = otMinutes.getTextField(); minutes.addFocusListener(dialog); add(otMinutes); if (bDisplayOnly) { otMinutes.setDisplayOnly(true); minutes.setBorder(dialog.empty_); } if (i < 0) otMinutes.setIgnored(true); // game type if (!bBreak) { dd = dialog.createCombo(TournamentProfile.PARAM_GAMETYPE, TournamentProfile.DATA_ELEMENT_GAMETYPE, sStyle, 80, i, "msg.header.game", bDisplayOnly); add(dd); if (i >= 0 && !bDisplayOnly) { ocGame = (OptionCombo) dd; ocGame.getComboBox().addFocusListener(dialog); ocGame.getComboBox().setShowNotSelectedChoice(true); ocGame.getComboBox().setRequired(false); } if (i < 0 || bDisplayOnly) dd.setIgnored(true); } } public void update() { int index = getIndex(); LevelListItem levelitem = (LevelListItem) getItem(); int oldlevel = levelitem.index + 1; levelitem.index = index; int level = index + 1; label.setText(Integer.toString(level)); otAnte.setName(TournamentProfile.PARAM_ANTE + level); otSmall.setName(TournamentProfile.PARAM_SMALL + level); otBig.setName(TournamentProfile.PARAM_BIG + level); otMinutes.setName(TournamentProfile.PARAM_MINUTES + level); if (levelitem.bBreak) { int nMinutes = levelitem.dialog.profile_.getMinutes(oldlevel); //logger.debug("Update level " + level + " to " + nMinutes + " ("+oldlevel+")"); // note that old minutes may be incorrect if deleting, due to // order of update() calls by the ListPanel. However, in // those cases, it is fixed by saving the minutes to the map levelitem.dialog.profile_.setBreak(level, nMinutes); otMinutes.saveToMap(); // in case minutes defined in text field } else { otAnte.saveToMap(); otSmall.saveToMap(); otBig.saveToMap(); otMinutes.saveToMap(); //logger.debug("Update level " + level + " ("+oldlevel+") big now: "+otBig.getTextField().getText()); } } } /** * Buyin panel */ private JComponent createBuyIn() { OptionInteger oi; // buy in DDPanel buyin = new DDPanel(); buyin.setBorderLayoutGap(0, 5); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_BUYIN, STYLE, dummy_, null, 1, TournamentProfile.MAX_BUY, 70, true), buyin, BorderLayout.WEST); buyinCost_ = oi.getSpinner(); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_BUYINCHIPS, STYLE, dummy_, null, 1, TournamentProfile.MAX_CHIPS, 70, true), buyin, BorderLayout.CENTER); return buyin; } /** * Rebuy panel */ private JComponent createRebuy() { OptionInteger oi; OptionBoolean ob; // rebuys DDPanel rebuy = new DDPanel(); rebuy.setBorderLayoutGap(2, 0); ob = OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_REBUYS, STYLE, dummy_, false), rebuy, BorderLayout.NORTH); rebuys_ = ob.getCheckBox(); rebuys_.addActionListener(this); DDPanel rebuydata = new DDPanel(); rebuydata.setBorderLayoutGap(0, 5); rebuydata.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); rebuy.add(GuiUtils.WEST(rebuydata), BorderLayout.CENTER); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_REBUYCOST, STYLE, dummy_, null, 1, TournamentProfile.MAX_BUY, 70, true), rebuydata, BorderLayout.WEST); rebuyOptions_.add(oi); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_REBUYCHIPS, STYLE, dummy_, null, 1, TournamentProfile.MAX_CHIPS, 70, true), rebuydata, BorderLayout.CENTER); rebuyOptions_.add(oi); DDPanel rebuydata2 = new DDPanel(); rebuydata2.setBorderLayoutGap(0, 5); rebuydata2.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); rebuy.add(GuiUtils.WEST(rebuydata2), BorderLayout.SOUTH); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_REBUY_UNTIL, STYLE, dummy_, null, 1, TournamentProfile.MAX_LEVELS, 45, true), rebuydata2, BorderLayout.WEST); rebuyOptions_.add(oi); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_MAXREBUYS, STYLE, dummy_, null, 0, TournamentProfile.MAX_REBUYS, 45, true), rebuydata2, BorderLayout.CENTER); rebuyOptions_.add(oi); DDPanel rebuydata3 = new DDPanel(); rebuydata3.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); rebuydata2.add(rebuydata3, BorderLayout.SOUTH); ButtonGroup exprgroup = new ButtonGroup(); OptionRadio radio = OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_REBUYEXPR, STYLE, dummy_, "rebuyexpr.lte", exprgroup, PokerConstants.REBUY_LTE, null), rebuydata3); rebuyOptions_.add(radio); radio = OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_REBUYEXPR, STYLE, dummy_, "rebuyexpr.lt", exprgroup, PokerConstants.REBUY_LT, null), rebuydata3); rebuyOptions_.add(radio); Integer nDefault = profile_.getBuyinChips(); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_REBUYCHIPCNT, STYLE, dummy_, nDefault, 0, TournamentProfile.MAX_REBUY_CHIPS, 80, true), rebuydata3, BorderLayout.CENTER); rebuyOptions_.add(oi); return rebuy; } /** * addon panel */ private JComponent createAddon() { OptionInteger oi; OptionBoolean ob; // addons DDPanel addon = new DDPanel(); addon.setBorderLayoutGap(2, 0); ob = OptionMenu.add(new OptionBoolean(null, TournamentProfile.PARAM_ADDONS, STYLE, dummy_, false), addon, BorderLayout.NORTH); addons_ = ob.getCheckBox(); addons_.addActionListener(this); DDPanel addondata = new DDPanel(); addondata.setBorderLayoutGap(0, 5); addondata.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); addon.add(GuiUtils.WEST(addondata), BorderLayout.CENTER); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_ADDONCOST, STYLE, dummy_, null, 1, TournamentProfile.MAX_BUY, 70, true), addondata, BorderLayout.WEST); addonOptions_.add(oi); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_ADDONCHIPS, STYLE, dummy_, null, 1, TournamentProfile.MAX_CHIPS, 70, true), addondata, BorderLayout.CENTER); addonOptions_.add(oi); DDPanel addondata2 = new DDPanel(); addondata2.setBorderLayoutGap(0, 5); addondata2.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); addon.add(GuiUtils.WEST(addondata2), BorderLayout.SOUTH); oi = OptionMenu.add(new OptionInteger(null, TournamentProfile.PARAM_ADDONLEVEL, STYLE, dummy_, null, 1, TournamentProfile.MAX_LEVELS, 45, true), addondata2, BorderLayout.WEST); addonOptions_.add(oi); return addon; } /** * Payout panel */ private JComponent createPayout() { DDPanel base = new DDPanel(); base.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0)); DDPanel top = new DDPanel(); top.setBorderLayoutGap(0, 5); base.add(top, BorderLayout.NORTH); // payout type DDPanel typebase = new DDPanel(); typebase.setLayout(new GridLayout(0, 1, 0, -4)); top.add(typebase, BorderLayout.WEST); ButtonGroup payoutgroup = new ButtonGroup(); OptionInteger payoutperc = new OptionInteger(null, TournamentProfile.PARAM_PAYOUTPERC, STYLE, dummy_, null, 1, TournamentProfile.MAX_PERC, 47, true); spotPerc_ = payoutperc.getSpinner(); OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_PAYOUT, STYLE, dummy_, "payout.perc", payoutgroup, PokerConstants.PAYOUT_PERC, payoutperc), typebase); OptionInteger payoutnum = new OptionInteger(null, TournamentProfile.PARAM_PAYOUTNUM, STYLE, dummy_, null, 1, TournamentProfile.MAX_SPOTS, 47, true); spotAmount_ = payoutnum.getSpinner(); OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_PAYOUT, STYLE, dummy_, "payout.num", payoutgroup, PokerConstants.PAYOUT_SPOTS, payoutnum), typebase); OptionRadio radio = OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_PAYOUT, STYLE, dummy_, "payout.sat", payoutgroup, PokerConstants.PAYOUT_SATELLITE), typebase); buttonSatellite_ = radio.getRadioButton(); // sep JSeparator sep = new JSeparator(SwingConstants.VERTICAL); sep.setBackground(base_.getBackground().brighter()); sep.setForeground(base_.getBackground().darker()); top.add(sep, BorderLayout.CENTER); // house cut DDPanel housebase = new DDPanel(); housebase.setLayout(new GridLayout(0, 1, 0, -4)); top.add(GuiUtils.NORTH(housebase), BorderLayout.EAST); ButtonGroup housegroup = new ButtonGroup(); OptionInteger houseperc = new OptionInteger(null, TournamentProfile.PARAM_HOUSEPERC, STYLE, dummy_, null, 0, TournamentProfile.MAX_HOUSE_PERC, 55, true); OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_HOUSE, STYLE, dummy_, "house.perc", housegroup, PokerConstants.HOUSE_PERC, houseperc), housebase); OptionInteger houseamount = new OptionInteger(null, TournamentProfile.PARAM_HOUSEAMOUNT, STYLE, dummy_, null, 0, TournamentProfile.MAX_HOUSE_AMOUNT, 55, true); houseAmount_ = houseamount.getSpinner(); OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_HOUSE, STYLE, dummy_, "house.amount", housegroup, PokerConstants.HOUSE_AMOUNT, houseamount), housebase); return base; } /** * Allocation of payout */ private JComponent createAlloc() { DDPanel base = new DDPanel(); base.setBorderLayoutGap(5, 20); base.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // left panel DDPanel left = new DDPanel(); base.add(left, BorderLayout.WEST); // options OptionRadio radio; buttonGroup_ = new ButtonGroup(); DDPanel allocbase = new DDPanel(); allocbase.setLayout(new GridLayout(0, 1, 0, -4)); left.add(allocbase, BorderLayout.NORTH); radio = OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_ALLOC, STYLE, dummy_, "alloc.auto", buttonGroup_, PokerConstants.ALLOC_AUTO, null), allocbase); buttonAuto_ = radio.getRadioButton(); radio = OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_ALLOC, STYLE, dummy_, "alloc.perc", buttonGroup_, PokerConstants.ALLOC_PERC, null), allocbase); buttonPerc_ = radio.getRadioButton(); radio = OptionMenu.add(new OptionRadio(null, TournamentProfile.PARAM_ALLOC, STYLE, dummy_, "alloc.amount", buttonGroup_, PokerConstants.ALLOC_AMOUNT, null), allocbase); buttonAmount_ = radio.getRadioButton(); // clear button clear_ = new GlassButton("clear", "Glass"); left.add(GuiUtils.NORTH(GuiUtils.CENTER(clear_)), BorderLayout.CENTER); clear_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearSpots(); } }); // amount fields DDPanel center = new DDPanel(); center.setPreferredSize(new Dimension(100, 100)); base.add(center, BorderLayout.CENTER); spotsParent_ = new DDPanel(); spotsParent_.setLayout(new GridLayout(0, 1, 0, 2)); DDPanel format = new DDPanel(); format.add(spotsParent_, BorderLayout.NORTH); // scroll spotscroll_ = new DDScrollPane(format, STYLE, null, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); spotscroll_.setOpaque(false); GuiManager.addListeners(spotscroll_.getViewport()); GuiManager.addListeners(spotscroll_); spotscroll_.getVerticalScrollBar().setUnitIncrement(22); spotscroll_.getVerticalScrollBar().setBlockIncrement(88); center.add(spotscroll_, BorderLayout.CENTER); // label DDPanel labelnum = new DDPanel(); labelnum.setBorderLayoutGap(5, 0); center.add(labelnum, BorderLayout.NORTH); SpotPanel lsp; lsp = new SpotPanel(-1, STYLE); labelnum.add(lsp, BorderLayout.CENTER); // total total_ = new DDLabel(GuiManager.DEFAULT, STYLE); base.add(total_, BorderLayout.SOUTH); total_.setHorizontalAlignment(SwingConstants.CENTER); return base; } /** * Clear spots */ private void clearSpots() { // loop through all and calc total SpotPanel sp; for (int i = 0; i < TournamentProfile.MAX_SPOTS; i++) { sp = spots_[i]; if (sp == null) continue; sp.spot.setText(""); } } /** * Update paying spots */ private void updateSpots() { // levels SpotPanel sp; int nNum = profile_.getNumSpots(); if (buttonSatellite_.isSelected()) nNum = 1; DDRadioButton select = getSelectedButton(); // if no change in # spots or alloction type, skip if (select == null || (nNum == nNumSpots_ && select == buttonSelected_)) return; // remember new values DDRadioButton old = buttonSelected_; nNumSpots_ = nNum; buttonSelected_ = select; boolean bAuto = buttonAuto_.isSelected(); boolean bPerc = buttonPerc_.isSelected(); spotsParent_.removeAll(); for (int i = 0; i < TournamentProfile.MAX_SPOTS; i++) { sp = spots_[i]; if (sp == null && i < nNumSpots_) { sp = new SpotPanel(i, STYLE); spots_[i] = sp; } if (sp == null) continue; if (i < nNumSpots_) { if (sp.spot.isDisplayOnly() != bAuto) { sp.spot.setDisplayOnly(bAuto); if (bAuto) sp.spot.setBorder(empty_); else sp.spot.setBorder(DDTextField.TEXTBORDER); } if (!sp.spot.isEnabled()) sp.spot.setEnabled(true); if (bAuto) sp.spot.setRegExp("^.*$"); else if (bPerc) sp.spot.setRegExp("^([0-9\\,]*\\.?)\\%?|([0-9]*\\.([0-9][0-9][0-9]|[0-9][0-9]|[0-9]))\\%?$"); else sp.spot.setRegExp(PokerConstants.REGEXP_DOLLAR_AMOUNT); spotsParent_.add(sp); } else { // set hidden items disabled for validation reasons if (sp.spot.isEnabled()) sp.spot.setEnabled(false); } } // update spots if alloc type changed if (old != buttonSelected_ && old != null) { setSpots(buttonSelected_, old); } spotscroll_.revalidate(); spotscroll_.repaint(); } /** * set spot fields */ private void setSpots(DDRadioButton nu, DDRadioButton old) { // loop through all and calc total SpotPanel sp; String text; for (int i = 0; i < TournamentProfile.MAX_SPOTS; i++) { sp = spots_[i]; if (sp == null) continue; text = sp.spot.getText(); if (old == buttonAuto_ && (saveA_[i] == null || saveA_[i].length() == 0)) saveA_[i] = text; if (old == buttonAmount_) saveA_[i] = text; if (old == buttonPerc_) saveP_[i] = text; if (nu == buttonPerc_ && saveP_[i] != null && saveP_[i].length() > 0) { sp.spot.setText(saveP_[i]); } else if (nu == buttonAmount_ && saveA_[i] != null && saveA_[i].length() > 0) { sp.spot.setText(saveA_[i]); } else if (nu == buttonPerc_ || (nu == buttonAmount_ && old == buttonPerc_)) { sp.spot.setText(""); } } } /** * Set automatic spot percentages */ private void setAutoSpots() { profile_.setAutoSpots(); // loop through all and reset from new map value SpotPanel sp; for (int i = 0; i < TournamentProfile.MAX_SPOTS; i++) { sp = spots_[i]; if (sp == null) continue; sp.otspot.resetToMap(); } } /** * Get selected payout option (must be a way to use this using button group, but who cares) */ private DDRadioButton getSelectedButton() { if (buttonAuto_.isSelected()) return buttonAuto_; if (buttonPerc_.isSelected()) return buttonPerc_; if (buttonAmount_.isSelected()) return buttonAmount_; return null; } /** * Update paying spots total label. */ private void updateTotal() { double dTotal = getTotal(); // update text if (buttonSatellite_.isSelected()) { total_.setText(PropertyConfig.getMessage(isTotalCorrect(dTotal) ? "msg.total.sat.ok" : "msg.total.sat", dTotal)); } else if (buttonPerc_.isSelected()) { total_.setText(PropertyConfig.getMessage(isTotalCorrect(dTotal) ? "msg.total.perc.ok" : "msg.total.perc", fPerc.form(dTotal), fPerc.form(100.0d - dTotal))); } else { total_.setText(PropertyConfig.getMessage(isTotalCorrect(dTotal) ? "msg.total.amount.ok" : "msg.total.amount", dTotal, profile_.getPrizePool() - (int) dTotal)); } } /** * Return if total prizes are correct */ private boolean isTotalCorrect(double dTotal) { if (!bDetailsTabReady_) return true; double mustMatch; // get total validation if (buttonSatellite_.isSelected()) { return dTotal > 0; } else if (buttonPerc_.isSelected()) { mustMatch = 100.0d; } else { mustMatch = profile_.getPrizePool(); } return dTotal == mustMatch; } /** * Return total */ private double getTotal() { // loop through all and calc total SpotPanel sp; long dTotal = 0; long d; for (int i = 0; i < nNumSpots_; i++) { sp = spots_[i]; if (sp == null) continue; try { String text = sp.spot.getText(); StringBuilder sb = new StringBuilder(); char c; for (int j = 0; j < text.length(); j++) { c = text.charAt(j); if (c >= '0' && c <= '9' || c == '-' || c == '.') sb.append(c); } text = sb.toString(); d = (long) (Double.parseDouble(text) * TournamentProfile.ROUND_MULT); } catch (NumberFormatException nfe) { d = 0; } dTotal += d; //logger.debug(i + ": " + d + " = " + dTotal); } return ((double) dTotal) / (double) TournamentProfile.ROUND_MULT; } /** * SpotPanel */ private class SpotPanel extends DDPanel { int nNum; DDLabel label; DDTextField spot; OptionText otspot; public SpotPanel(int i, String sStyle) { super(GuiManager.DEFAULT, sStyle); // negative i means label if (i < 0) { sStyle = "OptionsDialogInfo"; } setLayout(new HorizontalFlowLayout(HorizontalFlowLayout.LEFT, 5, 0, HorizontalFlowLayout.CENTER)); nNum = i; // label label = new DDLabel("level", sStyle); if (i >= 0) { label.setText(Integer.toString(nNum + 1)); } label.setPreferredSize(new Dimension(30, 20)); add(label); // amount otspot = createText(TournamentProfile.PARAM_SPOTAMOUNT, sStyle, 11, 90, i, "msg.header.spotamount", "^.*$"); spot = otspot.getTextField(); spot.addFocusListener(TournamentProfileDialog.this); add(otspot); if (i < 0) otspot.setIgnored(true); // since these are added dynamically, make sure this dialog is // listened for changes and is initialized if (i >= 0 && bDetailsTabReady_) { checkChangeListener(otspot); otspot.setMap(profile_.getMap()); otspot.resetToMap(); } } } /** * monetary/numeric field */ private OptionText createText(String sName, String sStyle, int nDigits, int nWidth, int i, String sLabel, String sRegExp) { OptionText ot; DDTextField text; if (i >= 0) { ot = new OptionText(null, sName, sStyle, dummy_, nDigits, sRegExp, nWidth, false); text = ot.getTextField(); // change name used in map now that field has been created // and set default value. Use display level name ot.setName(sName + (i + 1)); ot.resetToDefault(); } else { ot = new OptionText(null, sName, sStyle, labelignore_, 100, "^.*$", nWidth, false); text = ot.getTextField(); text.setDisplayOnly(true); text.setText(PropertyConfig.getMessage(sLabel)); text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); } return ot; } /** * combo field (returns OptionText for label, OptionCombo for normal) */ private DDOption createCombo(String sName, String sDataElement, String sStyle, int nWidth, int i, String sLabel, boolean bDisplayOnly) { DDOption dd; DDTextField text; if (i >= 0 && !bDisplayOnly) { dd = new OptionCombo(null, sName, sDataElement, sStyle, dummy_, nWidth, false); // change name used in map now that field has been created // and set default value. Use display level name dd.setName(sName + (i + 1)); dd.resetToDefault(); } else { OptionText ot; dd = ot = new OptionText(null, sName, sStyle, labelignore_, 100, "^.*$", nWidth, false); text = ot.getTextField(); text.setDisplayOnly(true); if (i >= 0) { text.setText(profile_.getGameTypeDisplay(i + 1)); } else { text.setText(PropertyConfig.getMessage(sLabel)); } text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); } return dd; } /** * Focus to tabs */ protected Component getFocusComponent() { return tabs_; } /** * Default processButton calls closes dialog on any button press */ public boolean processButton(GameButton button) { setResult(Boolean.FALSE); return super.processButton(button); } /** * Okay button press */ protected void okayButton() { oppmix_.processOkay(); name_.removePropertyChangeListener(this); String sText = name_.getText(); String sCurrent = profile_.getName(); if (!sCurrent.equals(sText)) { profile_.setName(sText); } setResult(Boolean.TRUE); // set dummy map to prevent updates upon exiting (due to lost focus) DMTypedHashMap dummy = new DMTypedHashMap(); fillOptions(); DDOption dd; for (int i = 0; i < options_.size(); i++) { dd = ((DDOption) options_.get(i)); dd.setMap(dummy); } } /** * reset functionality - override to change map and reset to map */ protected void resetButton() { profile_.getMap().clear(); profile_.getMap().putAll(orig_); leveltab_.reset(); fillOptions(); DDOption dd; for (int i = 0; i < options_.size(); i++) { dd = ((DDOption) options_.get(i)); dd.resetToMap(); } } /** * Override to ignore non-Boolean results */ public void setResult(Object o) { if (o instanceof Boolean) { super.setResult(o); } } /** * name text change */ public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() == name_) { super.getDialog().setTitle(PropertyConfig.getMessage( "msg.windowtitle.tournamentProfileEdit.2", name_.getText().trim())); } if (evt.getPropertyName().equals("value")) checkButtons(); } /** * override to set prize pool amount */ public void checkButtons() { if (bDetailsTabReady_ && !bUpdating_) { bUpdating_ = true; // if satellite payout, we just want an amount if (buttonSatellite_.isSelected()) { buttonAmount_.setEnabled(true); if (!buttonAmount_.isSelected()) buttonAmount_.setSelected(true); buttonAuto_.setEnabled(false); buttonPerc_.setEnabled(false); } // no # spots to pay when rebuys on since total pool is not known else if (rebuys_.isSelected() || addons_.isSelected()) { buttonAuto_.setEnabled(true); buttonPerc_.setEnabled(true); if (buttonAmount_.isSelected()) buttonAuto_.setSelected(true); buttonAmount_.setEnabled(false); } else { buttonAmount_.setEnabled(true); buttonAuto_.setEnabled(true); buttonPerc_.setEnabled(true); } updateMaxValues(); displayPrizePool(); updateSpots(); if (buttonAuto_.isSelected()) { setAutoSpots(); } clear_.setEnabled(!buttonAuto_.isSelected()); updateTotal(); bUpdating_ = false; } // we do valid check automatically boolean bValid = tabs_.doValidCheck(); if (defaultButton_ != null) defaultButton_.setEnabled(bValid); } /** * check boxes */ public void actionPerformed(ActionEvent e) { checkBox(e.getSource()); } /** * Check box handling */ private void checkBox(Object o) { ArrayList list = null; boolean bOn = false; if (o == addons_) { list = addonOptions_; bOn = addons_.isSelected(); } else if (o == rebuys_) { list = rebuyOptions_; bOn = rebuys_.isSelected(); } if (list == null) return; DDOption ddOption; for (int i = 0; i < list.size(); i++) { ddOption = ((DDOption) list.get(i)); ddOption.setEnabled(bOn); ddOption.saveToMap(); // need to save values to map when enable } } /** * Set prize pool text */ private void displayPrizePool() { payout_.setText(PropertyConfig.getMessage("labelborder.payout.label", profile_.getPrizePool())); payout_.repaint(); } /** * Update max value */ private void updateMaxValues() { int nNumPlayers = numPlayers_.getValue(); // check max spot amount int nMax = profile_.getMaxPayoutSpots(nNumPlayers); if (nMax == 0) nMax = 1; int nValue = spotAmount_.getValue(); if (nValue > nMax) nValue = nMax; spotAmount_.setMax(nMax); spotAmount_.setValue(nValue); // max percentage is that which gets us closest to TournamentProfile.MAX_SPOTS nMax = profile_.getMaxPayoutPercent(nNumPlayers); if (nMax == 0) nMax = 1; nValue = spotPerc_.getValue(); if (nValue > nMax) nValue = nMax; spotPerc_.setMax(nMax); spotPerc_.setValue(nValue); // max house take can't be more than 50% of buyin int nNewMax = buyinCost_.getValue() / 2; if (nNewMax > TournamentProfile.MAX_HOUSE_AMOUNT) nNewMax = TournamentProfile.MAX_HOUSE_AMOUNT; nValue = houseAmount_.getValue(); nMax = houseAmount_.getMax(); if (nMax > nNewMax) { if (nValue > nNewMax) nValue = nNewMax; houseAmount_.setValue(nValue); } houseAmount_.setMax(nNewMax); } /** * scroll text to visible */ public void focusGained(FocusEvent e) { JComponent source = (JComponent) e.getSource(); JScrollPane p = GuiUtils.getScrollParent(source); if (p != null) { Point loc = source.getLocation(); loc = SwingUtilities.convertPoint(source.getParent(), loc, p.getViewport()); p.getViewport().scrollRectToVisible(new Rectangle(loc, source.getSize())); } } /** * EMPTY */ public void focusLost(FocusEvent e) { } }
412
0.919703
1
0.919703
game-dev
MEDIA
0.650821
game-dev,desktop-app
0.974195
1
0.974195
MohistMC/Youer
9,917
patches/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java.patch
--- a/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java +++ b/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java @@ -5,12 +_,14 @@ import com.mojang.logging.LogUtils; import com.mojang.serialization.Dynamic; import io.netty.buffer.ByteBuf; +import io.papermc.paper.adventure.PaperAdventure; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.function.Predicate; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; @@ -41,6 +_,12 @@ import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.saveddata.SavedData; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.map.CraftMapView; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.map.CraftMapCursor; +import org.bukkit.craftbukkit.map.RenderData; import org.slf4j.Logger; public class MapItemSavedData extends SavedData { @@ -65,6 +_,14 @@ private final Map<String, MapFrame> frameMarkers = Maps.newHashMap(); private int trackedDecorationCount; + // CraftBukkit start + public final CraftMapView mapView; + private CraftServer server; + public UUID uniqueId = null; + public MapId id; + // CraftBukkit end + public boolean isExplorerMap; // Purpur + public static SavedData.Factory<MapItemSavedData> factory() { return new SavedData.Factory<>(() -> { throw new IllegalStateException("Should never create an empty map saved data"); @@ -82,6 +_,10 @@ this.unlimitedTracking = p_164772_; this.locked = p_164773_; this.setDirty(); + // CraftBukkit start + mapView = new CraftMapView(this); + server = (CraftServer) org.bukkit.Bukkit.getServer(); + // CraftBukkit end } public static MapItemSavedData createFresh( @@ -100,9 +_,29 @@ } public static MapItemSavedData load(CompoundTag p_164808_, HolderLookup.Provider p_324560_) { + // CraftBukkit start ResourceKey<Level> resourcekey = DimensionType.parseLegacy(new Dynamic<>(NbtOps.INSTANCE, p_164808_.get("dimension"))) .resultOrPartial(LOGGER::error) - .orElseThrow(() -> new IllegalArgumentException("Invalid map dimension: " + p_164808_.get("dimension"))); + .orElseGet(() -> { + long least = p_164808_.getLong("UUIDLeast"); + long most = p_164808_.getLong("UUIDMost"); + + if (least != 0L && most != 0L) { + java.util.UUID uniqueId = new java.util.UUID(most, least); + + CraftWorld world = (CraftWorld) org.bukkit.Bukkit.getWorld(uniqueId); + // Check if the stored world details are correct. + if (world == null) { + /* All Maps which do not have their valid world loaded are set to a dimension which hopefully won't be reached. + This is to prevent them being corrupted with the wrong map data. */ + // PAIL: Use Vanilla exception handling for now + } else { + return world.getHandle().dimension(); + } + } + throw new IllegalArgumentException("Invalid map dimension: " + String.valueOf(p_164808_.get("dimension"))); + }); + // CraftBukkit end int i = p_164808_.getInt("xCenter"); int j = p_164808_.getInt("zCenter"); byte b0 = (byte)Mth.clamp(p_164808_.getByte("scale"), 0, 4); @@ -156,10 +_,32 @@ @Override public CompoundTag save(CompoundTag p_77956_, HolderLookup.Provider p_323858_) { - ResourceLocation.CODEC - .encodeStart(NbtOps.INSTANCE, this.dimension.location()) - .resultOrPartial(LOGGER::error) - .ifPresent(p_77954_ -> p_77956_.put("dimension", p_77954_)); + // CraftBukkit start + com.mojang.serialization.DataResult<net.minecraft.nbt.Tag> dataresult = ResourceLocation.CODEC.encodeStart(NbtOps.INSTANCE, this.dimension.location()); + Logger logger = LOGGER; + + Objects.requireNonNull(logger); + dataresult.resultOrPartial(logger::error).ifPresent((nbtbase) -> { + p_77956_.put("dimension", nbtbase); + }); + if (true) { + if (this.uniqueId == null) { + for (org.bukkit.World world : server.getWorlds()) { + CraftWorld cWorld = (CraftWorld) world; + if (cWorld.getHandle().dimension() == this.dimension) { + this.uniqueId = cWorld.getUID(); + break; + } + } + } + /* Perform a second check to see if a matching world was found, this is a necessary + change incase Maps are forcefully unlinked from a World and lack a UID.*/ + if (this.uniqueId != null) { + p_77956_.putLong("UUIDLeast", this.uniqueId.getLeastSignificantBits()); + p_77956_.putLong("UUIDMost", this.uniqueId.getMostSignificantBits()); + } + } + // CraftBukkit end p_77956_.putInt("xCenter", this.centerX); p_77956_.putInt("zCenter", this.centerZ); p_77956_.putByte("scale", this.scale); @@ -246,6 +_,7 @@ } MapFrame mapframe = new MapFrame(blockpos, itemframe.getDirection().get2DDataValue() * 90, itemframe.getId()); + if (this.decorations.size() < p_77919_.level().paperConfig().maps.itemFrameCursorLimit) { // Paper - Limit item frame cursors on maps this.addDecoration( MapDecorationTypes.FRAME, p_77919_.level(), @@ -256,6 +_,7 @@ null ); this.frameMarkers.put(mapframe.getId(), mapframe); + } // Paper - Limit item frame cursors on maps } MapDecorations mapdecorations = p_77920_.getOrDefault(DataComponents.MAP_DECORATIONS, MapDecorations.EMPTY); @@ -268,7 +_,7 @@ } } - public void removeDecoration(String p_164800_) { + private void removeDecoration(String p_164800_) { MapDecoration mapdecoration = this.decorations.remove(p_164800_); if (mapdecoration != null && mapdecoration.type().value().trackCount()) { this.trackedDecorationCount--; @@ -285,7 +_,7 @@ } } - public void addDecoration( + private void addDecoration( Holder<MapDecorationType> p_335830_, @Nullable LevelAccessor p_77939_, String p_77940_, @@ -407,7 +_,7 @@ return true; } - if (!this.isTrackedCountOverLimit(256)) { + if (!this.isTrackedCountOverLimit(((Level) p_77935_).paperConfig().maps.itemFrameCursorLimit)) { // Paper - Limit item frame cursors on maps this.bannerMarkers.put(mapbanner.getId(), mapbanner); this.addDecoration(mapbanner.getDecoration(), p_77935_, mapbanner.getId(), d0, d1, 180.0, mapbanner.name().orElse(null)); return true; @@ -506,7 +_,13 @@ this.player = p_77970_; } + private RenderData render; + private byte[] buffer; private MapItemSavedData.MapPatch createPatch() { + // CraftBukkit start + render = MapItemSavedData.this.mapView.render((CraftPlayer) this.player.getBukkitEntity()); + buffer = render.buffer; + int i = this.minDirtyX; int j = this.minDirtyY; int k = this.maxDirtyX + 1 - this.minDirtyX; @@ -515,15 +_,18 @@ for (int i1 = 0; i1 < k; i1++) { for (int j1 = 0; j1 < l; j1++) { - abyte[i1 + j1 * k] = MapItemSavedData.this.colors[i + i1 + (j + j1) * 128]; + abyte[i1 + j1 * k] = buffer[i + i1 + (j + j1) * 128]; } } + // CraftBukkit end return new MapItemSavedData.MapPatch(i, j, k, l, abyte); } @Nullable Packet<?> nextUpdatePacket(MapId p_324558_) { + RenderData render = MapItemSavedData.this.mapView.render((CraftPlayer) this.player.getBukkitEntity()); // CraftBukkit + MapItemSavedData.MapPatch mapitemsaveddata$mappatch; if (this.dirtyData) { this.dirtyData = false; @@ -533,9 +_,25 @@ } Collection<MapDecoration> collection; - if (this.dirtyDecorations && this.tick++ % 5 == 0) { + // CraftBukkit start + if ((true || this.dirtyDecorations) && this.tick++ % 5 == 0) { // custom maps don't update this yet this.dirtyDecorations = false; - collection = MapItemSavedData.this.decorations.values(); + + java.util.Collection<MapDecoration> icons = new java.util.ArrayList<MapDecoration>(); + + for (org.bukkit.map.MapCursor cursor : render.cursors) { + if (cursor.isVisible()) { + icons.add(new MapDecoration( + CraftMapCursor.CraftType.bukkitToMinecraftHolder(cursor.getType()), + cursor.getX(), + cursor.getY(), + cursor.getDirection(), + Optional.ofNullable(PaperAdventure.asVanilla(cursor.caption()) + ))); + } + } + collection = icons; + // CraftBukkit end } else { collection = null; }
412
0.764603
1
0.764603
game-dev
MEDIA
0.981364
game-dev
0.94446
1
0.94446
PentestSS13/Pentest
1,368
code/modules/antagonists/blood_contract/blood_contract.dm
/datum/antagonist/blood_contract name = "Blood Contract Target" show_in_roundend = FALSE show_in_antagpanel = FALSE show_name_in_check_antagonists = TRUE var/duration = 2 MINUTES /datum/antagonist/blood_contract/on_gain() . = ..() give_objective() start_the_hunt() /datum/antagonist/blood_contract/proc/give_objective() var/datum/objective/survive/survive = new survive.owner = owner objectives += survive /datum/antagonist/blood_contract/greet() . = ..() to_chat(owner, span_userdanger("You've been marked for death! Don't let the demons get you! KILL THEM ALL!")) /datum/antagonist/blood_contract/proc/start_the_hunt() var/mob/living/carbon/human/H = owner.current if(!istype(H)) return H.add_atom_colour("#FF0000", ADMIN_COLOUR_PRIORITY) var/obj/item/mine/pressure/pickup/bloodbath/B = new(H) B.duration = duration INVOKE_ASYNC(B, TYPE_PROC_REF(/obj/item/mine/pressure/pickup/bloodbath, mine_effect), H) //could use moving out from the mine for(var/mob/living/carbon/human/P in GLOB.player_list) if(P == H) continue to_chat(P, span_userdanger("You have an overwhelming desire to kill [H]. [H.p_theyve(TRUE)] been marked red! Whoever [H.p_they()] [H.p_were()], friend or foe, go kill [H.p_them()]!")) var/obj/item/I = new /obj/item/melee/knife/butcher(get_turf(P)) P.put_in_hands(I, del_on_fail=TRUE) QDEL_IN(I, duration)
412
0.916581
1
0.916581
game-dev
MEDIA
0.984616
game-dev
0.885985
1
0.885985
apache/incubator-pegasus
5,264
src/utils/autoref_ptr.h
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ #pragma once #include <atomic> #include <cassert> #include <type_traits> #include <utility> namespace dsn { class ref_counter { public: ref_counter() : _magic(0xdeadbeef), _counter(0) {} virtual ~ref_counter() { // 0xdeadbeef: 3735928559 assert(_magic == 0xdeadbeef); // 0xfacedead: 4207861421 _magic = 0xfacedead; } void add_ref() { // 0xdeadbeef: 3735928559 assert(_magic == 0xdeadbeef); // Increasing the reference counter can always be done with memory_order_relaxed: // New references to an object can only be formed from an existing reference, // and passing an existing reference from one thread to another must already provide any // required synchronization. _counter.fetch_add(1, std::memory_order_relaxed); } void release_ref() { // 0xdeadbeef: 3735928559 assert(_magic == 0xdeadbeef); // It is important to enforce any possible access to the object in one thread //(through an existing reference) to happen before deleting the object in a different // thread. // This is achieved by a "release" operation after dropping a reference //(any access to the object through this reference must obviously happened before), // and an "acquire" operation before deleting the object. // reference: http://www.boost.org/doc/libs/1_60_0/doc/html/atomic/usage_examples.html if (_counter.fetch_sub(1, std::memory_order_release) == 1) { std::atomic_thread_fence(std::memory_order_acquire); delete this; } } long get_count() const { return _counter.load(); } protected: unsigned int _magic; std::atomic<long> _counter; public: ref_counter(const ref_counter &) = delete; ref_counter &operator=(const ref_counter &) = delete; }; template <typename T> // T : ref_counter class ref_ptr { public: ref_ptr() : _obj(nullptr) {} ref_ptr(T *obj) : _obj(obj) { if (nullptr != _obj) _obj->add_ref(); } ref_ptr(const ref_ptr<T> &r) { _obj = r.get(); if (nullptr != _obj) _obj->add_ref(); } template <typename U, typename = typename std::enable_if<std::is_convertible<U *, T *>::value>::type> ref_ptr(const ref_ptr<U> &r) { _obj = r.get(); if (nullptr != _obj) _obj->add_ref(); } ref_ptr(ref_ptr<T> &&r) : _obj(r._obj) { r._obj = nullptr; } template <typename U, typename = typename std::enable_if<std::is_convertible<U *, T *>::value>::type> ref_ptr(ref_ptr<U> &&r) noexcept : _obj(r._obj) { r._obj = nullptr; } ~ref_ptr() { if (nullptr != _obj) { _obj->release_ref(); } } ref_ptr<T> &operator=(T *obj) { return *this = ref_ptr(obj); } ref_ptr<T> &operator=(ref_ptr<T> r) noexcept { swap(r); return *this; } template <typename U, typename = typename std::enable_if<std::is_convertible<U *, T *>::value>::type> ref_ptr<T> &operator=(ref_ptr<U> r) noexcept { ref_ptr<T> p(r); swap(p); return *this; } void swap(ref_ptr<T> &r) noexcept { std::swap(_obj, r._obj); } void reset(T *obj = nullptr) { *this = obj; } T *get() const { return _obj; } operator T *() const { return _obj; } T &operator*() const { return (*_obj); } T *operator->() const { return _obj; } bool operator==(const ref_ptr<T> &r) const { return _obj == r._obj; } template <typename U, typename = typename std::enable_if<std::is_convertible<U *, T *>::value>::type> bool operator==(const ref_ptr<U> &r) const { return _obj == r._obj; } bool operator==(T *r) const { return _obj == r; } bool operator!=(T *r) const { return _obj != r; } private: T *_obj; template <typename U> friend class ref_ptr; }; } // end namespace dsn
412
0.950338
1
0.950338
game-dev
MEDIA
0.185708
game-dev
0.969915
1
0.969915
BuildCraft/BuildCraft
2,328
common/buildcraft/lib/client/guide/parts/contents/PageLinkStatement.java
package buildcraft.lib.client.guide.parts.contents; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import net.minecraft.util.text.TextFormatting; import buildcraft.api.statements.IStatement; import buildcraft.lib.client.guide.PageLine; import buildcraft.lib.client.guide.entry.PageEntryStatement; import buildcraft.lib.client.guide.entry.PageValue; import buildcraft.lib.client.guide.parts.GuidePage; import buildcraft.lib.client.guide.parts.GuidePageFactory; import buildcraft.lib.gui.ISimpleDrawable; import buildcraft.lib.gui.statement.GuiElementStatementSource; public class PageLinkStatement extends PageLink { public final IStatement statement; public final List<String> tooltip; public final String searchText; public PageLinkStatement(boolean startVisible, IStatement statement) { super(createPageLine(statement), startVisible); this.statement = statement; List<String> tip = statement.getTooltip(); if (tip.isEmpty()) { String uniqueTag = statement.getUniqueTag(); this.tooltip = ImmutableList.of(uniqueTag); this.searchText = uniqueTag.toLowerCase(Locale.ROOT); } else { this.tooltip = tip; String joinedTooltip = tip.stream().collect(Collectors.joining(" ", "", "")); this.searchText = TextFormatting.getTextWithoutFormattingCodes(joinedTooltip).toLowerCase(Locale.ROOT); } } private static PageLine createPageLine(IStatement statement) { ISimpleDrawable icon = (x, y) -> GuiElementStatementSource.drawGuiSlot(statement, x, y); List<String> tooltip = statement.getTooltip(); String title = tooltip.isEmpty() ? statement.getUniqueTag() : tooltip.get(0); return new PageLine(icon, icon, 2, title, true); } @Override public String getSearchName() { return searchText; } @Override public List<String> getTooltip() { return tooltip.size() == 1 ? null : tooltip; } @Override public GuidePageFactory getFactoryLink() { // TODO: Populate this with useful information! return g -> new GuidePage(g, ImmutableList.of(), new PageValue<>(PageEntryStatement.INSTANCE, statement)); } }
412
0.808176
1
0.808176
game-dev
MEDIA
0.69445
game-dev
0.908213
1
0.908213
ryanjon2040/RTS-Community-Project
5,887
Plugins/VictoryPlugin/Source/VictoryEdEngine/Private/VictoryEdEngine.cpp
//Unreal Editor Fun With Rama #include "VictoryEdEnginePCH.h" #include "SlateBasics.h" #include "ScopedTransaction.h" #define LOCTEXT_NAMESPACE "VictoryEdEngine" const FName UVictoryEdEngine::VictoryEditorModeID = FName("VictoryEditorMode"); FMyEditorModeFactory::FMyEditorModeFactory() { } FMyEditorModeFactory::~FMyEditorModeFactory() { } void FMyEditorModeFactory::OnSelectionChanged( FEditorModeTools& Tools, UObject* ItemUndergoingChange ) const { //Super IEditorModeFactory::OnSelectionChanged(Tools, ItemUndergoingChange); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /* USelection* Selection = GEditor->GetSelectedActors(); if (ItemUndergoingChange != NULL && ItemUndergoingChange->IsSelected()) { AActor* SelectedActor = Cast<AActor>(ItemUndergoingChange); if (SelectedActor != NULL) { UPrimitiveComponent* PC = SelectedActor->GetRootPrimitiveComponent(); if (PC != NULL && PC->BodyInstance.bSimulatePhysics) { Tools.ActivateMode(FBuiltinEditorModes::EM_Physics); return; } } } else if (ItemUndergoingChange != NULL && !ItemUndergoingChange->IsA(USelection::StaticClass())) { Tools.DeactivateMode(FBuiltinEditorModes::EM_Physics); } */ } FEditorModeInfo FMyEditorModeFactory::GetModeInfo() const { return FEditorModeInfo(FBuiltinEditorModes::EM_Physics, NSLOCTEXT("EditorModes", "Rama Vertex Snap Mode", "Rama Vertex Snap Mode")); } TSharedRef<FEdMode> FMyEditorModeFactory::CreateMode() const { FVictoryEdAlignMode* EdPtr = new FVictoryEdAlignMode; //Joy Init! EdPtr->JoyInit(VictoryEd); //Victory Ed Set Before CreateMode() is called. //CreateMode() is called when the mode is registered return MakeShareable( EdPtr ); } UVictoryEdEngine::UVictoryEdEngine(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { CurrentVerticiesScale = 12; VertexDisplayChoice = 0; //stars DrawVerticiesMode = 2; //show all CreatedVictoryEdMode = false; PrevModeID = FBuiltinEditorModes::EM_Default; //Font static ConstructorHelpers::FObjectFinder<UFont> TheFontOb(TEXT("Font'/Engine/EngineFonts/RobotoDistanceField.RobotoDistanceField'")); VictoryEditorFont = (UFont*)TheFontOb.Object; } void UVictoryEdEngine::SwitchToVictoryEdMode() { //Create it if it not exist yet if(!CreatedVictoryEdMode) { //Create TSharedRef<FMyEditorModeFactory> Factory = MakeShareable( new FMyEditorModeFactory ); //Essential Link Factory->VictoryEd = this; //Register FEditorModeRegistry::Get().RegisterMode( VictoryEditorModeID, Factory ); //UE_LOG(Victory,Error, TEXT("RAMA VERTEX SNAP WAS JUST CREATED!!!: %s"), *VictoryEditorModeID.ToString() ); CreatedVictoryEdMode = true; } //~~~ Store Previous Editor Mode ~~~ TArray<FEdMode*> OutActiveModes; FEdMode* CurMode = NULL; GLevelEditorModeTools().GetActiveModes( OutActiveModes ); for(int32 Itr = 0; Itr < OutActiveModes.Num(); Itr++) { CurMode = OutActiveModes[Itr]; if(!CurMode) continue; if(CurMode->GetID() == VictoryEditorModeID ) continue; PrevModeID = CurMode->GetID(); //UE_LOG(Victory,Warning, TEXT("Previous Editor Mode: %s"), *CurMode->GetID().ToString() ); } //Activate Victory Editor Mode GLevelEditorModeTools().ActivateMode(VictoryEditorModeID); } bool UVictoryEdEngine::Exec( UWorld* InWorld, const TCHAR* Cmd, FOutputDevice& Ar) { bool bHandled = Super::Exec(InWorld,Cmd,Ar); //~~~~~~~~~~~~~~~ if ( FParse::Command(&Cmd,TEXT("VictoryConsole")) ) { VictoryConsole(); return true; } return bHandled; } void UVictoryEdEngine::VictoryConsole() { UE_LOG(Victory, Warning, TEXT("Victory!!!!")); } void UVictoryEdEngine::RunTests() { //tests } void UVictoryEdEngine::GetSelectedActorsRelativeOffsets() { SelectionRelativeOffsets.Empty(); //~~~~~~~~~~~~~~~~~~~~~~~~ //Get the Relative Offsets const FVector Origin = VSelectedActor->GetActorLocation(); AActor* VSelectItrActor; for(FSelectionIterator VSelectItr = GetSelectedActorIterator(); VSelectItr; ++VSelectItr ) { VSelectItrActor = Cast<AActor>(*VSelectItr); if(!VSelectItrActor) continue; //~~~~~~~~~~~~~~~~~~ SelectionRelativeOffsets.Add(VSelectItrActor->GetActorLocation() - Origin ); //UE_LOG(Victory, Error, TEXT("Relative offset %s"), *SelectionRelativeOffsets[SelectionRelativeOffsets.Num() - 1].ToString()); }; } void UVictoryEdEngine::NoteSelectionChange() { Super::NoteSelectionChange(); //~~~~~~~~~~~~~~~~~ if(!GetSelectedActors()) return; AActor* SelectedActor = Cast<AActor>(GetSelectedActors()->GetTop(AActor::StaticClass())); if(!SelectedActor) return; //~~~~~~~~~~~~~~~ //Not the Same? if(SelectedActor != VSelectedActor) { ClearSelectedVertex = true; } //Update VSelectedActor = SelectedActor; SelectedJoyISM = Cast<AJoyISM>(SelectedActor); if(!VSelectedActor) return; //Always Refresh SelectedActorVerticiesNeedsUpdating = true; //For use with multi-select moves GetSelectedActorsRelativeOffsets(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Only Activate for Static Mesh Actors Currently if(SelectedActor->IsA(AStaticMeshActor::StaticClass()) || SelectedActor->IsA(AJoyISM::StaticClass())) { //Switch to Victory Align Mode if not active already if(!GLevelEditorModeTools().IsModeActive(VictoryEditorModeID)) SwitchToVictoryEdMode(); } else { //Deactivate Mode for Non-Static Mesh Actors ExitVictoryAlignMode(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //RunTests(); //UE_LOG(Victory, Warning, TEXT("New Selected Actor %s"), *SelectedActor->GetName() ); //UE_LOG(Victory, Warning, TEXT("New Selected Actor Location %s"), *SelectedActor->GetActorLocation().ToString() ); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void UVictoryEdEngine::Tick(float DeltaSeconds, bool bIdleMode) { Super::Tick(DeltaSeconds,bIdleMode); }
412
0.908755
1
0.908755
game-dev
MEDIA
0.693901
game-dev
0.927237
1
0.927237
microsoft/PEACE
4,941
modules/HIE.py
import os os.sys.path.append(f"{os.path.dirname(os.path.realpath(__file__))}/..") import cv2 import json import collections from tool_pool import geological_knwoledge_type from utils import api, prompt, vision, common from agents import geologist_agent class hierarchical_information_extraction: def __init__(self): self.geologist = geologist_agent() def digitalize(self, image_path): image = cv2.imread(image_path) name = common.path2name(image_path) meta_path = os.path.join(common.cache_path(), "meta", name + ".json") if os.path.exists(meta_path): meta = json.loads(open(meta_path).read()) return meta # get headers of geologic map. meta = dict() meta["date"] = common.today_date() meta["name"] = name meta["version"] = "v1.0" meta["source"] = common.dataset_source meta["size"] = {"width": image.shape[1], "height": image.shape[0]} meta["regions"] = dict() meta["legend"] = dict() meta["information"] = dict() meta["faults"] = None # get layout of geologic map. map_layout = self.geologist.get_map_layout(image_path) regions = map_layout["regions"] meta["regions"] = regions # crop each component in geologic map. region_path_and_bbox = collections.defaultdict(list) for region_name, region_bndboxes in regions.items(): for i, region_bndbox in enumerate(region_bndboxes): region_path = os.path.join(common.cache_path(), "det", name, f"{region_name}_{i}.png") common.create_folder_by_file_path(region_path) vision.crop_and_save_image(image, region_bndbox, region_path) region_path_and_bbox[region_name].append((region_path, region_bndbox)) if "main_map" == region_name: # crop latitude and longitude region of geologic map. lonlat_name = "lonlat" lonlat_region_path = os.path.join(common.cache_path(), "det", name, f"{lonlat_name}_{i}.png") common.create_folder_by_file_path(lonlat_region_path) vision.crop_corners_and_save_image(region_path, lonlat_region_path) region_path_and_bbox[lonlat_name].append((lonlat_region_path, None)) elif "index_map" == region_name: # extend index map and add vision prompt. vision.annotate_image_with_directions(region_path, region_path) # get metadata of legend. if len(region_path_and_bbox["legend"]) > 0: legend_path, legend_bndbox = region_path_and_bbox["legend"][0] legend_metadata = self.geologist.get_legend_metadata(legend_path, legend_bndbox) legends = legend_metadata["legend"] for legend in legends.values(): legend["lithology"] = self.geologist.get_knowledge(geological_knwoledge_type.Rock_Type, legend["text"])["rock_type"] legend["stratigraphic_age"] = self.geologist.get_knowledge(geological_knwoledge_type.Rock_Age, legend["text"])["rock_age"] meta["legend"] = legends # get basic information of geologic map. region_names = ["title", "scale", "lonlat", "index_map"] for region_name in region_names: if region_name not in region_path_and_bbox: continue region_path, region_bndbox = region_path_and_bbox[region_name][0] keys, instruction = prompt.get_component_instruction(region_name) prompt_content = [ {"type": "image_url", "image_url": {"url": api.local_image_to_data_url(region_path)}}, {"type": "text", "text": instruction}, ] messages = [ {"role": "system", "content": prompt.system_prompt}, {"role": "user", "content": prompt_content}, ] answer = api.answer_wrapper(messages, structured=True) infos = eval(answer) key_value_pairs = prompt.get_basic_information(region_name, infos) for key, value in key_value_pairs: meta["information"][key] = value # get statistic information of rock. if len(region_path_and_bbox["main_map"]) > 0: main_map_path, main_map_bndbox = region_path_and_bbox["main_map"][0] vision.rock_region_seg(main_map_path, list(meta["legend"].values())) # output digitalization result of geologic map. common.create_folder_by_file_path(meta_path) with open(meta_path, "w", encoding="utf-8") as f: f.write(json.dumps(meta, indent=4, ensure_ascii=False)) return meta if __name__ == "__main__": image_path = "sample.jpg" hie = hierarchical_information_extraction() meta = hie.digitalize(image_path) print(meta)
412
0.643612
1
0.643612
game-dev
MEDIA
0.517792
game-dev
0.874214
1
0.874214
PiratesOnlineRewritten/Pirates-Online-Rewritten
3,795
pirates/effects/SimpleSmokeCloud.py
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.particles import ParticleEffect from direct.particles import Particles from direct.particles import ForceGroup from EffectController import EffectController from PooledEffect import PooledEffect import random class SimpleSmokeCloud(PooledEffect, EffectController): cardScale = 64.0 def __init__(self): PooledEffect.__init__(self) EffectController.__init__(self) model = loader.loadModel('models/effects/particleMaps') self.card = model.find('**/particleSmoke') if not SimpleSmokeCloud.particleDummy: SimpleSmokeCloud.particleDummy = render.attachNewNode(ModelNode('SimpleSmokeCloudParticleDummy')) SimpleSmokeCloud.particleDummy.setColorScaleOff() SimpleSmokeCloud.particleDummy.setDepthWrite(0) SimpleSmokeCloud.particleDummy.setLightOff() self.f = ParticleEffect.ParticleEffect('SimpleSmokeCloud') self.f.reparentTo(self) self.p0 = Particles.Particles('particles-1') self.p0.setFactory('ZSpinParticleFactory') self.p0.setRenderer('SpriteParticleRenderer') self.p0.setEmitter('SphereVolumeEmitter') self.f.addParticles(self.p0) self.p0.setPoolSize(3) self.p0.setBirthRate(0.1) self.p0.setLitterSize(1) self.p0.setLitterSpread(0) self.p0.setSystemLifespan(0.0) self.p0.setSystemGrowsOlderFlag(0) self.p0.factory.setLifespanBase(1.5) self.p0.factory.setLifespanSpread(0.25) self.p0.factory.setMassBase(1.0) self.p0.factory.setMassSpread(0.0) self.p0.factory.setTerminalVelocityBase(2000.0) self.p0.factory.setTerminalVelocitySpread(0.0) self.p0.factory.setInitialAngle(0.0) self.p0.factory.setInitialAngleSpread(180.0) self.p0.factory.enableAngularVelocity(0) self.p0.factory.setAngularVelocity(0.0) self.p0.factory.setAngularVelocitySpread(0.0) self.p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAOUT) self.p0.renderer.setUserAlpha(1.0) self.p0.renderer.setFromNode(self.card) self.p0.renderer.setColor(Vec4(1.0, 1.0, 1.0, 1.0)) self.p0.renderer.setXScaleFlag(1) self.p0.renderer.setYScaleFlag(1) self.p0.renderer.setAnimAngleFlag(1) self.p0.renderer.setNonanimatedTheta(0.0) self.p0.renderer.setAlphaBlendMethod(BaseParticleRenderer.PPNOBLEND) self.p0.renderer.setAlphaDisable(0) self.p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE) self.p0.emitter.setExplicitLaunchVector(Vec3(1.0, 0.0, 0.0)) self.p0.emitter.setRadiateOrigin(Point3(0.0, 0.0, 1.0)) self.setEffectScale(1.0) def createTrack(self): self.track = Sequence(Wait(0.1), Func(self.p0.setBirthRate, 0.1), Func(self.p0.clearToInitial), Func(self.f.start, self, self.particleDummy), Wait(1.0), Func(self.p0.setBirthRate, 100), Wait(3.0), Func(self.cleanUpEffect)) def setEffectScale(self, scale): self.p0.renderer.setInitialXScale(0.05 * self.cardScale * scale) self.p0.renderer.setFinalXScale(0.25 * self.cardScale * scale) self.p0.renderer.setInitialYScale(0.05 * self.cardScale * scale) self.p0.renderer.setFinalYScale(0.3 * self.cardScale * scale) self.p0.emitter.setAmplitude(6.0 * scale) self.p0.emitter.setAmplitudeSpread(2.0 * scale) self.p0.emitter.setOffsetForce(Vec3(2.5, 2.5, 5.0) * scale) self.p0.emitter.setRadius(6.0 * scale) def cleanUpEffect(self): EffectController.cleanUpEffect(self) self.checkInEffect(self) def destroy(self): EffectController.destroy(self) PooledEffect.destroy(self)
412
0.720032
1
0.720032
game-dev
MEDIA
0.53964
game-dev,graphics-rendering
0.5425
1
0.5425
moai/moai-beta
4,522
src/moaicore/MOAIBox2DFrictionJoint.cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <Box2D/Box2D.h> #include <moaicore/MOAIBox2DArbiter.h> #include <moaicore/MOAIBox2DBody.h> #include <moaicore/MOAIBox2DFrictionJoint.h> #include <moaicore/MOAIBox2DWorld.h> #include <moaicore/MOAILogMessages.h> SUPPRESS_EMPTY_FILE_WARNING #if USE_BOX2D //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name getMaxForce @text See Box2D documentation. @in MOAIBox2DFrictionJoint self @out number maxForce in kg * units / s^2, converted from N [kg * m / s^2]. */ int MOAIBox2DFrictionJoint::_getMaxForce ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DFrictionJoint, "U" ) float unitsToMeters = self->GetUnitsToMeters (); if ( !self->mJoint ) { MOAILog ( state, MOAILogMessages::MOAIBox2DJoint_MissingInstance ); return 0; } b2FrictionJoint* joint = ( b2FrictionJoint* )self->mJoint; state.Push ( joint->GetMaxForce () / unitsToMeters ); return 1; } //----------------------------------------------------------------// /** @name getMaxTorque @text See Box2D documentation. @in MOAIBox2DFrictionJoint self @out number maxTorque in (kg * units / s^2) * units, converted from N-m. */ int MOAIBox2DFrictionJoint::_getMaxTorque ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DFrictionJoint, "U" ) if ( !self->mJoint ) { MOAILog ( state, MOAILogMessages::MOAIBox2DJoint_MissingInstance ); return 0; } b2FrictionJoint* joint = ( b2FrictionJoint* )self->mJoint; float unitsToMeters = self->GetUnitsToMeters(); /* Convert to/from N-m (kg m / s^2) * m from/to (kg unit / s^2) * unit */ state.Push ( joint->GetMaxTorque () / ( unitsToMeters * unitsToMeters ) ); return 1; } //----------------------------------------------------------------// /** @name setMaxForce @text See Box2D documentation. @in MOAIBox2DFrictionJoint self @opt number maxForce in kg * units / s^2, converted to N [kg * m / s^2]. Default value is 0. @out nil */ int MOAIBox2DFrictionJoint::_setMaxForce ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DFrictionJoint, "U" ) float unitsToMeters = self->GetUnitsToMeters (); if ( !self->mJoint ) { MOAILog ( state, MOAILogMessages::MOAIBox2DJoint_MissingInstance ); return 0; } float maxForce = state.GetValue < float >( 2, 0.0f ) * unitsToMeters; b2FrictionJoint* joint = ( b2FrictionJoint* )self->mJoint; joint->SetMaxForce ( maxForce ); return 0; } //----------------------------------------------------------------// /** @name setMaxTorque @text See Box2D documentation. @in MOAIBox2DFrictionJoint self @opt number maxTorque in (kg * units / s^2) * units, converted to N-m. Default value is 0. @out nil */ int MOAIBox2DFrictionJoint::_setMaxTorque ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DFrictionJoint, "U" ) if ( !self->mJoint ) { MOAILog ( state, MOAILogMessages::MOAIBox2DJoint_MissingInstance ); return 0; } float unitsToMeters = self->GetUnitsToMeters(); /* Convert to/from N-m (kg m / s^2) * m from/to (kg unit / s^2) * unit */ float maxTorque = state.GetValue < float >( 2, 0.0f ) * unitsToMeters * unitsToMeters; b2FrictionJoint* joint = ( b2FrictionJoint* )self->mJoint; joint->SetMaxTorque ( maxTorque ); return 0; } //================================================================// // MOAIBox2DFrictionJoint //================================================================// //----------------------------------------------------------------// MOAIBox2DFrictionJoint::MOAIBox2DFrictionJoint () { RTTI_BEGIN RTTI_EXTEND ( MOAIBox2DJoint ) RTTI_END } //----------------------------------------------------------------// MOAIBox2DFrictionJoint::~MOAIBox2DFrictionJoint () { } //----------------------------------------------------------------// void MOAIBox2DFrictionJoint::RegisterLuaClass ( MOAILuaState& state ) { MOAIBox2DJoint::RegisterLuaClass ( state ); } //----------------------------------------------------------------// void MOAIBox2DFrictionJoint::RegisterLuaFuncs ( MOAILuaState& state ) { MOAIBox2DJoint::RegisterLuaFuncs ( state ); luaL_Reg regTable [] = { { "_getMaxForce", _getMaxForce }, { "_getMaxTorque", _getMaxTorque }, { "_setMaxForce", _setMaxForce }, { "_setMaxTorque", _setMaxTorque }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } #endif
412
0.741746
1
0.741746
game-dev
MEDIA
0.535202
game-dev
0.812501
1
0.812501
auser/beehive
3,806
lib/erlang/apps/beehive/src/bh_events/events/user_defined_event_handler.erl
%%%------------------------------------------------------------------- %%% File : user_defined_event_handler.erl %%% Author : Ari Lerner %%% Description : %%% %%% Created : Wed Nov 25 14:51:31 PST 2009 %%%------------------------------------------------------------------- -module (user_defined_event_handler). -include ("beehive.hrl"). -include ("common.hrl"). -behaviour(gen_event). %% gen_event callbacks -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]). %%==================================================================== %% gen_event callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} %% Description: Whenever a new event handler is added to an event manager, %% this function is called to initialize the event handler. %%-------------------------------------------------------------------- init([]) -> {ok, 500}. %%-------------------------------------------------------------------- %% Function: %% handle_event(Event, State) -> {ok, State} | %% {swap_handler, Args1, State1, Mod2, Args2} | %% remove_handler %% Description:Whenever an event manager receives an event sent using %% gen_event:notify/2 or gen_event:sync_notify/2, this function is called for %% each installed event handler to handle the event. %%-------------------------------------------------------------------- handle_event(Event, State) -> case config:search_for_application_value(user_defined_event_handler, undefined) of undefined -> ok; E -> case (catch E:handle_event(Event)) of {'EXIT', Msg} -> ?LOG(error, "Something bad is happening in Oz: ~p", [Msg]); _ -> ok end end, {ok, State}. %%-------------------------------------------------------------------- %% Function: %% handle_call(Request, State) -> {ok, Reply, State} | %% {swap_handler, Reply, Args1, State1, %% Mod2, Args2} | %% {remove_handler, Reply} %% Description: Whenever an event manager receives a request sent using %% gen_event:call/3,4, this function is called for the specified event %% handler to handle the request. %%-------------------------------------------------------------------- handle_call(_Request, State) -> Reply = ok, {ok, Reply, State}. %%-------------------------------------------------------------------- %% Function: %% handle_info(Info, State) -> {ok, State} | %% {swap_handler, Args1, State1, Mod2, Args2} | %% remove_handler %% Description: This function is called for each installed event handler when %% an event manager receives any other message than an event or a synchronous %% request (or a system message). %%-------------------------------------------------------------------- handle_info(_Info, State) -> {ok, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description:Whenever an event handler is deleted from an event manager, %% this function is called. It should be the opposite of Module:init/1 and %% do any necessary cleaning up. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- %% Function: code_change(OldVsn, State, Extra) -> {ok, NewState} %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}.
412
0.819095
1
0.819095
game-dev
MEDIA
0.147075
game-dev
0.759942
1
0.759942
kasper573/mp
4,252
apps/game-service/src/etc/movement-behavior.ts
import type { AreaId, CharacterId } from "@mp/db/types"; import type { AreaResource, Character, MovementTrait } from "@mp/game-shared"; import { getAreaIdFromObject, moveAlongPath } from "@mp/game-shared"; import type { InjectionContainer } from "@mp/ioc"; import type { Path, Vector, VectorLike } from "@mp/math"; import { assert, type Tile } from "@mp/std"; import type { TickEventHandler } from "@mp/time"; import { ctxArea, ctxGameEventClient, ctxGameState, ctxGameStateLoader, } from "../context"; export function movementBehavior(ioc: InjectionContainer): TickEventHandler { return function movementBehaviorTick({ timeSinceLastTick }) { const area = ioc.get(ctxArea); const state = ioc.get(ctxGameState); for (const actor of state.actors.values()) { // The dead don't move if (actor.combat.health <= 0) { actor.movement.path = undefined; actor.movement.moveTarget = undefined; continue; } // Consume the move target and produce a new path to move along if (actor.movement.moveTarget) { actor.movement.path = findPathForSubject( actor.movement, area, actor.movement.moveTarget, ); actor.movement.moveTarget = undefined; } moveAlongPath(actor.movement, timeSinceLastTick); // Process portals for (const object of area.hitTestObjects( area.tiled.tileCoordToWorld(actor.movement.coords), )) { const destinationAreaId = getAreaIdFromObject(object) as | AreaId | undefined; if ( destinationAreaId && actor.type === "character" && actor.movement.desiredPortalId === object.id ) { sendCharacterToArea(ioc, actor.identity.id, destinationAreaId); } } } }; } export function sendCharacterToArea( ioc: InjectionContainer, characterId: CharacterId, destinationAreaId: AreaId, coords?: Vector<Tile>, ) { const gameState = ioc.get(ctxGameState); const currentArea = ioc.get(ctxArea); const char = assert( gameState.actors.get(characterId), `Character ${characterId} not found in game state`, ) as Character; // Actors area ids are only stored in the database. // What controls which area an actor is associated with at runtime is simply if it's been added to a game server instance. // Each game service instance only houses one specific area, // so adding an actor to a game servers game state is equal to adding it to that area. char.movement.path = undefined; char.movement.desiredPortalId = undefined; // If we're portalling within the same area we can just change coords if (destinationAreaId === currentArea.id) { char.movement.coords = coords ?? currentArea.start; return; } // Since moving to another area means to remove the character from the current game service, // any mutations that's been done to this character this server tick would be lost unless we save them explicitly right now, // since regular persistence is done on interval, an interval which we would miss here. const loader = ioc.get(ctxGameStateLoader); void loader.saveCharacterToDb(char); // But if we're moving to a different area we must communicate // with other services and tell them to pick up this character. // RISK: Removing the character and blindly trusting other services to // reinstate them in their instance may lead to characters being left in the void. // It's a minor risk. At worst, the player will have disconnect and // reconnect to have a game service pick them up again. gameState.actors.delete(characterId); // Inform other services that the character wants to join another area const client = ioc.get(ctxGameEventClient); client.network.changeGameService({ characterId, areaId: destinationAreaId, }); } export function findPathForSubject( subject: MovementTrait, area: AreaResource, dest: VectorLike<Tile>, ): Path<Tile> | undefined { const fromNode = area.graph.getProximityNode(subject.coords); if (!fromNode) { return; } const destNode = area.graph.getProximityNode(dest); if (!destNode) { return; } return area.graph.findPath(fromNode, destNode); }
412
0.898073
1
0.898073
game-dev
MEDIA
0.829815
game-dev
0.948556
1
0.948556
Suprcode/Zircon
1,742
ServerLibrary/Models/Monsters/PachontheChaosbringer.cs
using Library; using Server.Envir; using System; namespace Server.Models.Monsters { public class PachontheChaosbringer : MonsterObject { public DateTime CastTime; protected override bool InAttackRange() { if (Target.CurrentMap != CurrentMap) return false; return Target.CurrentLocation != CurrentLocation && Functions.InRange(CurrentLocation, Target.CurrentLocation, 2); } public override void ProcessTarget() { if (Target == null) return; if (!Functions.InRange(Target.CurrentLocation, CurrentLocation, 8) && SEnvir.Now > CastTime) { MirDirection dir = Functions.DirectionFromPoint(CurrentLocation, Target.CurrentLocation); Cell cell = null; for (int i = 0; i < 8; i++) { cell = CurrentMap.GetCell(Functions.Move(Target.CurrentLocation, Functions.ShiftDirection(dir, i), 1)); if (cell == null || cell.Movements != null) { cell = null; continue; } break; } if (cell != null) { Direction = Functions.DirectionFromPoint(cell.Location, Target.CurrentLocation); Teleport(CurrentMap, cell.Location); CastTime = SEnvir.Now.AddSeconds(10); } } else if (InAttackRange() && SEnvir.Now > CastTime) { CastTime = SEnvir.Now.AddSeconds(20); DragonRepulse(); } base.ProcessTarget(); } } }
412
0.958051
1
0.958051
game-dev
MEDIA
0.951582
game-dev
0.95498
1
0.95498
krkrz/krkrz
3,045
tjs2/tjsGlobalStringMap.cpp
//--------------------------------------------------------------------------- /* TJS2 Script Engine Copyright (C) 2000 W.Dee <dee@kikyou.info> and contributors See details of license at "license.txt" */ //--------------------------------------------------------------------------- // TJS Global String Map //--------------------------------------------------------------------------- #include "tjsCommHead.h" #include "tjsGlobalStringMap.h" #include "tjsHashSearch.h" /* Global String Map is a large string hash table, to share the string which is already 'known' by the hash table, using TJS2 string heap management mechanism. This will dramatically decrease string heap size which is used for constant strings (member names, string literals, etc ...). */ #define TJS_GLOBAL_STRING_MAP_SIZE 5000 namespace TJS { //--------------------------------------------------------------------------- // tTJSGlobalStringMap - hash map to keep constant strings shared //--------------------------------------------------------------------------- class tTJSGlobalStringMap; static tTJSGlobalStringMap * TJSGlobalStringMap = NULL; struct tTJSEmptyClass {}; class tTJSGlobalStringMap { tTJSHashCache<tTJSString, tTJSEmptyClass, tTJSHashFunc<ttstr>, 1024> Hash; tjs_int RefCount; public: tTJSGlobalStringMap() : Hash (TJS_GLOBAL_STRING_MAP_SIZE) { RefCount = 1; TJSGlobalStringMap = this; } protected: ~tTJSGlobalStringMap() { TJSGlobalStringMap = NULL; } public: tTJSString _Map(const tTJSString & string) { // Search Hash, and return the string which to be shared const tTJSString * key; tTJSEmptyClass * v; tjs_uint32 hash = tTJSHashFunc<ttstr>::Make(string); if(Hash.FindAndTouchWithHash(string, hash, key, v)) { ttstr ret(*key); if(ret.GetHint()) *(ret.GetHint()) = hash; return ret; } else { Hash.AddWithHash(string, hash, tTJSEmptyClass()); ttstr ret(string); if(ret.GetHint()) *(ret.GetHint()) = hash; return ret; } } protected: void _AddRef() { RefCount ++; } void _Release() { if(RefCount == 1) delete this; else RefCount --; } public: static void AddRef() { if(TJSGlobalStringMap) TJSGlobalStringMap->_AddRef(); else new tTJSGlobalStringMap(); } static void Release() { if(TJSGlobalStringMap) TJSGlobalStringMap->_Release(); } static ttstr Map(const ttstr & string) { if(TJSGlobalStringMap) return TJSGlobalStringMap->_Map(string); else return string; } }; //--------------------------------------------------------------------------- void TJSAddRefGlobalStringMap() { tTJSGlobalStringMap::AddRef(); } //--------------------------------------------------------------------------- void TJSReleaseGlobalStringMap() { tTJSGlobalStringMap::Release(); } //--------------------------------------------------------------------------- ttstr TJSMapGlobalStringMap(const ttstr & string) { return tTJSGlobalStringMap::Map(string); } //--------------------------------------------------------------------------- } // namespace TJS
412
0.622147
1
0.622147
game-dev
MEDIA
0.257343
game-dev
0.559648
1
0.559648
TencentBlueKing/bk-bcs
3,973
bcs-scenarios/kourse/pkg/client/listers/tkex/v1alpha1/gamestatefulset.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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. * */ // Code generated by lister-gen. DO NOT EDIT. package v1alpha1 import ( v1alpha1 "github.com/Tencent/bk-bcs/bcs-scenarios/kourse/pkg/apis/tkex/v1alpha1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) // GameStatefulSetLister helps list GameStatefulSets. // All objects returned here must be treated as read-only. type GameStatefulSetLister interface { // List lists all GameStatefulSets in the indexer. // Objects returned here must be treated as read-only. List(selector labels.Selector) (ret []*v1alpha1.GameStatefulSet, err error) // GameStatefulSets returns an object that can list and get GameStatefulSets. GameStatefulSets(namespace string) GameStatefulSetNamespaceLister GameStatefulSetListerExpansion } // gameStatefulSetLister implements the GameStatefulSetLister interface. type gameStatefulSetLister struct { indexer cache.Indexer } // NewGameStatefulSetLister returns a new GameStatefulSetLister. func NewGameStatefulSetLister(indexer cache.Indexer) GameStatefulSetLister { return &gameStatefulSetLister{indexer: indexer} } // List lists all GameStatefulSets in the indexer. func (s *gameStatefulSetLister) List(selector labels.Selector) (ret []*v1alpha1.GameStatefulSet, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.GameStatefulSet)) }) return ret, err } // GameStatefulSets returns an object that can list and get GameStatefulSets. func (s *gameStatefulSetLister) GameStatefulSets(namespace string) GameStatefulSetNamespaceLister { return gameStatefulSetNamespaceLister{indexer: s.indexer, namespace: namespace} } // GameStatefulSetNamespaceLister helps list and get GameStatefulSets. // All objects returned here must be treated as read-only. type GameStatefulSetNamespaceLister interface { // List lists all GameStatefulSets in the indexer for a given namespace. // Objects returned here must be treated as read-only. List(selector labels.Selector) (ret []*v1alpha1.GameStatefulSet, err error) // Get retrieves the GameStatefulSet from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. Get(name string) (*v1alpha1.GameStatefulSet, error) GameStatefulSetNamespaceListerExpansion } // gameStatefulSetNamespaceLister implements the GameStatefulSetNamespaceLister // interface. type gameStatefulSetNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all GameStatefulSets in the indexer for a given namespace. func (s gameStatefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.GameStatefulSet, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.GameStatefulSet)) }) return ret, err } // Get retrieves the GameStatefulSet from the indexer for a given namespace and name. func (s gameStatefulSetNamespaceLister) Get(name string) (*v1alpha1.GameStatefulSet, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1alpha1.Resource("gamestatefulset"), name) } return obj.(*v1alpha1.GameStatefulSet), nil }
412
0.816263
1
0.816263
game-dev
MEDIA
0.748083
game-dev
0.905322
1
0.905322
opentibiabr/otservbr-global
7,066
data/npc/rachel.lua
local internalNpcName = "Rachel" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 136, lookHead = 58, lookBody = 84, lookLegs = 86, lookFeet = 114, lookAddons = 0 } npcConfig.flags = { floorchange = false } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end keywordHandler:addKeyword({"magic"}, StdModule.say, { npcHandler = npcHandler, text = "Okay, then just browse through all of my wares." } ) local items = { [VOCATION.BASE_ID.SORCERER] = 3074, [VOCATION.BASE_ID.DRUID] = 3066 } local function creatureSayCallback(npc, creature, type, message) local player = Player(creature) local playerId = player:getId() if not npcHandler:checkInteraction(npc, creature) then return false end local itemId = items[player:getVocation():getBaseId()] if MsgContains(message, "first rod") or MsgContains(message, "first wand") then if player:isMage() then if player:getStorageValue(Storage.firstMageWeapon) == -1 then npcHandler:say("So you ask me for a {" .. ItemType(itemId):getName() .. "} to begin your adventure?", npc, creature) npcHandler:setTopic(playerId, 1) else npcHandler:say("What? I have already gave you one {" .. ItemType(itemId):getName() .. "}!", npc, creature) end else npcHandler:say("Sorry, you aren't a druid either a sorcerer.", npc, creature) end elseif MsgContains(message, "yes") then if npcHandler:getTopic(playerId) == 1 then player:addItem(itemId, 1) npcHandler:say("Here you are young adept, take care yourself.", npc, creature) player:setStorageValue(Storage.firstMageWeapon, 1) end npcHandler:setTopic(playerId, 0) elseif MsgContains(message, "no") and npcHandler:getTopic(playerId) == 1 then npcHandler:say("Ok then.", npc, creature) npcHandler:setTopic(playerId, 0) end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:setMessage(MESSAGE_GREET, "Welcome |PLAYERNAME|! Whats your need?") npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye, |PLAYERNAME|.") npcHandler:setMessage(MESSAGE_WALKAWAY, "Good bye, |PLAYERNAME|.") npcHandler:setMessage(MESSAGE_SENDTRADE, "Of course, just browse through my wares. \z Or do you want to look only at {potions}, {wands} or {runes}?") npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) npcConfig.shop = { { itemName = "avalanche rune", clientId = 3161, buy = 57 }, { itemName = "blank rune", clientId = 3147, buy = 10 }, { itemName = "chameleon rune", clientId = 3178, buy = 210 }, { itemName = "convince creature rune", clientId = 3177, buy = 80 }, { itemName = "cure poison rune", clientId = 3153, buy = 65 }, { itemName = "destroy field rune", clientId = 3148, buy = 15 }, { itemName = "durable exercise rod", clientId = 35283, buy = 945000, count = 1800 }, { itemName = "durable exercise wand", clientId = 35284, buy = 945000, count = 1800 }, { itemName = "empty potion flask", clientId = 283, sell = 5 }, { itemName = "empty potion flask", clientId = 284, sell = 5 }, { itemName = "empty potion flask", clientId = 285, sell = 5 }, { itemName = "energy field rune", clientId = 3164, buy = 38 }, { itemName = "energy wall rune", clientId = 3166, buy = 85 }, { itemName = "exercise rod", clientId = 28556, buy = 262500, count = 500 }, { itemName = "exercise wand", clientId = 28557, buy = 262500, count = 500 }, { itemName = "explosion rune", clientId = 3200, buy = 31 }, { itemName = "fire bomb rune", clientId = 3192, buy = 147 }, { itemName = "fire field rune", clientId = 3188, buy = 28 }, { itemName = "fire wall rune", clientId = 3190, buy = 61 }, { itemName = "great fireball rune", clientId = 3191, buy = 57 }, { itemName = "great health potion", clientId = 239, buy = 225 }, { itemName = "great mana potion", clientId = 238, buy = 144 }, { itemName = "great spirit potion", clientId = 7642, buy = 228 }, { itemName = "health potion", clientId = 266, buy = 50 }, { itemName = "heavy magic missile rune", clientId = 3198, buy = 12 }, { itemName = "intense healing rune", clientId = 3152, buy = 95 }, { itemName = "lasting exercise rod", clientId = 35289, buy = 7560000, count = 14400 }, { itemName = "lasting exercise wand", clientId = 35290, buy = 7560000, count = 14400 }, { itemName = "light magic missile rune", clientId = 3174, buy = 4 }, { itemName = "mana potion", clientId = 268, buy = 56 }, { itemName = "moonlight rod", clientId = 3070, buy = 1000 }, { itemName = "necrotic rod", clientId = 3069, buy = 5000 }, { itemName = "poison field rune", clientId = 3172, buy = 21 }, { itemName = "poison wall rune", clientId = 3176, buy = 52 }, { itemName = "snakebite rod", clientId = 3066, buy = 500 }, { itemName = "spellbook", clientId = 3059, buy = 150 }, { itemName = "spellwand", clientId = 651, sell = 299 }, { itemName = "stalagmite rune", clientId = 3179, buy = 12 }, { itemName = "strong health potion", clientId = 236, buy = 115 }, { itemName = "strong mana potion", clientId = 237, buy = 93 }, { itemName = "sudden death rune", clientId = 3155, buy = 135 }, { itemName = "talon", clientId = 3034, sell = 320 }, { itemName = "terra rod", clientId = 3065, buy = 10000 }, { itemName = "ultimate healing rune", clientId = 3160, buy = 175 }, { itemName = "ultimate health potion", clientId = 7643, buy = 379 }, { itemName = "vial", clientId = 2874, sell = 5 }, { itemName = "wand of cosmic energy", clientId = 3073, buy = 10000 }, { itemName = "wand of decay", clientId = 3072, buy = 5000 }, { itemName = "wand of dragonbreath", clientId = 3075, buy = 1000 }, { itemName = "wand of vortex", clientId = 3074, buy = 500 } } -- On buy npc shop message npcType.onBuyItem = function(npc, player, itemId, subType, amount, ignore, inBackpacks, totalCost) npc:sellItem(player, itemId, amount, subType, 0, ignore, inBackpacks) end -- On sell npc shop message npcType.onSellItem = function(npc, player, itemId, subtype, amount, ignore, name, totalCost) player:sendTextMessage(MESSAGE_INFO_DESCR, string.format("Sold %ix %s for %i gold.", amount, name, totalCost)) end -- On check npc shop message (look item) npcType.onCheckItem = function(npc, player, clientId, subType) end npcType:register(npcConfig)
412
0.89727
1
0.89727
game-dev
MEDIA
0.853712
game-dev
0.704748
1
0.704748
cocos2d/cocos2d-x-samples
3,483
samples/SwiftTetris/cocos2d/external/Box2D/Collision/Shapes/b2PolygonShape.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_POLYGON_SHAPE_H #define B2_POLYGON_SHAPE_H #include <Box2D/Collision/Shapes/b2Shape.h> /// A convex polygon. It is assumed that the interior of the polygon is to /// the left of each edge. /// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. /// In most cases you should not need many vertices for a convex polygon. class b2PolygonShape : public b2Shape { public: b2PolygonShape(); /// Implement b2Shape. b2Shape* Clone(b2BlockAllocator* allocator) const; /// @see b2Shape::GetChildCount int32 GetChildCount() const; /// Create a convex hull from the given array of local points. /// The count must be in the range [3, b2_maxPolygonVertices]. /// @warning the points may be re-ordered, even if they form a convex polygon /// @warning collinear points are handled but not removed. Collinear points /// may lead to poor stacking behavior. void Set(const b2Vec2* points, int32 count); /// Build vertices to represent an axis-aligned box centered on the local origin. /// @param hx the half-width. /// @param hy the half-height. void SetAsBox(float32 hx, float32 hy); /// Build vertices to represent an oriented box. /// @param hx the half-width. /// @param hy the half-height. /// @param center the center of the box in local coordinates. /// @param angle the rotation of the box in local coordinates. void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); /// @see b2Shape::TestPoint bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; /// Implement b2Shape. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeAABB void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const; /// @see b2Shape::ComputeMass void ComputeMass(b2MassData* massData, float32 density) const; /// Get the vertex count. int32 GetVertexCount() const { return m_count; } /// Get a vertex by index. const b2Vec2& GetVertex(int32 index) const; /// Validate convexity. This is a very time consuming operation. /// @returns true if valid bool Validate() const; b2Vec2 m_centroid; b2Vec2 m_vertices[b2_maxPolygonVertices]; b2Vec2 m_normals[b2_maxPolygonVertices]; int32 m_count; }; inline b2PolygonShape::b2PolygonShape() { m_type = e_polygon; m_radius = b2_polygonRadius; m_count = 0; m_centroid.SetZero(); } inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const { b2Assert(0 <= index && index < m_count); return m_vertices[index]; } #endif
412
0.946263
1
0.946263
game-dev
MEDIA
0.930118
game-dev
0.934426
1
0.934426
Decane/SRP
5,858
gamedata/configs/scripts/agroprom/stalker_trader.ltx
;-----------------------------------------------------------------------------------------; ; ; ; Experimental invulnerability fix by Decane! Inluded since SRP 0.7.2. Changed in v1.0.2. ; ; ; ;-----------------------------------------------------------------------------------------; [logic] active = remark@wait trade = misc\trade\trade_trader_agr_stalker.ltx level_spot = trader [remark@enemy] path_walk = agr_stalker_trader_walk path_look = agr_stalker_trader_look out_restr = agr_in_restr_stalker_trader anim = hands_up target = actor meet = no_meet on_info = {!gulag_enemy_actor(agr_smart_terrain_4_4)} remark@wait combat_ignore_cond = true combat_ignore_keep_when_attacked = true [remark@invul_enemy] invulnerable = true path_walk = agr_stalker_trader_walk path_look = agr_stalker_trader_look out_restr = agr_in_restr_stalker_trader anim = hands_up target = actor meet = no_meet on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {!is_smart_in_combat(agr_smart_terrain_4_4)} remark@wait combat_ignore_cond = true combat_ignore_keep_when_attacked = true [remark@wait] invulnerable = true path_walk = agr_stalker_trader_walk path_look = agr_stalker_trader_look out_restr = agr_in_restr_stalker_trader anim = wait_trade meet = meet combat_ignore_cond = true combat_ignore_keep_when_attacked = true on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = smartcover@near_table [smartcover@near_table] invulnerable = true cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = idle_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 13330 | smartcover@near_table2 def_state_moving = walk on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@near_table2] invulnerable = true cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 15000 | smartcover@near_table3 def_state_moving = walk on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@near_table3] invulnerable = true cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = fire_no_lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 4500 | smartcover@near_table4 def_state_moving = walk on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@near_table4] invulnerable = true cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = fire_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 6500 | smartcover@near_table def_state_moving = walk on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@look_up] invulnerable = true cover_name = agr_smart_cover_stalker_trader_2 loophole_name = lead_stand_look_down_2 cover_state = lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 15000 | smartcover@look_up2 def_state_moving = walk on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@look_up2] invulnerable = true cover_name = agr_smart_cover_stalker_trader_2 loophole_name = lead_stand_look_down_2 cover_state = fire_no_lookout_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader on_timer = 15000 | smartcover@near_table def_state_moving = walk on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {=actor_in_zone(agr_stalker_trader_tradezone)} smartcover@trade meet = meet [smartcover@trade] invulnerable = true cover_name = agr_smart_cover_stalker_trader_1 loophole_name = lead_stand_look_at_table cover_state = idle_target combat_ignore_cond = true combat_ignore_keep_when_attacked = true out_restr = agr_in_restr_stalker_trader def_state_moving = walk meet = meet on_info = {=gulag_enemy_actor(agr_smart_terrain_4_4)} remark@enemy on_info2 = {=is_smart_in_combat(agr_smart_terrain_4_4)} remark@invul_enemy on_info3 = {!actor_in_zone(agr_stalker_trader_tradezone)} smartcover@near_table [meet] meet_state = 0 | nil@nil victim = 0 | nil use = true abuse = false
412
0.883395
1
0.883395
game-dev
MEDIA
0.902595
game-dev
0.808315
1
0.808315
OSSDC/OSSDC-SIM
6,184
Assets/Scripts/Components/SegmentationIdMapping.cs
/** * Copyright (c) 2021 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ namespace Simulator.Components { using System; using System.Collections.Generic; using UnityEngine; public class SegmentationIdMapping { public enum SegmentationEntityType { None, Agent, NPC, Pedestrian } private class EntityData { // public string guid; public uint gtid; public int segmentationId; public GameObject gameObject; public SegmentationEntityType type; } private Dictionary<uint, EntityData> gtidDict = new Dictionary<uint, EntityData>(); private Dictionary<int, EntityData> segIdDict = new Dictionary<int, EntityData>(); private Dictionary<int, Bounds> boundsDict = new Dictionary<int, Bounds>(); public int AddSegmentationId(GameObject obj, uint gtid) { if (gtidDict.ContainsKey(gtid)) { throw new Exception($"This GUID ({gtid}) has segmentation ID already assigned."); } var newIndex = 255; // 0 is reserved for clear color, 255 for non-agent segmentation for (var i = 1; i < 255; ++i) { if (segIdDict.ContainsKey(i)) continue; newIndex = i; break; } if (newIndex == 255) { Debug.LogError("NPC and pedestrians number exceeded maximum amount trackable by perception sensor (254)."); return -1; } var npcController = obj.GetComponent<NPCController>(); var agentController = obj.GetComponent<IAgentController>(); var pedController = obj.GetComponent<PedestrianController>(); var type = SegmentationEntityType.None; if (agentController != null) { type = SegmentationEntityType.Agent; } else if (npcController != null) { type = SegmentationEntityType.NPC; } else if (pedController != null) { type = SegmentationEntityType.Pedestrian; } var data = new EntityData() { gtid = gtid, segmentationId = newIndex, gameObject = obj, type = type }; segIdDict[newIndex] = data; gtidDict[gtid] = data; return newIndex; } public void RemoveSegmentationId(uint gtid) { if (!gtidDict.ContainsKey(gtid)) return; var index = gtidDict[gtid].segmentationId; gtidDict.Remove(gtid); segIdDict.Remove(index); boundsDict.Remove(index); } public bool TryGetEntityGameObject(int segmentationId, out GameObject go, out SegmentationEntityType type) { go = null; type = SegmentationEntityType.None; if (!segIdDict.TryGetValue(segmentationId, out var data)) return false; go = data.gameObject; type = data.type; return true; } public bool TryGetEntityLocalBoundingBox(int segmentationId, out Bounds bounds) { bounds = new Bounds(); if (!boundsDict.TryGetValue(segmentationId, out bounds)) { if (TryGetEntityGameObject(segmentationId, out var go, out var type)) { bounds = GetLocalBoundsTight(go); boundsDict[segmentationId] = bounds; return true; } return false; } return true; } private Bounds GetLocalBoundsTight(GameObject go) { var renderers = go.GetComponentsInChildren<Renderer>(); var skinnedMeshRenderer = go.GetComponentInChildren<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { return TransformBounds(skinnedMeshRenderer.localBounds, skinnedMeshRenderer.rootBone, skinnedMeshRenderer.transform); } if (renderers.Length > 0) { Bounds bounds = new Bounds(); foreach (var renderer in renderers) { var mf = renderer.GetComponent<MeshFilter>(); if (mf == null) continue; var meshBounds = TransformBounds(mf.sharedMesh.bounds, mf.transform, go.transform); bounds.Encapsulate(meshBounds); return bounds; } } return new Bounds(); } private Bounds TransformBounds(Bounds bounds, Transform from, Transform to) { var result = new Bounds(); var c = bounds.center; var e = bounds.extents; result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x + e.x, c.y + e.y, c.z + e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x + e.x, c.y + e.y, c.z - e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x + e.x, c.y - e.y, c.z + e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x + e.x, c.y - e.y, c.z - e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x - e.x, c.y + e.y, c.z + e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x - e.x, c.y + e.y, c.z - e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x - e.x, c.y - e.y, c.z + e.z)))); result.Encapsulate(to.InverseTransformPoint(from.TransformPoint(new Vector3(c.x - e.x, c.y - e.y, c.z - e.z)))); return result; } } }
412
0.86595
1
0.86595
game-dev
MEDIA
0.932337
game-dev
0.961432
1
0.961432
Doddler/RagnarokRebuildTcp
2,006
RebuildClient/Assets/Scripts/UI/Hud/ToastNotificationArea.cs
using System.Collections.Generic; using Assets.Scripts.Objects; using Assets.Scripts.Utility; using UnityEngine; namespace Assets.Scripts.UI.Hud { public class ToastNotificationArea : MonoBehaviour { public GameObject PartyInvitePrefab; public Transform ToastZone; private Dictionary<string, PartyInviteToast> partyInvites; public void AddPartyInvite(int partyId, string leaderName, string partyName) { partyInvites ??= new(); if (partyInvites.ContainsKey(leaderName)) return; CameraFollower.Instance.AppendChatText($"<color=#77FF77>{leaderName} has invited you to join their party '{partyName}'.</color>"); var toastObject = GameObject.Instantiate(PartyInvitePrefab, ToastZone); var toast = toastObject.GetComponent<PartyInviteToast>(); toast.PartyId = partyId; toast.LeaderName = leaderName; toast.PartyName = partyName; toast.Parent = this; toast.SecondaryCaption.text = $"<size=-2>From</size> <i>{leaderName}"; toast.ToastBox.RectTransform().anchoredPosition = new Vector3(400, 0); var lt = LeanTween.moveLocalX(toast.ToastBox, 150, 0.5f); lt.setEaseOutQuad(); partyInvites.Add(leaderName, toast); AudioManager.Instance.PlaySystemSound("버튼소리_.ogg"); gameObject.SetActive(true); } public void CloseAllPartyInvites() { foreach (var (_, p) in partyInvites) { Destroy(p.gameObject); } partyInvites.Clear(); gameObject.SetActive(false); } public void OnCloseNotification(string partyLeader) { partyInvites?.Remove(partyLeader); if(ToastZone.childCount == 0) gameObject.SetActive(false); } } }
412
0.605252
1
0.605252
game-dev
MEDIA
0.807676
game-dev
0.768895
1
0.768895
challacade/udemy-love2d
2,682
_lectures/game3/l9_flip-animation/main.lua
function love.load() anim8 = require 'libraries/anim8/anim8' sprites = {} sprites.playerSheet = love.graphics.newImage('sprites/playerSheet.png') local grid = anim8.newGrid(614, 564, sprites.playerSheet:getWidth(), sprites.playerSheet:getHeight()) animations = {} animations.idle = anim8.newAnimation(grid('1-15',1), 0.05) animations.jump = anim8.newAnimation(grid('1-7',2), 0.05) animations.run = anim8.newAnimation(grid('1-15',3), 0.05) wf = require 'libraries/windfield/windfield' world = wf.newWorld(0, 800, false) world:setQueryDebugDrawing(true) world:addCollisionClass('Platform') world:addCollisionClass('Player'--[[, {ignores = {'Platform'}}]]) world:addCollisionClass('Danger') player = world:newRectangleCollider(360, 100, 40, 100, {collision_class = "Player"}) player:setFixedRotation(true) player.speed = 240 player.animation = animations.idle player.isMoving = false player.direction = 1 platform = world:newRectangleCollider(250, 400, 300, 100, {collision_class = "Platform"}) platform:setType('static') dangerZone = world:newRectangleCollider(0, 550, 800, 50, {collision_class = "Danger"}) dangerZone:setType('static') end function love.update(dt) world:update(dt) if player.body then player.isMoving = false local px, py = player:getPosition() if love.keyboard.isDown('right') then player:setX(px + player.speed*dt) player.isMoving = true player.direction = 1 end if love.keyboard.isDown('left') then player:setX(px - player.speed*dt) player.isMoving = true player.direction = -1 end if player:enter('Danger') then player:destroy() end end if player.isMoving then player.animation = animations.run else player.animation = animations.idle end player.animation:update(dt) end function love.draw() world:draw() local px, py = player:getPosition() player.animation:draw(sprites.playerSheet, px, py, nil, 0.25 * player.direction, 0.25, 130, 300) end function love.keypressed(key) if key == 'up' then local colliders = world:queryRectangleArea(player:getX() - 20, player:getY() + 50, 40, 2, {'Platform'}) if #colliders > 0 then player:applyLinearImpulse(0, -4000) end end end function love.mousepressed(x, y, button) if button == 1 then local colliders = world:queryCircleArea(x, y, 200, {'Platform', 'Danger'}) for i,c in ipairs(colliders) do c:destroy() end end end
412
0.870399
1
0.870399
game-dev
MEDIA
0.754313
game-dev
0.820566
1
0.820566
spartanoah/acrimony-client
1,581
com/viaversion/viaversion/sponge/platform/SpongeViaLoader.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). * * Could not load the following classes: * org.spongepowered.api.Sponge * org.spongepowered.api.event.EventManager */ package com.viaversion.viaversion.sponge.platform; import com.viaversion.viaversion.SpongePlugin; import com.viaversion.viaversion.api.platform.PlatformTask; import com.viaversion.viaversion.api.platform.ViaPlatformLoader; import com.viaversion.viaversion.sponge.listeners.UpdateListener; import java.util.HashSet; import java.util.Set; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.EventManager; public class SpongeViaLoader implements ViaPlatformLoader { private final SpongePlugin plugin; private final Set<Object> listeners = new HashSet<Object>(); private final Set<PlatformTask> tasks = new HashSet<PlatformTask>(); public SpongeViaLoader(SpongePlugin plugin) { this.plugin = plugin; } private void registerListener(Object listener) { Sponge.eventManager().registerListeners(this.plugin.container(), this.storeListener(listener)); } private <T> T storeListener(T listener) { this.listeners.add(listener); return listener; } @Override public void load() { this.registerListener(new UpdateListener()); } @Override public void unload() { this.listeners.forEach(arg_0 -> ((EventManager)Sponge.eventManager()).unregisterListeners(arg_0)); this.listeners.clear(); this.tasks.forEach(PlatformTask::cancel); this.tasks.clear(); } }
412
0.603552
1
0.603552
game-dev
MEDIA
0.582482
game-dev
0.847212
1
0.847212
The-Cataclysm-Preservation-Project/TrinityCore
4,525
src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp
/* * This file is part of the TrinityCore 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 <http://www.gnu.org/licenses/>. */ /* Name: Boss_Zum_Rah Category: Tanaris, ZulFarrak */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "ScriptedCreature.h" #include "zulfarrak.h" namespace Zulfarrak::ZumRah { enum Says { SAY_SANCT_INVADE = 0, SAY_WARD = 1, SAY_KILL = 2 }; enum Spells { SPELL_SHADOW_BOLT = 12739, SPELL_SHADOWBOLT_VOLLEY = 15245, SPELL_WARD_OF_ZUM_RAH = 11086, SPELL_HEALING_WAVE = 12491 }; enum Events { EVENT_SHADOW_BOLT = 1, EVENT_SHADOWBOLT_VOLLEY = 2, EVENT_WARD_OF_ZUM_RAH = 3, EVENT_HEALING_WAVE = 4 }; class boss_zum_rah : public CreatureScript { public: boss_zum_rah() : CreatureScript("boss_zum_rah") { } struct boss_zum_rahAI : public BossAI { boss_zum_rahAI(Creature* creature) : BossAI(creature, DATA_ZUM_RAH) { Initialize(); } void Initialize() { _ward80 = false; _ward40 = false; _heal30 = false; } void Reset() override { me->SetFaction(FACTION_FRIENDLY); // areatrigger sets faction to enemy Initialize(); } void JustEngagedWith(Unit* /*who*/) override { Talk(SAY_SANCT_INVADE); events.ScheduleEvent(EVENT_SHADOW_BOLT, 1000); events.ScheduleEvent(EVENT_SHADOWBOLT_VOLLEY, 10000); } void JustDied(Unit* /*killer*/) override { instance->SetData(DATA_ZUM_RAH, DONE); } void KilledUnit(Unit* /*victim*/) override { Talk(SAY_KILL); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SHADOW_BOLT: DoCastVictim(SPELL_SHADOW_BOLT); events.ScheduleEvent(EVENT_SHADOW_BOLT, 4000); break; case EVENT_WARD_OF_ZUM_RAH: DoCast(me,SPELL_WARD_OF_ZUM_RAH); break; case EVENT_HEALING_WAVE: DoCast(me,SPELL_HEALING_WAVE); break; case EVENT_SHADOWBOLT_VOLLEY: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_SHADOWBOLT_VOLLEY); events.ScheduleEvent(EVENT_SHADOWBOLT_VOLLEY, 9000); break; default: break; } } if (!_ward80 && HealthBelowPct(80)) { _ward80 = true; Talk(SAY_WARD); events.ScheduleEvent(EVENT_WARD_OF_ZUM_RAH, 1000); } if (!_ward40 && HealthBelowPct(40)) { _ward40 = true; Talk(SAY_WARD); events.ScheduleEvent(EVENT_WARD_OF_ZUM_RAH, 1000); } if (!_heal30 && HealthBelowPct(30)) { _heal30 = true; events.ScheduleEvent(EVENT_HEALING_WAVE, 3000); } DoMeleeAttackIfReady(); } private: bool _ward80; bool _ward40; bool _heal30; }; CreatureAI* GetAI(Creature* creature) const override { return GetZulFarrakAI<boss_zum_rahAI>(creature); } }; } void AddSC_boss_zum_rah() { using namespace Zulfarrak::ZumRah; new boss_zum_rah(); }
412
0.957495
1
0.957495
game-dev
MEDIA
0.983804
game-dev
0.960479
1
0.960479
unikraft/kraftkit
2,354
unikraft/runtime/runtime.go
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2022, Unikraft GmbH and The KraftKit Authors. // Licensed under the BSD-3-Clause License (the "License"). // You may not use this file except in compliance with the License. package runtime import ( "strings" "kraftkit.sh/kconfig" "kraftkit.sh/pack" "kraftkit.sh/packmanager" "kraftkit.sh/unikraft" ) type Runtime struct { registry packmanager.PackageManager // Path to the kernel of the ELF loader. kernel string // The package representing the ELF Loader. pack pack.Package // Platform specifies the platform of the loader. platform string // Architecture specifies the architecture of the loader. architecture string // The name of the elfloader. name string // The version of the elfloader. version string // The source of the elfloader (can be either remote or local, this attribute // is ultimately handled by the packmanager). source string // List of kconfig key-values specific to this core. kconfig kconfig.KeyValueMap // The rootfs (initramfs) of the ELF loader. rootfs string } var _ unikraft.Nameable = (*Runtime)(nil) // Type implements kraftkit.sh/unikraft.Nameable func (elfloader *Runtime) Type() unikraft.ComponentType { return unikraft.ComponentTypeApp } // Name implements kraftkit.sh/unikraft.Nameable func (elfloader *Runtime) Name() string { return elfloader.name } // SetName overwrites the name of the runtime. func (elfloader *Runtime) SetName(name string) { if runtime := strings.Split(name, ":"); len(runtime) == 2 { elfloader.name = runtime[0] elfloader.version = runtime[1] return } elfloader.name = name } // String implements fmt.Stringer func (ocipack *Runtime) String() string { return ocipack.pack.Name() } // Version implements kraftkit.sh/unikraft.Nameable func (elfloader *Runtime) Version() string { return elfloader.version } // Source of the ELF Loader runtime. func (elfloader *Runtime) Source() string { return elfloader.source } func (elfloader *Runtime) MarshalYAML() (interface{}, error) { ret := map[string]interface{}{} if len(elfloader.name) > 0 { ret["name"] = elfloader.name } if len(elfloader.version) > 0 { ret["version"] = elfloader.version } if len(elfloader.source) > 0 { ret["source"] = elfloader.source } if len(ret) == 0 { return nil, nil } return ret, nil }
412
0.799254
1
0.799254
game-dev
MEDIA
0.765265
game-dev
0.866656
1
0.866656
dream-young-soul/h5_mir
10,581
src/GameMap/CustomGameMap.ts
/** * 游戏地图操作类,游戏中实际可用的地图类 * @author 后天 2017.9.29 * */ module GameMap { export class CustomGameMap extends CustomRenderMap { private static _Instance:CustomGameMap = null; private m_MoveTargetPos: Laya.Point = null;//移动的目的地坐标,为null表示当前不在移动中 private m_nMoveDir: number = 0;//移动的方向 private m_nMoveStartTick: number = 0;//开始移动的时间 private m_nMoveEndTick: number = 0;//移动完成的时间 private m_dMoveSpeedH: number = 0;//水平方向的移动速度(每毫秒移动多少像素) private m_dMoveSpeedV: number = 0;//竖直方向的移动速度(每毫秒移动多少像素) private m_sMapName:string = ""; //地图名称 private m_nMapID:number = 0; //地图id private m_szMapFile:string = ""; //地图路径 private m_ArrEffect:Array<Common.Animation>; //场景特效 private m_EffectLayer:Laya.Sprite ; constructor() { super(); //场景层特效 this.m_EffectLayer = new Laya.Sprite(); this.m_MapLayerRoot.addChild(this.m_EffectLayer); this.m_ArrEffect =new Array<Common.Animation>(); } public static Init():void { CustomGameMap._Instance = new CustomGameMap(); } public static GetInstance():CustomGameMap{ return CustomGameMap._Instance; } public LoadMap(szMapFile:string,szMapName:string,nMapId:number) { this.m_sMapName = szMapName; this.m_nMapID = nMapId; this.m_szMapFile = szMapFile; let assat=[]; assat.push( { url:Config.GlobalConfig._Instance._szUrl+ szMapFile, type:Laya.Loader.BUFFER, } ) Laya.loader.load(assat,Laya.Handler.create(this,this.OnLoadMap)); } public GetMapId():number { return this.m_nMapID; } public GetmapFile():string { return this.m_szMapFile; } private OnLoadMap():void { let data = Laya.loader.getRes(Config.GlobalConfig._Instance._szUrl+this.m_szMapFile); let bytes:Laya.Byte = new Laya.Byte(data); this.Load(bytes); let pPlayer:Entity.Player = Entity.Player.GetInstance(); this.SetCurrentPosition(pPlayer.GetCurentX(),pPlayer.GetCurrentY()); } /** * 地图移动等操作的更新函数 * 周期性的处理或移动等操作必须由使用者调用update函数当做事件驱动来执行更新 * @param CurrentTick 当前系统运行时间 */ public Update(CurrentTick: number): void { //如果移动的目的坐标存在,则处理移动或完成移动 if ( this.m_MoveTargetPos != null) { //仍在移动 if ( CurrentTick < this.m_nMoveEndTick ) { this.ProcessMove(CurrentTick); } else { //完成移动 this.EndMove(); } } //更新特效 for(let i:number = this.m_ArrEffect.length - 1;i > 0 ;i--) { let pAni:Common.Animation = this.m_ArrEffect[i]; pAni.Update(CurrentTick); if(pAni.parent == null) { this.m_ArrEffect.splice(i,1); } } } /** * 覆盖函数——设置当前中心位置的X和Y坐标 * @param x * @param y * */ public SetCurrentPosition(x: number, y: number): void { //如果正在移动则首先停止移动 if ( this.m_MoveTargetPos != null ) { this.EndMove(); } super.SetCurrentPosition(x, y); } /** *使地图向x,y坐标以speed速度移动 * @param x, y 移动的目的坐标 * @param speed 移动的速度,指在多少毫秒内完成移动 * */ public MoveTo(x: number, y: number, speed: number): void { if ( this.m_MoveTargetPos != null ) { return; } //计算移动后的目标位置 if ( x < 0 || y < 0 || x >= this.m_nWidth || y >= this.m_nHeight ) { throw new Error("无法将地图向(" + x + "," + y + ")位置移动"); } this.m_MoveTargetPos = new Laya.Point(x, y); this.m_nMoveDir = CustomMap.CalcForwardDirection( this.m_nCurrentX, this.m_nCurrentY, x, y ); this.m_nMoveStartTick = Config.GlobalConfig.s_dwUpdateTick; this.m_nMoveEndTick = this.m_nMoveStartTick + speed; //计算水平和竖直方向移动的速度 this.m_dMoveSpeedH = (this.m_nCurrentX - x) * CustomMap.MAPCELLUNITWIDTH / speed; this.m_dMoveSpeedV = (this.m_nCurrentY - y) * CustomMap.MAPCELLUNITHEIGHT / speed; } /** *使地图向direction方向移动step坐标 * @param direction 移动的方向,游戏具有8个方向,0点钟方向为0方向,6点钟方向为4方向,以此类推 * @param step 移动的距离,单位是坐标,移动的距离必须小于4坐标 * @param speed 移动的速度,指在多少毫秒内完成移动 * */ public MoveBy(direction: number, step: number, speed: number): void { if ( step <= 0 || step > 3 ) { throw new Error("移动的距离超出最大设计范围:" + step); } if ( this.m_MoveTargetPos != null ) { return; } //计算移动后的目标位置 this.m_MoveTargetPos = CustomMap.CalcForwardPosition( this.m_nCurrentX, this.m_nCurrentY, direction, step ); //console.log("mapx:"+this.m_MoveTargetPos.x+"mapy:"+this.m_MoveTargetPos.y); if ( this.m_MoveTargetPos.x < 0 || this.m_MoveTargetPos.y < 0 || this.m_MoveTargetPos.x >= this.m_nWidth || this.m_MoveTargetPos.y >= this.m_nHeight ) { throw new Error("无法将地图向" + direction + "方向移动" + step); } this.m_nMoveDir = direction; this.m_nMoveStartTick =Config.GlobalConfig.s_dwUpdateTick; this.m_nMoveEndTick = this.m_nMoveStartTick + speed; //计算水平和竖直方向移动的速度 this.m_dMoveSpeedH = (this.m_nCurrentX - this.m_MoveTargetPos.x) * CustomMap.MAPCELLUNITWIDTH / speed; this.m_dMoveSpeedV = (this.m_nCurrentY - this.m_MoveTargetPos.y) * CustomMap.MAPCELLUNITHEIGHT / speed; } /** * 停止场景移动 * */ public StopMove(): void { this.EndMove(); } /** *完成移动,将当前坐标设置为m_MoveTargetPos并将m_MoveTargetPos设为null; * */ private EndMove(): void { if ( this.m_MoveTargetPos != null) { //要使用一个中间变量保存m_MoveTargetPos并将m_MoveTargetPos置空 //放置在调用setCurrentPosition后再次调用endMove造成死递归 let targetPos: Laya.Point = this.m_MoveTargetPos; this.m_MoveTargetPos = null; this.SetCurrentPosition(targetPos.x, targetPos.y); } } /****************************************************************** * * 以下函数均为似有和保护函数 * * ***************************************************************/ /** * 处理移动过程 * @param CurrentTick 当前时间 */ private ProcessMove(CurrentTick: number): void { let nMovedTick: number = CurrentTick - this.m_nMoveStartTick;//计算得已移动的时间 let nXMoved: number = this.m_dMoveSpeedH * nMovedTick; let nYMoved: number = this.m_dMoveSpeedV * nMovedTick; let offx:number = -this.m_nCurrentX * CustomMap.MAPCELLUNITWIDTH + nXMoved; let offy = -this.m_nCurrentY * CustomMap.MAPCELLUNITHEIGHT + nYMoved; offx = Math.ceil(offx) offy = Math.ceil(offy) this.SetLayersPosition(offx,offy); } public GetGlobalPoint(x:number,y:number):Laya.Point { let point:Laya.Point = new Laya.Point(x,y); this.m_MapLayerRoot.localToGlobal(point); return point; } public AddEffect(nEffId:number,type:Config.EffectType,nX:number,nY:number,nDuration:number):void { let pEffect:Common.Animation =null; let pack = Resources.ResourcesManager._Instance.GetSkillEffectPackage(nEffId); //特效并没有加载完成 if(pack.GetFrameCount() <= 0) { return; } switch(type) { case Config.EffectType.meKeepOnBody: case Config.EffectType.meKeepOnFeet: case Config.EffectType.meExplode: { let nStartFrame:number = 0; let nEndFrame:number = pack.GetFrameCount(); pEffect = new Common.Animation(pack,nStartFrame,nEndFrame,0,1) break; } } if(pEffect != null) { this.m_EffectLayer.addChild(pEffect); pEffect.x = (nX + 0.5) * CustomMap.MAPCELLUNITWIDTH; pEffect.y = (nY + 0.5) * CustomMap.MAPCELLUNITHEIGHT; this.m_ArrEffect.push(pEffect); //播放音效 let pStdEffect:Config.StdEffect = Config.ConfigManager.GetInstance().GetEffectConfig().GetEffectByID(nEffId); if(pStdEffect != null && pStdEffect._nSoundId > 0) { SoundManager.GetInstance().PlayEffectSound(pStdEffect._nSoundId); } } } } }
412
0.840461
1
0.840461
game-dev
MEDIA
0.845026
game-dev
0.928122
1
0.928122
jinhosung96/Unity-VContainer-UniRx-MVP-Example
6,492
Assets/Other/Plugins/UniTask/Runtime/Linq/TakeUntil.cs
using Cysharp.Threading.Tasks.Internal; using System; using System.Threading; namespace Cysharp.Threading.Tasks.Linq { public static partial class UniTaskAsyncEnumerable { public static IUniTaskAsyncEnumerable<TSource> TakeUntil<TSource>(this IUniTaskAsyncEnumerable<TSource> source, UniTask other) { Error.ThrowArgumentNullException(source, nameof(source)); return new TakeUntil<TSource>(source, other, null); } public static IUniTaskAsyncEnumerable<TSource> TakeUntil<TSource>(this IUniTaskAsyncEnumerable<TSource> source, Func<CancellationToken, UniTask> other) { Error.ThrowArgumentNullException(source, nameof(source)); Error.ThrowArgumentNullException(source, nameof(other)); return new TakeUntil<TSource>(source, default, other); } } internal sealed class TakeUntil<TSource> : IUniTaskAsyncEnumerable<TSource> { readonly IUniTaskAsyncEnumerable<TSource> source; readonly UniTask other; readonly Func<CancellationToken, UniTask> other2; public TakeUntil(IUniTaskAsyncEnumerable<TSource> source, UniTask other, Func<CancellationToken, UniTask> other2) { this.source = source; this.other = other; this.other2 = other2; } public IUniTaskAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken = default) { if (other2 != null) { return new _TakeUntil(source, this.other2(cancellationToken), cancellationToken); } else { return new _TakeUntil(source, this.other, cancellationToken); } } sealed class _TakeUntil : MoveNextSource, IUniTaskAsyncEnumerator<TSource> { static readonly Action<object> CancelDelegate1 = OnCanceled1; static readonly Action<object> MoveNextCoreDelegate = MoveNextCore; readonly IUniTaskAsyncEnumerable<TSource> source; CancellationToken cancellationToken1; CancellationTokenRegistration cancellationTokenRegistration1; bool completed; Exception exception; IUniTaskAsyncEnumerator<TSource> enumerator; UniTask<bool>.Awaiter awaiter; public _TakeUntil(IUniTaskAsyncEnumerable<TSource> source, UniTask other, CancellationToken cancellationToken1) { this.source = source; this.cancellationToken1 = cancellationToken1; if (cancellationToken1.CanBeCanceled) { this.cancellationTokenRegistration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(CancelDelegate1, this); } TaskTracker.TrackActiveTask(this, 3); RunOther(other).Forget(); } public TSource Current { get; private set; } public UniTask<bool> MoveNextAsync() { if (completed) { return CompletedTasks.False; } if (exception != null) { return UniTask.FromException<bool>(exception); } if (cancellationToken1.IsCancellationRequested) { return UniTask.FromCanceled<bool>(cancellationToken1); } if (enumerator == null) { enumerator = source.GetAsyncEnumerator(cancellationToken1); } completionSource.Reset(); SourceMoveNext(); return new UniTask<bool>(this, completionSource.Version); } void SourceMoveNext() { try { awaiter = enumerator.MoveNextAsync().GetAwaiter(); if (awaiter.IsCompleted) { MoveNextCore(this); } else { awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); } } catch (Exception ex) { completionSource.TrySetException(ex); } } static void MoveNextCore(object state) { var self = (_TakeUntil)state; if (self.TryGetResult(self.awaiter, out var result)) { if (result) { if (self.exception != null) { self.completionSource.TrySetException(self.exception); } else if (self.cancellationToken1.IsCancellationRequested) { self.completionSource.TrySetCanceled(self.cancellationToken1); } else { self.Current = self.enumerator.Current; self.completionSource.TrySetResult(true); } } else { self.completionSource.TrySetResult(false); } } } async UniTaskVoid RunOther(UniTask other) { try { await other; completed = true; completionSource.TrySetResult(false); } catch (Exception ex) { exception = ex; completionSource.TrySetException(ex); } } static void OnCanceled1(object state) { var self = (_TakeUntil)state; self.completionSource.TrySetCanceled(self.cancellationToken1); } public UniTask DisposeAsync() { TaskTracker.RemoveTracking(this); cancellationTokenRegistration1.Dispose(); if (enumerator != null) { return enumerator.DisposeAsync(); } return default; } } } }
412
0.9321
1
0.9321
game-dev
MEDIA
0.682637
game-dev
0.939498
1
0.939498
BetonQuest/BetonQuest
11,094
src/main/java/org/betonquest/betonquest/compatibility/holograms/HologramLoop.java
package org.betonquest.betonquest.compatibility.holograms; import org.betonquest.betonquest.BetonQuest; import org.betonquest.betonquest.api.config.quest.QuestPackage; import org.betonquest.betonquest.api.config.quest.QuestPackageManager; import org.betonquest.betonquest.api.identifier.Identifier; import org.betonquest.betonquest.api.instruction.argument.Argument; import org.betonquest.betonquest.api.instruction.argument.PackageArgument; import org.betonquest.betonquest.api.instruction.argument.types.NumberParser; import org.betonquest.betonquest.api.instruction.variable.Variable; import org.betonquest.betonquest.api.instruction.variable.VariableList; import org.betonquest.betonquest.api.logger.BetonQuestLogger; import org.betonquest.betonquest.api.logger.BetonQuestLoggerFactory; import org.betonquest.betonquest.api.quest.QuestException; import org.betonquest.betonquest.api.quest.condition.ConditionID; import org.betonquest.betonquest.compatibility.holograms.lines.AbstractLine; import org.betonquest.betonquest.compatibility.holograms.lines.ItemLine; import org.betonquest.betonquest.compatibility.holograms.lines.TextLine; import org.betonquest.betonquest.compatibility.holograms.lines.TopLine; import org.betonquest.betonquest.compatibility.holograms.lines.TopXObject; import org.betonquest.betonquest.id.ItemID; import org.betonquest.betonquest.kernel.processor.SectionProcessor; import org.betonquest.betonquest.kernel.processor.quest.VariableProcessor; import org.bukkit.ChatColor; import org.bukkit.configuration.ConfigurationSection; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Hides and shows holograms to players, based on conditions. */ @SuppressWarnings("PMD.CouplingBetweenObjects") public abstract class HologramLoop extends SectionProcessor<HologramLoop.HologramID, HologramWrapper> { /** * The regex for one color. */ private static final String COLOR_REGEX = ";?([&§]?[0-9a-f])?"; /** * Pattern to match the correct syntax for the top line content. */ private static final Pattern TOP_LINE_VALIDATOR = Pattern.compile("^top:([\\w.]+);(\\w+);(\\d+)" + COLOR_REGEX + COLOR_REGEX + COLOR_REGEX + COLOR_REGEX + "$", Pattern.CASE_INSENSITIVE); /** * The string to match the descending order. */ private static final String ORDER_DESC = "desc"; /** * The string to match the ascending order. */ private static final String ORDER_ASC = "asc"; /** * The {@link VariableProcessor} to use. */ protected final VariableProcessor variableProcessor; /** * Hologram provider to create new Holograms. */ protected final HologramProvider hologramProvider; /** * The {@link BetonQuestLoggerFactory} to use for creating {@link BetonQuestLogger} instances. */ private final BetonQuestLoggerFactory loggerFactory; /** * Default refresh Interval for Holograms. */ private int defaultInterval = 10 * 20; /** * Creates a new instance of the loop. * * @param loggerFactory logger factory to use * @param log the logger that will be used for logging * @param packManager the quest package manager to get quest packages from * @param variableProcessor the {@link VariableProcessor} to use * @param hologramProvider the hologram provider to create new holograms * @param readable the type name used for logging, with the first letter in upper case * @param internal the section name and/or bstats topic identifier */ public HologramLoop(final BetonQuestLoggerFactory loggerFactory, final BetonQuestLogger log, final QuestPackageManager packManager, final VariableProcessor variableProcessor, final HologramProvider hologramProvider, final String readable, final String internal) { super(log, packManager, readable, internal); this.loggerFactory = loggerFactory; this.variableProcessor = variableProcessor; this.hologramProvider = hologramProvider; } @Override public void clear() { super.clear(); defaultInterval = BetonQuest.getInstance().getPluginConfig().getInt("hologram.update_interval", 10 * 20); } @Override protected HologramWrapper loadSection(final QuestPackage pack, final ConfigurationSection section) throws QuestException { final String checkIntervalString = section.getString("check_interval", String.valueOf(defaultInterval)); final Variable<Number> checkInterval = new Variable<>(variableProcessor, pack, checkIntervalString, Argument.NUMBER); final Variable<Number> maxRange = new Variable<>(variableProcessor, pack, section.getString("max_range", "0"), NumberParser.NUMBER); final List<String> lines = section.getStringList("lines"); final List<ConditionID> conditions = new VariableList<>(variableProcessor, pack, section.getString("conditions", ""), value -> new ConditionID(packManager, pack, value)).getValue(null); final List<AbstractLine> cleanedLines = new ArrayList<>(); for (final String line : lines) { if (line.startsWith("item:")) { cleanedLines.add(parseItemLine(pack, line)); } else if (line.startsWith("top:")) { cleanedLines.add(parseTopLine(pack, line)); } else { cleanedLines.add(parseTextLine(pack, line.replace('&', '§'))); } } final List<BetonHologram> holograms = getHologramsFor(pack, section); for (final BetonHologram hologram : holograms) { hologram.hideAll(); } final HologramWrapper hologramWrapper = new HologramWrapper( loggerFactory.create(HologramWrapper.class), BetonQuest.getInstance().getQuestTypeApi(), BetonQuest.getInstance().getProfileProvider(), checkInterval.getValue(null).intValue(), holograms, isStaticHologram(cleanedLines), conditions, cleanedLines, pack, maxRange); HologramRunner.addHologram(BetonQuest.getInstance(), hologramWrapper); return hologramWrapper; } /** * Creates and returns a list of holograms for the given section. * * @param pack the package of the holograms * @param section the section of the holograms * @return a list of holograms * @throws QuestException if there is an error while parsing the holograms */ protected abstract List<BetonHologram> getHologramsFor(QuestPackage pack, ConfigurationSection section) throws QuestException; private boolean isStaticHologram(final List<AbstractLine> lines) { return lines.stream().noneMatch(AbstractLine::isNotStaticText); } private ItemLine parseItemLine(final QuestPackage pack, final String line) throws QuestException { try { final String[] args = line.substring(5).split(":"); final ItemID itemID = new ItemID(packManager, pack, args[0]); int stackSize; try { stackSize = Integer.parseInt(args[1]); } catch (final NumberFormatException | ArrayIndexOutOfBoundsException e) { stackSize = 1; } return new ItemLine(BetonQuest.getInstance().getFeatureApi().getItem(itemID, null).generate(stackSize)); } catch (final QuestException e) { throw new QuestException("Error while loading item: " + e.getMessage(), e); } } private TopLine parseTopLine(final QuestPackage pack, final String line) throws QuestException { final Matcher validator = TOP_LINE_VALIDATOR.matcher(line); if (!validator.matches()) { throw new QuestException("Malformed top line in hologram! Expected format: 'top:<point>;<order>;<limit>[;<color>][;<color>][;<color>][;<color>]'."); } final String pointName = PackageArgument.IDENTIFIER.apply(pack, validator.group(1)); final TopXObject.OrderType orderType; if (ORDER_DESC.equalsIgnoreCase(validator.group(2))) { orderType = TopXObject.OrderType.DESCENDING; } else if (ORDER_ASC.equalsIgnoreCase(validator.group(2))) { orderType = TopXObject.OrderType.ASCENDING; } else { throw new QuestException("Top list order type '" + validator.group(2) + "' unknown! Expected 'asc' or 'desc'."); } final int limit; try { limit = Integer.parseInt(validator.group(3)); } catch (final NumberFormatException e) { throw new QuestException("Top list limit must be numeric! Expected format: 'top:<point>;<order>;<limit>[;<color>][;<color>][;<color>][;<color>]'.", e); } final ChatColor colorPlace = getColorCodes(validator.group(4)); final ChatColor colorName = getColorCodes(validator.group(5)); final ChatColor colorDash = getColorCodes(validator.group(6)); final ChatColor colorScore = getColorCodes(validator.group(7)); return new TopLine(loggerFactory, pointName, orderType, limit, new TopLine.FormatColors(colorPlace, colorName, colorDash, colorScore)); } private ChatColor getColorCodes(@Nullable final String color) { if (color != null) { final int length = color.length(); if (length == 1 || length == 2) { final char colorChar = color.charAt(length - 1); final ChatColor byChar = ChatColor.getByChar(colorChar); if (byChar != null) { return byChar; } } } return ChatColor.WHITE; } private TextLine parseTextLine(final QuestPackage pack, final String line) { final Matcher matcher = HologramProvider.VARIABLE_VALIDATOR.matcher(line); return new TextLine(matcher.find() ? hologramProvider.parseVariable(pack, line) : line); } @Override protected HologramID getIdentifier(final QuestPackage pack, final String identifier) throws QuestException { return new HologramID(packManager, pack, identifier); } /** * Internal identifier/key for a Hologram. */ protected static class HologramID extends Identifier { /** * Creates a new ID. * * @param packManager the quest package manager to get quest packages from * @param pack the package the ID is in * @param identifier the id instruction string * @throws QuestException if the ID could not be parsed */ protected HologramID(final QuestPackageManager packManager, @Nullable final QuestPackage pack, final String identifier) throws QuestException { super(packManager, pack, identifier); } } }
412
0.803509
1
0.803509
game-dev
MEDIA
0.796812
game-dev
0.871356
1
0.871356
CharonChui/CyberLink4Android
1,111
library/src/main/java/org/cybergarage/upnp/std/av/server/object/sort/DCDateSortCap.java
/****************************************************************** * * MediaServer for CyberLink * * Copyright (C) Satoshi Konno 2003-2004 * * File: DCDateSortCap.java * * Revision; * * 02/03/04 * - first revision. * ******************************************************************/ package org.cybergarage.upnp.std.av.server.object.sort; import org.cybergarage.upnp.std.av.server.DC; import org.cybergarage.upnp.std.av.server.object.*; import org.cybergarage.upnp.std.av.server.object.item.*; public class DCDateSortCap implements SortCap { public DCDateSortCap() { } public String getType() { return DC.DATE; } public int compare(ContentNode conNode1, ContentNode conNode2) { if (conNode1 == null || conNode2 == null) return 0; if (!(conNode1 instanceof ItemNode) || !(conNode2 instanceof ItemNode)) return 0; ItemNode itemNode1 = (ItemNode)conNode1; ItemNode itemNode2 = (ItemNode)conNode2; long itemTime1 = itemNode1.getDateTime(); long itemTime2 = itemNode2.getDateTime(); if (itemTime1 == itemTime2) return 0; return (itemTime1 < itemTime2) ? -1 : 1; } }
412
0.607652
1
0.607652
game-dev
MEDIA
0.242089
game-dev
0.715089
1
0.715089
openclonk/openclonk
6,861
planet/Arena.ocf/HotIce.ocs/Script.c
/* Hot ice */ func InitializeRound() // called by Goal_MultiRoundMelee { g_player_spawn_index = 0; if (GetType(g_player_spawn_positions) == C4V_Array) ShuffleArray(g_player_spawn_positions); // Materials: Chests var i, pos; var ls_wdt = LandscapeWidth(), ls_hgt = LandscapeHeight(); var chest_area_y = ls_hgt*[0, 30][SCENPAR_MapType]/100; var chest_area_hgt = ls_hgt/2; // Chests in regular mode. Boom packs in grenade launcher mode. var num_extras = [6, 12][SCENPAR_Weapons]; for (i = 0; i<num_extras; ++i) { var pos = FindLocation(Loc_InRect(0, chest_area_y, ls_wdt, chest_area_hgt-100), Loc_Wall(CNAT_Bottom)); // Loc_Wall adds us 100 pixels... if (pos) { if (SCENPAR_Weapons == 0) { var chest = CreateObjectAbove(Chest, pos.x, pos.y); if (chest) { chest->CreateContents(Firestone, 5); chest->CreateContents(Bread, 1); chest->CreateContents(Bow, 1); chest->CreateContents(FireArrow, 1)->SetStackCount(5); chest->CreateContents(BombArrow, 1)->SetStackCount(5); chest->CreateContents(Shield, 1); chest->CreateContents(IronBomb, 3); } } else { var boompack = CreateObjectAbove(Boompack, pos.x, pos.y); } } } // Materials: Firestones for (i = 0; i<30; ++i) { var pos = FindLocation(Loc_InRect(0, chest_area_y, ls_wdt, chest_area_hgt), Loc_Solid()); if (pos) if (IsFirestoneSpot(pos.x, pos.y)) CreateObjectAbove(Firestone, pos.x, pos.y-1); } // Some firestones and bombs in lower half. For ap type 1, more firestones in lower than upper half. for (i = 0; i<30; ++i) { var pos = FindLocation(Loc_InRect(0, ls_hgt/2, ls_wdt, ls_hgt/3), Loc_Solid()); if (pos) if (IsFirestoneSpot(pos.x, pos.y)) CreateObjectAbove([Firestone, IronBomb][Random(Random(3))],pos.x, pos.y-1); } SetSky(g_theme.Sky); g_theme->InitializeRound(); g_theme->InitializeMusic(); } static g_player_spawn_positions, g_map_width, g_player_spawn_index; func InitPlayerRound(int plr, object crew) // called by Goal_MultiRoundMelee { // everything visible SetFoW(false, plr); // Player positioning. var ls_wdt = LandscapeWidth(), ls_hgt = LandscapeHeight(); var start_pos; // Position by map type? if (SCENPAR_SpawnType == 0) { if (g_player_spawn_positions && g_player_spawn_index < GetLength(g_player_spawn_positions)) { start_pos = g_player_spawn_positions[g_player_spawn_index++]; var map_zoom = ls_wdt / g_map_width; start_pos = {x = start_pos[0]*map_zoom + map_zoom/2, y = start_pos[1]*map_zoom}; } else { // Start positions not defined or exhausted: Spawn in lower area for both maps becuase starting high is an an advantage. start_pos = FindLocation(Loc_InRect(ls_wdt/5, ls_hgt/2, ls_wdt*3/5, ls_hgt/3), Loc_Wall(CNAT_Bottom), Loc_Func(Scenario.IsStartSpot)); if (!start_pos) start_pos = FindLocation(Loc_InRect(ls_wdt/10, 0, ls_wdt*8/10, ls_hgt*4/5), Loc_Wall(CNAT_Bottom), Loc_Func(Scenario.IsStartSpot)); if (!start_pos) start_pos = {x = Random(ls_wdt*6/10)+ls_wdt*2/10, y = ls_hgt*58/100}; } crew->SetPosition(start_pos.x, start_pos.y-10); } else // Balloon spawn { var spawn_x = ls_wdt/3, spawn_y = 10; spawn_x += Random(spawn_x); var balloon = CreateObject(BalloonDeployed, spawn_x, spawn_y - 16, plr); crew->SetPosition(spawn_x, spawn_y); balloon->SetRider(crew); crew->SetAction("Ride", balloon); balloon->SetSpeed(0, 0); crew->SetSpeed(0, 0); balloon->CreateEffect(IntNoGravity, 1, 1); } // initial material if (SCENPAR_Weapons == 0) { crew->CreateContents(Shovel); crew->CreateContents(Club); crew->CreateContents(WindBag); crew->CreateContents(Firestone, 2); } else { // Grenade launcher mode crew.MaxContentsCount = 2; crew->CreateContents(WindBag); var launcher = crew->CreateContents(GrenadeLauncher); if (launcher) { var ammo = launcher->CreateContents(IronBomb); launcher->AddTimer(Scenario.ReplenishLauncherAmmo, 10); // Start reloading the launcher during the countdown. if (!Goal_MultiRoundMelee->IsHandicapped(plr)) { crew->SetHandItemPos(0, crew->GetItemPos(launcher)); // This doesn't play the animation properly - simulate a click instead. /* crew->StartLoad(launcher); */ crew->StartUseControl(CON_Use, 0, 0, launcher); crew->StopUseControl(0, 0, launcher); } } } crew.MaxEnergy = 100000; crew->DoEnergy(1000); } func StartRound() // called by Goal_MultiRoundMelee { for (var clonk in FindObjects(Find_OCF(OCF_CrewMember))) if (SCENPAR_SpawnType == 1 && clonk->GetActionTarget()) RemoveEffect("IntNoGravity", clonk->GetActionTarget()); } local IntNoGravity = new Effect { Timer = func() { Target->SetSpeed(0, 0); } }; /* Called periodically in grenade launcher */ func ReplenishLauncherAmmo() { if (!ContentsCount()) CreateContents(IronBomb); return true; } // Horizontal Loc_Space doesn't work with Loc_Wall because it checks inside the ground. func IsStartSpot(int x, int y) { // Don't spawn just at the border of an island. if (!GBackSolid(x-3, y + 2)) return false; if (!GBackSolid(x + 3, y + 2)) return false; // Spawn with some space. return PathFree(x-5, y, x + 5, y) && PathFree(x, y-21, x, y-1); } func IsFirestoneSpot(int x, int y) { // Very thorough ice surrounding check so they don't explode right away or when the first layer of ice melts return GBackSolid(x, y-1) && GBackSolid(x, y + 4) && GBackSolid(x-2, y) && GBackSolid(x + 2, y); } // ============= Themes ============= static const DefaultTheme = new Global { InitializeRound = func() { }, LavaMat = "^DuroLava", IceMats = ["^Ice-ice", "^Ice-ice2"], AltMatRatio = 50, BackgroundMat = nil, Sky = "Default", PlayList = nil, InitializeMusic = func() { // No special play list => music by Ambience if (this.PlayList == nil) InitializeAmbience(); else { // Remove Ambience to avoid interference. RemoveAll(Find_ID(Ambience)); SetPlayList(this.PlayList, NO_OWNER, true); SetGlobalSoundModifier(nil); } } }; static const HotIce = new DefaultTheme { InitializeRound = func() { Stalactite->Place(10 + Random(3)); } }; static const EciToh = new DefaultTheme { LavaMat = "DuroLava", IceMats = ["Coal", "Rock-rock"], AltMatRatio = 8, BackgroundMat = "Tunnel", InitializeRound = func() { Stalactite->Place(10 + Random(3)); } }; static const MiamiIce = new DefaultTheme { IceMats = ["^BlackIce-black", "^BlackIce-black"], Sky = "SkyMiami", PlayList = { PlayList = "beach", MusicBreakChance = 0, }, InitializeRound = func() { // Colors Scenario->CreateEffect(MiamiObjects, 1, 1); Tree_Coconut->Place(RandomX(7, 13)); }, MiamiObjects = new Effect { Timer = func(int time) { for (var o in FindObjects(Find_NoContainer())) { if (o->GetID() == Tree_Coconut) continue; o->SetClrModulation(HSL(time, 255, 100)); } }, } };
412
0.80691
1
0.80691
game-dev
MEDIA
0.924368
game-dev
0.767993
1
0.767993
ME3Tweaks/LegendaryExplorer
1,855
LegendaryExplorer/LegendaryExplorer/Tools/AssetDatabase/Scanners/MeshScanner.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LegendaryExplorerCore.Packages; using LegendaryExplorerCore.Unreal.BinaryConverters; namespace LegendaryExplorer.Tools.AssetDatabase.Scanners { class MeshScanner : AssetScanner { public MeshScanner() : base() { } public override void ScanExport(ExportScanInfo e, ConcurrentAssetDB db, AssetDBScanOptions options) { if (e.IsDefault) return; if (e.ClassName is "SkeletalMesh" or "StaticMesh") { var meshUsage = new MeshUsage(e.FileKey, e.Export.UIndex, e.IsMod); if (db.GeneratedMeshes.ContainsKey(e.AssetKey)) { var mr = db.GeneratedMeshes[e.AssetKey]; lock (mr) { mr.Usages.Add(meshUsage); } } else { bool IsSkel = e.ClassName == "SkeletalMesh"; int bones = 0; if (IsSkel) { var bin = ObjectBinary.From<SkeletalMesh>(e.Export); bones = bin?.RefSkeleton.Length ?? 0; } var NewMeshRec = new MeshRecord(e.ObjectNameInstanced, IsSkel, e.IsMod, bones); NewMeshRec.Usages.Add(meshUsage); if (!db.GeneratedMeshes.TryAdd(e.AssetKey, NewMeshRec)) { var mr = db.GeneratedMeshes[e.AssetKey]; lock (mr) { mr.Usages.Add(meshUsage); } } } } } } }
412
0.505838
1
0.505838
game-dev
MEDIA
0.953305
game-dev
0.730296
1
0.730296
DanceManiac/Advanced-X-Ray-Public
9,027
SourcesAXR/xrGame/UITeamState.cpp
#include "StdAfx.h" #include "UITeamState.h" #include "UITeamPanels.h" #include "UIPlayerItem.h" #include "UITeamHeader.h" #include "ui/UIFrameWindow.h" #include "ui/UIScrollView.h" #include "ui/UIStatic.h" #include "game_cl_mp.h" UITeamState::UITeamState() { m_artefact_count = 0; } UITeamState::UITeamState(ETeam teamId, UITeamPanels *teamPanels) { myTeam = teamId; /*myScrollList = xr_new<CUIScrollView>(); myScrollList->SetAutoDelete(true); myScrollList->m_sort_function = fastdelegate::MakeDelegate (this, &UITeamState::SortingLessFunction); myTeamHeader = xr_new<UITeamHeader>(this); myTeamHeader->SetAutoDelete(true); AttachChild(myTeamHeader); AttachChild(myScrollList);*/ mainUiXml = NULL; m_teamPanels = teamPanels; } UITeamState::~UITeamState() { CleanupInternal(); } void UITeamState::CleanupInternal() { MapClientIdToUIPlayer::iterator it = myPlayers.begin(); MapClientIdToUIPlayer::iterator it_e = myPlayers.end(); for(;it!=it_e;++it) { xr_delete(it->second.m_player_wnd); } myPlayers.clear(); } bool UITeamState::SortingLessFunction(CUIWindow* left, CUIWindow* right) { UIPlayerItem* lpi = static_cast<UIPlayerItem*>(left); UIPlayerItem* rpi = static_cast<UIPlayerItem*>(right); VERIFY(lpi && rpi); if (lpi->GetPlayerCheckPoints() > rpi->GetPlayerCheckPoints()) return true; return false; } void UITeamState::Init(CUIXml& uiXml, LPCSTR teamNodeName, int index) { VERIFY(teamNodeName); mainUiXml = &uiXml; //warning ! teamXmlNode = uiXml.NavigateToNode(teamNodeName, index); VERIFY2(teamXmlNode, make_string("team xml node (%s) not found", teamNodeName).c_str()); CUIXmlInit::InitWindow(uiXml, teamNodeName, index, this); XML_NODE* tempRoot = uiXml.GetLocalRoot(); uiXml.SetLocalRoot(teamXmlNode); InitScrollPanels(); //CUIXmlInit::InitScrollView(uiXml, "scroll_panel", 0, myScrollList); //myTeamHeader->Init(uiXml, "team_header"); uiXml.SetLocalRoot(tempRoot); } int UITeamState::InitScrollPanels() { XML_NODE* scroll_panels_root = mainUiXml->NavigateToNode("scroll_panels", 0); VERIFY2(scroll_panels_root, "scroll_panels tag not found"); XML_NODE* tempRoot = mainUiXml->GetLocalRoot(); int panels_count = mainUiXml->ReadAttribInt(scroll_panels_root, "count", 0); VERIFY2(panels_count, "count of scroll panels is 0, minimum is 1"); for (int i = 0; i < panels_count; ++i) { mainUiXml->SetLocalRoot(scroll_panels_root); TScrollPanel temp_panel; XML_NODE* panel_root = mainUiXml->NavigateToNode("panel", i); if (!panel_root) break; mainUiXml->SetLocalRoot(panel_root); temp_panel.first = xr_new<CUIScrollView>(); temp_panel.first->m_sort_function = fastdelegate::MakeDelegate (this, &UITeamState::SortingLessFunction); temp_panel.second = xr_new<UITeamHeader>(this); temp_panel.first->SetAutoDelete(true); temp_panel.second->SetAutoDelete(true); this->AttachChild(temp_panel.first); CUIXmlInit::InitScrollView(*mainUiXml, "scroll_panel", 0, temp_panel.first); this->AttachChild(temp_panel.second); temp_panel.second->Init(*mainUiXml, "team_header"); m_scroll_panels.push_back(temp_panel); } m_last_panel = 0; mainUiXml->SetLocalRoot(tempRoot); return 0; } inline UITeamState::TScrollPanels::size_type UITeamState::GetNeedScrollPanelIndex() { int panels_count = m_scroll_panels.size(); VERIFY (panels_count); if (m_last_panel >= panels_count) { m_last_panel = 0; return 0; } return m_last_panel++; } void UITeamState::ReStoreAllPlayers() { typedef MapClientIdToUIPlayer::iterator PlayerIter; if (m_scroll_panels.size() == 1) return; PlayerIter ite = myPlayers.end(); m_last_panel = 0; for (PlayerIter i = myPlayers.begin(); i != ite; ++i) { VERIFY (i->second.m_panel_number < m_scroll_panels.size()); m_scroll_panels[i->second.m_panel_number].first->RemoveWindow (i->second.m_player_wnd); TScrollPanels::size_type new_store_panel = GetNeedScrollPanelIndex(); VERIFY (new_store_panel < m_scroll_panels.size()); m_scroll_panels[new_store_panel].first->AddWindow (i->second.m_player_wnd, false); i->second.m_panel_number = new_store_panel; } } void UITeamState::AddPlayer(ClientID const & clientId) { game_cl_GameState::PLAYERS_MAP & playersMap = Game().players; game_cl_GameState::PLAYERS_MAP::iterator pi = playersMap.find(clientId); VERIFY(pi != playersMap.end()); /*if (pi == playersMap.end()) { Msg("--- Player not found by ClientID = 0x%08x", clientId.value()); return; }*/ game_PlayerState *ps = pi->second; VERIFY(ps); /*if (!ps) { return; }*/ // if player not in my team... if (Game().IsPlayerInTeam(ps, myTeam) == false) { return; } #ifdef DEBUG Msg("--- UITeamState: adding player (ClientID = 0x%08x) to %d team (0x%08x)", clientId.value(), myTeam, this); #endif // #ifdef DEBUG UIPlayerItem* tempPlayerItem = xr_new<UIPlayerItem>(static_cast<ETeam>(ps->team), clientId, this, m_teamPanels); VERIFY2(tempPlayerItem, make_string("failed to create player with ClientID = 0x%08x", clientId.value()).c_str()); TScrollPanels::size_type panel_index = GetNeedScrollPanelIndex(); VERIFY(panel_index < m_scroll_panels.size()); m_scroll_panels[panel_index].first->AddWindow(tempPlayerItem, false); VERIFY2(mainUiXml, "main UI XML not initialized"); XML_NODE* tempRoot = mainUiXml->GetLocalRoot(); mainUiXml->SetLocalRoot(teamXmlNode); if (clientId == Game().local_svdpnid) { tempPlayerItem->Init(*mainUiXml, "local_player_item", 0); } else { tempPlayerItem->Init(*mainUiXml, "player_item", 0); } mainUiXml->SetLocalRoot(tempRoot); myPlayers.insert(std::make_pair(clientId, TPlayerItem(tempPlayerItem, panel_index))); } void UITeamState::RemovePlayer(ClientID const & clientId) { MapClientIdToUIPlayer::iterator tempIter = myPlayers.find(clientId); if (tempIter != myPlayers.end()) { toDeletePlayers.push_back(clientId); } } bool UITeamState::UpdatePlayer(ClientID const & clientId) { bool retVal = false; MapClientIdToUIPlayer::iterator tempIter = myPlayers.find(clientId); if (tempIter != myPlayers.end()) { retVal = true; game_cl_GameState::PLAYERS_MAP & playersMap = Game().players; game_cl_GameState::PLAYERS_MAP::iterator pi = playersMap.find(clientId); VERIFY2(pi != playersMap.end(), "player not found in Game().player list, but in UI list it exist"); game_PlayerState *ps = pi->second; // it can be NULL... and player will be removed by player item window VERIFY(ps); /*if (!ps) { Msg("--- Player state of ClientID = 0x%08x is NULL", clientId.value()); return true; }*/ if (Game().IsPlayerInTeam(ps, myTeam) == false) { RemovePlayer(clientId); retVal = false; //tricky step :) player will be added by UITeamPanels::UpdatePlayer method :) } // warning ! after this Update tempIter will be not valid !!! Update(); // --^ } return retVal; } s32 UITeamState::GetFieldValue(shared_str const & field_name) const { if (field_name.equal("mp_artefacts_upcase")) { return m_artefact_count; } else if (field_name.equal("mp_players")) { return static_cast<s32>(myPlayers.size()); } else if (field_name.equal("mp_frags_upcase")) { return GetSummaryFrags(); } return -1; } s32 UITeamState::GetSummaryFrags() const { typedef game_cl_GameState::PLAYERS_MAP::const_iterator PlCIter; game_cl_GameState::PLAYERS_MAP & playersMap = Game().players; s32 sum = 0; PlCIter eiter = playersMap.end(); for (PlCIter i = playersMap.begin(); i != eiter; ++i) { game_PlayerState* ps = i->second; if (!ps) continue; game_cl_mp* tempGame = smart_cast<game_cl_mp*>(&Game()); R_ASSERT(tempGame); if (static_cast<ETeam>(tempGame->ModifyTeam(ps->team)) == myTeam) sum = sum + ps->m_iRivalKills; } return sum; } void UITeamState::Draw() { inherited::Draw(); } void UITeamState::Update() { if (toDeletePlayers.size()) { xr_vector<ClientID>::iterator ie = toDeletePlayers.end(); for (xr_vector<ClientID>::iterator i = toDeletePlayers.begin(); i != ie; ++i) { MapClientIdToUIPlayer::iterator tempIter = myPlayers.find(*i); VERIFY2(tempIter != myPlayers.end(), "player not found while deleting"); #ifdef DEBUG Msg("--- UITeamState: deleting player (ClientID = 0x%08x) from %d team (0x%08x)", i->value(), myTeam, this); #endif // #ifdef DEBUG VERIFY(m_scroll_panels.size() > tempIter->second.m_panel_number); m_scroll_panels[tempIter->second.m_panel_number].first->RemoveWindow(tempIter->second.m_player_wnd); xr_delete(tempIter->second.m_player_wnd); myPlayers.erase(tempIter); } ReStoreAllPlayers(); //warning ! uses myPlayers toDeletePlayers.clear(); } TScrollPanels::iterator ite = m_scroll_panels.end(); for (TScrollPanels::iterator it = m_scroll_panels.begin(); it != ite; ++it) { it->first->ForceUpdate(); } inherited::Update(); } void UITeamState::SetArtefactsCount(s32 greenTeamArtC, s32 blueTeamArtC) { if (myTeam == etGreenTeam) { m_artefact_count = greenTeamArtC; } else if (myTeam == etBlueTeam) { m_artefact_count = blueTeamArtC; } }
412
0.968374
1
0.968374
game-dev
MEDIA
0.512835
game-dev,desktop-app
0.976387
1
0.976387
amkhrjee/pathfinder
1,238
algorithm/astar.go
package algorithm import ( "math" "pfinder/grid" pq "gopkg.in/dnaeon/go-priorityqueue.v1" ) // A* Search func AStar(g *grid.Grid, start *grid.Box, target *grid.Box) ([]*grid.Box, []*grid.Box) { q := pq.New[*grid.Box, float64](pq.MinHeap) track := make([]*grid.Box, 0, (grid.WIDTH/grid.BOX_DIM)*(grid.HEIGHT/grid.BOX_DIM)) final_path := make([]*grid.Box, 0, (grid.WIDTH/grid.BOX_DIM)*(grid.HEIGHT/grid.BOX_DIM)) // inserting the initial nodes for _, n := range neighbors(g, start) { relative_cost := math.Abs(n.Cost - start.Cost) euclidean_dist := get_distance(target, n) q.Put(n, relative_cost+euclidean_dist) n.Visited = true } for !q.IsEmpty() { curr := q.Get() track = append(track, curr.Value) if curr.Value == target { break } for _, n := range neighbors(g, curr.Value) { if !n.Visited { euclidean_dist := get_distance(target, n) relative_cost := math.Abs(n.Cost - curr.Value.Cost) total_cost := curr.Priority + relative_cost + euclidean_dist q.Put(n, total_cost) n.Parent = curr.Value n.Visited = true } } } // backtracking the path curr := target for curr != nil { final_path = append(final_path, curr) curr = curr.Parent } return track, final_path }
412
0.837725
1
0.837725
game-dev
MEDIA
0.429124
game-dev
0.866589
1
0.866589
ScutGame/Scut-samples
5,199
Koudai/Server/src/ZyGames.Tianjiexing.Web/Script/CsScript/Action/Action6202.cs
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.Data; using ZyGames.Framework.Cache.Generic; using ZyGames.Framework.Cache.Generic; using ZyGames.Framework.Collection; using ZyGames.Framework.Common; using ZyGames.Framework.Game.Service; using ZyGames.Tianjiexing.BLL.Base; using ZyGames.Tianjiexing.Lang; using ZyGames.Tianjiexing.Model; using ZyGames.Tianjiexing.Model.Config; namespace ZyGames.Tianjiexing.BLL.Action { /// <summary> /// 6202_公会技能可升级列表接口 /// </summary> public class Action6202 : BaseAction { private int pageIndex; private int pageSize; private int pageCount; private List<GuildAbility> abilityArray = new List<GuildAbility>(); public Action6202(ZyGames.Framework.Game.Contract.HttpGet httpGet) : base(ActionIDDefine.Cst_Action6202, httpGet) { } public override void BuildPacket() { this.PushIntoStack(pageCount); this.PushIntoStack(abilityArray.Count); foreach (GuildAbility item in abilityArray) { GuildAbilityInfo gAbilityInfo = new ShareCacheStruct<GuildAbilityInfo>().FindKey(item.ID); GuildAbilityLvInfo abilityLvInfo = new ShareCacheStruct<GuildAbilityLvInfo>().FindKey(item.ID, item.Lv); DataStruct dsItem = new DataStruct(); dsItem.PushIntoStack(item.ID); dsItem.PushIntoStack(gAbilityInfo == null ? string.Empty : gAbilityInfo.AbilityName.ToNotNullString()); dsItem.PushIntoStack(gAbilityInfo == null ? string.Empty : gAbilityInfo.AbilityHead.ToNotNullString()); dsItem.PushIntoStack(item.Lv); dsItem.PushIntoStack(abilityLvInfo == null ? string.Empty : abilityLvInfo.EffectNum.ToNotNullString()); this.PushIntoStack(dsItem); } } public override bool GetUrlElement() { if (httpGet.GetInt("PageIndex", ref pageIndex) && httpGet.GetInt("PageSize", ref pageSize)) { return true; } return false; } public override bool TakeAction() { if (!string.IsNullOrEmpty(ContextUser.MercenariesID)) { GuildMember member = new ShareCacheStruct<GuildMember>().FindKey(ContextUser.MercenariesID, ContextUser.UserID); if (member != null && member.PostType == PostType.Member) { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St6007_AuditPermissions; return false; } UserGuild guild = new ShareCacheStruct<UserGuild>().FindKey(ContextUser.MercenariesID); if (guild != null && guild.AbilityInfo.Count > 0) { List<GuildAbility> guildAbilitiesList = new List<GuildAbility>(); List<GuildAbility> abilitiesList = guild.AbilityInfo.FindAll(m => m.Lv < 10); foreach (GuildAbility ability in abilitiesList) { GuildAbilityLvInfo abilityLvInfo = new ShareCacheStruct<GuildAbilityLvInfo>().FindKey(ability.ID, ability.Lv); if (abilityLvInfo != null && guild.CurrDonateNum >= abilityLvInfo.UpDonateNum) { guildAbilitiesList.Add(ability); } } abilityArray = guildAbilitiesList.GetPaging(pageIndex, pageSize, out pageCount); } } else { ErrorCode = LanguageManager.GetLang().ErrorCode; ErrorInfo = LanguageManager.GetLang().St6203_GuildMemberNotEnough; return false; } return true; } } }
412
0.789951
1
0.789951
game-dev
MEDIA
0.799885
game-dev
0.885575
1
0.885575
InsiderAnh/StellarProtect
2,275
v1_20_R2/src/main/java/io/github/insideranh/stellarprotect/nms/v1_20_R2/listeners/BlockListener_v1_20_R2.java
package io.github.insideranh.stellarprotect.nms.v1_20_R2.listeners; import io.github.insideranh.stellarprotect.api.events.EventLogicHandler; import org.bukkit.block.BlockState; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityResurrectEvent; import org.bukkit.event.inventory.BrewEvent; import org.bukkit.event.inventory.SmithItemEvent; import org.bukkit.event.world.PortalCreateEvent; import org.spigotmc.event.entity.EntityDismountEvent; import org.spigotmc.event.entity.EntityMountEvent; import java.util.ArrayList; import java.util.stream.Collectors; public class BlockListener_v1_20_R2 implements Listener { private final EventLogicHandler eventLogicHandler; public BlockListener_v1_20_R2(EventLogicHandler eventLogicHandler) { this.eventLogicHandler = eventLogicHandler; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPortalCreate(PortalCreateEvent event) { this.eventLogicHandler.onPortalCreate(event.getBlocks().stream().map(BlockState::getBlock).collect(Collectors.toCollection(ArrayList::new))); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onSmithEvent(SmithItemEvent event) { this.eventLogicHandler.onSmithEvent(event.getWhoClicked(), event.getInventory().getResult()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBrewEvent(BrewEvent event) { this.eventLogicHandler.onBrewEvent(event.getContents().getIngredient(), event.getContents().getFuel(), event.getResults()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onTotemEvent(EntityResurrectEvent event) { this.eventLogicHandler.onTotemEvent(event.getEntity(), event.getHand() == null ? "" : event.getHand().name()); } @EventHandler public void onMount(EntityMountEvent event) { this.eventLogicHandler.onMount(event.getMount(), event.getEntity()); } @EventHandler public void onDismount(EntityDismountEvent event) { this.eventLogicHandler.onDismount(event.getDismounted(), event.getEntity()); } }
412
0.82237
1
0.82237
game-dev
MEDIA
0.403682
game-dev
0.923014
1
0.923014
ForestDango/Hollow-Knight-Demo
1,548
Assets/PlayMaker/Actions/Animator/GetAnimatorDelta.cs
// (c) Copyright HutongGames, LLC 2010-2016. All rights reserved. using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Animator)] [Tooltip("Gets the avatar delta position and rotation for the last evaluated frame.")] public class GetAnimatorDelta: FsmStateActionAnimatorBase { [RequiredField] [CheckForComponent(typeof(Animator))] [Tooltip("The GameObject with an Animator Component.")] public FsmOwnerDefault gameObject; [UIHint(UIHint.Variable)] [Tooltip("The avatar delta position for the last evaluated frame")] public FsmVector3 deltaPosition; [UIHint(UIHint.Variable)] [Tooltip("The avatar delta position for the last evaluated frame")] public FsmQuaternion deltaRotation; private Animator animator { get { return cachedComponent; } } public override void Reset() { base.Reset(); gameObject = null; deltaPosition= null; deltaRotation = null; } public override void OnEnter() { DoGetDeltaPosition(); if (!everyFrame) { Finish(); } } public override void OnActionUpdate() { DoGetDeltaPosition(); } private void DoGetDeltaPosition() { if (!UpdateCache(Fsm.GetOwnerDefaultTarget(gameObject))) { Finish(); return; } deltaPosition.Value = animator.deltaPosition; deltaRotation.Value = animator.deltaRotation; } } }
412
0.890529
1
0.890529
game-dev
MEDIA
0.99124
game-dev
0.853828
1
0.853828
2dos/DK64-Randomizer
1,158
base-hack/src/shorteners/quality_shorteners.c
#include "../../include/common.h" void qualityOfLife_shorteners(void) { if (Rando.quality_of_life.reduce_lag) { if (CurrentMap == MAP_CASTLE) { if (ObjectModel2Timer <= 5) { actorData* lzcontroller = (actorData*)findActorWithType(0xC); char* lzpaad = (char*)lzcontroller->paad; *(char*)(lzpaad) = 0; } } } } void fastWarp(void* actor, int player_index) { unkMultiplayerWarpFunction(actor,player_index); renderScreenTransition(3); } void fastWarp_playMusic(void* actor) { clearTagSlide(actor); playLevelMusic(); } void fastWarpShockwaveFix(void) { if (!Rando.fast_warp) { return; } if (!Player) { return; } if (Player->control_state != 0x54) { // Not Multiplayer Warp return; } if (Player->shockwave_timer == -1) { // Not Charging Shockwave return; } if (Player->shockwave_timer >= 5) { return; } Player->shockwave_timer += 1; if (Player->shockwave_timer < 2) { Player->shockwave_timer += 1; // Prevent ever being a frame where you can shockwave } }
412
0.916122
1
0.916122
game-dev
MEDIA
0.932858
game-dev
0.906007
1
0.906007
Legacy-Fabric/fabric
1,591
legacy-fabric-block-api-v1/1.7.10/src/main/java/net/legacyfabric/fabric/mixin/block/versioned/ItemMixin.java
/* * Copyright (c) 2020 - 2025 Legacy Fabric * Copyright (c) 2016 - 2022 FabricMC * * 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. */ package net.legacyfabric.fabric.mixin.block.versioned; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.legacyfabric.fabric.api.registry.v2.RegistryHelper; import net.legacyfabric.fabric.api.util.Identifier; @Mixin(Item.class) public class ItemMixin { @Inject(method = "fromBlock", at = @At("HEAD"), cancellable = true) private static void fixItemFromBlock(Block block, CallbackInfoReturnable<Item> cir) { Identifier identifier = RegistryHelper.getId(Block.REGISTRY, block); if (identifier != null) { Item item = RegistryHelper.<Item>getValue(Item.REGISTRY, identifier); if (item != null) { cir.setReturnValue(item); return; } } cir.setReturnValue(null); } }
412
0.657097
1
0.657097
game-dev
MEDIA
0.938709
game-dev
0.797512
1
0.797512
magefree/mage
4,319
Mage.Sets/src/mage/cards/p/ParnesseTheSubtleBrush.java
package mage.cards.p; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.common.BecomesTargetControllerTriggeredAbility; import mage.abilities.costs.common.PayLifeCost; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.CounterUnlessPaysEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.StaticFilters; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.stack.Spell; import mage.players.Player; import mage.target.common.TargetOpponent; import java.util.UUID; /** * @author Alex-Vasile */ public class ParnesseTheSubtleBrush extends CardImpl { protected static final String SPELL_KEY = "castCopiedSpell"; public ParnesseTheSubtleBrush(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{B}{R}"); this.supertype.add(SuperType.LEGENDARY); this.addSubType(SubType.VAMPIRE, SubType.WIZARD); this.power = new MageInt(4); this.toughness = new MageInt(4); // Whenever you or a permanent you control becomes the target of a spell or ability an opponent controls, // counter that spell or ability unless that player pays 4 life. this.addAbility(new BecomesTargetControllerTriggeredAbility(new CounterUnlessPaysEffect(new PayLifeCost(4).setText("4 life")), StaticFilters.FILTER_CONTROLLED_A_PERMANENT, StaticFilters.FILTER_SPELL_OR_ABILITY_OPPONENTS, SetTargetPointer.SPELL, false)); // Whenever you copy a spell, up to one target opponent may also copy that spell. // They may choose new targets for that copy. this.addAbility(new ParnesseTheSubtleBrushCopySpellTriggeredAbility()); } private ParnesseTheSubtleBrush(final ParnesseTheSubtleBrush card) { super(card); } @Override public ParnesseTheSubtleBrush copy() { return new ParnesseTheSubtleBrush(this); } } class ParnesseTheSubtleBrushCopySpellOpponentEffect extends OneShotEffect { ParnesseTheSubtleBrushCopySpellOpponentEffect() { super(Outcome.Detriment); this.staticText = "up to one target opponent may also copy that spell. " + "They may choose new targets for that copy"; } private ParnesseTheSubtleBrushCopySpellOpponentEffect(final ParnesseTheSubtleBrushCopySpellOpponentEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Player opponent = game.getPlayer(source.getFirstTarget()); Object object = getValue(ParnesseTheSubtleBrush.SPELL_KEY); if (opponent == null || !(object instanceof Spell)) { return false; } Spell spellToCopy = (Spell) object; spellToCopy.createCopyOnStack(game, source, opponent.getId(), true); return true; } @Override public ParnesseTheSubtleBrushCopySpellOpponentEffect copy() { return new ParnesseTheSubtleBrushCopySpellOpponentEffect(this); } } class ParnesseTheSubtleBrushCopySpellTriggeredAbility extends TriggeredAbilityImpl { ParnesseTheSubtleBrushCopySpellTriggeredAbility() { super(Zone.BATTLEFIELD, new ParnesseTheSubtleBrushCopySpellOpponentEffect(), false); this.getTargets().add(new TargetOpponent(0, 1, false)); setTriggerPhrase("Whenever you copy a spell, "); } private ParnesseTheSubtleBrushCopySpellTriggeredAbility(final ParnesseTheSubtleBrushCopySpellTriggeredAbility ability) { super(ability); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.COPIED_STACKOBJECT; } @Override public boolean checkTrigger(GameEvent event, Game game) { Spell spell = game.getSpell(event.getTargetId()); if (spell == null || !spell.isControlledBy(this.getControllerId())) { return false; } getEffects().setValue(ParnesseTheSubtleBrush.SPELL_KEY, spell); return true; } @Override public ParnesseTheSubtleBrushCopySpellTriggeredAbility copy() { return new ParnesseTheSubtleBrushCopySpellTriggeredAbility(this); } }
412
0.914706
1
0.914706
game-dev
MEDIA
0.632889
game-dev,testing-qa
0.915124
1
0.915124
mynameisProjects/pokeemeraldplusplus
2,412
data/maps/AquaHideout_UnusedRubyMap1/scripts.inc
AquaHideout_UnusedRubyMap1_MapScripts:: .byte 0 AquaHideout_UnusedRubyMap1_EventScript_MewTwoStoneOne:: finditem ITEM_MEWTWONITE_X end AquaHideout_UnusedRubyMap1_EventScript_MewTwoStoneTwo:: finditem ITEM_MEWTWONITE_Y end AquaHideout_UnusedRubyMap1_EventScript_MAG1:: trainerbattle_single TRAINER_MAG1_MEWTWO, AquaHideout_UnusedRubyMap1_Text_MAG1Intro, AquaHideout_UnusedRubyMap1_Text_MAG1Defeat msgbox AquaHideout_UnusedRubyMap1_Text_MAG1PostBattle, MSGBOX_AUTOCLOSE end AquaHideout_UnusedRubyMap1_EventScript_FMG1:: trainerbattle_single TRAINER_FMG1_MEWTWO, AquaHideout_UnusedRubyMap1_Text_FMG1Intro, AquaHideout_UnusedRubyMap1_Text_FMG1Defeat msgbox AquaHideout_UnusedRubyMap1_Text_FMG1PostBattle, MSGBOX_AUTOCLOSE end AquaHideout_UnusedRubyMap1_EventScript_MMG1:: trainerbattle_single TRAINER_MMG1_MEWTWO, AquaHideout_UnusedRubyMap1_Text_MMG1Intro, AquaHideout_UnusedRubyMap1_Text_MMG1Defeat msgbox AquaHideout_UnusedRubyMap1_Text_MMG1PostBattle, MSGBOX_AUTOCLOSE end AquaHideout_UnusedRubyMap1_EventScript_FAG1:: trainerbattle_single TRAINER_FAG1_MEWTWO, AquaHideout_UnusedRubyMap1_Text_FAG1Intro, AquaHideout_UnusedRubyMap1_Text_FAG1Defeat msgbox AquaHideout_UnusedRubyMap1_Text_FAG1PostBattle, MSGBOX_AUTOCLOSE end AquaHideout_UnusedRubyMap1_Text_MAG1Intro: .string "Hey kid, this place is off limits!$" AquaHideout_UnusedRubyMap1_Text_MAG1Defeat: .string "You're nothing!$" AquaHideout_UnusedRubyMap1_Text_MAG1PostBattle: .string "The others will put you in your place.$" AquaHideout_UnusedRubyMap1_Text_FMG1Intro: .string "We got wise and ditched our teams to\n" .string "make a new team!$" AquaHideout_UnusedRubyMap1_Text_FMG1Defeat: .string "I can't believe it.$" AquaHideout_UnusedRubyMap1_Text_FMG1PostBattle: .string "You won't stop our plans.$" AquaHideout_UnusedRubyMap1_Text_MMG1Intro: .string "The boss is up to some weird stuff with\n" .string "some kinda lab POKéMON.$" AquaHideout_UnusedRubyMap1_Text_MMG1Defeat: .string "I didn't sign up for this!$" AquaHideout_UnusedRubyMap1_Text_MMG1PostBattle: .string "I don't get paid enough to deal with\n" .string "brats like you.$" AquaHideout_UnusedRubyMap1_Text_FAG1Intro: .string "Stop trying! You can't stop us!$" AquaHideout_UnusedRubyMap1_Text_FAG1Defeat: .string "Okay.. maybe you can.$" AquaHideout_UnusedRubyMap1_Text_FAG1PostBattle: .string "Just wait till the boss hears about this...$"
412
0.528084
1
0.528084
game-dev
MEDIA
0.724457
game-dev
0.771219
1
0.771219
sunsvip/GF_X
41,915
Assets/Plugins/DOTween/Modules/DOTweenModuleUI.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 #if true // MODULE_MARKER using System; using System.Globalization; using UnityEngine; using UnityEngine.UI; using DG.Tweening.Core; using DG.Tweening.Core.Enums; using DG.Tweening.Plugins; using DG.Tweening.Plugins.Options; using Outline = UnityEngine.UI.Outline; using Text = UnityEngine.UI.Text; #pragma warning disable 1591 namespace DG.Tweening { public static class DOTweenModuleUI { #region Shortcuts #region CanvasGroup /// <summary>Tweens a CanvasGroup's alpha color to the given value. /// Also stores the canvasGroup as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<float, float, FloatOptions> DOFade(this CanvasGroup target, float endValue, float duration) { TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.alpha, x => target.alpha = x, endValue, duration); t.SetTarget(target); return t; } #endregion #region Graphic /// <summary>Tweens an Graphic's color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Graphic target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Graphic's alpha color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Graphic target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } #endregion #region Image /// <summary>Tweens an Image's color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Image target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Image's alpha color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Image target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Image's fillAmount to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach (0 to 1)</param><param name="duration">The duration of the tween</param> public static TweenerCore<float, float, FloatOptions> DOFillAmount(this Image target, float endValue, float duration) { if (endValue > 1) endValue = 1; else if (endValue < 0) endValue = 0; TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.fillAmount, x => target.fillAmount = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Image's colors using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Image target, Gradient gradient, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.color = c.color; continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } #endregion #region LayoutElement /// <summary>Tweens an LayoutElement's flexibleWidth/Height to the given value. /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOFlexibleSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.flexibleWidth, target.flexibleHeight), x => { target.flexibleWidth = x.x; target.flexibleHeight = x.y; }, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens an LayoutElement's minWidth/Height to the given value. /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOMinSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.minWidth, target.minHeight), x => { target.minWidth = x.x; target.minHeight = x.y; }, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens an LayoutElement's preferredWidth/Height to the given value. /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPreferredSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.preferredWidth, target.preferredHeight), x => { target.preferredWidth = x.x; target.preferredHeight = x.y; }, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } #endregion #region Outline /// <summary>Tweens a Outline's effectColor to the given value. /// Also stores the Outline as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Outline target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.effectColor, x => target.effectColor = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Outline's effectColor alpha to the given value. /// Also stores the Outline as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Outline target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.effectColor, x => target.effectColor = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Outline's effectDistance to the given value. /// Also stores the Outline as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOScale(this Outline target, Vector2 endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.effectDistance, x => target.effectDistance = x, endValue, duration); t.SetTarget(target); return t; } #endregion #region RectTransform /// <summary>Tweens a RectTransform's anchoredPosition to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPos(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition X to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosX(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue, 0), duration); t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition Y to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosY(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, endValue), duration); t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3D(this RectTransform target, Vector3 endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D X to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DX(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(endValue, 0, 0), duration); t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D Y to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DY(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, endValue, 0), duration); t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D Z to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DZ(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, 0, endValue), duration); t.SetOptions(AxisConstraint.Z, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchorMax to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMax(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMax, x => target.anchorMax = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchorMin to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMin(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMin, x => target.anchorMin = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's pivot to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivot(this RectTransform target, Vector2 endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a RectTransform's pivot X to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotX(this RectTransform target, float endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(endValue, 0), duration); t.SetOptions(AxisConstraint.X).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's pivot Y to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotY(this RectTransform target, float endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(0, endValue), duration); t.SetOptions(AxisConstraint.Y).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's sizeDelta to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOSizeDelta(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.sizeDelta, x => target.sizeDelta = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Punches a RectTransform's anchoredPosition towards the given direction and then back to the starting one /// as if it was connected to the starting position via an elastic. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="punch">The direction and strength of the punch (added to the RectTransform's current position)</param> /// <param name="duration">The duration of the tween</param> /// <param name="vibrato">Indicates how much will the punch vibrate</param> /// <param name="elasticity">Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards. /// 1 creates a full oscillation between the punch direction and the opposite direction, /// while 0 oscillates only between the punch and the start position</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DOPunchAnchorPos(this RectTransform target, Vector2 punch, float duration, int vibrato = 10, float elasticity = 1, bool snapping = false) { return DOTween.Punch(() => target.anchoredPosition, x => target.anchoredPosition = x, punch, duration, vibrato, elasticity) .SetTarget(target).SetOptions(snapping); } /// <summary>Shakes a RectTransform's anchoredPosition with the given values. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="duration">The duration of the tween</param> /// <param name="strength">The shake strength</param> /// <param name="vibrato">Indicates how much will the shake vibrate</param> /// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). /// Setting it to 0 will shake along a single direction.</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> /// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param> /// <param name="randomnessMode">Randomness mode</param> public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, float strength = 100, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true, ShakeRandomnessMode randomnessMode = ShakeRandomnessMode.Full) { return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, true, fadeOut, randomnessMode) .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping); } /// <summary>Shakes a RectTransform's anchoredPosition with the given values. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="duration">The duration of the tween</param> /// <param name="strength">The shake strength on each axis</param> /// <param name="vibrato">Indicates how much will the shake vibrate</param> /// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). /// Setting it to 0 will shake along a single direction.</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> /// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param> /// <param name="randomnessMode">Randomness mode</param> public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, Vector2 strength, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true, ShakeRandomnessMode randomnessMode = ShakeRandomnessMode.Full) { return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, fadeOut, randomnessMode) .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping); } #region Special /// <summary>Tweens a RectTransform's anchoredPosition to the given value, while also applying a jump effect along the Y axis. /// Returns a Sequence instead of a Tweener. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param> /// <param name="jumpPower">Power of the jump (the max height of the jump is represented by this plus the final Y offset)</param> /// <param name="numJumps">Total number of jumps</param> /// <param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Sequence DOJumpAnchorPos(this RectTransform target, Vector2 endValue, float jumpPower, int numJumps, float duration, bool snapping = false) { if (numJumps < 1) numJumps = 1; float startPosY = 0; float offsetY = -1; bool offsetYSet = false; // Separate Y Tween so we can elaborate elapsedPercentage on that insted of on the Sequence // (in case users add a delay or other elements to the Sequence) Sequence s = DOTween.Sequence(); Tween yTween = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, jumpPower), duration / (numJumps * 2)) .SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative() .SetLoops(numJumps * 2, LoopType.Yoyo) .OnStart(()=> startPosY = target.anchoredPosition.y); s.Append(DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue.x, 0), duration) .SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear) ).Join(yTween) .SetTarget(target).SetEase(DOTween.defaultEaseType); s.OnUpdate(() => { if (!offsetYSet) { offsetYSet = true; offsetY = s.isRelative ? endValue.y : endValue.y - startPosY; } Vector2 pos = target.anchoredPosition; pos.y += DOVirtual.EasedValue(0, offsetY, s.ElapsedDirectionalPercentage(), Ease.OutQuad); target.anchoredPosition = pos; }); return s; } #endregion #endregion #region ScrollRect /// <summary>Tweens a ScrollRect's horizontal/verticalNormalizedPosition to the given value. /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DONormalizedPos(this ScrollRect target, Vector2 endValue, float duration, bool snapping = false) { return DOTween.To(() => new Vector2(target.horizontalNormalizedPosition, target.verticalNormalizedPosition), x => { target.horizontalNormalizedPosition = x.x; target.verticalNormalizedPosition = x.y; }, endValue, duration) .SetOptions(snapping).SetTarget(target); } /// <summary>Tweens a ScrollRect's horizontalNormalizedPosition to the given value. /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DOHorizontalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false) { return DOTween.To(() => target.horizontalNormalizedPosition, x => target.horizontalNormalizedPosition = x, endValue, duration) .SetOptions(snapping).SetTarget(target); } /// <summary>Tweens a ScrollRect's verticalNormalizedPosition to the given value. /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DOVerticalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false) { return DOTween.To(() => target.verticalNormalizedPosition, x => target.verticalNormalizedPosition = x, endValue, duration) .SetOptions(snapping).SetTarget(target); } #endregion #region Slider /// <summary>Tweens a Slider's value to the given value. /// Also stores the Slider as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<float, float, FloatOptions> DOValue(this Slider target, float endValue, float duration, bool snapping = false) { TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.value, x => target.value = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } #endregion #region Text /// <summary>Tweens a Text's color to the given value. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Text target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary> /// Tweens a Text's text from one integer to another, with options for thousands separators /// </summary> /// <param name="fromValue">The value to start from</param> /// <param name="endValue">The end value to reach</param> /// <param name="duration">The duration of the tween</param> /// <param name="addThousandsSeparator">If TRUE (default) also adds thousands separators</param> /// <param name="culture">The <see cref="CultureInfo"/> to use (InvariantCulture if NULL)</param> public static TweenerCore<int, int, NoOptions> DOCounter( this Text target, int fromValue, int endValue, float duration, bool addThousandsSeparator = true, CultureInfo culture = null ){ int v = fromValue; CultureInfo cInfo = !addThousandsSeparator ? null : culture ?? CultureInfo.InvariantCulture; TweenerCore<int, int, NoOptions> t = DOTween.To(() => v, x => { v = x; target.text = addThousandsSeparator ? v.ToString("N0", cInfo) : v.ToString(); }, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Text's alpha color to the given value. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Text target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Text's text to the given value. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end string to tween to</param><param name="duration">The duration of the tween</param> /// <param name="richTextEnabled">If TRUE (default), rich text will be interpreted correctly while animated, /// otherwise all tags will be considered as normal text</param> /// <param name="scrambleMode">The type of scramble mode to use, if any</param> /// <param name="scrambleChars">A string containing the characters to use for scrambling. /// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters. /// Leave it to NULL (default) to use default ones</param> public static TweenerCore<string, string, StringOptions> DOText(this Text target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null) { if (endValue == null) { if (Debugger.logPriority > 0) Debugger.LogWarning("You can't pass a NULL string to DOText: an empty string will be used instead to avoid errors"); endValue = ""; } TweenerCore<string, string, StringOptions> t = DOTween.To(() => target.text, x => target.text = x, endValue, duration); t.SetOptions(richTextEnabled, scrambleMode, scrambleChars) .SetTarget(target); return t; } #endregion #region Blendables #region Graphic /// <summary>Tweens a Graphic's color to the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the Graphic as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this Graphic target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #region Image /// <summary>Tweens a Image's color to the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the Image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this Image target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #region Text /// <summary>Tweens a Text's color BY the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this Text target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #endregion #region Shapes /// <summary>Tweens a RectTransform's anchoredPosition so that it draws a circle around the given center. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations.<para/> /// IMPORTANT: SetFrom(value) requires a <see cref="Vector2"/> instead of a float, where the X property represents the "from degrees value"</summary> /// <param name="center">Circle-center/pivot around which to rotate (in UI anchoredPosition coordinates)</param> /// <param name="endValueDegrees">The end value degrees to reach (to rotate counter-clockwise pass a negative value)</param> /// <param name="duration">The duration of the tween</param> /// <param name="relativeCenter">If TRUE the <see cref="center"/> coordinates will be considered as relative to the target's current anchoredPosition</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, CircleOptions> DOShapeCircle( this RectTransform target, Vector2 center, float endValueDegrees, float duration, bool relativeCenter = false, bool snapping = false ) { TweenerCore<Vector2, Vector2, CircleOptions> t = DOTween.To( CirclePlugin.Get(), () => target.anchoredPosition, x => target.anchoredPosition = x, center, duration ); t.SetOptions(endValueDegrees, relativeCenter, snapping).SetTarget(target); return t; } #endregion #endregion // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ public static class Utils { /// <summary> /// Converts the anchoredPosition of the first RectTransform to the second RectTransform, /// taking into consideration offset, anchors and pivot, and returns the new anchoredPosition /// </summary> public static Vector2 SwitchToRectTransform(RectTransform from, RectTransform to) { Vector2 localPoint; Vector2 fromPivotDerivedOffset = new Vector2(from.rect.width * 0.5f + from.rect.xMin, from.rect.height * 0.5f + from.rect.yMin); Vector2 screenP = RectTransformUtility.WorldToScreenPoint(null, from.position); screenP += fromPivotDerivedOffset; RectTransformUtility.ScreenPointToLocalPointInRectangle(to, screenP, null, out localPoint); Vector2 pivotDerivedOffset = new Vector2(to.rect.width * 0.5f + to.rect.xMin, to.rect.height * 0.5f + to.rect.yMin); return to.anchoredPosition + localPoint - pivotDerivedOffset; } } } } #endif
412
0.929233
1
0.929233
game-dev
MEDIA
0.406733
game-dev
0.96637
1
0.96637
dotnet/iot
16,265
src/devices/Nmea0183/Ais/AisTargetExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Iot.Device.Common; using UnitsNet; using UnitsNet.Units; namespace Iot.Device.Nmea0183.Ais { /// <summary> /// Extension methods on AIS targets /// </summary> public static class AisTargetExtensions { /// <summary> /// Calculates the distance to another target /// </summary> /// <param name="self">First target</param> /// <param name="other">Other target</param> /// <returns>The distance between the two targets, based on their last known position</returns> public static Length DistanceTo(this AisTarget self, AisTarget other) { GreatCircle.DistAndDir(self.Position, other.Position, out Length distance, out _); return distance.ToUnit(LengthUnit.NauticalMile); } /// <summary> /// Returns the age of this target, relative to the indicated time. /// </summary> /// <param name="self">The target under investigation</param> /// <param name="toTime">The time to compare to (often <see cref="DateTimeOffset.UtcNow"/>)</param> /// <returns></returns> public static TimeSpan Age(this AisTarget self, DateTimeOffset toTime) { return toTime - self.LastSeen; } /// <summary> /// Calculates the relative position data set to another vessel. /// </summary> /// <param name="self">Our own vessel</param> /// <param name="other">The other ship or target (can also be a stationary target, such as an <see cref="AidToNavigation"/> instance)</param> /// <param name="now">The time at which the comparison occurs. Typically now, but it is also possible to estimate the dangers at another time. When playing /// back old data, this must correspond to the playback time</param> /// <param name="parameters">The parameters used for the calculation</param> /// <returns>An instance of <see cref="ShipRelativePosition"/> with all possible fields filled out.</returns> public static ShipRelativePosition? RelativePositionTo(this Ship self, AisTarget other, DateTimeOffset now, TrackEstimationParameters parameters) { return RelativePositionsTo(self, new List<AisTarget>() { other }, now, parameters).FirstOrDefault(); } /// <summary> /// Calculates the relative positions and the collision vectors from one ship to a group of targets. /// The algorithm used is inspired by https://core.ac.uk/download/74237799.pdf /// </summary> /// <param name="self">The own ship</param> /// <param name="others">The list of visible AIS targets</param> /// <param name="now">The current time (or the time the data is valid for)</param> /// <param name="parameters">Parameters controlling the accuracy and speed of the calculation</param> /// <returns>A list of relative positions between our ship and the targets. Targets without a valid position are skipped.</returns> /// <exception cref="ArgumentException">Our ship has no valid position</exception> /// <exception cref="InvalidDataException">An internal error occurred</exception> public static List<ShipRelativePosition> RelativePositionsTo(this Ship self, IEnumerable<AisTarget> others, DateTimeOffset now, TrackEstimationParameters parameters) { List<ShipRelativePosition> retList = new List<ShipRelativePosition>(); if (self.Position.ContainsValidPosition() == false) { throw new ArgumentException("The own ship has no valid position", nameof(self)); } var self1 = EstimatePosition(self, now, parameters.NormalStepSize); List<MovingTarget> thisTrack = GetEstimatedTrack(self1, now - parameters.StartTimeOffset, now + parameters.EndTimeOffset, parameters.NormalStepSize); foreach (var other in others) { if (other.Position.ContainsValidPosition() == false) { continue; } MovingTarget? otherAsMovingTarget = other as MovingTarget; Length distance; Angle direction; AisSafetyState state = AisSafetyState.Safe; if (other.LastSeen + parameters.TargetLostTimeout < now) { // For a lost target, don't do a full computation state = AisSafetyState.Lost; otherAsMovingTarget = null; } if (otherAsMovingTarget == null) { GreatCircle.DistAndDir(self.Position, other.Position, out distance, out direction); Angle? relativeDirection = null; if (self1.TrueHeading.HasValue) { relativeDirection = (direction - self1.TrueHeading.Value).Normalize(false); } // The other is not a ship - Assume static position (but make sure a lost target doesn't become a // dangerous target - we warn about lost targets separately) if (distance < parameters.WarningDistance && state != AisSafetyState.Lost) { state = AisSafetyState.Dangerous; } retList.Add(new ShipRelativePosition(self, other, distance, direction, state, now) { RelativeDirection = relativeDirection, }); } else { var otherPos = other.Position; GreatCircle.DistAndDir(self1.Position, otherPos, out distance, out direction); List<MovingTarget> otherTrack = GetEstimatedTrack(otherAsMovingTarget, now - parameters.StartTimeOffset, now + parameters.EndTimeOffset, parameters.NormalStepSize); if (thisTrack.Count != otherTrack.Count || thisTrack.Count < 1) { // The two lists must have equal length and contain at least one element throw new InvalidDataException("Internal error: Data structures inconsistent"); } Angle? relativeDirection = null; if (self1.TrueHeading.HasValue) { relativeDirection = (direction - self1.TrueHeading.Value).Normalize(false); } // Some really large distance Length minimumDistance = Length.FromAstronomicalUnits(1); DateTimeOffset timeOfMinimumDistance = default; int usedIndex = 0; for (int i = 0; i < thisTrack.Count; i++) { GreatCircle.DistAndDir(thisTrack[i].Position, otherTrack[i].Position, out Length distance1, out _, out _); if (distance1 < minimumDistance) { minimumDistance = distance1; timeOfMinimumDistance = thisTrack[i].LastSeen; usedIndex = i; } } // if the closest point is the first or the last element, we assume it's more than that, and leave the fields empty if (usedIndex == 0 || usedIndex == thisTrack.Count - 1) { retList.Add(new ShipRelativePosition(self, other, distance, direction, AisSafetyState.FarAway, now) { RelativeDirection = relativeDirection, ClosestPointOfApproach = null, TimeOfClosestPointOfApproach = null, }); } else { var pos = new ShipRelativePosition(self, other, distance, direction, state, now) { RelativeDirection = relativeDirection, // Todo: Should subtract the size of both ships here (ideally considering the direction of the ships hulls) ClosestPointOfApproach = minimumDistance, TimeOfClosestPointOfApproach = timeOfMinimumDistance, }; var timeToClosest = pos.TimeToClosestPointOfApproach(now); if (pos.ClosestPointOfApproach < parameters.WarningDistance && timeToClosest > -TimeSpan.FromMinutes(1) && timeToClosest < parameters.WarningTime) { pos.SafetyState = AisSafetyState.Dangerous; } retList.Add(pos); } } } return retList; } /// <summary> /// Estimates where a ship will be after some time. /// </summary> /// <param name="ship">The ship to extrapolate</param> /// <param name="extrapolationTime">How much time shall pass. Very large values are probably useless, because the ship might start a turn.</param> /// <param name="stepSize">The extrapolation step size. Smaller values will lead to better estimation, but are computationally expensive</param> /// <returns>A <see cref="Ship"/> instance with the estimated position and course</returns> /// <exception cref="ArgumentOutOfRangeException">Stepsize is not positive</exception> /// <remarks>The reference time is the position/time the last report was received from this ship. To be able to compare two ships, the /// times still need to be aligned. Use the overload <see cref="EstimatePosition(Iot.Device.Nmea0183.Ais.MovingTarget,System.DateTimeOffset,System.TimeSpan)"/> if you /// want to estimate the ship position at a certain position in time.</remarks> public static MovingTarget EstimatePosition(this MovingTarget ship, TimeSpan extrapolationTime, TimeSpan stepSize) { if (stepSize <= TimeSpan.FromMilliseconds(1)) { throw new ArgumentOutOfRangeException(nameof(stepSize), "Step size must be positive and greater than 1ms"); } if (extrapolationTime.Duration() < stepSize) { stepSize = extrapolationTime.Duration(); // one step only } DateTimeOffset currentTime = ship.LastSeen; MovingTarget newShip = ship with { Position = new GeographicPosition(ship.Position), IsEstimate = true }; Angle cogChange; if (ship.RateOfTurn.HasValue && Math.Abs(ship.RateOfTurn.Value.DegreesPerMinute) > 1) { var rot = ship.RateOfTurn.Value; cogChange = rot * stepSize; } else { // No turn indication -> Calculate directly Length distance = extrapolationTime * newShip.SpeedOverGround; newShip.Position = GreatCircle.CalcCoords(newShip.Position, newShip.CourseOverGround, distance); newShip.LastSeen = currentTime + extrapolationTime; return newShip; } // Differentiate between moving forward and backward in time. Note that stepSize is expected // to be positive in either case if (extrapolationTime > TimeSpan.Zero) { while (currentTime < ship.LastSeen + extrapolationTime) { currentTime += stepSize; newShip.CourseOverGround = (newShip.CourseOverGround + cogChange).Normalize(true); Length distanceDuringStep = stepSize * newShip.SpeedOverGround; newShip.Position = GreatCircle.CalcCoords(newShip.Position, newShip.CourseOverGround, distanceDuringStep); newShip.LastSeen = currentTime; } } else { while (currentTime > ship.LastSeen + extrapolationTime) // extrapolationTime is negative here { currentTime -= stepSize; Length distanceDuringStep = -(stepSize * newShip.SpeedOverGround); newShip.Position = GreatCircle.CalcCoords(newShip.Position, newShip.CourseOverGround, distanceDuringStep); // To get the closes possible inverse of the above, we correct the cog afterwards here newShip.CourseOverGround = (newShip.CourseOverGround - cogChange).Normalize(true); newShip.LastSeen = currentTime; } } return newShip; } /// <summary> /// Estimates where a ship will at a certain time. /// </summary> /// <param name="ship">The ship to extrapolate</param> /// <param name="time">The time at which the position shall be estimated. The estimate is better the closer this time is to the last position /// of the ship.</param> /// <param name="stepSize">The extrapolation step size. Smaller values will lead to better estimation, but are computationally expensive</param> /// <returns>A <see cref="Ship"/> instance with the estimated position and course</returns> /// <exception cref="ArgumentOutOfRangeException">Stepsize is not positive</exception> public static MovingTarget EstimatePosition(this MovingTarget ship, DateTimeOffset time, TimeSpan stepSize) { TimeSpan delta = ship.Age(time); return EstimatePosition(ship, delta, stepSize); } /// <summary> /// Calculate a track estimation for a ship /// </summary> /// <param name="ship">The ship to move</param> /// <param name="startTime">The time at which the track should start (may be in the past)</param> /// <param name="endTime">The time at which the track should end</param> /// <param name="stepSize">The step size of the returned track</param> /// <returns>A list of targets (for each estimated position from <paramref name="startTime"/> to <paramref name="endTime"/>).</returns> /// <exception cref="ArgumentOutOfRangeException">Stepsize is to small or negative</exception> /// <exception cref="ArgumentException">Start time is after end time</exception> /// <remarks>The calculation of this track may be expensive, when the timespan between start and end is large or stepSize is small. Or when the /// timespan is far from the time the ship was last seen.</remarks> public static List<MovingTarget> GetEstimatedTrack(this MovingTarget ship, DateTimeOffset startTime, DateTimeOffset endTime, TimeSpan stepSize) { if (stepSize <= TimeSpan.FromMilliseconds(1)) { throw new ArgumentOutOfRangeException(nameof(stepSize), "Step size must be positive and greater than 1ms"); } if (startTime >= endTime) { throw new ArgumentException("startTime must be before endTime"); } List<MovingTarget> track = new List<MovingTarget>(); DateTimeOffset currentTime = startTime; var ship1 = EstimatePosition(ship, currentTime, stepSize); track.Add(ship1); while (currentTime < endTime) { currentTime += stepSize; ship1 = ship1.EstimatePosition(stepSize, stepSize); // One step ahead track.Add(ship1); } return track; } } }
412
0.933272
1
0.933272
game-dev
MEDIA
0.35619
game-dev
0.943951
1
0.943951
philkr/pystk
2,350
src/physics/stk_dynamics_world.hpp
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2011-2015 Joerg Henrichs // // 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_STK_DYNAMICS_WORLD_HPP #define HEADER_STK_DYNAMICS_WORLD_HPP #include "btBulletDynamicsCommon.h" /** A thin wrapper around bullet's btDiscreteDynamicsWorld. Used to * be able to query and set the 'left over' time from a previous * time step, which is needed for more precise rewind/replays. */ class STKDynamicsWorld : public btDiscreteDynamicsWorld { public: /** The standard constructor which just created a btDiscreteDynamicsWorld. */ STKDynamicsWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration) : btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration) { } /** Resets m_localTime to 0. This allows more precise replay of * physics, which is important for replaying histories. */ void resetLocalTime() { m_localTime = 0; } // ------------------------------------------------------------------------ /** Sets the local time to a specified value. Used in rewinding. */ void setLocalTime(float t) { m_localTime = t; } // ------------------------------------------------------------------------ /** Gets the local time. */ float getLocalTime() const { return m_localTime; } }; // STKDynamicsWorld #endif /* EOF */
412
0.633186
1
0.633186
game-dev
MEDIA
0.659035
game-dev
0.59042
1
0.59042
files-community/Files
3,664
src/Files.App/Data/Items/DetailsLayoutColumnItem.cs
// Copyright (c) Files Community // Licensed under the MIT License. using Microsoft.UI.Xaml; namespace Files.App.Data.Items { /// <summary> /// Represents item for a column shown in <see cref="DetailsLayoutPage"/>. /// </summary> public sealed partial class DetailsLayoutColumnItem : ObservableObject { private const int GRID_SPLITTER_WIDTH = 12; public double UserLengthPixels { get => UserLength.Value; set => UserLength = new GridLength(value, GridUnitType.Pixel); } private double _NormalMaxLength = 800; [RegistryIgnore] public double NormalMaxLength { get => _NormalMaxLength; set => SetProperty(ref _NormalMaxLength, value); } private bool _UserCollapsed; public bool UserCollapsed { get => _UserCollapsed; set { if (SetProperty(ref _UserCollapsed, value)) UpdateVisibility(); } } [RegistryIgnore] public bool IsResizable { get; set; } = true; public double MinLength => UserCollapsed || IsHidden ? 0 : NormalMinLength; public Visibility Visibility => UserCollapsed || IsHidden ? Visibility.Collapsed : Visibility.Visible; public GridLength Length => UserCollapsed || IsHidden ? new GridLength(0) : UserLength; public GridLength LengthIncludingGridSplitter => UserCollapsed || IsHidden ? new(0) : new(UserLength.Value + (IsResizable ? GRID_SPLITTER_WIDTH : 0)); public double MaxLength => UserCollapsed || IsHidden ? 0 : NormalMaxLength; private bool _IsHidden; public bool IsHidden { get => _IsHidden; set => SetProperty(ref _IsHidden, value); } private double _NormalMinLength = 50; [RegistryIgnore] public double NormalMinLength { get => _NormalMinLength; set { if (SetProperty(ref _NormalMinLength, value)) OnPropertyChanged(nameof(MinLength)); } } private GridLength _UserLength = new(200, GridUnitType.Pixel); [RegistryIgnore] public GridLength UserLength { get => _UserLength; set { if (SetProperty(ref _UserLength, value)) { OnPropertyChanged(nameof(Length)); OnPropertyChanged(nameof(LengthIncludingGridSplitter)); } } } public void Hide() { IsHidden = true; UpdateVisibility(); } public void Show() { IsHidden = false; UpdateVisibility(); } private void UpdateVisibility() { OnPropertyChanged(nameof(Length)); OnPropertyChanged(nameof(LengthIncludingGridSplitter)); OnPropertyChanged(nameof(MaxLength)); OnPropertyChanged(nameof(Visibility)); OnPropertyChanged(nameof(MinLength)); } public override bool Equals(object? obj) { if (obj is null) return false; if (obj == this) return true; if (obj is DetailsLayoutColumnItem model) { return model.UserCollapsed == UserCollapsed && model.Length.Value == Length.Value && model.LengthIncludingGridSplitter.Value == LengthIncludingGridSplitter.Value && model.UserLength.Value == UserLength.Value; } return base.Equals(obj); } public override int GetHashCode() { var hashCode = UserCollapsed.GetHashCode(); hashCode = (hashCode * 397) ^ Length.Value.GetHashCode(); hashCode = (hashCode * 397) ^ LengthIncludingGridSplitter.Value.GetHashCode(); hashCode = (hashCode * 397) ^ UserLength.Value.GetHashCode(); return hashCode; } public void Update(DetailsLayoutColumnItem other) { UserLengthPixels = other.UserLengthPixels; NormalMaxLength = other.NormalMaxLength; UserCollapsed = other.UserCollapsed; IsResizable = other.IsResizable; IsHidden = other.IsHidden; NormalMinLength = other.NormalMinLength; UserLength = other.UserLength; } } }
412
0.919173
1
0.919173
game-dev
MEDIA
0.50234
game-dev
0.94434
1
0.94434
DarkstarProject/darkstar
1,112
scripts/globals/mobskills/cross_reaver.lua
--------------------------------------------- -- Cross Reaver -- -- Description: Deals high damage to players in a fan-shaped area. Additional effect: Stun -- Type: Physical -- ? ? ? (No data offered) -- Range: Melee -- Special weaponskill unique to Ark Angel HM. Deals ~500-900 damage. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) -- TODO: Can skillchain? Unknown property. local numhits = 2 local accmod = 1 local dmgmod = 4 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,MOBPARAM_2_SHADOW) MobPhysicalStatusEffectMove(mob, target, skill, dsp.effect.STUN, 1, 0, 4) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING) return dmg end
412
0.763975
1
0.763975
game-dev
MEDIA
0.974981
game-dev
0.55971
1
0.55971
googlecreativelab/balloon-pop
2,528
Assets/Scripts/BalloonPop/PelletShot.cs
//----------------------------------------------------------------------- // <copyright file="PelletShot.cs" company="Google"> // // Copyright 2022 Google Inc. All Rights Reserved. // // 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. // // </copyright> //----------------------------------------------------------------------- namespace Google.CreativeLab.BalloonPop { using UnityEngine; [RequireComponent(typeof (Rigidbody))] [RequireComponent(typeof (SphereCollider))] public class PelletShot : MonoBehaviour { private Rigidbody _rigidBody = null; private SphereCollider _sphereCollider = null; // private bool _isAirborne = false; private float _speed = 0; /// <summary> /// Start is called before the first frame update /// </summary> void Start() { _sphereCollider = GetComponent<SphereCollider>(); _rigidBody = GetComponent<Rigidbody>(); _rigidBody.useGravity = true; _rigidBody.drag = 1f; _rigidBody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; _sphereCollider.radius = transform.localScale.x * 3.8f; } /// <summary> /// Remove any forces from the Pellet's Rigidbody /// </summary> public void removeAllForces() { if (_rigidBody == null) return; _rigidBody.velocity = Vector3.zero; } /// <summary> /// Perform a shot with the provided speedPercent at the Pellet's current rotation /// </summary> /// <param name="speedPercent">A speed to perform the pellet shot with</param> public void ShootWithSpeedAtCurrentRotation(float speedPercent) { if (_rigidBody == null) return; // _isAirborne = true; _speed = 50f * speedPercent; Vector3 force = transform.forward * _speed; _rigidBody.AddForce(force, ForceMode.Impulse); } } }
412
0.593601
1
0.593601
game-dev
MEDIA
0.940068
game-dev
0.620822
1
0.620822
ratrecommends/dice-heroes
3,779
main/src/com/vlaaad/dice/ui/scene2d/LocLabel.java
/* * Dice heroes is a turn based rpg-strategy game where characters are dice. * Copyright (C) 2016 Vladislav Protsenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vlaaad.dice.ui.scene2d; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.utils.ObjectMap; import com.vlaaad.dice.Config; import com.vlaaad.dice.game.config.thesaurus.Localizable; import com.vlaaad.dice.game.config.thesaurus.Thesaurus; /** * Created 05.11.13 by vlaaad */ public class LocLabel extends Label implements Localizable { private String key; private ObjectMap<String, String> params; public LocLabel(String key) { this(key, Thesaurus.EMPTY); validate(); } public LocLabel(String key, ObjectMap<String, String> params) { super(key, Config.skin); this.key = key; this.params = params; } public LocLabel(String key, String colorName) { super(key, Config.skin, "default", colorName); this.key = key; this.params = Thesaurus.EMPTY; } public LocLabel(String key, Color color) { super(key, Config.skin, "default", color); this.key = key; this.params = Thesaurus.EMPTY; } public LocLabel(String key, ObjectMap<String, String> params, Color color) { super(key, Config.skin, "default", color); this.key = key; this.params = params; } public LocLabel(String key, ObjectMap<String, String> params, String styleName) { super(key, Config.skin, styleName); this.key = key; this.params = params; } public LocLabel(Thesaurus.LocalizationData localizationData) { this(localizationData.key, localizationData.params); } public LocLabel(Thesaurus.LocalizationData data, Color color) { this(data.key, data.params, color); } @Override public void invalidate() { super.invalidate(); } @Override public void layout() { setText(Config.thesaurus.localize(key, params)); super.layout(); } @Override protected void setStage(Stage stage) { if (stage == null && getStage() != null) { //unregister Config.thesaurus.unregister(this); } else if (stage != null && getStage() == null) { //register Config.thesaurus.register(this, key, params); } super.setStage(stage); } public void setKey(String key) { if (this.key.equals(key)) return; this.key = key; if (getStage() != null) { Config.thesaurus.register(this, key, params); } } public void setParams(ObjectMap<String, String> params) { if (this.params.equals(params)) return; this.params = params; if (getStage() != null) { Config.thesaurus.register(this, key, params); } } @Override public void localize(String localizedString) { setText(localizedString); } public ObjectMap<String, String> getParams() { return params; } }
412
0.853072
1
0.853072
game-dev
MEDIA
0.46098
game-dev,desktop-app
0.739812
1
0.739812
cliqz-oss/browser-f
8,864
mozilla-release/gfx/thebes/gfxSkipChars.h
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GFX_SKIP_CHARS_H #define GFX_SKIP_CHARS_H #include "nsTArray.h" /* * gfxSkipChars is a data structure representing a list of characters that * have been skipped. The initial string is called the "original string" * and after skipping some characters, the result is called the "skipped * string". gfxSkipChars provides efficient ways to translate between offsets in * the original string and the skipped string. It is used by textrun code to * keep track of offsets before and after text transformations such as * whitespace compression and control code deletion. */ /** * The gfxSkipChars is represented as a sorted array of skipped ranges. * * A freshly-created gfxSkipChars means "all chars kept". */ class gfxSkipChars { friend struct SkippedRangeStartComparator; friend struct SkippedRangeOffsetComparator; private: class SkippedRange { public: SkippedRange(uint32_t aOffset, uint32_t aLength, uint32_t aDelta) : mOffset(aOffset), mLength(aLength), mDelta(aDelta) {} uint32_t Start() const { return mOffset; } uint32_t End() const { return mOffset + mLength; } uint32_t Length() const { return mLength; } uint32_t SkippedOffset() const { return mOffset - mDelta; } uint32_t Delta() const { return mDelta; } uint32_t NextDelta() const { return mDelta + mLength; } void Extend(uint32_t aChars) { mLength += aChars; } private: uint32_t mOffset; // original-string offset at which we want to skip uint32_t mLength; // number of skipped chars at this offset uint32_t mDelta; // sum of lengths of preceding skipped-ranges }; public: gfxSkipChars() : mCharCount(0) {} void SkipChars(uint32_t aChars) { NS_ASSERTION(mCharCount + aChars > mCharCount, "Character count overflow"); uint32_t rangeCount = mRanges.Length(); uint32_t delta = 0; if (rangeCount > 0) { SkippedRange& lastRange = mRanges[rangeCount - 1]; if (lastRange.End() == mCharCount) { lastRange.Extend(aChars); mCharCount += aChars; return; } delta = lastRange.NextDelta(); } mRanges.AppendElement(SkippedRange(mCharCount, aChars, delta)); mCharCount += aChars; } void KeepChars(uint32_t aChars) { NS_ASSERTION(mCharCount + aChars > mCharCount, "Character count overflow"); mCharCount += aChars; } void SkipChar() { SkipChars(1); } void KeepChar() { KeepChars(1); } void TakeFrom(gfxSkipChars* aSkipChars) { mRanges.SwapElements(aSkipChars->mRanges); mCharCount = aSkipChars->mCharCount; aSkipChars->mCharCount = 0; } int32_t GetOriginalCharCount() const { return mCharCount; } const SkippedRange& LastRange() const { // this is only valid if mRanges is non-empty; no assertion here // because nsTArray will already assert if we abuse it return mRanges[mRanges.Length() - 1]; } friend class gfxSkipCharsIterator; private: nsTArray<SkippedRange> mRanges; uint32_t mCharCount; }; /** * A gfxSkipCharsIterator represents a position in the original string. It lets * you map efficiently to and from positions in the string after skipped * characters have been removed. You can also specify an offset that is added to * all incoming original string offsets and subtracted from all outgoing * original string offsets --- useful when the gfxSkipChars corresponds to * something offset from the original DOM coordinates, which it often does for * gfxTextRuns. * * The current positions (in both the original and skipped strings) are * always constrained to be >= 0 and <= the string length. When the position * is equal to the string length, it is at the end of the string. The current * positions do not include any aOriginalStringToSkipCharsOffset. * * When the position in the original string corresponds to a skipped character, * the skipped-characters offset is the offset of the next unskipped character, * or the skipped-characters string length if there is no next unskipped * character. */ class gfxSkipCharsIterator { public: /** * @param aOriginalStringToSkipCharsOffset add this to all incoming and * outgoing original string offsets */ gfxSkipCharsIterator(const gfxSkipChars& aSkipChars, int32_t aOriginalStringToSkipCharsOffset, int32_t aOriginalStringOffset) : mSkipChars(&aSkipChars), mOriginalStringOffset(0), mSkippedStringOffset(0), mCurrentRangeIndex(-1), mOriginalStringToSkipCharsOffset(aOriginalStringToSkipCharsOffset) { SetOriginalOffset(aOriginalStringOffset); } explicit gfxSkipCharsIterator(const gfxSkipChars& aSkipChars, int32_t aOriginalStringToSkipCharsOffset = 0) : mSkipChars(&aSkipChars), mOriginalStringOffset(0), mSkippedStringOffset(0), mOriginalStringToSkipCharsOffset(aOriginalStringToSkipCharsOffset) { mCurrentRangeIndex = mSkipChars->mRanges.IsEmpty() || mSkipChars->mRanges[0].Start() > 0 ? -1 : 0; } gfxSkipCharsIterator(const gfxSkipCharsIterator& aIterator) = default; /** * The empty constructor creates an object that is useless until it is * assigned. */ gfxSkipCharsIterator() : mSkipChars(nullptr), mOriginalStringOffset(0), mSkippedStringOffset(0), mCurrentRangeIndex(0), mOriginalStringToSkipCharsOffset(0) {} /** * Return true if this iterator is properly initialized and usable. */ bool IsInitialized() const { return mSkipChars != nullptr; } /** * Set the iterator to aOriginalStringOffset in the original string. * This can efficiently move forward or backward from the current position. * aOriginalStringOffset is clamped to [0,originalStringLength]. */ void SetOriginalOffset(int32_t aOriginalStringOffset); /** * Set the iterator to aSkippedStringOffset in the skipped string. * This can efficiently move forward or backward from the current position. * aSkippedStringOffset is clamped to [0,skippedStringLength]. */ void SetSkippedOffset(uint32_t aSkippedStringOffset); uint32_t ConvertOriginalToSkipped(int32_t aOriginalStringOffset) { SetOriginalOffset(aOriginalStringOffset); return GetSkippedOffset(); } int32_t ConvertSkippedToOriginal(uint32_t aSkippedStringOffset) { SetSkippedOffset(aSkippedStringOffset); return GetOriginalOffset(); } /** * Test if the character at the current position in the original string * is skipped or not. If aRunLength is non-null, then *aRunLength is set * to a number of characters all of which are either skipped or not, starting * at this character. When the current position is at the end of the original * string, we return true and *aRunLength is set to zero. */ bool IsOriginalCharSkipped(int32_t* aRunLength = nullptr) const; void AdvanceOriginal(int32_t aDelta) { SetOriginalOffset(GetOriginalOffset() + aDelta); } void AdvanceSkipped(int32_t aDelta) { SetSkippedOffset(GetSkippedOffset() + aDelta); } /** * @return the offset within the original string */ int32_t GetOriginalOffset() const { return mOriginalStringOffset - mOriginalStringToSkipCharsOffset; } /** * @return the offset within the skipped string corresponding to the * current position in the original string. If the current position * in the original string is a character that is skipped, then we return * the position corresponding to the first non-skipped character in the * original string after the current position, or the length of the skipped * string if there is no such character. */ uint32_t GetSkippedOffset() const { return mSkippedStringOffset; } int32_t GetOriginalEnd() const { return mSkipChars->GetOriginalCharCount() - mOriginalStringToSkipCharsOffset; } private: const gfxSkipChars* mSkipChars; // Current position int32_t mOriginalStringOffset; uint32_t mSkippedStringOffset; // Index of the last skippedRange that precedes or contains the current // position in the original string. // If index == -1 then we are before the first skipped char. int32_t mCurrentRangeIndex; // This offset is added to map from "skipped+unskipped characters in // the original DOM string" character space to "skipped+unskipped // characters in the textrun's gfxSkipChars" character space int32_t mOriginalStringToSkipCharsOffset; }; #endif /*GFX_SKIP_CHARS_H*/
412
0.938055
1
0.938055
game-dev
MEDIA
0.232324
game-dev
0.773545
1
0.773545
efroemling/ballistica
1,510
src/external/open_dynamics_engine-ef/ode/IceAxes.h
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains axes definition. * \file IceAxes.h * \author Pierre Terdiman * \date January, 29, 2000 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Include Guard #ifndef __ICEAXES_H__ #define __ICEAXES_H__ // ericf added #ifdef _X #undef _X #endif enum PointComponent { _X = 0, _Y = 1, _Z = 2, _W = 3, _FORCE_DWORD = 0x7fffffff }; enum AxisOrder { AXES_XYZ = (_X)|(_Y<<2)|(_Z<<4), AXES_XZY = (_X)|(_Z<<2)|(_Y<<4), AXES_YXZ = (_Y)|(_X<<2)|(_Z<<4), AXES_YZX = (_Y)|(_Z<<2)|(_X<<4), AXES_ZXY = (_Z)|(_X<<2)|(_Y<<4), AXES_ZYX = (_Z)|(_Y<<2)|(_X<<4), AXES_FORCE_DWORD = 0x7fffffff }; class ICEMATHS_API Axes { public: inline_ Axes(AxisOrder order) { mAxis0 = (order ) & 3; mAxis1 = (order>>2) & 3; mAxis2 = (order>>4) & 3; } inline_ ~Axes() {} udword mAxis0; udword mAxis1; udword mAxis2; }; #endif // __ICEAXES_H__
412
0.588967
1
0.588967
game-dev
MEDIA
0.543888
game-dev
0.573874
1
0.573874
LittleEndianLtd/SpectrumWorx
18,696
3rd_party/JUCE/trunk/extras/Introjucer/Source/Project/jucer_ModulesPanel.h
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #ifndef __JUCER_MODULESPANEL_JUCEHEADER__ #define __JUCER_MODULESPANEL_JUCEHEADER__ class ModulesPanel : public PropertyComponent, public FilenameComponentListener, public ButtonListener { public: ModulesPanel (Project& p) : PropertyComponent ("Modules", 500), project (p), modulesLocation ("modules", ModuleList::getLocalModulesFolder (&project), true, true, false, "*", String::empty, "Select a folder containing your JUCE modules..."), modulesLabel (String::empty, "Module source folder:"), updateModulesButton ("Check for module updates..."), moduleListBox (moduleList), copyingMessage (p, moduleList) { moduleList.rescan (ModuleList::getLocalModulesFolder (&project)); addAndMakeVisible (&modulesLocation); modulesLocation.addListener (this); modulesLabel.attachToComponent (&modulesLocation, true); addAndMakeVisible (&updateModulesButton); updateModulesButton.addListener (this); moduleListBox.setOwner (this); addAndMakeVisible (&moduleListBox); addAndMakeVisible (&copyingMessage); copyingMessage.refresh(); } void filenameComponentChanged (FilenameComponent*) { moduleList.rescan (modulesLocation.getCurrentFile()); modulesLocation.setCurrentFile (moduleList.getModulesFolder(), false, dontSendNotification); ModuleList::setLocalModulesFolder (moduleList.getModulesFolder()); moduleListBox.refresh(); } void buttonClicked (Button*) { JuceUpdater::show (moduleList, getTopLevelComponent(), ""); filenameComponentChanged (nullptr); } bool isEnabled (const ModuleList::Module* m) const { return project.isModuleEnabled (m->uid); } void setEnabled (const ModuleList::Module* m, bool enable) { if (enable) project.addModule (m->uid, true); else project.removeModule (m->uid); refresh(); } bool areDependenciesMissing (const ModuleList::Module* m) { return moduleList.getExtraDependenciesNeeded (project, *m).size() > 0; } void selectionChanged (const ModuleList::Module* selectedModule) { settings = nullptr; if (selectedModule != nullptr) addAndMakeVisible (settings = new ModuleSettingsPanel (project, moduleList, selectedModule->uid)); copyingMessage.refresh(); resized(); } void refresh() { moduleListBox.refresh(); if (settings != nullptr) settings->refreshAll(); copyingMessage.refresh(); } void paint (Graphics& g) // (overridden to avoid drawing the name) { getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this); } void resized() { modulesLocation.setBounds (150, 3, getWidth() - 180 - 150, 25); updateModulesButton.setBounds (modulesLocation.getRight() + 6, 3, getWidth() - modulesLocation.getRight() - 12, 25); moduleListBox.setBounds (5, 34, getWidth() / 3, getHeight() - 72); copyingMessage.setBounds (5, moduleListBox.getBottom() + 2, getWidth() - 10, getHeight() - moduleListBox.getBottom() - 4); if (settings != nullptr) settings->setBounds (moduleListBox.getRight() + 5, moduleListBox.getY(), getWidth() - moduleListBox.getRight() - 9, moduleListBox.getHeight()); } //============================================================================== class ModuleSelectionListBox : public ListBox, public ListBoxModel { public: ModuleSelectionListBox (ModuleList& ml) : list (ml), owner (nullptr) { setColour (ListBox::backgroundColourId, Colours::white.withAlpha (0.4f)); setTooltip ("Use this list to select which modules should be included in your app.\n" "Any modules which have missing dependencies will be shown in red."); } void setOwner (ModulesPanel* newOwner) { owner = newOwner; setModel (this); } void refresh() { updateContent(); repaint(); } int getNumRows() { return list.modules.size(); } void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected) { if (rowIsSelected) g.fillAll (findColour (TextEditor::highlightColourId)); if (const ModuleList::Module* const m = list.modules [rowNumber]) { const float tickSize = height * 0.7f; getLookAndFeel().drawTickBox (g, *this, (height - tickSize) / 2, (height - tickSize) / 2, tickSize, tickSize, owner->isEnabled (m), true, false, false); if (owner->isEnabled (m) && owner->areDependenciesMissing (m)) g.setColour (Colours::red); else g.setColour (Colours::black); g.setFont (Font (height * 0.7f, Font::bold)); g.drawFittedText (m->uid, height, 0, width - height, height, Justification::centredLeft, 1); } } void listBoxItemClicked (int row, const MouseEvent& e) { if (e.x < getRowHeight()) flipRow (row); } void listBoxItemDoubleClicked (int row, const MouseEvent&) { flipRow (row); } void returnKeyPressed (int row) { flipRow (row); } void selectedRowsChanged (int row) { owner->selectionChanged (list.modules [row]); } void flipRow (int row) { if (const ModuleList::Module* const m = list.modules [row]) owner->setEnabled (m, ! owner->isEnabled (m)); } private: ModuleList& list; ModulesPanel* owner; }; //============================================================================== class ModuleSettingsPanel : public PropertyPanel { public: ModuleSettingsPanel (Project& p, ModuleList& list, const String& modID) : project (p), moduleList (list), moduleID (modID) { refreshAll(); } void refreshAll() { setEnabled (project.isModuleEnabled (moduleID)); clear(); PropertyListBuilder props; ScopedPointer<LibraryModule> module (moduleList.loadModule (moduleID)); if (module != nullptr) { props.add (new ModuleInfoComponent (moduleList, moduleID)); if (project.isModuleEnabled (moduleID)) { if (const ModuleList::Module* m = moduleList.findModuleInfo (moduleID)) if (moduleList.getExtraDependenciesNeeded (project, *m).size() > 0) props.add (new MissingDependenciesComponent (project, moduleList, moduleID)); } props.add (new BooleanPropertyComponent (project.shouldShowAllModuleFilesInProject (moduleID), "Add source to project", "Make module files browsable in projects"), "If this is enabled, then the entire source tree from this module will be shown inside your project, " "making it easy to browse/edit the module's classes. If disabled, then only the minimum number of files " "required to compile it will appear inside your project."); props.add (new BooleanPropertyComponent (project.shouldCopyModuleFilesLocally (moduleID), "Create local copy", "Copy the module into the project folder"), "If this is enabled, then a local copy of the entire module will be made inside your project (in the auto-generated JuceLibraryFiles folder), " "so that your project will be self-contained, and won't need to contain any references to files in other folders. " "This also means that you can check the module into your source-control system to make sure it is always in sync with your own code."); StringArray possibleValues; possibleValues.add ("(Use Default)"); possibleValues.add ("Enabled"); possibleValues.add ("Disabled"); Array<var> mappings; mappings.add (Project::configFlagDefault); mappings.add (Project::configFlagEnabled); mappings.add (Project::configFlagDisabled); OwnedArray <Project::ConfigFlag> configFlags; module->getConfigFlags (project, configFlags); for (int i = 0; i < configFlags.size(); ++i) { ChoicePropertyComponent* c = new ChoicePropertyComponent (configFlags[i]->value, configFlags[i]->symbol, possibleValues, mappings); c->setTooltip (configFlags[i]->description); props.add (c); } } addProperties (props.components); } private: Project& project; ModuleList& moduleList; String moduleID; //============================================================================== class ModuleInfoComponent : public PropertyComponent { public: ModuleInfoComponent (ModuleList& list, const String& modID) : PropertyComponent ("Module", 100), moduleList (list), moduleID (modID) { } void refresh() {} void paint (Graphics& g) { g.setColour (Colours::white.withAlpha (0.4f)); g.fillRect (0, 0, getWidth(), getHeight() - 1); if (const ModuleList::Module* module = moduleList.findModuleInfo (moduleID)) { AttributedString s; s.setJustification (Justification::topLeft); Font f (13.0f); s.append (module->name + "\n", f.boldened()); s.append ("Version: " + module->version + " License: " + module->license + "\n", f.italicised()); s.append ("\n" + module->description, f); s.draw (g, getLocalBounds().reduced (4, 2).toFloat()); } } private: ModuleList& moduleList; String moduleID; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleInfoComponent) }; //============================================================================== class MissingDependenciesComponent : public PropertyComponent, public ButtonListener { public: MissingDependenciesComponent (Project& p, ModuleList& list, const String& modID) : PropertyComponent ("Dependencies", 100), project (p), moduleList (list), moduleID (modID), fixButton ("Enable Required Modules") { if (const ModuleList::Module* module = moduleList.findModuleInfo (moduleID)) missingDependencies = moduleList.getExtraDependenciesNeeded (project, *module); addAndMakeVisible (&fixButton); fixButton.setColour (TextButton::buttonColourId, Colours::red); fixButton.setColour (TextButton::textColourOffId, Colours::white); fixButton.addListener (this); } void refresh() {} void paint (Graphics& g) { g.setColour (Colours::white.withAlpha (0.4f)); g.fillRect (0, 0, getWidth(), getHeight() - 1); String text ("This module requires the following dependencies:\n"); text << missingDependencies.joinIntoString (", "); AttributedString s; s.setJustification (Justification::topLeft); s.append (text, Font (13.0f), Colours::red); s.draw (g, getLocalBounds().reduced (4, 16).toFloat()); } void buttonClicked (Button*) { bool isModuleCopiedLocally = project.shouldCopyModuleFilesLocally (moduleID).getValue(); for (int i = missingDependencies.size(); --i >= 0;) project.addModule (missingDependencies[i], isModuleCopiedLocally); if (ModulesPanel* mp = findParentComponentOfClass<ModulesPanel>()) mp->refresh(); } void resized() { fixButton.setBounds (getWidth() - 168, getHeight() - 26, 160, 22); } private: Project& project; ModuleList& moduleList; String moduleID; StringArray missingDependencies; TextButton fixButton; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingDependenciesComponent) }; }; //============================================================================== class ModuleCopyingInfo : public Component, public ButtonListener, public Timer { public: ModuleCopyingInfo (Project& p, ModuleList& modules) : project (p), list (modules), copyModeButton ("Set Copying Mode...") { addAndMakeVisible (&copyModeButton); copyModeButton.addListener (this); startTimer (1500); } void paint (Graphics& g) { g.setFont (11.0f); g.setColour (Colours::darkred); g.drawFittedText (getName(), copyModeButton.getRight() + 10, 0, getWidth() - copyModeButton.getRight() - 16, getHeight(), Justification::centredRight, 4); } void resized() { copyModeButton.setBounds (0, getHeight() / 2 - 10, 160, 20); } void refresh() { int numCopied, numNonCopied; countCopiedModules (numCopied, numNonCopied); String newName; if (numCopied > 0 && numNonCopied > 0) newName = "Warning! Some of your modules are set to use local copies, and others are using remote references.\n" "This may create problems if some modules expect to share the same parent folder, so you may " "want to make sure that they are all either copied or not."; if (project.isAudioPluginModuleMissing()) newName = "Warning! Your project is an audio plugin, but you haven't enabled the 'juce_audio_plugin_client' module!"; if (newName != getName()) { setName (newName); repaint(); } } void countCopiedModules (int& numCopied, int& numNonCopied) { numCopied = numNonCopied = 0; for (int i = list.modules.size(); --i >= 0;) { const String moduleID (list.modules.getUnchecked(i)->uid); if (project.isModuleEnabled (moduleID)) { if (project.shouldCopyModuleFilesLocally (moduleID).getValue()) ++numCopied; else ++numNonCopied; } } } void buttonClicked (Button*) { PopupMenu menu; menu.addItem (1, "Enable local copying for all modules"); menu.addItem (2, "Disable local copying for all modules"); menu.showMenuAsync (PopupMenu::Options().withTargetComponent (&copyModeButton), ModalCallbackFunction::forComponent (copyMenuItemChosen, this)); } static void copyMenuItemChosen (int resultCode, ModuleCopyingInfo* comp) { if (resultCode > 0 && comp != nullptr) comp->setCopyModeForAllModules (resultCode == 1); } void setCopyModeForAllModules (bool copyEnabled) { for (int i = list.modules.size(); --i >= 0;) { const String moduleID (list.modules.getUnchecked(i)->uid); if (project.isModuleEnabled (moduleID)) project.shouldCopyModuleFilesLocally (moduleID) = copyEnabled; } refresh(); } void timerCallback() override { refresh(); } private: Project& project; ModuleList& list; TextButton copyModeButton; }; private: Project& project; ModuleList moduleList; FilenameComponent modulesLocation; Label modulesLabel; TextButton updateModulesButton; ModuleSelectionListBox moduleListBox; ModuleCopyingInfo copyingMessage; ScopedPointer<ModuleSettingsPanel> settings; }; #endif // __JUCER_MODULESPANEL_JUCEHEADER__
412
0.925077
1
0.925077
game-dev
MEDIA
0.577897
game-dev,desktop-app
0.926841
1
0.926841