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
SirPlease/L4D2-Competitive-Rework
13,590
addons/sourcemod/scripting/sourcemod/funcommands/ice.sp
/** * vim: set ts=4 : * ============================================================================= * SourceMod Basefuncommands Plugin * Provides freeze and freezebomb functionality * * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ int g_FreezeSerial[MAXPLAYERS+1] = { 0, ... }; int g_FreezeBombSerial[MAXPLAYERS+1] = { 0, ... }; int g_FreezeTime[MAXPLAYERS+1] = { 0, ... }; int g_FreezeBombTime[MAXPLAYERS+1] = { 0, ... }; ConVar g_Cvar_FreezeDuration; ConVar g_Cvar_FreezeBombTicks; ConVar g_Cvar_FreezeBombRadius; ConVar g_Cvar_FreezeBombMode; void FreezeClient(int client, int time) { if (g_FreezeSerial[client] != 0) { UnfreezeClient(client); return; } SetEntityMoveType(client, MOVETYPE_NONE); SetEntityRenderColor(client, 0, 128, 255, 192); if (g_FreezeSound[0]) { float vec[3]; GetClientEyePosition(client, vec); EmitAmbientSound(g_FreezeSound, vec, client, SNDLEVEL_RAIDSIREN); } g_FreezeTime[client] = time; g_FreezeSerial[client] = ++ g_Serial_Gen; CreateTimer(1.0, Timer_Freeze, client | (g_Serial_Gen << 7), DEFAULT_TIMER_FLAGS); } void UnfreezeClient(int client) { g_FreezeSerial[client] = 0; g_FreezeTime[client] = 0; if (IsClientInGame(client)) { if (g_FreezeSound[0]) { float vec[3]; GetClientAbsOrigin(client, vec); vec[2] += 10; GetClientEyePosition(client, vec); EmitAmbientSound(g_FreezeSound, vec, client, SNDLEVEL_RAIDSIREN); } SetEntityMoveType(client, MOVETYPE_WALK); SetEntityRenderColor(client, 255, 255, 255, 255); } } void CreateFreezeBomb(int client) { if (g_FreezeBombSerial[client] != 0) { KillFreezeBomb(client); return; } g_FreezeBombTime[client] = g_Cvar_FreezeBombTicks.IntValue; g_FreezeBombSerial[client] = ++g_Serial_Gen; CreateTimer(1.0, Timer_FreezeBomb, client | (g_Serial_Gen << 7), DEFAULT_TIMER_FLAGS); } void KillFreezeBomb(int client) { g_FreezeBombSerial[client] = 0; g_FreezeBombTime[client] = 0; if (IsClientInGame(client)) { SetEntityRenderColor(client, 255, 255, 255, 255); } } void KillAllFreezes() { for(int i = 1; i <= MaxClients; i++) { if (g_FreezeSerial[i] != 0) { UnfreezeClient(i); } if (g_FreezeBombSerial[i] != 0) { KillFreezeBomb(i); } } } void PerformFreeze(int client, int target, int time) { FreezeClient(target, time); LogAction(client, target, "\"%L\" froze \"%L\"", client, target); } void PerformFreezeBomb(int client, int target) { if (g_FreezeBombSerial[target] != 0) { KillFreezeBomb(target); LogAction(client, target, "\"%L\" removed a FreezeBomb on \"%L\"", client, target); } else { CreateFreezeBomb(target); LogAction(client, target, "\"%L\" set a FreezeBomb on \"%L\"", client, target); } } public Action Timer_Freeze(Handle timer, any value) { int client = value & 0x7f; int serial = value >> 7; if (!IsClientInGame(client) || !IsPlayerAlive(client) || g_FreezeSerial[client] != serial) { UnfreezeClient(client); return Plugin_Stop; } if (g_FreezeTime[client] == 0) { UnfreezeClient(client); /* HintText doesn't work on Dark Messiah */ if (g_GameEngine != Engine_DarkMessiah) { PrintHintText(client, "%t", "Unfrozen"); } else { PrintCenterText(client, "%t", "Unfrozen"); } return Plugin_Stop; } if (g_GameEngine != Engine_DarkMessiah) { PrintHintText(client, "%t", "You will be unfrozen", g_FreezeTime[client]); } else { PrintCenterText(client, "%t", "You will be unfrozen", g_FreezeTime[client]); } g_FreezeTime[client]--; SetEntityMoveType(client, MOVETYPE_NONE); SetEntityRenderColor(client, 0, 128, 255, 135); float vec[3]; GetClientAbsOrigin(client, vec); vec[2] += 10; if (g_GlowSprite > -1) { TE_SetupGlowSprite(vec, g_GlowSprite, 0.95, 1.5, 50); TE_SendToAll(); } else if (g_HaloSprite > -1) { TE_SetupGlowSprite(vec, g_HaloSprite, 0.95, 1.5, 50); TE_SendToAll(); } return Plugin_Continue; } public Action Timer_FreezeBomb(Handle timer, any value) { int client = value & 0x7f; int serial = value >> 7; if (!IsClientInGame(client) || !IsPlayerAlive(client) || g_FreezeBombSerial[client] != serial) { KillFreezeBomb(client); return Plugin_Stop; } float vec[3]; GetClientEyePosition(client, vec); g_FreezeBombTime[client]--; if (g_FreezeBombTime[client] > 0) { int color; if (g_FreezeBombTime[client] > 1) { color = RoundToFloor(g_FreezeBombTime[client] * (255.0 / g_Cvar_FreezeBombTicks.FloatValue)); if (g_BeepSound[0]) { EmitAmbientSound(g_BeepSound, vec, client, SNDLEVEL_RAIDSIREN); } } else { color = 0; if (g_FinalSound[0]) { EmitAmbientSound(g_FinalSound, vec, client, SNDLEVEL_RAIDSIREN); } } SetEntityRenderColor(client, color, color, 255, 255); char name[MAX_NAME_LENGTH]; GetClientName(client, name, sizeof(name)); PrintCenterTextAll("%t", "Till Explodes", name, g_FreezeBombTime[client]); if (g_BeamSprite > -1 && g_HaloSprite > -1) { GetClientAbsOrigin(client, vec); vec[2] += 10; TE_SetupBeamRingPoint(vec, 10.0, g_Cvar_FreezeBombRadius.FloatValue / 3.0, g_BeamSprite, g_HaloSprite, 0, 15, 0.5, 5.0, 0.0, greyColor, 10, 0); TE_SendToAll(); TE_SetupBeamRingPoint(vec, 10.0, g_Cvar_FreezeBombRadius.FloatValue / 3.0, g_BeamSprite, g_HaloSprite, 0, 10, 0.6, 10.0, 0.5, whiteColor, 10, 0); TE_SendToAll(); } return Plugin_Continue; } else { if (g_ExplosionSprite > -1) { TE_SetupExplosion(vec, g_ExplosionSprite, 5.0, 1, 0, g_Cvar_FreezeBombRadius.IntValue, 5000); TE_SendToAll(); } if (g_BoomSound[0]) { EmitAmbientSound(g_BoomSound, vec, client, SNDLEVEL_RAIDSIREN); } KillFreezeBomb(client); FreezeClient(client, g_Cvar_FreezeDuration.IntValue); if (g_Cvar_FreezeBombMode.IntValue > 0) { bool teamOnly = ((g_Cvar_FreezeBombMode.IntValue == 1) ? true : false); for (int i = 1; i <= MaxClients; i++) { if (!IsClientInGame(i) || !IsPlayerAlive(i) || i == client) { continue; } if (teamOnly && GetClientTeam(i) != GetClientTeam(client)) { continue; } float pos[3]; GetClientEyePosition(i, pos); float distance = GetVectorDistance(vec, pos); if (distance > g_Cvar_FreezeBombRadius.FloatValue) { continue; } if (g_HaloSprite > -1) { if (g_BeamSprite2 > -1) { TE_SetupBeamPoints(vec, pos, g_BeamSprite2, g_HaloSprite, 0, 1, 0.7, 20.0, 50.0, 1, 1.5, blueColor, 10); TE_SendToAll(); } else if (g_BeamSprite > -1) { TE_SetupBeamPoints(vec, pos, g_BeamSprite, g_HaloSprite, 0, 1, 0.7, 20.0, 50.0, 1, 1.5, blueColor, 10); TE_SendToAll(); } } FreezeClient(i, g_Cvar_FreezeDuration.IntValue); } } return Plugin_Stop; } } public void AdminMenu_Freeze(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) { if (action == TopMenuAction_DisplayOption) { Format(buffer, maxlength, "%T", "Freeze player", param); } else if (action == TopMenuAction_SelectOption) { DisplayFreezeMenu(param); } } public void AdminMenu_FreezeBomb(TopMenu topmenu, TopMenuAction action, TopMenuObject object_id, int param, char[] buffer, int maxlength) { if (action == TopMenuAction_DisplayOption) { Format(buffer, maxlength, "%T", "FreezeBomb player", param); } else if (action == TopMenuAction_SelectOption) { DisplayFreezeBombMenu(param); } } void DisplayFreezeMenu(int client) { Menu menu = new Menu(MenuHandler_Freeze); char title[100]; Format(title, sizeof(title), "%T:", "Freeze player", client); menu.SetTitle(title); menu.ExitBackButton = true; AddTargetsToMenu(menu, client, true, true); menu.Display(client, MENU_TIME_FOREVER); } void DisplayFreezeBombMenu(int client) { Menu menu = new Menu(MenuHandler_FreezeBomb); char title[100]; Format(title, sizeof(title), "%T:", "FreezeBomb player", client); menu.SetTitle(title); menu.ExitBackButton = true; AddTargetsToMenu(menu, client, true, true); menu.Display(client, MENU_TIME_FOREVER); } public int MenuHandler_Freeze(Menu menu, MenuAction action, int param1, int param2) { if (action == MenuAction_End) { delete menu; } else if (action == MenuAction_Cancel) { if (param2 == MenuCancel_ExitBack && hTopMenu) { hTopMenu.Display(param1, TopMenuPosition_LastCategory); } } else if (action == MenuAction_Select) { char info[32]; int userid, target; menu.GetItem(param2, info, sizeof(info)); userid = StringToInt(info); if ((target = GetClientOfUserId(userid)) == 0) { PrintToChat(param1, "[SM] %t", "Player no longer available"); } else if (!CanUserTarget(param1, target)) { PrintToChat(param1, "[SM] %t", "Unable to target"); } else { char name[MAX_NAME_LENGTH]; GetClientName(target, name, sizeof(name)); PerformFreeze(param1, target, g_Cvar_FreezeDuration.IntValue); ShowActivity2(param1, "[SM] ", "%t", "Froze target", "_s", name); } /* Re-draw the menu if they're still valid */ if (IsClientInGame(param1) && !IsClientInKickQueue(param1)) { DisplayFreezeMenu(param1); } } return 0; } public int MenuHandler_FreezeBomb(Menu menu, MenuAction action, int param1, int param2) { if (action == MenuAction_End) { delete menu; } else if (action == MenuAction_Cancel) { if (param2 == MenuCancel_ExitBack && hTopMenu) { hTopMenu.Display(param1, TopMenuPosition_LastCategory); } } else if (action == MenuAction_Select) { char info[32]; int userid, target; menu.GetItem(param2, info, sizeof(info)); userid = StringToInt(info); if ((target = GetClientOfUserId(userid)) == 0) { PrintToChat(param1, "[SM] %t", "Player no longer available"); } else if (!CanUserTarget(param1, target)) { PrintToChat(param1, "[SM] %t", "Unable to target"); } else { char name[MAX_NAME_LENGTH]; GetClientName(target, name, sizeof(name)); PerformFreezeBomb(param1, target); ShowActivity2(param1, "[SM] ", "%t", "Toggled FreezeBomb on target", "_s", name); } /* Re-draw the menu if they're still valid */ if (IsClientInGame(param1) && !IsClientInKickQueue(param1)) { DisplayFreezeBombMenu(param1); } } return 0; } public Action Command_Freeze(int client, int args) { if (args < 1) { ReplyToCommand(client, "[SM] Usage: sm_freeze <#userid|name> [time]"); return Plugin_Handled; } char arg[65]; GetCmdArg(1, arg, sizeof(arg)); int seconds = g_Cvar_FreezeDuration.IntValue; if (args > 1 && !GetCmdArgIntEx(2, seconds)) { ReplyToCommand(client, "[SM] %t", "Invalid Amount"); return Plugin_Handled; } char target_name[MAX_TARGET_LENGTH]; int target_list[MAXPLAYERS], target_count; bool tn_is_ml; if ((target_count = ProcessTargetString( arg, client, target_list, MAXPLAYERS, COMMAND_FILTER_ALIVE, target_name, sizeof(target_name), tn_is_ml)) <= 0) { ReplyToTargetError(client, target_count); return Plugin_Handled; } for (int i = 0; i < target_count; i++) { PerformFreeze(client, target_list[i], seconds); } if (tn_is_ml) { ShowActivity2(client, "[SM] ", "%t", "Froze target", target_name); } else { ShowActivity2(client, "[SM] ", "%t", "Froze target", "_s", target_name); } return Plugin_Handled; } public Action Command_FreezeBomb(int client, int args) { if (args < 1) { ReplyToCommand(client, "[SM] Usage: sm_freezebomb <#userid|name>"); return Plugin_Handled; } char arg[65]; GetCmdArg(1, arg, sizeof(arg)); char target_name[MAX_TARGET_LENGTH]; int target_list[MAXPLAYERS], target_count; bool tn_is_ml; if ((target_count = ProcessTargetString( arg, client, target_list, MAXPLAYERS, COMMAND_FILTER_ALIVE, target_name, sizeof(target_name), tn_is_ml)) <= 0) { ReplyToTargetError(client, target_count); return Plugin_Handled; } for (int i = 0; i < target_count; i++) { PerformFreezeBomb(client, target_list[i]); } if (tn_is_ml) { ShowActivity2(client, "[SM] ", "%t", "Toggled FreezeBomb on target", target_name); } else { ShowActivity2(client, "[SM] ", "%t", "Toggled FreezeBomb on target", "_s", target_name); } return Plugin_Handled; }
412
0.925306
1
0.925306
game-dev
MEDIA
0.673734
game-dev
0.9371
1
0.9371
SinlessDevil/TestTaskArmageddonica
2,303
Assets/Code/UI/Game/Cards/PM/CardPM.cs
using Code.Services.StaticData; using Code.StaticData.Cards; using Code.StaticData.Cards.Definition; using Code.StaticData.Cards.Rank; using Code.StaticData.Invocation.DTO; using UnityEngine; namespace Code.UI.Game.Cards.PM { public class CardPM : ICardPM { private readonly IStaticDataService _staticDataService; public CardPM(InvocationDTO dto, IStaticDataService staticDataService) { _staticDataService = staticDataService; DTO = dto; } public InvocationDTO DTO { get; } public CardDefinitionStaticData? DefinitionData => DefinitionCollectionData.GetCardDefinitionByType(DTO.CardDefinition); public CardDefinitionType DefinitionType => DTO.CardDefinition; public string RankId => RankData?.RankText; public string CardName => DefinitionData?.Name ?? "Unknown Card"; public string CardDescription => DefinitionData?.Description ?? "No description available"; public string CardMainInfo => DTO switch { UnitDTO unitDto => $"Attack: {unitDto.Damage}, Health: {unitDto.Health}, Speed: {unitDto.Speed}", BuildDTO buildDto => $"Defence: {buildDto.Defense}, Attack: {buildDto.Damage}, Skill{buildDto.Skill.SkillType}: {buildDto.Skill?.Value ?? 0}", SkillDTO skillDto => $"Skill{skillDto.Skill.SkillType}: {skillDto.Skill?.Value ?? 0}", _ => "Unknown type" }; public Sprite CardIcon => DefinitionData?.Icon; public Color RankColor => RankData?.Color ?? Color.white; public Sprite BackgroundSprite => RankData?.BgSprite; public Sprite BodySprite => RankData?.BodySprite; public Sprite LevelBackgroundSprite => RankData?.BgLevelSprite; public string RankText => RankData?.RankText ?? DTO.Rank.ToString(); private CardRankData? RankData => RankStaticData.GetCardDataByRank(DTO.Rank); private CardRankStaticData RankStaticData => _staticDataService.Balance.CardRankStaticData; private CardDefinitionCollectionStaticData DefinitionCollectionData => _staticDataService.Balance.CardDefinitionCollectionStaticData; } }
412
0.777028
1
0.777028
game-dev
MEDIA
0.552188
game-dev
0.559248
1
0.559248
Earnestly/plan9
2,282
sys/src/libc/sparc/memmove.s
TEXT memmove(SB), $0 JMP move TEXT memcpy(SB), $0 move: /* * performance: * (tba) */ MOVW R7, s1+0(FP) MOVW n+8(FP), R9 /* R9 is count */ MOVW R7, R10 /* R10 is to-pointer */ SUBCC R0,R9, R0 BGE ok MOVW 0(R0), R0 ok: MOVW s2+4(FP), R11 /* R11 is from-pointer */ ADD R9,R11, R13 /* R13 is end from-pointer */ ADD R9,R10, R12 /* R12 is end to-pointer */ /* * easiest test is copy backwards if * destination string has higher mem address */ SUBCC R11,R10, R0 BGU back /* * if not at least 8 chars, * dont even mess around. * 7 chars to guarantee any * rounding up to a word * boundary and 8 characters * to get at least maybe one * full word store. */ SUBCC $8,R9, R0 BL fout /* * test if both pointers * are similarly word aligned */ XOR R10,R11, R7 ANDCC $7,R7, R0 BNE fout /* * byte at a time to double align */ f1: ANDCC $7,R10, R0 BE f2 MOVB 0(R11), R16 ADD $1, R11 MOVB R16, 0(R10) ADD $1, R10 JMP f1 /* * turn R9 into to-end pointer-15 * copy 16 at a time while theres room. * R12 is smaller than R13 -- * there are problems if R13 is 0. */ f2: SUB $15,R12, R9 f3: SUBCC R10,R9, R0 BLEU f4 MOVD 0(R11), R16 MOVD R16, 0(R10) MOVD 8(R11), R16 ADD $16, R11 MOVD R16, 8(R10) ADD $16, R10 JMP f3 /* * turn R9 into to-end pointer-3 * copy 4 at a time while theres room */ f4: SUB $3,R12, R9 f5: SUBCC R10,R9, R0 BLEU fout MOVW 0(R11), R16 ADD $4, R11 MOVW R16, 0(R10) ADD $4, R10 JMP f5 /* * last loop, copy byte at a time */ fout: SUBCC R11,R13, R0 BLEU ret MOVB 0(R11), R16 ADD $1, R11 MOVB R16, 0(R10) ADD $1, R10 JMP fout /* * whole thing repeated for backwards */ back: SUBCC $8,R9, R0 BL bout XOR R12,R13, R7 ANDCC $7,R7, R0 BNE bout b1: ANDCC $7,R13, R0 BE b2 MOVB -1(R13), R16 SUB $1, R13 MOVB R16, -1(R12) SUB $1, R12 JMP b1 b2: ADD $15,R11, R9 b3: SUBCC R9,R13, R0 BLEU b4 MOVD -8(R13), R16 MOVD R16, -8(R12) MOVD -16(R13), R16 SUB $16, R13 MOVD R16, -16(R12); SUB $16, R12 JMP b3 b4: ADD $3,R11, R9 b5: SUBCC R9,R13, R0 BLEU bout MOVW -4(R13), R16 SUB $4, R13 MOVW R16, -4(R12) SUB $4, R12 JMP b5 bout: SUBCC R11,R13, R0 BLEU ret MOVB -1(R13), R16 SUB $1, R13 MOVB R16, -1(R12) SUB $1, R12 JMP bout ret: MOVW s1+0(FP), R7 RETURN
412
0.698997
1
0.698997
game-dev
MEDIA
0.427268
game-dev
0.69768
1
0.69768
ImLegiitXD/Dream-Advanced
6,384
dll/back/1.12/net/minecraft/client/renderer/tileentity/TileEntitySkullRenderer.java
package net.minecraft.client.renderer.tileentity; import com.mojang.authlib.GameProfile; import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelDragonHead; import net.minecraft.client.model.ModelHumanoidHead; import net.minecraft.client.model.ModelSkeletonHead; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; public class TileEntitySkullRenderer extends TileEntitySpecialRenderer<TileEntitySkull> { private static final ResourceLocation SKELETON_TEXTURES = new ResourceLocation("textures/entity/skeleton/skeleton.png"); private static final ResourceLocation WITHER_SKELETON_TEXTURES = new ResourceLocation("textures/entity/skeleton/wither_skeleton.png"); private static final ResourceLocation ZOMBIE_TEXTURES = new ResourceLocation("textures/entity/zombie/zombie.png"); private static final ResourceLocation CREEPER_TEXTURES = new ResourceLocation("textures/entity/creeper/creeper.png"); private static final ResourceLocation DRAGON_TEXTURES = new ResourceLocation("textures/entity/enderdragon/dragon.png"); private final ModelDragonHead dragonHead = new ModelDragonHead(0.0F); public static TileEntitySkullRenderer instance; private final ModelSkeletonHead skeletonHead = new ModelSkeletonHead(0, 0, 64, 32); private final ModelSkeletonHead humanoidHead = new ModelHumanoidHead(); public void render(TileEntitySkull te, double x, double y, double z, float partialTicks, int destroyStage, float alpha) { EnumFacing enumfacing = EnumFacing.getFront(te.getBlockMetadata() & 7); float f = te.getAnimationProgress(partialTicks); this.renderSkull((float)x, (float)y, (float)z, enumfacing, (float)(te.getSkullRotation() * 360) / 16.0F, te.getSkullType(), te.getPlayerProfile(), destroyStage, f); } public void setRendererDispatcher(TileEntityRendererDispatcher rendererDispatcherIn) { super.setRendererDispatcher(rendererDispatcherIn); instance = this; } public void renderSkull(float x, float y, float z, EnumFacing facing, float rotationIn, int skullType, @Nullable GameProfile profile, int destroyStage, float animateTicks) { ModelBase modelbase = this.skeletonHead; if (destroyStage >= 0) { this.bindTexture(DESTROY_STAGES[destroyStage]); GlStateManager.matrixMode(5890); GlStateManager.pushMatrix(); GlStateManager.scale(4.0F, 2.0F, 1.0F); GlStateManager.translate(0.0625F, 0.0625F, 0.0625F); GlStateManager.matrixMode(5888); } else { switch (skullType) { case 0: default: this.bindTexture(SKELETON_TEXTURES); break; case 1: this.bindTexture(WITHER_SKELETON_TEXTURES); break; case 2: this.bindTexture(ZOMBIE_TEXTURES); modelbase = this.humanoidHead; break; case 3: modelbase = this.humanoidHead; ResourceLocation resourcelocation = DefaultPlayerSkin.getDefaultSkinLegacy(); if (profile != null) { Minecraft minecraft = Minecraft.getMinecraft(); Map<Type, MinecraftProfileTexture> map = minecraft.getSkinManager().loadSkinFromCache(profile); if (map.containsKey(Type.SKIN)) { resourcelocation = minecraft.getSkinManager().loadSkin(map.get(Type.SKIN), Type.SKIN); } else { UUID uuid = EntityPlayer.getUUID(profile); resourcelocation = DefaultPlayerSkin.getDefaultSkin(uuid); } } this.bindTexture(resourcelocation); break; case 4: this.bindTexture(CREEPER_TEXTURES); break; case 5: this.bindTexture(DRAGON_TEXTURES); modelbase = this.dragonHead; } } GlStateManager.pushMatrix(); GlStateManager.disableCull(); if (facing == EnumFacing.UP) { GlStateManager.translate(x + 0.5F, y, z + 0.5F); } else { switch (facing) { case NORTH: GlStateManager.translate(x + 0.5F, y + 0.25F, z + 0.74F); break; case SOUTH: GlStateManager.translate(x + 0.5F, y + 0.25F, z + 0.26F); rotationIn = 180.0F; break; case WEST: GlStateManager.translate(x + 0.74F, y + 0.25F, z + 0.5F); rotationIn = 270.0F; break; case EAST: default: GlStateManager.translate(x + 0.26F, y + 0.25F, z + 0.5F); rotationIn = 90.0F; } } float f = 0.0625F; GlStateManager.enableRescaleNormal(); GlStateManager.scale(-1.0F, -1.0F, 1.0F); GlStateManager.enableAlpha(); if (skullType == 3) { GlStateManager.enableBlendProfile(GlStateManager.Profile.PLAYER_SKIN); } modelbase.render((Entity)null, animateTicks, 0.0F, 0.0F, rotationIn, 0.0F, 0.0625F); GlStateManager.popMatrix(); if (destroyStage >= 0) { GlStateManager.matrixMode(5890); GlStateManager.popMatrix(); GlStateManager.matrixMode(5888); } } }
412
0.557806
1
0.557806
game-dev
MEDIA
0.924453
game-dev,graphics-rendering
0.977421
1
0.977421
xBimTeam/XbimEssentials
3,165
Xbim.Ifc4x3/SharedBldgElements/IfcStairType.cs
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool Xbim.CodeGeneration // // Changes to this file may cause incorrect behaviour and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ using Xbim.Ifc4x3.ProductExtension; using System; using System.Collections.Generic; using System.Linq; using Xbim.Common; using Xbim.Common.Exceptions; using Xbim.Ifc4x3.SharedBldgElements; //## Custom using statements //## namespace Xbim.Ifc4x3.SharedBldgElements { [ExpressType("IfcStairType", 1278)] // ReSharper disable once PartialTypeWithSinglePart public partial class @IfcStairType : IfcBuiltElementType, IInstantiableEntity, IContainsEntityReferences, IContainsIndexedReferences, IEquatable<@IfcStairType> { //internal constructor makes sure that objects are not created outside of the model/ assembly controlled area internal IfcStairType(IModel model, int label, bool activated) : base(model, label, activated) { } #region Explicit attribute fields private IfcStairTypeEnum _predefinedType; #endregion #region Explicit attribute properties [EntityAttribute(10, EntityAttributeState.Mandatory, EntityAttributeType.Enum, EntityAttributeType.None, null, null, 19)] public IfcStairTypeEnum @PredefinedType { get { if(_activated) return _predefinedType; Activate(); return _predefinedType; } set { SetValue( v => _predefinedType = v, _predefinedType, value, "PredefinedType", 10); } } #endregion #region IPersist implementation public override void Parse(int propIndex, IPropertyValue value, int[] nestedIndex) { switch (propIndex) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: base.Parse(propIndex, value, nestedIndex); return; case 9: _predefinedType = (IfcStairTypeEnum) System.Enum.Parse(typeof (IfcStairTypeEnum), value.EnumVal, true); return; default: throw new XbimParserException(string.Format("Attribute index {0} is out of range for {1}", propIndex + 1, GetType().Name.ToUpper())); } } #endregion #region Equality comparers and operators public bool Equals(@IfcStairType other) { return this == other; } #endregion #region IContainsEntityReferences IEnumerable<IPersistEntity> IContainsEntityReferences.References { get { if (@OwnerHistory != null) yield return @OwnerHistory; foreach(var entity in @HasPropertySets) yield return entity; foreach(var entity in @RepresentationMaps) yield return entity; } } #endregion #region IContainsIndexedReferences IEnumerable<IPersistEntity> IContainsIndexedReferences.IndexedReferences { get { foreach(var entity in @HasPropertySets) yield return entity; } } #endregion #region Custom code (will survive code regeneration) //## Custom code //## #endregion } }
412
0.932615
1
0.932615
game-dev
MEDIA
0.189192
game-dev
0.956538
1
0.956538
JACoders/OpenJK
108,121
codemp/game/g_active.c
/* =========================================================================== Copyright (C) 1999 - 2005, Id Software, Inc. Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2005 - 2015, ioquake3 contributors Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "g_local.h" #include "bg_saga.h" extern void Jedi_Cloak( gentity_t *self ); extern void Jedi_Decloak( gentity_t *self ); qboolean PM_SaberInTransition( int move ); qboolean PM_SaberInStart( int move ); qboolean PM_SaberInReturn( int move ); qboolean WP_SaberStyleValidForSaber( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel ); qboolean saberCheckKnockdown_DuelLoss(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other); void P_SetTwitchInfo(gclient_t *client) { client->ps.painTime = level.time; client->ps.painDirection ^= 1; } /* =============== G_DamageFeedback Called just before a snapshot is sent to the given player. Totals up all damage and generates both the playerState_t damage values to that client for pain blends and kicks, and global pain sound events for all clients. =============== */ void P_DamageFeedback( gentity_t *player ) { gclient_t *client; float count; vec3_t angles; client = player->client; if ( client->ps.pm_type == PM_DEAD || client->tempSpectate >= level.time ) { return; } // total points of damage shot at the player this frame count = client->damage_blood + client->damage_armor; if ( count == 0 ) { return; // didn't take any damage } if ( count > 255 ) { count = 255; } // send the information to the client // world damage (falling, slime, etc) uses a special code // to make the blend blob centered instead of positional if ( client->damage_fromWorld ) { client->ps.damagePitch = 255; client->ps.damageYaw = 255; client->damage_fromWorld = qfalse; } else { vectoangles( client->damage_from, angles ); client->ps.damagePitch = angles[PITCH]/360.0 * 256; client->ps.damageYaw = angles[YAW]/360.0 * 256; //cap them since we can't send negative values in here across the net if (client->ps.damagePitch < 0) { client->ps.damagePitch = 0; } if (client->ps.damageYaw < 0) { client->ps.damageYaw = 0; } } // play an appropriate pain sound if ( (level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) && !(player->s.eFlags & EF_DEAD) && (player->client->tempSpectate < level.time)) { // don't do more than two pain sounds a second // nmckenzie: also don't make him loud and whiny if he's only getting nicked. if ( level.time - client->ps.painTime < 500 || count < 10) { return; } P_SetTwitchInfo(client); player->pain_debounce_time = level.time + 700; G_AddEvent( player, EV_PAIN, player->health ); client->ps.damageEvent++; if (client->damage_armor && !client->damage_blood) { client->ps.damageType = 1; //pure shields } else if (client->damage_armor) { client->ps.damageType = 2; //shields and health } else { client->ps.damageType = 0; //pure health } } client->ps.damageCount = count; // // clear totals // client->damage_blood = 0; client->damage_armor = 0; client->damage_knockback = 0; } /* ============= P_WorldEffects Check for lava / slime contents and drowning ============= */ void P_WorldEffects( gentity_t *ent ) { qboolean envirosuit = qfalse; int waterlevel; if ( ent->client->noclip ) { ent->client->airOutTime = level.time + 12000; // don't need air return; } waterlevel = ent->waterlevel; envirosuit = ent->client->ps.powerups[PW_BATTLESUIT] > level.time; // // check for drowning // if ( waterlevel == 3 ) { // envirosuit give air if ( envirosuit ) ent->client->airOutTime = level.time + 10000; // if out of air, start drowning if ( ent->client->airOutTime < level.time) { // drown! ent->client->airOutTime += 1000; if ( ent->health > 0 && ent->client->tempSpectate < level.time ) { // take more damage the longer underwater ent->damage += 2; if (ent->damage > 15) ent->damage = 15; // play a gurp sound instead of a normal pain sound if (ent->health <= ent->damage) { G_Sound(ent, CHAN_VOICE, G_SoundIndex(/*"*drown.wav"*/"sound/player/gurp1.wav")); } else if (rand()&1) { G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp1.wav")); } else { G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp2.wav")); } // don't play a normal pain sound ent->pain_debounce_time = level.time + 200; G_Damage (ent, NULL, NULL, NULL, NULL, ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); } } } else { ent->client->airOutTime = level.time + 12000; ent->damage = 2; } // // check for sizzle damage (move to pmove?) // if ( waterlevel && (ent->watertype & (CONTENTS_LAVA|CONTENTS_SLIME)) ) { if ( ent->health > 0 && ent->client->tempSpectate < level.time && ent->pain_debounce_time <= level.time ) { if ( envirosuit ) G_AddEvent( ent, EV_POWERUP_BATTLESUIT, 0 ); else { if ( ent->watertype & CONTENTS_LAVA ) G_Damage( ent, NULL, NULL, NULL, NULL, 30*waterlevel, 0, MOD_LAVA ); if ( ent->watertype & CONTENTS_SLIME ) G_Damage( ent, NULL, NULL, NULL, NULL, 10*waterlevel, 0, MOD_SLIME ); } } } } //============================================================== extern void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ); void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) { float magnitude, my_mass; vec3_t velocity; int cont; qboolean easyBreakBrush = qtrue; if( self->client ) { VectorCopy( self->client->ps.velocity, velocity ); if( !self->mass ) { my_mass = 10; } else { my_mass = self->mass; } } else { VectorCopy( self->s.pos.trDelta, velocity ); if ( self->s.pos.trType == TR_GRAVITY ) { velocity[2] -= 0.25f * g_gravity.value; } if( !self->mass ) { my_mass = 1; } else if ( self->mass <= 10 ) { my_mass = 10; } else { my_mass = self->mass;///10; } } magnitude = VectorLength( velocity ) * my_mass / 10; /* if(pointcontents(self.absmax)==CONTENT_WATER)//FIXME: or other watertypes magnitude/=3; //water absorbs 2/3 velocity if(self.classname=="barrel"&&self.aflag)//rolling barrels are made for impacts! magnitude*=3; if(self.frozen>0&&magnitude<300&&self.flags&FL_ONGROUND&&loser==world&&self.velocity_z<-20&&self.last_onground+0.3<time) magnitude=300; */ if ( other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || ((other->flags&FL_BBRUSH)&&(other->spawnflags&8/*THIN*/)) || (other->r.svFlags&SVF_GLASS_BRUSH) ) { easyBreakBrush = qtrue; } if ( !self->client || self->client->ps.lastOnGround+300<level.time || ( self->client->ps.lastOnGround+100 < level.time && easyBreakBrush ) ) { vec3_t dir1, dir2; float force = 0, dot; if ( easyBreakBrush ) magnitude *= 2; //damage them if ( magnitude >= 100 && other->s.number < ENTITYNUM_WORLD ) { VectorCopy( velocity, dir1 ); VectorNormalize( dir1 ); if( VectorCompare( other->r.currentOrigin, vec3_origin ) ) {//a brush with no origin VectorCopy ( dir1, dir2 ); } else { VectorSubtract( other->r.currentOrigin, self->r.currentOrigin, dir2 ); VectorNormalize( dir2 ); } dot = DotProduct( dir1, dir2 ); if ( dot >= 0.2 ) { force = dot; } else { force = 0; } force *= (magnitude/50); cont = trap->PointContents( other->r.absmax, other->s.number ); if( (cont&CONTENTS_WATER) )//|| (self.classname=="barrel"&&self.aflag))//FIXME: or other watertypes { force /= 3; //water absorbs 2/3 velocity } /* if(self.frozen>0&&force>10) force=10; */ if( ( force >= 1 && other->s.number >= MAX_CLIENTS ) || force >= 10) { /* dprint("Damage other ("); dprint(loser.classname); dprint("): "); dprint(ftos(force)); dprint("\n"); */ if ( other->r.svFlags & SVF_GLASS_BRUSH ) { other->splashRadius = (float)(self->r.maxs[0] - self->r.mins[0])/4.0f; } if ( other->takedamage ) { G_Damage( other, self, self, velocity, self->r.currentOrigin, force, DAMAGE_NO_ARMOR, MOD_CRUSH);//FIXME: MOD_IMPACT } else { G_ApplyKnockback( other, dir2, force ); } } } if ( damageSelf && self->takedamage ) { //Now damage me //FIXME: more lenient falling damage, especially for when driving a vehicle if ( self->client && self->client->ps.fd.forceJumpZStart ) {//we were force-jumping if ( self->r.currentOrigin[2] >= self->client->ps.fd.forceJumpZStart ) {//we landed at same height or higher than we landed magnitude = 0; } else {//FIXME: take off some of it, at least? magnitude = (self->client->ps.fd.forceJumpZStart-self->r.currentOrigin[2])/3; } } //if(self.classname!="monster_mezzoman"&&self.netname!="spider")//Cats always land on their feet if( ( magnitude >= 100 + self->health && self->s.number >= MAX_CLIENTS && self->s.weapon != WP_SABER ) || ( magnitude >= 700 ) )//&& self.safe_time < level.time ))//health here is used to simulate structural integrity { if ( (self->s.weapon == WP_SABER) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 ) {//players and jedi take less impact damage //allow for some lenience on high falls magnitude /= 2; /* if ( self.absorb_time >= time )//crouching on impact absorbs 1/2 the damage { magnitude/=2; } */ } magnitude /= 40; magnitude = magnitude - force/2;//If damage other, subtract half of that damage off of own injury if ( magnitude >= 1 ) { //FIXME: Put in a thingtype impact sound function /* dprint("Damage self ("); dprint(self.classname); dprint("): "); dprint(ftos(magnitude)); dprint("\n"); */ /* if ( self.classname=="player_sheep "&& self.flags&FL_ONGROUND && self.velocity_z > -50 ) return; */ G_Damage( self, NULL, NULL, NULL, self->r.currentOrigin, magnitude/2, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT } } } //FIXME: slow my velocity some? // NOTENOTE We don't use lastimpact as of yet // self->lastImpact = level.time; /* if(self.flags&FL_ONGROUND) self.last_onground=time; */ } } void Client_CheckImpactBBrush( gentity_t *self, gentity_t *other ) { if ( !other || !other->inuse ) { return; } if (!self || !self->inuse || !self->client || self->client->tempSpectate >= level.time || self->client->sess.sessionTeam == TEAM_SPECTATOR) { //hmm.. let's not let spectators ram into breakables. return; } /* if (BG_InSpecialJump(self->client->ps.legsAnim)) { //don't do this either, qa says it creates "balance issues" return; } */ if ( other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || ((other->flags&FL_BBRUSH)&&(other->spawnflags&8/*THIN*/)) || ((other->flags&FL_BBRUSH)&&(other->health<=10)) || (other->r.svFlags&SVF_GLASS_BRUSH) ) {//clients only do impact damage against easy-break breakables DoImpact( self, other, qfalse ); } } /* =============== G_SetClientSound =============== */ void G_SetClientSound( gentity_t *ent ) { if (ent->client && ent->client->isHacking) { //loop hacking sound ent->client->ps.loopSound = level.snd_hack; ent->s.loopIsSoundset = qfalse; } else if (ent->client && ent->client->isMedHealed > level.time) { //loop healing sound ent->client->ps.loopSound = level.snd_medHealed; ent->s.loopIsSoundset = qfalse; } else if (ent->client && ent->client->isMedSupplied > level.time) { //loop supplying sound ent->client->ps.loopSound = level.snd_medSupplied; ent->s.loopIsSoundset = qfalse; } else if (ent->client && ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) { ent->client->ps.loopSound = level.snd_fry; ent->s.loopIsSoundset = qfalse; } else if (ent->client) { ent->client->ps.loopSound = 0; ent->s.loopIsSoundset = qfalse; } else { ent->s.loopSound = 0; ent->s.loopIsSoundset = qfalse; } } //============================================================== /* ============== ClientImpacts ============== */ void ClientImpacts( gentity_t *ent, pmove_t *pmove ) { int i, j; trace_t trace; gentity_t *other; memset( &trace, 0, sizeof( trace ) ); for (i=0 ; i<pmove->numtouch ; i++) { for (j=0 ; j<i ; j++) { if (pmove->touchents[j] == pmove->touchents[i] ) { break; } } if (j != i) { continue; // duplicated } other = &g_entities[ pmove->touchents[i] ]; if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) { ent->touch( ent, other, &trace ); } if ( !other->touch ) { continue; } other->touch( other, ent, &trace ); } } /* ============ G_TouchTriggers Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ void G_TouchTriggers( gentity_t *ent ) { int i, num; int touch[MAX_GENTITIES]; gentity_t *hit; trace_t trace; vec3_t mins, maxs; static vec3_t range = { 40, 40, 52 }; if ( !ent->client ) { return; } // dead clients don't activate triggers! if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { return; } VectorSubtract( ent->client->ps.origin, range, mins ); VectorAdd( ent->client->ps.origin, range, maxs ); num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); // can't use ent->r.absmin, because that has a one unit pad VectorAdd( ent->client->ps.origin, ent->r.mins, mins ); VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs ); for ( i=0 ; i<num ; i++ ) { hit = &g_entities[touch[i]]; if ( !hit->touch && !ent->touch ) { continue; } if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) { continue; } // ignore most entities if a spectator if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { if ( hit->s.eType != ET_TELEPORT_TRIGGER && // this is ugly but adding a new ET_? type will // most likely cause network incompatibilities hit->touch != Touch_DoorTrigger) { continue; } } // use seperate code for determining if an item is picked up // so you don't have to actually contact its bounding box if ( hit->s.eType == ET_ITEM ) { if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) { continue; } } else { if ( !trap->EntityContact( mins, maxs, (sharedEntity_t *)hit, qfalse ) ) { continue; } } memset( &trace, 0, sizeof(trace) ); if ( hit->touch ) { hit->touch (hit, ent, &trace); } if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) { ent->touch( ent, hit, &trace ); } } // if we didn't touch a jump pad this pmove frame if ( ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount ) { ent->client->ps.jumppad_frame = 0; ent->client->ps.jumppad_ent = 0; } } /* ============ G_MoverTouchTriggers Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ) { int i, num; float step, stepSize, dist; int touch[MAX_GENTITIES]; gentity_t *hit; trace_t trace; vec3_t mins, maxs, dir, size, checkSpot; const vec3_t range = { 40, 40, 52 }; // non-moving movers don't hit triggers! if ( !VectorLengthSquared( ent->s.pos.trDelta ) ) { return; } VectorSubtract( ent->r.mins, ent->r.maxs, size ); stepSize = VectorLength( size ); if ( stepSize < 1 ) { stepSize = 1; } VectorSubtract( ent->r.currentOrigin, oldOrg, dir ); dist = VectorNormalize( dir ); for ( step = 0; step <= dist; step += stepSize ) { VectorMA( ent->r.currentOrigin, step, dir, checkSpot ); VectorSubtract( checkSpot, range, mins ); VectorAdd( checkSpot, range, maxs ); num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); // can't use ent->r.absmin, because that has a one unit pad VectorAdd( checkSpot, ent->r.mins, mins ); VectorAdd( checkSpot, ent->r.maxs, maxs ); for ( i=0 ; i<num ; i++ ) { hit = &g_entities[touch[i]]; if ( hit->s.eType != ET_PUSH_TRIGGER ) { continue; } if ( hit->touch == NULL ) { continue; } if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) { continue; } if ( !trap->EntityContact( mins, maxs, (sharedEntity_t *)hit, qfalse ) ) { continue; } memset( &trace, 0, sizeof(trace) ); if ( hit->touch != NULL ) { hit->touch(hit, ent, &trace); } } } } static void SV_PMTrace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask ) { trap->Trace( results, start, mins, maxs, end, passEntityNum, contentMask, qfalse, 0, 10 ); } /* ================= SpectatorThink ================= */ void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) { pmove_t pmove; gclient_t *client; client = ent->client; if ( client->sess.spectatorState != SPECTATOR_FOLLOW ) { client->ps.pm_type = PM_SPECTATOR; client->ps.speed = 400; // faster than normal client->ps.basespeed = 400; //hmm, shouldn't have an anim if you're a spectator, make sure //it gets cleared. client->ps.legsAnim = 0; client->ps.legsTimer = 0; client->ps.torsoAnim = 0; client->ps.torsoTimer = 0; // set up for pmove memset (&pmove, 0, sizeof(pmove)); pmove.ps = &client->ps; pmove.cmd = *ucmd; pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies pmove.trace = SV_PMTrace; pmove.pointcontents = trap->PointContents; pmove.noSpecMove = g_noSpecMove.integer; pmove.animations = NULL; pmove.nonHumanoid = qfalse; //Set up bg entity data pmove.baseEnt = (bgEntity_t *)g_entities; pmove.entSize = sizeof(gentity_t); // perform a pmove Pmove (&pmove); // save results of pmove VectorCopy( client->ps.origin, ent->s.origin ); if (ent->client->tempSpectate < level.time) { G_TouchTriggers( ent ); } trap->UnlinkEntity( (sharedEntity_t *)ent ); } client->oldbuttons = client->buttons; client->buttons = ucmd->buttons; if (client->tempSpectate < level.time) { // attack button cycles through spectators if ( (client->buttons & BUTTON_ATTACK) && !(client->oldbuttons & BUTTON_ATTACK) ) Cmd_FollowCycle_f( ent, 1 ); else if ( client->sess.spectatorState == SPECTATOR_FOLLOW && (client->buttons & BUTTON_ALT_ATTACK) && !(client->oldbuttons & BUTTON_ALT_ATTACK) ) Cmd_FollowCycle_f( ent, -1 ); if (client->sess.spectatorState == SPECTATOR_FOLLOW && (ucmd->upmove > 0)) { //jump now removes you from follow mode StopFollowing(ent); } } } /* ================= ClientInactivityTimer Returns qfalse if the client is dropped ================= */ qboolean ClientInactivityTimer( gclient_t *client ) { if ( ! g_inactivity.integer ) { // give everyone some time, so if the operator sets g_inactivity during // gameplay, everyone isn't kicked client->inactivityTime = level.time + 60 * 1000; client->inactivityWarning = qfalse; } else if ( client->pers.cmd.forwardmove || client->pers.cmd.rightmove || client->pers.cmd.upmove || (client->pers.cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) { client->inactivityTime = level.time + g_inactivity.integer * 1000; client->inactivityWarning = qfalse; } else if ( !client->pers.localClient ) { if ( level.time > client->inactivityTime ) { trap->DropClient( client - level.clients, "Dropped due to inactivity" ); return qfalse; } if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) { client->inactivityWarning = qtrue; trap->SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" ); } } return qtrue; } /* ================== ClientTimerActions Actions that happen once a second ================== */ void ClientTimerActions( gentity_t *ent, int msec ) { gclient_t *client; client = ent->client; client->timeResidual += msec; while ( client->timeResidual >= 1000 ) { client->timeResidual -= 1000; // count down health when over max if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] ) { ent->health--; } // count down armor when over max if ( client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH] ) { client->ps.stats[STAT_ARMOR]--; } } } /* ==================== ClientIntermissionThink ==================== */ void ClientIntermissionThink( gclient_t *client ) { client->ps.eFlags &= ~EF_TALK; client->ps.eFlags &= ~EF_FIRING; // the level will exit when everyone wants to or after timeouts // swap and latch button actions client->oldbuttons = client->buttons; client->buttons = client->pers.cmd.buttons; if ( client->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) & ( client->oldbuttons ^ client->buttons ) ) { // this used to be an ^1 but once a player says ready, it should stick client->readyToExit = qtrue; } } extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags); void G_VehicleAttachDroidUnit( gentity_t *vehEnt ) { if ( vehEnt && vehEnt->m_pVehicle && vehEnt->m_pVehicle->m_pDroidUnit != NULL ) { gentity_t *droidEnt = (gentity_t *)vehEnt->m_pVehicle->m_pDroidUnit; mdxaBone_t boltMatrix; vec3_t fwd; trap->G2API_GetBoltMatrix(vehEnt->ghoul2, 0, vehEnt->m_pVehicle->m_iDroidUnitTag, &boltMatrix, vehEnt->r.currentAngles, vehEnt->r.currentOrigin, level.time, NULL, vehEnt->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, droidEnt->r.currentOrigin); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fwd); vectoangles( fwd, droidEnt->r.currentAngles ); if ( droidEnt->client ) { VectorCopy( droidEnt->r.currentAngles, droidEnt->client->ps.viewangles ); VectorCopy( droidEnt->r.currentOrigin, droidEnt->client->ps.origin ); } G_SetOrigin( droidEnt, droidEnt->r.currentOrigin ); trap->LinkEntity( (sharedEntity_t *)droidEnt ); if ( droidEnt->NPC ) { NPC_SetAnim( droidEnt, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } } //called gameside only from pmove code (convenience) extern qboolean BG_SabersOff( playerState_t *ps ); void G_CheapWeaponFire(int entNum, int ev) { gentity_t *ent = &g_entities[entNum]; if (!ent->inuse || !ent->client) { return; } switch (ev) { case EV_FIRE_WEAPON: if (ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && ent->client && ent->client->ps.m_iVehicleNum) { //a speeder with a pilot gentity_t *rider = &g_entities[ent->client->ps.m_iVehicleNum-1]; if (rider->inuse && rider->client) { //pilot is valid... if (rider->client->ps.weapon != WP_MELEE && (rider->client->ps.weapon != WP_SABER || !BG_SabersOff(&rider->client->ps))) { //can only attack on speeder when using melee or when saber is holstered break; } } } FireWeapon( ent, qfalse ); ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; break; case EV_ALT_FIRE: FireWeapon( ent, qtrue ); ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; break; } } /* ================ ClientEvents Events will be passed on to the clients for presentation, but any server game effects are handled here ================ */ qboolean BG_InKnockDownOnly( int anim ); void ClientEvents( gentity_t *ent, int oldEventSequence ) { int i;//, j; int event; gclient_t *client; int damage; vec3_t dir; // vec3_t origin, angles; // qboolean fired; // gitem_t *item; // gentity_t *drop; client = ent->client; if ( oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS ) { oldEventSequence = client->ps.eventSequence - MAX_PS_EVENTS; } for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) { event = client->ps.events[ i & (MAX_PS_EVENTS-1) ]; switch ( event ) { case EV_FALL: case EV_ROLL: { int delta = client->ps.eventParms[ i & (MAX_PS_EVENTS-1) ]; qboolean knockDownage = qfalse; if (ent->client && ent->client->ps.fallingToDeath) { break; } if ( ent->s.eType != ET_PLAYER ) { break; // not in the player model } if ( dmflags.integer & DF_NO_FALLING ) { break; } if (BG_InKnockDownOnly(ent->client->ps.legsAnim)) { if (delta <= 14) { break; } knockDownage = qtrue; } else { if (delta <= 44) { break; } } if (knockDownage) { damage = delta*1; //you suffer for falling unprepared. A lot. Makes throws and things useful, and more realistic I suppose. } else { if (level.gametype == GT_SIEGE && delta > 60) { //longer falls hurt more damage = delta*1; //good enough for now, I guess } else { damage = delta*0.16; //good enough for now, I guess } } VectorSet (dir, 0, 0, 1); ent->pain_debounce_time = level.time + 200; // no normal pain sound G_Damage (ent, NULL, NULL, NULL, NULL, damage, DAMAGE_NO_ARMOR, MOD_FALLING); if (ent->health < 1) { G_Sound(ent, CHAN_AUTO, G_SoundIndex( "sound/player/fallsplat.wav" )); } } break; case EV_FIRE_WEAPON: FireWeapon( ent, qfalse ); ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; break; case EV_ALT_FIRE: FireWeapon( ent, qtrue ); ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; break; case EV_SABER_ATTACK: ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; break; //rww - Note that these must be in the same order (ITEM#-wise) as they are in holdable_t case EV_USE_ITEM1: //seeker droid ItemUse_Seeker(ent); break; case EV_USE_ITEM2: //shield ItemUse_Shield(ent); break; case EV_USE_ITEM3: //medpack ItemUse_MedPack(ent); break; case EV_USE_ITEM4: //big medpack ItemUse_MedPack_Big(ent); break; case EV_USE_ITEM5: //binoculars ItemUse_Binoculars(ent); break; case EV_USE_ITEM6: //sentry gun ItemUse_Sentry(ent); break; case EV_USE_ITEM7: //jetpack ItemUse_Jetpack(ent); break; case EV_USE_ITEM8: //health disp //ItemUse_UseDisp(ent, HI_HEALTHDISP); break; case EV_USE_ITEM9: //ammo disp //ItemUse_UseDisp(ent, HI_AMMODISP); break; case EV_USE_ITEM10: //eweb ItemUse_UseEWeb(ent); break; case EV_USE_ITEM11: //cloak ItemUse_UseCloak(ent); break; default: break; } } } /* ============== SendPendingPredictableEvents ============== */ void SendPendingPredictableEvents( playerState_t *ps ) { gentity_t *t; int event, seq; int extEvent, number; // if there are still events pending if ( ps->entityEventSequence < ps->eventSequence ) { // create a temporary entity for this event which is sent to everyone // except the client who generated the event seq = ps->entityEventSequence & (MAX_PS_EVENTS-1); event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 ); // set external event to zero before calling BG_PlayerStateToEntityState extEvent = ps->externalEvent; ps->externalEvent = 0; // create temporary entity for event t = G_TempEntity( ps->origin, event ); number = t->s.number; BG_PlayerStateToEntityState( ps, &t->s, qtrue ); t->s.number = number; t->s.eType = ET_EVENTS + event; t->s.eFlags |= EF_PLAYER_EVENT; t->s.otherEntityNum = ps->clientNum; // send to everyone except the client who generated the event t->r.svFlags |= SVF_NOTSINGLECLIENT; t->r.singleClient = ps->clientNum; // set back external event ps->externalEvent = extEvent; } } static const float maxJediMasterDistance = 2500.0f * 2500.0f; // x^2, optimisation static const float maxJediMasterFOV = 100.0f; static const float maxForceSightDistance = Square( 1500.0f ) * 1500.0f; // x^2, optimisation static const float maxForceSightFOV = 100.0f; void G_UpdateClientBroadcasts( gentity_t *self ) { int i; gentity_t *other; // we are always sent to ourselves // we are always sent to other clients if we are in their PVS // if we are not in their PVS, we must set the broadcastClients bit field // if we do not wish to be sent to any particular entity, we must set the broadcastClients bit field and the // SVF_BROADCASTCLIENTS bit flag self->r.broadcastClients[0] = 0u; self->r.broadcastClients[1] = 0u; for ( i = 0, other = g_entities; i < MAX_CLIENTS; i++, other++ ) { qboolean send = qfalse; float dist; vec3_t angles; if ( !other->inuse || other->client->pers.connected != CON_CONNECTED ) { // no need to compute visibility for non-connected clients continue; } if ( other == self ) { // we are always sent to ourselves anyway, this is purely an optimisation continue; } VectorSubtract( self->client->ps.origin, other->client->ps.origin, angles ); dist = VectorLengthSquared( angles ); vectoangles( angles, angles ); // broadcast jedi master to everyone if we are in distance/field of view if ( level.gametype == GT_JEDIMASTER && self->client->ps.isJediMaster ) { if ( dist < maxJediMasterDistance && InFieldOfVision( other->client->ps.viewangles, maxJediMasterFOV, angles ) ) { send = qtrue; } } // broadcast this client to everyone using force sight if we are in distance/field of view if ( (other->client->ps.fd.forcePowersActive & (1 << FP_SEE)) ) { if ( dist < maxForceSightDistance && InFieldOfVision( other->client->ps.viewangles, maxForceSightFOV, angles ) ) { send = qtrue; } } if ( send ) { Q_AddToBitflags( self->r.broadcastClients, i, 32 ); } } trap->LinkEntity( (sharedEntity_t *)self ); } void G_AddPushVecToUcmd( gentity_t *self, usercmd_t *ucmd ) { vec3_t forward, right, moveDir; float pushSpeed, fMove, rMove; if ( !self->client ) { return; } pushSpeed = VectorLengthSquared(self->client->pushVec); if(!pushSpeed) {//not being pushed return; } AngleVectors(self->client->ps.viewangles, forward, right, NULL); VectorScale(forward, ucmd->forwardmove/127.0f * self->client->ps.speed, moveDir); VectorMA(moveDir, ucmd->rightmove/127.0f * self->client->ps.speed, right, moveDir); //moveDir is now our intended move velocity VectorAdd(moveDir, self->client->pushVec, moveDir); self->client->ps.speed = VectorNormalize(moveDir); //moveDir is now our intended move velocity plus our push Vector fMove = 127.0 * DotProduct(forward, moveDir); rMove = 127.0 * DotProduct(right, moveDir); ucmd->forwardmove = floor(fMove);//If in the same dir , will be positive ucmd->rightmove = floor(rMove);//If in the same dir , will be positive if ( self->client->pushVecTime < level.time ) { VectorClear( self->client->pushVec ); } } qboolean G_StandingAnim( int anim ) {//NOTE: does not check idles or special (cinematic) stands switch ( anim ) { case BOTH_STAND1: case BOTH_STAND2: case BOTH_STAND3: case BOTH_STAND4: return qtrue; break; } return qfalse; } qboolean G_ActionButtonPressed(int buttons) { if (buttons & BUTTON_ATTACK) { return qtrue; } else if (buttons & BUTTON_USE_HOLDABLE) { return qtrue; } else if (buttons & BUTTON_GESTURE) { return qtrue; } else if (buttons & BUTTON_USE) { return qtrue; } else if (buttons & BUTTON_FORCEGRIP) { return qtrue; } else if (buttons & BUTTON_ALT_ATTACK) { return qtrue; } else if (buttons & BUTTON_FORCEPOWER) { return qtrue; } else if (buttons & BUTTON_FORCE_LIGHTNING) { return qtrue; } else if (buttons & BUTTON_FORCE_DRAIN) { return qtrue; } return qfalse; } void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) { vec3_t viewChange; qboolean actionPressed; int buttons; if ( !ent || !ent->client || ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 || ent->client->sess.sessionTeam == TEAM_SPECTATOR || (ent->client->ps.pm_flags & PMF_FOLLOW)) { return; } buttons = ucmd->buttons; if (ent->r.svFlags & SVF_BOT) { //they press use all the time.. buttons &= ~BUTTON_USE; } actionPressed = G_ActionButtonPressed(buttons); VectorSubtract(ent->client->ps.viewangles, ent->client->idleViewAngles, viewChange); if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) || actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || !G_StandingAnim( ent->client->ps.legsAnim ) || (ent->health+ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth || VectorLength(viewChange) > 10 || ent->client->ps.legsTimer > 0 || ent->client->ps.torsoTimer > 0 || ent->client->ps.weaponTime > 0 || ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT || ent->client->ps.zoomMode || (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER) || ent->client->ps.forceHandExtend != HANDEXTEND_NONE || ent->client->ps.saberBlocked != BLOCKED_NONE || ent->client->ps.saberBlocking >= level.time || ent->client->ps.weapon == WP_MELEE || (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC)) {//FIXME: also check for turning? qboolean brokeOut = qfalse; if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) || actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || (ent->health+ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth || ent->client->ps.zoomMode || (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER) || (ent->client->ps.weaponTime > 0 && ent->client->ps.weapon == WP_SABER) || ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT || ent->client->ps.forceHandExtend != HANDEXTEND_NONE || ent->client->ps.saberBlocked != BLOCKED_NONE || ent->client->ps.saberBlocking >= level.time || ent->client->ps.weapon == WP_MELEE || (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC)) { //if in an idle, break out switch ( ent->client->ps.legsAnim ) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: case BOTH_STAND3IDLE1: case BOTH_STAND5IDLE1: ent->client->ps.legsTimer = 0; brokeOut = qtrue; break; } switch ( ent->client->ps.torsoAnim ) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: case BOTH_STAND3IDLE1: case BOTH_STAND5IDLE1: ent->client->ps.torsoTimer = 0; ent->client->ps.weaponTime = 0; ent->client->ps.saberMove = LS_READY; brokeOut = qtrue; break; } } // ent->client->idleHealth = (ent->health+ent->client->ps.stats[STAT_ARMOR]); VectorCopy(ent->client->ps.viewangles, ent->client->idleViewAngles); if ( ent->client->idleTime < level.time ) { ent->client->idleTime = level.time; } if (brokeOut && (ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT)) { ent->client->ps.torsoAnim = TORSO_RAISEWEAP1; } } else if ( level.time - ent->client->idleTime > 5000 ) {//been idle for 5 seconds int idleAnim = -1; switch ( ent->client->ps.legsAnim ) { case BOTH_STAND1: idleAnim = BOTH_STAND1IDLE1; break; case BOTH_STAND2: idleAnim = BOTH_STAND2IDLE1;//Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2); break; case BOTH_STAND3: idleAnim = BOTH_STAND3IDLE1; break; case BOTH_STAND5: idleAnim = BOTH_STAND5IDLE1; break; } if (idleAnim == BOTH_STAND2IDLE1 && Q_irand(1, 10) <= 5) { idleAnim = BOTH_STAND2IDLE2; } if ( /*PM_HasAnimation( ent, idleAnim )*/idleAnim > 0 && idleAnim < MAX_ANIMATIONS ) { G_SetAnim(ent, ucmd, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); //don't idle again after this anim for a while //ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 ); ent->client->idleTime = level.time + ent->client->ps.legsTimer + Q_irand( 0, 2000 ); } } } void NPC_Accelerate( gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc ) { if ( !ent->client || !ent->NPC ) { return; } if ( !ent->NPC->stats.acceleration ) {//No acceleration means just start and stop ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } //FIXME: in cinematics always accel/decel? else if ( ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed ) {//Only accelerate if at walkSpeeds if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) { //ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) { //ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } else if ( fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) {//decelerate even when walking ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) {//stop on a dime ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } else// if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) {//Only decelerate if at runSpeeds if ( fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) {//Accelerate to runspeed //ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) {//accelerate instantly //ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } else if ( fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) { ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; } else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) { ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } } /* ------------------------- NPC_GetWalkSpeed ------------------------- */ static int NPC_GetWalkSpeed( gentity_t *ent ) { int walkSpeed = 0; if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) return 0; switch ( ent->client->playerTeam ) { case NPCTEAM_PLAYER: //To shutup compiler, will add entries later (this is stub code) default: walkSpeed = ent->NPC->stats.walkSpeed; break; } return walkSpeed; } /* ------------------------- NPC_GetRunSpeed ------------------------- */ static int NPC_GetRunSpeed( gentity_t *ent ) { int runSpeed = 0; if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) return 0; // team no longer indicates species/race. Use NPC_class to adjust speed for specific npc types switch( ent->client->NPC_class) { case CLASS_PROBE: // droid cases here to shut-up compiler case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: case CLASS_MARK1: case CLASS_MARK2: case CLASS_PROTOCOL: case CLASS_ATST: // hmm, not really your average droid case CLASS_MOUSE: case CLASS_SEEKER: case CLASS_REMOTE: runSpeed = ent->NPC->stats.runSpeed; break; default: runSpeed = ent->NPC->stats.runSpeed*1.3f; //rww - seems to slow in MP for some reason. break; } return runSpeed; } //Seems like a slightly less than ideal method for this, could it be done on the client? extern qboolean FlyingCreature( gentity_t *ent ); void G_CheckMovingLoopingSounds( gentity_t *ent, usercmd_t *ucmd ) { if ( ent->client ) { if ( (ent->NPC&&!VectorCompare( vec3_origin, ent->client->ps.moveDir ))//moving using moveDir || ucmd->forwardmove || ucmd->rightmove//moving using ucmds || (ucmd->upmove&&FlyingCreature( ent ))//flier using ucmds to move || (FlyingCreature( ent )&&!VectorCompare( vec3_origin, ent->client->ps.velocity )&&ent->health>0))//flier using velocity to move { switch( ent->client->NPC_class ) { case CLASS_R2D2: ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); break; case CLASS_R5D2: ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); break; case CLASS_MARK2: ent->s.loopSound = G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); break; case CLASS_MOUSE: ent->s.loopSound = G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); break; case CLASS_PROBE: ent->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); default: break; } } else {//not moving under your own control, stop loopSound if ( ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_PROBE ) { ent->s.loopSound = 0; } } } } void G_HeldByMonster( gentity_t *ent, usercmd_t *ucmd ) { if ( ent && ent->client && ent->client->ps.hasLookTarget )//NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor... { gentity_t *monster = &g_entities[ent->client->ps.lookTarget]; if ( monster && monster->client ) { //take the monster's waypoint as your own ent->waypoint = monster->waypoint; if ( monster->s.NPC_class == CLASS_RANCOR ) {//only possibility right now, may add Wampa and Sand Creature later BG_AttachToRancor( monster->ghoul2, //ghoul2 info monster->r.currentAngles[YAW], monster->r.currentOrigin, level.time, NULL, monster->modelScale, (monster->client->ps.eFlags2&EF2_GENERIC_NPC_FLAG), ent->client->ps.origin, ent->client->ps.viewangles, NULL ); } VectorClear( ent->client->ps.velocity ); G_SetOrigin( ent, ent->client->ps.origin ); SetClientViewAngle( ent, ent->client->ps.viewangles ); G_SetAngles( ent, ent->client->ps.viewangles ); trap->LinkEntity( (sharedEntity_t *)ent );//redundant? } } // don't allow movement, weapon switching, and most kinds of button presses ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 0; } typedef enum tauntTypes_e { TAUNT_TAUNT = 0, TAUNT_BOW, TAUNT_MEDITATE, TAUNT_FLOURISH, TAUNT_GLOAT } tauntTypes_t; void G_SetTauntAnim( gentity_t *ent, int taunt ) { if (ent->client->pers.cmd.upmove || ent->client->pers.cmd.forwardmove || ent->client->pers.cmd.rightmove) { //hack, don't do while moving return; } if ( taunt != TAUNT_TAUNT ) {//normal taunt always allowed if ( level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL ) {//no taunts unless in Duel return; } } // fix: rocket lock bug BG_ClearRocketLock(&ent->client->ps); if ( ent->client->ps.torsoTimer < 1 && ent->client->ps.forceHandExtend == HANDEXTEND_NONE && ent->client->ps.legsTimer < 1 && ent->client->ps.weaponTime < 1 && ent->client->ps.saberLockTime < level.time ) { int anim = -1; switch ( taunt ) { case TAUNT_TAUNT: if ( ent->client->ps.weapon != WP_SABER ) { anim = BOTH_ENGAGETAUNT; } else if ( ent->client->saber[0].tauntAnim != -1 ) { anim = ent->client->saber[0].tauntAnim; } else if ( ent->client->saber[1].model[0] && ent->client->saber[1].tauntAnim != -1 ) { anim = ent->client->saber[1].tauntAnim; } else { switch ( ent->client->ps.fd.saberAnimLevel ) { case SS_FAST: case SS_TAVION: if ( ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0] ) {//turn off second saber G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff ); } else if ( ent->client->ps.saberHolstered == 0 ) {//turn off first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff ); } ent->client->ps.saberHolstered = 2; anim = BOTH_GESTURE1; break; case SS_MEDIUM: case SS_STRONG: case SS_DESANN: anim = BOTH_ENGAGETAUNT; break; case SS_DUAL: if ( ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0] ) {//turn on second saber G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn ); } else if ( ent->client->ps.saberHolstered == 2 ) {//turn on first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); } ent->client->ps.saberHolstered = 0; anim = BOTH_DUAL_TAUNT; break; case SS_STAFF: if ( ent->client->ps.saberHolstered > 0 ) {//turn on all blades G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); } ent->client->ps.saberHolstered = 0; anim = BOTH_STAFF_TAUNT; break; } } break; case TAUNT_BOW: if ( ent->client->saber[0].bowAnim != -1 ) { anim = ent->client->saber[0].bowAnim; } else if ( ent->client->saber[1].model[0] && ent->client->saber[1].bowAnim != -1 ) { anim = ent->client->saber[1].bowAnim; } else { anim = BOTH_BOW; } if ( ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0] ) {//turn off second saber G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff ); } else if ( ent->client->ps.saberHolstered == 0 ) {//turn off first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff ); } ent->client->ps.saberHolstered = 2; break; case TAUNT_MEDITATE: if ( ent->client->saber[0].meditateAnim != -1 ) { anim = ent->client->saber[0].meditateAnim; } else if ( ent->client->saber[1].model[0] && ent->client->saber[1].meditateAnim != -1 ) { anim = ent->client->saber[1].meditateAnim; } else { anim = BOTH_MEDITATE; } if ( ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0] ) {//turn off second saber G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff ); } else if ( ent->client->ps.saberHolstered == 0 ) {//turn off first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff ); } ent->client->ps.saberHolstered = 2; break; case TAUNT_FLOURISH: if ( ent->client->ps.weapon == WP_SABER ) { if ( ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0] ) {//turn on second saber G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn ); } else if ( ent->client->ps.saberHolstered == 2 ) {//turn on first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); } ent->client->ps.saberHolstered = 0; if ( ent->client->saber[0].flourishAnim != -1 ) { anim = ent->client->saber[0].flourishAnim; } else if ( ent->client->saber[1].model[0] && ent->client->saber[1].flourishAnim != -1 ) { anim = ent->client->saber[1].flourishAnim; } else { switch ( ent->client->ps.fd.saberAnimLevel ) { case SS_FAST: case SS_TAVION: anim = BOTH_SHOWOFF_FAST; break; case SS_MEDIUM: anim = BOTH_SHOWOFF_MEDIUM; break; case SS_STRONG: case SS_DESANN: anim = BOTH_SHOWOFF_STRONG; break; case SS_DUAL: anim = BOTH_SHOWOFF_DUAL; break; case SS_STAFF: anim = BOTH_SHOWOFF_STAFF; break; } } } break; case TAUNT_GLOAT: if ( ent->client->saber[0].gloatAnim != -1 ) { anim = ent->client->saber[0].gloatAnim; } else if ( ent->client->saber[1].model[0] && ent->client->saber[1].gloatAnim != -1 ) { anim = ent->client->saber[1].gloatAnim; } else { switch ( ent->client->ps.fd.saberAnimLevel ) { case SS_FAST: case SS_TAVION: anim = BOTH_VICTORY_FAST; break; case SS_MEDIUM: anim = BOTH_VICTORY_MEDIUM; break; case SS_STRONG: case SS_DESANN: if ( ent->client->ps.saberHolstered ) {//turn on first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); } ent->client->ps.saberHolstered = 0; anim = BOTH_VICTORY_STRONG; break; case SS_DUAL: if ( ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0] ) {//turn on second saber G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn ); } else if ( ent->client->ps.saberHolstered == 2 ) {//turn on first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); } ent->client->ps.saberHolstered = 0; anim = BOTH_VICTORY_DUAL; break; case SS_STAFF: if ( ent->client->ps.saberHolstered ) {//turn on first G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); } ent->client->ps.saberHolstered = 0; anim = BOTH_VICTORY_STAFF; break; } } break; } if ( anim != -1 ) { if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) { ent->client->ps.forceHandExtend = HANDEXTEND_TAUNT; ent->client->ps.forceDodgeAnim = anim; ent->client->ps.forceHandExtendTime = level.time + BG_AnimLength(ent->localAnimIndex, (animNumber_t)anim); } if ( taunt != TAUNT_MEDITATE && taunt != TAUNT_BOW ) {//no sound for meditate or bow G_AddEvent( ent, EV_TAUNT, taunt ); } } } } /* ============== ClientThink This will be called once for each client frame, which will usually be a couple times for each server frame on fast clients. If "g_synchronousClients 1" is set, this will be called exactly once for each server frame, which makes for smooth demo recording. ============== */ void ClientThink_real( gentity_t *ent ) { gclient_t *client; pmove_t pmove; int oldEventSequence; int msec; usercmd_t *ucmd; qboolean isNPC = qfalse; qboolean controlledByPlayer = qfalse; qboolean killJetFlags = qtrue; qboolean isFollowing; client = ent->client; if (ent->s.eType == ET_NPC) { isNPC = qtrue; } // don't think if the client is not yet connected (and thus not yet spawned in) if (client->pers.connected != CON_CONNECTED && !isNPC) { return; } // This code was moved here from clientThink to fix a problem with g_synchronousClients // being set to 1 when in vehicles. if ( ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum ) {//driving a vehicle if (g_entities[ent->client->ps.m_iVehicleNum].client) { gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum]; if (veh->m_pVehicle && veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent) { //only take input from the pilot... veh->client->ps.commandTime = ent->client->ps.commandTime; memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t)); if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK ) { //forced input if "chat bubble" is up veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK; veh->m_pVehicle->m_ucmd.forwardmove = 0; veh->m_pVehicle->m_ucmd.rightmove = 0; veh->m_pVehicle->m_ucmd.upmove = 0; } } } } isFollowing = (client->ps.pm_flags & PMF_FOLLOW) ? qtrue : qfalse; if (!isFollowing) { if (level.gametype == GT_SIEGE && client->siegeClass != -1 && bgSiegeClasses[client->siegeClass].saberStance) { //the class says we have to use this stance set. if (!(bgSiegeClasses[client->siegeClass].saberStance & (1 << client->ps.fd.saberAnimLevel))) { //the current stance is not in the bitmask, so find the first one that is. int i = SS_FAST; while (i < SS_NUM_SABER_STYLES) { if (bgSiegeClasses[client->siegeClass].saberStance & (1 << i)) { if (i == SS_DUAL && client->ps.saberHolstered == 1 ) {//one saber should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevelBase = i; client->ps.fd.saberAnimLevel = SS_FAST; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } else if ( i == SS_STAFF && client->ps.saberHolstered == 1 && client->saber[0].singleBladeStyle != SS_NONE) {//one saber or blade should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevelBase = i; client->ps.fd.saberAnimLevel = client->saber[0].singleBladeStyle; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } else { client->ps.fd.saberAnimLevelBase = client->ps.fd.saberAnimLevel = i; client->ps.fd.saberDrawAnimLevel = i; } break; } i++; } } } else if (client->saber[0].model[0] && client->saber[1].model[0]) { //with two sabs always use akimbo style if ( client->ps.saberHolstered == 1 ) {//one saber should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevelBase = SS_DUAL; client->ps.fd.saberAnimLevel = SS_FAST; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } else { if ( !WP_SaberStyleValidForSaber( &client->saber[0], &client->saber[1], client->ps.saberHolstered, client->ps.fd.saberAnimLevel ) ) {//only use dual style if the style we're trying to use isn't valid client->ps.fd.saberAnimLevelBase = client->ps.fd.saberAnimLevel = SS_DUAL; } client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } } else { if (client->saber[0].stylesLearned == (1<<SS_STAFF) ) { //then *always* use the staff style client->ps.fd.saberAnimLevelBase = SS_STAFF; } if ( client->ps.fd.saberAnimLevelBase == SS_STAFF ) {//using staff style if ( client->ps.saberHolstered == 1 && client->saber[0].singleBladeStyle != SS_NONE) {//one blade should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevel = client->saber[0].singleBladeStyle; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } else { client->ps.fd.saberAnimLevel = SS_STAFF; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } } } } // mark the time, so the connection sprite can be removed ucmd = &ent->client->pers.cmd; if ( client && !isFollowing && (client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) { G_HeldByMonster( ent, ucmd ); } // sanity check the command time to prevent speedup cheating if ( ucmd->serverTime > level.time + 200 ) { ucmd->serverTime = level.time + 200; // trap->Print("serverTime <<<<<\n" ); } if ( ucmd->serverTime < level.time - 1000 ) { ucmd->serverTime = level.time - 1000; // trap->Print("serverTime >>>>>\n" ); } if (isNPC && (ucmd->serverTime - client->ps.commandTime) < 1) { ucmd->serverTime = client->ps.commandTime + 100; } msec = ucmd->serverTime - client->ps.commandTime; // following others may result in bad times, but we still want // to check for follow toggles if ( msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW ) { return; } if ( msec > 200 ) { msec = 200; } if ( pmove_msec.integer < 8 ) { trap->Cvar_Set("pmove_msec", "8"); } else if (pmove_msec.integer > 33) { trap->Cvar_Set("pmove_msec", "33"); } if ( pmove_fixed.integer || client->pers.pmoveFixed ) { ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer; //if (ucmd->serverTime - client->ps.commandTime <= 0) // return; } // // check for exiting intermission // if ( level.intermissiontime ) { if ( ent->s.number < MAX_CLIENTS || client->NPC_class == CLASS_VEHICLE ) {//players and vehicles do nothing in intermissions ClientIntermissionThink( client ); return; } } // spectators don't do much if ( client->sess.sessionTeam == TEAM_SPECTATOR || client->tempSpectate >= level.time ) { if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) { return; } SpectatorThink( ent, ucmd ); return; } if (ent && ent->client && (ent->client->ps.eFlags & EF_INVULNERABLE)) { if (ent->client->invulnerableTimer <= level.time) { ent->client->ps.eFlags &= ~EF_INVULNERABLE; } } if (ent->s.eType != ET_NPC) { // check for inactivity timer, but never drop the local client of a non-dedicated server if ( !ClientInactivityTimer( client ) ) { return; } } //Check if we should have a fullbody push effect around the player if (client->pushEffectTime > level.time) { client->ps.eFlags |= EF_BODYPUSH; } else if (client->pushEffectTime) { client->pushEffectTime = 0; client->ps.eFlags &= ~EF_BODYPUSH; } if (client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) { client->ps.eFlags |= EF_JETPACK; } else { client->ps.eFlags &= ~EF_JETPACK; } if ( client->noclip ) { client->ps.pm_type = PM_NOCLIP; } else if ( client->ps.eFlags & EF_DISINTEGRATION ) { client->ps.pm_type = PM_NOCLIP; } else if ( client->ps.stats[STAT_HEALTH] <= 0 ) { client->ps.pm_type = PM_DEAD; } else { if (client->ps.forceGripChangeMovetype) { client->ps.pm_type = client->ps.forceGripChangeMovetype; } else { if (client->jetPackOn) { client->ps.pm_type = PM_JETPACK; client->ps.eFlags |= EF_JETPACK_ACTIVE; killJetFlags = qfalse; } else { client->ps.pm_type = PM_NORMAL; } } } if (killJetFlags) { client->ps.eFlags &= ~EF_JETPACK_ACTIVE; client->ps.eFlags &= ~EF_JETPACK_FLAMING; } #define SLOWDOWN_DIST 128.0f #define MIN_NPC_SPEED 16.0f if (client->bodyGrabIndex != ENTITYNUM_NONE) { gentity_t *grabbed = &g_entities[client->bodyGrabIndex]; if (!grabbed->inuse || grabbed->s.eType != ET_BODY || (grabbed->s.eFlags & EF_DISINTEGRATION) || (grabbed->s.eFlags & EF_NODRAW)) { if (grabbed->inuse && grabbed->s.eType == ET_BODY) { grabbed->s.ragAttach = 0; } client->bodyGrabIndex = ENTITYNUM_NONE; } else { mdxaBone_t rhMat; vec3_t rhOrg, tAng; vec3_t bodyDir; float bodyDist; ent->client->ps.forceHandExtend = HANDEXTEND_DRAGGING; if (ent->client->ps.forceHandExtendTime < level.time + 500) { ent->client->ps.forceHandExtendTime = level.time + 1000; } VectorSet(tAng, 0, ent->client->ps.viewangles[YAW], 0); trap->G2API_GetBoltMatrix(ent->ghoul2, 0, 0, &rhMat, tAng, ent->client->ps.origin, level.time, NULL, ent->modelScale); //0 is always going to be right hand bolt BG_GiveMeVectorFromMatrix(&rhMat, ORIGIN, rhOrg); VectorSubtract(rhOrg, grabbed->r.currentOrigin, bodyDir); bodyDist = VectorLength(bodyDir); if (bodyDist > 40.0f) { //can no longer reach grabbed->s.ragAttach = 0; client->bodyGrabIndex = ENTITYNUM_NONE; } else if (bodyDist > 24.0f) { bodyDir[2] = 0; //don't want it floating //VectorScale(bodyDir, 0.1f, bodyDir); VectorAdd(grabbed->epVelocity, bodyDir, grabbed->epVelocity); G_Sound(grabbed, CHAN_AUTO, G_SoundIndex("sound/player/roll1.wav")); } } } else if (ent->client->ps.forceHandExtend == HANDEXTEND_DRAGGING) { ent->client->ps.forceHandExtend = HANDEXTEND_WEAPONREADY; } if (ent->NPC && ent->s.NPC_class != CLASS_VEHICLE) //vehicles manage their own speed { //FIXME: swoop should keep turning (and moving forward?) for a little bit? if ( ent->NPC->combatMove == qfalse ) { //if ( !(ucmd->buttons & BUTTON_USE) ) if (1) {//Not leaning qboolean Flying = (ucmd->upmove && (ent->client->ps.eFlags2&EF2_FLYING));//ent->client->moveType == MT_FLYSWIM); qboolean Climbing = (ucmd->upmove && ent->watertype&CONTENTS_LADDER ); //client->ps.friction = 6; if ( ucmd->forwardmove || ucmd->rightmove || Flying ) { //if ( ent->NPC->behaviorState != BS_FORMATION ) {//In - Formation NPCs set thier desiredSpeed themselves if ( ucmd->buttons & BUTTON_WALKING ) { ent->NPC->desiredSpeed = NPC_GetWalkSpeed( ent );//ent->NPC->stats.walkSpeed; } else//running { ent->NPC->desiredSpeed = NPC_GetRunSpeed( ent );//ent->NPC->stats.runSpeed; } if ( ent->NPC->currentSpeed >= 80 && !controlledByPlayer ) {//At higher speeds, need to slow down close to stuff //Slow down as you approach your goal if ( ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128 { if ( ent->NPC->desiredSpeed > MIN_NPC_SPEED ) { float slowdownSpeed = ((float)ent->NPC->desiredSpeed) * ent->NPC->distToGoal / SLOWDOWN_DIST; ent->NPC->desiredSpeed = ceil(slowdownSpeed); if ( ent->NPC->desiredSpeed < MIN_NPC_SPEED ) {//don't slow down too much ent->NPC->desiredSpeed = MIN_NPC_SPEED; } } } } } } else if ( Climbing ) { ent->NPC->desiredSpeed = ent->NPC->stats.walkSpeed; } else {//We want to stop ent->NPC->desiredSpeed = 0; } NPC_Accelerate( ent, qfalse, qfalse ); if ( ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) {//No-one walks this slow client->ps.speed = ent->NPC->currentSpeed = 0;//Full stop ucmd->forwardmove = 0; ucmd->rightmove = 0; } else { if ( ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed ) {//Play the walkanim ucmd->buttons |= BUTTON_WALKING; } else { ucmd->buttons &= ~BUTTON_WALKING; } if ( ent->NPC->currentSpeed > 0 ) {//We should be moving if ( Climbing || Flying ) { if ( !ucmd->upmove ) {//We need to force them to take a couple more steps until stopped ucmd->upmove = ent->NPC->last_ucmd.upmove;//was last_upmove; } } else if ( !ucmd->forwardmove && !ucmd->rightmove ) {//We need to force them to take a couple more steps until stopped ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove;//was last_forwardmove; ucmd->rightmove = ent->NPC->last_ucmd.rightmove;//was last_rightmove; } } client->ps.speed = ent->NPC->currentSpeed; // if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) // { // } // else //rwwFIXMEFIXME: do this and also check for all real client if (1) { //Slow down on turns - don't orbit!!! float turndelta = 0; // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always thinks it trying to turn according to desiredYaw //if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack... if (0) //rwwFIXMEFIXME: ... { turndelta = (180 - fabs( AngleDelta( ent->r.currentAngles[YAW], ent->NPC->lockedDesiredYaw ) ))/180; } else { turndelta = (180 - fabs( AngleDelta( ent->r.currentAngles[YAW], ent->NPC->desiredYaw ) ))/180; } if ( turndelta < 0.75f ) { client->ps.speed = 0; } else if ( ent->NPC->distToGoal < 100 && turndelta < 1.0 ) {//Turn is greater than 45 degrees or closer than 100 to goal client->ps.speed = floor(((float)(client->ps.speed))*turndelta); } } } } } else { ent->NPC->desiredSpeed = ( ucmd->buttons & BUTTON_WALKING ) ? NPC_GetWalkSpeed( ent ) : NPC_GetRunSpeed( ent ); client->ps.speed = ent->NPC->desiredSpeed; } if (ucmd->buttons & BUTTON_WALKING) { //sort of a hack I guess since MP handles walking differently from SP (has some proxy cheat prevention methods) /* if (ent->client->ps.speed > 64) { ent->client->ps.speed = 64; } */ if (ucmd->forwardmove > 64) { ucmd->forwardmove = 64; } else if (ucmd->forwardmove < -64) { ucmd->forwardmove = -64; } if (ucmd->rightmove > 64) { ucmd->rightmove = 64; } else if ( ucmd->rightmove < -64) { ucmd->rightmove = -64; } //ent->client->ps.speed = ent->client->ps.basespeed = NPC_GetRunSpeed( ent ); } client->ps.basespeed = client->ps.speed; } else if (!client->ps.m_iVehicleNum && (!ent->NPC || ent->s.NPC_class != CLASS_VEHICLE)) //if riding a vehicle it will manage our speed and such { // set speed client->ps.speed = g_speed.value; //Check for a siege class speed multiplier if (level.gametype == GT_SIEGE && client->siegeClass != -1) { client->ps.speed *= bgSiegeClasses[client->siegeClass].speed; } if (client->bodyGrabIndex != ENTITYNUM_NONE) { //can't go nearly as fast when dragging a body around client->ps.speed *= 0.2f; } client->ps.basespeed = client->ps.speed; } if ( !ent->NPC || !(ent->NPC->aiFlags&NPCAI_CUSTOM_GRAVITY) ) {//use global gravity if (ent->NPC && ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->gravity) { //use custom veh gravity client->ps.gravity = ent->m_pVehicle->m_pVehicleInfo->gravity; } else { if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) { //in space, so no gravity... client->ps.gravity = 1.0f; if (ent->s.number < MAX_CLIENTS) { VectorScale(client->ps.velocity, 0.8f, client->ps.velocity); } } else { if (client->ps.eFlags2 & EF2_SHIP_DEATH) { //float there VectorClear(client->ps.velocity); client->ps.gravity = 1.0f; } else { client->ps.gravity = g_gravity.value; } } } } if (ent->client->ps.duelInProgress) { gentity_t *duelAgainst = &g_entities[ent->client->ps.duelIndex]; //Keep the time updated, so once this duel ends this player can't engage in a duel for another //10 seconds. This will give other people a chance to engage in duels in case this player wants //to engage again right after he's done fighting and someone else is waiting. ent->client->ps.fd.privateDuelTime = level.time + 10000; if (ent->client->ps.duelTime < level.time) { //Bring out the sabers if (ent->client->ps.weapon == WP_SABER && ent->client->ps.saberHolstered && ent->client->ps.duelTime ) { ent->client->ps.saberHolstered = 0; if (ent->client->saber[0].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOn); } if (ent->client->saber[1].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOn); } G_AddEvent(ent, EV_PRIVATE_DUEL, 2); ent->client->ps.duelTime = 0; } if (duelAgainst && duelAgainst->client && duelAgainst->inuse && duelAgainst->client->ps.weapon == WP_SABER && duelAgainst->client->ps.saberHolstered && duelAgainst->client->ps.duelTime) { duelAgainst->client->ps.saberHolstered = 0; if (duelAgainst->client->saber[0].soundOn) { G_Sound(duelAgainst, CHAN_AUTO, duelAgainst->client->saber[0].soundOn); } if (duelAgainst->client->saber[1].soundOn) { G_Sound(duelAgainst, CHAN_AUTO, duelAgainst->client->saber[1].soundOn); } G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 2); duelAgainst->client->ps.duelTime = 0; } } else { client->ps.speed = 0; client->ps.basespeed = 0; ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 0; } if (!duelAgainst || !duelAgainst->client || !duelAgainst->inuse || duelAgainst->client->ps.duelIndex != ent->s.number) { ent->client->ps.duelInProgress = 0; G_AddEvent(ent, EV_PRIVATE_DUEL, 0); } else if (duelAgainst->health < 1 || duelAgainst->client->ps.stats[STAT_HEALTH] < 1) { ent->client->ps.duelInProgress = 0; duelAgainst->client->ps.duelInProgress = 0; G_AddEvent(ent, EV_PRIVATE_DUEL, 0); G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 0); //Winner gets full health.. providing he's still alive if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0) { if (ent->health < ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_HEALTH] = ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; } if (g_spawnInvulnerability.integer) { ent->client->ps.eFlags |= EF_INVULNERABLE; ent->client->invulnerableTimer = level.time + g_spawnInvulnerability.integer; } } /* trap->SendServerCommand( ent-g_entities, va("print \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER")) ); trap->SendServerCommand( duelAgainst-g_entities, va("print \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER")) ); */ //Private duel announcements are now made globally because we only want one duel at a time. if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0) { trap->SendServerCommand( -1, va("cp \"%s %s %s!\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER"), duelAgainst->client->pers.netname) ); } else { //it was a draw, because we both managed to die in the same frame trap->SendServerCommand( -1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELTIE")) ); } } else { vec3_t vSub; float subLen = 0; VectorSubtract(ent->client->ps.origin, duelAgainst->client->ps.origin, vSub); subLen = VectorLength(vSub); if (subLen >= 1024) { ent->client->ps.duelInProgress = 0; duelAgainst->client->ps.duelInProgress = 0; G_AddEvent(ent, EV_PRIVATE_DUEL, 0); G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 0); trap->SendServerCommand( -1, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELSTOP")) ); } } } if (ent->client->doingThrow > level.time) { gentity_t *throwee = &g_entities[ent->client->throwingIndex]; if (!throwee->inuse || !throwee->client || throwee->health < 1 || throwee->client->sess.sessionTeam == TEAM_SPECTATOR || (throwee->client->ps.pm_flags & PMF_FOLLOW) || throwee->client->throwingIndex != ent->s.number) { ent->client->doingThrow = 0; ent->client->ps.forceHandExtend = HANDEXTEND_NONE; if (throwee->inuse && throwee->client) { throwee->client->ps.heldByClient = 0; throwee->client->beingThrown = 0; if (throwee->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN) { throwee->client->ps.forceHandExtend = HANDEXTEND_NONE; } } } } if (ent->client->beingThrown > level.time) { gentity_t *thrower = &g_entities[ent->client->throwingIndex]; if (!thrower->inuse || !thrower->client || thrower->health < 1 || thrower->client->sess.sessionTeam == TEAM_SPECTATOR || (thrower->client->ps.pm_flags & PMF_FOLLOW) || thrower->client->throwingIndex != ent->s.number) { ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; if (ent->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN) { ent->client->ps.forceHandExtend = HANDEXTEND_NONE; } if (thrower->inuse && thrower->client) { thrower->client->doingThrow = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_NONE; } } else if (thrower->inuse && thrower->client && thrower->ghoul2 && trap->G2API_HaveWeGhoul2Models(thrower->ghoul2)) { #if 0 int lHandBolt = trap->G2API_AddBolt(thrower->ghoul2, 0, "*l_hand"); int pelBolt = trap->G2API_AddBolt(thrower->ghoul2, 0, "pelvis"); if (lHandBolt != -1 && pelBolt != -1) #endif { float pDif = 40.0f; vec3_t boltOrg, pBoltOrg; vec3_t tAngles; vec3_t vDif; vec3_t entDir, otherAngles; vec3_t fwd, right; //Always look at the thrower. VectorSubtract( thrower->client->ps.origin, ent->client->ps.origin, entDir ); VectorCopy( ent->client->ps.viewangles, otherAngles ); otherAngles[YAW] = vectoyaw( entDir ); SetClientViewAngle( ent, otherAngles ); VectorCopy(thrower->client->ps.viewangles, tAngles); tAngles[PITCH] = tAngles[ROLL] = 0; //Get the direction between the pelvis and position of the hand #if 0 mdxaBone_t boltMatrix, pBoltMatrix; trap->G2API_GetBoltMatrix(thrower->ghoul2, 0, lHandBolt, &boltMatrix, tAngles, thrower->client->ps.origin, level.time, 0, thrower->modelScale); boltOrg[0] = boltMatrix.matrix[0][3]; boltOrg[1] = boltMatrix.matrix[1][3]; boltOrg[2] = boltMatrix.matrix[2][3]; trap->G2API_GetBoltMatrix(thrower->ghoul2, 0, pelBolt, &pBoltMatrix, tAngles, thrower->client->ps.origin, level.time, 0, thrower->modelScale); pBoltOrg[0] = pBoltMatrix.matrix[0][3]; pBoltOrg[1] = pBoltMatrix.matrix[1][3]; pBoltOrg[2] = pBoltMatrix.matrix[2][3]; #else //above tends to not work once in a while, for various reasons I suppose. VectorCopy(thrower->client->ps.origin, pBoltOrg); AngleVectors(tAngles, fwd, right, 0); boltOrg[0] = pBoltOrg[0] + fwd[0]*8 + right[0]*pDif; boltOrg[1] = pBoltOrg[1] + fwd[1]*8 + right[1]*pDif; boltOrg[2] = pBoltOrg[2]; #endif //G_TestLine(boltOrg, pBoltOrg, 0x0000ff, 50); VectorSubtract(ent->client->ps.origin, boltOrg, vDif); if (VectorLength(vDif) > 32.0f && (thrower->client->doingThrow - level.time) < 4500) { //the hand is too far away, and can no longer hold onto us, so escape. ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; thrower->client->doingThrow = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_NONE; G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav") ); ent->client->ps.forceDodgeAnim = 2; ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; ent->client->ps.forceHandExtendTime = level.time + 500; ent->client->ps.velocity[2] = 400; G_PreDefSound(ent->client->ps.origin, PDSOUND_FORCEJUMP); } else if ((client->beingThrown - level.time) < 4000) { //step into the next part of the throw, and go flying back float vScale = 400.0f; ent->client->ps.forceHandExtend = HANDEXTEND_POSTTHROWN; ent->client->ps.forceHandExtendTime = level.time + 1200; ent->client->ps.forceDodgeAnim = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_POSTTHROW; thrower->client->ps.forceHandExtendTime = level.time + 200; ent->client->ps.heldByClient = 0; ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; thrower->client->doingThrow = 0; AngleVectors(thrower->client->ps.viewangles, vDif, 0, 0); ent->client->ps.velocity[0] = vDif[0]*vScale; ent->client->ps.velocity[1] = vDif[1]*vScale; ent->client->ps.velocity[2] = 400; G_EntitySound( ent, CHAN_VOICE, G_SoundIndex("*pain100.wav") ); G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*jump1.wav") ); //Set the thrower as the "other killer", so if we die from fall/impact damage he is credited. ent->client->ps.otherKiller = thrower->s.number; ent->client->ps.otherKillerTime = level.time + 8000; ent->client->ps.otherKillerDebounceTime = level.time + 100; } else { //see if we can move to be next to the hand.. if it's not clear, break the throw. vec3_t intendedOrigin; trace_t tr; trace_t tr2; VectorSubtract(boltOrg, pBoltOrg, vDif); VectorNormalize(vDif); VectorClear(ent->client->ps.velocity); intendedOrigin[0] = pBoltOrg[0] + vDif[0]*pDif; intendedOrigin[1] = pBoltOrg[1] + vDif[1]*pDif; intendedOrigin[2] = thrower->client->ps.origin[2]; trap->Trace(&tr, intendedOrigin, ent->r.mins, ent->r.maxs, intendedOrigin, ent->s.number, ent->clipmask, qfalse, 0, 0); trap->Trace(&tr2, ent->client->ps.origin, ent->r.mins, ent->r.maxs, intendedOrigin, ent->s.number, CONTENTS_SOLID, qfalse, 0, 0); if (tr.fraction == 1.0 && !tr.startsolid && tr2.fraction == 1.0 && !tr2.startsolid) { VectorCopy(intendedOrigin, ent->client->ps.origin); if ((client->beingThrown - level.time) < 4800) { ent->client->ps.heldByClient = thrower->s.number+1; } } else { //if the guy can't be put here then it's time to break the throw off. ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; thrower->client->doingThrow = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_NONE; G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav") ); ent->client->ps.forceDodgeAnim = 2; ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; ent->client->ps.forceHandExtendTime = level.time + 500; ent->client->ps.velocity[2] = 400; G_PreDefSound(ent->client->ps.origin, PDSOUND_FORCEJUMP); } } } } } else if (ent->client->ps.heldByClient) { ent->client->ps.heldByClient = 0; } /* if ( client->ps.powerups[PW_HASTE] ) { client->ps.speed *= 1.3; } */ //Will probably never need this again, since we have g2 properly serverside now. //But just in case. /* if (client->ps.usingATST && ent->health > 0) { //we have special shot clip boxes as an ATST ent->r.contents |= CONTENTS_NOSHOT; ATST_ManageDamageBoxes(ent); } else { ent->r.contents &= ~CONTENTS_NOSHOT; client->damageBoxHandle_Head = 0; client->damageBoxHandle_RLeg = 0; client->damageBoxHandle_LLeg = 0; } */ //rww - moved this stuff into the pmove code so that it's predicted properly //BG_AdjustClientSpeed(&client->ps, &client->pers.cmd, level.time); // set up for pmove oldEventSequence = client->ps.eventSequence; memset (&pmove, 0, sizeof(pmove)); if ( ent->flags & FL_FORCE_GESTURE ) { ent->flags &= ~FL_FORCE_GESTURE; ent->client->pers.cmd.buttons |= BUTTON_GESTURE; } if (ent->client && ent->client->ps.fallingToDeath && (level.time - FALL_FADE_TIME) > ent->client->ps.fallingToDeath) { //die! if (ent->health > 0) { gentity_t *otherKiller = ent; if (ent->client->ps.otherKillerTime > level.time && ent->client->ps.otherKiller != ENTITYNUM_NONE) { otherKiller = &g_entities[ent->client->ps.otherKiller]; if (!otherKiller->inuse) { otherKiller = ent; } } G_Damage(ent, otherKiller, otherKiller, NULL, ent->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_FALLING); //player_die(ent, ent, ent, 100000, MOD_FALLING); // if (!ent->NPC) // { // ClientRespawn(ent); // } // ent->client->ps.fallingToDeath = 0; G_MuteSound(ent->s.number, CHAN_VOICE); //stop screaming, because you are dead! } } if (ent->client->ps.otherKillerTime > level.time && ent->client->ps.groundEntityNum != ENTITYNUM_NONE && ent->client->ps.otherKillerDebounceTime < level.time) { ent->client->ps.otherKillerTime = 0; ent->client->ps.otherKiller = ENTITYNUM_NONE; } else if (ent->client->ps.otherKillerTime > level.time && ent->client->ps.groundEntityNum == ENTITYNUM_NONE) { if (ent->client->ps.otherKillerDebounceTime < (level.time + 100)) { ent->client->ps.otherKillerDebounceTime = level.time + 100; } } // WP_ForcePowersUpdate( ent, msec, ucmd); //update any active force powers // WP_SaberPositionUpdate(ent, ucmd); //check the server-side saber point, do apprioriate server-side actions (effects are cs-only) //NOTE: can't put USE here *before* PMove!! if ( ent->client->ps.useDelay > level.time && ent->client->ps.m_iVehicleNum ) {//when in a vehicle, debounce the use... ucmd->buttons &= ~BUTTON_USE; } //FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) G_AddPushVecToUcmd( ent, ucmd ); //play/stop any looping sounds tied to controlled movement G_CheckMovingLoopingSounds( ent, ucmd ); pmove.ps = &client->ps; pmove.cmd = *ucmd; if ( pmove.ps->pm_type == PM_DEAD ) { pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; } else if ( ent->r.svFlags & SVF_BOT ) { pmove.tracemask = MASK_PLAYERSOLID | CONTENTS_MONSTERCLIP; } else { pmove.tracemask = MASK_PLAYERSOLID; } pmove.trace = SV_PMTrace; pmove.pointcontents = trap->PointContents; pmove.debugLevel = g_debugMove.integer; pmove.noFootsteps = (dmflags.integer & DF_NO_FOOTSTEPS) > 0; pmove.pmove_fixed = pmove_fixed.integer | client->pers.pmoveFixed; pmove.pmove_msec = pmove_msec.integer; pmove.pmove_float = pmove_float.integer; pmove.animations = bgAllAnims[ent->localAnimIndex].anims;//NULL; //rww - bgghoul2 pmove.ghoul2 = NULL; #ifdef _DEBUG if (g_disableServerG2.integer) { } else #endif if (ent->ghoul2) { if (ent->localAnimIndex > 1) { //if it isn't humanoid then we will be having none of this. pmove.ghoul2 = NULL; } else { pmove.ghoul2 = ent->ghoul2; pmove.g2Bolts_LFoot = trap->G2API_AddBolt(ent->ghoul2, 0, "*l_leg_foot"); pmove.g2Bolts_RFoot = trap->G2API_AddBolt(ent->ghoul2, 0, "*r_leg_foot"); } } //point the saber data to the right place #if 0 k = 0; while (k < MAX_SABERS) { if (ent->client->saber[k].model[0]) { pm.saber[k] = &ent->client->saber[k]; } else { pm.saber[k] = NULL; } k++; } #endif //I'll just do this every frame in case the scale changes in realtime (don't need to update the g2 inst for that) VectorCopy(ent->modelScale, pmove.modelScale); //rww end bgghoul2 pmove.gametype = level.gametype; pmove.debugMelee = g_debugMelee.integer; pmove.stepSlideFix = g_stepSlideFix.integer; pmove.noSpecMove = g_noSpecMove.integer; pmove.nonHumanoid = (ent->localAnimIndex > 0); VectorCopy( client->ps.origin, client->oldOrigin ); /* if (level.intermissionQueued != 0 && g_singlePlayer.integer) { if ( level.time - level.intermissionQueued >= 1000 ) { pm.cmd.buttons = 0; pm.cmd.forwardmove = 0; pm.cmd.rightmove = 0; pm.cmd.upmove = 0; if ( level.time - level.intermissionQueued >= 2000 && level.time - level.intermissionQueued <= 2500 ) { trap->SendConsoleCommand( EXEC_APPEND, "centerview\n"); } ent->client->ps.pm_type = PM_SPINTERMISSION; } } */ //Set up bg entity data pmove.baseEnt = (bgEntity_t *)g_entities; pmove.entSize = sizeof(gentity_t); if (ent->client->ps.saberLockTime > level.time) { gentity_t *blockOpp = &g_entities[ent->client->ps.saberLockEnemy]; if (blockOpp && blockOpp->inuse && blockOpp->client) { vec3_t lockDir, lockAng; //VectorClear( ent->client->ps.velocity ); VectorSubtract( blockOpp->r.currentOrigin, ent->r.currentOrigin, lockDir ); //lockAng[YAW] = vectoyaw( defDir ); vectoangles(lockDir, lockAng); SetClientViewAngle( ent, lockAng ); } if ( ent->client->ps.saberLockHitCheckTime < level.time ) {//have moved to next frame since last lock push ent->client->ps.saberLockHitCheckTime = level.time;//so we don't push more than once per server frame if ( ( ent->client->buttons & BUTTON_ATTACK ) && ! ( ent->client->oldbuttons & BUTTON_ATTACK ) ) { if ( ent->client->ps.saberLockHitIncrementTime < level.time ) {//have moved to next frame since last saberlock attack button press int lockHits = 0; ent->client->ps.saberLockHitIncrementTime = level.time;//so we don't register an attack key press more than once per server frame //NOTE: FP_SABER_OFFENSE level already taken into account in PM_SaberLocked if ( (ent->client->ps.fd.forcePowersActive&(1<<FP_RAGE)) ) {//raging: push harder lockHits = 1+ent->client->ps.fd.forcePowerLevel[FP_RAGE]; } else {//normal attack switch ( ent->client->ps.fd.saberAnimLevel ) { case SS_FAST: lockHits = 1; break; case SS_MEDIUM: case SS_TAVION: case SS_DUAL: case SS_STAFF: lockHits = 2; break; case SS_STRONG: case SS_DESANN: lockHits = 3; break; } } if ( ent->client->ps.fd.forceRageRecoveryTime > level.time && Q_irand( 0, 1 ) ) {//finished raging: weak lockHits -= 1; } lockHits += ent->client->saber[0].lockBonus; if ( ent->client->saber[1].model[0] && !ent->client->ps.saberHolstered ) { lockHits += ent->client->saber[1].lockBonus; } ent->client->ps.saberLockHits += lockHits; if ( g_saberLockRandomNess.integer ) { ent->client->ps.saberLockHits += Q_irand( 0, g_saberLockRandomNess.integer ); if ( ent->client->ps.saberLockHits < 0 ) { ent->client->ps.saberLockHits = 0; } } } } if ( ent->client->ps.saberLockHits > 0 ) { if ( !ent->client->ps.saberLockAdvance ) { ent->client->ps.saberLockHits--; } ent->client->ps.saberLockAdvance = qtrue; } } } else { ent->client->ps.saberLockFrame = 0; //check for taunt if ( (pmove.cmd.generic_cmd == GENCMD_ENGAGE_DUEL) && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) ) {//already in a duel, make it a taunt command pmove.cmd.buttons |= BUTTON_GESTURE; } } if (ent->s.number >= MAX_CLIENTS) { VectorCopy(ent->r.mins, pmove.mins); VectorCopy(ent->r.maxs, pmove.maxs); #if 1 if (ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle ) { if ( ent->m_pVehicle->m_pPilot) { //vehicles want to use their last pilot ucmd I guess if ((level.time - ent->m_pVehicle->m_ucmd.serverTime) > 2000) { //Previous owner disconnected, maybe ent->m_pVehicle->m_ucmd.serverTime = level.time; ent->client->ps.commandTime = level.time-100; msec = 100; } memcpy(&pmove.cmd, &ent->m_pVehicle->m_ucmd, sizeof(usercmd_t)); //no veh can strafe pmove.cmd.rightmove = 0; //no crouching or jumping! pmove.cmd.upmove = 0; //NOTE: button presses were getting lost! assert(g_entities[ent->m_pVehicle->m_pPilot->s.number].client); pmove.cmd.buttons = (g_entities[ent->m_pVehicle->m_pPilot->s.number].client->pers.cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)); } if ( ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) { if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//ATST crushes anything underneath it gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; if ( under && under->health && under->takedamage ) { vec3_t down = {0,0,-1}; //FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin G_Damage( under, ent, ent, down, under->r.currentOrigin, 100, 0, MOD_CRUSH ); } } } } #endif } Pmove (&pmove); if (ent->client->solidHack) { if (ent->client->solidHack > level.time) { //whee! ent->r.contents = 0; } else { ent->r.contents = CONTENTS_BODY; ent->client->solidHack = 0; } } if ( ent->NPC ) { VectorCopy( ent->client->ps.viewangles, ent->r.currentAngles ); } if (pmove.checkDuelLoss) { if (pmove.checkDuelLoss > 0 && (pmove.checkDuelLoss <= MAX_CLIENTS || (pmove.checkDuelLoss < (MAX_GENTITIES-1) && g_entities[pmove.checkDuelLoss-1].s.eType == ET_NPC) ) ) { gentity_t *clientLost = &g_entities[pmove.checkDuelLoss-1]; if (clientLost && clientLost->inuse && clientLost->client && Q_irand(0, 40) > clientLost->health) { vec3_t attDir; VectorSubtract(ent->client->ps.origin, clientLost->client->ps.origin, attDir); VectorNormalize(attDir); VectorClear(clientLost->client->ps.velocity); clientLost->client->ps.forceHandExtend = HANDEXTEND_NONE; clientLost->client->ps.forceHandExtendTime = 0; gGAvoidDismember = 1; G_Damage(clientLost, ent, ent, attDir, clientLost->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_SABER); if (clientLost->health < 1) { gGAvoidDismember = 2; G_CheckForDismemberment(clientLost, ent, clientLost->client->ps.origin, 999, (clientLost->client->ps.legsAnim), qfalse); } gGAvoidDismember = 0; } else if (clientLost && clientLost->inuse && clientLost->client && clientLost->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN && clientLost->client->ps.saberEntityNum) { //if we didn't knock down it was a circle lock. So as punishment, make them lose their saber and go into a proper anim saberCheckKnockdown_DuelLoss(&g_entities[clientLost->client->ps.saberEntityNum], clientLost, ent); } } pmove.checkDuelLoss = 0; } if (pmove.cmd.generic_cmd && (pmove.cmd.generic_cmd != ent->client->lastGenCmd || ent->client->lastGenCmdTime < level.time)) { ent->client->lastGenCmd = pmove.cmd.generic_cmd; if (pmove.cmd.generic_cmd != GENCMD_FORCE_THROW && pmove.cmd.generic_cmd != GENCMD_FORCE_PULL) { //these are the only two where you wouldn't care about a delay between ent->client->lastGenCmdTime = level.time + 300; //default 100ms debounce between issuing the same command. } switch(pmove.cmd.generic_cmd) { case 0: break; case GENCMD_SABERSWITCH: Cmd_ToggleSaber_f(ent); break; case GENCMD_ENGAGE_DUEL: if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) {//already in a duel, made it a taunt command } else { Cmd_EngageDuel_f(ent); } break; case GENCMD_FORCE_HEAL: ForceHeal(ent); break; case GENCMD_FORCE_SPEED: ForceSpeed(ent, 0); break; case GENCMD_FORCE_THROW: ForceThrow(ent, qfalse); break; case GENCMD_FORCE_PULL: ForceThrow(ent, qtrue); break; case GENCMD_FORCE_DISTRACT: ForceTelepathy(ent); break; case GENCMD_FORCE_RAGE: ForceRage(ent); break; case GENCMD_FORCE_PROTECT: ForceProtect(ent); break; case GENCMD_FORCE_ABSORB: ForceAbsorb(ent); break; case GENCMD_FORCE_HEALOTHER: ForceTeamHeal(ent); break; case GENCMD_FORCE_FORCEPOWEROTHER: ForceTeamForceReplenish(ent); break; case GENCMD_FORCE_SEEING: ForceSeeing(ent); break; case GENCMD_USE_SEEKER: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SEEKER)) && G_ItemUsable(&ent->client->ps, HI_SEEKER) ) { ItemUse_Seeker(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_SEEKER, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SEEKER); } break; case GENCMD_USE_FIELD: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SHIELD)) && G_ItemUsable(&ent->client->ps, HI_SHIELD) ) { ItemUse_Shield(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_SHIELD, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SHIELD); } break; case GENCMD_USE_BACTA: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC)) && G_ItemUsable(&ent->client->ps, HI_MEDPAC) ) { ItemUse_MedPack(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_MEDPAC, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_MEDPAC); } break; case GENCMD_USE_BACTABIG: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC_BIG)) && G_ItemUsable(&ent->client->ps, HI_MEDPAC_BIG) ) { ItemUse_MedPack_Big(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_MEDPAC_BIG, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_MEDPAC_BIG); } break; case GENCMD_USE_ELECTROBINOCULARS: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) && G_ItemUsable(&ent->client->ps, HI_BINOCULARS) ) { ItemUse_Binoculars(ent); if (ent->client->ps.zoomMode == 0) { G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1); } else { G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2); } } break; case GENCMD_ZOOM: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) && G_ItemUsable(&ent->client->ps, HI_BINOCULARS) ) { ItemUse_Binoculars(ent); if (ent->client->ps.zoomMode == 0) { G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1); } else { G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2); } } break; case GENCMD_USE_SENTRY: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SENTRY_GUN)) && G_ItemUsable(&ent->client->ps, HI_SENTRY_GUN) ) { ItemUse_Sentry(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_SENTRY_GUN, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SENTRY_GUN); } break; case GENCMD_USE_JETPACK: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) && G_ItemUsable(&ent->client->ps, HI_JETPACK) ) { ItemUse_Jetpack(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_JETPACK, 0); /* if (ent->client->ps.zoomMode == 0) { G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1); } else { G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2); } */ } break; case GENCMD_USE_HEALTHDISP: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_HEALTHDISP)) && G_ItemUsable(&ent->client->ps, HI_HEALTHDISP) ) { //ItemUse_UseDisp(ent, HI_HEALTHDISP); G_AddEvent(ent, EV_USE_ITEM0+HI_HEALTHDISP, 0); } break; case GENCMD_USE_AMMODISP: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_AMMODISP)) && G_ItemUsable(&ent->client->ps, HI_AMMODISP) ) { //ItemUse_UseDisp(ent, HI_AMMODISP); G_AddEvent(ent, EV_USE_ITEM0+HI_AMMODISP, 0); } break; case GENCMD_USE_EWEB: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_EWEB)) && G_ItemUsable(&ent->client->ps, HI_EWEB) ) { ItemUse_UseEWeb(ent); G_AddEvent(ent, EV_USE_ITEM0+HI_EWEB, 0); } break; case GENCMD_USE_CLOAK: if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_CLOAK)) && G_ItemUsable(&ent->client->ps, HI_CLOAK) ) { if ( ent->client->ps.powerups[PW_CLOAKED] ) {//decloak Jedi_Decloak( ent ); } else {//cloak Jedi_Cloak( ent ); } } break; case GENCMD_SABERATTACKCYCLE: Cmd_SaberAttackCycle_f(ent); break; case GENCMD_TAUNT: G_SetTauntAnim( ent, TAUNT_TAUNT ); break; case GENCMD_BOW: G_SetTauntAnim( ent, TAUNT_BOW ); break; case GENCMD_MEDITATE: G_SetTauntAnim( ent, TAUNT_MEDITATE ); break; case GENCMD_FLOURISH: G_SetTauntAnim( ent, TAUNT_FLOURISH ); break; case GENCMD_GLOAT: G_SetTauntAnim( ent, TAUNT_GLOAT ); break; default: break; } } // save results of pmove if ( ent->client->ps.eventSequence != oldEventSequence ) { ent->eventTime = level.time; } if (g_smoothClients.integer) { BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse ); //rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up. } else { BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qfalse ); } if (isNPC) { ent->s.eType = ET_NPC; } SendPendingPredictableEvents( &ent->client->ps ); if ( !( ent->client->ps.eFlags & EF_FIRING ) ) { client->fireHeld = qfalse; // for grapple } // use the snapped origin for linking so it matches client predicted versions VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin ); if (ent->s.eType != ET_NPC || ent->s.NPC_class != CLASS_VEHICLE || !ent->m_pVehicle || !ent->m_pVehicle->m_iRemovedSurfaces) { //let vehicles that are getting broken apart do their own crazy sizing stuff VectorCopy (pmove.mins, ent->r.mins); VectorCopy (pmove.maxs, ent->r.maxs); } ent->waterlevel = pmove.waterlevel; ent->watertype = pmove.watertype; // execute client events ClientEvents( ent, oldEventSequence ); if ( pmove.useEvent ) { //TODO: Use // TryUse( ent ); } if ((ent->client->pers.cmd.buttons & BUTTON_USE) && ent->client->ps.useDelay < level.time) { TryUse(ent); ent->client->ps.useDelay = level.time + 100; } // link entity now, after any personal teleporters have been used trap->LinkEntity ((sharedEntity_t *)ent); if ( !ent->client->noclip ) { G_TouchTriggers( ent ); } // NOTE: now copy the exact origin over otherwise clients can be snapped into solid VectorCopy( ent->client->ps.origin, ent->r.currentOrigin ); //test for solid areas in the AAS file // BotTestAAS(ent->r.currentOrigin); // touch other objects ClientImpacts( ent, &pmove ); // save results of triggers and client events if (ent->client->ps.eventSequence != oldEventSequence) { ent->eventTime = level.time; } // swap and latch button actions client->oldbuttons = client->buttons; client->buttons = ucmd->buttons; client->latched_buttons |= client->buttons & ~client->oldbuttons; // G_VehicleAttachDroidUnit( ent ); // Did we kick someone in our pmove sequence? if (client->ps.forceKickFlip) { gentity_t *faceKicked = &g_entities[client->ps.forceKickFlip-1]; if (faceKicked && faceKicked->client && (!OnSameTeam(ent, faceKicked) || g_friendlyFire.integer) && (!faceKicked->client->ps.duelInProgress || faceKicked->client->ps.duelIndex == ent->s.number) && (!ent->client->ps.duelInProgress || ent->client->ps.duelIndex == faceKicked->s.number)) { if ( faceKicked && faceKicked->client && faceKicked->health && faceKicked->takedamage ) {//push them away and do pain vec3_t oppDir; int strength = (int)VectorNormalize2( client->ps.velocity, oppDir ); strength *= 0.05; VectorScale( oppDir, -1, oppDir ); G_Damage( faceKicked, ent, ent, oppDir, client->ps.origin, strength, DAMAGE_NO_ARMOR, MOD_MELEE ); if ( faceKicked->client->ps.weapon != WP_SABER || faceKicked->client->ps.fd.saberAnimLevel != FORCE_LEVEL_3 || (!BG_SaberInAttack(faceKicked->client->ps.saberMove) && !PM_SaberInStart(faceKicked->client->ps.saberMove) && !PM_SaberInReturn(faceKicked->client->ps.saberMove) && !PM_SaberInTransition(faceKicked->client->ps.saberMove)) ) { if (faceKicked->health > 0 && faceKicked->client->ps.stats[STAT_HEALTH] > 0 && faceKicked->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) { if (BG_KnockDownable(&faceKicked->client->ps) && Q_irand(1, 10) <= 3) { //only actually knock over sometimes, but always do velocity hit faceKicked->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; faceKicked->client->ps.forceHandExtendTime = level.time + 1100; faceKicked->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim } faceKicked->client->ps.otherKiller = ent->s.number; faceKicked->client->ps.otherKillerTime = level.time + 5000; faceKicked->client->ps.otherKillerDebounceTime = level.time + 100; faceKicked->client->ps.velocity[0] = oppDir[0]*(strength*40); faceKicked->client->ps.velocity[1] = oppDir[1]*(strength*40); faceKicked->client->ps.velocity[2] = 200; } } G_Sound( faceKicked, CHAN_AUTO, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); } } client->ps.forceKickFlip = 0; } // check for respawning if ( client->ps.stats[STAT_HEALTH] <= 0 && !(client->ps.eFlags2&EF2_HELD_BY_MONSTER)//can't respawn while being eaten && ent->s.eType != ET_NPC ) { // wait for the attack button to be pressed if ( level.time > client->respawnTime && !gDoSlowMoDuel ) { // forcerespawn is to prevent users from waiting out powerups int forceRes = g_forceRespawn.integer; if (level.gametype == GT_POWERDUEL) { forceRes = 1; } else if (level.gametype == GT_SIEGE && g_siegeRespawn.integer) { //wave respawning on forceRes = 1; } if ( forceRes > 0 && ( level.time - client->respawnTime ) > forceRes * 1000 ) { ClientRespawn( ent ); return; } // pressing attack or use is the normal respawn method if ( ucmd->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) ) { ClientRespawn( ent ); } } else if (gDoSlowMoDuel) { client->respawnTime = level.time + 1000; } return; } // perform once-a-second actions ClientTimerActions( ent, msec ); G_UpdateClientBroadcasts ( ent ); //try some idle anims on ent if getting no input and not moving for some time G_CheckClientIdle( ent, ucmd ); // This code was moved here from clientThink to fix a problem with g_synchronousClients // being set to 1 when in vehicles. if ( ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum ) {//driving a vehicle //run it if (g_entities[ent->client->ps.m_iVehicleNum].inuse && g_entities[ent->client->ps.m_iVehicleNum].client) { ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd); } else { //vehicle no longer valid? ent->client->ps.m_iVehicleNum = 0; } } } /* ================== G_CheckClientTimeouts Checks whether a client has exceded any timeouts and act accordingly ================== */ void G_CheckClientTimeouts ( gentity_t *ent ) { // Only timeout supported right now is the timeout to spectator mode if ( !g_timeouttospec.integer ) { return; } // Already a spectator, no need to boot them to spectator if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { return; } // See how long its been since a command was received by the client and if its // longer than the timeout to spectator then force this client into spectator mode if ( level.time - ent->client->pers.cmd.serverTime > g_timeouttospec.integer * 1000 ) { SetTeam ( ent, "spectator" ); } } /* ================== ClientThink A new command has arrived from the client ================== */ void ClientThink( int clientNum, usercmd_t *ucmd ) { gentity_t *ent; ent = g_entities + clientNum; if (clientNum < MAX_CLIENTS) { trap->GetUsercmd( clientNum, &ent->client->pers.cmd ); } // mark the time we got info, so we can display the // phone jack if they don't get any for a while ent->client->lastCmdTime = level.time; if (ucmd) { ent->client->pers.cmd = *ucmd; } /* This was moved to clientthink_real, but since its sort of a risky change i left it here for now as a more concrete reference - BSD if ( clientNum < MAX_CLIENTS && ent->client->ps.m_iVehicleNum ) {//driving a vehicle if (g_entities[ent->client->ps.m_iVehicleNum].client) { gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum]; if (veh->m_pVehicle && veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent) { //only take input from the pilot... veh->client->ps.commandTime = ent->client->ps.commandTime; memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t)); if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK ) { //forced input if "chat bubble" is up veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK; veh->m_pVehicle->m_ucmd.forwardmove = 0; veh->m_pVehicle->m_ucmd.rightmove = 0; veh->m_pVehicle->m_ucmd.upmove = 0; } } } } */ if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) { ClientThink_real( ent ); } // vehicles are clients and when running synchronous they still need to think here // so special case them. else if ( clientNum >= MAX_CLIENTS ) { ClientThink_real( ent ); } /* This was moved to clientthink_real, but since its sort of a risky change i left it here for now as a more concrete reference - BSD if ( clientNum < MAX_CLIENTS && ent->client->ps.m_iVehicleNum ) {//driving a vehicle //run it if (g_entities[ent->client->ps.m_iVehicleNum].inuse && g_entities[ent->client->ps.m_iVehicleNum].client) { ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd); } else { //vehicle no longer valid? ent->client->ps.m_iVehicleNum = 0; } } */ } void G_RunClient( gentity_t *ent ) { // force client updates if they're not sending packets at roughly 4hz if ( !(ent->r.svFlags & SVF_BOT) && g_forceClientUpdateRate.integer && ent->client->lastCmdTime < level.time - g_forceClientUpdateRate.integer ) { trap->GetUsercmd( ent-g_entities, &ent->client->pers.cmd ); ent->client->lastCmdTime = level.time; // fill with seemingly valid data ent->client->pers.cmd.serverTime = level.time; ent->client->pers.cmd.buttons = 0; ent->client->pers.cmd.forwardmove = ent->client->pers.cmd.rightmove = ent->client->pers.cmd.upmove = 0; ClientThink_real( ent ); return; } if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) { return; } ent->client->pers.cmd.serverTime = level.time; ClientThink_real( ent ); } /* ================== SpectatorClientEndFrame ================== */ void SpectatorClientEndFrame( gentity_t *ent ) { gclient_t *cl; if (ent->s.eType == ET_NPC) { assert(0); return; } // if we are doing a chase cam or a remote view, grab the latest info if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) { int clientNum;//, flags; clientNum = ent->client->sess.spectatorClient; // team follow1 and team follow2 go to whatever clients are playing if ( clientNum == -1 ) { clientNum = level.follow1; } else if ( clientNum == -2 ) { clientNum = level.follow2; } if ( clientNum >= 0 ) { cl = &level.clients[ clientNum ]; if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR ) { //flags = (cl->mGameFlags & ~(PSG_VOTED | PSG_TEAMVOTED)) | (ent->client->mGameFlags & (PSG_VOTED | PSG_TEAMVOTED)); //ent->client->mGameFlags = flags; ent->client->ps.eFlags = cl->ps.eFlags; ent->client->ps = cl->ps; ent->client->ps.pm_flags |= PMF_FOLLOW; return; } else { // drop them to free spectators unless they are dedicated camera followers if ( ent->client->sess.spectatorClient >= 0 ) { ent->client->sess.spectatorState = SPECTATOR_FREE; ClientBegin( ent->client - level.clients, qtrue ); } } } } if ( ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD ) { ent->client->ps.pm_flags |= PMF_SCOREBOARD; } else { ent->client->ps.pm_flags &= ~PMF_SCOREBOARD; } } /* ============== ClientEndFrame Called at the end of each server frame for each connected client A fast client will have multiple ClientThink for each ClientEdFrame, while a slow client may have multiple ClientEndFrame between ClientThink. ============== */ void ClientEndFrame( gentity_t *ent ) { int i; qboolean isNPC = qfalse; if (ent->s.eType == ET_NPC) { isNPC = qtrue; } if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { SpectatorClientEndFrame( ent ); return; } // turn off any expired powerups for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { if ( ent->client->ps.powerups[ i ] < level.time ) { ent->client->ps.powerups[ i ] = 0; } } // save network bandwidth #if 0 if ( !g_synchronousClients->integer && (ent->client->ps.pm_type == PM_NORMAL || ent->client->ps.pm_type == PM_JETPACK || ent->client->ps.pm_type == PM_FLOAT) ) { // FIXME: this must change eventually for non-sync demo recording VectorClear( ent->client->ps.viewangles ); } #endif // // If the end of unit layout is displayed, don't give // the player any normal movement attributes // if ( level.intermissiontime ) { if ( ent->s.number < MAX_CLIENTS || ent->client->NPC_class == CLASS_VEHICLE ) {//players and vehicles do nothing in intermissions return; } } // burn from lava, etc P_WorldEffects (ent); // apply all the damage taken this frame P_DamageFeedback (ent); // add the EF_CONNECTION flag if we haven't gotten commands recently if ( level.time - ent->client->lastCmdTime > 1000 ) ent->client->ps.eFlags |= EF_CONNECTION; else ent->client->ps.eFlags &= ~EF_CONNECTION; ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... G_SetClientSound (ent); // set the latest infor if (g_smoothClients.integer) { BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse ); //rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up. } else { BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qfalse ); } if (isNPC) { ent->s.eType = ET_NPC; } SendPendingPredictableEvents( &ent->client->ps ); // set the bit for the reachability area the client is currently in // i = trap->AAS_PointReachabilityAreaIndex( ent->client->ps.origin ); // ent->client->areabits[i >> 3] |= 1 << (i & 7); }
412
0.991285
1
0.991285
game-dev
MEDIA
0.988896
game-dev
0.99549
1
0.99549
hieki-chan/Supermarket-Simulator-Prototype
3,769
Library/PackageCache/com.unity.2d.sprite@1.0.0/Editor/SpriteEditorModule/SpriteFrameModule/SpritePolygonModeModule.cs
using UnityEngine; using System.Collections.Generic; namespace UnityEditor.U2D.Sprites { [RequireSpriteDataProvider(typeof(ISpriteOutlineDataProvider), typeof(ITextureDataProvider))] internal partial class SpritePolygonModeModule : SpriteFrameModuleBase { List<List<Vector2[]>> m_Outline; public SpritePolygonModeModule(ISpriteEditor sw, IEventSystem es, IUndoSystem us, IAssetDatabase ad) : base("Sprite Polygon Mode Editor", sw, es, us, ad) {} // ISpriteEditorModule implemenation public override void OnModuleActivate() { base.OnModuleActivate(); AddMainUI(spriteEditor.GetMainVisualContainer()); m_Outline = new List<List<Vector2[]>>(); for (int i = 0; i < m_RectsCache.spriteRects.Count; ++i) { var rect = m_RectsCache.spriteRects[i]; m_Outline.Add(spriteEditor.GetDataProvider<ISpriteOutlineDataProvider>().GetOutlines(rect.spriteID)); } showChangeShapeWindow = polygonSprite; if (polygonSprite) DeterminePolygonSides(); } public override bool CanBeActivated() { return SpriteFrameModule.GetSpriteImportMode(spriteEditor.GetDataProvider<ISpriteEditorDataProvider>()) == SpriteImportMode.Polygon; } private bool polygonSprite { get { return spriteImportMode == SpriteImportMode.Polygon; } } private void DeterminePolygonSides() { if (polygonSprite && m_RectsCache.spriteRects.Count == 1 && m_Outline.Count == 1 && m_Outline[0].Count == 1) { polygonSides = m_Outline[0][0].Length; } else // If for reasons we cannot determine the sides of the polygon, fall back to 0 (Square) polygonSides = 0; ViewUpdateSideCountField(); } public int GetPolygonSideCount() { DeterminePolygonSides(); return polygonSides; } public int polygonSides { get; set; } public List<Vector2[]> GetSpriteOutlineAt(int i) { return m_Outline[i]; } public void GeneratePolygonOutline() { for (int i = 0; i < m_RectsCache.spriteRects.Count; i++) { SpriteRect currentRect = m_RectsCache.spriteRects[i]; var result = UnityEditor.Sprites.SpriteUtility.GeneratePolygonOutlineVerticesOfSize(polygonSides, (int)currentRect.rect.width, (int)currentRect.rect.height); m_Outline.Clear(); var newOutlineList = new List<Vector2[]>(); newOutlineList.Add(result); m_Outline.Add(newOutlineList); spriteEditor.SetDataModified(); } Repaint(); } public override bool ApplyRevert(bool apply) { var outlineProvider = spriteEditor.GetDataProvider<ISpriteOutlineDataProvider>(); if (apply) { for (int i = 0; i < m_RectsCache.spriteRects.Count && i < m_Outline.Count; ++i) outlineProvider.SetOutlines(m_RectsCache.spriteRects[i].spriteID, m_Outline[i]); } else { m_Outline.Clear(); for (int i = 0; i < m_RectsCache.spriteRects.Count; ++i) m_Outline.Add(outlineProvider.GetOutlines(m_RectsCache.spriteRects[i].spriteID)); DeterminePolygonSides(); ViewUpdateSideCountField(); } return base.ApplyRevert(apply); } } }
412
0.9246
1
0.9246
game-dev
MEDIA
0.713894
game-dev,graphics-rendering
0.955638
1
0.955638
amethyst/amethyst
3,509
examples/prefab/main.rs
//! Demonstrates loading prefabs using the Amethyst engine. use amethyst::{ assets::{ prefab::{legion_prefab, register_component_type, serde_diff, Prefab, SerdeDiff}, DefaultLoader, Handle, Loader, LoaderBundle, }, core::{transform::TransformBundle, Time}, prelude::*, renderer::{ plugins::{RenderShaded3D, RenderToWindow}, rendy::hal::command::ClearColor, types::DefaultBackend, RenderingBundle, }, utils::application_root_dir, Error, }; use serde::{Deserialize, Serialize}; use type_uuid::TypeUuid; #[derive(TypeUuid, Serialize, Deserialize, SerdeDiff, Clone, Default, Debug)] #[uuid = "f5780013-bae4-49f0-ac0e-a108ff52fec0"] struct Position2D { position: Vec<f32>, } register_component_type!(Position2D); struct AssetsExample { prefab_handle: Option<Handle<Prefab>>, } impl SimpleState for AssetsExample { fn update(&mut self, data: &mut StateData<'_, GameData>) -> SimpleTrans { if self.prefab_handle.is_none() { log::info!("No prefab loaded, loading now..."); let loader = data.resources.get_mut::<DefaultLoader>().unwrap(); let prefab_handle: Handle<Prefab> = loader.load("prefab/test.prefab"); self.prefab_handle = Some(prefab_handle.clone()); data.world.push((prefab_handle,)); } let time = data.resources.get::<Time>().unwrap(); if time.frame_number() % 60 == 0 { let mut query = <(Entity,)>::query(); let entities: Vec<Entity> = query.iter(data.world).map(|(ent,)| *ent).collect(); for entity in entities { if let Some(entry) = data.world.entry(entity) { log::info!("{:?}: {:?}", entity, entry.archetype()); if let Ok(pos) = entry.get_component::<Position2D>() { log::info!("{:?}", pos); } } } } Trans::None } } /// Wrapper around the main, so we can return errors easily. fn main() -> Result<(), Error> { let config = amethyst::LoggerConfig { level_filter: amethyst::LogLevelFilter::Debug, module_levels: vec![ ( "amethyst_assets".to_string(), amethyst::LogLevelFilter::Trace, ), ("distill_daemon".to_string(), amethyst::LogLevelFilter::Warn), ("distill_loader".to_string(), amethyst::LogLevelFilter::Warn), ], ..Default::default() }; amethyst::start_logger(config); let app_root = application_root_dir()?; // Add our meshes directory to the asset loader. let assets_dir = app_root.join("assets"); let display_config_path = app_root.join("config/display.ron"); let mut dispatcher_builder = DispatcherBuilder::default(); dispatcher_builder .add_bundle(LoaderBundle) .add_bundle(TransformBundle) .add_bundle( RenderingBundle::<DefaultBackend>::new() .with_plugin( RenderToWindow::from_config_path(display_config_path)?.with_clear(ClearColor { float32: [0.34, 0.36, 0.52, 1.0], }), ) .with_plugin(RenderShaded3D::default()), ); let game = Application::new( assets_dir, AssetsExample { prefab_handle: None, }, dispatcher_builder, )?; game.run(); Ok(()) }
412
0.936967
1
0.936967
game-dev
MEDIA
0.778618
game-dev
0.925693
1
0.925693
arianne/marauroa
2,664
src/marauroa/server/game/dbcommand/LogGameEventCommand.java
/*************************************************************************** * (C) Copyright 2009-2020 - Marauroa * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package marauroa.server.game.dbcommand; import java.sql.SQLException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import marauroa.server.db.DBTransaction; import marauroa.server.db.command.AbstractDBCommand; import marauroa.server.game.db.DAORegister; import marauroa.server.game.db.GameEventDAO; import marauroa.server.game.rp.GameEvent; /** * logs gameEvents * * @author hendrik */ public class LogGameEventCommand extends AbstractDBCommand { private final List<GameEvent> gameEvents; private String source; private String event; private String[] params; /** * creates a new LogGameEventCommand. * * @param gameEvents list of GameEvent */ public LogGameEventCommand(List<GameEvent> gameEvents) { this.gameEvents = new LinkedList<GameEvent>(gameEvents); } /** * creates a new LogGameEventCommand. * * @param source player name * @param event event type * @param params parameters */ public LogGameEventCommand(String source, String event, String... params) { this.gameEvents = null; this.source = source; this.event = event; this.params = new String[params.length]; System.arraycopy(params, 0, this.params, 0, params.length); } @Override public void execute(DBTransaction transaction) throws SQLException { if (gameEvents == null) { DAORegister.get().get(GameEventDAO.class).addGameEvent(transaction, this.getEnqueueTime(), source, event, params); } else { DAORegister.get().get(GameEventDAO.class).addGameEvents(transaction, gameEvents); } } /** * returns a string suitable for debug output of this DBCommand. * * @return debug string */ @Override public String toString() { return "LogGameEventCommand [source=" + source + ", event=" + event + ", params=" + Arrays.toString(params) + "]"; } }
412
0.746622
1
0.746622
game-dev
MEDIA
0.582369
game-dev
0.588525
1
0.588525
team-eternity/eternity
1,958
source/e_switch.h
// // The Eternity Engine // Copyright (C) 2025 James Haley et al. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ // // Additional terms and conditions compatible with the GPLv3 apply. See the // file COPYING-EE for details. // //------------------------------------------------------------------------------ // // Purpose: EDF switch definitions. // Authors: Ioan Chera // #ifndef E_SWITCH_H_ #define E_SWITCH_H_ #include "Confuse/confuse.h" #include "m_collection.h" #include "m_dllist.h" #include "m_qstr.h" constexpr const char EDF_SEC_SWITCH[] = "switch"; struct cfg_t; // // EDF switch definition // class ESwitchDef : public ZoneObject { public: ESwitchDef() : episode(), link() {} // // Call reset on an unlinked definition // void reset(); bool emptyDef() const { return onpic.empty() && onsound.empty() && offsound.empty(); } qstring offpic; qstring onpic; qstring onsound; qstring offsound; int episode; DLListItem<ESwitchDef> link; }; extern cfg_opt_t edf_switch_opts[]; extern PODCollection<ESwitchDef *> eswitches; void E_ProcessSwitches(cfg_t *cfg); void E_AddSwitchDef(const ESwitchDef &def); const ESwitchDef *E_SwitchForName(const char *name); #endif // EOF
412
0.88285
1
0.88285
game-dev
MEDIA
0.542789
game-dev
0.869997
1
0.869997
opdenkamp/xbmc-pvr-addons
4,042
addons/pvr.mediaportal.tvserver/src/GenreTable.cpp
/* * Copyright (C) 2005-2012 Team XBMC * http://www.xbmc.org * * 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/>. * */ #include "client.h" #include "GenreTable.h" #include "tinyxml/tinyxml.h" using namespace ADDON; using namespace std; bool CGenreTable::LoadGenreXML(const std::string &filename) { TiXmlDocument xmlDoc; if (!xmlDoc.LoadFile(filename)) { XBMC->Log(LOG_ERROR, "Unable to load %s: %s at line %d", filename.c_str(), xmlDoc.ErrorDesc(), xmlDoc.ErrorRow()); return false; } XBMC->Log(LOG_NOTICE, "Opened %s to read genre string to type/subtype translation table", filename.c_str()); TiXmlHandle hDoc(&xmlDoc); TiXmlElement* pElem; TiXmlHandle hRoot(0); const char* sGenreType = NULL; const char* sGenreSubType = NULL; genre_t genre; // block: genrestrings pElem = hDoc.FirstChildElement("genrestrings").Element(); // should always have a valid root but handle gracefully if it does if (!pElem) { XBMC->Log(LOG_ERROR, "Could not find <genrestrings> element"); return false; } //This should hold: pElem->Value() == "genrestrings" // save this for later hRoot=TiXmlHandle(pElem); // iterate through all genre elements TiXmlElement* pGenreNode = hRoot.FirstChildElement("genre").Element(); //This should hold: pGenreNode->Value() == "genre" if (!pGenreNode) { XBMC->Log(LOG_ERROR, "Could not find <genre> element"); return false; } for (; pGenreNode != NULL; pGenreNode = pGenreNode->NextSiblingElement("genre")) { const char* sGenreString = pGenreNode->GetText(); if (sGenreString) { sGenreType = pGenreNode->Attribute("type"); sGenreSubType = pGenreNode->Attribute("subtype"); if ((sGenreType) && (strlen(sGenreType) > 2)) { if(sscanf(sGenreType + 2, "%5x", &genre.type) != 1) genre.type = 0; } else { genre.type = 0; } if ((sGenreSubType) && (strlen(sGenreSubType) > 2 )) { if(sscanf(sGenreSubType + 2, "%5x", &genre.subtype) != 1) genre.subtype = 0; } else { genre.subtype = 0; } if (genre.type > 0) { XBMC->Log(LOG_DEBUG, "Genre '%s' => 0x%x, 0x%x", sGenreString, genre.type, genre.subtype); m_genremap.insert(std::pair<std::string, genre_t>(sGenreString, genre)); } } } return true; } void CGenreTable::GenreToTypes(string& strGenre, int& genreType, int& genreSubType) { // The xmltv plugin from the MediaPortal TV Server can return genre // strings in local language (depending on the external TV guide source). // The only way to solve this at the XMBC side is to transfer the // genre string to XBMC or to let this plugin (or the TVServerXBMC // plugin) translate it into XBMC compatible (numbered) genre types string m_genre = strGenre; if(!m_genremap.empty() && !m_genre.empty()) { GenreMap::iterator it; std::transform(m_genre.begin(), m_genre.end(), m_genre.begin(), ::tolower); it = m_genremap.find(m_genre); if (it != m_genremap.end()) { genreType = it->second.type; genreSubType = it->second.subtype; } else { XBMC->Log(LOG_DEBUG, "EPG: No mapping of '%s' to genre type/subtype found.", strGenre.c_str()); genreType = EPG_GENRE_USE_STRING; genreSubType = 0; } } else { genreType = 0; genreSubType = 0; } }
412
0.915724
1
0.915724
game-dev
MEDIA
0.787928
game-dev
0.874048
1
0.874048
newtron-vania/Undead_Survivor-Vampire_Survivor-copy-practice
3,504
Assets/Scripts/Contents/WorldScrolling.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class WorldScrolling : MonoBehaviour { [SerializeField] private Transform _playerTransform; private Vector2Int _currentTilePosition = new Vector2Int(0,0); [SerializeField ] private Vector2Int _playerTilePosition; private Vector2Int _onTileGridPlayerPosition; [SerializeField] private float _tileSize = 25f; private GameObject[,] _terrainTiles; [SerializeField] private int terrainTileHorizontalCount; [SerializeField] private int terrainTileVerticalCount; [SerializeField] private int fieldOfVisionHeight = 3; [SerializeField] private int fieldOfVisionWidth = 3; private void Awake() { _playerTransform = Managers.Game.getPlayer().transform; _terrainTiles = new GameObject[terrainTileHorizontalCount, terrainTileVerticalCount]; } private void Update() { _playerTilePosition.x = (int)(_playerTransform.position.x / _tileSize); _playerTilePosition.y = (int)(_playerTransform.position.y / _tileSize); _playerTilePosition.x -= _playerTransform.position.x < 0 ? 1 : 0; _playerTilePosition.y -= _playerTransform.position.y < 0 ? 1 : 0; if (_currentTilePosition != _playerTilePosition) { _currentTilePosition = _playerTilePosition; _currentTilePosition.x = CalculatePositionOnAxis(_currentTilePosition.x, true); _currentTilePosition.y = CalculatePositionOnAxis(_currentTilePosition.y, false); UpdateTileInScreen(); } } private void UpdateTileInScreen() { for(int pov_x= -(fieldOfVisionWidth/2); pov_x <= fieldOfVisionWidth/2; pov_x++) { for (int pov_y = -(fieldOfVisionHeight/2); pov_y <= fieldOfVisionWidth/2; pov_y++) { int tileToUpdate_x = CalculatePositionOnAxis(_playerTilePosition.x + pov_x, true); int tileToUpdate_y = CalculatePositionOnAxis(_playerTilePosition.y + pov_y, false); GameObject tile = _terrainTiles[tileToUpdate_x, tileToUpdate_y]; tile.transform.position = CalculateTilePosition( _playerTilePosition.x + pov_x, _playerTilePosition.y + pov_y ); } } } private Vector3 CalculateTilePosition(int x, int y) { return new Vector3(x * _tileSize, y * _tileSize, 0f); } private int CalculatePositionOnAxis(float currentValue, bool horizontal) { if (horizontal) { if(currentValue >= 0) currentValue = currentValue % terrainTileHorizontalCount; else { currentValue += 1; currentValue = (terrainTileHorizontalCount - 1) + currentValue % terrainTileHorizontalCount; } } else { if (currentValue >= 0) currentValue = currentValue % terrainTileVerticalCount; else { currentValue += 1; currentValue = (terrainTileVerticalCount - 1) + currentValue % terrainTileVerticalCount; } } return (int)currentValue; } internal void Add(GameObject tileGameObject, Vector2Int tilePosition) { _terrainTiles[tilePosition.x, tilePosition.y] = tileGameObject; } }
412
0.778099
1
0.778099
game-dev
MEDIA
0.960749
game-dev
0.991235
1
0.991235
FishRPG/FishRPG-public
4,428
RPG-Core/src/main/java/me/acraftingfish/minecraftrpg/content/mobs/mushroom/SporeMotherMob.java
package me.acraftingfish.minecraftrpg.content.mobs.mushroom; import com.marcusslover.plus.lib.color.Color; import com.marcusslover.plus.lib.sound.Note; import me.acraftingfish.fishutils.NumUtil; import me.acraftingfish.minecraftrpg.MinecraftRPG; import me.acraftingfish.minecraftrpg.common.item.ItemRegistry; import me.acraftingfish.minecraftrpg.common.mob.MobRegistry; import me.acraftingfish.minecraftrpg.common.mob.xmob.GameMob; import me.acraftingfish.minecraftrpg.common.mob.xmob.MobAttributes; import me.acraftingfish.minecraftrpg.common.mob.xmob.MobStat; import me.acraftingfish.minecraftrpg.common.mob.xmob.behaviour.ZombieBehaviour; import me.acraftingfish.minecraftrpg.common.mob.xmob.loot.LootTable; import me.acraftingfish.minecraftrpg.common.mob.xmob.type.CustomMobTypes; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class SporeMotherMob extends GameMob { public SporeMotherMob() { super(CustomMobTypes.ZOMBIE, "Spore Mother", new MobAttributes().set(MobStat.HEALTH, 250) .set(MobStat.DAMAGE, 40) .set(MobStat.MAX_RANGE, 35) .set(MobStat.SPEED, 120) .set(MobStat.KB_MULTIPLIER, 0.2) .set(MobStat.ATTACK_INTERVAL, 25), new ZombieBehaviour(), 5, 30); LootTable shroomLoot = new LootTable(false, true); shroomLoot.addEntry(ItemRegistry.RED_MUSHROOM, 2); shroomLoot.addEntry(ItemRegistry.RED_MUSHROOM, 3); addLoot(shroomLoot); LootTable otherLoot = new LootTable(); otherLoot.addEntry(ItemRegistry.FUNGUS_HELMET, 2.5); otherLoot.addEntry(ItemRegistry.FUNGUS_CHESTPLATE, 2.5); otherLoot.addEntry(ItemRegistry.FUNGUS_LEGGINGS, 2.5); otherLoot.addEntry(ItemRegistry.FUNGUS_BOOTS, 2.5); otherLoot.addEntry(ItemRegistry.MUSHROOM_STEM, 1, 33); addLoot(otherLoot); this.equipment.coloredAllArmor(Color.of("#bf8959")); } @Override protected void onKill(@Nullable Player player, @NotNull Entity entity) { long sporeChildren = NumUtil.random(0, 2); if(NumUtil.random(0, 100000) == 42069) sporeChildren = 5; final int max_tries = 25; Location location = entity.getLocation(); spawnKids: for (long i = 0; i < sporeChildren; i++) { for (int o = 1; o <= max_tries; o++) { Location kidLoc = location.clone().add(Math.pow(NumUtil.random(0, 2.5), 2) - 3.125, 0.0, Math.pow(NumUtil.random(0, 2.5), 2) - 3.125); if(!kidLoc.getBlock().getType().isAir()){ if(o == max_tries) break spawnKids; continue; } int ticks = (int) NumUtil.random(20, 30); /*new LineParticleEffect(location.clone().add(0.5, 0, 0.5).toVector(), kidLoc.clone().add(0.5, 0, 0.5).toVector(), NumUtil.random(20, 30), 2) .addParticle(ParticleData.create(Particle.BLOCK_DUST, 0, 0, 0, 2, Material.MUD_BRICKS.createBlockData())) .addParticle(ParticleData.create(Particle.BLOCK_DUST, 0, 0, 0, 2, Material.BROWN_MUSHROOM_BLOCK.createBlockData())) .setParticlesPerTick(2) .whenDone(l -> { child.spawn(kidLoc); Note.of(Sound.ENTITY_SHULKER_DEATH, 0.4f, 1f).send(kidLoc); Note.of(Sound.ENTITY_SHULKER_AMBIENT, 0.4f, 0f).send(kidLoc); }) .start(location.getWorld());*/ new BukkitRunnable() { @Override public void run() { MobRegistry.SPORE_CHILD.spawn(kidLoc); Note.of(Sound.ENTITY_SHULKER_DEATH, 0.4f, 1f).send(kidLoc); Note.of(Sound.ENTITY_SHULKER_AMBIENT, 0.4f, 0f).send(kidLoc); } }.runTaskLater(MinecraftRPG.getInstance(), ticks); Note.of(Sound.ENTITY_SHULKER_HURT, 0.4f, 1f).send(kidLoc); break; } } } }
412
0.855426
1
0.855426
game-dev
MEDIA
0.94148
game-dev
0.90299
1
0.90299
facebook/hhvm
5,769
hphp/hack/src/arena_collections/set.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use arena_trait::Arena; use arena_trait::TrivialDrop; use ocamlrep::FromOcamlRepIn; use ocamlrep::ToOcamlRep; use serde::Deserialize; use serde::Serialize; use crate::map::Map; use crate::map::MapIter; /// An arena-allocated set. /// /// See `Map` for more info. #[derive(Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[serde(bound(deserialize = "K: 'de + arena_deserializer::DeserializeInArena<'de>"))] #[must_use] pub struct Set<'a, K>( #[serde(deserialize_with = "arena_deserializer::arena", borrow)] Map<'a, K, ()>, ); impl<'a, K> Clone for Set<'a, K> { fn clone(&self) -> Self { Set(self.0.clone()) } } arena_deserializer::impl_deserialize_in_arena!(Set<'arena, K>); impl<'a, K> Copy for Set<'a, K> {} impl<'a, K> TrivialDrop for Set<'a, K> {} impl<K> Default for Set<'_, K> { fn default() -> Self { Set(Map::default()) } } impl<K: ToOcamlRep + Ord> ToOcamlRep for Set<'_, K> { fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> { let len = self.count(); let mut iter = self.iter().map(|x| x.to_ocamlrep(alloc)); let (value, _) = ocamlrep::sorted_iter_to_ocaml_set(&mut iter, alloc, len); value } } impl<'a, K> FromOcamlRepIn<'a> for Set<'a, K> where K: FromOcamlRepIn<'a> + Ord + TrivialDrop + Clone, { fn from_ocamlrep_in( value: ocamlrep::Value<'_>, alloc: &'a bumpalo::Bump, ) -> Result<Self, ocamlrep::FromError> { // TODO: This is a bit wasteful. If we had iter_from_ocaml_set_in // instead, we wouldn't need the extra vec. let mut elements = bumpalo::collections::Vec::new_in(alloc); ocamlrep::vec_from_ocaml_set_in(value, &mut elements, alloc)?; let mut set = Set::empty(); for element in elements { set = set.add(alloc, element); } Ok(set) } } #[macro_export] macro_rules! set { ( ) => ({ Set::empty() }); ( $arena:expr; $($x:expr),* ) => ({ let mut temp_map = Set::empty(); $( temp_map = temp_map.add($arena, $x); )* temp_map }); } impl<'a, K: Ord> Set<'a, K> { pub fn mem(self, x: &K) -> bool { self.0.mem(x) } pub fn intersection(self, other: Self) -> Intersection<'a, K> { Intersection { iter: self.iter(), other, } } } impl<'a, K> Set<'a, K> { pub const fn empty() -> Self { Set(Map::empty()) } pub fn count(self) -> usize { self.0.count() } } impl<'a, K: Ord> Set<'a, K> { pub fn is_empty(self) -> bool { self.0.is_empty() } } impl<'a, K: TrivialDrop + Clone + Ord> Set<'a, K> { pub fn singleton<A: Arena>(arena: &'a A, x: K) -> Self { Set(Map::singleton(arena, x, ())) } pub fn from<A: Arena, I>(arena: &'a A, i: I) -> Self where I: IntoIterator<Item = K>, { let mut s = Self::empty(); for k in i { s = s.add(arena, k); } s } pub fn add<A: Arena>(self, arena: &'a A, x: K) -> Self { Set(self.0.add(arena, x, ())) } pub fn remove<A: Arena>(self, arena: &'a A, x: &K) -> Self { Set(self.0.remove(arena, x)) } pub fn min_entry(self) -> Option<&'a K> { let v = self.0.min_entry(); v.map(|(k, _)| k) } pub fn remove_min_entry<A: Arena>(self, arena: &'a A) -> Self { Set(self.0.remove_min_entry(arena)) } pub fn max_entry(self) -> Option<&'a K> { let v = self.0.max_entry(); v.map(|(k, _)| k) } /// Remove the maximum key-value entry. pub fn remove_max_entry<A: Arena>(self, arena: &'a A) -> Self { Set(self.0.remove_max_entry(arena)) } pub fn diff<A: Arena>(self, arena: &'a A, other: Self) -> Self { Set(self.0.diff(arena, other.0)) } } impl<'a, T> Set<'a, T> { pub fn iter(&self) -> SetIter<'a, T> { SetIter { iter: self.0.iter(), } } } /// Iterator state for set. pub struct SetIter<'a, K> { iter: MapIter<'a, K, ()>, } impl<'a, K> IntoIterator for &Set<'a, K> { type Item = &'a K; type IntoIter = SetIter<'a, K>; fn into_iter(self) -> Self::IntoIter { SetIter { iter: self.0.into_iter(), } } } impl<'a, K> Iterator for SetIter<'a, K> { type Item = &'a K; fn next(&mut self) -> Option<Self::Item> { match self.iter.next() { None => None, Some((k, _)) => Some(k), } } } pub struct Intersection<'a, T> { iter: SetIter<'a, T>, other: Set<'a, T>, } impl<'a, T: Ord> Iterator for Intersection<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.iter.by_ref().find(|&x| self.other.mem(x)) } } #[cfg(test)] pub mod tests_macro { use bumpalo::Bump; use super::*; #[test] fn test_empty() { assert_eq!(set![], Set::<i32>::empty()); } #[test] fn test_non_empty() { let a = Bump::new(); assert_eq!(set![&a; 5, 3, 9, 4], Set::<i32>::from(&a, vec![3, 4, 5, 9])); } } #[cfg(test)] pub mod tests_iter { use bumpalo::Bump; use super::*; #[test] fn test_empty() { let s: Set<'_, i32> = set![]; assert!(s.into_iter().copied().eq(vec![].into_iter())); } #[test] fn test_non_empty() { let a = Bump::new(); let s: Set<'_, i32> = set![&a; 6, 4, 5]; assert!(s.into_iter().copied().eq(vec![4, 5, 6].into_iter())); } }
412
0.968952
1
0.968952
game-dev
MEDIA
0.71453
game-dev
0.979677
1
0.979677
argotorg/solidity
1,433
test/libsolidity/smtCheckerTests/types/array_mapping_aliasing_1.sol
contract C { mapping (uint => uint) singleMap; mapping (uint => uint)[] severalMaps; mapping (uint => uint8)[] severalMaps8; mapping (uint => uint)[][] severalMaps3d; function p() public { severalMaps.push(); severalMaps8.push(); severalMaps3d.push().push(); } function f(mapping (uint => uint) storage map) internal { require(severalMaps.length > 0); require(severalMaps8.length > 0); require(severalMaps3d.length > 0); require(severalMaps3d[0].length > 0); severalMaps[0][0] = 42; severalMaps8[0][0] = 42; severalMaps3d[0][0][0] = 42; map[0] = 2; // Should fail since map == severalMaps[0] is possible. // Access is safe but oob is reported because of aliasing. assert(severalMaps[0][0] == 42); // Should not fail since knowledge is erased only for mapping (uint => uint). assert(severalMaps8[0][0] == 42); // Should fail since map == severalMaps3d[0][0] is possible. // Removed because current Spacer seg faults in cex generation. //assert(severalMaps3d[0][0][0] == 42); } function g(uint x) public { require(x < severalMaps.length); f(severalMaps[x]); } } // ==== // SMTEngine: all // SMTIgnoreCex: yes // ---- // Warning 6368: (706-720): CHC: Out of bounds access happens here. // Warning 6328: (699-730): CHC: Assertion violation happens here. // Info 1391: CHC: 8 verification condition(s) proved safe! Enable the model checker option "show proved safe" to see all of them.
412
0.895232
1
0.895232
game-dev
MEDIA
0.795129
game-dev
0.590241
1
0.590241
javakam/Windows-Scripts
1,190
定时关机_设定.bat
@echo off %1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit cd /d "%~dp0" @echo off echo. echo ============================================= echo ʱػ echo 0(ȡжʱػ) echo 1Сʱ(3600) echo 2Сʱ(7200) echo 3Сʱ(10800) echo 4Сʱ(14400) echo 5Сʱ(18000) echo 6Сʱ(21600) echo 7Сʱ(25200) echo 8Сʱ(28800) echo 9Сʱ(32400) echo 10Сʱ(36000) echo ============================================= :prompt :select set /p opt=ѡ if %opt%==0 ( set SHUTDOWN_DELAY=0 )else if %opt%==1 ( set SHUTDOWN_DELAY=1 )else if %opt%==2 ( set SHUTDOWN_DELAY=2 )else if %opt%==3 ( set SHUTDOWN_DELAY=3 )else if %opt%==4 ( set SHUTDOWN_DELAY=4 )else if %opt%==5 ( set SHUTDOWN_DELAY=5 )else if %opt%==6 ( set SHUTDOWN_DELAY=6 )else if %opt%==7 ( set SHUTDOWN_DELAY=7 )else if %opt%==8 ( set SHUTDOWN_DELAY=8 )else if %opt%==9 ( set SHUTDOWN_DELAY=9 )else if %opt%==10 ( set SHUTDOWN_DELAY=10 )else ( echo ЧЧѡ goto prompt ) setlocal enabledelayedexpansion if %SHUTDOWN_DELAY%==0 ( echo ȡԶػ Shutdown -a )else ( echo %SHUTDOWN_DELAY%СʱԶػ set /a result=%SHUTDOWN_DELAY% * 3600 Shutdown -s -f -t !result! ) echo ɣٴ޸á goto prompt ::pause
412
0.704822
1
0.704822
game-dev
MEDIA
0.137144
game-dev
0.660083
1
0.660083
gitzhzhg/SeismicPackage
5,215
CPSeis/spws_home/include/sl/slp_text.hh
/*<license> ------------------------------------------------------------------------------- Copyright (c) 2007 ConocoPhillips Company 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. ------------------------------------------------------------------------------- </license>*/ //------------------------- slp_text.hh -------------------------------// //------------------------- slp_text.hh -------------------------------// //------------------------- slp_text.hh -------------------------------// // header file for the SLpText class // derived from the SLpBase class // subdirectory sl // This is a class for text widgets which display long, // float, double, or char. #ifndef _SLP_TEXT_HH_ #define _SLP_TEXT_HH_ #include "sl/slp_base.hh" class SLpText : public SLpBase, virtual public IminGuiResource, virtual public ImaxGuiResource, virtual public FminGuiResource, virtual public FmaxGuiResource, virtual public DminGuiResource, virtual public DmaxGuiResource { //------------------------------- data --------------------------// //------------------------------- data --------------------------// //------------------------------- data --------------------------// private: enum { _NORMAL_APPEARANCE, _LABEL_APPEARANCE, _FRAMED_LABEL_APPEARANCE }; Boolean _flush; // whether to flush buffer when value changes. long _show; // one of the above enums long _nchar, _ndec; //------------------------------- functions ------------------------// //------------------------------- functions ------------------------// //------------------------------- functions ------------------------// public: void flushWhenValueChanges(Boolean flush = TRUE) { _flush = flush; } void showNormalAppearance() { _show = _NORMAL_APPEARANCE; setSenseResource(); } void showLabelAppearance() { _show = _LABEL_APPEARANCE ; setSenseResource(); } void showFramedLabelAppearance() { _show = _FRAMED_LABEL_APPEARANCE; setSenseResource(); } SLpText (SLDelay *slparent, char *name, long ident = 0, long type = _CHAR, long nchar = 0, long ndec = 999); SLpText (Widget wparent , char *name, long ident = 0, long type = _CHAR, long nchar = 0, long ndec = 999); SLpText (Widget w, long ident = 0, long type = _CHAR, long nchar = 0, long ndec = 999); virtual ~SLpText (void); virtual Widget make (Widget p = NULL); // overrides SLDelay static void displayMessage(void *data, char *msg); private: void constructorHelper(); int checkValue (int ivar, int istat); float checkValue (float fvar, int istat); double checkValue (double dvar, int istat); virtual void setSenseResource(void); // overrides PrimSupport virtual void setIvarResource (void); // overrides PrimSupport virtual void setFvarResource (void); // overrides PrimSupport virtual void setDvarResource (void); // overrides PrimSupport virtual void setCvarResource (void); // overrides PrimSupport virtual long ivarResource (void) const; // overrides PrimSupport virtual float fvarResource (void) const; // overrides PrimSupport virtual double dvarResource (void) const; // overrides PrimSupport virtual char *cvarResource (void) const; // overrides PrimSupport virtual long ivarDefault (void) const; // overrides PrimSupport virtual float fvarDefault (void) const; // overrides PrimSupport virtual double dvarDefault (void) const; // overrides PrimSupport virtual char *cvarDefault (void) const; // overrides PrimSupport static void tCallback(Widget w, XtPointer user, XtPointer call); } ; #endif //---------------------------- end --------------------------------------// //---------------------------- end --------------------------------------// //---------------------------- end --------------------------------------//
412
0.993683
1
0.993683
game-dev
MEDIA
0.665803
game-dev
0.735879
1
0.735879
jbatonnet/Rinkhals.apps
9,211
apps/vanilla-klipper/lib/python3.11/site-packages/jinja2/idtracking.py
from ._compat import iteritems from .visitor import NodeVisitor VAR_LOAD_PARAMETER = "param" VAR_LOAD_RESOLVE = "resolve" VAR_LOAD_ALIAS = "alias" VAR_LOAD_UNDEFINED = "undefined" def find_symbols(nodes, parent_symbols=None): sym = Symbols(parent=parent_symbols) visitor = FrameSymbolVisitor(sym) for node in nodes: visitor.visit(node) return sym def symbols_for_node(node, parent_symbols=None): sym = Symbols(parent=parent_symbols) sym.analyze_node(node) return sym class Symbols(object): def __init__(self, parent=None, level=None): if level is None: if parent is None: level = 0 else: level = parent.level + 1 self.level = level self.parent = parent self.refs = {} self.loads = {} self.stores = set() def analyze_node(self, node, **kwargs): visitor = RootVisitor(self) visitor.visit(node, **kwargs) def _define_ref(self, name, load=None): ident = "l_%d_%s" % (self.level, name) self.refs[name] = ident if load is not None: self.loads[ident] = load return ident def find_load(self, target): if target in self.loads: return self.loads[target] if self.parent is not None: return self.parent.find_load(target) def find_ref(self, name): if name in self.refs: return self.refs[name] if self.parent is not None: return self.parent.find_ref(name) def ref(self, name): rv = self.find_ref(name) if rv is None: raise AssertionError( "Tried to resolve a name to a reference that " "was unknown to the frame (%r)" % name ) return rv def copy(self): rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.refs = self.refs.copy() rv.loads = self.loads.copy() rv.stores = self.stores.copy() return rv def store(self, name): self.stores.add(name) # If we have not see the name referenced yet, we need to figure # out what to set it to. if name not in self.refs: # If there is a parent scope we check if the name has a # reference there. If it does it means we might have to alias # to a variable there. if self.parent is not None: outer_ref = self.parent.find_ref(name) if outer_ref is not None: self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref)) return # Otherwise we can just set it to undefined. self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None)) def declare_parameter(self, name): self.stores.add(name) return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None)) def load(self, name): target = self.find_ref(name) if target is None: self._define_ref(name, load=(VAR_LOAD_RESOLVE, name)) def branch_update(self, branch_symbols): stores = {} for branch in branch_symbols: for target in branch.stores: if target in self.stores: continue stores[target] = stores.get(target, 0) + 1 for sym in branch_symbols: self.refs.update(sym.refs) self.loads.update(sym.loads) self.stores.update(sym.stores) for name, branch_count in iteritems(stores): if branch_count == len(branch_symbols): continue target = self.find_ref(name) assert target is not None, "should not happen" if self.parent is not None: outer_target = self.parent.find_ref(name) if outer_target is not None: self.loads[target] = (VAR_LOAD_ALIAS, outer_target) continue self.loads[target] = (VAR_LOAD_RESOLVE, name) def dump_stores(self): rv = {} node = self while node is not None: for name in node.stores: if name not in rv: rv[name] = self.find_ref(name) node = node.parent return rv def dump_param_targets(self): rv = set() node = self while node is not None: for target, (instr, _) in iteritems(self.loads): if instr == VAR_LOAD_PARAMETER: rv.add(target) node = node.parent return rv class RootVisitor(NodeVisitor): def __init__(self, symbols): self.sym_visitor = FrameSymbolVisitor(symbols) def _simple_visit(self, node, **kwargs): for child in node.iter_child_nodes(): self.sym_visitor.visit(child) visit_Template = ( visit_Block ) = ( visit_Macro ) = ( visit_FilterBlock ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit def visit_AssignBlock(self, node, **kwargs): for child in node.body: self.sym_visitor.visit(child) def visit_CallBlock(self, node, **kwargs): for child in node.iter_child_nodes(exclude=("call",)): self.sym_visitor.visit(child) def visit_OverlayScope(self, node, **kwargs): for child in node.body: self.sym_visitor.visit(child) def visit_For(self, node, for_branch="body", **kwargs): if for_branch == "body": self.sym_visitor.visit(node.target, store_as_param=True) branch = node.body elif for_branch == "else": branch = node.else_ elif for_branch == "test": self.sym_visitor.visit(node.target, store_as_param=True) if node.test is not None: self.sym_visitor.visit(node.test) return else: raise RuntimeError("Unknown for branch") for item in branch or (): self.sym_visitor.visit(item) def visit_With(self, node, **kwargs): for target in node.targets: self.sym_visitor.visit(target) for child in node.body: self.sym_visitor.visit(child) def generic_visit(self, node, *args, **kwargs): raise NotImplementedError( "Cannot find symbols for %r" % node.__class__.__name__ ) class FrameSymbolVisitor(NodeVisitor): """A visitor for `Frame.inspect`.""" def __init__(self, symbols): self.symbols = symbols def visit_Name(self, node, store_as_param=False, **kwargs): """All assignments to names go through this function.""" if store_as_param or node.ctx == "param": self.symbols.declare_parameter(node.name) elif node.ctx == "store": self.symbols.store(node.name) elif node.ctx == "load": self.symbols.load(node.name) def visit_NSRef(self, node, **kwargs): self.symbols.load(node.name) def visit_If(self, node, **kwargs): self.visit(node.test, **kwargs) original_symbols = self.symbols def inner_visit(nodes): self.symbols = rv = original_symbols.copy() for subnode in nodes: self.visit(subnode, **kwargs) self.symbols = original_symbols return rv body_symbols = inner_visit(node.body) elif_symbols = inner_visit(node.elif_) else_symbols = inner_visit(node.else_ or ()) self.symbols.branch_update([body_symbols, elif_symbols, else_symbols]) def visit_Macro(self, node, **kwargs): self.symbols.store(node.name) def visit_Import(self, node, **kwargs): self.generic_visit(node, **kwargs) self.symbols.store(node.target) def visit_FromImport(self, node, **kwargs): self.generic_visit(node, **kwargs) for name in node.names: if isinstance(name, tuple): self.symbols.store(name[1]) else: self.symbols.store(name) def visit_Assign(self, node, **kwargs): """Visit assignments in the correct order.""" self.visit(node.node, **kwargs) self.visit(node.target, **kwargs) def visit_For(self, node, **kwargs): """Visiting stops at for blocks. However the block sequence is visited as part of the outer scope. """ self.visit(node.iter, **kwargs) def visit_CallBlock(self, node, **kwargs): self.visit(node.call, **kwargs) def visit_FilterBlock(self, node, **kwargs): self.visit(node.filter, **kwargs) def visit_With(self, node, **kwargs): for target in node.values: self.visit(target) def visit_AssignBlock(self, node, **kwargs): """Stop visiting at block assigns.""" self.visit(node.target, **kwargs) def visit_Scope(self, node, **kwargs): """Stop visiting at scopes.""" def visit_Block(self, node, **kwargs): """Stop visiting at blocks.""" def visit_OverlayScope(self, node, **kwargs): """Do not visit into overlay scopes."""
412
0.924064
1
0.924064
game-dev
MEDIA
0.691824
game-dev
0.939686
1
0.939686
electronicarts/CnC_Generals_Zero_Hour
4,337
Generals/Code/GameEngine/Source/GameLogic/Object/Die/FXListDie.cpp
/* ** Command & Conquer Generals(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ //////////////////////////////////////////////////////////////////////////////// // // // (c) 2001-2003 Electronic Arts Inc. // // // //////////////////////////////////////////////////////////////////////////////// // FILE: FXListDie.cpp /////////////////////////////////////////////////////////////////////////// // Author: Steven Johnson, Jan 2002 // Desc: Simple Die module /////////////////////////////////////////////////////////////////////////////////////////////////// // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine #define DEFINE_DAMAGE_NAMES #include "Common/INI.h" #include "Common/ThingTemplate.h" #include "Common/Xfer.h" #include "GameClient/FXList.h" #include "GameLogic/Damage.h" #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" #include "GameLogic/Module/FXListDie.h" #include "GameLogic/Module/AIUpdate.h" //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- FXListDie::FXListDie( Thing *thing, const ModuleData* moduleData ) : DieModule( thing, moduleData ) { } //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- FXListDie::~FXListDie( void ) { } //------------------------------------------------------------------------------------------------- /** The die callback. */ //------------------------------------------------------------------------------------------------- void FXListDie::onDie( const DamageInfo *damageInfo ) { if (!isDieApplicable(damageInfo)) return; const FXListDieModuleData* d = getFXListDieModuleData(); if (d->m_defaultDeathFX) { // if the object has any ambient sound(s), kill 'em now. TheAudio->stopAllAmbientsBy(getObject()); if (d->m_orientToObject) { Object *damageDealer = TheGameLogic->findObjectByID( damageInfo->in.m_sourceID ); FXList::doFXObj(getFXListDieModuleData()->m_defaultDeathFX, getObject(), damageDealer); } else { FXList::doFXPos(getFXListDieModuleData()->m_defaultDeathFX, getObject()->getPosition()); } } } // ------------------------------------------------------------------------------------------------ /** CRC */ // ------------------------------------------------------------------------------------------------ void FXListDie::crc( Xfer *xfer ) { // extend base class DieModule::crc( xfer ); } // end crc // ------------------------------------------------------------------------------------------------ /** Xfer method * Version Info: * 1: Initial version */ // ------------------------------------------------------------------------------------------------ void FXListDie::xfer( Xfer *xfer ) { // version XferVersion currentVersion = 1; XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); // extend base class DieModule::xfer( xfer ); } // end xfer // ------------------------------------------------------------------------------------------------ /** Load post process */ // ------------------------------------------------------------------------------------------------ void FXListDie::loadPostProcess( void ) { // extend base class DieModule::loadPostProcess(); } // end loadPostProcess
412
0.751264
1
0.751264
game-dev
MEDIA
0.47833
game-dev
0.527391
1
0.527391
mc-zhonghuang/Urticaria-Public
9,524
src/main/java/net/minecraft/client/renderer/block/model/ModelBlockDefinition.java
package net.minecraft.client.renderer.block.model; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.*; import net.minecraft.client.resources.model.ModelRotation; import net.minecraft.util.JsonUtils; import net.minecraft.util.ResourceLocation; import java.io.Reader; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class ModelBlockDefinition { static final Gson GSON = (new GsonBuilder()).registerTypeAdapter(ModelBlockDefinition.class, new ModelBlockDefinition.Deserializer()).registerTypeAdapter(ModelBlockDefinition.Variant.class, new ModelBlockDefinition.Variant.Deserializer()).create(); private final Map<String, ModelBlockDefinition.Variants> mapVariants = Maps.newHashMap(); public static ModelBlockDefinition parseFromReader(final Reader p_178331_0_) { return GSON.fromJson(p_178331_0_, ModelBlockDefinition.class); } public ModelBlockDefinition(final Collection<ModelBlockDefinition.Variants> p_i46221_1_) { for (final ModelBlockDefinition.Variants modelblockdefinition$variants : p_i46221_1_) { this.mapVariants.put(modelblockdefinition$variants.name, modelblockdefinition$variants); } } public ModelBlockDefinition(final List<ModelBlockDefinition> p_i46222_1_) { for (final ModelBlockDefinition modelblockdefinition : p_i46222_1_) { this.mapVariants.putAll(modelblockdefinition.mapVariants); } } public ModelBlockDefinition.Variants getVariants(final String p_178330_1_) { final ModelBlockDefinition.Variants modelblockdefinition$variants = this.mapVariants.get(p_178330_1_); if (modelblockdefinition$variants == null) { throw new ModelBlockDefinition.MissingVariantException(); } else { return modelblockdefinition$variants; } } public boolean equals(final Object p_equals_1_) { if (this == p_equals_1_) { return true; } else if (p_equals_1_ instanceof ModelBlockDefinition) { final ModelBlockDefinition modelblockdefinition = (ModelBlockDefinition) p_equals_1_; return this.mapVariants.equals(modelblockdefinition.mapVariants); } else { return false; } } public int hashCode() { return this.mapVariants.hashCode(); } public static class Deserializer implements JsonDeserializer<ModelBlockDefinition> { public ModelBlockDefinition deserialize(final JsonElement p_deserialize_1_, final Type p_deserialize_2_, final JsonDeserializationContext p_deserialize_3_) throws JsonParseException { final JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); final List<ModelBlockDefinition.Variants> list = this.parseVariantsList(p_deserialize_3_, jsonobject); return new ModelBlockDefinition(list); } protected List<ModelBlockDefinition.Variants> parseVariantsList(final JsonDeserializationContext p_178334_1_, final JsonObject p_178334_2_) { final JsonObject jsonobject = JsonUtils.getJsonObject(p_178334_2_, "variants"); final List<ModelBlockDefinition.Variants> list = Lists.newArrayList(); for (final Entry<String, JsonElement> entry : jsonobject.entrySet()) { list.add(this.parseVariants(p_178334_1_, entry)); } return list; } protected ModelBlockDefinition.Variants parseVariants(final JsonDeserializationContext p_178335_1_, final Entry<String, JsonElement> p_178335_2_) { final String s = p_178335_2_.getKey(); final List<ModelBlockDefinition.Variant> list = Lists.newArrayList(); final JsonElement jsonelement = p_178335_2_.getValue(); if (jsonelement.isJsonArray()) { for (final JsonElement jsonelement1 : jsonelement.getAsJsonArray()) { list.add(p_178335_1_.deserialize(jsonelement1, Variant.class)); } } else { list.add(p_178335_1_.deserialize(jsonelement, Variant.class)); } return new ModelBlockDefinition.Variants(s, list); } } public class MissingVariantException extends RuntimeException { } public static class Variant { private final ResourceLocation modelLocation; private final ModelRotation modelRotation; private final boolean uvLock; private final int weight; public Variant(final ResourceLocation modelLocationIn, final ModelRotation modelRotationIn, final boolean uvLockIn, final int weightIn) { this.modelLocation = modelLocationIn; this.modelRotation = modelRotationIn; this.uvLock = uvLockIn; this.weight = weightIn; } public ResourceLocation getModelLocation() { return this.modelLocation; } public ModelRotation getRotation() { return this.modelRotation; } public boolean isUvLocked() { return this.uvLock; } public int getWeight() { return this.weight; } public boolean equals(final Object p_equals_1_) { if (this == p_equals_1_) { return true; } else if (!(p_equals_1_ instanceof ModelBlockDefinition.Variant)) { return false; } else { final ModelBlockDefinition.Variant modelblockdefinition$variant = (ModelBlockDefinition.Variant) p_equals_1_; return this.modelLocation.equals(modelblockdefinition$variant.modelLocation) && this.modelRotation == modelblockdefinition$variant.modelRotation && this.uvLock == modelblockdefinition$variant.uvLock; } } public int hashCode() { int i = this.modelLocation.hashCode(); i = 31 * i + (this.modelRotation != null ? this.modelRotation.hashCode() : 0); i = 31 * i + (this.uvLock ? 1 : 0); return i; } public static class Deserializer implements JsonDeserializer<ModelBlockDefinition.Variant> { public ModelBlockDefinition.Variant deserialize(final JsonElement p_deserialize_1_, final Type p_deserialize_2_, final JsonDeserializationContext p_deserialize_3_) throws JsonParseException { final JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); final String s = this.parseModel(jsonobject); final ModelRotation modelrotation = this.parseRotation(jsonobject); final boolean flag = this.parseUvLock(jsonobject); final int i = this.parseWeight(jsonobject); return new ModelBlockDefinition.Variant(this.makeModelLocation(s), modelrotation, flag, i); } private ResourceLocation makeModelLocation(final String p_178426_1_) { ResourceLocation resourcelocation = new ResourceLocation(p_178426_1_); resourcelocation = new ResourceLocation(resourcelocation.getResourceDomain(), "block/" + resourcelocation.getResourcePath()); return resourcelocation; } private boolean parseUvLock(final JsonObject p_178429_1_) { return JsonUtils.getBoolean(p_178429_1_, "uvlock", false); } protected ModelRotation parseRotation(final JsonObject p_178428_1_) { final int i = JsonUtils.getInt(p_178428_1_, "x", 0); final int j = JsonUtils.getInt(p_178428_1_, "y", 0); final ModelRotation modelrotation = ModelRotation.getModelRotation(i, j); if (modelrotation == null) { throw new JsonParseException("Invalid BlockModelRotation x: " + i + ", y: " + j); } else { return modelrotation; } } protected String parseModel(final JsonObject p_178424_1_) { return JsonUtils.getString(p_178424_1_, "model"); } protected int parseWeight(final JsonObject p_178427_1_) { return JsonUtils.getInt(p_178427_1_, "weight", 1); } } } public static class Variants { private final String name; private final List<ModelBlockDefinition.Variant> listVariants; public Variants(final String nameIn, final List<ModelBlockDefinition.Variant> listVariantsIn) { this.name = nameIn; this.listVariants = listVariantsIn; } public List<ModelBlockDefinition.Variant> getVariants() { return this.listVariants; } public boolean equals(final Object p_equals_1_) { if (this == p_equals_1_) { return true; } else if (!(p_equals_1_ instanceof ModelBlockDefinition.Variants)) { return false; } else { final ModelBlockDefinition.Variants modelblockdefinition$variants = (ModelBlockDefinition.Variants) p_equals_1_; return this.name.equals(modelblockdefinition$variants.name) && this.listVariants.equals(modelblockdefinition$variants.listVariants); } } public int hashCode() { int i = this.name.hashCode(); i = 31 * i + this.listVariants.hashCode(); return i; } } }
412
0.840387
1
0.840387
game-dev
MEDIA
0.44447
game-dev
0.924232
1
0.924232
beyond-aion/aion-server
2,539
game-server/data/handlers/quest/brusthonin/_4020ParicasSpecialOrder.java
package quest.brusthonin; import static com.aionemu.gameserver.model.DialogAction.*; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.questEngine.handlers.AbstractQuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Aion Gates */ public class _4020ParicasSpecialOrder extends AbstractQuestHandler { public _4020ParicasSpecialOrder() { super(4020); } @Override public void register() { qe.registerQuestNpc(205120).addOnQuestStart(questId); qe.registerQuestNpc(205120).addOnTalkEvent(questId); qe.registerQuestNpc(205141).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); int targetId = 0; if (env.getVisibleObject() instanceof Npc) targetId = ((Npc) env.getVisibleObject()).getNpcId(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (targetId == 205120) { if (qs == null || qs.isStartable()) { if (env.getDialogActionId() == QUEST_SELECT) return sendQuestDialog(env, 1011); else return sendQuestStartDialog(env); } else if (qs.getStatus() == QuestStatus.START) { if (env.getDialogActionId() == QUEST_SELECT) return sendQuestDialog(env, 2375); else if (env.getDialogActionId() == SELECT_QUEST_REWARD) { qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10)); return true; } else return sendQuestEndDialog(env); } else if (qs.getStatus() == QuestStatus.REWARD) { return sendQuestEndDialog(env); } } else if (targetId == 205141) { if (qs != null && qs.getStatus() == QuestStatus.START && qs.getQuestVarById(0) == 0) { if (env.getDialogActionId() == QUEST_SELECT) return sendQuestDialog(env, 1352); else if (env.getDialogActionId() == SETPRO1) { qs.setQuestVarById(0, qs.getQuestVarById(0) + 1); updateQuestStatus(env); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10)); return true; } else return sendQuestStartDialog(env); } } return false; } }
412
0.866488
1
0.866488
game-dev
MEDIA
0.949797
game-dev
0.943622
1
0.943622
manisha-v/Number-Cruncher
4,029
Codes/Minor2d/Library/PackageCache/com.unity.timeline@1.2.18/Editor/treeview/TimelineClipUnion.cs
using System.Collections.Generic; using System.Linq; using UnityEditorInternal; using UnityEngine; namespace UnityEditor.Timeline { class TimelineClipUnion { List<TimelineClipGUI> m_Members = new List<TimelineClipGUI>(); Rect m_BoundingRect; Rect m_Union; double m_Start; double m_Duration; bool m_InitUnionRect = true; void Add(TimelineClipGUI clip) { m_Members.Add(clip); if (m_Members.Count == 1) { m_BoundingRect = clip.clippedRect; } else { m_BoundingRect = Encompass(m_BoundingRect, clip.rect); } } public void Draw(Rect parentRect, WindowState state) { if (m_InitUnionRect) { m_Start = m_Members.OrderBy(c => c.clip.start).First().clip.start; m_Duration = m_Members.Sum(c => c.clip.duration); m_InitUnionRect = false; } m_Union = new Rect((float)(m_Start) * state.timeAreaScale.x, 0, (float)m_Duration * state.timeAreaScale.x, 0); // transform clipRect into pixel-space m_Union.xMin += state.timeAreaTranslation.x + parentRect.x; m_Union.xMax += state.timeAreaTranslation.x + parentRect.x; m_Union.y = parentRect.y + 4.0f; m_Union.height = parentRect.height - 8.0f; // calculate clipped rect if (m_Union.x < parentRect.xMin) { var overflow = parentRect.xMin - m_Union.x; m_Union.x = parentRect.xMin; m_Union.width -= overflow; } // bail out if completely clipped if (m_Union.xMax < parentRect.xMin) return; if (m_Union.xMin > parentRect.xMax) return; EditorGUI.DrawRect(m_Union, DirectorStyles.Instance.customSkin.colorClipUnion); } public static List<TimelineClipUnion> Build(List<TimelineClipGUI> clips) { var unions = new List<TimelineClipUnion>(); if (clips == null) return unions; TimelineClipUnion currentUnion = null; foreach (var c in clips) { if (currentUnion == null) { currentUnion = new TimelineClipUnion(); currentUnion.Add(c); unions.Add(currentUnion); } else { Rect result; if (Intersection(c.rect, currentUnion.m_BoundingRect, out result)) { currentUnion.Add(c); } else { currentUnion = new TimelineClipUnion(); currentUnion.Add(c); unions.Add(currentUnion); } } } return unions; } public static Rect Encompass(Rect a, Rect b) { Rect newRect = a; newRect.xMin = Mathf.Min(a.xMin, b.xMin); newRect.yMin = Mathf.Min(a.yMin, b.yMin); newRect.xMax = Mathf.Max(a.xMax, b.xMax); newRect.yMax = Mathf.Max(a.yMax, b.yMax); return newRect; } public static bool Intersection(Rect r1, Rect r2, out Rect intersection) { if (!r1.Overlaps(r2) && !r2.Overlaps(r1)) { intersection = new Rect(0, 0, 0, 0); return false; } float left = Mathf.Max(r1.xMin, r2.xMin); float top = Mathf.Max(r1.yMin, r2.yMin); float right = Mathf.Min(r1.xMax, r2.xMax); float bottom = Mathf.Min(r1.yMax, r2.yMax); intersection = new Rect(left, top, right - left, bottom - top); return true; } } }
412
0.932197
1
0.932197
game-dev
MEDIA
0.799767
game-dev
0.949313
1
0.949313
samizdatco/arbor
12,218
src/physics/physics.js
// // physics.js // // the particle system itself. either run inline or in a worker (see worker.js) // var Physics = function(dt, stiffness, repulsion, friction, updateFn, integrator){ var bhTree = BarnesHutTree() // for computing particle repulsion var active = {particles:{}, springs:{}} var free = {particles:{}} var particles = [] var springs = [] var _epoch=0 var _energy = {sum:0, max:0, mean:0} var _bounds = {topleft:new Point(-1,-1), bottomright:new Point(1,1)} var SPEED_LIMIT = 1000 // the max particle velocity per tick var that = { integrator:['verlet','euler'].indexOf(integrator)>=0 ? integrator : 'verlet', stiffness:(stiffness!==undefined) ? stiffness : 1000, repulsion:(repulsion!==undefined)? repulsion : 600, friction:(friction!==undefined)? friction : .3, gravity:false, dt:(dt!==undefined)? dt : 0.02, theta:.4, // the criterion value for the barnes-hut s/d calculation init:function(){ return that }, modifyPhysics:function(param){ $.each(['stiffness','repulsion','friction','gravity','dt','precision', 'integrator'], function(i, p){ if (param[p]!==undefined){ if (p=='precision'){ that.theta = 1-param[p] return } that[p] = param[p] if (p=='stiffness'){ var stiff=param[p] $.each(active.springs, function(id, spring){ spring.k = stiff }) } } }) }, addNode:function(c){ var id = c.id var mass = c.m var w = _bounds.bottomright.x - _bounds.topleft.x var h = _bounds.bottomright.y - _bounds.topleft.y var randomish_pt = new Point((c.x != null) ? c.x: _bounds.topleft.x + w*Math.random(), (c.y != null) ? c.y: _bounds.topleft.y + h*Math.random()) active.particles[id] = new Particle(randomish_pt, mass); active.particles[id].connections = 0 active.particles[id].fixed = (c.f===1) free.particles[id] = active.particles[id] particles.push(active.particles[id]) }, dropNode:function(c){ var id = c.id var dropping = active.particles[id] var idx = $.inArray(dropping, particles) if (idx>-1) particles.splice(idx,1) delete active.particles[id] delete free.particles[id] }, modifyNode:function(id, mods){ if (id in active.particles){ var pt = active.particles[id] if ('x' in mods) pt.p.x = mods.x if ('y' in mods) pt.p.y = mods.y if ('m' in mods) pt.m = mods.m if ('f' in mods) pt.fixed = (mods.f===1) if ('_m' in mods){ if (pt._m===undefined) pt._m = pt.m pt.m = mods._m } } }, addSpring:function(c){ var id = c.id var length = c.l var from = active.particles[c.fm] var to = active.particles[c.to] if (from!==undefined && to!==undefined){ active.springs[id] = new Spring(from, to, length, that.stiffness) springs.push(active.springs[id]) from.connections++ to.connections++ delete free.particles[c.fm] delete free.particles[c.to] } }, dropSpring:function(c){ var id = c.id var dropping = active.springs[id] dropping.point1.connections-- dropping.point2.connections-- var idx = $.inArray(dropping, springs) if (idx>-1){ springs.splice(idx,1) } delete active.springs[id] }, _update:function(changes){ // batch changes phoned in (automatically) by a ParticleSystem _epoch++ $.each(changes, function(i, c){ if (c.t in that) that[c.t](c) }) return _epoch }, tick:function(){ that.tendParticles() if (that.integrator=='euler'){ that.updateForces() that.updateVelocity(that.dt) that.updatePosition(that.dt) }else{ // default to verlet that.updateForces(); that.cacheForces(); // snapshot f(t) that.updatePosition(that.dt); // update position to x(t + 1) that.updateForces(); // calculate f(t+1) that.updateVelocity(that.dt); // update using f(t) and f(t+1) } that.tock() }, tock:function(){ var coords = [] $.each(active.particles, function(id, pt){ coords.push(id) coords.push(pt.p.x) coords.push(pt.p.y) }) if (updateFn) updateFn({geometry:coords, epoch:_epoch, energy:_energy, bounds:_bounds}) }, tendParticles:function(){ $.each(active.particles, function(id, pt){ // decay down any of the temporary mass increases that were passed along // by using an {_m:} instead of an {m:} (which is to say via a Node having // its .tempMass attr set) if (pt._m!==undefined){ if (Math.abs(pt.m-pt._m)<1){ pt.m = pt._m delete pt._m }else{ pt.m *= .98 } } // zero out the velocity from one tick to the next pt.v.x = pt.v.y = 0 }) }, // Physics stuff updateForces:function() { if (that.repulsion>0){ if (that.theta>0) that.applyBarnesHutRepulsion() else that.applyBruteForceRepulsion() } if (that.stiffness>0) that.applySprings() that.applyCenterDrift() if (that.gravity) that.applyCenterGravity() }, cacheForces:function() { // keep a snapshot of the current forces for the verlet integrator $.each(active.particles, function(id, point) { point._F = point.f; }); }, applyBruteForceRepulsion:function(){ $.each(active.particles, function(id1, point1){ $.each(active.particles, function(id2, point2){ if (point1 !== point2){ var d = point1.p.subtract(point2.p); var distance = Math.max(1.0, d.magnitude()); var direction = ((d.magnitude()>0) ? d : Point.random(1)).normalize() // apply force to each end point // (consult the cached `real' mass value if the mass is being poked to allow // for repositioning. the poked mass will still be used in .applyforce() so // all should be well) point1.applyForce(direction.multiply(that.repulsion*(point2._m||point2.m)*.5) .divide(distance * distance * 0.5) ); point2.applyForce(direction.multiply(that.repulsion*(point1._m||point1.m)*.5) .divide(distance * distance * -0.5) ); } }) }) }, applyBarnesHutRepulsion:function(){ if (!_bounds.topleft || !_bounds.bottomright) return var bottomright = new Point(_bounds.bottomright) var topleft = new Point(_bounds.topleft) // build a barnes-hut tree... bhTree.init(topleft, bottomright, that.theta) $.each(active.particles, function(id, particle){ bhTree.insert(particle) }) // ...and use it to approximate the repulsion forces $.each(active.particles, function(id, particle){ bhTree.applyForces(particle, that.repulsion) }) }, applySprings:function(){ $.each(active.springs, function(id, spring){ var d = spring.point2.p.subtract(spring.point1.p); // the direction of the spring var displacement = spring.length - d.magnitude()//Math.max(.1, d.magnitude()); var direction = ( (d.magnitude()>0) ? d : Point.random(1) ).normalize() // BUG: // since things oscillate wildly for hub nodes, should probably normalize spring // forces by the number of incoming edges for each node. naive normalization // doesn't work very well though. what's the `right' way to do it? // apply force to each end point spring.point1.applyForce(direction.multiply(spring.k * displacement * -0.5)) spring.point2.applyForce(direction.multiply(spring.k * displacement * 0.5)) }); }, applyCenterDrift:function(){ // find the centroid of all the particles in the system and shift everything // so the cloud is centered over the origin var numParticles = 0 var centroid = new Point(0,0) $.each(active.particles, function(id, point) { centroid.add(point.p) numParticles++ }); if (numParticles==0) return var correction = centroid.divide(-numParticles) $.each(active.particles, function(id, point) { point.applyForce(correction) }) }, applyCenterGravity:function(){ // attract each node to the origin $.each(active.particles, function(id, point) { var direction = point.p.multiply(-1.0); point.applyForce(direction.multiply(that.repulsion / 100.0)); }); }, updateVelocity:function(timestep){ // translate forces to a new velocity for this particle var sum=0, max=0, n = 0; $.each(active.particles, function(id, point) { if (point.fixed){ point.v = new Point(0,0) point.f = new Point(0,0) return } if (that.integrator=='euler'){ point.v = point.v.add(point.f.multiply(timestep)).multiply(1-that.friction); }else{ point.v = point.v.add(point.f.add(point._F.divide(point._m)).multiply(timestep*0.5)).multiply(1-that.friction); } point.f.x = point.f.y = 0 var speed = point.v.magnitude() if (speed>SPEED_LIMIT) point.v = point.v.divide(speed*speed) var speed = point.v.magnitude(); var e = speed*speed sum += e max = Math.max(e,max) n++ }); _energy = {sum:sum, max:max, mean:sum/n, n:n} }, updatePosition:function(timestep){ // translate velocity to a position delta var bottomright = null var topleft = null $.each(active.particles, function(i, point) { // move the node to its new position if (that.integrator=='euler'){ point.p = point.p.add(point.v.multiply(timestep)); }else{ //this should follow the equation //x(t+1) = x(t) + v(t) * timestep + 1/2 * timestep^2 * a(t) var accel = point.f.multiply(0.5 * timestep * timestep).divide(point.m); point.p = point.p.add(point.v.multiply(timestep)).add(accel); } if (!bottomright){ bottomright = new Point(point.p.x, point.p.y) topleft = new Point(point.p.x, point.p.y) return } var pt = point.p if (pt.x===null || pt.y===null) return if (pt.x > bottomright.x) bottomright.x = pt.x; if (pt.y > bottomright.y) bottomright.y = pt.y; if (pt.x < topleft.x) topleft.x = pt.x; if (pt.y < topleft.y) topleft.y = pt.y; }); _bounds = {topleft:topleft||new Point(-1,-1), bottomright:bottomright||new Point(1,1)} }, systemEnergy:function(timestep){ // system stats return _energy } } return that.init() } var _nearParticle = function(center_pt, r){ var r = r || .0 var x = center_pt.x var y = center_pt.y var d = r*2 return new Point(x-r+Math.random()*d, y-r+Math.random()*d) }
412
0.833528
1
0.833528
game-dev
MEDIA
0.740044
game-dev
0.912332
1
0.912332
eccentricdevotion/TARDIS
5,862
src/main/java/me/eccentric_nz/TARDIS/console/telepathic/TelepathicGUIListener.java
/* * Copyright (C) 2025 eccentric_nz * * 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 me.eccentric_nz.TARDIS.console.telepathic; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.advanced.TARDISCircuitChecker; import me.eccentric_nz.TARDIS.custommodels.keys.SwitchVariant; import me.eccentric_nz.TARDIS.database.resultset.ResultSetTravellers; import me.eccentric_nz.TARDIS.enumeration.TardisModule; import me.eccentric_nz.TARDIS.listeners.TARDISMenuListener; import me.eccentric_nz.TARDIS.upgrades.SystemTree; import me.eccentric_nz.TARDIS.upgrades.SystemUpgradeChecker; import me.eccentric_nz.TARDIS.utility.ComponentUtils; import org.bukkit.NamespacedKey; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.HashMap; public class TelepathicGUIListener extends TARDISMenuListener { private final TARDIS plugin; public TelepathicGUIListener(TARDIS plugin) { super(plugin); this.plugin = plugin; } @EventHandler(ignoreCancelled = true) public void onTelepathicMenuClick(InventoryClickEvent event) { if (!(event.getInventory().getHolder(false) instanceof TARDISTelepathicInventory)) { return; } Player player = (Player) event.getWhoClicked(); String uuid = player.getUniqueId().toString(); // get id of TARDIS player is in HashMap<String, Object> where = new HashMap<>(); where.put("uuid", uuid); ResultSetTravellers rs = new ResultSetTravellers(plugin, where, false); if (rs.resultSet()) { // check for telepathic circuit TARDISCircuitChecker tcc = null; if (plugin.getConfig().getBoolean("difficulty.circuits") && !plugin.getUtils().inGracePeriod(player, true)) { tcc = new TARDISCircuitChecker(plugin, rs.getTardis_id()); tcc.getCircuits(); } if (tcc != null && !tcc.hasTelepathic()) { plugin.getMessenger().send(player, TardisModule.TARDIS, "NO_TELEPATHIC_CIRCUIT"); event.setCancelled(true); return; } int slot = event.getRawSlot(); if (slot < 0 || slot > 53) { ClickType click = event.getClick(); if (click.equals(ClickType.SHIFT_RIGHT) || click.equals(ClickType.SHIFT_LEFT) || click.equals(ClickType.DOUBLE_CLICK)) { plugin.debug("TelepathicGUIListener"); event.setCancelled(true); } return; } event.setCancelled(true); ItemStack choice = event.getView().getItem(slot); if (slot > 0 && slot < 8 && plugin.getConfig().getBoolean("difficulty.system_upgrades") && !new SystemUpgradeChecker(plugin).has(uuid, SystemTree.TELEPATHIC_CIRCUIT)) { plugin.getMessenger().send(player, TardisModule.TARDIS, "SYS_NEED", "Telepathic Circuit"); return; } switch (slot) { // toggle telepathy on/off case 0 -> { ItemMeta im = choice.getItemMeta(); int b = (im.hasLore() && ComponentUtils.endsWith(im.lore().getFirst(), "ON")) ? 0 : 1; // update database HashMap<String, Object> set = new HashMap<>(); HashMap<String, Object> whereu = new HashMap<>(); whereu.put("uuid", player.getUniqueId().toString()); set.put("telepathy_on", b); plugin.getQueryFactory().doUpdate("player_prefs", set, whereu); // set item model NamespacedKey model = im.getItemModel(); im.setItemModel((model == SwitchVariant.TELEPATHIC_CIRCUIT_OFF.getKey()) ? SwitchVariant.TELEPATHIC_CIRCUIT_ON.getKey() : SwitchVariant.TELEPATHIC_CIRCUIT_OFF.getKey()); choice.setItemMeta(im); plugin.getMessenger().announceRepeater(player, "Telepathic Circuit " + (b == 1 ? "ON" : "OFF")); close(player); } // cave finder case 2 -> { if (choice != null) { player.performCommand("tardistravel cave"); close(player); } } // structure finder case 4 -> { if (choice != null) { player.openInventory(new TARDISTelepathicStructure(plugin).getInventory()); } } // biome finder case 6 -> { if (choice != null) { player.openInventory(new TARDISTelepathicBiome(plugin, rs.getTardis_id()).getInventory()); } } // close case 8 -> close(player); // do nothing default -> { } } } } }
412
0.857485
1
0.857485
game-dev
MEDIA
0.906508
game-dev
0.941603
1
0.941603
StudioCherno/Coral
20,526
Coral.Managed/Source/TypeInterface.cs
using Coral.Managed.Interop; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Runtime.Loader; namespace Coral.Managed; using static ManagedHost; internal static class TypeInterface { internal readonly static UniqueIdList<Type> s_CachedTypes = new(); internal readonly static UniqueIdList<MethodInfo> s_CachedMethods = new(); internal readonly static UniqueIdList<FieldInfo> s_CachedFields = new(); internal readonly static UniqueIdList<PropertyInfo> s_CachedProperties = new(); internal readonly static UniqueIdList<Attribute> s_CachedAttributes = new(); internal static Type? FindType(int InAssemblyLoadContextId, string? InTypeName) { var type = Type.GetType(InTypeName!, (name) => { AssemblyLoader.s_AssemblyContexts.TryGetValue(InAssemblyLoadContextId, out AssemblyLoadContext? alc); return AssemblyLoader.ResolveAssembly(alc, name); }, (assembly, name, ignore) => { return assembly != null ? assembly.GetType(name, false, ignore) : Type.GetType(name, false, ignore); } ); return type; } internal static object? CreateInstance(Type InType, params object?[]? InArguments) { return InType.Assembly.CreateInstance(InType.FullName ?? string.Empty, false, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, InArguments!, null, null); } private static Dictionary<Type, ManagedType> s_TypeConverters = new() { { typeof(sbyte), ManagedType.SByte }, { typeof(byte), ManagedType.Byte }, { typeof(short), ManagedType.Short }, { typeof(ushort), ManagedType.UShort }, { typeof(int), ManagedType.Int }, { typeof(uint), ManagedType.UInt }, { typeof(long), ManagedType.Long }, { typeof(ulong), ManagedType.ULong }, { typeof(float), ManagedType.Float }, { typeof(double), ManagedType.Double }, { typeof(Bool32), ManagedType.Bool }, { typeof(bool), ManagedType.Bool }, { typeof(NativeString), ManagedType.String }, { typeof(string), ManagedType.String }, }; internal static unsafe T? FindSuitableMethod<T>(string? InMethodName, ManagedType* InParameterTypes, int InParameterCount, ReadOnlySpan<T> InMethods) where T : MethodBase { if (InMethodName == null) return null; T? result = null; foreach (var methodInfo in InMethods) { var methodParams = methodInfo.GetParameters(); if (methodParams.Length != InParameterCount) continue; // Check if the method name matches the signature of methodInfo, if so we ignore the automatic type checking if (InMethodName == methodInfo.ToString()) { result = methodInfo; break; } if (methodInfo.Name != InMethodName) continue; int matchingTypes = 0; for (int i = 0; i < methodParams.Length; i++) { ManagedType paramType; if (methodParams[i].ParameterType.IsPointer || methodParams[i].ParameterType == typeof(IntPtr)) { paramType = ManagedType.Pointer; } else if (!s_TypeConverters.TryGetValue(methodParams[i].ParameterType, out paramType)) { paramType = ManagedType.Unknown; } if (paramType == InParameterTypes[i]) { matchingTypes++; } } if (matchingTypes == InParameterCount) { result = methodInfo; break; } } return result; } [UnmanagedCallersOnly] internal static unsafe void GetAssemblyTypes(int InAssemblyLoadContextId, int InAssemblyId, int* OutTypes, int* OutTypeCount) { try { if (!AssemblyLoader.TryGetAssembly(InAssemblyLoadContextId, InAssemblyId, out var assembly)) { LogMessage($"Couldn't get types for assembly '{InAssemblyId}', assembly not found.", MessageLevel.Error); return; } if (assembly == null) { LogMessage($"Couldn't get types for assembly '{InAssemblyId}', assembly was null.", MessageLevel.Error); return; } ReadOnlySpan<Type> assemblyTypes = assembly.GetTypes(); if (OutTypeCount != null) *OutTypeCount = assemblyTypes.Length; if (OutTypes == null) return; for (int i = 0; i < assemblyTypes.Length; i++) { OutTypes[i] = s_CachedTypes.Add(assemblyTypes[i]); } } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe NativeString GetFullTypeName(int InType) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return NativeString.Null(); return type.FullName; } catch (Exception e) { HandleException(e); return NativeString.Null(); } } [UnmanagedCallersOnly] internal static unsafe NativeString GetAssemblyQualifiedName(int InType) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return NativeString.Null(); return type.AssemblyQualifiedName; } catch (Exception e) { HandleException(e); return NativeString.Null(); } } [UnmanagedCallersOnly] internal static unsafe void GetBaseType(int InType, int* OutBaseType) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || OutBaseType == null || type == null) return; if (type.BaseType == null) { *OutBaseType = 0; return; } *OutBaseType = s_CachedTypes.Add(type.BaseType); } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe void GetInterfaceTypeCount(int InType, int* OutCount) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || OutCount == null || type == null) return; var typeInterfaces = type.GetInterfaces(); if (typeInterfaces == null) { *OutCount = 0; return; } *OutCount = typeInterfaces.Length; } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe void GetInterfaceTypes(int InType, int* OutTypes) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || OutTypes == null || type == null) return; var typeInterfaces = type.GetInterfaces(); if (typeInterfaces == null) { return; } for (int i = 0; i < typeInterfaces.Length; ++i) { OutTypes[i] = s_CachedTypes.Add(typeInterfaces[i]); } } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static int GetTypeSize(int InType) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return -1; return Marshal.SizeOf(type); } catch (Exception e) { HandleException(e); return -1; } } [UnmanagedCallersOnly] internal static unsafe Bool32 IsTypeSubclassOf(int InType0, int InType1) { try { if (!s_CachedTypes.TryGetValue(InType0, out var type0) || type0 == null || !s_CachedTypes.TryGetValue(InType1, out var type1) || type1 == null) return false; return type0.IsSubclassOf(type1); } catch (Exception e) { HandleException(e); return false; } } [UnmanagedCallersOnly] internal static unsafe Bool32 IsTypeAssignableTo(int InType0, int InType1) { try { if (!s_CachedTypes.TryGetValue(InType0, out var type0) || type0 == null || !s_CachedTypes.TryGetValue(InType1, out var type1) || type1 == null) return false; return type0.IsAssignableTo(type1); } catch (Exception e) { HandleException(e); return false; } } [UnmanagedCallersOnly] internal static unsafe Bool32 IsTypeAssignableFrom(int InType0, int InType1) { try { if (!s_CachedTypes.TryGetValue(InType0, out var type0) || type0 == null || !s_CachedTypes.TryGetValue(InType1, out var type1) || type1 == null) return false; return type0.IsAssignableFrom(type1); } catch (Exception e) { HandleException(e); return false; } } [UnmanagedCallersOnly] internal static unsafe Bool32 IsTypeSZArray(int InTypeID) { try { if (!s_CachedTypes.TryGetValue(InTypeID, out var type)) return false; if (type == null) { return false; } return type.IsSZArray; } catch (Exception e) { HandleException(e); return false; } } [UnmanagedCallersOnly] internal static unsafe void GetElementType(int InTypeID, int* OutElementTypeID) { try { if (!s_CachedTypes.TryGetValue(InTypeID, out var type) || type == null) return; var elementType = type.GetElementType(); if (elementType == null) *OutElementTypeID = 0; *OutElementTypeID = s_CachedTypes.Add(elementType); } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe void GetTypeMethods(int InType, int* InMethodArray, int* InMethodCount) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return; ReadOnlySpan<MethodInfo> methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); if (methods.Length == 0) { *InMethodCount = 0; return; } *InMethodCount = methods.Length; if (InMethodArray == null) return; for (int i = 0; i < methods.Length; i++) { InMethodArray[i] = s_CachedMethods.Add(methods[i]); } } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe void GetTypeFields(int InType, int* InFieldArray, int* InFieldCount) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return; ReadOnlySpan<FieldInfo> fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); if (fields.Length == 0) { *InFieldCount = 0; return; } *InFieldCount = fields.Length; if (InFieldArray == null) return; for (int i = 0; i < fields.Length; i++) { InFieldArray[i] = s_CachedFields.Add(fields[i]); } } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe void GetTypeProperties(int InType, int* InPropertyArray, int* InPropertyCount) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return; ReadOnlySpan<PropertyInfo> properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); if (properties.Length == 0) { *InPropertyCount = 0; return; } *InPropertyCount = properties.Length; if (InPropertyArray == null) return; for (int i = 0; i < properties.Length; i++) { InPropertyArray[i] = s_CachedProperties.Add(properties[i]); } } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe Bool32 HasTypeAttribute(int InType, int InAttributeType) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null || !s_CachedTypes.TryGetValue(InAttributeType, out var attributeType) || attributeType == null) return false; return type.GetCustomAttribute(attributeType) != null; } catch (Exception ex) { HandleException(ex); return false; } } [UnmanagedCallersOnly] internal static unsafe void GetTypeAttributes(int InType, int* OutAttributes, int* OutAttributesCount) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return; var attributes = type.GetCustomAttributes().ToImmutableArray(); if (attributes.Length == 0) { *OutAttributesCount = 0; return; } *OutAttributesCount = attributes.Length; if (OutAttributes == null) return; for (int i = 0; i < attributes.Length; i++) { var attribute = attributes[i]; OutAttributes[i] = s_CachedAttributes.Add(attribute); } } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe ManagedType GetTypeManagedType(int InType) { try { if (!s_CachedTypes.TryGetValue(InType, out var type) || type == null) return ManagedType.Unknown; if (!s_TypeConverters.TryGetValue(type, out var managedType)) managedType = ManagedType.Unknown; return managedType; } catch (Exception ex) { HandleException(ex); return ManagedType.Unknown; } } // TODO(Peter): Refactor this to GetMemberInfoName (should work for all types of members) [UnmanagedCallersOnly] internal static unsafe NativeString GetMethodInfoName(int InMethodInfo) { try { if (!s_CachedMethods.TryGetValue(InMethodInfo, out var methodInfo) || methodInfo == null) return NativeString.Null(); return methodInfo.Name; } catch (Exception ex) { HandleException(ex); return NativeString.Null(); } } [UnmanagedCallersOnly] internal static unsafe void GetMethodInfoReturnType(int InMethodInfo, int* OutReturnType) { try { if (!s_CachedMethods.TryGetValue(InMethodInfo, out var methodInfo) || OutReturnType == null || methodInfo == null) return; *OutReturnType = s_CachedTypes.Add(methodInfo.ReturnType); } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe void GetMethodInfoParameterTypes(int InMethodInfo, int* OutParameterTypes, int* OutParameterCount) { try { if (!s_CachedMethods.TryGetValue(InMethodInfo, out var methodInfo) || methodInfo == null) return; ReadOnlySpan<ParameterInfo> parameters = methodInfo.GetParameters(); if (parameters.Length == 0) { *OutParameterCount = 0; return; } *OutParameterCount = parameters.Length; if (OutParameterTypes == null) return; for (int i = 0; i < parameters.Length; i++) { OutParameterTypes[i] = s_CachedTypes.Add(parameters[i].ParameterType); } } catch (Exception e) { HandleException(e); } } [UnmanagedCallersOnly] internal static unsafe void GetMethodInfoAttributes(int InMethodInfo, int* OutAttributes, int* OutAttributesCount) { try { if (!s_CachedMethods.TryGetValue(InMethodInfo, out var methodInfo) || methodInfo == null) return; var attributes = methodInfo.GetCustomAttributes().ToImmutableArray(); if (attributes.Length == 0) { *OutAttributesCount = 0; return; } *OutAttributesCount = attributes.Length; if (OutAttributes == null) return; for (int i = 0; i < attributes.Length; i++) { OutAttributes[i] = s_CachedAttributes.Add(attributes[i]); } } catch (Exception ex) { HandleException(ex); } } internal enum TypeAccessibility { Public, Private, Protected, Internal, ProtectedPublic, PrivateProtected } private static TypeAccessibility GetTypeAccessibility(FieldInfo InFieldInfo) { if (InFieldInfo.IsPublic) return TypeAccessibility.Public; if (InFieldInfo.IsPrivate) return TypeAccessibility.Private; if (InFieldInfo.IsFamily) return TypeAccessibility.Protected; if (InFieldInfo.IsAssembly) return TypeAccessibility.Internal; if (InFieldInfo.IsFamilyOrAssembly) return TypeAccessibility.ProtectedPublic; if (InFieldInfo.IsFamilyAndAssembly) return TypeAccessibility.PrivateProtected; return TypeAccessibility.Public; } private static TypeAccessibility GetTypeAccessibility(MethodInfo InMethodInfo) { if (InMethodInfo.IsPublic) return TypeAccessibility.Public; if (InMethodInfo.IsPrivate) return TypeAccessibility.Private; if (InMethodInfo.IsFamily) return TypeAccessibility.Protected; if (InMethodInfo.IsAssembly) return TypeAccessibility.Internal; if (InMethodInfo.IsFamilyOrAssembly) return TypeAccessibility.ProtectedPublic; if (InMethodInfo.IsFamilyAndAssembly) return TypeAccessibility.PrivateProtected; return TypeAccessibility.Public; } [UnmanagedCallersOnly] internal static unsafe TypeAccessibility GetMethodInfoAccessibility(int InMethodInfo) { try { if (!s_CachedMethods.TryGetValue(InMethodInfo, out var methodInfo) || methodInfo == null) return TypeAccessibility.Internal; return GetTypeAccessibility(methodInfo); } catch (Exception ex) { HandleException(ex); return TypeAccessibility.Public; } } [UnmanagedCallersOnly] internal static unsafe NativeString GetFieldInfoName(int InFieldInfo) { try { if (!s_CachedFields.TryGetValue(InFieldInfo, out var fieldInfo) || fieldInfo == null) return NativeString.Null(); return fieldInfo.Name; } catch (Exception ex) { HandleException(ex); return NativeString.Null(); } } [UnmanagedCallersOnly] internal static unsafe void GetFieldInfoType(int InFieldInfo, int* OutFieldType) { try { if (!s_CachedFields.TryGetValue(InFieldInfo, out var fieldInfo) || fieldInfo == null) return; *OutFieldType = s_CachedTypes.Add(fieldInfo.FieldType); } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe TypeAccessibility GetFieldInfoAccessibility(int InFieldInfo) { try { if (!s_CachedFields.TryGetValue(InFieldInfo, out var fieldInfo) || fieldInfo == null) return TypeAccessibility.Public; return GetTypeAccessibility(fieldInfo); } catch (Exception ex) { HandleException(ex); return TypeAccessibility.Public; } } [UnmanagedCallersOnly] internal static unsafe void GetFieldInfoAttributes(int InFieldInfo, int* OutAttributes, int* OutAttributesCount) { try { if (!s_CachedFields.TryGetValue(InFieldInfo, out var fieldInfo) || fieldInfo == null) return; var attributes = fieldInfo.GetCustomAttributes().ToImmutableArray(); if (attributes.Length == 0) { *OutAttributesCount = 0; return; } *OutAttributesCount = attributes.Length; if (OutAttributes == null) return; for (int i = 0; i < attributes.Length; i++) { OutAttributes[i] = s_CachedAttributes.Add(attributes[i]); } } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe NativeString GetPropertyInfoName(int InPropertyInfo) { try { if (!s_CachedProperties.TryGetValue(InPropertyInfo, out var propertyInfo) || propertyInfo == null) return NativeString.Null(); return propertyInfo.Name; } catch (Exception ex) { HandleException(ex); return NativeString.Null(); } } [UnmanagedCallersOnly] internal static unsafe void GetPropertyInfoType(int InPropertyInfo, int* OutPropertyType) { try { if (!s_CachedProperties.TryGetValue(InPropertyInfo, out var propertyInfo) || propertyInfo == null) return; *OutPropertyType = s_CachedTypes.Add(propertyInfo.PropertyType); } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe void GetPropertyInfoAttributes(int InPropertyInfo, int* OutAttributes, int* OutAttributesCount) { try { if (!s_CachedProperties.TryGetValue(InPropertyInfo, out var propertyInfo) || propertyInfo == null) return; var attributes = propertyInfo.GetCustomAttributes().ToImmutableArray(); if (attributes.Length == 0) { *OutAttributesCount = 0; return; } *OutAttributesCount = attributes.Length; if (OutAttributes == null) return; for (int i = 0; i < attributes.Length; i++) { OutAttributes[i] = s_CachedAttributes.Add(attributes[i]); } } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe void GetAttributeFieldValue(int InAttribute, NativeString InFieldName, IntPtr OutValue) { try { if (!s_CachedAttributes.TryGetValue(InAttribute, out var attribute) || attribute == null) return; var targetType = attribute.GetType(); var fieldInfo = targetType.GetField(InFieldName!, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (fieldInfo == null) { LogMessage($"Failed to find field with name '{InFieldName}' in attribute {targetType.FullName}.", MessageLevel.Error); return; } Marshalling.MarshalReturnValue(attribute, fieldInfo.GetValue(attribute), fieldInfo, OutValue); } catch (Exception ex) { HandleException(ex); } } [UnmanagedCallersOnly] internal static unsafe void GetAttributeType(int InAttribute, int* OutType) { try { if (!s_CachedAttributes.TryGetValue(InAttribute, out var attribute) || attribute == null) return; *OutType = s_CachedTypes.Add(attribute.GetType()); } catch (Exception ex) { HandleException(ex); } } }
412
0.993026
1
0.993026
game-dev
MEDIA
0.377924
game-dev
0.988639
1
0.988639
azsdaja/Osnowa
2,108
Assets/Plugins/Zenject/Source/Runtime/Kernels/MonoKernel.cs
#if !NOT_UNITY3D using ModestTree; using UnityEngine; namespace Zenject { public abstract class MonoKernel : MonoBehaviour { [InjectLocal] TickableManager _tickableManager = null; [InjectLocal] InitializableManager _initializableManager = null; [InjectLocal] DisposableManager _disposablesManager = null; bool _hasInitialized; bool _isDestroyed; protected bool IsDestroyed { get { return _isDestroyed; } } public virtual void Start() { Initialize(); } public void Initialize() { // We don't put this in start in case Start is overridden if (!_hasInitialized) { _hasInitialized = true; _initializableManager.Initialize(); } } public virtual void Update() { // Don't spam the log every frame if initialization fails and leaves it as null if (_tickableManager != null) { _tickableManager.Update(); } } public virtual void FixedUpdate() { // Don't spam the log every frame if initialization fails and leaves it as null if (_tickableManager != null) { _tickableManager.FixedUpdate(); } } public virtual void LateUpdate() { // Don't spam the log every frame if initialization fails and leaves it as null if (_tickableManager != null) { _tickableManager.LateUpdate(); } } public virtual void OnDestroy() { // _disposablesManager can be null if we get destroyed before the Start event if (_disposablesManager != null) { Assert.That(!_isDestroyed); _isDestroyed = true; _disposablesManager.Dispose(); _disposablesManager.LateDispose(); } } } } #endif
412
0.820831
1
0.820831
game-dev
MEDIA
0.830441
game-dev
0.889881
1
0.889881
MegaMek/mekhq
8,982
MekHQ/src/mekhq/campaign/parts/kfs/KFBoom.java
/* * Copyright (C) 2019-2025 The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPL), * version 3 or (at your option) any later version, * as published by the Free Software Foundation. * * MekHQ 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. * * A copy of the GPL should have been included with this project; * if not, see <https://www.gnu.org/licenses/>. * * NOTICE: The MegaMek organization is a non-profit group of volunteers * creating free software for the BattleTech community. * * MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks * of The Topps Company, Inc. All Rights Reserved. * * Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of * InMediaRes Productions, LLC. * * MechWarrior Copyright Microsoft Corporation. MekHQ was created under * Microsoft's "Game Content Usage Rules" * <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or * affiliated with Microsoft. */ package mekhq.campaign.parts.kfs; import java.io.PrintWriter; import megamek.common.SimpleTechLevel; import megamek.common.TechAdvancement; import megamek.common.annotations.Nullable; import megamek.common.compute.Compute; import megamek.common.enums.AvailabilityValue; import megamek.common.enums.Faction; import megamek.common.enums.TechBase; import megamek.common.enums.TechRating; import megamek.common.units.Dropship; import megamek.common.units.Entity; import megamek.logging.MMLogger; import mekhq.campaign.Campaign; import mekhq.campaign.finances.Money; import mekhq.campaign.parts.Part; import mekhq.campaign.parts.missing.MissingKFBoom; import mekhq.campaign.parts.missing.MissingPart; import mekhq.campaign.personnel.skills.SkillType; import mekhq.utilities.MHQXMLUtility; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author MKerensky */ public class KFBoom extends Part { private static final MMLogger LOGGER = MMLogger.create(KFBoom.class); public static final TechAdvancement TA_KF_BOOM = new TechAdvancement(TechBase.ALL) .setAdvancement(2458, 2470, 2500) .setPrototypeFactions(Faction.TH) .setProductionFactions(Faction.TH) .setTechRating(TechRating.C) .setAvailability(AvailabilityValue.D, AvailabilityValue.C, AvailabilityValue.C, AvailabilityValue.C) .setStaticTechLevel(SimpleTechLevel.STANDARD); public static final TechAdvancement TA_PROTOTYPE_KF_BOOM = new TechAdvancement(TechBase.ALL) .setAdvancement(2458, 2470, 2500) .setPrototypeFactions(Faction.TH) .setProductionFactions(Faction.TH) .setTechRating(TechRating.C) .setAvailability(AvailabilityValue.F, AvailabilityValue.X, AvailabilityValue.X, AvailabilityValue.X) .setStaticTechLevel(SimpleTechLevel.ADVANCED); private int boomType; public KFBoom() { this(0, null, Dropship.BOOM_STANDARD); } public KFBoom(int tonnage, Campaign c, int boomType) { super(tonnage, c); this.boomType = boomType; this.name = "DropShip K-F Boom"; if (boomType == Dropship.BOOM_PROTOTYPE) { name += " (Prototype)"; } } @Override public KFBoom clone() { KFBoom clone = new KFBoom(getUnitTonnage(), campaign, boomType); clone.copyBaseData(this); return clone; } public int getBoomType() { return boomType; } @Override public void updateConditionFromEntity(boolean checkForDestruction) { int priorHits = hits; if (null != unit && unit.getEntity() instanceof Dropship) { if (((Dropship) unit.getEntity()).isKFBoomDamaged()) { hits = 1; } else { hits = 0; } if (checkForDestruction && hits > priorHits && Compute.d6(2) < campaign.getCampaignOptions().getDestroyPartTarget()) { remove(false); } } } @Override public int getBaseTime() { if (isSalvaging()) { return 3600; } return 360; } @Override public int getDifficulty() { if (isSalvaging()) { return 0; } return -1; } @Override public void updateConditionFromPart() { if (null != unit && unit.getEntity() instanceof Dropship) { ((Dropship) unit.getEntity()).setDamageKFBoom(hits > 0); } } @Override public void fix() { super.fix(); if (null != unit && unit.getEntity() instanceof Dropship) { ((Dropship) unit.getEntity()).setDamageKFBoom(false); } } @Override public void remove(boolean salvage) { if (null != unit && unit.getEntity() instanceof Dropship) { ((Dropship) unit.getEntity()).setDamageKFBoom(true); Part spare = campaign.getWarehouse().checkForExistingSparePart(this); if (!salvage) { campaign.getWarehouse().removePart(this); } else if (null != spare) { spare.changeQuantity(1); campaign.getWarehouse().removePart(this); } unit.removePart(this); Part missing = getMissingPart(); unit.addPart(missing); campaign.getQuartermaster().addPart(missing, 0, false); } setUnit(null); updateConditionFromEntity(false); } @Override public MissingPart getMissingPart() { return new MissingKFBoom(getUnitTonnage(), campaign, boomType); } @Override public @Nullable String checkFixable() { return null; } @Override public boolean needsFixing() { return (hits > 0); } @Override public Money getStickerPrice() { if (boomType == Dropship.BOOM_STANDARD) { return Money.of(10000); } else if (boomType == Dropship.BOOM_PROTOTYPE) { return Money.of(1010000); } else { return Money.zero(); } } @Override public double getTonnage() { return 0; } @Override public boolean isSamePartType(Part part) { return (part instanceof KFBoom) && (boomType == ((KFBoom) part).boomType); } @Override public void writeToXML(final PrintWriter pw, int indent) { indent = writeToXMLBegin(pw, indent); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "boomType", boomType); writeToXMLEnd(pw, indent); } @Override protected void loadFieldsFromXmlNode(Node wn) { NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); try { if (wn2.getNodeName().equalsIgnoreCase("boomType")) { boomType = Integer.parseInt(wn2.getTextContent()); } } catch (Exception ex) { LOGGER.error("", ex); } } } @Override public boolean isRightTechType(String skillType) { return skillType.equals(SkillType.S_TECH_VESSEL); } @Override public String getLocationName() { // TODO Auto-generated method stub return null; } @Override public int getLocation() { return Entity.LOC_NONE; } @Override public TechAdvancement getTechAdvancement() { if (boomType != Dropship.BOOM_STANDARD) { return TA_PROTOTYPE_KF_BOOM; } else { return TA_KF_BOOM; } } }
412
0.77592
1
0.77592
game-dev
MEDIA
0.975029
game-dev
0.961359
1
0.961359
spoutcraft/Spoutcraft
5,099
src/main/java/org/spoutcraft/client/gui/error/GuiConnectionLost.java
/* * This file is part of Spoutcraft. * * Copyright (c) 2011 SpoutcraftDev <http://spoutcraft.org/> * Spoutcraft is licensed under the GNU Lesser General Public License. * * Spoutcraft 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. * * Spoutcraft 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, see <http://www.gnu.org/licenses/>. */ package org.spoutcraft.client.gui.error; import org.lwjgl.opengl.GL11; import org.newdawn.slick.opengl.Texture; import net.minecraft.src.Minecraft; import net.minecraft.src.GuiConnecting; import net.minecraft.src.GuiScreen; import org.spoutcraft.api.Spoutcraft; import org.spoutcraft.api.gui.Button; import org.spoutcraft.api.gui.Color; import org.spoutcraft.api.gui.GenericButton; import org.spoutcraft.api.gui.GenericLabel; import org.spoutcraft.api.gui.GenericScrollArea; import org.spoutcraft.api.gui.GenericTexture; import org.spoutcraft.api.gui.RenderPriority; import org.spoutcraft.api.gui.WidgetAnchor; import org.spoutcraft.client.SpoutClient; import org.spoutcraft.client.gui.MCRenderDelegate; import org.spoutcraft.client.io.CustomTextureManager; import org.spoutcraft.client.io.FileUtil; public class GuiConnectionLost extends GuiScreen { public static String lastServerIp; public static int lastServerPort; private String message; public GuiConnectionLost() { message = "The connection to the server has been lost!"; } public GuiConnectionLost(String message) { this.message = message; } @Override public void initGui() { GenericScrollArea screen = new GenericScrollArea(); screen.setHeight(height - 16 - 24).setWidth(width).setY(16 + 24).setX(0); getScreen().attachWidget("Spoutcraft", screen); GenericLabel label = new GenericLabel("Connection Lost!"); int size = Spoutcraft.getMinecraftFont().getTextWidth(label.getText()); label.setX((int) (width / 2 - size / 2)).setY(16); label.setFixed(true).setPriority(RenderPriority.Lowest); getScreen().attachWidget("Spoutcraft", label); int top = 5; Color grey = new Color(0.80F, 0.80F, 0.80F, 0.65F); label = new GenericLabel(message); size = Spoutcraft.getMinecraftFont().getTextWidth(label.getText()); label.setX((int) (width / 2 - size / 2)).setY(top); label.setTextColor(grey); screen.attachWidget("Spoutcraft", label); LocalTexture texture = new LocalTexture(); texture.setUrl(FileUtil.getAssetsDir().getPath()+"/misc/disconnected.png").setX((int) (width / 2 - 64)).setY(top); texture.setHeight(128).setWidth(128); screen.attachWidget("Spoutcraft", texture); top += 116; Button button; button = new ReconnectButton().setText("Attempt to Reconnect"); button.setHeight(20).setWidth(200); button.setX((int) (width / 2 - button.getWidth() / 2)); button.setY(top); button.setAlign(WidgetAnchor.TOP_CENTER); screen.attachWidget("Spoutcraft", button); top += 26; button = new ReturnToServerList().setText("Return to " + SpoutClient.getInstance().getServerManager().getJoinedFromName()); button.setHeight(20).setWidth(200); button.setX((int) (width / 2 - button.getWidth() / 2)); button.setY(top); button.setAlign(WidgetAnchor.TOP_CENTER); screen.attachWidget("Spoutcraft", button); top += 26; button = new ReturnToMainMenu().setText("Return to Main Menu"); button.setHeight(20).setWidth(200); button.setX((int) (width / 2 - button.getWidth() / 2)); button.setY(top); button.setAlign(WidgetAnchor.TOP_CENTER); screen.attachWidget("Spoutcraft", button); top += 26; } @Override public void drawScreen(int var1, int var2, float var3) { drawDefaultBackground(); } } class ReconnectButton extends GenericButton { public void onButtonClick() { Minecraft.getMinecraft().displayGuiScreen(new GuiConnecting(Minecraft.getMinecraft(), GuiConnectionLost.lastServerIp, GuiConnectionLost.lastServerPort)); } } class ReturnToMainMenu extends GenericButton { public void onButtonClick() { Minecraft.getMinecraft().displayGuiScreen(new org.spoutcraft.client.gui.mainmenu.MainMenu()); } } class ReturnToServerList extends GenericButton { public void onButtonClick() { Minecraft.theMinecraft.displayGuiScreen(SpoutClient.getInstance().getServerManager().getJoinedFrom()); } } class LocalTexture extends GenericTexture { public void render() { Texture texture = CustomTextureManager.getTextureFromPath(getUrl()); if (texture != null) { GL11.glTranslatef((float) getScreenX(), (float) getScreenY(), 0); // Moves texture into place ((MCRenderDelegate)Spoutcraft.getRenderDelegate()).drawTexture(texture, (int)getWidth(), (int)getHeight(), isDrawingAlphaChannel()); } } }
412
0.876588
1
0.876588
game-dev
MEDIA
0.982563
game-dev
0.942312
1
0.942312
Kei-Luna/LunaGC_5.3.0
1,937
src/main/java/emu/grasscutter/command/commands/KillAllCommand.java
package emu.grasscutter.command.commands; import static emu.grasscutter.utils.lang.Language.translate; import emu.grasscutter.command.*; import emu.grasscutter.game.entity.*; import emu.grasscutter.game.player.Player; import emu.grasscutter.game.world.Scene; import java.util.List; @Command( label = "killall", usage = {"[<sceneId>]"}, permission = "server.killall", permissionTargeted = "server.killall.others") public final class KillAllCommand implements CommandHandler { @Override public void execute(Player sender, Player targetPlayer, List<String> args) { Scene scene = targetPlayer.getScene(); try { switch (args.size()) { case 0: // *No args* break; case 1: // [sceneId] scene = targetPlayer.getWorld().getSceneById(Integer.parseInt(args.get(0))); break; default: sendUsageMessage(sender); return; } } catch (NumberFormatException ignored) { CommandHandler.sendMessage(sender, translate(sender, "commands.execution.argument_error")); } if (scene == null) { CommandHandler.sendMessage( sender, translate(sender, "commands.killall.scene_not_found_in_player_world")); return; } // Separate into list to avoid concurrency issue final Scene sceneF = scene; List<GameEntity> toKill = sceneF.getEntities().values().stream() .filter(entity -> entity instanceof EntityMonster) .toList(); toKill.forEach(entity -> sceneF.killEntity(entity, 0)); CommandHandler.sendMessage( sender, translate(sender, "commands.killall.kill_monsters_in_scene", toKill.size(), scene.getId())); } }
412
0.890538
1
0.890538
game-dev
MEDIA
0.946809
game-dev
0.908705
1
0.908705
rogerboesch/SceneKitTutorial
2,997
partV/Handicap.swift
// // Handicap.swift // // Part 5 of the SceneKit Tutorial Series 'From Zero to Hero' at: // https://rogerboesch.github.io/ // // Created by Roger Boesch on 13/12/17. // Copyright © 2017 Roger Boesch. All rights reserved. // import SceneKit // ----------------------------------------------------------------------------- class Handicap : GameObject { private var _node: SCNNode! private var _height: CGFloat = 0 // ------------------------------------------------------------------------- // MARK: - Propertiues override var description: String { get { return "handicap \(self.id)" } } // ------------------------------------------------------------------------- var height: CGFloat { get { return _height } } // ------------------------------------------------------------------------- // MARK: - Actions override func hit() { if self.state != .alive { return } self.state = .died let action1 = SCNAction.moveBy(x: 0, y: -3, z: 0, duration: 0.15) _node.runAction(action1) let action2 = SCNAction.rotateBy(x: degreesToRadians(value: 30), y: 0, z: degreesToRadians(value: 15), duration: 0.3) _node.runAction(action2) if let emitter = SCNParticleSystem(named: "art.scnassets/fire.scnp", inDirectory: nil) { self.addParticleSystem(emitter) } } // ------------------------------------------------------------------------- // MARK: - Initialisation override init() { super.init() // Use some randomness in height, width and color let material = SCNMaterial() material.diffuse.contents = UIColor.random(list: UIGreenColorList) let width = RBRandom.cgFloat(4.0, 9.0) _height = RBRandom.cgFloat(15.0, 25) var geometry: SCNGeometry! let rnd = RBRandom.integer(1, 3) if rnd == 1 { geometry = SCNBox(width: width, height: _height, length: 2.0, chamferRadius: 0.0) } else if rnd == 2 { geometry = SCNCylinder(radius: width, height: _height) } else { geometry = SCNCone(topRadius: 0.0, bottomRadius: width, height: _height) } geometry.materials = [material] _node = SCNNode(geometry: geometry) _node.name = "handicap" _node.physicsBody = SCNPhysicsBody(type: .kinematic, shape: nil) _node.physicsBody?.categoryBitMask = Game.Physics.Categories.enemy self.addChildNode(_node) self.state = .alive } // ------------------------------------------------------------------------- required init(coder: NSCoder) { fatalError("Not yet implemented") } // ------------------------------------------------------------------------- }
412
0.844973
1
0.844973
game-dev
MEDIA
0.560037
game-dev,graphics-rendering
0.735193
1
0.735193
provencher/MRTK-Quest-Sample
3,618
Assets/Oculus/VR/Scripts/Util/OVRCustomSkeleton.cs
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Your use of this SDK or tool is subject to the Oculus SDK License Agreement, available at https://developer.oculus.com/licenses/oculussdk/ Unless required by applicable law or agreed to in writing, the Utilities SDK 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.Collections; using System.Collections.Generic; using UnityEngine; [DefaultExecutionOrder(-80)] public class OVRCustomSkeleton : OVRSkeleton { [SerializeField] private bool _applyBoneTranslations = true; [HideInInspector] [SerializeField] private List<Transform> _customBones_V2 = new List<Transform>(new Transform[(int)BoneId.Max]); #if UNITY_EDITOR private static readonly string[] _fbxHandSidePrefix = { "l_", "r_" }; private static readonly string _fbxHandBonePrefix = "b_"; private static readonly string[] _fbxHandBoneNames = { "wrist", "forearm_stub", "thumb0", "thumb1", "thumb2", "thumb3", "index1", "index2", "index3", "middle1", "middle2", "middle3", "ring1", "ring2", "ring3", "pinky0", "pinky1", "pinky2", "pinky3" }; private static readonly string[] _fbxHandFingerNames = { "thumb", "index", "middle", "ring", "pinky" }; #endif public List<Transform> CustomBones { get { return _customBones_V2; } } #if UNITY_EDITOR public void TryAutoMapBonesByName() { BoneId start = GetCurrentStartBoneId(); BoneId end = GetCurrentEndBoneId(); SkeletonType skeletonType = GetSkeletonType(); if (start != BoneId.Invalid && end != BoneId.Invalid) { for (int bi = (int)start; bi < (int)end; ++bi) { string fbxBoneName = FbxBoneNameFromBoneId(skeletonType, (BoneId)bi); Transform t = transform.FindChildRecursive(fbxBoneName); if (t != null) { _customBones_V2[(int)bi] = t; } } } } private static string FbxBoneNameFromBoneId(SkeletonType skeletonType, BoneId bi) { { if (bi >= BoneId.Hand_ThumbTip && bi <= BoneId.Hand_PinkyTip) { return _fbxHandSidePrefix[(int)skeletonType] + _fbxHandFingerNames[(int)bi - (int)BoneId.Hand_ThumbTip] + "_finger_tip_marker"; } else { return _fbxHandBonePrefix + _fbxHandSidePrefix[(int)skeletonType] + _fbxHandBoneNames[(int)bi]; } } } #endif protected override void InitializeBones() { bool flipX = (_skeletonType == SkeletonType.HandLeft || _skeletonType == SkeletonType.HandRight); if (_bones == null || _bones.Count != _skeleton.NumBones) { _bones = new List<OVRBone>(new OVRBone[_skeleton.NumBones]); Bones = _bones.AsReadOnly(); } for (int i = 0; i < _bones.Count; ++i) { OVRBone bone = _bones[i] ?? (_bones[i] = new OVRBone()); bone.Id = (OVRSkeleton.BoneId)_skeleton.Bones[i].Id; bone.ParentBoneIndex = _skeleton.Bones[i].ParentBoneIndex; bone.Transform = _customBones_V2[(int)bone.Id]; if (_applyBoneTranslations) { bone.Transform.localPosition = flipX ? _skeleton.Bones[i].Pose.Position.FromFlippedXVector3f() : _skeleton.Bones[i].Pose.Position.FromFlippedZVector3f(); } bone.Transform.localRotation = flipX ? _skeleton.Bones[i].Pose.Orientation.FromFlippedXQuatf() : _skeleton.Bones[i].Pose.Orientation.FromFlippedZQuatf(); } } }
412
0.782626
1
0.782626
game-dev
MEDIA
0.957095
game-dev
0.923498
1
0.923498
Systems-ShiftLab/MultiPIM
5,760
common/DRAMPower/src/MemBankWiseParams.cc
/* * Copyright (c) 2012-2014, TU Delft * Copyright (c) 2012-2014, TU Eindhoven * Copyright (c) 2012-2016, TU Kaiserslautern * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Subash Kannoth, Matthias Jung, Éder F. Zulian * */ #include "MemBankWiseParams.h" using namespace Data; /** * Sets the default bankwise configurations. */ MemBankWiseParams::MemBankWiseParams(): bwPowerFactRho(100), bwPowerFactSigma(100), bwMode(false), flgPASR(false) { } /** * Sets all the bankwise parameters required in bankwise mode */ MemBankWiseParams::MemBankWiseParams(int64_t factRho, int64_t factSigma, bool hasPASR, int64_t pasrMode, bool opMode, unsigned nbrofBanks) { bwPowerFactRho = factRho; bwPowerFactSigma = factSigma; bwMode = opMode; flgPASR = hasPASR; /////////////////////////////////////////////////////////// // Activate banks for self refresh based on the PASR mode // ACTIVE - X // NOT ACTIVE - 0 /////////////////////////////////////////////////////////// switch(pasrMode){ case(PASR_0):{ // PASR MODE 0 // FULL ARRAY // |X X X X | // |X X X X | activeBanks.resize(nbrofBanks); std::iota(activeBanks.begin(), activeBanks.end(), 0); break; } case(PASR_1):{ // PASR MODE 1 // (1/2) ARRAY // |X X X X | // |0 0 0 0 | activeBanks.resize(nbrofBanks - 4); std::iota(activeBanks.begin(), activeBanks.end(), 0); break; } case(PASR_2):{ // PASR MODE 2 // (1/4) ARRAY // |X X 0 0 | // |0 0 0 0 | activeBanks.resize(nbrofBanks - 6); std::iota(activeBanks.begin(), activeBanks.end(), 0); break; } case(PASR_3):{ // PASR MODE 3 // (1/8) ARRAY // |X 0 0 0 | // |0 0 0 0 | activeBanks.resize(nbrofBanks - 7); std::iota(activeBanks.begin(), activeBanks.end(), 0); break; } case(PASR_4):{ // PASR MODE 4 // (3/4) ARRAY // |0 0 X X | // |X X X X | activeBanks.resize(nbrofBanks - 2); std::iota(activeBanks.begin(), activeBanks.end(), 2); break; } case(PASR_5):{ // PASR MODE 5 // (1/2) ARRAY // |0 0 0 0 | // |X X X X | activeBanks.resize(nbrofBanks - 4); std::iota(activeBanks.begin(), activeBanks.end(), 4); break; } case(PASR_6):{ // PASR MODE 6 // (1/4) ARRAY // |0 0 0 0 | // |0 0 X X | activeBanks.resize(nbrofBanks - 6); std::iota(activeBanks.begin(), activeBanks.end(), 6); break; } case(PASR_7):{ // PASR MODE 7 // (1/8) ARRAY // |0 0 0 0 | // |0 0 0 X | activeBanks.resize(nbrofBanks - 7); std::iota(activeBanks.begin(), activeBanks.end(), 7); break; } default:{ // PASR MODE 0 // FULL ARRAY // |X X X X | // |X X X X | activeBanks.resize(nbrofBanks); std::iota(activeBanks.begin(), activeBanks.end(), 0); break; } } } /** * Returns true if the given bank is active under the current PASR mode. */ bool MemBankWiseParams::isBankActiveInPasr(const unsigned bankIdx) const { return (std::find(activeBanks.begin(), activeBanks.end(), bankIdx) != activeBanks.end()); }
412
0.561164
1
0.561164
game-dev
MEDIA
0.534987
game-dev
0.947591
1
0.947591
quiverteam/Engine
1,087
src/Tracker/AdminServer/rulesinfomsghandler.h
//========= Copyright 1996-2001, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #ifndef RULESINFOMSGHANDLERDETAILS_H #define RULESINFOMSGHANDLERDETAILS_H #ifdef _WIN32 #pragma once #endif #include "Socket.h" #include "UtlVector.h" class CRulesInfo; #include <VGUI_PropertyPage.h> #include <VGUI_Frame.h> #include <VGUI_ListPanel.h> #include <VGUI_KeyValues.h> //----------------------------------------------------------------------------- // Purpose: Socket handler for pinging internet servers //----------------------------------------------------------------------------- class CRulesInfoMsgHandlerDetails : public CMsgHandler { public: CRulesInfoMsgHandlerDetails(CRulesInfo *baseobject, HANDLERTYPE type, void *typeinfo = NULL); virtual bool Process(netadr_t *from, CMsgBuffer *msg); private: // the parent class that we push info back to CRulesInfo *m_pRulesInfo; CUtlVector<vgui::KeyValues *> *m_vRules; }; #endif // RULESINFOMSGHANDLERDETAILS_H
412
0.842129
1
0.842129
game-dev
MEDIA
0.602958
game-dev
0.537839
1
0.537839
RoyTheunissen/URP-Custom-Gbuffer
3,341
Packages/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePathInspector.cs
using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.EditorTools; namespace UnityEditor.Rendering.Universal.Path2D { internal class GenericScriptablePathInspector<U, T> : ScriptablePathInspector where U : ScriptableData<T> { private List<U> m_DataObjects = new List<U>(); private List<U> m_SelectedDataObjects = new List<U>(); private Editor m_CachedEditor = null; private void OnEnable() { PrepareDataObjects(); } private void OnDestroy() { DestroyDataObjects(); } public override void OnInspectorGUI() { base.OnInspectorGUI(); DoCustomDataInspector(); } protected void DoCustomDataInspector() { PrepareDataObjects(); if (m_SelectedDataObjects.Count > 0) { CreateCachedEditor(m_SelectedDataObjects.ToArray(), null, ref m_CachedEditor); EditorGUI.BeginChangeCheck(); m_CachedEditor.OnInspectorGUI(); if (EditorGUI.EndChangeCheck()) SetDataObjects(); } } private void PrepareDataObjects() { var elementCount = 0; m_SelectedDataObjects.Clear(); foreach (var path in paths) elementCount += path.pointCount; while (m_DataObjects.Count < elementCount) CreateDataObject(); var index = 0; foreach (var path in paths) { var genericPath = path as GenericScriptablePath<T>; var customDataArray = genericPath.data; var length = customDataArray.Length; for (var i = 0; i < length; ++i) { var dataObject = m_DataObjects[index + i]; dataObject.data = customDataArray[i]; if (path.selection.Contains(i)) { dataObject.owner = path.owner; dataObject.index = i; m_SelectedDataObjects.Add(dataObject); } } index += length; } } private void SetDataObjects() { var index = 0; foreach (var path in paths) { var genericPath = path as GenericScriptablePath<T>; var customDataArray = genericPath.data; var length = customDataArray.Length; for (var i = 0; i < length; ++i) customDataArray[i] = m_DataObjects[index + i].data; genericPath.data = customDataArray; index += length; } } private U CreateDataObject() { var dataObject = ScriptableObject.CreateInstance<U>(); m_DataObjects.Add(dataObject); return dataObject; } private void DestroyDataObjects() { foreach (var customDataObject in m_DataObjects) DestroyImmediate(customDataObject); m_DataObjects.Clear(); m_SelectedDataObjects.Clear(); } } }
412
0.922338
1
0.922338
game-dev
MEDIA
0.676025
game-dev
0.893034
1
0.893034
aers/FFXIVClientStructs
143,384
ida/old/data_2022.03.01.0000.0000.yml
version: 2022.03.01.0000.0000 globals: 0x141714860: g_UIColorTable 0x141757368: g_HUDScaleTable 0x141E235D0: g_InputManager 0x141E235F8: g_InputManager_MouseButtonHoldState 0x141E6F400: g_RenderSkeletonLinkedListStart 0x141E6F408: g_RenderSkeletonLinkedListEnd 0x141E6F460: g_RenderModelLinkedListStart 0x141E6F468: g_RenderModelLinkedListEnd 0x141E7C740: g_PlayerMoveController 0x141E7CCE8: g_LocalPlayerObjectID 0x141E7CCF0: g_LocalPlayer 0x141EA2770: g_LastTextCommand 0x141EA2B00: g_CharacterManager_BattleCharaMemoryPtr 0x141EA2B08: g_CharacterManager_CompanionMemoryPtr 0x141EA2B38: g_GameObjectManager_ObjectList 0x141EA3878: g_GameObjectManager_ObjectListEnd 0x141EA7388: g_Client::Game::UI::Buddy.Pet # not a pointer 0x141EA7398: g_Client::Game::UI::Buddy.Pet.BuffList # not a pointer 0x141EA8048: g_Client::Game::UI::Buddy.CompanionStats # not a pointer. Member of UIState 0x141EA8050: g_Client::Game::UI::Buddy.CompanionStats.TimeRemaining # not a pointer 0x141EA80A0: g_Client::Game::UI::Buddy.BattleBuddyListPtr # Member of UIState 0x141EA81E8: g_Client::Game::UI::RelicNote # not a pointer 0x141EB43F0: g_TitleController 0x141EB43F8: g_TitleList 0x141ECBA88: g_FateTablePtr 0x141ECB740: g_ClientObjectManager 0x141E5D330: g_SomeOtherRenderingState 0x141E6F494: g_InvSqrt3 functions: 0x140060CC0: MemoryManager_Alloc 0x1400623D0: MemoryManager_GetDefaultSpace 0x140062490: MemoryManager_GetApricotSpace 0x1400624B0: MemoryManager_GetAnimationSpace 0x1400624D0: MemoryManager_GetUISpace 0x140062550: MemoryManager_GetFileSpace 0x1400624F0: MemoryManager_GetSoundSpace_1 0x140062510: MemoryManager_GetSoundSpace_2 0x140065720: IsMacClient 0x1400A51E0: Client::UI::PlaySoundEffect # this is a static function in the UI namespace, arg1 is the SE 0x1400A6CD0: Client::UI::GetUIColor # (idx, &color, &edgeColor) 0x14019D1C0: j_SleepEx 0x1401C1100: Client::System::Resource::Handle::ModelResourceHandle_GetMaterialFileNameBySlot 0x1402B57A0: CountdownPointer 0x1402F9620: std::vector_SetSize 0x140439EB0: GetGameObjectByIndex 0x1404532E0: PrepareColorSet 0x1404535B0: ReadStainingTemplate 0x1404A5070: Client::Game::Control::InputManager_GetInputStatus 0x1404BC4A0: Client::System::Input::InputData_IsInputIDKeyPress 0x1404BC5B0: Client::System::Input::InputData_IsInputIDClicked 0x1404BCEF0: Client::System::Input::InputData_IsMouseCombinationDragged 0x1404C6D90: Component::GUI::AtkCursor_SetCursorType # the cursor's icon I believe 0x1404EF4E0: GetScaleListEntryFromScale 0x1404FDAF0: GetScaleForListOption 0x14054AC20: Component::GUI::TextModuleInterface::GetTextLabelByID 0x140626690: ConvertLogMessageIdToCharaLogKind 0x140706350: ExecuteCommand 0x1408AC6E0: CreateSelectYesno 0x140A47F10: GetBeastTribeAllowance 0x141034790: Client::UI::AddonHudLayoutScreen::MoveableAddonInfoStruct_UpdateAddonPosition 0x141125440: Client::Graphics::Kernel::CreateShader # static function 0x1411B98C0: lua_close 0x1411B9940: lua_newstate 0x1411B9C40: lua_index2addr 0x1411B9D10: lua_atpanic 0x1411B9D30: lua_call 0x1411B9D80: lua_checkstack 0x1411B9E20: lua_concat 0x1411B9EB0: lua_cpcall 0x1411B9EF0: lua_createtable 0x1411B9F60: lua_dump 0x1411B9FE0: lua_equal 0x1411BA040: lua_error 0x1411BA050: lua_gc 0x1411BA1F0: lua_getallocf 0x1411BA210: lua_getfenv 0x1411BA290: lua_getfield 0x1411BA300: lua_getmetatable 0x1411BA360: lua_gettable 0x1411BA390: lua_gettop 0x1411BA3A0: lua_setupvalue 0x1411BA440: lua_insert 0x1411BA490: lua_iscfunction 0x1411BA4C0: lua_isnumber 0x1411BA4F0: lua_isstring 0x1411BA530: lua_isuserdata 0x1411BA560: lua_lessthan 0x1411BA5B0: lua_load 0x1411BA600: lua_newthread 0x1411BA640: lua_newuserdata 0x1411BA6B0: lua_next 0x1411BA6F0: lua_objlen 0x1411BA770: lua_pcall 0x1411BA800: lua_pushboolean 0x1411BA820: lua_pushcclosure 0x1411BA8F0: lua_pushfstring 0x1411BA940: lua_pushinteger 0x1411BA960: lua_pushlightuserdata 0x1411BA980: lua_pushlstring 0x1411BA9F0: lua_pushnil 0x1411BAA10: lua_pushnumber 0x1411BAA30: lua_pushstring 0x1411BAA60: lua_pushthread 0x1411BAA90: lua_pushvalue 0x1411BAAC0: lua_pushvfstring 0x1411BAB10: lua_rawequal 0x1411BAB60: lua_rawget 0x1411BABA0: lua_rawgeti 0x1411BABE0: lua_rawset 0x1411BAC60: lua_rawseti 0x1411BACE0: lua_remove 0x1411BAD30: lua_replace 0x1411BAE00: lua_setallocf 0x1411BAE20: lua_setfenv 0x1411BAEC0: lua_setfield 0x1411BAF30: lua_setlevel 0x1411BAF40: lua_setmetatable 0x1411BB000: lua_settable 0x1411BB030: lua_settop 0x1411BB090: lua_getupvalue 0x1411BB180: lua_status 0x1411BB190: lua_toboolean 0x1411BB1C0: lua_tocfunction 0x1411BB1F0: lua_tointeger 0x1411BB220: lua_tolstring 0x1411BB2C0: lua_tonumber 0x1411BB300: lua_topointer 0x1411BB370: lua_tothread 0x1411BB390: lua_touserdata 0x1411BB3D0: lua_type 0x1411BB400: lua_typename 0x1411BB420: lua_xmove 0x1411BC330: lua_resume 0x1411BC480: lua_yield 0x1412A9F50: lua_gethook 0x1412A9F60: lua_gethookcount 0x1412A9F70: lua_gethookmask 0x1412A9F80: lua_getinfo 0x1412AA070: lua_getlocal 0x1412AA0E0: lua_getstack 0x1412AA160: lua_sethook 0x1412AA190: lua_setlocal 0x1411BC6C0: luaL_openlibs 0x1411BC8B0: luaL_addlstring 0x1411BC950: luaL_addstring 0x1411BD960: luaL_openlib 0x1411BC970: luaL_addvalue 0x1411BCA30: luaL_argerror 0x1411BCB20: luaL_buffinit 0x1411BCB40: luaL_callmeta 0x1411BCBC0: luaL_checkany 0x1411BCC00: luaL_checkinteger 0x1411BCC50: luaL_checklstring 0x1411BCCE0: luaL_checknumber 0x1411BCD40: luaL_checkoption 0x1411BCE00: luaL_checkstack 0x1411BCE40: luaL_checktype 0x1411BCE80: luaL_checkudata 0x1411BCF40: luaL_error 0x1411BCFA0: luaL_findtable 0x1411BD0D0: luaL_getmetafield 0x1411BD150: luaL_gsub 0x1411BD590: luaL_loadbuffer 0x1411BD5C0: luaL_loadfile 0x1411BD860: luaL_loadstring 0x1411BD8A0: luaL_newmetatable 0x1411BD920: luaL_newstate 0x1411BDAE0: luaL_optinteger 0x1411BDB50: luaL_optlstring 0x1411BDBD0: luaL_optnumber 0x1411BDC40: luaL_prepbuffer 0x1411BDCA0: luaL_pushresult 0x1411BDCF0: luaL_ref 0x1411BDDB0: luaL_register 0x1411BDDC0: luaL_typerror 0x1411BDE20: luaL_unref 0x1411BDEA0: luaL_where 0x1412A9F80: lua_getinfo 0x1412AA070: lua_getlocal 0x1412AA0E0: lua_getstack 0x1412B2FF0: luaopen_base 0x1412B3B50: luaopen_table 0x1412B4EF0: luaopen_io 0x1412B5CC0: luaopen_os 0x1412B70E0: luaopen_string 0x1412B8750: luaopen_math 0x1412B97E0: luaopen_debug 0x1412BA2D0: luaopen_package 0x14138BBE0: crc 0x1413E1174: ThrowException 0x141407A34: FreeMemory 0x140055A40: FreeMemory_2 # nullsub, gets called together with some AllocatorManager vfunc 0x14140F990: _purecall # Ghidra does not have a notation for pure virtual calls 0x140060C20: MemAlloc 0x1401E4DF0: MatrixMultiply 0x1401E1E00: MatrixMultiply2 0x1401E0B60: MatrixVectorMultiply 0x1401E2100: MatrixInverse 0x1401E2720: MatrixInverseMaybe 0x1401E40D0: MakeProjectionMatrix 0x1401E4360: MakeProjectionMatrix2 0x140328F50: SubmitConstantBufferUpdate 0x1400A8B80: IsLocalPlayerPartyLeader 0x1400A8A90: IsLocalPlayerInParty 0x1400A8BE0: IsPartyMemberByNameOrContentId # (name, contentId) 0x1400A8D10: GetPartyMemberClassJobByContentId 0x1406DEFE0: ObjectIdToPlayerObjectId # returns invalid id if objectid is not a player classes: Client::Game::GameMain: instances: - ea: 0x141E72FB0 pointer: False funcs: 0x140492EC0: Initialize 0x1404931D0: Terminate 0x1404934C0: Update 0x1404952B0: ctor Client::Game::StatusManager: funcs: 0x1406E7D30: Initialize 0x1406E9CD0: HasStatus 0x1406EAE70: GetStatusIndex 0x1406EACB0: GetStatusIdByIndex 0x1406EACD0: GetRemainingTimeByIndex 0x1406EAD00: GetSourceIdByIndex Client::Game::RetainerManager: instances: - ea: 0x141ECADC0 pointer: False funcs: 0x140CB1B10: GetRetainerBySortedIndex Client::Game::Control::TargetSystem::ListFeeder: Client::Game::InstanceContent::ContentSheetWaiterInterface: Client::Game::Object::IGameObjectEventListener: Client::Graphics::RenderObjectList: Client::Graphics::Singleton: Client::System::Common::NonCopyable: Client::System::Crypt::CryptInterface: Client::System::Input::InputData::InputCodeModifiedInterface: Client::System::Input::SoftKeyboardDeviceInterface::SoftKeyboardInputInterface: Client::System::Input::TextServiceInterface: Client::System::Input::TextServiceInterface::TextServiceEvent: Client::System::Input::InputDeviceManager: instances: - ea: 0x141E72D18 Client::System::Resource::Handle::ResourceHandleFactory: Client::UI::Agent::AgentMap::MapMarkerStructSearch: Client::UI::Atk2DMap: Component::Excel::ExcelLanguageEvent: Component::GUI::AtkComponentWindowGrab: Component::GUI::AtkDragDropInterface: Component::GUI::AtkExternalInterface: Component::GUI::AtkManagedInterface: Component::GUI::AtkModuleEvent: Component::GUI::AtkModuleInterface: Component::GUI::AtkModuleInterface::AtkEventInterface: vtbls: - ea: 0x141714C40 vfuncs: 0: ReceiveEvent Component::GUI::AtkTextInput::AtkTextInputEventInterface: Component::Text::TextChecker::ExecNonMacroFunc: Component::Text::TextModule: Component::Text::TextModuleInterface: SQEX::CDev::Engine::Sd::SdMemoryAllocator: SQEX::CDev::Engine::Sd::Driver::BankController: Client::System::Scheduler::Base::LinkList: Client::Game::Network::PacketElement: vtbls: - ea: 0x14176FA40 Client::Game::Network::PacketContext: vtbls: - ea: 0x14176FA48 Client::Game::Control::Control: funcs: 0x1404B4880: Initialize 0x1404B4AF0: Update Component::GUI::AtkInputManager: funcs: 0x1404FF5F0: HandleInput 0x140500DB0: SetFocus 0x1405018A0: HandleFocus 0x140501D80: ctor Client::Game::CameraManager: funcs: 0x14118D7C0: PreUpdate Client::Game::Object::GameObjectManager: instances: - ea: 0x141EA2B20 pointer: False funcs: 0x1407559E0: Update 0x140756170: DeleteAllModels 0x140756280: DeleteAllObjects # IMPORTANT:: DONT EVER CALL THIS FOR REAL OKAY 0x140755400: GetFilteredObjectById 0x1407555D0: UpdateObjectArrays 0x140755770: UpdateObjectArraysWrapper 0x140755780: UpdateObjectArraysWrapper2 0x1407557A0: ClearObjectArrays Client::Game::Character::CharacterManager: instances: - ea: 0x141EA27E0 pointer: False funcs: 0x140754380: Initialize 0x1407547F0: DeleteCharacterAtIndex 0x140754890: DeleteAllCharacters 0x140754980: LookupBattleCharaByObjectID 0x1407549E0: LookupBattleCharaByName 0x140754AD0: LookupRetainerByName 0x140754B70: LookupBuddyByOwnerObject 0x140754BF0: LookupPetByOwnerObject 0x140754CD0: LookupBattleNpcPartsByObjectId Client::Game::Group::GroupManager: instances: - ea: 0x141EC3260 pointer: False - ea: 0x141EC6FD0 name: SecondInstance pointer: False funcs: 0x140757570: ctor 0x1407576E0: SetPartyEmpty 0x140758470: GetAllianceMemberByGroupAndIndex # (this, group, index) 0x1407584D0: GetAllianceMemberByIndex # (this, index) 0x1407584F0: IsObjectIDInParty # (this, objectID) 0x140758550: IsCharacterInPartyByName # (this, char*) 0x1407585D0: IsObjectIDInAlliance 0x140758640: IsObjectIDPartyLeader 0x140758900: UpdateAllianceMemberAtIndex 0x140758C10: GetPartyMemberByIndex 0x140758C90: GetPartyMemberByContentId 0x140758BB0: GetPartyMemberByObjectId 0x140B97F90: Create 0x140B97ED0: GetGroupManager Client::Game::Balloon: funcs: 0x141239090: OpenBalloon 0x141239100: CloseBalloon 0x1412391F0: Initialize 0x141239230: SetDefaultId 0x141239240: Reset # this is near identical to Initialize but is called in update instead 0x141239280: Update 0x1412393E0: Terminate 0x141239430: StartTimerMode # (Balloon* this, float timer, ushort id) if id == 1 use default id else use id 0x141239470: StartOtherMode # (Balloon* this, ushort id) id same as above FateManager: funcs: 0x14110C950: HasValue # g_FateTablePtr != 0 0x14110C970: GetPtr # return g_FateTablePtr 0x14110C980: ctor 0x14110C9D0: dtor BattleBuddyList: funcs: 0x14079B1E0: GetMemberBattleCharaByIndex InventoryManager: instances: - ea: 0x141E9E160 pointer: False funcs: 0x1406B7600: GetInventoryContainer # (this, containerId) 0x1406B87E0: MoveItemSlot # (srcContainer, srcSlot, dstContainer, dstSlot, 1) 0x1406BF7A0: GetInventoryItemCount # (this, itemId, hq, 1, 1, 0) 0x1406BFF10: GetItemCountInContainer # (this, itemId, containerId, hq, 0) InventoryContainer: funcs: 0x1406B5F40: GetInventorySlot # (this, slotIndex) Client::System::String::Utf8String: funcs: 0x140059D80: ctor # empty string ctor 0x140059DC0: ctor_copy # copy constructor 0x140059E40: ctor_FromCStr # from null-terminated string 0x140059ED0: ctor_FromSequence # (FFXIVString, char * str, size_t size) 0x14005A440: Copy 0x14005A990: dtor 0x14005AA10: SetString 0x14005ABE0: FormatString 0x14005B0E0: GetString 0x14005CF50: Clear Component::GUI::AtkValue: funcs: 0x1404BE590: dtor 0x1404BE5D0: GetBool 0x1404BE5F0: GetInt 0x1404BE610: GetUInt # these two could be backwards 0x1404BE630: GetFloat 0x1404BE650: GetString 0x1404BE670: GetUnkPtr # could also be string, returns a pointer size 0x1404BE6B0: SetString 0x1404BE740: CopyValue # = operator 0x1404BE7B0: Equals # == operator 0x1404BE930: CreateArray # uses std::vector for array type (9) 0x1404BEBD0: ChangeType 0x1404BEDE0: ReleaseManagedMemory # called by SetString, frees old strings Component::GUI::AtkEvent: funcs: 0x1404C5A60: SetEventIsHandled Component::GUI::AtkEventManager: funcs: 0x1404C5AC0: RegisterEvent 0x1404C5BB0: UnregisterEvent 0x1404C5D80: DispatchEvent 0x1404C5EF0: Cleanup Component::GUI::AtkEventDispatcher: funcs: 0x1404C61E0: DispatchEvent 0x1404C64D0: RemoveEvent Component::GUI::AtkTooltipArgs: funcs: 0x1404C7D70: ctor Component::GUI::AtkUldManager: funcs: 0x1404E7C80: SetupFromULDResourceHandle 0x1404EA0A0: ReadTPHD 0x1404EA2B0: ReadASHDAndLoadTextures 0x1404EA790: CreateAtkNode 0x1404EBBA0: CreateAtkComponent 0x1404ED1A0: DuplicateNode 0x1404ED680: SearchNodeByIndex # this supports indexes greater than the node count, there's something i don't understand going on w/ addons here 0x1404ED6F0: GetDuplicatedNode Component::GUI::AtkArrayDataHolder: funcs: 0x1404BEE90: ctor Client::System::Resource::ResourceManager: instances: - ea: 0x141E5D3B0 funcs: 0x1401B8190: ctor 0x1401B8680: CreateSingleton 0x1401B8780: Update 0x1401B8B60: GetResourceAsync 0x1401B8D90: GetResourceSync 0x1401BD570: Initialize Client::Game::UI::UIState: instances: - ea: 0x141EA5800 pointer: False funcs: 0x1407BBB80: Initialize 0x1407CCB00: ctor 0x1407B96F0: IsUnlockLinkUnlocked Client::Game::UI::PlayerState: funcs: 0x140760460: SetCharacterName 0x140761A40: GetBeastTribeRank 0x140761AC0: GetBeastTribeCurrentRep 0x140761B00: GetBeastTribeNeededRep 0x140764390: Initialize 0x1407CC2E0: ctor Client::Game::UI::Revive: vtbls: - ea: 0x141780488 base: Component::GUI::AtkModuleInterface::AtkEventInterface Client::Game::UI::Buddy: instances: - ea: 0x141EA71F0 pointer: False funcs: 0x14079B570: ctor Client::Game::UI::RelicNote: vtbls: - ea: 0x1417813B0 funcs: 0x1407A5940: GetRelicID 0x1407A5950: GetRelicNoteID 0x1407A5960: GetMonsterProgress 0x1407A5A00: IsDungeonComplete 0x1407A5A40: IsFateComplete 0x1407A5A80: IsLeveComplete Client::Game::UI::MobHunt: vtbls: - ea: 0x141781430 Client::Game::BattleLog: funcs: 0x1407BD430: AddLogMessage 0x1407BE310: AddActionLogMessage 0x1407BEA20: AddToScreenLogWithLogMessageId # this converts log message id to screen log kind and calls below function 0x1407BEB00: AddToScreenLogWithScreenLogKind Client::Game::ActionManager: instances: - ea: 0x141E26720 pointer: False vtbls: - ea: 0x1417818D0 base: Client::Graphics::Vfx::VfxDataListenner funcs: 0x140048D80: StaticInitializer 0x1400A9770: GetCurrentComboActionId 0x1407DDF90: GetActionRange 0x1407DE330: GetActionInRangeOrLoS 0x1407DE960: GetAdjustedCastTime 0x1407DF130: GetAdjustedRecastTime 0x1407DF890: GetActionCost 0x1407E0120: GetSpellIdForAction 0x1407E1640: UseActionLocation 0x1407E2460: UseGeneralAction 0x1407E30B0: UseWaymarkAction 0x1407E3BA0: CheckActionResources 0x1407E73A0: GetActionStatus 0x1407E9090: CanUseAction 0x1407E9850: GetAdjustedActionId 0x1407EAA50: UseAction 0x1407EB1C0: UseComboAction 0x1407EBAE0: GetRecastTimerActive 0x1407EBEA0: StartCooldown 0x1407EC1D0: GetRecastTimerElapsed 0x1407EC280: GetRecastTime 0x1407EC390: UpdateRecastFromNetwork 0x1407F06D0: GetMaxCharges 0x1407E13C0: GetRecastGroup 0x1407E6600: GetRecastGroupDetail 0x1407E66D0: Update Client::Game::JobGaugeManager: instances: - ea: 0x141E73A88 pointer: False funcs: 0x1407FAE60: ctor 0x1407FAE90: dtor 0x1407FAFD0: Update 0x1407FB0F0: ChangeGauge Client::Game::Gauge::JobGauge: vtbls: - ea: 0x1417818E0 vfuncs: 0: dtor 1: Init 4: SetValues Client::Game::Gauge::PaladinGauge: vtbls: - ea: 0x141781918 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::MonkGauge: vtbls: - ea: 0x141781950 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::WarriorGauge: vtbls: - ea: 0x141781988 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::DragoonGauge: vtbls: - ea: 0x1417819C0 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::BardGauge: vtbls: - ea: 0x1417819F8 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::WhiteMageGauge: vtbls: - ea: 0x141781A30 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::BlackMageGauge: vtbls: - ea: 0x141781A68 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::SummonerGauge: vtbls: - ea: 0x141781AA0 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::ScholarGauge: vtbls: - ea: 0x141781AD8 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::NinjaGauge: vtbls: - ea: 0x141781B10 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::MachinistGauge: vtbls: - ea: 0x141781B48 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::DarkKnightGauge: vtbls: - ea: 0x141781B80 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::AstrologianGauge: vtbls: - ea: 0x141781BB8 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::SamuraiGauge: vtbls: - ea: 0x141781BF0 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::RedMageGauge: vtbls: - ea: 0x141781C28 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::DancerGauge: vtbls: - ea: 0x141781C60 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::GunbreakerGauge: vtbls: - ea: 0x141781C98 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::ReaperGauge: vtbls: - ea: 0x141781CD0 base: Client::Game::Gauge::JobGauge Client::Game::Gauge::SageGauge: vtbls: - ea: 0x141781D08 base: Client::Game::Gauge::JobGauge Common::Configuration::ConfigBase: vtbls: - ea: 0x141709618 base: Client::System::Common::NonCopyable funcs: 0x140069440: ctor Common::Configuration::UIConfig: vtbls: - ea: 0x141709638 base: Common::Configuration::ConfigBase Common::Configuration::UIControlConfig: vtbls: - ea: 0x141709658 base: Common::Configuration::ConfigBase Common::Configuration::SystemConfig: vtbls: - ea: 0x141709678 base: Common::Configuration::ConfigBase funcs: 0x1400798A0: ctor 0x14007EF30: GetLastWorldId Common::Configuration::DevConfig: vtbls: - ea: 0x141709698 base: Common::Configuration::ConfigBase funcs: 0x14007F590: ctor Client::System::Framework::Task: vtbls: - ea: 0x14170A8F0 funcs: 0x1400954F0: TaskRunner # task starter which runs the task's function pointer Client::System::Framework::TaskManager::RootTask: vtbls: - ea: 0x14170A908 base: Client::System::Framework::Task Client::System::Framework::TaskManager: instances: - ea: 0x141E58118 vtbls: - ea: 0x14170A920 funcs: 0x140094CA0: ctor 0x140179500: SetTask Common::Game::Time::GameTime: vtbls: - ea: 0x14170A928 Client::System::Timer::ClientTime: vtbls: - ea: 0x14170A930 base: Common::Game::Time::GameTime Client::System::Configuration::SystemConfig: vtbls: - ea: 0x14170A938 base: Common::Configuration::SystemConfig Client::System::Configuration::DevConfig: vtbls: - ea: 0x14170A958 base: Common::Configuration::DevConfig Client::System::Framework::Framework: instances: - ea: 0x141E548A0 - ea: 0x141E56448 name: InstancePointer2 vtbls: - ea: 0x14170A978 vfuncs: 0: dtor 1: Setup 4: Tick funcs: 0x14008F860: ctor 0x140092CB0: GetUIModule 0x140093B80: TaskBegin 0x140093CB0: TaskDraw2DBegin 0x140093CF0: TaskUpdateInputDevice 0x140093D30: TaskUpdateInputUI 0x140094110: TaskRenderManagerUpdate 0x140094130: TaskRenderManagerRender 0x140094170: TaskUpdateBonePhysics 0x1400941D0: TaskUpdateLayoutWorld 0x1400941F0: TaskResourceManagerUpdate Component::Excel::ExcelModuleInterface: vtbls: - ea: 0x14170A9A0 vfuncs: 1: GetSheetByIndex 2: GetSheetByName Component::Excel::ExcelModule: vtbls: - ea: 0x141A6AC20 vfuncs: 1: GetSheetByIndex 2: GetSheetByName 3: LoadSheet funcs: 0x14169A550: ctor Client::System::Input::TextService: vtbls: - ea: 0x14170B048 base: Client::System::Input::TextServiceInterface Component::Shell::ShellCommandModule: vtbls: - ea: 0x14170B140 base: Client::UI::Shell::RaptureShellCommandInterface funcs: 0x140099840: ExecuteCommandInner Component::GUI::AtkEventListener: vtbls: - ea: 0x141714D70 vfuncs: 0: dtor 1: ReceiveGlobalEvent # this seems to be a common event handler shared by all AtkUnitBase instances, they don't overwrite it 2: ReceiveEvent Component::GUI::AtkUnitList: vtbls: - ea: 0x141714DA8 Component::GUI::AtkUnitManager: vtbls: - ea: 0x141714DB0 base: Component::GUI::AtkEventListener vfuncs: 11: UpdateAddonByID funcs: 0x1404F95A0: ctor 0x1404FAFF0: GetAddonById 0x1404FB050: GetAddonByName 0x1404FB100: GetAddonByNode Client::UI::RaptureAtkUnitManager: vtbls: - ea: 0x141714F08 base: Component::GUI::AtkUnitManager funcs: 0x1400AC750: ctor Client::UI::RaptureAtkModule: vtbls: - ea: 0x141715170 base: Component::GUI::AtkModule funcs: 0x1400B2200: ctor 0x1400B4200: OpenAddon 0x1400B4980: OpenYesNo 0x1400C6F30: OnUpdate_Nameplates 0x1400D5F80: UpdateNameplates_BattleChara 0x1400D6C60: UpdateNameplates_NPC 0x1400D8F80: IsUIVisible Client::UI::Info::InfoProxyInterface: vtbls: - ea: 0x141714C90 Client::UI::Info::InfoProxyPageInterface: vtbls: - ea: 0x141714CF0 base: Client::UI::Info::InfoProxyInterface Common::Configuration::ConfigBase::ChangeEventInterface: vtbls: - ea: 0x141715418 Client::UI::Info::InfoProxyCrossRealm: instances: - ea: 0x141E58088 vtbls: - ea: 0x141715620 base: Client::UI::Info::InfoProxyInterface funcs: 0x1400EA1F0: ctor 0x1400EA2D0: GetPtr # Static 0x1400ECE50: IsCrossRealmParty # Static 0x1400ECED0: IsCrossRealmPartyLeader # Static 0x1400ECEF0: IsAllianceRaid # Static 0x1400ECF40: GetPartyMemberCount # Static 0x1400ECFA0: GetTotalMemberCount # Static 0x1400ED000: GetGroupMemberCount # Static 0x1400ED090: GetAllianceGroupCount # Static 0x1400ED0C0: GetPartyMemberCount_2 # Static 0x1400ED100: GetGroupIndex # Static 0x1400ED690: IsLocalPlayerInParty # Static 0x1400ED6D0: GetMember # Static 0x1400ED780: GetMemberByContentId # Static 0x1400ED850: GetMemberByObjectId # Static 0x1400ED900: IsContentIdInParty # Static Client::Graphics::Kernel::Notifier: vtbls: - ea: 0x14171D820 Client::System::Crypt::Crc32: vtbls: - ea: 0x1417212B8 Client::Graphics::ReferencedClassBase: vtbls: - ea: 0x1417279F0 vfuncs: 0: dtor 1: Cleanup # this is called by DecRef when there are no refs left, before the dtor is called 2: IncRef 3: DecRef Client::Graphics::Environment::EnvSoundState: vtbls: - ea: 0x141727A38 Client::Graphics::Environment::EnvState: vtbls: - ea: 0x141727A58 Client::Graphics::Environment::EnvSimulator: vtbls: - ea: 0x141727AA8 Client::Graphics::Environment::EnvManager: instances: - ea: 0x141E564C8 vtbls: - ea: 0x141727AB8 base: Client::Graphics::Singleton funcs: 0x140188020: ctor Client::Graphics::Environment::EnvRenderController: instances: - ea: 0x141E5D000 pointer: False vtbls: - ea: 0x141727AE8 Client::System::Threading::Thread: vtbls: - ea: 0x141727EE0 base: Client::System::Common::NonCopyable vfuncs: 5: Run funcs: 0x14019D0C0: CreateThread Client::System::File::FileInterface: vtbls: - ea: 0x141727FA8 Client::System::File::FileThread: vtbls: - ea: 0x141727FC8 base: Client::System::Threading::Thread Client::System::File::FileManager: vtbls: - ea: 0x141727FF8 base: Client::System::Framework::Task funcs: 0x1401A45E0: ctor Client::System::Resource::Handle::ResourceHandle: vtbls: - ea: 0x141729788 base: Client::System::Common::NonCopyable vfuncs: 23: GetData 33: Load funcs: 0x1401A81A0: DecRef 0x1401A81D0: IncRef 0x1401A8390: ctor Client::System::Resource::Handle::DefaultResourceHandle: vtbls: - ea: 0x141729908 base: Client::System::Resource::Handle::ResourceHandle Client::System::Resource::Handle::MaterialResourceHandle: vtbls: - ea: 0x141729A88 base: Client::System::Resource::Handle::DefaultResourceHandle Client::System::Resource::Handle::ShaderPackageResourceHandle: vtbls: - ea: 0x141729C08 base: Client::System::Resource::Handle::DefaultResourceHandle funcs: 0x1401AB550: ctor Client::System::Resource::Handle::TextureResourceHandle: vtbls: - ea: 0x141729D88 base: Client::System::Resource::Handle::ResourceHandle funcs: 0x1401AB880: ctor Client::System::Resource::ResourceEventListener: vtbls: - ea: 0x14172A0C8 funcs: 0x1401B0C10: ctor Client::System::Resource::Handle::CharaMakeParameterResourceHandle: vtbls: - ea: 0x14172A5B8 base: Client::System::Resource::Handle::DefaultResourceHandle Client::System::Resource::Handle::ApricotResourceHandle: vtbls: - ea: 0x14172B838 base: Client::System::Resource::Handle::DefaultResourceHandle Client::System::Resource::Handle::UldResourceHandle: vtbls: - ea: 0x14172E6E8 base: Client::System::Resource::Handle::DefaultResourceHandle Client::System::Resource::Handle::UldResourceHandleFactory: vtbls: - ea: 0x14172E850 base: Client::System::Resource::Handle::ResourceHandleFactory Client::Graphics::Primitive::Manager: instances: - ea: 0x141E56490 vtbls: - ea: 0x14172EE78 base: Client::Graphics::Singleton funcs: 0x1401DAFD0: ctor Client::Graphics::DelayedReleaseClassBase: vtbls: - ea: 0x14172F040 base: Client::Graphics::ReferencedClassBase funcs: 0x1401DD930: ctor Client::Graphics::IAllocator: vtbls: - ea: 0x14172F068 Client::Graphics::AllocatorLowLevel: vtbls: - ea: 0x14172F1B8 base: Client::Graphics::IAllocator Client::Graphics::AllocatorManager: instances: - ea: 0x141E56488 vtbls: - ea: 0x14172F270 base: Client::Graphics::Singleton funcs: 0x1401DFEB0: ctor Client::Network::NetworkModuleProxy: vtbls: - ea: 0x141730780 base: Client::System::Common::NonCopyable funcs: 0x1401F6540: ctor Client::UI::Agent::AgentInterface: vtbls: - ea: 0x141731770 base: Component::GUI::AtkModuleInterface::AtkEventInterface vfuncs: 2: dtor 3: Show 4: Hide 5: IsAgentActive 6: Update 8: GetAddonId funcs: 0x1401F82C0: ctor 0x1401F8870: GetAgentByInternalId 0x1401F88F0: GetAgentInventoryContext 0x1401F88D0: GetAgentContext 0x1401F8940: GetAddonTextById Client::UI::Agent::AgentCharaMake: vtbls: - ea: 0x1417317E8 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentModule: vtbls: - ea: 0x141731C20 funcs: 0x1402007B0: ctor 0x140205A10: GetAgentByInternalID 0x140205A20: GetAgentByInternalID_2 # dupe? Client::UI::Agent::AgentContext::AgentContextUpdateChecker: vtbls: - ea: 0x141731CB8 Client::UI::Agent::AgentContext: vtbls: - ea: 0x141731CC0 base: Client::UI::Agent::AgentInterface funcs: 0x14020F400: ctor 0x14020F840: OpenContextMenu 0x14020F5A0: OpenContextMenuForAddon 0x14020FEB0: GetOwnerAddonId 0x14020FEC0: ClearMenu 0x14020FF10: SetMenuTitle 0x140210000: ResetMenu 0x1402100C0: SetPositionX 0x1402100E0: SetPositionY 0x1402129B0: SetUpdateChecker 0x140212BD0: CloseSubMenu 0x140210100: OpenSubMenu 0x140213E80: OpenYesNo # (this, char* msgText, uint yesId, uint noId, uint checkboxId, bool setOwner) 0x140210E60: SetupButtonsForTarget 0x140212590: AddMenuItem2 # (this, uint textId, AtkEventInterface* handler, long handlerParam, bool disabled, bool submenu) 0x140212600: AddMenuItem # (this, char* text, AtkEventInterface* handler, long handlerParam, bool disabled, bool submenu) 0x140214250: AddContextMenuItem2 # (this, int eventId, uint textId, bool disabled, bool submenu) 0x1402142C0: AddContextMenuItem # (this, int eventId, char* text, bool disabled, bool submenu, bool copyText) Client::UI::Agent::AgentLobby: vtbls: - ea: 0x1417322B0 base: Client::UI::Agent::AgentInterface funcs: 0x14021BFD0: ctor Client::UI::Agent::AgentCursor: vtbls: - ea: 0x141732AA0 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentCursorLocation: vtbls: - ea: 0x141732B18 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentLetterEdit: vtbls: - ea: 0x141733B90 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentFreeCompanyChest: vtbls: - ea: 0x141733FA0 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentExplorationInterface: vtbls: - ea: 0x141734688 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentAirShipExploration: vtbls: - ea: 0x141734750 base: Client::UI::Agent::AgentExplorationInterface Client::UI::Agent::AgentSubmersibleExplorationDetail: vtbls: - ea: 0x141734B28 base: Client::UI::Agent::AgentExplorationDetailInterface Client::UI::Agent::AgentAirShipExplorationDetail: vtbls: - ea: 0x141733590 base: Client::UI::Agent::AgentExplorationDetailInterface Client::UI::Agent::AgentExplorationDetailInterface: vtbls: - ea: 0x1417334B0 base: Client::UI::Agent::AgentInterface Client::Graphics::Animation::IAnimationControllerListener: vtbls: - ea: 0x141739840 Client::Graphics::Animation::PartialSkeleton: vtbls: - ea: 0x141739888 base: Client::Graphics::Animation::IAnimationControllerListener Client::Graphics::Kernel::Resource: vtbls: - ea: 0x14173A458 base: Client::Graphics::DelayedReleaseClassBase Client::Graphics::Kernel::Shader: vtbls: - ea: 0x14173A480 base: Client::Graphics::Kernel::Resource Client::Graphics::Kernel::Texture: vtbls: - ea: 0x14173A4A8 base: Client::Graphics::Kernel::Resource funcs: 0x14030B9D0: ctor Client::Graphics::Kernel::SwapChain: vtbls: - ea: 0x14173A4E8 base: Client::Graphics::Kernel::Resource funcs: 0x14030F9B0: Present Client::Graphics::Kernel::Buffer: vtbls: - ea: 0x14173A528 base: Client::Graphics::Kernel::Resource Client::Graphics::Kernel::ConstantBuffer: vtbls: - ea: 0x14173A730 base: Client::Graphics::Kernel::Buffer funcs: 0x140312780: ctor 0x140312AE0: LoadSourcePointer 0x140323590: LoadBuffer 0x140327DB0: Activate Client::Graphics::Kernel::Device: instances: - ea: 0x141E54A70 vtbls: - ea: 0x14173A7B8 base: Client::Graphics::Singleton funcs: 0x140313040: ctor 0x1403131E0: Initialize 0x140313D60: CreateTexture2D 0x140314950: CreateConstantBuffer 0x140315080: PostTick Client::Graphics::Kernel::Context: funcs: 0x1401D1CA0: PushBackCommand 0x140324A30: PrepareModel 0x1403BC170: Draw_cmd Client::Graphics::Kernel::Device::ImmediateContext: vtbls: - ea: 0x14173A7C0 funcs: 0x14031E0E0: ProcessCommands 0x14031E390: PrimeForDraw Client::Graphics::Kernel::Device::RenderThread: vtbls: - ea: 0x14173A810 base: Client::System::Threading::Thread Client::Graphics::Render::Skeleton: vtbls: - ea: 0x1417419F0 base: Client::Graphics::ReferencedClassBase funcs: 0x14032CB10: ctor Client::Graphics::Kernel::ShaderSceneKey: vtbls: - ea: 0x141741A58 Client::Graphics::Kernel::ShaderSubViewKey: vtbls: - ea: 0x141741A60 Client::Graphics::Render::GraphicsConfig: instances: - ea: 0x141E56438 vtbls: - ea: 0x141741A78 base: Client::Graphics::Singleton funcs: 0x140331B00: ctor Client::Graphics::Render::Camera: vtbls: - ea: 0x141741A80 base: Client::Graphics::ReferencedClassBase vfuncs: 5: UpdateConstantBuffer funcs: 0x1403330F0: LoadMatrix 0x140336530: MakeProjectionMatrix Client::Graphics::Render::ShadowCamera: vtbls: - ea: 0x141741AB8 base: Client::Graphics::Render::Camera Client::Graphics::Render::Camera_CascadeShadow: vtbls: - ea: 0x141741AF0 base: Client::Graphics::Render::Camera Client::Graphics::Render::Camera_SpecialShadow: vtbls: - ea: 0x141741B30 base: Client::Graphics::Render::Camera Client::Graphics::Render::Camera_OmniShadow: vtbls: - ea: 0x141741B70 base: Client::Graphics::Render::Camera funcs: 0x140336DC0: SubmitRenderCameraData Client::Graphics::Render::Camera_OmniShadow::CameraOmniFace: vtbls: - ea: 0x141741BB8 base: Client::Graphics::Render::Camera Client::Graphics::Render::View: vtbls: - ea: 0x141741C00 Client::Graphics::Render::PostBoneDeformerBase: vtbls: - ea: 0x141741C88 base: Client::System::Framework::Task Client::Graphics::Render::RenderObject: vtbls: - ea: 0x141741CF0 base: Client::Graphics::ReferencedClassBase Client::Graphics::Render::OffscreenRenderingManager: instances: - ea: 0x141E6F458 vtbls: - ea: 0x141741CE8 funcs: 0x14033A160: ctor 0x14033A250: Initialize Client::Graphics::Render::AmbientLight: vtbls: - ea: 0x141741D70 funcs: 0x14033B520: ctor Client::Graphics::Render::Model: vtbls: - ea: 0x141741D80 base: Client::Graphics::Render::RenderObject funcs: 0x14033D490: ctor 0x14033D5E0: SetupFromModelResourceHandle Client::Graphics::Render::BaseRenderer: vtbls: - ea: 0x141741E00 Client::Graphics::JobSystem<Client::Graphics::Render::ModelRenderer>: vtbls: - ea: 0x141741E38 Client::Graphics::Render::ModelRenderer: vtbls: - ea: 0x141741E40 base: Client::Graphics::Render::BaseRenderer Client::Graphics::Render::GeometryInstancingRenderer: vtbls: - ea: 0x141741E68 base: Client::Graphics::Render::BaseRenderer Client::Graphics::JobSystem<Client::Graphics::Render::BGInstancingRenderer>: vtbls: - ea: 0x141741F10 Client::Graphics::Render::BGInstancingRenderer: vtbls: - ea: 0x141741F18 base: Client::Graphics::Render::GeometryInstancingRenderer Client::Graphics::JobSystem<Client::Graphics::Render::TerrainRenderer>: vtbls: - ea: 0x141741F80 Client::Graphics::Render::TerrainRenderer: vtbls: - ea: 0x141741F88 base: Client::Graphics::Render::BaseRenderer Client::Graphics::Render::UnknownRenderer: vtbls: - ea: 0x141741FF8 base: Client::Graphics::Render::BaseRenderer Client::Graphics::JobSystem<Client::Graphics::Render::WaterRenderer>: vtbls: - ea: 0x141742060 Client::Graphics::Render::WaterRenderer: vtbls: - ea: 0x141742068 base: Client::Graphics::Render::BaseRenderer Client::Graphics::JobSystem<Client::Graphics::Render::VerticalFogRenderer>: vtbls: - ea: 0x141742150 Client::Graphics::Render::VerticalFogRenderer: vtbls: - ea: 0x141742158 base: Client::Graphics::Render::BaseRenderer Client::Graphics::Render::ShadowMaskUnit: vtbls: - ea: 0x141742270 Client::Graphics::Render::ShaderManager: vtbls: - ea: 0x141742288 Client::Graphics::JobSystem<Client::Graphics::Render::Manager>: vtbls: - ea: 0x141742298 funcs: 0x140399160: Initialize Client::Graphics::Render::Updater<Client::Graphics::Render::PostBoneDeformerBase>: vtbls: - ea: 0x1417422A0 Client::Graphics::Render::Manager: instances: - ea: 0x141E56498 vtbls: - ea: 0x1417422A8 base: Client::Graphics::Singleton funcs: 0x140375640: ctor 0x140375A80: Initialize 0x140375F00: Terminate 0x140376570: CreateCamera 0x140376820: CreateModel Client::Graphics::Render::ShadowManager: instances: - ea: 0x141E564A0 vtbls: - ea: 0x1417422C0 funcs: 0x140377B00: ctor Client::Graphics::Render::LightingManager::LightShape: vtbls: - ea: 0x1417422D0 Client::Graphics::JobSystem<Client::Graphics::Render::LightingManager::LightingRenderer>: vtbls: - ea: 0x1417422D8 Client::Graphics::Render::LightingManager::LightingRenderer: vtbls: - ea: 0x1417422E0 funcs: 0x14037C130: ctor Client::Graphics::Render::LightingManager: instances: - ea: 0x141E564A8 vtbls: - ea: 0x1417422E8 base: Client::Graphics::Singleton - ea: 0x1417422F0 base: Client::Graphics::Kernel::Notifier funcs: 0x1403869E0: ctor Client::Graphics::Render::RenderTargetManager: instances: - ea: 0x141E564B0 vtbls: - ea: 0x141742310 base: Client::Graphics::Singleton - ea: 0x141742318 base: Client::Graphics::Kernel::Notifier funcs: 0x1403871C0: ctor 0x1403873F0: Initialize Client::Graphics::PostEffect::PostEffectChain: vtbls: - ea: 0x141744968 Client::Graphics::PostEffect::PostEffectRainbow: vtbls: - ea: 0x141744970 Client::Graphics::PostEffect::PostEffectLensFlare: vtbls: - ea: 0x141744978 Client::Graphics::PostEffect::PostEffectRoofQuery: vtbls: - ea: 0x141744980 Client::Graphics::PostEffect::PostEffectManager: instances: - ea: 0x141E564C0 vtbls: - ea: 0x141744990 base: Client::Graphics::Singleton - ea: 0x141744998 base: Client::Graphics::Kernel::Notifier funcs: 0x1403A7F70: ctor Client::Graphics::JobSystem<Apricot::Engine::Core>: instances: - ea: 0x141E702B0 pointer: False vtbls: - ea: 0x141748610 funcs: 0x1403EF560: ctor 0x1403EF790: GetSingleton Apricot::IInstanceListenner: vtbls: - ea: 0x141747FB8 Apricot::ApricotInstanceListenner: vtbls: - ea: 0x141748240 base: Apricot::IInstanceListenner Client::Graphics::Scene::CharacterBase::VfxInstanceListenner: vtbls: - ea: 0x141752218 base: Apricot::IInstanceListenner Client::Graphics::Scene::Attach: vtbls: - ea: 0x1417521D8 base: Client::Graphics::Render::PostBoneDeformerBase Client::Graphics::Scene::Object: vtbls: - ea: 0x141751DD0 vfuncs: 0: dtor 1: CleanupRender 2: GetObjectType 4: UpdateRender Client::Graphics::Scene::DrawObject: vtbls: - ea: 0x141751E00 base: Client::Graphics::Scene::Object vfuncs: 11: UpdateMaterials funcs: 0x14043E180: ctor Client::Graphics::JobSystem<Client::Graphics::Scene::World>: vtbls: - ea: 0x141751F98 Client::Graphics::Scene::World: instances: - ea: 0x141E564D0 vtbls: - ea: 0x141751FA0 base: Client::Graphics::Scene::Object - ea: 0x141751FD0 base: Client::Graphics::Singleton funcs: 0x14043E730: ctor Client::Graphics::Scene::Camera: vtbls: - ea: 0x141751FD8 base: Client::Graphics::Scene::Object funcs: 0x14043E9F0: ctor 0x14043FB60: CalculateViewMatrix 0x1404402E0: PrepareRenderCamera Client::Graphics::Singleton<Client::Graphics::Scene::CameraManager>: vtbls: - ea: 0x141752038 vfuncs: 0: dtor Client::Graphics::Scene::CameraManager: instances: - ea: 0x141E564D8 vtbls: - ea: 0x141752040 base: Client::Graphics::Singleton<Client::Graphics::Scene::CameraManager> funcs: 0x1404404C0: ctor Client::Graphics::Scene::CharacterUtility: instances: - ea: 0x141E564E0 vtbls: - ea: 0x141752208 base: Client::Graphics::Singleton funcs: 0x140443BF0: ctor 0x140443E00: CreateDXRenderObjects 0x140444250: LoadDataFiles 0x140447FD0: GetSlotEqpFlags 0x1404495D0: GetEqpDataForAdults 0x140449830: GetEqpDataForChildren 0x140449980: GetEqpDataForOther Client::Graphics::Scene::CharacterBase: vtbls: - ea: 0x141752288 base: Client::Graphics::Scene::DrawObject vfuncs: 67: FlagSlotForUpdate 68: GetDataForSlot 71: ResolveRootPath 72: ResolveSKLBPath 73: ResolveMDLPath 74: ResolveSKPPath 75: ResolvePHYBPath 76: ResolvePAPPath 77: ResolveTMBPath 79: ResolveMaterialPAPPath 81: ResolveIMCPath 82: ResolveMTRLPath 83: ResolveDecalPath 84: ResolveVFXPath 85: ResolveEIDPath 86: GetDyeForSlot 87: GetSkeletonCount 92: CreateRenderModelForMDL funcs: 0x14044B060: ctor 0x14044EE80: CreateBonePhysicsModule 0x1404508F0: LoadAnimation 0x1404512C0: LoadMDLForSlot 0x1404513B0: LoadIMCForSlot 0x140451580: LoadAllMTRLsFromMDLInSlot 0x140451720: LoadAllDecalTexFromMDLInSlot 0x140451890: LoadPHYBForSlot 0x140451AF0: UnloadMDLForSlot 0x140452040: CopyIMCForSlot 0x1404523B0: CreateStagingArea 0x1404524D0: PopulateMaterialsFromStaging 0x140452620: LoadMDLSubFilesIntoStaging 0x140452830: LoadMDLSubFilesForSlot 0x14045D190: CreateSlotStorage 0x1404723C0: dtor2 # Called by base dtor 0x1406FB3A0: Create Client::Graphics::Scene::Human: vtbls: - ea: 0x141752598 base: Client::Graphics::Scene::CharacterBase vfuncs: 58: OnModelLoadComplete funcs: 0x140456320: ctor 0x140456560: SetupFromCharacterData 0x14045A680: UpdateModels 0x14045A8B0: CheckSlotsForUnload 0x14045ABE0: SetupModelAttributes # wrist, fingers, tail all got inlined here 0x14045AEC0: SetupHelmetModelAttributes 0x14045B010: SetupTopModelAttributes 0x14045B3E0: SetupHandModelAttributes 0x14045B540: SetupLegModelAttributes 0x14045B850: SetupFeetModelAttributes 0x14045BA40: SetupEarringModelAttributes 0x14045BB50: SetupNecklaceModelAttributes 0x14045BDF0: SetupHairModelAttributes 0x14045C180: SetupFaceModelAttributes 0x14045C7C0: SetupConnectorModelAttributes Client::Graphics::Scene::Demihuman: vtbls: - ea: 0x1417528A8 base: Client::Graphics::Scene::CharacterBase funcs: 0x14045D460: ctor Client::Graphics::Scene::Weapon: vtbls: - ea: 0x141752BB8 base: Client::Graphics::Scene::CharacterBase funcs: 0x14045EB10: ctor Client::Graphics::Scene::Monster: vtbls: - ea: 0x141752EC8 base: Client::Graphics::Scene::CharacterBase funcs: 0x14045FB00: ctor Client::Graphics::Scene::BGManager: vtbls: - ea: 0x141753688 base: Client::Graphics::Scene::Object funcs: 0x140466400: ctor Client::Graphics::Vfx::VfxResourceInstanceListenner: vtbls: - ea: 0x1417482C8 Client::Graphics::Scene::VfxObject: vtbls: - ea: 0x1417539E0 base: Client::Graphics::Scene::DrawObject - ea: 0x141753B80 base: Apricot::ApricotInstanceListenner - ea: 0x141753BF0 base: Client::Graphics::Vfx::VfxResourceInstanceListenner funcs: 0x14046A180: ctor Client::Graphics::Scene::Terrain: vtbls: - ea: 0x1417531D8 base: Client::Graphics::Scene::DrawObject funcs: 0x140460820: ctor Client::Graphics::Scene::Light: vtbls: - ea: 0x141752048 base: Client::Graphics::Scene::DrawObject funcs: 0x140440F00: ctor Client::Graphics::Scene::EnvLocation: vtbls: - ea: 0x1417536B8 base: Client::Graphics::Scene::DrawObject funcs: 0x140466A20: ctor Client::Graphics::Scene::EnvSpace: vtbls: - ea: 0x141753848 base: Client::Graphics::Scene::DrawObject funcs: 0x140467440: ctor Client::Graphics::Scene::BGObject: vtbls: - ea: 0x1417534F8 base: Client::Graphics::Scene::DrawObject funcs: 0x140463A60: ctor Client::Graphics::Scene::EnvScene: vtbls: - ea: 0x1417539D8 funcs: 0x1404686C0: ctor Client::Graphics::Scene::ResidentResourceManager::ResourceList: vtbls: - ea: 0x141753C60 Client::Graphics::Scene::ResidentResourceManager: instances: - ea: 0x141E564E8 vtbls: - ea: 0x141753C70 base: Client::Graphics::Singleton funcs: 0x140470810: ctor 0x140470840: nullsub_1 0x140470870: LoadDataFiles Client::System::Task::SpursJobEntityWorkerThread: vtbls: - ea: 0x141753D50 base: Client::System::Threading::Thread Common::Lua::LuaState: vtbls: - ea: 0x141754158 vfuncs: 0: dtor funcs: 0x14047B7D0: ctor 0x14047B800: ctor_FromState 0x14047BB20: GetTop 0x14047BB30: SetTop 0x14047BC10: LoadString 0x14047BCC0: LoadFile 0x14047C1F0: PCall 0x14047BD50: DestroyGlobalClass 0x14047BDF0: GetGlobalOrNil 0x14047BE20: IncClassRef 0x14047BED0: DecClassRef 0x14047BF80: SetNil 0x14047BFE0: SetStringField 0x14047C030: SetIntegerField 0x14047C080: SetFunctionField 0x14047C0E0: SetNumberField 0x14047C130: SetNilField 0x14047C170: GetField 0x14047C180: ClassNameOf 0x14047C290: CallMemberFunction # (this, member, class, nresults) => pcall(_G[class][member], _G[class]) 0x14047C4F0: CallMemberFunction_2 # (this, member, class, (int)arg2, (int)arg3, nresults) => pcall(_G[class][member], _G[class], arg2, arg3) 0x14047C5F0: CallMemberFunction_3 # (this, member, class, argName, nresults) => pcall(_G[class][member], _G[class], _G[argName]) 0x14047C6F0: CallMemberFunction_4 # (this, member, class, argName, (int[])args, argCount nresults): above but with extra int args - used for the next 3 0x14047C820: CallMemberFunction_5 # (this, member, class, argName, (int)arg3, nresults) 0x14047C860: CallMemberFunction_6 # (this, member, class, argName, (int)arg3, (int)arg4, nresults) 0x14047C8B0: CallMemberFunction_7 # (this, member, class, argName, (int)arg3, (int)arg4, (int)arg5, nresults) 0x14047C930: CallMemberFunction_8 # (this, member, class, argName, (int)arg3, (int)arg4, (int)arg5, (int)arg6, nresults) 0x14047C9B0: CallMemberFunction_9 # (this, member, class, argName, (int)arg3, (int)arg4, (int)arg5, (int)arg6, (int)arg7, nresults) 0x14047CA40: CallMemberFunction_10 # (this, member, class, argName, (int)arg3, (int[])args, argCount, nresults) 0x14047CB80: CallMemberFunction_11 # (this, member, class, argName, (int)arg3, (int)arg4, (int[])args, argCount, nresults) 0x14047CCD0: CallMemberFunction_12 # (this, member, class, argName, (int)arg3, (int)arg4, (bool)arg5, (int[])args, argCount nresults) 0x14047CE30: CallMemberFunction_13 # (this, member, class, argName, argName2, nresults) => pcall(_G[class][member], _G[class], _G[argName], _G[argName2]) 0x14047E030: IsFunction 0x14047E0A0: PopBoolean 0x14047E110: CheckNumber 0x14047E140: CheckBoolean 0x14047E180: CheckString 0x14047E1A0: PushNumber 0x14047E1D0: PushBoolean 0x14047E1F0: PushString 0x14047E200: PushGlobal 0x14047E230: PushNil 0x14047E240: IsNil 0x14047E260: IsNumber 0x14047E280: IsString 0x14047E2A0: IsBoolean 0x14047E2C0: GetBoolean 0x14047E2E0: GetString 0x14047E300: NewThread # (this, LuaState* other) 0x14047E400: CloseThread # (this, LuaState* other) 0x14047E4C0: LuaError 0x14047E610: GC 0x14047E620: GCStop 0x14047E640: GCRestart 0x14047E6A0: GCStep # (this, data) 0x140AFEB80: PopByte 0x140AFEBE0: PopShort 0x140AFEC40: PopInteger 0x140AFECA0: PopInteger_2 0x140AFED00: PopInteger_3 Common::Lua::LuaThread: vtbls: - ea: 0x141754160 base: Common::Lua::LuaState funcs: 0x14047E6C0: ctor_FromState 0x14047E710: ctor Client::Game::Event::LuaActor: vtbls: - ea: 0x1417A2C20 vfuncs: 0: dtor Client::Game::Event::LuaPc: vtbls: - ea: 0x1417A5630 base: Client::Game::Event::LuaActor funcs: 0x140AA5FE0: ctor Client::Game::Event::LuaAetheryte: vtbls: - ea: 0x1417A4DB8 base: Client::Game::Event::LuaActor funcs: 0x140AA5040: ctor Client::Game::Event::LuaHousingEventObject: vtbls: - ea: 0x1417A4DA8 base: Client::Game::Event::LuaActor funcs: 0x140AA48F0: ctor Client::Game::Event::LuaEventObject: vtbls: - ea: 0x1417A4D98 base: Client::Game::Event::LuaActor funcs: 0x140AA3FE0: ctor Client::Game::Event::LuaCompanion: vtbls: - ea: 0x1417A4D88 base: Client::Game::Event::LuaActor funcs: 0x140AA3C30: ctor Client::Game::Event::LuaRetainer: vtbls: - ea: 0x1417A4D78 base: Client::Game::Event::LuaActor funcs: 0x140AA37F0: ctor Client::Game::Event::LuaBattleNpc: vtbls: - ea: 0x1417A4D68 base: Client::Game::Event::LuaActor funcs: 0x140AA2EB0: ctor Client::Game::Event::LuaEventNpc: vtbls: - ea: 0x1417A4D58 base: Client::Game::Event::LuaActor funcs: 0x140AA2B00: ctor Component::Exd::ExdModule: vtbls: - ea: 0x1417546A0 funcs: 0x140486790: ctor 0x140486D80: GetSheetRowById 0x140486E00: GetEntryByIndex Client::System::Scheduler::ScheduleManagement: vtbls: - ea: 0x1417546F0 base: Client::System::Framework::Task Client::Graphics::Vfx::VfxDataListenner: vtbls: - ea: 0x141714C30 Client::Game::Control::TargetSystem::AggroListFeeder: vtbls: - ea: 0x141754F88 base: Client::Game::Control::TargetSystem::ListFeeder Client::Game::Control::TargetSystem::AllianceListFeeder: vtbls: - ea: 0x141754F98 base: Client::Game::Control::TargetSystem::ListFeeder Client::Game::Control::TargetSystem::PartyListFeeder: vtbls: - ea: 0x141754FA8 base: Client::Game::Control::TargetSystem::ListFeeder Client::Game::Control::TargetSystem: instances: - ea: 0x141E78A00 vtbls: - ea: 0x141754FF8 base: Client::Game::Object::IGameObjectEventListener funcs: 0x1404A6420: ctor 0x1404B01D0: GetHardTargetObjectId 0x1404B01F0: GetHardTargetId 0x1404B0210: GetHardTarget 0x1404B0230: GetSoftTargetObjectId 0x1404B0250: GetSoftTargetId 0x1404B0270: GetSoftTarget 0x1404B0290: GetMouseOverTargetPlayerId 0x1404B02D0: GetMouseOverTarget 0x1404B02E0: SetMouseOverEventObj 0x1404B02F0: GetTargetObjectId 0x1404B0320: GetTargetPlayerId 0x1404B0370: GetTargetObject 0x1404B0390: GetTargetObjectId2 0x1404B03C0: GetTargetPlayerId2 0x1404B0410: GetTargetObject2 0x1404B06C0: ClearFocusTarget 0x1404B06E0: SetFocusTargetByObjectId 0x1404B1080: IsObjectInViewRange 0x1404B28D0: RemoveObjectFromTargets Client::System::Input::InputData: vtbls: - ea: 0x141755240 funcs: 0x1404BBF30: ctor Component::GUI::AtkArrayData: vtbls: - ea: 0x1417573C8 Component::GUI::NumberArrayData: vtbls: - ea: 0x1417573D8 base: Component::GUI::AtkArrayData funcs: 0x1404BDD60: SetValueIfDifferentAndNotify 0x1404BDE00: SetValueForced Component::GUI::StringArrayData: vtbls: - ea: 0x1417573E8 base: Component::GUI::AtkArrayData funcs: 0x1404BE070: SetValue 0x1404BE250: SetValueUtf8 0x1404BE2B0: SetValueIfDifferentAndNotify 0x1404BE2E0: SetValueIfDifferentAndNotifyUtf8 0x1404BE320: SetValueForced 0x1404BE360: SetValueForcedUtf8 Component::GUI::ExtendArrayData: vtbls: - ea: 0x1417573F8 base: Component::GUI::AtkArrayData Component::GUI::AtkTooltipManager: vtbls: - ea: 0x1417574C0 base: Component::GUI::AtkEventListener funcs: 0x1404C8490: AttachTooltip 0x1404C86D0: DetachTooltipNode 0x1404C88F0: ShowNodeTooltip # takes node as argument 0x1404C8980: ShowTooltip # similar args to attach tooltip 0x1404C9430: DetachTooltipAddon Component::GUI::AtkEventTarget: vtbls: - ea: 0x141759C68 Component::GUI::AtkEventListenerUnk: # Used in AddonTalk vtbls: - ea: 0x141759C70 base: Component::GUI::AtkEventListener Component::GUI::AtkSimpleTween: vtbls: - ea: 0x141757508 base: Component::GUI::AtkEventTarget Component::GUI::AtkTexture: vtbls: - ea: 0x141757488 funcs: 0x1404C4F80: LoadIconTexture 0x1404C51A0: GetLoadState 0x1404C5200: IsTextureReady 0x1404C52B0: ReleaseTexture 0x1404C53E0: GetKernelTexture Component::GUI::AtkStage: instances: - ea: 0x141E7CDB0 vtbls: - ea: 0x141757668 base: Component::GUI::AtkEventTarget funcs: 0x1404CED70: GetFocus 0x1404CEDA0: SetFocus 0x1404CEE00: ClearFocus 0x1404CFD30: GetNumberArrayData 0x1404CFE60: ctor 0x1404F2090: GetSingleton1 # dalamud GetBaseUIObject Component::GUI::AtkResNode: vtbls: - ea: 0x141757F10 base: Component::GUI::AtkEventTarget vfuncs: 1: Destroy funcs: 0x1404E05E0: ctor 0x1404E0740: GetAsAtkImageNode 0x1404E0760: GetAsAtkTextNode 0x1404E0780: GetAsAtkNineGridNode 0x1404E07A0: GetAsAtkCounterNode 0x1404E07C0: GetAsAtkCollisionNode 0x1404E07E0: GetAsAtkComponentNode 0x1404E0800: GetComponent 0x1404E0FB0: RegisterEvent 0x1404E0FF0: UnregisterEvent 0x1404E1030: DispatchEvent 0x1404E13A0: GetPositionFloat 0x1404E13C0: SetPositionFloat 0x1404E1410: GetPositionShort 0x1404E1440: SetPositionShort 0x1404E14A0: GetScale 0x1404E14C0: GetScaleX 0x1404E14E0: GetScaleY 0x1404E1500: SetScale 0x1404E1620: SetSize0 0x1404E1660: GetYFloat 0x1404E16A0: GetYShort 0x1404E1870: GetWidth 0x1404E1890: GetHeight 0x1404E1AD0: SetWidth 0x1404E1AF0: SetHeight 0x1404E1B40: GetRotation 0x1404E1B60: SetRotation 0x1404E1BD0: GetRotationDegrees 0x1404E1C00: SetRotationDegrees 0x1404E1C80: GetColor 0x1404E1CA0: SetColor 0x1404E1CE0: SetAddRGB 0x1404E1D30: SetMultiplyRGB 0x1404E1D80: GetPriority 0x1404E1DA0: SetPriority 0x1404E1DC0: IsVisible 0x1404E1DF0: SetVisibility 0x1404E21D0: GetIsUsingDepthBasedDrawPriority 0x1404E21F0: SetUseDepthBasedDrawPriority 0x1404E2240: SetDepth 0x1404E2610: Init 0x1404E27E0: SetScale0 # SetScale jumps to this 0x1404ECEC0: SetSize Component::GUI::AtkImageNode: vtbls: - ea: 0x141757F28 base: Component::GUI::AtkResNode funcs: 0x1404E2CE0: LoadIconTexture 0x1404E2EE0: UnloadTexture 0x140554260: ctor Component::GUI::AtkTextNode: vtbls: - ea: 0x141757F40 base: Component::GUI::AtkResNode funcs: 0x1404E3140: SetText 0x1404E3C70: SetForegroundColour 0x1404E3FB0: GetTextDrawSize 0x1404E49B0: SetNumber 0x1404E4C80: SetFontSize 0x1404E4D90: SetGlowColour 0x1404E53D0: ToggleFixedFontResolution # this stops text from auto scaling, they turned this on for nameplates in 5.5 0x1404E60E0: ToggleFontCache 0x1404E62D0: ResizeNodeForCurrentText 0x140554410: ctor Component::GUI::AtkNineGridNode: vtbls: - ea: 0x141757F58 base: Component::GUI::AtkResNode funcs: 0x1405542C0: ctor Component::GUI::AtkCounterNode: vtbls: - ea: 0x141757F70 base: Component::GUI::AtkResNode funcs: 0x1405541E0: ctor Component::GUI::AtkCollisionNode: vtbls: - ea: 0x141757F88 base: Component::GUI::AtkResNode funcs: 0x140554120: ctor Component::GUI::AtkComponentNode: vtbls: - ea: 0x141757FA0 base: Component::GUI::AtkResNode funcs: 0x140554180: ctor Component::GUI::AtkUnitBase: vtbls: - ea: 0x141757FB8 base: Component::GUI::AtkEventListener vfuncs: 7: SetPosition 8: SetX 9: SetY 10: GetX 11: GetY 12: GetPosition 13: SetAlpha 14: SetScale 37: Initialize 38: Finalize 39: Update 40: Draw 42: LoadUldResourceHandle 45: OnSetup 47: OnRefresh 48: OnUpdate 58: OnMouseOver 59: OnMouseOut funcs: 0x1404EE7D0: ctor 0x1404EEE40: FireCallbackInt # this creates an int AtkValue and puts its argument into it before calling Callback 0x1404EF080: SetPosition 0x1404EF200: SetAlpha 0x1404EF230: GetScale 0x1404EF450: GetGlobalUIScale 0x1404EF460: SetGlobalUIScale 0x1404EF600: SetScale 0x1404EF970: CalculateBounds 0x1404F00B0: SetFlag 0x1404F1BF0: Draw 0x1404F2540: SetFocusNode 0x1404F2AC0: GetNodeById 0x1404F2D80: GetTextNodeById 0x1404F2DE0: GetImageNodeById 0x1404F2EE0: FireCallback 0x1404F5520: ResizeCollisionNodeList Component::GUI::AtkComponentBase: vtbls: - ea: 0x141758250 base: Component::GUI::AtkEventListener vfuncs: 10: SetEnabledState 17: InitializeFromComponentData funcs: 0x140506750: ctor 0x140506A00: GetOwnerNodePosition Component::GUI::AtkComponentButton: vtbls: - ea: 0x1417582F0 base: Component::GUI::AtkComponentBase funcs: 0x140507E80: ctor Component::GUI::AtkComponentIcon: vtbls: - ea: 0x1417583B8 base: Component::GUI::AtkComponentBase funcs: 0x14050A3F0: ctor Component::GUI::AtkComponentListItemRenderer: vtbls: - ea: 0x1417584D8 base: Component::GUI::AtkComponentButton funcs: 0x14050AFC0: ctor Component::GUI::AtkComponentList: vtbls: - ea: 0x141758648 base: Component::GUI::AtkComponentBase funcs: 0x140516470: ctor Component::GUI::AtkComponentTreeList: vtbls: - ea: 0x1417587B0 base: Component::GUI::AtkComponentList funcs: 0x14051AE20: ctor Component::GUI::AtkModule: vtbls: - ea: 0x141758920 base: Component::GUI::AtkModuleInterface vfuncs: 17: SetHandlerFunction 39: SetUIVisibility 58: OnUpdate 63: OpenMapWithMapLink funcs: 0x14051FB70: ctor 0x1405209D0: HandleInput Component::GUI::AtkComponentCheckBox: vtbls: - ea: 0x141758BC8 base: Component::GUI::AtkComponentButton funcs: 0x140523BA0: ctor Component::GUI::AtkComponentGaugeBar: vtbls: - ea: 0x141758C98 base: Component::GUI::AtkComponentBase funcs: 0x140524AD0: ctor Component::GUI::AtkComponentSlider: vtbls: - ea: 0x141758D38 base: Component::GUI::AtkComponentBase funcs: 0x140526C00: ctor Component::GUI::AtkComponentInputBase: vtbls: - ea: 0x141758DD8 base: Component::GUI::AtkComponentBase funcs: 0x140528010: ctor Component::GUI::AtkComponentTextInput: vtbls: - ea: 0x141758E78 base: Component::GUI::AtkComponentInputBase funcs: 0x140529800: ctor Component::GUI::AtkComponentNumericInput: vtbls: - ea: 0x141758F78 base: Component::GUI::AtkComponentInputBase funcs: 0x14052DF20: ctor Component::GUI::AtkComponentDropDownList: vtbls: - ea: 0x141759040 base: Component::GUI::AtkComponentBase funcs: 0x140531BD0: ctor Component::GUI::AtkComponentRadioButton: vtbls: - ea: 0x1417590E0 base: Component::GUI::AtkComponentButton funcs: 0x1405330D0: ctor Component::GUI::AtkComponentTab: vtbls: - ea: 0x1417591F0 base: Component::GUI::AtkComponentRadioButton funcs: 0x1405339A0: ctor Component::GUI::AtkComponentGuildLeveCard: vtbls: - ea: 0x141759300 base: Component::GUI::AtkComponentBase funcs: 0x140533F70: ctor Component::GUI::AtkComponentTextNineGrid: vtbls: - ea: 0x1417593A0 base: Component::GUI::AtkComponentBase funcs: 0x140534300: ctor Component::GUI::AtkResourceRendererBase: vtbls: - ea: 0x141759440 vfuncs: 1: ShouldRender 2: Draw Component::GUI::AtkImageNodeRenderer: vtbls: - ea: 0x141759458 base: Component::GUI::AtkResourceRendererBase Component::GUI::AtkTextNodeRenderer: vtbls: - ea: 0x141759470 base: Component::GUI::AtkResourceRendererBase Component::GUI::AtkNineGridNodeRenderer: vtbls: - ea: 0x141759490 base: Component::GUI::AtkResourceRendererBase Component::GUI::AtkCounterNodeRenderer: vtbls: - ea: 0x1417594A8 base: Component::GUI::AtkResourceRendererBase Component::GUI::AtkComponentNodeRenderer: vtbls: - ea: 0x1417594C0 base: Component::GUI::AtkResourceRendererBase Component::GUI::AtkResourceRendererManager: vtbls: - ea: 0x1417594D8 funcs: 0x140536EA0: ctor 0x1405370A0: DrawUldFromData 0x140537180: DrawUldFromDataClipped Component::GUI::AtkComponentMap: vtbls: - ea: 0x1417594F8 base: Component::GUI::AtkComponentBase funcs: 0x1405399D0: ctor Component::GUI::AtkComponentPreview: vtbls: - ea: 0x141759598 base: Component::GUI::AtkComponentBase funcs: 0x14053C350: ctor Component::GUI::AtkComponentScrollBar: vtbls: - ea: 0x141759638 base: Component::GUI::AtkComponentBase funcs: 0x14053D3B0: ctor Component::GUI::AtkComponentIconText: vtbls: - ea: 0x1417596D8 base: Component::GUI::AtkComponentBase funcs: 0x14053E9C0: LoadIconByID 0x14053E9F0: LoadIcon # this takes a struct arg that includes the icon ID and some params 0x14053EBF0: SetText 0x14053EC10: SetTextColor 0x14053EC30: SetTextEdgeColor 0x14053EDB0: ctor Component::GUI::AtkComponentDragDrop: vtbls: - ea: 0x141759778 base: Component::GUI::AtkComponentBase funcs: 0x140540030: ctor Component::GUI::AtkComponentMultipurpose: vtbls: - ea: 0x141759898 base: Component::GUI::AtkComponentBase funcs: 0x140541C90: ctor Component::GUI::AtkComponentWindow: vtbls: - ea: 0x141759A08 base: Component::GUI::AtkComponentBase funcs: 0x1405425C0: ctor Component::GUI::AtkComponentJournalCanvas: vtbls: - ea: 0x141759AD8 base: Component::GUI::AtkComponentBase funcs: 0x140547BE0: ctor Component::GUI::AtkComponentHoldButton: vtbls: - ea: 0x141759B78 base: Component::GUI::AtkComponentButton funcs: 0x14054B730: ctor Client::LayoutEngine::IManagerBase: vtbls: - ea: 0x14175AB08 base: Client::System::Common::NonCopyable Client::LayoutEngine::ILayoutInstance: vtbls: - ea: 0x14175AB28 base: Client::System::Common::NonCopyable Client::LayoutEngine::LayoutWorld: instances: - ea: 0x141E7D3C0 vtbls: - ea: 0x14175B340 base: Client::LayoutEngine::IManagerBase funcs: 0x14056EAC0: ctor 0x14056ED50: CreateSingleton Client::LayoutEngine::Group::TimeLineLayoutInstance: vtbls: - ea: 0x141762330 base: Client::LayoutEngine::ILayoutInstance vfuncs: 0: dtor Client::UI::Misc::UserFileManager::UserFileEvent: vtbls: - ea: 0x141766680 vfuncs: 1: ReadFile 2: WriteFile 6: GetFileVersion Client::UI::Misc::UserFileManager: vtbls: - ea: 0x1417666E8 base: Client::System::Resource::ResourceEventListener funcs: 0x140614C50: SaveFile Component::GUI::AtkInputData: vtbls: - ea: 0x141766710 base: Client::System::Input::InputData Client::UI::UIInputData: vtbls: - ea: 0x1417667A0 base: Component::GUI::AtkInputData - ea: 0x141766838 base: Client::UI::Misc::UserFileManager::UserFileEvent funcs: 0x1405CAC80: ctor Client::UI::UI3DModule::MapInfo: vtbls: - ea: 0x141767008 Client::UI::UI3DModule::ObjectInfo: vtbls: - ea: 0x141767030 base: Client::UI::UI3DModule::MapInfo Client::UI::UI3DModule::MemberInfo: vtbls: - ea: 0x141767060 base: Client::UI::UI3DModule::MapInfo Client::UI::UI3DModule: vtbls: - ea: 0x1417670C0 funcs: 0x1405D1390: CalculateIsInScreen 0x1405D14A0: CalculateNamePlatePosition 0x1405D17C0: GetUIObjectKind 0x1405D18C0: CalculateNamePlateScale 0x1405D1AB0: ctor 0x1405D1E90: Update 0x1405D20A0: UpdateGameObjects 0x1405D24F0: SetupNamePlateForObjectInfo 0x1405D25A0: FinalizeNamePlates Client::UI::UIInputModule: vtbls: - ea: 0x1417670C8 funcs: 0x1405D3F30: ctor 0x1405D4020: HandleInputUpdate 0x1405D5240: CheckCastCancel 0x1405D88E0: CheckScreenshotState Client::UI::UIModuleInterface: vtbls: - ea: 0x1417668A0 vfuncs: # todo: check new vfuncs 0: dtor 4: Abort 5: GetExcelModule 6: GetRaptureTextModule 7: GetRaptureAtkModule 8: GetRaptureAtkModule2 9: GetRaptureShellModule 10: GetPronounModule 11: GetRaptureLogModule 12: GetRaptureMacroModule 13: GetRaptureHotbarModule 14: GetRaptureGearsetModule 15: GetAcquaintanceModule 16: GetItemOrderModule 17: GetItemFinderModule 18: GetConfigModule 19: GetAddonConfig 20: GetUiSavePackModule 21: GetLetterDataModule 22: GetRetainerTaskDataModule 23: GetFlagStatusModule 29: GetRaptureTeleportHistory 34: GetAgentModule 36: GetUI3DModule 53: GetUIInputData 54: GetUIInputModule 56: GetLogFilterConfig 132: AnnounceHowTo 134: HideHowTo 137: HideGoldSaucerReward 140: HideGoldSaucerReward_2 142: ShowGoldSaucerReward 143: HideGoldSaucerReward_3 149: ShowImage 150: ShowText 151: ShowTextChain 152: ShowWideText 153: ShowPoisonText 154: ShowErrorText 155: ShowTextClassChange 156: ShowGetAction 157: ShowLocationTitle 161: ShowGrandCompany1 164: ShowStreak 165: ShowAddonKillStreakForManeuvers 166: ShowBaloonMessage 167: ShowBattleTalk 168: ShowBattleTalkImage 169: ShowBattleTalkUnknown 170: ShowBattleTalkSound 175: ExecuteMainCommand Client::UI::UIModule: vtbls: - ea: 0x1417670D8 base: Client::UI::UIModuleInterface - ea: 0x141767770 base: Component::GUI::AtkModuleEvent - ea: 0x141767778 base: Component::Excel::ExcelLanguageEvent - ea: 0x141767788 base: Common::Configuration::ConfigBase::ChangeEventInterface funcs: 0x1405DABC0: ctor 0x1405DBA10: Update 0x1405DBE80: HandleInputUpdate Client::System::Crypt::SimpleString: vtbls: - ea: 0x141767920 base: Client::System::Crypt::CryptInterface vfuncs: 1: Encrypt 2: Decrypt Component::Text::MacroDecoder: vtbls: - ea: 0x1417687E8 Component::Text::TextChecker: vtbls: - ea: 0x1417689A8 base: Component::Text::MacroDecoder Client::System::Data::Bit: vtbls: - ea: 0x141769378 funcs: 0x1406018B0: ctor Client::UI::Misc::ConfigModule: vtbls: - ea: 0x14176BF58 base: Component::GUI::AtkModuleInterface::AtkEventInterface - ea: 0x14176BF70 base: Common::Configuration::ConfigBase::ChangeEventInterface funcs: 0x140612510: ctor 0x1406128D0: SetValueByIndex 0x140612AA0: GetValueByIndex Client::UI::Misc::RaptureMacroModule: vtbls: - ea: 0x14176BF80 base: Client::UI::Misc::UserFileManager::UserFileEvent funcs: 0x1406151B0: ctor 0x1406152B0: GetMacro 0x1406152F0: ReplaceMacroLines # replaces macro with lines stored in string 0x140615310: AppendMacroLines # appends lines stored in string to macro 0x140615360: GetLineCount 0x140616A40: SetMacroLines # function called by replace/append Client::UI::Misc::RaptureTextModule: vtbls: - ea: 0x14176BFE8 funcs: 0x140618D20: GetAddonText 0x140619EF0: FormatAddonText 0x14061A1A0: FormatAddonText2 0x14061EB50: FormatAddonText3 0x14061F1B0: FormatAddonText4 0x140623630: FormatAddonTextApply Client::UI::Misc::RaptureLogModule: vtbls: - ea: 0x14176C260 base: Component::Log::LogModule funcs: 0x140627150: ctor 0x140628910: PrintMessage 0x140629CC0: ShowLogMessage 0x14062BD60: GetContentIdForLogMessage Client::UI::Misc::RaptureHotbarModule: vtbls: - ea: 0x14176C2B0 base: Client::UI::Misc::UserFileManager::UserFileEvent - ea: 0x14176C318 base: Client::System::Input::InputData::InputCodeModifiedInterface funcs: 0x1406320E0: ctor 0x140634660: IsHotbarEmpty 0x140637C20: ExecuteSlot 0x140632D40: ExecuteSlotById Client::UI::Misc::RaptureHotbarModule::HotbarSlot: funcs: 0x140630BA0: Set 0x140631EC0: LoadIconFromSlotB 0x14062F4D0: GetIconIdForSlot 0x14062FDB0: GetDisplayNameForSlot Client::UI::Misc::PronounModule: vtbls: - ea: 0x14176C460 base: Component::Text::TextChecker::ExecNonMacroFunc funcs: 0x140642440: ctor Client::UI::Misc::RaptureGearsetModule: vtbls: - ea: 0x14176C470 base: Client::UI::Misc::UserFileManager::UserFileEvent funcs: 0x140646EA0: ctor Client::UI::Misc::ItemFinderModule: vtbls: - ea: 0x14176C4E8 base: Client::UI::Misc::UserFileManager::UserFileEvent funcs: 0x14064A7E0: ctor 0x14064C790: SearchForItem Client::UI::Misc::ItemOrderModule: vtbls: - ea: 0x14176C690 base: Client::UI::Misc::UserFileManager::UserFileEvent funcs: 0x140659340: ctor Client::UI::Misc::RaptureTeleportHistory: vtbls: - ea: 0x14176C7C8 base: Client::UI::Misc::UserFileManager::UserFileEvent funcs: 0x140660360: AddHistoryEntry Client::UI::Misc::CharaView: vtbls: - ea: 0x14176CF40 vfuncs: 0: dtor 1: Initialize 2: Finalize funcs: 0x14066AC60: ctor Client::Game::Object::GameObject: vtbls: - ea: 0x14176E3D8 vfuncs: 2: GetObjectID 3: GetObjectKind 4: GetObjectType 5: GetIsTargetable 7: GetName 8: GetRadius 9: GetHeight 12: GetGender 17: EnableDraw 18: DisableDraw 22: SetDrawObject 28: GetDrawObject 29: GetDrawObject_2 30: UpdateRadius 41: Update 49: GetNpcID 58: IsDead 60: Terminate 61: Destroy 62: IsCharacter 69: OnInitialize funcs: 0x1406DEE30: IsMountOrOrnament 0x1406DFB30: GetPosition 0x1406DFB80: SetPosition 0x1406E3520: Initialize 0x1406E3790: ctor Client::Game::Character::Character: vtbls: - ea: 0x14176F0E0 base: Client::Game::Object::GameObject - ea: 0x14176F3A8 base: Client::Graphics::Vfx::VfxDataListenner vfuncs: 77: GetModelChara 80: GetStatusManager 81: GetStatusManager_2 82: GetCastInfo 83: GetCastInfo_2 86: GetForayInfo 87: GetForayInfo_2 88: IsMount funcs: 0x1406DE3C0: IsCasting 0x1406EE940: GetCompanionOwnerID 0x1406F2E80: dtor 0x140755040: ctor Component::Shell::ShellCommandInterface: vtbls: - ea: 0x14177C7B0 vfuncs: 0: dtor 1: ExecuteCommand Component::Shell::DebugCommandInterface: vtbls: - ea: 0x14177C7C8 Client::UI::Shell::RaptureShellCommandInterface: vtbls: - ea: 0x14177C7D8 base: Component::Shell::ShellCommandInterface Client::UI::Shell::RaptureShellModule: vtbls: - ea: 0x14177C7F0 base: Component::Shell::ShellCommandModule - ea: 0x14177C808 base: Client::UI::Shell::RaptureShellCommandInterface funcs: 0x1407200C0: ctor 0x1407244E0: SetChatChannel Client::UI::Shell::ShellCommandBlueAction: vtbls: - ea: 0x14177C820 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandAction: vtbls: - ea: 0x14177C838 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBattleMode: vtbls: - ea: 0x14177C850 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandGear: vtbls: - ea: 0x14177C868 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandAssist: vtbls: - ea: 0x14177C880 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFollow: vtbls: - ea: 0x14177C898 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTarget: vtbls: - ea: 0x14177C8B0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTargetPc: vtbls: - ea: 0x14177C8C8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTargetNpc: vtbls: - ea: 0x14177C8E0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTargetEnemy: vtbls: - ea: 0x14177C8F8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTargetEnemyNext: vtbls: - ea: 0x14177C910 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTargetEnemyPrev: vtbls: - ea: 0x14177C928 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBattleTarget: vtbls: - ea: 0x14177C940 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandRecast: vtbls: - ea: 0x14177C958 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandMarking: vtbls: - ea: 0x14177C978 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFaceTarget: vtbls: - ea: 0x14177C990 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandAddAdditionalAction: vtbls: - ea: 0x14177C9A8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandAddPvpAction: vtbls: - ea: 0x14177C9C0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandAutoMove: vtbls: - ea: 0x14177C9D8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandLockon: vtbls: - ea: 0x14177C9F0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFocus: vtbls: - ea: 0x14177CA08 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPetAction: vtbls: - ea: 0x14177CA20 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBuddyAction: vtbls: - ea: 0x14177CA38 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFaceCamera: vtbls: - ea: 0x14177CA50 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFieldMarker: vtbls: - ea: 0x14177CA68 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandLevelSync: vtbls: - ea: 0x14177CA80 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandMount: vtbls: - ea: 0x14177CA98 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandMinion: vtbls: - ea: 0x14177CAB0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandStatusOff: vtbls: - ea: 0x14177CAC8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandQuickChat: vtbls: - ea: 0x14177CAE0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBlueSpellbook: vtbls: - ea: 0x14177CAF8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFashion: vtbls: - ea: 0x14177CB10 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandEcho: vtbls: - ea: 0x14177CB40 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatSay: vtbls: - ea: 0x14177CB58 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatYell: vtbls: - ea: 0x14177CB70 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatShout: vtbls: - ea: 0x14177CB88 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatTell: vtbls: - ea: 0x14177CBA0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatReply: vtbls: - ea: 0x14177CBC0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatParty: vtbls: - ea: 0x14177CBF0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatFC: vtbls: - ea: 0x14177CC08 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatLinkshell: vtbls: - ea: 0x14177CC20 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUnknown1416EC328: vtbls: - ea: 0x14177CC38 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatAlliance: vtbls: - ea: 0x14177CC50 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatNovice: vtbls: - ea: 0x14177CC68 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatPvp: vtbls: - ea: 0x14177CC80 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatCrossWorldLinkshell: vtbls: - ea: 0x14177CC98 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandParty: vtbls: - ea: 0x14177CCB0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartyJoin: vtbls: - ea: 0x14177CCC8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartyDecline: vtbls: - ea: 0x14177CCE0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartyInvite: vtbls: - ea: 0x14177CCF8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartyLeave: vtbls: - ea: 0x14177CD10 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartyKick: vtbls: - ea: 0x14177CD28 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartyLeader: vtbls: - ea: 0x14177CD40 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFC: vtbls: - ea: 0x14177CD58 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandLinkshell: vtbls: - ea: 0x14177CD70 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandFriendlist: vtbls: - ea: 0x14177CD88 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBlacklist: vtbls: - ea: 0x14177CDB0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandEmote: vtbls: - ea: 0x14177CDD8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandCheck: vtbls: - ea: 0x14177CDF0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandSearch: vtbls: - ea: 0x14177CE08 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTrade: vtbls: - ea: 0x14177CE20 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandMateria: vtbls: - ea: 0x14177CE38 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandSalute: vtbls: - ea: 0x14177CE50 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandLookParty: vtbls: - ea: 0x14177CE68 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandComment: vtbls: - ea: 0x14177CE88 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandReadyCheck: vtbls: - ea: 0x14177CEA0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandRandom: vtbls: - ea: 0x14177CEB8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandDice: vtbls: - ea: 0x14177CED0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandClearTellHistory: vtbls: - ea: 0x14177CEE8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandLogout: vtbls: - ea: 0x14177CF00 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandCommand: vtbls: - ea: 0x14177CF38 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandQuit: vtbls: - ea: 0x14177CF50 base: Client::UI::Shell::ShellCommandLogout Client::UI::Shell::ShellCommandFaq: vtbls: - ea: 0x14177CF88 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandGM: vtbls: - ea: 0x14177CFB0 base: Component::Shell::DebugCommandInterface Client::UI::Shell::ShellCommandReturn: vtbls: - ea: 0x14177F058 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandLegacy: vtbls: - ea: 0x14177F070 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandHotbarBase: vtbls: - ea: 0x14177F088 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandHotbar: vtbls: - ea: 0x14177F0D8 base: Client::UI::Shell::ShellCommandHotbarBase Client::UI::Shell::ShellCommandHotbarCross: vtbls: - ea: 0x14177F128 base: Client::UI::Shell::ShellCommandHotbarBase Client::UI::Shell::ShellCommandMacroConfig: vtbls: - ea: 0x14177F178 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandInventory: vtbls: - ea: 0x14177F1A8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandItemSort: vtbls: - ea: 0x14177F1C0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandClearLog: vtbls: - ea: 0x14177F1D8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandInstanceArea: vtbls: - ea: 0x14177F1F0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandMacroError: vtbls: - ea: 0x14177F208 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandMacroCancel: vtbls: - ea: 0x14177F220 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPlayTime: vtbls: - ea: 0x14177F238 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandGroupPose: vtbls: - ea: 0x14177F250 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandItemSearch: vtbls: - ea: 0x14177F268 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandIdlingCamera: vtbls: - ea: 0x14177F280 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandGeneralDutyKey: vtbls: - ea: 0x14177F298 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandTitle: vtbls: - ea: 0x14177F2B0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandAlarm: vtbls: - ea: 0x14177F2C8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandHud: vtbls: - ea: 0x14177F2F8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandChatLog: vtbls: - ea: 0x14177F310 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUnk1416EE8C0: vtbls: - ea: 0x14177F328 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUnk1416EE8D8: vtbls: - ea: 0x14177F340 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBattleEffect: vtbls: - ea: 0x14177F358 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandHudReset: vtbls: - ea: 0x14177F370 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUiReset: vtbls: - ea: 0x14177F388 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandPartySort: vtbls: - ea: 0x14177F3A0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUiScale: vtbls: - ea: 0x14177F3B8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUnk1416EE968: vtbls: - ea: 0x14177F3D0 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandUnk1416EE990: vtbls: - ea: 0x14177F3F8 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandCrossHotbarType: vtbls: - ea: 0x14177F410 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandEgiGlamour: vtbls: - ea: 0x14177F428 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandBahamutSize: vtbls: - ea: 0x14177F440 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandConfigToggle: vtbls: - ea: 0x14177F460 base: Client::UI::Shell::RaptureShellCommandInterface Client::UI::Shell::ShellCommandNameplateConfig: vtbls: - ea: 0x14177F478 base: Client::UI::Shell::RaptureShellCommandInterface Client::Game::Character::BattleChara: vtbls: - ea: 0x14177F5F0 base: Client::Game::Character::Character - ea: 0x14177F8B8 base: Client::Graphics::Vfx::VfxDataListenner funcs: 0x140754F50: ctor 0x1407551B0: dtor Client::Game::TitleController: vtbls: - ea: 0x141780478 vfuncs: 0: dtor Client::Game::TitleList: vtbls: - ea: 0x141780480 vfuncs: 0: dtor Client::UI::Misc::RaptureHotbarModule::ClearCallback: vtbls: - ea: 0x1417804A0 Client::Game::UI::Hotbar: vtbls: - ea: 0x1417804C0 base: Client::UI::Misc::RaptureHotbarModule::ClearCallback vfuncs: 0: dtor funcs: 0x1407BAFE0: CancelCast Client::Game::UI::MarkingController: instances: - ea: 0x141EB4130 pointer: False vtbls: - ea: 0x141780468 vfuncs: 0: dtor funcs: 0x140787F10: ClearWaymarks Client::Game::LimitBreakController: instances: - ea: 0x141EB43E0 pointer: False vtbls: - ea: 0x141780470 vfuncs: 0: dtor Client::Game::UI::Telepo::SelectUseTicketInvoker: vtbls: - ea: 0x141780580 base: Component::GUI::AtkModuleInterface::AtkEventInterface vfuncs: 2: dtor Client::Game::UI::Telepo: instances: - ea: 0x141EA6C48 pointer: False vtbls: - ea: 0x141780598 base: Component::GUI::AtkModuleInterface::AtkEventInterface vfuncs: 2: dtor funcs: 0x140793CB0: ctor 0x140793E10: IsSelectUseTicketInactive 0x140793E40: UpdatePlayerAetheryteList 0x1407949E0: Teleport 0x140795CE0: TeleportWithTicket 0x140795D70: InvokeSelectUseTicket Client::UI::Agent::AgentHUD: vtbls: - ea: 0x141783BC8 base: Client::UI::Agent::AgentInterface funcs: 0x14080AE40: ctor 0x140810E40: UpdateParty 0x140814C50: UpdateHotBar 0x140822470: OpenContextMenuFromTarget 0x1408253E0: GetMainCommandString # MainCommand exd 0x140825720: OpenSystemMenu Client::UI::Agent::AgentChatLog: vtbls: - ea: 0x1417841C0 base: Client::UI::Agent::AgentInterface funcs: 0x140842C40: ctor 0x140847CB0: InsertTextCommandParam Client::UI::Agent::AgentInventory: vtbls: - ea: 0x141783C50 base: Client::UI::Agent::AgentInterface funcs: 0x140827330: ctor Client::UI::Agent::AgentInventoryContext: vtbls: - ea: 0x141731C38 base: Client::UI::Agent::AgentInterface funcs: 0x140207420: ctor 0x140208AB0: UnblockItemSlot Client::UI::Agent::AgentConfigLogColor: vtbls: - ea: 0x141732678 base: Client::UI::Agent::AgentInterface funcs: 0x140238BA0: ctor Client::UI::Agent::AgentConfigKey: vtbls: - ea: 0x1417326F8 base: Client::UI::Agent::AgentInterface funcs: 0x14023BB90: ctor Client::UI::Agent::AgentConfigPadCustomize: vtbls: - ea: 0x141732A20 base: Client::UI::Agent::AgentInterface funcs: 0x14024A330: ctor Client::UI::Agent::AgentEmote: vtbls: - ea: 0x141784868 base: Client::UI::Agent::AgentInterface funcs: 0x140879210: ctor Client::UI::Agent::AgentMacro: vtbls: - ea: 0x141784FC8 base: Client::UI::Agent::AgentInterface funcs: 0x14089C0A0: ctor Client::UI::Agent::AgentFishingNote: vtbls: - ea: 0x141784C20 base: Client::UI::Agent::AgentInterface funcs: 0x140891B10: ctor Client::UI::Agent::AgentFishGuide: vtbls: - ea: 0x141784CA8 base: Client::UI::Agent::AgentInterface funcs: 0x140894A90: ctor Client::UI::Agent::AgentFishRecord: vtbls: - ea: 0x141784D30 base: Client::UI::Agent::AgentInterface funcs: 0x140895DC0: ctor Client::UI::Agent::AgentQuestJournal: vtbls: - ea: 0x141784468 base: Client::UI::Agent::AgentInterface funcs: 0x140858C00: ctor Client::UI::Agent::AgentActionMenu: vtbls: - ea: 0x1417838F0 base: Client::UI::Agent::AgentInterface funcs: 0x140800280: ctor Client::UI::Agent::AgentMarker: vtbls: - ea: 0x141785F78 base: Client::UI::Agent::AgentInterface funcs: 0x1408DE270: ctor Client::UI::Agent::AgentTrade: vtbls: - ea: 0x141783DC8 base: Client::UI::Agent::AgentInterface funcs: 0x140833370: ctor Client::UI::Agent::AgentScreenLog: vtbls: - ea: 0x141786710 base: Client::UI::Agent::AgentInterface funcs: 0x1408FD390: ctor 0x1408FF830: OpenBalloon 0x1408FFCE0: CloseBalloon 0x1408FFE70: ResetBalloon Client::UI::Agent::AgentLoot: vtbls: - ea: 0x141785298 base: Client::UI::Agent::AgentInterface funcs: 0x1408A1F70: ctor Client::UI::Agent::AgentRepair: vtbls: - ea: 0x141786488 base: Client::UI::Agent::AgentInterface funcs: 0x1408F67B0: ctor Client::UI::Agent::AgentColorant: vtbls: - ea: 0x141786CB8 base: Client::UI::Agent::AgentInterface funcs: 0x14090CB30: ctor Client::UI::Agent::AgentHowTo: vtbls: - ea: 0x141784348 base: Client::UI::Agent::AgentInterface funcs: 0x140853EF0: ctor Client::UI::Agent::AgentHowToNotice: vtbls: - ea: 0x141784ED8 base: Client::UI::Agent::AgentInterface funcs: 0x14089A8B0: ctor Client::UI::Agent::AgentInspect: vtbls: - ea: 0x141785810 base: Client::UI::Agent::AgentInterface funcs: 0x1408B60A0: ctor Client::UI::Agent::AgentTelepotTown: vtbls: - ea: 0x1418CBA68 base: Client::UI::Agent::AgentInterface funcs: 0x14107E340: ctor Client::UI::Agent::AgentSocial: vtbls: - ea: 0x1417336A8 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentBlacklist: vtbls: - ea: 0x141733720 base: Client::UI::Agent::AgentInterface funcs: 0x140255B00: ctor Client::UI::Agent::AgentFriendlist: vtbls: - ea: 0x141733798 base: Client::UI::Agent::AgentInterface funcs: 0x140256C50: ctor Client::UI::Agent::AgentPartyMember: vtbls: - ea: 0x141733910 base: Client::UI::Agent::AgentInterface - ea: 0x141733988 base: Client::UI::Agent::AgentContext::AgentContextUpdateChecker funcs: 0x14025BDC0: ctor Client::UI::Agent::AgentLinkshell: vtbls: - ea: 0x141733810 base: Client::UI::Agent::AgentInterface funcs: 0x140259810: ctor Client::UI::Agent::AgentSearch: vtbls: - ea: 0x141733A08 base: Client::UI::Agent::AgentInterface funcs: 0x14025FA50: ctor Client::UI::Agent::AgentDetail: vtbls: - ea: 0x141733990 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentLetter: vtbls: - ea: 0x141733A88 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentLetterView: vtbls: - ea: 0x141733B18 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentActionDetail: vtbls: - ea: 0x141785D50 base: Client::UI::Agent::AgentInterface funcs: 0x1408D7C10: ctor Client::UI::Agent::AgentRetainer: vtbls: - ea: 0x141783D40 base: Client::UI::Agent::AgentInterface funcs: 0x14082CDC0: ctor Client::UI::Agent::AgentCutsceneReplay: vtbls: - ea: 0x141787378 base: Client::UI::Agent::AgentInterface funcs: 0x140924630: ctor Client::UI::Agent::AgentMonsterNote: vtbls: - ea: 0x141785FF0 base: Client::UI::Agent::AgentInterface funcs: 0x1408DE750: ctor Client::UI::Agent::AgentItemSearch: vtbls: - ea: 0x141733C18 base: Client::UI::Agent::AgentInterface funcs: 0x140268170: ctor Client::UI::Agent::AgentCatch: vtbls: - ea: 0x141787288 base: Client::UI::Agent::AgentInterface funcs: 0x140922FA0: ctor Client::UI::Agent::AgentFreeCompany: vtbls: - ea: 0x141733CB8 base: Client::UI::Agent::AgentInterface funcs: 0x140279B50: ctor Client::UI::Agent::AgentFreeCompanyProfile: vtbls: - ea: 0x141733DB8 base: Client::UI::Agent::AgentInterface funcs: 0x14027BA10: ctor Client::UI::Agent::AgentFreeCompanyInputString: vtbls: - ea: 0x141733F28 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentFreeCompanyExchange: vtbls: - ea: 0x141734030 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentFreeCompanyCrestEditor: vtbls: - ea: 0x1417340B0 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentFreeCompanyCrestDecal: vtbls: - ea: 0x141734130 base: Client::UI::Agent::AgentInterface funcs: 0x1402856D0: ctor Client::UI::Agent::AgentArmouryBoard: vtbls: - ea: 0x141783CC8 base: Client::UI::Agent::AgentInterface funcs: 0x14082A290: ctor Client::UI::Agent::AgentHowToList: vtbls: - ea: 0x1417868F0 base: Client::UI::Agent::AgentInterface funcs: 0x1409037D0: ctor Client::UI::Agent::AgentCabinet: vtbls: - ea: 0x141786990 base: Client::UI::Agent::AgentInterface funcs: 0x140906390: ctor Client::UI::Agent::AgentGrandCompanyRank: vtbls: - ea: 0x141785888 base: Client::UI::Agent::AgentInterface funcs: 0x1408B86B0: ctor Client::UI::Agent::AgentGrandCompanySupply: vtbls: - ea: 0x141786EB8 base: Client::UI::Agent::AgentInterface funcs: 0x1409173A0: ctor Client::UI::Agent::AgentGrandCompanyExchange: vtbls: - ea: 0x141786F30 base: Client::UI::Agent::AgentInterface funcs: 0x140919790: ctor Client::UI::Agent::AgentGearSet: vtbls: - ea: 0x141783E88 base: Client::UI::Agent::AgentInterface funcs: 0x140834A70: ctor Client::UI::Agent::AgentSupportMain: vtbls: - ea: 0x141736D98 base: Client::UI::Agent::AgentInterface funcs: 0x1402D4DC0: ctor Client::UI::Agent::AgentSupportSubList: vtbls: - ea: 0x141736E10 base: Client::UI::Agent::AgentInterface funcs: 0x1402D6690: ctor Client::UI::Agent::AgentSupportSubView: vtbls: - ea: 0x141736E90 base: Client::UI::Agent::AgentInterface funcs: 0x1402D7410: ctor Client::UI::Agent::AgentSupportSubEdit: vtbls: - ea: 0x141736F10 base: Client::UI::Agent::AgentInterface funcs: 0x1402D86B0: ctor Client::UI::Agent::AgentAchievement: vtbls: - ea: 0x1417842C0 base: Client::UI::Agent::AgentInterface funcs: 0x14084BD30: ctor Client::UI::Agent::AgentLicenseViewer: vtbls: - ea: 0x141732350 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentMovieSubtitle: vtbls: - ea: 0x141786FA8 base: Client::UI::Agent::AgentInterface funcs: 0x140919FD0: ctor Client::UI::Agent::AgentPadMouseMode: vtbls: - ea: 0x141787020 base: Client::UI::Agent::AgentInterface funcs: 0x14091A3B0: ctor Client::UI::Agent::AgentRecommendList: vtbls: - ea: 0x1417860A8 base: Client::UI::Agent::AgentInterface funcs: 0x1408E1CB0: ctor Client::UI::Agent::AgentBuddy: vtbls: - ea: 0x141784E60 base: Client::UI::Agent::AgentInterface funcs: 0x140897910: ctor Client::UI::Agent::AgentCloseMessage: vtbls: - ea: 0x141732C08 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentCreditCast: vtbls: - ea: 0x141733130 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentShop: vtbls: - ea: 0x141785698 base: Client::UI::Agent::AgentInterface funcs: 0x1408B23C0: ctor Client::UI::Agent::AgentBait: vtbls: - ea: 0x141787418 base: Client::UI::Agent::AgentInterface funcs: 0x140926B60: ctor Client::UI::Agent::AgentHousing: vtbls: - ea: 0x1418D8FD8 base: Client::UI::Agent::AgentInterface funcs: 0x1410CFC80: ctor Client::UI::Agent::AgentHousingSignboard: vtbls: - ea: 0x1418D9070 base: Client::UI::Agent::AgentInterface funcs: 0x1410E4810: ctor Client::UI::Agent::AgentHousingPortal: vtbls: - ea: 0x1418D92E0 base: Client::UI::Agent::AgentInterface funcs: 0x1410EA3D0: ctor Client::UI::Agent::AgentHousingPlant: vtbls: - ea: 0x1418D9250 base: Client::UI::Agent::AgentInterface funcs: 0x1410E8D70: ctor Client::UI::Agent::AgentPersonalRoomPortal: vtbls: - ea: 0x141787880 base: Client::UI::Agent::AgentInterface funcs: 0x140936C40: ctor Client::UI::Agent::AgentTreasureHunt: vtbls: - ea: 0x1418D93D0 base: Client::UI::Agent::AgentInterface funcs: 0x1410EC7A0: ctor Client::UI::Agent::AgentLookingForGroup: vtbls: - ea: 0x141734228 base: Client::UI::Agent::AgentInterface funcs: 0x140287AD0: ctor Client::UI::Agent::AgentContentsMvp: vtbls: - ea: 0x141785220 base: Client::UI::Agent::AgentInterface funcs: 0x1408A15E0: ctor Client::UI::Agent::AgentVoteKick: vtbls: - ea: 0x1417851A8 base: Client::UI::Agent::AgentInterface funcs: 0x1408A0E60: ctor Client::UI::Agent::AgentVoteGiveUp: vtbls: - ea: 0x141785130 base: Client::UI::Agent::AgentInterface funcs: 0x1408A09D0: ctor Client::UI::Agent::AgentVoteTreasure: vtbls: - ea: 0x1417850B8 base: Client::UI::Agent::AgentInterface funcs: 0x1408A0460: ctor Client::UI::Agent::AgentPvpProfile: vtbls: - ea: 0x141787490 base: Client::UI::Agent::AgentInterface funcs: 0x140927720: ctor Client::UI::Agent::AgentContentsNote: vtbls: - ea: 0x141787530 base: Client::UI::Agent::AgentInterface funcs: 0x14092CD70: ctor Client::UI::Agent::AgentFieldMarker: vtbls: - ea: 0x141784BA8 base: Client::UI::Agent::AgentInterface funcs: 0x14088FF00: ctor Client::UI::Agent::AgentRetainerStatus: vtbls: - ea: 0x141786610 base: Client::UI::Agent::AgentInterface funcs: 0x1408FAE30: ctor Client::UI::Agent::AgentRetainerTask: vtbls: - ea: 0x1417875A8 base: Client::UI::Agent::AgentInterface funcs: 0x14092EBA0: ctor Client::UI::Agent::AgentRelicNoteBook: vtbls: - ea: 0x1417876F8 base: Client::UI::Agent::AgentInterface funcs: 0x140932970: ctor Client::UI::Agent::AgentMiniGame: vtbls: - ea: 0x141737110 base: Client::UI::Agent::AgentInterface funcs: 0x1402DC2B0: ctor Client::UI::Agent::AgentAdventureNoteBook: vtbls: - ea: 0x141783B50 base: Client::UI::Agent::AgentInterface funcs: 0x1408099F0: ctor Client::UI::Agent::AgentMinionMountBase: vtbls: - ea: 0x141787A08 base: Client::UI::Agent::AgentInterface funcs: 0x14093C550: ctor Client::UI::Agent::AgentMinionNoteBook: vtbls: - ea: 0x141787B80 base: Client::UI::Agent::AgentMinionMountBase funcs: 0x14093F140: ctor Client::UI::Agent::AgentMountNoteBook: vtbls: - ea: 0x141787D50 base: Client::UI::Agent::AgentMinionMountBase funcs: 0x140941CF0: ctor Client::UI::Agent::AgentItemComp: vtbls: - ea: 0x141784040 base: Client::UI::Agent::AgentInterface funcs: 0x14083D040: ctor 0x14083D1D0: CompareItem Client::UI::Agent::AgentMobhunt: vtbls: - ea: 0x141787198 base: Client::UI::Agent::AgentInterface funcs: 0x14091F6B0: ctor Client::UI::Agent::AgentMateriaAttach: vtbls: - ea: 0x141785B68 base: Client::UI::Agent::AgentInterface funcs: 0x1408C78D0: ctor Client::UI::Agent::AgentMiragePrism: vtbls: - ea: 0x141786B60 base: Client::UI::Agent::AgentInterface funcs: 0x140909150: ctor Client::UI::Agent::AgentAetherCurrent: vtbls: - ea: 0x141785DC8 base: Client::UI::Agent::AgentInterface funcs: 0x1408DC230: ctor Client::UI::Agent::AgentCurrency: vtbls: - ea: 0x141784F50 base: Client::UI::Agent::AgentInterface funcs: 0x14089AC40: ctor Client::UI::Agent::AgentLovmParty: vtbls: - ea: 0x1417CA978 base: Client::UI::Agent::AgentInterface funcs: 0x140BC4950: ctor Client::UI::Agent::AgentLovmRanking: vtbls: - ea: 0x1417CAA18 base: Client::UI::Agent::AgentInterface funcs: 0x140BCAA30: ctor Client::UI::Agent::AgentLovmNamePlate: vtbls: - ea: 0x1417CAA90 base: Client::UI::Agent::AgentInterface funcs: 0x140BCB180: ctor Client::UI::Agent::AgentLovmResult: vtbls: - ea: 0x1417CAB08 base: Client::UI::Agent::AgentInterface funcs: 0x140BCB730: ctor Client::UI::Agent::AgentLotteryDaily: vtbls: - ea: 0x1417CA198 base: Client::UI::Agent::AgentInterface funcs: 0x140BAEC80: ctor Client::UI::Agent::AgentLotteryWeekly: vtbls: - ea: 0x1417CA228 base: Client::UI::Agent::AgentInterface funcs: 0x140BB0120: ctor Client::UI::Agent::AgentLovmPaletteEdit: vtbls: - ea: 0x1417CA318 base: Client::UI::Agent::AgentInterface funcs: 0x140BB8EF0: ctor Client::UI::Agent::AgentDpsChallenge: vtbls: - ea: 0x141788BA8 base: Client::UI::Agent::AgentInterface funcs: 0x14094A890: ctor Client::UI::Agent::AgentOrchestrion: vtbls: - ea: 0x141788C48 base: Client::UI::Agent::AgentInterface funcs: 0x14094C570: ctor Client::UI::Agent::AgentOrchestrionInn: vtbls: - ea: 0x141788DA0 base: Client::UI::Agent::AgentOrchestrion funcs: 0x1409534D0: ctor Client::UI::Agent::AgentDeepDungeonMap: vtbls: - ea: 0x141841780 base: Client::UI::Agent::AgentInterface funcs: 0x140C22EC0: ctor Client::UI::Agent::AgentDeepDungeonStatus: vtbls: - ea: 0x1418417F8 base: Client::UI::Agent::AgentInterface funcs: 0x140C24360: ctor Client::UI::Agent::AgentDeepDungeonSaveData: vtbls: - ea: 0x141841870 base: Client::UI::Agent::AgentInterface funcs: 0x140C25820: ctor Client::UI::Agent::AgentDeepDungeonScore: vtbls: - ea: 0x141841978 base: Client::UI::Agent::AgentInterface funcs: 0x140C28D40: ctor Client::UI::Agent::AgentOrchestrionPlayList: vtbls: - ea: 0x141788D08 base: Client::UI::Agent::AgentInterface funcs: 0x14094F760: ctor Client::UI::Agent::AgentWeeklyBingo: vtbls: - ea: 0x1418435F0 base: Client::UI::Agent::AgentInterface funcs: 0x140C73730: ctor Client::UI::Agent::AgentDeepDungeonMenu: vtbls: - ea: 0x1418418E8 base: Client::UI::Agent::AgentInterface funcs: 0x140C27C50: ctor Client::UI::Agent::AgentItemAppraisal: vtbls: - ea: 0x141789188 base: Client::UI::Agent::AgentInterface funcs: 0x140957290: ctor Client::UI::Agent::AgentItemInspection: vtbls: - ea: 0x141785C58 base: Client::UI::Agent::AgentInterface funcs: 0x1408D0200: ctor Client::UI::Agent::AgentTeleportHousingFriend: vtbls: - ea: 0x141789530 base: Client::UI::Agent::AgentInterface funcs: 0x14095BED0: ctor Client::UI::Agent::AgentHousingGuestBook: vtbls: - ea: 0x1418D9600 base: Client::UI::Agent::AgentInterface funcs: 0x1410F3920: ctor Client::UI::Agent::AgentAozNoteBook: vtbls: - ea: 0x141789638 base: Client::UI::Agent::AgentInterface funcs: 0x14095E7A0: ctor Client::UI::Agent::AgentWorldTravel: vtbls: - ea: 0x141842F18 base: Client::UI::Agent::AgentInterface funcs: 0x140C65540: ctor Client::UI::Agent::AgentDawn: vtbls: - ea: 0x141842EA0 base: Client::UI::Agent::AgentInterface funcs: 0x140C60E60: ctor Client::UI::Agent::AgentTargetCircle: vtbls: - ea: 0x141786878 base: Client::UI::Agent::AgentInterface funcs: 0x140902410: ctor Client::UI::Agent::AgentCraftActionSimulator: vtbls: - ea: 0x141789938 base: Client::UI::Agent::AgentInterface funcs: 0x140969880: ctor Client::UI::Agent::AgentTryon::TryonCharaView: vtbls: - ea: 0x141783F08 base: Client::UI::Misc::CharaView funcs: 0x140838410: ctor Client::UI::Agent::AgentTryon: vtbls: - ea: 0x141783F48 base: Client::UI::Agent::AgentInterface funcs: 0x140838BC0: ctor Client::UI::Agent::AgentItemDetailBase: vtbls: - ea: 0x141783FC0 base: Client::UI::Agent::AgentInterface funcs: 0x14083B770: ctor Client::UI::Agent::AgentContentsFinderSetting: vtbls: - ea: 0x141784568 base: Client::UI::Agent::AgentInterface funcs: 0x140864FA0: ctor Client::UI::Agent::AgentContentsFinder: vtbls: - ea: 0x141784610 base: Client::UI::Agent::AgentInterface funcs: 0x140868CC0: ctor Client::UI::Agent::AgentMap::MapMarkerStructSearchName: vtbls: - ea: 0x141784B20 base: Client::UI::Agent::AgentMap::MapMarkerStructSearch vfuncs: 1: Evaluate Client::UI::Agent::AgentMap: vtbls: - ea: 0x141784B30 base: Client::UI::Agent::AgentInterface funcs: 0x140884060: ctor 0x140880990: AddGatheringTempMapMarker 0x14087FCD0: OpenMap 0x14088B010: OpenMapByMapId 0x140880CE0: SetFlagMapMarker # (this, territoryId, mapId, (float)x, (float)y, iconId) 0x14088F0C0: CanUseTeleport # static Client::UI::Agent::AgentRecipeNote: vtbls: - ea: 0x141786228 base: Client::UI::Agent::AgentInterface funcs: 0x1408EAFA0: ctor Client::UI::Agent::AgentTeleport: vtbls: - ea: 0x1418CB5B0 base: Client::UI::Agent::AgentInterface funcs: 0x14106E240: ctor Client::UI::Agent::AgentRevive: vtbls: - ea: 0x141785040 base: Client::UI::Agent::AgentInterface funcs: 0x14089F0E0: ctor Client::UI::Agent::AgentConfigBase: vtbls: - ea: 0x141732780 base: Client::UI::Agent::AgentInterface funcs: 0x14023DD30: ctor Client::UI::Agent::AgentConfigSystem: vtbls: - ea: 0x141732858 base: Client::UI::Agent::AgentConfigBase funcs: 0x140243C50: ctor Client::UI::Agent::AgentConfigCharacter: vtbls: - ea: 0x141732938 base: Client::UI::Agent::AgentConfigBase funcs: 0x140245240: ctor Client::UI::Agent::AgentHudLayout: vtbls: - ea: 0x141785578 base: Client::UI::Agent::AgentInterface funcs: 0x1408ABA00: ctor Client::UI::Agent::AgentItemDetail: vtbls: - ea: 0x141785AE8 base: Client::UI::Agent::AgentItemDetailBase funcs: 0x1408BF850: ctor 0x1408C0880: OnItemHovered Client::UI::Agent::AgentStatus::StatusCharaView: vtbls: - ea: 0x141786500 base: Client::UI::Misc::CharaView Client::UI::Agent::AgentStatus: vtbls: - ea: 0x141786538 base: Client::UI::Agent::AgentInterface funcs: 0x1408F92A0: ctor Client::UI::Agent::AgentMaterialize: vtbls: - ea: 0x141786A80 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentContentsTimer: vtbls: - ea: 0x141786DB8 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentGatheringNote: vtbls: - ea: 0x1418CB4F8 base: Client::UI::Agent::AgentInterface Client::UI::Agent::AgentMcguffin: vtbls: - ea: 0x141843578 base: Client::UI::Agent::AgentInterface Client::Game::Event::EventHandler: vtbls: - ea: 0x141796A20 Client::Game::Event::LuaScriptLoader<Client::Game::Event::ModuleBase>: vtbls: - ea: 0x141797238 base: Client::System::Resource::ResourceEventListener Client::Game::Event::ModuleBase: vtbls: - ea: 0x141797260 vfuncs: 1: SetupClasses 4: SetupClasses_2 Client::Game::Event::LuaScriptLoader<Client::Game::Event::LuaEventHandler>: vtbls: - ea: 0x141797298 base: Client::System::Resource::ResourceEventListener Client::Game::Event::LuaEventHandler: vtbls: - ea: 0x1417972C0 base: Client::Game::Event::EventHandler Client::Game::Event::EventSceneModuleImplBase: vtbls: - ea: 0x141797AE8 Client::Game::Event::EventSceneModuleUsualImpl: vtbls: - ea: 0x141798210 base: Client::Game::Event::EventSceneModuleImplBase Client::Game::Event::Director: vtbls: - ea: 0x14179A130 base: Client::Game::Event::LuaEventHandler Client::Game::Event::EventFramework: instances: - ea: 0x141EBDF70 pointer: True funcs: 0x140A58140: GetSingleton 0x140A58430: ctor 0x140A58BF0: dtor 0x140A60EF0: ProcessDirectorUpdate 0x140A64740: GetInstanceContentDirector Client::Game::Event::EventHandlerModule: vtbls: - ea: 0x14179C600 base: Client::Game::Event::ModuleBase funcs: 0x140A3AE80: ctor Client::Game::Event::LuaActorModule: vtbls: - ea: 0x14179C640 base: Client::Game::Event::ModuleBase funcs: 0x140A3ED60: ctor Client::Game::Event::DirectorModule: vtbls: - ea: 0x14179C678 base: Client::Game::Event::ModuleBase funcs: 0x140A3F610: ctor Client::Game::Event::LeveDirector: vtbls: - ea: 0x14179E7E8 base: Client::Game::Event::Director Client::Game::Event::GatheringLeveDirector: vtbls: - ea: 0x1417ADD90 base: Client::Game::Event::LeveDirector Client::Game::Event::BattleLeveDirector: vtbls: - ea: 0x14179F0D8 base: Client::Game::Event::LeveDirector Client::Game::Event::CompanyLeveDirector: vtbls: - ea: 0x1417B0758 base: Client::Game::Event::LeveDirector Client::Game::Gimmick::GimmickBill: vtbls: - ea: 0x1417AD518 base: Client::Game::Gimmick::GimmickEventHandler Client::Game::InstanceContent::ContentDirector: vtbls: - ea: 0x14179AA20 base: Client::Game::Event::Director Client::Game::InstanceContent::InstanceContentDirector: vtbls: - ea: 0x1417CC2A8 base: Client::Game::InstanceContent::ContentDirector Client::Game::InstanceContent::PublicContentDirector: vtbls: - ea: 0x14192F4D8 base: Client::Game::InstanceContent::ContentDirector Client::UI::PopupMenu: vtbls: - ea: 0x141847868 base: Component::GUI::AtkEventListener vfuncs: 3: OnItemSelected Client::UI::AddonFadeMiddleBack: vtbls: - ea: 0x141847F58 base: Component::GUI::AtkUnitBase Client::UI::AddonFilter: vtbls: - ea: 0x141848600 base: Component::GUI::AtkUnitBase Client::UI::AddonOperationGuide: vtbls: - ea: 0x141848840 base: Component::GUI::AtkUnitBase Client::UI::AddonNowLoading: vtbls: - ea: 0x141848A80 base: Component::GUI::AtkUnitBase funcs: 0x140CBC080: ctor Client::UI::AddonSelectOk: vtbls: - ea: 0x141849110 base: Component::GUI::AtkUnitBase Client::UI::AddonContextMenu: vtbls: - ea: 0x141849360 base: Component::GUI::AtkUnitBase Client::UI::AddonContextMenuTitle: vtbls: - ea: 0x141849590 base: Client::UI::AddonContextMenu Client::UI::AddonSelectString::PopupMenuDerive: vtbls: - ea: 0x1418497C0 base: Client::UI::PopupMenu Client::UI::AddonSelectString: vtbls: - ea: 0x1418497E8 base: Component::GUI::AtkUnitBase Client::UI::AddonSelectIconString::PopupMenuDerive: vtbls: - ea: 0x141849E60 base: Client::UI::PopupMenu Client::UI::AddonSelectIconString: vtbls: - ea: 0x141849E88 base: Component::GUI::AtkUnitBase Client::UI::AddonTooltip: vtbls: - ea: 0x14184A0B0 base: Component::GUI::AtkUnitBase Client::UI::AddonContextIconMenu: vtbls: - ea: 0x14184A968 base: Component::GUI::AtkUnitBase Client::UI::AddonSelectYesno: vtbls: - ea: 0x14184B680 base: Component::GUI::AtkUnitBase funcs: 0x140CC7AA0: ctor Client::UI::AddonSocial: vtbls: - ea: 0x141857D10 base: Component::GUI::AtkUnitBase Client::UI::AddonRequest: vtbls: - ea: 0x14184E200 base: Component::GUI::AtkUnitBase Client::UI::AddonContactList: vtbls: - ea: 0x1418529A0 base: Component::GUI::AtkUnitBase Client::UI::AddonAirShipExploration: vtbls: - ea: 0x141856F98 base: Component::GUI::AtkUnitBase Client::UI::AddonItemSearchResult: vtbls: - ea: 0x14184F118 base: Component::GUI::AtkUnitBase funcs: 0x140CECEE0: ctor 0x140CEDBE0: UpdateResult Client::UI::AddonConfigSystem: vtbls: - ea: 0x14185B8C8 base: Component::GUI::AtkUnitBase Client::UI::AddonCharaSelectWorldServer: vtbls: - ea: 0x141861A38 base: Component::GUI::AtkUnitBase Client::UI::AddonJournalDetail: vtbls: - ea: 0x1418745E0 base: Component::GUI::AtkUnitBase Client::UI::AddonJournalResult: vtbls: - ea: 0x141874E80 base: Component::GUI::AtkUnitBase Client::UI::AddonGuildLeve: vtbls: - ea: 0x1418750C8 base: Component::GUI::AtkUnitBase Client::UI::AddonRetainerList: vtbls: - ea: 0x141879E98 base: Component::GUI::AtkUnitBase Client::UI::AddonRetainerTaskList: vtbls: - ea: 0x141879820 base: Component::GUI::AtkUnitBase Client::UI::AddonRetainerTaskAsk: vtbls: - ea: 0x141879A48 base: Component::GUI::AtkUnitBase Client::UI::AddonRetainerTaskResult: vtbls: - ea: 0x141879C70 base: Component::GUI::AtkUnitBase Client::UI::AddonRetainerSellList: vtbls: - ea: 0x141878438 base: Component::GUI::AtkUnitBase Client::UI::AddonRetainerSell: vtbls: - ea: 0x141878210 base: Component::GUI::AtkUnitBase Client::UI::AddonGatheringNoteBook: vtbls: - ea: 0x14187A570 base: Component::GUI::AtkUnitBase Client::UI::AddonRecipeNote: vtbls: - ea: 0x14187A7B8 base: Component::GUI::AtkUnitBase funcs: 0x140E0C1A0: ReceiveEvent_ClickSynthesizeButton 0x140E0C1F0: ReceiveEvent_ClickQuickSynthesisButton 0x140E0C240: ReceiveEvent_ClickTrialSynthesisButton Client::UI::Atk2DAreaMap: vtbls: - ea: 0x14187B080 base: Client::UI::Atk2DMap Client::UI::AddonRelicNoteBook: vtbls: - ea: 0x14187B988 base: Component::GUI::AtkUnitBase Client::UI::AddonAOZNotebook: vtbls: - ea: 0x14187CA88 base: Component::GUI::AtkUnitBase Client::UI::AddonAOZNotebookPresetList: vtbls: - ea: 0x14187CD70 base: Component::GUI::AtkUnitBase Client::UI::AddonRepair: vtbls: - ea: 0x1418903E0 base: Component::GUI::AtkUnitBase Client::UI::AddonCabinetWithdraw: vtbls: - ea: 0x1418919D0 base: Component::GUI::AtkUnitBase Client::UI::AddonContentsFinder: vtbls: - ea: 0x141893608 base: Component::GUI::AtkUnitBase Client::UI::AddonContentsFinderSetting: vtbls: - ea: 0x14187DB38 base: Component::GUI::AtkUnitBase Client::UI::AddonContentsFinderConfirm: vtbls: - ea: 0x14187DF88 base: Component::GUI::AtkUnitBase Client::UI::AddonRaidFinder: vtbls: - ea: 0x14187E610 base: Component::GUI::AtkUnitBase Client::UI::AddonMaterializeDialog: vtbls: - ea: 0x14187ECB8 base: Component::GUI::AtkUnitBase funcs: 0x140E3BDD0: ctor Client::UI::AddonSynthesis: vtbls: - ea: 0x14188F4C8 base: Component::GUI::AtkUnitBase Client::UI::AddonMateriaAttach: vtbls: - ea: 0x141891580 base: Component::GUI::AtkUnitBase Client::UI::AddonMateriaDialogBase: vtbls: - ea: 0x14187F108 base: Component::GUI::AtkUnitBase Client::UI::AddonMateriaAttachDialog: vtbls: - ea: 0x14187F330 base: Client::UI::AddonMateriaDialogBase Client::UI::AddonMateriaRetrieveDialog: vtbls: - ea: 0x14187F560 base: Client::UI::AddonMateriaDialogBase Client::UI::AddonMiragePrismMiragePlate: vtbls: - ea: 0x1418940F0 base: Component::GUI::AtkUnitBase funcs: 0x140EF5900: ctor Client::UI::AddonMiragePrismPrismBox: vtbls: - ea: 0x141880278 base: Component::GUI::AtkUnitBase Client::UI::AddonMiragePrismPrismBoxCrystallize: vtbls: - ea: 0x141880598 base: Component::GUI::AtkUnitBase Client::UI::AddonGrandCompanySupplyReward: vtbls: - ea: 0x1418992E0 base: Component::GUI::AtkUnitBase Client::UI::AddonTalk: vtbls: - ea: 0x141886568 base: Component::GUI::AtkUnitBase funcs: 0x140E73AB0: ctor Client::UI::AddonChatLogPanel: vtbls: - ea: 0x141887258 base: Component::GUI::AtkUnitBase Client::UI::AddonChatLog: vtbls: - ea: 0x141887480 base: Component::GUI::AtkUnitBase Client::UI::AddonActionDetail: vtbls: - ea: 0x141887DC0 base: Component::GUI::AtkUnitBase funcs: 0x140E87C20: ctor 0x140E883B0: GenerateTooltip Client::UI::AddonItemDetail: vtbls: - ea: 0x141888258 base: Component::GUI::AtkUnitBase funcs: 0x140E88A00: ctor 0x140E89F20: GenerateTooltip Client::UI::AddonCharacterInspect: vtbls: - ea: 0x141889438 base: Component::GUI::AtkUnitBase Client::UI::AddonSalvageDialog: vtbls: - ea: 0x14188CD18 base: Component::GUI::AtkUnitBase funcs: 0x140EAC0F0: ctor Client::UI::AddonAreaMap: vtbls: - ea: 0x14188E6F8 base: Component::GUI::AtkUnitBase funcs: 0x140EB61C0: ctor Client::UI::AddonScreenText: vtbls: - ea: 0x1418B48C0 base: Component::GUI::AtkUnitBase funcs: 0x140FD6DE0: ctor Client::UI::AddonPopUpText: vtbls: - ea: 0x14188ED90 base: Component::GUI::AtkUnitBase funcs: 0x140EC03F0: ctor Client::UI::AddonFlyText: vtbls: - ea: 0x14188EFB8 base: Component::GUI::AtkUnitBase funcs: 0x140EC27F0: ctor Client::UI::AddonMiniTalk: vtbls: - ea: 0x14188F1E0 base: Component::GUI::AtkUnitBase funcs: 0x140EC5220: ctor Client::UI::AddonGathering: vtbls: - ea: 0x14188FB40 base: Component::GUI::AtkUnitBase funcs: 0x140EC8520: ctor 0x140F88E50: ReceiveEvent_ToggleQuickGathering 0x140EC8D20: ReceiveEvent_Gather Client::UI::AddonGatheringMasterpiece: vtbls: - ea: 0x14188FD68 base: Component::GUI::AtkUnitBase Client::UI::AddonNamePlate::BakePlateRenderer: vtbls: - ea: 0x141890608 base: Component::GUI::AtkTextNodeRenderer Client::UI::AddonNamePlate: vtbls: - ea: 0x141890628 base: Component::GUI::AtkUnitBase funcs: 0x140ED1600: ctor 0x140ED18E0: SetCommonNamePlate # x, y, scale, etc 0x140ED1B10: SetPlayerNamePlate # player specific nodes 0x140ED44E0: ToggleTextRenderMode Client::UI::AddonTeleport: vtbls: - ea: 0x141894E38 base: Component::GUI::AtkUnitBase funcs: 0x140EFA100: ctor 0x140EFAD70: ChangeTab Client::UI::AddonDeepDungeonStatus: vtbls: - ea: 0x14189F9B8 base: Component::GUI::AtkUnitBase funcs: 0x140F41DE0: ctor Client::UI::AddonItemInspectionList: vtbls: - ea: 0x1418A2370 base: Component::GUI::AtkUnitBase Client::UI::AddonItemInspectionResult: vtbls: - ea: 0x1418A27C0 base: Component::GUI::AtkUnitBase Client::UI::AddonWeeklyBingo::DutySlot: vtbls: - ea: 0x1418AA730 base: Component::GUI::AtkEventListener Client::UI::AddonWeeklyBingo::DutySlotList: vtbls: - ea: 0x1418AA748 Client::UI::AddonWeeklyBingo::StringThing: vtbls: - ea: 0x1418AA750 Client::UI::AddonWeeklyBingo::StickerSlot: vtbls: - ea: 0x1418AA758 Client::UI::AddonWeeklyBingo::StickerSlotList: vtbls: - ea: 0x1418AA760 Client::UI::AddonWeeklyBingo::RewardCategory: vtbls: - ea: 0x1418AA768 base: Component::GUI::AtkEventListener Client::UI::AddonWeeklyBingo::RewardGuaranteed: vtbls: - ea: 0x1418AA780 base: Component::GUI::AtkEventListener Client::UI::AddonWeeklyBingo::RewardCategoryList: vtbls: - ea: 0x1418AA798 Client::UI::AddonWeeklyBingo: vtbls: - ea: 0x1418AA7A0 base: Component::GUI::AtkUnitBase Client::UI::AddonWeeklyPuzzle: vtbls: - ea: 0x1418AAE18 base: Component::GUI::AtkUnitBase Client::UI::AddonMYCItemBox: vtbls: - ea: 0x1418AC458 base: Component::GUI::AtkUnitBase Client::UI::AddonTargetInfoBase: vtbls: - ea: 0x1418B0350 base: Component::GUI::AtkUnitBase Client::UI::AddonTargetInfo: vtbls: - ea: 0x1418B0578 base: Client::UI::AddonTargetInfoBase Client::UI::AddonTargetInfoUnknown1: vtbls: - ea: 0x1418B07A0 base: Client::UI::AddonTargetInfoBase Client::UI::AddonTargetInfoUnknown2: vtbls: - ea: 0x1418B09C8 base: Client::UI::AddonTargetInfoBase Client::UI::AddonTargetInfoMainTarget: vtbls: - ea: 0x1418B0BF0 base: Client::UI::AddonTargetInfoBase Client::UI::AddonTargetCursor: vtbls: - ea: 0x1418B0E18 base: Component::GUI::AtkUnitBase funcs: 0x140FC9FA0: ctor Client::UI::AddonBattleTalk: vtbls: - ea: 0x1418B1268 base: Component::GUI::AtkUnitBase Client::UI::AddonScreenInfoFrontBack: vtbls: - ea: 0x1418B1490 base: Component::GUI::AtkUnitBase Client::UI::AddonMainCommand: vtbls: - ea: 0x1418B9CD0 base: Component::GUI::AtkUnitBase Client::UI::AddonParameterWidget: vtbls: - ea: 0x1418B9F18 base: Component::GUI::AtkUnitBase Client::UI::AddonExp: vtbls: - ea: 0x1418BA140 base: Component::GUI::AtkUnitBase Client::UI::AddonEnemyList: vtbls: - ea: 0x1418BA368 base: Component::GUI::AtkUnitBase Client::UI::AddonBagWidget: vtbls: - ea: 0x1418BAF38 base: Component::GUI::AtkUnitBase Client::UI::AddonMoney: vtbls: - ea: 0x1418BB160 base: Component::GUI::AtkUnitBase Client::UI::AddonNotification: vtbls: - ea: 0x1418BB388 base: Component::GUI::AtkUnitBase Client::UI::AddonShopCardDialog: vtbls: - ea: 0x1418CEE50 base: Component::GUI::AtkUnitBase Client::UI::AddonDTR: vtbls: - ea: 0x1418BB930 base: Component::GUI::AtkUnitBase Client::UI::AddonCastBar: vtbls: - ea: 0x1418BBB58 base: Component::GUI::AtkUnitBase Client::UI::AddonNaviMap: vtbls: - ea: 0x1418BBDB0 base: Component::GUI::AtkUnitBase Client::UI::AddonActionBarBase: vtbls: - ea: 0x1418BBFE0 base: Component::GUI::AtkUnitBase vfuncs: 75: PulseActionBarSlot Client::UI::AddonActionBarX: vtbls: - ea: 0x1418BC290 base: Client::UI::AddonActionBarBase Client::UI::AddonActionBar: vtbls: - ea: 0x1418BC5A8 base: Client::UI::AddonActionBarX Client::UI::AddonPartyList: vtbls: - ea: 0x1418BCB70 base: Component::GUI::AtkUnitBase funcs: 0x140FF5590: ResizeForPartySize Client::UI::AddonAllianceListX: vtbls: - ea: 0x1418BCDA0 base: Component::GUI::AtkUnitBase Client::UI::AddonToDoList: vtbls: - ea: 0x1418BD748 base: Component::GUI::AtkUnitBase Client::UI::AddonActionCross: vtbls: - ea: 0x1418BDFA0 base: Client::UI::AddonActionBarBase Client::UI::AddonActionContents: vtbls: - ea: 0x1418BE258 base: Component::GUI::AtkUnitBase Client::UI::AddonActionDoubleCrossBase: vtbls: - ea: 0x1418BE490 base: Client::UI::AddonActionBarX Client::UI::AddonActionDoubleCrossL: vtbls: - ea: 0x1418BE780 base: Client::UI::AddonActionDoubleCrossBase Client::UI::AddonActionDoubleCrossR: vtbls: - ea: 0x1418BEA80 base: Client::UI::AddonActionDoubleCrossBase Client::UI::AddonFocusTargetInfo: vtbls: - ea: 0x1418BED70 base: Component::GUI::AtkUnitBase Client::UI::AddonLimitBreak: vtbls: - ea: 0x1418BEF98 base: Component::GUI::AtkUnitBase Client::UI::AddonMainCross: vtbls: - ea: 0x1418BF1F8 base: Component::GUI::AtkUnitBase Client::UI::AddonHudLayoutWindow: vtbls: - ea: 0x1418C5010 base: Component::GUI::AtkUnitBase funcs: 0x1410303D0: ctor Client::UI::AddonHudLayoutScreen: vtbls: - ea: 0x1418C5238 base: Component::GUI::AtkUnitBase funcs: 0x141031660: ctor 0x1410362D0: AddonOverlayMouseMovedEvent 0x141036500: AddonOverlayMouseClickEvent 0x141036900: AddonOverlayMouseReleaseEvent 0x1410385B0: _SetAddonScale Client::Game::Fate::FateDirector: vtbls: - ea: 0x1418DA648 base: Client::Game::Event::Director Client::Game::Fate::FateContext: vtbls: - ea: 0x1418DAF48 vfuncs: 0: dtor Client::UI::AddonLotteryDaily: vtbls: - ea: 0x1418D6A30 base: Component::GUI::AtkUnitBase Client::Game::Object::EventObject: vtbls: - ea: 0x1418D9B10 base: Client::Game::Object::GameObject Client::Game::Object::Treasure: vtbls: - ea: 0x1418D9D80 base: Client::Game::Object::GameObject Client::Game::Object::GatheringPointObject::GatheringPointObjectImplBase: vtbls: - ea: 0x1418D9FF0 Client::Game::Object::GatheringPointObject::GatheringPointObjectImpl: vtbls: - ea: 0x1418DA058 base: Client::Game::Object::GatheringPointObject::GatheringPointObjectImplBase Client::Game::Object::GatheringPointObject: vtbls: - ea: 0x1418DA0C0 base: Client::Game::Object::GameObject Client::Game::Object::AreaObject: vtbls: - ea: 0x1418DA330 base: Client::Game::Object::GameObject Client::Graphics::JobSystem<Client::Graphics::Culling::CullingManager,Client::Graphics::Culling::CullingJobOpt>: vtbls: - ea: 0x1418DB098 Client::Graphics::JobSystem<Client::Graphics::Culling::CullingManager,Client::Graphics::Culling::CallbackJobOpt>: vtbls: - ea: 0x1418DB0A0 Client::Graphics::JobSystem<Client::Graphics::Culling::CullingManager,Client::Graphics::Culling::RenderCallbackJob>: vtbls: - ea: 0x1418DB0A8 Client::Graphics::Culling::CullingManager: instances: - ea: 0x141E580F8 vtbls: - ea: 0x1418DB0B0 base: Client::Graphics::Singleton Client::Graphics::Kernel::CVector<Client::Graphics::Kernel::VertexShader*>: vtbls: - ea: 0x1418DB658 Client::Graphics::Kernel::CVector<Client::Graphics::Kernel::PixelShader*>: vtbls: - ea: 0x1418DB660 Client::Graphics::Kernel::CVector<Client::Graphics::Kernel::ShaderNode*>: vtbls: - ea: 0x1418DB668 Client::Graphics::Kernel::CBalanceSet<Client::Graphics::Kernel::ShaderPackage::SItem>: vtbls: - ea: 0x1418DB670 Client::Graphics::Kernel::ShaderPackage: vtbls: - ea: 0x1418DB678 base: Client::Graphics::ReferencedClassBase funcs: 0x141125A10: CreateShaderPackage # static function 0x1411261B0: ctor 0x141127590: VectorResize_PixelShader # these 3 functions are identical, just template-generated functions from std::vectors 0x141127680: VectorResize_ShaderNode 0x141127770: VectorResize_VertexShader Client::Game::Character::Companion: vtbls: - ea: 0x1418DE7F0 base: Client::Game::Character::Character funcs: 0x141141040: ctor Client::Game::Character::Ornament: vtbls: - ea: 0x1418DE4E0 base: Client::Game::Character::Character funcs: 0x141140C00: ctor Client::Game::Character::CutsceneCharacter: vtbls: - ea: 0x141978330 base: Client::Game::Character::Character funcs: 0x14133EED0: ctor Client::Game::CameraBase: vtbls: - ea: 0x1418DFF28 Client::Game::Camera: vtbls: - ea: 0x1418DFF90 base: Client::Game::CameraBase funcs: 0x1411824B0: UpdateRotation 0x141184FB0: ctor Client::Game::LowCutCamera: vtbls: - ea: 0x1418E0098 base: Client::Game::CameraBase funcs: 0x1411881C0: ctor Client::Game::Camera2: vtbls: - ea: 0x1418E0208 base: Client::Game::Camera funcs: 0x14118E1A0: ctor Client::Game::Camera3: vtbls: - ea: 0x1418E0100 base: Client::Game::Camera funcs: 0x14118BE90: ctor Client::Graphics::Culling::OcclusionCullingManager: instances: - ea: 0x141E6F420 vtbls: - ea: 0x1418E1AF0 base: Client::Graphics::Singleton funcs: 0x1411A16E0: ctor 0x1411A17C0: Initialize Client::Graphics::JobSystem<Client::Graphics::Streaming::StreamingManager>: vtbls: - ea: 0x1418E1B00 base: Client::Graphics::Singleton Client::Graphics::Streaming::StreamingManager: instances: - ea: 0x141E564B8 vtbls: - ea: 0x1418E1B08 base: Client::Graphics::Singleton Client::Graphics::JobSystem<Client::Graphics::Physics::BonePhysicsUpdater,Client::Graphics::Physics::BonePhysicsUpdater::CollisionObjectJob>: vtbls: - ea: 0x1418E1B28 Client::Graphics::JobSystem<Client::Graphics::Physics::BonePhysicsUpdater,Client::Graphics::Physics::BonePhysicsUpdater::BoneSimulatorJob>: vtbls: - ea: 0x1418E1B30 Client::Graphics::JobSystem<Client::Graphics::Physics::BonePhysicsUpdater,Client::Graphics::Physics::BonePhysicsUpdater::TransformUpdaterJob>: vtbls: - ea: 0x1418E1B38 Client::Graphics::Physics::BonePhysicsUpdater: instances: - ea: 0x141E6F470 vtbls: - ea: 0x1418E1B40 base: Client::Graphics::Singleton funcs: 0x1411A3FD0: ctor 0x1411A40F0: Initialize 0x1411A4470: Update Client::Graphics::Physics::BonePhysicsModule: vtbls: - ea: 0x1418E40E8 vfuncs: 0: dtor funcs: 0x1411B4120: ctor 0x1411B42A0: Initialize Client::System::Scheduler::Base::SchedulerState: vtbls: - ea: 0x1418E7EC0 Client::Graphics::Physics::BoneSimulator: vtbls: - ea: 0x1418E8978 funcs: 0x1411D4E20: ctor 0x1411D5290: Reset 0x1411D5310: Update 0x1411D5CC0: UpdateWithoutIntegration Client::Game::Object::Aetheryte: vtbls: - ea: 0x1418E92D0 base: Client::Game::Object::GameObject funcs: 0x1411F98B0: Create Component::Log::LogModuleInterface: vtbls: - ea: 0x1418E9C00 Component::Log::LogModule: vtbls: - ea: 0x1418E9C50 base: Component::Log::LogModuleInterface funcs: 0x141216910: ctor Client::Game::Object::HousingObject: vtbls: - ea: 0x14192DC30 base: Client::Game::Object::GameObject Client::Game::Gimmick::GimmickEventHandler: vtbls: - ea: 0x14193E0D0 base: Client::Game::Event::LuaEventHandler Client::Game::Gimmick::Gimmick_Unk1: vtbls: - ea: 0x14193E948 base: Client::Game::Gimmick::GimmickEventHandler Client::Game::Gimmick::GimmickRect: vtbls: - ea: 0x14193F1C0 base: Client::Game::Gimmick::GimmickEventHandler Client::Game::Object::HousingCombinedObject: vtbls: - ea: 0x141942EF0 base: Client::Game::Object::HousingObject Client::System::Scheduler::Clip::BaseClip: vtbls: - ea: 0x14194F2D0 base: Client::System::Scheduler::Base::SchedulerState Client::System::Scheduler::Clip::HavokAnimationClip: vtbls: - ea: 0x1419504E0 base: Client::System::Scheduler::Clip::BaseClip Client::System::Scheduler::Base::SceneConnectionBlock: vtbls: - ea: 0x14195B918 base: Client::System::Scheduler::Base::SchedulerState SQEX::CDev::Engine::Sd::Driver::IEffect: vtbls: - ea: 0x141A1C640 base: SQEX::CDev::Engine::Sd::SdMemoryAllocator SQEX::CDev::Engine::Sd::Driver::FilterBase: vtbls: - ea: 0x141A1C670 base: SQEX::CDev::Engine::Sd::Driver::IEffect SQEX::CDev::Engine::Sd::Driver::DynamicValue: vtbls: - ea: 0x141A1A538 base: SQEX::CDev::Engine::Sd::SdMemoryAllocator SQEX::CDev::Engine::Sd::Driver::ISound: vtbls: - ea: 0x141A1A570 SQEX::CDev::Engine::Sd::Driver::RootSound: vtbls: - ea: 0x141A1A930 base: SQEX::CDev::Engine::Sd::Driver::ISound SQEX::CDev::Engine::Sd::Driver::StreamSoundEx: vtbls: - ea: 0x141A1B4F0 base: SQEX::CDev::Engine::Sd::Driver::RootSound SQEX::CDev::Engine::Sd::Driver::AtomosgearSound: vtbls: - ea: 0x141A1B8D8 base: SQEX::CDev::Engine::Sd::Driver::RootSound SQEX::CDev::Engine::Sd::Driver::Surround4chSound: vtbls: - ea: 0x141A1C0A8 base: SQEX::CDev::Engine::Sd::Driver::RootSound SQEX::CDev::Engine::Sd::Driver::ISoundDriver: vtbls: - ea: 0x141A70980 base: SQEX::CDev::Engine::Sd::SdMemoryAllocator SQEX::CDev::Engine::Sd::Driver::SoundDriver: vtbls: - ea: 0x141A70BA0 base: SQEX::CDev::Engine::Sd::Driver::ISoundDriver SQEX::CDev::Engine::Sd::Driver::ToolBankController: vtbls: - ea: 0x141A70DC0 base: SQEX::CDev::Engine::Sd::Driver::BankController Client::System::Memory::IMemorySpace: instances: - ea: 0x141E55CB0 name: DefaultSpace - ea: 0x141E55CB8 name: ApricotSpace - ea: 0x141E55CC0 name: AnimationSpace - ea: 0x141E55CC8 name: UISpace - ea: 0x141E55CD0 name: FileSpace - ea: 0x141E55CD8 name: SoundSpace vtbls: - ea: 0x141702DA0 Client::System::Memory::IMemoryModule: vtbls: - ea: 0x141702EA8 Client::System::Memory::Regular::RegularAllocator: vtbls: - ea: 0x141702FF0 base: Client::System::Memory::IMemoryModule Client::System::Memory::Regular::UIAllocator: vtbls: - ea: 0x1417030D8 base: Client::System::Memory::Regular::RegularAllocator Client::System::Memory::Regular::FileAllocator: vtbls: - ea: 0x141703150 base: Client::System::Memory::Regular::RegularAllocator Client::System::Memory::Regular::SystemAllocator: vtbls: - ea: 0x141703068 base: Client::System::Memory::IMemoryModule Client::System::Memory::Regular::FixedSpace: vtbls: - ea: 0x1417031C8 base: Client::System::Memory::IMemorySpace Client::Game::ControlSystem::CameraManager: instances: - ea: 0x141E78880 funcs: 0x14118C940: ctor Vector3: funcs: 0x14019A760: Normalize
412
0.728495
1
0.728495
game-dev
MEDIA
0.457287
game-dev,graphics-rendering
0.716303
1
0.716303
gmlscripts/scripts
1,466
Game_Play/Collisions/range_finder.gml
#define range_finder /// range_finder(x,y,dir,range,object,prec,notme) // // Returns the exact distance to the nearest instance of an object in a // given direction from a given point, or noone if no instance is found. // The solution is found in log2(range) collision checks. // // x,y position in room, real // dir direction to look in degrees, real // range the greatest distance to look in pixels, real // object which objects to look for (or all), real // prec true to use precise collision checking, bool // notme true to ignore the calling instance, bool // /// GMLscripts.com/license { var ox,oy,dir,range,object,prec,notme,dx,dy,sx,sy,distance; ox = argument0; oy = argument1; dir = argument2; range = argument3; object = argument4; prec = argument5; notme = argument6; sx = lengthdir_x(range,dir); sy = lengthdir_y(range,dir); dx = ox + sx; dy = oy + sy; if (collision_line(ox,oy,dx,dy,object,prec,notme) < 0) { distance = -1; }else{ while ((abs(sx) >= 1) || (abs(sy) >= 1)) { sx /= 2; sy /= 2; if (collision_line(ox,oy,dx,dy,object,prec,notme) < 0) { dx += sx; dy += sy; }else{ dx -= sx; dy -= sy; } } distance = point_distance(ox,oy,dx,dy); } return distance; }
412
0.744816
1
0.744816
game-dev
MEDIA
0.810523
game-dev
0.838618
1
0.838618
hikalium/liumos
2,739
src/pmem.cc
#include "pmem.h" #include "liumos.h" void PersistentObjectHeader::Init(uint64_t id, uint64_t num_of_pages) { signature_ = ~kSignature; CLFlush(&signature_); id_ = id; num_of_pages_ = num_of_pages; next_ = nullptr; signature_ = kSignature; CLFlush(this); } void PersistentObjectHeader::SetNext(PersistentObjectHeader* next) { assert(IsValid()); next_ = next; CLFlush(&next_); } void PersistentObjectHeader::Print() { PutStringAndHex("Object #", id_); assert(IsValid()); PutStringAndHex(" base", GetObjectBase<void*>()); PutStringAndHex(" num_of_pages", num_of_pages_); } void PersistentMemoryManager::Init() { using namespace ACPI; assert(liumos->acpi.nfit); assert((reinterpret_cast<uint64_t>(this) & kPageAddrMask) == 0); NFIT& nfit = *liumos->acpi.nfit; for (auto& it : nfit) { if (it.type != NFIT::Entry::kTypeSPARangeStructure) continue; NFIT::SPARange* spa_range = reinterpret_cast<NFIT::SPARange*>(&it); if (!IsEqualGUID( reinterpret_cast<GUID*>(&spa_range->address_range_type_guid), &NFIT::SPARange::kByteAddressablePersistentMemory)) continue; if (spa_range->system_physical_address_range_base != reinterpret_cast<uint64_t>(this)) continue; signature_ = ~kSignature; PutStringAndHex("SPARange #", spa_range->spa_range_structure_index); PutStringAndHex(" Base", spa_range->system_physical_address_range_base); PutStringAndHex(" Length", spa_range->system_physical_address_range_length); page_idx_ = reinterpret_cast<uint64_t>(this) >> kPageSizeExponent; num_of_pages_ = spa_range->system_physical_address_range_length >> kPageSizeExponent; head_ = nullptr; last_persistent_process_info_ = nullptr; signature_ = kSignature; CLFlush(this, sizeof(*this)); sentinel_.Init(0, 0); SetHead(&sentinel_); return; } assert(false); } PersistentProcessInfo* PersistentMemoryManager::AllocPersistentProcessInfo() { PersistentProcessInfo* info = AllocPages<PersistentProcessInfo*>( ByteSizeToPageSize(sizeof(PersistentProcessInfo))); last_persistent_process_info_ = info; CLFlush(&last_persistent_process_info_); return last_persistent_process_info_; } void PersistentMemoryManager::Print() { PutStringAndHex("PMEM at", this); if (!IsValid()) { PutString(" INVALID. initialize will be required.\n"); return; } PutString(" signature valid.\n"); PutStringAndHex(" Size in byte", num_of_pages_ << kPageSizeExponent); for (PersistentObjectHeader* h = head_; h; h = h->GetNext()) { h->Print(); } } void PersistentMemoryManager::SetHead(PersistentObjectHeader* head) { head_ = head; CLFlush(&head_); }
412
0.971071
1
0.971071
game-dev
MEDIA
0.263748
game-dev
0.902431
1
0.902431
ChengF3ng233/Aluminium
2,114
src/main/java/net/minecraft/client/gui/GuiHopper.java
package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ContainerHopper; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; public class GuiHopper extends GuiContainer { /** * The ResourceLocation containing the gui texture for the hopper */ private static final ResourceLocation HOPPER_GUI_TEXTURE = new ResourceLocation("textures/gui/container/hopper.png"); /** * The player inventory currently bound to this GUI instance */ private final IInventory playerInventory; /** * The hopper inventory bound to this GUI instance */ private final IInventory hopperInventory; public GuiHopper(InventoryPlayer playerInv, IInventory hopperInv) { super(new ContainerHopper(playerInv, hopperInv, Minecraft.getMinecraft().thePlayer)); this.playerInventory = playerInv; this.hopperInventory = hopperInv; this.allowUserInput = false; this.ySize = 133; } /** * Draw the foreground layer for the GuiContainer (everything in front of the items). Args : mouseX, mouseY */ protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { this.fontRendererObj.drawString(this.hopperInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, this.ySize - 96 + 2, 4210752); } /** * Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.mc.getTextureManager().bindTexture(HOPPER_GUI_TEXTURE); int i = (this.width - this.xSize) / 2; int j = (this.height - this.ySize) / 2; this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); } }
412
0.690631
1
0.690631
game-dev
MEDIA
0.885886
game-dev
0.779324
1
0.779324
jMonkeyEngine/jmonkeyengine
4,213
jme3-plugins/src/fbx/java/com/jme3/scene/plugins/fbx/file/FbxId.java
/* * Copyright (c) 2009-2015 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.scene.plugins.fbx.file; public abstract class FbxId { public static final FbxId ROOT = new LongFbxId(0); protected FbxId() { } private static final class StringFbxId extends FbxId { private final String id; public StringFbxId(String id) { this.id = id; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != StringFbxId.class) { return false; } return this.id.equals(((StringFbxId) obj).id); } @Override public String toString() { return id; } @Override public boolean isNull() { return id.equals("Scene\u0000\u0001Model"); } } private static final class LongFbxId extends FbxId { private final long id; public LongFbxId(long id) { this.id = id; } @Override public int hashCode() { return (int) (this.id ^ (this.id >>> 32)); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != LongFbxId.class) { return false; } return this.id == ((LongFbxId) obj).id; } @Override public boolean isNull() { return id == 0; } @Override public String toString() { return Long.toString(id); } } public abstract boolean isNull(); public static FbxId create(Object obj) { if (obj instanceof Long) { return new LongFbxId((Long)obj); } else if (obj instanceof String) { return new StringFbxId((String)obj); } else { throw new UnsupportedOperationException("Unsupported ID object type: " + obj.getClass()); } } public static FbxId getObjectId(FbxElement el) { if (el.propertiesTypes.length == 2 && el.propertiesTypes[0] == 'S' && el.propertiesTypes[1] == 'S') { return new StringFbxId((String) el.properties.get(0)); } else if (el.propertiesTypes.length == 3 && el.propertiesTypes[0] == 'L' && el.propertiesTypes[1] == 'S' && el.propertiesTypes[2] == 'S') { return new LongFbxId((Long) el.properties.get(0)); } else { return null; } } }
412
0.810929
1
0.810929
game-dev
MEDIA
0.314052
game-dev
0.936156
1
0.936156
corretto/corretto-17
3,489
src/hotspot/share/ci/ciArrayKlass.cpp
/* * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "ci/ciArrayKlass.hpp" #include "ci/ciObjArrayKlass.hpp" #include "ci/ciTypeArrayKlass.hpp" #include "ci/ciUtilities.hpp" // ciArrayKlass // // This class represents a Klass* in the HotSpot virtual machine // whose Klass part in an ArrayKlass. // ------------------------------------------------------------------ // ciArrayKlass::ciArrayKlass // // Loaded array klass. ciArrayKlass::ciArrayKlass(Klass* k) : ciKlass(k) { assert(get_Klass()->is_array_klass(), "wrong type"); _dimension = get_ArrayKlass()->dimension(); } // ------------------------------------------------------------------ // ciArrayKlass::ciArrayKlass // // Unloaded array klass. ciArrayKlass::ciArrayKlass(ciSymbol* name, int dimension, BasicType bt) : ciKlass(name, bt) { _dimension = dimension; } // ------------------------------------------------------------------ // ciArrayKlass::element_type // // What type is obtained when this array is indexed once? ciType* ciArrayKlass::element_type() { if (is_type_array_klass()) { return ciType::make(as_type_array_klass()->element_type()); } else { return as_obj_array_klass()->element_klass()->as_klass(); } } // ------------------------------------------------------------------ // ciArrayKlass::base_element_type // // What type is obtained when this array is indexed as many times as possible? ciType* ciArrayKlass::base_element_type() { if (is_type_array_klass()) { return ciType::make(as_type_array_klass()->element_type()); } else { ciKlass* ek = as_obj_array_klass()->base_element_klass(); if (ek->is_type_array_klass()) { return ciType::make(ek->as_type_array_klass()->element_type()); } return ek; } } // ------------------------------------------------------------------ // ciArrayKlass::is_leaf_type bool ciArrayKlass::is_leaf_type() { if (is_type_array_klass()) { return true; } else { return as_obj_array_klass()->base_element_klass()->is_leaf_type(); } } // ------------------------------------------------------------------ // ciArrayKlass::base_element_type // // What type is obtained when this array is indexed as many times as possible? ciArrayKlass* ciArrayKlass::make(ciType* element_type) { if (element_type->is_primitive_type()) { return ciTypeArrayKlass::make(element_type->basic_type()); } else { return ciObjArrayKlass::make(element_type->as_klass()); } }
412
0.954171
1
0.954171
game-dev
MEDIA
0.279053
game-dev
0.963492
1
0.963492
Russian-Doom/russian-doom
2,667
src/heretic/deh_ammo.c
// // Copyright(C) 2005-2014 Simon Howard // Copyright(C) 2016-2023 Julian Nechaevsky // Copyright(C) 2020-2025 Leonid Murin (Dasperal) // // 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. // // // Parses "Ammo" sections in dehacked files // #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hr_local.h" #include "doomtype.h" #include "deh_defs.h" #include "deh_io.h" #include "deh_main.h" #include "p_local.h" static void *DEH_AmmoStart(deh_context_t *context, char *line) { int ammo_number = 0; if (sscanf(line, "Ammo %i", &ammo_number) != 1) { DEH_Warning(context, "Parse error on section start"); return NULL; } if (ammo_number < 0 || ammo_number >= NUMAMMO) { DEH_Warning(context, "Invalid ammo number: %i", ammo_number); return NULL; } return &maxammo[ammo_number]; } static void DEH_AmmoParseLine(deh_context_t *context, char *line, void *tag) { char *variable_name, *value; int ivalue; int ammo_number; if (tag == NULL) return; ammo_number = ((int *) tag) - maxammo; // Parse the assignment if (!DEH_ParseAssignment(line, &variable_name, &value)) { // Failed to parse DEH_Warning(context, "Failed to parse assignment"); return; } ivalue = atoi(value); if (!strcasecmp(variable_name, "Per ammo")) { // Heretic doesn't have a "per clip" ammo array, instead // it is per weapon. However, the weapon number lines // up with the ammo number if we add one. GetWeaponAmmo[ammo_number + 1] = ivalue; } else if (!strcasecmp(variable_name, "Max ammo")) { maxammo[ammo_number] = ivalue; } else { DEH_Warning(context, "Field named '%s' not found", variable_name); } } static void DEH_AmmoSHA1Hash(sha1_context_t *context) { int i; for (i=0; i<NUMAMMO; ++i) { SHA1_UpdateInt32(context, maxammo[i]); } for (i=0; i<NUMWEAPONS; ++i) { SHA1_UpdateInt32(context, GetWeaponAmmo[i]); } } deh_section_t deh_section_ammo = { "Ammo", NULL, DEH_AmmoStart, DEH_AmmoParseLine, NULL, DEH_AmmoSHA1Hash, };
412
0.765762
1
0.765762
game-dev
MEDIA
0.769994
game-dev
0.557823
1
0.557823
KaiijuMC/Kaiiju
2,674
patches/server/0035-Option-to-disable-dolphin-swim-to-treasure.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Xymb <xymb@endcrystal.me> Date: Thu, 22 Jun 2023 00:52:00 +0200 Subject: [PATCH] Option to disable dolphin swim to treasure diff --git a/src/main/java/dev/kaiijumc/kaiiju/KaiijuWorldConfig.java b/src/main/java/dev/kaiijumc/kaiiju/KaiijuWorldConfig.java index c9830912019079369268bfbf2c95de18ad598f52..e2fb7d7a7b3126d386b46442c115085d1974ac4e 100644 --- a/src/main/java/dev/kaiijumc/kaiiju/KaiijuWorldConfig.java +++ b/src/main/java/dev/kaiijumc/kaiiju/KaiijuWorldConfig.java @@ -152,6 +152,7 @@ public class KaiijuWorldConfig { public boolean enableEntityThrottling = false; public boolean disableAchievements = false; public boolean disableCreaturesSpawnEvents = false; + public boolean disableDolphinSwimToTreasure = false; private void optimizationSettings() { shulkerBoxDropContentsWhenDestroyed = getBoolean("optimization.shulker-box-drop-contents-when-destroyed", shulkerBoxDropContentsWhenDestroyed); @@ -160,6 +161,7 @@ public class KaiijuWorldConfig { enableEntityThrottling = getBoolean("optimization.enable-entity-throttling", enableEntityThrottling); disableAchievements = getBoolean("optimization.disable-achievements", disableAchievements); disableCreaturesSpawnEvents = getBoolean("optimization.disable-creatures-spawn-events", disableCreaturesSpawnEvents); + disableDolphinSwimToTreasure = getBoolean("optimization.disable-dolphin-swim-to-treasure", disableDolphinSwimToTreasure); } public boolean fixVoidTrading = true; diff --git a/src/main/java/net/minecraft/world/entity/animal/Dolphin.java b/src/main/java/net/minecraft/world/entity/animal/Dolphin.java index 8448c5d778998390cf2b683f36e4e18ca7ffdc34..8438ae5194bba7cad22af5e350c5a288529cbcdb 100644 --- a/src/main/java/net/minecraft/world/entity/animal/Dolphin.java +++ b/src/main/java/net/minecraft/world/entity/animal/Dolphin.java @@ -164,7 +164,7 @@ public class Dolphin extends WaterAnimal { protected void registerGoals() { this.goalSelector.addGoal(0, new BreathAirGoal(this)); this.goalSelector.addGoal(0, new TryFindWaterGoal(this)); - this.goalSelector.addGoal(1, new Dolphin.DolphinSwimToTreasureGoal(this)); + if (!this.level().kaiijuConfig.disableDolphinSwimToTreasure) this.goalSelector.addGoal(1, new Dolphin.DolphinSwimToTreasureGoal(this)); // Kaiiju this.goalSelector.addGoal(2, new Dolphin.DolphinSwimWithPlayerGoal(this, 4.0D)); this.goalSelector.addGoal(4, new RandomSwimmingGoal(this, 1.0D, 10)); this.goalSelector.addGoal(4, new RandomLookAroundGoal(this));
412
0.686047
1
0.686047
game-dev
MEDIA
0.958842
game-dev
0.592236
1
0.592236
lostmyself8/Mekanism-Extras
3,707
src/main/java/com/jerry/mekanism_extras/client/gui/machine/GuiAdvancedElectricPump.java
package com.jerry.mekanism_extras.client.gui.machine; import com.jerry.mekanism_extras.common.tile.machine.TileEntityAdvancedElectricPump; import mekanism.client.gui.GuiMekanismTile; import mekanism.client.gui.element.GuiDownArrow; import mekanism.client.gui.element.GuiInnerScreen; import mekanism.client.gui.element.bar.GuiVerticalPowerBar; import mekanism.client.gui.element.gauge.GaugeType; import mekanism.client.gui.element.gauge.GuiFluidGauge; import mekanism.client.gui.element.tab.GuiEnergyTab; import mekanism.common.MekanismLang; import mekanism.common.capabilities.energy.MachineEnergyContainer; import mekanism.common.inventory.container.tile.MekanismTileContainer; import mekanism.common.inventory.warning.WarningTracker; import mekanism.common.util.text.EnergyDisplay; import mekanism.common.util.text.TextUtils; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; import net.minecraftforge.fluids.FluidStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class GuiAdvancedElectricPump extends GuiMekanismTile<TileEntityAdvancedElectricPump, MekanismTileContainer<TileEntityAdvancedElectricPump>> { public GuiAdvancedElectricPump(MekanismTileContainer<TileEntityAdvancedElectricPump> container, Inventory inv, Component title) { super(container, inv, title); inventoryLabelY += 2; dynamicSlots = true; } @Override protected void addGuiElements() { super.addGuiElements(); addRenderableWidget(new GuiInnerScreen(this, 54, 23, 80, 41, () -> { List<Component> list = new ArrayList<>(); list.add(EnergyDisplay.of(tile.getEnergyContainer()).getTextComponent()); FluidStack fluidStack = tile.fluidTank.getFluid(); if (fluidStack.isEmpty()) { FluidStack fallBack = tile.getActiveType(); if (fallBack.isEmpty()) { list.add(MekanismLang.NO_FLUID.translate()); } else { list.add(fallBack.getDisplayName()); } } else { list.add(MekanismLang.GENERIC_STORED_MB.translate(fluidStack, TextUtils.format(fluidStack.getAmount()))); } return list; })); addRenderableWidget(new GuiDownArrow(this, 32, 39)); addRenderableWidget(new GuiVerticalPowerBar(this, tile.getEnergyContainer(), 164, 15)) .warning(WarningTracker.WarningType.NOT_ENOUGH_ENERGY, () -> { MachineEnergyContainer<TileEntityAdvancedElectricPump> energyContainer = tile.getEnergyContainer(); return energyContainer.getEnergyPerTick().greaterThan(energyContainer.getEnergy()); }); addRenderableWidget(new GuiFluidGauge(() -> tile.fluidTank, () -> tile.getFluidTanks(null), GaugeType.STANDARD, this, 6, 13)) .warning(WarningTracker.WarningType.NO_SPACE_IN_OUTPUT, () -> tile.fluidTank.getNeeded() < tile.estimateIncrementAmount()); //TODO: Eventually we may want to consider showing a warning if the block under the pump is of the wrong type or there wasn't a valid spot to suck addRenderableWidget(new GuiEnergyTab(this, tile.getEnergyContainer(), tile::usedEnergy)); } @Override protected void drawForegroundText(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY) { renderTitleText(guiGraphics); drawString(guiGraphics, playerInventoryTitle, inventoryLabelX, inventoryLabelY, titleTextColor()); super.drawForegroundText(guiGraphics, mouseX, mouseY); } }
412
0.898503
1
0.898503
game-dev
MEDIA
0.930875
game-dev
0.954666
1
0.954666
dsa28s/android-studio-apple-m1
5,269
src/hotspot/share/services/management.hpp
/* * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_SERVICES_MANAGEMENT_HPP #define SHARE_VM_SERVICES_MANAGEMENT_HPP #include "jmm.h" #include "memory/allocation.hpp" #include "runtime/handles.hpp" #include "runtime/timer.hpp" class OopClosure; class ThreadSnapshot; class Management : public AllStatic { private: static PerfVariable* _begin_vm_creation_time; static PerfVariable* _end_vm_creation_time; static PerfVariable* _vm_init_done_time; static jmmOptionalSupport _optional_support; static TimeStamp _stamp; // Timestamp since vm init done time // Management klasses static InstanceKlass* _diagnosticCommandImpl_klass; static InstanceKlass* _garbageCollectorExtImpl_klass; static InstanceKlass* _garbageCollectorMXBean_klass; static InstanceKlass* _gcInfo_klass; static InstanceKlass* _managementFactoryHelper_klass; static InstanceKlass* _memoryManagerMXBean_klass; static InstanceKlass* _memoryPoolMXBean_klass; static InstanceKlass* _memoryUsage_klass; static InstanceKlass* _sensor_klass; static InstanceKlass* _threadInfo_klass; static InstanceKlass* load_and_initialize_klass(Symbol* sh, TRAPS); static InstanceKlass* load_and_initialize_klass_or_null(Symbol* sh, TRAPS); static InstanceKlass* initialize_klass(Klass* k, TRAPS); public: static void init(); static void initialize(TRAPS); static jlong ticks_to_ms(jlong ticks) NOT_MANAGEMENT_RETURN_(0L); static jlong timestamp() NOT_MANAGEMENT_RETURN_(0L); static void oops_do(OopClosure* f) NOT_MANAGEMENT_RETURN; static void* get_jmm_interface(int version); static void get_optional_support(jmmOptionalSupport* support); static void get_loaded_classes(JavaThread* cur_thread, GrowableArray<Klass*>* klass_array); static void record_vm_startup_time(jlong begin, jlong duration) NOT_MANAGEMENT_RETURN; static void record_vm_init_completed() { // Initialize the timestamp to get the current time _vm_init_done_time->set_value(os::javaTimeMillis()); // Update the timestamp to the vm init done time _stamp.update(); } static jlong begin_vm_creation_time() { return _begin_vm_creation_time->get_value(); } static jlong vm_init_done_time() { return _vm_init_done_time->get_value(); } // methods to return a Klass*. static InstanceKlass* java_lang_management_ThreadInfo_klass(TRAPS); static InstanceKlass* java_lang_management_MemoryUsage_klass(TRAPS) NOT_MANAGEMENT_RETURN_(NULL); static InstanceKlass* java_lang_management_MemoryPoolMXBean_klass(TRAPS); static InstanceKlass* java_lang_management_MemoryManagerMXBean_klass(TRAPS); static InstanceKlass* java_lang_management_GarbageCollectorMXBean_klass(TRAPS); static InstanceKlass* sun_management_ManagementFactoryHelper_klass(TRAPS) NOT_MANAGEMENT_RETURN_(NULL); static InstanceKlass* sun_management_Sensor_klass(TRAPS) NOT_MANAGEMENT_RETURN_(NULL); static InstanceKlass* com_sun_management_internal_GarbageCollectorExtImpl_klass(TRAPS) NOT_MANAGEMENT_RETURN_(NULL); static InstanceKlass* com_sun_management_GcInfo_klass(TRAPS) NOT_MANAGEMENT_RETURN_(NULL); static InstanceKlass* com_sun_management_internal_DiagnosticCommandImpl_klass(TRAPS) NOT_MANAGEMENT_RETURN_(NULL); static instanceOop create_thread_info_instance(ThreadSnapshot* snapshot, TRAPS); static instanceOop create_thread_info_instance(ThreadSnapshot* snapshot, objArrayHandle monitors_array, typeArrayHandle depths_array, objArrayHandle synchronizers_array, TRAPS); }; class TraceVmCreationTime : public StackObj { private: TimeStamp _timer; jlong _begin_time; public: TraceVmCreationTime() {} ~TraceVmCreationTime() {} void start() { _timer.update_to(0); _begin_time = os::javaTimeMillis(); } jlong begin_time() const { return _begin_time; } /** * Only call this if initialization completes successfully; it will * crash if PerfMemory_exit() has already been called (usually by * os::shutdown() when there was an initialization failure). */ void end() { Management::record_vm_startup_time(_begin_time, _timer.milliseconds()); } }; #endif // SHARE_VM_SERVICES_MANAGEMENT_HPP
412
0.689648
1
0.689648
game-dev
MEDIA
0.57681
game-dev
0.864371
1
0.864371
deephaven/deephaven-core
3,268
engine/table/src/main/java/io/deephaven/engine/table/impl/updateby/fill/BooleanFillByOperator.java
// // Copyright (c) 2016-2025 Deephaven Data Labs and Patent Pending // // ****** AUTO-GENERATED CLASS - DO NOT EDIT MANUALLY // ****** Edit CharFillByOperator and run "./gradlew replicateUpdateBy" to regenerate // // @formatter:off package io.deephaven.engine.table.impl.updateby.fill; import io.deephaven.engine.table.ColumnSource; import java.util.Map; import java.util.Collections; import io.deephaven.engine.table.impl.sources.BooleanArraySource; import io.deephaven.engine.table.impl.sources.BooleanSparseArraySource; import io.deephaven.engine.table.WritableColumnSource; import io.deephaven.util.BooleanUtils; import io.deephaven.base.verify.Assert; import io.deephaven.chunk.ByteChunk; import io.deephaven.chunk.Chunk; import io.deephaven.chunk.attributes.Values; import io.deephaven.engine.table.impl.MatchPair; import io.deephaven.engine.table.impl.updateby.UpdateByOperator; import io.deephaven.engine.table.impl.updateby.internal.BaseByteUpdateByOperator; import org.jetbrains.annotations.NotNull; public class BooleanFillByOperator extends BaseByteUpdateByOperator { // region extra-fields // endregion extra-fields protected class Context extends BaseByteUpdateByOperator.Context { public ByteChunk<? extends Values> booleanValueChunk; protected Context(final int chunkSize) { super(chunkSize); } @Override public void setValueChunks(@NotNull final Chunk<? extends Values>[] valueChunks) { booleanValueChunk = valueChunks[0].asByteChunk(); } @Override public void push(int pos, int count) { Assert.eq(count, "push count", 1); byte val = booleanValueChunk.get(pos); if(!BooleanUtils.isNull(val)) { curVal = val; } } } public BooleanFillByOperator( @NotNull final MatchPair pair // region extra-constructor-args // endregion extra-constructor-args ) { super(pair, new String[] { pair.rightColumn }); // region constructor // endregion constructor } @Override public UpdateByOperator copy() { return new BooleanFillByOperator( pair // region extra-copy-args // endregion extra-copy-args ); } @NotNull @Override public UpdateByOperator.Context makeUpdateContext(final int affectedChunkSize, final int influencerChunkSize) { return new Context(affectedChunkSize); } // region extra-methods @Override protected byte getNullValue() { return BooleanUtils.NULL_BOOLEAN_AS_BYTE; } @Override protected WritableColumnSource<Byte> makeSparseSource() { return (WritableColumnSource<Byte>) new BooleanSparseArraySource().reinterpret(byte.class); } @Override protected WritableColumnSource<Byte> makeDenseSource() { return (WritableColumnSource<Byte>) new BooleanArraySource().reinterpret(byte.class); } @NotNull @Override public Map<String, ColumnSource<?>> getOutputColumns() { return Collections.singletonMap(pair.leftColumn, outputSource.reinterpret(Boolean.class)); } // endregion extra-methods }
412
0.869977
1
0.869977
game-dev
MEDIA
0.466738
game-dev
0.904887
1
0.904887
Baystation12/Baystation12
10,100
code/datums/uplink/devices and tools.dm
/******************** * Devices and Tools * ********************/ /datum/uplink_item/item/tools category = /datum/uplink_category/tools /datum/uplink_item/item/tools/personal_shield name = "Personal Shield" desc = "A very expensive device that uses energy to block bullets and lasers from tearing you a new hole." item_cost = 40 path = /obj/item/device/personal_shield /datum/uplink_item/item/tools/eshield name = "Energy Shield" desc = "An extendable hardlight shield projector." item_cost = 24 path = /obj/item/shield/energy /datum/uplink_item/item/tools/toolbox name = "Fully Loaded Toolbox" desc = "A hefty toolbox filled with all the equipment you need to get past any construction or electrical issues. \ Instructions and materials not included." item_cost = 8 path = /obj/item/storage/toolbox/syndicate /datum/uplink_item/item/tools/ductape name = "Duct Tape" desc = "A roll of duct tape." item_cost = 2 path = /obj/item/tape_roll /datum/uplink_item/item/tools/money name = "Operations Funding" item_cost = 8 path = /obj/item/storage/secure/briefcase/money /datum/uplink_item/item/tools/money/New() . = ..() desc = "A briefcase with 10,000 untraceable [GLOB.using_map.local_currency_name]. Makes a great bribe if they're willing to take you up on your offer." /datum/uplink_item/item/tools/clerical name = "Morphic Clerical Kit" desc = "Comes with everything you need to fake paperwork, assuming you know how to forge the required documents." item_cost = 16 path = /obj/item/storage/backpack/satchel/syndie_kit/clerical /datum/uplink_item/item/tools/plastique name = "C-4" desc = "Set this on a wall to put a hole exactly where you need it." item_cost = 16 path = /obj/item/plastique /datum/uplink_item/item/tools/heavy_armor name = "Heavy Armor Vest and Helmet" desc = "This satchel holds a combat helmet and fully equipped plate carrier. \ Suit up, and strap in, things are about to get hectic." item_cost = 16 path = /obj/item/storage/backpack/satchel/syndie_kit/armor /datum/uplink_item/item/tools/encryptionkey_radio name = "Encrypted Radio Channel Key" desc = "This headset encryption key will allow you to speak on a hidden, encrypted radio channel. Use a screwdriver on your headset to exchange keys." item_cost = 1 path = /obj/item/device/encryptionkey/syndicate /datum/uplink_item/item/tools/shield_diffuser name = "Handheld Shield Diffuser" desc = "A small device used to disrupt energy barriers, and allow passage through them." item_cost = 16 path = /obj/item/shield_diffuser /datum/uplink_item/item/tools/suit_sensor_mobile name = "Suit Sensor Jamming Device" desc = "This tiny device can temporarily change sensor levels, report random readings, or false readings on any \ suit sensors in your vicinity. The range at which this device operates can be toggled as well. All of these \ options drain the internal battery." item_cost = 20 path = /obj/item/device/suit_sensor_jammer /datum/uplink_item/item/tools/encryptionkey_binary name = "Binary Translator Key" desc = "This headset encryption key will allow you to both listen and speak on the binary channel that \ synthetics and AI have access to. Remember, non-synths don't normally have access to this channel, so talking in it will raise suspicion. \ Use a screwdriver on your headset to exchange keys." item_cost = 20 path = /obj/item/device/encryptionkey/binary /datum/uplink_item/item/tools/emag name = "Cryptographic Sequencer" desc = "An electromagnetic card capable of scrambling electronics to either subvert them into serving you, \ or giving you access to things you normally can't. Doors can be opened with this card \ even if you aren't normally able to, but will destroy them in the proccess. This card can have its appearance changed \ to look less conspicuous." item_cost = 24 path = /obj/item/card/emag /datum/uplink_item/item/tools/hacking_tool name = "Door Hacking Tool" item_cost = 24 path = /obj/item/device/multitool/hacktool desc = "Appears and functions as a standard multitool until a screwdriver is used to toggle it. \ While in hacking mode, this device will grant full access to any airlock in 20 to 40 seconds. \ This device will be able to continuously reaccess the last 6 to 8 airlocks it was used on." /datum/uplink_item/item/tools/radio_jammer name = "Portable Radio Jammer" item_cost = 24 path = /obj/item/device/radio_jammer desc = "A pocket sized portable radio jammer that can intercept outgoing radio signals in a given distance. \ However, radios attempting to send outgoing transmissions will emit a faint buzzing noise. \ The jammer can be signaled remotely using assembly signalers." /datum/uplink_item/item/tools/space_suit name = "Voidsuit and Tactical Mask" desc = "A satchel containing a non-regulation voidsuit, voidsuit helmet, tactical mask, and oxygen tank. \ Conceal your identity, while also not dying in space." item_cost = 28 path = /obj/item/storage/backpack/satchel/syndie_kit/space /datum/uplink_item/item/tools/divinghelmet name = "Diving Helmet" desc = "An antique diver's helmet that was designed to withstand immense pressures. Works as a space helmet. Only fits humans." item_cost = 12 path = /obj/item/clothing/head/helmet/divinghelmet /datum/uplink_item/item/tools/thermal name = "Thermal Imaging Glasses (Goggles)" desc = "A pair of meson goggles that have been modified to instead show synthetics or living creatures, through thermal imaging." item_cost = 24 path = /obj/item/clothing/glasses/thermal/syndi antag_roles = list(MODE_TRAITOR) /datum/uplink_item/item/tools/thermal_avi name = "Thermal Imaging Glasses (Aviators)" desc = "A pair of aviator sunglasses that have been modified to instead show synthetics or living creatures, through thermal imaging." item_cost = 24 path = /obj/item/clothing/glasses/thermal/syndi/aviators antag_roles = list(MODE_TRAITOR) /datum/uplink_item/item/tools/thermal_goggles name = "Helmet-Attached Thermal Sights" desc = "A set of thermal sights that can attach to combat or voidsuit helmets. Range is limited, along with the color palette, and it will be obvious what you are wearing." item_cost = 12 path = /obj/item/clothing/head/helmet/nvgmount/thermal antag_roles = list(MODE_TRAITOR) /datum/uplink_item/item/tools/night_goggles name = "Helmet-Attached Light-Enhancing Sights" desc = "A set of light-enhancing sights for seeing in the dark. They can attach to combat or voidsuit helmets. Range is slightly limited, along with your perceptible range of colors. It will be obvious what you are wearing." item_cost = 12 path = /obj/item/clothing/head/helmet/nvgmount/nvg antag_roles = list(MODE_MERCENARY, MODE_TRAITOR) //don't give mercs extra thermals but NVGs are okay /datum/uplink_item/item/tools/flashdark name = "Flashdark" desc = "A device similar to a flash light that absorbs the surrounding light, casting a shadowy, black mass." item_cost = 32 path = /obj/item/device/flashlight/flashdark /datum/uplink_item/item/tools/powersink name = "Powersink (DANGER!)" desc = "A device, that when bolted down to an exposed wire, spikes the surrounding electrical systems, \ draining power at an alarming rate. Use with caution, as this will be extremely noticable to anyone \ monitoring the power systems." item_cost = 40 path = /obj/item/device/powersink /datum/uplink_item/item/tools/ai_module name = "Hacked AI Upload Module" desc = "A module that can be used anonymously add a singular, top level law to an active AI. \ All you need to do is write in the law and insert it into any available AI Upload Console." item_cost = 52 path = /obj/item/aiModule/syndicate /datum/uplink_item/item/tools/supply_beacon name = "Hacked Supply Beacon (DANGER!)" desc = "Wrench this large beacon onto an exposed power cable, in order to activate it. This will call in a \ drop pod to the target location, containing a random assortment of (possibly useful) items. \ The ship's computer system will announce when this pod is enroute." item_cost = 52 path = /obj/item/supply_beacon /datum/uplink_item/item/tools/camera_mask name = "Camera MIU" desc = "Wearing this mask allows you to remotely view any cameras you currently have access to. Take the mask off to stop viewing." item_cost = 60 antag_costs = list(MODE_MERCENARY = 30) path = /obj/item/clothing/mask/ai /datum/uplink_item/item/tools/interceptor name = "Radio Interceptor" item_cost = 30 path = /obj/item/device/radio/intercept desc = "A receiver-like device that can intercept secure radio channels. This item is too big to fit into your pockets." /datum/uplink_item/item/tools/ttv name = "Binary Gas Bomb" item_cost = 30 path = /obj/spawner/newbomb/traitor desc = "A remote-activated phoron-oxygen bomb assembly with an included signaler. \ A flashing disclaimer begins with the warning 'SOME DISASSEMBLY/REASSEMBLY REQUIRED.'" /datum/uplink_item/item/tools/polychromic_dye_bottle name = "Extra-Strength Polychromic Dye" item_cost = 10 path = /obj/item/reagent_containers/glass/bottle/dye/polychromic/strong desc = "15 units of a tasteless dye that causes chemical mixtures to take on the color of the dye itself. \ Very useful for disguising poisons to the untrained eye; even large amounts of reagents can be fully recolored with only a few drops of dye. \ Like the mundane variety of polychromic dye, you can use the bottle in your hand to change the dye's color to suit your needs." /datum/uplink_item/item/tools/handcuffs name = "Handcuffs" item_cost = 5 path = /obj/item/storage/box/handcuffs desc = "A box of 7 handcuffs." /datum/uplink_item/item/tools/vendorcoins name = "Syndicate Coins" item_cost = 50 path = /obj/item/storage/fancy/smokable/case/syndiecoins desc = "A packet of five coins that unlock a secret compartment in any vending machine. \ Each coin unlocks on average 15 TCs worth of items. Depending on your luck, you may half or more than triple your TCs worth! \ These compartments cannot be accessed by hacking."
412
0.917177
1
0.917177
game-dev
MEDIA
0.987497
game-dev
0.744784
1
0.744784
mmogdeveloper/MO.Framework
2,646
MO.Client/MO.Unity3d.Online/Assets/GameFramework/Scripts/Runtime/Utility/Helper.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2020 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using GameFramework; using UnityEngine; namespace UnityGameFramework.Runtime { /// <summary> /// 辅助器创建器相关的实用函数。 /// </summary> public static class Helper { /// <summary> /// 创建辅助器。 /// </summary> /// <typeparam name="T">要创建的辅助器类型。</typeparam> /// <param name="helperTypeName">要创建的辅助器类型名称。</param> /// <param name="customHelper">若要创建的辅助器类型为空时,使用的自定义辅助器类型。</param> /// <returns>创建的辅助器。</returns> public static T CreateHelper<T>(string helperTypeName, T customHelper) where T : MonoBehaviour { return CreateHelper(helperTypeName, customHelper, 0); } /// <summary> /// 创建辅助器。 /// </summary> /// <typeparam name="T">要创建的辅助器类型。</typeparam> /// <param name="helperTypeName">要创建的辅助器类型名称。</param> /// <param name="customHelper">若要创建的辅助器类型为空时,使用的自定义辅助器类型。</param> /// <param name="index">要创建的辅助器索引。</param> /// <returns>创建的辅助器。</returns> public static T CreateHelper<T>(string helperTypeName, T customHelper, int index) where T : MonoBehaviour { T helper = null; if (!string.IsNullOrEmpty(helperTypeName)) { System.Type helperType = Utility.Assembly.GetType(helperTypeName); if (helperType == null) { Log.Warning("Can not find helper type '{0}'.", helperTypeName); return null; } if (!typeof(T).IsAssignableFrom(helperType)) { Log.Warning("Type '{0}' is not assignable from '{1}'.", typeof(T).FullName, helperType.FullName); return null; } helper = (T)new GameObject().AddComponent(helperType); } else if (customHelper == null) { Log.Warning("You must set custom helper with '{0}' type first.", typeof(T).FullName); return null; } else if (customHelper.gameObject.InScene()) { helper = index > 0 ? Object.Instantiate(customHelper) : customHelper; } else { helper = Object.Instantiate(customHelper); } return helper; } } }
412
0.779374
1
0.779374
game-dev
MEDIA
0.191783
game-dev
0.675545
1
0.675545
DefinitelyTyped/DefinitelyTyped
2,122
types/tictactoejs/index.d.ts
export class TicTacToe { /** * The game's constructor */ constructor(requestSize?: number); /** * Restart the game */ reset(requestSize?: number): void; /** * Get the current game's size * @returns the game size */ getSize(): number; /** * Check, whether it's X' turn or O's * @returns whose turn it is */ turn(): "X" | "O"; /** * Get the current board * @returns the current board as ascii */ ascii(): string; /** * Get the current board * @returns the current board as ascii (alternative style) */ ascii2(): string; /** * Does a move (bottom left is 1|1, bottom right is 3|1) * @returns whether the move was successful */ move(x: number, y: number): boolean; /** * Check whether the provided coordinates exist on the current board * @returns whether the current coordinates exist */ exists(x: number, y: number): boolean; /** * Check which player occupies the provided coordinates * @returns the player occupying these coordinates */ get(x: number, y: number): "X" | "O" | null; /** * Do a move with array style coordinates (top left is 0|0, top right is 0|2) * @returns whether the move was successful */ moveArray(row: number, col: number): boolean; /** * Check the game's current state * @returns the game state */ status(): "X" | "O" | "draw" | "in progress"; /** * Check whether the game is over * @returns the game state */ gameOver(): boolean; /** * Check whether the game ended in a draw * @returns the game state */ isDraw(): boolean; /** * Check the valid moves (all unoccupied coordinates) * @returns an array of objects with the x and y values */ legalMoves(): [{ x: number; y: number }]; /** * Do a random move (no logic or AI involved, this is completely random) * @returns an object with the x and y value of the random move */ randomMove(): { x: number; y: number }; }
412
0.670912
1
0.670912
game-dev
MEDIA
0.345238
game-dev
0.749167
1
0.749167
HushengStudent/myGameFramework
10,293
Client/Assets/Scripts/Framework/Lua/LuaUtility.cs
/******************************************************************************** ** auth: https://github.com/HushengStudent ** date: 2018/01/07 17:33:17 ** desc: Lua工具集; *********************************************************************************/ using LuaInterface; using System; using System.IO; using System.Security.Cryptography; using System.Text; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Framework { public class LuaUtility : Singleton<LuaUtility> { #region Math public static int Int(object o) { return Convert.ToInt32(o); } public static float Float(object o) { return (float)Math.Round(Convert.ToSingle(o), 2); } public static long Long(object o) { return Convert.ToInt64(o); } public static int Random(int min, int max) { return UnityEngine.Random.Range(min, max); } public static float Random(float min, float max) { return UnityEngine.Random.Range(min, max); } #endregion #region Unity /// <summary> /// 搜索子物体组件:GameObject版; /// </summary> /// <typeparam name="T"></typeparam> /// <param name="go"></param> /// <param name="subnode"></param> /// <returns></returns> public static T Get<T>(GameObject go, string subnode) where T : Component { if (go != null) { var sub = go.transform.Find(subnode); if (sub != null) { return sub.GetComponent<T>(); } } return null; } /// <summary> /// 搜索子物体组件:Transform版; /// </summary> /// <typeparam name="T"></typeparam> /// <param name="go"></param> /// <param name="subnode"></param> /// <returns></returns> public static T Get<T>(Transform go, string subnode) where T : Component { if (go != null) { var sub = go.Find(subnode); if (sub != null) { return sub.GetComponent<T>(); } } return null; } /// <summary> /// 搜索子物体组件:Component版; /// </summary> /// <typeparam name="T"></typeparam> /// <param name="go"></param> /// <param name="subnode"></param> /// <returns></returns> public static T Get<T>(Component go, string subnode) where T : Component { return go.transform.Find(subnode).GetComponent<T>(); } /// <summary> /// 添加组件; /// </summary> public static T Add<T>(GameObject go) where T : Component { if (go != null) { var ts = go.GetComponents<T>(); for (var i = 0; i < ts.Length; i++) { if (ts[i] != null) { UnityObject.Destroy(ts[i]); } } return go.AddComponent<T>(); } return null; } /// <summary> /// 添加组件; /// </summary> public static T Add<T>(Transform go) where T : Component { return Add<T>(go.gameObject); } /// <summary> /// 查找子对象; /// </summary> public static GameObject Child(GameObject go, string subnode) { return Child(go.transform, subnode); } /// <summary> /// 查找子对象; /// </summary> public static GameObject Child(Transform go, string subnode) { var tran = go.Find(subnode); if (tran == null) { return null; } return tran.gameObject; } /// <summary> /// 取平级对象; /// </summary> public static GameObject Peer(GameObject go, string subnode) { return Peer(go.transform, subnode); } /// <summary> /// 取平级对象; /// </summary> public static GameObject Peer(Transform go, string subnode) { var tran = go.parent.Find(subnode); if (tran == null) { return null; } return tran.gameObject; } /// <summary> /// 清除所有子节点; /// </summary> public static void ClearChild(Transform go) { if (go == null) { return; } for (var i = go.childCount - 1; i >= 0; i--) { UnityObject.Destroy(go.GetChild(i).gameObject); } } #endregion #region System public static string Uid(string uid) { var position = uid.LastIndexOf('_'); return uid.Remove(0, position + 1); } public static long GetTime() { //TODO:使用服务器时间; var ts = new TimeSpan(DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks); return (long)ts.TotalMilliseconds; } /// <summary> /// 计算字符串的MD5值; /// </summary> public static string Md5(string source) { var md5 = new MD5CryptoServiceProvider(); var data = Encoding.UTF8.GetBytes(source); var md5Data = md5.ComputeHash(data, 0, data.Length); md5.Clear(); var destString = ""; for (var i = 0; i < md5Data.Length; i++) { destString += Convert.ToString(md5Data[i], 16).PadLeft(2, '0'); } destString = destString.PadLeft(32, '0'); return destString; } /// <summary> /// 计算文件的MD5值; /// </summary> public static string Md5file(string file) { try { var fs = new FileStream(file, FileMode.Open); var md5 = new MD5CryptoServiceProvider(); var retVal = md5.ComputeHash(fs); fs.Close(); var sb = new StringBuilder(); for (var i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } } /// <summary> /// 清理内存; /// </summary> public static void ClearMemory() { GC.Collect(); Resources.UnloadUnusedAssets(); if (LuaMgr.singleton != null) { LuaMgr.singleton.LuaGC(); } } /// <summary> /// 取得行文本; /// </summary> public static string GetFileText(string path) { return File.ReadAllText(path); } /// <summary> /// 网络可用; /// </summary> public static bool NetAvailable { get { return Application.internetReachability != NetworkReachability.NotReachable; } } /// <summary> /// 是否是无线; /// </summary> public static bool IsWifi { get { return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork; } } /// <summary> /// 应用程序内容路径; /// </summary> public static string AppContentPath() { var path = string.Empty; switch (Application.platform) { case RuntimePlatform.Android: path = "jar:file://" + Application.dataPath + "!/assets/"; break; case RuntimePlatform.IPhonePlayer: path = Application.dataPath + "/Raw/"; break; default: //path = Application.dataPath + "/" + AppConst.AssetDir + "/"; break; } return path; } #endregion #region Call Lua /// <summary> /// 执行Lua方法; /// </summary> public static object[] CallMethod(string module, string func, params object[] args) { if (LuaMgr.singleton == null) { return null; } return LuaMgr.singleton.CallFunction(module + "." + func, args); } public static void CallLuaModuleMethod(string module, string func, params object[] args) { if (LuaMgr.singleton == null) { return; } LuaMgr.singleton.CallLuaModuleMethod(module + "." + func, args); } public static void CallLuaTableMethod(string module, string func, params object[] args) { if (LuaMgr.singleton == null) { return; } LuaMgr.singleton.CallLuaTableMethod(module, func, args); } /// <summary> /// pbc/pblua函数回调; /// </summary> /// <param name="data"></param> /// <param name="func"></param> public static void OnCallLuaFunc(LuaByteBuffer data, LuaFunction func) { if (func != null) { func.Call(data); } LogHelper.Print("OnCallLuaFunc length:>>" + data.buffer.Length); } #endregion #region Json /// <summary> /// cjson函数回调; /// </summary> /// <param name="data"></param> /// <param name="func"></param> public static void OnJsonCallFunc(string data, LuaFunction func) { Debug.LogWarning("OnJsonCallback data:>>" + data + " lenght:>>" + data.Length); if (func != null) { func.Call(data); } } #endregion } }
412
0.853786
1
0.853786
game-dev
MEDIA
0.91748
game-dev
0.957064
1
0.957064
vlad250906/Create-UfoPort
2,713
modules/create/src/main/java/com/simibubi/create/content/redstone/diodes/BrassDiodeScrollValueBehaviour.java
package com.simibubi.create.content.redstone.diodes; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.ValueBoxTransform; import com.simibubi.create.foundation.blockEntity.behaviour.ValueSettingsBoard; import com.simibubi.create.foundation.blockEntity.behaviour.ValueSettingsFormatter; import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollValueBehaviour; import com.simibubi.create.foundation.utility.Components; import com.simibubi.create.foundation.utility.Lang; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; public class BrassDiodeScrollValueBehaviour extends ScrollValueBehaviour { public BrassDiodeScrollValueBehaviour(Component label, SmartBlockEntity be, ValueBoxTransform slot) { super(label, be, slot); } @Override public ValueSettingsBoard createBoard(Player player, BlockHitResult hitResult) { return new ValueSettingsBoard(label, 60, 10, Lang.translatedOptions("generic.unit", "ticks", "seconds", "minutes"), new ValueSettingsFormatter(this::formatSettings)); } @Override public void onShortInteract(Player player, InteractionHand hand, Direction side) { BlockState blockState = blockEntity.getBlockState(); if (blockState.getBlock()instanceof BrassDiodeBlock bdb) bdb.toggle(player.getItemInHand(hand), getWorld(), getPos(), blockState, player, hand); } @Override public void setValueSettings(Player player, ValueSettings valueSetting, boolean ctrlHeld) { int value = valueSetting.value(); int multiplier = switch (valueSetting.row()) { case 0 -> 1; case 1 -> 20; default -> 60 * 20; }; if (!valueSetting.equals(getValueSettings())) playFeedbackSound(this); setValue(Math.max(2, Math.max(1, value) * multiplier)); } @Override public ValueSettings getValueSettings() { int row = 0; int value = this.value; if (value > 60 * 20) { value = value / (60 * 20); row = 2; } else if (value > 60) { value = value / 20; row = 1; } return new ValueSettings(row, value); } public MutableComponent formatSettings(ValueSettings settings) { int value = Math.max(1, settings.value()); return Components.literal(switch (settings.row()) { case 0 -> Math.max(2, value) + "t"; case 1 -> "0:" + (value < 10 ? "0" : "") + value; default -> value + ":00"; }); } @Override public String getClipboardKey() { return "Timings"; } }
412
0.872466
1
0.872466
game-dev
MEDIA
0.981103
game-dev
0.927349
1
0.927349
latte-soft/builtinplugins
1,437
src/BuiltInPlugins/R15Migrator/Bin/publishLoader.server.luau
local l_script_FirstAncestor_0 = script:FindFirstAncestor("R15Migrator"); local v1 = require(l_script_FirstAncestor_0.Src.Util.DebugFlags); if require(l_script_FirstAncestor_0.Src.Util.shouldPluginRun)() then if not v1.RunTests() and not v1.RunningUnderCLI() then local v2 = require(l_script_FirstAncestor_0.PluginLoader.PluginLoaderBuilder); local l_SourceStrings_0 = l_script_FirstAncestor_0.Src.Resources.Localization.SourceStrings; local l_LocalizedStrings_0 = l_script_FirstAncestor_0.Src.Resources.Localization.LocalizedStrings; local l_StudioPublishService_0 = game:GetService("StudioPublishService"); local v6 = v2.build({ plugin = plugin, pluginName = "PublishBlocked", translationResourceTable = l_LocalizedStrings_0, fallbackResourceTable = l_SourceStrings_0, overrideLocaleId = nil, localizationNamespace = nil, noToolbar = true, extraTriggers = { ["StudioPublishService.OnPublishAttempt"] = function() return l_StudioPublishService_0.OnPublishAttempt; end } }); if v6.pluginLoader:waitForUserInteraction() then require(script.Parent.publishMain)(plugin, v6); return ; else return ; end; else return ; end; else return ; end;
412
0.883977
1
0.883977
game-dev
MEDIA
0.604045
game-dev
0.808654
1
0.808654
Grasscutters/Grasscutter
1,454
src/main/java/emu/grasscutter/game/home/suite/event/HomeAvatarEvent.java
package emu.grasscutter.game.home.suite.event; import emu.grasscutter.game.inventory.GameItem; import emu.grasscutter.game.player.Player; import emu.grasscutter.utils.Utils; import java.util.List; import java.util.Objects; import lombok.AccessLevel; import lombok.Getter; import lombok.experimental.FieldDefaults; @Getter @FieldDefaults(level = AccessLevel.PRIVATE) public abstract class HomeAvatarEvent { final Player homeOwner; final int eventId; final int rewardId; final int avatarId; final int suiteId; final int guid; final int randomPos; public HomeAvatarEvent( Player homeOwner, int eventId, int rewardId, int avatarId, int suiteId, int guid) { this.homeOwner = homeOwner; this.eventId = eventId; this.rewardId = rewardId; this.avatarId = avatarId; this.suiteId = suiteId; this.guid = guid; this.randomPos = this.generateRandomPos(); } public int generateRandomPos() { return Utils.randomRange(1, 97); } public List<GameItem> giveRewards() { return List.of(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HomeAvatarEvent that = (HomeAvatarEvent) o; return eventId == that.eventId; } @Override public int hashCode() { return Objects.hash(eventId); } }
412
0.624165
1
0.624165
game-dev
MEDIA
0.955912
game-dev
0.962257
1
0.962257
minigdx/tiny
25,057
tiny-engine/src/commonMain/kotlin/com/github/minigdx/tiny/engine/GameEngine.kt
package com.github.minigdx.tiny.engine import com.github.minigdx.tiny.ColorIndex import com.github.minigdx.tiny.Seconds import com.github.minigdx.tiny.file.VirtualFileSystem import com.github.minigdx.tiny.graphic.ColorPalette import com.github.minigdx.tiny.graphic.FrameBuffer import com.github.minigdx.tiny.input.InputHandler import com.github.minigdx.tiny.input.InputManager import com.github.minigdx.tiny.input.Key import com.github.minigdx.tiny.input.internal.ObjectPool import com.github.minigdx.tiny.input.internal.PoolObject import com.github.minigdx.tiny.log.Logger import com.github.minigdx.tiny.lua.toTinyException import com.github.minigdx.tiny.platform.Platform import com.github.minigdx.tiny.render.RenderContext import com.github.minigdx.tiny.render.RenderFrame import com.github.minigdx.tiny.render.RenderUnit import com.github.minigdx.tiny.render.operations.DrawSprite import com.github.minigdx.tiny.render.operations.RenderOperation import com.github.minigdx.tiny.resources.GameLevel import com.github.minigdx.tiny.resources.GameResource import com.github.minigdx.tiny.resources.GameScript import com.github.minigdx.tiny.resources.ResourceFactory import com.github.minigdx.tiny.resources.ResourceType.BOOT_GAMESCRIPT import com.github.minigdx.tiny.resources.ResourceType.BOOT_SPRITESHEET import com.github.minigdx.tiny.resources.ResourceType.ENGINE_GAMESCRIPT import com.github.minigdx.tiny.resources.ResourceType.GAME_GAMESCRIPT import com.github.minigdx.tiny.resources.ResourceType.GAME_LEVEL import com.github.minigdx.tiny.resources.ResourceType.GAME_SOUND import com.github.minigdx.tiny.resources.ResourceType.GAME_SPRITESHEET import com.github.minigdx.tiny.resources.Sound import com.github.minigdx.tiny.resources.SpriteSheet import com.github.minigdx.tiny.sound.MusicalBar import com.github.minigdx.tiny.sound.MusicalSequence import com.github.minigdx.tiny.sound.SoundHandler import com.github.minigdx.tiny.sound.SoundManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.launch import org.luaj.vm2.Globals import org.luaj.vm2.LuaError import org.luaj.vm2.LuaValue.Companion.valueOf import kotlin.math.max import kotlin.math.min import kotlin.reflect.KClass @OptIn(ExperimentalCoroutinesApi::class) class GameEngine( val gameOptions: GameOptions, val platform: Platform, val vfs: VirtualFileSystem, val logger: Logger, val customizeLuaGlobal: GameResourceAccess.(Globals) -> Unit = {}, val listener: GameEngineListener? = null, ) : GameLoop, GameResourceAccess { private val events: MutableList<GameResource> = mutableListOf() private val workEvents: MutableList<GameResource> = mutableListOf() private var numberOfResources: Int = 0 private var debugEnabled: Boolean = true private val debugActions = mutableListOf<DebugAction>() private val ops = mutableListOf<RenderOperation>() private lateinit var scripts: Array<GameScript?> private lateinit var spriteSheets: Array<SpriteSheet?> private lateinit var levels: Array<GameLevel?> private lateinit var sounds: Array<Sound?> override var bootSpritesheet: SpriteSheet? = null private set private var engineGameScript: GameScript? = null private var inError = false /** * Current script by index. */ private var current: Int = 0 override val frameBuffer = FrameBuffer(gameOptions.width, gameOptions.height, gameOptions.colors()) private var accumulator: Seconds = 0f lateinit var renderContext: RenderContext lateinit var inputHandler: InputHandler lateinit var inputManager: InputManager lateinit var soundManager: SoundManager private lateinit var resourceFactory: ResourceFactory private val operationFactory = OperationsObjectPool() fun main() { val windowManager = platform.initWindowManager() inputHandler = platform.initInputHandler() inputManager = platform.initInputManager() soundManager = platform.initSoundManager(inputHandler) resourceFactory = ResourceFactory( vfs = vfs, platform = platform, logger = logger, colorPalette = gameOptions.colors(), ) val resourcesScope = CoroutineScope(platform.io()) val gameScripts = gameOptions.gameScripts.mapIndexed { index, script -> resourceFactory.gamescript(index + 1, script, inputHandler, gameOptions) } this.scripts = Array(gameScripts.size + 1) { null } val spriteSheets = gameOptions.spriteSheets.mapIndexed { index, sheet -> resourceFactory.gameSpritesheet(index, sheet) } this.spriteSheets = Array(spriteSheets.size) { null } val gameLevels = gameOptions.gameLevels.mapIndexed { index, level -> resourceFactory.gameLevel(index, level) } this.levels = Array(gameLevels.size) { null } val sounds = gameOptions.sounds.mapIndexed { index, sound -> resourceFactory.soundEffect(index, sound) } this.sounds = Array(sounds.size) { null } val resources = listOf( resourceFactory.bootscript("_boot.lua", inputHandler, gameOptions), resourceFactory.enginescript("_engine.lua", inputHandler, gameOptions), resourceFactory.bootSpritesheet("_boot.png"), ) + gameScripts + spriteSheets + gameLevels + sounds numberOfResources = resources.size logger.debug("GAME_ENGINE") { "Number of resources to load: $numberOfResources" } resourcesScope.launch { resources.asFlow() .flatMapMerge(concurrency = 128) { resource -> resource } .collect(ScriptsCollector(events)) } renderContext = platform.initRenderManager(windowManager) platform.gameLoop(this) } override suspend fun advance(delta: Seconds) { workEvents.addAll(events) workEvents.forEach { resource -> // The resource is loading if (!resource.reload) { logger.info("GAME_ENGINE") { "Loaded ${resource.name} ${resource.type} (version: ${resource.version})" } when (resource.type) { BOOT_GAMESCRIPT -> { // Always put the boot script at the top of the stack val bootScript = resource as GameScript bootScript.resourceAccess = this bootScript.evaluate(customizeLuaGlobal) scripts[0] = bootScript } GAME_GAMESCRIPT -> { resource as GameScript resource.resourceAccess = this // Game script will be evaluated when the boot script will exit scripts[resource.index] = resource } ENGINE_GAMESCRIPT -> { // Don't put the engine script in the stack engineGameScript = resource as GameScript engineGameScript?.resourceAccess = this engineGameScript?.evaluate(customizeLuaGlobal) } BOOT_SPRITESHEET -> { bootSpritesheet = resource as SpriteSheet } GAME_SPRITESHEET -> { spriteSheets[resource.index] = resource as SpriteSheet } GAME_LEVEL -> { levels[resource.index] = resource as GameLevel } GAME_SOUND -> { sounds[resource.index] = resource as Sound } } numberOfResources-- logger.debug("GAME_ENGINE") { "Remaining resources to load: $numberOfResources." } if (numberOfResources == 0) { logger.debug("GAME_ENGINE") { "All resources are loaded. Notify the boot script." } // Force to notify the boot script scripts[0]!!.resourcesLoaded() } } else { logger.info("GAME_ENGINE") { "Reload ${resource.name} ${resource.type} (version: ${resource.version})" } // The resource already has been loaded. when (resource.type) { BOOT_GAMESCRIPT -> { // Always put the boot script at the top of the stack val bootScript = resource as GameScript bootScript.resourceAccess = this bootScript.evaluate(customizeLuaGlobal) scripts[0] = bootScript } GAME_GAMESCRIPT -> { resource as GameScript resource.resourceAccess = this val isValid = try { resource.isValid(customizeLuaGlobal) true } catch (ex: LuaError) { popupError(ex.toTinyException(resource.content.decodeToString())) false } if (isValid) { scripts[resource.index] = resource // Force the reloading of the script, as the script update might be used as resource of // the current game script. scripts[current]?.reload = true clear() } } ENGINE_GAMESCRIPT -> { // Don't put the engine script in the stack engineGameScript = resource as GameScript engineGameScript?.resourceAccess = this engineGameScript?.evaluate(customizeLuaGlobal) } BOOT_SPRITESHEET -> { bootSpritesheet = resource as SpriteSheet } GAME_SPRITESHEET -> { spriteSheets[resource.index] = resource as SpriteSheet } GAME_LEVEL -> { levels[resource.index] = resource as GameLevel // Force the reloading of the script as level init might occur in the _init block. scripts[current]?.reload = true } GAME_SOUND -> { sounds[resource.index] = resource as Sound } } } } events.removeAll(workEvents) workEvents.clear() with(scripts[current]) { if (this == null) return if (exited >= 0) { val previous = current // next script current = min(exited + 1, scripts.size - 1) try { val state = getState() logger.debug("GAME_ENGINE") { "Stop $name to switch the next game script ${scripts[current]?.name}" } // Reevaluate the game to flush the previous state. scripts[current]?.evaluate(customizeLuaGlobal) scripts[current]?.setState(state) listener?.switchScript(scripts[previous], scripts[current]) } catch (ex: LuaError) { popupError(ex.toTinyException(content.decodeToString())) } } else if (reload) { clear() try { val state = getState() evaluate(customizeLuaGlobal) setState(state) listener?.reload(scripts[current]) inError = false } catch (ex: LuaError) { popupError(ex.toTinyException(content.decodeToString())) } } // Fixed step simulation accumulator += delta if (accumulator >= REFRESH_LIMIT) { inputManager.record() inError = try { ops.clear() // Remove all drawing operation to prepare the new frame. scripts[current]?.advance() false } catch (ex: TinyException) { if (!inError) { // display the log only once. popupError(ex) } true } engineGameScript?.advance() accumulator -= REFRESH_LIMIT // The user hit Ctrl + R(ecord) if (inputHandler.isCombinationPressed(Key.CTRL, Key.R)) { popup("recording GIF", "#00FF00") platform.record() // The user hit Ctrl + S(creenshot) } else if (inputHandler.isCombinationPressed(Key.CTRL, Key.S)) { popup("screenshot PNG", "#00FF00") platform.screenshot() } var msgIndex = 0 if (!debugEnabled) { debugActions.clear() } debugActions.forEach { debugAction -> when (debugAction) { is DebugMessage -> { val (msg, color) = debugAction engineGameScript?.invoke( "printDebug", valueOf(msgIndex++), valueOf(msg), valueOf(color), ) } is DebugRect -> { val (x, y, width, height, color) = debugAction engineGameScript?.invoke( "shape.rect", valueOf(x), valueOf(y), valueOf(width), valueOf(height), valueOf(color), ) } is DebugEnabled -> Unit // NOP is DebugLine -> { val (x1, y1, x2, y2, color) = debugAction engineGameScript?.invoke( "shape.line", valueOf(x1), valueOf(y1), valueOf(x2), valueOf(y2), valueOf(color), ) } is DebugPoint -> { val (x, y, color) = debugAction engineGameScript?.invoke( "shape.circlef", valueOf(x), valueOf(y), valueOf(2), valueOf(color), ) } } } debugActions.clear() inputManager.reset() } } } override fun debug(action: DebugAction) { when (action) { is DebugEnabled -> { debugEnabled = action.enabled } else -> debugActions.add(action) } } private suspend fun GameEngine.popupError(ex: TinyException) { logger.warn( "TINY", ) { val error = "line ${ex.lineNumber}:${ex.line} <-- the \uD83D\uDC1E is around here (${ex.message})" "The line ${ex.lineNumber} trigger an execution error (${ex.message}). Please fix your script!\n" + error } val msg = "error line ${ex.lineNumber}:${ex.line} (${ex.message})" popup(msg, "#FF0000", true) } private suspend fun popup( message: String, color: String, forever: Boolean = false, ) { engineGameScript?.invoke("popup", valueOf(0), valueOf(message), valueOf(color), valueOf(forever)) } private suspend fun clear() { engineGameScript?.invoke("clear") } override fun spritesheet(index: Int): SpriteSheet? { val protected = max(0, min(index, spriteSheets.size - 1)) if (protected >= spriteSheets.size) return null return spriteSheets[protected] } override fun spritesheet(name: String): Int? { return spriteSheets .indexOfFirst { it?.name == name } .takeIf { it >= 0 } } override fun newSpritesheetIndex(): Int { return spriteSheets.size } override fun spritesheet(sheet: SpriteSheet) { if (sheet.index < 0) { // The index is negative. Let's copy it at the last place. spriteSheets = spriteSheets.copyOf(spriteSheets.size + 1) spriteSheets[spriteSheets.size - 1] = sheet } else if (sheet.index >= spriteSheets.size) { require(sheet.index <= 256) { "Tiny support only 256 spritesheets" } spriteSheets = spriteSheets.copyOf(sheet.index + 1) spriteSheets[sheet.index] = sheet } else { spriteSheets[sheet.index] = sheet } } override fun level(index: Int): GameLevel? { val protected = max(0, min(index, levels.size - 1)) if (protected >= levels.size) return null return levels[protected] } override fun sound(index: Int): Sound? { return sounds.getOrNull(index.coerceIn(0, sounds.size - 1)) } override fun sound(name: String): Sound? { val index = sounds.indexOfFirst { it?.data?.name == name } .takeIf { it >= 0 } ?: return null return sound(index) } override fun play(musicalBar: MusicalBar): SoundHandler { return soundManager.createSoundHandler(musicalBar).also { it.play() } } override fun play(musicalSequence: MusicalSequence): SoundHandler { return soundManager.createSoundHandler(musicalSequence).also { it.play() } } override fun play(track: MusicalSequence.Track): SoundHandler { return soundManager.createSoundHandler(track).also { it.play() } } override fun exportAsSound(sequence: MusicalSequence) { soundManager.exportAsSound(sequence) } override fun script(name: String): GameScript? { return scripts .drop(1) // drop the _boot.lua .firstOrNull { script -> script?.name == name } } override fun addOp(op: RenderOperation) { renderFrame = null // invalid the previous render frame val last = ops.lastOrNull() if (op.mergeWith(last)) { return } if (last == null || op.target.compatibleWith(last.target)) { ops.add(op) } else { // Render only the framebuffer OR GPU operations render() ops.add(op) } } override fun renderAsBuffer(block: () -> Unit): FrameBuffer { // Render on the screen to clean up render states. render() val renderFrame = platform.executeOffScreen(renderContext) { block.invoke() render() } val buffer = FrameBuffer(gameOptions.width, gameOptions.height, gameOptions.colors()) renderFrame.copyInto(buffer.colorIndexBuffer) return buffer } /** * Will render the remaining operations on the screen. */ override fun draw() { render() // Render the last operation into the frame buffer platform.draw(renderContext) } /** * Will render the actual operations in the frame buffer */ fun render() { val last = ops.lastOrNull() ?: return val frameBufferRender = last.target.compatibleWith(RenderUnit.CPU) if (frameBufferRender) { // The remaining operations are only for the CPU. // Let's execute it now. ops.forEach { check(it.target.compatibleWith(RenderUnit.CPU)) { "Expected only ops than can be executed on CPU!" } } ops.clear() // The framebuffer will be the next render operation val op = DrawSprite.from( this, frameBuffer.asSpriteSheet, 0, 0, frameBuffer.width, frameBuffer.height, ) ops.add(op) } // Render operations in the GPU frame buffer platform.render(renderContext, ops) // The framebuffer has been rendered. // It can be reset. if (frameBufferRender) { frameBuffer.clear() } ops.clear() } private var renderFrame: RenderFrame? = null override fun readPixel( x: Int, y: Int, ): ColorIndex { if (renderFrame == null) { render() renderFrame = platform.readRender(renderContext) } return renderFrame?.getPixel(x, y) ?: ColorPalette.TRANSPARENT_INDEX } override fun readFrame(): FrameBuffer { if (renderFrame == null) { render() renderFrame = platform.readRender(renderContext) } val copy = FrameBuffer(frameBuffer.width, frameBuffer.height, frameBuffer.gamePalette) renderFrame?.copyInto(copy.colorIndexBuffer) return copy } override fun end() { soundManager.destroy() } override fun save( filename: String, content: String, ) { platform.createLocalFile(filename, null).save(content.encodeToByteArray()) } override fun <T : PoolObject<T>> obtain(type: KClass<T>): T { return operationFactory.obtain(type) } override fun <T : PoolObject<T>> releaseOperation( operation: T, type: KClass<T>, ) { operationFactory.release(operation, type) } companion object { private const val REFRESH_LIMIT: Seconds = 1 / 60f } } class OperationsObjectPool { private abstract class PoolObjectPool<T : PoolObject<T>>(size: Int) : ObjectPool<T>(size) { abstract fun new(): T abstract fun destroy(obj: T) override fun newInstance(): T { return new().also { it.pool = this } } override fun destroyInstance(obj: T) { destroy(obj) obj.pool = null } } private val drawSprite = object : PoolObjectPool<DrawSprite>(256) { override fun new(): DrawSprite { return DrawSprite() } override fun destroy(obj: DrawSprite) { obj.source = null obj.dither = 0xFFFF obj.pal = emptyArray() obj.camera = null obj.clipper = null obj._attributes.forEach { attribute -> attribute.release() } obj._attributes.clear() } } private val drawSpriteAttribute = object : PoolObjectPool<DrawSprite.DrawSpriteAttribute>(2048) { override fun new(): DrawSprite.DrawSpriteAttribute { return DrawSprite.DrawSpriteAttribute() } override fun destroy(obj: DrawSprite.DrawSpriteAttribute) { obj.sourceX = 0 obj.sourceY = 0 obj.sourceWidth = 0 obj.sourceHeight = 0 obj.destinationX = 0 obj.destinationY = 0 obj.flipX = false obj.flipY = false } } private fun <T : PoolObject<T>> getPool(type: KClass<T>): ObjectPool<T> { @Suppress("UNCHECKED_CAST") val pool: ObjectPool<T> = when (type) { DrawSprite::class -> drawSprite as ObjectPool<T> DrawSprite.DrawSpriteAttribute::class -> drawSpriteAttribute as ObjectPool<T> else -> throw IllegalArgumentException("No pool found for type: $type") } return pool } fun <T : PoolObject<T>> obtain(type: KClass<T>): T { return getPool(type).obtain() } fun <T : PoolObject<T>> release( operation: T, type: KClass<T>, ) { getPool(type).destroyInstance(operation) } }
412
0.854442
1
0.854442
game-dev
MEDIA
0.920715
game-dev
0.900889
1
0.900889
opentibiabr/canary
1,298
data-otservbr-global/npc/willem.lua
local internalNpcName = "Willem" 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 = 140, lookHead = 60, lookBody = 24, lookLegs = 38, lookFeet = 0, 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 npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) -- npcType registering the npcConfig table npcType:register(npcConfig)
412
0.812563
1
0.812563
game-dev
MEDIA
0.906444
game-dev
0.542229
1
0.542229
glKarin/com.n0n3m4.diii4a
1,919
Q3E/src/main/jni/source/game/server/serverbenchmark_base.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #ifndef SERVERBENCHMARK_BASE_H #define SERVERBENCHMARK_BASE_H #ifdef _WIN32 #pragma once #endif // The base server code calls into this. class IServerBenchmark { public: virtual bool StartBenchmark() = 0; virtual void UpdateBenchmark() = 0; virtual void EndBenchmark() = 0; virtual bool IsBenchmarkRunning() = 0; virtual bool IsLocalBenchmarkPlayer( CBasePlayer *pPlayer ) = 0; // Game-specific benchmark code should use this. virtual int RandomInt( int nMin, int nMax ) = 0; virtual float RandomFloat( float flMin, float flMax ) = 0; virtual int GetTickOffset() = 0; }; extern IServerBenchmark *g_pServerBenchmark; // // Each game can derive from this to hook into the server benchmark. // // Hooks should always use g_pServerBenchmark->RandomInt/Float to get random numbers // so the benchmark is deterministic. // // If they use an absolute tick number for anything, then they should also call g_pServerBenchmark->GetTickOffset() // to get a tick count since the start of the benchmark instead of looking at gpGlobals->tickcount. // class CServerBenchmarkHook { public: CServerBenchmarkHook(); virtual void StartBenchmark() {} virtual void UpdateBenchmark() {} virtual void EndBenchmark() {} // Give a list of model names that can be spawned in for physics props during the simulation. virtual void GetPhysicsModelNames( CUtlVector<char*> &modelNames ) = 0; // The benchmark will call this to create a bot each time it wants to create a player. // If you want to manage the bots yourself, you can return NULL here. virtual CBasePlayer* CreateBot() = 0; private: friend class CServerBenchmark; static CServerBenchmarkHook *s_pBenchmarkHook; // There can be only one!! }; #endif // SERVERBENCHMARK_BASE_H
412
0.855529
1
0.855529
game-dev
MEDIA
0.476846
game-dev
0.719407
1
0.719407
fanx-dev/fanx
1,672
compiler/testCompilerx/res/inherit/testInheritErrors.fan
virtual class A { new ctor() { return } Bool a() { return false } virtual Bool b() { return false } virtual Bool c() { return false } virtual Void d(Bool b) { } private Void e() {} virtual Int f () { return 9 } Bool g virtual Int h abstract Bool i virtual Int j virtual Void k() {} } class B : A { static B ctor() { return null } // ok Bool a() { return true } Bool b() { return true } override Int c() { return 0 } override Void d(Bool b, Int x) { } private Void e_(Int x, Int y) {} // ok override Str f override Str g Int h override Str i override final Int j override final Void k() {} } class C : B { override Int j override Void k() {} } class SubOut : OutStream { override Void close() { } This flush() { this } override This write() { return this } override This writeBool(Bool x) { return this } } mixin ConflictX { static Void a() {} virtual Int b() { return 3 } virtual Void c(Str q) { } virtual Void d(Str q) { } } mixin ConflictY { static Void a() {} virtual Bool b() { return true } virtual Void c(Str q, Int p) { } virtual Void d(Int q) { } } class Conflict : ConflictX, ConflictY {} mixin WhichX { virtual Str name() { return null } } mixin WhichY { virtual Str name() { return null } } class Which : WhichX, WhichY {} class Ouch { override Bool isImmutable() { return true } override Void figgle() {} override Str foogle virtual Obj returnObj() { return null } virtual Void returnVoid() {} } class SubOuch : Ouch { override Void returnObj() {} override Obj returnVoid() { return null } }
412
0.860869
1
0.860869
game-dev
MEDIA
0.46995
game-dev
0.608931
1
0.608931
google-deepmind/lab
29,063
q3map2/common/polylib.c
/* Copyright (C) 1999-2007 id Software, Inc. and contributors. For a list of contributors, see the accompanying CONTRIBUTORS file. This file is part of GtkRadiant. GtkRadiant 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. GtkRadiant 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 GtkRadiant; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stddef.h> #include "cmdlib.h" #include "mathlib.h" #include "inout.h" #include "polylib.h" #include "qfiles.h" extern int numthreads; // counters are only bumped when running single threaded, // because they are an awefull coherence problem int c_active_windings; int c_peak_windings; int c_winding_allocs; int c_winding_points; #define BOGUS_RANGE WORLD_SIZE void pw( winding_t *w ){ int i; for ( i = 0 ; i < w->numpoints ; i++ ) Sys_Printf( "(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2] ); } /* ============= AllocWinding ============= */ winding_t *AllocWinding( int points ){ winding_t *w; int s; if ( points >= MAX_POINTS_ON_WINDING ) { Error( "AllocWinding failed: MAX_POINTS_ON_WINDING exceeded" ); } if ( numthreads == 1 ) { c_winding_allocs++; c_winding_points += points; c_active_windings++; if ( c_active_windings > c_peak_windings ) { c_peak_windings = c_active_windings; } } s = sizeof( *w ) + points * sizeof( *w->p ); w = safe_malloc( s ); memset( w, 0, s ); return w; } /* ============= AllocWindingAccu ============= */ winding_accu_t *AllocWindingAccu( int points ){ winding_accu_t *w; int s; if ( points >= MAX_POINTS_ON_WINDING ) { Error( "AllocWindingAccu failed: MAX_POINTS_ON_WINDING exceeded" ); } if ( numthreads == 1 ) { // At the time of this writing, these statistics were not used in any way. c_winding_allocs++; c_winding_points += points; c_active_windings++; if ( c_active_windings > c_peak_windings ) { c_peak_windings = c_active_windings; } } s = sizeof( *w ) + points * sizeof( *w->p ); w = safe_malloc( s ); memset( w, 0, s ); return w; } /* ============= FreeWinding ============= */ void FreeWinding( winding_t *w ){ if ( !w ) { Error( "FreeWinding: winding is NULL" ); } if ( *(unsigned *)w == 0xdeaddead ) { Error( "FreeWinding: freed a freed winding" ); } *(unsigned *)w = 0xdeaddead; if ( numthreads == 1 ) { c_active_windings--; } free( w ); } /* ============= FreeWindingAccu ============= */ void FreeWindingAccu( winding_accu_t *w ){ if ( !w ) { Error( "FreeWindingAccu: winding is NULL" ); } if ( *( (unsigned *) w ) == 0xdeaddead ) { Error( "FreeWindingAccu: freed a freed winding" ); } *( (unsigned *) w ) = 0xdeaddead; if ( numthreads == 1 ) { c_active_windings--; } free( w ); } /* ============ RemoveColinearPoints ============ */ int c_removed; void RemoveColinearPoints( winding_t *w ){ int i, j, k; vec3_t v1, v2; int nump; vec3_t p[MAX_POINTS_ON_WINDING]; nump = 0; for ( i = 0 ; i < w->numpoints ; i++ ) { j = ( i + 1 ) % w->numpoints; k = ( i + w->numpoints - 1 ) % w->numpoints; VectorSubtract( w->p[j], w->p[i], v1 ); VectorSubtract( w->p[i], w->p[k], v2 ); VectorNormalize( v1,v1 ); VectorNormalize( v2,v2 ); if ( DotProduct( v1, v2 ) < 0.999 ) { VectorCopy( w->p[i], p[nump] ); nump++; } } if ( nump == w->numpoints ) { return; } if ( numthreads == 1 ) { c_removed += w->numpoints - nump; } w->numpoints = nump; memcpy( w->p, p, nump * sizeof( p[0] ) ); } /* ============ WindingPlane ============ */ void WindingPlane( winding_t *w, vec3_t normal, vec_t *dist ){ vec3_t v1, v2; VectorSubtract( w->p[1], w->p[0], v1 ); VectorSubtract( w->p[2], w->p[0], v2 ); CrossProduct( v2, v1, normal ); VectorNormalize( normal, normal ); *dist = DotProduct( w->p[0], normal ); } /* ============= WindingArea ============= */ vec_t WindingArea( winding_t *w ){ int i; vec3_t d1, d2, cross; vec_t total; total = 0; for ( i = 2 ; i < w->numpoints ; i++ ) { VectorSubtract( w->p[i - 1], w->p[0], d1 ); VectorSubtract( w->p[i], w->p[0], d2 ); CrossProduct( d1, d2, cross ); total += 0.5 * VectorLength( cross ); } return total; } void WindingBounds( winding_t *w, vec3_t mins, vec3_t maxs ){ vec_t v; int i,j; mins[0] = mins[1] = mins[2] = 99999; maxs[0] = maxs[1] = maxs[2] = -99999; for ( i = 0 ; i < w->numpoints ; i++ ) { for ( j = 0 ; j < 3 ; j++ ) { v = w->p[i][j]; if ( v < mins[j] ) { mins[j] = v; } if ( v > maxs[j] ) { maxs[j] = v; } } } } /* ============= WindingCenter ============= */ void WindingCenter( winding_t *w, vec3_t center ){ int i; float scale; VectorCopy( vec3_origin, center ); for ( i = 0 ; i < w->numpoints ; i++ ) VectorAdd( w->p[i], center, center ); scale = 1.0 / w->numpoints; VectorScale( center, scale, center ); } /* ================= BaseWindingForPlaneAccu ================= */ winding_accu_t *BaseWindingForPlaneAccu( vec3_t normal, vec_t dist ){ // The goal in this function is to replicate the behavior of the original BaseWindingForPlane() // function (see below) but at the same time increasing accuracy substantially. // The original code gave a preference for the vup vector to start out as (0, 0, 1), unless the // normal had a dominant Z value, in which case vup started out as (1, 0, 0). After that, vup // was "bent" [along the plane defined by normal and vup] to become perpendicular to normal. // After that the vright vector was computed as the cross product of vup and normal. // I'm constructing the winding polygon points in a fashion similar to the method used in the // original function. Orientation is the same. The size of the winding polygon, however, is // variable in this function (depending on the angle of normal), and is larger (by about a factor // of 2) than the winding polygon in the original function. int x, i; vec_t max, v; vec3_accu_t vright, vup, org, normalAccu; winding_accu_t *w; // One of the components of normal must have a magnitiude greater than this value, // otherwise normal is not a unit vector. This is a little bit of inexpensive // partial error checking we can do. max = 0.56; // 1 / sqrt(1^2 + 1^2 + 1^2) = 0.577350269 x = -1; for ( i = 0; i < 3; i++ ) { v = (vec_t) fabs( normal[i] ); if ( v > max ) { x = i; max = v; } } if ( x == -1 ) { Error( "BaseWindingForPlaneAccu: no dominant axis found because normal is too short" ); } switch ( x ) { case 0: // Fall through to next case. case 1: vright[0] = (vec_accu_t) -normal[1]; vright[1] = (vec_accu_t) normal[0]; vright[2] = 0; break; case 2: vright[0] = 0; vright[1] = (vec_accu_t) -normal[2]; vright[2] = (vec_accu_t) normal[1]; break; } // vright and normal are now perpendicular; you can prove this by taking their // dot product and seeing that it's always exactly 0 (with no error). // NOTE: vright is NOT a unit vector at this point. vright will have length // not exceeding 1.0. The minimum length that vright can achieve happens when, // for example, the Z and X components of the normal input vector are equal, // and when normal's Y component is zero. In that case Z and X of the normal // vector are both approximately 0.70711. The resulting vright vector in this // case will have a length of 0.70711. // We're relying on the fact that MAX_WORLD_COORD is a power of 2 to keep // our calculation precise and relatively free of floating point error. // [However, the code will still work fine if that's not the case.] VectorScaleAccu( vright, ( (vec_accu_t) MAX_WORLD_COORD ) * 4.0, vright ); // At time time of this writing, MAX_WORLD_COORD was 65536 (2^16). Therefore // the length of vright at this point is at least 185364. In comparison, a // corner of the world at location (65536, 65536, 65536) is distance 113512 // away from the origin. VectorCopyRegularToAccu( normal, normalAccu ); CrossProductAccu( normalAccu, vright, vup ); // vup now has length equal to that of vright. VectorScaleAccu( normalAccu, (vec_accu_t) dist, org ); // org is now a point on the plane defined by normal and dist. Furthermore, // org, vright, and vup are pairwise perpendicular. Now, the 4 vectors // { (+-)vright + (+-)vup } have length that is at least sqrt(185364^2 + 185364^2), // which is about 262144. That length lies outside the world, since the furthest // point in the world has distance 113512 from the origin as mentioned above. // Also, these 4 vectors are perpendicular to the org vector. So adding them // to org will only increase their length. Therefore the 4 points defined below // all lie outside of the world. Furthermore, it can be easily seen that the // edges connecting these 4 points (in the winding_accu_t below) lie completely // outside the world. sqrt(262144^2 + 262144^2)/2 = 185363, which is greater than // 113512. w = AllocWindingAccu( 4 ); VectorSubtractAccu( org, vright, w->p[0] ); VectorAddAccu( w->p[0], vup, w->p[0] ); VectorAddAccu( org, vright, w->p[1] ); VectorAddAccu( w->p[1], vup, w->p[1] ); VectorAddAccu( org, vright, w->p[2] ); VectorSubtractAccu( w->p[2], vup, w->p[2] ); VectorSubtractAccu( org, vright, w->p[3] ); VectorSubtractAccu( w->p[3], vup, w->p[3] ); w->numpoints = 4; return w; } /* ================= BaseWindingForPlane Original BaseWindingForPlane() function that has serious accuracy problems. Here is why. The base winding is computed as a rectangle with very large coordinates. These coordinates are in the range 2^17 or 2^18. "Epsilon" (meaning the distance between two adjacent numbers) at these magnitudes in 32 bit floating point world is about 0.02. So for example, if things go badly (by bad luck), then the whole plane could be shifted by 0.02 units (its distance could be off by that much). Then if we were to compute the winding of this plane and another of the brush's planes met this winding at a very acute angle, that error could multiply to around 0.1 or more when computing the final vertex coordinates of the winding. 0.1 is a very large error, and can lead to all sorts of disappearing triangle problems. ================= */ winding_t *BaseWindingForPlane( vec3_t normal, vec_t dist ){ int i, x; vec_t max, v; vec3_t org, vright, vup; winding_t *w; // find the major axis max = -BOGUS_RANGE; x = -1; for ( i = 0 ; i < 3; i++ ) { v = fabs( normal[i] ); if ( v > max ) { x = i; max = v; } } if ( x == -1 ) { Error( "BaseWindingForPlane: no axis found" ); } VectorCopy( vec3_origin, vup ); switch ( x ) { case 0: case 1: vup[2] = 1; break; case 2: vup[0] = 1; break; } v = DotProduct( vup, normal ); VectorMA( vup, -v, normal, vup ); VectorNormalize( vup, vup ); VectorScale( normal, dist, org ); CrossProduct( vup, normal, vright ); // LordHavoc: this has to use *2 because otherwise some created points may // be inside the world (think of a diagonal case), and any brush with such // points should be removed, failure to detect such cases is disasterous VectorScale( vup, MAX_WORLD_COORD * 2, vup ); VectorScale( vright, MAX_WORLD_COORD * 2, vright ); // project a really big axis aligned box onto the plane w = AllocWinding( 4 ); VectorSubtract( org, vright, w->p[0] ); VectorAdd( w->p[0], vup, w->p[0] ); VectorAdd( org, vright, w->p[1] ); VectorAdd( w->p[1], vup, w->p[1] ); VectorAdd( org, vright, w->p[2] ); VectorSubtract( w->p[2], vup, w->p[2] ); VectorSubtract( org, vright, w->p[3] ); VectorSubtract( w->p[3], vup, w->p[3] ); w->numpoints = 4; return w; } /* ================== CopyWinding ================== */ winding_t *CopyWinding( winding_t *w ){ int size; winding_t *c; if ( !w ) { Error( "CopyWinding: winding is NULL" ); } c = AllocWinding( w->numpoints ); size = sizeof( *w ) + sizeof( *w->p ) * w->numpoints; memcpy( c, w, size ); return c; } /* ================== CopyWindingAccuIncreaseSizeAndFreeOld ================== */ winding_accu_t *CopyWindingAccuIncreaseSizeAndFreeOld( winding_accu_t *w ){ int i; winding_accu_t *c; if ( !w ) { Error( "CopyWindingAccuIncreaseSizeAndFreeOld: winding is NULL" ); } c = AllocWindingAccu( w->numpoints + 1 ); c->numpoints = w->numpoints; for ( i = 0; i < c->numpoints; i++ ) { VectorCopyAccu( w->p[i], c->p[i] ); } FreeWindingAccu( w ); return c; } /* ================== CopyWindingAccuToRegular ================== */ winding_t *CopyWindingAccuToRegular( winding_accu_t *w ){ int i; winding_t *c; if ( !w ) { Error( "CopyWindingAccuToRegular: winding is NULL" ); } c = AllocWinding( w->numpoints ); c->numpoints = w->numpoints; for ( i = 0; i < c->numpoints; i++ ) { VectorCopyAccuToRegular( w->p[i], c->p[i] ); } return c; } /* ================== ReverseWinding ================== */ winding_t *ReverseWinding( winding_t *w ){ int i; winding_t *c; c = AllocWinding( w->numpoints ); for ( i = 0 ; i < w->numpoints ; i++ ) { VectorCopy( w->p[w->numpoints - 1 - i], c->p[i] ); } c->numpoints = w->numpoints; return c; } /* ============= ClipWindingEpsilon ============= */ void ClipWindingEpsilon( winding_t *in, vec3_t normal, vec_t dist, vec_t epsilon, winding_t **front, winding_t **back ){ vec_t dists[MAX_POINTS_ON_WINDING + 4]; int sides[MAX_POINTS_ON_WINDING + 4]; int counts[3]; static vec_t dot; // VC 4.2 optimizer bug if not static int i, j; vec_t *p1, *p2; vec3_t mid; winding_t *f, *b; int maxpts; counts[0] = counts[1] = counts[2] = 0; // determine sides for each point for ( i = 0 ; i < in->numpoints ; i++ ) { dot = DotProduct( in->p[i], normal ); dot -= dist; dists[i] = dot; if ( dot > epsilon ) { sides[i] = SIDE_FRONT; } else if ( dot < -epsilon ) { sides[i] = SIDE_BACK; } else { sides[i] = SIDE_ON; } counts[sides[i]]++; } sides[i] = sides[0]; dists[i] = dists[0]; *front = *back = NULL; if ( !counts[0] ) { *back = CopyWinding( in ); return; } if ( !counts[1] ) { *front = CopyWinding( in ); return; } maxpts = in->numpoints + 4; // cant use counts[0]+2 because // of fp grouping errors *front = f = AllocWinding( maxpts ); *back = b = AllocWinding( maxpts ); for ( i = 0 ; i < in->numpoints ; i++ ) { p1 = in->p[i]; if ( sides[i] == SIDE_ON ) { VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; VectorCopy( p1, b->p[b->numpoints] ); b->numpoints++; continue; } if ( sides[i] == SIDE_FRONT ) { VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; } if ( sides[i] == SIDE_BACK ) { VectorCopy( p1, b->p[b->numpoints] ); b->numpoints++; } if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { continue; } // generate a split point p2 = in->p[( i + 1 ) % in->numpoints]; dot = dists[i] / ( dists[i] - dists[i + 1] ); for ( j = 0 ; j < 3 ; j++ ) { // avoid round off error when possible if ( normal[j] == 1 ) { mid[j] = dist; } else if ( normal[j] == -1 ) { mid[j] = -dist; } else{ mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); } } VectorCopy( mid, f->p[f->numpoints] ); f->numpoints++; VectorCopy( mid, b->p[b->numpoints] ); b->numpoints++; } if ( f->numpoints > maxpts || b->numpoints > maxpts ) { Error( "ClipWinding: points exceeded estimate" ); } if ( f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING ) { Error( "ClipWinding: MAX_POINTS_ON_WINDING" ); } } /* ============= ChopWindingInPlaceAccu ============= */ void ChopWindingInPlaceAccu( winding_accu_t **inout, vec3_t normal, vec_t dist, vec_t crudeEpsilon ){ vec_accu_t fineEpsilon; winding_accu_t *in; int counts[3]; int i, j; vec_accu_t dists[MAX_POINTS_ON_WINDING + 1]; int sides[MAX_POINTS_ON_WINDING + 1]; int maxpts; winding_accu_t *f; vec_accu_t *p1, *p2; vec_accu_t w; vec3_accu_t mid, normalAccu; // We require at least a very small epsilon. It's a good idea for several reasons. // First, we will be dividing by a potentially very small distance below. We don't // want that distance to be too small; otherwise, things "blow up" with little accuracy // due to the division. (After a second look, the value w below is in range (0,1), but // graininess problem remains.) Second, Having minimum epsilon also prevents the following // situation. Say for example we have a perfect octagon defined by the input winding. // Say our chopping plane (defined by normal and dist) is essentially the same plane // that the octagon is sitting on. Well, due to rounding errors, it may be that point // 1 of the octagon might be in front, point 2 might be in back, point 3 might be in // front, point 4 might be in back, and so on. So we could end up with a very ugly- // looking chopped winding, and this might be undesirable, and would at least lead to // a possible exhaustion of MAX_POINTS_ON_WINDING. It's better to assume that points // very very close to the plane are on the plane, using an infinitesimal epsilon amount. // Now, the original ChopWindingInPlace() function used a vec_t-based winding_t. // So this minimum epsilon is quite similar to casting the higher resolution numbers to // the lower resolution and comparing them in the lower resolution mode. We explicitly // choose the minimum epsilon as something around the vec_t epsilon of one because we // want the resolution of vec_accu_t to have a large resolution around the epsilon. // Some of that leftover resolution even goes away after we scale to points far away. // Here is a further discussion regarding the choice of smallestEpsilonAllowed. // In the 32 float world (we can assume vec_t is that), the "epsilon around 1.0" is // 0.00000011921. In the 64 bit float world (we can assume vec_accu_t is that), the // "epsilon around 1.0" is 0.00000000000000022204. (By the way these two epsilons // are defined as VEC_SMALLEST_EPSILON_AROUND_ONE VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE // respectively.) If you divide the first by the second, you get approximately // 536,885,246. Dividing that number by 200,000 (a typical base winding coordinate) // gives 2684. So in other words, if our smallestEpsilonAllowed was chosen as exactly // VEC_SMALLEST_EPSILON_AROUND_ONE, you would be guaranteed at least 2000 "ticks" in // 64-bit land inside of the epsilon for all numbers we're dealing with. static const vec_accu_t smallestEpsilonAllowed = ( (vec_accu_t) VEC_SMALLEST_EPSILON_AROUND_ONE ) * 0.5; if ( crudeEpsilon < smallestEpsilonAllowed ) { fineEpsilon = smallestEpsilonAllowed; } else{fineEpsilon = (vec_accu_t) crudeEpsilon; } in = *inout; counts[0] = counts[1] = counts[2] = 0; VectorCopyRegularToAccu( normal, normalAccu ); for ( i = 0; i < in->numpoints; i++ ) { dists[i] = DotProductAccu( in->p[i], normalAccu ) - dist; if ( dists[i] > fineEpsilon ) { sides[i] = SIDE_FRONT; } else if ( dists[i] < -fineEpsilon ) { sides[i] = SIDE_BACK; } else{sides[i] = SIDE_ON; } counts[sides[i]]++; } sides[i] = sides[0]; dists[i] = dists[0]; // I'm wondering if whatever code that handles duplicate planes is robust enough // that we never get a case where two nearly equal planes result in 2 NULL windings // due to the 'if' statement below. TODO: Investigate this. if ( !counts[SIDE_FRONT] ) { FreeWindingAccu( in ); *inout = NULL; return; } if ( !counts[SIDE_BACK] ) { return; // Winding is unmodified. } // NOTE: The least number of points that a winding can have at this point is 2. // In that case, one point is SIDE_FRONT and the other is SIDE_BACK. maxpts = counts[SIDE_FRONT] + 2; // We dynamically expand if this is too small. f = AllocWindingAccu( maxpts ); for ( i = 0; i < in->numpoints; i++ ) { p1 = in->p[i]; if ( sides[i] == SIDE_ON || sides[i] == SIDE_FRONT ) { if ( f->numpoints >= MAX_POINTS_ON_WINDING ) { Error( "ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING" ); } if ( f->numpoints >= maxpts ) { // This will probably never happen. Sys_FPrintf( SYS_VRB, "WARNING: estimate on chopped winding size incorrect (no problem)\n" ); f = CopyWindingAccuIncreaseSizeAndFreeOld( f ); maxpts++; } VectorCopyAccu( p1, f->p[f->numpoints] ); f->numpoints++; if ( sides[i] == SIDE_ON ) { continue; } } if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { continue; } // Generate a split point. p2 = in->p[( ( i + 1 ) == in->numpoints ) ? 0 : ( i + 1 )]; // The divisor's absolute value is greater than the dividend's absolute value. // w is in the range (0,1). w = dists[i] / ( dists[i] - dists[i + 1] ); for ( j = 0; j < 3; j++ ) { // Avoid round-off error when possible. Check axis-aligned normal. if ( normal[j] == 1 ) { mid[j] = dist; } else if ( normal[j] == -1 ) { mid[j] = -dist; } else{mid[j] = p1[j] + ( w * ( p2[j] - p1[j] ) ); } } if ( f->numpoints >= MAX_POINTS_ON_WINDING ) { Error( "ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING" ); } if ( f->numpoints >= maxpts ) { // This will probably never happen. Sys_FPrintf( SYS_VRB, "WARNING: estimate on chopped winding size incorrect (no problem)\n" ); f = CopyWindingAccuIncreaseSizeAndFreeOld( f ); maxpts++; } VectorCopyAccu( mid, f->p[f->numpoints] ); f->numpoints++; } FreeWindingAccu( in ); *inout = f; } /* ============= ChopWindingInPlace ============= */ void ChopWindingInPlace( winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon ){ winding_t *in; vec_t dists[MAX_POINTS_ON_WINDING + 4]; int sides[MAX_POINTS_ON_WINDING + 4]; int counts[3]; static vec_t dot; // VC 4.2 optimizer bug if not static int i, j; vec_t *p1, *p2; vec3_t mid; winding_t *f; int maxpts; in = *inout; counts[0] = counts[1] = counts[2] = 0; // determine sides for each point for ( i = 0 ; i < in->numpoints ; i++ ) { dot = DotProduct( in->p[i], normal ); dot -= dist; dists[i] = dot; if ( dot > epsilon ) { sides[i] = SIDE_FRONT; } else if ( dot < -epsilon ) { sides[i] = SIDE_BACK; } else { sides[i] = SIDE_ON; } counts[sides[i]]++; } sides[i] = sides[0]; dists[i] = dists[0]; if ( !counts[0] ) { FreeWinding( in ); *inout = NULL; return; } if ( !counts[1] ) { return; // inout stays the same } maxpts = in->numpoints + 4; // cant use counts[0]+2 because // of fp grouping errors f = AllocWinding( maxpts ); for ( i = 0 ; i < in->numpoints ; i++ ) { p1 = in->p[i]; if ( sides[i] == SIDE_ON ) { VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; continue; } if ( sides[i] == SIDE_FRONT ) { VectorCopy( p1, f->p[f->numpoints] ); f->numpoints++; } if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { continue; } // generate a split point p2 = in->p[( i + 1 ) % in->numpoints]; dot = dists[i] / ( dists[i] - dists[i + 1] ); for ( j = 0 ; j < 3 ; j++ ) { // avoid round off error when possible if ( normal[j] == 1 ) { mid[j] = dist; } else if ( normal[j] == -1 ) { mid[j] = -dist; } else{ mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); } } VectorCopy( mid, f->p[f->numpoints] ); f->numpoints++; } if ( f->numpoints > maxpts ) { Error( "ClipWinding: points exceeded estimate" ); } if ( f->numpoints > MAX_POINTS_ON_WINDING ) { Error( "ClipWinding: MAX_POINTS_ON_WINDING" ); } FreeWinding( in ); *inout = f; } /* ================= ChopWinding Returns the fragment of in that is on the front side of the cliping plane. The original is freed. ================= */ winding_t *ChopWinding( winding_t *in, vec3_t normal, vec_t dist ){ winding_t *f, *b; ClipWindingEpsilon( in, normal, dist, ON_EPSILON, &f, &b ); FreeWinding( in ); if ( b ) { FreeWinding( b ); } return f; } /* ================= CheckWinding ================= */ void CheckWinding( winding_t *w ){ int i, j; vec_t *p1, *p2; vec_t d, edgedist; vec3_t dir, edgenormal, facenormal; vec_t area; vec_t facedist; if ( w->numpoints < 3 ) { Error( "CheckWinding: %i points",w->numpoints ); } area = WindingArea( w ); if ( area < 1 ) { Error( "CheckWinding: %f area", area ); } WindingPlane( w, facenormal, &facedist ); for ( i = 0 ; i < w->numpoints ; i++ ) { p1 = w->p[i]; for ( j = 0 ; j < 3 ; j++ ) if ( p1[j] > MAX_WORLD_COORD || p1[j] < MIN_WORLD_COORD ) { Error( "CheckFace: MAX_WORLD_COORD exceeded: %f",p1[j] ); } j = i + 1 == w->numpoints ? 0 : i + 1; // check the point is on the face plane d = DotProduct( p1, facenormal ) - facedist; if ( d < -ON_EPSILON || d > ON_EPSILON ) { Error( "CheckWinding: point off plane" ); } // check the edge isnt degenerate p2 = w->p[j]; VectorSubtract( p2, p1, dir ); if ( VectorLength( dir ) < ON_EPSILON ) { Error( "CheckWinding: degenerate edge" ); } CrossProduct( facenormal, dir, edgenormal ); VectorNormalize( edgenormal, edgenormal ); edgedist = DotProduct( p1, edgenormal ); edgedist += ON_EPSILON; // all other points must be on front side for ( j = 0 ; j < w->numpoints ; j++ ) { if ( j == i ) { continue; } d = DotProduct( w->p[j], edgenormal ); if ( d > edgedist ) { Error( "CheckWinding: non-convex" ); } } } } /* ============ WindingOnPlaneSide ============ */ int WindingOnPlaneSide( winding_t *w, vec3_t normal, vec_t dist ){ qboolean front, back; int i; vec_t d; front = qfalse; back = qfalse; for ( i = 0 ; i < w->numpoints ; i++ ) { d = DotProduct( w->p[i], normal ) - dist; if ( d < -ON_EPSILON ) { if ( front ) { return SIDE_CROSS; } back = qtrue; continue; } if ( d > ON_EPSILON ) { if ( back ) { return SIDE_CROSS; } front = qtrue; continue; } } if ( back ) { return SIDE_BACK; } if ( front ) { return SIDE_FRONT; } return SIDE_ON; } /* ================= AddWindingToConvexHull Both w and *hull are on the same plane ================= */ #define MAX_HULL_POINTS 128 void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal ) { int i, j, k; float *p, *copy; vec3_t dir; float d; int numHullPoints, numNew; vec3_t hullPoints[MAX_HULL_POINTS]; vec3_t newHullPoints[MAX_HULL_POINTS]; vec3_t hullDirs[MAX_HULL_POINTS]; qboolean hullSide[MAX_HULL_POINTS]; qboolean outside; if ( !*hull ) { *hull = CopyWinding( w ); return; } numHullPoints = ( *hull )->numpoints; memcpy( hullPoints, ( *hull )->p, numHullPoints * sizeof( vec3_t ) ); for ( i = 0 ; i < w->numpoints ; i++ ) { p = w->p[i]; // calculate hull side vectors for ( j = 0 ; j < numHullPoints ; j++ ) { k = ( j + 1 ) % numHullPoints; VectorSubtract( hullPoints[k], hullPoints[j], dir ); VectorNormalize( dir, dir ); CrossProduct( normal, dir, hullDirs[j] ); } outside = qfalse; for ( j = 0 ; j < numHullPoints ; j++ ) { VectorSubtract( p, hullPoints[j], dir ); d = DotProduct( dir, hullDirs[j] ); if ( d >= ON_EPSILON ) { outside = qtrue; } if ( d >= -ON_EPSILON ) { hullSide[j] = qtrue; } else { hullSide[j] = qfalse; } } // if the point is effectively inside, do nothing if ( !outside ) { continue; } // find the back side to front side transition for ( j = 0 ; j < numHullPoints ; j++ ) { if ( !hullSide[ j % numHullPoints ] && hullSide[ ( j + 1 ) % numHullPoints ] ) { break; } } if ( j == numHullPoints ) { continue; } // insert the point here VectorCopy( p, newHullPoints[0] ); numNew = 1; // copy over all points that aren't double fronts j = ( j + 1 ) % numHullPoints; for ( k = 0 ; k < numHullPoints ; k++ ) { if ( hullSide[ ( j + k ) % numHullPoints ] && hullSide[ ( j + k + 1 ) % numHullPoints ] ) { continue; } copy = hullPoints[ ( j + k + 1 ) % numHullPoints ]; VectorCopy( copy, newHullPoints[numNew] ); numNew++; } numHullPoints = numNew; memcpy( hullPoints, newHullPoints, numHullPoints * sizeof( vec3_t ) ); } FreeWinding( *hull ); w = AllocWinding( numHullPoints ); w->numpoints = numHullPoints; *hull = w; memcpy( w->p, hullPoints, numHullPoints * sizeof( vec3_t ) ); }
412
0.89812
1
0.89812
game-dev
MEDIA
0.181666
game-dev
0.994795
1
0.994795
SpongePowered/Sponge
2,736
src/main/java/org/spongepowered/common/registry/SpongeResourceKeyBuilder.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.registry; import net.minecraft.ResourceLocationException; import net.minecraft.resources.ResourceLocation; import org.spongepowered.api.ResourceKey; import org.spongepowered.common.util.Preconditions; import java.util.Objects; public final class SpongeResourceKeyBuilder implements ResourceKey.Builder { private String namespace; private String value; @Override public ResourceKey.Builder namespace(String namespace) { Objects.requireNonNull(namespace, "Namespace cannot be null"); this.namespace = namespace; return this; } @Override public ResourceKey.Builder value(String value) { Objects.requireNonNull(value, "Value cannot be null"); this.value = value; return this; } @Override public ResourceKey build() throws IllegalStateException { Preconditions.checkState(this.namespace != null, "Namespace cannot be empty"); Preconditions.checkState(this.value != null, "Value cannot be empty"); try { final ResourceLocation resourceLocation = ResourceLocation.fromNamespaceAndPath(this.namespace, this.value); return (ResourceKey) (Object) resourceLocation; } catch (ResourceLocationException e) { throw new IllegalStateException(e); } } @Override public ResourceKey.Builder reset() { this.namespace = null; this.value = null; return this; } }
412
0.617909
1
0.617909
game-dev
MEDIA
0.724784
game-dev
0.699706
1
0.699706
thindil/steamsky
48,915
src/ui/mapsui.nim
# Copyright 2023-2025 Bartek thindil Jasicki # # This file is part of Steam Sky. # # Steam Sky 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. # # Steam Sky 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 Steam Sky. If not, see <http://www.gnu.org/licenses/>. ## Provides code related to showing the main game's map, like drawing the map, ## updating movement buttons, etc. import std/[colors, os, parsecfg, streams, strutils, tables, unicode] import contracts import ../[bases, basestypes, config, game, log, maps, missions, statistics, stories, tk, types] import coreui, dialogs, errordialog, themes, updateheader, utilsui2 var mapView: string = ".gameframe.paned.mapframe.map" menuAccelerators*: array[1..11, string] = ["s", "o", "r", "m", "k", "w", "g", "F1", "p", "q", "x"] ## The game menu keyboard shortcuts mapAccelerators*: array[1..37, string] = ["e", "v", "plus", "minus", "KP_Home", "KP_Up", "KP_Prior", "KP_Left", "KP_Begin", "KP_Right", "KP_End", "KP_Down", "KP_Next", "KP_Divide", "Shift-Return", "Shift-h", "Shift-KP_Home", "Shift-KP_Up", "Shift-KP_Prior", "Shift-KP_Left", "Shift-KP_Right", "Shift-KP_End", "Shift-KP_Down", "Shift-KP_Next", "Control-KP_Home", "Control-KP_Up", "Control-KP_Prior", "Control-KP_Left", "Control-KP_Right", "Control-KP_End", "Control-KP_Down", "Control-KP_Next", "Control-Return", "Control-a", "Control-b", "Control-c", "Control-d"] ## The keyboard shortcuts used on the map fullScreenAccel*: string = "Control-f" ## Keyboard shortcut for toggle full screen defaultFontSizes*: array[3, Positive] = [10, 10, 10] ## The default sizes of fonts proc updateMoveButtons*() {.raises: [], tags: [], contractual.} = ## Update the player's ship movement buttons, depending on the state of the ## ship const moveButtonsNames: array[8, string] = ["nw", "n", "ne", "w", "e", "sw", "s", "se"] frameName: string = mainPaned & ".controls.buttons" speedBox: string = frameName & ".box.speed" var button: string = frameName & ".box.moveto" if playerShip.speed == docked: tclEval(script = "grid remove " & speedBox) tclEval(script = "grid remove " & button) button = frameName & ".wait" tclEval(script = button & " configure -image waiticon") tclEval(script = "tooltip::tooltip " & button & " \"Wait " & $gameSettings.waitMinutes & " minute" & (if gameSettings.waitMinutes > 1: "s" else: "") & ".\"") tclEval(script = "grid configure " & button & " -columnspan 3 -column 0 -row 1") for buttonName in moveButtonsNames: button = frameName & "." & buttonName tclEval(script = "grid remove " & button) else: tclEval(script = speedBox & " current " & $(playerShip.speed.ord - 1)) tclEval(script = "grid " & speedBox) if playerShip.destinationX > 0 and playerShip.destinationY > 0: button = frameName & ".box.moveto" tclEval(script = "grid " & button) tclEval(script = "grid configure " & speedBox) button = frameName & ".wait" tclEval(script = button & " configure -image movestepicon") tclEval(script = "tooltip::tooltip " & button & " \"Move ship one map field toward destination.\"") else: button = frameName & ".box.moveto" tclEval(script = "grid remove " & button) tclEval(script = "grid configure " & speedBox) button = frameName & ".wait" tclEval(script = button & " configure -image waiticon") tclEval(script = "tooltip::tooltip " & button & " \"" & ( if gameSettings.waitMinutes == 1: "Wait 1 minute." else: "Wait " & $gameSettings.waitMinutes & " minutes.") & "\"") tclEval(script = "grid configure " & button & " -columnspan 1 -column 1 -row 2") for index, name in moveButtonsNames: button = frameName & "." & name tclEval(script = "grid " & button) button = frameName & ".box.orders" if skyMap[playerShip.skyX][playerShip.skyY].eventIndex == -1 and skyMap[ playerShip.skyX][playerShip.skyY].baseIndex == 0: tclEval(script = "grid remove " & button) else: tclEval(script = "grid " & button) proc finishStory*() {.raises: [], tags: [WriteIOEffect, TimeEffect, RootEffect], contractual.} = ## Finish the current player's story. Give experience and ask about ## finishing the game gameStats.points += (10_000 * currentStory.maxSteps) clearCurrentStory() try: showQuestion(question = storiesList[currentStory.index].endText & " Do you want to finish the game?", res = "retire") except KeyError: showError(message = "Can't get the end text of the current story. Result: " & tclGetResult2()) proc showSkyMap*(clear: bool = false) {.raises: [], tags: [WriteIOEffect, TimeEffect, RootEffect], contractual.} = ## Show the sky map, draw the map, update the header, etc ## ## * clear - if true, remove the old subwindow and replace it with the one ## with the sky map tclSetVar(varName = "refreshmap", newValue = "1") if clear: showScreen(newScreenName = "mapframe") tclSetVar(varName = "gamestate", newValue = "general") updateHeader() if tclGetVar(varName = "refreshmap") == "1": tclEval(script = "DrawMap") updateMoveButtons() tclEval(script = "update") updateMessages() if playerShip.speed != docked: const speedBox: string = "$bframe.box.speed" tclEval(script = "bind " & speedBox & " <<ComboboxSelected>> {}") tclEval(script = speedBox & " current " & $(playerShip.speed.ord - 1)) tclEval(script = "bind " & speedBox & " <<ComboboxSelected>> {SetShipSpeed [" & speedBox & " current]}") if currentStory.index.len > 0 and currentStory.showText: if currentStory.currentStep > -2: try: showInfo(text = getCurrentStoryText(), title = "Story") except KeyError: showError(message = "Can't show the story text.") else: finishStory() if playerShip.crew[0].health == 0: showQuestion(question = "You are dead. Would you like to see your game statistics?", res = "showstats") currentStory.showText = true proc showMission(currentTheme: ThemeRecord; mType: MissionsTypes): tuple[icon, tag: string] {.raises: [], tags: [], contractual.} = ## Show the mission info on the map, based on the missions' type ## ## * mType - the type of the mission ## ## Returns the tuple with icon and text tag for the selected mission case mType of deliver: result.icon = currentTheme.deliverIcon result.tag = "yellow" of destroy: result.icon = currentTheme.destroyIcon result.tag = "red" of patrol: result.icon = currentTheme.patrolIcon result.tag = "lime" of explore: result.icon = currentTheme.exploreIcon result.tag = "green" of passenger: result.icon = currentTheme.passengerIcon result.tag = "cyan" var preview: bool = false proc drawMap*() {.raises: [], tags: [WriteIOEffect, TimeEffect, RootEffect], contractual.} = ## Draw the map on the screen preview = (if tclGetVar(varName = "mappreview").len > 0: true else: false) if preview and playerShip.speed != docked: tclUnsetVar(varName = "mappreview") preview = false tclEval(script = mapView & " configure -state normal") tclEval(script = mapView & " delete 1.0 end") let mapHeight: Positive = try: tclEval2(script = mapView & " cget -height").parseInt() except: showError(message = "Can't get map height.") return mapWidth: Positive = try: tclEval2(script = mapView & " cget -width").parseInt() except: showError(message = "Can't get map width.") return startX = centerX - (mapWidth / 2).int startY = centerY - (mapHeight / 2).int var endY: int = centerY + (mapHeight / 2).int endX: int = centerX + (mapWidth / 2).int storyX: int = 1 storyY: int = 1 if startY < 1: startY = 1 endY = mapHeight + 1 if startX < 1: startX = 1 endX = mapWidth + 1 if endY > 1_024: endY = 1_024 startY = 1_024 - mapHeight if endX > 1_024: endX = 1_024 startX = 1_025 - mapWidth if currentStory.index.len > 0: (storyX, storyY) = try: getStoryLocation() except: showError(message = "Can't get the current story location.") return if storyX == playerShip.skyX and storyY == playerShip.skyY: storyX = 0 storyY = 0 if playerShip.speed == docked and skyMap[playerShip.skyX][ playerShip.skyY].baseIndex == 0: playerShip.speed = fullStop let currentTheme: ThemeRecord = try: themesList[gameSettings.interfaceTheme] except: showError(message = "Can't get the curernt game's theme.") return for y in startY..endY: for x in startX..endX: var mapTag, mapChar: string = "" if x == playerShip.skyX and y == playerShip.skyY: mapChar = currentTheme.playerShipIcon else: mapChar = currentTheme.emptyMapIcon mapTag = (if skyMap[x][y].visited: "black" else: "unvisited gray") if x == playerShip.destinationX and y == playerShip.destinationY: mapChar = currentTheme.targetIcon mapTag = (if skyMap[x][y].visited: "" else: "unvisited") elif currentStory.index.len > 0 and (x == storyX and y == storyY): mapChar = currentTheme.storyIcon mapTag = "green" elif skyMap[x][y].missionIndex > -1: (mapChar, mapTag) = showMission(currentTheme = currentTheme, mType = acceptedMissions[skyMap[x][y].missionIndex].mType) if not skyMap[x][y].visited: mapTag &= " unvisited" elif skyMap[x][y].eventIndex > -1: if skyMap[x][y].eventIndex > eventsList.high: skyMap[x][y].eventIndex = -1 else: case eventsList[skyMap[x][y].eventIndex].eType of enemyShip: mapChar = currentTheme.enemyShipIcon mapTag = "red" of attackOnBase: mapChar = currentTheme.attackOnBaseIcon mapTag = "red2" of enemyPatrol: mapChar = currentTheme.enemyPatrolIcon mapTag = "red3" of disease: mapChar = currentTheme.diseaseIcon mapTag = "yellow" of fullDocks: mapChar = currentTheme.fullDocksIcon mapTag = "cyan" of doublePrice: mapChar = currentTheme.doublePriceIcon mapTag = "lime" of trader: mapChar = currentTheme.traderIcon mapTag = "green" of friendlyShip: mapChar = currentTheme.friendlyShipIcon mapTag = "green2" of EventsTypes.none, baseRecovery: discard if not skyMap[x][y].visited: mapTag &= " unvisited" elif skyMap[x][y].baseIndex > 0: mapChar = currentTheme.notVisitedBaseIcon if skyBases[skyMap[x][y].baseIndex].known: if skyBases[skyMap[x][y].baseIndex].visited.year > 0: mapChar = try: factionsList[skyBases[skyMap[x][ y].baseIndex].owner].baseIcon.Rune.toUTF8 except: showError(message = "Can't get the base icon.") return mapTag = skyBases[skyMap[x][y].baseIndex].baseType else: mapTag = "unvisited" else: mapTag = "unvisited gray" if preview: for mission in skyBases[skyMap[playerShip.skyX][ playerShip.skyY].baseIndex].missions: if mission.targetX == x and mission.targetY == y: (mapChar, mapTag) = showMission(currentTheme = currentTheme, mType = mission.mType) if not skyMap[x][y].visited: mapTag &= " unvisited" break tclEval(script = mapView & " insert end {" & mapChar & "} [list " & mapTag & "]") if y < endY: tclEval(script = mapView & " insert end {\n}") tclEval(script = mapView & " configure -state disable") proc updateMapInfo*(x: Positive = playerShip.skyX; y: Positive = playerShip.skyY) {.raises: [], tags: [WriteIOEffect, TimeEffect, RootEffect], contractual.} = ## Update frame with information about the map cell on which the player ## currently points. ## ## * x - the X coordinate of the map's cell ## * y - the Y coordinate of the map's cell const mapInfo: string = mainPaned & ".mapframe.info" tclEval(script = mapInfo & " configure -state normal") tclEval(script = mapInfo & " delete 1.0 end") var width: int = 1 proc insertText(newText: string; tagName: string = "") {.raises: [], tags: [], contractual.} = ## Insert a text into the map info ## ## newText - the text to insert ## tagName - the text's tag to add to the text in the info widget if newText.len > width: width = newText.len if width > 21: width = 21 tclEval(script = mapInfo & " insert end {" & newText & "}" & ( if tagName.len == 0: "" else: " [list " & tagName & "]")) insertText(newText = "X:") insertText(newText = " " & $x, tagName = "yellow2") insertText(newText = " Y:") insertText(newText = " " & $y, tagName = "yellow2") if playerShip.skyX != x or playerShip.skyY != y: let distance: Natural = countDistance(destinationX = x, destinationY = y) travelValues: TravelArray = travelInfo(distance = distance) insertText(newText = "\nDistance: ") insertText(newText = $distance, tagName = "yellow2") if travelValues[1] > 0: insertText(newText = "\nETA:") var distanceText: string = "" minutesToDate(minutes = travelValues[1], infoText = distanceText) insertText(newText = distanceText, tagName = "yellow2") insertText(newText = "\nApprox fuel usage: ") insertText(newText = $travelValues[2], tagName = "yellow2") if skyMap[x][y].baseIndex > 0: let baseIndex: Positive = skyMap[x][y].baseIndex if skyBases[baseIndex].known: insertText(newText = "\nBase info:", tagName = "pink underline") insertText(newText = "\nName: ") insertText(newText = skyBases[baseIndex].name, tagName = "yellow2") if skyBases[baseIndex].visited.year > 0: try: discard tclEval(script = mapInfo & " tag configure basetype -foreground " & $basesTypesList[skyBases[ baseIndex].baseType].color) except: showError(message = "Can't get the color of the base's type.") return insertText(newText = "\nType: ") try: insertText(newText = basesTypesList[skyBases[baseIndex].baseType].name, tagName = "basetype") except: showError(message = "Can't get the name of the base's type.") return let population: BasePopulation = getBasePopulation(baseIndex = baseIndex) if population > empty: insertText(newText = "\nPopulation: ") insertText(newText = $population, tagName = "yellow2") insertText(newText = "\nSize: ") insertText(newText = $skyBases[baseIndex].size & "\n", tagName = "yellow2") if population > empty: insertText(newText = "Owner: ") try: insertText(newText = factionsList[skyBases[baseIndex].owner].name, tagName = "yellow2") except: showError(message = "Can't get the name of the owner's faction.") return else: insertText(newText = "Base is abandoned") if population > empty: var baseInfoText: string = "\n" color: string = "" case skyBases[baseIndex].reputation.level of -100.. -75: baseInfoText &= "You are hated here" color = "red" of -74.. -50: baseInfoText &= "You are outlawed here" color = "red" of -49.. -25: baseInfoText &= "You are disliked here" color = "red" of -24.. -1: baseInfoText &= "They are unfriendly to you" color = "red" of 0: baseInfoText &= "You are unknown here" of 1..25: baseInfoText &= "You are know here as visitor" color = "green" of 26..50: baseInfoText &= "You are know here as trader" color = "green" of 51..75: baseInfoText &= "You are know here as friend" color = "green" of 76..100: baseInfoText &= "You are well known here" color = "green" insertText(newText = baseInfoText, tagName = color) if baseIndex == playerShip.homeBase: insertText(newText = "\nIt is your home base", tagName = "cyan") if skyMap[x][y].missionIndex > -1: var missionInfoText: string = "\n" if skyMap[x][y].baseIndex > 0 or skyMap[x][y].eventIndex > -1: missionInfoText &= "\n" let missionIndex: int = skyMap[x][y].missionIndex case acceptedMissions[missionIndex].mType of deliver: try: missionInfoText &= "Deliver " & itemsList[ acceptedMissions[missionIndex].itemIndex].name except: showError(message = "Can't get the name of the item to deliver.") return of destroy: try: missionInfoText &= "Destroy " & protoShipsList[ acceptedMissions[missionIndex].shipIndex].name except: showError(message = "Can't get the name of the ship to destroy.") return of patrol: missionInfoText &= "Patrol area" of explore: missionInfoText &= "Explore area" of passenger: missionInfoText &= "Transport passenger" insertText(newText = missionInfoText) if preview: for mission in skyBases[skyMap[playerShip.skyX][ playerShip.skyY].baseIndex].missions: if mission.targetX == x and mission.targetY == y: var missionInfoText: string = "\n" if skyMap[x][y].baseIndex > 0 or skyMap[x][y].eventIndex > -1: missionInfoText &= "\n" case mission.mType of deliver: try: missionInfoText &= "Deliver " & itemsList[mission.itemIndex].name except: showError(message = "Can't get the name of the item to deliver.") return of destroy: try: missionInfoText &= "Destroy " & protoShipsList[ mission.shipIndex].name except: showError(message = "Can't get the name of the ship to destroy.") return of patrol: missionInfoText &= "Patrol area" of explore: missionInfoText &= "Explore area" of passenger: missionInfoText &= "Transport passenger" insertText(newText = missionInfoText) if currentStory.index.len > 0: var storyX, storyY: Natural = 1 try: (storyX, storyY) = getStoryLocation() except: showError(message = "Can't get the location of the current story.") return if storyX == playerShip.skyX and storyY == playerShip.skyY: storyX = 0 storyY = 0 var finishCondition: StepConditionType = any if y == storyX and y == storyY: try: finishCondition = (if currentStory.currentStep == 0: storiesList[ currentStory.index].startingStep.finishCondition elif currentStory.currentStep > 0: storiesList[currentStory.index].steps[ currentStory.currentStep].finishCondition else: storiesList[ currentStory.index].finalStep.finishCondition) if finishCondition in {askInBase, destroyShip, explore}: insertText(newText = "\nStory leads you here") except: showError(message = "Can't get the finish condition of the current story.") return if x == playerShip.skyX and y == playerShip.skyY: insertText(newText = "\nYou are here", tagName = "yellow") if skyMap[x][y].eventIndex > -1: let eventIndex: Natural = skyMap[x][y].eventIndex var eventInfoText: string = "" if eventsList[eventIndex].eType notin {baseRecovery, EventsTypes.none}: eventInfoText = "\n\n" var color: string = "" case eventsList[eventIndex].eType of trader: try: eventInfoText &= protoShipsList[eventsList[ eventIndex].shipIndex].name except: showError(message = "Can't get the name of the trader's ship for the event.") return color = "green" of friendlyShip: try: eventInfoText &= protoShipsList[eventsList[ eventIndex].shipIndex].name except: showError(message = "Can't get the name of the friendly ship for the event.") return color = "green2" of enemyShip: try: eventInfoText &= protoShipsList[eventsList[ eventIndex].shipIndex].name except: showError(message = "Can't get the name of the enemy's ship for the event.") return color = "red" of fullDocks: eventInfoText &= "Full docks in base" color = "cyan" of attackOnBase: eventInfoText &= "Base is under attack" color = "red" of disease: eventInfoText &= "Disease in base" color = "yellow" of enemyPatrol: eventInfoText &= "Enemy patrol" color = "red3" of doublePrice: try: eventInfoText &= "Double price for " & itemsList[ eventsList[eventIndex].itemIndex].name except: showError(message = "Can't get the name of the item for the event.") return color = "lime" of EventsTypes.none, baseRecovery: discard insertText(newText = eventInfoText, tagName = color) tclEval(script = mapInfo & " configure -state disabled -width " & $width & " -height " & tclEval2(script = mapInfo & " count -displaylines 0.0 end")) proc setKeys*() {.raises: [], tags: [], contractual.} = ## Set the keyboard shortcuts for the map const tclCommandsArray: array[37, string] = [ "{if {[winfo class [focus]] != {TEntry} && [tk busy status " & gameHeader & "] == 0} {ShowGameMenu}}", "{" & mainPaned & ".mapframe.buttons.wait invoke}", "{ZoomMap raise}", "{ZoomMap lower}", "{InvokeButton $bframe.nw}", "{InvokeButton $bframe.n}", "{InvokeButton $bframe.ne}", "{InvokeButton $bframe.w}", "{InvokeButton $bframe.wait}", "{InvokeButton $bframe.e}", "{InvokeButton $bframe.sw}", "{InvokeButton $bframe.s}", "{InvokeButton $bframe.se}", "{InvokeButton $bframe.box.moveto}", "{MoveMap centeronship}", "{MoveMap centeronhome}", "{MoveMap nw}", "{MoveMap n}", "{MoveMap ne}", "{MoveMap w}", "{MoveMap e}", "{MoveMap sw}", "{MoveMap s}", "{MoveMap se}", "{MoveCursor nw %x %y}", "{MoveCursor n %x %y}", "{MoveCursor ne %x %y}", "{MoveCursor w %x %y}", "{MoveCursor e %x %y}", "{MoveCursor sw %x %y}", "{MoveCursor s %x %y}", "{MoveCursor se %x %y}", "{MoveCursor click %x %y}", "{" & mainPaned & ".controls.buttons.box.speed current 0}", "{" & mainPaned & ".controls.buttons.box.speed current 1}", "{" & mainPaned & ".controls.buttons.box.speed current 2}", "{" & mainPaned & ".controls.buttons.box.speed current 3}"] for index, command in tclCommandsArray: var pos: int = mapAccelerators[index + 1].rfind(sub = '-') keyName: string = "" if pos > -1: keyName = mapAccelerators[index + 1][0..pos] & "KeyPress-" & mapAccelerators[index + 1][pos + 1 .. ^1] else: keyName = "KeyPress-" & mapAccelerators[index + 1] tclEval(script = "bind . <" & keyName & "> " & command) var pos: int = fullScreenAccel.rfind(sub = '-') keyName: string = "" if pos > -1: keyName = fullScreenAccel[0..pos] & "KeyPress-" & fullScreenAccel[pos + 1 .. ^1] else: keyName = "KeyPress-" & fullScreenAccel tclEval(script = "bind . <" & keyName & "> {ToggleFullScreen}") import basesui, baseslootui, basesrecruitui, basesschoolui, basesshipyardui, craftsui, debugui, gameoptions, helpui, knowledge, mapsuicommands, messagesui, missionsui, ordersmenu, shipsui, statisticsui, tradesui, waitmenu proc createGameUi*() {.raises: [], tags: [WriteIOEffect, TimeEffect, RootEffect, ReadIOEffect, RootEffect], contractual.} = ## Create the game UI and show sky map to the player const gameFrame: string = ".gameframe" paned: string = gameFrame & ".paned" mapView = paned & ".mapframe.map" var newStart: bool = false if tclEval2(script = "winfo exists " & mapView) == "0": newStart = true let fileName: string = saveDirectory & "keys.cfg" var configFile: FileStream = newFileStream(filename = fileName) if configFile == nil: if DirSep == '\\': mapAccelerators[5] = "Home" mapAccelerators[6] = "Up" mapAccelerators[7] = "Prior" mapAccelerators[8] = "Left" mapAccelerators[9] = "Clear" mapAccelerators[10] = "Right" mapAccelerators[11] = "End" mapAccelerators[12] = "Down" mapAccelerators[13] = "Next" mapAccelerators[14] = "slash" mapAccelerators[17] = "Shift-Home" mapAccelerators[18] = "Shift-Up" mapAccelerators[19] = "Shift-Prior" mapAccelerators[20] = "Shift-Left" mapAccelerators[21] = "Shift-Right" mapAccelerators[22] = "Shift-End" mapAccelerators[23] = "Shift-Down" mapAccelerators[24] = "Shift-Next" mapAccelerators[25] = "Control-Home" mapAccelerators[26] = "Control-Up" mapAccelerators[27] = "Control-Prior" mapAccelerators[28] = "Control-Left" mapAccelerators[29] = "Control-Right" mapAccelerators[30] = "Control-End" mapAccelerators[31] = "Control-Down" mapAccelerators[32] = "Control-Next" else: var parser: CfgParser = CfgParser() try: parser.open(input = configFile, filename = fileName) except: showError(message = "Can't open the shortcut's configuration file.") return while true: var entry: CfgEvent = try: parser.next except: showError(message = "Can't get next shortcut setting.") return case entry.kind of cfgEof: break of cfgSectionStart, cfgOption: discard of cfgKeyValuePair: case entry.key of "ShipInfo": menuAccelerators[1] = entry.value of "Orders": menuAccelerators[2] = entry.value of "Crafting": menuAccelerators[3] = entry.value of "LastMessages": menuAccelerators[4] = entry.value of "Knowledge": menuAccelerators[5] = entry.value of "WaitOrders": menuAccelerators[6] = entry.value of "GameStats": menuAccelerators[7] = entry.value of "Help": menuAccelerators[8] = entry.value of "GameOptions": menuAccelerators[9] = entry.value of "Quit": menuAccelerators[10] = entry.value of "Resign": menuAccelerators[11] = entry.value of "GameMenu": mapAccelerators[1] = entry.value of "MapOptions": mapAccelerators[2] = entry.value of "ZoomInMap": mapAccelerators[3] = entry.value of "ZoomOutMap": mapAccelerators[4] = entry.value of "MoveUpLeft": mapAccelerators[5] = entry.value of "MoveUp": mapAccelerators[6] = entry.value of "MoveUpRight": mapAccelerators[7] = entry.value of "MoveLeft": mapAccelerators[8] = entry.value of "WaitInPlace": mapAccelerators[10] = entry.value of "MoveRight": mapAccelerators[9] = entry.value of "MoveDownLeft": mapAccelerators[11] = entry.value of "MoveDown": mapAccelerators[12] = entry.value of "MoveDownRight": mapAccelerators[13] = entry.value of "MoveTo": mapAccelerators[14] = entry.value of "CenterMap": mapAccelerators[15] = entry.value of "CenterMapOnHomeBase": mapAccelerators[16] = entry.value of "MoveMapUpLeft": mapAccelerators[17] = entry.value of "MoveMapUp": mapAccelerators[18] = entry.value of "MoveMapUpRight": mapAccelerators[19] = entry.value of "MoveMapLeft": mapAccelerators[20] = entry.value of "MoveMapRight": mapAccelerators[21] = entry.value of "MoveMapDownLeft": mapAccelerators[22] = entry.value of "MoveMapDown": mapAccelerators[23] = entry.value of "MoveMapDownRight": mapAccelerators[24] = entry.value of "MoveCursorUpLeft": mapAccelerators[25] = entry.value of "MoveCursorUp": mapAccelerators[26] = entry.value of "MoveCursorUpRight": mapAccelerators[27] = entry.value of "MoveCursorLeft": mapAccelerators[28] = entry.value of "MoveCursorRight": mapAccelerators[29] = entry.value of "MoveCursorDownLeft": mapAccelerators[30] = entry.value of "MoveCursorDown": mapAccelerators[31] = entry.value of "MoveCursorDownRight": mapAccelerators[32] = entry.value of "LeftClickMouse": mapAccelerators[33] = entry.value of "FullStop": mapAccelerators[34] = entry.value of "QuarterSpeed": mapAccelerators[35] = entry.value of "HalfSpeed": mapAccelerators[36] = entry.value of "FullSpeed": mapAccelerators[37] = entry.value of "FullScreen": fullScreenAccel = entry.value of cfgError: showError(message = "Can't set keyboard shortcuts. Message: " & entry.msg) try: parser.close() except: showError(message = "Can't close the shortcuts' configuration file.") return mapsuicommands.addCommands() tclEval(script = """ pack [ttk::frame .gameframe -style Main.TFrame] -fill both -expand true # Game header ttk::frame .gameframe.header grid [ttk::button .gameframe.header.menubutton -style Small.TButton \ -command ShowGameMenu] -sticky w tooltip::tooltip .gameframe.header.menubutton \ "The main game menu. Show info about the ships,\nits crew and allow to quit the game" ttk::button .gameframe.header.closebutton -style Small.TButton \ -command {ShowSkyMap} tooltip::tooltip .gameframe.header.closebutton {Back to the game map [Escape key]} ttk::button .gameframe.header.morebutton -style Small.TButton \ -command {ShowMore} tooltip::tooltip .gameframe.header.morebutton {Show more options} grid [ttk::label .gameframe.header.time -text {1600-03-01}] -row 0 -column 3 tooltip::tooltip .gameframe.header.time {The game time} grid columnconfigure .gameframe.header .gameframe.header.time -weight 1 grid [ttk::label .gameframe.header.fuel] -row 0 -column 4 -padx 3 grid [ttk::label .gameframe.header.food] -row 0 -column 5 -padx 3 grid [ttk::label .gameframe.header.drinks] -row 0 -column 6 -padx 3 grid [ttk::label .gameframe.header.overloaded] -row 0 -column 7 -padx 3 grid [ttk::label .gameframe.header.pilot] -row 0 -column 8 -padx 3 grid [ttk::label .gameframe.header.engineer] -row 0 -column 9 -padx 3 grid [ttk::label .gameframe.header.gunner] -row 0 -column 10 -padx 3 grid [ttk::label .gameframe.header.talk] -row 0 -column 11 -padx 3 grid [ttk::label .gameframe.header.repairs] -row 0 -column 12 -padx 3 grid [ttk::label .gameframe.header.upgrade] -row 0 -column 13 -padx 3 grid [ttk::label .gameframe.header.clean] -row 0 -column 14 -padx 3 grid [ttk::label .gameframe.header.crafting] -row 0 -column 15 -padx 3 grid .gameframe.header -sticky we -padx 5 -pady {5 0} ttk::panedwindow .gameframe.paned # Game map .gameframe.paned add [ttk::frame .gameframe.paned.mapframe] set mapview [text .gameframe.paned.mapframe.map \ -bg [set ttk::theme::[ttk::style theme use]::colors(-black)] -wrap none \ -fg white -font MapFont -cursor crosshair -bd 0] grid $mapview -sticky nwes $mapview tag configure unvisited -background [ttk::style lookup Map -unvisited] $mapview tag configure yellow -foreground [ttk::style lookup Map -yellow] $mapview tag configure green -foreground [ttk::style lookup Map -green] $mapview tag configure red -foreground [ttk::style lookup Map -red] $mapview tag configure cyan -foreground [ttk::style lookup Map -cyan] $mapview tag configure lime -foreground [ttk::style lookup Map -lime] $mapview tag configure red2 -foreground [ttk::style lookup Map -red2] $mapview tag configure red3 -foreground [ttk::style lookup Map -red3] $mapview tag configure green2 -foreground [ttk::style lookup Map -green2] $mapview tag configure gray -foreground [ttk::style lookup Map -gray] $mapview tag configure black -foreground [ttk::style lookup Map -black] proc ValidateSpinbox {widget value button} { if {$value == ""} { if {$button != ""} { $button configure -state disabled } return true } if {$button != ""} { $button configure -state normal } set newvalue [regsub -all {[^0-9]} $value {}] set minvalue [$widget cget -from] if {$newvalue == ""} { $widget set $minvalue return false } if {$newvalue < $minvalue} { $widget set $minvalue return true } set maxvalue [$widget cget -to] if {$newvalue > $maxvalue} { $widget set $maxvalue return true } $widget set $newvalue $widget icursor end return true } # Move map buttons set mframe [ttk::frame .gameframe.paned.mapframe.buttons] grid [ttk::button $mframe.show -style Toolbutton -command ShowMapButtons] \ -columnspan 5 -sticky we tooltip::tooltip $mframe.show {Show the map manipulation buttons} grid [ttk::button $mframe.left -style Map.Toolbutton \ -command {MoveMapButtons left}] -rowspan 3 -row 1 -column 0 -sticky ns tooltip::tooltip $mframe.left {Move map buttons to the left corner} grid [ttk::button $mframe.nw -style Map.Toolbutton -command {MoveMap nw}] \ -row 1 -column 1 tooltip::tooltip $mframe.nw {Move map up and left} grid [ttk::button $mframe.n -style Map.Toolbutton -command {MoveMap n}] \ -column 2 -row 1 tooltip::tooltip $mframe.n {Move map up} grid [ttk::button $mframe.ne -style Map.Toolbutton -command {MoveMap ne}] \ -column 3 -row 1 tooltip::tooltip $mframe.ne {Move map up and right} grid [ttk::button $mframe.right -style Map.Toolbutton \ -command {MoveMapButtons right}] -rowspan 3 -row 1 -column 4 -sticky ns tooltip::tooltip $mframe.right {Move map buttons to the right corner} grid [ttk::button $mframe.w -style Map.Toolbutton -command {MoveMap w}] \ -row 2 -column 1 tooltip::tooltip $mframe.w {Move map left} grid [ttk::button $mframe.wait -style Map.Toolbutton -command { if {[winfo ismapped .gameframe.paned.mapframe] == "0"} { return } if {[winfo exists .gameframe.movemapdialog]} { CloseDialog .gameframe.movemapdialog return } tk busy .gameframe.header tk busy .gameframe.paned ttk::frame .gameframe.movemapdialog -style Dialog.TFrame grid [ttk::label .gameframe.movemapdialog.header -text {Move map} \ -style Header.TLabel] -sticky we -columnspan 2 grid [ttk::label .gameframe.movemapdialog.xlabel -text X: -takefocus 0] \ -pady {5 0} grid [ttk::spinbox .gameframe.movemapdialog.x -from 1 -to 1024 \ -validate key \ -validatecommand {ValidateSpinbox %W %P .gameframe.movemapdialog.moveto} \ -width 5] -row 1 -column 1 -pady {5 0} .gameframe.movemapdialog.x set 1 grid [ttk::label .gameframe.movemapdialog.ylabel -text Y: -takefocus 0] \ -row 2 grid [ttk::spinbox .gameframe.movemapdialog.y -from 1 -to 1024 \ -validate key \ -validatecommand {ValidateSpinbox %W %P .gameframe.movemapdialog.moveto} \ -width 5] -row 2 -column 1 .gameframe.movemapdialog.y set 1 grid [ttk::button .gameframe.movemapdialog.moveto \ -text {Move map to selected location} -command {MoveMap movemapto} \ -underline 0] -row 3 -columnspan 2 -sticky we -padx 5 grid [ttk::button .gameframe.movemapdialog.centeronship \ -text {Center map on ship} -command {MoveMap centeronship} -underline 0] \ -row 4 -columnspan 2 -sticky we -padx 5 grid [ttk::button .gameframe.movemapdialog.centeronhome \ -text {Center map on home base} -command {MoveMap centeronhome} \ -underline 1] -row 5 -columnspan 2 -sticky we -padx 5 grid [ttk::button .gameframe.movemapdialog.close -text {Close} \ -command {CloseDialog .gameframe.movemapdialog}] -row 6 -columnspan 2 \ -sticky we -padx 5 -pady {0 5} place .gameframe.movemapdialog -in .gameframe -relx 0.3 -rely 0.25 focus .gameframe.movemapdialog.close foreach widget [winfo children .gameframe.movemapdialog] { bind $widget <Alt-m> {.gameframe.movemapdialog.moveto invoke;break} bind $widget <Alt-c> {.gameframe.movemapdialog.centeronship invoke;break} bind $widget <Alt-e> {.gameframe.movemapdialog.centeronhome invoke;break} bind $widget <Escape> {.gameframe.movemapdialog.close invoke;break} } bind .gameframe.movemapdialog.close <Tab> \ {focus .gameframe.movemapdialog.x;break} }] -column 2 -row 2 tooltip::tooltip $mframe.wait {Show more the map's options} grid [ttk::button $mframe.e -style Map.Toolbutton -command {MoveMap e}] \ -column 3 -row 2 tooltip::tooltip $mframe.e {Move map right} grid [ttk::button $mframe.sw -style Map.Toolbutton -command {MoveMap sw}] \ -row 3 -column 1 tooltip::tooltip $mframe.sw {Move map down and left} grid [ttk::button $mframe.s -style Map.Toolbutton -command {MoveMap s}] \ -column 2 -row 3 tooltip::tooltip $mframe.s {Move map down} grid [ttk::button $mframe.se -style Map.Toolbutton -command {MoveMap se}] \ -column 3 -row 3 tooltip::tooltip $mframe.se {Move map down and right} grid [ttk::button $mframe.hide -style Map.Toolbutton -command HideMapButtons] \ -columnspan 5 -row 4 -sticky we tooltip::tooltip $mframe.hide {Hide the map manipulation buttons} grid $mframe -row 0 -column 0 -sticky se # Map info frame set mapinfo [text .gameframe.paned.mapframe.info -wrap word -height 10 \ -width 20 -background [ttk::style lookup MapInfo -background] \ -relief ridge -borderwidth 3 -padx 5] $mapinfo tag configure yellow -foreground [ttk::style lookup Map -yellow] $mapinfo tag configure green -foreground [ttk::style lookup Map -green] $mapinfo tag configure red -foreground [ttk::style lookup Map -red] $mapinfo tag configure cyan -foreground [ttk::style lookup Map -cyan] $mapinfo tag configure lime -foreground [ttk::style lookup Map -lime] $mapinfo tag configure red2 -foreground [ttk::style lookup Map -red2] $mapinfo tag configure red3 -foreground [ttk::style lookup Map -red3] $mapinfo tag configure green2 -foreground [ttk::style lookup Map -green2] $mapinfo tag configure pink -foreground [ttk::style lookup Map -pink] $mapinfo tag configure yellow2 -foreground [ttk::style lookup Map -goldenyellow] $mapinfo tag configure underline -font UnderlineFont grid $mapinfo -column 0 -row 0 -sticky ne bind .gameframe.paned.mapframe.info <Enter> MoveMapInfo grid rowconfigure .gameframe.paned.mapframe 0 -weight 1 grid columnconfigure .gameframe.paned.mapframe 0 -weight 1 # Last messages .gameframe.paned add [ttk::frame .gameframe.paned.controls] grid [ttk::frame .gameframe.paned.controls.messages -style LastMessages.TFrame] \ -sticky we pack [ttk::scrollbar .gameframe.paned.controls.messages.scroll -orient vertical \ -command [list .gameframe.paned.controls.messages.view yview]] -side right \ -fill y -padx {0 5} -pady 5 set messagesview [text .gameframe.paned.controls.messages.view -wrap word \ -yscrollcommand [list .gameframe.paned.controls.messages.scroll set]] $messagesview tag configure yellow -foreground \ [ttk::style lookup Messages -yellow] $messagesview tag configure green -foreground \ [ttk::style lookup Messages -green] $messagesview tag configure red -foreground \ [ttk::style lookup Messages -red] $messagesview tag configure cyan -foreground \ [ttk::style lookup Messages -cyan] $messagesview tag configure blue -foreground \ [ttk::style lookup Messages -blue] $messagesview tag configure gray -foreground \ [ttk::style lookup Messages -gray] pack $messagesview -side top -fill both -padx 5 -pady 5 tooltip::tooltip $messagesview \ "The last game messages. You can see more of them\nIn Menu->Last messages screen" ::autoscroll::autoscroll .gameframe.paned.controls.messages.scroll bind .gameframe.paned.controls <Configure> { $messagesview configure -height [expr \ [winfo height .gameframe.paned.controls] / [font metrics InterfaceFont \ -linespace]] } # Movement buttons set bframe [ttk::frame .gameframe.paned.controls.buttons] grid $bframe -row 0 -column 1 -sticky nw grid [ttk::frame $bframe.box] -columnspan 3 -sticky we grid [ttk::button $bframe.box.orders -command {ShowOrders} -text {Ship Orders}] tooltip::tooltip $bframe.box.orders "Show available orders for your ship." grid [ttk::combobox $bframe.box.speed -state readonly -values [list {Full stop} \ {Quarted speed} {Half speed} {Full speed}] -width 10] -sticky we tooltip::tooltip $bframe.box.speed \ "Set speed for your ship. The faster you move,\nthe more fuel used. But faster movement has\nbigger chance to evade enemies." grid [ttk::button $bframe.box.moveto -command {MoveShip moveto} \ -style Move.TButton] -row 0 -column 1 tooltip::tooltip $bframe.box.moveto "Auto move your ship to its destination" grid [ttk::button $bframe.nw -command {MoveShip nw} -style Move.TButton] \ -row 1 -sticky we tooltip::tooltip $bframe.nw "Move ship up and left" grid [ttk::button $bframe.n -command {MoveShip n} -style Move.TButton] \ -column 1 -row 1 -sticky we tooltip::tooltip $bframe.n "Move ship up" grid [ttk::button $bframe.ne -command {MoveShip ne} -style Move.TButton] \ -column 2 -row 1 -sticky we tooltip::tooltip $bframe.ne "Move ship up and right" grid [ttk::button $bframe.w -command {MoveShip w} -style Move.TButton] -row 2 \ -sticky we tooltip::tooltip $bframe.w "Move ship left" grid [ttk::button $bframe.wait -command {MoveShip waitormove} \ -style Move.TButton] -column 1 -row 2 -sticky we grid [ttk::button $bframe.e -command {MoveShip e} -style Move.TButton] \ -column 2 -row 2 -sticky we tooltip::tooltip $bframe.e "Move ship right" grid [ttk::button $bframe.sw -command {MoveShip sw} -style Move.TButton] \ -row 3 -sticky we tooltip::tooltip $bframe.sw "Move ship down and left" grid [ttk::button $bframe.s -command {MoveShip s} -style Move.TButton] \ -column 1 -row 3 -sticky we tooltip::tooltip $bframe.s "Move ship down" grid [ttk::button $bframe.se -command {MoveShip se} -style Move.TButton] \ -column 2 -row 3 -sticky we tooltip::tooltip $bframe.se "Move ship down and right" grid columnconfigure .gameframe.paned.controls \ .gameframe.paned.controls.messages -weight 1 grid .gameframe.paned -sticky nwes -padx 5 -pady {0 5} grid columnconfigure .gameframe .gameframe.paned -weight 1 grid rowconfigure .gameframe .gameframe.paned -weight 1 update """) setTheme() ordersmenu.addCommands() waitmenu.addCommands() helpui.addCommands() shipsui.addCommands() craftsui.addCommands() messagesui.addCommands() gameoptions.addCommands() tradesui.addCommands() basesschoolui.addCommands() basesrecruitui.addCommands() basesui.addCommands() basesshipyardui.addCommands() baseslootui.addCommands() knowledge.addCommands() missionsui.addCommands() statisticsui.addCommands() const messagesFrame: string = paned & ".controls.messages" tclEval(script = "bind " & messagesFrame & " <Configure> {ResizeLastMessages}") tclEval(script = "bind " & mapView & " <Configure> {DrawMap}") tclEval(script = "bind " & mapView & " <Motion> {UpdateMapInfo %x %y}") tclEval(script = "bind " & mapView & " <Button-" & ( if gameSettings.rightButton: "3" else: "1") & "> {ShowDestinationMenu %X %Y;break}") tclEval(script = "bind " & mapView & " <MouseWheel> {if {%D > 0} {ZoomMap raise} else {ZoomMap lower}}") tclEval(script = "bind " & mapView & " <Button-4> {ZoomMap raise}") tclEval(script = "bind " & mapView & " <Button-5> {ZoomMap lower}") setKeys() if debugMode == menu: showDebugUi() else: tclEval(script = "pack " & gameFrame & " -fill both -expand true") tclSetVar(varName = "refreshmap", newValue = "1") tclEval(script = "wm title . {Steam Sky}") if gameSettings.fullScreen: tclEval(script = "wm attributes . -fullscreen 1") for accel in menuAccelerators: let pos: int = accel.rfind(sub = '-') tclEval(script = "bind . <" & accel[0..pos] & "KeyPress-" & accel[pos + 1..^1] & "> {InvokeMenu " & accel & "}") if not tclEval2(script = "grid slaves .").contains(sub = ".gameframe.header"): let header: string = gameFrame & ".header" tclEval(script = "grid " & header) updateHeader() centerX = playerShip.skyX centerY = playerShip.skyY for index, baseType in basesTypesList: tclEval(script = mapView & " tag configure " & index & " -foreground " & $baseType.color) let panedPosition: int = (if gameSettings.windowHeight - gameSettings.messagesPosition < 0: gameSettings.windowHeight else: gameSettings.windowHeight - gameSettings.messagesPosition) tclEval(script = paned & " sashpos 0 " & $panedPosition) if not tclEval2(script = "grid slaves .").contains(sub = ".gameframe.paned"): tclEval(script = "grid " & paned) tclEval(script = "update") const button: string = paned & ".mapframe.buttons.hide" tclEval(script = button & " invoke") tclEval(script = "bind . <Escape> {InvokeButton " & closeButton & "}") updateMessages() if not newStart: tclEval(script = "DrawMap") updateMoveButtons() updateMapInfo() if not gameSettings.showLastMessages: const messagesFrame: string = paned & ".controls.messages" tclEval(script = "grid remove " & messagesFrame) tclSetVar(varName = "shipname", newValue = playerShip.name) tclSetVar(varName = "gamestate", newValue = "general") if tclEval2(script = "winfo ismapped " & closeButton) == "1": showSkyMap(clear = true) tclEval(script = "grid remove " & closeButton)
412
0.917235
1
0.917235
game-dev
MEDIA
0.935545
game-dev
0.922287
1
0.922287
JACoders/OpenJK
7,744
code/cgame/cg_servercmds.cpp
/* =========================================================================== Copyright (C) 1999 - 2005, Id Software, Inc. Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ // cg_servercmds.c -- text commands sent by the server #include "cg_headers.h" #include "cg_media.h" #include "FxScheduler.h" /* ================ CG_ParseServerinfo This is called explicitly when the gamestate is first received, and whenever the server updates any serverinfo flagged cvars ================ */ void CG_ParseServerinfo( void ) { const char *info; const char *mapname; info = CG_ConfigString( CS_SERVERINFO ); cgs.dmflags = atoi( Info_ValueForKey( info, "dmflags" ) ); cgs.teamflags = atoi( Info_ValueForKey( info, "teamflags" ) ); cgs.timelimit = atoi( Info_ValueForKey( info, "timelimit" ) ); cgs.maxclients = 1; mapname = Info_ValueForKey( info, "mapname" ); Com_sprintf( cgs.mapname, sizeof( cgs.mapname ), "maps/%s.bsp", mapname ); const char *p = strrchr(mapname,'/'); Q_strncpyz( cgs.stripLevelName[0], p?p+1:mapname, sizeof(cgs.stripLevelName[0]) ); Q_strupr( cgs.stripLevelName[0] ); for (int i=1; i<STRIPED_LEVELNAME_VARIATIONS; i++) // clear retry-array { cgs.stripLevelName[i][0]='\0'; } // be careful with the []-numbers here. Currently I use 0,1,2 for replacements or substitution, and [3] for "INGAME" // I know, if I'd known there was going to be this much messing about I'd have subroutinised it all and done it // neater, but it kinda evolved... Feel free to bug me if you want to add to it... ? -Ste. // //FIXME: a better way to handle sound-matched strings from other levels (currently uses levelname+sound as key) // additional String files needed for some levels... // // JKA... if (!Q_stricmp(cgs.stripLevelName[0],"YAVIN1B")) { Q_strncpyz( cgs.stripLevelName[1], "YAVIN1", sizeof(cgs.stripLevelName[1])); } /* // JK2... if (!stricmp(cgs.stripLevelName[0],"KEJIM_BASE") || !stricmp(cgs.stripLevelName[0],"KEJIM_POST") ) { strcpy( cgs.stripLevelName[1], "ARTUS_MINE" ); } if (!stricmp(cgs.stripLevelName[0],"DOOM_DETENTION") || !stricmp(cgs.stripLevelName[0],"DOOM_SHIELDS") ) { strcpy( cgs.stripLevelName[1], "DOOM_COMM" ); } if (!stricmp(cgs.stripLevelName[0],"DOOM_COMM")) { strcpy( cgs.stripLevelName[1], "CAIRN_BAY" ); } if (!stricmp(cgs.stripLevelName[0],"NS_STARPAD")) { strcpy( cgs.stripLevelName[1], "ARTUS_TOPSIDE" ); // for dream sequence... strcpy( cgs.stripLevelName[2], "BESPIN_UNDERCITY" ); // for dream sequence... } if (!stricmp(cgs.stripLevelName[0],"BESPIN_PLATFORM")) { strcpy( cgs.stripLevelName[1], "BESPIN_UNDERCITY" ); } */ } /* ================ CG_ConfigStringModified ================ */ void CG_RegisterClientModels (int entityNum); extern void cgi_R_WorldEffectCommand( const char *command ); static void CG_ConfigStringModified( void ) { const char *str; int num; num = atoi( CG_Argv( 1 ) ); // get the gamestate from the client system, which will have the // new configstring already integrated cgi_GetGameState( &cgs.gameState ); // look up the individual string that was modified str = CG_ConfigString( num ); // do something with it if necessary if ( num == CS_ITEMS ) { int i; for ( i = 1 ; i < bg_numItems ; i++ ) { if ( str[ i ] == '1' ) { if (bg_itemlist[i].classname) { CG_RegisterItemSounds( i ); CG_RegisterItemVisuals( i ); } } } } else if ( num == CS_MUSIC ) { CG_StartMusic( qtrue ); } else if ( num == CS_SERVERINFO ) { CG_ParseServerinfo(); } else if ( num >= CS_MODELS && num < CS_MODELS+MAX_MODELS ) { cgs.model_draw[ num-CS_MODELS ] = cgi_R_RegisterModel( str ); // OutputDebugString(va("### CG_ConfigStringModified(): cgs.model_draw[%d] = \"%s\"\n",num-CS_MODELS,str)); // GHOUL2 Insert start } else if ( num >= CS_CHARSKINS && num < CS_CHARSKINS+MAX_CHARSKINS ) { cgs.skins[ num-CS_CHARSKINS ] = cgi_R_RegisterSkin( str ); // Ghoul2 Insert end } else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_SOUNDS ) { if ( str[0] != '*' ) { cgs.sound_precache[ num-CS_SOUNDS] = cgi_S_RegisterSound( str ); } } else if ( num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX ) { theFxScheduler.RegisterEffect( str ); } else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS ) { CG_NewClientinfo( num - CS_PLAYERS ); CG_RegisterClientModels( num - CS_PLAYERS ); } else if ( num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES*3)) { CG_SetLightstyle(num - CS_LIGHT_STYLES); } else if ( num >= CS_WORLD_FX && num < CS_WORLD_FX + MAX_WORLD_FX ) { cgi_R_WorldEffectCommand( str ); } } static void CG_CenterPrint_f( void ) { CG_CenterPrint( CG_Argv( 1 ), SCREEN_HEIGHT * 0.25 ); } static void CG_Print_f( void ) { CG_Printf( "%s", CG_Argv( 1 ) ); } static void CG_CaptionText_f( void ) { sfxHandle_t sound = (sfxHandle_t)atoi( CG_Argv( 2 ) ); CG_CaptionText( CG_Argv( 1 ), sound >= 0 && sound < MAX_SOUNDS ? cgs.sound_precache[sound] : NULL_SOUND ); } static void CG_ScrollText_f( void ) { CG_ScrollText( CG_Argv( 1 ), SCREEN_WIDTH - 16 ); } static void CG_LCARSText_f( void ) { CG_Printf( "CG_LCARSText() being called. Tell Ste\n" "String: \"%s\"\n", CG_Argv( 1 ) ); } static void CG_ClientLevelShot_f( void ) { // clientLevelShot is sent before taking a special screenshot for // the menu system during development cg.levelShot = qtrue; } typedef struct serverCommand_s { const char *cmd; void (*func)(void); } serverCommand_t; static int svcmdcmp( const void *a, const void *b ) { return Q_stricmp( (const char *)a, ((serverCommand_t*)b)->cmd ); } /* This array MUST be sorted correctly by alphabetical name field */ static serverCommand_t commands[] = { { "chat", CG_Print_f }, { "clientLevelShot", CG_ClientLevelShot_f }, { "cp", CG_CenterPrint_f }, { "cs", CG_ConfigStringModified }, { "ct", CG_CaptionText_f }, { "cts", CG_CaptionTextStop }, { "lt", CG_LCARSText_f }, { "print", CG_Print_f }, { "st", CG_ScrollText_f }, }; static const size_t numCommands = ARRAY_LEN( commands ); /* ================= CG_ServerCommand The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ static void CG_ServerCommand( void ) { const char *cmd = CG_Argv( 0 ); serverCommand_t *command = NULL; if ( !cmd[0] ) { // server claimed the command return; } command = (serverCommand_t *)Q_LinearSearch( cmd, commands, numCommands, sizeof( commands[0] ), svcmdcmp ); if ( command ) { command->func(); return; } CG_Printf( "Unknown client game command: %s\n", cmd ); } /* ==================== CG_ExecuteNewServerCommands Execute all of the server commands that were received along with this this snapshot. ==================== */ void CG_ExecuteNewServerCommands( int latestSequence ) { while ( cgs.serverCommandSequence < latestSequence ) { if ( cgi_GetServerCommand( ++cgs.serverCommandSequence ) ) { CG_ServerCommand(); } } }
412
0.922373
1
0.922373
game-dev
MEDIA
0.891715
game-dev
0.840471
1
0.840471
rotators/fo2238
2,779
Server/scripts/map_sf_shi.fos
// // FOnline: 2238 // Rotators // // map_sf_shi.fos // #include "_macros.fos" #include "factions_vc_q_scoutsf.fos" void map_init(Map& map, bool firstTime) { map.SetEvent(MAP_EVENT_IN_CRITTER, "_OnInCritter"); // sovhoz } void _OnInCritter(Map& map, Critter& player) { // We are only interested in players if(!player.IsPlayer()) return; // Quest related method. ScoutSFMap(map, player); } ////////////////////////////////////////////////// // Emperor // - when bos scribe(science req) will use holodisk on it // emperor predicts some abstract stuff, and produce output on that holodisk // which determine score gained ////////////////////////////////////////////////// // around this repair level emperor repairing resolves #define EMPEROR_REPAIR_DIFFICULTY (150) // percentage value determining condition of the mainframe int EmperorCondition = 50; bool s_EmperorTerminal(Critter& player, Scenery& terminal, int skill, Item@ item) { if(skill == SK_SCIENCE) return EmperorRepair(player, terminal, skill, item); // if(item.GetProtoID() == PID_HOLODISK) // return EmperorProcessData(player, terminal, skill, item); return true; } bool s_EmperorMainframe(Critter& player, Scenery& emperor, int skill, Item@ item) { if(skill == SK_REPAIR) return EmperorRepair(player, emperor, skill, item); return true; } // // Fixing emperor condition // // This can be done in following ways: // - using repair on mainfram objects // - usin science on terminal // bool EmperorRepair(Critter& player, Scenery& scenery, int skill, Item@ item) { // science or repair uint skill_value = (skill == SK_REPAIR) ? player.Skill[SK_REPAIR] : player.Skill[SK_SCIENCE]; uint difficulty = EMPEROR_REPAIR_DIFFICULTY + (100 - EmperorCondition); DPlayerLog(player, "Repairing with skill " + skill + ": " + skill_value + " vs: " + difficulty); int newCondition = EmperorCondition + (skill_value - difficulty) + Random(-50, 50); newCondition = CLAMP(newCondition, 1, 100); if(newCondition > EmperorCondition) { player.Say(SAY_NETMSG, "You've succesfully repaired the mainframe."); } else { player.Say(SAY_NETMSG, "You've failed to repair the mainframe."); } // set timeout for player (relates to the amount of repairing done) if(skill == SK_REPAIR) _SetTimeout(player, TO_SK_REPAIR, GAME_MINUTE(ABS(newCondition - EmperorCondition))); else if(skill == SK_SCIENCE) _SetTimeout(player, TO_SK_SCIENCE, GAME_MINUTE(ABS(newCondition - EmperorCondition))); EmperorCondition = newCondition; DPlayerLog(player, "Emperor condition: " + EmperorCondition); return true; }
412
0.846129
1
0.846129
game-dev
MEDIA
0.975599
game-dev
0.634562
1
0.634562
Ares-Developers/Ares
2,298
src/Ext/BulletType/Body.h
#pragma once #include <CCINIClass.h> #include <BulletTypeClass.h> #include "../_Container.hpp" #include "../../Utilities/Constructs.h" #include "../../Utilities/Template.h" #include "../../Ares.h" #include "../../Misc/Debug.h" class BulletClass; class ConvertClass; class BulletTypeExt { public: using base_type = BulletTypeClass; class ExtData final : public Extension<BulletTypeClass> { public: // solid Valueable<bool> SubjectToSolid; Valueable<int> Solid_Level; // firewall Valueable<bool> SubjectToFirewall; Valueable<bool> Parachuted; // added on 11.11.09 for #667 (part of Trenches) Valueable<bool> SubjectToTrenches; //! if false, this projectile/weapon *always* passes through to the occupants, regardless of UC.PassThrough // cache for the image animation's palette convert OptionalStruct<ConvertClass*> ImageConvert; Valueable<bool> Splits; Valueable<double> RetargetAccuracy; Valueable<double> AirburstSpread; Nullable<bool> AroundTarget; // aptly named, for both Splits and Airburst, defaulting to Splits Nullable<Leptons> BallisticScatterMin; Nullable<Leptons> BallisticScatterMax; Valueable<int> AnimLength; ExtData(BulletTypeClass* OwnerObject) : Extension<BulletTypeClass>(OwnerObject), Splits(false), RetargetAccuracy(0.0), AirburstSpread(1.5), SubjectToSolid(false), Solid_Level(0), SubjectToFirewall(true), Parachuted(false), SubjectToTrenches(true), ImageConvert() { } virtual ~ExtData() = default; virtual void LoadFromINIFile(CCINIClass* pINI) override; virtual void InvalidatePointer(void *ptr, bool bRemoved) override { } virtual void LoadFromStream(AresStreamReader &Stm) override; virtual void SaveToStream(AresStreamWriter &Stm) override; ConvertClass* GetConvert(); bool HasSplitBehavior(); BulletClass* CreateBullet(AbstractClass* pTarget, TechnoClass* pOwner, WeaponTypeClass* pWeapon) const; BulletClass* CreateBullet(AbstractClass* pTarget, TechnoClass* pOwner, int damage, WarheadTypeClass* pWarhead, int speed, int range, bool bright) const; private: template <typename T> void Serialize(T& Stm); }; class ExtContainer final : public Container<BulletTypeExt> { public: ExtContainer(); ~ExtContainer(); }; static ExtContainer ExtMap; };
412
0.932119
1
0.932119
game-dev
MEDIA
0.86311
game-dev
0.83455
1
0.83455
DevTalles-corp/patrones-diseno
4,151
03-comportamiento/07-state.ts
/** * ! Patrón State * Este patrón permite a un objeto cambiar su comportamiento * cuando su estado interno cambia. * * * Es útil cuando un objeto tiene un comportamiento que depende de su estado * * y debe cambiar su comportamiento en tiempo de ejecución dependiendo de ese estado. * * https://refactoring.guru/es/design-patterns/state */ import { COLORS } from '../helpers/colors.ts'; import { sleep } from '../helpers/sleep.ts'; /** * * Objetivo: Implementar el patrón State para simular el funcionamiento * * de una máquina expendedora. * * La máquina tiene diferentes estados, * * Como Esperando Dinero, * * Seleccionando Producto, * * Entregando Producto, * * y su comportamiento varía dependiendo del estado actual. */ interface State { name: string; insertMoney(): void; selectProduct(): void; dispenseProduct(): void; } class VendingMachine { private state: State; constructor() { this.state = new WaitingForMoney(this); } insertMoney() { this.state.insertMoney(); } selectProduct() { this.state.selectProduct(); } dispenseProduct() { this.state.dispenseProduct(); } setState(newState: State) { this.state = newState; console.log(`Estado cambió a: %c${newState.name}`, COLORS.yellow); } getStateName(): string { return this.state.name; } } // Estados class WaitingForMoney implements State { public name: string = 'Esperando Dinero'; private vendingMachine: VendingMachine; constructor(vendingMachine: VendingMachine) { this.vendingMachine = vendingMachine; } insertMoney(): void { console.log( 'Dinero insertado: %cAhora puedes seleccionar un producto', COLORS.green ); this.vendingMachine.setState(new ProductSelected(this.vendingMachine)); } selectProduct(): void { console.log('%cPrimero debes de insertar dinero.', COLORS.red); } dispenseProduct(): void { console.log('%cPrimero debes de insertar dinero.', COLORS.red); } } class ProductSelected implements State { public name: string = 'Seleccionando Producto'; private vendingMachine: VendingMachine; constructor(vendingMachine: VendingMachine) { this.vendingMachine = vendingMachine; } insertMoney(): void { console.log( '%cPor favor selecciona un producto - dinero ya insertado', COLORS.red ); } selectProduct(): void { this.vendingMachine.setState(new DispensingProduct(this.vendingMachine)); } dispenseProduct(): void { console.log( '%cPor favor selecciona un producto - antes de despacharlo', COLORS.red ); } } class DispensingProduct implements State { public name: string = 'Despachando producto'; private vendingMachine: VendingMachine; constructor(vendingMachine: VendingMachine) { this.vendingMachine = vendingMachine; } insertMoney(): void { console.log('%cPor favor espera a que se entregue el producto', COLORS.red); } selectProduct(): void { console.log('%cProducto ya seleccionado y despachando', COLORS.red); } dispenseProduct(): void { console.log( '%cProducto despachado, Cambiando estado a EsperandoDinero', COLORS.green ); this.vendingMachine.setState(new WaitingForMoney(this.vendingMachine)); } } async function main() { const vendingMachine = new VendingMachine(); let selectedOption: string | null = '4'; do { console.clear(); console.log( `Selecciona una opción: %c${vendingMachine.getStateName()}`, COLORS.blue ); selectedOption = prompt( ` 1. Insertar dinero 2. Seleccionar producto 3. Dispensar producto 4. Salir opción: ` ); switch (selectedOption) { case '1': vendingMachine.insertMoney(); break; case '2': vendingMachine.selectProduct(); break; case '3': vendingMachine.dispenseProduct(); break; case '4': console.log('Saliendo de sistema'); break; default: console.log('Opción no válida'); } await sleep(3000); } while (selectedOption !== '4'); } main();
412
0.621315
1
0.621315
game-dev
MEDIA
0.778609
game-dev
0.733427
1
0.733427
BlueLightJapan/BlueLight
2,309
src/pocketmine/inventory/FurnaceInventory.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\inventory; use pocketmine\item\Item; use pocketmine\network\mcpe\protocol\types\WindowTypes; use pocketmine\tile\Furnace; class FurnaceInventory extends ContainerInventory{ /** @var Furnace */ protected $holder; public function __construct(Furnace $tile){ parent::__construct($tile); } public function getNetworkType() : int{ return WindowTypes::FURNACE; } public function getName() : string{ return "Furnace"; } public function getDefaultSize() : int{ return 3; //1 input, 1 fuel, 1 output } /** * This override is here for documentation and code completion purposes only. * @return Furnace */ public function getHolder(){ return $this->holder; } /** * @return Item */ public function getResult() : Item{ return $this->getItem(2); } /** * @return Item */ public function getFuel() : Item{ return $this->getItem(1); } /** * @return Item */ public function getSmelting() : Item{ return $this->getItem(0); } /** * @param Item $item * * @return bool */ public function setResult(Item $item) : bool{ return $this->setItem(2, $item); } /** * @param Item $item * * @return bool */ public function setFuel(Item $item) : bool{ return $this->setItem(1, $item); } /** * @param Item $item * * @return bool */ public function setSmelting(Item $item) : bool{ return $this->setItem(0, $item); } public function onSlotChange(int $index, Item $before, bool $send) { parent::onSlotChange($index, $before, $send); $this->getHolder()->scheduleUpdate(); } }
412
0.916245
1
0.916245
game-dev
MEDIA
0.75769
game-dev
0.840847
1
0.840847
COMBINE-lab/cuttlefish
2,930
src/Kmers_Validator.cpp
#include "Validator.hpp" #include "Directed_Kmer.hpp" #include "Kmer_Container.hpp" #include "spdlog/sinks/stdout_color_sinks.h" #include <fstream> template <uint16_t k> void Validator<k>::validate_kmer_set(bool& result) const { console->info("Testing validation of the uniqueness of the k-mers and completeness of the k-mer set in the produced unitigs.\n"); const std::string& kmc_db_path = params.kmc_db_path(); const std::string& cdbg_file_path = params.cdbg_file_path(); const Kmer_Container<k> kmer_container(kmc_db_path); const uint64_t kmer_count = kmer_container.size(); console->info("Number of k-mers in the database: {}\n", kmer_count); std::vector<bool> is_present(kmer_count); uint64_t kmers_seen = 0; uint64_t kmers_repeated = 0; uint64_t unitigs_processed = 0; uint64_t kmers_invalid = 0; // Scan through the unitigs one-by-one. std::string unitig; std::ifstream input(cdbg_file_path.c_str(), std::ifstream::in); while(input >> unitig) { const Kmer<k> first_kmer(unitig, 0); Directed_Kmer<k> kmer(first_kmer); // Scan through the k-mers one-by-one. for(size_t kmer_idx = 0; kmer_idx <= unitig.length() - k; ++kmer_idx) { uint64_t hash_val = mph->lookup(kmer.canonical()); // Encountered a k-mer that is absent at the k-mer database and hashes outside of the valid range. if(hash_val >= kmer_count) { console->error("Invalid k-mer encountered.\n"); kmers_invalid++; } // Encountered a k-mer for the first time that is either a k-mer present at the database, or is // absent there but hashes to the value of a present one (and that present one hasn't been seen yet). else if(!is_present[hash_val]) is_present[hash_val] = true; // A repeated k-mer is seen. else { console->info("Repeated k-mer encountered.\n"); kmers_repeated++; } if(kmer_idx < unitig.length() - k) kmer.roll_to_next_kmer(unitig[kmer_idx + k]); } kmers_seen += unitig.length() - k + 1; unitigs_processed++; if(unitigs_processed % PROGRESS_GRAIN_SIZE == 0) console->info("Validated {}M unitigs.\n", unitigs_processed / 1000000); } console->info("Total number of repeated k-mers: {}\n", kmers_repeated); console->info("Total number of invalid k-mers: {}\n", kmers_invalid); console->info("Total number of k-mers seen: {}\n", kmers_seen); console->info("Total number of k-mers expected: {}\n", kmer_count); input.close(); result = (!kmers_repeated && !kmers_invalid && kmers_seen == kmer_count); } // Template instantiations for the required instances. ENUMERATE(INSTANCE_COUNT, INSTANTIATE, Validator)
412
0.899455
1
0.899455
game-dev
MEDIA
0.455225
game-dev
0.857867
1
0.857867
blueeee/BLEProgressView
3,449
BLEProgressView/Pods/Headers/Private/pop/POPSpringAnimationInternal.h
/** Copyright (c) 2014-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #import "POPAnimationExtras.h" #import "POPPropertyAnimationInternal.h" struct _POPSpringAnimationState : _POPPropertyAnimationState { SpringSolver4d *solver; CGFloat springSpeed; CGFloat springBounciness; // normalized springiness CGFloat dynamicsTension; // tension CGFloat dynamicsFriction; // friction CGFloat dynamicsMass; // mass _POPSpringAnimationState(id __unsafe_unretained anim) : _POPPropertyAnimationState(anim), solver(nullptr), springSpeed(12.), springBounciness(4.), dynamicsTension(0), dynamicsFriction(0), dynamicsMass(0) { type = kPOPAnimationSpring; } bool hasConverged() { NSUInteger count = valueCount; if (shouldRound()) { return vec_equal(previous2Vec, previousVec) && vec_equal(previousVec, toVec); } else { if (!previousVec || !previous2Vec) return false; CGFloat t = dynamicsThreshold / 5; const CGFloat *toValues = toVec->data(); const CGFloat *previousValues = previousVec->data(); const CGFloat *previous2Values = previous2Vec->data(); for (NSUInteger idx = 0; idx < count; idx++) { if ((fabsf(toValues[idx] - previousValues[idx]) >= t) || (fabsf(previous2Values[idx] - previousValues[idx]) >= t)) { return false; } } return true; } } bool isDone() { if (_POPPropertyAnimationState::isDone()) { return true; } return solver->started() && (hasConverged() || solver->hasConverged()); } void updatedDynamics() { if (NULL != solver) { solver->setConstants(dynamicsTension, dynamicsFriction, dynamicsMass); } } void updatedDynamicsThreshold() { _POPPropertyAnimationState::updatedDynamicsThreshold(); if (NULL != solver) { solver->setThreshold(dynamicsThreshold); } } void updatedBouncinessAndSpeed() { [POPSpringAnimation convertBounciness:springBounciness speed:springSpeed toTension:&dynamicsTension friction:&dynamicsFriction mass:&dynamicsMass]; updatedDynamics(); } bool advance(CFTimeInterval time, CFTimeInterval dt, id obj) { // advance past not yet initialized animations if (NULL == currentVec) { return false; } CFTimeInterval localTime = time - startTime; Vector4d value = vector4d(currentVec); Vector4d toValue = vector4d(toVec); Vector4d velocity = vector4d(velocityVec); SSState4d state; state.p = toValue - value; // the solver assumes a spring of size zero // flip the velocity from user perspective to solver perspective state.v = velocity * -1; solver->advance(state, localTime, dt); value = toValue - state.p; // flip velocity back to user perspective velocity = state.v * -1; *currentVec = value; if (velocityVec) { *velocityVec = velocity; } clampCurrentValue(); return true; } virtual void reset(bool all) { _POPPropertyAnimationState::reset(all); if (solver) { solver->setConstants(dynamicsTension, dynamicsFriction, dynamicsMass); solver->reset(); } } }; typedef struct _POPSpringAnimationState POPSpringAnimationState;
412
0.942466
1
0.942466
game-dev
MEDIA
0.840014
game-dev
0.985237
1
0.985237
magmafoundation/Magma-Neo
1,247
patches/net/minecraft/world/level/block/Blocks.java.patch
--- a/net/minecraft/world/level/block/Blocks.java +++ b/net/minecraft/world/level/block/Blocks.java @@ -754,7 +_,7 @@ public static final Block RED_BED = register("red_bed", bed(DyeColor.RED)); public static final Block BLACK_BED = register("black_bed", bed(DyeColor.BLACK)); public static final Block POWERED_RAIL = register( - "powered_rail", new PoweredRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL)) + "powered_rail", new PoweredRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL), true) ); public static final Block DETECTOR_RAIL = register( "detector_rail", new DetectorRailBlock(BlockBehaviour.Properties.of().noCollission().strength(0.7F).sound(SoundType.METAL)) @@ -7806,7 +_,8 @@ static { for (Block block : BuiltInRegistries.BLOCK) { for (BlockState blockstate : block.getStateDefinition().getPossibleStates()) { - Block.BLOCK_STATE_REGISTRY.add(blockstate); + // Neo: comment out, it's done in NeoForgeRegistryCallbacks + //Block.BLOCK_STATE_REGISTRY.add(blockstate); blockstate.initCache(); }
412
0.670836
1
0.670836
game-dev
MEDIA
0.986173
game-dev
0.665344
1
0.665344
DaFuqs/Spectrum
6,933
src/main/java/de/dafuqs/spectrum/blocks/rock_candy/SugarStickBlock.java
package de.dafuqs.spectrum.blocks.rock_candy; import com.mojang.serialization.*; import de.dafuqs.spectrum.blocks.*; import de.dafuqs.spectrum.blocks.redstone.*; import de.dafuqs.spectrum.helpers.*; import de.dafuqs.spectrum.particle.effect.*; import de.dafuqs.spectrum.registries.*; import net.minecraft.core.*; import net.minecraft.core.component.*; import net.minecraft.network.chat.*; import net.minecraft.server.level.*; import net.minecraft.sounds.*; import net.minecraft.util.*; import net.minecraft.world.entity.item.*; import net.minecraft.world.item.*; import net.minecraft.world.item.component.*; import net.minecraft.world.item.context.*; import net.minecraft.world.level.*; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.*; import net.minecraft.world.level.block.state.properties.*; import net.minecraft.world.level.material.*; import net.minecraft.world.level.pathfinder.*; import net.minecraft.world.phys.*; import net.minecraft.world.phys.shapes.*; import org.jetbrains.annotations.*; import java.util.*; public class SugarStickBlock extends Block implements RockCandy { protected final static Map<RockCandyVariant, Block> SUGAR_STICK_BLOCKS = new EnumMap<>(RockCandyVariant.class); protected final RockCandyVariant rockCandyVariant; public static final int ITEM_SEARCH_RANGE = 5; public static final int REQUIRED_ITEM_COUNT_PER_STAGE = 4; public static final EnumProperty<FluidLogging.State> LOGGED = FluidLogging.NONE_AND_CRYSTAL; public static final IntegerProperty AGE = BlockStateProperties.AGE_2; protected static final VoxelShape SHAPE = Block.box(5.0D, 3.0D, 5.0D, 11.0D, 16.0D, 11.0D); public SugarStickBlock(BlockBehaviour.Properties settings, RockCandyVariant rockCandyVariant) { super(settings); this.rockCandyVariant = rockCandyVariant; SUGAR_STICK_BLOCKS.put(this.rockCandyVariant, this); this.registerDefaultState(this.stateDefinition.any().setValue(AGE, 0).setValue(LOGGED, FluidLogging.State.NOT_LOGGED)); } @Override public MapCodec<? extends BlockBreakerBlock> codec() { //TODO: Make the codec return null; } @Override public RockCandyVariant getVariant() { return this.rockCandyVariant; } @Override @Nullable public BlockState getStateForPlacement(BlockPlaceContext ctx) { FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); if (fluidState.getType() == SpectrumFluids.LIQUID_CRYSTAL) { return super.getStateForPlacement(ctx).setValue(LOGGED, FluidLogging.State.LIQUID_CRYSTAL); } else { return super.getStateForPlacement(ctx); } } @Override public FluidState getFluidState(BlockState state) { return state.getValue(LOGGED).isOf(SpectrumFluids.LIQUID_CRYSTAL) ? SpectrumFluids.LIQUID_CRYSTAL.getSource(false) : super.getFluidState(state); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(AGE, LOGGED); } @Override protected boolean isRandomlyTicking(BlockState state) { return state.getValue(LOGGED).isOf(SpectrumFluids.LIQUID_CRYSTAL) && state.getValue(AGE) < BlockStateProperties.MAX_AGE_2; } @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { super.tick(state, level, pos, random); if (state.getValue(LOGGED).isOf(Fluids.EMPTY)) { int age = state.getValue(AGE); if (age == 2 || (age == 1 ? random.nextBoolean() : random.nextFloat() < 0.25)) { level.addParticle(new DynamicParticleEffect(0.1F, SpectrumColorHelper.getRGBVec(rockCandyVariant.getDyeColor()), 0.5F, 120, true, true), pos.getX() + 0.25 + random.nextFloat() * 0.5, pos.getY() + 0.25 + random.nextFloat() * 0.5, pos.getZ() + 0.25 + random.nextFloat() * 0.5, 0.08 - random.nextFloat() * 0.16, 0.04 - random.nextFloat() * 0.16, 0.08 - random.nextFloat() * 0.16); } } } @Override public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { super.randomTick(state, world, pos, random); if (state.getValue(LOGGED).isOf(SpectrumFluids.LIQUID_CRYSTAL)) { int age = state.getValue(AGE); if (age < BlockStateProperties.MAX_AGE_2) { List<ItemEntity> itemEntities = world.getEntitiesOfClass(ItemEntity.class, AABB.ofSize(Vec3.atCenterOf(pos), ITEM_SEARCH_RANGE, ITEM_SEARCH_RANGE, ITEM_SEARCH_RANGE)); Collections.shuffle(itemEntities); for (ItemEntity itemEntity : itemEntities) { // is the item also submerged? // lazy, but mostly accurate and performant way to check if it's the same liquid pool if (!itemEntity.isEyeInFluid(SpectrumFluidTags.LIQUID_CRYSTAL)) { continue; } ItemStack stack = itemEntity.getItem(); if (stack.getCount() >= REQUIRED_ITEM_COUNT_PER_STAGE) { @Nullable RockCandyVariant itemVariant = RockCandyVariant.getFor(stack); if (itemVariant != null) { BlockState newState; if (rockCandyVariant != RockCandyVariant.SUGAR) { newState = state; } else { newState = SUGAR_STICK_BLOCKS.get(itemVariant).defaultBlockState(); } stack.shrink(REQUIRED_ITEM_COUNT_PER_STAGE); world.setBlockAndUpdate(pos, newState.setValue(AGE, age + 1).setValue(LOGGED, state.getValue(LOGGED))); world.playSound(null, pos, newState.getSoundType().getHitSound(), SoundSource.BLOCKS, 0.5F, 1.0F); break; } } } } } } @Override public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { return SHAPE; } @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { Direction direction = Direction.UP; return Block.canSupportCenter(world, pos.relative(direction), direction.getOpposite()); } @Override public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { return direction == Direction.UP && !state.canSurvive(world, pos) ? Blocks.AIR.defaultBlockState() : super.updateShape(state, direction, neighborState, world, pos, neighborPos); } @Override public boolean isPathfindable(BlockState state, PathComputationType type) { return false; } @Override public void appendHoverText(ItemStack stack, Item.TooltipContext context, List<Component> tooltip, TooltipFlag type) { super.appendHoverText(stack, context, tooltip, type); BlockItemStateProperties stateComponent = stack.get(DataComponents.BLOCK_STATE); if (stateComponent != null) { Integer age = stateComponent.get(SugarStickBlock.AGE); switch (age) { case 1 -> { tooltip.add(Component.translatable("block.spectrum.sugar_stick.tooltip.medium")); } case 2 -> { tooltip.add(Component.translatable("block.spectrum.sugar_stick.tooltip.large")); } case null, default -> { } } } } }
412
0.882179
1
0.882179
game-dev
MEDIA
0.988177
game-dev
0.912292
1
0.912292
joelgwebber/bench2d
8,087
c/Box2D_2.3.1/Box2D/Dynamics/Joints/b2MotorJoint.cpp
/* * Copyright (c) 2006-2012 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. */ #include <Box2D/Dynamics/Joints/b2MotorJoint.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> // Point-to-point constraint // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB) { bodyA = bA; bodyB = bB; b2Vec2 xB = bodyB->GetPosition(); linearOffset = bodyA->GetLocalPoint(xB); float32 angleA = bodyA->GetAngle(); float32 angleB = bodyB->GetAngle(); angularOffset = angleB - angleA; } b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def) : b2Joint(def) { m_linearOffset = def->linearOffset; m_angularOffset = def->angularOffset; m_linearImpulse.SetZero(); m_angularImpulse = 0.0f; m_maxForce = def->maxForce; m_maxTorque = def->maxTorque; m_correctionFactor = def->correctionFactor; } void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); // Compute the effective mass matrix. m_rA = b2Mul(qA, -m_localCenterA); m_rB = b2Mul(qB, -m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Mat22 K; K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; m_linearMass = K.GetInverse(); m_angularMass = iA + iB; if (m_angularMass > 0.0f) { m_angularMass = 1.0f / m_angularMass; } m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset); m_angularError = aB - aA - m_angularOffset; if (data.step.warmStarting) { // Scale impulses to support a variable time step. m_linearImpulse *= data.step.dtRatio; m_angularImpulse *= data.step.dtRatio; b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); } else { m_linearImpulse.SetZero(); m_angularImpulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; float32 h = data.step.dt; float32 inv_h = data.step.inv_dt; // Solve angular friction { float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError; float32 impulse = -m_angularMass * Cdot; float32 oldImpulse = m_angularImpulse; float32 maxImpulse = h * m_maxTorque; m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError; b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); b2Vec2 oldImpulse = m_linearImpulse; m_linearImpulse += impulse; float32 maxImpulse = h * m_maxForce; if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { m_linearImpulse.Normalize(); m_linearImpulse *= maxImpulse; } impulse = m_linearImpulse - oldImpulse; vA -= mA * impulse; wA -= iA * b2Cross(m_rA, impulse); vB += mB * impulse; wB += iB * b2Cross(m_rB, impulse); } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data) { B2_NOT_USED(data); return true; } b2Vec2 b2MotorJoint::GetAnchorA() const { return m_bodyA->GetPosition(); } b2Vec2 b2MotorJoint::GetAnchorB() const { return m_bodyB->GetPosition(); } b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const { return inv_dt * m_linearImpulse; } float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_angularImpulse; } void b2MotorJoint::SetMaxForce(float32 force) { b2Assert(b2IsValid(force) && force >= 0.0f); m_maxForce = force; } float32 b2MotorJoint::GetMaxForce() const { return m_maxForce; } void b2MotorJoint::SetMaxTorque(float32 torque) { b2Assert(b2IsValid(torque) && torque >= 0.0f); m_maxTorque = torque; } float32 b2MotorJoint::GetMaxTorque() const { return m_maxTorque; } void b2MotorJoint::SetCorrectionFactor(float32 factor) { b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f); m_correctionFactor = factor; } float32 b2MotorJoint::GetCorrectionFactor() const { return m_correctionFactor; } void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset) { if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_linearOffset = linearOffset; } } const b2Vec2& b2MotorJoint::GetLinearOffset() const { return m_linearOffset; } void b2MotorJoint::SetAngularOffset(float32 angularOffset) { if (angularOffset != m_angularOffset) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_angularOffset = angularOffset; } } float32 b2MotorJoint::GetAngularOffset() const { return m_angularOffset; } void b2MotorJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2MotorJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y); b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset); b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
412
0.929799
1
0.929799
game-dev
MEDIA
0.987672
game-dev
0.972026
1
0.972026
RektSuddenDeath/College-Champ-Data-pack
1,996
Lab-RP/data/gr/functions/rooms/archived/sunken_chambers/pink/complete.mcfunction
# Open Gates execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run summon area_effect_cloud ~ ~10 ~15 {Duration:9999999,Tags:["gr_opener"]} execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~5 101 ~2 ~5 104 ~4 air destroy execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~5 101 ~26 ~5 104 ~28 air destroy execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~5 101 ~14 ~7 101 ~16 air destroy execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~5 100 ~7 ~27 96 ~24 water # Playsound execute as @a[team=pink] at @s run playsound gr.roomcomplete record @s # Clear Inv clear @a[team=pink] effect clear @a[team=pink] absorption effect give @a[team=pink] resistance infinite 5 true execute as @a[team=pink] run attribute @s generic.max_health base set 20 # Save times scoreboard players operation @e[type=area_effect_cloud,tag=gr_general,tag=gr_pinkany] gr_room8time = pink gr_currenttime # Trim execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run fill ~1 111 ~-1 ~31 111 ~31 pink_terracotta replace smooth_quartz # Calculate Position, and update scoreboard scoreboard players add pink gr_completeroom 1 scoreboard players add 8 gr_indvroom 1 function gr:scoreboard/moveup/pink scoreboard players operation pink gr_currentpos = 8 gr_indvroom function gr:scoreboard/calc # Announce position tellraw @a[team=!pink] ["",{"translate":"team.pink"},"§7第",{"score":{"name": "8","objective": "gr_indvroom"},"color": "aqua"},"§7个完成了房间","§e[","§9Sunken Chambers","§e]"] tellraw @a[team=pink] ["","§7你","§7第",{"score":{"name": "8","objective": "gr_indvroom"},"color": "aqua"},"§7个完成了房间","§e[","§9Sunken Chambers","§e]"] # Initiate next room scoreboard players add pink gr_teamphase 1 execute as @e[type=minecraft:area_effect_cloud,tag=gr_pinkanchor] at @s run tp @s ~-60 ~ ~ function gr:rooms/9/pink/divider function gr:rooms/9/pink/master
412
0.921045
1
0.921045
game-dev
MEDIA
0.943438
game-dev
0.639519
1
0.639519
IJEMIN/Unity-Programming-Essence
2,328
18/Done/Zombie Multiplayer/Assets/Photon/PhotonUnityNetworking/UtilityScripts/UI/TextToggleIsOnTransition.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TextToggleIsOnTransition.cs" company="Exit Games GmbH"> // </copyright> // <summary> // Use this on Button texts to have some color transition on the text as well without corrupting button's behaviour. // </summary> // <author>developer@exitgames.com</author> // -------------------------------------------------------------------------------------------------------------------- using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Photon.Pun.UtilityScripts { /// <summary> /// Use this on toggles texts to have some color transition on the text depending on the isOn State. /// </summary> [RequireComponent(typeof(Text))] public class TextToggleIsOnTransition : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { /// <summary> /// The toggle Component. /// </summary> public Toggle toggle; Text _text; /// <summary> /// The color of the normal on transition state. /// </summary> public Color NormalOnColor= Color.white; /// <summary> /// The color of the normal off transition state. /// </summary> public Color NormalOffColor = Color.black; /// <summary> /// The color of the hover on transition state. /// </summary> public Color HoverOnColor= Color.black; /// <summary> /// The color of the hover off transition state. /// </summary> public Color HoverOffColor = Color.black; bool isHover; public void OnEnable() { _text = GetComponent<Text>(); OnValueChanged (toggle.isOn); toggle.onValueChanged.AddListener(OnValueChanged); } public void OnDisable() { toggle.onValueChanged.RemoveListener(OnValueChanged); } public void OnValueChanged(bool isOn) { _text.color = isOn? (isHover?HoverOnColor:HoverOnColor) : (isHover?NormalOffColor:NormalOffColor) ; } public void OnPointerEnter(PointerEventData eventData) { isHover = true; _text.color = toggle.isOn?HoverOnColor:HoverOffColor; } public void OnPointerExit(PointerEventData eventData) { isHover = false; _text.color = toggle.isOn?NormalOnColor:NormalOffColor; } } }
412
0.853471
1
0.853471
game-dev
MEDIA
0.868536
game-dev
0.893469
1
0.893469
magefree/mage
1,477
Mage.Sets/src/mage/cards/m/MindControl.java
package mage.cards.m; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.continuous.ControlEnchantedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Outcome; import mage.constants.Zone; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; /** * * @author BetaSteward_at_googlemail.com */ public final class MindControl extends CardImpl { public MindControl(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{3}{U}{U}"); this.subtype.add(SubType.AURA); // Enchant creature TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.GainControl)); Ability ability = new EnchantAbility(auraTarget); this.addAbility(ability); // You control enchanted creature. this.addAbility(new SimpleStaticAbility(new ControlEnchantedEffect())); } private MindControl(final MindControl card) { super(card); } @Override public MindControl copy() { return new MindControl(this); } }
412
0.910996
1
0.910996
game-dev
MEDIA
0.97481
game-dev
0.897754
1
0.897754
hlrs-vis/covise
1,801
src/module/SCA/EmbossingSimulation/EmbossingSimulation.h
/* This file is part of COVISE. You can use it under the terms of the GNU Lesser General Public License version 2.1 or later, see lgpl-2.1.txt. * License: LGPL 2+ */ #ifndef _EMBOSSING_SIMULATION_H_ #define _EMBOSSING_SIMULATION_H_ #include <api/coModule.h> using namespace covise; #include "ResultDataBase.h" #include "ResultFloatParam.h" #include "ResultEnumParam.h" #include <sstream> #include <fstream> #include <vector> #include <string> class EmbossingSimulation : public coModule { public: EmbossingSimulation(int argc, char *argv[]); ~EmbossingSimulation(); protected: virtual int compute(const char *port); private: coInputPort *p_PraegeParam_; coInputPort *p_colors_; coOutputPort *p_Done_; coIntSliderParam *p_ndivMet_; // esize param for metal part coIntSliderParam *p_ndivPap_; // esize param for paper part string simDir_; float noppenHoehe_; bool readNoppenHoehe_; float ausrundungsRadius_; bool readAusrundungsRadius_; float abnutzungsRadius_; bool readAbnutzungsRadius_; float noppenWinkel_; bool readNoppenWinkel_; int noppenForm_; bool readNoppenForm_; float laenge1_; bool readLaenge1_; float laenge2_; bool readLaenge2_; int tissueTyp_; bool readTissueTyp_; float gummiHaerte_; bool readGummiHaerte_; float anpressDruck_; bool readAnpressDruck_; // ......................... void setBooleanFalse(); void outputDummies(); void gotDummies(); int ANSYSInputAndLaunch(); int CorrectLSDynaFormat(); int checkReadFlags(); int LSDYNALaunch(); int createDirectories(string &); int LaunchANSYSForLS(); int checkKnobPath(string &getPath, std::vector<Candidate *> &FinalCandidates); }; #endif
412
0.859322
1
0.859322
game-dev
MEDIA
0.363994
game-dev
0.504562
1
0.504562
Harlan-H/M3u8Downloader_H
2,707
M3u8Downloader_H.Plugin/PluginManagers/PluginManger.cs
using M3u8Downloader_H.Abstractions.Common; using M3u8Downloader_H.Abstractions.Plugins; using M3u8Downloader_H.Plugin.AttributeReaderManagers; using System.Reflection; namespace M3u8Downloader_H.Plugin.PluginManagers { public partial class PluginManger : IPluginManager { private readonly IPluginBuilder pluginBuilder; public IDictionary<string, IAttributeReader> AttributeReaders { get; private set; } = default!; public IDownloadService? PluginService { get; private set; } public IM3uFileReader? M3UFileReaderInterface { get; private set; } public IM3u8FileInfoStreamService? M3U8FileInfoStreamService { get; private set; } private PluginManger(IPluginBuilder pluginBuilder) { this.pluginBuilder = pluginBuilder; } private void Build() { M3UFileReaderInterface = pluginBuilder.CreateM3u8FileReader(); M3U8FileInfoStreamService = pluginBuilder.CreateM3U8FileInfoStreamService(); var attributeReaderManager = new AttributeReaderManager(); pluginBuilder.SetAttributeReader(attributeReaderManager); AttributeReaders = attributeReaderManager.AttributeReaders; PluginService = pluginBuilder.CreatePluginService(); } } public partial class PluginManger { public static PluginManger? CreatePluginMangaer(Type? type,HttpClient httpClient,ILog log) { if (type is null) return null; ConstructorInfo constructor = type.GetConstructors()[0]; ParameterInfo[] parameterInfos = constructor.GetParameters(); IPluginBuilder pluginBuilder; if (parameterInfos.Length == 0) pluginBuilder = (IPluginBuilder)constructor.Invoke(null); else { object[] argsArray = new object[parameterInfos.Length]; for (int i = 0; i < parameterInfos.Length; i++) { if (parameterInfos[i].ParameterType == typeof(HttpClient)) { argsArray[i] = httpClient; }else if (parameterInfos[i].ParameterType == typeof(ILog)) { argsArray[i] = log; }else { argsArray[i] = default!; } } pluginBuilder = (IPluginBuilder)constructor.Invoke(argsArray); } PluginManger pluginManger = new(pluginBuilder); pluginManger.Build(); return pluginManger; } } }
412
0.636074
1
0.636074
game-dev
MEDIA
0.35449
game-dev
0.772399
1
0.772399
Gravemind2401/Reclaimer
1,469
Reclaimer.Blam/Blam/Common/TagBlock.cs
using Reclaimer.Blam.Utilities; using Reclaimer.IO; namespace Reclaimer.Blam.Common { [FixedSize(12, MaxVersion = (int)CacheType.Halo2Xbox)] [FixedSize(8, MinVersion = (int)CacheType.Halo2Xbox, MaxVersion = (int)CacheType.Halo3Beta)] [FixedSize(12, MinVersion = (int)CacheType.Halo3Beta)] public class TagBlock : IWriteable { public int Count { get; } public Pointer Pointer { get; } public bool IsInvalid { get; } public TagBlock(int count, Pointer pointer) { Count = count; Pointer = pointer; IsInvalid = Count <= 0 || Pointer.Address < 0; } public TagBlock(DependencyReader reader, ICacheFile cache, IAddressTranslator translator) : this(reader, cache, translator, null) { } public TagBlock(DependencyReader reader, ICacheFile cache, IAddressTranslator translator, IPointerExpander expander) { ArgumentNullException.ThrowIfNull(reader); ArgumentNullException.ThrowIfNull(translator); Count = reader.ReadInt32(); Pointer = new Pointer(reader.ReadInt32(), translator, expander); IsInvalid = Count <= 0 || Pointer.Address < 0 || Pointer.Address >= reader.BaseStream.Length; } public void Write(EndianWriter writer, double? version) { writer.Write(Count); Pointer.Write(writer, version); } } }
412
0.765848
1
0.765848
game-dev
MEDIA
0.227987
game-dev
0.633405
1
0.633405
magefree/mage
1,269
Mage.Sets/src/mage/cards/p/PlanarVoid.java
package mage.cards.p; import mage.abilities.common.PutCardIntoGraveFromAnywhereAllTriggeredAbility; import mage.abilities.effects.common.ExileTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SetTargetPointer; import mage.constants.TargetController; import mage.filter.FilterCard; import mage.filter.predicate.mageobject.AnotherPredicate; import java.util.UUID; /** * @author spjspj */ public final class PlanarVoid extends CardImpl { private static final FilterCard filter = new FilterCard("another card"); static { filter.add(AnotherPredicate.instance); } public PlanarVoid(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{B}"); // Whenever another card is put into a graveyard from anywhere, exile that card. this.addAbility(new PutCardIntoGraveFromAnywhereAllTriggeredAbility(new ExileTargetEffect() .setText("exile that card"), false, filter, TargetController.ANY, SetTargetPointer.CARD)); } private PlanarVoid(final PlanarVoid card) { super(card); } @Override public PlanarVoid copy() { return new PlanarVoid(this); } }
412
0.988269
1
0.988269
game-dev
MEDIA
0.880423
game-dev
0.948286
1
0.948286
Flemmli97/Flan
6,366
common/src/main/java/io/github/flemmli97/flan/config/ConfigUpdater.java
package io.github.flemmli97.flan.config; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.serialization.JsonOps; import io.github.flemmli97.flan.Flan; import io.github.flemmli97.flan.api.permission.BuiltinPermission; import io.github.flemmli97.flan.api.permission.PermissionManager; import net.minecraft.advancements.critereon.ItemPredicate; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class ConfigUpdater { private static final Map<Integer, Updater> UPDATER = Config.createHashMap(map -> { map.put(7, new Updater() { @Override public JsonObject configUpdater(JsonObject oldVals) { return oldVals; } @Override public void postUpdater(Config config) { config.defaultGroups.computeIfPresent("Co-Owner", (k, v) -> { if (v.isEmpty()) { PermissionManager.getInstance().getAll().forEach(p -> v.put(p.getId(), true)); } return v; }); config.defaultGroups.computeIfPresent("Visitor", (k, v) -> { if (v.isEmpty()) { v.put(BuiltinPermission.BED, true); v.put(BuiltinPermission.DOOR, true); v.put(BuiltinPermission.FENCEGATE, true); v.put(BuiltinPermission.TRAPDOOR, true); v.put(BuiltinPermission.BUTTONLEVER, true); v.put(BuiltinPermission.PRESSUREPLATE, true); v.put(BuiltinPermission.ENDERCHEST, true); v.put(BuiltinPermission.ENCHANTMENTTABLE, true); v.put(BuiltinPermission.ITEMFRAMEROTATE, true); v.put(BuiltinPermission.PORTAL, true); v.put(BuiltinPermission.TRADING, true); } return v; }); } }); map.put(6, new Updater() { @Override public JsonObject configUpdater(JsonObject oldVals) { return oldVals; } @Override public void postUpdater(Config config) { config.globalDefaultPerms.computeIfPresent("*", (k, v) -> { v.put(BuiltinPermission.ALLOW_FLIGHT, Config.GlobalType.ALLTRUE); v.put(BuiltinPermission.MAY_FLIGHT, Config.GlobalType.ALLFALSE); return v; }); } }); map.put(5, config -> { Flan.debug("Updating config to version 5"); JsonObject buySellHandler = ConfigHandler.fromJson(config, "buySellHandler"); JsonArray buyItems = ConfigHandler.arrayFromJson(buySellHandler, "buyIngredients"); List<JsonElement> toRemove = new ArrayList<>(); buyItems.forEach(k -> { JsonObject o = k.getAsJsonObject(); if (o.has("ingredient")) { try { Ingredient ingredient = Ingredient.CODEC.parse(JsonOps.INSTANCE, buySellHandler.get("ingredient")) .getOrThrow(); ItemPredicate pred = ItemPredicate.Builder.item() .of(Arrays.stream(ingredient.getItems()).map(ItemStack::getItem).toArray(ItemLike[]::new)) .build(); o.add("predicate", ItemPredicate.CODEC.encodeStart(JsonOps.INSTANCE, pred).getOrThrow()); o.remove("ingredient"); } catch (Exception ignored) { } } if (!o.has("predicate") || !o.has("amount")) { Flan.error("Unable to update buy handler ", o); toRemove.add(k); } }); toRemove.forEach(buyItems::remove); buySellHandler.add("buyItems", buyItems); if (buySellHandler.has("ingredient") || buySellHandler.has("sellIngredient")) { Ingredient legacy = buySellHandler.has("ingredient") ? Ingredient.CODEC.parse(JsonOps.INSTANCE, buySellHandler.get("ingredient")) .getOrThrow() : Ingredient.EMPTY; legacy = buySellHandler.has("sellIngredient") ? Ingredient.CODEC.parse(JsonOps.INSTANCE, buySellHandler.get("sellIngredient")) .getOrThrow() : legacy; if (!legacy.isEmpty() && !legacy.getItems()[0].isEmpty()) { buySellHandler.add("sellItems", BuySellHandler.ITEM_STACK_CODEC.encodeStart(JsonOps.INSTANCE, legacy.getItems()[0]) .result().map(e -> { JsonArray arr = new JsonArray(); JsonObject val = new JsonObject(); val.add("amount", buySellHandler.get("sellValue")); val.add("item", e); arr.add(val); return arr; }).orElse(new JsonArray())); } else { buySellHandler.add("sellItems", new JsonArray()); } } return config; }); }); public static JsonObject updateConfig(int preVersion, JsonObject config) { for (Map.Entry<Integer, Updater> updater : UPDATER.entrySet()) { if (updater.getKey() > preVersion) { config = updater.getValue().configUpdater(config); } } return config; } public static void postUpdateConfig(int preVersion, Config config) { for (Map.Entry<Integer, Updater> updater : UPDATER.entrySet()) { if (updater.getKey() > preVersion) { updater.getValue().postUpdater(config); } } } interface Updater { JsonObject configUpdater(JsonObject oldVals); default void postUpdater(Config config) { } } }
412
0.944238
1
0.944238
game-dev
MEDIA
0.978998
game-dev
0.935675
1
0.935675
PhongFeng/FFramework
1,776
Assets/Editor/Game/DataTableGenerator/DataTableProcessor.Color32Processor.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2020 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using System.IO; using UnityEngine; namespace Flower.Editor.DataTableTools { public sealed partial class DataTableProcessor { private sealed class Color32Processor : GenericDataProcessor<Color32> { public override bool IsSystem { get { return false; } } public override string LanguageKeyword { get { return "Color32"; } } public override string[] GetTypeStrings() { return new string[] { "color32", "unityengine.color32" }; } public override Color32 Parse(string value) { string[] splitedValue = value.Split(','); return new Color32(byte.Parse(splitedValue[0]), byte.Parse(splitedValue[1]), byte.Parse(splitedValue[2]), byte.Parse(splitedValue[3])); } public override void WriteToStream(DataTableProcessor dataTableProcessor, BinaryWriter binaryWriter, string value) { Color32 color32 = Parse(value); binaryWriter.Write(color32.r); binaryWriter.Write(color32.g); binaryWriter.Write(color32.b); binaryWriter.Write(color32.a); } } } }
412
0.738778
1
0.738778
game-dev
MEDIA
0.697723
game-dev,graphics-rendering
0.697849
1
0.697849
cutajarj/multithreadinginpython
1,139
deadlocks_train/hierarchy/train.py
import time def lock_intersections_in_distance(id, reserve_start, reserve_end, crossings): intersections_to_lock = [] for crossing in crossings: if reserve_end >= crossing.position >= reserve_start and crossing.intersection.locked_by != id: intersections_to_lock.append(crossing.intersection) intersections_to_lock = sorted(intersections_to_lock, key=lambda it: it.uid) for intersection in intersections_to_lock: intersection.mutex.acquire() intersection.locked_by = id time.sleep(0.01) def move_train(train, distance, crossings): while train.front < distance: train.front += 1 for crossing in crossings: if train.front == crossing.position: lock_intersections_in_distance(train.uid, crossing.position, crossing.position + train.train_length, crossings) back = train.front - train.train_length if back == crossing.position: crossing.intersection.locked_by = -1 crossing.intersection.mutex.release() time.sleep(0.01)
412
0.784166
1
0.784166
game-dev
MEDIA
0.500681
game-dev
0.766389
1
0.766389
grinfans/Niffler
2,274
src/renderer/db.js
let keyPostedUnconfirmed = 'posted_unconfirmed_txs' let keyLocalGnodeStatus = 'local_gnode_status' let keyGnodeLocation = 'local_gnode_location' let keySpendable = 'spendable' let keyLocalGnodeCheckable = 'local_gnode_checkable' let keyTorRunning = 'tor_running' class DBService{ static getPostedUnconfirmedTxs(){ let txs = localStorage.getItem(keyPostedUnconfirmed) if(txs === null){ return new Set() } return new Set(JSON.parse(txs)) } static setPostedUnconfirmedTxs(txs){ if(txs === null){ localStorage.removeItem(keyPostedUnconfirmed) }else{ let txs_ = [...txs] localStorage.setItem(keyPostedUnconfirmed, JSON.stringify(txs_)) } } static addPostedUnconfirmedTx(tx_id){ let txs = DBService.getPostedUnconfirmedTxs() txs.add(tx_id) DBService.setPostedUnconfirmedTxs(txs) } static deletePostedUnconfirmedTx(tx_id){ let txs = DBService.getPostedUnconfirmedTxs() txs.delete(tx_id) DBService.setPostedUnconfirmedTxs(txs) } static getSpendable(){ let amount = localStorage.getItem(keySpendable) if(amount){ return parseFloat(amount) } } static setSpendable(amount){ return localStorage.setItem(keySpendable, amount) } static setLocalGnodeStatus(status){ return localStorage.setItem(keyLocalGnodeStatus, status) } static getLocalGnodeStatus(){ return localStorage.getItem(keyLocalGnodeStatus) } static setGnodeLocation(location){ return localStorage.setItem(keyGnodeLocation, location) } static getGnodeLocation(){ return localStorage.getItem(keyGnodeLocation) } static setLocalGnodeCheckable(checkable){ return localStorage.setItem(keyLocalGnodeCheckable, JSON.stringify(checkable)) } static getLocalGnodeCheckable(){ return JSON.parse(localStorage.getItem(keyLocalGnodeCheckable)) } static setTorRunning(running){ return localStorage.setItem(keyTorRunning, JSON.stringify(running)) } static getTorRunning(){ return JSON.parse(localStorage.getItem(keyTorRunning)) } } export default DBService
412
0.510686
1
0.510686
game-dev
MEDIA
0.521927
game-dev
0.857254
1
0.857254
rtcwcoop/rtcwcoop
88,413
code/botlib/be_ai_chat.c
/* =========================================================================== Return to Castle Wolfenstein single player GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Return to Castle Wolfenstein single player GPL Source Code (“RTCW SP Source Code”). RTCW SP Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RTCW SP Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ /***************************************************************************** * name: be_ai_chat.c * * desc: bot chat AI * * *****************************************************************************/ #include "../qcommon/q_shared.h" #include "l_memory.h" #include "l_libvar.h" #include "l_script.h" #include "l_precomp.h" #include "l_struct.h" #include "l_utils.h" #include "l_log.h" #include "aasfile.h" #include "botlib.h" #include "be_aas.h" #include "be_aas_funcs.h" #include "be_interface.h" #include "be_ea.h" #include "be_ai_chat.h" //escape character #define ESCAPE_CHAR 0x01 //'_' // // "hi ", people, " ", 0, " entered the game" //becomes: // "hi _rpeople_ _v0_ entered the game" // //match piece types #define MT_VARIABLE 1 //variable match piece #define MT_STRING 2 //string match piece //reply chat key flags #define RCKFL_AND 1 //key must be present #define RCKFL_NOT 2 //key must be absent #define RCKFL_NAME 4 //name of bot must be present #define RCKFL_STRING 8 //key is a string #define RCKFL_VARIABLES 16 //key is a match template #define RCKFL_BOTNAMES 32 //key is a series of botnames #define RCKFL_GENDERFEMALE 64 //bot must be female #define RCKFL_GENDERMALE 128 //bot must be male #define RCKFL_GENDERLESS 256 //bot must be genderless //time to ignore a chat message after using it #define CHATMESSAGE_RECENTTIME 20 //the actuall chat messages typedef struct bot_chatmessage_s { char *chatmessage; //chat message string float time; //last time used struct bot_chatmessage_s *next; //next chat message in a list } bot_chatmessage_t; //bot chat type with chat lines typedef struct bot_chattype_s { char name[MAX_CHATTYPE_NAME]; int numchatmessages; bot_chatmessage_t *firstchatmessage; struct bot_chattype_s *next; } bot_chattype_t; //bot chat lines typedef struct bot_chat_s { bot_chattype_t *types; } bot_chat_t; //random string typedef struct bot_randomstring_s { char *string; struct bot_randomstring_s *next; } bot_randomstring_t; //list with random strings typedef struct bot_randomlist_s { char *string; int numstrings; bot_randomstring_t *firstrandomstring; struct bot_randomlist_s *next; } bot_randomlist_t; //synonym typedef struct bot_synonym_s { char *string; float weight; struct bot_synonym_s *next; } bot_synonym_t; //list with synonyms typedef struct bot_synonymlist_s { unsigned long int context; float totalweight; bot_synonym_t *firstsynonym; struct bot_synonymlist_s *next; } bot_synonymlist_t; //fixed match string typedef struct bot_matchstring_s { char *string; struct bot_matchstring_s *next; } bot_matchstring_t; //piece of a match template typedef struct bot_matchpiece_s { int type; bot_matchstring_t *firststring; int variable; struct bot_matchpiece_s *next; } bot_matchpiece_t; //match template typedef struct bot_matchtemplate_s { unsigned long int context; int type; int subtype; bot_matchpiece_t *first; struct bot_matchtemplate_s *next; } bot_matchtemplate_t; //reply chat key typedef struct bot_replychatkey_s { int flags; char *string; bot_matchpiece_t *match; struct bot_replychatkey_s *next; } bot_replychatkey_t; //reply chat typedef struct bot_replychat_s { bot_replychatkey_t *keys; float priority; int numchatmessages; bot_chatmessage_t *firstchatmessage; struct bot_replychat_s *next; } bot_replychat_t; //string list typedef struct bot_stringlist_s { char *string; struct bot_stringlist_s *next; } bot_stringlist_t; //chat state of a bot typedef struct bot_chatstate_s { int gender; //0=it, 1=female, 2=male char name[32]; //name of the bot char chatmessage[MAX_MESSAGE_SIZE]; int handle; //the console messages visible to the bot bot_consolemessage_t *firstmessage; //first message is the first typed message bot_consolemessage_t *lastmessage; //last message is the last typed message, bottom of console //number of console messages stored in the state int numconsolemessages; //the bot chat lines bot_chat_t *chat; } bot_chatstate_t; typedef struct { bot_chat_t *chat; int inuse; char filename[MAX_QPATH]; char chatname[MAX_QPATH]; } bot_ichatdata_t; bot_ichatdata_t ichatdata[MAX_CLIENTS]; bot_chatstate_t *botchatstates[MAX_CLIENTS + 1]; //console message heap bot_consolemessage_t *consolemessageheap = NULL; bot_consolemessage_t *freeconsolemessages = NULL; //list with match strings bot_matchtemplate_t *matchtemplates = NULL; //list with synonyms bot_synonymlist_t *synonyms = NULL; //list with random strings bot_randomlist_t *randomstrings = NULL; //reply chats bot_replychat_t *replychats = NULL; //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== bot_chatstate_t *BotChatStateFromHandle( int handle ) { if ( handle <= 0 || handle > MAX_CLIENTS ) { botimport.Print( PRT_FATAL, "chat state handle %d out of range\n", handle ); return NULL; } //end if if ( !botchatstates[handle] ) { botimport.Print( PRT_FATAL, "invalid chat state %d\n", handle ); return NULL; } //end if return botchatstates[handle]; } //end of the function BotChatStateFromHandle //=========================================================================== // initialize the heap with unused console messages // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void InitConsoleMessageHeap( void ) { int i, max_messages; if ( consolemessageheap ) { FreeMemory( consolemessageheap ); } // max_messages = (int) LibVarValue( "max_messages", "1024" ); consolemessageheap = (bot_consolemessage_t *) GetClearedHunkMemory( max_messages * sizeof( bot_consolemessage_t ) ); consolemessageheap[0].prev = NULL; consolemessageheap[0].next = &consolemessageheap[1]; for ( i = 1; i < max_messages - 1; i++ ) { consolemessageheap[i].prev = &consolemessageheap[i - 1]; consolemessageheap[i].next = &consolemessageheap[i + 1]; } //end for consolemessageheap[max_messages - 1].prev = &consolemessageheap[max_messages - 2]; consolemessageheap[max_messages - 1].next = NULL; //pointer to the free console messages freeconsolemessages = consolemessageheap; } //end of the function InitConsoleMessageHeap //=========================================================================== // allocate one console message from the heap // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_consolemessage_t *AllocConsoleMessage( void ) { bot_consolemessage_t *message; message = freeconsolemessages; if ( freeconsolemessages ) { freeconsolemessages = freeconsolemessages->next; } if ( freeconsolemessages ) { freeconsolemessages->prev = NULL; } return message; } //end of the function AllocConsoleMessage //=========================================================================== // deallocate one console message from the heap // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void FreeConsoleMessage( bot_consolemessage_t *message ) { if ( freeconsolemessages ) { freeconsolemessages->prev = message; } message->prev = NULL; message->next = freeconsolemessages; freeconsolemessages = message; } //end of the function FreeConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotRemoveConsoleMessage( int chatstate, int handle ) { bot_consolemessage_t *m, *nextm; bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } for ( m = cs->firstmessage; m; m = nextm ) { nextm = m->next; if ( m->handle == handle ) { if ( m->next ) { m->next->prev = m->prev; } else { cs->lastmessage = m->prev;} if ( m->prev ) { m->prev->next = m->next; } else { cs->firstmessage = m->next;} FreeConsoleMessage( m ); cs->numconsolemessages--; break; } //end if } //end for } //end of the function BotRemoveConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotQueueConsoleMessage( int chatstate, int type, char *message ) { bot_consolemessage_t *m; bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } m = AllocConsoleMessage(); if ( !m ) { botimport.Print( PRT_ERROR, "empty console message heap\n" ); return; } //end if cs->handle++; if ( cs->handle <= 0 || cs->handle > 8192 ) { cs->handle = 1; } m->handle = cs->handle; m->time = AAS_Time(); m->type = type; Q_strncpyz( m->message, message, MAX_MESSAGE_SIZE ); m->next = NULL; if ( cs->lastmessage ) { cs->lastmessage->next = m; m->prev = cs->lastmessage; cs->lastmessage = m; } //end if else { cs->lastmessage = m; cs->firstmessage = m; m->prev = NULL; } //end if cs->numconsolemessages++; } //end of the function BotQueueConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotNextConsoleMessage( int chatstate, bot_consolemessage_t *cm ) { bot_chatstate_t *cs; bot_consolemessage_t *firstmsg; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return 0; } if ((firstmsg = cs->firstmessage)) { cm->handle = firstmsg->handle; cm->time = firstmsg->time; cm->type = firstmsg->type; Q_strncpyz(cm->message, firstmsg->message, sizeof(cm->message)); /* We omit setting the two pointers in cm because pointer * size in the VM differs between the size in the engine on * 64 bit machines, which would lead to a buffer overflow if * this functions is called from the VM. The pointers are * of no interest to functions calling * BotNextConsoleMessage anyways. */ return cm->handle; } //end if return 0; } //end of the function BotConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotNumConsoleMessages( int chatstate ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return 0; } return cs->numconsolemessages; } //end of the function BotNumConsoleMessages //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int IsWhiteSpace( char c ) { if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) || c == '(' || c == ')' || c == '?' || c == '\'' || c == ':' || c == ',' || c == '[' || c == ']' || c == '-' || c == '_' || c == '+' || c == '=' ) { return qfalse; } return qtrue; } //end of the function IsWhiteSpace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotRemoveTildes( char *message ) { int i; //remove all tildes from the chat message for ( i = 0; message[i]; i++ ) { if ( message[i] == '~' ) { memmove( &message[i], &message[i + 1], strlen( &message[i + 1] ) + 1 ); } //end if } //end for } //end of the function BotRemoveTildes //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void UnifyWhiteSpaces( char *string ) { char *ptr, *oldptr; for ( ptr = oldptr = string; *ptr; oldptr = ptr ) { while ( *ptr && IsWhiteSpace( *ptr ) ) ptr++; if ( ptr > oldptr ) { //if not at the start and not at the end of the string //write only one space if ( oldptr > string && *ptr ) { *oldptr++ = ' '; } //remove all other white spaces if ( ptr > oldptr ) { memmove( oldptr, ptr, strlen( ptr ) + 1 ); } } //end if while ( *ptr && !IsWhiteSpace( *ptr ) ) ptr++; } //end while } //end of the function UnifyWhiteSpaces //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int StringContains( char *str1, char *str2, int casesensitive ) { int len, i, j, index; if ( str1 == NULL || str2 == NULL ) { return -1; } len = strlen( str1 ) - strlen( str2 ); index = 0; for ( i = 0; i <= len; i++, str1++, index++ ) { for ( j = 0; str2[j]; j++ ) { if ( casesensitive ) { if ( str1[j] != str2[j] ) { break; } } //end if else { if ( toupper( str1[j] ) != toupper( str2[j] ) ) { break; } } //end else } //end for if ( !str2[j] ) { return index; } } //end for return -1; } //end of the function StringContains //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== char *StringContainsWord( char *str1, char *str2, int casesensitive ) { int len, i, j; len = strlen( str1 ) - strlen( str2 ); for ( i = 0; i <= len; i++, str1++ ) { //if not at the start of the string if ( i ) { //skip to the start of the next word while ( *str1 && *str1 != ' ' ) str1++; if ( !*str1 ) { break; } str1++; } //end for //compare the word for ( j = 0; str2[j]; j++ ) { if ( casesensitive ) { if ( str1[j] != str2[j] ) { break; } } //end if else { if ( toupper( str1[j] ) != toupper( str2[j] ) ) { break; } } //end else } //end for //if there was a word match if ( !str2[j] ) { //if the first string has an end of word if ( !str1[j] || str1[j] == ' ' ) { return str1; } } //end if } //end for return NULL; } //end of the function StringContainsWord //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void StringReplaceWords( char *string, char *synonym, char *replacement ) { char *str, *str2; //find the synonym in the string str = StringContainsWord( string, synonym, qfalse ); //if the synonym occured in the string while ( str ) { //if the synonym isn't part of the replacement which is already in the string //usefull for abreviations str2 = StringContainsWord( string, replacement, qfalse ); while ( str2 ) { if ( str2 <= str && str < str2 + strlen( replacement ) ) { break; } str2 = StringContainsWord( str2 + 1, replacement, qfalse ); } //end while if ( !str2 ) { memmove( str + strlen( replacement ), str + strlen( synonym ), strlen( str + strlen( synonym ) ) + 1 ); //append the synonum replacement memcpy( str, replacement, strlen( replacement ) ); } //end if //find the next synonym in the string str = StringContainsWord( str + strlen( replacement ), synonym, qfalse ); } //end if } //end of the function StringReplaceWords //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpSynonymList( bot_synonymlist_t *synlist ) { FILE *fp; bot_synonymlist_t *syn; bot_synonym_t *synonym; fp = Log_FilePointer(); if ( !fp ) { return; } for ( syn = synlist; syn; syn = syn->next ) { fprintf( fp, "%ld : [", syn->context ); for ( synonym = syn->firstsynonym; synonym; synonym = synonym->next ) { fprintf( fp, "(\"%s\", %1.2f)", synonym->string, synonym->weight ); if ( synonym->next ) { fprintf( fp, ", " ); } } //end for fprintf( fp, "]\n" ); } //end for } //end of the function BotDumpSynonymList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_synonymlist_t *BotLoadSynonyms( char *filename ) { int pass, size, contextlevel, numsynonyms; unsigned long int context, contextstack[32]; char *ptr = NULL; source_t *source; token_t token; bot_synonymlist_t *synlist, *lastsyn, *syn; bot_synonym_t *synonym, *lastsynonym; size = 0; synlist = NULL; //make compiler happy syn = NULL; //make compiler happy synonym = NULL; //make compiler happy //the synonyms are parsed in two phases for ( pass = 0; pass < 2; pass++ ) { // if ( pass && size ) { ptr = (char *) GetClearedHunkMemory( size ); } // source = LoadSourceFile( filename ); if ( !source ) { botimport.Print( PRT_ERROR, "counldn't load %s\n", filename ); return NULL; } //end if // context = 0; contextlevel = 0; synlist = NULL; //list synonyms lastsyn = NULL; //last synonym in the list // while ( PC_ReadToken( source, &token ) ) { if ( token.type == TT_NUMBER ) { context |= token.intvalue; contextstack[contextlevel] = token.intvalue; contextlevel++; if ( contextlevel >= 32 ) { SourceError( source, "more than 32 context levels" ); FreeSource( source ); return NULL; } //end if if ( !PC_ExpectTokenString( source, "{" ) ) { FreeSource( source ); return NULL; } //end if } //end if else if ( token.type == TT_PUNCTUATION ) { if ( !strcmp( token.string, "}" ) ) { contextlevel--; if ( contextlevel < 0 ) { SourceError( source, "too many }" ); FreeSource( source ); return NULL; } //end if context &= ~contextstack[contextlevel]; } //end if else if ( !strcmp( token.string, "[" ) ) { size += sizeof( bot_synonymlist_t ); if ( pass && ptr ) { syn = (bot_synonymlist_t *) ptr; ptr += sizeof( bot_synonymlist_t ); syn->context = context; syn->firstsynonym = NULL; syn->next = NULL; if ( lastsyn ) { lastsyn->next = syn; } else { synlist = syn;} lastsyn = syn; } //end if numsynonyms = 0; lastsynonym = NULL; while ( 1 ) { size_t len; if ( !PC_ExpectTokenString( source, "(" ) || !PC_ExpectTokenType( source, TT_STRING, 0, &token ) ) { FreeSource( source ); return NULL; } //end if StripDoubleQuotes( token.string ); if ( strlen( token.string ) <= 0 ) { SourceError( source, "empty string" ); FreeSource( source ); return NULL; } //end if len = strlen(token.string) + 1; len = PAD(len, sizeof(long)); size += sizeof(bot_synonym_t) + len; if ( pass && ptr ) { synonym = (bot_synonym_t *) ptr; ptr += sizeof( bot_synonym_t ); synonym->string = ptr; ptr += len; strcpy( synonym->string, token.string ); // if ( lastsynonym ) { lastsynonym->next = synonym; } else { syn->firstsynonym = synonym;} lastsynonym = synonym; } //end if numsynonyms++; if ( !PC_ExpectTokenString( source, "," ) || !PC_ExpectTokenType( source, TT_NUMBER, 0, &token ) || !PC_ExpectTokenString( source, ")" ) ) { FreeSource( source ); return NULL; } //end if if ( pass && ptr ) { synonym->weight = token.floatvalue; syn->totalweight += synonym->weight; } //end if if ( PC_CheckTokenString( source, "]" ) ) { break; } if ( !PC_ExpectTokenString( source, "," ) ) { FreeSource( source ); return NULL; } //end if } //end while if ( numsynonyms < 2 ) { SourceError( source, "synonym must have at least two entries" ); FreeSource( source ); return NULL; } //end if } //end else else { SourceError( source, "unexpected %s", token.string ); FreeSource( source ); return NULL; } //end if } //end else if } //end while // FreeSource( source ); // if ( contextlevel > 0 ) { SourceError( source, "missing }" ); return NULL; } //end if } //end for botimport.Print( PRT_MESSAGE, "loaded %s\n", filename ); // //BotDumpSynonymList(synlist); // return synlist; } //end of the function BotLoadSynonyms //=========================================================================== // replace all the synonyms in the string // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotReplaceSynonyms( char *string, unsigned long int context ) { bot_synonymlist_t *syn; bot_synonym_t *synonym; for ( syn = synonyms; syn; syn = syn->next ) { if ( !( syn->context & context ) ) { continue; } for ( synonym = syn->firstsynonym->next; synonym; synonym = synonym->next ) { StringReplaceWords( string, synonym->string, syn->firstsynonym->string ); } //end for } //end for } //end of the function BotReplaceSynonyms //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotReplaceWeightedSynonyms( char *string, unsigned long int context ) { bot_synonymlist_t *syn; bot_synonym_t *synonym, *replacement; float weight, curweight; for ( syn = synonyms; syn; syn = syn->next ) { if ( !( syn->context & context ) ) { continue; } //choose a weighted random replacement synonym weight = random() * syn->totalweight; if ( !weight ) { continue; } curweight = 0; for ( replacement = syn->firstsynonym; replacement; replacement = replacement->next ) { curweight += replacement->weight; if ( weight < curweight ) { break; } } //end for if ( !replacement ) { continue; } //replace all synonyms with the replacement for ( synonym = syn->firstsynonym; synonym; synonym = synonym->next ) { if ( synonym == replacement ) { continue; } StringReplaceWords( string, synonym->string, replacement->string ); } //end for } //end for } //end of the function BotReplaceWeightedSynonyms //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotReplaceReplySynonyms( char *string, unsigned long int context ) { char *str1, *str2, *replacement; bot_synonymlist_t *syn; bot_synonym_t *synonym; for ( str1 = string; *str1; ) { //go to the start of the next word while ( *str1 && *str1 <= ' ' ) str1++; if ( !*str1 ) { break; } // for ( syn = synonyms; syn; syn = syn->next ) { if ( !( syn->context & context ) ) { continue; } for ( synonym = syn->firstsynonym->next; synonym; synonym = synonym->next ) { //if the synonym is not at the front of the string continue str2 = StringContainsWord( str1, synonym->string, qfalse ); if ( !str2 || str2 != str1 ) { continue; } // replacement = syn->firstsynonym->string; //if the replacement IS in front of the string continue str2 = StringContainsWord( str1, replacement, qfalse ); if ( str2 && str2 == str1 ) { continue; } // memmove( str1 + strlen( replacement ), str1 + strlen( synonym->string ), strlen( str1 + strlen( synonym->string ) ) + 1 ); //append the synonum replacement memcpy( str1, replacement, strlen( replacement ) ); // break; } //end for //if a synonym has been replaced if ( synonym ) { break; } } //end for //skip over this word while ( *str1 && *str1 > ' ' ) str1++; if ( !*str1 ) { break; } } //end while } //end of the function BotReplaceReplySynonyms //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotLoadChatMessage( source_t *source, char *chatmessagestring ) { char *ptr; token_t token; ptr = chatmessagestring; *ptr = 0; // while ( 1 ) { if ( !PC_ExpectAnyToken( source, &token ) ) { return qfalse; } //fixed string if ( token.type == TT_STRING ) { StripDoubleQuotes( token.string ); if ( strlen( ptr ) + strlen( token.string ) + 1 > MAX_MESSAGE_SIZE ) { SourceError( source, "chat message too long" ); return qfalse; } //end if strcat( ptr, token.string ); } //end else if //variable string else if ( token.type == TT_NUMBER && ( token.subtype & TT_INTEGER ) ) { if ( strlen( ptr ) + 7 > MAX_MESSAGE_SIZE ) { SourceError( source, "chat message too long" ); return qfalse; } //end if sprintf( &ptr[strlen( ptr )], "%cv%ld%c", ESCAPE_CHAR, token.intvalue, ESCAPE_CHAR ); } //end if //random string else if ( token.type == TT_NAME ) { if ( strlen( ptr ) + 7 > MAX_MESSAGE_SIZE ) { SourceError( source, "chat message too long" ); return qfalse; } //end if sprintf( &ptr[strlen( ptr )], "%cr%s%c", ESCAPE_CHAR, token.string, ESCAPE_CHAR ); } //end else if else { SourceError( source, "unknown message component %s", token.string ); return qfalse; } //end else if ( PC_CheckTokenString( source, ";" ) ) { break; } if ( !PC_ExpectTokenString( source, "," ) ) { return qfalse; } } //end while // return qtrue; } //end of the function BotLoadChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpRandomStringList( bot_randomlist_t *randomlist ) { FILE *fp; bot_randomlist_t *random; bot_randomstring_t *rs; fp = Log_FilePointer(); if ( !fp ) { return; } for ( random = randomlist; random; random = random->next ) { fprintf( fp, "%s = {", random->string ); for ( rs = random->firstrandomstring; rs; rs = rs->next ) { fprintf( fp, "\"%s\"", rs->string ); if ( rs->next ) { fprintf( fp, ", " ); } else { fprintf( fp, "}\n" );} } //end for } //end for } //end of the function BotDumpRandomStringList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_randomlist_t *BotLoadRandomStrings( char *filename ) { int pass, size; char *ptr = NULL, chatmessagestring[MAX_MESSAGE_SIZE]; source_t *source; token_t token; bot_randomlist_t *randomlist, *lastrandom, *random; bot_randomstring_t *randomstring; #ifdef DEBUG int starttime = Sys_MilliSeconds(); #endif //DEBUG size = 0; randomlist = NULL; random = NULL; //the synonyms are parsed in two phases for ( pass = 0; pass < 2; pass++ ) { // if ( pass && size ) { ptr = (char *) GetClearedHunkMemory( size ); } // source = LoadSourceFile( filename ); if ( !source ) { botimport.Print( PRT_ERROR, "counldn't load %s\n", filename ); return NULL; } //end if // randomlist = NULL; //list lastrandom = NULL; //last // while ( PC_ReadToken( source, &token ) ) { size_t len; if ( token.type != TT_NAME ) { SourceError( source, "unknown random %s", token.string ); FreeSource( source ); return NULL; } //end if len = strlen(token.string) + 1; len = PAD(len, sizeof(long)); size += sizeof(bot_randomlist_t) + len; if ( pass && ptr ) { random = (bot_randomlist_t *) ptr; ptr += sizeof( bot_randomlist_t ); random->string = ptr; ptr += len; strcpy( random->string, token.string ); random->firstrandomstring = NULL; random->numstrings = 0; // if ( lastrandom ) { lastrandom->next = random; } else { randomlist = random;} lastrandom = random; } //end if if ( !PC_ExpectTokenString( source, "=" ) || !PC_ExpectTokenString( source, "{" ) ) { FreeSource( source ); return NULL; } //end if while ( !PC_CheckTokenString( source, "}" ) ) { if ( !BotLoadChatMessage( source, chatmessagestring ) ) { FreeSource( source ); return NULL; } //end if len = strlen(chatmessagestring) + 1; len = PAD(len, sizeof(long)); size += sizeof(bot_randomstring_t) + len; if ( pass && ptr ) { randomstring = (bot_randomstring_t *) ptr; ptr += sizeof( bot_randomstring_t ); randomstring->string = ptr; ptr += len; strcpy( randomstring->string, chatmessagestring ); // random->numstrings++; randomstring->next = random->firstrandomstring; random->firstrandomstring = randomstring; } //end if } //end while } //end while //free the source after one pass FreeSource( source ); } //end for botimport.Print( PRT_MESSAGE, "loaded %s\n", filename ); // #ifdef DEBUG botimport.Print( PRT_MESSAGE, "random strings %d msec\n", Sys_MilliSeconds() - starttime ); //BotDumpRandomStringList(randomlist); #endif //DEBUG // return randomlist; } //end of the function BotLoadRandomStrings //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== char *RandomString( char *name ) { bot_randomlist_t *random; bot_randomstring_t *rs; int i; for ( random = randomstrings; random; random = random->next ) { if ( !strcmp( random->string, name ) ) { i = random() * random->numstrings; for ( rs = random->firstrandomstring; rs; rs = rs->next ) { if ( --i < 0 ) { break; } } //end for if ( rs ) { return rs->string; } //end if } //end for } //end for return NULL; } //end of the function RandomString //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpMatchTemplates( bot_matchtemplate_t *matches ) { FILE *fp; bot_matchtemplate_t *mt; bot_matchpiece_t *mp; bot_matchstring_t *ms; fp = Log_FilePointer(); if ( !fp ) { return; } for ( mt = matches; mt; mt = mt->next ) { //fprintf(fp, "%8d { "); for ( mp = mt->first; mp; mp = mp->next ) { if ( mp->type == MT_STRING ) { for ( ms = mp->firststring; ms; ms = ms->next ) { fprintf( fp, "\"%s\"", ms->string ); if ( ms->next ) { fprintf( fp, "|" ); } } //end for } //end if else if ( mp->type == MT_VARIABLE ) { fprintf( fp, "%d", mp->variable ); } //end else if if ( mp->next ) { fprintf( fp, ", " ); } } //end for fprintf( fp, " = (%d, %d);}\n", mt->type, mt->subtype ); } //end for } //end of the function BotDumpMatchTemplates //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFreeMatchPieces( bot_matchpiece_t *matchpieces ) { bot_matchpiece_t *mp, *nextmp; bot_matchstring_t *ms, *nextms; for ( mp = matchpieces; mp; mp = nextmp ) { nextmp = mp->next; if ( mp->type == MT_STRING ) { for ( ms = mp->firststring; ms; ms = nextms ) { nextms = ms->next; FreeMemory( ms ); } //end for } //end if FreeMemory( mp ); } //end for } //end of the function BotFreeMatchPieces //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_matchpiece_t *BotLoadMatchPieces( source_t *source, char *endtoken ) { int lastwasvariable, emptystring; token_t token; bot_matchpiece_t *matchpiece, *firstpiece, *lastpiece; bot_matchstring_t *matchstring, *lastmatchstring; firstpiece = NULL; lastpiece = NULL; // lastwasvariable = qfalse; // while ( PC_ReadToken( source, &token ) ) { if ( token.type == TT_NUMBER && ( token.subtype & TT_INTEGER ) ) { if (token.intvalue >= MAX_MATCHVARIABLES) { SourceError( source, "can't have more than %d match variables", MAX_MATCHVARIABLES ); FreeSource( source ); BotFreeMatchPieces( firstpiece ); return NULL; } //end if if ( lastwasvariable ) { SourceError( source, "not allowed to have adjacent variables" ); FreeSource( source ); BotFreeMatchPieces( firstpiece ); return NULL; } //end if lastwasvariable = qtrue; // matchpiece = (bot_matchpiece_t *) GetClearedHunkMemory( sizeof( bot_matchpiece_t ) ); matchpiece->type = MT_VARIABLE; matchpiece->variable = token.intvalue; matchpiece->next = NULL; if ( lastpiece ) { lastpiece->next = matchpiece; } else { firstpiece = matchpiece;} lastpiece = matchpiece; } //end if else if ( token.type == TT_STRING ) { // matchpiece = (bot_matchpiece_t *) GetClearedHunkMemory( sizeof( bot_matchpiece_t ) ); matchpiece->firststring = NULL; matchpiece->type = MT_STRING; matchpiece->variable = 0; matchpiece->next = NULL; if ( lastpiece ) { lastpiece->next = matchpiece; } else { firstpiece = matchpiece;} lastpiece = matchpiece; // lastmatchstring = NULL; emptystring = qfalse; // do { if ( matchpiece->firststring ) { if ( !PC_ExpectTokenType( source, TT_STRING, 0, &token ) ) { FreeSource( source ); BotFreeMatchPieces( firstpiece ); return NULL; } //end if } //end if StripDoubleQuotes( token.string ); matchstring = (bot_matchstring_t *) GetClearedHunkMemory( sizeof( bot_matchstring_t ) + strlen( token.string ) + 1 ); matchstring->string = (char *) matchstring + sizeof( bot_matchstring_t ); strcpy( matchstring->string, token.string ); if ( !strlen( token.string ) ) { emptystring = qtrue; } matchstring->next = NULL; if ( lastmatchstring ) { lastmatchstring->next = matchstring; } else { matchpiece->firststring = matchstring;} lastmatchstring = matchstring; } while ( PC_CheckTokenString( source, "|" ) ); //if there was no empty string found if ( !emptystring ) { lastwasvariable = qfalse; } } //end if else { SourceError( source, "invalid token %s", token.string ); FreeSource( source ); BotFreeMatchPieces( firstpiece ); return NULL; } //end else if ( PC_CheckTokenString( source, endtoken ) ) { break; } if ( !PC_ExpectTokenString( source, "," ) ) { FreeSource( source ); BotFreeMatchPieces( firstpiece ); return NULL; } //end if } //end while return firstpiece; } //end of the function BotLoadMatchPieces //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFreeMatchTemplates( bot_matchtemplate_t *mt ) { bot_matchtemplate_t *nextmt; for (; mt; mt = nextmt ) { nextmt = mt->next; BotFreeMatchPieces( mt->first ); FreeMemory( mt ); } //end for } //end of the function BotFreeMatchTemplates //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_matchtemplate_t *BotLoadMatchTemplates( char *matchfile ) { source_t *source; token_t token; bot_matchtemplate_t *matchtemplate, *matches, *lastmatch; unsigned long int context; source = LoadSourceFile( matchfile ); if ( !source ) { botimport.Print( PRT_ERROR, "counldn't load %s\n", matchfile ); return NULL; } //end if // matches = NULL; //list with matches lastmatch = NULL; //last match in the list while ( PC_ReadToken( source, &token ) ) { if ( token.type != TT_NUMBER || !( token.subtype & TT_INTEGER ) ) { SourceError( source, "expected integer, found %s", token.string ); BotFreeMatchTemplates( matches ); FreeSource( source ); return NULL; } //end if //the context context = token.intvalue; // if ( !PC_ExpectTokenString( source, "{" ) ) { BotFreeMatchTemplates( matches ); FreeSource( source ); return NULL; } //end if // while ( PC_ReadToken( source, &token ) ) { if ( !strcmp( token.string, "}" ) ) { break; } // PC_UnreadLastToken( source ); // matchtemplate = (bot_matchtemplate_t *) GetClearedHunkMemory( sizeof( bot_matchtemplate_t ) ); matchtemplate->context = context; matchtemplate->next = NULL; //add the match template to the list if ( lastmatch ) { lastmatch->next = matchtemplate; } else { matches = matchtemplate;} lastmatch = matchtemplate; //load the match template matchtemplate->first = BotLoadMatchPieces( source, "=" ); if ( !matchtemplate->first ) { BotFreeMatchTemplates( matches ); return NULL; } //end if //read the match type if ( !PC_ExpectTokenString( source, "(" ) || !PC_ExpectTokenType( source, TT_NUMBER, TT_INTEGER, &token ) ) { BotFreeMatchTemplates( matches ); FreeSource( source ); return NULL; } //end if matchtemplate->type = token.intvalue; //read the match subtype if ( !PC_ExpectTokenString( source, "," ) || !PC_ExpectTokenType( source, TT_NUMBER, TT_INTEGER, &token ) ) { BotFreeMatchTemplates( matches ); FreeSource( source ); return NULL; } //end if matchtemplate->subtype = token.intvalue; //read trailing punctuations if ( !PC_ExpectTokenString( source, ")" ) || !PC_ExpectTokenString( source, ";" ) ) { BotFreeMatchTemplates( matches ); FreeSource( source ); return NULL; } //end if } //end while } //end while //free the source FreeSource( source ); botimport.Print( PRT_MESSAGE, "loaded %s\n", matchfile ); // //BotDumpMatchTemplates(matches); // return matches; } //end of the function BotLoadMatchTemplates //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int StringsMatch( bot_matchpiece_t *pieces, bot_match_t *match ) { int lastvariable, index; char *strptr, *newstrptr; bot_matchpiece_t *mp; bot_matchstring_t *ms; //no last variable lastvariable = -1; //pointer to the string to compare the match string with strptr = match->string; //Log_Write("match: %s", strptr); //compare the string with the current match string for ( mp = pieces; mp; mp = mp->next ) { //if it is a piece of string if ( mp->type == MT_STRING ) { newstrptr = NULL; for ( ms = mp->firststring; ms; ms = ms->next ) { if ( !strlen( ms->string ) ) { newstrptr = strptr; break; } //end if //Log_Write("MT_STRING: %s", mp->string); index = StringContains( strptr, ms->string, qfalse ); if ( index >= 0 ) { newstrptr = strptr + index; if ( lastvariable >= 0 ) { match->variables[lastvariable].length = newstrptr - match->variables[lastvariable].ptr; lastvariable = -1; break; } //end if else if ( index == 0 ) { break; } //end else newstrptr = NULL; } //end if } //end for if ( !newstrptr ) { return qfalse; } strptr = newstrptr + strlen( ms->string ); } //end if //if it is a variable piece of string else if ( mp->type == MT_VARIABLE ) { //Log_Write("MT_VARIABLE"); match->variables[mp->variable].ptr = strptr; lastvariable = mp->variable; } //end else if } //end for //if a match was found if ( !mp && ( lastvariable >= 0 || !strlen( strptr ) ) ) { //if the last piece was a variable string if ( lastvariable >= 0 ) { match->variables[lastvariable].length = strlen( match->variables[lastvariable].ptr ); } //end if return qtrue; } //end if return qfalse; } //end of the function StringsMatch //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotFindMatch( char *str, bot_match_t *match, unsigned long int context ) { int i; bot_matchtemplate_t *ms; Q_strncpyz( match->string, str, MAX_MESSAGE_SIZE ); //remove any trailing enters while ( strlen( match->string ) && match->string[strlen( match->string ) - 1] == '\n' ) { match->string[strlen( match->string ) - 1] = '\0'; } //end while //compare the string with all the match strings for ( ms = matchtemplates; ms; ms = ms->next ) { if ( !( ms->context & context ) ) { continue; } //reset the match variable pointers for ( i = 0; i < MAX_MATCHVARIABLES; i++ ) match->variables[i].ptr = NULL; // if ( StringsMatch( ms->first, match ) ) { match->type = ms->type; match->subtype = ms->subtype; return qtrue; } //end if } //end for return qfalse; } //end of the function BotFindMatch //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotMatchVariable( bot_match_t *match, int variable, char *buf, int size ) { if ( variable < 0 || variable >= MAX_MATCHVARIABLES ) { botimport.Print( PRT_FATAL, "BotMatchVariable: variable out of range\n" ); strcpy( buf, "" ); return; } //end if if ( match->variables[variable].ptr ) { if ( match->variables[variable].length < size ) { size = match->variables[variable].length + 1; } strncpy( buf, match->variables[variable].ptr, size - 1 ); buf[size - 1] = '\0'; } //end if else { strcpy( buf, "" ); } //end else } //end of the function BotMatchVariable //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_stringlist_t *BotFindStringInList( bot_stringlist_t *list, char *string ) { bot_stringlist_t *s; for ( s = list; s; s = s->next ) { if ( !strcmp( s->string, string ) ) { return s; } } //end for return NULL; } //end of the function BotFindStringInList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_stringlist_t *BotCheckChatMessageIntegrety( char *message, bot_stringlist_t *stringlist ) { int i; char *msgptr; char temp[MAX_MESSAGE_SIZE]; bot_stringlist_t *s; msgptr = message; // while ( *msgptr ) { if ( *msgptr == ESCAPE_CHAR ) { msgptr++; switch ( *msgptr ) { case 'v': //variable { //step over the 'v' msgptr++; while ( *msgptr && *msgptr != ESCAPE_CHAR ) msgptr++; //step over the trailing escape char if ( *msgptr ) { msgptr++; } break; } //end case case 'r': //random { //step over the 'r' msgptr++; for ( i = 0; ( *msgptr && *msgptr != ESCAPE_CHAR ); i++ ) { temp[i] = *msgptr++; } //end while temp[i] = '\0'; //step over the trailing escape char if ( *msgptr ) { msgptr++; } //find the random keyword if ( !RandomString( temp ) ) { if ( !BotFindStringInList( stringlist, temp ) ) { Log_Write( "%s = {\"%s\"} //MISSING RANDOM\r\n", temp, temp ); s = GetClearedMemory( sizeof( bot_stringlist_t ) + strlen( temp ) + 1 ); s->string = (char *) s + sizeof( bot_stringlist_t ); strcpy( s->string, temp ); s->next = stringlist; stringlist = s; } //end if } //end if break; } //end case default: { botimport.Print( PRT_FATAL, "BotCheckChatMessageIntegrety: message \"%s\" invalid escape char\n", message ); break; } //end default } //end switch } //end if else { msgptr++; } //end else } //end while return stringlist; } //end of the function BotCheckChatMessageIntegrety //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotCheckReplyChatIntegrety( bot_replychat_t *replychat ) { bot_replychat_t *rp; bot_chatmessage_t *cm; bot_stringlist_t *stringlist, *s, *nexts; stringlist = NULL; for ( rp = replychat; rp; rp = rp->next ) { for ( cm = rp->firstchatmessage; cm; cm = cm->next ) { stringlist = BotCheckChatMessageIntegrety( cm->chatmessage, stringlist ); } //end for } //end for for ( s = stringlist; s; s = nexts ) { nexts = s->next; FreeMemory( s ); } //end for } //end of the function BotCheckReplyChatIntegrety //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotCheckInitialChatIntegrety( bot_chat_t *chat ) { bot_chattype_t *t; bot_chatmessage_t *cm; bot_stringlist_t *stringlist, *s, *nexts; stringlist = NULL; for ( t = chat->types; t; t = t->next ) { for ( cm = t->firstchatmessage; cm; cm = cm->next ) { stringlist = BotCheckChatMessageIntegrety( cm->chatmessage, stringlist ); } //end for } //end for for ( s = stringlist; s; s = nexts ) { nexts = s->next; FreeMemory( s ); } //end for } //end of the function BotCheckInitialChatIntegrety //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpReplyChat( bot_replychat_t *replychat ) { FILE *fp; bot_replychat_t *rp; bot_replychatkey_t *key; bot_chatmessage_t *cm; bot_matchpiece_t *mp; fp = Log_FilePointer(); if ( !fp ) { return; } fprintf( fp, "BotDumpReplyChat:\n" ); for ( rp = replychat; rp; rp = rp->next ) { fprintf( fp, "[" ); for ( key = rp->keys; key; key = key->next ) { if ( key->flags & RCKFL_AND ) { fprintf( fp, "&" ); } else if ( key->flags & RCKFL_NOT ) { fprintf( fp, "!" ); } // if ( key->flags & RCKFL_NAME ) { fprintf( fp, "name" ); } else if ( key->flags & RCKFL_GENDERFEMALE ) { fprintf( fp, "female" ); } else if ( key->flags & RCKFL_GENDERMALE ) { fprintf( fp, "male" ); } else if ( key->flags & RCKFL_GENDERLESS ) { fprintf( fp, "it" ); } else if ( key->flags & RCKFL_VARIABLES ) { fprintf( fp, "(" ); for ( mp = key->match; mp; mp = mp->next ) { if ( mp->type == MT_STRING ) { fprintf( fp, "\"%s\"", mp->firststring->string ); } else { fprintf( fp, "%d", mp->variable );} if ( mp->next ) { fprintf( fp, ", " ); } } //end for fprintf( fp, ")" ); } //end if else if ( key->flags & RCKFL_STRING ) { fprintf( fp, "\"%s\"", key->string ); } //end if if ( key->next ) { fprintf( fp, ", " ); } else { fprintf( fp, "] = %1.0f\n", rp->priority );} } //end for fprintf( fp, "{\n" ); for ( cm = rp->firstchatmessage; cm; cm = cm->next ) { fprintf( fp, "\t\"%s\";\n", cm->chatmessage ); } //end for fprintf( fp, "}\n" ); } //end for } //end of the function BotDumpReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFreeReplyChat( bot_replychat_t *replychat ) { bot_replychat_t *rp, *nextrp; bot_replychatkey_t *key, *nextkey; bot_chatmessage_t *cm, *nextcm; for ( rp = replychat; rp; rp = nextrp ) { nextrp = rp->next; for ( key = rp->keys; key; key = nextkey ) { nextkey = key->next; if ( key->match ) { BotFreeMatchPieces( key->match ); } if ( key->string ) { FreeMemory( key->string ); } FreeMemory( key ); } //end for for ( cm = rp->firstchatmessage; cm; cm = nextcm ) { nextcm = cm->next; FreeMemory( cm ); } //end for FreeMemory( rp ); } //end for } //end of the function BotFreeReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_replychat_t *BotLoadReplyChat( char *filename ) { char chatmessagestring[MAX_MESSAGE_SIZE]; char namebuffer[MAX_MESSAGE_SIZE]; source_t *source; token_t token; bot_chatmessage_t *chatmessage = NULL; bot_replychat_t *replychat, *replychatlist; bot_replychatkey_t *key; source = LoadSourceFile( filename ); if ( !source ) { botimport.Print( PRT_ERROR, "counldn't load %s\n", filename ); return NULL; } //end if // replychatlist = NULL; // while ( PC_ReadToken( source, &token ) ) { if ( strcmp( token.string, "[" ) ) { SourceError( source, "expected [, found %s", token.string ); BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if // replychat = GetClearedHunkMemory( sizeof( bot_replychat_t ) ); replychat->keys = NULL; replychat->next = replychatlist; replychatlist = replychat; //read the keys, there must be at least one key do { //allocate a key key = (bot_replychatkey_t *) GetClearedHunkMemory( sizeof( bot_replychatkey_t ) ); key->flags = 0; key->string = NULL; key->match = NULL; key->next = replychat->keys; replychat->keys = key; //check for MUST BE PRESENT and MUST BE ABSENT keys if ( PC_CheckTokenString( source, "&" ) ) { key->flags |= RCKFL_AND; } else if ( PC_CheckTokenString( source, "!" ) ) { key->flags |= RCKFL_NOT; } //special keys if ( PC_CheckTokenString( source, "name" ) ) { key->flags |= RCKFL_NAME; } else if ( PC_CheckTokenString( source, "female" ) ) { key->flags |= RCKFL_GENDERFEMALE; } else if ( PC_CheckTokenString( source, "male" ) ) { key->flags |= RCKFL_GENDERMALE; } else if ( PC_CheckTokenString( source, "it" ) ) { key->flags |= RCKFL_GENDERLESS; } else if ( PC_CheckTokenString( source, "(" ) ) { //match key key->flags |= RCKFL_VARIABLES; key->match = BotLoadMatchPieces( source, ")" ); if ( !key->match ) { BotFreeReplyChat( replychatlist ); return NULL; } //end if } //end else if else if ( PC_CheckTokenString( source, "<" ) ) { //bot names key->flags |= RCKFL_BOTNAMES; strcpy( namebuffer, "" ); do { if ( !PC_ExpectTokenType( source, TT_STRING, 0, &token ) ) { BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if StripDoubleQuotes( token.string ); if ( strlen( namebuffer ) ) { strcat( namebuffer, "\\" ); } strcat( namebuffer, token.string ); } while ( PC_CheckTokenString( source, "," ) ); if ( !PC_ExpectTokenString( source, ">" ) ) { BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if key->string = (char *) GetClearedHunkMemory( strlen( namebuffer ) + 1 ); strcpy( key->string, namebuffer ); } //end else if else //normal string key { key->flags |= RCKFL_STRING; if ( !PC_ExpectTokenType( source, TT_STRING, 0, &token ) ) { BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if StripDoubleQuotes( token.string ); key->string = (char *) GetClearedHunkMemory( strlen( token.string ) + 1 ); strcpy( key->string, token.string ); } //end else // PC_CheckTokenString( source, "," ); } while ( !PC_CheckTokenString( source, "]" ) ); //read the = sign and the priority if ( !PC_ExpectTokenString( source, "=" ) || !PC_ExpectTokenType( source, TT_NUMBER, 0, &token ) ) { BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if replychat->priority = token.floatvalue; //read the leading { if ( !PC_ExpectTokenString( source, "{" ) ) { BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if replychat->numchatmessages = 0; //while the trailing } is not found while ( !PC_CheckTokenString( source, "}" ) ) { if ( !BotLoadChatMessage( source, chatmessagestring ) ) { BotFreeReplyChat( replychatlist ); FreeSource( source ); return NULL; } //end if chatmessage = (bot_chatmessage_t *) GetClearedHunkMemory( sizeof( bot_chatmessage_t ) + strlen( chatmessagestring ) + 1 ); chatmessage->chatmessage = (char *) chatmessage + sizeof( bot_chatmessage_t ); strcpy( chatmessage->chatmessage, chatmessagestring ); chatmessage->time = -2 * CHATMESSAGE_RECENTTIME; chatmessage->next = replychat->firstchatmessage; //add the chat message to the reply chat replychat->firstchatmessage = chatmessage; replychat->numchatmessages++; } //end while } //end while FreeSource( source ); botimport.Print( PRT_MESSAGE, "loaded %s\n", filename ); // //BotDumpReplyChat(replychatlist); if ( botDeveloper ) { BotCheckReplyChatIntegrety( replychatlist ); } //end if // if ( !replychatlist ) { botimport.Print( PRT_MESSAGE, "no rchats\n" ); } // return replychatlist; } //end of the function BotLoadReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpInitialChat( bot_chat_t *chat ) { bot_chattype_t *t; bot_chatmessage_t *m; Log_Write( "{" ); for ( t = chat->types; t; t = t->next ) { Log_Write( " type \"%s\"", t->name ); Log_Write( " {" ); Log_Write( " numchatmessages = %d", t->numchatmessages ); for ( m = t->firstchatmessage; m; m = m->next ) { Log_Write( " \"%s\"", m->chatmessage ); } //end for Log_Write( " }" ); } //end for Log_Write( "}" ); } //end of the function BotDumpInitialChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== bot_chat_t *BotLoadInitialChat( char *chatfile, char *chatname ) { int pass, foundchat, indent, size; char *ptr = NULL; char chatmessagestring[MAX_MESSAGE_SIZE]; source_t *source; token_t token; bot_chat_t *chat = NULL; bot_chattype_t *chattype = NULL; bot_chatmessage_t *chatmessage = NULL; #ifdef DEBUG int starttime; starttime = Sys_MilliSeconds(); #endif //DEBUG // size = 0; foundchat = qfalse; //a bot chat is parsed in two phases for ( pass = 0; pass < 2; pass++ ) { //allocate memory if ( pass && size ) { ptr = (char *) GetClearedMemory( size ); } //load the source file source = LoadSourceFile( chatfile ); if ( !source ) { botimport.Print( PRT_ERROR, "counldn't load %s\n", chatfile ); return NULL; } //end if //chat structure if ( pass ) { chat = (bot_chat_t *) ptr; ptr += sizeof( bot_chat_t ); } //end if size = sizeof( bot_chat_t ); // while ( PC_ReadToken( source, &token ) ) { if ( !strcmp( token.string, "chat" ) ) { if ( !PC_ExpectTokenType( source, TT_STRING, 0, &token ) ) { FreeSource( source ); return NULL; } //end if StripDoubleQuotes( token.string ); //after the chat name we expect an opening brace if ( !PC_ExpectTokenString( source, "{" ) ) { FreeSource( source ); return NULL; } //end if //if the chat name is found if ( !Q_stricmp( token.string, chatname ) ) { foundchat = qtrue; //read the chat types while ( 1 ) { if ( !PC_ExpectAnyToken( source, &token ) ) { FreeSource( source ); return NULL; } //end if if ( !strcmp( token.string, "}" ) ) { break; } if ( strcmp( token.string, "type" ) ) { SourceError( source, "expected type found %s", token.string ); FreeSource( source ); return NULL; } //end if //expect the chat type name if ( !PC_ExpectTokenType( source, TT_STRING, 0, &token ) || !PC_ExpectTokenString( source, "{" ) ) { FreeSource( source ); return NULL; } //end if StripDoubleQuotes( token.string ); if ( pass && ptr ) { chattype = (bot_chattype_t *) ptr; Q_strncpyz( chattype->name, token.string, MAX_CHATTYPE_NAME ); chattype->firstchatmessage = NULL; //add the chat type to the chat chattype->next = chat->types; chat->types = chattype; // ptr += sizeof( bot_chattype_t ); } //end if size += sizeof( bot_chattype_t ); //read the chat messages while ( !PC_CheckTokenString( source, "}" ) ) { size_t len; if ( !BotLoadChatMessage( source, chatmessagestring ) ) { FreeSource( source ); return NULL; } //end if len = strlen(chatmessagestring) + 1; len = PAD(len, sizeof(long)); if ( pass && ptr ) { chatmessage = (bot_chatmessage_t *) ptr; chatmessage->time = -2 * CHATMESSAGE_RECENTTIME; //put the chat message in the list chatmessage->next = chattype->firstchatmessage; chattype->firstchatmessage = chatmessage; //store the chat message ptr += sizeof( bot_chatmessage_t ); chatmessage->chatmessage = ptr; strcpy( chatmessage->chatmessage, chatmessagestring ); ptr += len; //the number of chat messages increased chattype->numchatmessages++; } //end if size += sizeof(bot_chatmessage_t) + len; } //end if } //end while } //end if else //skip the bot chat { indent = 1; while ( indent ) { if ( !PC_ExpectAnyToken( source, &token ) ) { FreeSource( source ); return NULL; } //end if if ( !strcmp( token.string, "{" ) ) { indent++; } else if ( !strcmp( token.string, "}" ) ) { indent--; } } //end while } //end else } //end if else { SourceError( source, "unknown definition %s", token.string ); FreeSource( source ); return NULL; } //end else } //end while //free the source FreeSource( source ); //if the requested character is not found if ( !foundchat ) { botimport.Print( PRT_ERROR, "couldn't find chat %s in %s\n", chatname, chatfile ); return NULL; } //end if } //end for // botimport.Print( PRT_MESSAGE, "loaded %s from %s\n", chatname, chatfile ); // //BotDumpInitialChat(chat); if ( botDeveloper ) { BotCheckInitialChatIntegrety( chat ); } //end if #ifdef DEBUG botimport.Print( PRT_MESSAGE, "initial chats loaded in %d msec\n", Sys_MilliSeconds() - starttime ); #endif //DEBUG //character was read successfully return chat; } //end of the function BotLoadInitialChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFreeChatFile( int chatstate ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } if ( cs->chat ) { FreeMemory( cs->chat ); } cs->chat = NULL; } //end of the function BotFreeChatFile //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotLoadChatFile( int chatstate, char *chatfile, char *chatname ) { bot_chatstate_t *cs; int n, avail = 0; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return BLERR_CANNOTLOADICHAT; } BotFreeChatFile( chatstate ); if ( !LibVarGetValue( "bot_reloadcharacters" ) ) { avail = -1; for ( n = 0; n < MAX_CLIENTS; n++ ) { if ( !ichatdata[n].inuse ) { if ( avail == -1 ) { avail = n; } continue; } if ( strcmp( chatfile, ichatdata[n].filename ) != 0 ) { continue; } if ( strcmp( chatname, ichatdata[n].chatname ) != 0 ) { continue; } cs->chat = ichatdata[n].chat; // botimport.Print( PRT_MESSAGE, "retained %s from %s\n", chatname, chatfile ); return BLERR_NOERROR; } if ( avail == -1 ) { botimport.Print( PRT_FATAL, "ichatdata table full; couldn't load chat %s from %s\n", chatname, chatfile ); return BLERR_CANNOTLOADICHAT; } } cs->chat = BotLoadInitialChat( chatfile, chatname ); if ( !cs->chat ) { botimport.Print( PRT_FATAL, "couldn't load chat %s from %s\n", chatname, chatfile ); return BLERR_CANNOTLOADICHAT; } //end if if ( !LibVarGetValue( "bot_reloadcharacters" ) ) { ichatdata[avail].chat = cs->chat; Q_strncpyz( ichatdata[avail].chatname, chatname, sizeof( ichatdata[avail].chatname ) ); Q_strncpyz( ichatdata[avail].filename, chatfile, sizeof( ichatdata[avail].filename ) ); ichatdata[avail].inuse = qtrue; } //end if return BLERR_NOERROR; } //end of the function BotLoadChatFile //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotExpandChatMessage( char *outmessage, char *message, unsigned long mcontext, bot_matchvariable_t *variables, unsigned long vcontext, int reply ) { int num, len, i, expansion; char *outputbuf, *ptr, *msgptr; char temp[MAX_MESSAGE_SIZE]; expansion = qfalse; msgptr = message; outputbuf = outmessage; len = 0; // while ( *msgptr ) { if ( *msgptr == ESCAPE_CHAR ) { msgptr++; switch ( *msgptr ) { case 'v': //variable { msgptr++; num = 0; while ( *msgptr && *msgptr != ESCAPE_CHAR ) { num = num * 10 + ( *msgptr++ ) - '0'; } //end while //step over the trailing escape char if ( *msgptr ) { msgptr++; } if ( num > MAX_MATCHVARIABLES ) { botimport.Print( PRT_ERROR, "BotConstructChat: message %s variable %d out of range\n", message, num ); return qfalse; } //end if ptr = variables[num].ptr; if ( ptr ) { for ( i = 0; i < variables[num].length; i++ ) { temp[i] = ptr[i]; } //end for temp[i] = 0; //if it's a reply message if ( reply ) { //replace the reply synonyms in the variables BotReplaceReplySynonyms( temp, vcontext ); } //end if else { //replace synonyms in the variable context BotReplaceSynonyms( temp, vcontext ); } //end else // if ( len + strlen( temp ) >= MAX_MESSAGE_SIZE ) { botimport.Print( PRT_ERROR, "BotConstructChat: message %s too long\n", message ); return qfalse; } //end if strcpy( &outputbuf[len], temp ); len += strlen( temp ); } //end if break; } //end case case 'r': //random { msgptr++; for ( i = 0; ( *msgptr && *msgptr != ESCAPE_CHAR ); i++ ) { temp[i] = *msgptr++; } //end while temp[i] = '\0'; //step over the trailing escape char if ( *msgptr ) { msgptr++; } //find the random keyword ptr = RandomString( temp ); if ( !ptr ) { botimport.Print( PRT_ERROR, "BotConstructChat: unknown random string %s\n", temp ); return qfalse; } //end if if ( len + strlen( ptr ) >= MAX_MESSAGE_SIZE ) { botimport.Print( PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message ); return qfalse; } //end if strcpy( &outputbuf[len], ptr ); len += strlen( ptr ); expansion = qtrue; break; } //end case default: { botimport.Print( PRT_FATAL, "BotConstructChat: message \"%s\" invalid escape char\n", message ); break; } //end default } //end switch } //end if else { outputbuf[len++] = *msgptr++; if ( len >= MAX_MESSAGE_SIZE ) { botimport.Print( PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message ); break; } //end if } //end else } //end while outputbuf[len] = '\0'; //replace synonyms weighted in the message context BotReplaceWeightedSynonyms( outputbuf, mcontext ); //return true if a random was expanded return expansion; } //end of the function BotExpandChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotConstructChatMessage( bot_chatstate_t *chatstate, char *message, unsigned long mcontext, bot_matchvariable_t *variables, unsigned long vcontext, int reply ) { int i; char srcmessage[MAX_MESSAGE_SIZE]; strcpy( srcmessage, message ); for ( i = 0; i < 10; i++ ) { if ( !BotExpandChatMessage( chatstate->chatmessage, srcmessage, mcontext, variables, vcontext, reply ) ) { break; } //end if strcpy( srcmessage, chatstate->chatmessage ); } //end for if ( i >= 10 ) { botimport.Print( PRT_WARNING, "too many expansions in chat message\n" ); botimport.Print( PRT_WARNING, "%s\n", chatstate->chatmessage ); } //end if } //end of the function BotConstructChatMessage //=========================================================================== // randomly chooses one of the chat message of the given type // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== char *BotChooseInitialChatMessage( bot_chatstate_t *cs, char *type ) { int n, numchatmessages; float besttime; bot_chattype_t *t; bot_chatmessage_t *m, *bestchatmessage; bot_chat_t *chat; chat = cs->chat; for ( t = chat->types; t; t = t->next ) { if ( !Q_stricmp( t->name, type ) ) { numchatmessages = 0; for ( m = t->firstchatmessage; m; m = m->next ) { if ( m->time > AAS_Time() ) { continue; } numchatmessages++; } //end if //if all chat messages have been used recently if ( numchatmessages <= 0 ) { besttime = 0; bestchatmessage = NULL; for ( m = t->firstchatmessage; m; m = m->next ) { if ( !besttime || m->time < besttime ) { bestchatmessage = m; besttime = m->time; } //end if } //end for if ( bestchatmessage ) { return bestchatmessage->chatmessage; } } //end if else //choose a chat message randomly { n = random() * numchatmessages; for ( m = t->firstchatmessage; m; m = m->next ) { if ( m->time > AAS_Time() ) { continue; } if ( --n < 0 ) { m->time = AAS_Time() + CHATMESSAGE_RECENTTIME; return m->chatmessage; } //end if } //end for } //end else return NULL; } //end if } //end for return NULL; } //end of the function BotChooseInitialChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotNumInitialChats( int chatstate, char *type ) { bot_chatstate_t *cs; bot_chattype_t *t; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return 0; } for ( t = cs->chat->types; t; t = t->next ) { if ( !Q_stricmp( t->name, type ) ) { if ( LibVarGetValue( "bot_testichat" ) ) { botimport.Print( PRT_MESSAGE, "%s has %d chat lines\n", type, t->numchatmessages ); botimport.Print( PRT_MESSAGE, "-------------------\n" ); } return t->numchatmessages; } //end if } //end for return 0; } //end of the function BotNumInitialChats //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotInitialChat( int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { char *message; bot_matchvariable_t variables[MAX_MATCHVARIABLES]; bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } //if no chat file is loaded if ( !cs->chat ) { return; } //choose a chat message randomly of the given type message = BotChooseInitialChatMessage( cs, type ); //if there's no message of the given type if ( !message ) { #ifdef DEBUG botimport.Print( PRT_MESSAGE, "no chat messages of type %s\n", type ); #endif //DEBUG return; } //end if // memset( variables, 0, sizeof( variables ) ); if ( var0 ) { variables[0].ptr = var0; variables[0].length = strlen( var0 ); } if ( var1 ) { variables[1].ptr = var1; variables[1].length = strlen( var1 ); } if ( var2 ) { variables[2].ptr = var2; variables[2].length = strlen( var2 ); } if ( var3 ) { variables[3].ptr = var3; variables[3].length = strlen( var3 ); } if ( var4 ) { variables[4].ptr = var4; variables[4].length = strlen( var4 ); } if ( var5 ) { variables[5].ptr = var5; variables[5].length = strlen( var5 ); } if ( var6 ) { variables[6].ptr = var6; variables[6].length = strlen( var6 ); } if ( var7 ) { variables[7].ptr = var7; variables[7].length = strlen( var7 ); } // BotConstructChatMessage( cs, message, mcontext, variables, 0, qfalse ); } //end of the function BotInitialChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotPrintReplyChatKeys( bot_replychat_t *replychat ) { bot_replychatkey_t *key; bot_matchpiece_t *mp; botimport.Print( PRT_MESSAGE, "[" ); for ( key = replychat->keys; key; key = key->next ) { if ( key->flags & RCKFL_AND ) { botimport.Print( PRT_MESSAGE, "&" ); } else if ( key->flags & RCKFL_NOT ) { botimport.Print( PRT_MESSAGE, "!" ); } // if ( key->flags & RCKFL_NAME ) { botimport.Print( PRT_MESSAGE, "name" ); } else if ( key->flags & RCKFL_GENDERFEMALE ) { botimport.Print( PRT_MESSAGE, "female" ); } else if ( key->flags & RCKFL_GENDERMALE ) { botimport.Print( PRT_MESSAGE, "male" ); } else if ( key->flags & RCKFL_GENDERLESS ) { botimport.Print( PRT_MESSAGE, "it" ); } else if ( key->flags & RCKFL_VARIABLES ) { botimport.Print( PRT_MESSAGE, "(" ); for ( mp = key->match; mp; mp = mp->next ) { if ( mp->type == MT_STRING ) { botimport.Print( PRT_MESSAGE, "\"%s\"", mp->firststring->string ); } else { botimport.Print( PRT_MESSAGE, "%d", mp->variable );} if ( mp->next ) { botimport.Print( PRT_MESSAGE, ", " ); } } //end for botimport.Print( PRT_MESSAGE, ")" ); } //end if else if ( key->flags & RCKFL_STRING ) { botimport.Print( PRT_MESSAGE, "\"%s\"", key->string ); } //end if if ( key->next ) { botimport.Print( PRT_MESSAGE, ", " ); } else { botimport.Print( PRT_MESSAGE, "] = %1.0f\n", replychat->priority );} } //end for botimport.Print( PRT_MESSAGE, "{\n" ); } //end of the function BotPrintReplyChatKeys //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotReplyChat( int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { bot_replychat_t *rchat, *bestrchat; bot_replychatkey_t *key; bot_chatmessage_t *m, *bestchatmessage; bot_match_t match, bestmatch; int bestpriority, num, found, res, numchatmessages; bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return qfalse; } memset( &match, 0, sizeof( bot_match_t ) ); strcpy( match.string, message ); bestpriority = -1; bestchatmessage = NULL; bestrchat = NULL; //go through all the reply chats for ( rchat = replychats; rchat; rchat = rchat->next ) { found = qfalse; for ( key = rchat->keys; key; key = key->next ) { res = qfalse; //get the match result if ( key->flags & RCKFL_NAME ) { res = ( StringContains( message, cs->name, qfalse ) != -1 ); } else if ( key->flags & RCKFL_BOTNAMES ) { res = ( StringContains( key->string, cs->name, qfalse ) != -1 ); } else if ( key->flags & RCKFL_GENDERFEMALE ) { res = ( cs->gender == CHAT_GENDERFEMALE ); } else if ( key->flags & RCKFL_GENDERMALE ) { res = ( cs->gender == CHAT_GENDERMALE ); } else if ( key->flags & RCKFL_GENDERLESS ) { res = ( cs->gender == CHAT_GENDERLESS ); } else if ( key->flags & RCKFL_VARIABLES ) { res = StringsMatch( key->match, &match ); } else if ( key->flags & RCKFL_STRING ) { res = ( StringContainsWord( message, key->string, qfalse ) != NULL ); } //if the key must be present if ( key->flags & RCKFL_AND ) { if ( !res ) { found = qfalse; break; } //end if //botnames is an exception //if (!(key->flags & RCKFL_BOTNAMES)) found = qtrue; } //end else if //if the key must be absent else if ( key->flags & RCKFL_NOT ) { if ( res ) { found = qfalse; break; } //end if } //end if else if ( res ) { found = qtrue; } //end else } //end for // if ( found ) { if ( rchat->priority > bestpriority ) { numchatmessages = 0; for ( m = rchat->firstchatmessage; m; m = m->next ) { if ( m->time > AAS_Time() ) { continue; } numchatmessages++; } //end if num = random() * numchatmessages; for ( m = rchat->firstchatmessage; m; m = m->next ) { if ( --num < 0 ) { break; } if ( m->time > AAS_Time() ) { continue; } } //end for //if the reply chat has a message if ( m ) { memcpy( &bestmatch, &match, sizeof( bot_match_t ) ); bestchatmessage = m; bestrchat = rchat; bestpriority = rchat->priority; } //end if } //end if } //end if } //end for if ( bestchatmessage ) { if ( var0 ) { bestmatch.variables[0].ptr = var0; bestmatch.variables[0].length = strlen( var0 ); } if ( var1 ) { bestmatch.variables[1].ptr = var1; bestmatch.variables[1].length = strlen( var1 ); } if ( var2 ) { bestmatch.variables[2].ptr = var2; bestmatch.variables[2].length = strlen( var2 ); } if ( var3 ) { bestmatch.variables[3].ptr = var3; bestmatch.variables[3].length = strlen( var3 ); } if ( var4 ) { bestmatch.variables[4].ptr = var4; bestmatch.variables[4].length = strlen( var4 ); } if ( var5 ) { bestmatch.variables[5].ptr = var5; bestmatch.variables[5].length = strlen( var5 ); } if ( var6 ) { bestmatch.variables[6].ptr = var6; bestmatch.variables[6].length = strlen( var6 ); } if ( var7 ) { bestmatch.variables[7].ptr = var7; bestmatch.variables[7].length = strlen( var7 ); } if ( LibVarGetValue( "bot_testrchat" ) ) { for ( m = bestrchat->firstchatmessage; m; m = m->next ) { BotConstructChatMessage( cs, m->chatmessage, mcontext, bestmatch.variables, vcontext, qtrue ); BotRemoveTildes( cs->chatmessage ); botimport.Print( PRT_MESSAGE, "%s\n", cs->chatmessage ); } //end if } //end if else { bestchatmessage->time = AAS_Time() + CHATMESSAGE_RECENTTIME; BotConstructChatMessage( cs, bestchatmessage->chatmessage, mcontext, bestmatch.variables, vcontext, qtrue ); } //end else return qtrue; } //end if return qfalse; } //end of the function BotReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotChatLength( int chatstate ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return 0; } return strlen( cs->chatmessage ); } //end of the function BotChatLength //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotEnterChat( int chatstate, int client, int sendto ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } if ( strlen( cs->chatmessage ) ) { BotRemoveTildes( cs->chatmessage ); if ( LibVarGetValue( "bot_testichat" ) ) { botimport.Print( PRT_MESSAGE, "%s\n", cs->chatmessage ); } else { if ( sendto == CHAT_TEAM ) { EA_SayTeam( client, cs->chatmessage ); } else { EA_Say( client, cs->chatmessage );} } //clear the chat message from the state strcpy( cs->chatmessage, "" ); } //end if } //end of the function BotEnterChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotGetChatMessage( int chatstate, char *buf, int size ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } BotRemoveTildes( cs->chatmessage ); strncpy( buf, cs->chatmessage, size - 1 ); buf[size - 1] = '\0'; //clear the chat message from the state strcpy( cs->chatmessage, "" ); } //end of the function BotGetChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotSetChatGender( int chatstate, int gender ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } switch ( gender ) { case CHAT_GENDERFEMALE: cs->gender = CHAT_GENDERFEMALE; break; case CHAT_GENDERMALE: cs->gender = CHAT_GENDERMALE; break; default: cs->gender = CHAT_GENDERLESS; break; } //end switch } //end of the function BotSetChatGender //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotSetChatName( int chatstate, char *name ) { bot_chatstate_t *cs; cs = BotChatStateFromHandle( chatstate ); if ( !cs ) { return; } memset( cs->name, 0, sizeof( cs->name ) ); strncpy( cs->name, name, sizeof( cs->name ) - 1 ); cs->name[sizeof( cs->name ) - 1] = '\0'; } //end of the function BotSetChatName //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotResetChatAI( void ) { bot_replychat_t *rchat; bot_chatmessage_t *m; for ( rchat = replychats; rchat; rchat = rchat->next ) { for ( m = rchat->firstchatmessage; m; m = m->next ) { m->time = 0; } //end for } //end for } //end of the function BotResetChatAI //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== int BotAllocChatState( void ) { int i; for ( i = 1; i <= MAX_CLIENTS; i++ ) { if ( !botchatstates[i] ) { botchatstates[i] = GetClearedMemory( sizeof( bot_chatstate_t ) ); return i; } //end if } //end for return 0; } //end of the function BotAllocChatState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== void BotFreeChatState( int handle ) { bot_consolemessage_t m; int h; if ( handle <= 0 || handle > MAX_CLIENTS ) { botimport.Print( PRT_FATAL, "chat state handle %d out of range\n", handle ); return; } //end if if ( !botchatstates[handle] ) { botimport.Print( PRT_FATAL, "invalid chat state %d\n", handle ); return; } //end if if ( LibVarGetValue( "bot_reloadcharacters" ) ) { BotFreeChatFile( handle ); } //end if //free all the console messages left in the chat state for ( h = BotNextConsoleMessage( handle, &m ); h; h = BotNextConsoleMessage( handle, &m ) ) { //remove the console message BotRemoveConsoleMessage( handle, h ); } //end for FreeMemory( botchatstates[handle] ); botchatstates[handle] = NULL; } //end of the function BotFreeChatState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotSetupChatAI( void ) { char *file; #ifdef DEBUG int starttime = Sys_MilliSeconds(); #endif //DEBUG file = LibVarString( "synfile", "syn.c" ); synonyms = BotLoadSynonyms( file ); file = LibVarString( "rndfile", "rnd.c" ); randomstrings = BotLoadRandomStrings( file ); file = LibVarString( "matchfile", "match.c" ); matchtemplates = BotLoadMatchTemplates( file ); // if ( !LibVarValue( "nochat", "0" ) ) { file = LibVarString( "rchatfile", "rchat.c" ); replychats = BotLoadReplyChat( file ); } //end if InitConsoleMessageHeap(); #ifdef DEBUG botimport.Print( PRT_MESSAGE, "setup chat AI %d msec\n", Sys_MilliSeconds() - starttime ); #endif //DEBUG return BLERR_NOERROR; } //end of the function BotSetupChatAI //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotShutdownChatAI( void ) { int i; //free all remaining chat states for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( botchatstates[i] ) { BotFreeChatState( i ); } //end if } //end for //free all cached chats for ( i = 0; i < MAX_CLIENTS; i++ ) { if ( ichatdata[i].inuse ) { FreeMemory( ichatdata[i].chat ); ichatdata[i].inuse = qfalse; } //end if } //end for if ( consolemessageheap ) { FreeMemory( consolemessageheap ); } consolemessageheap = NULL; if ( matchtemplates ) { BotFreeMatchTemplates( matchtemplates ); } matchtemplates = NULL; if ( randomstrings ) { FreeMemory( randomstrings ); } randomstrings = NULL; if ( synonyms ) { FreeMemory( synonyms ); } synonyms = NULL; if ( replychats ) { BotFreeReplyChat( replychats ); } replychats = NULL; } //end of the function BotShutdownChatAI
412
0.945885
1
0.945885
game-dev
MEDIA
0.697377
game-dev
0.739024
1
0.739024
qw225967/Bifrost
7,620
worker/third_party/libns3/src/propagation/model/three-gpp-v2v-propagation-loss-model.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2020 SIGNET Lab, Department of Information Engineering, * University of Padova * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "three-gpp-v2v-propagation-loss-model.h" #include "ns3/double.h" #include "ns3/log.h" #include "ns3/string.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("ThreeGppV2vPropagationLossModel"); // ------------------------------------------------------------------------- // NS_OBJECT_ENSURE_REGISTERED (ThreeGppV2vUrbanPropagationLossModel); TypeId ThreeGppV2vUrbanPropagationLossModel::GetTypeId (void) { static TypeId tid = TypeId ("ns3::ThreeGppV2vUrbanPropagationLossModel") .SetParent<ThreeGppPropagationLossModel> () .SetGroupName ("Propagation") .AddConstructor<ThreeGppV2vUrbanPropagationLossModel> () .AddAttribute ("PercType3Vehicles", "The percentage of vehicles of type 3 (i.e., trucks) in the scenario", DoubleValue (0.0), MakeDoubleAccessor (&ThreeGppV2vUrbanPropagationLossModel::m_percType3Vehicles), MakeDoubleChecker<double> (0.0, 100.0)) ; return tid; } ThreeGppV2vUrbanPropagationLossModel::ThreeGppV2vUrbanPropagationLossModel () : ThreeGppPropagationLossModel () { NS_LOG_FUNCTION (this); m_uniformVar = CreateObject<UniformRandomVariable> (); m_logNorVar = CreateObject<LogNormalRandomVariable> (); // set a default channel condition model // TODO the default ccm needs buildings, how to do this? // m_channelConditionModel = CreateObject<ThreeGppRmaChannelConditionModel> (); } ThreeGppV2vUrbanPropagationLossModel::~ThreeGppV2vUrbanPropagationLossModel () { NS_LOG_FUNCTION (this); } double ThreeGppV2vUrbanPropagationLossModel::GetLossLos (double /* distance2D */, double distance3D, double /* hUt */, double /* hBs */) const { NS_LOG_FUNCTION (this); // compute the pathloss (see 3GPP TR 37.885, Table 6.2.1-1) double loss = 38.77 + 16.7 * log10 (distance3D) + 18.2 * log10 (m_frequency / 1e9); return loss; } double ThreeGppV2vUrbanPropagationLossModel::GetLossNlosv (double distance2D, double distance3D, double hUt, double hBs) const { NS_LOG_FUNCTION (this); // compute the pathloss (see 3GPP TR 37.885, Table 6.2.1-1) double loss = GetLossLos (distance2D, distance3D, hUt, hBs) + GetAdditionalNlosvLoss (distance3D, hUt, hBs); return loss; } double ThreeGppV2vUrbanPropagationLossModel::GetAdditionalNlosvLoss (double distance3D, double hUt, double hBs) const { NS_LOG_FUNCTION (this); // From TR 37.885 v15.2.0 // When a V2V link is in NLOSv, additional vehicle blockage loss is // added as follows: // 1. The blocker height is the vehicle height which is randomly selected // out of the three vehicle types according to the portion of the vehicle // types in the simulated scenario. double additionalLoss = 0; double blockerHeight = 0; double mu_a = 0; double sigma_a = 0; double randomValue = m_uniformVar->GetValue () * 3.0; if (randomValue < m_percType3Vehicles) { // vehicles of type 3 have height 3 meters blockerHeight = 3.0; } else { // vehicles of type 1 and 2 have height 1.6 meters blockerHeight = 1.6; } // The additional blockage loss is max {0 dB, a log-normal random variable} if (std::min (hUt, hBs) > blockerHeight) { // Case 1: Minimum antenna height value of TX and RX > Blocker height additionalLoss = 0; } else if (std::max (hUt, hBs) < blockerHeight) { // Case 2: Maximum antenna height value of TX and RX < Blocker height mu_a = 9.0 + std::max (0.0, 15 * log10 (distance3D) - 41.0); sigma_a = 4.5; m_logNorVar->SetAttribute ("Mu", DoubleValue (log10 (pow (mu_a, 2) / sqrt (pow (sigma_a, 2) + pow (mu_a, 2))))); m_logNorVar->SetAttribute ("Sigma", DoubleValue (sqrt (log10 (pow (sigma_a, 2) / pow (mu_a, 2) + 1)))); additionalLoss = std::max (0.0, m_logNorVar->GetValue ()); } else { // Case 3: Otherwise mu_a = 5.0 + std::max (0.0, 15 * log10 (distance3D) - 41.0); sigma_a = 4.0; m_logNorVar->SetAttribute ("Mu", DoubleValue (log10 (pow (mu_a,2) / sqrt (pow (sigma_a, 2) + pow (mu_a, 2))))); m_logNorVar->SetAttribute ("Sigma", DoubleValue (sqrt (log10 (pow (sigma_a,2) / pow (mu_a, 2) + 1)))); additionalLoss = std::max (0.0, m_logNorVar->GetValue ()); } return additionalLoss; } double ThreeGppV2vUrbanPropagationLossModel::GetLossNlos (double /* distance2D */, double distance3D, double /* hUt */, double /* hBs */) const { NS_LOG_FUNCTION (this); double loss = 36.85 + 30 * log10 (distance3D) + 18.9 * log10 (m_frequency / 1e9); return loss; } double ThreeGppV2vUrbanPropagationLossModel::GetShadowingStd (Ptr<MobilityModel> /* a */, Ptr<MobilityModel> /* b */, ChannelCondition::LosConditionValue cond) const { NS_LOG_FUNCTION (this); double shadowingStd; if (cond == ChannelCondition::LosConditionValue::LOS || cond == ChannelCondition::LosConditionValue::NLOSv) { shadowingStd = 3.0; } else if (cond == ChannelCondition::LosConditionValue::NLOS) { shadowingStd = 4.0; } else { NS_FATAL_ERROR ("Unknown channel condition"); } return shadowingStd; } double ThreeGppV2vUrbanPropagationLossModel::GetShadowingCorrelationDistance (ChannelCondition::LosConditionValue cond) const { NS_LOG_FUNCTION (this); double correlationDistance; // See 3GPP TR 37.885, Table 6.2.3-1 if (cond == ChannelCondition::LosConditionValue::LOS) { correlationDistance = 10; } else if (cond == ChannelCondition::LosConditionValue::NLOSv || cond == ChannelCondition::LosConditionValue::NLOS) { correlationDistance = 13; } else { NS_FATAL_ERROR ("Unknown channel condition"); } return correlationDistance; } // ------------------------------------------------------------------------- // NS_OBJECT_ENSURE_REGISTERED (ThreeGppV2vHighwayPropagationLossModel); TypeId ThreeGppV2vHighwayPropagationLossModel::GetTypeId (void) { static TypeId tid = TypeId ("ns3::ThreeGppV2vHighwayPropagationLossModel") .SetParent<ThreeGppV2vUrbanPropagationLossModel> () .SetGroupName ("Propagation") .AddConstructor<ThreeGppV2vHighwayPropagationLossModel> () ; return tid; } ThreeGppV2vHighwayPropagationLossModel::ThreeGppV2vHighwayPropagationLossModel () : ThreeGppV2vUrbanPropagationLossModel () { NS_LOG_FUNCTION (this); } ThreeGppV2vHighwayPropagationLossModel::~ThreeGppV2vHighwayPropagationLossModel () { NS_LOG_FUNCTION (this); } double ThreeGppV2vHighwayPropagationLossModel::GetLossLos (double /* distance2D */, double distance3D, double /* hUt */, double /* hBs */) const { NS_LOG_FUNCTION (this); // compute the pathloss (see 3GPP TR 37.885, Table 6.2.1-1) double loss = 32.4 + 20 * log10 (distance3D) + 20 * log10 (m_frequency / 1e9); return loss; } } // namespace ns3
412
0.957261
1
0.957261
game-dev
MEDIA
0.533563
game-dev
0.951997
1
0.951997
Sheights/StarboundSimpleVoreMod
5,485
mods/StarboundSimpleVoreMod/objects/vore/spo/sergal/sergaldanger.lua
function init() -- Makes detection area around the predatores. if not virtual then self.detectArea = config.getParameter("detectArea") end -- Imports the lines from the predatores object file. chatOptions = config.getParameter("chatOptions", {}) gulpLines = config.getParameter("gulpLines", {}) rubLines = config.getParameter("rubLines", {}) -- Animation related animLock = false soundLock = false releaseLock = false idleTimer = 0 eatingTimer = 0 releaseTimer = 0 -- Chat related ohSnap = false -- Health related preyMaxHealth = 0 preyCurrentHealth = 0 preyPercentHealth = 0 digestState = 0 end function update(dt) -- Uses the previously made detection area to say the IdleFull or IdleEmpty lines when a player is closeby. local players = world.entityQuery( object.position(), 7, { includedTypes = {"player"}, boundMode = "CollisionArea" }) local chatIdleEmpty = config.getParameter("chatIdleEmpty", {}) local chatIdleFull = config.getParameter("chatIdleFull", {}) -- Only displays the lines if more than 0 players are in, and ohSnap is false (to prevent spam). if #players > 0 and not ohSnap then -- Displays the empty lines if the predator is empty, else full. if world.loungeableOccupied(entity.id()) == false then -- But only if it isnt already displaying a line. if #chatIdleEmpty > 0 then object.say(chatIdleEmpty[math.random(1, #chatIdleEmpty)]) end else if #chatIdleFull > 0 then object.say(chatIdleFull[math.random(1, #chatIdleFull)]) end end ohSnap = true -- Sets ohSnap to false when no players are within the dection area. elseif #players == 0 and ohSnap then ohSnap = false end -- Randomly displays the "Player inside Pred" lines if world.loungeableOccupied(entity.id()) and math.random(150) == 1 then if #chatOptions > 0 then object.say(chatOptions[math.random(1, #chatOptions)]) end end -- Animations that happens while the predator is empty (hungry). if world.loungeableOccupied(entity.id()) == false then if digestState == 4 then animator.setAnimationState("bodyState", "waiting") eatingTimer = 0 animLock = true end -- Resets the digestState checker. digestState = 0 -- Resets the predator to the idle state if animLock == false then animator.setAnimationState("bodyState", "waiting") idleTimer = 0 releaseLock = false releaseTimer = 0 -- If player leaves after being eaten, it plays the release animation. if eatingTimer >= 20 then animLock = true eatingTimer = 0 releaseLock = true animator.setAnimationState("bodyState", "release") animator.playSound("lay") end end -- Randomises different animations, like idle2, blink and waiting. if animLock == false and math.random(200) == 1 then animLock = true animator.setAnimationState("bodyState", "idle1") end if animLock == false and math.random(200) == 1 then animLock = true animator.setAnimationState("bodyState", "idle2") end if animLock == false and math.random(100) == 1 then animator.setAnimationState("bodyState", "blink") end if idleTimer >= 30 or releaseTimer >= 9 then animLock = false end -- Counts time being idle and empty. idleTimer = idleTimer + 1 if releaseLock == true then releaseTimer = releaseTimer + 1 end elseif world.loungeableOccupied(entity.id()) == true and eatingTimer <= 20 then -- Swallow animation if soundLock == false then animator.playSound("swallow") soundLock = true end animator.setAnimationState("bodyState", "swallow") eatingTimer = eatingTimer + 1 else -- Animations that happens while the predator is full (digesting). -- Math to find player percent health preyCurrentHealth = world.entityHealth(prey)[1] * 100 preyMaxHealth = world.entityHealth(prey)[2] preyPercentHealth = math.floor(preyCurrentHealth / preyMaxHealth) soundLock = false -- Changes player state based on their current percent health if preyPercentHealth <= 100 and digestState == 0 then animator.setAnimationState("bodyState", "fullbig") digestState = digestState + 1 elseif preyPercentHealth <= 55 and digestState == 1 then animator.setAnimationState("bodyState", "bigtosmall") digestState = digestState + 1 elseif preyPercentHealth <= 25 and digestState == 2 then animator.setAnimationState("bodyState", "smalltomicro") digestState = digestState + 1 elseif preyPercentHealth <= 3 and digestState == 3 then animator.setAnimationState("bodyState", "microtonone") digestState = digestState + 1 end end end function onInteraction(args) if not prey then prey = nil end -- Makes sure only the pred only checks the health of the prey inside. if world.loungeableOccupied(entity.id()) == false then prey = args.sourceId end -- Unless the predator is full it will activate this code. if world.loungeableOccupied(entity.id()) == false then -- Swallows the prey, playing the gulp sound and displaying a line. Also sets the player to be "prey". if #gulpLines > 0 then object.say(gulpLines[math.random(1, #gulpLines)]) prey = args.sourceId end -- If the interaction is done by someone NOT flagged as this predators prey then the RubLines are displayed. elseif world.loungeableOccupied(entity.id()) and prey ~= args.sourceId then if #rubLines > 0 then object.say(rubLines[math.random(1, #rubLines)]) end end end
412
0.921225
1
0.921225
game-dev
MEDIA
0.972782
game-dev
0.946509
1
0.946509
Monkestation/Monkestation2.0
1,155
code/datums/elements/death_gases.dm
/** * ## death gases element! * * Bespoke element that spawns one type of gas when a mob is killed */ /datum/element/death_gases element_flags = ELEMENT_BESPOKE argument_hash_start_idx = 3 ///What gas the target spawns when killed var/datum/gas/gas_type ///The amount of gas spawned on death var/amount_of_gas /datum/element/death_gases/Attach(datum/target, datum/gas/gas_type, amount_of_gas = 10) . = ..() if(!isliving(target)) return ELEMENT_INCOMPATIBLE if(!gas_type) stack_trace("[type] added to [target] with NO GAS TYPE.") src.gas_type = gas_type src.amount_of_gas = amount_of_gas RegisterSignal(target, COMSIG_LIVING_DEATH, PROC_REF(on_death)) /datum/element/death_gases/Detach(datum/target) . = ..() UnregisterSignal(target, COMSIG_LIVING_DEATH) ///signal called by the stat of the target changing /datum/element/death_gases/proc/on_death(mob/living/target, gibbed) SIGNAL_HANDLER var/datum/gas_mixture/mix_to_spawn = new() mix_to_spawn.add_gas(gas_type) mix_to_spawn.gases[gas_type][MOLES] = amount_of_gas mix_to_spawn.temperature = T20C var/turf/open/our_turf = get_turf(target) our_turf.assume_air(mix_to_spawn)
412
0.577205
1
0.577205
game-dev
MEDIA
0.943096
game-dev
0.555956
1
0.555956
TeamPneumatic/pnc-repressurized
7,731
src/main/java/me/desht/pneumaticcraft/common/drone/progwidgets/ProgWidgetCoordinate.java
/* * This file is part of pnc-repressurized. * * pnc-repressurized 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. * * pnc-repressurized 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 pnc-repressurized. If not, see <https://www.gnu.org/licenses/>. */ package me.desht.pneumaticcraft.common.drone.progwidgets; import com.google.common.collect.ImmutableList; import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import me.desht.pneumaticcraft.api.drone.IProgWidget; import me.desht.pneumaticcraft.api.drone.ProgWidgetType; import me.desht.pneumaticcraft.common.drone.ai.DroneAIManager; import me.desht.pneumaticcraft.common.item.GPSToolItem; import me.desht.pneumaticcraft.common.registry.ModProgWidgetTypes; import me.desht.pneumaticcraft.common.util.PneumaticCraftUtils; import me.desht.pneumaticcraft.lib.Textures; import net.minecraft.core.BlockPos; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; import java.util.*; import static me.desht.pneumaticcraft.common.util.PneumaticCraftUtils.xlate; public class ProgWidgetCoordinate extends ProgWidget implements IVariableWidget { public static final MapCodec<ProgWidgetCoordinate> CODEC = RecordCodecBuilder.mapCodec(builder -> baseParts(builder).and(builder.group( BlockPos.CODEC.optionalFieldOf("coord", BlockPos.ZERO).forGetter(p -> p.coord), Codec.STRING.optionalFieldOf("var", "").forGetter(ProgWidgetCoordinate::getVariable), Codec.BOOL.optionalFieldOf("using_var", false).forGetter(ProgWidgetCoordinate::isUsingVariable) )).apply(builder, ProgWidgetCoordinate::new)); public static final StreamCodec<RegistryFriendlyByteBuf, ProgWidgetCoordinate> STREAM_CODEC = StreamCodec.composite( PositionFields.STREAM_CODEC, ProgWidget::getPosition, BlockPos.STREAM_CODEC, p -> p.coord, ByteBufCodecs.STRING_UTF8, ProgWidgetCoordinate::getVariable, ByteBufCodecs.BOOL, ProgWidgetCoordinate::isUsingVariable, ProgWidgetCoordinate::new ); private BlockPos coord = BlockPos.ZERO; private String variable = ""; private boolean useVariable; private DroneAIManager aiManager; public ProgWidgetCoordinate() { super(PositionFields.DEFAULT); } private ProgWidgetCoordinate(PositionFields pos, BlockPos coord, String variable, boolean useVariable) { super(pos); this.coord = coord; this.variable = variable; this.useVariable = useVariable; } public static ProgWidgetCoordinate fromPos(BlockPos pos) { ProgWidgetCoordinate w = new ProgWidgetCoordinate(); w.setCoordinate(pos); return w; } public static ProgWidgetCoordinate fromGPSTool(ItemStack gpsTool) { ProgWidgetCoordinate w = new ProgWidgetCoordinate(); w.loadFromGPSTool(gpsTool); return w; } @Override public IProgWidget copyWidget() { return new ProgWidgetCoordinate(getPosition(), coord, variable, useVariable); } @Override public boolean hasStepInput() { return false; } @Override public ProgWidgetType<?> returnType() { return ModProgWidgetTypes.COORDINATE.get(); } @Override public List<ProgWidgetType<?>> getParameters() { return ImmutableList.of(ModProgWidgetTypes.COORDINATE.get()); } @Override public void addWarnings(List<Component> curInfo, List<IProgWidget> widgets) { super.addWarnings(curInfo, widgets); if (!useVariable && coord == null) { curInfo.add(xlate("pneumaticcraft.gui.progWidget.coordinate.warning.noCoordinate")); } } @Override public void addErrors(List<Component> curInfo, List<IProgWidget> widgets) { super.addErrors(curInfo, widgets); if (useVariable && variable.isEmpty()) { curInfo.add(xlate("pneumaticcraft.gui.progWidget.general.error.emptyVariable")); } } @Override public DyeColor getColor() { return DyeColor.GREEN; } @Override public WidgetDifficulty getDifficulty() { return WidgetDifficulty.ADVANCED; } @Override public ResourceLocation getTexture() { return Textures.PROG_WIDGET_COORDINATE; } @Override public void setAIManager(DroneAIManager aiManager) { this.aiManager = aiManager; } public Optional<BlockPos> getCoordinate() { if (useVariable && aiManager != null) { return aiManager.getCoordinate(aiManager.getDrone().getOwnerUUID(), variable); } else { return getRawCoordinate(); } } public Optional<BlockPos> getRawCoordinate() { return Optional.ofNullable(coord); } public void setCoordinate(BlockPos pos) { coord = pos; } public void setVariable(String varName) { variable = varName; } public String getVariable() { return variable; } public boolean isUsingVariable() { return useVariable; } public void setUsingVariable(boolean useVariable) { this.useVariable = useVariable; } public void loadFromGPSTool(ItemStack gpsTool){ String variable = GPSToolItem.getVariable(gpsTool); if (variable.isEmpty()) { setCoordinate(GPSToolItem.getGPSLocation(gpsTool).orElse(BlockPos.ZERO)); setUsingVariable(false); } else { setVariable(variable); setUsingVariable(true); } } @Override public ProgWidgetType<?> getType() { return ModProgWidgetTypes.COORDINATE.get(); } @Override public void getTooltip(List<Component> curTooltip) { super.getTooltip(curTooltip); if (useVariable) { curTooltip.add(Component.literal("XYZ: var '" + variable + "'")); } else { curTooltip.add(Component.literal(PneumaticCraftUtils.posToString(coord))); } } @Override public List<Component> getExtraStringInfo() { return useVariable ? Collections.singletonList(varAsTextComponent(variable)) : Collections.singletonList(Component.literal(PneumaticCraftUtils.posToString(coord))); } @Override public void addVariables(Set<String> variables) { variables.add(variable); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProgWidgetCoordinate that = (ProgWidgetCoordinate) o; return baseEquals(that) && useVariable == that.useVariable && Objects.equals(coord, that.coord) && Objects.equals(variable, that.variable); } @Override public int hashCode() { return Objects.hash(baseHashCode(), coord, variable, useVariable); } }
412
0.627335
1
0.627335
game-dev
MEDIA
0.428198
game-dev
0.770283
1
0.770283
7kayoh/Lydie
3,576
src/Components/Controls/Slider.luau
-- 7kayoh -- Slider.lua -- 2 Apr 2022 local UserInputService = game:GetService("UserInputService") local Components = script.Parent.Parent local Modules = Components.Parent.Modules local Lydie = Components.Parent local Fusion = require(Lydie.Parent.Fusion) local Scheme = require(Modules.Scheme) local Constants = require(Modules.Constants) local BaseButton = require(Components.Controls.BaseButton) local ToolTip = require(Components.Views.ToolTip) local New = Fusion.New local Children = Fusion.Children local Value = Fusion.Value local Computed = Fusion.Computed local Observer = Fusion.Observer local Tween = Fusion.Tween return function(props) local isListening = Value(false) props.Value = props.Value or Value(0) props.Stepper = props.Stepper or Value(5) local bar = BaseButton({ Size = UDim2.new(0, 200, 0, 8), RoundedValue = 1, [Children] = { New "UISizeConstraint" { MaxSize = Vector2.new(math.huge, 8), MinSize = Vector2.new(0, 8), }, New "UIGradient" { Color = props.GradientColor, }, BaseButton({ BackgroundColor = Scheme.GetAnimated(Scheme.Accent), BackgroundOpacity = 0, ZIndex = 3, AnchorPoint = Vector2.new(0.5, 0.5), Position = Computed(function() return UDim2.fromScale(props.Value:get(), 0.5) end), Size = UDim2.new(3, 0, 3, 0), RoundedValue = 1, [Children] = { New("UIAspectRatioConstraint")({ AspectRatio = 1, }), New("ImageLabel")({ BackgroundTransparency = 1, ImageColor3 = Scheme.GetAnimated(Scheme.Elevation[4]), Image = Constants.Rounded.Id, ScaleType = Enum.ScaleType.Slice, SliceCenter = Constants.Rounded.Center, SliceScale = 1, AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), Size = Tween(Computed(function() if isListening:get() then return UDim2.fromScale(0.6, 0.6) else return UDim2.fromScale(0.7, 0.7) end end), TweenInfo.new(0.3, Enum.EasingStyle.Back)), }), ToolTip({ Text = props.Value, Visible = isListening, }), }, OnClickDown = function() isListening:set(true) end, OnClick = function() isListening:set(false) end, }), }, OnClickDown = function() isListening:set(true) end, OnClick = function() isListening:set(false) end, }) local function getClosestStep(value) local step = props.Stepper:get() local closest = math.floor(value / step) * step return closest / 100 end local function update(input) if isListening:get() then local percentage if table.find( { Enum.UserInputType.MouseMovement, Enum.UserInputType.Touch, Enum.UserInputType.MouseButton1 }, input.UserInputType ) then local delta = input.Position.X - bar.AbsolutePosition.X percentage = delta / bar.AbsoluteSize.X end if percentage then percentage = getClosestStep(math.clamp(percentage, 0, 1) * 100) props.Value:set(percentage) end end end local connection = UserInputService.InputChanged:Connect(update) local connection2 = UserInputService.InputBegan:Connect(update) local disconnectObserver = Observer(props.Value):onChange(function() props.Value:set(getClosestStep(math.clamp(props.Value:get(), 0, 1) * 100)) end) bar.Destroying:Connect(function() connection:Disconnect() connection2:Disconnect() disconnectObserver() end) return bar end
412
0.964689
1
0.964689
game-dev
MEDIA
0.498357
game-dev
0.971319
1
0.971319
mcclure/bitbucket-backup
6,500
repos/fps2/contents/source/bridge.h
#ifndef _BRIDGE_H #define _BRIDGE_H #include "program.h" #include "PolyPortSound.h" /* * bridge.h * PolycodeTemplate * * Created by Andi McClure on 12/26/11. * Copyright 2011 Run Hello. All rights reserved. * */ // Limitations in create_lua_library mean static or non-object methods cannot be called from Lua. // This is an empty object that does nothing but contain staticky methods that Lua can actually see. struct type_automaton; struct lua_State; struct NumberArray { NumberArray() {} vector<Number> contents; int size() { return contents.size(); } Number get(int at) { return at >= 0 && at < contents.size() ? contents[at] : 0.0; } void push_back(Number value) { contents.push_back(value); } }; struct StringArray { vector<string> contents; int size() { return contents.size(); } String get(int at) { return at >= 0 && at < contents.size() ? String(contents[at]) : String(); } void push_back(String value) { contents.push_back(value.getSTLString()); } }; struct VectorArray { vector<Vector3> contents; int size() { return contents.size(); } Vector3 get(int at) { return at >= 0 && at < contents.size() ? contents[at] : Vector3(0,0,0); } void push_back(Vector3 value) { contents.push_back(value); } }; struct EntityArray { vector<Entity *> contents; int size() { return contents.size(); } Entity *get(int at) { return at >= 0 && at < contents.size() ? contents[at] : NULL; } void push_back(Entity *value) { contents.push_back(value); } }; struct project_bridge { Screen *room_screen(); Scene *room_scene(); StringArray *room_objs(); StringArray *room_oncollide_objs(); StringArray *room_onclick_objs(); Entity *room_id(String _at); String room_name(SceneEntity *of); Entity *room_a(); Entity *room_b(); void room_remove_scene(SceneEntity *obj); void room_remove_screen(ScreenEntity *obj, bool doRemove = true); void load_room(String from); void load_room_txt(String from); Screen *standalone_screen(String svg, String objectPath = String(), bool isPhysics = false); void room_remove_standalone_screen_all(Screen *s); void clear(); ScreenMesh *meshFor(Polycode::Polygon *p); String saved_level(); void set_saved_level(int priority); String filedump(String _path); String filedump_external(String _path); void filedump_external_out(String _path, String data); String help(String _path); void fake(); void rebirth(); void Quit(); Matrix4 mmult(Matrix4 a, Matrix4 b); Quaternion qmult(Quaternion a, Quaternion b); Quaternion Slerp(Number fT, const Quaternion& rkP, const Quaternion& rkQ, bool shortestPath=false); Quaternion Squad(Number fT, const Quaternion& rkP, const Quaternion& rkA, const Quaternion& rkB, const Quaternion& rkQ, bool shortestPath); Vector3 matrixApply(Matrix4 mat, Vector3 val); Vector3 bBox(Entity *e); void setSceneClearColor(Scene *scene, int r, int g, int b, int a); project_bridge() {} String custEntityType(Entity *obj); type_automaton *col40(); String charCode(InputEvent *e); Sound *soundFromValues(NumberArray *values, int channels = 1, int freq = 44100, int bps = 16); void playback_index(); // Only useful in debug mode void playback_from(int idx); void stackthrash(Screen *s, ScreenEntity *e); int getTextHeight(Label *l); int luaTestAddOne(lua_State *); int saveTableIntoObject(lua_State *); int loadTableFromObject(lua_State *); int saveTableIntoFile(lua_State *); int loadTableFromFile(lua_State *); int saveTableIntoXml(lua_State *); int loadTableFromXml(lua_State *); int getChildAtScreenPosition(lua_State *); bool getVisible(Entity *e); void setVisible(Entity *e, bool visible); CoreServices *coreServices(); int userSettings(lua_State *L); int debugSettings(lua_State *L); void register_room_name(SceneEntity *of, String name); int register_room_onCollision(lua_State *L); int register_room_onClick(lua_State *L); String pwd(); void setColorObj(Entity *e, Color *c); SceneMesh *normalPlane(Number x, Number y, Number xs = 1, Number ys = 1, bool no_backface = true); SceneMesh *uprightBox(Number x, Number y, Number z, bool stretch = true); void term_setOverride(bool v); void term_setHidden(bool v); void term_setEntry(String str); void term_setLine(int y, String str); void term_setColor(int y, Color *c); void term_reset(); int term_height(); int term_width(); bool term_busy(); String editor_dir(); Number labelWidth(ScreenLabel *label); Number labelHeight(ScreenLabel *label); void paramSetNumber(LocalShaderParam *param, Number x); void paramSetVector2(LocalShaderParam *param, Vector2 x); void paramSetVector3(LocalShaderParam *param, Vector3 x); void paramSetColor(LocalShaderParam *param, Color x); int bindingId(lua_State *L); int unlinkgc(lua_State *L); void Audio1(); void Audio2(); void Audio3(); void unfocus(); SceneEntity *collidesWith(CollisionScene *scene, SceneEntity *test); String oneFilePicker(String ext); Entity *getFirstEntityInRay(CollisionScene *s, const Vector3 &origin, const Vector3 &dest); }; // Draws a "copy" of a scene object without having to duplicate its resources. struct SceneEcho : SceneEntity { SceneEcho(Entity *_copying); virtual void transformAndRender(); Entity *getEntity(); protected: Entity *copying; }; // Draws a "copy" of a screen object without having to duplicate its resources. struct ScreenEcho : ScreenEntity { ScreenEcho(Entity *_copying); virtual void transformAndRender(); Entity *getEntity(); protected: Entity *copying; }; #define BPARAMCOUNT 3 #define BIPARAMCOUNT 2 #define TONEMAX 5 #define STEPMAX 5 #define BASEFREQ param[0] #define PREAMP param[1] #define THRESHOLD param[2] #define TONECOUNT iparam[0] #define TONEVARY iparam[1] #define TONERESET 4 struct BSound : PSound { BSound(); virtual ~BSound(); Number param[BPARAMCOUNT]; int iparam[BIPARAMCOUNT]; virtual int soundCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); double pitch; double volume; double theta[TONEMAX]; double stepoff[TONEMAX]; int stepis[TONEMAX]; int steps[STEPMAX]; int stepc; int step2c; void setPitch(Number newPitch); Number getPitch(); void setVolume(Number newVolume); Number getVolume(); void setParam(int idx, Number v); Number getParam(int idx); void setIparam(int idx, int v); int getIparam(int idx); }; string fromMatrix4(const Matrix4 &mat); Vector3 matrixApply(const Matrix4 &m, Vector3 &v2); #endif /* _BRIDGE_H */
412
0.883267
1
0.883267
game-dev
MEDIA
0.46169
game-dev
0.614494
1
0.614494
oiuv/mud
1,833
kungfu/skill/longxiang-gong/exert/powerup.c
#include <ansi.h> inherit F_CLEAN_UP; void remove_effect(object me, int amount); int exert(object me, object target) { int skill, layer; skill = me->query_skill("longxiang-gong", 1); layer = skill / 30; if (layer > 13) layer = 13; if (target != me) return notify_fail("你只能提升自己的战斗力。\n"); if (layer < 3) return notify_fail("你龙象般若功修为不够,难以运功。\n"); if ((int)me->query("neili") < 500) return notify_fail("你目前的真气不够。\n"); if ((int)me->query_temp("powerup")) return notify_fail("你已经在运功中了。\n"); message_combatd(HIY "$N" HIY "运足龙象般若功第" + chinese_number(layer) + "层功力,全身骨骼节节暴响,罡气向四周扩散开来!\n" NOR, me); me->add_temp("apply/attack", (skill / 3) + (layer * 15)); me->add_temp("apply/parry", skill / 3); me->add_temp("apply/dodge", skill / 3); me->add_temp("str", layer * 6); me->set_temp("powerup", 1); me->add("neili", -100); me->start_call_out((: call_other, __FILE__, "remove_effect", me, skill / 3 :), skill); if (me->is_fighting()) me->start_busy(1 + random(3)); return 1; } void remove_effect(object me, int amount) { int /*skill,*/ lvl, layer; lvl = me->query_skill("longxiang-gong", 1); layer = lvl / 30; if (layer > 13) layer = 13; if ((int)me->query_temp("powerup")) { me->add_temp("apply/attack", -amount - (layer * 15)); me->add_temp("apply/parry", -amount); me->add_temp("apply/dodge", -amount); me->add_temp("str", -layer * 6); me->delete_temp("powerup"); tell_object(me, "你的龙象般若功运行完毕,将内力收回丹田。\n"); } }
412
0.523502
1
0.523502
game-dev
MEDIA
0.668091
game-dev
0.810011
1
0.810011
opentibiabr/otservbr-global
5,769
data/npc/nah_bob.lua
local internalNpcName = "Nah'Bob" 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 = 80 } 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 function creatureSayCallback(npc, creature, type, message) local player = Player(creature) local playerId = player:getId() if not npcHandler:checkInteraction(npc, creature) then return false end if MsgContains(message, 'cookie') then if player:getStorageValue(Storage.WhatAFoolish.Questline) == 31 and player:getStorageValue(Storage.WhatAFoolish.CookieDelivery.Djinn) ~= 1 then npcHandler:say('You brought cookies! How nice of you! Can I have one?', npc, creature) npcHandler:setTopic(playerId, 1) end elseif MsgContains(message, 'yes') then if npcHandler:getTopic(playerId) == 1 then if not player:removeItem(130, 1) then npcHandler:say('You have no cookie that I\'d like.', npc, creature) npcHandler:setTopic(playerId, 0) return true end player:setStorageValue(Storage.WhatAFoolish.CookieDelivery.Djinn, 1) if player:getCookiesDelivered() == 10 then player:addAchievement('Allow Cookies?') end npc:getPosition():sendMagicEffect(CONST_ME_GIFT_WRAPS) npcHandler:say('You see, good deeds like this will ... YOU ... YOU SPAWN OF EVIL! I WILL MAKE SURE THE MASTER LEARNS ABOUT THIS!', npc, creature) npcHandler:removeInteraction(npc, creature) npcHandler:resetNpc(creature) end elseif MsgContains(message, 'no') then if npcHandler:getTopic(playerId) == 1 then npcHandler:say('I see.', npc, creature) npcHandler:setTopic(playerId, 0) end end return true end local function onTradeRequest(npc, creature) local player = Player(creature) local playerId = player:getId() if player:getStorageValue(Storage.DjinnWar.MaridFaction.Mission03) ~= 3 then npcHandler:say('I\'m sorry, human. But you need Gabel\'s permission to trade with me.', npc, creature) return false end return true end npcHandler:setMessage(MESSAGE_GREET, "<Sighs> Another {customer}! I've only just sat down! What is it, |PLAYERNAME|?") npcHandler:setMessage(MESSAGE_FAREWELL, "Bye now, Neutrala |PLAYERNAME|. Visit old Bob again one day!") npcHandler:setMessage(MESSAGE_WALKAWAY, "Bye then.") npcHandler:setMessage(MESSAGE_SENDTRADE, 'At your service, just browse through my wares.') npcHandler:setCallback(CALLBACK_ON_TRADE_REQUEST, onTradeRequest) npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) npcConfig.shop = { { itemName = "angelic axe", clientId = 7436, sell = 5000 }, { itemName = "blue robe", clientId = 3567, sell = 10000 }, { itemName = "bonelord shield", clientId = 3418, buy = 7000, sell = 1200 }, { itemName = "boots of haste", clientId = 3079, sell = 30000 }, { itemName = "broadsword", clientId = 3301, sell = 500 }, { itemName = "butcher's axe", clientId = 7412, sell = 18000 }, { itemName = "crown armor", clientId = 3381, sell = 12000 }, { itemName = "crown helmet", clientId = 3385, sell = 2500 }, { itemName = "crown legs", clientId = 3382, sell = 12000 }, { itemName = "crown shield", clientId = 3419, sell = 8000 }, { itemName = "crusader helmet", clientId = 3391, sell = 6000 }, { itemName = "dragon lance", clientId = 3302, sell = 9000 }, { itemName = "dragon shield", clientId = 3416, sell = 4000 }, { itemName = "fire axe", clientId = 3320, sell = 8000 }, { itemName = "fire sword", clientId = 3280, sell = 4000 }, { itemName = "glorious axe", clientId = 7454, sell = 3000 }, { itemName = "guardian shield", clientId = 3415, sell = 2000 }, { itemName = "ice rapier", clientId = 3284, sell = 1000 }, { itemName = "noble armor", clientId = 3380, buy = 8000, sell = 900 }, { itemName = "obsidian lance", clientId = 3313, buy = 3000, sell = 500 }, { itemName = "phoenix shield", clientId = 3439, sell = 16000 }, { itemName = "queen's sceptre", clientId = 7410, sell = 20000 }, { itemName = "royal helmet", clientId = 3392, sell = 30000 }, { itemName = "shadow sceptre", clientId = 7451, sell = 10000 }, { itemName = "spike sword", clientId = 3271, buy = 8000, sell = 1000 }, { itemName = "thaian sword", clientId = 7391, sell = 16000 }, { itemName = "war hammer", clientId = 3279, buy = 10000, sell = 1200 } } -- 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.934608
1
0.934608
game-dev
MEDIA
0.820855
game-dev
0.845227
1
0.845227
ServUO/ServUO
2,119
Scripts/Mobiles/Normal/PutridUndeadGuardian.cs
using System; namespace Server.Mobiles { [CorpseName("an putrid undead guardian corpse")] public class PutridUndeadGuardian : BaseCreature { [Constructable] public PutridUndeadGuardian() : base(AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4) { Name = "an putrid undead guardian"; Body = 722; SetStr(79); SetDex(63); SetInt(187); SetHits(553); SetDamage(3, 7); SetDamageType(ResistanceType.Physical, 100); SetResistance(ResistanceType.Physical, 40); SetResistance(ResistanceType.Fire, 23); SetResistance(ResistanceType.Cold, 57); SetResistance(ResistanceType.Poison, 29); SetResistance(ResistanceType.Energy, 39); SetSkill(SkillName.MagicResist, 62.7); SetSkill(SkillName.Tactics, 45.4); SetSkill(SkillName.Wrestling, 50.7); Fame = 3000; Karma = -3000; PackNecroReg(10, 15); /// Stratics didn't specify } public PutridUndeadGuardian(Serial serial) : base(serial) { } public override int Meat { get { return 1; } } public override void GenerateLoot() { AddLoot(LootPack.FilthyRich, 3); } public override int GetIdleSound() { return 1609; } public override int GetAngerSound() { return 1606; } public override int GetHurtSound() { return 1608; } public override int GetDeathSound() { return 1607; } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
412
0.909945
1
0.909945
game-dev
MEDIA
0.967607
game-dev
0.866316
1
0.866316
HandyOrg/HandyControl
5,062
src/Shared/Microsoft.Expression.Drawing/Media/GeometryEffect.cs
using System; using System.ComponentModel; using System.Windows; using System.Windows.Media; using System.Windows.Threading; namespace HandyControl.Expression.Media; [TypeConverter(typeof(GeometryEffectConverter))] public abstract class GeometryEffect : Freezable { // ReSharper disable once InconsistentNaming private static GeometryEffect defaultGeometryEffect; public static readonly DependencyProperty GeometryEffectProperty = DependencyProperty.RegisterAttached("GeometryEffect", typeof(GeometryEffect), typeof(GeometryEffect), new DrawingPropertyMetadata(DefaultGeometryEffect, DrawingPropertyMetadataOptions.AffectsRender, OnGeometryEffectChanged)); protected Geometry CachedGeometry; private bool _effectInvalidated; static GeometryEffect() { DrawingPropertyMetadata.DrawingPropertyChanged += delegate (object sender, DrawingPropertyChangedEventArgs args) { if (sender is GeometryEffect effect && args.Metadata.AffectsRender) effect.InvalidateGeometry(InvalidateGeometryReasons.PropertyChanged); }; } public static GeometryEffect DefaultGeometryEffect => defaultGeometryEffect ?? (defaultGeometryEffect = new NoGeometryEffect()); public Geometry OutputGeometry => CachedGeometry; protected internal DependencyObject Parent { get; private set; } protected internal virtual void Attach(DependencyObject obj) { if (Parent != null) Detach(); _effectInvalidated = true; CachedGeometry = null; if (InvalidateParent(obj)) Parent = obj; } public new GeometryEffect CloneCurrentValue() { return (GeometryEffect) base.CloneCurrentValue(); } protected override Freezable CreateInstanceCore() { return (Freezable) Activator.CreateInstance(GetType()); } protected abstract GeometryEffect DeepCopy(); protected internal virtual void Detach() { _effectInvalidated = true; CachedGeometry = null; if (Parent != null) { InvalidateParent(Parent); Parent = null; } } public abstract bool Equals(GeometryEffect geometryEffect); public static GeometryEffect GetGeometryEffect(DependencyObject obj) { return (GeometryEffect) obj.GetValue(GeometryEffectProperty); } public bool InvalidateGeometry(InvalidateGeometryReasons reasons) { if (_effectInvalidated) return false; _effectInvalidated = true; if (reasons != InvalidateGeometryReasons.ParentInvalidated) InvalidateParent(Parent); return true; } private static bool InvalidateParent(DependencyObject parent) { if (parent is IShape shape) { shape.InvalidateGeometry(InvalidateGeometryReasons.ChildInvalidated); return true; } if (parent is GeometryEffect effect) { effect.InvalidateGeometry(InvalidateGeometryReasons.ChildInvalidated); return true; } return false; } private static void OnGeometryEffectChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var oldValue = e.OldValue as GeometryEffect; var newValue = e.NewValue as GeometryEffect; if (!Equals(oldValue, newValue)) { if (oldValue != null && obj.Equals(oldValue.Parent)) oldValue.Detach(); if (newValue != null) { if (newValue.Parent != null) { obj.Dispatcher.BeginInvoke(new Action(() => { var effect = newValue.CloneCurrentValue(); obj.SetValue(GeometryEffectProperty, effect); }), DispatcherPriority.Send, null); } else { newValue.Attach(obj); } } } } public bool ProcessGeometry(Geometry input) { var flag = false; if (_effectInvalidated) { flag |= UpdateCachedGeometry(input); _effectInvalidated = false; } return flag; } public static void SetGeometryEffect(DependencyObject obj, GeometryEffect value) { obj.SetValue(GeometryEffectProperty, value); } protected abstract bool UpdateCachedGeometry(Geometry input); private class NoGeometryEffect : GeometryEffect { protected override GeometryEffect DeepCopy() { return new NoGeometryEffect(); } public override bool Equals(GeometryEffect geometryEffect) { if (geometryEffect != null) return geometryEffect is NoGeometryEffect; return true; } protected override bool UpdateCachedGeometry(Geometry input) { CachedGeometry = input; return false; } } }
412
0.806362
1
0.806362
game-dev
MEDIA
0.500312
game-dev
0.885943
1
0.885943
fredakilla/GPlayEngine
46,468
thirdparty/bullet/src/Bullet3OpenCL/NarrowphaseCollision/b3QuantizedBvh.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "b3QuantizedBvh.h" #include "Bullet3Geometry/b3AabbUtil.h" #define RAYAABB2 b3QuantizedBvh::b3QuantizedBvh() : m_bulletVersion(B3_BULLET_VERSION), m_useQuantization(false), m_traversalMode(TRAVERSAL_STACKLESS_CACHE_FRIENDLY) //m_traversalMode(TRAVERSAL_STACKLESS) //m_traversalMode(TRAVERSAL_RECURSIVE) ,m_subtreeHeaderCount(0) //PCK: add this line { m_bvhAabbMin.setValue(-B3_INFINITY,-B3_INFINITY,-B3_INFINITY); m_bvhAabbMax.setValue(B3_INFINITY,B3_INFINITY,B3_INFINITY); } void b3QuantizedBvh::buildInternal() { ///assumes that caller filled in the m_quantizedLeafNodes m_useQuantization = true; int numLeafNodes = 0; if (m_useQuantization) { //now we have an array of leafnodes in m_leafNodes numLeafNodes = m_quantizedLeafNodes.size(); m_quantizedContiguousNodes.resize(2*numLeafNodes); } m_curNodeIndex = 0; buildTree(0,numLeafNodes); ///if the entire tree is small then subtree size, we need to create a header info for the tree if(m_useQuantization && !m_SubtreeHeaders.size()) { b3BvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[0]); subtree.m_rootNodeIndex = 0; subtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex(); } //PCK: update the copy of the size m_subtreeHeaderCount = m_SubtreeHeaders.size(); //PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary m_quantizedLeafNodes.clear(); m_leafNodes.clear(); } ///just for debugging, to visualize the individual patches/subtrees #ifdef DEBUG_PATCH_COLORS b3Vector3 color[4]= { b3Vector3(1,0,0), b3Vector3(0,1,0), b3Vector3(0,0,1), b3Vector3(0,1,1) }; #endif //DEBUG_PATCH_COLORS void b3QuantizedBvh::setQuantizationValues(const b3Vector3& bvhAabbMin,const b3Vector3& bvhAabbMax,b3Scalar quantizationMargin) { //enlarge the AABB to avoid division by zero when initializing the quantization values b3Vector3 clampValue =b3MakeVector3(quantizationMargin,quantizationMargin,quantizationMargin); m_bvhAabbMin = bvhAabbMin - clampValue; m_bvhAabbMax = bvhAabbMax + clampValue; b3Vector3 aabbSize = m_bvhAabbMax - m_bvhAabbMin; m_bvhQuantization = b3MakeVector3(b3Scalar(65533.0),b3Scalar(65533.0),b3Scalar(65533.0)) / aabbSize; m_useQuantization = true; } b3QuantizedBvh::~b3QuantizedBvh() { } #ifdef DEBUG_TREE_BUILDING int gStackDepth = 0; int gMaxStackDepth = 0; #endif //DEBUG_TREE_BUILDING void b3QuantizedBvh::buildTree (int startIndex,int endIndex) { #ifdef DEBUG_TREE_BUILDING gStackDepth++; if (gStackDepth > gMaxStackDepth) gMaxStackDepth = gStackDepth; #endif //DEBUG_TREE_BUILDING int splitAxis, splitIndex, i; int numIndices =endIndex-startIndex; int curIndex = m_curNodeIndex; b3Assert(numIndices>0); if (numIndices==1) { #ifdef DEBUG_TREE_BUILDING gStackDepth--; #endif //DEBUG_TREE_BUILDING assignInternalNodeFromLeafNode(m_curNodeIndex,startIndex); m_curNodeIndex++; return; } //calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'. splitAxis = calcSplittingAxis(startIndex,endIndex); splitIndex = sortAndCalcSplittingIndex(startIndex,endIndex,splitAxis); int internalNodeIndex = m_curNodeIndex; //set the min aabb to 'inf' or a max value, and set the max aabb to a -inf/minimum value. //the aabb will be expanded during buildTree/mergeInternalNodeAabb with actual node values setInternalNodeAabbMin(m_curNodeIndex,m_bvhAabbMax);//can't use b3Vector3(B3_INFINITY,B3_INFINITY,B3_INFINITY)) because of quantization setInternalNodeAabbMax(m_curNodeIndex,m_bvhAabbMin);//can't use b3Vector3(-B3_INFINITY,-B3_INFINITY,-B3_INFINITY)) because of quantization for (i=startIndex;i<endIndex;i++) { mergeInternalNodeAabb(m_curNodeIndex,getAabbMin(i),getAabbMax(i)); } m_curNodeIndex++; //internalNode->m_escapeIndex; int leftChildNodexIndex = m_curNodeIndex; //build left child tree buildTree(startIndex,splitIndex); int rightChildNodexIndex = m_curNodeIndex; //build right child tree buildTree(splitIndex,endIndex); #ifdef DEBUG_TREE_BUILDING gStackDepth--; #endif //DEBUG_TREE_BUILDING int escapeIndex = m_curNodeIndex - curIndex; if (m_useQuantization) { //escapeIndex is the number of nodes of this subtree const int sizeQuantizedNode =sizeof(b3QuantizedBvhNode); const int treeSizeInBytes = escapeIndex * sizeQuantizedNode; if (treeSizeInBytes > MAX_SUBTREE_SIZE_IN_BYTES) { updateSubtreeHeaders(leftChildNodexIndex,rightChildNodexIndex); } } else { } setInternalNodeEscapeIndex(internalNodeIndex,escapeIndex); } void b3QuantizedBvh::updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex) { b3Assert(m_useQuantization); b3QuantizedBvhNode& leftChildNode = m_quantizedContiguousNodes[leftChildNodexIndex]; int leftSubTreeSize = leftChildNode.isLeafNode() ? 1 : leftChildNode.getEscapeIndex(); int leftSubTreeSizeInBytes = leftSubTreeSize * static_cast<int>(sizeof(b3QuantizedBvhNode)); b3QuantizedBvhNode& rightChildNode = m_quantizedContiguousNodes[rightChildNodexIndex]; int rightSubTreeSize = rightChildNode.isLeafNode() ? 1 : rightChildNode.getEscapeIndex(); int rightSubTreeSizeInBytes = rightSubTreeSize * static_cast<int>(sizeof(b3QuantizedBvhNode)); if(leftSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES) { b3BvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); subtree.setAabbFromQuantizeNode(leftChildNode); subtree.m_rootNodeIndex = leftChildNodexIndex; subtree.m_subtreeSize = leftSubTreeSize; } if(rightSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES) { b3BvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); subtree.setAabbFromQuantizeNode(rightChildNode); subtree.m_rootNodeIndex = rightChildNodexIndex; subtree.m_subtreeSize = rightSubTreeSize; } //PCK: update the copy of the size m_subtreeHeaderCount = m_SubtreeHeaders.size(); } int b3QuantizedBvh::sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis) { int i; int splitIndex =startIndex; int numIndices = endIndex - startIndex; b3Scalar splitValue; b3Vector3 means=b3MakeVector3(b3Scalar(0.),b3Scalar(0.),b3Scalar(0.)); for (i=startIndex;i<endIndex;i++) { b3Vector3 center = b3Scalar(0.5)*(getAabbMax(i)+getAabbMin(i)); means+=center; } means *= (b3Scalar(1.)/(b3Scalar)numIndices); splitValue = means[splitAxis]; //sort leafNodes so all values larger then splitValue comes first, and smaller values start from 'splitIndex'. for (i=startIndex;i<endIndex;i++) { b3Vector3 center = b3Scalar(0.5)*(getAabbMax(i)+getAabbMin(i)); if (center[splitAxis] > splitValue) { //swap swapLeafNodes(i,splitIndex); splitIndex++; } } //if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex //otherwise the tree-building might fail due to stack-overflows in certain cases. //unbalanced1 is unsafe: it can cause stack overflows //bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1))); //unbalanced2 should work too: always use center (perfect balanced trees) //bool unbalanced2 = true; //this should be safe too: int rangeBalancedIndices = numIndices/3; bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices))); if (unbalanced) { splitIndex = startIndex+ (numIndices>>1); } bool unbal = (splitIndex==startIndex) || (splitIndex == (endIndex)); (void)unbal; b3Assert(!unbal); return splitIndex; } int b3QuantizedBvh::calcSplittingAxis(int startIndex,int endIndex) { int i; b3Vector3 means=b3MakeVector3(b3Scalar(0.),b3Scalar(0.),b3Scalar(0.)); b3Vector3 variance=b3MakeVector3(b3Scalar(0.),b3Scalar(0.),b3Scalar(0.)); int numIndices = endIndex-startIndex; for (i=startIndex;i<endIndex;i++) { b3Vector3 center = b3Scalar(0.5)*(getAabbMax(i)+getAabbMin(i)); means+=center; } means *= (b3Scalar(1.)/(b3Scalar)numIndices); for (i=startIndex;i<endIndex;i++) { b3Vector3 center = b3Scalar(0.5)*(getAabbMax(i)+getAabbMin(i)); b3Vector3 diff2 = center-means; diff2 = diff2 * diff2; variance += diff2; } variance *= (b3Scalar(1.)/ ((b3Scalar)numIndices-1) ); return variance.maxAxis(); } void b3QuantizedBvh::reportAabbOverlappingNodex(b3NodeOverlapCallback* nodeCallback,const b3Vector3& aabbMin,const b3Vector3& aabbMax) const { //either choose recursive traversal (walkTree) or stackless (walkStacklessTree) if (m_useQuantization) { ///quantize query AABB unsigned short int quantizedQueryAabbMin[3]; unsigned short int quantizedQueryAabbMax[3]; quantizeWithClamp(quantizedQueryAabbMin,aabbMin,0); quantizeWithClamp(quantizedQueryAabbMax,aabbMax,1); switch (m_traversalMode) { case TRAVERSAL_STACKLESS: walkStacklessQuantizedTree(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax,0,m_curNodeIndex); break; case TRAVERSAL_STACKLESS_CACHE_FRIENDLY: walkStacklessQuantizedTreeCacheFriendly(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); break; case TRAVERSAL_RECURSIVE: { const b3QuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[0]; walkRecursiveQuantizedTreeAgainstQueryAabb(rootNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); } break; default: //unsupported b3Assert(0); } } else { walkStacklessTree(nodeCallback,aabbMin,aabbMax); } } static int b3s_maxIterations = 0; void b3QuantizedBvh::walkStacklessTree(b3NodeOverlapCallback* nodeCallback,const b3Vector3& aabbMin,const b3Vector3& aabbMax) const { b3Assert(!m_useQuantization); const b3OptimizedBvhNode* rootNode = &m_contiguousNodes[0]; int escapeIndex, curIndex = 0; int walkIterations = 0; bool isLeafNode; //PCK: unsigned instead of bool unsigned aabbOverlap; while (curIndex < m_curNodeIndex) { //catch bugs in tree data b3Assert (walkIterations < m_curNodeIndex); walkIterations++; aabbOverlap = b3TestAabbAgainstAabb2(aabbMin,aabbMax,rootNode->m_aabbMinOrg,rootNode->m_aabbMaxOrg); isLeafNode = rootNode->m_escapeIndex == -1; //PCK: unsigned instead of bool if (isLeafNode && (aabbOverlap != 0)) { nodeCallback->processNode(rootNode->m_subPart,rootNode->m_triangleIndex); } //PCK: unsigned instead of bool if ((aabbOverlap != 0) || isLeafNode) { rootNode++; curIndex++; } else { escapeIndex = rootNode->m_escapeIndex; rootNode += escapeIndex; curIndex += escapeIndex; } } if (b3s_maxIterations < walkIterations) b3s_maxIterations = walkIterations; } /* ///this was the original recursive traversal, before we optimized towards stackless traversal void b3QuantizedBvh::walkTree(b3OptimizedBvhNode* rootNode,b3NodeOverlapCallback* nodeCallback,const b3Vector3& aabbMin,const b3Vector3& aabbMax) const { bool isLeafNode, aabbOverlap = TestAabbAgainstAabb2(aabbMin,aabbMax,rootNode->m_aabbMin,rootNode->m_aabbMax); if (aabbOverlap) { isLeafNode = (!rootNode->m_leftChild && !rootNode->m_rightChild); if (isLeafNode) { nodeCallback->processNode(rootNode); } else { walkTree(rootNode->m_leftChild,nodeCallback,aabbMin,aabbMax); walkTree(rootNode->m_rightChild,nodeCallback,aabbMin,aabbMax); } } } */ void b3QuantizedBvh::walkRecursiveQuantizedTreeAgainstQueryAabb(const b3QuantizedBvhNode* currentNode,b3NodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const { b3Assert(m_useQuantization); bool isLeafNode; //PCK: unsigned instead of bool unsigned aabbOverlap; //PCK: unsigned instead of bool aabbOverlap = b3TestQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,currentNode->m_quantizedAabbMin,currentNode->m_quantizedAabbMax); isLeafNode = currentNode->isLeafNode(); //PCK: unsigned instead of bool if (aabbOverlap != 0) { if (isLeafNode) { nodeCallback->processNode(currentNode->getPartId(),currentNode->getTriangleIndex()); } else { //process left and right children const b3QuantizedBvhNode* leftChildNode = currentNode+1; walkRecursiveQuantizedTreeAgainstQueryAabb(leftChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); const b3QuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? leftChildNode+1:leftChildNode+leftChildNode->getEscapeIndex(); walkRecursiveQuantizedTreeAgainstQueryAabb(rightChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); } } } void b3QuantizedBvh::walkStacklessTreeAgainstRay(b3NodeOverlapCallback* nodeCallback, const b3Vector3& raySource, const b3Vector3& rayTarget, const b3Vector3& aabbMin, const b3Vector3& aabbMax, int startNodeIndex,int endNodeIndex) const { b3Assert(!m_useQuantization); const b3OptimizedBvhNode* rootNode = &m_contiguousNodes[0]; int escapeIndex, curIndex = 0; int walkIterations = 0; bool isLeafNode; //PCK: unsigned instead of bool unsigned aabbOverlap=0; unsigned rayBoxOverlap=0; b3Scalar lambda_max = 1.0; /* Quick pruning by quantized box */ b3Vector3 rayAabbMin = raySource; b3Vector3 rayAabbMax = raySource; rayAabbMin.setMin(rayTarget); rayAabbMax.setMax(rayTarget); /* Add box cast extents to bounding box */ rayAabbMin += aabbMin; rayAabbMax += aabbMax; #ifdef RAYAABB2 b3Vector3 rayDir = (rayTarget-raySource); rayDir.normalize (); lambda_max = rayDir.dot(rayTarget-raySource); ///what about division by zero? --> just set rayDirection[i] to 1.0 b3Vector3 rayDirectionInverse; rayDirectionInverse[0] = rayDir[0] == b3Scalar(0.0) ? b3Scalar(B3_LARGE_FLOAT) : b3Scalar(1.0) / rayDir[0]; rayDirectionInverse[1] = rayDir[1] == b3Scalar(0.0) ? b3Scalar(B3_LARGE_FLOAT) : b3Scalar(1.0) / rayDir[1]; rayDirectionInverse[2] = rayDir[2] == b3Scalar(0.0) ? b3Scalar(B3_LARGE_FLOAT) : b3Scalar(1.0) / rayDir[2]; unsigned int sign[3] = { rayDirectionInverse[0] < 0.0, rayDirectionInverse[1] < 0.0, rayDirectionInverse[2] < 0.0}; #endif b3Vector3 bounds[2]; while (curIndex < m_curNodeIndex) { b3Scalar param = 1.0; //catch bugs in tree data b3Assert (walkIterations < m_curNodeIndex); walkIterations++; bounds[0] = rootNode->m_aabbMinOrg; bounds[1] = rootNode->m_aabbMaxOrg; /* Add box cast extents */ bounds[0] -= aabbMax; bounds[1] -= aabbMin; aabbOverlap = b3TestAabbAgainstAabb2(rayAabbMin,rayAabbMax,rootNode->m_aabbMinOrg,rootNode->m_aabbMaxOrg); //perhaps profile if it is worth doing the aabbOverlap test first #ifdef RAYAABB2 ///careful with this check: need to check division by zero (above) and fix the unQuantize method ///thanks Joerg/hiker for the reproduction case! ///http://www.bulletphysics.com/Bullet/phpBB3/viewtopic.php?f=9&t=1858 rayBoxOverlap = aabbOverlap ? b3RayAabb2 (raySource, rayDirectionInverse, sign, bounds, param, 0.0f, lambda_max) : false; #else b3Vector3 normal; rayBoxOverlap = b3RayAabb(raySource, rayTarget,bounds[0],bounds[1],param, normal); #endif isLeafNode = rootNode->m_escapeIndex == -1; //PCK: unsigned instead of bool if (isLeafNode && (rayBoxOverlap != 0)) { nodeCallback->processNode(rootNode->m_subPart,rootNode->m_triangleIndex); } //PCK: unsigned instead of bool if ((rayBoxOverlap != 0) || isLeafNode) { rootNode++; curIndex++; } else { escapeIndex = rootNode->m_escapeIndex; rootNode += escapeIndex; curIndex += escapeIndex; } } if (b3s_maxIterations < walkIterations) b3s_maxIterations = walkIterations; } void b3QuantizedBvh::walkStacklessQuantizedTreeAgainstRay(b3NodeOverlapCallback* nodeCallback, const b3Vector3& raySource, const b3Vector3& rayTarget, const b3Vector3& aabbMin, const b3Vector3& aabbMax, int startNodeIndex,int endNodeIndex) const { b3Assert(m_useQuantization); int curIndex = startNodeIndex; int walkIterations = 0; int subTreeSize = endNodeIndex - startNodeIndex; (void)subTreeSize; const b3QuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex]; int escapeIndex; bool isLeafNode; //PCK: unsigned instead of bool unsigned boxBoxOverlap = 0; unsigned rayBoxOverlap = 0; b3Scalar lambda_max = 1.0; #ifdef RAYAABB2 b3Vector3 rayDirection = (rayTarget-raySource); rayDirection.normalize (); lambda_max = rayDirection.dot(rayTarget-raySource); ///what about division by zero? --> just set rayDirection[i] to 1.0 rayDirection[0] = rayDirection[0] == b3Scalar(0.0) ? b3Scalar(B3_LARGE_FLOAT) : b3Scalar(1.0) / rayDirection[0]; rayDirection[1] = rayDirection[1] == b3Scalar(0.0) ? b3Scalar(B3_LARGE_FLOAT) : b3Scalar(1.0) / rayDirection[1]; rayDirection[2] = rayDirection[2] == b3Scalar(0.0) ? b3Scalar(B3_LARGE_FLOAT) : b3Scalar(1.0) / rayDirection[2]; unsigned int sign[3] = { rayDirection[0] < 0.0, rayDirection[1] < 0.0, rayDirection[2] < 0.0}; #endif /* Quick pruning by quantized box */ b3Vector3 rayAabbMin = raySource; b3Vector3 rayAabbMax = raySource; rayAabbMin.setMin(rayTarget); rayAabbMax.setMax(rayTarget); /* Add box cast extents to bounding box */ rayAabbMin += aabbMin; rayAabbMax += aabbMax; unsigned short int quantizedQueryAabbMin[3]; unsigned short int quantizedQueryAabbMax[3]; quantizeWithClamp(quantizedQueryAabbMin,rayAabbMin,0); quantizeWithClamp(quantizedQueryAabbMax,rayAabbMax,1); while (curIndex < endNodeIndex) { //#define VISUALLY_ANALYZE_BVH 1 #ifdef VISUALLY_ANALYZE_BVH //some code snippet to debugDraw aabb, to visually analyze bvh structure static int drawPatch = 0; //need some global access to a debugDrawer extern b3IDebugDraw* debugDrawerPtr; if (curIndex==drawPatch) { b3Vector3 aabbMin,aabbMax; aabbMin = unQuantize(rootNode->m_quantizedAabbMin); aabbMax = unQuantize(rootNode->m_quantizedAabbMax); b3Vector3 color(1,0,0); debugDrawerPtr->drawAabb(aabbMin,aabbMax,color); } #endif//VISUALLY_ANALYZE_BVH //catch bugs in tree data b3Assert (walkIterations < subTreeSize); walkIterations++; //PCK: unsigned instead of bool // only interested if this is closer than any previous hit b3Scalar param = 1.0; rayBoxOverlap = 0; boxBoxOverlap = b3TestQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax); isLeafNode = rootNode->isLeafNode(); if (boxBoxOverlap) { b3Vector3 bounds[2]; bounds[0] = unQuantize(rootNode->m_quantizedAabbMin); bounds[1] = unQuantize(rootNode->m_quantizedAabbMax); /* Add box cast extents */ bounds[0] -= aabbMax; bounds[1] -= aabbMin; #if 0 b3Vector3 normal; bool ra2 = b3RayAabb2 (raySource, rayDirection, sign, bounds, param, 0.0, lambda_max); bool ra = b3RayAabb (raySource, rayTarget, bounds[0], bounds[1], param, normal); if (ra2 != ra) { printf("functions don't match\n"); } #endif #ifdef RAYAABB2 ///careful with this check: need to check division by zero (above) and fix the unQuantize method ///thanks Joerg/hiker for the reproduction case! ///http://www.bulletphysics.com/Bullet/phpBB3/viewtopic.php?f=9&t=1858 //B3_PROFILE("b3RayAabb2"); rayBoxOverlap = b3RayAabb2 (raySource, rayDirection, sign, bounds, param, 0.0f, lambda_max); #else rayBoxOverlap = true;//b3RayAabb(raySource, rayTarget, bounds[0], bounds[1], param, normal); #endif } if (isLeafNode && rayBoxOverlap) { nodeCallback->processNode(rootNode->getPartId(),rootNode->getTriangleIndex()); } //PCK: unsigned instead of bool if ((rayBoxOverlap != 0) || isLeafNode) { rootNode++; curIndex++; } else { escapeIndex = rootNode->getEscapeIndex(); rootNode += escapeIndex; curIndex += escapeIndex; } } if (b3s_maxIterations < walkIterations) b3s_maxIterations = walkIterations; } void b3QuantizedBvh::walkStacklessQuantizedTree(b3NodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const { b3Assert(m_useQuantization); int curIndex = startNodeIndex; int walkIterations = 0; int subTreeSize = endNodeIndex - startNodeIndex; (void)subTreeSize; const b3QuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex]; int escapeIndex; bool isLeafNode; //PCK: unsigned instead of bool unsigned aabbOverlap; while (curIndex < endNodeIndex) { //#define VISUALLY_ANALYZE_BVH 1 #ifdef VISUALLY_ANALYZE_BVH //some code snippet to debugDraw aabb, to visually analyze bvh structure static int drawPatch = 0; //need some global access to a debugDrawer extern b3IDebugDraw* debugDrawerPtr; if (curIndex==drawPatch) { b3Vector3 aabbMin,aabbMax; aabbMin = unQuantize(rootNode->m_quantizedAabbMin); aabbMax = unQuantize(rootNode->m_quantizedAabbMax); b3Vector3 color(1,0,0); debugDrawerPtr->drawAabb(aabbMin,aabbMax,color); } #endif//VISUALLY_ANALYZE_BVH //catch bugs in tree data b3Assert (walkIterations < subTreeSize); walkIterations++; //PCK: unsigned instead of bool aabbOverlap = b3TestQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax); isLeafNode = rootNode->isLeafNode(); if (isLeafNode && aabbOverlap) { nodeCallback->processNode(rootNode->getPartId(),rootNode->getTriangleIndex()); } //PCK: unsigned instead of bool if ((aabbOverlap != 0) || isLeafNode) { rootNode++; curIndex++; } else { escapeIndex = rootNode->getEscapeIndex(); rootNode += escapeIndex; curIndex += escapeIndex; } } if (b3s_maxIterations < walkIterations) b3s_maxIterations = walkIterations; } //This traversal can be called from Playstation 3 SPU void b3QuantizedBvh::walkStacklessQuantizedTreeCacheFriendly(b3NodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const { b3Assert(m_useQuantization); int i; for (i=0;i<this->m_SubtreeHeaders.size();i++) { const b3BvhSubtreeInfo& subtree = m_SubtreeHeaders[i]; //PCK: unsigned instead of bool unsigned overlap = b3TestQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax); if (overlap != 0) { walkStacklessQuantizedTree(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax, subtree.m_rootNodeIndex, subtree.m_rootNodeIndex+subtree.m_subtreeSize); } } } void b3QuantizedBvh::reportRayOverlappingNodex (b3NodeOverlapCallback* nodeCallback, const b3Vector3& raySource, const b3Vector3& rayTarget) const { reportBoxCastOverlappingNodex(nodeCallback,raySource,rayTarget,b3MakeVector3(0,0,0),b3MakeVector3(0,0,0)); } void b3QuantizedBvh::reportBoxCastOverlappingNodex(b3NodeOverlapCallback* nodeCallback, const b3Vector3& raySource, const b3Vector3& rayTarget, const b3Vector3& aabbMin,const b3Vector3& aabbMax) const { //always use stackless if (m_useQuantization) { walkStacklessQuantizedTreeAgainstRay(nodeCallback, raySource, rayTarget, aabbMin, aabbMax, 0, m_curNodeIndex); } else { walkStacklessTreeAgainstRay(nodeCallback, raySource, rayTarget, aabbMin, aabbMax, 0, m_curNodeIndex); } /* { //recursive traversal b3Vector3 qaabbMin = raySource; b3Vector3 qaabbMax = raySource; qaabbMin.setMin(rayTarget); qaabbMax.setMax(rayTarget); qaabbMin += aabbMin; qaabbMax += aabbMax; reportAabbOverlappingNodex(nodeCallback,qaabbMin,qaabbMax); } */ } void b3QuantizedBvh::swapLeafNodes(int i,int splitIndex) { if (m_useQuantization) { b3QuantizedBvhNode tmp = m_quantizedLeafNodes[i]; m_quantizedLeafNodes[i] = m_quantizedLeafNodes[splitIndex]; m_quantizedLeafNodes[splitIndex] = tmp; } else { b3OptimizedBvhNode tmp = m_leafNodes[i]; m_leafNodes[i] = m_leafNodes[splitIndex]; m_leafNodes[splitIndex] = tmp; } } void b3QuantizedBvh::assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex) { if (m_useQuantization) { m_quantizedContiguousNodes[internalNode] = m_quantizedLeafNodes[leafNodeIndex]; } else { m_contiguousNodes[internalNode] = m_leafNodes[leafNodeIndex]; } } //PCK: include #include <new> #if 0 //PCK: consts static const unsigned BVH_ALIGNMENT = 16; static const unsigned BVH_ALIGNMENT_MASK = BVH_ALIGNMENT-1; static const unsigned BVH_ALIGNMENT_BLOCKS = 2; #endif unsigned int b3QuantizedBvh::getAlignmentSerializationPadding() { // I changed this to 0 since the extra padding is not needed or used. return 0;//BVH_ALIGNMENT_BLOCKS * BVH_ALIGNMENT; } unsigned b3QuantizedBvh::calculateSerializeBufferSize() const { unsigned baseSize = sizeof(b3QuantizedBvh) + getAlignmentSerializationPadding(); baseSize += sizeof(b3BvhSubtreeInfo) * m_subtreeHeaderCount; if (m_useQuantization) { return baseSize + m_curNodeIndex * sizeof(b3QuantizedBvhNode); } return baseSize + m_curNodeIndex * sizeof(b3OptimizedBvhNode); } bool b3QuantizedBvh::serialize(void *o_alignedDataBuffer, unsigned /*i_dataBufferSize */, bool i_swapEndian) const { b3Assert(m_subtreeHeaderCount == m_SubtreeHeaders.size()); m_subtreeHeaderCount = m_SubtreeHeaders.size(); /* if (i_dataBufferSize < calculateSerializeBufferSize() || o_alignedDataBuffer == NULL || (((unsigned)o_alignedDataBuffer & BVH_ALIGNMENT_MASK) != 0)) { ///check alignedment for buffer? b3Assert(0); return false; } */ b3QuantizedBvh *targetBvh = (b3QuantizedBvh *)o_alignedDataBuffer; // construct the class so the virtual function table, etc will be set up // Also, m_leafNodes and m_quantizedLeafNodes will be initialized to default values by the constructor new (targetBvh) b3QuantizedBvh; if (i_swapEndian) { targetBvh->m_curNodeIndex = static_cast<int>(b3SwapEndian(m_curNodeIndex)); b3SwapVector3Endian(m_bvhAabbMin,targetBvh->m_bvhAabbMin); b3SwapVector3Endian(m_bvhAabbMax,targetBvh->m_bvhAabbMax); b3SwapVector3Endian(m_bvhQuantization,targetBvh->m_bvhQuantization); targetBvh->m_traversalMode = (b3TraversalMode)b3SwapEndian(m_traversalMode); targetBvh->m_subtreeHeaderCount = static_cast<int>(b3SwapEndian(m_subtreeHeaderCount)); } else { targetBvh->m_curNodeIndex = m_curNodeIndex; targetBvh->m_bvhAabbMin = m_bvhAabbMin; targetBvh->m_bvhAabbMax = m_bvhAabbMax; targetBvh->m_bvhQuantization = m_bvhQuantization; targetBvh->m_traversalMode = m_traversalMode; targetBvh->m_subtreeHeaderCount = m_subtreeHeaderCount; } targetBvh->m_useQuantization = m_useQuantization; unsigned char *nodeData = (unsigned char *)targetBvh; nodeData += sizeof(b3QuantizedBvh); unsigned sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; nodeData += sizeToAdd; int nodeCount = m_curNodeIndex; if (m_useQuantization) { targetBvh->m_quantizedContiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); if (i_swapEndian) { for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]); targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]); targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]); targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]); targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]); targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]); targetBvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = static_cast<int>(b3SwapEndian(m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex)); } } else { for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]; targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]; targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]; targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]; targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]; targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]; targetBvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex; } } nodeData += sizeof(b3QuantizedBvhNode) * nodeCount; // this clears the pointer in the member variable it doesn't really do anything to the data // it does call the destructor on the contained objects, but they are all classes with no destructor defined // so the memory (which is not freed) is left alone targetBvh->m_quantizedContiguousNodes.initializeFromBuffer(NULL, 0, 0); } else { targetBvh->m_contiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); if (i_swapEndian) { for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { b3SwapVector3Endian(m_contiguousNodes[nodeIndex].m_aabbMinOrg, targetBvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg); b3SwapVector3Endian(m_contiguousNodes[nodeIndex].m_aabbMaxOrg, targetBvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg); targetBvh->m_contiguousNodes[nodeIndex].m_escapeIndex = static_cast<int>(b3SwapEndian(m_contiguousNodes[nodeIndex].m_escapeIndex)); targetBvh->m_contiguousNodes[nodeIndex].m_subPart = static_cast<int>(b3SwapEndian(m_contiguousNodes[nodeIndex].m_subPart)); targetBvh->m_contiguousNodes[nodeIndex].m_triangleIndex = static_cast<int>(b3SwapEndian(m_contiguousNodes[nodeIndex].m_triangleIndex)); } } else { for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { targetBvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg = m_contiguousNodes[nodeIndex].m_aabbMinOrg; targetBvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg = m_contiguousNodes[nodeIndex].m_aabbMaxOrg; targetBvh->m_contiguousNodes[nodeIndex].m_escapeIndex = m_contiguousNodes[nodeIndex].m_escapeIndex; targetBvh->m_contiguousNodes[nodeIndex].m_subPart = m_contiguousNodes[nodeIndex].m_subPart; targetBvh->m_contiguousNodes[nodeIndex].m_triangleIndex = m_contiguousNodes[nodeIndex].m_triangleIndex; } } nodeData += sizeof(b3OptimizedBvhNode) * nodeCount; // this clears the pointer in the member variable it doesn't really do anything to the data // it does call the destructor on the contained objects, but they are all classes with no destructor defined // so the memory (which is not freed) is left alone targetBvh->m_contiguousNodes.initializeFromBuffer(NULL, 0, 0); } sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; nodeData += sizeToAdd; // Now serialize the subtree headers targetBvh->m_SubtreeHeaders.initializeFromBuffer(nodeData, m_subtreeHeaderCount, m_subtreeHeaderCount); if (i_swapEndian) { for (int i = 0; i < m_subtreeHeaderCount; i++) { targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = b3SwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[0]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = b3SwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[1]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = b3SwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[2]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = b3SwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[0]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = b3SwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[1]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = b3SwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[2]); targetBvh->m_SubtreeHeaders[i].m_rootNodeIndex = static_cast<int>(b3SwapEndian(m_SubtreeHeaders[i].m_rootNodeIndex)); targetBvh->m_SubtreeHeaders[i].m_subtreeSize = static_cast<int>(b3SwapEndian(m_SubtreeHeaders[i].m_subtreeSize)); } } else { for (int i = 0; i < m_subtreeHeaderCount; i++) { targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = (m_SubtreeHeaders[i].m_quantizedAabbMin[0]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = (m_SubtreeHeaders[i].m_quantizedAabbMin[1]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = (m_SubtreeHeaders[i].m_quantizedAabbMin[2]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = (m_SubtreeHeaders[i].m_quantizedAabbMax[0]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = (m_SubtreeHeaders[i].m_quantizedAabbMax[1]); targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = (m_SubtreeHeaders[i].m_quantizedAabbMax[2]); targetBvh->m_SubtreeHeaders[i].m_rootNodeIndex = (m_SubtreeHeaders[i].m_rootNodeIndex); targetBvh->m_SubtreeHeaders[i].m_subtreeSize = (m_SubtreeHeaders[i].m_subtreeSize); // need to clear padding in destination buffer targetBvh->m_SubtreeHeaders[i].m_padding[0] = 0; targetBvh->m_SubtreeHeaders[i].m_padding[1] = 0; targetBvh->m_SubtreeHeaders[i].m_padding[2] = 0; } } nodeData += sizeof(b3BvhSubtreeInfo) * m_subtreeHeaderCount; // this clears the pointer in the member variable it doesn't really do anything to the data // it does call the destructor on the contained objects, but they are all classes with no destructor defined // so the memory (which is not freed) is left alone targetBvh->m_SubtreeHeaders.initializeFromBuffer(NULL, 0, 0); // this wipes the virtual function table pointer at the start of the buffer for the class *((void**)o_alignedDataBuffer) = NULL; return true; } b3QuantizedBvh *b3QuantizedBvh::deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian) { if (i_alignedDataBuffer == NULL)// || (((unsigned)i_alignedDataBuffer & BVH_ALIGNMENT_MASK) != 0)) { return NULL; } b3QuantizedBvh *bvh = (b3QuantizedBvh *)i_alignedDataBuffer; if (i_swapEndian) { bvh->m_curNodeIndex = static_cast<int>(b3SwapEndian(bvh->m_curNodeIndex)); b3UnSwapVector3Endian(bvh->m_bvhAabbMin); b3UnSwapVector3Endian(bvh->m_bvhAabbMax); b3UnSwapVector3Endian(bvh->m_bvhQuantization); bvh->m_traversalMode = (b3TraversalMode)b3SwapEndian(bvh->m_traversalMode); bvh->m_subtreeHeaderCount = static_cast<int>(b3SwapEndian(bvh->m_subtreeHeaderCount)); } unsigned int calculatedBufSize = bvh->calculateSerializeBufferSize(); b3Assert(calculatedBufSize <= i_dataBufferSize); if (calculatedBufSize > i_dataBufferSize) { return NULL; } unsigned char *nodeData = (unsigned char *)bvh; nodeData += sizeof(b3QuantizedBvh); unsigned sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; nodeData += sizeToAdd; int nodeCount = bvh->m_curNodeIndex; // Must call placement new to fill in virtual function table, etc, but we don't want to overwrite most data, so call a special version of the constructor // Also, m_leafNodes and m_quantizedLeafNodes will be initialized to default values by the constructor new (bvh) b3QuantizedBvh(*bvh, false); if (bvh->m_useQuantization) { bvh->m_quantizedContiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); if (i_swapEndian) { for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]); bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]); bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]); bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]); bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]); bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]); bvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = static_cast<int>(b3SwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex)); } } nodeData += sizeof(b3QuantizedBvhNode) * nodeCount; } else { bvh->m_contiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); if (i_swapEndian) { for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { b3UnSwapVector3Endian(bvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg); b3UnSwapVector3Endian(bvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg); bvh->m_contiguousNodes[nodeIndex].m_escapeIndex = static_cast<int>(b3SwapEndian(bvh->m_contiguousNodes[nodeIndex].m_escapeIndex)); bvh->m_contiguousNodes[nodeIndex].m_subPart = static_cast<int>(b3SwapEndian(bvh->m_contiguousNodes[nodeIndex].m_subPart)); bvh->m_contiguousNodes[nodeIndex].m_triangleIndex = static_cast<int>(b3SwapEndian(bvh->m_contiguousNodes[nodeIndex].m_triangleIndex)); } } nodeData += sizeof(b3OptimizedBvhNode) * nodeCount; } sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; nodeData += sizeToAdd; // Now serialize the subtree headers bvh->m_SubtreeHeaders.initializeFromBuffer(nodeData, bvh->m_subtreeHeaderCount, bvh->m_subtreeHeaderCount); if (i_swapEndian) { for (int i = 0; i < bvh->m_subtreeHeaderCount; i++) { bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = b3SwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0]); bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = b3SwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1]); bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = b3SwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2]); bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = b3SwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0]); bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = b3SwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1]); bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = b3SwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2]); bvh->m_SubtreeHeaders[i].m_rootNodeIndex = static_cast<int>(b3SwapEndian(bvh->m_SubtreeHeaders[i].m_rootNodeIndex)); bvh->m_SubtreeHeaders[i].m_subtreeSize = static_cast<int>(b3SwapEndian(bvh->m_SubtreeHeaders[i].m_subtreeSize)); } } return bvh; } // Constructor that prevents b3Vector3's default constructor from being called b3QuantizedBvh::b3QuantizedBvh(b3QuantizedBvh &self, bool /* ownsMemory */) : m_bvhAabbMin(self.m_bvhAabbMin), m_bvhAabbMax(self.m_bvhAabbMax), m_bvhQuantization(self.m_bvhQuantization), m_bulletVersion(B3_BULLET_VERSION) { } void b3QuantizedBvh::deSerializeFloat(struct b3QuantizedBvhFloatData& quantizedBvhFloatData) { m_bvhAabbMax.deSerializeFloat(quantizedBvhFloatData.m_bvhAabbMax); m_bvhAabbMin.deSerializeFloat(quantizedBvhFloatData.m_bvhAabbMin); m_bvhQuantization.deSerializeFloat(quantizedBvhFloatData.m_bvhQuantization); m_curNodeIndex = quantizedBvhFloatData.m_curNodeIndex; m_useQuantization = quantizedBvhFloatData.m_useQuantization!=0; { int numElem = quantizedBvhFloatData.m_numContiguousLeafNodes; m_contiguousNodes.resize(numElem); if (numElem) { b3OptimizedBvhNodeFloatData* memPtr = quantizedBvhFloatData.m_contiguousNodesPtr; for (int i=0;i<numElem;i++,memPtr++) { m_contiguousNodes[i].m_aabbMaxOrg.deSerializeFloat(memPtr->m_aabbMaxOrg); m_contiguousNodes[i].m_aabbMinOrg.deSerializeFloat(memPtr->m_aabbMinOrg); m_contiguousNodes[i].m_escapeIndex = memPtr->m_escapeIndex; m_contiguousNodes[i].m_subPart = memPtr->m_subPart; m_contiguousNodes[i].m_triangleIndex = memPtr->m_triangleIndex; } } } { int numElem = quantizedBvhFloatData.m_numQuantizedContiguousNodes; m_quantizedContiguousNodes.resize(numElem); if (numElem) { b3QuantizedBvhNodeData* memPtr = quantizedBvhFloatData.m_quantizedContiguousNodesPtr; for (int i=0;i<numElem;i++,memPtr++) { m_quantizedContiguousNodes[i].m_escapeIndexOrTriangleIndex = memPtr->m_escapeIndexOrTriangleIndex; m_quantizedContiguousNodes[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0]; m_quantizedContiguousNodes[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1]; m_quantizedContiguousNodes[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2]; m_quantizedContiguousNodes[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0]; m_quantizedContiguousNodes[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1]; m_quantizedContiguousNodes[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2]; } } } m_traversalMode = b3TraversalMode(quantizedBvhFloatData.m_traversalMode); { int numElem = quantizedBvhFloatData.m_numSubtreeHeaders; m_SubtreeHeaders.resize(numElem); if (numElem) { b3BvhSubtreeInfoData* memPtr = quantizedBvhFloatData.m_subTreeInfoPtr; for (int i=0;i<numElem;i++,memPtr++) { m_SubtreeHeaders[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0] ; m_SubtreeHeaders[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1]; m_SubtreeHeaders[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2]; m_SubtreeHeaders[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0]; m_SubtreeHeaders[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1]; m_SubtreeHeaders[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2]; m_SubtreeHeaders[i].m_rootNodeIndex = memPtr->m_rootNodeIndex; m_SubtreeHeaders[i].m_subtreeSize = memPtr->m_subtreeSize; } } } } void b3QuantizedBvh::deSerializeDouble(struct b3QuantizedBvhDoubleData& quantizedBvhDoubleData) { m_bvhAabbMax.deSerializeDouble(quantizedBvhDoubleData.m_bvhAabbMax); m_bvhAabbMin.deSerializeDouble(quantizedBvhDoubleData.m_bvhAabbMin); m_bvhQuantization.deSerializeDouble(quantizedBvhDoubleData.m_bvhQuantization); m_curNodeIndex = quantizedBvhDoubleData.m_curNodeIndex; m_useQuantization = quantizedBvhDoubleData.m_useQuantization!=0; { int numElem = quantizedBvhDoubleData.m_numContiguousLeafNodes; m_contiguousNodes.resize(numElem); if (numElem) { b3OptimizedBvhNodeDoubleData* memPtr = quantizedBvhDoubleData.m_contiguousNodesPtr; for (int i=0;i<numElem;i++,memPtr++) { m_contiguousNodes[i].m_aabbMaxOrg.deSerializeDouble(memPtr->m_aabbMaxOrg); m_contiguousNodes[i].m_aabbMinOrg.deSerializeDouble(memPtr->m_aabbMinOrg); m_contiguousNodes[i].m_escapeIndex = memPtr->m_escapeIndex; m_contiguousNodes[i].m_subPart = memPtr->m_subPart; m_contiguousNodes[i].m_triangleIndex = memPtr->m_triangleIndex; } } } { int numElem = quantizedBvhDoubleData.m_numQuantizedContiguousNodes; m_quantizedContiguousNodes.resize(numElem); if (numElem) { b3QuantizedBvhNodeData* memPtr = quantizedBvhDoubleData.m_quantizedContiguousNodesPtr; for (int i=0;i<numElem;i++,memPtr++) { m_quantizedContiguousNodes[i].m_escapeIndexOrTriangleIndex = memPtr->m_escapeIndexOrTriangleIndex; m_quantizedContiguousNodes[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0]; m_quantizedContiguousNodes[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1]; m_quantizedContiguousNodes[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2]; m_quantizedContiguousNodes[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0]; m_quantizedContiguousNodes[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1]; m_quantizedContiguousNodes[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2]; } } } m_traversalMode = b3TraversalMode(quantizedBvhDoubleData.m_traversalMode); { int numElem = quantizedBvhDoubleData.m_numSubtreeHeaders; m_SubtreeHeaders.resize(numElem); if (numElem) { b3BvhSubtreeInfoData* memPtr = quantizedBvhDoubleData.m_subTreeInfoPtr; for (int i=0;i<numElem;i++,memPtr++) { m_SubtreeHeaders[i].m_quantizedAabbMax[0] = memPtr->m_quantizedAabbMax[0] ; m_SubtreeHeaders[i].m_quantizedAabbMax[1] = memPtr->m_quantizedAabbMax[1]; m_SubtreeHeaders[i].m_quantizedAabbMax[2] = memPtr->m_quantizedAabbMax[2]; m_SubtreeHeaders[i].m_quantizedAabbMin[0] = memPtr->m_quantizedAabbMin[0]; m_SubtreeHeaders[i].m_quantizedAabbMin[1] = memPtr->m_quantizedAabbMin[1]; m_SubtreeHeaders[i].m_quantizedAabbMin[2] = memPtr->m_quantizedAabbMin[2]; m_SubtreeHeaders[i].m_rootNodeIndex = memPtr->m_rootNodeIndex; m_SubtreeHeaders[i].m_subtreeSize = memPtr->m_subtreeSize; } } } } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* b3QuantizedBvh::serialize(void* dataBuffer, b3Serializer* serializer) const { b3Assert(0); return 0; }
412
0.96172
1
0.96172
game-dev
MEDIA
0.776501
game-dev
0.994249
1
0.994249
Winds-Studio/Leaf
7,676
leaf-server/minecraft-patches/features/0013-Optimize-random-calls-in-chunk-ticking.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Martijn Muijsers <martijnmuijsers@live.nl> Date: Wed, 23 Nov 2022 16:45:45 +0100 Subject: [PATCH] Optimize random calls in chunk ticking License: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html) Gale - https://galemc.org This patch is based on the following patch: "Optimize random calls in chunk ticking" By: Paul Sauve <paul@technove.co> As part of: Airplane (https://github.com/TECHNOVE/Airplane) Licensed under: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html) The patch also received the following subsequent modification: By: Kevin Raneri <kevin.raneri@gmail.com> As part of: Pufferfish (https://github.com/pufferfish-gg/Pufferfish) Licensed under: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html) * Airplane description * Especially at over 30,000 chunks these random calls are fairly heavy. We use a different method here for checking lightning, and for checking ice. Lightning: Each chunk now keeps an int of how many ticks until the lightning should strike. This int is a random number from 0 to 100000 * 2, the multiplication is required to keep the probability the same. Ice and snow: We just generate a single random number 0-16 and increment it, while checking if it's 0 for the current chunk. Depending on configuration for things that tick in a chunk, this is a 5-10% improvement. * Airplane copyright * Airplane Copyright (C) 2020 Technove LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. diff --git a/net/minecraft/server/level/ServerChunkCache.java b/net/minecraft/server/level/ServerChunkCache.java index 6020b71802babb35ef60aca65afe9c2612c05bb7..e53440bd5f0e659db0745a009540520f6dc41238 100644 --- a/net/minecraft/server/level/ServerChunkCache.java +++ b/net/minecraft/server/level/ServerChunkCache.java @@ -500,6 +500,7 @@ public class ServerChunkCache extends ChunkSource implements ca.spottedleaf.moon long l = gameTime - this.lastInhabitedUpdate; this.lastInhabitedUpdate = gameTime; if (!this.level.isDebug()) { + this.level.resetIceAndSnowTick(); // Gale - Airplane - optimize random calls in chunk ticking - reset ice & snow tick random if (this.level.tickRateManager().runsNormally()) { this.tickChunks(l); // Gale - Purpur - remove vanilla profiler } diff --git a/net/minecraft/server/level/ServerLevel.java b/net/minecraft/server/level/ServerLevel.java index 7b7794eb8f9a663bd6d4f6e27ddf907c0aed8c5a..3507691e6f18b90464627617e11b2fcd36ce7f68 100644 --- a/net/minecraft/server/level/ServerLevel.java +++ b/net/minecraft/server/level/ServerLevel.java @@ -925,13 +925,15 @@ public class ServerLevel extends Level implements ServerEntityGetter, WorldGenLe } // Paper end - optimise random ticking + private int currentIceAndSnowTick = 0; protected void resetIceAndSnowTick() { this.currentIceAndSnowTick = this.simpleRandom.nextInt(16); } // Gale - Airplane - optimize random calls in chunk ticking + public void tickChunk(LevelChunk chunk, int randomTickSpeed) { final ca.spottedleaf.moonrise.common.util.SimpleThreadUnsafeRandom simpleRandom = this.simpleRandom; // Paper - optimise random ticking ChunkPos pos = chunk.getPos(); int minBlockX = pos.getMinBlockX(); int minBlockZ = pos.getMinBlockZ(); - if (!this.paperConfig().environment.disableIceAndSnow) { // Paper - Option to disable ice and snow + if (!this.paperConfig().environment.disableIceAndSnow && (this.currentIceAndSnowTick++ & 15) == 0) { // Paper - Option to disable ice and snow // Gale - Airplane - optimize random calls in chunk ticking - optimize further random ticking for (int i = 0; i < randomTickSpeed; i++) { if (simpleRandom.nextInt(48) == 0) { // Paper - optimise random ticking this.tickPrecipitation(this.getBlockRandomPos(minBlockX, 0, minBlockZ, 15)); @@ -949,7 +951,7 @@ public class ServerLevel extends Level implements ServerEntityGetter, WorldGenLe boolean isRaining = this.isRaining(); int minBlockX = pos.getMinBlockX(); int minBlockZ = pos.getMinBlockZ(); - if (!this.paperConfig().environment.disableThunder && isRaining && this.isThundering() && this.spigotConfig.thunderChance > 0 && this.random.nextInt(this.spigotConfig.thunderChance) == 0) { // Spigot // Paper - Option to disable thunder + if (!this.paperConfig().environment.disableThunder && isRaining && this.isThundering() && this.spigotConfig.thunderChance > 0 /*&& this.random.nextInt(this.spigotConfig.thunderChance) == 0*/ && chunk.shouldDoLightning(this.random)) { // Spigot // Paper - Option to disable thunder // Gale - Airplane - optimize random calls in chunk ticking - replace random with shouldDoLightning BlockPos blockPos = this.findLightningTargetAround(this.getBlockRandomPos(minBlockX, 0, minBlockZ, 15)); if (this.isRainingAt(blockPos)) { DifficultyInstance currentDifficultyAt = this.getCurrentDifficultyAt(blockPos); diff --git a/net/minecraft/world/level/chunk/LevelChunk.java b/net/minecraft/world/level/chunk/LevelChunk.java index b88254fb3c12b99684c6ede1ae8a6671ffbe9ad6..9e2debee38bc4b25281c8a8c6e7082cca1f7b569 100644 --- a/net/minecraft/world/level/chunk/LevelChunk.java +++ b/net/minecraft/world/level/chunk/LevelChunk.java @@ -128,6 +128,18 @@ public class LevelChunk extends ChunkAccess implements ca.spottedleaf.moonrise.p } // Paper end - get block chunk optimisation + // Gale start - Airplane - optimize random calls in chunk ticking - instead of using a random every time the chunk is ticked, define when lightning strikes preemptively + private int lightningTick; + // shouldDoLightning compiles down to 29 bytes, which with the default of 35 byte inlining should guarantee an inline + public final boolean shouldDoLightning(net.minecraft.util.RandomSource random) { + if (this.lightningTick-- <= 0) { + this.lightningTick = random.nextInt(this.level.spigotConfig.thunderChance) << 1; + return true; + } + return false; + } + // Gale end - Airplane - optimize random calls in chunk ticking - instead of using a random every time the chunk is ticked, define when lightning strikes preemptively + public LevelChunk(Level level, ChunkPos pos) { this(level, pos, UpgradeData.EMPTY, new LevelChunkTicks<>(), new LevelChunkTicks<>(), 0L, null, null, null); } @@ -164,6 +176,8 @@ public class LevelChunk extends ChunkAccess implements ca.spottedleaf.moonrise.p this.debug = !empty && this.level.isDebug(); this.defaultBlockState = empty ? VOID_AIR_BLOCKSTATE : AIR_BLOCKSTATE; // Paper end - get block chunk optimisation + + this.lightningTick = this.level.simpleRandom.nextInt(100000) << 1; // Gale - Airplane - optimize random calls in chunk ticking - initialize lightning tick } public LevelChunk(ServerLevel level, ProtoChunk chunk, @Nullable LevelChunk.PostLoadProcessor postLoad) {
412
0.706732
1
0.706732
game-dev
MEDIA
0.973608
game-dev
0.583717
1
0.583717
ragemp-pro/redage_v3
1,241
src_client/animation/customScenario.js
const customScenarioMap = new Map(); class CustomScenario { constructor(data) { this.name = data; customScenarioMap.set(data, this); } isActive(player) { return player.cSen === this.name; } onStart(player) {} onStartForNew(player) {} onEnd(player) {} } global.CustomScenario = CustomScenario; gm.events.add("playerStreamIn", (entity) => { const data = entity.cSen; if (data) { const customScenario = customScenarioMap.get(data); if (customScenario) customScenario.onStartForNew(entity); } }); mp.events.addDataHandler("cSen", function (entity, data) { if (entity) { if (entity.cSen) { if (entity.handle !== 0) { const customScenario = customScenarioMap.get(entity.cSen); if (customScenario) customScenario.onEnd(entity); } delete entity.cSen; } if (null !== data) { if (entity.handle !== 0) { const customScenario = customScenarioMap.get(data); if (customScenario) customScenario.onStart(entity); } entity.cSen = data; } } });
412
0.862954
1
0.862954
game-dev
MEDIA
0.270705
game-dev
0.741718
1
0.741718
cadet/CADET-Core
3,280
src/libcadet/model/paramdep/PowerLawParameterDependence.cpp
// ============================================================================= // CADET // // Copyright © 2008-present: The CADET-Core Authors // Please see the AUTHORS.md file. // // All rights reserved. This program and the accompanying materials // are made available under the terms of the GNU Public License v3.0 (or, at // your option, any later version) which accompanies this distribution, and // is available at http://www.gnu.org/licenses/gpl.html // ============================================================================= #include "model/paramdep/ParameterDependenceBase.hpp" #include "SimulationTypes.hpp" #include "cadet/ParameterId.hpp" #include <cmath> namespace cadet { namespace model { /** * @brief Defines a power law parameter parameter dependence * @details The parameter dependence is defined as * @f[\begin{align} p_{new}(p) = \alpha p^k, \end{align} @f] where @f$ \alpha @f$ and @f$ k @f$ are (meta-)parameters. */ class PowerLawParameterParameterDependence : public ParameterParameterDependenceBase { public: PowerLawParameterParameterDependence() { } virtual ~PowerLawParameterParameterDependence() CADET_NOEXCEPT { } static const char* identifier() { return "POWER_LAW"; } virtual const char* name() const CADET_NOEXCEPT { return PowerLawParameterParameterDependence::identifier(); } CADET_PARAMETERPARAMETERDEPENDENCE_BOILERPLATE protected: active _base; active _exponent; bool _useAbs; virtual bool configureImpl(IParameterProvider& paramProvider, UnitOpIdx unitOpIdx, ParticleTypeIdx parTypeIdx, BoundStateIdx bndIdx, const std::string& name) { const std::string baseName = name + "_BASE"; const std::string expName = name + "_EXPONENT"; const std::string flagName = name + "_ABS"; if (paramProvider.exists(baseName)) _base = paramProvider.getDouble(baseName); else _base = 1.0; _exponent = paramProvider.getDouble(expName); if (paramProvider.exists(flagName)) _useAbs = paramProvider.getBool(flagName); else _useAbs = true; _parameters[makeParamId(hashStringRuntime(baseName), unitOpIdx, CompIndep, parTypeIdx, bndIdx, ReactionIndep, SectionIndep)] = &_base; _parameters[makeParamId(hashStringRuntime(expName), unitOpIdx, CompIndep, parTypeIdx, bndIdx, ReactionIndep, SectionIndep)] = &_exponent; return true; } template <typename ParamType> ParamType getValueImpl(const IModel& model, const ColumnPosition& colPos, int comp, int parType, int bnd) const { return 0.0; } template <typename ParamType> ParamType getValueImpl(const IModel& model, const ColumnPosition& colPos, int comp, int parType, int bnd, ParamType val) const { using std::pow; using std::abs; if (_useAbs) return static_cast<ParamType>(_base) * pow(abs(val), static_cast<ParamType>(_exponent)); else return static_cast<ParamType>(_base) * pow(val, static_cast<ParamType>(_exponent)); } }; namespace paramdep { void registerPowerLawParamDependence(std::unordered_map<std::string, std::function<model::IParameterParameterDependence*()>>& paramDeps) { paramDeps[PowerLawParameterParameterDependence::identifier()] = []() { return new PowerLawParameterParameterDependence(); }; } } // namespace paramdep } // namespace model } // namespace cadet
412
0.890715
1
0.890715
game-dev
MEDIA
0.499841
game-dev
0.649416
1
0.649416
dgant/PurpleWave
5,267
src/Information/Geography/Types/Geo.scala
package Information.Geography.Types import Debugging.RadianArrow import Lifecycle.With import Mathematics.Maff import Mathematics.Points.{Direction, Pixel, Points, Tile, TileRectangle} import Performance.Cache import ProxyBwapi.Players.PlayerInfo import ProxyBwapi.UnitInfo.UnitInfo import Utilities.? trait Geo { val tiles : Set[Tile] def heart : Tile def owner : PlayerInfo def units : Seq[UnitInfo] def bases : Vector[Base] def zones : Vector[Zone] lazy val isMain : Boolean = bases.map(_.townHallTile).exists(With.geography.startLocations.contains) lazy val isNatural : Boolean = bases.exists(_.naturalOf.isDefined) lazy val isCross : Boolean = ! With.geography.mains.sortBy(With.geography.ourMain.groundPixels).exists(bases.contains) lazy val island : Boolean = With.geography.mains.map(_.heart).count(With.paths.groundPathExists(_, centroid)) < 2 lazy val isInterior : Boolean = zones.forall(z => z.metro.exists(m => ! m.exits.exists(_.zones.contains(z)))) lazy val isBackyard : Boolean = zones.forall(z => z.metro.exists(m => ! m.exits.exists(_.zones.contains(z)) && z.rushDistanceMin > m.rushDistanceMin)) lazy val isPocket : Boolean = isInterior && ! isMain && ! island lazy val maxAltitude : Int = Maff.max(tiles.view.map(_.altitude)).getOrElse(0) lazy val radians : Double = Points.middle.radiansTo(heart.center) lazy val rushDistanceMin : Double = Maff.max(rushDistances).getOrElse(0) lazy val rushDistanceMax : Double = Maff.max(rushDistances).getOrElse(0) lazy val arrow : String = RadianArrow(Points.tileMiddle.radiansTo(heart)) lazy val adjective : String = if (island) "island " else if (isBackyard) "backyard " else if (isPocket) "pocket " else "" lazy val centroid : Tile = Maff.centroidTiles(Maff.orElse(tiles.filter(_.walkableUnchecked), tiles)) lazy val peak : Option[Tile] = Maff.minBy(peaks)(_.pixelDistance(heart)).filter(_.pixelDistance(heart) < 320).orElse(Maff.minBy(peaks)(p => Maff.min(edges.map(_.pixelCenter.pixelDistance(p.center))).getOrElse(heart.pixelDistance(p)))) lazy val boundary : TileRectangle = new TileRectangle(tiles) lazy val border : Set[Tile] = tiles.filter( ! _.adjacent8.forall(tiles.contains)) lazy val peaks : Set[Tile] = tiles.filter(_.altitude >= maxAltitude && maxAltitude > heart.altitude) lazy val selfAndChildren : Vector[Geo] = (Vector[Geo](this) ++ zones ++ bases).distinct lazy val edges : Vector[Edge] = With.geography.edges.filter(_.zones.exists(zones.contains)) lazy val exits : Vector[Edge] = edges.filter(_.zones.exists( ! zones.contains(_))).distinct lazy val rushDistances : Vector[Double] = With.geography.metros.filter(_.isMain).filterNot(_.selfAndChildren.contains(this)).map(groundPixels) lazy val entranceOriginal : Option[Edge] = _entranceCache() lazy val exitOriginal : Option[Edge] = Maff.minBy(exits)(e => With.geography.mains.map(_.heart).map(e.distanceGrid.get).max) lazy val exitDirection : Option[Direction] = exitOriginal.map(_.pixelCenter.subtract(heart.center).direction) lazy val groundPixelsToBases: Map[Base, Double] = With.geography.bases.map(b => (b, b.heart.groundPixels(heart))).toMap lazy val groundPixelsToZones: Map[Zone, Double] = With.geography.zones.map(z => (z, z.heart.groundPixels(heart))).toMap def isOurs : Boolean = owner.isUs def isAlly : Boolean = owner.isAlly def isEnemy : Boolean = owner.isEnemy def isNeutral : Boolean = owner.isNeutral def ourUnits : Seq[UnitInfo] = units.view.filter(_.isOurs) def allies : Seq[UnitInfo] = units.view.filter(_.isFriendly) def enemies : Seq[UnitInfo] = units.view.filter(_.isEnemy) def entranceNow : Option[Edge] = _entranceCache() def exitNow : Option[Edge] = _exitCache() def airDistance (other: Geo) : Double = heart.pixelDistance(other.heart) def groundPixels (other: Geo) : Double = heart.groundPixelsBidirectional(other.heart) def groundPixels (to: Pixel) : Double = heart.groundPixels(to) def groundPixels (to: Tile) : Double = heart.groundPixels(to) def edgeTo (to: Pixel) : Option[Edge] = Maff.minBy(exits)(_.pixelCenter.groundPixels(to)) private val _entranceCache = new Cache(() => Maff.minBy(exits)(edge => With.geography.startLocations.map(edge.distanceGrid.get).min)) private val _exitCache = new Cache(() => { val enemyZone = bases.exists(_.isEnemy) && ! bases.exists(_.isOurs) // Take the edge closest to opposing production Maff.minBy(edges)(edge => Maff.orElse( ?(enemyZone, Seq(With.geography.ourMain.heart), With.scouting.enemyMain.map(_.heart).toSeq), ?(enemyZone, Seq(With.scouting.ourThreatOrigin), Seq(With.scouting.enemyThreatOrigin))) .map(edge.distanceGrid.get)) }) }
412
0.799598
1
0.799598
game-dev
MEDIA
0.815062
game-dev
0.837912
1
0.837912
RedPandaProjects/STALKERonUE
7,859
gamedata_soc/scripts/ui_options_dialog.script
-- File: UI_MAIN_MENU.SCRIPT -- Description: Load Dialog for STALKER -- Created: 28.10.2004 -- Copyright: 2004 GSC Game World -- Author: Serhiy Vynnychenko (narrator@gsc-game.kiev.ua) -- Version: 0.1 function main() local dlg = ui_options_dialog.options_dialog() level.start_stop_menu(dlg,true) while true do wait(3000) end end class "options_dialog" (ui_base_dialog.base_dialog) function options_dialog:__init() super() self:SetFont(GetFontMedium()) --set base font for dialog. self:InitControls() self:InitCallBacks() end function options_dialog:__finalize() end function options_dialog:InitControls() ui_base_dialog.base_dialog.InitControls(self, "Options") ----- DATA ---- ----- BUTTONS --->>> local btn_video_rect = {x = self.left_align_x, y = self.top_align_y, width = self.btn_rect.width, height = self.btn_rect.height} local btn_sound_rect = {x = self.left_align_x, y = btn_video_rect.y + btn_video_rect.height + self.indent, width = self.btn_rect.width, height = self.btn_rect.height} local btn_game_rect = {x = self.left_align_x, y = btn_sound_rect.y + btn_sound_rect.height + self.indent, width = self.btn_rect.width, height = self.btn_rect.height} local btn_control_rect= {x = self.left_align_x, y = btn_game_rect.y + btn_game_rect.height + self.indent, width = self.btn_rect.width, height = self.btn_rect.height} local btn_profiles_rect={x = self.left_align_x, y = btn_control_rect.y + btn_control_rect.height + self.indent, width = self.btn_rect.width, height = self.btn_rect.height} ----- Bottom right align --->>> local btn_cancel_rect = {x = self.btn_special_rect.x, y = self.btn_special_rect.y, width = self.btn_special_rect.width, height = self.btn_special_rect.height} local btn_accept_rect = {x = btn_cancel_rect.x - self.btn_special_rect.width - self.indent, y = btn_cancel_rect.y, width = self.btn_special_rect.width, height = self.btn_special_rect.height} ----- CODE ------- -------- BUTTONS AND TABS ------------------------------- --------->> VIDEO local btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_video") btn:Init("ui\\ui_button_01", btn_video_rect.x, btn_video_rect.y, btn_video_rect.width, btn_video_rect.height) btn:SetText("Video") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) --------->> SOUND btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_sound") btn:Init("ui\\ui_button_03", btn_sound_rect.x, btn_sound_rect.y, btn_sound_rect.width, btn_sound_rect.height) btn:SetText("Sound") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) --------->> GAME btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_game") btn:Init("ui\\ui_button_02", btn_game_rect.x, btn_game_rect.y, btn_game_rect.width, btn_game_rect.height) btn:SetText("Game") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) --------->> CONTROLS btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_controls") btn:Init("ui\\ui_button_05", btn_control_rect.x, btn_control_rect.y, btn_control_rect.width, btn_control_rect.height) btn:SetText("Controls") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) --------->> PROFILES btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_profiles") btn:Init("ui\\ui_button_01", btn_profiles_rect.x, btn_profiles_rect.y, btn_profiles_rect.width, btn_profiles_rect.height) btn:SetText("Profiles") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) --------->> BACK btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_cancel") btn:Init("ui\\ui_button_02", btn_cancel_rect.x, btn_cancel_rect.y, btn_cancel_rect.width, btn_cancel_rect.height) btn:SetText("Cancel") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) btn = CUIButton() btn:SetAutoDelete(true) btn:SetWindowName("btn_accept") btn:Init("ui\\ui_button_03", btn_accept_rect.x, btn_accept_rect.y, btn_accept_rect.width, btn_accept_rect.height) btn:SetText("Accept") btn:SetFont(self.button_font) btn:SetTextAlign(CGameFont.alCenter) btn:SetTextY(self.button_indent) self:Register(btn) self.main_frame:AttachChild(btn) --------- >> TABS ---- >> VIDEO self.tab_video = ui_options_video_tab.options_video_tab() self.tab_video:InitControls(btn_video_rect.x + btn_video_rect.width + self.indent, self.top_align_y) self.main_frame:AttachChild(self.tab_video) ---- >> SOUND self.tab_sound = ui_options_sound_tab.options_sound_tab() self.tab_sound:InitControls(btn_sound_rect.x + btn_sound_rect.width + self.indent, self.top_align_y) self.main_frame:AttachChild(self.tab_sound) ---- >> GAME self.tab_game = ui_options_game_tab.options_game_tab() self.tab_game:InitControls(btn_sound_rect.x + btn_sound_rect.width + self.indent, self.top_align_y) self.main_frame:AttachChild(self.tab_game) ---- >> CONTROLS self.tab_controls = ui_options_controls_tab.options_controls_tab() self.tab_controls:InitControls(btn_sound_rect.x + btn_sound_rect.width + self.indent, self.top_align_y) self.main_frame:AttachChild(self.tab_controls) ---- >> PROFILES self.tab_profiles = ui_options_profiles_tab.options_profiles_tab() self.tab_profiles:InitControls(btn_sound_rect.x + btn_sound_rect.width + self.indent, self.top_align_y) self.main_frame:AttachChild(self.tab_profiles) end function options_dialog:InitCallBacks() self:AddCallback("btn_accept", ui_events.BUTTON_CLICKED, self, "OnButton_accept") self:AddCallback("btn_cancel", ui_events.BUTTON_CLICKED, self, "OnButton_cancel") self:AddCallback("btn_video", ui_events.BUTTON_CLICKED, self, "OnButton_video") self:AddCallback("btn_sound", ui_events.BUTTON_CLICKED, self, "OnButton_sound") self:AddCallback("btn_game", ui_events.BUTTON_CLICKED, self, "OnButton_game") self:AddCallback("btn_controls", ui_events.BUTTON_CLICKED, self, "OnButton_controls") self:AddCallback("btn_profiles", ui_events.BUTTON_CLICKED, self, "OnButton_profiles") end function options_dialog:HideAllTabs() self.tab_video:Show(false) self.tab_sound:Show(false) self.tab_game:Show(false) self.tab_controls:Show(false) self.tab_profiles:Show(false) end function options_dialog:OnButton_video() self:HideAllTabs() self.tab_video:Show(true) end function options_dialog:OnButton_sound() self:HideAllTabs() self.tab_sound:Show(true) end function options_dialog:OnButton_game() self:HideAllTabs() self.tab_game:Show(true) end function options_dialog:OnButton_controls() self:HideAllTabs() self.tab_controls:Show(true) end function options_dialog:OnButton_profiles() self:HideAllTabs() self.tab_profiles:Show(true) end function options_dialog:OnButton_accept() -- level.start_stop_menu(self,true) self:GetHolder():start_stop_menu(self,true) end function options_dialog:OnButton_cancel() self:GetHolder():start_stop_menu(self,true) --level.start_stop_menu(self,true) end function options_dialog:OnKeyboard(dik, keyboard_action) --virtual function ui_base_dialog.base_dialog.OnKeyboard(self,dik,keyboard_action) return true end
412
0.669848
1
0.669848
game-dev
MEDIA
0.889919
game-dev,desktop-app
0.741565
1
0.741565
BlesseNtumble/GalaxySpace
3,537
src/main/java/galaxyspace/systems/ACentauriSystem/planets/proxima_b/world/gen/we/Proxima_B_Plains.java
package galaxyspace.systems.ACentauriSystem.planets.proxima_b.world.gen.we; import java.util.Random; import asmodeuscore.core.utils.worldengine.WE_Biome; import asmodeuscore.core.utils.worldengine.standardcustomgen.WE_BiomeLayer; import galaxyspace.core.prefab.world.gen.WorldGenPool; import galaxyspace.systems.ACentauriSystem.core.ACBlocks; import galaxyspace.systems.ACentauriSystem.planets.proxima_b.blocks.Proxima_B_Blocks; import micdoodle8.mods.galacticraft.core.GCFluids; import micdoodle8.mods.galacticraft.core.entities.EntityEvolvedEnderman; import micdoodle8.mods.galacticraft.core.entities.EntityEvolvedSkeleton; import micdoodle8.mods.galacticraft.core.entities.EntityEvolvedSpider; import micdoodle8.mods.galacticraft.core.entities.EntityEvolvedZombie; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; public class Proxima_B_Plains extends WE_Biome { public Proxima_B_Plains() { super(new BiomeProperties("proxima_b_plains"), new int[] {0x00FF00, 0xEEDD44, 0x00FF00}); biomeMinValueOnMap = -0.4D; biomeMaxValueOnMap = -0.2D; biomePersistence = 1.4D; biomeNumberOfOctaves = 5; biomeScaleX = 280.0D; biomeScaleY = 1.7D; biomeSurfaceHeight = 80; biomeInterpolateQuality = 15; //-// decorateChunkGen_List.clear(); createChunkGen_InXZ_List.clear(); spawnableMonsterList.add(new Biome.SpawnListEntry(EntityEvolvedSpider.class, 10, 1, 2)); spawnableMonsterList.add(new Biome.SpawnListEntry(EntityEvolvedSkeleton.class, 10, 1, 2)); spawnableMonsterList.add(new Biome.SpawnListEntry(EntityEvolvedZombie.class, 10, 1, 4)); spawnableMonsterList.add(new Biome.SpawnListEntry(EntityEvolvedEnderman.class, 10, 1, 2)); WE_BiomeLayer standardBiomeLayers = new WE_BiomeLayer(); standardBiomeLayers.add(ACBlocks.PROXIMA_B_BLOCKS.getStateFromMeta(1), ACBlocks.PROXIMA_B_BLOCKS.getStateFromMeta(2), -256, 0, -4, -1, true); standardBiomeLayers.add(ACBlocks.PROXIMA_B_BLOCKS.getStateFromMeta(0), ACBlocks.PROXIMA_B_BLOCKS.getStateFromMeta(1), -256, 0, -256, 0, false); standardBiomeLayers.add(Blocks.BEDROCK.getDefaultState(), 0, 2, 0, 0, true); createChunkGen_InXZ_List.add(standardBiomeLayers); } @Override public void decorateBiome(World world, Random rand, int x, int z) { int randPosX = x + rand.nextInt(16) + 8; int randPosZ = z + rand.nextInt(16) + 8; BlockPos pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ)); for(int i = 0; i < 3; i++){ randPosX = x + rand.nextInt(16) + 8; //randPosY = this.rand.nextInt(256); randPosZ = z + rand.nextInt(16) + 8; pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ)); if(world.getBlockState(pos.down()) == ACBlocks.PROXIMA_B_BLOCKS.getDefaultState().withProperty(Proxima_B_Blocks.BASIC_TYPE, Proxima_B_Blocks.EnumBlockProximaB.SURFACE)) world.setBlockState(pos, Blocks.DEADBUSH.getDefaultState()); } int kx = x + rand.nextInt(16) + 8; int kz = x + rand.nextInt(16) + 8; if (rand.nextInt(50) == 0) { int l2 = world.getTopSolidOrLiquidBlock(new BlockPos(kx, 0, kz)).getY() - 20 - rand.nextInt(25); new WorldGenPool(ACBlocks.PROXIMA_B_BLOCKS.getDefaultState().withProperty(Proxima_B_Blocks.BASIC_TYPE, Proxima_B_Blocks.EnumBlockProximaB.STONE), GCFluids.fluidOil.getBlock().getDefaultState(), 5).generate(world, rand, new BlockPos(x, l2, z)); } } }
412
0.785851
1
0.785851
game-dev
MEDIA
0.935491
game-dev
0.607194
1
0.607194
opentibiabr/canary
22,386
src/io/iobestiary.cpp
/** * Canary - A free and open-source MMORPG server emulator * Copyright (©) 2019-2024 OpenTibiaBR <opentibiabr@outlook.com> * Repository: https://github.com/opentibiabr/canary * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.com/ */ #include "io/iobestiary.hpp" #include "creatures/combat/combat.hpp" #include "creatures/combat/condition.hpp" #include "creatures/monsters/monster.hpp" #include "creatures/monsters/monsters.hpp" #include "creatures/players/player.hpp" #include "game/game.hpp" #include "lib/metrics/metrics.hpp" SoftSingleton IOBestiary::instanceTracker("IOBestiary"); void IOBestiary::parseOffensiveCharmCombatDamage(const std::shared_ptr<Charm> &charm, int32_t damage, CombatDamage &charmDamage, CombatParams &charmParams) { charmDamage.primary.type = charm->damageType; charmDamage.primary.value = damage; charmDamage.extension = true; if (!charmDamage.exString.empty()) { charmDamage.exString += ", "; } if (charm->logMessage) { charmDamage.exString += fmt::format("({} charm)", asLowerCaseString(charm->name)); } charmParams.impactEffect = charm->effect; charmParams.combatType = charmDamage.primary.type; charmParams.aggressive = true; charmParams.soundImpactEffect = charm->soundImpactEffect; charmParams.soundCastEffect = charm->soundCastEffect; } void IOBestiary::parseCharmCarnage(const std::shared_ptr<Charm> &charm, const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, int32_t damage) { CombatDamage charmDamage; CombatParams charmParams; parseOffensiveCharmCombatDamage(charm, damage, charmDamage, charmParams); Combat::doCombatHealth(player, target, charmDamage, charmParams); } bool IOBestiary::parseOffensiveCharmCombat(const std::shared_ptr<Charm> &charm, const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, CombatDamage &charmDamage, CombatParams &charmParams) { static double_t maxHealthLimit = 0.08; // 8% max health (max damage) static uint8_t maxLevelsLimit = 2; // 2x level (max damage) static constexpr std::array<std::pair<int8_t, int8_t>, 4> offsets = { { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } } }; int32_t value = 0; const auto &targetPosition = target->getPosition(); const auto &monster = target->getMonster(); switch (charm->id) { case CHARM_WOUND: case CHARM_ENFLAME: case CHARM_POISON: case CHARM_FREEZE: case CHARM_ZAP: case CHARM_CURSE: case CHARM_DIVINE: value = std::min<int32_t>(std::ceil(player->getLevel() * maxLevelsLimit), std::ceil(target->getMaxHealth() * (charm->percent / 100.0))); break; case CHARM_CARNAGE: if (!monster || !monster->isDead()) { return false; } maxLevelsLimit = 6; value = target->getMaxHealth(); for (const auto &[dx, dy] : offsets) { Position damagePosition(targetPosition.x + dx, targetPosition.y + dy, targetPosition.z); const auto &tile = g_game().map.getTile(damagePosition); if (!tile) { continue; } g_game().addMagicEffect(damagePosition, CONST_ME_DRAWBLOOD); const auto &topCreature = tile->getTopCreature(); if (topCreature && topCreature->getType() == CREATURETYPE_MONSTER) { int32_t damage = std::min<int32_t>( std::ceil(value * (charm->percent / 100.0)), player->getLevel() * maxLevelsLimit ); parseCharmCarnage(charm, player, topCreature, -damage); } } return false; case CHARM_OVERPOWER: value = std::min<int32_t>(std::ceil(target->getMaxHealth() * maxHealthLimit), std::ceil(player->getMaxHealth() * (charm->percent / 100.0))); break; case CHARM_OVERFLUX: value = std::min<int32_t>(std::ceil(target->getMaxHealth() * maxHealthLimit), std::ceil(player->getMaxMana() * (charm->percent / 100.0))); break; case CHARM_CRIPPLE: { const auto &cripple = std::static_pointer_cast<ConditionSpeed>(Condition::createCondition(CONDITIONID_COMBAT, CONDITION_PARALYZE, 10000, 0)); cripple->setFormulaVars(-1, 0, -1, 0); target->addCondition(cripple); return false; } default: g_logger().warn("[{}] - No handler found for offensive charm id {}.", __FUNCTION__, charm->id); return false; } // This will be handled if any switch statement be break. parseOffensiveCharmCombatDamage(charm, -value, charmDamage, charmParams); return true; } bool IOBestiary::parseDefensiveCharmCombat(const std::shared_ptr<Charm> &charm, const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, int32_t realDamage, bool checkArmor, CombatDamage &charmDamage, CombatParams &charmParams) { switch (charm->id) { case CHARM_PARRY: { charmDamage.primary.type = COMBAT_NEUTRALDAMAGE; charmDamage.primary.value = -realDamage; charmDamage.extension = true; if (!charmDamage.exString.empty()) { charmDamage.exString += ", "; } if (charm->logMessage) { charmDamage.exString += fmt::format("({} charm)", asLowerCaseString(charm->name)); } charmParams.aggressive = true; charmParams.blockedByArmor = checkArmor; return true; } case CHARM_DODGE: { const Position &targetPos = target->getPosition(); g_game().addMagicEffect(targetPos, charm->effect); break; } case CHARM_ADRENALINE: { const auto &adrenaline = std::static_pointer_cast<ConditionSpeed>(Condition::createCondition(CONDITIONID_COMBAT, CONDITION_HASTE, 10000, 0)); adrenaline->setFormulaVars(2.5, 40, 2.5, 40); player->addCondition(adrenaline); break; } case CHARM_NUMB: { const auto &numb = std::static_pointer_cast<ConditionSpeed>(Condition::createCondition(CONDITIONID_COMBAT, CONDITION_PARALYZE, 10000, 0)); numb->setFormulaVars(-1, 0, -1, 0); target->addCondition(numb); break; } default: g_logger().warn("[{}] - No handler found for defensive charm id {}.", __FUNCTION__, charm->id); break; } return false; } bool IOBestiary::parsePassiveCharmCombat(const std::shared_ptr<Charm> &charm, const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, int32_t value, CombatDamage &charmDamage, CombatParams &charmParams) { const auto &monster = target->getMonster(); switch (charm->id) { case CHARM_BLESS: case CHARM_GUT: case CHARM_LOW: case CHARM_SAVAGE: case CHARM_SCAVENGE: case CHARM_VAMP: case CHARM_VOID: case CHARM_VOIDINVERSION: // All the charms above are being handled separately. break; case CHARM_FATAL: if (monster) { constexpr int32_t preventFleeDuration = 30000; // Fatal Hold prevents fleeing for 30 seconds. monster->setFatalHoldDuration(preventFleeDuration); } break; default: g_logger().warn("[{}] - No handler found for passive charm id {}.", __FUNCTION__, charm->id); break; } return false; } bool IOBestiary::parseCharmCombat(const std::shared_ptr<Charm> &charm, const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, int32_t realDamage, bool checkArmor) { if (!charm || !player || !target) { return false; } CombatDamage charmDamage; CombatParams charmParams; bool callCombat = false; switch (charm->type) { case CHARM_OFFENSIVE: callCombat = parseOffensiveCharmCombat(charm, player, target, charmDamage, charmParams); break; case CHARM_DEFENSIVE: callCombat = parseDefensiveCharmCombat(charm, player, target, realDamage, checkArmor, charmDamage, charmParams); break; case CHARM_PASSIVE: callCombat = parsePassiveCharmCombat(charm, player, target, realDamage, charmDamage, charmParams); break; default: g_logger().warn("[{}] - No handler found for charm type {}.", __FUNCTION__, static_cast<uint8_t>(charm->type)); return false; } if (!charm->cancelMessage.empty()) { player->sendCancelMessage(charm->cancelMessage); } if (callCombat) { Combat::doCombatHealth(player, target, charmDamage, charmParams); } return true; } IOBestiary &IOBestiary::getInstance() { return inject<IOBestiary>(); } std::shared_ptr<Charm> IOBestiary::getBestiaryCharm(charmRune_t activeCharm, bool force /*= false*/) const { const auto charmInternal = g_game().getCharmList(); for (const auto &tmpCharm : charmInternal) { if (tmpCharm->id == activeCharm) { return tmpCharm; } } if (force) { auto charm = std::make_shared<Charm>(); charm->id = activeCharm; charm->binary = 1 << activeCharm; g_game().addCharmRune(charm); return charm; } return nullptr; } std::map<uint16_t, std::string> IOBestiary::findRaceByName(const std::string &race, bool Onlystring /*= true*/, BestiaryType_t raceNumber /*= BESTY_RACE_NONE*/) const { const std::map<uint16_t, std::string> &best_list = g_game().getBestiaryList(); std::map<uint16_t, std::string> race_list; if (Onlystring) { for (const auto &it : best_list) { const auto tmpType = g_monsters().getMonsterType(it.second); if (tmpType && tmpType->info.bestiaryClass == race) { race_list.insert({ it.first, it.second }); } } } else { for (const auto &itn : best_list) { const auto tmpType = g_monsters().getMonsterType(itn.second); if (tmpType && tmpType->info.bestiaryRace == raceNumber) { race_list.insert({ itn.first, itn.second }); } } } return race_list; } uint8_t IOBestiary::getKillStatus(const std::shared_ptr<MonsterType> &mtype, uint32_t killAmount) const { if (killAmount < mtype->info.bestiaryFirstUnlock) { return 1; } else if (killAmount < mtype->info.bestiarySecondUnlock) { return 2; } else if (killAmount < mtype->info.bestiaryToUnlock) { return 3; } return 4; } void IOBestiary::resetCharmRuneCreature(const std::shared_ptr<Player> &player, const std::shared_ptr<Charm> &charm) const { if (!player || !charm) { return; } int32_t value = bitToggle(player->getUsedRunesBit(), charm, false); player->setUsedRunesBit(value); player->parseRacebyCharm(charm->id, true, 0); } void IOBestiary::resetAllCharmRuneCreatures(const std::shared_ptr<Player> &player) const { if (!player) { return; } const auto charmList = g_game().getCharmList(); for (const auto &charm : charmList) { if (!charm) { continue; } player->parseRacebyCharm(charm->id, true, 0); player->setCharmTier(charm->id, 0); } } void IOBestiary::setCharmRuneCreature(const std::shared_ptr<Player> &player, const std::shared_ptr<Charm> &charm, uint16_t raceid) const { if (!player || !charm) { return; } player->parseRacebyCharm(charm->id, true, raceid); int32_t Toggle = bitToggle(player->getUsedRunesBit(), charm, true); player->setUsedRunesBit(Toggle); } std::list<charmRune_t> IOBestiary::getCharmUsedRuneBitAll(const std::shared_ptr<Player> &player) { int32_t input = player->getUsedRunesBit(); int8_t i = 0; std::list<charmRune_t> rtn; while (input != 0) { if ((input & 1) == 1) { auto tmpcharm = static_cast<charmRune_t>(i); rtn.push_front(tmpcharm); } input = input >> 1; i += 1; } return rtn; } uint16_t IOBestiary::getBestiaryRaceUnlocked(const std::shared_ptr<Player> &player, BestiaryType_t race) const { if (!player) { return 0; } uint16_t count = 0; std::map<uint16_t, std::string> besty_l = g_game().getBestiaryList(); for (const auto &it : besty_l) { const auto mtype = g_monsters().getMonsterType(it.second); if (mtype && mtype->info.bestiaryRace == race && player->getBestiaryKillCount(mtype->info.raceid) > 0) { count++; } } return count; } void IOBestiary::addCharmPoints(const std::shared_ptr<Player> &player, uint32_t amount, bool negative /*= false*/) { if (!player) { return; } uint32_t myCharms = player->getCharmPoints(); if (negative) { myCharms -= amount; } else { myCharms += amount; const auto maxCharmPoints = player->getMaxCharmPoints(); player->setMaxCharmPoints(maxCharmPoints + amount); } player->setCharmPoints(myCharms); } void IOBestiary::addMinorCharmEchoes(const std::shared_ptr<Player> &player, uint32_t amount, bool negative /*= false*/) { if (!player) { return; } uint32_t myCharms = player->getMinorCharmEchoes(); if (negative) { myCharms -= amount; } else { myCharms += amount; const auto maxCharmPoints = player->getMaxMinorCharmEchoes(); player->setMaxMinorCharmEchoes(maxCharmPoints + amount); } player->setMinorCharmEchoes(myCharms); } void IOBestiary::addBestiaryKill(const std::shared_ptr<Player> &player, const std::shared_ptr<MonsterType> &mtype, uint32_t amount /*= 1*/) { uint16_t raceid = mtype->info.raceid; if (raceid == 0 || !player || !mtype) { return; } uint32_t curCount = player->getBestiaryKillCount(raceid); std::ostringstream ss; player->addBestiaryKillCount(raceid, amount); if ((curCount == 0) || // Initial kill stage (curCount < mtype->info.bestiaryFirstUnlock && (curCount + amount) >= mtype->info.bestiaryFirstUnlock) || // First kill stage reached (curCount < mtype->info.bestiarySecondUnlock && (curCount + amount) >= mtype->info.bestiarySecondUnlock) || // Second kill stage reached (curCount < mtype->info.bestiaryToUnlock && (curCount + amount) >= mtype->info.bestiaryToUnlock)) { // Final kill stage reached ss << "You unlocked details for the creature '" << mtype->name << "'"; player->sendTextMessage(MESSAGE_STATUS, ss.str()); player->sendBestiaryEntryChanged(raceid); if ((curCount + amount) >= mtype->info.bestiaryToUnlock) { addCharmPoints(player, mtype->info.bestiaryCharmsPoints); } } // Reload bestiary tracker only if the monster is being tracked if (player->isMonsterOnBestiaryTracker(mtype)) { player->refreshCyclopediaMonsterTracker(); } } PlayerCharmsByMonster IOBestiary::getCharmFromTarget(const std::shared_ptr<Player> &player, const std::shared_ptr<MonsterType> &mtype, charmCategory_t category /* = CHARM_ALL */) { PlayerCharmsByMonster playerCharmByMonster; if (!player || !mtype) { return {}; } uint16_t bestiaryEntry = mtype->info.raceid; std::list<charmRune_t> usedRunes = getCharmUsedRuneBitAll(player); for (charmRune_t it : usedRunes) { const auto &charm = getBestiaryCharm(it); if (bestiaryEntry == player->parseRacebyCharm(charm->id) && (category == CHARM_ALL || charm->category == category)) { if (charm->category == CHARM_MAJOR) { playerCharmByMonster.major = charm->id; } else if (charm->category == CHARM_MINOR) { playerCharmByMonster.minor = charm->id; } } } return playerCharmByMonster; } bool IOBestiary::hasCharmUnlockedRuneBit(const std::shared_ptr<Charm> &charm, int32_t input) const { if (!charm) { return false; } return ((input & charm->binary) != 0); } int32_t IOBestiary::bitToggle(int32_t input, const std::shared_ptr<Charm> &charm, bool on) const { if (!charm) { return CHARM_NONE; } int32_t returnToggle; int32_t binary = charm->binary; if (on) { returnToggle = input | binary; return returnToggle; } else { binary = ~binary; returnToggle = input & binary; return returnToggle; } } void IOBestiary::sendBuyCharmRune(const std::shared_ptr<Player> &player, uint8_t action, charmRune_t charmId, uint16_t raceId) { const auto &charm = getBestiaryCharm(charmId); if (!player || (action != 3 && !charm)) { return; } if (action == 0) { if (charm->category == CHARM_MAJOR) { auto charmTier = player->getCharmTier(charm->id); if (charmTier > 2) { player->sendFYIBox("Charm at max level."); return; } if (player->getCharmPoints() < charm->points[charmTier]) { player->sendFYIBox("You don't have enough charm points to unlock this rune."); return; } addCharmPoints(player, charm->points[charmTier], true); addMinorCharmEchoes(player, 25 * charmTier * charmTier + 25 * charmTier + 50); player->setCharmTier(charm->id, charmTier + 1); } else if (charm->category == CHARM_MINOR) { auto charmTier = player->getCharmTier(charm->id); if (charmTier > 2) { player->sendFYIBox("Charm at max level."); return; } if (player->getMinorCharmEchoes() < charm->points[charmTier]) { player->sendFYIBox("You don't have enough minor charm echoes to unlock this rune."); return; } addMinorCharmEchoes(player, charm->points[charmTier], true); player->setCharmTier(charm->id, charmTier + 1); } else { return; } int32_t value = bitToggle(player->getUnlockedRunesBit(), charm, true); player->setUnlockedRunesBit(value); } else if (action == 1) { std::list<charmRune_t> usedRunes = getCharmUsedRuneBitAll(player); uint16_t limitRunes = 2; if (player->isPremium()) { limitRunes = player->hasCharmExpansion() ? 25 : 6; } if (limitRunes <= usedRunes.size()) { player->sendFYIBox("You don't have any charm slots available."); return; } const auto &mType = g_monsters().getMonsterTypeByRaceId(raceId); if (mType && charm->category == CHARM_MAJOR) { const uint32_t killedAmount = player->getBestiaryKillCount(raceId); if (killedAmount < mType->info.bestiaryToUnlock) { return; } } auto [major, minor] = getCharmFromTarget(player, mType); if ((charm->category == CHARM_MAJOR && major != CHARM_NONE) || (charm->category == CHARM_MINOR && minor != CHARM_NONE)) { player->sendFYIBox(fmt::format("You already have this monster set on another {} Charm!", charm->category == CHARM_MAJOR ? "Major" : "Minor")); return; } setCharmRuneCreature(player, charm, raceId); if (!player->isPremium()) { player->sendFYIBox("Creature has been set! You are a Free player, so you benefit from up to 2 runes! Premium players benefit from 6 and Charm Expansion allow you to set creatures to all runes at once!."); } else if (!player->hasCharmExpansion()) { player->sendFYIBox("Creature has been set! You are a Premium player, so you benefit from up to 6 runes! Charm Expansion allow you to set creatures to all runes at once!"); } } else if (action == 2) { int32_t fee = player->getLevel() * 100; if (player->hasCharmExpansion()) { fee = (fee * 75) / 100; } if (!g_game().removeMoney(player, fee, 0, true)) { player->sendFYIBox("You don't have enough gold."); return; } resetCharmRuneCreature(player, charm); g_metrics().addCounter("balance_decrease", fee, { { "player", player->getName() }, { "context", "charm_removal" } }); } else if (action == 3) { const auto playerLevel = player->getLevel(); uint64_t resetAllCharmsCost = 100000 + (playerLevel > 100 ? playerLevel * 11000 : 0); if (player->hasCharmExpansion()) { resetAllCharmsCost = (resetAllCharmsCost * 75) / 100; } if (!g_game().removeMoney(player, resetAllCharmsCost, 0, true)) { player->sendFYIBox("You don't have enough gold."); return; } resetAllCharmRuneCreatures(player); const auto maxCharmPoints = player->getMaxCharmPoints(); player->setCharmPoints(maxCharmPoints); uint16_t echoesResetValue = 0; const auto isPromoted = player->kv()->get("promoted"); if (isPromoted) { echoesResetValue = 100; } player->setMinorCharmEchoes(echoesResetValue); player->setMaxMinorCharmEchoes(echoesResetValue); player->setUsedRunesBit(0); player->setUnlockedRunesBit(0); g_metrics().addCounter("balance_decrease", resetAllCharmsCost, { { "player", player->getName() }, { "context", "charm_removal" } }); } player->sendBestiaryCharms(); } std::map<uint8_t, int16_t> IOBestiary::getMonsterElements(const std::shared_ptr<MonsterType> &mtype) const { std::map<uint8_t, int16_t> defaultMap = {}; for (uint8_t i = 0; i <= 7; i++) { defaultMap[i] = 100; } for (const auto &elementEntry : mtype->info.elementMap) { switch (elementEntry.first) { case COMBAT_PHYSICALDAMAGE: defaultMap[0] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_FIREDAMAGE: defaultMap[1] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_EARTHDAMAGE: defaultMap[2] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_ENERGYDAMAGE: defaultMap[3] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_ICEDAMAGE: defaultMap[4] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_HOLYDAMAGE: defaultMap[5] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_DEATHDAMAGE: defaultMap[6] -= static_cast<int16_t>(elementEntry.second); break; case COMBAT_HEALING: defaultMap[7] -= static_cast<int16_t>(elementEntry.second); break; default: break; } } return defaultMap; } std::map<uint16_t, uint32_t> IOBestiary::getBestiaryKillCountByMonsterIDs(const std::shared_ptr<Player> &player, const std::map<uint16_t, std::string> &mtype_list) const { std::map<uint16_t, uint32_t> raceMonsters = {}; for (const auto &it : mtype_list) { uint16_t raceid = it.first; uint32_t thisKilled = player->getBestiaryKillCount(raceid); if (thisKilled > 0) { raceMonsters[raceid] = thisKilled; } } return raceMonsters; } std::vector<uint16_t> IOBestiary::getBestiaryFinished(const std::shared_ptr<Player> &player) const { const auto &bestiaryMap = g_game().getBestiaryList(); stdext::vector_set<uint16_t> finishedMonsters; finishedMonsters.reserve(bestiaryMap.size()); for (const auto &[monsterTypeRaceId, monsterTypeName] : bestiaryMap) { const auto &mtype = g_monsters().getMonsterType(monsterTypeName); const uint32_t thisKilled = player->getBestiaryKillCount(monsterTypeRaceId); if (mtype && thisKilled >= mtype->info.bestiaryToUnlock) { finishedMonsters.insert(monsterTypeRaceId); } } return finishedMonsters.data(); } std::vector<uint16_t> IOBestiary::getBestiaryStageTwo(const std::shared_ptr<Player> &player) const { const auto &bestiaryMap = g_game().getBestiaryList(); stdext::vector_set<uint16_t> stageTwoMonsters; stageTwoMonsters.reserve(bestiaryMap.size()); for (const auto &[monsterTypeRaceId, monsterTypeName] : bestiaryMap) { const auto &mtype = g_monsters().getMonsterType(monsterTypeName); const uint32_t thisKilled = player->getBestiaryKillCount(monsterTypeRaceId); if (mtype && thisKilled >= mtype->info.bestiarySecondUnlock) { stageTwoMonsters.insert(monsterTypeRaceId); } } return stageTwoMonsters.data(); } int8_t IOBestiary::calculateDifficult(uint32_t chance) const { float chanceInPercent = chance / 1000; if (chanceInPercent < 0.2) { return 4; } else if (chanceInPercent < 1) { return 3; } else if (chanceInPercent < 5) { return 2; } else if (chanceInPercent < 25) { return 1; } return 0; }
412
0.980858
1
0.980858
game-dev
MEDIA
0.753681
game-dev
0.967501
1
0.967501
desertkun/brainout
7,488
server/src/com/desertkun/brainout/server/mapsource/CustomMapSource.java
package com.desertkun.brainout.server.mapsource; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.*; import com.desertkun.brainout.BrainOutServer; import com.desertkun.brainout.Constants; import com.desertkun.brainout.content.SpawnTarget; import com.desertkun.brainout.content.Team; import com.desertkun.brainout.content.active.SpawnPoint; import com.desertkun.brainout.data.Map; import com.desertkun.brainout.data.ServerMap; import com.desertkun.brainout.data.active.ActiveData; import com.desertkun.brainout.data.active.SpawnPointData; import com.desertkun.brainout.data.components.SubPointComponentData; import com.desertkun.brainout.mode.GameMode; import com.desertkun.brainout.playstate.PlayState; import com.desertkun.brainout.reflection.Reflect; import com.desertkun.brainout.reflection.ReflectAlias; import com.desertkun.brainout.server.ServerSettings; import com.desertkun.brainout.utils.SteamAPIUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @Reflect("source.CustomMapSource") public class CustomMapSource extends MapSource implements MapSource.Settings { private ObjectMap<String, ServerSettings.GameModeConditions> modes; private static Array<GameMode.ID> DEFAULT_MODES = new Array<>(new GameMode.ID[]{ GameMode.ID.normal, GameMode.ID.domination }); private final String mapId; private PlayState.ID playState; private GameMode.ID preferableMode; private final byte[] map; private final SteamAPIUtil.WorkshopItemResult workshopItemResult; private static byte[] convert(InputStream is) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } public CustomMapSource(InputStream map, String mapId, SteamAPIUtil.WorkshopItemResult workshopItemResult) throws IOException { this.modes = new ObjectMap<>(); this.map = convert(map); this.mapId = mapId; this.playState = PlayState.ID.game; this.workshopItemResult = workshopItemResult; read(new Json(), new JsonReader().parse(Gdx.files.local("maps-set-custom.json"))); } public void setPreferableMode(String preferableMode) { try { this.preferableMode = GameMode.ID.valueOf(preferableMode); } catch (Exception ignored) { this.preferableMode = null; } } @Override public void read(Json json, JsonValue jsonData) { if (jsonData.has("modes")) { this.modes = json.readValue(ObjectMap.class, ServerSettings.GameModeConditions.class, jsonData.get("modes")); } } @Override public boolean insert(String map, String mode) { this.playState = PlayState.ID.game; return true; } @Override public void wrapPlayState(PlayState.ID playState) { this.playState = playState; } private void renderSpawns(ServerMap map) { renderSpawnsForTeam(map, "team-green", "SPAWN_BASE"); renderSpawnsForTeam(map, "team-blue", "SPAWN_BASE"); renderSpawnsForTeam(map, "team-dm", "SPAWN_RANDOM"); } private void renderSpawnsForTeam(ServerMap map, String teamName, String spawnName) { SpawnPoint spawn = BrainOutServer.ContentMgr.get("spawn", SpawnPoint.class); Team team = BrainOutServer.ContentMgr.get(teamName, Team.class); SpawnPointData data = (SpawnPointData)map.getActiveForTag(Constants.ActiveTags.SPAWNABLE, activeData -> { if (!(activeData instanceof SpawnPointData)) return false; if (activeData.getContent() != spawn) return false; return activeData.getTeam() == team; }); if (data == null) { data = spawn.getData(map.getDimension()); map.addActive(map.generateServerId(), data, true); } Vector2 middleGround = new Vector2(); int amount = map.countActivesForTag(Constants.ActiveTags.SPAWNABLE, new Map.Predicate() { @Override public boolean match(ActiveData activeData) { if (activeData instanceof SpawnPointData) return false; SubPointComponentData spc = activeData.getComponent(SubPointComponentData.class); if (spc == null) return false; if (spc.getTarget() == SpawnTarget.flag) return false; if (activeData.getTeam() == team) { middleGround.add(activeData.getX(), activeData.getY()); return true; } return false; } }); if (amount > 0) { middleGround.scl(1.0f / (float) amount); } data.spawnRange = 256; data.setTeam(team); data.setName(spawnName); data.setPosition(middleGround.x, middleGround.y); } @Override public Settings next() { return this; } @Override public ServerSettings.MapConditions acquireMap() { return new ServerSettings.MapConditions(mapId); } @Override public ServerSettings.GameModeConditions acquireMode() { Array<GameMode.ID> suitableModes = new Array<>(); for (String tagName : workshopItemResult.getTags()) { GameMode.ID gameModeId; try { gameModeId = GameMode.ID.valueOf(tagName); } catch (Exception ignored) { continue; } suitableModes.add(gameModeId); } if (preferableMode != null && suitableModes.indexOf(preferableMode, true) >= 0) { ServerSettings.GameModeConditions m = modes.get(preferableMode.toString()); if (m != null) { return m; } } if (suitableModes.size == 0) { return modes.get(DEFAULT_MODES.random().toString()); } return modes.get(suitableModes.random().toString()); } @Override public ServerSettings.BaseConditions getAdditionalSettings() { return null; } @Override public Array<ServerMap> loadMaps(ServerSettings.MapConditions settings, boolean init) { Array<ServerMap> maps = BrainOutServer.Controller.loadMaps(new ByteArrayInputStream(this.map), true); if (maps != null) { for (ServerMap map : maps) { map.setName("custom"); map.setCustom("workshop-id", mapId); renderSpawns(map); } if (init) { for (ServerMap map : maps) { map.init(); } } } return maps; } @Override public PlayState init(PlayState.InitCallback callback) { return BrainOutServer.Controller.setPlayState(callback, playState); } }
412
0.948461
1
0.948461
game-dev
MEDIA
0.945877
game-dev
0.939031
1
0.939031