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
Petrolpark-Mods/Destroy
3,079
src/main/java/com/petrolpark/destroy/core/recipe/ingredient/fluid/MixtureFluidIngredient.java
package com.petrolpark.destroy.core.recipe.ingredient.fluid; import java.util.HashMap; import java.util.List; import java.util.Map; import com.petrolpark.destroy.DestroyFluids; import com.petrolpark.destroy.chemistry.legacy.LegacyMixture; import com.petrolpark.destroy.chemistry.legacy.ReadOnlyMixture; import com.petrolpark.destroy.chemistry.minecraft.MixtureFluid; import com.simibubi.create.foundation.fluid.FluidIngredient; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.fluids.FluidStack; public abstract class MixtureFluidIngredient<T extends MixtureFluidIngredient<T>> extends FluidIngredient { public static final Map<String, MixtureFluidIngredientSubType<?>> MIXTURE_FLUID_INGREDIENT_SUBTYPES = new HashMap<>(); static { registerMixtureFluidIngredientSubType(MoleculeFluidIngredient.TYPE); registerMixtureFluidIngredientSubType(SaltFluidIngredient.TYPE); registerMixtureFluidIngredientSubType(MoleculeTagFluidIngredient.TYPE); registerMixtureFluidIngredientSubType(RefrigerantDummyFluidIngredient.TYPE); registerMixtureFluidIngredientSubType(IonFluidIngredient.TYPE); registerMixtureFluidIngredientSubType(PureSpeciesFluidIngredient.TYPE); }; public static void registerMixtureFluidIngredientSubType(MixtureFluidIngredientSubType<?> ingredientType) { MIXTURE_FLUID_INGREDIENT_SUBTYPES.put(ingredientType.getMixtureFluidIngredientSubtype(), ingredientType); }; @Override protected boolean testInternal(FluidStack fluidStack) { if (!(fluidStack.getFluid().getFluidType() == DestroyFluids.MIXTURE.getType())) return false; // If it's not a Mixture CompoundTag mixtureTag = fluidStack.getChildTag("Mixture"); if (mixtureTag.isEmpty()) return false; // If this Mixture Fluid has no associated Mixture return testMixture(LegacyMixture.readNBT(mixtureTag)); }; @Override protected final List<FluidStack> determineMatchingFluidStacks() { return getExampleMixtures().stream().map(mixture -> { FluidStack stack = MixtureFluid.of(amountRequired, mixture); stack.getOrCreateTag().putString("MixtureFluidIngredientSubtype", getType().getMixtureFluidIngredientSubtype()); addNBT(stack.getOrCreateTag()); return stack; }).toList(); }; public abstract MixtureFluidIngredientSubType<T> getType(); protected abstract boolean testMixture(LegacyMixture mixture); /** * Add data to the NBT of the Fluid Ingredient when it is displayed in JEI. The only use of this is to control the * {@link MixtureFluidIngredientSubType#getDescription description}. Careful not to overwite the tags {@code Mixture} or * {@code MixtureFluidIngredientSubtype}. * @param fluidTag */ public abstract void addNBT(CompoundTag fluidTag); /** * Get the Mixtures this ingredient should cycle through when shown in JEI. * @return */ public List<ReadOnlyMixture> getExampleMixtures() { return List.of(); }; };
1
0.849524
1
0.849524
game-dev
MEDIA
0.923259
game-dev
0.825425
1
0.825425
mangostwo/server
102,916
src/game/BattleGround/BattleGroundMgr.cpp
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "Common.h" #include "SharedDefines.h" #include "Player.h" #include "BattleGroundMgr.h" #include "BattleGroundAV.h" #include "BattleGroundAB.h" #include "BattleGroundEY.h" #include "BattleGroundWS.h" #include "BattleGroundNA.h" #include "BattleGroundBE.h" #include "BattleGroundAA.h" #include "BattleGroundRL.h" #include "BattleGroundSA.h" #include "BattleGroundDS.h" #include "BattleGroundRV.h" #include "BattleGroundIC.h" #include "BattleGroundRB.h" #include "MapManager.h" #include "Map.h" #include "ObjectMgr.h" #include "ProgressBar.h" #include "Chat.h" #include "ArenaTeam.h" #include "World.h" #include "WorldPacket.h" #include "GameEventMgr.h" #include "Formulas.h" #include "DisableMgr.h" #include "GameTime.h" #ifdef ENABLE_ELUNA #include "LuaEngine.h" #endif /* ENABLE_ELUNA */ #include "Policies/Singleton.h" INSTANTIATE_SINGLETON_1(BattleGroundMgr); /*********************************************************/ /*** BATTLEGROUND QUEUE SYSTEM ***/ /*********************************************************/ BattleGroundQueue::BattleGroundQueue() { for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i) { for (uint8 j = 0; j < MAX_BATTLEGROUND_BRACKETS; ++j) { m_SumOfWaitTimes[i][j] = 0; m_WaitTimeLastPlayer[i][j] = 0; for (uint8 k = 0; k < COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME; ++k) { m_WaitTimes[i][j][k] = 0; } } } } BattleGroundQueue::~BattleGroundQueue() { m_QueuedPlayers.clear(); for (uint8 i = 0; i < MAX_BATTLEGROUND_BRACKETS; ++i) { for (uint8 j = 0; j < BG_QUEUE_GROUP_TYPES_COUNT; ++j) { for (GroupsQueueType::iterator itr = m_QueuedGroups[i][j].begin(); itr != m_QueuedGroups[i][j].end(); ++itr) { delete(*itr); } m_QueuedGroups[i][j].clear(); } } } /*********************************************************/ /*** BATTLEGROUND QUEUE SELECTION POOLS ***/ /*********************************************************/ // selection pool initialization, used to clean up from prev selection void BattleGroundQueue::SelectionPool::Init() { SelectedGroups.clear(); PlayerCount = 0; } // remove group info from selection pool // returns true when we need to try to add new group to selection pool // returns false when selection pool is ok or when we kicked smaller group than we need to kick // sometimes it can be called on empty selection pool bool BattleGroundQueue::SelectionPool::KickGroup(uint32 size) { // find maxgroup or LAST group with size == size and kick it bool found = false; GroupsQueueType::iterator groupToKick = SelectedGroups.begin(); for (GroupsQueueType::iterator itr = groupToKick; itr != SelectedGroups.end(); ++itr) { if (abs((int32)((*itr)->Players.size() - size)) <= 1) { groupToKick = itr; found = true; } else if (!found && (*itr)->Players.size() >= (*groupToKick)->Players.size()) { groupToKick = itr; } } // if pool is empty, do nothing if (GetPlayerCount()) { // update player count GroupQueueInfo* ginfo = (*groupToKick); SelectedGroups.erase(groupToKick); PlayerCount -= ginfo->Players.size(); // return false if we kicked smaller group or there are enough players in selection pool if (ginfo->Players.size() <= size + 1) { return false; } } return true; } // add group to selection pool // used when building selection pools // returns true if we can invite more players, or when we added group to selection pool // returns false when selection pool is full bool BattleGroundQueue::SelectionPool::AddGroup(GroupQueueInfo* ginfo, uint32 desiredCount) { // if group is larger than desired count - don't allow to add it to pool if (!ginfo->IsInvitedToBGInstanceGUID && desiredCount >= PlayerCount + ginfo->Players.size()) { SelectedGroups.push_back(ginfo); // increase selected players count PlayerCount += ginfo->Players.size(); return true; } if (PlayerCount < desiredCount) { return true; } return false; } /*********************************************************/ /*** BATTLEGROUND QUEUES ***/ /*********************************************************/ // add group or player (grp == NULL) to bg queue with the given leader and bg specifications GroupQueueInfo* BattleGroundQueue::AddGroup(Player* leader, Group* grp, BattleGroundTypeId BgTypeId, PvPDifficultyEntry const* bracketEntry, ArenaType arenaType, bool isRated, bool isPremade, uint32 arenaRating, uint32 arenateamid) { BattleGroundBracketId bracketId = bracketEntry->GetBracketId(); // create new ginfo GroupQueueInfo* ginfo = new GroupQueueInfo; ginfo->BgTypeId = BgTypeId; ginfo->arenaType = arenaType; ginfo->ArenaTeamId = arenateamid; ginfo->IsRated = isRated; ginfo->IsInvitedToBGInstanceGUID = 0; ginfo->JoinTime = GameTime::GetGameTimeMS(); ginfo->RemoveInviteTime = 0; ginfo->GroupTeam = leader->GetTeam(); ginfo->ArenaTeamRating = arenaRating; ginfo->OpponentsTeamRating = 0; ginfo->Players.clear(); // compute index (if group is premade or joined a rated match) to queues uint32 index = 0; if (!isRated && !isPremade) { index += PVP_TEAM_COUNT; // BG_QUEUE_PREMADE_* -> BG_QUEUE_NORMAL_* } if (ginfo->GroupTeam == HORDE) { ++index; // BG_QUEUE_*_ALLIANCE -> BG_QUEUE_*_HORDE } DEBUG_LOG("Adding Group to BattleGroundQueue bgTypeId : %u, bracket_id : %u, index : %u", BgTypeId, bracketId, index); uint32 lastOnlineTime = GameTime::GetGameTimeMS(); // announce world (this don't need mutex) if (isRated && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_JOIN)) { sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN, ginfo->arenaType, ginfo->arenaType, ginfo->ArenaTeamRating); } // add players from group to ginfo { // ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_Lock); if (grp) { for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* member = itr->getSource(); if (!member) { continue; // this should never happen } PlayerQueueInfo& pl_info = m_QueuedPlayers[member->GetObjectGuid()]; pl_info.LastOnlineTime = lastOnlineTime; pl_info.GroupInfo = ginfo; // add the pinfo to ginfo's list ginfo->Players[member->GetObjectGuid()] = &pl_info; } } else { PlayerQueueInfo& pl_info = m_QueuedPlayers[leader->GetObjectGuid()]; pl_info.LastOnlineTime = lastOnlineTime; pl_info.GroupInfo = ginfo; ginfo->Players[leader->GetObjectGuid()] = &pl_info; } // add GroupInfo to m_QueuedGroups m_QueuedGroups[bracketId][index].push_back(ginfo); // announce to world, this code needs mutex if (arenaType == ARENA_TYPE_NONE && !isRated && !isPremade && sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN)) { if (BattleGround* bg = sBattleGroundMgr.GetBattleGroundTemplate(ginfo->BgTypeId)) { char const* bgName = bg->GetName(); uint32 MinPlayers = bg->GetMinPlayersPerTeam(); uint32 qHorde = 0; uint32 qAlliance = 0; uint32 q_min_level = bracketEntry->minLevel; uint32 q_max_level = bracketEntry->maxLevel; GroupsQueueType::const_iterator itr; for (itr = m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_ALLIANCE].begin(); itr != m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_ALLIANCE].end(); ++itr) if (!(*itr)->IsInvitedToBGInstanceGUID) { qAlliance += (*itr)->Players.size(); } for (itr = m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_HORDE].begin(); itr != m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_HORDE].end(); ++itr) if (!(*itr)->IsInvitedToBGInstanceGUID) { qHorde += (*itr)->Players.size(); } // Show queue status to player only (when joining queue) if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN) == 1) { ChatHandler(leader).PSendSysMessage(LANG_BG_QUEUE_ANNOUNCE_SELF, bgName, q_min_level, q_max_level, qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0); } // System message else { sWorld.SendWorldText(LANG_BG_QUEUE_ANNOUNCE_WORLD, bgName, q_min_level, q_max_level, qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0); } } } // release mutex } return ginfo; } void BattleGroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo, BattleGroundBracketId bracket_id) { uint32 timeInQueue = getMSTimeDiff(ginfo->JoinTime, GameTime::GetGameTimeMS()); uint8 team_index = TEAM_INDEX_ALLIANCE; // default set to BG_TEAM_ALLIANCE - or non rated arenas! if (ginfo->arenaType == ARENA_TYPE_NONE) { if (ginfo->GroupTeam == HORDE) { team_index = TEAM_INDEX_HORDE; } } else { if (ginfo->IsRated) { team_index = TEAM_INDEX_HORDE; // for rated arenas use TEAM_INDEX_HORDE } } // store pointer to arrayindex of player that was added first uint32* lastPlayerAddedPointer = &(m_WaitTimeLastPlayer[team_index][bracket_id]); // remove his time from sum m_SumOfWaitTimes[team_index][bracket_id] -= m_WaitTimes[team_index][bracket_id][(*lastPlayerAddedPointer)]; // set average time to new m_WaitTimes[team_index][bracket_id][(*lastPlayerAddedPointer)] = timeInQueue; // add new time to sum m_SumOfWaitTimes[team_index][bracket_id] += timeInQueue; // set index of last player added to next one (*lastPlayerAddedPointer)++; (*lastPlayerAddedPointer) %= COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME; } uint32 BattleGroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattleGroundBracketId bracket_id) { uint8 team_index = TEAM_INDEX_ALLIANCE; // default set to TEAM_INDEX_ALLIANCE - or non rated arenas! if (ginfo->arenaType == ARENA_TYPE_NONE) { if (ginfo->GroupTeam == HORDE) { team_index = TEAM_INDEX_HORDE; } } else { if (ginfo->IsRated) { team_index = TEAM_INDEX_HORDE; // for rated arenas use TEAM_INDEX_HORDE } } // check if there is enought values(we always add values > 0) if (m_WaitTimes[team_index][bracket_id][COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME - 1]) { return (m_SumOfWaitTimes[team_index][bracket_id] / COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME); } else // if there aren't enough values return 0 - not available { return 0; } } // remove player from queue and from group info, if group info is empty then remove it too void BattleGroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount) { // Player *plr = sObjectMgr.GetPlayer(guid); // ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_Lock); int32 bracket_id = -1; // signed for proper for-loop finish QueuedPlayersMap::iterator itr; // remove player from map, if he's there itr = m_QueuedPlayers.find(guid); if (itr == m_QueuedPlayers.end()) { sLog.outError("BattleGroundQueue: couldn't find for remove: %s", guid.GetString().c_str()); return; } GroupQueueInfo* group = itr->second.GroupInfo; GroupsQueueType::iterator group_itr, group_itr_tmp; // mostly people with the highest levels are in battlegrounds, thats why // we count from MAX_BATTLEGROUND_QUEUES - 1 to 0 // variable index removes useless searching in other team's queue uint32 index = BattleGround::GetTeamIndexByTeamId(group->GroupTeam); for (int8 bracket_id_tmp = MAX_BATTLEGROUND_BRACKETS - 1; bracket_id_tmp >= 0 && bracket_id == -1; --bracket_id_tmp) { // we must check premade and normal team's queue - because when players from premade are joining bg, // they leave groupinfo so we can't use its players size to find out index for (uint8 j = index; j < BG_QUEUE_GROUP_TYPES_COUNT; j += BG_QUEUE_NORMAL_ALLIANCE) { for (group_itr_tmp = m_QueuedGroups[bracket_id_tmp][j].begin(); group_itr_tmp != m_QueuedGroups[bracket_id_tmp][j].end(); ++group_itr_tmp) { if ((*group_itr_tmp) == group) { bracket_id = bracket_id_tmp; group_itr = group_itr_tmp; // we must store index to be able to erase iterator index = j; break; } } } } // player can't be in queue without group, but just in case if (bracket_id == -1) { sLog.outError("BattleGroundQueue: ERROR Can not find groupinfo for %s", guid.GetString().c_str()); return; } DEBUG_LOG("BattleGroundQueue: Removing %s, from bracket_id %u", guid.GetString().c_str(), (uint32)bracket_id); // ALL variables are correctly set // We can ignore leveling up in queue - it should not cause crash // remove player from group // if only one player there, remove group // remove player queue info from group queue info GroupQueueInfoPlayers::iterator pitr = group->Players.find(guid); if (pitr != group->Players.end()) { group->Players.erase(pitr); } // if invited to bg, and should decrease invited count, then do it if (decreaseInvitedCount && group->IsInvitedToBGInstanceGUID) { BattleGround* bg = sBattleGroundMgr.GetBattleGround(group->IsInvitedToBGInstanceGUID, group->BgTypeId); if (bg) { bg->DecreaseInvitedCount(group->GroupTeam); } } // remove player queue info m_QueuedPlayers.erase(itr); // announce to world if arena team left queue for rated match, show only once if (group->arenaType != ARENA_TYPE_NONE && group->IsRated && group->Players.empty() && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_EXIT)) { sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, group->arenaType, group->arenaType, group->ArenaTeamRating); } // if player leaves queue and he is invited to rated arena match, then he have to loose if (group->IsInvitedToBGInstanceGUID && group->IsRated && decreaseInvitedCount) { ArenaTeam* at = sObjectMgr.GetArenaTeamById(group->ArenaTeamId); if (at) { DEBUG_LOG("UPDATING memberLost's personal arena rating for %s by opponents rating: %u", guid.GetString().c_str(), group->OpponentsTeamRating); Player* plr = sObjectMgr.GetPlayer(guid); if (plr) { at->MemberLost(plr, group->OpponentsTeamRating); } else { at->OfflineMemberLost(guid, group->OpponentsTeamRating); } at->SaveToDB(); } } // remove group queue info if needed if (group->Players.empty()) { m_QueuedGroups[bracket_id][index].erase(group_itr); delete group; } // if group wasn't empty, so it wasn't deleted, and player have left a rated // queue -> everyone from the group should leave too // don't remove recursively if already invited to bg! else if (!group->IsInvitedToBGInstanceGUID && group->IsRated) { // remove next player, this is recursive // first send removal information if (Player* plr2 = sObjectMgr.GetPlayer(group->Players.begin()->first)) { BattleGround* bg = sBattleGroundMgr.GetBattleGroundTemplate(group->BgTypeId); BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(group->BgTypeId, group->arenaType); uint32 queueSlot = plr2->GetBattleGroundQueueIndex(bgQueueTypeId); plr2->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to // queue->removeplayer, it causes bugs WorldPacket data; sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE, TEAM_NONE); plr2->GetSession()->SendPacket(&data); } // then actually delete, this may delete the group as well! RemovePlayer(group->Players.begin()->first, decreaseInvitedCount); } } // returns true when player pl_guid is in queue and is invited to bgInstanceGuid bool BattleGroundQueue::IsPlayerInvited(ObjectGuid pl_guid, const uint32 bgInstanceGuid, const uint32 removeTime) { // ACE_Guard<ACE_Recursive_Thread_Mutex> g(m_Lock); QueuedPlayersMap::const_iterator qItr = m_QueuedPlayers.find(pl_guid); return (qItr != m_QueuedPlayers.end() && qItr->second.GroupInfo->IsInvitedToBGInstanceGUID == bgInstanceGuid && qItr->second.GroupInfo->RemoveInviteTime == removeTime); } bool BattleGroundQueue::GetPlayerGroupInfoData(ObjectGuid guid, GroupQueueInfo* ginfo) { // ACE_Guard<ACE_Recursive_Thread_Mutex> g(m_Lock); QueuedPlayersMap::const_iterator qItr = m_QueuedPlayers.find(guid); if (qItr == m_QueuedPlayers.end()) { return false; } *ginfo = *(qItr->second.GroupInfo); return true; } bool BattleGroundQueue::InviteGroupToBG(GroupQueueInfo* ginfo, BattleGround* bg, Team side) { // set side if needed if (side) { ginfo->GroupTeam = side; } if (!ginfo->IsInvitedToBGInstanceGUID) { // not yet invited // set invitation ginfo->IsInvitedToBGInstanceGUID = bg->GetInstanceID(); BattleGroundTypeId bgTypeId = bg->GetTypeID(); BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, bg->GetArenaType()); BattleGroundBracketId bracket_id = bg->GetBracketId(); // set ArenaTeamId for rated matches if (bg->isArena() && bg->isRated()) { bg->SetArenaTeamIdForTeam(ginfo->GroupTeam, ginfo->ArenaTeamId); } ginfo->RemoveInviteTime = GameTime::GetGameTimeMS() + INVITE_ACCEPT_WAIT_TIME; // loop through the players for (GroupQueueInfoPlayers::iterator itr = ginfo->Players.begin(); itr != ginfo->Players.end(); ++itr) { // get the player Player* plr = sObjectMgr.GetPlayer(itr->first); // if offline, skip him, this should not happen - player is removed from queue when he logs out if (!plr) { continue; } // invite the player PlayerInvitedToBGUpdateAverageWaitTime(ginfo, bracket_id); // sBattleGroundMgr.InvitePlayer(plr, bg, ginfo->Team); // set invited player counters bg->IncreaseInvitedCount(ginfo->GroupTeam); plr->SetInviteForBattleGroundQueueType(bgQueueTypeId, ginfo->IsInvitedToBGInstanceGUID); // create remind invite events BGQueueInviteEvent* inviteEvent = new BGQueueInviteEvent(plr->GetObjectGuid(), ginfo->IsInvitedToBGInstanceGUID, bgTypeId, ginfo->arenaType, ginfo->RemoveInviteTime); plr->m_Events.AddEvent(inviteEvent, plr->m_Events.CalculateTime(INVITATION_REMIND_TIME)); // create automatic remove events BGQueueRemoveEvent* removeEvent = new BGQueueRemoveEvent(plr->GetObjectGuid(), ginfo->IsInvitedToBGInstanceGUID, bgTypeId, bgQueueTypeId, ginfo->RemoveInviteTime); plr->m_Events.AddEvent(removeEvent, plr->m_Events.CalculateTime(INVITE_ACCEPT_WAIT_TIME)); WorldPacket data; uint32 queueSlot = plr->GetBattleGroundQueueIndex(bgQueueTypeId); DEBUG_LOG("Battleground: invited %s to BG instance %u queueindex %u bgtype %u, I can't help it if they don't press the enter battle button.", plr->GetGuidStr().c_str(), bg->GetInstanceID(), queueSlot, bg->GetTypeID()); // send status packet sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, 0, ginfo->arenaType, TEAM_NONE); plr->GetSession()->SendPacket(&data); } return true; } return false; } /* This function is inviting players to already running battlegrounds Invitation type is based on config file large groups are disadvantageous, because they will be kicked first if invitation type = 1 */ void BattleGroundQueue::FillPlayersToBG(BattleGround* bg, BattleGroundBracketId bracket_id) { int32 hordeFree = bg->GetFreeSlotsForTeam(HORDE); int32 aliFree = bg->GetFreeSlotsForTeam(ALLIANCE); // iterator for iterating through bg queue GroupsQueueType::const_iterator Ali_itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].begin(); // count of groups in queue - used to stop cycles uint32 aliCount = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].size(); // index to queue which group is current uint32 aliIndex = 0; for (; aliIndex < aliCount && m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*Ali_itr), aliFree); ++aliIndex) { ++Ali_itr; } // the same thing for horde GroupsQueueType::const_iterator Horde_itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].begin(); uint32 hordeCount = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].size(); uint32 hordeIndex = 0; for (; hordeIndex < hordeCount && m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*Horde_itr), hordeFree); ++hordeIndex) { ++Horde_itr; } // if ofc like BG queue invitation is set in config, then we are happy if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE) == 0) { return; } /* if we reached this code, then we have to solve NP - complete problem called Subset sum problem So one solution is to check all possible invitation subgroups, or we can use these conditions: 1. Last time when BattleGroundQueue::Update was executed we invited all possible players - so there is only small possibility that we will invite now whole queue, because only 1 change has been made to queues from the last BattleGroundQueue::Update call 2. Other thing we should consider is group order in queue */ // At first we need to compare free space in bg and our selection pool int32 diffAli = aliFree - int32(m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount()); int32 diffHorde = hordeFree - int32(m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()); while (abs(diffAli - diffHorde) > 1 && (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() > 0 || m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() > 0)) { // each cycle execution we need to kick at least 1 group if (diffAli < diffHorde) { // kick alliance group, add to pool new group if needed if (m_SelectionPools[TEAM_INDEX_ALLIANCE].KickGroup(diffHorde - diffAli)) { for (; aliIndex < aliCount && m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*Ali_itr), (aliFree >= diffHorde) ? aliFree - diffHorde : 0); ++aliIndex) { ++Ali_itr; } } // if ali selection is already empty, then kick horde group, but if there are less horde than ali in bg - break; if (!m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount()) { if (aliFree <= diffHorde + 1) { break; } m_SelectionPools[TEAM_INDEX_HORDE].KickGroup(diffHorde - diffAli); } } else { // kick horde group, add to pool new group if needed if (m_SelectionPools[TEAM_INDEX_HORDE].KickGroup(diffAli - diffHorde)) { for (; hordeIndex < hordeCount && m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*Horde_itr), (hordeFree >= diffAli) ? hordeFree - diffAli : 0); ++hordeIndex) { ++Horde_itr; } } if (!m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()) { if (hordeFree <= diffAli + 1) { break; } m_SelectionPools[TEAM_INDEX_ALLIANCE].KickGroup(diffAli - diffHorde); } } // count diffs after small update diffAli = aliFree - int32(m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount()); diffHorde = hordeFree - int32(m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()); } } // this method checks if premade versus premade battleground is possible // then after 30 mins (default) in queue it moves premade group to normal queue // it tries to invite as much players as it can - to MaxPlayersPerTeam, because premade groups have more than MinPlayersPerTeam players bool BattleGroundQueue::CheckPremadeMatch(BattleGroundBracketId bracket_id, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam) { // check match if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty() && !m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty()) { // start premade match // if groups aren't invited GroupsQueueType::const_iterator ali_group, horde_group; for (ali_group = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].begin(); ali_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end(); ++ali_group) if (!(*ali_group)->IsInvitedToBGInstanceGUID) { break; } for (horde_group = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].begin(); horde_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end(); ++horde_group) if (!(*horde_group)->IsInvitedToBGInstanceGUID) { break; } if (ali_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end() && horde_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end()) { m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*ali_group), MaxPlayersPerTeam); m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*horde_group), MaxPlayersPerTeam); // add groups/players from normal queue to size of bigger group uint32 maxPlayers = std::max(m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount(), m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()); GroupsQueueType::const_iterator itr; for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i) { for (itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].begin(); itr != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].end(); ++itr) { // if itr can join BG and player count is less that maxPlayers, then add group to selectionpool if (!(*itr)->IsInvitedToBGInstanceGUID && !m_SelectionPools[i].AddGroup((*itr), maxPlayers)) { break; } } } // premade selection pools are set return true; } } // now check if we can move group from Premade queue to normal queue (timer has expired) or group size lowered!! // this could be 2 cycles but i'm checking only first team in queue - it can cause problem - // if first is invited to BG and seconds timer expired, but we can ignore it, because players have only 80 seconds to click to enter bg // and when they click or after 80 seconds the queue info is removed from queue uint32 time_before = GameTime::GetGameTimeMS() - sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH); for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i) { if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].empty()) { GroupsQueueType::iterator itr = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].begin(); if (!(*itr)->IsInvitedToBGInstanceGUID && ((*itr)->JoinTime < time_before || (*itr)->Players.size() < MinPlayersPerTeam)) { // we must insert group to normal queue and erase pointer from premade queue m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].push_front((*itr)); m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].erase(itr); } } } // selection pools are not set return false; } // this method tries to create battleground or arena with MinPlayersPerTeam against MinPlayersPerTeam bool BattleGroundQueue::CheckNormalMatch(BattleGround* bg_template, BattleGroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers) { GroupsQueueType::const_iterator itr_team[PVP_TEAM_COUNT]; for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i) { itr_team[i] = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].begin(); for (; itr_team[i] != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].end(); ++(itr_team[i])) { if (!(*(itr_team[i]))->IsInvitedToBGInstanceGUID) { m_SelectionPools[i].AddGroup(*(itr_team[i]), maxPlayers); if (m_SelectionPools[i].GetPlayerCount() >= minPlayers) { break; } } } } // try to invite same number of players - this cycle may cause longer wait time even if there are enough players in queue, but we want ballanced bg uint32 j = TEAM_INDEX_ALLIANCE; if (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() < m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount()) { j = TEAM_INDEX_HORDE; } if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE) != 0 && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() >= minPlayers) { // we will try to invite more groups to team with less players indexed by j ++(itr_team[j]); // this will not cause a crash, because for cycle above reached break; for (; itr_team[j] != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + j].end(); ++(itr_team[j])) { if (!(*(itr_team[j]))->IsInvitedToBGInstanceGUID) if (!m_SelectionPools[j].AddGroup(*(itr_team[j]), m_SelectionPools[(j + 1) % PVP_TEAM_COUNT].GetPlayerCount())) { break; } } // do not allow to start bg with more than 2 players more on 1 faction if (abs((int32)(m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() - m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount())) > 2) { return false; } } // allow 1v0 if debug bg if (sBattleGroundMgr.isTesting() && bg_template->isBattleGround() && (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() || m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount())) { return true; } // return true if there are enough players in selection pools - enable to work .debug bg command correctly return m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() >= minPlayers; } // this method will check if we can invite players to same faction skirmish match bool BattleGroundQueue::CheckSkirmishForSameFaction(BattleGroundBracketId bracket_id, uint32 minPlayersPerTeam) { if (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() < minPlayersPerTeam && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() < minPlayersPerTeam) { return false; } PvpTeamIndex teamIdx = TEAM_INDEX_ALLIANCE; PvpTeamIndex otherTeamIdx = TEAM_INDEX_HORDE; Team otherTeamId = HORDE; if (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() == minPlayersPerTeam) { teamIdx = TEAM_INDEX_HORDE; otherTeamIdx = TEAM_INDEX_ALLIANCE; otherTeamId = ALLIANCE; } // clear other team's selection m_SelectionPools[otherTeamIdx].Init(); // store last ginfo pointer GroupQueueInfo* ginfo = m_SelectionPools[teamIdx].SelectedGroups.back(); // set itr_team to group that was added to selection pool latest GroupsQueueType::iterator itr_team = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].begin(); for (; itr_team != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team) { if (ginfo == *itr_team) { break; } } if (itr_team == m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end()) { return false; } GroupsQueueType::iterator itr_team2 = itr_team; ++itr_team2; // invite players to other selection pool for (; itr_team2 != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team2) { // if selection pool is full then break; if (!(*itr_team2)->IsInvitedToBGInstanceGUID && !m_SelectionPools[otherTeamIdx].AddGroup(*itr_team2, minPlayersPerTeam)) { break; } } if (m_SelectionPools[otherTeamIdx].GetPlayerCount() != minPlayersPerTeam) { return false; } // here we have correct 2 selections and we need to change one teams team and move selection pool teams to other team's queue for (GroupsQueueType::iterator itr = m_SelectionPools[otherTeamIdx].SelectedGroups.begin(); itr != m_SelectionPools[otherTeamIdx].SelectedGroups.end(); ++itr) { // set correct team (*itr)->GroupTeam = otherTeamId; // add team to other queue m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + otherTeamIdx].push_front(*itr); // remove team from old queue GroupsQueueType::iterator itr2 = itr_team; ++itr2; for (; itr2 != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr2) { if (*itr2 == *itr) { m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].erase(itr2); break; } } } return true; } /* this method is called when group is inserted, or player / group is removed from BG Queue - there is only one player's status changed, so we don't use while(true) cycles to invite whole queue it must be called after fully adding the members of a group to ensure group joining should be called from BattleGround::RemovePlayer function in some cases */ void BattleGroundQueue::Update(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id, ArenaType arenaType, bool isRated, uint32 arenaRating) { // ACE_Guard<ACE_Recursive_Thread_Mutex> guard(m_Lock); // if no players in queue - do nothing if (m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty() && m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty() && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].empty() && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].empty()) { return; } // battleground with free slot for player should be always in the beggining of the queue // maybe it would be better to create bgfreeslotqueue for each bracket_id BGFreeSlotQueueType::iterator itr, next; for (itr = sBattleGroundMgr.BGFreeSlotQueue[bgTypeId].begin(); itr != sBattleGroundMgr.BGFreeSlotQueue[bgTypeId].end(); itr = next) { next = itr; ++next; // DO NOT allow queue manager to invite new player to arena if ((*itr)->isBattleGround() && (*itr)->GetTypeID() == bgTypeId && (*itr)->GetBracketId() == bracket_id && (*itr)->GetStatus() > STATUS_WAIT_QUEUE && (*itr)->GetStatus() < STATUS_WAIT_LEAVE) { BattleGround* bg = *itr; // we have to store battleground pointer here, because when battleground is full, it is removed from free queue (not yet implemented!!) // and iterator is invalid // clear selection pools m_SelectionPools[TEAM_INDEX_ALLIANCE].Init(); m_SelectionPools[TEAM_INDEX_HORDE].Init(); // call a function that does the job for us FillPlayersToBG(bg, bracket_id); // now everything is set, invite players for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_ALLIANCE].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_ALLIANCE].SelectedGroups.end(); ++citr) { InviteGroupToBG((*citr), bg, (*citr)->GroupTeam); } for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_HORDE].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_HORDE].SelectedGroups.end(); ++citr) { InviteGroupToBG((*citr), bg, (*citr)->GroupTeam); } if (!bg->HasFreeSlots()) { // remove BG from BGFreeSlotQueue bg->RemoveFromBGFreeSlotQueue(); } } } // finished iterating through the bgs with free slots, maybe we need to create a new bg BattleGround* bg_template = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId); if (!bg_template) { sLog.outError("Battleground: Update: bg template not found for %u", bgTypeId); return; } PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketById(bg_template->GetMapId(), bracket_id); if (!bracketEntry) { sLog.outError("Battleground: Update: bg bracket entry not found for map %u bracket id %u", bg_template->GetMapId(), bracket_id); return; } // get the min. players per team, properly for larger arenas as well. (must have full teams for arena matches!) uint32 MinPlayersPerTeam = bg_template->GetMinPlayersPerTeam(); uint32 MaxPlayersPerTeam = bg_template->GetMaxPlayersPerTeam(); if (sBattleGroundMgr.isTesting()) { MinPlayersPerTeam = 1; } if (bg_template->isArena()) { if (sBattleGroundMgr.isArenaTesting()) { MaxPlayersPerTeam = 1; MinPlayersPerTeam = 1; } else { // this switch can be much shorter MaxPlayersPerTeam = arenaType; MinPlayersPerTeam = arenaType; /*switch(arenaType) { case ARENA_TYPE_2v2: MaxPlayersPerTeam = 2; MinPlayersPerTeam = 2; break; case ARENA_TYPE_3v3: MaxPlayersPerTeam = 3; MinPlayersPerTeam = 3; break; case ARENA_TYPE_5v5: MaxPlayersPerTeam = 5; MinPlayersPerTeam = 5; break; }*/ } } m_SelectionPools[TEAM_INDEX_ALLIANCE].Init(); m_SelectionPools[TEAM_INDEX_HORDE].Init(); if (bg_template->isBattleGround()) { // check if there is premade against premade match if (CheckPremadeMatch(bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam)) { // create new battleground BattleGround* bg2 = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, ARENA_TYPE_NONE, false); if (!bg2) { sLog.outError("BattleGroundQueue::Update - Can not create battleground: %u", bgTypeId); return; } // invite those selection pools for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i) for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.end(); ++citr) { InviteGroupToBG((*citr), bg2, (*citr)->GroupTeam); } // start bg bg2->StartBattleGround(); // clear structures m_SelectionPools[TEAM_INDEX_ALLIANCE].Init(); m_SelectionPools[TEAM_INDEX_HORDE].Init(); } } // now check if there are in queues enough players to start new game of (normal battleground, or non-rated arena) if (!isRated) { // if there are enough players in pools, start new battleground or non rated arena if (CheckNormalMatch(bg_template, bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam) || (bg_template->isArena() && CheckSkirmishForSameFaction(bracket_id, MinPlayersPerTeam))) { // we successfully created a pool BattleGround* bg2 = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, arenaType, false); if (!bg2) { sLog.outError("BattleGroundQueue::Update - Can not create battleground: %u", bgTypeId); return; } // invite those selection pools for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i) for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.end(); ++citr) { InviteGroupToBG((*citr), bg2, (*citr)->GroupTeam); } // start bg bg2->StartBattleGround(); } } else if (bg_template->isArena()) { // found out the minimum and maximum ratings the newly added team should battle against // arenaRating is the rating of the latest joined team, or 0 // 0 is on (automatic update call) and we must set it to team's with longest wait time if (!arenaRating) { GroupQueueInfo* front1 = NULL; GroupQueueInfo* front2 = NULL; if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty()) { front1 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].front(); arenaRating = front1->ArenaTeamRating; } if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty()) { front2 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].front(); arenaRating = front2->ArenaTeamRating; } if (front1 && front2) { if (front1->JoinTime < front2->JoinTime) { arenaRating = front1->ArenaTeamRating; } } else if (!front1 && !front2) { return; // queues are empty } } // set rating range uint32 arenaMinRating = (arenaRating <= sBattleGroundMgr.GetMaxRatingDifference()) ? 0 : arenaRating - sBattleGroundMgr.GetMaxRatingDifference(); uint32 arenaMaxRating = arenaRating + sBattleGroundMgr.GetMaxRatingDifference(); // if max rating difference is set and the time past since server startup is greater than the rating discard time // (after what time the ratings aren't taken into account when making teams) then // the discard time is current_time - time_to_discard, teams that joined after that, will have their ratings taken into account // else leave the discard time on 0, this way all ratings will be discarded uint32 discardTime = GameTime::GetGameTimeMS() - sBattleGroundMgr.GetRatingDiscardTimer(); // we need to find 2 teams which will play next game GroupsQueueType::iterator itr_team[PVP_TEAM_COUNT]; // optimalization : --- we dont need to use selection_pools - each update we select max 2 groups for (uint8 i = BG_QUEUE_PREMADE_ALLIANCE; i < BG_QUEUE_NORMAL_ALLIANCE; ++i) { // take the group that joined first itr_team[i] = m_QueuedGroups[bracket_id][i].begin(); for (; itr_team[i] != m_QueuedGroups[bracket_id][i].end(); ++(itr_team[i])) { // if group match conditions, then add it to pool if (!(*itr_team[i])->IsInvitedToBGInstanceGUID && (((*itr_team[i])->ArenaTeamRating >= arenaMinRating && (*itr_team[i])->ArenaTeamRating <= arenaMaxRating) || (*itr_team[i])->JoinTime < discardTime)) { m_SelectionPools[i].AddGroup((*itr_team[i]), MaxPlayersPerTeam); // break for cycle to be able to start selecting another group from same faction queue break; } } } // now we are done if we have 2 groups - ali vs horde! // if we don't have, we must try to continue search in same queue // tmp variables are correctly set // this code isn't much userfriendly - but it is supposed to continue search for mathing group in HORDE queue if (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() == 0 && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()) { itr_team[TEAM_INDEX_ALLIANCE] = itr_team[TEAM_INDEX_HORDE]; ++itr_team[TEAM_INDEX_ALLIANCE]; for (; itr_team[TEAM_INDEX_ALLIANCE] != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end(); ++(itr_team[TEAM_INDEX_ALLIANCE])) { if (!(*itr_team[TEAM_INDEX_ALLIANCE])->IsInvitedToBGInstanceGUID && (((*itr_team[TEAM_INDEX_ALLIANCE])->ArenaTeamRating >= arenaMinRating && (*itr_team[TEAM_INDEX_ALLIANCE])->ArenaTeamRating <= arenaMaxRating) || (*itr_team[TEAM_INDEX_ALLIANCE])->JoinTime < discardTime)) { m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*itr_team[TEAM_INDEX_ALLIANCE]), MaxPlayersPerTeam); break; } } } // this code isn't much userfriendly - but it is supposed to continue search for mathing group in ALLIANCE queue if (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() == 0 && m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount()) { itr_team[TEAM_INDEX_HORDE] = itr_team[TEAM_INDEX_ALLIANCE]; ++itr_team[TEAM_INDEX_HORDE]; for (; itr_team[TEAM_INDEX_HORDE] != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end(); ++(itr_team[TEAM_INDEX_HORDE])) { if (!(*itr_team[TEAM_INDEX_HORDE])->IsInvitedToBGInstanceGUID && (((*itr_team[TEAM_INDEX_HORDE])->ArenaTeamRating >= arenaMinRating && (*itr_team[TEAM_INDEX_HORDE])->ArenaTeamRating <= arenaMaxRating) || (*itr_team[TEAM_INDEX_HORDE])->JoinTime < discardTime)) { m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*itr_team[TEAM_INDEX_HORDE]), MaxPlayersPerTeam); break; } } } // if we have 2 teams, then start new arena and invite players! if (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()) { BattleGround* arena = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, arenaType, true); if (!arena) { sLog.outError("BattlegroundQueue::Update couldn't create arena instance for rated arena match!"); return; } (*(itr_team[TEAM_INDEX_ALLIANCE]))->OpponentsTeamRating = (*(itr_team[TEAM_INDEX_HORDE]))->ArenaTeamRating; DEBUG_LOG("setting oposite teamrating for team %u to %u", (*(itr_team[TEAM_INDEX_ALLIANCE]))->ArenaTeamId, (*(itr_team[TEAM_INDEX_ALLIANCE]))->OpponentsTeamRating); (*(itr_team[TEAM_INDEX_HORDE]))->OpponentsTeamRating = (*(itr_team[TEAM_INDEX_ALLIANCE]))->ArenaTeamRating; DEBUG_LOG("setting oposite teamrating for team %u to %u", (*(itr_team[TEAM_INDEX_HORDE]))->ArenaTeamId, (*(itr_team[TEAM_INDEX_HORDE]))->OpponentsTeamRating); // now we must move team if we changed its faction to another faction queue, because then we will spam log by errors in Queue::RemovePlayer if ((*(itr_team[TEAM_INDEX_ALLIANCE]))->GroupTeam != ALLIANCE) { // add to alliance queue m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].push_front(*(itr_team[TEAM_INDEX_ALLIANCE])); // erase from horde queue m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].erase(itr_team[TEAM_INDEX_ALLIANCE]); itr_team[TEAM_INDEX_ALLIANCE] = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].begin(); } if ((*(itr_team[TEAM_INDEX_HORDE]))->GroupTeam != HORDE) { m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].push_front(*(itr_team[TEAM_INDEX_HORDE])); m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].erase(itr_team[TEAM_INDEX_HORDE]); itr_team[TEAM_INDEX_HORDE] = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].begin(); } InviteGroupToBG(*(itr_team[TEAM_INDEX_ALLIANCE]), arena, ALLIANCE); InviteGroupToBG(*(itr_team[TEAM_INDEX_HORDE]), arena, HORDE); DEBUG_LOG("Starting rated arena match!"); arena->StartBattleGround(); } } } /*********************************************************/ /*** BATTLEGROUND QUEUE EVENTS ***/ /*********************************************************/ bool BGQueueInviteEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) { Player* plr = sObjectMgr.GetPlayer(m_PlayerGuid); // player logged off (we should do nothing, he is correctly removed from queue in another procedure) if (!plr) { return true; } BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId); // if battleground ended and its instance deleted - do nothing if (!bg) { return true; } BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bg->GetTypeID(), bg->GetArenaType()); uint32 queueSlot = plr->GetBattleGroundQueueIndex(bgQueueTypeId); if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue or in battleground { // check if player is invited to this bg BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId]; if (bgQueue.IsPlayerInvited(m_PlayerGuid, m_BgInstanceGUID, m_RemoveTime)) { WorldPacket data; // we must send remaining time in queue sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, 0, m_ArenaType, TEAM_NONE); plr->GetSession()->SendPacket(&data); } } return true; // event will be deleted } void BGQueueInviteEvent::Abort(uint64 /*e_time*/) { // do nothing } /* this event has many possibilities when it is executed: 1. player is in battleground ( he clicked enter on invitation window ) 2. player left battleground queue and he isn't there any more 3. player left battleground queue and he joined it again and IsInvitedToBGInstanceGUID = 0 4. player left queue and he joined again and he has been invited to same battleground again -> we should not remove him from queue yet 5. player is invited to bg and he didn't choose what to do and timer expired - only in this condition we should call queue::RemovePlayer we must remove player in the 5. case even if battleground object doesn't exist! */ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) { Player* plr = sObjectMgr.GetPlayer(m_PlayerGuid); if (!plr) { // player logged off (we should do nothing, he is correctly removed from queue in another procedure) return true; } BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId); // battleground can be deleted already when we are removing queue info // bg pointer can be NULL! so use it carefully! uint32 queueSlot = plr->GetBattleGroundQueueIndex(m_BgQueueTypeId); if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue, or in Battleground { // check if player is in queue for this BG and if we are removing his invite event BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[m_BgQueueTypeId]; if (bgQueue.IsPlayerInvited(m_PlayerGuid, m_BgInstanceGUID, m_RemoveTime)) { DEBUG_LOG("Battleground: removing player %u from bg queue for instance %u because of not pressing enter battle in time.", plr->GetGUIDLow(), m_BgInstanceGUID); plr->RemoveBattleGroundQueueId(m_BgQueueTypeId); bgQueue.RemovePlayer(m_PlayerGuid, true); // update queues if battleground isn't ended if (bg && bg->isBattleGround() && bg->GetStatus() != STATUS_WAIT_LEAVE) { sBattleGroundMgr.ScheduleQueueUpdate(0, ARENA_TYPE_NONE, m_BgQueueTypeId, m_BgTypeId, bg->GetBracketId()); } WorldPacket data; sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE, TEAM_NONE); plr->GetSession()->SendPacket(&data); } } // event will be deleted return true; } void BGQueueRemoveEvent::Abort(uint64 /*e_time*/) { // do nothing } /*********************************************************/ /*** BATTLEGROUND MANAGER ***/ /*********************************************************/ BattleGroundMgr::BattleGroundMgr() : m_AutoDistributionTimeChecker(0), m_ArenaTesting(false) { for (uint8 i = BATTLEGROUND_TYPE_NONE; i < MAX_BATTLEGROUND_TYPE_ID; ++i) { m_BattleGrounds[i].clear(); } m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER); m_Testing = false; } BattleGroundMgr::~BattleGroundMgr() { DeleteAllBattleGrounds(); } void BattleGroundMgr::DeleteAllBattleGrounds() { // will also delete template bgs: for (uint8 i = BATTLEGROUND_TYPE_NONE; i < MAX_BATTLEGROUND_TYPE_ID; ++i) { for (BattleGroundSet::iterator itr = m_BattleGrounds[i].begin(); itr != m_BattleGrounds[i].end();) { BattleGround* bg = itr->second; ++itr; // step from invalidate iterator pos in result element remove in ~BattleGround call delete bg; } } } // used to update running battlegrounds, and delete finished ones void BattleGroundMgr::Update(uint32 diff) { // update scheduled queues if (!m_QueueUpdateScheduler.empty()) { std::vector<uint64> scheduled; { // create mutex // ACE_Guard<ACE_Thread_Mutex> guard(SchedulerLock); // copy vector and clear the other scheduled = std::vector<uint64>(m_QueueUpdateScheduler); m_QueueUpdateScheduler.clear(); // release lock } for (uint8 i = 0; i < scheduled.size(); ++i) { uint32 arenaRating = scheduled[i] >> 32; ArenaType arenaType = ArenaType(scheduled[i] >> 24 & 255); BattleGroundQueueTypeId bgQueueTypeId = BattleGroundQueueTypeId(scheduled[i] >> 16 & 255); BattleGroundTypeId bgTypeId = BattleGroundTypeId((scheduled[i] >> 8) & 255); BattleGroundBracketId bracket_id = BattleGroundBracketId(scheduled[i] & 255); m_BattleGroundQueues[bgQueueTypeId].Update(bgTypeId, bracket_id, arenaType, arenaRating > 0, arenaRating); } } // if rating difference counts, maybe force-update queues if (sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE) && sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER)) { // it's time to force update if (m_NextRatingDiscardUpdate < diff) { // forced update for rated arenas (scan all, but skipped non rated) DEBUG_LOG("BattleGroundMgr: UPDATING ARENA QUEUES"); for (uint8 qtype = BATTLEGROUND_QUEUE_2v2; qtype <= BATTLEGROUND_QUEUE_5v5; ++qtype) for (uint8 bracket = BG_BRACKET_ID_FIRST; bracket < MAX_BATTLEGROUND_BRACKETS; ++bracket) m_BattleGroundQueues[qtype].Update( BATTLEGROUND_AA, BattleGroundBracketId(bracket), BattleGroundMgr::BGArenaType(BattleGroundQueueTypeId(qtype)), true, 0); m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER); } else { m_NextRatingDiscardUpdate -= diff; } } if (sWorld.getConfig(CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS)) { if (m_AutoDistributionTimeChecker < diff) { if (sWorld.GetGameTime() > m_NextAutoDistributionTime) { DistributeArenaPoints(); m_NextAutoDistributionTime = time_t(m_NextAutoDistributionTime + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld.getConfig(CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS)); CharacterDatabase.PExecute("UPDATE `saved_variables` SET `NextArenaPointDistributionTime` = '" UI64FMTD "'", uint64(m_NextAutoDistributionTime)); } m_AutoDistributionTimeChecker = 600000; // check 10 minutes } else { m_AutoDistributionTimeChecker -= diff; } } } void BattleGroundMgr::BuildBattleGroundStatusPacket(WorldPacket* data, BattleGround* bg, uint8 QueueSlot, uint8 StatusID, uint32 Time1, uint32 Time2, ArenaType arenatype, Team arenaTeam) { // we can be in 2 queues in same time... if (StatusID == 0 || !bg) { data->Initialize(SMSG_BATTLEFIELD_STATUS, 4 + 8); *data << uint32(QueueSlot); // queue id (0...1) *data << uint64(0); return; } data->Initialize(SMSG_BATTLEFIELD_STATUS, (4 + 8 + 1 + 1 + 4 + 1 + 4 + 4 + 4)); *data << uint32(QueueSlot); // queue id (0...1) - player can be in 2 queues in time // uint64 in client *data << uint64(uint64(arenatype) | (uint64(0x0D) << 8) | (uint64(bg->GetTypeID()) << 16) | (uint64(0x1F90) << 48)); *data << uint8(0); // 3.3.0, some level, only saw 80... *data << uint8(0); // 3.3.0, some level, only saw 80... *data << uint32(bg->GetClientInstanceID()); // alliance/horde for BG and skirmish/rated for Arenas // following displays the minimap-icon 0 = faction icon 1 = arenaicon *data << uint8(bg->isRated()); *data << uint32(StatusID); // status switch (StatusID) { case STATUS_WAIT_QUEUE: // status_in_queue *data << uint32(Time1); // average wait time, milliseconds *data << uint32(Time2); // time in queue, updated every minute!, milliseconds break; case STATUS_WAIT_JOIN: // status_invite *data << uint32(bg->GetMapId()); // map id *data << uint64(0); // 3.3.5, unknown *data << uint32(Time1); // time to remove from queue, milliseconds break; case STATUS_IN_PROGRESS: // status_in_progress *data << uint32(bg->GetMapId()); // map id *data << uint64(0); // 3.3.5, unknown *data << uint32(Time1); // time to bg auto leave, 0 at bg start, 120000 after bg end, milliseconds *data << uint32(Time2); // time from bg start, milliseconds *data << uint8(arenaTeam == ALLIANCE ? 1 : 0); // arenaTeam (0 for horde, 1 for alliance) break; default: sLog.outError("Unknown BG status!"); break; } } void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket* data, BattleGround* bg) { uint8 type = (bg->isArena() ? 1 : 0); // last check on 3.0.3 data->Initialize(MSG_PVP_LOG_DATA, (1 + 1 + 4 + 40 * bg->GetPlayerScoresSize())); *data << uint8(type); // type (battleground=0/arena=1) if (type) // arena { // it seems this must be according to BG_WINNER_A/H and _NOT_ TEAM_INDEX_A/H for (int8 i = 1; i >= 0; --i) { uint32 pointsLost = bg->m_ArenaTeamRatingChanges[i] < 0 ? abs(bg->m_ArenaTeamRatingChanges[i]) : 0; uint32 pointsGained = bg->m_ArenaTeamRatingChanges[i] > 0 ? bg->m_ArenaTeamRatingChanges[i] : 0; *data << uint32(pointsLost); // Rating Lost *data << uint32(pointsGained); // Rating gained *data << uint32(0); // Matchmaking Value DEBUG_LOG("rating change: %d", bg->m_ArenaTeamRatingChanges[i]); } for (int8 i = 1; i >= 0; --i) { uint32 at_id = bg->m_ArenaTeamIds[i]; ArenaTeam* at = sObjectMgr.GetArenaTeamById(at_id); if (at) { *data << at->GetName(); } else { *data << (uint8)0; } } } if (bg->GetStatus() != STATUS_WAIT_LEAVE) { *data << uint8(0); // bg not ended } else { *data << uint8(1); // bg ended *data << uint8(bg->GetWinner() == ALLIANCE ? 1 : 0);// who win } *data << (int32)(bg->GetPlayerScoresSize()); for (BattleGround::BattleGroundScoreMap::const_iterator itr = bg->GetPlayerScoresBegin(); itr != bg->GetPlayerScoresEnd(); ++itr) { const BattleGroundScore* score = itr->second; *data << ObjectGuid(itr->first); *data << (int32)score->KillingBlows; if (type == 0) { *data << (int32)score->HonorableKills; *data << (int32)score->Deaths; *data << (int32)(score->BonusHonor); } else { Team team = bg->GetPlayerTeam(itr->first); if (!team) { if (Player* player = sObjectMgr.GetPlayer(itr->first)) { team = player->GetTeam(); } } if (bg->GetWinner() == team && team != TEAM_NONE) { *data << uint8(1); } else { *data << uint8(0); } } *data << (int32)score->DamageDone; // damage done *data << (int32)score->HealingDone; // healing done switch (bg->GetTypeID(true)) // battleground specific things { case BATTLEGROUND_AV: *data << (uint32)0x00000005; // count of next fields *data << (uint32)((BattleGroundAVScore*)score)->GraveyardsAssaulted; // GraveyardsAssaulted *data << (uint32)((BattleGroundAVScore*)score)->GraveyardsDefended; // GraveyardsDefended *data << (uint32)((BattleGroundAVScore*)score)->TowersAssaulted; // TowersAssaulted *data << (uint32)((BattleGroundAVScore*)score)->TowersDefended; // TowersDefended *data << (uint32)((BattleGroundAVScore*)score)->SecondaryObjectives; // SecondaryObjectives - free some of the Lieutnants break; case BATTLEGROUND_WS: *data << (uint32)0x00000002; // count of next fields *data << (uint32)((BattleGroundWGScore*)score)->FlagCaptures; // flag captures *data << (uint32)((BattleGroundWGScore*)score)->FlagReturns; // flag returns break; case BATTLEGROUND_AB: *data << (uint32)0x00000002; // count of next fields *data << (uint32)((BattleGroundABScore*)score)->BasesAssaulted; // bases asssulted *data << (uint32)((BattleGroundABScore*)score)->BasesDefended; // bases defended break; case BATTLEGROUND_EY: *data << (uint32)0x00000001; // count of next fields *data << (uint32)((BattleGroundEYScore*)score)->FlagCaptures; // flag captures break; case BATTLEGROUND_NA: case BATTLEGROUND_BE: case BATTLEGROUND_AA: case BATTLEGROUND_RL: case BATTLEGROUND_SA: // wotlk case BATTLEGROUND_DS: // wotlk case BATTLEGROUND_RV: // wotlk case BATTLEGROUND_IC: // wotlk case BATTLEGROUND_RB: // wotlk *data << (int32)0; // 0 break; default: sLog.outDebug("Unhandled MSG_PVP_LOG_DATA for BG id %u", bg->GetTypeID(true)); *data << (int32)0; break; } } } void BattleGroundMgr::BuildGroupJoinedBattlegroundPacket(WorldPacket* data, GroupJoinBattlegroundResult result) { /*bgTypeId is: 0 - Your group has joined a battleground queue, but you are not eligible 1 - Your group has joined the queue for AV 2 - Your group has joined the queue for WS 3 - Your group has joined the queue for AB 4 - Your group has joined the queue for NA 5 - Your group has joined the queue for BE Arena 6 - Your group has joined the queue for All Arenas 7 - Your group has joined the queue for EotS*/ data->Initialize(SMSG_GROUP_JOINED_BATTLEGROUND, 4); *data << int32(result); if (result == ERR_BATTLEGROUND_JOIN_TIMED_OUT || result == ERR_BATTLEGROUND_JOIN_FAILED) { *data << uint64(0); // player guid } } void BattleGroundMgr::BuildUpdateWorldStatePacket(WorldPacket* data, uint32 field, uint32 value) { data->Initialize(SMSG_UPDATE_WORLD_STATE, 4 + 4); *data << uint32(field); *data << uint32(value); } void BattleGroundMgr::BuildPlaySoundPacket(WorldPacket* data, uint32 soundid) { data->Initialize(SMSG_PLAY_SOUND, 4); *data << uint32(soundid); } void BattleGroundMgr::BuildPlayerLeftBattleGroundPacket(WorldPacket* data, ObjectGuid guid) { data->Initialize(SMSG_BATTLEGROUND_PLAYER_LEFT, 8); *data << ObjectGuid(guid); } void BattleGroundMgr::BuildPlayerJoinedBattleGroundPacket(WorldPacket* data, Player* plr) { data->Initialize(SMSG_BATTLEGROUND_PLAYER_JOINED, 8); *data << plr->GetObjectGuid(); } BattleGround* BattleGroundMgr::GetBattleGroundThroughClientInstance(uint32 instanceId, BattleGroundTypeId bgTypeId) { // cause at HandleBattleGroundJoinOpcode the clients sends the instanceid he gets from // SMSG_BATTLEFIELD_LIST we need to find the battleground with this clientinstance-id BattleGround* bg = GetBattleGroundTemplate(bgTypeId); if (!bg) { return NULL; } if (bg->isArena()) { return GetBattleGround(instanceId, bgTypeId); } for (BattleGroundSet::iterator itr = m_BattleGrounds[bgTypeId].begin(); itr != m_BattleGrounds[bgTypeId].end(); ++itr) { if (itr->second->GetClientInstanceID() == instanceId) { return itr->second; } } return NULL; } BattleGround* BattleGroundMgr::GetBattleGround(uint32 InstanceID, BattleGroundTypeId bgTypeId) { // search if needed BattleGroundSet::iterator itr; if (bgTypeId == BATTLEGROUND_TYPE_NONE) { for (uint8 i = BATTLEGROUND_AV; i < MAX_BATTLEGROUND_TYPE_ID; ++i) { itr = m_BattleGrounds[i].find(InstanceID); if (itr != m_BattleGrounds[i].end()) { return itr->second; } } return NULL; } itr = m_BattleGrounds[bgTypeId].find(InstanceID); return ((itr != m_BattleGrounds[bgTypeId].end()) ? itr->second : NULL); } BattleGround* BattleGroundMgr::GetBattleGroundTemplate(BattleGroundTypeId bgTypeId) { // map is sorted and we can be sure that lowest instance id has only BG template return m_BattleGrounds[bgTypeId].empty() ? NULL : m_BattleGrounds[bgTypeId].begin()->second; } uint32 BattleGroundMgr::CreateClientVisibleInstanceId(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id) { if (IsArenaType(bgTypeId)) { return 0; // arenas don't have client-instanceids } // we create here an instanceid, which is just for // displaying this to the client and without any other use.. // the client-instanceIds are unique for each battleground-type // the instance-id just needs to be as low as possible, beginning with 1 // the following works, because std::set is default ordered with "<" // the optimalization would be to use as bitmask std::vector<uint32> - but that would only make code unreadable uint32 lastId = 0; ClientBattleGroundIdSet& ids = m_ClientBattleGroundIds[bgTypeId][bracket_id]; for (ClientBattleGroundIdSet::const_iterator itr = ids.begin(); itr != ids.end();) { if ((++lastId) != *itr) // if there is a gap between the ids, we will break.. { break; } lastId = *itr; } ids.insert(lastId + 1); return lastId + 1; } // create a new battleground that will really be used to play BattleGround* BattleGroundMgr::CreateNewBattleGround(BattleGroundTypeId bgTypeId, PvPDifficultyEntry const* bracketEntry, ArenaType arenaType, bool isRated) { // get the template BG BattleGround* bg_template = GetBattleGroundTemplate(bgTypeId); if (!bg_template) { sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId); return NULL; } // for arenas there is random map used if (bg_template->isArena()) { BattleGroundTypeId arenas[] = { BATTLEGROUND_NA, BATTLEGROUND_BE, BATTLEGROUND_RL/*, BATTLEGROUND_DS, BATTLEGROUND_RV*/ }; bgTypeId = arenas[urand(0, countof(arenas) - 1)]; bg_template = GetBattleGroundTemplate(bgTypeId); if (!bg_template) { sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId); return NULL; } } bool isRandom = false; if (bgTypeId == BATTLEGROUND_RB) { BattleGroundTypeId random_bgs[] = {BATTLEGROUND_AV, BATTLEGROUND_WS, BATTLEGROUND_AB, BATTLEGROUND_EY/*, BATTLEGROUND_SA, BATTLEGROUND_IC*/}; uint32 bg_num = urand(0, sizeof(random_bgs)/sizeof(BattleGroundTypeId)-1); bgTypeId = random_bgs[bg_num]; bg_template = GetBattleGroundTemplate(bgTypeId); if (!bg_template) { sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId); return NULL; } isRandom = true; } BattleGround* bg = NULL; // create a copy of the BG template switch (bgTypeId) { case BATTLEGROUND_AV: bg = new BattleGroundAV(*(BattleGroundAV*)bg_template); break; case BATTLEGROUND_WS: bg = new BattleGroundWS(*(BattleGroundWS*)bg_template); break; case BATTLEGROUND_AB: bg = new BattleGroundAB(*(BattleGroundAB*)bg_template); break; case BATTLEGROUND_NA: bg = new BattleGroundNA(*(BattleGroundNA*)bg_template); break; case BATTLEGROUND_BE: bg = new BattleGroundBE(*(BattleGroundBE*)bg_template); break; case BATTLEGROUND_AA: bg = new BattleGroundAA(*(BattleGroundAA*)bg_template); break; case BATTLEGROUND_EY: bg = new BattleGroundEY(*(BattleGroundEY*)bg_template); break; case BATTLEGROUND_RL: bg = new BattleGroundRL(*(BattleGroundRL*)bg_template); break; case BATTLEGROUND_SA: bg = new BattleGroundSA(*(BattleGroundSA*)bg_template); break; case BATTLEGROUND_DS: bg = new BattleGroundDS(*(BattleGroundDS*)bg_template); break; case BATTLEGROUND_RV: bg = new BattleGroundRV(*(BattleGroundRV*)bg_template); break; case BATTLEGROUND_IC: bg = new BattleGroundIC(*(BattleGroundIC*)bg_template); break; case BATTLEGROUND_RB: bg = new BattleGroundRB(*(BattleGroundRB*)bg_template); break; default: // error, but it is handled few lines above return 0; } // set before Map creating for let use proper difficulty bg->SetBracket(bracketEntry); // will also set m_bgMap, instanceid sMapMgr.CreateBgMap(bg->GetMapId(), bg); bg->SetClientInstanceID(CreateClientVisibleInstanceId(isRandom ? BATTLEGROUND_RB : bgTypeId, bracketEntry->GetBracketId())); // reset the new bg (set status to status_wait_queue from status_none) bg->Reset(); // start the joining of the bg bg->SetStatus(STATUS_WAIT_JOIN); bg->SetArenaType(arenaType); bg->SetRated(isRated); bg->SetRandom(isRandom); bg->SetTypeID(isRandom ? BATTLEGROUND_RB : bgTypeId); bg->SetRandomTypeID(bgTypeId); return bg; } // used to create the BG templates uint32 BattleGroundMgr::CreateBattleGround(BattleGroundTypeId bgTypeId, bool IsArena, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam, uint32 LevelMin, uint32 LevelMax, char const* BattleGroundName, uint32 MapID, float Team1StartLocX, float Team1StartLocY, float Team1StartLocZ, float Team1StartLocO, float Team2StartLocX, float Team2StartLocY, float Team2StartLocZ, float Team2StartLocO) { // Create the BG BattleGround* bg = NULL; switch (bgTypeId) { case BATTLEGROUND_AV: bg = new BattleGroundAV; break; case BATTLEGROUND_WS: bg = new BattleGroundWS; break; case BATTLEGROUND_AB: bg = new BattleGroundAB; break; case BATTLEGROUND_NA: bg = new BattleGroundNA; break; case BATTLEGROUND_BE: bg = new BattleGroundBE; break; case BATTLEGROUND_AA: bg = new BattleGroundAA; break; case BATTLEGROUND_EY: bg = new BattleGroundEY; break; case BATTLEGROUND_RL: bg = new BattleGroundRL; break; case BATTLEGROUND_SA: bg = new BattleGroundSA; break; case BATTLEGROUND_DS: bg = new BattleGroundDS; break; case BATTLEGROUND_RV: bg = new BattleGroundRV; break; case BATTLEGROUND_IC: bg = new BattleGroundIC; break; case BATTLEGROUND_RB: bg = new BattleGroundRB; break; default: bg = new BattleGround; break; // placeholder for non implemented BG } bg->SetMapId(MapID); bg->SetTypeID(bgTypeId); bg->SetArenaorBGType(IsArena); bg->SetMinPlayersPerTeam(MinPlayersPerTeam); bg->SetMaxPlayersPerTeam(MaxPlayersPerTeam); bg->SetMinPlayers(MinPlayersPerTeam * 2); bg->SetMaxPlayers(MaxPlayersPerTeam * 2); bg->SetName(BattleGroundName); bg->SetTeamStartLoc(ALLIANCE, Team1StartLocX, Team1StartLocY, Team1StartLocZ, Team1StartLocO); bg->SetTeamStartLoc(HORDE, Team2StartLocX, Team2StartLocY, Team2StartLocZ, Team2StartLocO); bg->SetLevelRange(LevelMin, LevelMax); // add bg to update list AddBattleGround(bg->GetInstanceID(), bg->GetTypeID(), bg); // return some not-null value, bgTypeId is good enough for me return bgTypeId; } void BattleGroundMgr::CreateInitialBattleGrounds() { uint32 count = 0; // 0 1 2 3 4 5 6 QueryResult* result = WorldDatabase.Query("SELECT `id`, `MinPlayersPerTeam`,`MaxPlayersPerTeam`,`AllianceStartLoc`,`AllianceStartO`,`HordeStartLoc`,`HordeStartO` FROM `battleground_template`"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outErrorDb(">> Loaded 0 battlegrounds. DB table `battleground_template` is empty."); sLog.outString(); return; } BarGoLink bar(result->GetRowCount()); do { Field* fields = result->Fetch(); bar.step(); uint32 bgTypeID_ = fields[0].GetUInt32(); // can be overwrite by values from DB BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(bgTypeID_); if (!bl) { sLog.outError("Battleground ID %u not found in BattlemasterList.dbc. Battleground not created.", bgTypeID_); continue; } if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeID_)) { continue; } BattleGroundTypeId bgTypeID = BattleGroundTypeId(bgTypeID_); bool IsArena = (bl->type == TYPE_ARENA); uint32 MinPlayersPerTeam = fields[1].GetUInt32(); uint32 MaxPlayersPerTeam = fields[2].GetUInt32(); // check values from DB if (MaxPlayersPerTeam == 0) { sLog.outErrorDb("Table `battleground_template` for id %u have wrong min/max players per team settings. BG not created.", bgTypeID); continue; } if (MinPlayersPerTeam > MaxPlayersPerTeam) { MinPlayersPerTeam = MaxPlayersPerTeam; sLog.outErrorDb("Table `battleground_template` for id %u has min players > max players per team settings. Min players will use same value as max players.", bgTypeID); } float AStartLoc[4]; float HStartLoc[4]; uint32 start1 = fields[3].GetUInt32(); WorldSafeLocsEntry const* start = sWorldSafeLocsStore.LookupEntry(start1); if (start) { AStartLoc[0] = start->x; AStartLoc[1] = start->y; AStartLoc[2] = start->z; AStartLoc[3] = fields[4].GetFloat(); } else if (bgTypeID == BATTLEGROUND_AA || bgTypeID == BATTLEGROUND_RB) { AStartLoc[0] = 0; AStartLoc[1] = 0; AStartLoc[2] = 0; AStartLoc[3] = fields[4].GetFloat(); } else { sLog.outErrorDb("Table `battleground_template` for id %u have nonexistent WorldSafeLocs.dbc id %u in field `AllianceStartLoc`. BG not created.", bgTypeID, start1); continue; } uint32 start2 = fields[5].GetUInt32(); start = sWorldSafeLocsStore.LookupEntry(start2); if (start) { HStartLoc[0] = start->x; HStartLoc[1] = start->y; HStartLoc[2] = start->z; HStartLoc[3] = fields[6].GetFloat(); } else if (bgTypeID == BATTLEGROUND_AA || bgTypeID == BATTLEGROUND_RB) { HStartLoc[0] = 0; HStartLoc[1] = 0; HStartLoc[2] = 0; HStartLoc[3] = fields[6].GetFloat(); } else { sLog.outErrorDb("Table `battleground_template` for id %u have nonexistent WorldSafeLocs.dbc id %u in field `HordeStartLoc`. BG not created.", bgTypeID, start2); continue; } // sLog.outDetail("Creating battleground %s, %u-%u", bl->name[sWorld.GetDBClang()], MinLvl, MaxLvl); if (!CreateBattleGround(bgTypeID, IsArena, MinPlayersPerTeam, MaxPlayersPerTeam, bl->minLevel, bl->maxLevel, bl->name[sWorld.GetDefaultDbcLocale()], bl->mapid[0], AStartLoc[0], AStartLoc[1], AStartLoc[2], AStartLoc[3], HStartLoc[0], HStartLoc[1], HStartLoc[2], HStartLoc[3])) { continue; } ++count; } while (result->NextRow()); delete result; sLog.outString(">> Loaded %u battlegrounds", count); sLog.outString(); } void BattleGroundMgr::InitAutomaticArenaPointDistribution() { if (sWorld.getConfig(CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS)) { DEBUG_LOG("Initializing Automatic Arena Point Distribution"); QueryResult* result = CharacterDatabase.Query("SELECT `NextArenaPointDistributionTime` FROM `saved_variables`"); if (!result) { DEBUG_LOG("Battleground: Next arena point distribution time not found in SavedVariables, reseting it now."); m_NextAutoDistributionTime = time_t(sWorld.GetGameTime() + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld.getConfig(CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS)); CharacterDatabase.PExecute("INSERT INTO `saved_variables` (`NextArenaPointDistributionTime`) VALUES ('" UI64FMTD "')", uint64(m_NextAutoDistributionTime)); } else { m_NextAutoDistributionTime = time_t((*result)[0].GetUInt64()); delete result; } DEBUG_LOG("Automatic Arena Point Distribution initialized."); } } void BattleGroundMgr::DistributeArenaPoints() { // used to distribute arena points based on last week's stats sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_START); sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_ONLINE_START); // temporary structure for storing maximum points to add values for all players std::map<uint32, uint32> PlayerPoints; // at first update all points for all team members for (ObjectMgr::ArenaTeamMap::iterator team_itr = sObjectMgr.GetArenaTeamMapBegin(); team_itr != sObjectMgr.GetArenaTeamMapEnd(); ++team_itr) { if (ArenaTeam* at = team_itr->second) { at->UpdateArenaPointsHelper(PlayerPoints); } } // cycle that gives points to all players for (std::map<uint32, uint32>::iterator plr_itr = PlayerPoints.begin(); plr_itr != PlayerPoints.end(); ++plr_itr) { // update to database CharacterDatabase.PExecute("UPDATE `characters` SET `arenaPoints` = `arenaPoints` + '%u' WHERE `guid` = '%u'", plr_itr->second, plr_itr->first); // add points if player is online if (Player* pl = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, plr_itr->first))) { pl->ModifyArenaPoints(plr_itr->second); } } PlayerPoints.clear(); sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_ONLINE_END); sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_TEAM_START); for (ObjectMgr::ArenaTeamMap::iterator titr = sObjectMgr.GetArenaTeamMapBegin(); titr != sObjectMgr.GetArenaTeamMapEnd(); ++titr) { if (ArenaTeam* at = titr->second) { at->FinishWeek(); // set played this week etc values to 0 in memory, too at->SaveToDB(); // save changes at->NotifyStatsChanged(); // notify the players of the changes } } sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_TEAM_END); sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_END); } void BattleGroundMgr::BuildBattleGroundListPacket(WorldPacket* data, ObjectGuid guid, Player* plr, BattleGroundTypeId bgTypeId, uint8 fromWhere) { if (!plr) { return; } uint32 win_kills = plr->GetRandomWinner() ? BG_REWARD_WINNER_HONOR_LAST : BG_REWARD_WINNER_HONOR_FIRST; uint32 win_arena = plr->GetRandomWinner() ? BG_REWARD_WINNER_ARENA_LAST : BG_REWARD_WINNER_ARENA_FIRST; uint32 loos_kills = plr->GetRandomWinner() ? BG_REWARD_LOOSER_HONOR_LAST : BG_REWARD_LOOSER_HONOR_FIRST; win_kills = (uint32)MaNGOS::Honor::hk_honor_at_level(plr->getLevel(), win_kills*4); loos_kills = (uint32)MaNGOS::Honor::hk_honor_at_level(plr->getLevel(), loos_kills*4); data->Initialize(SMSG_BATTLEFIELD_LIST); *data << guid; // battlemaster guid *data << uint8(fromWhere); // from where you joined *data << uint32(bgTypeId); // battleground id *data << uint8(0); // unk *data << uint8(0); // unk // Rewards *data << uint8(plr->GetRandomWinner()); // 3.3.3 hasWin *data << uint32(win_kills); // 3.3.3 winHonor *data << uint32(win_arena); // 3.3.3 winArena *data << uint32(loos_kills); // 3.3.3 lossHonor uint8 isRandom = bgTypeId == BATTLEGROUND_RB; *data << uint8(isRandom); // 3.3.3 isRandom if (isRandom) { // Rewards (random) *data << uint8(plr->GetRandomWinner()); // 3.3.3 hasWin_Random *data << uint32(win_kills); // 3.3.3 winHonor_Random *data << uint32(win_arena); // 3.3.3 winArena_Random *data << uint32(loos_kills); // 3.3.3 lossHonor_Random } if (bgTypeId == BATTLEGROUND_AA) // arena { *data << uint32(0); // arena - no instances showed } else // battleground { size_t count_pos = data->wpos(); uint32 count = 0; *data << uint32(0); // number of bg instances if (BattleGround* bgTemplate = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId)) { // expected bracket entry if (PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgTemplate->GetMapId(), plr->getLevel())) { BattleGroundBracketId bracketId = bracketEntry->GetBracketId(); ClientBattleGroundIdSet const& ids = m_ClientBattleGroundIds[bgTypeId][bracketId]; for (ClientBattleGroundIdSet::const_iterator itr = ids.begin(); itr != ids.end(); ++itr) { *data << uint32(*itr); ++count; } data->put<uint32>(count_pos , count); } } } } void BattleGroundMgr::SendToBattleGround(Player* pl, uint32 instanceId, BattleGroundTypeId bgTypeId) { BattleGround* bg = GetBattleGround(instanceId, bgTypeId); if (bg) { uint32 mapid = bg->GetMapId(); float x, y, z, O; Team team = pl->GetBGTeam(); if (team == 0) { team = pl->GetTeam(); } bg->GetTeamStartLoc(team, x, y, z, O); DETAIL_LOG("BATTLEGROUND: Sending %s to map %u, X %f, Y %f, Z %f, O %f", pl->GetName(), mapid, x, y, z, O); pl->TeleportTo(mapid, x, y, z, O); } else { sLog.outError("player %u trying to port to nonexistent bg instance %u", pl->GetGUIDLow(), instanceId); } } bool BattleGroundMgr::IsArenaType(BattleGroundTypeId bgTypeId) { switch (bgTypeId) { case BATTLEGROUND_NA: case BATTLEGROUND_BE: case BATTLEGROUND_RL: case BATTLEGROUND_DS: case BATTLEGROUND_RV: case BATTLEGROUND_AA: return true; default: return false; }; } BattleGroundQueueTypeId BattleGroundMgr::BGQueueTypeId(BattleGroundTypeId bgTypeId, ArenaType arenaType) { switch (bgTypeId) { case BATTLEGROUND_WS: return BATTLEGROUND_QUEUE_WS; case BATTLEGROUND_AB: return BATTLEGROUND_QUEUE_AB; case BATTLEGROUND_AV: return BATTLEGROUND_QUEUE_AV; case BATTLEGROUND_EY: return BATTLEGROUND_QUEUE_EY; case BATTLEGROUND_SA: return BATTLEGROUND_QUEUE_SA; case BATTLEGROUND_IC: return BATTLEGROUND_QUEUE_IC; case BATTLEGROUND_RB: return BATTLEGROUND_QUEUE_RB; case BATTLEGROUND_AA: case BATTLEGROUND_NA: case BATTLEGROUND_RL: case BATTLEGROUND_BE: case BATTLEGROUND_DS: case BATTLEGROUND_RV: switch (arenaType) { case ARENA_TYPE_2v2: return BATTLEGROUND_QUEUE_2v2; case ARENA_TYPE_3v3: return BATTLEGROUND_QUEUE_3v3; case ARENA_TYPE_5v5: return BATTLEGROUND_QUEUE_5v5; default: return BATTLEGROUND_QUEUE_NONE; } default: return BATTLEGROUND_QUEUE_NONE; } } BattleGroundTypeId BattleGroundMgr::BGTemplateId(BattleGroundQueueTypeId bgQueueTypeId) { switch (bgQueueTypeId) { case BATTLEGROUND_QUEUE_WS: return BATTLEGROUND_WS; case BATTLEGROUND_QUEUE_AB: return BATTLEGROUND_AB; case BATTLEGROUND_QUEUE_AV: return BATTLEGROUND_AV; case BATTLEGROUND_QUEUE_EY: return BATTLEGROUND_EY; case BATTLEGROUND_QUEUE_SA: return BATTLEGROUND_SA; case BATTLEGROUND_QUEUE_IC: return BATTLEGROUND_IC; case BATTLEGROUND_QUEUE_2v2: case BATTLEGROUND_QUEUE_3v3: case BATTLEGROUND_QUEUE_5v5: return BATTLEGROUND_AA; default: return BattleGroundTypeId(0); // used for unknown template (it exist and do nothing) } } ArenaType BattleGroundMgr::BGArenaType(BattleGroundQueueTypeId bgQueueTypeId) { switch (bgQueueTypeId) { case BATTLEGROUND_QUEUE_2v2: return ARENA_TYPE_2v2; case BATTLEGROUND_QUEUE_3v3: return ARENA_TYPE_3v3; case BATTLEGROUND_QUEUE_5v5: return ARENA_TYPE_5v5; default: return ARENA_TYPE_NONE; } } void BattleGroundMgr::ToggleTesting() { m_Testing = !m_Testing; if (m_Testing) { sWorld.SendWorldText(LANG_DEBUG_BG_ON); } else { sWorld.SendWorldText(LANG_DEBUG_BG_OFF); } } void BattleGroundMgr::ToggleArenaTesting() { m_ArenaTesting = !m_ArenaTesting; if (m_ArenaTesting) { sWorld.SendWorldText(LANG_DEBUG_ARENA_ON); } else { sWorld.SendWorldText(LANG_DEBUG_ARENA_OFF); } } void BattleGroundMgr::ScheduleQueueUpdate(uint32 arenaRating, ArenaType arenaType, BattleGroundQueueTypeId bgQueueTypeId, BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id) { // ACE_Guard<ACE_Thread_Mutex> guard(SchedulerLock); // we will use only 1 number created of bgTypeId and bracket_id uint64 schedule_id = ((uint64)arenaRating << 32) | (arenaType << 24) | (bgQueueTypeId << 16) | (bgTypeId << 8) | bracket_id; bool found = false; for (uint8 i = 0; i < m_QueueUpdateScheduler.size(); ++i) { if (m_QueueUpdateScheduler[i] == schedule_id) { found = true; break; } } if (!found) { m_QueueUpdateScheduler.push_back(schedule_id); } } uint32 BattleGroundMgr::GetMaxRatingDifference() const { // this is for stupid people who can't use brain and set max rating difference to 0 uint32 diff = sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE); if (diff == 0) { diff = 5000; } return diff; } uint32 BattleGroundMgr::GetRatingDiscardTimer() const { return sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER); } uint32 BattleGroundMgr::GetPrematureFinishTime() const { return sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMATURE_FINISH_TIMER); } void BattleGroundMgr::LoadBattleMastersEntry() { mBattleMastersMap.clear(); // need for reload case QueryResult* result = WorldDatabase.Query("SELECT `entry`,`bg_template` FROM `battlemaster_entry`"); uint32 count = 0; if (!result) { BarGoLink bar(1); bar.step(); sLog.outString(">> Loaded 0 battlemaster entries - table is empty!"); sLog.outString(); return; } BarGoLink bar(result->GetRowCount()); do { ++count; bar.step(); Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 bgTypeId = fields[1].GetUInt32(); if (!sBattlemasterListStore.LookupEntry(bgTypeId)) { sLog.outErrorDb("Table `battlemaster_entry` contain entry %u for nonexistent battleground type %u, ignored.", entry, bgTypeId); continue; } mBattleMastersMap[entry] = BattleGroundTypeId(bgTypeId); } while (result->NextRow()); delete result; sLog.outString(">> Loaded %u battlemaster entries", count); sLog.outString(); } HolidayIds BattleGroundMgr::BGTypeToWeekendHolidayId(BattleGroundTypeId bgTypeId) { switch (bgTypeId) { case BATTLEGROUND_AV: return HOLIDAY_CALL_TO_ARMS_AV; case BATTLEGROUND_EY: return HOLIDAY_CALL_TO_ARMS_EY; case BATTLEGROUND_WS: return HOLIDAY_CALL_TO_ARMS_WS; case BATTLEGROUND_SA: return HOLIDAY_CALL_TO_ARMS_SA; case BATTLEGROUND_AB: return HOLIDAY_CALL_TO_ARMS_AB; default: return HOLIDAY_NONE; } } BattleGroundTypeId BattleGroundMgr::WeekendHolidayIdToBGType(HolidayIds holiday) { switch (holiday) { case HOLIDAY_CALL_TO_ARMS_AV: return BATTLEGROUND_AV; case HOLIDAY_CALL_TO_ARMS_EY: return BATTLEGROUND_EY; case HOLIDAY_CALL_TO_ARMS_WS: return BATTLEGROUND_WS; case HOLIDAY_CALL_TO_ARMS_SA: return BATTLEGROUND_SA; case HOLIDAY_CALL_TO_ARMS_AB: return BATTLEGROUND_AB; default: return BATTLEGROUND_TYPE_NONE; } } bool BattleGroundMgr::IsBGWeekend(BattleGroundTypeId bgTypeId) { return sGameEventMgr.IsActiveHoliday(BGTypeToWeekendHolidayId(bgTypeId)); } void BattleGroundMgr::LoadBattleEventIndexes() { BattleGroundEventIdx events; events.event1 = BG_EVENT_NONE; events.event2 = BG_EVENT_NONE; m_GameObjectBattleEventIndexMap.clear(); // need for reload case m_GameObjectBattleEventIndexMap[-1] = events; m_CreatureBattleEventIndexMap.clear(); // need for reload case m_CreatureBattleEventIndexMap[-1] = events; uint32 count = 0; QueryResult* result = // 0 1 2 3 4 5 6 WorldDatabase.Query("SELECT `data`.`typ`, `data`.`guid1`, `data`.`ev1` AS `ev1`, `data`.`ev2` AS ev2, `data`.`map` AS m, `data`.`guid2`, `description`.`map`, " // 7 8 9 "`description`.`event1`, `description`.`event2`, `description`.`description` " "FROM " "(SELECT '1' AS typ, `a`.`guid` AS `guid1`, `a`.`event1` AS ev1, `a`.`event2` AS ev2, `b`.`map` AS map, `b`.`guid` AS guid2 " "FROM `gameobject_battleground` AS a " "LEFT OUTER JOIN `gameobject` AS b ON `a`.`guid` = `b`.`guid` " "UNION " "SELECT '2' AS typ, `a`.`guid` AS guid1, `a`.`event1` AS ev1, `a`.`event2` AS ev2, `b`.`map` AS map, `b`.`guid` AS guid2 " "FROM `creature_battleground` AS a " "LEFT OUTER JOIN `creature` AS b ON `a`.`guid` = `b`.`guid` " ") data " "RIGHT OUTER JOIN `battleground_events` AS `description` ON `data`.`map` = `description`.`map` " "AND `data`.`ev1` = `description`.`event1` AND `data`.`ev2` = `description`.`event2` " // full outer join doesn't work in mysql :-/ so just UNION-select the same again and add a left outer join "UNION " "SELECT `data`.`typ`, `data`.`guid1`, `data`.`ev1`, `data`.`ev2`, `data`.`map`, `data`.`guid2`, `description`.`map`, " "`description`.`event1`, `description`.`event2`, `description`.`description` " "FROM " "(SELECT '1' AS typ, `a`.`guid` AS guid1, `a`.`event1` AS ev1, `a`.`event2` AS ev2, `b`.`map` AS map, `b`.`guid` AS guid2 " "FROM `gameobject_battleground` AS a " "LEFT OUTER JOIN `gameobject` AS b ON `a`.`guid` = `b`.`guid` " "UNION " "SELECT '2' AS typ, `a`.`guid` AS guid1, `a`.`event1` AS ev1, `a`.`event2` AS ev2, `b`.`map` AS map, `b`.`guid` AS guid2 " "FROM `creature_battleground` AS a " "LEFT OUTER JOIN `creature` AS b ON `a`.`guid` = `b`.`guid` " ") data " "LEFT OUTER JOIN `battleground_events` AS `description` ON `data`.`map` = `description`.`map` " "AND `data`.`ev1` = `description`.`event1` AND `data`.`ev2` = `description`.`event2` " "ORDER BY `m`, `ev1`, `ev2`"); if (!result) { BarGoLink bar(1); bar.step(); sLog.outErrorDb(">> Loaded 0 battleground eventindexes."); sLog.outString(); return; } BarGoLink bar(result->GetRowCount()); do { bar.step(); Field* fields = result->Fetch(); if (fields[2].GetUInt8() == BG_EVENT_NONE || fields[3].GetUInt8() == BG_EVENT_NONE) { continue; // we don't need to add those to the eventmap } bool gameobject = (fields[0].GetUInt8() == 1); uint32 dbTableGuidLow = fields[1].GetUInt32(); events.event1 = fields[2].GetUInt8(); events.event2 = fields[3].GetUInt8(); uint32 map = fields[4].GetUInt32(); uint32 desc_map = fields[6].GetUInt32(); uint8 desc_event1 = fields[7].GetUInt8(); uint8 desc_event2 = fields[8].GetUInt8(); const char* description = fields[9].GetString(); // checking for NULL - through right outer join this will mean following: if (fields[5].GetUInt32() != dbTableGuidLow) { sLog.outErrorDb("BattleGroundEvent: %s with nonexistent guid %u for event: map:%u, event1:%u, event2:%u (\"%s\")", (gameobject) ? "gameobject" : "creature", dbTableGuidLow, map, events.event1, events.event2, description); continue; } // checking for NULL - through full outer join this can mean 2 things: if (desc_map != map) { // there is an event missing if (dbTableGuidLow == 0) { sLog.outErrorDb("BattleGroundEvent: missing db-data for map:%u, event1:%u, event2:%u (\"%s\")", desc_map, desc_event1, desc_event2, description); continue; } // we have an event which shouldn't exist else { sLog.outErrorDb("BattleGroundEvent: %s with guid %u is registered, for a nonexistent event: map:%u, event1:%u, event2:%u", (gameobject) ? "gameobject" : "creature", dbTableGuidLow, map, events.event1, events.event2); continue; } } if (gameobject) { m_GameObjectBattleEventIndexMap[dbTableGuidLow] = events; } else { m_CreatureBattleEventIndexMap[dbTableGuidLow] = events; } ++count; } while (result->NextRow()); sLog.outString(">> Loaded %u battleground eventindexes", count); sLog.outString(); delete result; }
1
0.805348
1
0.805348
game-dev
MEDIA
0.882313
game-dev
0.830068
1
0.830068
vegapnk/Cumpilation
1,717
1.6/Source/Common/HediffComps/HediffComp_SpawnOtherHediffOverTime.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; namespace Cumpilation.Common { public class HediffComp_SpawnOtherHediffOverTime : HediffComp { public HediffCompProperties_SpawnOtherHediffOverTime Props => (HediffCompProperties_SpawnOtherHediffOverTime)this.props; public override void CompPostTick(ref float severityAdjustment) { base.CompPostTick(ref severityAdjustment); if (this.props == null || parent == null || parent.pawn == null || !parent.pawn.Spawned) return; // See #15, this was missing and Blue Balls would spawn all the time. if (Props.needsOscillationSettingOn && !Settings.EnableOscillationMechanics) return; if (this.props != null && parent.pawn.IsHashIntervalTick(Props.tickInterval) && Props.IsValidPawn(parent.pawn)) { if ((new Random()).NextDouble() <= Props.applicationChance){ Hediff spawnedHediff = parent.pawn.health.hediffSet.GetFirstHediffOfDef(Props.hediff); if (spawnedHediff == null) { BodyPartRecord bpr = Props.tryToSpawnInSameBodyPart ? parent.Part : null; spawnedHediff = HediffMaker.MakeHediff(Props.hediff, parent.pawn, bpr); spawnedHediff.Severity = 0.0f; Pawn.health.AddHediff(spawnedHediff); } spawnedHediff.Severity += Props.scaleWithHediffSeverity ? parent.Severity * Props.severityIncrease : Props.severityIncrease; } } } } }
1
0.91137
1
0.91137
game-dev
MEDIA
0.783515
game-dev
0.821215
1
0.821215
FlyingOakGames/GreedyKid
1,489
GreedyKid_Desktop/GreedyKid_Desktop/Helper/Steamworks.NET/types/SteamTypes/AccountID_t.cs
// This file is provided under The MIT License as part of Steamworks.NET. // Copyright (c) 2013-2022 Riley Labrecque // Please see the included LICENSE.txt for additional information. // This file is automatically generated. // Changes to this file will be reverted when you update Steamworks.NET #if STEAM using System.Runtime.InteropServices; using IntPtr = System.IntPtr; namespace Steamworks { [System.Serializable] public struct AccountID_t : System.IEquatable<AccountID_t>, System.IComparable<AccountID_t> { public uint m_AccountID; public AccountID_t(uint value) { m_AccountID = value; } public override string ToString() { return m_AccountID.ToString(); } public override bool Equals(object other) { return other is AccountID_t && this == (AccountID_t)other; } public override int GetHashCode() { return m_AccountID.GetHashCode(); } public static bool operator ==(AccountID_t x, AccountID_t y) { return x.m_AccountID == y.m_AccountID; } public static bool operator !=(AccountID_t x, AccountID_t y) { return !(x == y); } public static explicit operator AccountID_t(uint value) { return new AccountID_t(value); } public static explicit operator uint(AccountID_t that) { return that.m_AccountID; } public bool Equals(AccountID_t other) { return m_AccountID == other.m_AccountID; } public int CompareTo(AccountID_t other) { return m_AccountID.CompareTo(other.m_AccountID); } } } #endif // STEAM
1
0.860724
1
0.860724
game-dev
MEDIA
0.195831
game-dev
0.873254
1
0.873254
Wynntils/Wynntils-Legacy
14,363
src/main/java/com/wynntils/modules/map/managers/LootRunManager.java
/* * * Copyright © Wynntils - 2018 - 2022. */ package com.wynntils.modules.map.managers; import com.google.gson.*; import com.wynntils.Reference; import com.wynntils.core.framework.rendering.colors.CommonColors; import com.wynntils.core.framework.rendering.colors.CustomColor; import com.wynntils.core.framework.rendering.textures.Textures; import com.wynntils.core.utils.objects.Location; import com.wynntils.core.utils.objects.Pair; import com.wynntils.modules.map.configs.MapConfig; import com.wynntils.modules.map.instances.LootRunNote; import com.wynntils.modules.map.instances.LootRunPath; import com.wynntils.modules.map.instances.PathWaypointProfile; import com.wynntils.modules.map.overlays.objects.MapIcon; import com.wynntils.modules.map.overlays.objects.MapPathWaypointIcon; import com.wynntils.modules.map.rendering.PointRenderer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import org.apache.commons.lang3.ArrayUtils; import java.io.*; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; public class LootRunManager { private static final Gson GSON = new GsonBuilder() .setPrettyPrinting() .registerTypeHierarchyAdapter(Vec3i.class, new BlockPosSerializer()) .registerTypeAdapter(LootRunNote.class, new LootRunNote.LootrunNoteSerializer()) .create(); public static final File STORAGE_FOLDER = new File(Reference.MOD_STORAGE_ROOT, "lootruns"); private final static Map<String, LootRunPath> activePaths = new HashMap<>(); private static LootRunPath latestLootrun = null; private static String latestLootrunName = null; private static LootRunPath recordingPath = null; private static LootRunPath lastRecorded = null; private final static List<PathWaypointProfile> mapPath = new ArrayList<>(); private final static List<CustomColor> pathColors = Arrays.asList( CommonColors.BLUE, CommonColors.GREEN, CommonColors.RED, CommonColors.YELLOW, CommonColors.PURPLE, CommonColors.CYAN, CommonColors.ORANGE, CommonColors.PINK, CommonColors.LIGHT_BLUE, CommonColors.LIGHT_GREEN, CommonColors.LIGHT_GRAY ); public static void setup() { // Make sure lootrun folder exists at startup to simplify for users wanting to import lootruns if (!LootRunManager.STORAGE_FOLDER.exists()) { LootRunManager.STORAGE_FOLDER.mkdirs(); } } public static List<String> getStoredLootruns() { String[] files = STORAGE_FOLDER.list(); if (files == null) return Collections.emptyList(); List<String> result = new ArrayList<>(files.length); for (String file : files) { if (!file.endsWith(".json")) continue; result.add(file.substring(0, file.length() - 5)); } return result; } /** * Returns whether a lootrun can be loaded (Respects case-insensitive file systems) */ public static boolean hasLootrun(String name) { String[] files = STORAGE_FOLDER.list(); if (files == null) return false; File expectedFile = new File(STORAGE_FOLDER, name + ".json"); for (String file : files) { if (new File(STORAGE_FOLDER, file).equals(expectedFile)) return true; } return false; } public static Optional<LootRunPath> loadFromFile(String lootRunName) { File file = new File(STORAGE_FOLDER, lootRunName + ".json"); if (!file.exists()) return Optional.empty(); try { InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); LootRunPath path = GSON.fromJson(reader, LootRunPathIntermediary.class).toPath(); activePaths.put(lootRunName, path); updateMapPath(); reader.close(); latestLootrun = path; latestLootrunName = lootRunName; return Optional.of(path); } catch (Exception ex) { ex.printStackTrace(); return Optional.empty(); } } public static boolean saveToFile(String lootRunName, boolean recording) { try { File file = new File(STORAGE_FOLDER, lootRunName + ".json"); if (!file.exists()) file.createNewFile(); try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { LootRunPathIntermediary intermediary = new LootRunPathIntermediary(recording ? lastRecorded : activePaths.get(lootRunName)); GSON.toJson(intermediary, writer); } } catch (Exception ex) { ex.printStackTrace(); return false; } return true; } public static boolean saveToFile(String lootRunName) { return saveToFile(lootRunName, false); } public static boolean delete(String lootRunName) { try { File f = new File(STORAGE_FOLDER, lootRunName + ".json"); if (!f.exists()) return false; return f.delete(); } catch (Exception ex) { ex.printStackTrace(); return false; } } public static boolean rename(String oldName, String newName) { try { File f = new File(STORAGE_FOLDER, oldName + ".json"); if (!f.exists()) return false; return f.renameTo(new File(STORAGE_FOLDER, newName + ".json")); } catch (Exception ex) { ex.printStackTrace(); return false; } } public static void clear() { activePaths.clear(); recordingPath = null; updateMapPath(); } public static Map<String, LootRunPath> getActivePaths() { return activePaths; } public static LootRunPath getRecordingPath() { return recordingPath; } public static List<MapIcon> getMapPathWaypoints() { if (!mapPath.isEmpty() && MapConfig.LootRun.INSTANCE.displayLootrunOnMap) return mapPath.stream().map(MapPathWaypointIcon::new).collect(Collectors.toList()); else return new ArrayList<>(); } public static boolean isRecording() { return recordingPath != null; } public static void stopRecording() { lastRecorded = recordingPath; recordingPath = null; } public static void startRecording() { recordingPath = new LootRunPath(); } public static void recordMovement(double x, double y, double z) { if (!isRecording()) return; Location to = new Location(x, y + .25d, z); if (recordingPath.isEmpty()) { recordingPath.addPoint(to); return; } if (recordingPath.getLastPoint().distanceSquared(to) < 4d) return; recordingPath.addPoint(to); } public static boolean undoMovement(double x, double y, double z) { if (!isRecording()) return false; Location to = new Location(x, y + .25d, z); List<Location> recordedPoints = recordingPath.getPoints(); List<Location> removed = new ArrayList<>(); boolean pastInitial = false; for (int i = recordedPoints.size() - 1; i >= 0; i--) { if (i == 0) return false; // never found a point to rewind to if (recordedPoints.get(i).distanceSquared(to) < 4d) { if (pastInitial) break; // we've reached the player again } else { if (!pastInitial) pastInitial = true; // we've moved past the end of the path } removed.add(recordedPoints.get(i)); } recordingPath.removePoints(removed); return true; } public static boolean addChest(BlockPos pos) { if (isRecording()) { recordingPath.addChest(pos); return true; } if (!activePaths.isEmpty()) { Optional<Pair<String, LootRunPath>> lastAdded = getLastLootrun(); if (!lastAdded.isPresent()) return false; lastAdded.get().b.addChest(pos); saveToFile(lastAdded.get().a); return true; } return false; } public static boolean removeChest(BlockPos pos) { if (isRecording()) { recordingPath.removeChest(pos); return true; } if (!activePaths.isEmpty()) { Optional<Pair<String, LootRunPath>> lastAdded = getLastLootrun(); if (!lastAdded.isPresent()) return false; lastAdded.get().b.removeChest(pos); saveToFile(lastAdded.get().a); return true; } return false; } public static boolean addNote(LootRunNote note) { if (isRecording()) { recordingPath.addNote(note); return true; } if (!activePaths.isEmpty()) { Optional<Pair<String, LootRunPath>> lastAdded = getLastLootrun(); if (!lastAdded.isPresent()) return false; lastAdded.get().b.addNote(note); saveToFile(lastAdded.get().a); return true; } return false; } public static boolean removeNote(String location) { if (isRecording()) { recordingPath.removeNote(location); return true; } if (!activePaths.isEmpty()) { Optional<Pair<String, LootRunPath>> lastAdded = getLastLootrun(); if (!lastAdded.isPresent()) return false; lastAdded.get().b.removeNote(location); saveToFile(lastAdded.get().a); return true; } return false; } public static Optional<Pair<String, LootRunPath>> getLastLootrun() { if(latestLootrun == null || latestLootrunName == null) return Optional.empty(); return Optional.of(new Pair<>(latestLootrunName, latestLootrun)); } public static void renderActivePaths() { if (!activePaths.isEmpty()) { if (MapConfig.LootRun.INSTANCE.pathType == MapConfig.LootRun.PathType.TEXTURED) { for (LootRunPath path : activePaths.values()) { CustomColor color = getPathColor(path); PointRenderer.drawTexturedLines(Textures.World.path_arrow, path.getRoughPointsByChunk(), path.getRoughDirectionsByChunk(), color, .5f); } } else { for (LootRunPath path : activePaths.values()) { CustomColor color = getPathColor(path); PointRenderer.drawLines(path.getSmoothPointsByChunk(), color); } } activePaths.values().forEach(path -> path.getChests().forEach(c -> PointRenderer.drawCube(c, getPathColor(path)))); if (MapConfig.LootRun.INSTANCE.showNotes) activePaths.values().forEach(path -> path.getNotes().forEach(n -> n.drawNote(getPathColor(path)))); } if (recordingPath != null) { PointRenderer.drawLines(recordingPath.getSmoothPointsByChunk(), MapConfig.LootRun.INSTANCE.recordingPathColour); recordingPath.getChests().forEach(c -> PointRenderer.drawCube(c, MapConfig.LootRun.INSTANCE.recordingPathColour)); recordingPath.getNotes().forEach(n -> n.drawNote(MapConfig.LootRun.INSTANCE.recordingPathColour)); } } private static CustomColor getPathColor(LootRunPath path){ CustomColor defaultColor = MapConfig.LootRun.INSTANCE.rainbowLootRun ? CommonColors.RAINBOW : MapConfig.LootRun.INSTANCE.activePathColour; if (!MapConfig.LootRun.INSTANCE.differentColorsMultipleLootruns || getActivePaths().size() == 1 || MapConfig.LootRun.INSTANCE.rainbowLootRun) return defaultColor; int index = ArrayUtils.indexOf(getActivePaths().values().toArray(), path) % pathColors.size(); return pathColors.get(index); } private static void updateMapPath() { mapPath.clear(); if (!activePaths.isEmpty()) { mapPath.addAll(activePaths.values().stream().map(PathWaypointProfile::new).collect(Collectors.toList())); } } public static void clearLootrun(String name) { activePaths.remove(name); recordingPath = null; updateMapPath(); } public static boolean unloadLootrun(String name) { if(!activePaths.containsKey(name)) { return false; } if(activePaths.get(name) == latestLootrun) latestLootrun = null; activePaths.remove(name); updateMapPath(); return true; } private static class LootRunPathIntermediary { public List<Location> points; public List<BlockPos> chests; public List<LootRunNote> notes; LootRunPathIntermediary(LootRunPath fromPath) { this.points = fromPath.getPoints(); this.chests = new ArrayList<>(fromPath.getChests()); this.notes = new ArrayList<>(fromPath.getNotes()); } LootRunPath toPath() { return new LootRunPath(points, chests, notes); } } private static class BlockPosSerializer implements JsonSerializer<Vec3i>, JsonDeserializer<Vec3i> { private static final String srg_x = "field_177962_a"; private static final String srg_y = "field_177960_b"; private static final String srg_z = "field_177961_c"; @Override public BlockPos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); if (o.has(srg_x)) { return new BlockPos(o.get(srg_x).getAsInt(), o.get(srg_y).getAsInt(), o.get(srg_z).getAsInt()); } return new BlockPos(o.get("x").getAsInt(), o.get("y").getAsInt(), o.get("z").getAsInt()); } @Override public JsonElement serialize(Vec3i src, Type typeOfSrc, JsonSerializationContext context) { JsonObject o = new JsonObject(); o.addProperty("x", src.getX()); o.addProperty("y", src.getY()); o.addProperty("z", src.getZ()); return o; } } }
1
0.958028
1
0.958028
game-dev
MEDIA
0.751815
game-dev
0.993574
1
0.993574
Geant4/geant4
4,710
examples/advanced/human_phantom/src/G4HumanPhantomMessenger.cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // Previous authors: G. Guerrieri, S. Guatelli, and M. G. Pia, INFN Genova, Italy // Authors (since 2007): S. Guatelli, University of Wollongong, Australia // #include "G4HumanPhantomMessenger.hh" #include "G4HumanPhantomConstruction.hh" #include "G4UIdirectory.hh" #include "G4UIcmdWithAString.hh" #include "G4UIcmdWithoutParameter.hh" #include "globals.hh" #include "G4RunManager.hh" G4HumanPhantomMessenger::G4HumanPhantomMessenger(G4HumanPhantomConstruction* myUsrPhtm) :fUserPhantom(myUsrPhtm),fBps(false) { fPhantomDir = new G4UIdirectory("/phantom/"); fPhantomDir->SetGuidance("Set Your Phantom."); fDir = new G4UIdirectory("/bodypart/"); fDir->SetGuidance("Add Body Part to Phantom"); fModelCmd = new G4UIcmdWithAString("/phantom/setPhantomModel",this); fModelCmd->SetGuidance("Set sex of Phantom: MIRD, ORNLFemale, ORNLMale, MIX, MIRDHead, ORNLHead."); fModelCmd->SetParameterName("phantomModel",true); fModelCmd->SetDefaultValue("MIRD"); fModelCmd->SetCandidates("MIRD ORNLFemale ORNLMale MIRDHead ORNLHead"); fModelCmd->AvailableForStates(G4State_PreInit,G4State_Idle); fSexCmd = new G4UIcmdWithAString("/phantom/setPhantomSex",this); fSexCmd->SetGuidance("Set sex of Phantom: Male or Female."); fSexCmd->SetParameterName("phantomSex",true); fSexCmd->SetDefaultValue("Female"); fSexCmd->SetCandidates("Male Female"); fSexCmd->AvailableForStates(G4State_PreInit,G4State_Idle); fBodypartCmd = new G4UIcmdWithAString("/bodypart/addBodyPart",this); fBodypartCmd->SetGuidance("Add a Body Part to Phantom"); fBodypartCmd->SetParameterName("bpName",true); fBodypartCmd->AvailableForStates(G4State_PreInit,G4State_Idle); fEndCmd = new G4UIcmdWithoutParameter("/phantom/buildNewPhantom",this); fEndCmd->SetGuidance("Build your Phantom."); fEndCmd->AvailableForStates(G4State_PreInit,G4State_Idle); } G4HumanPhantomMessenger::~G4HumanPhantomMessenger() { delete fModelCmd; delete fSexCmd; delete fBodypartCmd; delete fEndCmd; delete fPhantomDir; delete fDir; } void G4HumanPhantomMessenger::SetNewValue(G4UIcommand* command,G4String newValue){ if( command == fModelCmd ) { fUserPhantom->SetPhantomModel(newValue); } if( command == fSexCmd ) { fUserPhantom->SetPhantomSex(newValue); } if( command == fBodypartCmd ) { AddBodyPart(newValue); } if( command == fEndCmd ) { G4cout << " ****************>>>> NEW PHANTOM CONSTRUCTION <<<<***************** " << G4endl; } } void G4HumanPhantomMessenger::AddBodyPart(G4String newBodyPartSensitivity) { char* str = new char[newBodyPartSensitivity.length()+1]; strcpy(str, newBodyPartSensitivity.c_str()); std::string bpart = strtok(str," "); std::string sensitivity = strtok(nullptr," "); if(sensitivity=="yes"){ fBps=true; }else{ fBps=false; } G4cout << " >>> Body Part = " << bpart << "\n" << " >>> Sensitivity = " << sensitivity << G4endl; fUserPhantom->SetBodyPartSensitivity(bpart,fBps); }
1
0.9325
1
0.9325
game-dev
MEDIA
0.736867
game-dev
0.710064
1
0.710064
Fluorohydride/ygopro-scripts
1,093
c1003028.lua
--トラブル・ダイバー function c1003028.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,1003028+EFFECT_COUNT_CODE_OATH) e1:SetCondition(c1003028.spcon) c:RegisterEffect(e1) --xyzlimit local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_XYZ_MATERIAL) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e2:SetValue(c1003028.xyzlimit) c:RegisterEffect(e2) end function c1003028.cfilter(c) return c:IsFaceup() and not c:IsLevel(4) end function c1003028.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)>0 and Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0 and not Duel.IsExistingMatchingCard(c1003028.cfilter,tp,LOCATION_MZONE,0,1,nil) end function c1003028.xyzlimit(e,c) if not c then return false end return not c:IsRace(RACE_WARRIOR) end
1
0.903704
1
0.903704
game-dev
MEDIA
0.967068
game-dev
0.531386
1
0.531386
jaykrow/pvz2-experimental
5,815
SixLaneAmbushFix.cpp
#include "pch.h" #include "SixLaneAmbushFix.h" #include "memUtils.h" #include "PvZ2/Board.h" #include "PvZ2/RtWeakPtr.h" typedef int (*addZombieByTypeType)(Board*, int, int, int, int); addZombieByTypeType addZombieByType = NULL; typedef void (*spawnAmbushBeach)(int, int, int, int*); spawnAmbushBeach oSpawnAmbushBeach = NULL; void hkSpawnAmbushBeach(int beachEventSpawner, int amount, int a3, int a4) { int propSheet = getWeakPtr(beachEventSpawner + 0x10); typedef int (*getZombieTypeDirectoryInstance)(); int typeDir = ((getZombieTypeDirectoryInstance)getActualOffset(0x28FE30))(); SexyString a1; typedef int* (*subEBFC8C)(SexyString*, int); ((subEBFC8C)getActualOffset(0xEBFC8C))(&a1, propSheet); typedef void (*getZombieType)(RtWeakPtr<int>*, int, std::string*); RtWeakPtr<int> zType; ((getZombieType)getActualOffset(0x28FE9C))(&zType, typeDir, &a1); int totalSpawns = *(int*)(propSheet + 0x38); int amountSpawned = *(int*)(beachEventSpawner + 0x2C); amount = std::min(amount, totalSpawns - amountSpawned); if (amount == 0) { return; } // LOGI("we want to spawn %d more total = %d spawned = %d", amount, totalSpawns, amountSpawned); for (int i = 0; i < amount; ++i) { Board* board = getBoard(); int rowCount = board->m_rowCount; int zombie = addZombieByType(board, (int)&zType, a3, 6, -1); typedef void (*sub8BC738)(int, int); ((sub8BC738)getActualOffset(0x8BC738))(zombie, 0); typedef int (*zombieSetLoot)(int, int); ((zombieSetLoot)getActualOffset(0x8BC728))(zombie, *(int*)(*(int*)(beachEventSpawner + 0x18) + 4 * i)); // this is a vector of loots //LOGI("loot set"); int animRig = getWeakPtr(zombie + 0x80); typedef int(*setLayerVisible)(int, SexyString*, bool); SexyString seaweed = "zombie_seaweed1"; ((setLayerVisible)getActualOffset(0x667590))(animRig, &seaweed, true); //LOGI("got past set layer visible"); int colStart = *(int*)(propSheet + 0x44); int colEnd = *(int*)(propSheet + 0x48); if (colEnd > colStart) { typedef int (*sub112D0BC)(int, int); colStart += ((sub112D0BC)getActualOffset(0x112D0BC))(a4, colEnd - colStart); } int nextRowToSpawn = *(int*)(beachEventSpawner + 0x30); *(int*)(beachEventSpawner + 0x30) = (nextRowToSpawn + 0x11) % rowCount; // I REMADE THIS JUST TO FIX THIS //LOGI("got next row to spawn"); SexyVector3 loc = SexyVector3(colStart * 64 + 0xE8, nextRowToSpawn * 76 + 0xDE, 600.0); typedef void (*zombieFun57)(int, SexyVector3*, int); (*(zombieFun57*)(*(uint*)zombie + 0xE4))(zombie, &loc, 1); ++amountSpawned; *(int*)(beachEventSpawner + 0x2C) = amountSpawned; } } typedef void (*zombieRainSpawnerSpawnAmbush)(int, int, int, int*); zombieRainSpawnerSpawnAmbush oZombieRainSpawnerSpawnAmbush = NULL; void hkZombieRainSpawnerSpawnAmbush(int zombieRainSpawner, int amount, int a3, int a4) { int propSheet = getWeakPtr(zombieRainSpawner + 0x10); typedef int (*getZombieTypeDirectoryInstance)(); int typeDir = ((getZombieTypeDirectoryInstance)getActualOffset(0x28FE30))(); SexyString a1; typedef int* (*sub291E5C)(SexyString*, int); ((sub291E5C)getActualOffset(0x291E5C))(&a1, propSheet); typedef void (*getZombieType)(RtWeakPtr<int>*, int, std::string*); RtWeakPtr<int> zType; ((getZombieType)getActualOffset(0x28FE9C))(&zType, typeDir, &a1); int totalSpawns = *(int*)(propSheet + 0x38); int amountSpawned = *(int*)(zombieRainSpawner + 0x2C); amount = std::min(amount, totalSpawns - amountSpawned); if (amount == 0) { return; } int rowCount = getBoard()->m_rowCount; for (int i = 0; i < amount; ++i) { typedef int (*spawnZombieFunc)(int, RtWeakPtr<int>*, int, int); int zombie = ((spawnZombieFunc)getActualOffset(0x28EDD0))(0, &zType, a3, 6); // LOGI("spawned zombie func"); typedef void (*sub8BC738)(int, int); ((sub8BC738)getActualOffset(0x8BC738))(zombie, 0); typedef int (*zombieSetLoot)(int, int); ((zombieSetLoot)getActualOffset(0x8BC728))(zombie, *(int*)(*(int*)(zombieRainSpawner + 0x18) + 4 * i)); // this is a vector of loots // LOGI("Spawn zombie so far and set loot"); int colStart = *(int*)(propSheet + 0x48); int colEnd = *(int*)(propSheet + 0x4C); typedef int (*sub112D0BC)(int, int); colStart += ((sub112D0BC)getActualOffset(0x112D0BC))(a4, colEnd - colStart); int nextRowToSpawn = *(int*)(zombieRainSpawner + 0x30); *(int*)(zombieRainSpawner + 0x30) = (nextRowToSpawn + 1) % rowCount; SexyVector3 loc = SexyVector3(colStart * 64 + 0xE8 - 10.0, nextRowToSpawn * 76 + 0xDE - 10.0, 600.0); // LOGI("location decided"); typedef void (*setPosition)(int, SexyVector3*); ((setPosition)getActualOffset(0x2D850C))(zombie, &loc); // LOGI("set position"); typedef void (*someFunc)(int, int, float, float, int, int, int); someFunc fun = *(someFunc*)(*(uint*)zombieRainSpawner + 0x58); int zombieFallTime = *(int*)(propSheet + 0x44); fun(zombieRainSpawner, zombie, loc.mX, loc.mY, 0, zombieFallTime, 0x44160000); // LOGI("set dropdown"); ++amountSpawned; *(int*)(zombieRainSpawner + 0x2C) = amountSpawned; } } void initSixLaneAmbushFix() { addZombieByType = (addZombieByTypeType)getActualOffset(0x72B4D8); PVZ2HookFunction(0xEBF84C, (void*)hkSpawnAmbushBeach, (void**)&oSpawnAmbushBeach, "SpawnAmbushBeach"); PVZ2HookFunction(0x29184C, (void*)hkZombieRainSpawnerSpawnAmbush, (void**)&oZombieRainSpawnerSpawnAmbush, "ZombieRainSpawner::SpawnAmbush"); }
1
0.534469
1
0.534469
game-dev
MEDIA
0.935803
game-dev
0.722589
1
0.722589
ourcade/ecs-dependency-injection
2,785
src/container.ts
import { createContainer } from 'brandi' import * as Token from './tokens' import { gameUpdateCreator, createECSWorld, indexToTexture, createBricks, Texture, textureToIndex, createPaddle, createBall, createWalls, createLauncher, createPhysicsEngine, startGame, } from './game' import { registerInjections } from './injections' import { KeyboardService, GlobalState } from './game/services' export const container = createContainer() export function createChildContainer() { return createContainer().extend(container) } registerInjections() container.bind(Token.Root).toConstant(container) container.bind(Token.GameConfig).toConstant({ world: { width: 960, height: 540, }, brick: { width: 64, height: 32, }, ball: { width: 24, height: 24, }, paddle: { width: 100, height: 24, }, }) // assets container.bind(Token.AssetsData).toConstant({ ball: { key: Texture.ball, path: 'assets/ball.png', }, paddle: { key: Texture.paddle, path: 'assets/paddle.png', }, brick: { key: Texture.brick, path: 'assets/brick.png', }, logo: { phaser: { path: 'assets/logos/phaser.png', }, pixi: { path: 'assets/logos/pixi.png', }, react: { path: 'assets/logos/react.png', }, three: { path: 'assets/logos/three.png', }, }, }) container.bind(Token.IndexToTextureKey).toConstant(indexToTexture) container.bind(Token.TextureKeyToIndex).toConstant(textureToIndex) // input container.bind(Token.Keyboard).toInstance(KeyboardService).inSingletonScope() // game // 0 - nothing, 1 - red, 2 - green, 3 - blue, 4 - purple, 5 - yellow, 6 - white const layout = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 6, 3, 3, 3, 3, 0, 0, 0], [0, 0, 0, 2, 2, 2, 1, 6, 3, 5, 5, 5, 0, 0, 0], [0, 0, 0, 3, 3, 3, 1, 6, 3, 4, 4, 4, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 6, 3, 3, 3, 3, 0, 0, 0], ] container.bind(Token.BricksLayout).toConstant(layout) container.bind(Token.GlobalState).toInstance(GlobalState).inContainerScope() container.bind(Token.ECSWorld).toInstance(createECSWorld).inContainerScope() container .bind(Token.GameUpdate) .toInstance(gameUpdateCreator) .inTransientScope() container.bind(Token.CreateBricks).toInstance(createBricks).inTransientScope() container.bind(Token.CreatePaddle).toInstance(createPaddle).inTransientScope() container.bind(Token.CreateBall).toInstance(createBall).inTransientScope() container.bind(Token.CreateWalls).toInstance(createWalls).inTransientScope() container .bind(Token.CreateLauncher) .toInstance(createLauncher) .inTransientScope() container.bind(Token.StartGame).toInstance(startGame).inTransientScope() // physics container .bind(Token.PhysicsEngine) .toInstance(createPhysicsEngine) .inContainerScope()
1
0.744168
1
0.744168
game-dev
MEDIA
0.576854
game-dev
0.693287
1
0.693287
MeridiusIX/Modular-Encounters-Systems
7,799
Data/Scripts/ModularEncountersSystems/Configuration/ConfigRandomEncounters.cs
using ModularEncountersSystems.Configuration.Editor; using ModularEncountersSystems.Core; using ModularEncountersSystems.Logging; using Sandbox.ModAPI; using System; using System.Collections.Generic; using System.Xml.Serialization; namespace ModularEncountersSystems.Configuration { /* Hello Stranger! If you are in here because you want to change settings for how this mod behaves, you are in the wrong place. All the settings in this file, along with the other configuration files, are created as XML files in the \Storage\1521905890.sbm_ModularEncountersSpawner folder of your Save File. This means you do not need to edit the mod files here to tune the settings to your liking. The workshop page for this mod also has a link to a guide that explains what all the configuration options do, along with how to activate them in-game via chat commands if desired. If you plan to edit the values here anyway, I ask that you do not reupload this mod to the Steam Workshop. If this is not respected and I find out about it, I'll exercise my rights as the creator and file a DMCA takedown on any infringing copies. This warning can be found on the workshop page for this mod as well. Thank you. */ public class ConfigRandomEncounters : ConfigBase, IGridSpawn { public string ModVersion; public bool EnableSpawns; public int PlayerSpawnCooldown; public int SpawnTimerTrigger; public double PlayerTravelDistance; public int MaxShipsPerArea; public double AreaSize; public double MinSpawnDistanceFromPlayer; public double MaxSpawnDistanceFromPlayer; public double MinDistanceFromOtherEntities; public bool RemoveVoxelsIfGridRemoved; public int SpawnAttempts; public bool UseMaxSpawnGroupFrequency; public int MaxSpawnGroupFrequency; public double DespawnDistanceFromPlayer; [XmlIgnore] public Dictionary<string, Func<string, object, bool>> EditorReference; public ConfigRandomEncounters(){ ModVersion = MES_SessionCore.ModVersion; EnableSpawns = true; PlayerSpawnCooldown = 300; SpawnTimerTrigger = 60; PlayerTravelDistance = 15000; MaxShipsPerArea = 10; AreaSize = 25000; MinSpawnDistanceFromPlayer = 8000; MaxSpawnDistanceFromPlayer = 12000; MinDistanceFromOtherEntities = 3000; RemoveVoxelsIfGridRemoved = true; SpawnAttempts = 10; UseMaxSpawnGroupFrequency = false; MaxSpawnGroupFrequency = 5; DespawnDistanceFromPlayer = 1000; UseTimeout = true; TimeoutDuration = 900; TimeoutRadius = 25000; TimeoutSpawnLimit = 2; UseCleanupSettings = true; CleanupUseDistance = true; CleanupUseTimer = true; CleanupUseBlockLimit = false; CleanupDistanceStartsTimer = true; CleanupResetTimerWithinDistance = false; CleanupDistanceTrigger = 50000; CleanupTimerTrigger = 3600; CleanupBlockLimitTrigger = 0; CleanupIncludeUnowned = true; CleanupUnpoweredOverride = false; CleanupUnpoweredDistanceTrigger = 25000; CleanupUnpoweredTimerTrigger = 900; EditorReference = new Dictionary<string, Func<string, object, bool>> { {"EnableSpawns", (s, o) => EditorTools.SetCommandValueBool(s, ref EnableSpawns) }, {"PlayerSpawnCooldown", (s, o) => EditorTools.SetCommandValueInt(s, ref PlayerSpawnCooldown) }, {"SpawnTimerTrigger", (s, o) => EditorTools.SetCommandValueInt(s, ref SpawnTimerTrigger) }, {"PlayerTravelDistance", (s, o) => EditorTools.SetCommandValueDouble(s, ref PlayerTravelDistance) }, {"MaxShipsPerArea", (s, o) => EditorTools.SetCommandValueInt(s, ref MaxShipsPerArea) }, {"AreaSize", (s, o) => EditorTools.SetCommandValueDouble(s, ref AreaSize) }, {"MinSpawnDistanceFromPlayer", (s, o) => EditorTools.SetCommandValueDouble(s, ref MinSpawnDistanceFromPlayer) }, {"MaxSpawnDistanceFromPlayer", (s, o) => EditorTools.SetCommandValueDouble(s, ref MaxSpawnDistanceFromPlayer) }, {"MinDistanceFromOtherEntities", (s, o) => EditorTools.SetCommandValueDouble(s, ref MinDistanceFromOtherEntities) }, {"RemoveVoxelsIfGridRemoved", (s, o) => EditorTools.SetCommandValueBool(s, ref RemoveVoxelsIfGridRemoved) }, {"SpawnAttempts", (s, o) => EditorTools.SetCommandValueInt(s, ref SpawnAttempts) }, {"UseMaxSpawnGroupFrequency", (s, o) => EditorTools.SetCommandValueBool(s, ref UseMaxSpawnGroupFrequency) }, {"MaxSpawnGroupFrequency", (s, o) => EditorTools.SetCommandValueInt(s, ref MaxSpawnGroupFrequency) }, {"DespawnDistanceFromPlayer", (s, o) => EditorTools.SetCommandValueDouble(s, ref DespawnDistanceFromPlayer) }, }; } public ConfigRandomEncounters LoadSettings(string phase) { if(MyAPIGateway.Utilities.FileExistsInWorldStorage("Config-RandomEncounters.xml", typeof(ConfigRandomEncounters)) == true){ try{ ConfigRandomEncounters config = null; var reader = MyAPIGateway.Utilities.ReadFileInWorldStorage("Config-RandomEncounters.xml", typeof(ConfigRandomEncounters)); string configcontents = reader.ReadToEnd(); config = MyAPIGateway.Utilities.SerializeFromXML<ConfigRandomEncounters>(configcontents); config.ConfigLoaded = true; SpawnLogger.Write("Loaded Existing Settings From Config-RandomEncounters.xml. Phase: " + phase, SpawnerDebugEnum.Startup, true); return config; }catch(Exception exc){ SpawnLogger.Write("ERROR: Could Not Load Settings From Config-RandomEncounters.xml. Using Default Configuration. Phase: " + phase, SpawnerDebugEnum.Error, true); var defaultSettings = new ConfigRandomEncounters(); return defaultSettings; } } else { SpawnLogger.Write("Config-RandomEncounters.xml Doesn't Exist. Creating Default Configuration. Phase: " + phase, SpawnerDebugEnum.Startup, true); } var settings = new ConfigRandomEncounters(); try{ using (var writer = MyAPIGateway.Utilities.WriteFileInWorldStorage("Config-RandomEncounters.xml", typeof(ConfigRandomEncounters))){ writer.Write(MyAPIGateway.Utilities.SerializeToXML<ConfigRandomEncounters>(settings)); } }catch(Exception exc){ SpawnLogger.Write("ERROR: Could Not Create Config-RandomEncounters.xml. Default Settings Will Be Used. Phase: " + phase, SpawnerDebugEnum.Error, true); } return settings; } public override string SaveSettings(){ try{ using (var writer = MyAPIGateway.Utilities.WriteFileInWorldStorage("Config-RandomEncounters.xml", typeof(ConfigRandomEncounters))){ writer.Write(MyAPIGateway.Utilities.SerializeToXML<ConfigRandomEncounters>(this)); } SpawnLogger.Write("Settings In Config-RandomEncounters.xml Updated Successfully!", SpawnerDebugEnum.Settings); return "Settings Updated Successfully."; }catch(Exception exc){ SpawnLogger.Write("ERROR: Could Not Save To Config-RandomEncounters.xml. Changes Will Be Lost On World Reload.", SpawnerDebugEnum.Settings); } return "Settings Changed, But Could Not Be Saved To XML. Changes May Be Lost On Session Reload."; } public string EditFields(string receivedCommand) { var commandSplit = receivedCommand.Split('.'); if (commandSplit.Length < 5) return "Provided Command Missing Parameters."; Func<string, object, bool> referenceMethod = null; if (!EditorReference.TryGetValue(commandSplit[3], out referenceMethod)) if (!EditorBaseReference.TryGetValue(commandSplit[3], out referenceMethod)) return "Provided Field [" + commandSplit[3] + "] Does Not Exist."; if (!referenceMethod?.Invoke(receivedCommand, null) ?? false) return "Provided Value For [" + commandSplit[3] + "] Could Not Be Parsed."; InitDefinitionDisableList(); return SaveSettings(); } } }
1
0.889301
1
0.889301
game-dev
MEDIA
0.783111
game-dev
0.826787
1
0.826787
andreasdr/tdme2
4,549
src/tdme/tools/editor/controllers/DraggingScreenController.cpp
#include <tdme/tools/editor/controllers/DraggingScreenController.h> #include <memory> #include <string> #include <agui/agui.h> #include <agui/gui/elements/GUIMoveableController.h> #include <agui/gui/nodes/GUINode.h> #include <agui/gui/nodes/GUINode_RequestedConstraints.h> #include <agui/gui/nodes/GUINode_RequestedConstraints_RequestedConstraintsType.h> #include <agui/gui/nodes/GUIParentNode.h> #include <agui/gui/nodes/GUIScreenNode.h> #include <agui/gui/GUI.h> #include <agui/gui/GUIParser.h> #include <agui/utilities/MutableString.h> #include <tdme/tdme.h> #include <tdme/engine/Engine.h> #include <tdme/math/Math.h> #include <tdme/utilities/Action.h> #include <tdme/utilities/Console.h> #include <tdme/utilities/Exception.h> #include <tdme/utilities/StringTools.h> using tdme::tools::editor::controllers::DraggingScreenController; using std::string; using std::to_string; using std::unique_ptr; using std::unordered_map; using agui::gui::elements::GUIMoveableController; using agui::gui::events::GUIActionListenerType; using agui::gui::nodes::GUIElementNode; using agui::gui::nodes::GUINode; using agui::gui::nodes::GUINode_RequestedConstraints; using agui::gui::nodes::GUINode_RequestedConstraints_RequestedConstraintsType; using agui::gui::nodes::GUIParentNode; using agui::gui::nodes::GUIScreenNode; using agui::gui::GUIParser; using agui::utilities::MutableString; using tdme::engine::Engine; using tdme::math::Math; using tdme::utilities::Action; using tdme::utilities::Console; using tdme::utilities::Exception; using tdme::utilities::StringTools; DraggingScreenController::DraggingScreenController() { } DraggingScreenController::~DraggingScreenController() { screenNode = nullptr; } GUIScreenNode* DraggingScreenController::getScreenNode() { return screenNode; } void DraggingScreenController::initialize() { try { screenNode = GUIParser::parse("resources/engine/gui", "popup_dragging.xml"); screenNode->addMoveListener(this); screenNode->setEnabled(false); draggableNode = required_dynamic_cast<GUIParentNode*>(screenNode->getNodeById("draggable")); } catch (Exception& exception) { Console::printLine("DraggingScreenController::initialize(): An error occurred: " + string(exception.what())); } } void DraggingScreenController::dispose() { } bool DraggingScreenController::accept(GUINode* node) { return true; } void DraggingScreenController::onMove(GUINode* node) { } void DraggingScreenController::onRelease(GUINode* node, int mouseX, int mouseY) { dragReleaseMouseX = mouseX; dragReleaseMouseY = mouseY; close(); if (onReleaseAction != nullptr) { onReleaseAction->performAction(); onReleaseAction = nullptr; } } void DraggingScreenController::start(int mouseX, int mouseY, const string& xml, const string& payload, Action* onReleaseAction) { this->payload = payload; this->onReleaseAction = unique_ptr<Action>(onReleaseAction); dragReleaseMouseX = -1; dragReleaseMouseY = -1; // try { draggableNode->replaceSubNodes(xml, true); } catch (Exception& exception) { Console::printLine("DraggingScreenController::start(): An error occurred: " + string(exception.what())); } auto scaledMouseX = Engine::getInstance()->getGUI()->getScaledX(screenNode, mouseX); auto scaledMouseY = Engine::getInstance()->getGUI()->getScaledY(screenNode, mouseY); auto scaledX = Engine::getInstance()->getGUI()->getScaledX(screenNode, mouseX - draggableNode->getContentWidth() / 2); auto scaledY = Engine::getInstance()->getGUI()->getScaledY(screenNode, mouseY - draggableNode->getContentHeight() / 2); scaledX = Math::min(scaledX, screenNode->getScreenWidth() - draggableNode->getContentWidth()); scaledY = Math::min(scaledY, screenNode->getScreenHeight() - draggableNode->getContentHeight()); draggableNode->getRequestsConstraints().leftType = GUINode_RequestedConstraints_RequestedConstraintsType::PIXEL; draggableNode->getRequestsConstraints().left = scaledX; draggableNode->getRequestsConstraints().topType = GUINode_RequestedConstraints_RequestedConstraintsType::PIXEL; draggableNode->getRequestsConstraints().top = scaledY; screenNode->setEnabled(true); screenNode->layout(); // Engine::getInstance()->getGUI()->startMouseDragging(draggableNode); // try { ((GUIMoveableController*)(draggableNode->getController()))->startMoving(scaledMouseX, scaledMouseY); } catch (Exception& exception) { Console::printLine("DraggingScreenController::start(): An error occurred: " + string(exception.what())); } } void DraggingScreenController::close() { screenNode->setEnabled(false); }
1
0.85697
1
0.85697
game-dev
MEDIA
0.570413
game-dev,desktop-app
0.717957
1
0.717957
FoxMCTeam/TenacityRecode-master
1,719
src/java/net/minecraft/client/player/inventory/ContainerLocalMenu.java
package net.minecraft.client.player.inventory; import com.google.common.collect.Maps; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.InventoryBasic; import net.minecraft.util.IChatComponent; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; import java.util.Map; public class ContainerLocalMenu extends InventoryBasic implements ILockableContainer { private String guiID; private Map<Integer, Integer> field_174895_b = Maps.<Integer, Integer>newHashMap(); public boolean realChest; public ContainerLocalMenu(String id, IChatComponent title, int slotCount) { super(title, slotCount); this.realChest = title.toString().contains("container.chest"); this.guiID = id; } public int getField(int id) { return this.field_174895_b.containsKey(Integer.valueOf(id)) ? ((Integer)this.field_174895_b.get(Integer.valueOf(id))).intValue() : 0; } public void setField(int id, int value) { this.field_174895_b.put(Integer.valueOf(id), Integer.valueOf(value)); } public int getFieldCount() { return this.field_174895_b.size(); } public boolean isLocked() { return false; } public void setLockCode(LockCode code) { } public LockCode getLockCode() { return LockCode.EMPTY_CODE; } public String getGuiID() { return this.guiID; } public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) { throw new UnsupportedOperationException(); } }
1
0.684765
1
0.684765
game-dev
MEDIA
0.991008
game-dev
0.880402
1
0.880402
glinscott/Garbochess-JS
75,632
archived/garbochess-071210-01.js
"use strict"; // Perf TODO: // Merge material updating with psq values // Put move scoring inline in generator // Remove need for fliptable in psq tables. Access them by color // Optimize pawn move generation // Non-perf todo: // Checks in first q? // Pawn eval. // Better king evaluation // Better move sorting in PV nodes (especially root) var g_debug = true; var g_timeout = 40; function GetFen(){ var result = ""; for (row = 0; row < 8; row++) { if (row != 0) result += '/'; var empty = 0; for (col = 0; col < 8; col++) { var piece = g_board[((row + 2) << 4) + col + 4]; if (piece == 0) { empty++; } else { if (empty != 0) result += empty; empty = 0; var pieceChar = [" ", "p", "n", "b", "r", "q", "k", " "][(piece & 0x7)]; result += ((piece & colorWhite) != 0) ? pieceChar.toUpperCase() : pieceChar; } } if (empty != 0) { result += empty; } } result += g_toMove == colorWhite ? " w" : " b"; result += " "; if (g_castleRights == 0) { result += "-"; } else { if ((g_castleRights & 1) != 0) result += "K"; if ((g_castleRights & 2) != 0) result += "Q"; if ((g_castleRights & 4) != 0) result += "k"; if ((g_castleRights & 8) != 0) result += "q"; } result += " "; if (g_enPassentSquare == -1) { result += '-'; } else { result += FormatSquare(g_enPassentSquare); } return result; } function GetMoveSAN(move, validMoves) { var from = move & 0xFF; var to = (move >> 8) & 0xFF; if (move & moveflagCastleKing) return "O-O"; if (move & moveflagCastleQueen) return "O-O-O"; var pieceType = g_board[from] & 0x7; var result = ["", "", "N", "B", "R", "Q", "K", ""][pieceType]; var dupe = false, rowDiff = true, colDiff = true; if (validMoves == null) { validMoves = GenerateValidMoves(); } for (var i = 0; i < validMoves.length; i++) { var moveFrom = validMoves[i] & 0xFF; var moveTo = (validMoves[i] >> 8) & 0xFF; if (moveFrom != from && moveTo == to && (g_board[moveFrom] & 0x7) == pieceType) { dupe = true; if ((moveFrom & 0xF0) == (from & 0xF0)) { rowDiff = false; } if ((moveFrom & 0x0F) == (from & 0x0F)) { colDiff = false; } } } if (dupe) { if (colDiff) { result += FormatSquare(from).charAt(0); } else if (rowDiff) { result += FormatSquare(from).charAt(1); } else { result += FormatSquare(from); } } else if (pieceType == piecePawn && g_board[to] != 0) { result += FormatSquare(from).charAt(0); } if (g_board[to] != 0 || (move & moveflagEPC)) { result += "x"; } result += FormatSquare(to); if (move & moveflagPromotion) { if (move & moveflagPromoteBishop) result += "=B"; else if (move & moveflagPromoteKnight) result += "=N"; else if (move & moveflagPromoteQueen) result += "=Q"; else result += "=R"; } MakeMove(move); if (g_inCheck) { result += GenerateValidMoves().length == 0 ? "#" : "+"; } UnmakeMove(move); return result; } function FormatSquare(square) { var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; return letters[(square & 0xF) - 4] + ((9 - (square >> 4)) + 1); } function FormatMove(move) { var result = FormatSquare(move & 0xFF) + FormatSquare((move >> 8) & 0xFF); if (move & moveflagPromotion) { if (move & moveflagPromoteBishop) result += "b"; else if (move & moveflagPromoteKnight) result += "n"; else if (move & moveflagPromoteQueen) result += "q"; else result += "r"; } return result; } function GetMoveFromString(moveString) { var moves = GenerateValidMoves(); for (var i = 0; i < moves.length; i++) { if (FormatMove(moves[i]) == moveString) { return moves[i]; } } alert("busted! ->" + moveString + " fen:" + GetFen()); } function PVFromHash(move, ply) { if (ply == 0) return ""; var pvString = " " + GetMoveSAN(move); MakeMove(move); var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode != null && hashNode.lock == g_hashKeyHigh && hashNode.bestMove != null) { pvString += PVFromHash(hashNode.bestMove, ply - 1); } UnmakeMove(move); return pvString; } // // Searching code // var g_startTime; var g_nodeCount; var g_qNodeCount; var g_searchValid; var g_globalPly = 0; function Search(finishMoveCallback, maxPly) { var lastEval; var alpha = minEval; var beta = maxEval; g_globalPly++; g_nodeCount = 0; g_qNodeCount = 0; g_collisions = 0; g_searchValid = true; var bestMove; var value; g_startTime = (new Date()).getTime(); var i; for (i = 1; i <= maxPly && g_searchValid; i++) { var tmp = AlphaBeta(i, 0, alpha, beta); if (!g_searchValid) break; value = tmp; if (value > alpha && value < beta) { alpha = value - 500; beta = value + 500; } else if (alpha != minEval) { alpha = minEval; beta = maxEval; i--; continue; } if (g_hashTable[g_hashKeyLow & g_hashMask] != null) { bestMove = g_hashTable[g_hashKeyLow & g_hashMask].bestMove; } } finishMoveCallback(bestMove, value, (new Date()).getTime() - g_startTime, i - 1); } var minEval = -2000000; var maxEval = +2000000; var minMateBuffer = minEval + 2000; var maxMateBuffer = maxEval - 2000; var materialTable = [0, 800, 3350, 3450, 5000, 9750, 600000]; var pawnAdj = [ 0, 0, 0, 0, 0, 0, 0, 0, -25, 105, 135, 270, 270, 135, 105, -25, -80, 0, 30, 176, 176, 30, 0, -80, -85, -5, 25, 175, 175, 25, -5, -85, -90, -10, 20, 125, 125, 20, -10, -90, -95, -15, 15, 75, 75, 15, -15, -95, -100, -20, 10, 70, 70, 10, -20, -100, 0, 0, 0, 0, 0, 0, 0, 0 ]; var knightAdj = [-200, -100, -50, -50, -50, -50, -100, -200, -100, 0, 0, 0, 0, 0, 0, -100, -50, 0, 60, 60, 60, 60, 0, -50, -50, 0, 30, 60, 60, 30, 0, -50, -50, 0, 30, 60, 60, 30, 0, -50, -50, 0, 30, 30, 30, 30, 0, -50, -100, 0, 0, 0, 0, 0, 0, -100, -200, -50, -25, -25, -25, -25, -50, -200 ]; var bishopAdj = [ -50,-50,-25,-10,-10,-25,-50,-50, -50,-25,-10, 0, 0,-10,-25,-50, -25,-10, 0, 25, 25, 0,-10,-25, -10, 0, 25, 40, 40, 25, 0,-10, -10, 0, 25, 40, 40, 25, 0,-10, -25,-10, 0, 25, 25, 0,-10,-25, -50,-25,-10, 0, 0,-10,-25,-50, -50,-50,-25,-10,-10,-25,-50,-50 ]; var rookAdj = [ -60, -30, -10, 20, 20, -10, -30, -60, 40, 70, 90,120,120, 90, 70, 40, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60, -60, -30, -10, 20, 20, -10, -30, -60 ]; var kingAdj = [ 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 50, 150, -25, -125, -125, -25, 150, 50, 150, 250, 75, -25, -25, 75, 250, 150 ]; var emptyAdj = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; var pieceSquareAdj = new Array(8); // Returns the square flipped var flipTable = new Array(256); function PawnEval(color) { var pieceIdx = (color | 1) << 4; var from = g_pieceList[pieceIdx++]; while (from != 0) { from = g_pieceList[pieceIdx++]; } } function Mobility(color) { var result = 0; var from, to, mob, pieceIdx; var enemy = color == 8 ? 0x10 : 0x8 var mobUnit = color == 8 ? g_mobUnit[0] : g_mobUnit[1]; // Knight mobility mob = -3; pieceIdx = (color | 2) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { mob += mobUnit[g_board[from + 31]]; mob += mobUnit[g_board[from + 33]]; mob += mobUnit[g_board[from + 14]]; mob += mobUnit[g_board[from - 14]]; mob += mobUnit[g_board[from - 31]]; mob += mobUnit[g_board[from - 33]]; mob += mobUnit[g_board[from + 18]]; mob += mobUnit[g_board[from - 18]]; from = g_pieceList[pieceIdx++]; } result += 65 * mob; // Bishop mobility mob = -4; pieceIdx = (color | 3) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { to -= 15; mob++; } if (g_board[to] & enemy) mob++; to = from - 17; while (g_board[to] == 0) { to -= 17; mob++; } if (g_board[to] & enemy) mob++; to = from + 15; while (g_board[to] == 0) { to += 15; mob++; } if (g_board[to] & enemy) mob++; to = from + 17; while (g_board[to] == 0) { to += 17; mob++; } if (g_board[to] & enemy) mob++; from = g_pieceList[pieceIdx++]; } result += 50 * mob; // Rook mobility mob = -4; pieceIdx = (color | 4) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 1; while (g_board[to] == 0) { to--; mob++;} if (g_board[to] & enemy) mob++; to = from + 1; while (g_board[to] == 0) { to++; mob++; } if (g_board[to] & enemy) mob++; to = from + 16; while (g_board[to] == 0) { to += 16; mob++; } if (g_board[to] & enemy) mob++; to = from - 16; while (g_board[to] == 0) { to -= 16; mob++; } if (g_board[to] & enemy) mob++; from = g_pieceList[pieceIdx++]; } result += 25 * mob; // Queen mobility mob = -2; pieceIdx = (color | 5) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { to -= 15; mob++; } if (g_board[to] & enemy) mob++; to = from - 17; while (g_board[to] == 0) { to -= 17; mob++; } if (g_board[to] & enemy) mob++; to = from + 15; while (g_board[to] == 0) { to += 15; mob++; } if (g_board[to] & enemy) mob++; to = from + 17; while (g_board[to] == 0) { to += 17; mob++; } if (g_board[to] & enemy) mob++; to = from - 1; while (g_board[to] == 0) { to--; mob++; } if (g_board[to] & enemy) mob++; to = from + 1; while (g_board[to] == 0) { to++; mob++; } if (g_board[to] & enemy) mob++; to = from + 16; while (g_board[to] == 0) { to += 16; mob++; } if (g_board[to] & enemy) mob++; to = from - 16; while (g_board[to] == 0) { to -= 16; mob++; } if (g_board[to] & enemy) mob++; from = g_pieceList[pieceIdx++]; } result += 22 * mob; return result; } function Evaluate() { var curEval = g_baseEval; var evalAdjust = 0; // Black queen gone, then cancel white's penalty for king movement if (g_pieceList[pieceQueen << 4] == 0) evalAdjust -= pieceSquareAdj[pieceKing][g_pieceList[(colorWhite | pieceKing) << 4]]; // White queen gone, then cancel black's penalty for king movement if (g_pieceList[(colorWhite | pieceQueen) << 4] == 0) evalAdjust += pieceSquareAdj[pieceKing][flipTable[g_pieceList[pieceKing << 4]]]; // Black bishop pair if (g_pieceCount[pieceBishop] >= 2) evalAdjust -= 500; // White bishop pair if (g_pieceCount[pieceBishop | colorWhite] >= 2) evalAdjust += 500; var mobility = Mobility(8) - Mobility(0); if (g_toMove == 0) { // Black curEval -= mobility; curEval -= evalAdjust; } else { curEval += mobility; curEval += evalAdjust; } return curEval; } function ScoreMove(move){ var moveTo = (move >> 8) & 0xFF; var captured = g_board[moveTo] & 0x7; var piece = g_board[move & 0xFF]; var score; if (captured != 0) { var pieceType = piece & 0x7; score = (captured << 5) - pieceType; } else { score = historyTable[piece & 0xF][moveTo]; } return score; } function QSearch(alpha, beta, ply) { g_qNodeCount++; var realEval = g_inCheck ? (minEval + 1) : Evaluate(); if (realEval >= beta) return realEval; if (realEval > alpha) alpha = realEval; var moves = new Array(); var moveScores = new Array(); var wasInCheck = g_inCheck; if (wasInCheck) { // TODO: Fast check escape generator and fast checking moves generator GenerateCaptureMoves(moves, null); GenerateAllMoves(moves); for (var i = 0; i < moves.length; i++) { moveScores[i] = ScoreMove(moves[i]); } } else { GenerateCaptureMoves(moves, null); for (var i = 0; i < moves.length; i++) { var captured = g_board[(moves[i] >> 8) & 0xFF] & 0x7; var pieceType = g_board[moves[i] & 0xFF] & 0x7; moveScores[i] = (captured << 5) - pieceType; } } for (var i = 0; i < moves.length; i++) { var bestMove = i; for (var j = moves.length - 1; j > i; j--) { if (moveScores[j] > moveScores[bestMove]) { bestMove = j; } } { var tmpMove = moves[i]; moves[i] = moves[bestMove]; moves[bestMove] = tmpMove; var tmpScore = moveScores[i]; moveScores[i] = moveScores[bestMove]; moveScores[bestMove] = tmpScore; } if (!wasInCheck && !See(moves[i])) { continue; } if (!MakeMove(moves[i])) { continue; } /* if (ply == 0 && !wasInCheck) { // Search captures and checks at ply 0 of q-search if (!(g_inCheck || (moves[i] & 0xFF0000))) { UnmakeMove(moves[i]); continue; } }*/ var value = -QSearch(-beta, -alpha, ply - 1); UnmakeMove(moves[i]); if (value > realEval) { if (value >= beta) return value; if (value > alpha) alpha = value; realEval = value; } } return realEval; } function StoreHash(value, flags, ply, move, force){ var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode == null || ply >= hashNode.ply || force) { g_hashTable[g_hashKeyLow & g_hashMask] = new HashEntry(g_hashKeyHigh, value, flags, ply, move); } } function IsHashMoveValid(hashMove) { var from = hashMove & 0xFF; var to = (hashMove >> 8) & 0xFF; var ourPiece = g_board[from]; var pieceType = ourPiece & 0x7; if (pieceType < piecePawn || pieceType > pieceKing) return false; // Can't move a piece we don't control if (g_toMove != (ourPiece & 0x8)) return false; // Can't move to a square that has something of the same color if (g_board[to] != 0 && (g_toMove == (g_board[to] & 0x8))) return false; if (pieceType == piecePawn) { if (hashMove & moveflagEPC) { return false; } // Valid moves are push, capture, double push, promotions var dir = to - from; if ((g_toMove == colorWhite) != (dir < 0)) { // Pawns have to move in the right direction return false; } var row = to & 0xF0; if (((row == 0x90 && !g_toMove) || (row == 0x20 && g_toMove)) != (hashMove & moveflagPromotion)) { // Handle promotions return false; } if (dir == -16 || dir == 16) { // White/Black push return g_board[to] == 0; } else if (dir == -15 || dir == -17 || dir == 15 || dir == 17) { // White/Black capture return g_board[to] != 0; } else if (dir == -32) { // Double white push if (row != 0x60) return false; if (g_board[to] != 0) return false; if (g_board[from - 16] != 0) return false; } else if (dir == 32) { // Double black push if (row != 0x50) return false; if (g_board[to] != 0) return false; if (g_board[from + 16] != 0) return false; } else { return false; } return true; } else { // This validates that this piece type can actually make the attack if (hashMove >> 16) return false; return IsSquareAttackableFrom(to, from); } } function IsRepDraw() { var stop = g_moveCount - 1 - g_move50; stop = stop < 0 ? 0 : stop; for (var i = g_moveCount - 5; i >= stop; i -= 2) { if (g_repMoveStack[i] == g_hashKeyLow) return true; } return false; } function MovePicker(hashMove, depth, killer1, killer2) { this.hashMove = hashMove; this.depth = depth; this.killer1 = killer1; this.killer2 = killer2; this.moves = new Array(); this.losingCaptures = null; this.moveCount = 0; this.atMove = -1; this.moveScores = null; this.stage = 0; this.nextMove = function () { if (++this.atMove == this.moveCount) { this.stage++; if (this.stage == 1) { if (this.hashMove != null && IsHashMoveValid(hashMove)) { this.moves[0] = hashMove; this.moveCount = 1; } if (this.moveCount != 1) { this.hashMove = null; this.stage++; } } if (this.stage == 2) { GenerateCaptureMoves(this.moves, null); this.moveCount = this.moves.length; this.moveScores = new Array(this.moveCount); // Move ordering for (var i = this.atMove; i < this.moveCount; i++) { var captured = g_board[(this.moves[i] >> 8) & 0xFF] & 0x7; var pieceType = g_board[this.moves[i] & 0xFF] & 0x7; this.moveScores[i] = (captured << 5) - pieceType; } // No moves, onto next stage if (this.atMove == this.moveCount) this.stage++; } if (this.stage == 3) { if (IsHashMoveValid(this.killer1) && this.killer1 != this.hashMove) { this.moves[this.moves.length] = this.killer1; this.moveCount = this.moves.length; } else { this.killer1 = 0; this.stage++; } } if (this.stage == 4) { if (IsHashMoveValid(this.killer2) && this.killer2 != this.hashMove) { this.moves[this.moves.length] = this.killer2; this.moveCount = this.moves.length; } else { this.killer2 = 0; this.stage++; } } if (this.stage == 5) { GenerateAllMoves(this.moves); this.moveCount = this.moves.length; // Move ordering for (var i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]); // No moves, onto next stage if (this.atMove == this.moveCount) this.stage++; } if (this.stage == 6) { // Losing captures if (this.losingCaptures != null) { for (var i = 0; i < this.losingCaptures.length; i++) { this.moves[this.moves.length] = this.losingCaptures[i]; } for (var i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]); this.moveCount = this.moves.length; } // No moves, onto next stage if (this.atMove == this.moveCount) this.stage++; } if (this.stage == 7) return 0; } var bestMove = this.atMove; for (var j = this.atMove + 1; j < this.moveCount; j++) { if (this.moveScores[j] > this.moveScores[bestMove]) { bestMove = j; } } if (bestMove != this.atMove) { var tmpMove = this.moves[this.atMove]; this.moves[this.atMove] = this.moves[bestMove]; this.moves[bestMove] = tmpMove; var tmpScore = this.moveScores[this.atMove]; this.moveScores[this.atMove] = this.moveScores[bestMove]; this.moveScores[bestMove] = tmpScore; } var candidateMove = this.moves[this.atMove]; if ((this.stage > 1 && candidateMove == this.hashMove) || (this.stage > 3 && candidateMove == this.killer1) || (this.stage > 4 && candidateMove == this.killer2)) { return this.nextMove(); } if (this.stage == 2 && !See(candidateMove)) { if (this.losingCaptures == null) { this.losingCaptures = new Array(); } this.losingCaptures[this.losingCaptures.length] = candidateMove; return this.nextMove(); } return this.moves[this.atMove]; } } function AllCutNode(ply, depth, beta, allowNull) { if (ply <= 0) { return QSearch(beta - 1, beta, 0); } if ((g_nodeCount & 127) == 127) { if ((new Date()).getTime() - g_startTime > g_timeout) { // Time cutoff g_searchValid = false; return beta - 1; } } g_nodeCount++; if (IsRepDraw()) return 0; var hashMove = null; var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode != null && hashNode.lock == g_hashKeyHigh) { hashMove = hashNode.bestMove; if (hashNode.hashDepth >= ply) { if (hashNode.flags == hashflagExact) return hashNode.value; if (hashNode.flags == hashflagAlpha && hashNode.value < beta) return hashNode.value; if (hashNode.flags == hashflagBeta && hashNode.value >= beta) return hashNode.value; } } // TODO - positional gain? if (!g_inCheck && allowNull && beta > minMateBuffer && beta < maxMateBuffer) { // Try some razoring if (hashMove == null && ply < 4) { var razorMargin = 2500 + 200 * ply; if (g_baseEval < beta - razorMargin) { var razorBeta = beta - razorMargin; var v = QSearch(razorBeta - 1, razorBeta, 0); if (v < razorBeta) return v; } } // TODO - static null move // Null move if (ply > 1 && g_baseEval >= beta - (ply >= 4 ? 2500 : 0) && // Disable null move if potential zugzwang (no big pieces) (g_pieceCount[pieceBishop | g_toMove] != 0 || g_pieceCount[pieceKnight | g_toMove] != 0 || g_pieceCount[pieceRook | g_toMove] != 0 || g_pieceCount[pieceQueen | g_toMove] != 0)) { var r = 3 + (ply >= 5 ? 1 : ply / 4); if (g_baseEval - beta > 1500) r++; g_toMove = 8 - g_toMove; g_baseEval = -g_baseEval; g_hashKeyLow ^= g_zobristBlackLow; g_hashKeyHigh ^= g_zobristBlackHigh; var value = -AllCutNode(ply - r, depth + 1, -(beta - 1), false); g_hashKeyLow ^= g_zobristBlackLow; g_hashKeyHigh ^= g_zobristBlackHigh; g_toMove = 8 - g_toMove; g_baseEval = -g_baseEval; if (value >= beta) return beta; } } var moveMade = false; var realEval = minEval; var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]); for (;;) { var currentMove = movePicker.nextMove(); if (currentMove == 0) { break; } var plyToSearch = ply - 1; if (!MakeMove(currentMove)) { continue; } var value; var doFullSearch = true; if (g_inCheck) { // Check extensions plyToSearch++; } else { // Late move reductions if (movePicker.stage == 5 && movePicker.atMove > 5 && ply >= 3) { var reduced = plyToSearch - (movePicker.atMove > 14 ? 2 : 1); value = -AllCutNode(reduced, depth + 1, -(beta - 1), true); doFullSearch = (value >= beta); } } if (doFullSearch) { value = -AllCutNode(plyToSearch, depth + 1, -(beta - 1), true); } moveMade = true; UnmakeMove(currentMove); if (!g_searchValid) { return beta - 1; } if (value > realEval) { if (value >= beta) { var histTo = (currentMove >> 8) & 0xFF; if (g_board[histTo] == 0) { var histPiece = g_board[currentMove & 0xFF] & 0xF; historyTable[histPiece][histTo] += ply * ply; if (historyTable[histPiece][histTo] > 32767) { historyTable[histPiece][histTo] >>= 1; } if (g_killers[depth][0] != currentMove) { g_killers[depth][1] = g_killers[depth][0]; g_killers[depth][0] = currentMove; } } StoreHash(value, hashflagBeta, ply, currentMove, false); return value; } realEval = value; hashMove = currentMove; } } if (!moveMade) { // If we have no valid moves it's either stalemate or checkmate if (g_inCheck) // Checkmate. return minEval + 1; else // Stalemate return 0; } StoreHash(realEval, hashflagAlpha, ply, hashMove, false); return realEval; } function AlphaBeta(ply, depth, alpha, beta) { if (ply <= 0) { return QSearch(alpha, beta, 0); } g_nodeCount++; if (IsRepDraw()) return 0; var hashMove = null; var hashFlag = hashflagAlpha; var hashNode = g_hashTable[g_hashKeyLow & g_hashMask]; if (hashNode != null && hashNode.lock == g_hashKeyHigh) { hashMove = hashNode.bestMove; } var inCheck = g_inCheck; var moveMade = false; var realEval = minEval; var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]); for (;;) { var currentMove = movePicker.nextMove(); if (currentMove == 0) { break; } var plyToSearch = ply - 1; if (!MakeMove(currentMove)) { continue; } if (g_inCheck) { // Check extensions plyToSearch++; } var value; if (moveMade) { value = -AllCutNode(plyToSearch, depth + 1, -alpha, true); if (value > alpha) { value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha); } } else { value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha); } moveMade = true; UnmakeMove(currentMove); if (!g_searchValid) { return alpha; } if (value > realEval) { if (value >= beta) { var histTo = (currentMove >> 8) & 0xFF; if (g_board[histTo] == 0) { var histPiece = g_board[currentMove & 0xFF] & 0xF; historyTable[histPiece][histTo] += ply * ply; if (historyTable[histPiece][histTo] > 32767) { historyTable[histPiece][histTo] >>= 1; } if (g_killers[depth][0] != currentMove) { g_killers[depth][1] = g_killers[depth][0]; g_killers[depth][0] = currentMove; } } StoreHash(value, hashflagBeta, ply, currentMove, false); return value; } if (value > alpha) { hashFlag = hashflagExact; alpha = value; } realEval = value; hashMove = currentMove; } } if (!moveMade) { // If we have no valid moves it's either stalemate or checkmate if (inCheck) // Checkmate. return minEval + 1; else // Stalemate return 0; } StoreHash(realEval, hashFlag, ply, hashMove, true); return realEval; } // // Board code // // This somewhat funky scheme means that a piece is indexed by it's lower 4 bits when accessing in arrays. The fifth bit (black bit) // is used to allow quick edge testing on the board. var colorBlack = 0x10; var colorWhite = 0x08; var pieceEmpty = 0x00; var piecePawn = 0x01; var pieceKnight = 0x02; var pieceBishop = 0x03; var pieceRook = 0x04; var pieceQueen = 0x05; var pieceKing = 0x06; var g_vectorDelta = new Array(256); var g_bishopDeltas = [-15, -17, 15, 17]; var g_knightDeltas = [31, 33, 14, -14, -31, -33, 18, -18]; var g_rookDeltas = [-1, +1, -16, +16]; var g_queenDeltas = [-1, +1, -15, +15, -17, +17, -16, +16]; var g_castleRightsMask = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,15,15,15, 3,15,15,11, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0, 0, 0, 0, 0,13,15,15,15,12,15,15,14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var moveflagEPC = 0x2 << 16; var moveflagCastleKing = 0x4 << 16; var moveflagCastleQueen = 0x8 << 16; var moveflagPromotion = 0x10 << 16; var moveflagPromoteKnight = 0x20 << 16; var moveflagPromoteQueen = 0x40 << 16; var moveflagPromoteBishop = 0x80 << 16; function MT() { var N = 624; var M = 397; var MAG01 = [0x0, 0x9908b0df]; this.mt = new Array(N); this.mti = N + 1; this.setSeed = function() { var a = arguments; switch (a.length) { case 1: if (a[0].constructor === Number) { this.mt[0]= a[0]; for (var i = 1; i < N; ++i) { var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); this.mt[i] = ((1812433253 * ((s & 0xffff0000) >>> 16)) << 16) + 1812433253 * (s & 0x0000ffff) + i; } this.mti = N; return; } this.setSeed(19650218); var l = a[0].length; var i = 1; var j = 0; for (var k = N > l ? N : l; k != 0; --k) { var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30) this.mt[i] = (this.mt[i] ^ (((1664525 * ((s & 0xffff0000) >>> 16)) << 16) + 1664525 * (s & 0x0000ffff))) + a[0][j] + j; if (++i >= N) { this.mt[0] = this.mt[N - 1]; i = 1; } if (++j >= l) { j = 0; } } for (var k = N - 1; k != 0; --k) { var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); this.mt[i] = (this.mt[i] ^ (((1566083941 * ((s & 0xffff0000) >>> 16)) << 16) + 1566083941 * (s & 0x0000ffff))) - i; if (++i >= N) { this.mt[0] = this.mt[N-1]; i = 1; } } this.mt[0] = 0x80000000; return; default: var seeds = new Array(); for (var i = 0; i < a.length; ++i) { seeds.push(a[i]); } this.setSeed(seeds); return; } } this.setSeed(0x1BADF00D); this.next = function (bits) { if (this.mti >= N) { var x = 0; for (var k = 0; k < N - M; ++k) { x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff); this.mt[k] = this.mt[k + M] ^ (x >>> 1) ^ MAG01[x & 0x1]; } for (var k = N - M; k < N - 1; ++k) { x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff); this.mt[k] = this.mt[k + (M - N)] ^ (x >>> 1) ^ MAG01[x & 0x1]; } x = (this.mt[N - 1] & 0x80000000) | (this.mt[0] & 0x7fffffff); this.mt[N - 1] = this.mt[M - 1] ^ (x >>> 1) ^ MAG01[x & 0x1]; this.mti = 0; } var y = this.mt[this.mti++]; y ^= y >>> 11; y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= y >>> 18; return (y >>> (32 - bits)) & 0xFFFFFFFF; } } // Position variables var g_board = new Array(256); // Sentinel 0x80, pieces are in low 4 bits, 0x8 for color, 0x7 bits for piece type var g_toMove; // side to move, 0 or 8, 0 = black, 8 = white var g_castleRights; // bitmask representing castling rights, 1 = wk, 2 = wq, 4 = bk, 8 = bq var g_enPassentSquare; var g_baseEval; var g_hashKeyLow, g_hashKeyHigh; var g_inCheck; // Utility variables var g_moveCount = 0; var g_moveUndoStack = new Array(); var g_move50 = 0; var g_repMoveStack = new Array(); var g_hashSize = 1 << 22; var g_hashMask = g_hashSize - 1; var g_hashTable; var g_killers; var historyTable = new Array(32); var g_zobristLow; var g_zobristHigh; var g_zobristBlackLow; var g_zobristBlackHigh; // Evaulation variables var g_mobUnit; var hashflagAlpha = 1; var hashflagBeta = 2; var hashflagExact = 3; function HashEntry(lock, value, flags, hashDepth, bestMove, globalPly) { this.lock = lock; this.value = value; this.flags = flags; this.hashDepth = hashDepth; this.bestMove = bestMove; } function MakeSquare(row, column) { return ((row + 2) << 4) | (column + 4); } function MakeTable(table) { var result = new Array(256); for (var i = 0; i < 256; i++) { result[i] = 0; } for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { result[MakeSquare(row, col)] = table[row * 8 + col]; } } return result; } function ResetGame() { g_killers = new Array(128); for (var i = 0; i < 128; i++) { g_killers[i] = [0, 0]; } g_hashTable = new Array(g_hashSize); for (var i = 0; i < 32; i++) { historyTable[i] = new Array(256); for (var j = 0; j < 256; j++) historyTable[i][j] = 0; } var mt = new MT(0x1badf00d); g_zobristLow = new Array(256); g_zobristHigh = new Array(256); for (var i = 0; i < 256; i++) { g_zobristLow[i] = new Array(16); g_zobristHigh[i] = new Array(16); for (var j = 0; j < 16; j++) { g_zobristLow[i][j] = mt.next(32); g_zobristHigh[i][j] = mt.next(32); } } g_zobristBlackLow = mt.next(32); g_zobristBlackHigh = mt.next(32); for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { var square = MakeSquare(row, col); flipTable[square] = MakeSquare(7 - row, col); } } pieceSquareAdj[piecePawn] = MakeTable(pawnAdj); pieceSquareAdj[pieceKnight] = MakeTable(knightAdj); pieceSquareAdj[pieceBishop] = MakeTable(bishopAdj); pieceSquareAdj[pieceRook] = MakeTable(rookAdj); pieceSquareAdj[pieceQueen] = MakeTable(emptyAdj); pieceSquareAdj[pieceKing] = MakeTable(kingAdj); var pieceDeltas = [[], [], g_knightDeltas, g_bishopDeltas, g_rookDeltas, g_queenDeltas, g_queenDeltas]; for (var i = 0; i < 256; i++) { g_vectorDelta[i] = new Object(); g_vectorDelta[i].delta = 0; g_vectorDelta[i].pieceMask = new Array(2); g_vectorDelta[i].pieceMask[0] = 0; g_vectorDelta[i].pieceMask[1] = 0; } // Initialize the vector delta table for (var row = 0; row < 0x80; row += 0x10) for (var col = 0; col < 0x8; col++) { var square = row | col; // Pawn moves var index = square - (square - 17) + 128; g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn); index = square - (square - 15) + 128; g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn); index = square - (square + 17) + 128; g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn); index = square - (square + 15) + 128; g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn); for (var i = pieceKnight; i <= pieceKing; i++) { for (var dir = 0; dir < pieceDeltas[i].length; dir++) { var target = square + pieceDeltas[i][dir]; while (!(target & 0x88)) { index = square - target + 128; g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << i); g_vectorDelta[index].pieceMask[0] |= (1 << i); var flip = -1; if (square < target) flip = 1; if ((square & 0xF0) == (target & 0xF0)) { // On the same row g_vectorDelta[index].delta = flip * 1; } else if ((square & 0x0F) == (target & 0x0F)) { // On the same column g_vectorDelta[index].delta = flip * 16; } else if ((square % 15) == (target % 15)) { g_vectorDelta[index].delta = flip * 15; } else if ((square % 17) == (target % 17)) { g_vectorDelta[index].delta = flip * 17; } if (i == pieceKnight) { g_vectorDelta[index].delta = pieceDeltas[i][dir]; break; } if (i == pieceKing) break; target += pieceDeltas[i][dir]; } } } } InitializeEval(); InitializeFromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); } function InitializeEval() { g_mobUnit = new Array(2); for (var i = 0; i < 2; i++) { g_mobUnit[i] = new Array(); var enemy = i == 0 ? 0x10 : 8; var friend = i == 0 ? 8 : 0x10; g_mobUnit[i][0] = 1; g_mobUnit[i][0x80] = 0; g_mobUnit[i][enemy | piecePawn] = 1; g_mobUnit[i][enemy | pieceBishop] = 1; g_mobUnit[i][enemy | pieceKnight] = 1; g_mobUnit[i][enemy | pieceRook] = 1; g_mobUnit[i][enemy | pieceQueen] = 1; g_mobUnit[i][enemy | pieceKing] = 1; g_mobUnit[i][friend | piecePawn] = 0; g_mobUnit[i][friend | pieceBishop] = 0; g_mobUnit[i][friend | pieceKnight] = 0; g_mobUnit[i][friend | pieceRook] = 0; g_mobUnit[i][friend | pieceQueen] = 0; g_mobUnit[i][friend | pieceKing] = 0; } } function SetHash() { var result = new Object(); result.hashKeyLow = 0; result.hashKeyHigh = 0; for (var i = 0; i < 256; i++) { var piece = g_board[i]; if (piece & 0x18) { result.hashKeyLow ^= g_zobristLow[i][piece & 0xF] result.hashKeyHigh ^= g_zobristHigh[i][piece & 0xF] } } if (!g_toMove) { result.hashKeyLow ^= g_zobristBlackLow; result.hashKeyHigh ^= g_zobristBlackHigh; } return result; } function InitializeFromFen(fen){ var chunks = fen.split(' '); for (var i = 0; i < 256; i++) g_board[i] = 0x80; var row = 0; var col = 0; var pieces = chunks[0]; for (var i = 0; i < pieces.length; i++) { var c = pieces.charAt(i); if (c == '/') { row++; col = 0; } else { if (c >= '0' && c <= '9') { for (var j = 0; j < parseInt(c); j++) { g_board[((row + 2) * 0x10) + (col + 4)] = 0; col++; } } else { var isBlack = c >= 'a' && c <= 'z'; var piece = isBlack ? colorBlack : colorWhite; if (!isBlack) c = pieces.toLowerCase().charAt(i); switch (c) { case 'p': piece |= piecePawn; break; case 'b': piece |= pieceBishop; break; case 'n': piece |= pieceKnight; break; case 'r': piece |= pieceRook; break; case 'q': piece |= pieceQueen; break; case 'k': piece |= pieceKing; break; } g_board[((row + 2) * 0x10) + (col + 4)] = piece; col++; } } } InitializePieceList(); g_toMove = chunks[1].charAt(0) == 'w' ? colorWhite : 0; g_castleRights = 0; if (chunks[2].indexOf('K') != -1) g_castleRights |= 1; if (chunks[2].indexOf('Q') != -1) g_castleRights |= 2; if (chunks[2].indexOf('k') != -1) g_castleRights |= 4; if (chunks[2].indexOf('q') != -1) g_castleRights |= 8; g_enPassentSquare = -1; if (chunks[3].indexOf('-') == -1) { g_enPassentSquare = parseInt(chunks[3], 16); } var hashResult = SetHash(); g_hashKeyLow = hashResult.hashKeyLow; g_hashKeyHigh = hashResult.hashKeyHigh; g_baseEval = 0; for (var i = 0; i < 256; i++) { if (g_board[i] & colorWhite) { g_baseEval += pieceSquareAdj[g_board[i] & 0x7][i]; } else if (g_board[i] & colorBlack) { g_baseEval -= pieceSquareAdj[g_board[i] & 0x7][flipTable[i]]; } } g_move50 = 0; g_inCheck = IsSquareAttackable(g_pieceList[(g_toMove | pieceKing) << 4], 8 - g_toMove); } var g_pieceIndex = new Array(256); var g_pieceList = new Array(2 * 8 * 16); var g_pieceCount = new Array(2 * 8); function InitializePieceList() { for (var i = 0; i < 16; i++) { g_pieceCount[i] = 0; for (var j = 0; j < 16; j++) { // 0 is used as the terminator for piece lists g_pieceList[(i << 4) | j] = 0; } } for (var i = 0; i < 256; i++) { g_pieceIndex[i] = 0; if (g_board[i] & (colorWhite | colorBlack)) { var piece = g_board[i] & 0xF; g_pieceList[(piece << 4) | g_pieceCount[piece]] = i; g_pieceIndex[i] = g_pieceCount[piece]; g_pieceCount[piece]++; } } } function MakeMove(move){ var me = g_toMove >> 3; var otherColor = 8 - g_toMove; var flags = move & 0xFF0000; var to = (move >> 8) & 0xFF; var from = move & 0xFF; var captured = g_board[to]; var piece = g_board[from]; var epcEnd = to; if (flags & moveflagEPC) { epcEnd = me ? (to + 0x10) : (to - 0x10); captured = g_board[epcEnd]; g_board[epcEnd] = pieceEmpty; } g_moveUndoStack[g_moveCount] = new UndoHistory(g_enPassentSquare, g_castleRights, g_inCheck, g_baseEval, g_hashKeyLow, g_hashKeyHigh, g_move50, captured); g_moveCount++; g_enPassentSquare = -1; if (flags) { if (flags & moveflagCastleKing) { if (IsSquareAttackable(from + 1, otherColor) || IsSquareAttackable(from + 2, otherColor)) { g_moveCount--; return false; } var rook = g_board[to + 1]; g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF]; g_hashKeyLow ^= g_zobristLow[to - 1][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to - 1][rook & 0xF]; g_board[to - 1] = rook; g_board[to + 1] = pieceEmpty; g_baseEval -= pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to + 1] : (to + 1)]; g_baseEval += pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to - 1] : (to - 1)]; var rookIndex = g_pieceIndex[to + 1]; g_pieceIndex[to - 1] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 1; } else if (flags & moveflagCastleQueen) { if (IsSquareAttackable(from - 1, otherColor) || IsSquareAttackable(from - 2, otherColor)) { g_moveCount--; return false; } var rook = g_board[to - 2]; g_hashKeyLow ^= g_zobristLow[to -2][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to - 2][rook & 0xF]; g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF]; g_board[to + 1] = rook; g_board[to - 2] = pieceEmpty; g_baseEval -= pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to - 2] : (to - 2)]; g_baseEval += pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to + 1] : (to + 1)]; var rookIndex = g_pieceIndex[to - 2]; g_pieceIndex[to + 1] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1; } } if (captured) { // Remove our piece from the piece list var capturedType = captured & 0xF; g_pieceCount[capturedType]--; var lastPieceSquare = g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]]; g_pieceIndex[lastPieceSquare] = g_pieceIndex[epcEnd]; g_pieceList[(capturedType << 4) | g_pieceIndex[lastPieceSquare]] = lastPieceSquare; g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]] = 0; g_baseEval += materialTable[captured & 0x7]; g_baseEval += pieceSquareAdj[captured & 0x7][me ? flipTable[epcEnd] : epcEnd]; g_hashKeyLow ^= g_zobristLow[epcEnd][capturedType]; g_hashKeyHigh ^= g_zobristHigh[epcEnd][capturedType]; g_move50 = 0; } else if ((piece & 0x7) == piecePawn) { var diff = to - from; if (diff < 0) diff = -diff; if (diff > 16) { g_enPassentSquare = me ? (to + 0x10) : (to - 0x10); } g_move50 = 0; } g_hashKeyLow ^= g_zobristLow[from][piece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[from][piece & 0xF]; g_hashKeyLow ^= g_zobristLow[to][piece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF]; g_hashKeyLow ^= g_zobristBlackLow; g_hashKeyHigh ^= g_zobristBlackHigh; g_castleRights &= g_castleRightsMask[from] & g_castleRightsMask[to]; g_baseEval -= pieceSquareAdj[piece & 0x7][me == 0 ? flipTable[from] : from]; // Move our piece in the piece list g_pieceIndex[to] = g_pieceIndex[from]; g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[to]] = to; if (flags & moveflagPromotion) { var newPiece = piece & (~0x7); if (flags & moveflagPromoteKnight) newPiece |= pieceKnight; else if (flags & moveflagPromoteQueen) newPiece |= pieceQueen; else if (flags & moveflagPromoteBishop) newPiece |= pieceBishop; else newPiece |= pieceRook; g_hashKeyLow ^= g_zobristLow[to][piece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF]; g_board[to] = newPiece; g_hashKeyLow ^= g_zobristLow[to][newPiece & 0xF]; g_hashKeyHigh ^= g_zobristHigh[to][newPiece & 0xF]; g_baseEval += pieceSquareAdj[newPiece & 0x7][me == 0 ? flipTable[to] : to]; g_baseEval -= materialTable[piecePawn]; g_baseEval += materialTable[newPiece & 0x7]; var pawnType = piece & 0xF; var promoteType = newPiece & 0xF; g_pieceCount[pawnType]--; var lastPawnSquare = g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]]; g_pieceIndex[lastPawnSquare] = g_pieceIndex[to]; g_pieceList[(pawnType << 4) | g_pieceIndex[lastPawnSquare]] = lastPawnSquare; g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]] = 0; g_pieceIndex[to] = g_pieceCount[promoteType]; g_pieceList[(promoteType << 4) | g_pieceIndex[to]] = to; g_pieceCount[promoteType]++; } else { g_board[to] = g_board[from]; g_baseEval += pieceSquareAdj[piece & 0x7][me == 0 ? flipTable[to] : to]; } g_board[from] = pieceEmpty; g_toMove = otherColor; g_baseEval = -g_baseEval; if ((piece & 0x7) == pieceKing || g_inCheck) { if (IsSquareAttackable(g_pieceList[(pieceKing | (8 - g_toMove)) << 4], otherColor)) { UnmakeMove(move); return false; } } else { var kingPos = g_pieceList[(pieceKing | (8 - g_toMove)) << 4]; if (ExposesCheck(from, kingPos)) { UnmakeMove(move); return false; } if (epcEnd != to) { if (ExposesCheck(epcEnd, kingPos)) { UnmakeMove(move); return false; } } } g_inCheck = false; if (flags <= moveflagEPC) { var theirKingPos = g_pieceList[(pieceKing | g_toMove) << 4]; // First check if the piece we moved can attack the enemy king g_inCheck = IsSquareAttackableFrom(theirKingPos, to); if (!g_inCheck) { // Now check if the square we moved from exposes check on the enemy king g_inCheck = ExposesCheck(from, theirKingPos); if (!g_inCheck) { // Finally, ep. capture can cause another square to be exposed if (epcEnd != to) { g_inCheck = ExposesCheck(epcEnd, theirKingPos); } } } } else { // Castle or promotion, slow check g_inCheck = IsSquareAttackable(g_pieceList[(pieceKing | g_toMove) << 4], 8 - g_toMove); } g_repMoveStack[g_moveCount - 1] = g_hashKeyLow; g_move50++; return true; } function UnmakeMove(move){ g_toMove = 8 - g_toMove; g_baseEval = -g_baseEval; g_moveCount--; g_enPassentSquare = g_moveUndoStack[g_moveCount].ep; g_castleRights = g_moveUndoStack[g_moveCount].castleRights; g_inCheck = g_moveUndoStack[g_moveCount].inCheck; g_baseEval = g_moveUndoStack[g_moveCount].baseEval; g_hashKeyLow = g_moveUndoStack[g_moveCount].hashKeyLow; g_hashKeyHigh = g_moveUndoStack[g_moveCount].hashKeyHigh; g_move50 = g_moveUndoStack[g_moveCount].move50; var otherColor = 8 - g_toMove; var me = g_toMove >> 3; var them = otherColor >> 3; var flags = move & 0xFF0000; var captured = g_moveUndoStack[g_moveCount].captured; var to = (move >> 8) & 0xFF; var from = move & 0xFF; var piece = g_board[to]; if (flags) { if (flags & moveflagCastleKing) { var rook = g_board[to - 1]; g_board[to + 1] = rook; g_board[to - 1] = pieceEmpty; var rookIndex = g_pieceIndex[to - 1]; g_pieceIndex[to + 1] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1; } else if (flags & moveflagCastleQueen) { var rook = g_board[to + 1]; g_board[to - 2] = rook; g_board[to + 1] = pieceEmpty; var rookIndex = g_pieceIndex[to + 1]; g_pieceIndex[to - 2] = rookIndex; g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 2; } } if (flags & moveflagPromotion) { piece = (g_board[to] & (~0x7)) | piecePawn; g_board[from] = piece; var pawnType = g_board[from] & 0xF; var promoteType = g_board[to] & 0xF; g_pieceCount[promoteType]--; var lastPromoteSquare = g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]]; g_pieceIndex[lastPromoteSquare] = g_pieceIndex[to]; g_pieceList[(promoteType << 4) | g_pieceIndex[lastPromoteSquare]] = lastPromoteSquare; g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]] = 0; g_pieceIndex[to] = g_pieceCount[pawnType]; g_pieceList[(pawnType << 4) | g_pieceIndex[to]] = to; g_pieceCount[pawnType]++; } else { g_board[from] = g_board[to]; } var epcEnd = to; if (flags & moveflagEPC) { if (g_toMove == colorWhite) epcEnd = to + 0x10; else epcEnd = to - 0x10; g_board[to] = pieceEmpty; } g_board[epcEnd] = captured; // Move our piece in the piece list g_pieceIndex[from] = g_pieceIndex[to]; g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[from]] = from; if (captured) { // Restore our piece to the piece list var captureType = captured & 0xF; g_pieceIndex[epcEnd] = g_pieceCount[captureType]; g_pieceList[(captureType << 4) | g_pieceCount[captureType]] = epcEnd; g_pieceCount[captureType]++; } } function ExposesCheck(from, kingPos){ var index = kingPos - from + 128; // If a queen can't reach it, nobody can! if ((g_vectorDelta[index].pieceMask[0] & (1 << (pieceQueen))) != 0) { var delta = g_vectorDelta[index].delta; var pos = kingPos + delta; while (g_board[pos] == 0) pos += delta; var piece = g_board[pos]; if (((piece & (g_board[kingPos] ^ 0x18)) & 0x18) == 0) return false; // Now see if the piece can actually attack the king var backwardIndex = pos - kingPos + 128; return (g_vectorDelta[backwardIndex].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) != 0; } return false; } function IsSquareOnPieceLine(target, from) { var index = from - target + 128; var piece = g_board[from]; return (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) ? true : false; } function IsSquareAttackableFrom(target, from){ var index = from - target + 128; var piece = g_board[from]; if (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) { // Yes, this square is pseudo-attackable. Now, check for real attack var inc = g_vectorDelta[index].delta; do { from += inc; if (from == target) return true; } while (g_board[from] == 0); } return false; } function IsSquareAttackable(target, color) { // Attackable by pawns? var inc = color ? -16 : 16; var pawn = (color ? colorWhite : colorBlack) | 1; if (g_board[target - (inc - 1)] == pawn) return true; if (g_board[target - (inc + 1)] == pawn) return true; // Attackable by pieces? for (var i = 2; i <= 6; i++) { var index = (color | i) << 4; var square = g_pieceList[index]; while (square != 0) { if (IsSquareAttackableFrom(target, square)) return true; square = g_pieceList[++index]; } } return false; } function GenerateMove(from, to) { return from | (to << 8); } function GenerateMove(from, to, flags){ return from | (to << 8) | flags; } function GenerateValidMoves() { var moveList = new Array(); var allMoves = new Array(); GenerateCaptureMoves(allMoves, null); GenerateAllMoves(allMoves); for (var i = allMoves.length - 1; i >= 0; i--) { if (MakeMove(allMoves[i])) { moveList[moveList.length] = allMoves[i]; UnmakeMove(allMoves[i]); } } return moveList; } function GenerateAllMoves(moveStack) { var from, to, piece, pieceIdx; // Pawn quiet moves pieceIdx = (g_toMove | 1) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { GeneratePawnMoves(moveStack, from); from = g_pieceList[pieceIdx++]; } // Knight quiet moves pieceIdx = (g_toMove | 2) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from + 31; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 33; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 14; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 14; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 31; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 33; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 18; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 18; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Bishop quiet moves pieceIdx = (g_toMove | 3) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; } to = from - 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; } to = from + 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; } to = from + 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; } from = g_pieceList[pieceIdx++]; } // Rook quiet moves pieceIdx = (g_toMove | 4) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; } to = from + 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; } to = from + 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; } to = from - 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; } from = g_pieceList[pieceIdx++]; } // Queen quiet moves pieceIdx = (g_toMove | 5) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from - 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; } to = from - 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; } to = from + 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; } to = from + 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; } to = from - 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; } to = from + 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; } to = from + 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; } to = from - 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; } from = g_pieceList[pieceIdx++]; } // King quiet moves { pieceIdx = (g_toMove | 6) << 4; from = g_pieceList[pieceIdx]; to = from - 15; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 17; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 15; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 17; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 1; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 1; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 16; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 16; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to); if (!g_inCheck) { var castleRights = g_castleRights; if (!g_toMove) castleRights >>= 2; if (castleRights & 1) { // Kingside castle if (g_board[from + 1] == pieceEmpty && g_board[from + 2] == pieceEmpty) { moveStack[moveStack.length] = GenerateMove(from, from + 0x02, moveflagCastleKing); } } if (castleRights & 2) { // Queenside castle if (g_board[from - 1] == pieceEmpty && g_board[from - 2] == pieceEmpty && g_board[from - 3] == pieceEmpty) { moveStack[moveStack.length] = GenerateMove(from, from - 0x02, moveflagCastleQueen); } } } } } function GenerateCaptureMoves(moveStack, moveScores) { var from, to, piece, pieceIdx; var inc = (g_toMove == 8) ? -16 : 16; var enemy = g_toMove == 8 ? 0x10 : 0x8; // Pawn captures pieceIdx = (g_toMove | 1) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from + inc - 1; if (g_board[to] & enemy) { MovePawnTo(moveStack, from, to); } to = from + inc + 1; if (g_board[to] & enemy) { MovePawnTo(moveStack, from, to); } from = g_pieceList[pieceIdx++]; } if (g_enPassentSquare != -1) { var inc = (g_toMove == colorWhite) ? -16 : 16; var pawn = g_toMove | piecePawn; var from = g_enPassentSquare - (inc + 1); if ((g_board[from] & 0xF) == pawn) { moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC); } from = g_enPassentSquare - (inc - 1); if ((g_board[from] & 0xF) == pawn) { moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC); } } // Knight captures pieceIdx = (g_toMove | 2) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from + 31; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 33; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 14; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 14; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 31; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 33; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 18; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 18; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Bishop captures pieceIdx = (g_toMove | 3) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from; do { to -= 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Rook captures pieceIdx = (g_toMove | 4) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from; do { to--; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to++; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // Queen captures pieceIdx = (g_toMove | 5) << 4; from = g_pieceList[pieceIdx++]; while (from != 0) { to = from; do { to -= 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to--; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to++; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to -= 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from; do { to += 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); from = g_pieceList[pieceIdx++]; } // King captures { pieceIdx = (g_toMove | 6) << 4; from = g_pieceList[pieceIdx]; to = from - 15; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 17; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 15; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 17; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 1; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 1; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from - 16; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); to = from + 16; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to); } } function MovePawnTo(moveStack, start, square) { var row = square & 0xF0; if ((row == 0x90) || (row == 0x20)) { moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteQueen); moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteKnight); moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteBishop); moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion); } else { moveStack[moveStack.length] = GenerateMove(start, square, 0); } } function GeneratePawnMoves(moveStack, from) { var piece = g_board[from]; var color = piece & colorWhite; var inc = (color == colorWhite) ? -16 : 16; // Quiet pawn moves var to = from + inc; if (g_board[to] == 0) { MovePawnTo(moveStack, from, to, pieceEmpty); // Check if we can do a 2 square jump if ((((from & 0xF0) == 0x30) && color != colorWhite) || (((from & 0xF0) == 0x80) && color == colorWhite)) { to += inc; if (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); } } } } function UndoHistory(ep, castleRights, inCheck, baseEval, hashKeyLow, hashKeyHigh, move50, captured) { this.ep = ep; this.castleRights = castleRights; this.inCheck = inCheck; this.baseEval = baseEval; this.hashKeyLow = hashKeyLow; this.hashKeyHigh = hashKeyHigh; this.move50 = move50; this.captured = captured; } var g_seeValues = [0, 1, 3, 3, 5, 9, 900, 0, 0, 1, 3, 3, 5, 9, 900, 0]; function See(move) { var from = move & 0xFF; var to = (move >> 8) & 0xFF; var fromPiece = g_board[from]; var fromValue = g_seeValues[fromPiece & 0xF]; var toValue = g_seeValues[g_board[to] & 0xF]; if (fromValue <= toValue) { return true; } if (move >> 16) { // Castles, promotion, ep are always good return true; } var us = (fromPiece & colorWhite) ? colorWhite : 0; var them = 8 - us; // Pawn attacks // If any opponent pawns can capture back, this capture is probably not worthwhile (as we must be using knight or above). var inc = (fromPiece & colorWhite) ? -16 : 16; // Note: this is capture direction from to, so reversed from normal move direction if (((g_board[to + inc + 1] & 0xF) == (piecePawn | them)) || ((g_board[to + inc - 1] & 0xF) == (piecePawn | them))) { return false; } var themAttacks = new Array(); // Knight attacks // If any opponent knights can capture back, and the deficit we have to make up is greater than the knights value, // it's not worth it. We can capture on this square again, and the opponent doesn't have to capture back. var captureDeficit = fromValue - toValue; SeeAddKnightAttacks(to, them, themAttacks); if (themAttacks.length != 0 && captureDeficit > g_seeValues[pieceKnight]) { return false; } // Slider attacks g_board[from] = 0; for (var pieceType = pieceBishop; pieceType <= pieceQueen; pieceType++) { if (SeeAddSliderAttacks(to, them, themAttacks, pieceType)) { if (captureDeficit > g_seeValues[pieceType]) { g_board[from] = fromPiece; return false; } } } // Pawn defenses // At this point, we are sure we are making a "losing" capture. The opponent can not capture back with a // pawn. They cannot capture back with a minor/major and stand pat either. So, if we can capture with // a pawn, it's got to be a winning or equal capture. if (((g_board[to - inc + 1] & 0xF) == (piecePawn | us)) || ((g_board[to - inc - 1] & 0xF) == (piecePawn | us))) { g_board[from] = fromPiece; return true; } // King attacks SeeAddSliderAttacks(to, them, themAttacks, pieceKing); // Our attacks var usAttacks = new Array(); SeeAddKnightAttacks(to, us, usAttacks); for (var pieceType = pieceBishop; pieceType <= pieceKing; pieceType++) { SeeAddSliderAttacks(to, us, usAttacks, pieceType); } g_board[from] = fromPiece; // We are currently winning the amount of material of the captured piece, time to see if the opponent // can get it back somehow. We assume the opponent can capture our current piece in this score, which // simplifies the later code considerably. var seeValue = toValue - fromValue; for (; ; ) { var capturingPieceValue = 1000; var capturingPieceIndex = -1; // Find the least valuable piece of the opponent that can attack the square for (var i = 0; i < themAttacks.length; i++) { if (themAttacks[i] != 0) { var pieceValue = g_seeValues[g_board[themAttacks[i]] & 0x7]; if (pieceValue < capturingPieceValue) { capturingPieceValue = pieceValue; capturingPieceIndex = i; } } } if (capturingPieceIndex == -1) { // Opponent can't capture back, we win return true; } // Now, if seeValue < 0, the opponent is winning. If even after we take their piece, // we can't bring it back to 0, then we have lost this battle. seeValue += capturingPieceValue; if (seeValue < 0) { return false; } var capturingPieceSquare = themAttacks[capturingPieceIndex]; themAttacks[capturingPieceIndex] = 0; // Add any x-ray attackers SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks); // Our turn to capture capturingPieceValue = 1000; capturingPieceIndex = -1; // Find our least valuable piece that can attack the square for (var i = 0; i < usAttacks.length; i++) { if (usAttacks[i] != 0) { var pieceValue = g_seeValues[g_board[usAttacks[i]] & 0x7]; if (pieceValue < capturingPieceValue) { capturingPieceValue = pieceValue; capturingPieceIndex = i; } } } if (capturingPieceIndex == -1) { // We can't capture back, we lose :( return false; } // Assume our opponent can capture us back, and if we are still winning, we can stand-pat // here, and assume we've won. seeValue -= capturingPieceValue; if (seeValue >= 0) { return true; } capturingPieceSquare = usAttacks[capturingPieceIndex]; usAttacks[capturingPieceIndex] = 0; // Add any x-ray attackers SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks); } } function SeeAddXrayAttack(target, square, us, usAttacks, themAttacks) { var index = square - target + 128; var delta = -g_vectorDelta[index].delta; if (delta == 0) return; square += delta; while (g_board[square] == 0) { square += delta; } if ((g_board[square] & 0x18) && IsSquareOnPieceLine(target, square)) { if ((g_board[square] & 8) == us) { usAttacks[usAttacks.length] = square; } else { themAttacks[themAttacks.length] = square; } } } // target = attacking square, us = color of knights to look for, attacks = array to add squares to function SeeAddKnightAttacks(target, us, attacks) { var pieceIdx = (us | pieceKnight) << 4; var attackerSq = g_pieceList[pieceIdx++]; while (attackerSq != 0) { if (IsSquareOnPieceLine(target, attackerSq)) { attacks[attacks.length] = attackerSq; } attackerSq = g_pieceList[pieceIdx++]; } } function SeeAddSliderAttacks(target, us, attacks, pieceType) { var pieceIdx = (us | pieceType) << 4; var attackerSq = g_pieceList[pieceIdx++]; var hit = false; while (attackerSq != 0) { if (IsSquareAttackableFrom(target, attackerSq)) { attacks[attacks.length] = attackerSq; hit = true; } attackerSq = g_pieceList[pieceIdx++]; } return hit; } ////////////////////////////////////////////////// // Test Harness ////////////////////////////////////////////////// function FinishMoveLocalTesting(bestMove, value, timeTaken, ply) { if (bestMove != null) { MakeMove(bestMove); postMessage(FormatMove(bestMove)); } } var needsReset = true; onmessage = function (e) { if (e.data == "go" || needsReset) { ResetGame(); needsReset = false; } if (e.data.match("^position") == "position") { ResetGame(); InitializeFromFen(e.data.substr(9, e.data.length - 9)); } else if (e.data == "search") { Search(FinishMoveLocalTesting, 99); } else { MakeMove(GetMoveFromString(e.data)); } }
1
0.718103
1
0.718103
game-dev
MEDIA
0.850413
game-dev
0.875444
1
0.875444
lightbend/config
1,537
config/src/main/java/com/typesafe/config/impl/ConfigNull.java
/** * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> */ package com.typesafe.config.impl; import java.io.ObjectStreamException; import java.io.Serializable; import com.typesafe.config.ConfigOrigin; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValueType; /** * This exists because sometimes null is not the same as missing. Specifically, * if a value is set to null we can give a better error message (indicating * where it was set to null) in case someone asks for the value. Also, null * overrides values set "earlier" in the search path, while missing values do * not. * */ final class ConfigNull extends AbstractConfigValue implements Serializable { private static final long serialVersionUID = 2L; ConfigNull(ConfigOrigin origin) { super(origin); } @Override public ConfigValueType valueType() { return ConfigValueType.NULL; } @Override public Object unwrapped() { return null; } @Override String transformToString() { return "null"; } @Override protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { sb.append("null"); } @Override protected ConfigNull newCopy(ConfigOrigin origin) { return new ConfigNull(origin); } // serialization all goes through SerializedConfigValue private Object writeReplace() throws ObjectStreamException { return new SerializedConfigValue(this); } }
1
0.933056
1
0.933056
game-dev
MEDIA
0.261468
game-dev
0.877211
1
0.877211
glKarin/com.n0n3m4.diii4a
32,916
Q3E/src/main/jni/source/thirdparty/SDL/SDL_gamecontroller.h
/* Simple DirectMedia Layer Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * \file SDL_gamecontroller.h * * Include file for SDL game controller event handling */ #ifndef SDL_gamecontroller_h_ #define SDL_gamecontroller_h_ #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_rwops.h" #include "SDL_sensor.h" #include "SDL_joystick.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \file SDL_gamecontroller.h * * In order to use these functions, SDL_Init() must have been called * with the ::SDL_INIT_GAMECONTROLLER flag. This causes SDL to scan the system * for game controllers, and load appropriate drivers. * * If you would like to receive controller updates while the application * is in the background, you should set the following hint before calling * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS */ /** * The gamecontroller structure used to identify an SDL game controller */ struct _SDL_GameController; typedef struct _SDL_GameController SDL_GameController; typedef enum { SDL_CONTROLLER_TYPE_UNKNOWN = 0, SDL_CONTROLLER_TYPE_XBOX360, SDL_CONTROLLER_TYPE_XBOXONE, SDL_CONTROLLER_TYPE_PS3, SDL_CONTROLLER_TYPE_PS4, SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO, SDL_CONTROLLER_TYPE_VIRTUAL, SDL_CONTROLLER_TYPE_PS5, SDL_CONTROLLER_TYPE_AMAZON_LUNA, SDL_CONTROLLER_TYPE_GOOGLE_STADIA } SDL_GameControllerType; typedef enum { SDL_CONTROLLER_BINDTYPE_NONE = 0, SDL_CONTROLLER_BINDTYPE_BUTTON, SDL_CONTROLLER_BINDTYPE_AXIS, SDL_CONTROLLER_BINDTYPE_HAT } SDL_GameControllerBindType; /** * Get the SDL joystick layer binding for this controller button/axis mapping */ typedef struct SDL_GameControllerButtonBind { SDL_GameControllerBindType bindType; union { int button; int axis; struct { int hat; int hat_mask; } hat; } value; } SDL_GameControllerButtonBind; /** * To count the number of game controllers in the system for the following: * * ```c * int nJoysticks = SDL_NumJoysticks(); * int nGameControllers = 0; * for (int i = 0; i < nJoysticks; i++) { * if (SDL_IsGameController(i)) { * nGameControllers++; * } * } * ``` * * Using the SDL_HINT_GAMECONTROLLERCONFIG hint or the SDL_GameControllerAddMapping() you can add support for controllers SDL is unaware of or cause an existing controller to have a different binding. The format is: * guid,name,mappings * * Where GUID is the string value from SDL_JoystickGetGUIDString(), name is the human readable string for the device and mappings are controller mappings to joystick ones. * Under Windows there is a reserved GUID of "xinput" that covers any XInput devices. * The mapping format for joystick is: * bX - a joystick button, index X * hX.Y - hat X with value Y * aX - axis X of the joystick * Buttons can be used as a controller axis and vice versa. * * This string shows an example of a valid mapping for a controller * * ```c * "03000000341a00003608000000000000,PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7", * ``` */ /** * Load a set of Game Controller mappings from a seekable SDL data stream. * * You can call this function several times, if needed, to load different * database files. * * If a new mapping is loaded for an already known controller GUID, the later * version will overwrite the one currently loaded. * * Mappings not belonging to the current platform or with no platform field * specified will be ignored (i.e. mappings for Linux will be ignored in * Windows, etc). * * This function will load the text database entirely in memory before * processing it, so take this into consideration if you are in a memory * constrained environment. * * \param rw the data stream for the mappings to be added * \param freerw non-zero to close the stream after being read * \returns the number of mappings added or -1 on error; call SDL_GetError() * for more information. * * \since This function is available since SDL 2.0.2. * * \sa SDL_GameControllerAddMapping * \sa SDL_GameControllerAddMappingsFromFile * \sa SDL_GameControllerMappingForGUID */ extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw); /** * Load a set of mappings from a file, filtered by the current SDL_GetPlatform() * * Convenience macro. */ #define SDL_GameControllerAddMappingsFromFile(file) SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), 1) /** * Add support for controllers that SDL is unaware of or to cause an existing * controller to have a different binding. * * The mapping string has the format "GUID,name,mapping", where GUID is the * string value from SDL_JoystickGetGUIDString(), name is the human readable * string for the device and mappings are controller mappings to joystick * ones. Under Windows there is a reserved GUID of "xinput" that covers all * XInput devices. The mapping format for joystick is: {| |bX |a joystick * button, index X |- |hX.Y |hat X with value Y |- |aX |axis X of the joystick * |} Buttons can be used as a controller axes and vice versa. * * This string shows an example of a valid mapping for a controller: * * ```c * "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7" * ``` * * \param mappingString the mapping string * \returns 1 if a new mapping is added, 0 if an existing mapping is updated, * -1 on error; call SDL_GetError() for more information. * * \sa SDL_GameControllerMapping * \sa SDL_GameControllerMappingForGUID */ extern DECLSPEC int SDLCALL SDL_GameControllerAddMapping(const char* mappingString); /** * Get the number of mappings installed. * * \returns the number of mappings. */ extern DECLSPEC int SDLCALL SDL_GameControllerNumMappings(void); /** * Get the mapping at a particular index. * * \returns the mapping string. Must be freed with SDL_free(). Returns NULL if * the index is out of range. */ extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForIndex(int mapping_index); /** * Get the game controller mapping string for a given GUID. * * The returned string must be freed with SDL_free(). * * \param guid a structure containing the GUID for which a mapping is desired * \returns a mapping string or NULL on error; call SDL_GetError() for more * information. * * \sa SDL_JoystickGetDeviceGUID * \sa SDL_JoystickGetGUID */ extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid); /** * Get the current mapping of a Game Controller. * * The returned string must be freed with SDL_free(). * * Details about mappings are discussed with SDL_GameControllerAddMapping(). * * \param gamecontroller the game controller you want to get the current * mapping for * \returns a string that has the controller's mapping or NULL if no mapping * is available; call SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerAddMapping * \sa SDL_GameControllerMappingForGUID */ extern DECLSPEC char * SDLCALL SDL_GameControllerMapping(SDL_GameController *gamecontroller); /** * Check if the given joystick is supported by the game controller interface. * * `joystick_index` is the same as the `device_index` passed to * SDL_JoystickOpen(). * * \param joystick_index the device_index of a device, up to * SDL_NumJoysticks() * \returns SDL_TRUE if the given joystick is supported by the game controller * interface, SDL_FALSE if it isn't or it's an invalid index. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerNameForIndex * \sa SDL_GameControllerOpen */ extern DECLSPEC SDL_bool SDLCALL SDL_IsGameController(int joystick_index); /** * Get the implementation dependent name for the game controller. * * This function can be called before any controllers are opened. * * `joystick_index` is the same as the `device_index` passed to * SDL_JoystickOpen(). * * \param joystick_index the device_index of a device, from zero to * SDL_NumJoysticks()-1 * \returns the implementation-dependent name for the game controller, or NULL * if there is no name or the index is invalid. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerName * \sa SDL_GameControllerOpen * \sa SDL_IsGameController */ extern DECLSPEC const char *SDLCALL SDL_GameControllerNameForIndex(int joystick_index); /** * Get the type of a game controller. * * This can be called before any controllers are opened. * * \param joystick_index the device_index of a device, from zero to * SDL_NumJoysticks()-1 * \returns the controller type. */ extern DECLSPEC SDL_GameControllerType SDLCALL SDL_GameControllerTypeForIndex(int joystick_index); /** * Get the mapping of a game controller. * * This can be called before any controllers are opened. * * \param joystick_index the device_index of a device, from zero to * SDL_NumJoysticks()-1 * \returns the mapping string. Must be freed with SDL_free(). Returns NULL if * no mapping is available. */ extern DECLSPEC char *SDLCALL SDL_GameControllerMappingForDeviceIndex(int joystick_index); /** * Open a game controller for use. * * `joystick_index` is the same as the `device_index` passed to * SDL_JoystickOpen(). * * The index passed as an argument refers to the N'th game controller on the * system. This index is not the value which will identify this controller in * future controller events. The joystick's instance id (SDL_JoystickID) will * be used there instead. * * \param joystick_index the device_index of a device, up to * SDL_NumJoysticks() * \returns a gamecontroller identifier or NULL if an error occurred; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerClose * \sa SDL_GameControllerNameForIndex * \sa SDL_IsGameController */ extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerOpen(int joystick_index); /** * Get the SDL_GameController associated with an instance id. * * \param joyid the instance id to get the SDL_GameController for * \returns an SDL_GameController on success or NULL on failure; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.4. */ extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromInstanceID(SDL_JoystickID joyid); /** * Get the SDL_GameController associated with a player index. * * Please note that the player index is _not_ the device index, nor is it the * instance id! * * \param player_index the player index, which is not the device index or the * instance id! * \returns the SDL_GameController associated with a player index. * * \sa SDL_GameControllerGetPlayerIndex * \sa SDL_GameControllerSetPlayerIndex */ extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromPlayerIndex(int player_index); /** * Get the implementation-dependent name for an opened game controller. * * This is the same name as returned by SDL_GameControllerNameForIndex(), but * it takes a controller identifier instead of the (unstable) device index. * * \param gamecontroller a game controller identifier previously returned by * SDL_GameControllerOpen() * \returns the implementation dependent name for the game controller, or NULL * if there is no name or the identifier passed is invalid. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerNameForIndex * \sa SDL_GameControllerOpen */ extern DECLSPEC const char *SDLCALL SDL_GameControllerName(SDL_GameController *gamecontroller); /** * Get the type of this currently opened controller * * This is the same name as returned by SDL_GameControllerTypeForIndex(), but * it takes a controller identifier instead of the (unstable) device index. * * \param gamecontroller the game controller object to query. * \returns the controller type. */ extern DECLSPEC SDL_GameControllerType SDLCALL SDL_GameControllerGetType(SDL_GameController *gamecontroller); /** * Get the player index of an opened game controller. * * For XInput controllers this returns the XInput user index. * * \param gamecontroller the game controller object to query. * \returns the player index for controller, or -1 if it's not available. */ extern DECLSPEC int SDLCALL SDL_GameControllerGetPlayerIndex(SDL_GameController *gamecontroller); /** * Set the player index of an opened game controller. * * \param gamecontroller the game controller object to adjust. * \param player_index Player index to assign to this controller. */ extern DECLSPEC void SDLCALL SDL_GameControllerSetPlayerIndex(SDL_GameController *gamecontroller, int player_index); /** * Get the USB vendor ID of an opened controller, if available. * * If the vendor ID isn't available this function returns 0. * * \param gamecontroller the game controller object to query. * \return the USB vendor ID, or zero if unavailable. */ extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetVendor(SDL_GameController *gamecontroller); /** * Get the USB product ID of an opened controller, if available. * * If the product ID isn't available this function returns 0. * * \param gamecontroller the game controller object to query. * \return the USB product ID, or zero if unavailable. */ extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProduct(SDL_GameController *gamecontroller); /** * Get the product version of an opened controller, if available. * * If the product version isn't available this function returns 0. * * \param gamecontroller the game controller object to query. * \return the USB product version, or zero if unavailable. */ extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProductVersion(SDL_GameController *gamecontroller); /** * Get the serial number of an opened controller, if available. * * Returns the serial number of the controller, or NULL if it is not * available. * * \param gamecontroller the game controller object to query. * \return the serial number, or NULL if unavailable. */ extern DECLSPEC const char * SDLCALL SDL_GameControllerGetSerial(SDL_GameController *gamecontroller); /** * Check if a controller has been opened and is currently connected. * * \param gamecontroller a game controller identifier previously returned by * SDL_GameControllerOpen() * \returns SDL_TRUE if the controller has been opened and is currently * connected, or SDL_FALSE if not. * * \sa SDL_GameControllerClose * \sa SDL_GameControllerOpen */ extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerGetAttached(SDL_GameController *gamecontroller); /** * Get the Joystick ID from a Game Controller. * * This function will give you a SDL_Joystick object, which allows you to use * the SDL_Joystick functions with a SDL_GameController object. This would be * useful for getting a joystick's position at any given time, even if it * hasn't moved (moving it would produce an event, which would have the axis' * value). * * The pointer returned is owned by the SDL_GameController. You should not * call SDL_JoystickClose() on it, for example, since doing so will likely * cause SDL to crash. * * \param gamecontroller the game controller object that you want to get a * joystick from * \returns a SDL_Joystick object; call SDL_GetError() for more information. */ extern DECLSPEC SDL_Joystick *SDLCALL SDL_GameControllerGetJoystick(SDL_GameController *gamecontroller); /** * Query or change current state of Game Controller events. * * If controller events are disabled, you must call SDL_GameControllerUpdate() * yourself and check the state of the controller when you want controller * information. * * Any number can be passed to SDL_GameControllerEventState(), but only -1, 0, * and 1 will have any effect. Other numbers will just be returned. * * \param state can be one of `SDL_QUERY`, `SDL_IGNORE`, or `SDL_ENABLE` * \returns the same value passed to the function, with exception to -1 * (SDL_QUERY), which will return the current state. * * \since This function is available since SDL 2.0.0. * * \sa SDL_JoystickEventState */ extern DECLSPEC int SDLCALL SDL_GameControllerEventState(int state); /** * Manually pump game controller updates if not using the loop. * * This function is called automatically by the event loop if events are * enabled. Under such circumstances, it will not be necessary to call this * function. */ extern DECLSPEC void SDLCALL SDL_GameControllerUpdate(void); /** * The list of axes available from a controller * * Thumbstick axis values range from SDL_JOYSTICK_AXIS_MIN to SDL_JOYSTICK_AXIS_MAX, * and are centered within ~8000 of zero, though advanced UI will allow users to set * or autodetect the dead zone, which varies between controllers. * * Trigger axis values range from 0 to SDL_JOYSTICK_AXIS_MAX. */ typedef enum { SDL_CONTROLLER_AXIS_INVALID = -1, SDL_CONTROLLER_AXIS_LEFTX, SDL_CONTROLLER_AXIS_LEFTY, SDL_CONTROLLER_AXIS_RIGHTX, SDL_CONTROLLER_AXIS_RIGHTY, SDL_CONTROLLER_AXIS_TRIGGERLEFT, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, SDL_CONTROLLER_AXIS_MAX } SDL_GameControllerAxis; /** * Convert a string into SDL_GameControllerAxis enum. * * This function is called internally to translate SDL_GameController mapping * strings for the underlying joystick device into the consistent * SDL_GameController mapping. You do not normally need to call this function * unless you are parsing SDL_GameController mappings in your own code. * * Note specially that "righttrigger" and "lefttrigger" map to * `SDL_CONTROLLER_AXIS_TRIGGERRIGHT` and `SDL_CONTROLLER_AXIS_TRIGGERLEFT`, * respectively. * * \param str string representing a SDL_GameController axis * \returns the SDL_GameControllerAxis enum corresponding to the input string, * or `SDL_CONTROLLER_AXIS_INVALID` if no match was found. * * \sa SDL_GameControllerGetStringForAxis */ extern DECLSPEC SDL_GameControllerAxis SDLCALL SDL_GameControllerGetAxisFromString(const char *str); /** * Convert from an SDL_GameControllerAxis enum to a string. * * The caller should not SDL_free() the returned string. * * \param axis an enum value for a given SDL_GameControllerAxis * \returns a string for the given axis, or NULL if an invalid axis is * specified. The string returned is of the format used by * SDL_GameController mapping strings. * * \sa SDL_GameControllerGetAxisFromString */ extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForAxis(SDL_GameControllerAxis axis); /** * Get the SDL joystick layer binding for a controller axis mapping. * * \param gamecontroller a game controller * \param axis an axis enum value (one of the SDL_GameControllerAxis values) * \returns a SDL_GameControllerButtonBind describing the bind. On failure * (like the given Controller axis doesn't exist on the device), its * `.bindType` will be `SDL_CONTROLLER_BINDTYPE_NONE`. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerGetBindForButton */ extern DECLSPEC SDL_GameControllerButtonBind SDLCALL SDL_GameControllerGetBindForAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis); /** * Query whether a game controller has a given axis. * * This merely reports whether the controller's mapping defined this axis, as * that is all the information SDL has about the physical device. * * \param gamecontroller a game controller * \param axis an axis enum value (an SDL_GameControllerAxis value) * \returns SDL_TRUE if the controller has this axis, SDL_FALSE otherwise. */ extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis); /** * Get the current state of an axis control on a game controller. * * The axis indices start at index 0. * * The state is a value ranging from -32768 to 32767. Triggers, however, range * from 0 to 32767 (they never return a negative value). * * \param gamecontroller a game controller * \param axis an axis index (one of the SDL_GameControllerAxis values) * \returns axis state (including 0) on success or 0 (also) on failure; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerGetButton */ extern DECLSPEC Sint16 SDLCALL SDL_GameControllerGetAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis); /** * The list of buttons available from a controller */ typedef enum { SDL_CONTROLLER_BUTTON_INVALID = -1, SDL_CONTROLLER_BUTTON_A, SDL_CONTROLLER_BUTTON_B, SDL_CONTROLLER_BUTTON_X, SDL_CONTROLLER_BUTTON_Y, SDL_CONTROLLER_BUTTON_BACK, SDL_CONTROLLER_BUTTON_GUIDE, SDL_CONTROLLER_BUTTON_START, SDL_CONTROLLER_BUTTON_LEFTSTICK, SDL_CONTROLLER_BUTTON_RIGHTSTICK, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, SDL_CONTROLLER_BUTTON_DPAD_UP, SDL_CONTROLLER_BUTTON_DPAD_DOWN, SDL_CONTROLLER_BUTTON_DPAD_LEFT, SDL_CONTROLLER_BUTTON_DPAD_RIGHT, SDL_CONTROLLER_BUTTON_MISC1, /* Xbox Series X share button, PS5 microphone button, Nintendo Switch Pro capture button, Amazon Luna microphone button */ SDL_CONTROLLER_BUTTON_PADDLE1, /* Xbox Elite paddle P1 */ SDL_CONTROLLER_BUTTON_PADDLE2, /* Xbox Elite paddle P3 */ SDL_CONTROLLER_BUTTON_PADDLE3, /* Xbox Elite paddle P2 */ SDL_CONTROLLER_BUTTON_PADDLE4, /* Xbox Elite paddle P4 */ SDL_CONTROLLER_BUTTON_TOUCHPAD, /* PS4/PS5 touchpad button */ SDL_CONTROLLER_BUTTON_MAX } SDL_GameControllerButton; /** * Convert a string into an SDL_GameControllerButton enum. * * This function is called internally to translate SDL_GameController mapping * strings for the underlying joystick device into the consistent * SDL_GameController mapping. You do not normally need to call this function * unless you are parsing SDL_GameController mappings in your own code. * * \param str string representing a SDL_GameController axis * \returns the SDL_GameControllerButton enum corresponding to the input * string, or `SDL_CONTROLLER_AXIS_INVALID` if no match was found. */ extern DECLSPEC SDL_GameControllerButton SDLCALL SDL_GameControllerGetButtonFromString(const char *str); /** * Convert from an SDL_GameControllerButton enum to a string. * * The caller should not SDL_free() the returned string. * * \param button an enum value for a given SDL_GameControllerButton * \returns a string for the given button, or NULL if an invalid axis is * specified. The string returned is of the format used by * SDL_GameController mapping strings. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerGetButtonFromString */ extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForButton(SDL_GameControllerButton button); /** * Get the SDL joystick layer binding for a controller button mapping. * * \param gamecontroller a game controller * \param button an button enum value (an SDL_GameControllerButton value) * \returns a SDL_GameControllerButtonBind describing the bind. On failure * (like the given Controller button doesn't exist on the device), * its `.bindType` will be `SDL_CONTROLLER_BINDTYPE_NONE`. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerGetBindForAxis */ extern DECLSPEC SDL_GameControllerButtonBind SDLCALL SDL_GameControllerGetBindForButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button); /** * Query whether a game controller has a given button. * * This merely reports whether the controller's mapping defined this button, * as that is all the information SDL has about the physical device. * * \param gamecontroller a game controller * \param button a button enum value (an SDL_GameControllerButton value) * \returns SDL_TRUE if the controller has this button, SDL_FALSE otherwise. */ extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button); /** * Get the current state of a button on a game controller. * * \param gamecontroller a game controller * \param button a button index (one of the SDL_GameControllerButton values) * \returns 1 for pressed state or 0 for not pressed state or error; call * SDL_GetError() for more information. * * \since This function is available since SDL 2.0.0. * * \sa SDL_GameControllerGetAxis */ extern DECLSPEC Uint8 SDLCALL SDL_GameControllerGetButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button); /** * Get the number of touchpads on a game controller. */ extern DECLSPEC int SDLCALL SDL_GameControllerGetNumTouchpads(SDL_GameController *gamecontroller); /** * Get the number of supported simultaneous fingers on a touchpad on a game * controller. */ extern DECLSPEC int SDLCALL SDL_GameControllerGetNumTouchpadFingers(SDL_GameController *gamecontroller, int touchpad); /** * Get the current state of a finger on a touchpad on a game controller. */ extern DECLSPEC int SDLCALL SDL_GameControllerGetTouchpadFinger(SDL_GameController *gamecontroller, int touchpad, int finger, Uint8 *state, float *x, float *y, float *pressure); /** * Return whether a game controller has a particular sensor. * * \param gamecontroller The controller to query * \param type The type of sensor to query * \returns SDL_TRUE if the sensor exists, SDL_FALSE otherwise. */ extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasSensor(SDL_GameController *gamecontroller, SDL_SensorType type); /** * Set whether data reporting for a game controller sensor is enabled. * * \param gamecontroller The controller to update * \param type The type of sensor to enable/disable * \param enabled Whether data reporting should be enabled * \returns 0 or -1 if an error occurred. */ extern DECLSPEC int SDLCALL SDL_GameControllerSetSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type, SDL_bool enabled); /** * Query whether sensor data reporting is enabled for a game controller. * * \param gamecontroller The controller to query * \param type The type of sensor to query * \returns SDL_TRUE if the sensor is enabled, SDL_FALSE otherwise. */ extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerIsSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type); /** * Get the data rate (number of events per second) of a game controller * sensor. * * \param gamecontroller The controller to query * \param type The type of sensor to query * \return the data rate, or 0.0f if the data rate is not available. */ extern DECLSPEC float SDLCALL SDL_GameControllerGetSensorDataRate(SDL_GameController *gamecontroller, SDL_SensorType type); /** * Get the current state of a game controller sensor. * * The number of values and interpretation of the data is sensor dependent. * See SDL_sensor.h for the details for each type of sensor. * * \param gamecontroller The controller to query * \param type The type of sensor to query * \param data A pointer filled with the current sensor state * \param num_values The number of values to write to data * \return 0 or -1 if an error occurred. */ extern DECLSPEC int SDLCALL SDL_GameControllerGetSensorData(SDL_GameController *gamecontroller, SDL_SensorType type, float *data, int num_values); /** * Start a rumble effect on a game controller. * * Each call to this function cancels any previous rumble effect, and calling * it with 0 intensity stops any rumbling. * * \param gamecontroller The controller to vibrate * \param low_frequency_rumble The intensity of the low frequency (left) * rumble motor, from 0 to 0xFFFF * \param high_frequency_rumble The intensity of the high frequency (right) * rumble motor, from 0 to 0xFFFF * \param duration_ms The duration of the rumble effect, in milliseconds * \returns 0, or -1 if rumble isn't supported on this controller */ extern DECLSPEC int SDLCALL SDL_GameControllerRumble(SDL_GameController *gamecontroller, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms); /** * Start a rumble effect in the game controller's triggers. * * Each call to this function cancels any previous trigger rumble effect, and * calling it with 0 intensity stops any rumbling. * * Note that this is rumbling of the _triggers_ and not the game controller as * a whole. The first controller to offer this feature was the PlayStation 5's * DualShock 5. * * \param gamecontroller The controller to vibrate * \param left_rumble The intensity of the left trigger rumble motor, from 0 * to 0xFFFF * \param right_rumble The intensity of the right trigger rumble motor, from 0 * to 0xFFFF * \param duration_ms The duration of the rumble effect, in milliseconds * \returns 0, or -1 if trigger rumble isn't supported on this controller */ extern DECLSPEC int SDLCALL SDL_GameControllerRumbleTriggers(SDL_GameController *gamecontroller, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms); /** * Query whether a game controller has an LED. * * \param gamecontroller The controller to query * \returns SDL_TRUE, or SDL_FALSE if this controller does not have a * modifiable LED */ extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasLED(SDL_GameController *gamecontroller); /** * Update a game controller's LED color. * * \param gamecontroller The controller to update * \param red The intensity of the red LED * \param green The intensity of the green LED * \param blue The intensity of the blue LED * \returns 0, or -1 if this controller does not have a modifiable LED */ extern DECLSPEC int SDLCALL SDL_GameControllerSetLED(SDL_GameController *gamecontroller, Uint8 red, Uint8 green, Uint8 blue); /** * Send a controller specific effect packet * * \param gamecontroller The controller to affect * \param data The data to send to the controller * \param size The size of the data to send to the controller * \returns 0, or -1 if this controller or driver doesn't support effect * packets */ extern DECLSPEC int SDLCALL SDL_GameControllerSendEffect(SDL_GameController *gamecontroller, const void *data, int size); /** * Close a game controller previously opened with SDL_GameControllerOpen(). * * \param gamecontroller a game controller identifier previously returned by * SDL_GameControllerOpen() * * \sa SDL_GameControllerOpen */ extern DECLSPEC void SDLCALL SDL_GameControllerClose(SDL_GameController *gamecontroller); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_gamecontroller_h_ */ /* vi: set ts=4 sw=4 expandtab: */
1
0.893091
1
0.893091
game-dev
MEDIA
0.925303
game-dev
0.708332
1
0.708332
Baste-RainGames/AnimationPlayer
1,649
Runtime/AnimationPlayerExtensions.cs
//using System; //using System.Collections; //using System.Collections.Generic; //using UnityEngine; // //namespace Animation_Player //{ // public static class AnimationPlayerExtensions // { // // public static IEnumerable<T> FilterByType<T>(this IEnumerable collection) where T : class // { // foreach (var element in collection) // { // if (element is T asT) // yield return asT; // } // } // // public static T EnsureComponent<T>(this GameObject obj) where T : Component // { // var t = obj.GetComponent<T>(); // if (t == null) // t = obj.AddComponent<T>(); // return t; // } // // public static bool IsInBounds<T>(this List<T> arr, int index) // { // if (arr == null) // return false; // if (arr.Count == 0) // return false; // return index >= 0 && index < arr.Count; // } // // public static V GetOrAdd<K, V>(this Dictionary<K, V> dict, K key) where V : new() // { // if (dict.TryGetValue(key, out var value)) // return value; // // return dict[key] = new V(); // } // // public static float Duration(this AnimationCurve curve) { // if (curve == null) { // throw new ArgumentNullException(nameof(curve)); // } // // if (curve.keys.Length == 0) { // return 0; // } // // return curve[curve.length - 1].time - curve[0].time; // } // } //}
1
0.696104
1
0.696104
game-dev
MEDIA
0.641434
game-dev
0.833663
1
0.833663
StansAssets/com.stansassets.foundation
5,064
Runtime/Extensions/UnityEngine/TransformExtensions.cs
using UnityEngine; namespace StansAssets.Foundation.Extensions { /// <summary> /// Unity `Transform` extension methods. /// </summary> public static class TransformExtensions { /// <summary> /// Sets <see cref="Transform.lossyScale"/> value. /// </summary> /// <param name="transform">Transform component.</param> /// <param name="lossyScale">New lossyScale value.</param> public static void SetLossyScale(this Transform transform, Vector3 lossyScale) { transform.localScale = Vector3.one; var currentLossyScale = transform.lossyScale; transform.localScale = new Vector3(lossyScale.x / currentLossyScale.x, lossyScale.y / currentLossyScale.y, lossyScale.z / currentLossyScale.z); } /// <summary> /// Reset <see cref="Transform"/> component position, scale and rotation. /// </summary> /// <param name="transform">Transform component.</param> /// <param name="relativeTo">Space enum the Reset method relative to. /// Space.Self (default value) resets local space values. /// Space.World resets absolute world space values. /// Using World space may cause visual deformations, which depends on a parent's scale</param> public static void Reset(this Transform transform, Space relativeTo = Space.Self) { switch (relativeTo) { case Space.Self: transform.localScale = Vector3.one; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; break; case Space.World: transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity); transform.SetLossyScale(Vector3.one); break; default: throw new System.ArgumentException($"Parameter '{nameof(relativeTo)}' contains unknown value. '{nameof(Space.Self)}' and '{nameof(Space.World)}' are accepted", nameof(relativeTo)); } } /// <summary> /// Removes all transform children. /// </summary> /// <param name="transform">Transform component.</param> /// <param name="activeOnly">Will ignore disabled game-objects when set to <c>true</c>. </param> /// <returns></returns> public static void ClearHierarchy(this Transform transform, bool activeOnly = false) { if (transform.childCount == 0) return; for(int i = transform.childCount-1; i >= 0; --i) { GameObject child = transform.GetChild(i).gameObject; if (child == null) continue; if (activeOnly && !child.activeSelf) continue; Object.DestroyImmediate(transform.GetChild(i).gameObject); } } /// <summary> /// Find or create child with name. /// </summary> /// <param name="transform">Transform component.</param> /// <param name="name">Child name.</param> /// <returns>Child <see cref="Transform"/> component instance.</returns> public static Transform FindOrCreateChild(this Transform transform, string name) { var part = transform.Find(name); if (part == null) { part = new GameObject(name).transform; part.SetParent(transform, false); } return part; } /// <summary> /// Searches for a child with the provided name across the whole game objects hierarchy. /// </summary> /// <param name="transform">Transform component.</param> /// <param name="childName">Child name.</param> /// <returns>Child <see cref="Transform"/> component instance.</returns> public static Transform FindChildRecursively(this Transform transform, string childName) { foreach (Transform child in transform) { if (child.name == childName) { return child; } var found = FindChildRecursively(child, childName); if (found != null) { return found; } } return null; } /// <summary> /// Sets the <see cref="GameObject"/>'s Static flag. /// </summary> /// <param name="transform">Transform component.</param> /// <param name="includeChildren">If true, the Static flag will be set to it's children as well.</param> public static void SetStatic(this Transform transform, bool includeChildren = false) { transform.gameObject.isStatic = true; if (includeChildren) { var transforms = transform.GetComponentsInChildren<Transform>(true); foreach (var t in transforms) { t.gameObject.isStatic = true; } } } } }
1
0.918941
1
0.918941
game-dev
MEDIA
0.646226
game-dev
0.958404
1
0.958404
gamephysicsweekend/VulkanRenderer
1,336
code/Physics/Constraints/ConstraintConstantVelocity.h
// // ConstraintConstantVelocity.h // #pragma once #include "ConstraintBase.h" /* ================================ ConstraintConstantVelocity ================================ */ class ConstraintConstantVelocity : public Constraint { public: ConstraintConstantVelocity() : Constraint(), m_cachedLambda( 2 ), m_Jacobian( 2, 12 ) { m_cachedLambda.Zero(); m_baumgarte = 0.0f; } void PreSolve( const float dt_sec ) override; void Solve() override; void PostSolve() override; Quat m_q0; // The initial relative quaternion q1 * q2^-1 VecN m_cachedLambda; MatMN m_Jacobian; float m_baumgarte; }; /* ================================ ConstraintConstantVelocityLimited ================================ */ class ConstraintConstantVelocityLimited : public Constraint { public: ConstraintConstantVelocityLimited() : Constraint(), m_cachedLambda( 4 ), m_Jacobian( 4, 12 ) { m_cachedLambda.Zero(); m_baumgarte = 0.0f; m_isAngleViolatedU = false; m_isAngleViolatedV = false; m_angleU = 0.0f; m_angleV = 0.0f; } void PreSolve( const float dt_sec ) override; void Solve() override; void PostSolve() override; Quat m_q0; // The initial relative quaternion q1^-1 * q2 VecN m_cachedLambda; MatMN m_Jacobian; float m_baumgarte; bool m_isAngleViolatedU; bool m_isAngleViolatedV; float m_angleU; float m_angleV; };
1
0.938035
1
0.938035
game-dev
MEDIA
0.578052
game-dev,graphics-rendering
0.927859
1
0.927859
Lallassu/wizardwarz
6,834
server/player.js
///////////////////////////////////////////////////////////// // Autor: Nergal // Date: 2014-01-31 ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // Player class ///////////////////////////////////////////////////////////// function Player() { this.name = undefined; this.px = 0; this.py = 0; this.pz = 0; this.rx = 0; this.ry = 0; this.rz = 0; this.id = undefined; this.experience = 0; this.max_health = 100; this.max_power = 100; this.health = 100; this.level = 1; this.power = 0; this.deaths = 0; this.kills = 0; this.playtime = 0; this.spell = undefined; this.spells = new Array(); this.type = "player"; this.scale = 1.5; this.dead = 0; this.next_lvl_exp = 0; Player.prototype.CheckLevelUp = function(data, dbh, check) { var levelup = 0; var left = 0; if(this.level == 1 && this.experience > 10) { levelup = 1; left = 50; } else if(this.level == 2 && this.experience > 50) { levelup = 1; left = 100; } else if(this.level == 3 && this.experience > 100) { levelup = 1; left = 150; } else if(this.level == 4 && this.experience > 150) { levelup = 1; left = 250; } else if(this.level == 5 && this.experience > 250) { levelup = 1; left = 350; } else if(this.level == 6 && this.experience > 350) { levelup = 1; left = 450; } else if(this.level == 7 && this.experience > 450) { levelup = 1; left = 550; } else if(this.level == 8 && this.experience > 550) { levelup = 1; left = 1000; } if(check) { this.next_lvl_exp = left; return; } if(levelup) { this.level++; dbh.query( 'update players set level = level+1, health = health+10 where id = ?', [this.id]); data.socket.emit("ServerMsg", {msg_color: "#33FF33", msg: "** Level up ("+this.level+")! **"}); // data.socket.broadcast.emit("LevelUp", {player_id: this.id}); data.socket.emit("LevelUp", {player_id: this.id, exp: this.exp, level: this.level, nextlvlexp: left}); // } } }; Player.prototype.Reset = function() { this.health = this.max_health; this.spells.length = 0; this.spell = undefined; this.kills = 0; this.deaths = 0; this.power = 0; this.dead = 0; }; Player.prototype.SaveToDB = function() { // TBD: Save all data to DB. }; Player.prototype.KillPlayer = function(data, dbh) { var lvl_diff = data.other_level - this.level; var gained_exp = data.exp; if(lvl_diff > 0) { gained_exp = (data.exp*lvl_diff); } var exp = parseInt(this.experience)*parseInt(gainex_exp); this.experience = exp; console.log("* Player "+this.name+" gained "+ gained_exp + " NOW: "+this.experience); this.kills++; this.CheckLevelUp(data, dbh); dbh.query( 'update players set kills = kills + 1, experience = experience + ? where id = ?', [gained_exp, this.id]); return gained_exp; }; Player.prototype.Died = function(data, dbh) { this.deaths++; this.dead = 1; this.spell = undefined; this.spells.length = 0; dbh.query( 'update players set deaths = deaths + 1 where id = ?', [this.id]); }; Player.prototype.AddItem = function(item) { if(item == undefined) { return 0; } if(item.type == "health") { this.IncrHealth(item.amount); return 1; } else if(item.type == "power") { this.IncrPower(item.amount); return 1; } else { var exists = 0; for(var i=0; i < this.spells.length; i++) { if(this.spells[i] == item.type) { exists = 1; break; } } if(exists) { return 0; } this.spells.push(item); this.spell = item; return 1; } }; Player.prototype.IncrPower = function(amount) { this.power += amount; if(this.power > this.max_power) { this.power = this.max_power; } } Player.prototype.DecrPower = function(amount) { this.power -= amount; if(this.power < 0) { this.power = 0; } } Player.prototype.IncrHealth = function(amount) { this.health += amount; if(this.health > this.max_health) { this.health = this.max_health; } } Player.prototype.DecrHealth = function(amount) { this.health -= amount; if(this.health < 0) { this.health = 0; } } Player.prototype.GetUniqueID = function() { return ++this.unique_count; }; Player.prototype.CreateNew = function(args, world, id) { this.name = args.name; this.id = id; console.log("Create new player: "+args.name + " with id: "+this.id); this.GenerateSpawnPoint(world); }; Player.prototype.GenerateSpawnPoint = function(world) { this.health = this.max_health; this.spells.length = 0; this.spell = undefined; this.dead = 0; this.power = 0; this.px = Math.round(1-Math.random()*3000)+world.world_size/2; this.pz = Math.round(1-Math.random()*3000)+world.world_size/2; this.py = 1000; // spawn up in the air console.log("Generate spawn point("+this.name+"): "+this.px+ ","+this.py+","+this.pz); }; Player.prototype.CreateOld = function(args) { // Get from database => data.user, data.password this.GenerateSpawnPoint(); }; Player.prototype.UpdatePosition = function(data) { // Update position this.px = data.px; this.py = data.py; this.pz = data.pz; this.rx = data.rx; this.ry = data.ry; this.rz = data.rz; }; } function Bot() { Player.call(this); Bot.prototype.Spawn = function() { this.name = "[BOT] "+args.name; this.id = id; console.log("Create new bot: "+args.name + " with id: "+this.id); this.GenerateSpawnPoint(world); }; Bot.prototype.Run = function() { }; } Bot.prototype = new Player(); Bot.prototype.constructor = Bot; module.exports = { Player: Player, Bot: Bot };
1
0.633454
1
0.633454
game-dev
MEDIA
0.780532
game-dev
0.845978
1
0.845978
KhronosGroup/UnityGLTF
3,971
Runtime/Scripts/GLTFRecorderComponent.cs
#if ENABLE_INPUT_SYSTEM && HAVE_INPUTSYSTEM #define NEW_INPUT #endif using System.Collections; using System.Linq; using UnityEngine; using UnityEngine.Events; using UnityGLTF.Plugins; #if NEW_INPUT using UnityEngine.InputSystem; #endif using UnityGLTF.Timeline; namespace UnityGLTF { public class GLTFRecorderComponent : MonoBehaviour { public string outputFile = "Assets/Recordings/Recorded_<Timestamp>.glb"; public Transform exportRoot; public bool recordBlendShapes = true; public bool recordRootInWorldSpace = true; public bool recordAnimationPointer = false; #if NEW_INPUT public InputAction recordingKey = new InputAction(binding: "<Keyboard>/F11"); #else public KeyCode recordingKey = KeyCode.F11; #endif public bool IsRecording => recorder?.IsRecording ?? false; protected GLTFRecorder recorder; public UnityEvent recordingStarted; public UnityEvent<string> recordingEnded; private double CurrentTime => #if UNITY_2020_1_OR_NEWER Time.timeAsDouble; #else Time.time; #endif [ContextMenu("Start Recording")] public virtual void StartRecording() { if (!isActiveAndEnabled) return; var settings = GLTFSettings.GetOrCreateSettings(); var shouldRecordBlendShapes = recordBlendShapes; if (settings.BlendShapeExportProperties == GLTFSettings.BlendShapeExportPropertyFlags.None && recordBlendShapes) { Debug.LogWarning("Attempting to record blend shapes but export is disabled in ProjectSettings/UnityGLTF. Set BlendShapeExportProperties to something other than \"None\" if you want to export them."); shouldRecordBlendShapes = false; } var shouldUseAnimationPointer = recordAnimationPointer; var animationPointerIsEnabled = settings.ExportPlugins?.Any(x => x is AnimationPointerExport && x.Enabled) ?? false; if (animationPointerIsEnabled && recordAnimationPointer) { Debug.LogWarning("Attempting to record KHR_animation_pointer but that is disabled in ProjectSettings/UnityGLTF. Please enable it."); shouldUseAnimationPointer = false; } recorder = new GLTFRecorder(exportRoot, shouldRecordBlendShapes, recordRootInWorldSpace, shouldUseAnimationPointer); recorder.StartRecording(CurrentTime); recordingStarted?.Invoke(); StartCoroutine(_UpdateRecording()); } [ContextMenu("Stop Recording")] public virtual void StopRecording() { var filename = outputFile.Replace("<Timestamp>", System.DateTime.Now.ToString("yyyyMMdd-HHmmss")); recorder.EndRecording(filename); recordingEnded?.Invoke(filename); } private void ToggleRecording() { if (!exportRoot || string.IsNullOrEmpty(outputFile)) { Debug.LogError($"[GLTFRecorderComponent] Can't record, please assign exportRoot and outputFile on {nameof(GLTFRecorderComponent)}", this); return; } if(IsRecording) { StopRecording(); Debug.Log("Recording Stopped", this); } else { StartRecording(); Debug.Log("Recording Started", this); } } #if NEW_INPUT private void Start() { recordingKey.performed += _ => ToggleRecording(); } private void OnEnable() { recordingKey.Enable(); } #else protected virtual void Update() { if(Input.GetKeyDown(recordingKey)) ToggleRecording(); } #endif protected virtual void OnDisable() { if(IsRecording) StopRecording(); #if NEW_INPUT recordingKey.Disable(); #endif } protected virtual void UpdateRecording() { if(CurrentTime > recorder.LastRecordedTime) recorder.UpdateRecording(CurrentTime); } private IEnumerator _UpdateRecording() { while (true) { yield return new WaitForEndOfFrame(); if (!IsRecording) yield break; UpdateRecording(); } } } }
1
0.830236
1
0.830236
game-dev
MEDIA
0.637442
game-dev
0.91156
1
0.91156
Direwolf20-MC/BuildingGadgets
1,547
src/main/java/com/direwolf20/buildinggadgets/common/items/modes/HorizontalWallMode.java
package com.direwolf20.buildinggadgets.common.items.modes; import net.minecraft.world.entity.player.Player; import net.minecraft.core.BlockPos; import java.util.ArrayList; import java.util.List; public class HorizontalWallMode extends AbstractMode { public HorizontalWallMode() { super(false); } @Override List<BlockPos> collect(UseContext context, Player player, BlockPos start) { List<BlockPos> coordinates = new ArrayList<>(); // Handle top and bottom first. int halfRange = context.getRange() / 2; if( XYZ.isAxisY(context.getHitSide()) ) { for (int i = -halfRange; i <= halfRange; i ++) { for(int j = -halfRange; j <= halfRange; j++) coordinates.add(new BlockPos(start.getX() - i, start.getY(), start.getZ() + j)); } return coordinates; } // Draw complete column then expand by half the range on both sides :D XYZ xyz = XYZ.fromFacing(context.getHitSide()); for (int i = 0; i < context.getRange(); i ++) { for(int j = -halfRange; j <= halfRange; j++) { int value = XYZ.invertOnFace(context.getHitSide(), i); coordinates.add( xyz == XYZ.X ? new BlockPos(start.getX() + value, start.getY(), start.getZ() + j) : new BlockPos(start.getX() + j, start.getY(), start.getZ() + value) ); } } return coordinates; } }
1
0.512833
1
0.512833
game-dev
MEDIA
0.689064
game-dev
0.700296
1
0.700296
werman/noise-suppression-for-voice
4,652
external/JUCE/extras/AudioPluginHost/Builds/Android/app/src/main/assets/Box2DTests/Tiles.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef TILES_H #define TILES_H /// This stress tests the dynamic tree broad-phase. This also shows that tile /// based collision is _not_ smooth due to Box2D not knowing about adjacency. class Tiles : public Test { public: enum { e_count = 20 }; Tiles() { m_fixtureCount = 0; b2Timer timer; { float32 a = 0.5f; b2BodyDef bd; bd.position.y = -a; b2Body* ground = m_world->CreateBody(&bd); #if 1 int32 N = 200; int32 M = 10; b2Vec2 position; position.y = 0.0f; for (int32 j = 0; j < M; ++j) { position.x = -N * a; for (int32 i = 0; i < N; ++i) { b2PolygonShape shape; shape.SetAsBox(a, a, position, 0.0f); ground->CreateFixture(&shape, 0.0f); ++m_fixtureCount; position.x += 2.0f * a; } position.y -= 2.0f * a; } #else int32 N = 200; int32 M = 10; b2Vec2 position; position.x = -N * a; for (int32 i = 0; i < N; ++i) { position.y = 0.0f; for (int32 j = 0; j < M; ++j) { b2PolygonShape shape; shape.SetAsBox(a, a, position, 0.0f); ground->CreateFixture(&shape, 0.0f); position.y -= 2.0f * a; } position.x += 2.0f * a; } #endif } { float32 a = 0.5f; b2PolygonShape shape; shape.SetAsBox(a, a); b2Vec2 x(-7.0f, 0.75f); b2Vec2 y; b2Vec2 deltaX(0.5625f, 1.25f); b2Vec2 deltaY(1.125f, 0.0f); for (int32 i = 0; i < e_count; ++i) { y = x; for (int32 j = i; j < e_count; ++j) { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position = y; //if (i == 0 && j == 0) //{ // bd.allowSleep = false; //} //else //{ // bd.allowSleep = true; //} b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 5.0f); ++m_fixtureCount; y += deltaY; } x += deltaX; } } m_createTime = timer.GetMilliseconds(); } void Step(Settings* settings) { const b2ContactManager& cm = m_world->GetContactManager(); int32 height = cm.m_broadPhase.GetTreeHeight(); int32 leafCount = cm.m_broadPhase.GetProxyCount(); int32 minimumNodeCount = 2 * leafCount - 1; float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f)); m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); m_textLine += 15; Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", m_createTime, m_fixtureCount); m_textLine += 15; //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; //if (m_stepCount == 400) //{ // tree->RebuildBottomUp(); //} } static Test* Create() { return new Tiles; } int32 m_fixtureCount; float32 m_createTime; }; #endif
1
0.883553
1
0.883553
game-dev
MEDIA
0.603344
game-dev
0.924381
1
0.924381
AzureeDev/payday-2-luajit
20,403
pd2-lua/core/lib/units/editor/corehub.lua
CoreHub = CoreHub or class(HubElement) Hub = Hub or class(CoreHub) function Hub:init(...) CoreHub.init(self, ...) end function CoreHub:init(unit) HubElement.init(self, unit) self._timeline_color = Vector3(0, 1, 0) self._hed.required_triggers = "all" self._hed.trigger_once = true self._hed.trigger_on_inverse = false self._hed.actions_data = {} self._hed.triggers_data = {} self._hed.default_test_hub = false self._hed.use_as_start = false self._hed.never_start = false self._hed.start_from_relay = "none" self._hed.hub_entered_from_zone = "none" table.insert(self._save_values, "required_triggers") table.insert(self._save_values, "actions_data") table.insert(self._save_values, "triggers_data") table.insert(self._save_values, "default_test_hub") table.insert(self._save_values, "trigger_once") table.insert(self._save_values, "trigger_on_inverse") table.insert(self._save_values, "use_as_start") table.insert(self._save_values, "never_start") table.insert(self._hed.action_types, "activate") table.insert(self._hed.action_types, "deactivate") table.insert(self._hed.action_types, "trigger_actions") end function CoreHub:set_actions() if not self._actions_ctrlrs then return end self._actions_ctrlrs.actions:clear() if #self._hed.actions ~= 0 then self:append_actions_sorted() if self._selected_action and alive(self:action_unit(self._selected_action.unit_id)) then local u = self:action_unit(self._selected_action.unit_id) self:select_action(self:combobox_name(u), self._actions_ctrlrs.actions, self._actions_ctrlrs.action_types, self._actions_ctrlrs.action_delay) else self:select_action(self:_action_names()[1], self._actions_ctrlrs.actions, self._actions_ctrlrs.action_types, self._actions_ctrlrs.action_delay) end else self._actions_ctrlrs.actions:set_enabled(false) local action_types = self._actions_ctrlrs.action_types action_types:clear() action_types:set_enabled(false) local action_delay = self._actions_ctrlrs.action_delay action_delay:set_value("-") action_delay:set_enabled(false) end end function CoreHub:append_actions_sorted() self._actions_ctrlrs.actions:clear() for _, name in ipairs(self:_action_names()) do self._actions_ctrlrs.actions:append(name) end end function CoreHub:_action_names() local names = {} for _, action in ipairs(self._hed.actions) do table.insert(names, self:combobox_name(action)) end table.sort(names) return names end function CoreHub:set_triggers() if not self._triggers_ctrlrs then return end self._triggers_ctrlrs.triggers:clear() if #self._hed.triggers ~= 0 then self:append_triggers_sorted() if self._selected_trigger and alive(self:trigger_unit(self._selected_trigger.unit_id)) then local u = self:trigger_unit(self._selected_trigger.unit_id) self:select_trigger(self:combobox_name(u), self._triggers_ctrlrs.triggers, self._triggers_ctrlrs.trigger_types) else self:select_trigger(self:_trigger_names()[1], self._triggers_ctrlrs.triggers, self._triggers_ctrlrs.trigger_types) end else self._triggers_ctrlrs.triggers:set_enabled(false) local trigger_types = self._triggers_ctrlrs.trigger_types trigger_types:clear() trigger_types:set_enabled(false) end end function CoreHub:append_triggers_sorted() self._triggers_ctrlrs.triggers:clear() for _, name in ipairs(self:_trigger_names()) do self._triggers_ctrlrs.triggers:append(name) end end function CoreHub:_trigger_names() local names = {} for _, trigger in ipairs(self._hed.triggers) do table.insert(names, self:combobox_name(trigger)) end table.sort(names) return names end function CoreHub:set_required_triggers() self._required_triggers:clear() for i = 1, #self._hed.triggers - 1 do self._required_triggers:append(i) end self._required_triggers:append("all") if self._hed.required_triggers ~= "all" and tonumber(self._hed.required_triggers) > #self._hed.triggers - 1 then if tonumber(self._hed.required_triggers) == 1 then self._hed.required_triggers = "all" else self._hed.required_triggers = self._hed.required_triggers - 1 end end self._required_triggers:set_value(self._hed.required_triggers) end function CoreHub:set_trigger_type(trigger_types) if self._selected_trigger then self._selected_trigger.type = trigger_types:get_value() end end function CoreHub:set_action_type(action_types) if self._selected_action then self._selected_action.type = action_types:get_value() end end function CoreHub:set_action_delay(action_delay) if self._selected_action then local value = tonumber(action_delay:get_value()) or 0 self._selected_action.action_delay = value action_delay:change_value(string.format("%.4f", self._selected_action.action_delay)) if self._timeline then self._timeline:action_delay_updated(self._selected_action) end end end function CoreHub:ews_select_action() self:select_action(self._actions_ctrlrs.actions:get_value(), self._actions_ctrlrs.actions, self._actions_ctrlrs.action_types, self._actions_ctrlrs.action_delay) end function CoreHub:select_action_with_unit(unit) if not table.contains(self._hed.actions, unit) then return end self:select_action(self:combobox_name(unit), self._actions_ctrlrs.actions, self._actions_ctrlrs.action_types, self._actions_ctrlrs.action_delay) end function CoreHub:ews_select_trigger() self:select_trigger(self._triggers_ctrlrs.triggers:get_value(), self._triggers_ctrlrs.triggers, self._triggers_ctrlrs.trigger_types) end function CoreHub:select_trigger_with_unit(unit) if not table.contains(self._hed.triggers, unit) then return end self:select_trigger(self:combobox_name(unit), self._triggers_ctrlrs.triggers, self._triggers_ctrlrs.trigger_types) end function CoreHub:select_action(s, actions, action_types, action_delay) local action_id = self:combobox_id(s) local a = self._hed.actions_data[action_id] self._selected_action = a actions:set_enabled(true) actions:set_value(s) action_types:set_enabled(true) action_types:clear() local action_unit = self:action_unit(self._selected_action.unit_id) if #action_unit:hub_element_data().action_types ~= 0 then for _, types in ipairs(action_unit:hub_element_data().action_types) do action_types:append(types) end action_types:set_value(self._selected_action.type) else action_types:set_enabled(false) end action_delay:set_enabled(true) action_delay:change_value(string.format("%.4f", self._selected_action.action_delay)) if self._timeline then self._timeline:select_action(self._selected_action) end end function CoreHub:select_trigger(s, triggers, trigger_types) local trigger_id = self:combobox_id(s) local t = self._hed.triggers_data[trigger_id] self._selected_trigger = t triggers:set_enabled(true) triggers:set_value(s) trigger_types:set_enabled(true) trigger_types:clear() local trigger_unit = self:trigger_unit(self._selected_trigger.unit_id) if #trigger_unit:hub_element_data().trigger_types ~= 0 then for _, types in ipairs(trigger_unit:hub_element_data().trigger_types) do trigger_types:append(types) end trigger_types:set_value(self._selected_trigger.type) else trigger_types:set_enabled(false) end end function CoreHub:update_selected(t, dt) Application:draw_circle(self._unit:position(), 75, 1, 1, 0) end function CoreHub:draw_connections_selected(t, dt) self:draw_triggers(t, dt) self:draw_actions(t, dt) end function CoreHub:draw_actions(t, dt) for _, action in ipairs(self._hed.actions) do local r, g, b = action:hub_element():get_color(self._hed.actions_data[self:id_string(action)].type) self:draw_arrow(self._unit, action, r * 0.5, g * 0.5, b * 0.5, true) end if self._selected_action and alive(self:action_unit(self._selected_action.unit_id)) then local action = self:action_unit(self._selected_action.unit_id) local r, g, b = action:hub_element():get_color(self._selected_action.type) local s = 0.75 + (1 + math.sin(t * 100)) * 0.25 * 0.5 Application:draw(action, r * s, g * s, b * s) self:draw_arrow(self._unit, action, r * s, g * s, b * s, true) end end function CoreHub:draw_triggers(t, dt) for _, trigger in ipairs(self._hed.triggers) do local r = 1 local g = 1 local b = 0 if trigger:name() == "hub" then b = 1 g = 0 r = 0 end self:draw_arrow(trigger, self._unit, r * 0.5, g * 0.5, b * 0.5, true) end if self._selected_trigger and alive(self:trigger_unit(self._selected_trigger.unit_id)) then local r = 1 local g = 1 local b = 0 local trigger = self:trigger_unit(self._selected_trigger.unit_id) if trigger:name() == "hub" then b = 1 g = 0 r = 0 end local s = 0.75 + (1 + math.sin(t * 100)) * 0.25 * 0.5 Application:draw(trigger, r * s, g * s, b * s) self:draw_arrow(trigger, self._unit, r * s, g * s, b * s, true) end end function CoreHub:update_unselected() end function CoreHub:draw_connections_unselected() Application:draw_circle(self._unit:position(), 50, 1, 1, 0) for _, trigger in ipairs(self._hed.triggers) do local r = 1 local g = 1 local b = 0 if trigger:name() == "hub" then b = 0.75 g = 0.1 r = 0.1 end Application:draw_circle(trigger:position(), 50, r, g, b) self:draw_arrow(trigger, self._unit, r * 0.75, g * 0.75, b * 0.75, false) end for _, action in ipairs(self._hed.actions) do local r, g, b = action:hub_element():get_color(self._hed.actions_data[self:id_string(action)].type) Application:draw_circle(action:position(), 50, r, g, b) self:draw_arrow(self._unit, action, r * 0.5, g * 0.5, b * 0.5, false) end end function CoreHub:combobox_name(unit) return unit:unit_data().name_id .. " (" .. unit:unit_data().unit_id .. ")" end function CoreHub:combobox_id(name) local s = nil local e = string.len(name) - 1 for i = string.len(name), 0, -1 do local t = string.sub(name, i, i) if t == "(" then s = i + 1 break end end return string.sub(name, s, e) end function CoreHub:id_string(unit) return tostring(unit:unit_data().unit_id) end function CoreHub:save_mission_action(file, t, hub) HubElement.save_mission_action(self, file, t, hub, true) end function CoreHub:save_mission_trigger(file, tab) local name = self._unit:name() file:puts(tab .. "<trigger type=\"Hub\" name=\"" .. name .. self._unit:unit_data().unit_id .. "\"/>") end function CoreHub:layer_finished() local hed = self._hed local t = {} for key, value in pairs(hed.actions_data) do local unit = managers.worlddefinition:get_hub_element_unit(value.unit_id) t[self:id_string(unit)] = value end hed.actions_data = t for key, value in pairs(hed.actions_data) do local a = managers.worlddefinition:get_hub_element_unit(value.unit_id) table.insert(hed.actions, a) table.insert(a:hub_element_data().hubs, self._unit) end local tt = {} for key, value in pairs(hed.triggers_data) do local v = value if type_name(value) == "number" then v = { type = "", unit_id = v } end local unit = managers.worlddefinition:get_hub_element_unit(v.unit_id) tt[self:id_string(unit)] = v end hed.triggers_data = tt for key, value in pairs(hed.triggers_data) do local t = managers.worlddefinition:get_hub_element_unit(value.unit_id) table.insert(hed.triggers, t) table.insert(t:hub_element_data().hubs, self._unit) end end function CoreHub:action_unit(id) for _, unit in ipairs(self._hed.actions) do if unit:unit_data().unit_id == id then return unit end end end function CoreHub:trigger_unit(id) for _, unit in ipairs(self._hed.triggers) do if unit:unit_data().unit_id == id then return unit end end end function CoreHub:add_action(a) if table.contains(self._hed.actions, a) then return end table.insert(self._hed.actions, a) table.insert(a:hub_element_data().hubs, self._unit) local s = self:id_string(a) self._hed.actions_data[s] = { type = "", action_delay = 0, unit_id = a:unit_data().unit_id } if #a:hub_element_data().action_types ~= 0 then self._hed.actions_data[s].type = a:hub_element_data().action_types[1] end self:append_actions_sorted() if self._timeline then self._timeline:add_action(a) end self:select_action(self:combobox_name(a), self._actions_ctrlrs.actions, self._actions_ctrlrs.action_types, self._actions_ctrlrs.action_delay) end function CoreHub:add_trigger(t) if table.contains(self._hed.triggers, t) then return end table.insert(self._hed.triggers, t) table.insert(t:hub_element_data().hubs, self._unit) local s = self:id_string(t) self._hed.triggers_data[s] = { type = "", unit_id = t:unit_data().unit_id } if #t:hub_element_data().trigger_types ~= 0 then self._hed.triggers_data[s].type = t:hub_element_data().trigger_types[1] end if self._triggers_ctrlrs.triggers then self:append_triggers_sorted() end self:select_trigger(self:combobox_name(t), self._triggers_ctrlrs.triggers, self._triggers_ctrlrs.trigger_types) self:set_required_triggers() end function CoreHub:remove_action(a) cat_print("editor", "remove_action", a:name()) table.delete(a:hub_element_data().hubs, self._unit) self:delete_action(a) if self._timeline then self._timeline:remove_action(a) end end function CoreHub:delete_action(a) table.delete(self._unit:hub_element_data().actions, a) if self._selected_action and self:action_unit(self._selected_action.unit_id) == a then self._selected_action = nil end self._hed.actions_data[self:id_string(a)] = nil self:set_actions() if self._timeline then self._timeline:remove_action(a) end end function CoreHub:remove_trigger(t) cat_print("editor", "remove_trigger", t:name()) table.delete(t:hub_element_data().hubs, self._unit) self:delete_trigger(t) self:set_required_triggers() end function CoreHub:delete_trigger(t) table.delete(self._unit:hub_element_data().triggers, t) if self._selected_trigger and self:trigger_unit(self._selected_trigger.unit_id) == t then self._selected_trigger = nil end self._hed.triggers_data[self:id_string(t)] = nil self:set_triggers() end function CoreHub:get_hub_action(unit) return self._hed.actions_data[self:id_string(unit)] end function CoreHub:get_hub_trigger(unit) return self._hed.triggers_data[self:id_string(unit)] end function CoreHub:on_timeline_btn() if not self._timeline then self._timeline = HubTimeline:new(self._unit:unit_data().name_id) self._timeline:set_hub_unit(self._unit) else self._timeline:set_visible(true) end end function CoreHub:_build_panel() self:_create_panel() local timeline_btn = EWS:Button(self._panel, "Timeline", "", "BU_EXACTFIT,NO_BORDER") self._panel_sizer:add(timeline_btn, 0, 5, "TOP,BOTTOM,EXPAND") timeline_btn:connect("EVT_COMMAND_BUTTON_CLICKED", callback(self, self, "on_timeline_btn")) local use_as_start_cb = EWS:CheckBox(self._panel, "Start hub", "") use_as_start_cb:set_value(self._hed.use_as_start) use_as_start_cb:set_tool_tip("Tell the mission that this is the start hub, not the one without triggers.") use_as_start_cb:connect("EVT_COMMAND_CHECKBOX_CLICKED", callback(self, self, "set_element_data"), { value = "use_as_start", ctrlr = use_as_start_cb }) local trigger_once_cb = EWS:CheckBox(self._panel, "Trigger Once", "") trigger_once_cb:set_value(self._hed.trigger_once) trigger_once_cb:set_tool_tip("The hub will only perform actions once.") trigger_once_cb:connect("EVT_COMMAND_CHECKBOX_CLICKED", callback(self, self, "set_element_data"), { value = "trigger_once", ctrlr = trigger_once_cb }) local trigger_on_inverse_cb = EWS:CheckBox(self._panel, "Actions On Inverse", "") trigger_on_inverse_cb:set_value(self._hed.trigger_on_inverse) trigger_on_inverse_cb:set_tool_tip("Will have the hub perform actions when triggers reaches start state again.") trigger_on_inverse_cb:connect("EVT_COMMAND_CHECKBOX_CLICKED", callback(self, self, "set_element_data"), { value = "trigger_on_inverse", ctrlr = trigger_on_inverse_cb }) local trigger_cbs_sizer = EWS:BoxSizer("HORIZONTAL") local trigger_cb1_sizer = EWS:BoxSizer("VERTICAL") trigger_cb1_sizer:add(use_as_start_cb, 0, 5, "EXPAND,TOP") trigger_cb1_sizer:add(trigger_once_cb, 0, 5, "EXPAND,BOTTOM") trigger_cbs_sizer:add(trigger_cb1_sizer, 1, 0, "EXPAND") trigger_cbs_sizer:add(EWS:StaticLine(self._panel, "", "LI_VERTICAL"), 0, 5, "EXPAND,TOP,RIGHT") local trigger_cb2_sizer = EWS:BoxSizer("VERTICAL") trigger_cb2_sizer:add(trigger_on_inverse_cb, 0, 5, "EXPAND,TOP") trigger_cbs_sizer:add(trigger_cb2_sizer, 1, 0, "EXPAND") self._panel_sizer:add(trigger_cbs_sizer, 0, 0, "EXPAND") local text_prop = 1 local ctrl_prop = 3 local actions_sizer = EWS:StaticBoxSizer(self._panel, "VERTICAL", "Actions") local action_sizer = EWS:BoxSizer("HORIZONTAL") action_sizer:add(EWS:StaticText(self._panel, "Action:", 0, ""), text_prop, 0, "ALIGN_CENTER_VERTICAL") local actions = EWS:ComboBox(self._panel, "", "", "CB_DROPDOWN,CB_READONLY") action_sizer:add(actions, ctrl_prop, 0, "EXPAND") actions_sizer:add(action_sizer, 0, 0, "EXPAND") local action_types_sizer = EWS:BoxSizer("HORIZONTAL") action_types_sizer:add(EWS:StaticText(self._panel, "Types:", 0, ""), text_prop, 0, "ALIGN_CENTER_VERTICAL") local action_types = EWS:ComboBox(self._panel, "", "", "CB_DROPDOWN,CB_READONLY") action_types_sizer:add(action_types, ctrl_prop, 0, "EXPAND") action_types:connect("EVT_COMMAND_COMBOBOX_SELECTED", callback(self, self, "set_action_type"), action_types) actions_sizer:add(action_types_sizer, 0, 0, "EXPAND") local action_delay_sizer = EWS:BoxSizer("HORIZONTAL") action_delay_sizer:add(EWS:StaticText(self._panel, "Delay:", 0, ""), text_prop, 0, "ALIGN_CENTER_VERTICAL") local action_delay = EWS:TextCtrl(self._panel, "-", "", "TE_CENTRE") action_delay_sizer:add(action_delay, ctrl_prop, 0, "EXPAND") action_delay:connect("EVT_CHAR", callback(nil, _G, "verify_number"), action_delay) action_delay:connect("EVT_COMMAND_TEXT_ENTER", callback(self, self, "set_element_data"), { callback = "set_action_delay", ctrlr = action_delay }) action_delay:connect("EVT_KILL_FOCUS", callback(self, self, "set_element_data"), { callback = "set_action_delay", ctrlr = action_delay }) actions_sizer:add(action_delay_sizer, 0, 0, "EXPAND") self._panel_sizer:add(actions_sizer, 0, 0, "EXPAND") self._actions_ctrlrs = { actions = actions, action_delay = action_delay, action_types = action_types } local triggers_sizer = EWS:StaticBoxSizer(self._panel, "VERTICAL", "Triggers") local required_trigger_sizer = EWS:BoxSizer("HORIZONTAL") required_trigger_sizer:add(EWS:StaticText(self._panel, "Required:", 0, ""), text_prop, 0, "ALIGN_CENTER_VERTICAL") self._required_triggers = EWS:ComboBox(self._panel, "", "", "CB_DROPDOWN,CB_READONLY") required_trigger_sizer:add(self._required_triggers, ctrl_prop, 0, "EXPAND") self._required_triggers:connect("EVT_COMMAND_COMBOBOX_SELECTED", callback(self, self, "set_element_data"), { value = "required_triggers", ctrlr = self._required_triggers }) triggers_sizer:add(required_trigger_sizer, 0, 0, "EXPAND") local trigger_sizer = EWS:BoxSizer("HORIZONTAL") trigger_sizer:add(EWS:StaticText(self._panel, "Trigger:", 0, ""), text_prop, 0, "ALIGN_CENTER_VERTICAL") local triggers = EWS:ComboBox(self._panel, "", "", "CB_DROPDOWN,CB_READONLY") trigger_sizer:add(triggers, ctrl_prop, 0, "EXPAND") triggers_sizer:add(trigger_sizer, 0, 0, "EXPAND") local trigger_types_sizer = EWS:BoxSizer("HORIZONTAL") trigger_types_sizer:add(EWS:StaticText(self._panel, "Types:", 0, ""), text_prop, 0, "ALIGN_CENTER_VERTICAL") local trigger_types = EWS:ComboBox(self._panel, "", "", "CB_DROPDOWN,CB_READONLY") trigger_types_sizer:add(trigger_types, ctrl_prop, 0, "EXPAND") trigger_types:connect("EVT_COMMAND_COMBOBOX_SELECTED", callback(self, self, "set_trigger_type"), trigger_types) triggers_sizer:add(trigger_types_sizer, 0, 0, "EXPAND") self._panel_sizer:add(triggers_sizer, 0, 0, "EXPAND") self._triggers_ctrlrs = { triggers = triggers, trigger_types = trigger_types } actions:connect("EVT_COMMAND_COMBOBOX_SELECTED", callback(self, self, "ews_select_action"), actions) triggers:connect("EVT_COMMAND_COMBOBOX_SELECTED", callback(self, self, "ews_select_trigger"), triggers) self:set_actions() self:set_triggers() self:set_required_triggers() end function CoreHub:destroy() if self._timeline then self._timeline:destroy() end HubElement.destroy(self) end
1
0.97882
1
0.97882
game-dev
MEDIA
0.598293
game-dev,desktop-app
0.975506
1
0.975506
motherencore/MOTHER-Encore-Demo-Source-Code
3,086
Scripts/Main/Openable Door.gd
tool extends Sprite export (Texture) var sprite setget set_texture export (Vector2) var door_offset = Vector2(0, -32) setget set_offset export var sound = "" export var end_sound = "" export var key = "" #leave null if there's no need for a key item export var blocked = false export var remove_key = false export var flag = "" export var one_way = false var unlocked = true var touching = 0 func set_texture(tex): sprite = tex $Sprite.texture = sprite func set_offset(off): door_offset = off $Sprite.position = door_offset $Area2D.position.y = door_offset.y + 32 $interact.position.y = door_offset.y + 32 $StaticBody2D.position.y = door_offset.y + 32 func _ready(): if !Engine.is_editor_hint(): if key != "" or blocked or one_way: lock() else: unlock() if flag != "": if globaldata.flags.has(flag): unlocked = globaldata.flags[flag] $interact/ButtonPrompt.enabled = !globaldata.flags[flag] $AnimationPlayer.play("Normal") func _on_Area2D_body_entered(body): if touching == 0 and $Timer.time_left == 0 and unlocked == true and $AnimationPlayer.current_animation == "Normal" and !one_way: open() if blocked and global.persistPlayer.running and global.persistPlayer.direction.y == -1 and !unlocked: global.currentCamera.shake_camera(1, 0.2, Vector2(2,0)) open() unlock() blocked = false if flag != "": if globaldata.flags.has(flag): globaldata.flags[flag] = true touching += 1 func _on_Area2D_body_exited(body): touching -= 1 if global.persistPlayer.paused: $AnimationPlayer.play("Normal") elif touching == 0 and unlocked == true: $Timer.start() func _on_Timer_timeout(): if touching == 0: $AnimationPlayer.play("Normal") if end_sound != "" and !global.persistPlayer.paused: $AudioStreamPlayer.stream = load("Audio/Sound effects/" + end_sound) $AudioStreamPlayer.play() if one_way: lock() $AudioStreamPlayer.stream = load("Audio/Sound effects/" + end_sound) $AudioStreamPlayer.play() func open(): $AnimationPlayer.play("Action") $interact/ButtonPrompt.hide() $interact/ButtonPrompt.enabled = false if sound != "" and !global.persistPlayer.paused: if blocked and !unlocked: $AudioStreamPlayer.stream = load("res://Audio/Sound effects/bash.mp3") else: $AudioStreamPlayer.stream = load("Audio/Sound effects/" + sound) $AudioStreamPlayer.play() func unlock(): $StaticBody2D/CollisionShape2D.set_deferred("disabled", true) $interact/ButtonPrompt.enabled = false unlocked = true func lock(): $StaticBody2D/CollisionShape2D.set_deferred("disabled", false) $interact/ButtonPrompt.enabled = true unlocked = false func interact(): if !unlocked: if blocked: global.set_dialog("Reusable/doorblocked") elif InventoryManager.check_item_for_all(key): globaldata.flags[flag] = true open() unlock() if remove_key: InventoryManager.remove_item(key) global.item = InventoryManager.Load_item_data(key) global.set_dialog("Reusable/lockopened") else: global.set_dialog("Reusable/locklocked") uiManager.open_dialogue_box() global.persistPlayer.pause()
1
0.572575
1
0.572575
game-dev
MEDIA
0.825198
game-dev
0.501525
1
0.501525
ReikaKalseki/RotaryCraft
6,907
GUIs/Machine/Inventory/GuiItemFilter.java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.RotaryCraft.GUIs.Machine.Inventory; import java.util.ArrayList; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import Reika.DragonAPI.Instantiable.GUI.ImagedGuiButton; import Reika.DragonAPI.Instantiable.IO.PacketTarget; import Reika.DragonAPI.Libraries.IO.ReikaPacketHelper; import Reika.RotaryCraft.RotaryCraft; import Reika.RotaryCraft.Base.GuiPowerOnlyMachine; import Reika.RotaryCraft.Containers.Machine.Inventory.ContainerItemFilter; import Reika.RotaryCraft.Registry.PacketRegistry; import Reika.RotaryCraft.TileEntities.TileEntityItemFilter; import Reika.RotaryCraft.TileEntities.TileEntityItemFilter.MatchData; import Reika.RotaryCraft.TileEntities.TileEntityItemFilter.MatchDisplay; import Reika.RotaryCraft.TileEntities.TileEntityItemFilter.MatchType; import Reika.RotaryCraft.TileEntities.TileEntityItemFilter.SettingType; public class GuiItemFilter extends GuiPowerOnlyMachine { private final TileEntityItemFilter filter; private static final int LINES = 5; private SettingType page = SettingType.BASIC; private ArrayList<MatchDisplay> display; private int nbtListPos = 0; private MatchData lastData; public GuiItemFilter(EntityPlayer p5ep, TileEntityItemFilter te) { super(new ContainerItemFilter(p5ep, te), te); xSize = 256; ySize = 217; ep = p5ep; filter = te; } @Override public void initGui() { super.initGui(); int j = (width - xSize) / 2; int k = (height - ySize) / 2; MatchData data = filter.getData(); if (data != null) { display = null; switch(page) { case BASIC: display = data.getMainDisplay(); break; case NBT: display = data.getNBTDisplay(); break; case ORE: display = data.getOreDisplay(); break; case CLASS: display = data.getClassDisplay(); break; } if (display != null) { int d = page == SettingType.NBT ? 1 : 0; int max = Math.min(nbtListPos+display.size(), nbtListPos+5-d); for (int i = nbtListPos; i < max && i < display.size()+d; i++) { int i2 = i-nbtListPos+d; MatchDisplay m = display.get(i); int u = m.getSetting() == MatchType.MATCH ? 0 : 9; int v = m.getSetting() == MatchType.MISMATCH ? 54 : 63; buttonList.add(new ImagedGuiButton(i, j+30, k+18+i2*16, 9, 9, u, v, "Textures/GUI/buttons.png", RotaryCraft.class)); } } buttonList.add(new GuiButton(-1, j+30, k+100, 20, 20, "<")); buttonList.add(new GuiButton(-2, j+50, k+100, 20, 20, ">")); if (page == SettingType.NBT) { if (!display.isEmpty()) { for (int i = 0; i < 3; i++) { int u = i == 0 ? 0 : 9; int v = i == 1 ? 54 : 63; buttonList.add(new ImagedGuiButton(-5-i, j+30+i*10, k+18+0, 9, 9, u, v, "Textures/GUI/buttons.png", RotaryCraft.class)); } } if (display != null && display.size() > LINES) { buttonList.add(new GuiButton(-3, j+70, k+100, 20, 20, "+")); buttonList.add(new GuiButton(-4, j+90, k+100, 20, 20, "-")); } } } } @Override protected void actionPerformed(GuiButton b) { super.actionPerformed(b); if (this.isClickTooSoon()) return; if (b.id == -1) { page = page.previous(); } else if (b.id == -2) { page = page.next(); } else if (b.id == -3) { int d = page == SettingType.NBT ? 1 : 0; if (display != null && nbtListPos < display.size()-LINES+d) nbtListPos++; } else if (b.id == -4) { if (nbtListPos > 0) nbtListPos--; } else if (b.id == -5 || b.id == -6 || b.id == -7) { for (MatchDisplay m : display) { while (m.getSetting().ordinal() != (-b.id)-5) m.increment(); } this.sendData(); } else if (b.id >= 0 && b.id != 24000) { MatchDisplay m = display.get(b.id); m.increment(); this.sendData(); } this.initGui(); } private void sendData() { //ReikaJavaLibrary.pConsole(filter.getData()); NBTTagCompound nbt = filter.getData().writeToNBT(); //ReikaJavaLibrary.pConsole(nbt); nbt.setInteger("posX", tile.xCoord); nbt.setInteger("posY", tile.yCoord); nbt.setInteger("posZ", tile.zCoord); ReikaPacketHelper.sendNBTPacket(RotaryCraft.packetChannel, PacketRegistry.FILTERSETTING.ordinal(), nbt, PacketTarget.server); } @Override protected void drawGuiContainerForegroundLayer(int a, int b) { super.drawGuiContainerForegroundLayer(a, b); int j = (width - xSize) / 2; int k = (height - ySize) / 2; int dx = this.inventoryLabelLeft() ? 176 : xSize-50; fontRendererObj.drawString("Blacklist", dx, (ySize - 96) + 3, 4210752); MatchData data = filter.getData(); if (data != lastData) this.initGui(); lastData = data; int x = api.getMouseRealX(); int y = api.getMouseRealY(); if (filter.getData() != null) { /* int tx = 44; int ty = 16; Topology<String> t = match.getTopology(); Map<String, Integer> map = t.getDepthMap(); if (!map.isEmpty()) { fontRendererObj.drawString("NBT Data:", tx, ty, 0x000000); ty += fontRendererObj.FONT_HEIGHT+2; for (String s : map.keySet()) { if (!s.isEmpty()) { int lvl = map.get(s); s = s+": "+match.getTagString(s); for (int i = 0; i < lvl; i++) { s = " "+s; } fontRendererObj.drawString(s, tx, ty, 0x000000); ty += fontRendererObj.FONT_HEIGHT+2; } } } */ if (display != null) { if (display.isEmpty()) { fontRendererObj.drawString("[No Values]", 42, 19, 0x000000); } int d = page == SettingType.NBT ? 1 : 0; int max = Math.min(nbtListPos+display.size(), nbtListPos+LINES-d); for (int i = nbtListPos; i < max && i < display.size()+d; i++) { int i2 = i-nbtListPos+d; MatchDisplay m = display.get(i); int tx = 42; int ty = 19+i2*16; String s = m.displayName+" ("+m.value+"): "; fontRendererObj.drawString(s, tx, ty, 0x000000); fontRendererObj.drawString(m.getSetting().name, tx+fontRendererObj.getStringWidth(s), ty, m.getSetting().color); } if (page == SettingType.NBT) { if (!display.isEmpty()) { int tx = 42; int ty = 19+0*16; fontRendererObj.drawString("Toggle All", tx+22, ty, 0x000000); } } } } } @Override protected boolean inventoryLabelLeft() { return true; } @Override protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { super.drawGuiContainerBackgroundLayer(par1, par2, par3); int j = (width - xSize) / 2; int k = (height - ySize) / 2; } @Override protected String getGuiTexture() { return "filtergui2"; } }
1
0.893663
1
0.893663
game-dev
MEDIA
0.675083
game-dev
0.97254
1
0.97254
GodotECS/godex
16,013
thirdparty/bullet/Bullet3Dynamics/ConstraintSolver/b3Generic6DofConstraint.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /// 2009 March: b3Generic6DofConstraint refactored by Roman Ponomarev /// Added support for generic constraint solver through getInfo1/getInfo2 methods /* 2007-09-09 b3Generic6DofConstraint Refactored by Francisco Le?n email: projectileman@yahoo.com http://gimpact.sf.net */ #ifndef B3_GENERIC_6DOF_CONSTRAINT_H #define B3_GENERIC_6DOF_CONSTRAINT_H #include "Bullet3Common/b3Vector3.h" #include "b3JacobianEntry.h" #include "b3TypedConstraint.h" struct b3RigidBodyData; //! Rotation Limit structure for generic joints class b3RotationalLimitMotor { public: //! limit_parameters //!@{ b3Scalar m_loLimit; //!< joint limit b3Scalar m_hiLimit; //!< joint limit b3Scalar m_targetVelocity; //!< target motor velocity b3Scalar m_maxMotorForce; //!< max force on motor b3Scalar m_maxLimitForce; //!< max force on limit b3Scalar m_damping; //!< Damping. b3Scalar m_limitSoftness; //! Relaxation factor b3Scalar m_normalCFM; //!< Constraint force mixing factor b3Scalar m_stopERP; //!< Error tolerance factor when joint is at limit b3Scalar m_stopCFM; //!< Constraint force mixing factor when joint is at limit b3Scalar m_bounce; //!< restitution factor bool m_enableMotor; //!@} //! temp_variables //!@{ b3Scalar m_currentLimitError; //! How much is violated this limit b3Scalar m_currentPosition; //! current value of angle int m_currentLimit; //!< 0=free, 1=at lo limit, 2=at hi limit b3Scalar m_accumulatedImpulse; //!@} b3RotationalLimitMotor() { m_accumulatedImpulse = 0.f; m_targetVelocity = 0; m_maxMotorForce = 6.0f; m_maxLimitForce = 300.0f; m_loLimit = 1.0f; m_hiLimit = -1.0f; m_normalCFM = 0.f; m_stopERP = 0.2f; m_stopCFM = 0.f; m_bounce = 0.0f; m_damping = 1.0f; m_limitSoftness = 0.5f; m_currentLimit = 0; m_currentLimitError = 0; m_enableMotor = false; } b3RotationalLimitMotor(const b3RotationalLimitMotor& limot) { m_targetVelocity = limot.m_targetVelocity; m_maxMotorForce = limot.m_maxMotorForce; m_limitSoftness = limot.m_limitSoftness; m_loLimit = limot.m_loLimit; m_hiLimit = limot.m_hiLimit; m_normalCFM = limot.m_normalCFM; m_stopERP = limot.m_stopERP; m_stopCFM = limot.m_stopCFM; m_bounce = limot.m_bounce; m_currentLimit = limot.m_currentLimit; m_currentLimitError = limot.m_currentLimitError; m_enableMotor = limot.m_enableMotor; } //! Is limited bool isLimited() { if (m_loLimit > m_hiLimit) return false; return true; } //! Need apply correction bool needApplyTorques() { if (m_currentLimit == 0 && m_enableMotor == false) return false; return true; } //! calculates error /*! calculates m_currentLimit and m_currentLimitError. */ int testLimitValue(b3Scalar test_value); //! apply the correction impulses for two bodies b3Scalar solveAngularLimits(b3Scalar timeStep, b3Vector3& axis, b3Scalar jacDiagABInv, b3RigidBodyData* body0, b3RigidBodyData* body1); }; class b3TranslationalLimitMotor { public: b3Vector3 m_lowerLimit; //!< the constraint lower limits b3Vector3 m_upperLimit; //!< the constraint upper limits b3Vector3 m_accumulatedImpulse; //! Linear_Limit_parameters //!@{ b3Vector3 m_normalCFM; //!< Constraint force mixing factor b3Vector3 m_stopERP; //!< Error tolerance factor when joint is at limit b3Vector3 m_stopCFM; //!< Constraint force mixing factor when joint is at limit b3Vector3 m_targetVelocity; //!< target motor velocity b3Vector3 m_maxMotorForce; //!< max force on motor b3Vector3 m_currentLimitError; //! How much is violated this limit b3Vector3 m_currentLinearDiff; //! Current relative offset of constraint frames b3Scalar m_limitSoftness; //!< Softness for linear limit b3Scalar m_damping; //!< Damping for linear limit b3Scalar m_restitution; //! Bounce parameter for linear limit //!@} bool m_enableMotor[3]; int m_currentLimit[3]; //!< 0=free, 1=at lower limit, 2=at upper limit b3TranslationalLimitMotor() { m_lowerLimit.setValue(0.f, 0.f, 0.f); m_upperLimit.setValue(0.f, 0.f, 0.f); m_accumulatedImpulse.setValue(0.f, 0.f, 0.f); m_normalCFM.setValue(0.f, 0.f, 0.f); m_stopERP.setValue(0.2f, 0.2f, 0.2f); m_stopCFM.setValue(0.f, 0.f, 0.f); m_limitSoftness = 0.7f; m_damping = b3Scalar(1.0f); m_restitution = b3Scalar(0.5f); for (int i = 0; i < 3; i++) { m_enableMotor[i] = false; m_targetVelocity[i] = b3Scalar(0.f); m_maxMotorForce[i] = b3Scalar(0.f); } } b3TranslationalLimitMotor(const b3TranslationalLimitMotor& other) { m_lowerLimit = other.m_lowerLimit; m_upperLimit = other.m_upperLimit; m_accumulatedImpulse = other.m_accumulatedImpulse; m_limitSoftness = other.m_limitSoftness; m_damping = other.m_damping; m_restitution = other.m_restitution; m_normalCFM = other.m_normalCFM; m_stopERP = other.m_stopERP; m_stopCFM = other.m_stopCFM; for (int i = 0; i < 3; i++) { m_enableMotor[i] = other.m_enableMotor[i]; m_targetVelocity[i] = other.m_targetVelocity[i]; m_maxMotorForce[i] = other.m_maxMotorForce[i]; } } //! Test limit /*! - free means upper < lower, - locked means upper == lower - limited means upper > lower - limitIndex: first 3 are linear, next 3 are angular */ inline bool isLimited(int limitIndex) { return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]); } inline bool needApplyForce(int limitIndex) { if (m_currentLimit[limitIndex] == 0 && m_enableMotor[limitIndex] == false) return false; return true; } int testLimitValue(int limitIndex, b3Scalar test_value); b3Scalar solveLinearAxis( b3Scalar timeStep, b3Scalar jacDiagABInv, b3RigidBodyData& body1, const b3Vector3& pointInA, b3RigidBodyData& body2, const b3Vector3& pointInB, int limit_index, const b3Vector3& axis_normal_on_a, const b3Vector3& anchorPos); }; enum b36DofFlags { B3_6DOF_FLAGS_CFM_NORM = 1, B3_6DOF_FLAGS_CFM_STOP = 2, B3_6DOF_FLAGS_ERP_STOP = 4 }; #define B3_6DOF_FLAGS_AXIS_SHIFT 3 // bits per axis /// b3Generic6DofConstraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space /*! b3Generic6DofConstraint can leave any of the 6 degree of freedom 'free' or 'locked'. currently this limit supports rotational motors<br> <ul> <li> For Linear limits, use b3Generic6DofConstraint.setLinearUpperLimit, b3Generic6DofConstraint.setLinearLowerLimit. You can set the parameters with the b3TranslationalLimitMotor structure accsesible through the b3Generic6DofConstraint.getTranslationalLimitMotor method. At this moment translational motors are not supported. May be in the future. </li> <li> For Angular limits, use the b3RotationalLimitMotor structure for configuring the limit. This is accessible through b3Generic6DofConstraint.getLimitMotor method, This brings support for limit parameters and motors. </li> <li> Angulars limits have these possible ranges: <table border=1 > <tr> <td><b>AXIS</b></td> <td><b>MIN ANGLE</b></td> <td><b>MAX ANGLE</b></td> </tr><tr> <td>X</td> <td>-PI</td> <td>PI</td> </tr><tr> <td>Y</td> <td>-PI/2</td> <td>PI/2</td> </tr><tr> <td>Z</td> <td>-PI</td> <td>PI</td> </tr> </table> </li> </ul> */ B3_ATTRIBUTE_ALIGNED16(class) b3Generic6DofConstraint : public b3TypedConstraint { protected: //! relative_frames //!@{ b3Transform m_frameInA; //!< the constraint space w.r.t body A b3Transform m_frameInB; //!< the constraint space w.r.t body B //!@} //! Jacobians //!@{ // b3JacobianEntry m_jacLinear[3];//!< 3 orthogonal linear constraints // b3JacobianEntry m_jacAng[3];//!< 3 orthogonal angular constraints //!@} //! Linear_Limit_parameters //!@{ b3TranslationalLimitMotor m_linearLimits; //!@} //! hinge_parameters //!@{ b3RotationalLimitMotor m_angularLimits[3]; //!@} protected: //! temporal variables //!@{ b3Transform m_calculatedTransformA; b3Transform m_calculatedTransformB; b3Vector3 m_calculatedAxisAngleDiff; b3Vector3 m_calculatedAxis[3]; b3Vector3 m_calculatedLinearDiff; b3Scalar m_timeStep; b3Scalar m_factA; b3Scalar m_factB; bool m_hasStaticBody; b3Vector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes bool m_useLinearReferenceFrameA; bool m_useOffsetForConstraintFrame; int m_flags; //!@} b3Generic6DofConstraint& operator=(b3Generic6DofConstraint& other) { b3Assert(0); (void)other; return *this; } int setAngularLimits(b3ConstraintInfo2 * info, int row_offset, const b3Transform& transA, const b3Transform& transB, const b3Vector3& linVelA, const b3Vector3& linVelB, const b3Vector3& angVelA, const b3Vector3& angVelB); int setLinearLimits(b3ConstraintInfo2 * info, int row, const b3Transform& transA, const b3Transform& transB, const b3Vector3& linVelA, const b3Vector3& linVelB, const b3Vector3& angVelA, const b3Vector3& angVelB); // tests linear limits void calculateLinearInfo(); //! calcs the euler angles between the two bodies. void calculateAngleInfo(); public: B3_DECLARE_ALIGNED_ALLOCATOR(); b3Generic6DofConstraint(int rbA, int rbB, const b3Transform& frameInA, const b3Transform& frameInB, bool useLinearReferenceFrameA, const b3RigidBodyData* bodies); //! Calcs global transform of the offsets /*! Calcs the global transform for the joint offset for body A an B, and also calcs the agle differences between the bodies. \sa b3Generic6DofConstraint.getCalculatedTransformA , b3Generic6DofConstraint.getCalculatedTransformB, b3Generic6DofConstraint.calculateAngleInfo */ void calculateTransforms(const b3Transform& transA, const b3Transform& transB, const b3RigidBodyData* bodies); void calculateTransforms(const b3RigidBodyData* bodies); //! Gets the global transform of the offset for body A /*! \sa b3Generic6DofConstraint.getFrameOffsetA, b3Generic6DofConstraint.getFrameOffsetB, b3Generic6DofConstraint.calculateAngleInfo. */ const b3Transform& getCalculatedTransformA() const { return m_calculatedTransformA; } //! Gets the global transform of the offset for body B /*! \sa b3Generic6DofConstraint.getFrameOffsetA, b3Generic6DofConstraint.getFrameOffsetB, b3Generic6DofConstraint.calculateAngleInfo. */ const b3Transform& getCalculatedTransformB() const { return m_calculatedTransformB; } const b3Transform& getFrameOffsetA() const { return m_frameInA; } const b3Transform& getFrameOffsetB() const { return m_frameInB; } b3Transform& getFrameOffsetA() { return m_frameInA; } b3Transform& getFrameOffsetB() { return m_frameInB; } virtual void getInfo1(b3ConstraintInfo1 * info, const b3RigidBodyData* bodies); void getInfo1NonVirtual(b3ConstraintInfo1 * info, const b3RigidBodyData* bodies); virtual void getInfo2(b3ConstraintInfo2 * info, const b3RigidBodyData* bodies); void getInfo2NonVirtual(b3ConstraintInfo2 * info, const b3Transform& transA, const b3Transform& transB, const b3Vector3& linVelA, const b3Vector3& linVelB, const b3Vector3& angVelA, const b3Vector3& angVelB, const b3RigidBodyData* bodies); void updateRHS(b3Scalar timeStep); //! Get the rotation axis in global coordinates b3Vector3 getAxis(int axis_index) const; //! Get the relative Euler angle /*! \pre b3Generic6DofConstraint::calculateTransforms() must be called previously. */ b3Scalar getAngle(int axis_index) const; //! Get the relative position of the constraint pivot /*! \pre b3Generic6DofConstraint::calculateTransforms() must be called previously. */ b3Scalar getRelativePivotPosition(int axis_index) const; void setFrames(const b3Transform& frameA, const b3Transform& frameB, const b3RigidBodyData* bodies); //! Test angular limit. /*! Calculates angular correction and returns true if limit needs to be corrected. \pre b3Generic6DofConstraint::calculateTransforms() must be called previously. */ bool testAngularLimitMotor(int axis_index); void setLinearLowerLimit(const b3Vector3& linearLower) { m_linearLimits.m_lowerLimit = linearLower; } void getLinearLowerLimit(b3Vector3 & linearLower) { linearLower = m_linearLimits.m_lowerLimit; } void setLinearUpperLimit(const b3Vector3& linearUpper) { m_linearLimits.m_upperLimit = linearUpper; } void getLinearUpperLimit(b3Vector3 & linearUpper) { linearUpper = m_linearLimits.m_upperLimit; } void setAngularLowerLimit(const b3Vector3& angularLower) { for (int i = 0; i < 3; i++) m_angularLimits[i].m_loLimit = b3NormalizeAngle(angularLower[i]); } void getAngularLowerLimit(b3Vector3 & angularLower) { for (int i = 0; i < 3; i++) angularLower[i] = m_angularLimits[i].m_loLimit; } void setAngularUpperLimit(const b3Vector3& angularUpper) { for (int i = 0; i < 3; i++) m_angularLimits[i].m_hiLimit = b3NormalizeAngle(angularUpper[i]); } void getAngularUpperLimit(b3Vector3 & angularUpper) { for (int i = 0; i < 3; i++) angularUpper[i] = m_angularLimits[i].m_hiLimit; } //! Retrieves the angular limit informacion b3RotationalLimitMotor* getRotationalLimitMotor(int index) { return &m_angularLimits[index]; } //! Retrieves the limit informacion b3TranslationalLimitMotor* getTranslationalLimitMotor() { return &m_linearLimits; } //first 3 are linear, next 3 are angular void setLimit(int axis, b3Scalar lo, b3Scalar hi) { if (axis < 3) { m_linearLimits.m_lowerLimit[axis] = lo; m_linearLimits.m_upperLimit[axis] = hi; } else { lo = b3NormalizeAngle(lo); hi = b3NormalizeAngle(hi); m_angularLimits[axis - 3].m_loLimit = lo; m_angularLimits[axis - 3].m_hiLimit = hi; } } //! Test limit /*! - free means upper < lower, - locked means upper == lower - limited means upper > lower - limitIndex: first 3 are linear, next 3 are angular */ bool isLimited(int limitIndex) { if (limitIndex < 3) { return m_linearLimits.isLimited(limitIndex); } return m_angularLimits[limitIndex - 3].isLimited(); } virtual void calcAnchorPos(const b3RigidBodyData* bodies); // overridable int get_limit_motor_info2(b3RotationalLimitMotor * limot, const b3Transform& transA, const b3Transform& transB, const b3Vector3& linVelA, const b3Vector3& linVelB, const b3Vector3& angVelA, const b3Vector3& angVelB, b3ConstraintInfo2* info, int row, b3Vector3& ax1, int rotational, int rotAllowed = false); // access for UseFrameOffset bool getUseFrameOffset() { return m_useOffsetForConstraintFrame; } void setUseFrameOffset(bool frameOffsetOnOff) { m_useOffsetForConstraintFrame = frameOffsetOnOff; } ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5). ///If no axis is provided, it uses the default axis for this constraint. virtual void setParam(int num, b3Scalar value, int axis = -1); ///return the local value of parameter virtual b3Scalar getParam(int num, int axis = -1) const; void setAxis(const b3Vector3& axis1, const b3Vector3& axis2, const b3RigidBodyData* bodies); }; #endif //B3_GENERIC_6DOF_CONSTRAINT_H
1
0.95401
1
0.95401
game-dev
MEDIA
0.968814
game-dev
0.96565
1
0.96565
sebastienros/jint
1,112
Jint/Native/Intl/DateTimeFormatPrototype.cs
using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Runtime; using Jint.Runtime.Descriptors; namespace Jint.Native.Intl; /// <summary> /// https://tc39.es/ecma402/#sec-properties-of-intl-datetimeformat-prototype-object /// </summary> internal sealed class DateTimeFormatPrototype : Prototype { private readonly DateTimeFormatConstructor _constructor; public DateTimeFormatPrototype(Engine engine, Realm realm, DateTimeFormatConstructor constructor, ObjectPrototype objectPrototype) : base(engine, realm) { _prototype = objectPrototype; _constructor = constructor; } protected override void Initialize() { var properties = new PropertyDictionary(2, checkExistingKeys: false) { ["constructor"] = new PropertyDescriptor(_constructor, true, false, true), }; SetProperties(properties); var symbols = new SymbolDictionary(1) { [GlobalSymbolRegistry.ToStringTag] = new("Intl.DateTimeFormat", PropertyFlag.Configurable) }; SetSymbols(symbols); } }
1
0.55767
1
0.55767
game-dev
MEDIA
0.215864
game-dev
0.563648
1
0.563648
AliceLR/megazeux
17,128
src/idput.c
/* MegaZeux * * Copyright (C) 1998 MenTaLguY - mentalg@geocities.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include "board.h" #include "const.h" #include "data.h" #include "graphics.h" #include "idput.h" #include "world.h" #include "world_struct.h" #define thin_line 128 #define thick_line 144 #define ice_anim 160 #define lava_anim 164 #define low_ammo 167 #define hi_ammo 168 #define lit_bomb 169 #define energizer_glow 176 #define explosion_colors 184 #define horiz_door 188 #define vert_door 189 #define cw_anim 190 #define ccw_anim 194 #define open_door 198 #define trans_north 230 #define trans_south 234 #define trans_east 238 #define trans_west 242 #define trans_all 246 #define thick_arrow 250 #define thin_arrow 254 #define horiz_lazer 258 #define vert_lazer 262 #define fire_anim 266 #define fire_colors 272 #define life_anim 278 #define life_colors 282 #define ricochet_panels 286 #define mine_anim 288 #define shooting_fire_anim 290 #define shooting_fire_colors 292 #define seeker_anim 294 #define seeker_colors 298 #define whirlpool_glow 302 unsigned char id_chars[ID_CHARS_SIZE]; unsigned char id_dmg[ID_DMG_SIZE]; unsigned char bullet_color[ID_BULLET_COLOR_SIZE] = { 15, 15, 15 }; unsigned char missile_color = 8; /* Simulate DOS-era reads of id_chars, which was a single 455 byte array. * This is only accurate for out-of-bounds reads when drawing unusual thing * parameters until 2.51s3. * * 0-127: ID chars (0-127) * 128-322: ID animations (except bullet colors and missile color) * 323: missile color (until 2.51s3, unused after) * 324-326: bullet colors (until 2.51s3.1, unused after) * 327-454: ID damages 0-127 (until 2.51s3.1, unused after) * * 455-909: out of bounds default ID chars (until 2.51s3). * 455-: out of bounds misc pointers and various other things (2.51s3+) */ static unsigned char get_id_char_by_legacy_index(unsigned index) { if(index < ID_CHARS_SIZE) return id_chars[index]; if(index == ID_MISSILE_COLOR_POS) return missile_color; if(index < ID_DMG_POS) return bullet_color[index - ID_BULLET_COLOR_POS]; if(index < ID_CHARS_TOTAL_SIZE) return id_dmg[index - ID_DMG_POS]; return 255; } void set_id_char_by_legacy_index(unsigned index, unsigned char value) { if(index < ID_CHARS_SIZE) id_chars[index] = value; else if(index == ID_MISSILE_COLOR_POS) missile_color = value; else if(index < ID_DMG_POS) bullet_color[index - ID_BULLET_COLOR_POS] = value; else if(index < ID_CHARS_TOTAL_SIZE) id_dmg[index - ID_DMG_POS] = value; } static unsigned char get_special_id_char(struct board *src_board, enum thing cell_id, char param, int offset) { char *level_id = src_board->level_id; int board_width = src_board->board_width; int board_height = src_board->board_height; switch(cell_id) { case LINE: { int array_x = offset % board_width; int array_y = offset / board_width; int bits = 0; char *ptr = level_id + offset; if(array_y > 0) { if(*(ptr - board_width) == LINE) bits = 1; } else bits = 1; if(array_y < (board_height - 1)) { if(*(ptr + board_width) == LINE) bits |= 2; } else bits |= 2; if(array_x > 0) { if(*(ptr - 1) == LINE) bits |= 8; } else bits |= 8; if(array_x < (board_width - 1)) { if(*(ptr + 1) == LINE) bits |= 4; } else bits |= 4; return id_chars[thick_line + bits]; } case WEB: case THICK_WEB: { int array_x = offset % board_width; int array_y = offset / board_width; int bits = 0; char *ptr; ptr = level_id + offset; if(array_y > 0) { if(*(ptr - board_width) != SPACE) bits = 1; } else bits = 1; if(array_y < (board_height - 1)) { if(*(ptr + board_width) != SPACE) bits |= 2; } else bits |= 2; if(array_x > 0) { if(*(ptr - 1) != SPACE) bits |= 8; } else bits |= 8; if(array_x < (board_width - 1)) { if(*(ptr + 1) != SPACE) bits |= 4; } else bits |= 4; if(cell_id == WEB) return id_chars[thin_line + bits]; return id_chars[thick_line + bits]; } case ICE: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(ice_anim + param); } case LAVA: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(lava_anim + param); } case AMMO: { if(param < 10) return id_chars[low_ammo]; else return id_chars[hi_ammo]; } case LIT_BOMB: { return id_chars[lit_bomb + (param & 0x0F)]; } case DOOR: { if(param & 1) return id_chars[vert_door]; else return id_chars[horiz_door]; } case OPEN_DOOR: { return id_chars[open_door + (param & 0x1F)]; } case CW_ROTATE: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(cw_anim + param); } case CCW_ROTATE: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(ccw_anim + param); } case TRANSPORT: { switch(param & 0x07) { case 0: return id_chars[trans_north + ((param >> 3) & 0x03)]; case 1: return id_chars[trans_south + ((param >> 3) & 0x03)]; case 2: return id_chars[trans_east + ((param >> 3) & 0x03)]; case 3: return id_chars[trans_west + ((param >> 3) & 0x03)]; default: return id_chars[trans_all + ((param >> 3) & 0x03)]; } } case PUSHER: case MISSILE: case SPIKE: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(thick_arrow + param); } case LAZER: { if(param & 1) return id_chars[vert_lazer + ((param >> 1) & 0x03)]; else return id_chars[horiz_lazer + ((param >> 1) & 0x03)]; } case BULLET: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(bullet_char + param); } case FIRE: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(fire_anim + param); } case LIFE: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(life_anim + param); } case RICOCHET_PANEL: { /* Allowed OOB until 2.93d */ return get_id_char_by_legacy_index(ricochet_panels + param); } case MINE: { return id_chars[mine_anim + (param & 0x01)]; } case SHOOTING_FIRE: { return id_chars[shooting_fire_anim + (param & 0x01)]; } case SEEKER: { return id_chars[seeker_anim + (param & 0x03)]; } case BULLET_GUN: case SPINNING_GUN: { return id_chars[thin_arrow + ((param >> 3) & 0x03)]; } case MISSILE_GUN: { return id_chars[thick_arrow + ((param >> 3) & 0x03)]; } case SENSOR: { int idx = param; return (src_board->sensor_list[idx])->sensor_char; } case ROBOT: case ROBOT_PUSHABLE: { int idx = param; return (src_board->robot_list[idx])->robot_char; } case PLAYER: { return id_chars[player_char + (src_board->player_last_dir >> 4)]; } // everything else default: { return id_chars[cell_id]; } } } static unsigned char get_special_id_color(struct board *src_board, enum thing cell_id, char color, char param) { char normal_color = color, spec_color = 0; switch(cell_id) { case ENERGIZER: /* Allowed OOB until 2.93d */ spec_color = get_id_char_by_legacy_index(energizer_glow + param); break; case EXPLOSION: spec_color = id_chars[explosion_colors + (param & 0x0F)]; break; case FIRE: /* Allowed OOB until 2.93d */ spec_color = get_id_char_by_legacy_index(fire_colors + param); break; case LIFE: /* Allowed OOB until 2.93d */ spec_color = get_id_char_by_legacy_index(life_colors + param); break; case WHIRLPOOL_1: case WHIRLPOOL_2: case WHIRLPOOL_3: case WHIRLPOOL_4: spec_color = id_chars[whirlpool_glow + (int)(cell_id - WHIRLPOOL_1)]; break; case SHOOTING_FIRE: spec_color = id_chars[shooting_fire_colors + (param & 1)]; break; case SEEKER: spec_color = id_chars[seeker_colors + (param & 0x03)]; break; case SCROLL: spec_color = scroll_color; break; case PLAYER: /* player */ return id_chars[player_color]; default: return color; } if(!(spec_color & 0xF0)) { normal_color &= 0xF0; normal_color |= (spec_color & 0x0F); } else { normal_color = spec_color; } return normal_color; } unsigned char get_id_char(struct board *src_board, int id_offset) { unsigned char cell_id, cell_char; cell_id = src_board->level_id[id_offset]; cell_char = id_chars[cell_id]; switch(cell_char) { case 255: return src_board->level_param[id_offset]; case 0: return get_special_id_char(src_board, (enum thing)cell_id, src_board->level_param[id_offset], id_offset); default: return cell_char; } } unsigned char get_id_board_color(struct board *src_board, int id_offset, int ignore_under) { unsigned char color = get_special_id_color(src_board, (enum thing)src_board->level_id[id_offset], src_board->level_color[id_offset], src_board->level_param[id_offset] ); if(!(color & 0xF0) && !(ignore_under)) { color |= (src_board->level_under_color[id_offset] & 0xF0); } return color; } unsigned char get_id_color(struct board *src_board, int id_offset) { return get_id_board_color(src_board, id_offset, 0); } unsigned char get_id_under_char(struct board *src_board, int id_offset) { unsigned char cell_id, cell_char; cell_id = src_board->level_under_id[id_offset]; cell_char = id_chars[cell_id]; switch(cell_char) { case 255: return src_board->level_under_param[id_offset]; case 0: return get_special_id_char(src_board, (enum thing)cell_id, src_board->level_under_param[id_offset], id_offset); default: return cell_char; } } unsigned char get_id_under_color(struct board *src_board, int id_offset) { return get_special_id_color(src_board, (enum thing)src_board->level_under_id[id_offset], src_board->level_under_color[id_offset], src_board->level_under_param[id_offset] ); } void id_put(struct board *src_board, unsigned char x_pos, unsigned char y_pos, int array_x, int array_y, int ovr_x, int ovr_y) { int array_offset, overlay_offset; int overlay_mode = src_board->overlay_mode; int board_width = src_board->board_width; unsigned char c, color; array_offset = (array_y * board_width) + array_x; // Note: old worlds unfortunately can contain the hide overlay and hide board // flags, so their checks have been kept functionally intact unless noted. if(!(overlay_mode & OVERLAY_FLAG_HIDE_OVERLAY) && (overlay_mode & OVERLAY_MODE_MASK) != OVERLAY_OFF && (overlay_mode & OVERLAY_MODE_MASK) != OVERLAY_TRANSPARENT) { if((overlay_mode & OVERLAY_MODE_MASK) == OVERLAY_STATIC) { overlay_offset = (ovr_y * board_width) + ovr_x; } else { overlay_offset = array_offset; } select_layer(OVERLAY_LAYER); c = src_board->overlay[overlay_offset]; color = src_board->overlay_color[overlay_offset]; // NOTE: <2.51s3.1 won't display 32 even with OVERLAY_FLAG_HIDE_BOARD set. if(!(overlay_mode & OVERLAY_FLAG_HIDE_BOARD)) { if(c == 32) { select_layer(BOARD_LAYER); c = get_id_char(src_board, array_offset); color = get_id_color(src_board, array_offset); } else if(!(color & 0xF0)) { /* // Undocumented and inaccessible MZXak overlay mode 4. if(overlay_mode == 4) { select_layer(BOARD_LAYER); c = get_id_char(src_board, array_offset); } */ color = (color & 0x0F) | (get_id_color(src_board, array_offset) & 0xF0); } } } else // NOTE: <2.51s3 checked (overlay_mode & OVERLAY_FLAG_HIDE_BOARD) here. { select_layer(BOARD_LAYER); c = get_id_char(src_board, array_offset); color = get_id_color(src_board, array_offset); } draw_char_ext(c, color, x_pos, y_pos, 0, 0); } void draw_game_window(struct board *src_board, int array_x, int array_y) { int x_limit, y_limit; int x, y; int a_x, a_y; int o_x, o_y; x_limit = src_board->viewport_width; y_limit = src_board->viewport_height; for(y = src_board->viewport_y, a_y = array_y, o_y = 0; o_y < y_limit; y++, a_y++, o_y++) { for(x = src_board->viewport_x, a_x = array_x, o_x = 0; o_x < x_limit; x++, a_x++, o_x++) { id_put(src_board, x, y, a_x, a_y, o_x, o_y); } } } void draw_game_window_blind(struct board *src_board, int array_x, int array_y, int player_x, int player_y) { int viewport_x = src_board->viewport_x; int viewport_y = src_board->viewport_y; int viewport_width = src_board->viewport_width; int viewport_height = src_board->viewport_height; int i; select_layer(BOARD_LAYER); for(i = viewport_y; i < viewport_y + viewport_height; i++) fill_line(viewport_width, viewport_x, i, 176, 8); // Find where player would be and draw. if(player_x >= 0 && player_y >= 0) { id_put(src_board, player_x - array_x + viewport_x, player_y - array_y + viewport_y, player_x, player_y, player_x, player_y); } } void draw_viewport(struct board *src_board, int edge_color) { int i, i2; int viewport_x = src_board->viewport_x; int viewport_y = src_board->viewport_y; int viewport_width = src_board->viewport_width; int viewport_height = src_board->viewport_height; // Draw the current viewport if(viewport_y > 1) { // Top for(i = 0; i < viewport_y; i++) fill_line_ext(80, 0, i, 177, edge_color, 0, 0); } if((viewport_y + viewport_height) < 24) { // Bottom for(i = viewport_y + viewport_height + 1; i < 25; i++) fill_line_ext(80, 0, i, 177, edge_color, 0, 0); } if(viewport_x > 1) { // Left for(i = 0; i < 25; i++) fill_line_ext(viewport_x, 0, i, 177, edge_color, 0, 0); } if((viewport_x + viewport_width) < 79) { // Right i2 = viewport_x + viewport_width + 1; for(i = 0; i < 25; i++) { fill_line_ext(80 - i2, i2, i, 177, edge_color, 0, 0); } } // Draw the box if(viewport_x > 0) { // left for(i = 0; i < viewport_height; i++) { draw_char_ext('\xba', edge_color, viewport_x - 1, i + viewport_y, 0, 0); } if(viewport_y > 0) { draw_char_ext('\xc9', edge_color, viewport_x - 1, viewport_y - 1, 0, 0); } } if((viewport_x + viewport_width) < 80) { // right for(i = 0; i < viewport_height; i++) { draw_char_ext('\xba', edge_color, viewport_x + viewport_width, i + viewport_y, 0, 0); } if(viewport_y > 0) { draw_char_ext('\xbb', edge_color, viewport_x + viewport_width, viewport_y - 1, 0, 0); } } if(viewport_y > 0) { // top for(i = 0; i < viewport_width; i++) { draw_char_ext('\xcd', edge_color, viewport_x + i, viewport_y - 1, 0, 0); } } if((viewport_y + viewport_height) < 25) { // bottom for(i = 0; i < viewport_width; i++) { draw_char_ext('\xcd', edge_color, viewport_x + i, viewport_y + viewport_height, 0, 0); } if(viewport_x > 0) { draw_char_ext('\xc8', edge_color, viewport_x - 1, viewport_y + viewport_height, 0, 0); } if((viewport_x + viewport_width) < 80) { draw_char_ext('\xbc', edge_color, viewport_x + viewport_width, viewport_y + viewport_height, 0, 0); } } }
1
0.95735
1
0.95735
game-dev
MEDIA
0.568524
game-dev
0.887009
1
0.887009
Secrets-of-Sosaria/World
3,364
Data/Scripts/Mobiles/Gargoyles/CosmicGargoyle.cs
using System; using Server.Items; namespace Server.Mobiles { [CorpseName( "a gargoyle corpse" )] public class CosmicGargoyle : BaseCreature { public override int BreathPhysicalDamage{ get{ return 30; } } public override int BreathFireDamage{ get{ return 30; } } public override int BreathColdDamage{ get{ return 0; } } public override int BreathPoisonDamage{ get{ return 0; } } public override int BreathEnergyDamage{ get{ return 40; } } public override int BreathEffectHue{ get{ return 0; } } public override bool ReacquireOnMovement{ get{ return !Controlled; } } public override bool HasBreath{ get{ return true; } } public override int BreathEffectSound{ get{ return 0x54A; } } public override int BreathEffectItemID{ get{ return 0x28EF; } } public override void BreathDealDamage( Mobile target, int form ){ base.BreathDealDamage( target, 0 ); } [Constructable] public CosmicGargoyle() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 ) { Name = NameList.RandomName( "drakkul" ); Title = "the cosmic gargoyle"; Body = 127; BaseSoundID = 0x174; SetStr( 360, 550 ); SetDex( 102, 150 ); SetInt( 152, 200 ); SetHits( 282, 385 ); SetDamage( 7, 14 ); SetResistance( ResistanceType.Physical, 40, 60 ); SetResistance( ResistanceType.Fire, 15, 25 ); SetResistance( ResistanceType.Cold, 15, 25 ); SetResistance( ResistanceType.Poison, 15, 25 ); SetResistance( ResistanceType.Energy, 60, 70 ); SetSkill( SkillName.FistFighting, 90.1, 100.0 ); SetSkill( SkillName.Tactics, 90.1, 100.0 ); SetSkill( SkillName.MagicResist, 120.4, 160.0 ); SetSkill( SkillName.Anatomy, 50.5, 100.0 ); SetSkill( SkillName.Swords, 90.1, 100.0 ); SetSkill( SkillName.Bludgeoning, 90.1, 100.0 ); SetSkill( SkillName.Fencing, 90.1, 100.0 ); SetSkill( SkillName.Magery, 90.1, 100.0 ); SetSkill( SkillName.Psychology, 90.1, 100.0 ); SetSkill( SkillName.Meditation, 90.1, 100.0 ); Fame = 10000; Karma = -10000; VirtualArmor = 50; bool keepSword = true; if ( Utility.RandomMinMax( 1, 20 ) == 1 ){ keepSword = false; } if ( Utility.RandomBool() ){ Item sword = new LightSword(); if ( keepSword ){ sword.LootType = LootType.Blessed; } AddItem( sword ); } else { Item swords = new DoubleLaserSword(); if ( keepSword ){ swords.LootType = LootType.Blessed; } AddItem( swords ); } } public override void GenerateLoot() { AddLoot( LootPack.Rich, 2 ); AddLoot( LootPack.Gems, 3 ); } public override void CheckReflect( Mobile caster, ref bool reflect ) { if ( Utility.RandomMinMax( 1, 4 ) == 1 ){ reflect = true; } // 25% spells are reflected back to the caster else { reflect = false; } } public override int Meat{ get{ return 1; } } public override int Hides{ get{ return 3; } } public override HideType HideType{ get{ return HideType.Hellish; } } public override int Skeletal{ get{ return Utility.Random(3); } } public override SkeletalType SkeletalType{ get{ return SkeletalType.Gargoyle; } } public CosmicGargoyle( Serial serial ) : base( serial ) { } 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(); } } }
1
0.941224
1
0.941224
game-dev
MEDIA
0.980039
game-dev
0.963225
1
0.963225
Magneticraft-Team/Magneticraft
13,069
ignore/test/tileentity/multiblock/TileHydraulicPress.kt
package tileentity.multiblock import com.cout970.magneticraft.api.MagneticraftApi import com.cout970.magneticraft.api.heat.IHeatNode import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.api.internal.heat.HeatConnection import com.cout970.magneticraft.api.internal.heat.HeatContainer import com.cout970.magneticraft.api.internal.registries.machines.hydraulicpress.HydraulicPressRecipeManager import com.cout970.magneticraft.api.registries.machines.hydraulicpress.IHydraulicPressRecipe import com.cout970.magneticraft.block.PROPERTY_ACTIVE import com.cout970.magneticraft.block.PROPERTY_DIRECTION import com.cout970.magneticraft.config.Config import com.cout970.magneticraft.misc.ElectricConstants import com.cout970.magneticraft.misc.block.isIn import com.cout970.magneticraft.misc.crafting.CraftingProcess import com.cout970.magneticraft.misc.inventory.get import com.cout970.magneticraft.misc.inventory.set import com.cout970.magneticraft.misc.render.AnimationTimer import com.cout970.magneticraft.misc.tileentity.ITileTrait import com.cout970.magneticraft.misc.tileentity.TraitElectricity import com.cout970.magneticraft.misc.tileentity.TraitHeat import com.cout970.magneticraft.multiblock.IMultiblockCenter import com.cout970.magneticraft.multiblock.Multiblock import com.cout970.magneticraft.multiblock.impl.MultiblockHydraulicPress import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER import com.cout970.magneticraft.registry.HEAT_NODE_HANDLER import com.cout970.magneticraft.registry.ITEM_HANDLER import com.cout970.magneticraft.registry.fromTile import com.cout970.magneticraft.tileentity.TileBase import com.cout970.magneticraft.util.* import com.cout970.magneticraft.util.vector.plus import com.cout970.magneticraft.util.vector.rotatePoint import com.cout970.magneticraft.util.vector.toAABBWith import com.cout970.magneticraft.util.vector.unaryMinus import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.items.IItemHandler import net.minecraftforge.items.ItemStackHandler /** * Created by cout970 on 19/08/2016. */ @TileRegister("hydraulic_press") class TileHydraulicPress : TileBase(), IMultiblockCenter { override var multiblock: Multiblock? get() = MultiblockHydraulicPress set(value) {/* ignored */ } override var centerPos: BlockPos? get() = BlockPos.ORIGIN set(value) {/* ignored */ } override var multiblockFacing: EnumFacing? = null val hammerAnimation = AnimationTimer() val heatNode = HeatContainer( worldGetter = { this.world }, posGetter = { this.getPos() }, dissipation = 0.025, specificHeat = IRON_HEAT_CAPACITY * 10, /*PLACEHOLDER*/ maxHeat = (IRON_HEAT_CAPACITY * 10) * Config.defaultMachineMaxTemp, conductivity = DEFAULT_CONDUCTIVITY ) val traitHeat: TraitHeat = TraitHeat(this, heatNodes, this::updateHeatConnections) val node = ElectricNode({ worldObj }, { pos + direction.rotatePoint(BlockPos.ORIGIN, ENERGY_INPUT) }) val traitElectricity = TraitElectricity(this, listOf(node)) override val traits: List<ITileTrait> = listOf(traitHeat, traitElectricity) val heatNodes: List<IHeatNode> get() = listOf(heatNode) val safeHeat: Long = ((IRON_HEAT_CAPACITY * 10 * Config.defaultMachineSafeTemp)).toLong() val efficiency = 0.9 var overtemp = false val inventory = ItemStackHandler(1) val craftingProcess: CraftingProcess private var recipeCache: IHydraulicPressRecipe? = null private var inputCache: ItemStack? = null init { craftingProcess = CraftingProcess({ //craft val recipe = getRecipe()!! inventory[0] = null inventory[0] = recipe.output }, { //can craft node.voltage > ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE && getRecipe() != null && inventory[0]!!.stackSize == getRecipe()!!.input.stackSize && overtemp == false }, { // use energy val applied = Config.hydraulicPressConsumption * interpolate(node.voltage, 60.0, 70.0) node.applyPower(-applied, false) if (heatNode.applyHeat(applied * (1 - efficiency) * ENERGY_TO_HEAT, false) > 0) { //If there's any heat leftover after we tried to push heat, the machine has overheated overtemp = true } }, { getRecipe()?.duration ?: 120f }) } override fun shouldRefresh(world: World, pos: BlockPos, oldState: IBlockState, newSate: IBlockState): Boolean { return oldState?.block !== newSate?.block } fun getRecipe(input: ItemStack): IHydraulicPressRecipe? { if (input === inputCache) return recipeCache val recipe = HydraulicPressRecipeManager.findRecipe(input) if (recipe != null) { recipeCache = recipe inputCache = input } return recipe } fun getRecipe(): IHydraulicPressRecipe? = if (inventory[0] != null) getRecipe(inventory[0]!!) else null override fun update() { if (worldObj.isServer && active) { if (shouldTick(20)) sendUpdateToNearPlayers() craftingProcess.tick(worldObj, 1f) if (heatNode.heat < safeHeat) overtemp = false } super.update() } override fun onActivate() { getBlockState() sendUpdateToNearPlayers() } val direction: EnumFacing get() = if (PROPERTY_DIRECTION.isIn(getBlockState())) getBlockState()[PROPERTY_DIRECTION] else EnumFacing.NORTH val active: Boolean get() = if (PROPERTY_ACTIVE.isIn(getBlockState())) getBlockState()[PROPERTY_ACTIVE] else false fun updateHeatConnections(traitHeat: TraitHeat) { traitHeat.apply { for (j in POTENTIAL_CONNECTIONS) { val relPos = direction.rotatePoint(BlockPos.ORIGIN, j) + pos val tileOther = world.getTileEntity(relPos) ?: continue val handler = (HEAT_NODE_HANDLER!!.fromTile(tileOther) ?: continue) ?: continue for (otherNode in handler.nodes.filter { it is IHeatNode }.map { it as IHeatNode }) { connections.add(HeatConnection(heatNode, otherNode)) handler.addConnection(HeatConnection(otherNode, heatNode)) } } } } override fun save(): NBTTagCompound { val nbt = newNbt { if (multiblockFacing != null) { add("direction", multiblockFacing!!) } add("inv", inventory.serializeNBT()) add("crafting", craftingProcess.serializeNBT()) } return super.save().also { it.merge(nbt) } } override fun load(nbt: NBTTagCompound) = nbt.run { if (hasKey("direction")) multiblockFacing = getEnumFacing("direction") if (hasKey("inv")) inventory.deserializeNBT(getCompoundTag("inv")) if (hasKey("crafting")) craftingProcess.deserializeNBT(getCompoundTag("crafting")) super.load(nbt) } override fun getRenderBoundingBox(): AxisAlignedBB = (BlockPos.ORIGIN toAABBWith direction.rotatePoint( BlockPos.ORIGIN, multiblock!!.size)).offset(direction.rotatePoint(BlockPos.ORIGIN, -multiblock!!.center)).offset(pos) companion object { val ENERGY_INPUT = BlockPos(1, 1, 0) val HEAT_OUTPUT = BlockPos(-1, 1, 0) val POTENTIAL_CONNECTIONS = setOf(BlockPos(-2, 1, 0), BlockPos(-1, 1, 1), BlockPos(-1, 1, -1)) //Optimistation to stop multiblocks checking inside themselves for heat connections } override fun onBreak() { super.onBreak() if (worldObj.isServer) { for (i in 0 until inventory.slots) { val item = inventory[i] if (item != null) { dropItem(item, pos) dropItem(item, pos) } } } } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?, relPos: BlockPos): Boolean { if (capability == HEAT_NODE_HANDLER) { if (direction.rotatePoint(BlockPos.ORIGIN, HEAT_OUTPUT) == relPos || direction.rotatePoint(BlockPos.ORIGIN, ENERGY_INPUT) == relPos && (facing == direction.rotateY() || facing == null)) return true } return false } @Suppress("UNCHECKED_CAST") override fun <T> getCapability(capability: Capability<T>, facing: EnumFacing?, relPos: BlockPos): T? { if (capability == HEAT_NODE_HANDLER) if (direction.rotatePoint(BlockPos.ORIGIN, HEAT_OUTPUT) == relPos) return this as T if (direction.rotatePoint(BlockPos.ORIGIN, ENERGY_INPUT) == relPos && (facing == direction.rotateY())) return this as T return null } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean { if (capability == ITEM_HANDLER) return true if (capability == HEAT_NODE_HANDLER) return true if (capability == ELECTRIC_NODE_HANDLER) return true return super.hasCapability(capability, facing) } @Suppress("UNCHECKED_CAST") override fun <T : Any> getCapability(capability: Capability<T>, facing: EnumFacing?): T? { if (capability == ITEM_HANDLER) return Inventory(inventory) as T if (capability == HEAT_NODE_HANDLER) return traitHeat as T if (capability == ELECTRIC_NODE_HANDLER) return traitElectricity as T return super.getCapability(capability, facing) } override fun shouldRenderInPass(pass: Int): Boolean { return if (active) super.shouldRenderInPass(pass) else pass == 1 } class Inventory(val inv: IItemHandler) : IItemHandler by inv { override fun insertItem(slot: Int, stack: ItemStack?, simulate: Boolean): ItemStack? { if (stack == null) return null var canAccept = false if (inv[0] == null) { canAccept = true } else { val manager = MagneticraftApi.getHydraulicPressRecipeManager() val recipe = manager.findRecipe(inv[0]) if (recipe != null && recipe.input.stackSize > inv[0]!!.stackSize) { canAccept = true } } if (canAccept) { val manager = MagneticraftApi.getHydraulicPressRecipeManager() val recipe = manager.findRecipe(stack) ?: return stack if (inv[0] == null) { if (stack.stackSize == recipe.input.stackSize) { return inv.insertItem(slot, stack, simulate) } else if (stack.stackSize > recipe.input.stackSize) { val copy = stack.copy() val newStack = copy.splitStack(recipe.input.stackSize) inv.insertItem(slot, newStack, simulate) return copy } else { return inv.insertItem(slot, stack, simulate) } } else { val currentRecipe = manager.findRecipe(inv[0]) if (recipe != currentRecipe) return stack if (stack.stackSize + inv[0]!!.stackSize == recipe.input.stackSize) { return inv.insertItem(slot, stack, simulate) } else if (stack.stackSize + inv[0]!!.stackSize > recipe.input.stackSize) { val copy = stack.copy() val newStack = copy.splitStack(recipe.input.stackSize - inv[0]!!.stackSize) val ret = inv.insertItem(slot, newStack, simulate) if (ret == null) { return copy } else { return stack } } else { return inv.insertItem(slot, stack, simulate) } } } return stack } override fun extractItem(slot: Int, amount: Int, simulate: Boolean): ItemStack? { val input = inv[0] ?: return null val manager = MagneticraftApi.getHydraulicPressRecipeManager() if (manager.findRecipe(input) == null) { return inv.extractItem(slot, amount, simulate) } return null } } }
1
0.918468
1
0.918468
game-dev
MEDIA
0.971372
game-dev
0.905991
1
0.905991
casbin/node-casbin
2,012
src/model/functionMap.ts
// Copyright 2017 The casbin Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as util from '../util'; export type MatchingFunction = (...arg: any[]) => boolean | number | string | Promise<boolean> | Promise<number> | Promise<string>; // FunctionMap represents the collection of Function. export class FunctionMap { private functions: Map<string, any>; /** * constructor is the constructor for FunctionMap. */ constructor() { this.functions = new Map<string, any>(); } // loadFunctionMap loads an initial function map. public static loadFunctionMap(): FunctionMap { const fm = new FunctionMap(); fm.addFunction('keyMatch', util.keyMatchFunc); fm.addFunction('keyGet', util.keyGetFunc); fm.addFunction('keyMatch2', util.keyMatch2Func); fm.addFunction('keyGet2', util.keyGet2Func); fm.addFunction('keyMatch3', util.keyMatch3Func); fm.addFunction('keyMatch4', util.keyMatch4Func); fm.addFunction('keyMatch5', util.keyMatch5Func); fm.addFunction('regexMatch', util.regexMatchFunc); fm.addFunction('ipMatch', util.ipMatchFunc); fm.addFunction('globMatch', util.globMatch); return fm; } // addFunction adds an expression function. public addFunction(name: string, func: MatchingFunction): void { if (!this.functions.get(name)) { this.functions.set(name, func); } } // getFunctions return all functions. public getFunctions(): any { return this.functions; } }
1
0.571501
1
0.571501
game-dev
MEDIA
0.316551
game-dev
0.72646
1
0.72646
LanternPowered/Lantern
11,139
src/main/java/org/lanternpowered/server/inventory/AbstractBuilder.java
/* * This file is part of LanternServer, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * 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.lanternpowered.server.inventory; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.lanternpowered.server.util.Conditions.checkPlugin; import com.google.common.collect.ImmutableMap; import org.lanternpowered.server.game.Lantern; import org.lanternpowered.server.inventory.behavior.ShiftClickBehavior; import org.lanternpowered.server.inventory.constructor.InventoryConstructor; import org.lanternpowered.server.inventory.constructor.InventoryConstructorFactory; import org.lanternpowered.server.inventory.property.AbstractInventoryProperty; import org.lanternpowered.server.text.translation.TextTranslation; import org.spongepowered.api.CatalogKey; import org.spongepowered.api.item.inventory.InventoryArchetypes; import org.spongepowered.api.item.inventory.InventoryProperty; import org.spongepowered.api.item.inventory.property.GuiIdProperty; import org.spongepowered.api.item.inventory.property.Identifiable; import org.spongepowered.api.item.inventory.property.InventoryCapacity; import org.spongepowered.api.item.inventory.property.InventoryDimension; import org.spongepowered.api.item.inventory.property.InventoryTitle; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.translation.Translation; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.function.Supplier; import javax.annotation.Nullable; @SuppressWarnings({"unchecked", "ConstantConditions"}) public abstract class AbstractBuilder<R extends T, T extends AbstractInventory, B extends AbstractBuilder<R, T, B>> { @Nullable protected InventoryConstructor<R> constructor; protected final Map<Class<?>, Map<String, InventoryProperty<String, ?>>> properties = new HashMap<>(); @Nullable protected Map<Class<?>, Map<String, InventoryProperty<String, ?>>> cachedProperties; // Catalog properties @Nullable protected PluginContainer pluginContainer; @Nullable protected Translation translation; @Nullable protected ShiftClickBehavior shiftClickBehavior; private boolean viewable; /** * Sets the {@link Supplier} for the {@link AbstractInventory}, the * supplied slot may not be initialized yet. * * @param inventoryType The inventory type * @param <N> The inventory type * @return This builder, for chaining */ public <N extends T> AbstractBuilder<N, T, ?> type(Class<N> inventoryType) { checkNotNull(inventoryType, "inventoryType"); this.constructor = InventoryConstructorFactory.get().getConstructor((Class<R>) inventoryType); return (AbstractBuilder<N, T, ?>) this; } /** * Sets the {@link ShiftClickBehavior} of the {@link AbstractInventory}. This behavior * will only be used if this is the directly the top inventory. * * @param shiftClickBehavior The shift click behavior * @return This builder, for chaining */ public B shiftClickBehavior(ShiftClickBehavior shiftClickBehavior) { checkNotNull(shiftClickBehavior, "shiftClickBehavior"); this.shiftClickBehavior = shiftClickBehavior; return (B) this; } /** * Adds the provided {@link InventoryProperty}. * * @param property The property * @return This builder, for chaining */ public B property(InventoryProperty<String, ?> property) { checkNotNull(property, "property"); // checkState(!(property instanceof InventoryCapacity), "The inventory capacity cannot be modified with a property."); // checkState(!(property instanceof InventoryDimension), "The inventory dimension cannot be modified with a property."); if (property instanceof InventoryDimension || property instanceof InventoryCapacity) { return (B) this; } // All inventories with this property are viewable if (property instanceof GuiIdProperty) { this.viewable = true; } putProperty(property); if (property instanceof InventoryTitle) { this.translation = TextTranslation.of((Text) property.getValue()); } return (B) this; } /** * Sets the title {@link Translation}. * * @param translation The title translation * @return This builder, for chaining */ public B title(Translation translation) { checkNotNull(translation, "translation"); this.translation = translation; putProperty(InventoryTitle.builder().value(TextTranslation.toText(translation)).build()); return (B) this; } private void putProperty(InventoryProperty<String, ?> property) { this.properties.computeIfAbsent(AbstractInventoryProperty.getType(property.getClass()), type -> new HashMap<>()).put(property.getKey(), property); this.cachedProperties = null; } /** * Sets the plugin that provides the {@link LanternInventoryArchetype}. * * @param plugin The plugin instance * @return This builder, for chaining */ public B plugin(Object plugin) { this.pluginContainer = checkPlugin(plugin, "plugin"); return (B) this; } /** * Constructs a {@link AbstractInventory}. * * @return The inventory */ public R build() { return build0(false, this.pluginContainer == null ? Lantern.getImplementationPlugin() : this.pluginContainer, null); } /** * Constructs a {@link AbstractInventory} and sets the plugin * instance that constructed the inventory. * * @param plugin The plugin * @return The inventory */ public R build(Object plugin) { return build(false, plugin, null); } R build(boolean carried, Object plugin, @Nullable LanternInventoryArchetype<R> archetype) { return build0(carried, checkPlugin(plugin, "plugin"), archetype); } R build0(boolean carried, @Nullable PluginContainer plugin, @Nullable LanternInventoryArchetype<R> archetype) { checkState(this.constructor != null, "Inventory constructor must be set."); if (plugin == null) { plugin = this.pluginContainer == null ? Lantern.getImplementationPlugin() : this.pluginContainer; } int flags = 0; if (carried) { flags |= InventoryConstructor.CARRIED; } if (this.viewable) { flags |= InventoryConstructor.VIEWABLE; } final R inventory = this.constructor.construct(flags); if (inventory instanceof AbstractMutableInventory) { final AbstractMutableInventory mutableInventory = (AbstractMutableInventory) inventory; mutableInventory.setPlugin(plugin); // Copy the properties and set them in the inventory if (this.cachedProperties == null) { final ImmutableMap.Builder<Class<?>, Map<String, InventoryProperty<String, ?>>> builder = ImmutableMap.builder(); for (Map.Entry<Class<?>, Map<String, InventoryProperty<String, ?>>> entry : this.properties.entrySet()) { builder.put(entry.getKey(), ImmutableMap.copyOf(entry.getValue())); } this.cachedProperties = builder.build(); } Map<Class<?>, Map<String, InventoryProperty<String, ?>>> properties = this.cachedProperties; if (!properties.containsKey(Identifiable.class)) { final ImmutableMap.Builder<Class<?>, Map<String, InventoryProperty<String, ?>>> builder = ImmutableMap.builder(); builder.putAll(properties); final Identifiable identifiable = Identifiable.random(); builder.put(Identifiable.class, ImmutableMap.of(identifiable.getKey(), identifiable)); properties = builder.build(); } mutableInventory.setProperties((Map) properties); } if (this.translation != null) { inventory.setName(this.translation); } try { build(inventory); } catch (Exception e) { try { if (archetype == null) { archetype = (LanternInventoryArchetype<R>) inventory.getArchetype(); } if (archetype == InventoryArchetypes.UNKNOWN) { throw e; } final CatalogKey key = archetype.getKey(); final String builderType = archetype.getBuilder().getClass().getName(); throw new RuntimeException("An error occurred while constructing " + key + " with builder type " + builderType, e); } catch (Exception e1) { throw e; } } if (inventory instanceof AbstractMutableInventory) { final AbstractMutableInventory mutableInventory = (AbstractMutableInventory) inventory; if (archetype != null) { mutableInventory.setArchetype(archetype); } else if (this instanceof AbstractArchetypeBuilder) { final String pluginId = (this.pluginContainer == null ? Lantern.getImplementationPlugin() : this.pluginContainer).getId(); mutableInventory.setArchetype(((AbstractArchetypeBuilder) this).buildArchetype(pluginId, UUID.randomUUID().toString())); } if (this.shiftClickBehavior != null) { mutableInventory.setShiftClickBehavior(this.shiftClickBehavior); } } return inventory; } /** * Initializes the build {@link AbstractInventory}. * * @param inventory The inventory */ protected abstract void build(R inventory); }
1
0.940702
1
0.940702
game-dev
MEDIA
0.810209
game-dev
0.888225
1
0.888225
ElunaLuaEngine/ElunaTrinityWotlk
17,590
src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "GameTime.h" #include "InstanceScript.h" #include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "SpellScript.h" #include "ulduar.h" #include "Vehicle.h" enum Yells { SAY_AGGRO = 0, SAY_SUMMON = 1, SAY_SLAG_POT = 2, SAY_SCORCH = 3, SAY_SLAY = 4, SAY_BERSERK = 5, SAY_DEATH = 6, EMOTE_JETS = 7 }; enum Spells { SPELL_FLAME_JETS = 62680, SPELL_SCORCH = 62546, SPELL_SLAG_POT = 62717, SPELL_SLAG_POT_DAMAGE = 65722, SPELL_SLAG_IMBUED = 62836, SPELL_ACTIVATE_CONSTRUCT = 62488, SPELL_STRENGHT = 64473, SPELL_GRAB = 62707, SPELL_BERSERK = 47008, // Iron Construct SPELL_HEAT = 65667, SPELL_MOLTEN = 62373, SPELL_BRITTLE = 62382, SPELL_BRITTLE_25 = 67114, SPELL_SHATTER = 62383, SPELL_GROUND = 62548, }; enum Events { EVENT_JET = 1, EVENT_SCORCH = 2, EVENT_SLAG_POT = 3, EVENT_GRAB_POT = 4, EVENT_CHANGE_POT = 5, EVENT_END_POT = 6, EVENT_CONSTRUCT = 7, EVENT_BERSERK = 8, }; enum Actions { ACTION_REMOVE_BUFF = 20, }; enum Creatures { NPC_IRON_CONSTRUCT = 33121, NPC_GROUND_SCORCH = 33221, }; enum AchievementData { DATA_SHATTERED = 29252926, ACHIEVEMENT_IGNIS_START_EVENT = 20951, }; #define CONSTRUCT_SPAWN_POINTS 20 Position const ConstructSpawnPosition[CONSTRUCT_SPAWN_POINTS] = { {630.366f, 216.772f, 360.891f, 3.001970f}, {630.594f, 231.846f, 360.891f, 3.124140f}, {630.435f, 337.246f, 360.886f, 3.211410f}, {630.493f, 313.349f, 360.886f, 3.054330f}, {630.444f, 321.406f, 360.886f, 3.124140f}, {630.366f, 247.307f, 360.888f, 3.211410f}, {630.698f, 305.311f, 360.886f, 3.001970f}, {630.500f, 224.559f, 360.891f, 3.054330f}, {630.668f, 239.840f, 360.890f, 3.159050f}, {630.384f, 329.585f, 360.886f, 3.159050f}, {543.220f, 313.451f, 360.886f, 0.104720f}, {543.356f, 329.408f, 360.886f, 6.248280f}, {543.076f, 247.458f, 360.888f, 6.213370f}, {543.117f, 232.082f, 360.891f, 0.069813f}, {543.161f, 305.956f, 360.886f, 0.157080f}, {543.277f, 321.482f, 360.886f, 0.052360f}, {543.316f, 337.468f, 360.886f, 6.195920f}, {543.280f, 239.674f, 360.890f, 6.265730f}, {543.265f, 217.147f, 360.891f, 0.174533f}, {543.256f, 224.831f, 360.891f, 0.122173f}, }; class boss_ignis : public CreatureScript { public: boss_ignis() : CreatureScript("boss_ignis") { } struct boss_ignis_AI : public BossAI { boss_ignis_AI(Creature* creature) : BossAI(creature, DATA_IGNIS) { Initialize(); } void Initialize() { _slagPotGUID.Clear(); _shattered = false; _firstConstructKill = 0; } void Reset() override { _Reset(); if (Vehicle* _vehicle = me->GetVehicleKit()) _vehicle->RemoveAllPassengers(); instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEVEMENT_IGNIS_START_EVENT); } void JustEngagedWith(Unit* who) override { BossAI::JustEngagedWith(who); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_JET, 30s); events.ScheduleEvent(EVENT_SCORCH, 25s); events.ScheduleEvent(EVENT_SLAG_POT, 35s); events.ScheduleEvent(EVENT_CONSTRUCT, 15s); events.ScheduleEvent(EVENT_END_POT, 40s); events.ScheduleEvent(EVENT_BERSERK, 480s); Initialize(); instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEVEMENT_IGNIS_START_EVENT); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_DEATH); } uint32 GetData(uint32 type) const override { if (type == DATA_SHATTERED) return _shattered ? 1 : 0; return 0; } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } void JustSummoned(Creature* summon) override { if (summon->GetEntry() == NPC_IRON_CONSTRUCT) { summon->SetFaction(FACTION_MONSTER_2); summon->SetReactState(REACT_AGGRESSIVE); summon->RemoveUnitFlag(UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_UNINTERACTIBLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED); summon->SetImmuneToPC(false); summon->SetControlled(false, UNIT_STATE_ROOT); } summon->AI()->AttackStart(me->GetVictim()); summon->AI()->DoZoneInCombat(); summons.Summon(summon); } void DoAction(int32 action) override { if (action != ACTION_REMOVE_BUFF) return; me->RemoveAuraFromStack(SPELL_STRENGHT); // Shattered Achievement time_t secondKill = GameTime::GetGameTime(); if ((secondKill - _firstConstructKill) < 5) _shattered = true; _firstConstructKill = secondKill; } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_JET: Talk(EMOTE_JETS); DoCast(me, SPELL_FLAME_JETS); events.ScheduleEvent(EVENT_JET, 35s, 40s); break; case EVENT_SLAG_POT: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 1, 100, true)) { Talk(SAY_SLAG_POT); _slagPotGUID = target->GetGUID(); DoCast(target, SPELL_GRAB); events.DelayEvents(3s); events.ScheduleEvent(EVENT_GRAB_POT, 500ms); } events.ScheduleEvent(EVENT_SLAG_POT, RAID_MODE(30s, 15s)); break; case EVENT_GRAB_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { slagPotTarget->EnterVehicle(me, 0); events.CancelEvent(EVENT_GRAB_POT); events.ScheduleEvent(EVENT_CHANGE_POT, 1s); } break; case EVENT_CHANGE_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { DoCast(slagPotTarget, SPELL_SLAG_POT, true); slagPotTarget->EnterVehicle(me, 1); events.CancelEvent(EVENT_CHANGE_POT); events.ScheduleEvent(EVENT_END_POT, 10s); } break; case EVENT_END_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { slagPotTarget->ExitVehicle(); slagPotTarget = nullptr; _slagPotGUID.Clear(); events.CancelEvent(EVENT_END_POT); } break; case EVENT_SCORCH: Talk(SAY_SCORCH); if (Unit* target = me->GetVictim()) me->SummonCreature(NPC_GROUND_SCORCH, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 45s); DoCast(SPELL_SCORCH); events.ScheduleEvent(EVENT_SCORCH, 25s); break; case EVENT_CONSTRUCT: Talk(SAY_SUMMON); DoSummon(NPC_IRON_CONSTRUCT, ConstructSpawnPosition[urand(0, CONSTRUCT_SPAWN_POINTS - 1)], 30s, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT); DoCast(SPELL_STRENGHT); DoCast(me, SPELL_ACTIVATE_CONSTRUCT); events.ScheduleEvent(EVENT_CONSTRUCT, RAID_MODE(40s, 30s)); break; case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); Talk(SAY_BERSERK); break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } private: ObjectGuid _slagPotGUID; time_t _firstConstructKill; bool _shattered; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<boss_ignis_AI>(creature); } }; class npc_iron_construct : public CreatureScript { public: npc_iron_construct() : CreatureScript("npc_iron_construct") { } struct npc_iron_constructAI : public ScriptedAI { npc_iron_constructAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { Initialize(); creature->SetReactState(REACT_PASSIVE); } void Initialize() { _brittled = false; } void Reset() override { Initialize(); } void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType /*damageType*/, SpellInfo const* /*spellInfo = nullptr*/) override { if (me->HasAura(RAID_MODE(SPELL_BRITTLE, SPELL_BRITTLE_25)) && damage >= 5000) { DoCast(SPELL_SHATTER); if (Creature* ignis = _instance->GetCreature(DATA_IGNIS)) if (ignis->AI()) ignis->AI()->DoAction(ACTION_REMOVE_BUFF); me->DespawnOrUnsummon(1s); } } void UpdateAI(uint32 /*uiDiff*/) override { if (!UpdateVictim()) return; if (Aura* aur = me->GetAura(SPELL_HEAT)) { if (aur->GetStackAmount() >= 10) { me->RemoveAura(SPELL_HEAT); DoCast(SPELL_MOLTEN); _brittled = false; } } // Water pools if (me->IsInWater() && !_brittled && me->HasAura(SPELL_MOLTEN)) { DoCast(SPELL_BRITTLE); me->RemoveAura(SPELL_MOLTEN); _brittled = true; } DoMeleeAttackIfReady(); } private: InstanceScript* _instance; bool _brittled; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_iron_constructAI>(creature); } }; class npc_scorch_ground : public CreatureScript { public: npc_scorch_ground() : CreatureScript("npc_scorch_ground") { } struct npc_scorch_groundAI : public ScriptedAI { npc_scorch_groundAI(Creature* creature) : ScriptedAI(creature) { Initialize(); me->SetUnitFlag(UNIT_FLAG_UNINTERACTIBLE | UNIT_FLAG_PACIFIED); me->SetControlled(true, UNIT_STATE_ROOT); creature->SetDisplayId(16925); //model 2 in db cannot overwrite wdb fields } void Initialize() { _heat = false; _constructGUID.Clear(); _heatTimer = 0; } void MoveInLineOfSight(Unit* who) override { if (!_heat) { if (who->GetEntry() == NPC_IRON_CONSTRUCT) { if (!who->HasAura(SPELL_HEAT) || !who->HasAura(SPELL_MOLTEN)) { _constructGUID = who->GetGUID(); _heat = true; } } } } void Reset() override { Initialize(); DoCast(me, SPELL_GROUND); } void UpdateAI(uint32 uiDiff) override { if (_heat) { if (_heatTimer <= uiDiff) { Creature* construct = ObjectAccessor::GetCreature(*me, _constructGUID); if (construct && !construct->HasAura(SPELL_MOLTEN)) { me->AddAura(SPELL_HEAT, construct); _heatTimer = 1000; } } else _heatTimer -= uiDiff; } } private: ObjectGuid _constructGUID; uint32 _heatTimer; bool _heat; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_scorch_groundAI>(creature); } }; // 62717, 63477 - Slag Pot class spell_ignis_slag_pot : public SpellScriptLoader { public: spell_ignis_slag_pot() : SpellScriptLoader("spell_ignis_slag_pot") { } class spell_ignis_slag_pot_AuraScript : public AuraScript { PrepareAuraScript(spell_ignis_slag_pot_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_SLAG_POT_DAMAGE, SPELL_SLAG_IMBUED }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) { if (Unit* caster = GetCaster()) { Unit* target = GetTarget(); caster->CastSpell(target, SPELL_SLAG_POT_DAMAGE, true); } } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (GetTarget()->IsAlive()) GetTarget()->CastSpell(GetTarget(), SPELL_SLAG_IMBUED, true); } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_ignis_slag_pot_AuraScript::HandleEffectPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); AfterEffectRemove += AuraEffectRemoveFn(spell_ignis_slag_pot_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_ignis_slag_pot_AuraScript(); } }; class achievement_ignis_shattered : public AchievementCriteriaScript { public: achievement_ignis_shattered() : AchievementCriteriaScript("achievement_ignis_shattered") { } bool OnCheck(Player* /*source*/, Unit* target) override { if (UnitAI* ai = target ? target->GetAI() : nullptr) return ai->GetData(DATA_SHATTERED) != 0; return false; } }; void AddSC_boss_ignis() { new boss_ignis(); new npc_iron_construct(); new npc_scorch_ground(); new spell_ignis_slag_pot(); new achievement_ignis_shattered(); }
1
0.92362
1
0.92362
game-dev
MEDIA
0.994053
game-dev
0.926978
1
0.926978
followingthefasciaplane/source-engine-diff-check
1,432
misc/game/client/cstrike15/fx_cs_impacts.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Game-specific impact effect hooks // //=============================================================================// #include "cbase.h" #include "fx_impact.h" #include "engine/IEngineSound.h" // NOTE: This has to be the last file included! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: Handle weapon impacts //----------------------------------------------------------------------------- void ImpactCallback( const CEffectData &data ) { trace_t tr; Vector vecOrigin, vecStart, vecShotDir; int iMaterial, iDamageType, iHitbox; short nSurfaceProp; C_BaseEntity *pEntity = ParseImpactData( data, &vecOrigin, &vecStart, &vecShotDir, nSurfaceProp, iMaterial, iDamageType, iHitbox ); if ( !pEntity || pEntity->IsDormant()) return; int flags = 0; if ( (iDamageType & DMG_SHOCK) != 0 ) // no decals for shock damage { flags = IMPACT_NODECAL; } // If we hit, perform our custom effects and play the sound if ( Impact( vecOrigin, vecStart, iMaterial, iDamageType, iHitbox, pEntity, tr, flags ) ) { // Check for custom effects based on the Decal index PerformCustomEffects( vecOrigin, tr, vecShotDir, iMaterial, 1.0 ); } PlayImpactSound( pEntity, tr, vecOrigin, nSurfaceProp ); } DECLARE_CLIENT_EFFECT( Impact, ImpactCallback );
1
0.927247
1
0.927247
game-dev
MEDIA
0.905656
game-dev
0.661998
1
0.661998
OversizedSunCoreDev/ArtilleryEco
16,063
Barrage/Source/JoltPhysics/Jolt/Physics/SoftBody/SoftBodyShape.cpp
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2023 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <Jolt/Jolt.h> #include <Jolt/Physics/SoftBody/SoftBodyShape.h> #include <Jolt/Core/Profiler.h> #include <Jolt/Geometry/RayTriangle.h> #include <Jolt/Physics/Collision/RayCast.h> #include <Jolt/Physics/Collision/CastResult.h> #include <Jolt/Physics/Collision/TransformedShape.h> #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h> #include <Jolt/Physics/Collision/CastConvexVsTriangles.h> #include <Jolt/Physics/Collision/CastSphereVsTriangles.h> #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h> #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h> #include <Jolt/Physics/Collision/CollisionDispatch.h> #ifdef JPH_DEBUG_RENDERER #include <Jolt/Renderer/DebugRenderer.h> #endif // JPH_DEBUG_RENDERER JPH_NAMESPACE_BEGIN uint SoftBodyShape::GetSubShapeIDBits() const { // Ensure we have enough bits to encode our shape [0, n - 1] uint32 n = (uint32)mSoftBodyMotionProperties->GetFaces().size() - 1; return 32 - CountLeadingZeros(n); } uint32 SoftBodyShape::GetFaceIndex(const SubShapeID &inSubShapeID) const { SubShapeID remainder; uint32 face_index = inSubShapeID.PopID(GetSubShapeIDBits(), remainder); JPH_ASSERT(remainder.IsEmpty()); return face_index; } AABox SoftBodyShape::GetLocalBounds() const { return mSoftBodyMotionProperties->GetLocalBounds(); } bool SoftBodyShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const { JPH_PROFILE_FUNCTION(); uint num_triangle_bits = GetSubShapeIDBits(); uint triangle_idx = uint(-1); const Array<SoftBodyVertex> &vertices = mSoftBodyMotionProperties->GetVertices(); for (const SoftBodyMotionProperties::Face &f : mSoftBodyMotionProperties->GetFaces()) { Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, x1, x2, x3); if (fraction < ioHit.mFraction) { // Store fraction ioHit.mFraction = fraction; // Store triangle index triangle_idx = uint(&f - mSoftBodyMotionProperties->GetFaces().data()); } } if (triangle_idx == uint(-1)) return false; ioHit.mSubShapeID2 = inSubShapeIDCreator.PushID(triangle_idx, num_triangle_bits).GetID(); return true; } void SoftBodyShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const { JPH_PROFILE_FUNCTION(); // Test shape filter if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID())) return; uint num_triangle_bits = GetSubShapeIDBits(); bool check_backfaces = inRayCastSettings.mBackFaceModeTriangles == EBackFaceMode::IgnoreBackFaces && !mSoftBodyMotionProperties->GetFacesDoubleSided(); const Array<SoftBodyVertex> &vertices = mSoftBodyMotionProperties->GetVertices(); for (const SoftBodyMotionProperties::Face &f : mSoftBodyMotionProperties->GetFaces()) { Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; // Back facing check if (check_backfaces && (x2 - x1).Cross(x3 - x1).Dot(inRay.mDirection) > 0.0f) continue; // Test ray against triangle float fraction = RayTriangle(inRay.mOrigin, inRay.mDirection, x1, x2, x3); if (fraction < ioCollector.GetEarlyOutFraction()) { // Better hit than the current hit RayCastResult hit; hit.mBodyID = TransformedShape::sGetBodyID(ioCollector.GetContext()); hit.mFraction = fraction; hit.mSubShapeID2 = inSubShapeIDCreator.PushID(uint(&f - mSoftBodyMotionProperties->GetFaces().data()), num_triangle_bits).GetID(); ioCollector.AddHit(hit); } } } void SoftBodyShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const { sCollidePointUsingRayCast(*this, inPoint, inSubShapeIDCreator, ioCollector, inShapeFilter); } void SoftBodyShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const { /* Not implemented */ } const PhysicsMaterial *SoftBodyShape::GetMaterial(const SubShapeID &inSubShapeID) const { SubShapeID remainder; uint triangle_idx = inSubShapeID.PopID(GetSubShapeIDBits(), remainder); JPH_ASSERT(remainder.IsEmpty()); const SoftBodyMotionProperties::Face &f = mSoftBodyMotionProperties->GetFace(triangle_idx); return mSoftBodyMotionProperties->GetMaterials()[f.mMaterialIndex]; } Vec3 SoftBodyShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const { SubShapeID remainder; uint triangle_idx = inSubShapeID.PopID(GetSubShapeIDBits(), remainder); JPH_ASSERT(remainder.IsEmpty()); const SoftBodyMotionProperties::Face &f = mSoftBodyMotionProperties->GetFace(triangle_idx); const Array<SoftBodyVertex> &vertices = mSoftBodyMotionProperties->GetVertices(); Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; return (x2 - x1).Cross(x3 - x1).NormalizedOr(Vec3::sAxisY()); } void SoftBodyShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const { SubShapeID remainder; uint triangle_idx = inSubShapeID.PopID(GetSubShapeIDBits(), remainder); JPH_ASSERT(remainder.IsEmpty()); const SoftBodyMotionProperties::Face &f = mSoftBodyMotionProperties->GetFace(triangle_idx); const Array<SoftBodyVertex> &vertices = mSoftBodyMotionProperties->GetVertices(); for (uint32 i : f.mVertex) outVertices.push_back(inCenterOfMassTransform * (inScale * vertices[i].mPosition)); } void SoftBodyShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const { outSubmergedVolume = 0.0f; outTotalVolume = mSoftBodyMotionProperties->GetVolume(); outCenterOfBuoyancy = Vec3::sZero(); } #ifdef JPH_DEBUG_RENDERER void SoftBodyShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const { const Array<SoftBodyVertex> &vertices = mSoftBodyMotionProperties->GetVertices(); for (const SoftBodyMotionProperties::Face &f : mSoftBodyMotionProperties->GetFaces()) { RVec3 x1 = inCenterOfMassTransform * vertices[f.mVertex[0]].mPosition; RVec3 x2 = inCenterOfMassTransform * vertices[f.mVertex[1]].mPosition; RVec3 x3 = inCenterOfMassTransform * vertices[f.mVertex[2]].mPosition; inRenderer->DrawTriangle(x1, x2, x3, inColor, DebugRenderer::ECastShadow::On); } } #endif // JPH_DEBUG_RENDERER struct SoftBodyShape::SBSGetTrianglesContext { Mat44 mCenterOfMassTransform; int mTriangleIndex; }; void SoftBodyShape::GetTrianglesStart(GetTrianglesContext &ioContext, [[maybe_unused]] const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const { SBSGetTrianglesContext &context = reinterpret_cast<SBSGetTrianglesContext &>(ioContext); context.mCenterOfMassTransform = Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale); context.mTriangleIndex = 0; } int SoftBodyShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const { SBSGetTrianglesContext &context = reinterpret_cast<SBSGetTrianglesContext &>(ioContext); const Array<SoftBodyMotionProperties::Face> &faces = mSoftBodyMotionProperties->GetFaces(); const Array<SoftBodyVertex> &vertices = mSoftBodyMotionProperties->GetVertices(); const PhysicsMaterialList &materials = mSoftBodyMotionProperties->GetMaterials(); int num_triangles = min(inMaxTrianglesRequested, (int)faces.size() - context.mTriangleIndex); for (int i = 0; i < num_triangles; ++i) { const SoftBodyMotionProperties::Face &f = faces[context.mTriangleIndex + i]; Vec3 x1 = context.mCenterOfMassTransform * vertices[f.mVertex[0]].mPosition; Vec3 x2 = context.mCenterOfMassTransform * vertices[f.mVertex[1]].mPosition; Vec3 x3 = context.mCenterOfMassTransform * vertices[f.mVertex[2]].mPosition; x1.StoreFloat3(outTriangleVertices++); x2.StoreFloat3(outTriangleVertices++); x3.StoreFloat3(outTriangleVertices++); if (outMaterials != nullptr) *outMaterials++ = materials[f.mMaterialIndex]; } context.mTriangleIndex += num_triangles; return num_triangles; } Shape::Stats SoftBodyShape::GetStats() const { return Stats(sizeof(*this), (uint)mSoftBodyMotionProperties->GetFaces().size()); } float SoftBodyShape::GetVolume() const { return mSoftBodyMotionProperties->GetVolume(); } void SoftBodyShape::sCollideConvexVsSoftBody(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter) { JPH_ASSERT(inShape1->GetType() == EShapeType::Convex); const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1); JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::SoftBody); const SoftBodyShape *shape2 = static_cast<const SoftBodyShape *>(inShape2); const Array<SoftBodyVertex> &vertices = shape2->mSoftBodyMotionProperties->GetVertices(); const Array<SoftBodyMotionProperties::Face> &faces = shape2->mSoftBodyMotionProperties->GetFaces(); uint num_triangle_bits = shape2->GetSubShapeIDBits(); CollideShapeSettings settings(inCollideShapeSettings); if (shape2->mSoftBodyMotionProperties->GetFacesDoubleSided()) settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces; CollideConvexVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), settings, ioCollector); for (const SoftBodyMotionProperties::Face &f : faces) { Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; collider.Collide(x1, x2, x3, 0b111, inSubShapeIDCreator2.PushID(uint(&f - faces.data()), num_triangle_bits).GetID()); } } void SoftBodyShape::sCollideSphereVsSoftBody(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter) { JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere); const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1); JPH_ASSERT(inShape2->GetSubType() == EShapeSubType::SoftBody); const SoftBodyShape *shape2 = static_cast<const SoftBodyShape *>(inShape2); const Array<SoftBodyVertex> &vertices = shape2->mSoftBodyMotionProperties->GetVertices(); const Array<SoftBodyMotionProperties::Face> &faces = shape2->mSoftBodyMotionProperties->GetFaces(); uint num_triangle_bits = shape2->GetSubShapeIDBits(); CollideShapeSettings settings(inCollideShapeSettings); if (shape2->mSoftBodyMotionProperties->GetFacesDoubleSided()) settings.mBackFaceMode = EBackFaceMode::CollideWithBackFaces; CollideSphereVsTriangles collider(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), settings, ioCollector); for (const SoftBodyMotionProperties::Face &f : faces) { Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; collider.Collide(x1, x2, x3, 0b111, inSubShapeIDCreator2.PushID(uint(&f - faces.data()), num_triangle_bits).GetID()); } } void SoftBodyShape::sCastConvexVsSoftBody(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector) { JPH_ASSERT(inShape->GetSubType() == EShapeSubType::SoftBody); const SoftBodyShape *shape = static_cast<const SoftBodyShape *>(inShape); const Array<SoftBodyVertex> &vertices = shape->mSoftBodyMotionProperties->GetVertices(); const Array<SoftBodyMotionProperties::Face> &faces = shape->mSoftBodyMotionProperties->GetFaces(); uint num_triangle_bits = shape->GetSubShapeIDBits(); ShapeCastSettings settings(inShapeCastSettings); if (shape->mSoftBodyMotionProperties->GetFacesDoubleSided()) settings.mBackFaceModeTriangles = EBackFaceMode::CollideWithBackFaces; CastConvexVsTriangles caster(inShapeCast, settings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector); for (const SoftBodyMotionProperties::Face &f : faces) { Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; caster.Cast(x1, x2, x3, 0b111, inSubShapeIDCreator2.PushID(uint(&f - faces.data()), num_triangle_bits).GetID()); } } void SoftBodyShape::sCastSphereVsSoftBody(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector) { JPH_ASSERT(inShape->GetSubType() == EShapeSubType::SoftBody); const SoftBodyShape *shape = static_cast<const SoftBodyShape *>(inShape); const Array<SoftBodyVertex> &vertices = shape->mSoftBodyMotionProperties->GetVertices(); const Array<SoftBodyMotionProperties::Face> &faces = shape->mSoftBodyMotionProperties->GetFaces(); uint num_triangle_bits = shape->GetSubShapeIDBits(); ShapeCastSettings settings(inShapeCastSettings); if (shape->mSoftBodyMotionProperties->GetFacesDoubleSided()) settings.mBackFaceModeTriangles = EBackFaceMode::CollideWithBackFaces; CastSphereVsTriangles caster(inShapeCast, settings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector); for (const SoftBodyMotionProperties::Face &f : faces) { Vec3 x1 = vertices[f.mVertex[0]].mPosition; Vec3 x2 = vertices[f.mVertex[1]].mPosition; Vec3 x3 = vertices[f.mVertex[2]].mPosition; caster.Cast(x1, x2, x3, 0b111, inSubShapeIDCreator2.PushID(uint(&f - faces.data()), num_triangle_bits).GetID()); } } void SoftBodyShape::sRegister() { ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::SoftBody); f.mConstruct = nullptr; // Not supposed to be constructed by users! f.mColor = Color::sDarkGreen; for (EShapeSubType s : sConvexSubShapeTypes) { CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::SoftBody, sCollideConvexVsSoftBody); CollisionDispatch::sRegisterCastShape(s, EShapeSubType::SoftBody, sCastConvexVsSoftBody); CollisionDispatch::sRegisterCollideShape(EShapeSubType::SoftBody, s, CollisionDispatch::sReversedCollideShape); CollisionDispatch::sRegisterCastShape(EShapeSubType::SoftBody, s, CollisionDispatch::sReversedCastShape); } // Specialized collision functions CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::SoftBody, sCollideSphereVsSoftBody); CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::SoftBody, sCastSphereVsSoftBody); } JPH_NAMESPACE_END
1
0.966431
1
0.966431
game-dev
MEDIA
0.688521
game-dev,graphics-rendering
0.975679
1
0.975679
Flipper76/Kali-Zero-Firmware
1,133
applications/external/t5577_multiwriter/scenes/t5577_multiwriter_scene.c
#include "t5577_multiwriter_scene.h" // Generate scene on_enter handlers array #define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, void (*const t5577_multiwriter_on_enter_handlers[])(void*) = { #include "t5577_multiwriter_scene_config.h" }; #undef ADD_SCENE // Generate scene on_event handlers array #define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, bool (*const t5577_multiwriter_on_event_handlers[])(void* context, SceneManagerEvent event) = { #include "t5577_multiwriter_scene_config.h" }; #undef ADD_SCENE // Generate scene on_exit handlers array #define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, void (*const t5577_multiwriter_on_exit_handlers[])(void* context) = { #include "t5577_multiwriter_scene_config.h" }; #undef ADD_SCENE // Initialize scene handlers configuration structure const SceneManagerHandlers t5577_multiwriter_scene_handlers = { .on_enter_handlers = t5577_multiwriter_on_enter_handlers, .on_event_handlers = t5577_multiwriter_on_event_handlers, .on_exit_handlers = t5577_multiwriter_on_exit_handlers, .scene_num = LfRfidSceneNum, };
1
0.938418
1
0.938418
game-dev
MEDIA
0.511046
game-dev
0.872502
1
0.872502
airbnb/aerosolve
2,967
core/src/main/java/com/airbnb/aerosolve/core/transforms/MoveFloatToStringTransform.java
package com.airbnb.aerosolve.core.transforms; import com.airbnb.aerosolve.core.FeatureVector; import com.airbnb.aerosolve.core.util.TransformUtil; import com.airbnb.aerosolve.core.util.Util; import com.typesafe.config.Config; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.Map.Entry; import java.util.List; /** * Moves named fields from one family to another. If keys are not specified, all keys are moved * from the float family. Features are capped via a `cap` config, which defaults to 1e10, to avoid * exploding string features. The original float feature is removed but can be overridden using * `keep` boolean config. */ public class MoveFloatToStringTransform implements Transform { private String fieldName1; private double bucket; private String outputName; private List<String> keys; private double cap; private boolean keep; @Override public void configure(Config config, String key) { fieldName1 = config.getString(key + ".field1"); bucket = config.getDouble(key + ".bucket"); outputName = config.getString(key + ".output"); if (config.hasPath(key + ".keys")) { keys = config.getStringList(key + ".keys"); } if (config.hasPath(key + ".cap")) { cap = config.getDouble(key + ".cap"); } else { cap = 1e10; } if (config.hasPath(key + ".keep")) { keep = config.getBoolean(key + ".keep"); } else { keep = false; } } @Override public void doTransform(FeatureVector featureVector) { Map<String, Map<String, Double>> floatFeatures = featureVector.getFloatFeatures(); if (floatFeatures == null) { return; } Map<String, Double> feature1 = floatFeatures.get(fieldName1); if (feature1 == null || feature1.isEmpty()) { return; } Util.optionallyCreateStringFeatures(featureVector); Map<String, Set<String>> stringFeatures = featureVector.getStringFeatures(); Set<String> output = Util.getOrCreateStringFeature(outputName, stringFeatures); if (keys != null) { for (String key : keys) { moveFloat(feature1, output, key, cap, bucket); if(!keep) { feature1.remove(key); } } } else { for (Iterator<Entry<String, Double>> iterator = feature1.entrySet().iterator(); iterator.hasNext();) { Entry<String, Double> entry = iterator.next(); String key = entry.getKey(); moveFloat(feature1, output, key, cap, bucket); if(!keep) { iterator.remove(); } } } } public static void moveFloat( Map<String, Double> feature1, Set<String> output, String key, double cap, double bucket) { if (feature1.containsKey(key)) { Double dbl = feature1.get(key); if (dbl > cap) { dbl = cap; } Double quantized = TransformUtil.quantize(dbl, bucket); output.add(key + '=' + quantized); } } }
1
0.887717
1
0.887717
game-dev
MEDIA
0.581616
game-dev
0.95626
1
0.95626
microsoft/vsminecraft
2,243
minecraftpkg/MekanismModSample/src/main/java/mekanism/common/item/ItemGasMask.java
package mekanism.common.item; import mekanism.client.render.ModelCustomArmor; import mekanism.client.render.ModelCustomArmor.ArmorModel; import mekanism.common.Mekanism; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraftforge.common.util.EnumHelper; import net.minecraftforge.event.entity.living.LivingAttackEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemGasMask extends ItemArmor { public ItemGasMask() { super(EnumHelper.addArmorMaterial("GASMASK", 0, new int[] {0, 0, 0, 0}, 0), 0, 0); setCreativeTab(Mekanism.tabMekanism); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister register) {} @Override public boolean isValidArmor(ItemStack stack, int armorType, Entity entity) { return armorType == 0; } @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { return "mekanism:render/NullArmor.png"; } @Override @SideOnly(Side.CLIENT) public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { ModelCustomArmor model = ModelCustomArmor.INSTANCE; model.modelType = ArmorModel.GASMASK; return model; } @SubscribeEvent public void onEntityAttacked(LivingAttackEvent event) { EntityLivingBase base = event.entityLiving; if(base.getEquipmentInSlot(4) != null && base.getEquipmentInSlot(4).getItem() instanceof ItemGasMask) { ItemGasMask mask = (ItemGasMask)base.getEquipmentInSlot(4).getItem(); if(base.getEquipmentInSlot(3) != null && base.getEquipmentInSlot(3).getItem() instanceof ItemScubaTank) { ItemScubaTank tank = (ItemScubaTank)base.getEquipmentInSlot(3).getItem(); if(tank.getFlowing(base.getEquipmentInSlot(3)) && tank.getGas(base.getEquipmentInSlot(3)) != null) { if(event.source == DamageSource.magic) { event.setCanceled(true); } } } } } }
1
0.839116
1
0.839116
game-dev
MEDIA
0.993608
game-dev
0.918619
1
0.918619
scriptdev2/scriptdev2
3,668
scripts/eastern_kingdoms/scholomance/scholomance.h
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software licensed under GPL version 2 * Please see the included DOCS/LICENSE.TXT for more information */ #ifndef DEF_SCHOLOMANCE_H #define DEF_SCHOLOMANCE_H enum { MAX_ENCOUNTER = 10, MAX_EVENTS = 6, TYPE_KIRTONOS = 0, TYPE_RATTLEGORE = 1, TYPE_RAS_FROSTWHISPER = 2, TYPE_MALICIA = 3, TYPE_THEOLEN = 4, TYPE_POLKELT = 5, TYPE_RAVENIAN = 6, TYPE_ALEXEI_BAROV = 7, TYPE_ILLUCIA_BAROV = 8, TYPE_GANDLING = 9, NPC_KIRTONOS = 10506, NPC_RATTLEGORE = 11622, NPC_RAS_FROSTWHISPER = 10508, NPC_THEOLEN_KRASTINOV = 11261, NPC_LOREKEEPER_POLKELT = 10901, NPC_RAVENIAN = 10507, NPC_ILLUCIA_BAROV = 10502, NPC_ALEXEI_BAROV = 10504, NPC_INSTRUCTOR_MALICIA = 10505, NPC_DARKMASTER_GANDLING = 1853, NPC_BONE_MINION = 16119, // summoned in random rooms by gandling GO_GATE_KIRTONOS = 175570, GO_VIEWING_ROOM_DOOR = 175167, // Must be opened in reload case GO_GATE_RAS = 177370, GO_GATE_MALICIA = 177375, GO_GATE_THEOLEN = 177377, GO_GATE_POLKELT = 177376, GO_GATE_RAVENIAN = 177372, GO_GATE_BAROV = 177373, GO_GATE_ILLUCIA = 177371, GO_GATE_GANDLING = 177374, // Because the shadow portal teleport coordinates are guesswork (taken from old script) these IDs might be randomized // TODO Syncronise with correct DB coordinates when they will be known EVENT_ID_POLKELT = 5618, EVENT_ID_THEOLEN = 5619, EVENT_ID_MALICIA = 5620, EVENT_ID_ILLUCIA = 5621, EVENT_ID_BAROV = 5622, EVENT_ID_RAVENIAN = 5623, SAY_GANDLING_SPAWN = -1289000, }; struct SpawnLocation { float m_fX, m_fY, m_fZ, m_fO; }; static const SpawnLocation aGandlingSpawnLocs[1] = { {180.771f, -5.4286f, 75.5702f, 1.29154f} }; struct GandlingEventData { GandlingEventData() : m_bIsActive(false) {} bool m_bIsActive; ObjectGuid m_doorGuid; std::set<uint32> m_sAddGuids; }; static const uint32 aGandlingEvents[MAX_EVENTS] = {EVENT_ID_POLKELT, EVENT_ID_THEOLEN, EVENT_ID_MALICIA, EVENT_ID_ILLUCIA, EVENT_ID_BAROV, EVENT_ID_RAVENIAN}; typedef std::map<uint32, GandlingEventData> GandlingEventMap; class instance_scholomance : public ScriptedInstance { public: instance_scholomance(Map* pMap); ~instance_scholomance() {} void Initialize() override; void OnCreatureEnterCombat(Creature* pCreature) override; void OnCreatureEvade(Creature* pCreature); void OnCreatureDeath(Creature* pCreature) override; void OnCreatureCreate(Creature* pCreature) override; void OnObjectCreate(GameObject* pGo) override; void OnPlayerEnter(Player* pPlayer) override; void HandlePortalEvent(uint32 uiEventId, uint32 uiData); void SetData(uint32 uiType, uint32 uiData) override; uint32 GetData(uint32 uiType) const override; const char* Save() const override { return m_strInstData.c_str(); } void Load(const char* chrIn) override; private: void DoSpawnGandlingIfCan(bool bByPlayerEnter); uint32 m_auiEncounter[MAX_ENCOUNTER]; std::string m_strInstData; uint32 m_uiGandlingEvent; GandlingEventMap m_mGandlingData; }; #endif
1
0.853812
1
0.853812
game-dev
MEDIA
0.982652
game-dev
0.688843
1
0.688843
narknon/FF7R2UProj
1,296
Plugins/KineDriverPlugin/Source/KineDriverRt/Public/AnimNode_SQEX_KineDriver.h
#pragma once #include "CoreMinimal.h" #include "BoneControllers/AnimNode_SkeletalControlBase.h" #include "AnimNode_SQEX_KineDriver.generated.h" class USQEX_KineDriverData; USTRUCT(BlueprintType) struct KINEDRIVERRT_API FAnimNode_SQEX_KineDriver : public FAnimNode_SkeletalControlBase { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) int32 KineDriverIndex; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<USQEX_KineDriverData*> KineDriverData; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool EnableScaleOpChildSSC; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) TArray<FName> TargetNodeDisableScaleOpChildSSC; UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true)) bool Enabled; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool EnableLOD; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float MinScreenSize; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) bool EnableCheckDrawn; FAnimNode_SQEX_KineDriver(); };
1
0.915453
1
0.915453
game-dev
MEDIA
0.832455
game-dev
0.594013
1
0.594013
matpow2/voxie
4,269
include/win32/bullet/BulletCollision/CollisionShapes/btConvexHullShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CONVEX_HULL_SHAPE_H #define BT_CONVEX_HULL_SHAPE_H #include "btPolyhedralConvexShape.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types #include "LinearMath/btAlignedObjectArray.h" ///The btConvexHullShape implements an implicit convex hull of an array of vertices. ///Bullet provides a general and fast collision detector for convex shapes based on GJK and EPA using localGetSupportingVertex. ATTRIBUTE_ALIGNED16(class) btConvexHullShape : public btPolyhedralConvexAabbCachingShape { btAlignedObjectArray<btVector3> m_unscaledPoints; public: BT_DECLARE_ALIGNED_ALLOCATOR(); ///this constructor optionally takes in a pointer to points. Each point is assumed to be 3 consecutive btScalar (x,y,z), the striding defines the number of bytes between each point, in memory. ///It is easier to not pass any points in the constructor, and just add one point at a time, using addPoint. ///btConvexHullShape make an internal copy of the points. btConvexHullShape(const btScalar* points=0,int numPoints=0, int stride=sizeof(btVector3)); void addPoint(const btVector3& point); btVector3* getUnscaledPoints() { return &m_unscaledPoints[0]; } const btVector3* getUnscaledPoints() const { return &m_unscaledPoints[0]; } ///getPoints is obsolete, please use getUnscaledPoints const btVector3* getPoints() const { return getUnscaledPoints(); } SIMD_FORCE_INLINE btVector3 getScaledPoint(int i) const { return m_unscaledPoints[i] * m_localScaling; } SIMD_FORCE_INLINE int getNumPoints() const { return m_unscaledPoints.size(); } virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void project(const btTransform& trans, const btVector3& dir, btScalar& minProj, btScalar& maxProj, btVector3& witnesPtMin,btVector3& witnesPtMax) const; //debugging virtual const char* getName()const {return "Convex";} virtual int getNumVertices() const; virtual int getNumEdges() const; virtual void getEdge(int i,btVector3& pa,btVector3& pb) const; virtual void getVertex(int i,btVector3& vtx) const; virtual int getNumPlanes() const; virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i ) const; virtual bool isInside(const btVector3& pt,btScalar tolerance) const; ///in case we receive negative scaling virtual void setLocalScaling(const btVector3& scaling); virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btConvexHullShapeData { btConvexInternalShapeData m_convexInternalShapeData; btVector3FloatData *m_unscaledPointsFloatPtr; btVector3DoubleData *m_unscaledPointsDoublePtr; int m_numUnscaledPoints; char m_padding3[4]; }; SIMD_FORCE_INLINE int btConvexHullShape::calculateSerializeBufferSize() const { return sizeof(btConvexHullShapeData); } #endif //BT_CONVEX_HULL_SHAPE_H
1
0.939108
1
0.939108
game-dev
MEDIA
0.993636
game-dev
0.911598
1
0.911598
microsoft/MixedReality-WorldLockingTools-Samples
1,305
Advanced/ASA/Assets/MRTK/Core/Inspectors/PropertyDrawers/PhysicsLayerAttributeDrawer.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Editor; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Physics.Editor { /// <summary> /// Renders the physics layer dropdown based on the current layers set in the Tag Manager. /// </summary> [CustomPropertyDrawer(typeof(PhysicsLayerAttribute))] public sealed class PhysicsLayerAttributeDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var guiContents = new List<GUIContent>(); var layerIds = new List<int>(); for (int i = 0; i < EditorLayerExtensions.TagManagerLayers.arraySize; i++) { var layer = EditorLayerExtensions.TagManagerLayers.GetArrayElementAtIndex(i); if (!string.IsNullOrWhiteSpace(layer.stringValue)) { guiContents.Add(new GUIContent($"{i}: {layer.stringValue}")); layerIds.Add(i); } } property.intValue = EditorGUI.IntPopup(position, label, property.intValue, guiContents.ToArray(), layerIds.ToArray()); } } }
1
0.681437
1
0.681437
game-dev
MEDIA
0.546354
game-dev
0.786945
1
0.786945
google/j2objc
4,086
cycle_finder/src/main/java/com/google/devtools/cyclefinder/NameList.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cyclefinder; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; /** * Manages a set of suppress list or restrict-to list entries. * * @author Keith Stanger */ public class NameList { private Set<String> fields = Sets.newHashSet(); private SetMultimap<String, String> fieldsWithTypes = HashMultimap.create(); private Set<String> types = Sets.newHashSet(); private Set<String> namespaces = Sets.newHashSet(); private Set<String> outers = Sets.newHashSet(); public boolean containsField(TypeNode origin, String fieldName) { return fields.contains(origin.getQualifiedName() + '.' + fieldName); } public boolean isSuppressListedTypeForField(String fieldName, TypeNode type) { return fieldsWithTypes.containsEntry(fieldName, type.getQualifiedName()); } public boolean hasOuterForType(TypeNode type) { return outers.contains(type.getQualifiedName()); } public boolean containsType(TypeNode type) { String typeName = type.getQualifiedName(); if (types.contains(typeName)) { return true; } while (true) { if (namespaces.contains(typeName)) { return true; } int idx = typeName.lastIndexOf('.'); if (idx < 0) { break; } typeName = typeName.substring(0, idx); } return false; } private static final Splitter ENTRY_SPLITTER = Splitter.on(CharMatcher.whitespace()).trimResults().omitEmptyStrings(); public void addEntry(String entry) { String[] tokens = Iterables.toArray(ENTRY_SPLITTER.split(entry), String.class); if (tokens.length < 2) { badEntry(entry); } String entryType = tokens[0].toLowerCase(); if (entryType.equals("field")) { if (tokens.length == 2) { fields.add(tokens[1]); } else if (tokens.length == 3) { fieldsWithTypes.put(tokens[1], tokens[2]); } else { badEntry(entry); } } else if (entryType.equals("type") && tokens.length == 2) { types.add(tokens[1]); } else if (entryType.equals("namespace") && tokens.length == 2) { namespaces.add(tokens[1]); } else if (entryType.equals("outer") && tokens.length == 2) { outers.add(tokens[1]); } else { badEntry(entry); } } private void badEntry(String entry) { throw new IllegalArgumentException("Invalid suppress-list entry: " + entry); } public void addFile(String file, String encoding) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(new File(file)), encoding)); try { for (String line = in.readLine(); line != null; line = in.readLine()) { String entry = line.split("#", 2)[0].trim(); if (!Strings.isNullOrEmpty(entry)) { addEntry(entry); } } } finally { in.close(); } } public static NameList createFromFiles(Iterable<String> files, String encoding) throws IOException { NameList nameList = new NameList(); for (String file : files) { nameList.addFile(file, encoding); } return nameList; } }
1
0.87816
1
0.87816
game-dev
MEDIA
0.402039
game-dev
0.978647
1
0.978647
idiap/pygafro
3,462
src/cpp/bindings.cpp
/* * SPDX-FileCopyrightText: Copyright © 2024 Idiap Research Institute <contact@idiap.ch> * * SPDX-FileContributor: Philip Abbet <philip.abbet@idiap.ch> * * SPDX-License-Identifier: MPL-2.0 */ #include <pybind11/pybind11.h> #include <pybind11/eigen.h> #include <pybind11/stl.h> #include <gafro/gafro.hpp> namespace py = pybind11; using namespace gafro; void init_multivectors(py::module &); void init_algebra(py::module &); void init_singlemanipulatortargets(py::module &); void init_singlemanipulatormotorcosts(py::module &); void init_singlemanipulatordualtargets(py::module &); void init_physics(py::module &); void init_robots(py::module &); void init_geometric_products(py::module &); void init_inner_products(py::module &); void init_outer_products(py::module &); int grade(short blade) { static const int GRADES[] = { 0, // scalar 1, // e0 1, // e1 2, // e01 1, // e2 2, // e02 2, // e12 3, // e012 1, // e3 2, // e03 2, // e13 3, // e013 2, // e23 3, // e023 3, // e123 4, // e0123 1, // ei 2, // e0i 2, // e1i 3, // e01i 2, // e2i 3, // e02i 3, // e12i 4, // e012i 2, // e3i 3, // e03i 3, // e13i 4, // e013i 3, // e23i 4, // e023i 4, // e123i 5, // e0123i }; return GRADES[blade]; } PYBIND11_MODULE(_pygafro, m) { // blades-related constants py::module m_blades = m.def_submodule("blades"); m_blades.attr("scalar") = blades::scalar; m_blades.attr("e1") = blades::e1; m_blades.attr("e2") = blades::e2; m_blades.attr("e3") = blades::e3; m_blades.attr("ei") = blades::ei; m_blades.attr("e0") = blades::e0; m_blades.attr("e23") = blades::e23; m_blades.attr("e13") = blades::e13; m_blades.attr("e12") = blades::e12; m_blades.attr("e1i") = blades::e1i; m_blades.attr("e2i") = blades::e2i; m_blades.attr("e3i") = blades::e3i; m_blades.attr("e01") = blades::e01; m_blades.attr("e02") = blades::e02; m_blades.attr("e03") = blades::e03; m_blades.attr("e0i") = blades::e0i; m_blades.attr("e123") = blades::e123; m_blades.attr("e12i") = blades::e12i; m_blades.attr("e13i") = blades::e13i; m_blades.attr("e23i") = blades::e23i; m_blades.attr("e012") = blades::e012; m_blades.attr("e013") = blades::e013; m_blades.attr("e023") = blades::e023; m_blades.attr("e01i") = blades::e01i; m_blades.attr("e02i") = blades::e02i; m_blades.attr("e03i") = blades::e03i; m_blades.attr("e123i") = blades::e123i; m_blades.attr("e0123") = blades::e0123; m_blades.attr("e012i") = blades::e012i; m_blades.attr("e023i") = blades::e023i; m_blades.attr("e013i") = blades::e013i; m_blades.attr("e0123i") = blades::e0123i; // The grade() function m.def("grade", &grade); // Bindings of each sections init_multivectors(m); init_algebra(m); init_physics(m); init_robots(m); // Internal functions py::module m_internals = m.def_submodule("internals"); init_geometric_products(m_internals); init_inner_products(m_internals); init_outer_products(m_internals); init_singlemanipulatortargets(m_internals); init_singlemanipulatormotorcosts(m_internals); init_singlemanipulatordualtargets(m_internals); }
1
0.899459
1
0.899459
game-dev
MEDIA
0.304121
game-dev
0.665052
1
0.665052
OpenSAGE/OpenSAGE
3,735
src/OpenSage.Game/Scripting/ScriptArgument.cs
using System.IO; using System.Numerics; using OpenSage.FileFormats; namespace OpenSage.Scripting; public sealed class ScriptArgument { public ScriptArgumentType ArgumentType { get; set; } // Either... public int? IntValue { get; set; } public float? FloatValue { get; set; } public string StringValue { get; set; } // Or... public Vector3? PositionValue { get; set; } public bool IntValueAsBool => IntValue.Value == 1; public ScriptArgument() { } public ScriptArgument(ScriptArgumentType argumentType, float floatValue) { ArgumentType = argumentType; FloatValue = floatValue; } public ScriptArgument(ScriptArgumentType argumentType, string stringValue) { ArgumentType = argumentType; StringValue = stringValue; } public ScriptArgument(ScriptArgumentType argumentType, int intValue) { ArgumentType = argumentType; IntValue = intValue; } internal static ScriptArgument Parse(BinaryReader reader) { // TODO: Need to make game-specific ScriptArgumentType enums. var argumentType = (ScriptArgumentType)reader.ReadUInt32(); //var argumentType = reader.ReadUInt32AsEnum<ScriptArgumentType>(); int? uintValue = null; float? floatValue = null; string stringValue = null; Vector3? positionValue = null; if (argumentType == ScriptArgumentType.PositionCoordinate) { positionValue = reader.ReadVector3(); } else { uintValue = reader.ReadInt32(); floatValue = reader.ReadSingle(); stringValue = reader.ReadUInt16PrefixedAsciiString(); } return new ScriptArgument { ArgumentType = argumentType, IntValue = uintValue, FloatValue = floatValue, StringValue = stringValue, PositionValue = positionValue }; } internal void WriteTo(BinaryWriter writer) { writer.Write((uint)ArgumentType); if (ArgumentType == ScriptArgumentType.PositionCoordinate) { writer.Write(PositionValue.Value); } else { writer.Write(IntValue.Value); writer.Write(FloatValue.Value); writer.WriteUInt16PrefixedAsciiString(StringValue); } } public override string ToString() { var value = string.Empty; if (IntValue != null) { value = $"Int: {IntValue.Value.ToString()}"; } else if (FloatValue != null) { value = $"Float: {FloatValue.Value.ToString()}"; } else if (StringValue != null) { value = $"String: {StringValue}"; } else if (PositionValue != null) { value = $"Position: {PositionValue.Value.ToString()}"; } return $"({ArgumentType}) {value}"; } public ScriptArgument Copy(string appendix) { return new ScriptArgument() { ArgumentType = ArgumentType, FloatValue = FloatValue, PositionValue = PositionValue, IntValue = IntValue, StringValue = ArgumentType switch { ScriptArgumentType.CounterName => StringValue + appendix, ScriptArgumentType.FlagName => StringValue + appendix, ScriptArgumentType.ScriptName => StringValue + appendix, ScriptArgumentType.SubroutineName => StringValue + appendix, ScriptArgumentType.TeamName => StringValue + appendix, _ => StringValue } }; } }
1
0.919199
1
0.919199
game-dev
MEDIA
0.443669
game-dev
0.905282
1
0.905282
signalwire/freeswitch
4,584
src/mod/languages/mod_managed/managed/XmlSearchBinding.cs
/* * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed * Copyright (C) 2008, Michael Giagnocavo <mgg@giagnocavo.net> * * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed * * The Initial Developer of the Original Code is * Michael Giagnocavo <mgg@giagnocavo.net> * Portions created by the Initial Developer are Copyright (C) * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Michael Giagnocavo <mgg@giagnocavo.net> * * XmlSearchBinding.cs - Helpers for switch_xml_bind_search_function * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Reflection; using FreeSWITCH.Native; namespace FreeSWITCH { public class SwitchXmlSearchBinding : IDisposable { public class XmlBindingArgs { public string Section { get; set; } public string TagName { get; set; } public string KeyName { get; set; } public string KeyValue { get; set; } public switch_event Parameters { get; set; } } //typedef switch_xml_t (*switch_xml_search_function_t) (const char *section, // const char *tag_name, const char *key_name, const char *key_value, switch_event_t *params, // void *user_data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate IntPtr switch_xml_search_function_delegate(string section, string tag_name, string key_name, string key_value, IntPtr param, IntPtr user_data); readonly switch_xml_search_function_delegate del; // Prevent GC readonly SWIGTYPE_p_f_p_q_const__char_p_q_const__char_p_q_const__char_p_q_const__char_p_switch_event_t_p_void__p_switch_xml function; private SwitchXmlSearchBinding(SWIGTYPE_p_f_p_q_const__char_p_q_const__char_p_q_const__char_p_q_const__char_p_switch_event_t_p_void__p_switch_xml function, switch_xml_search_function_delegate origDelegate) { this.function = function; this.del = origDelegate; } bool disposed; public void Dispose() { dispose(); GC.SuppressFinalize(this); } void dispose() { if (disposed) return; // HACK: FS crashes if we unbind after shutdown is pretty complete. This is still a race condition. if (freeswitch.switch_core_ready() == switch_bool_t.SWITCH_FALSE) return; freeswitch.switch_xml_unbind_search_function_ptr(this.function); disposed = true; } ~SwitchXmlSearchBinding() { dispose(); } public static IDisposable Bind(Func<XmlBindingArgs, string> f, switch_xml_section_enum_t sections) { switch_xml_search_function_delegate boundFunc = (section, tag, key, keyval, param, userData) => { var args = new XmlBindingArgs { Section = section, TagName = tag, KeyName = key, KeyValue = keyval, Parameters = new switch_event(param, false) }; var xmlStr = f(args); var fsxml = string.IsNullOrEmpty(xmlStr) ? null : freeswitch.switch_xml_parse_str_dynamic(xmlStr, switch_bool_t.SWITCH_TRUE); return switch_xml.getCPtr(fsxml).Handle; }; var fp = Marshal.GetFunctionPointerForDelegate(boundFunc); var swigFp = new SWIGTYPE_p_f_p_q_const__char_p_q_const__char_p_q_const__char_p_q_const__char_p_switch_event_t_p_void__p_switch_xml(fp, false); var res = freeswitch.switch_xml_bind_search_function_ret(swigFp, (uint)sections, null, null); if (res != switch_status_t.SWITCH_STATUS_SUCCESS) { throw new InvalidOperationException("Call to switch_xml_bind_search_function_ret failed, result: " + res + "."); } return new SwitchXmlSearchBinding(swigFp, boundFunc); } } }
1
0.85922
1
0.85922
game-dev
MEDIA
0.300522
game-dev
0.712024
1
0.712024
Layers-of-Railways/Railway
20,422
forge/src/main/java/com/railwayteam/railways/content/fuel/tank/FuelTankBlockEntity.java
/* * Steam 'n' Rails * Copyright (c) 2022-2024 The Railways Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.railwayteam.railways.content.fuel.tank; import com.railwayteam.railways.content.fuel.LiquidFuelTrainHandler; import com.simibubi.create.api.connectivity.ConnectivityHandler; import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation; import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.blockEntity.IMultiBlockEntityContainer; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import com.simibubi.create.foundation.fluid.SmartFluidTank; import com.simibubi.create.foundation.utility.animation.LerpedFloat; import com.simibubi.create.infrastructure.config.AllConfigs; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidType; import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.templates.FluidTank; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import static java.lang.Math.abs; public class FuelTankBlockEntity extends SmartBlockEntity implements IHaveGoggleInformation, IMultiBlockEntityContainer.Fluid { private static final int MAX_SIZE = 3; protected LazyOptional<IFluidHandler> fluidCapability; protected boolean forceFluidLevelUpdate; protected FuelFluidHandler tankInventory; protected BlockPos controller; protected BlockPos lastKnownPos; protected boolean updateConnectivity; protected boolean updateCapability; protected boolean window; protected int luminosity; protected int width; protected int height; private static final int SYNC_RATE = 8; protected int syncCooldown; protected boolean queuedSync; // For rendering purposes only private LerpedFloat fluidLevel; public FuelTankBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state); tankInventory = createInventory(); fluidCapability = LazyOptional.of(() -> tankInventory); forceFluidLevelUpdate = true; updateConnectivity = false; updateCapability = false; window = true; height = 1; width = 1; refreshCapability(); } protected FuelFluidHandler createInventory() { return new FuelFluidHandler(getCapacityMultiplier(), this::onFluidStackChanged); } protected void updateConnectivity() { updateConnectivity = false; if (level.isClientSide) return; if (!isController()) return; ConnectivityHandler.formMulti(this); } @Override public void tick() { super.tick(); if (syncCooldown > 0) { syncCooldown--; if (syncCooldown == 0 && queuedSync) sendData(); } if (lastKnownPos == null) lastKnownPos = getBlockPos(); else if (!lastKnownPos.equals(worldPosition) && worldPosition != null) { onPositionChanged(); return; } if (updateCapability) { updateCapability = false; refreshCapability(); } if (updateConnectivity) updateConnectivity(); if (fluidLevel != null) fluidLevel.tickChaser(); } @Override public BlockPos getLastKnownPos() { return lastKnownPos; } @Override public boolean isController() { return controller == null || worldPosition.getX() == controller.getX() && worldPosition.getY() == controller.getY() && worldPosition.getZ() == controller.getZ(); } @Override public void initialize() { super.initialize(); sendData(); if (level.isClientSide) invalidateRenderBoundingBox(); } private void onPositionChanged() { removeController(true); lastKnownPos = worldPosition; } protected void onFluidStackChanged(FluidStack newFluidStack) { if (!hasLevel()) return; FluidType attributes = newFluidStack.getFluid() .getFluidType(); int luminosity = (int) (attributes.getLightLevel(newFluidStack) / 1.2f); boolean reversed = attributes.isLighterThanAir(); int maxY = (int) ((getFillState() * height) + 1); for (int yOffset = 0; yOffset < height; yOffset++) { boolean isBright = reversed ? (height - yOffset <= maxY) : (yOffset < maxY); int actualLuminosity = isBright ? luminosity : luminosity > 0 ? 1 : 0; for (int xOffset = 0; xOffset < width; xOffset++) { for (int zOffset = 0; zOffset < width; zOffset++) { BlockPos pos = this.worldPosition.offset(xOffset, yOffset, zOffset); FuelTankBlockEntity tankAt = ConnectivityHandler.partAt(getType(), level, pos); if (tankAt == null) continue; level.updateNeighbourForOutputSignal(pos, tankAt.getBlockState() .getBlock()); if (tankAt.luminosity == actualLuminosity) continue; tankAt.setLuminosity(actualLuminosity); } } } if (!level.isClientSide) { setChanged(); sendData(); } if (isVirtual()) { if (fluidLevel == null) fluidLevel = LerpedFloat.linear() .startWithValue(getFillState()); fluidLevel.chase(getFillState(), .5f, LerpedFloat.Chaser.EXP); } } protected void setLuminosity(int luminosity) { if (level.isClientSide) return; if (this.luminosity == luminosity) return; this.luminosity = luminosity; sendData(); } @SuppressWarnings("unchecked") @Override public FuelTankBlockEntity getControllerBE() { if (isController()) return this; BlockEntity blockEntity = level.getBlockEntity(controller); if (blockEntity instanceof FuelTankBlockEntity) return (FuelTankBlockEntity) blockEntity; return null; } public void applyFluidTankSize(int blocks) { tankInventory.setCapacity(blocks * getCapacityMultiplier()); int overflow = tankInventory.getFluidAmount() - tankInventory.getCapacity(); if (overflow > 0) tankInventory.drain(overflow, IFluidHandler.FluidAction.EXECUTE); forceFluidLevelUpdate = true; } public void removeController(boolean keepFluids) { if (level.isClientSide) return; updateConnectivity = true; if (!keepFluids) applyFluidTankSize(1); controller = null; width = 1; height = 1; onFluidStackChanged(tankInventory.getFluid()); BlockState state = getBlockState(); if (FuelTankBlock.isTank(state)) { state = state.setValue(FuelTankBlock.BOTTOM, true); state = state.setValue(FuelTankBlock.TOP, true); state = state.setValue(FuelTankBlock.SHAPE, window ? FuelTankBlock.Shape.WINDOW : FuelTankBlock.Shape.PLAIN); getLevel().setBlock(worldPosition, state, 22); } refreshCapability(); setChanged(); sendData(); } public void toggleWindows() { FuelTankBlockEntity be = getControllerBE(); if (be == null) return; be.setWindows(!be.window); } public void sendDataImmediately() { syncCooldown = 0; queuedSync = false; sendData(); } @Override public void sendData() { if (syncCooldown > 0) { queuedSync = true; return; } super.sendData(); queuedSync = false; syncCooldown = SYNC_RATE; } public void setWindows(boolean window) { this.window = window; for (int yOffset = 0; yOffset < height; yOffset++) { for (int xOffset = 0; xOffset < width; xOffset++) { for (int zOffset = 0; zOffset < width; zOffset++) { BlockPos pos = this.worldPosition.offset(xOffset, yOffset, zOffset); BlockState blockState = level.getBlockState(pos); if (!FuelTankBlock.isTank(blockState)) continue; FuelTankBlock.Shape shape = FuelTankBlock.Shape.PLAIN; if (window) { // SIZE 1: Every tank has a window if (width == 1) shape = FuelTankBlock.Shape.WINDOW; // SIZE 2: Every tank has a corner window if (width == 2) shape = xOffset == 0 ? zOffset == 0 ? FuelTankBlock.Shape.WINDOW_NW : FuelTankBlock.Shape.WINDOW_SW : zOffset == 0 ? FuelTankBlock.Shape.WINDOW_NE : FuelTankBlock.Shape.WINDOW_SE; // SIZE 3: Tanks in the center have a window if (width == 3 && abs(abs(xOffset) - abs(zOffset)) == 1) shape = FuelTankBlock.Shape.WINDOW; } level.setBlock(pos, blockState.setValue(FuelTankBlock.SHAPE, shape), 22); level.getChunkSource() .getLightEngine() .checkBlock(pos); } } } } @Override public void setController(BlockPos controller) { if (level.isClientSide && !isVirtual()) return; if (controller.equals(this.controller)) return; this.controller = controller; refreshCapability(); setChanged(); sendData(); } private void refreshCapability() { LazyOptional<IFluidHandler> oldCap = fluidCapability; fluidCapability = LazyOptional.of(this::handlerForCapability); oldCap.invalidate(); } private IFluidHandler handlerForCapability() { return isController() ? tankInventory : getControllerBE() != null ? getControllerBE().handlerForCapability() : new FluidTank(0); } @Override public BlockPos getController() { return isController() ? worldPosition : controller; } @Override protected AABB createRenderBoundingBox() { if (isController()) return super.createRenderBoundingBox().expandTowards(width - 1, height - 1, width - 1); else return super.createRenderBoundingBox(); } @Override public boolean addToGoggleTooltip(List<Component> tooltip, boolean isPlayerSneaking) { FuelTankBlockEntity controllerBE = getControllerBE(); if (controllerBE == null) return false; return containedFluidTooltip(tooltip, isPlayerSneaking, controllerBE.getCapability(ForgeCapabilities.FLUID_HANDLER)); } @Override protected void read(CompoundTag compound, boolean clientPacket) { super.read(compound, clientPacket); BlockPos controllerBefore = controller; int prevSize = width; int prevHeight = height; int prevLum = luminosity; updateConnectivity = compound.contains("Uninitialized"); luminosity = compound.getInt("Luminosity"); controller = null; lastKnownPos = null; if (compound.contains("LastKnownPos")) lastKnownPos = NbtUtils.readBlockPos(compound.getCompound("LastKnownPos")); if (compound.contains("Controller")) controller = NbtUtils.readBlockPos(compound.getCompound("Controller")); if (isController()) { window = compound.getBoolean("Window"); width = compound.getInt("Size"); height = compound.getInt("Height"); tankInventory.setCapacity(getTotalTankSize() * getCapacityMultiplier()); tankInventory.readFromNBT(compound.getCompound("TankContent")); if (tankInventory.getSpace() < 0) tankInventory.drain(-tankInventory.getSpace(), IFluidHandler.FluidAction.EXECUTE); } if (compound.contains("ForceFluidLevel") || fluidLevel == null) fluidLevel = LerpedFloat.linear() .startWithValue(getFillState()); updateCapability = true; if (!clientPacket) return; boolean changeOfController = !Objects.equals(controllerBefore, controller); if (changeOfController || prevSize != width || prevHeight != height) { if (hasLevel()) level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), 16); if (isController()) tankInventory.setCapacity(getCapacityMultiplier() * getTotalTankSize()); invalidateRenderBoundingBox(); } if (isController()) { float fillState = getFillState(); if (compound.contains("ForceFluidLevel") || fluidLevel == null) fluidLevel = LerpedFloat.linear() .startWithValue(fillState); fluidLevel.chase(fillState, 0.5f, LerpedFloat.Chaser.EXP); } if (luminosity != prevLum && hasLevel()) level.getChunkSource() .getLightEngine() .checkBlock(worldPosition); if (compound.contains("LazySync")) fluidLevel.chase(fluidLevel.getChaseTarget(), 0.125f, LerpedFloat.Chaser.EXP); } public float getFillState() { return (float) tankInventory.getFluidAmount() / tankInventory.getCapacity(); } @Override public void write(CompoundTag compound, boolean clientPacket) { if (updateConnectivity) compound.putBoolean("Uninitialized", true); if (lastKnownPos != null) compound.put("LastKnownPos", NbtUtils.writeBlockPos(lastKnownPos)); if (!isController()) compound.put("Controller", NbtUtils.writeBlockPos(controller)); if (isController()) { compound.putBoolean("Window", window); compound.put("TankContent", tankInventory.writeToNBT(new CompoundTag())); compound.putInt("Size", width); compound.putInt("Height", height); } compound.putInt("Luminosity", luminosity); super.write(compound, clientPacket); if (!clientPacket) return; if (forceFluidLevelUpdate) compound.putBoolean("ForceFluidLevel", true); if (queuedSync) compound.putBoolean("LazySync", true); forceFluidLevelUpdate = false; } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { if (!fluidCapability.isPresent()) refreshCapability(); if (cap == ForgeCapabilities.FLUID_HANDLER) return fluidCapability.cast(); return super.getCapability(cap, side); } @Override public void invalidate() { super.invalidate(); } @Override public void addBehaviours(List<BlockEntityBehaviour> behaviours) { registerAwardables(behaviours, AllAdvancements.STEAM_ENGINE_MAXED, AllAdvancements.PIPE_ORGAN); } public IFluidTank getTankInventory() { return tankInventory; } public int getTotalTankSize() { return width * width * height; } public static int getMaxSize() { return MAX_SIZE; } public static int getCapacityMultiplier() { return AllConfigs.server().fluids.fluidTankCapacity.get() * 1000; } public static int getMaxHeight() { return AllConfigs.server().fluids.fluidTankMaxHeight.get(); } public LerpedFloat getFluidLevel() { return fluidLevel; } public void setFluidLevel(LerpedFloat fluidLevel) { this.fluidLevel = fluidLevel; } @Override public void preventConnectivityUpdate() { updateConnectivity = false; } @Override public void notifyMultiUpdated() { BlockState state = this.getBlockState(); if (FuelTankBlock.isTank(state)) { // safety state = state.setValue(FuelTankBlock.BOTTOM, getController().getY() == getBlockPos().getY()); state = state.setValue(FuelTankBlock.TOP, getController().getY() + height - 1 == getBlockPos().getY()); level.setBlock(getBlockPos(), state, 6); } if (isController()) setWindows(window); onFluidStackChanged(tankInventory.getFluid()); setChanged(); } @Override public void setExtraData(@Nullable Object data) { if (data instanceof Boolean) window = (boolean) data; } @Override @Nullable public Object getExtraData() { return window; } @Override public Object modifyExtraData(Object data) { if (data instanceof Boolean windows) { windows |= window; return windows; } return data; } @Override public Direction.Axis getMainConnectionAxis() { return Direction.Axis.Y; } @Override public int getMaxLength(Direction.Axis longAxis, int width) { if (longAxis == Direction.Axis.Y) return getMaxHeight(); return getMaxWidth(); } @Override public int getMaxWidth() { return MAX_SIZE; } @Override public int getHeight() { return height; } @Override public void setHeight(int height) { this.height = height; } @Override public int getWidth() { return width; } @Override public void setWidth(int width) { this.width = width; } @Override public boolean hasTank() { return true; } @Override public int getTankSize(int tank) { return getCapacityMultiplier(); } @Override public void setTankSize(int tank, int blocks) { applyFluidTankSize(blocks); } @Override public IFluidTank getTank(int tank) { return tankInventory; } @Override public FluidStack getFluid(int tank) { return tankInventory.getFluid().copy(); } public static class FuelFluidHandler extends SmartFluidTank { public FuelFluidHandler(int capacity, Consumer<FluidStack> updateCallback) { super(capacity, updateCallback); } public boolean isFluidValid(FluidStack stack) { return LiquidFuelTrainHandler.isFuel(stack.getFluid()); } @Override public int fill(FluidStack resource, FluidAction action) { if (!isFluidValid(resource)) return 0; return super.fill(resource, action); } } }
1
0.912486
1
0.912486
game-dev
MEDIA
0.979553
game-dev
0.959916
1
0.959916
Low-Drag-MC/Photon
2,680
src/main/java/com/lowdragmc/photon/client/gameobject/emitter/data/RotationOverLifetimeSetting.java
package com.lowdragmc.photon.client.gameobject.emitter.data; import com.lowdragmc.lowdraglib2.configurator.annotation.Configurable; import com.lowdragmc.photon.client.gameobject.emitter.data.number.Constant; import com.lowdragmc.photon.client.gameobject.emitter.data.number.NumberFunction; import com.lowdragmc.photon.client.gameobject.emitter.data.number.NumberFunctionConfig; import com.lowdragmc.photon.client.gameobject.emitter.data.number.RandomConstant; import com.lowdragmc.photon.client.gameobject.emitter.data.number.curve.Curve; import com.lowdragmc.photon.client.gameobject.emitter.data.number.curve.CurveConfig; import com.lowdragmc.photon.client.gameobject.emitter.data.number.curve.RandomCurve; import com.lowdragmc.photon.client.gameobject.particle.IParticle; import org.joml.Vector3f; import lombok.Getter; import lombok.Setter; import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.OnlyIn; import net.minecraft.util.Mth; /** * @author KilaBash * @date 2023/5/30 * @implNote RotationOverLifetimeSetting */ @OnlyIn(Dist.CLIENT) @Setter @Getter public class RotationOverLifetimeSetting extends ToggleGroup { @Configurable(name = "RotationBySpeedSetting.roll", tips = "photon.emitter.config.rotation.roll") @NumberFunctionConfig(types = {Constant.class, RandomConstant.class, Curve.class, RandomCurve.class}, wheelDur = 10, curveConfig = @CurveConfig(bound = {0, 360}, xAxis = "lifetime", yAxis = "roll")) protected NumberFunction roll = NumberFunction.constant(0); @Configurable(name = "RotationBySpeedSetting.pitch", tips = "photon.emitter.config.rotation.pitch") @NumberFunctionConfig(types = {Constant.class, RandomConstant.class, Curve.class, RandomCurve.class}, wheelDur = 10, curveConfig = @CurveConfig(bound = {0, 360}, xAxis = "lifetime", yAxis = "pitch")) protected NumberFunction pitch = NumberFunction.constant(0); @Configurable(name = "RotationBySpeedSetting.yaw", tips = "photon.emitter.config.rotation.yaw") @NumberFunctionConfig(types = {Constant.class, RandomConstant.class, Curve.class, RandomCurve.class}, wheelDur = 10, curveConfig = @CurveConfig(bound = {0, 360}, xAxis = "lifetime", yAxis = "yaw")) protected NumberFunction yaw = NumberFunction.constant(0); public Vector3f getRotation(IParticle particle, float partialTicks) { var t = particle.getT(partialTicks); return new Vector3f( yaw.get(t, () -> particle.getMemRandom("rol2")).floatValue(), pitch.get(t, () -> particle.getMemRandom("rol1")).floatValue(), roll.get(t, () -> particle.getMemRandom("rol0")).floatValue()).mul(Mth.TWO_PI / 360); } }
1
0.752277
1
0.752277
game-dev
MEDIA
0.712859
game-dev
0.915317
1
0.915317
MrFast-js/Skyblock-Tweaks
4,452
src/main/java/mrfast/sbt/features/dungeons/FireFreezeHelper.kt
package mrfast.sbt.features.dungeons import mrfast.sbt.SkyblockTweaks import mrfast.sbt.managers.GuiManager import mrfast.sbt.config.categories.DungeonConfig import mrfast.sbt.config.categories.GeneralConfig import mrfast.sbt.managers.FontManager import mrfast.sbt.utils.GuiUtils import mrfast.sbt.managers.LocationManager import mrfast.sbt.managers.TickManager import mrfast.sbt.utils.ItemUtils.getSkyblockId import mrfast.sbt.utils.Utils import net.minecraft.client.renderer.GlStateManager import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.event.world.WorldEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.TickEvent // Shows when to use fire freeze on F2,F3,M2,M3 in order to freeze boss perfectly @SkyblockTweaks.EventComponent object FireFreezeHelper { private const val textScale = 2.0 private val triggersAndTimings = mapOf( "[BOSS] The Professor: Oh? You found my Guardians' one weakness?" to 8, // Floor 3 "[BOSS] Scarf: Those toys are not strong enough I see." to 9 // Floor 2 ) private var shouldFireFreeze = false private var currentDisplayText = "" private var playerHasFireFreeze = false @SubscribeEvent fun onTick(event: TickEvent.ClientTickEvent) { if (!LocationManager.inDungeons || !DungeonConfig.fireFreezeTimer || event.phase != TickEvent.Phase.START) return if (TickManager.tickCount % 20 != 0) return if (!Utils.isWorldLoaded()) return var foundFireFreeze = false Utils.getPlayer()!!.inventoryContainer.inventoryItemStacks.forEach { itemStack -> if (itemStack != null && itemStack.getSkyblockId() == "FIRE_FREEZE_STAFF") { foundFireFreeze = true } } playerHasFireFreeze = foundFireFreeze } @SubscribeEvent(receiveCanceled = true) fun onChatMessage(event: ClientChatReceivedEvent) { if (!LocationManager.inDungeons || event.type.toInt() == 2 || !DungeonConfig.fireFreezeTimer) return val text = event.message.unformattedText if (triggersAndTimings.contains(text)) { val time = triggersAndTimings[text] ?: -1 for (i in 1..time) { val threshold = time - 2 val count = if (i >= threshold) "§aFire Freeze Now!" else "§cFire Freeze in " + (threshold - i) + " seconds" Utils.setTimeout({ currentDisplayText = count if (i == threshold) shouldFireFreeze = true if (i == time) currentDisplayText = "" }, (i * 880).toLong()) } } } @SubscribeEvent fun onLoad(event: WorldEvent.Load?) { currentDisplayText = "" shouldFireFreeze = false } init { FireFreezeTimer() } class FireFreezeTimer : GuiManager.Element() { init { this.relativeX = 0.373 this.relativeY = 0.522 this.elementName = "Fire Freeze Timer" this.needsExample = true this.height = FontManager.getFontRenderer().FONT_HEIGHT * 2 + 2 this.width = FontManager.getFontRenderer().getStringWidth("Fire Freeze in 5 seconds!") * 2 + 2 this.addToList() } override fun draw() { GlStateManager.scale(textScale, textScale, 1.0) val centerX = this.width / 4f GuiUtils.drawText( currentDisplayText, centerX, 0f, GuiUtils.TextStyle.DROP_SHADOW, GeneralConfig.effectiveHealthNumberColor.get(), centered = true ) GlStateManager.scale(1 / textScale, 1 / textScale, 1.0) } override fun drawExample() { GlStateManager.scale(textScale, textScale, 1.0) val centerX = this.width / 4f GuiUtils.drawText( "§cFire Freeze in 5 seconds!", centerX, 0f, GuiUtils.TextStyle.DROP_SHADOW, GeneralConfig.effectiveHealthNumberColor.get(), centered = true ) GlStateManager.scale(1 / textScale, 1 / textScale, 1.0) } override fun isActive(): Boolean { return DungeonConfig.fireFreezeTimer } override fun isVisible(): Boolean { return playerHasFireFreeze && currentDisplayText.isNotEmpty() } } }
1
0.906815
1
0.906815
game-dev
MEDIA
0.959381
game-dev
0.963132
1
0.963132
wy19910222/Unity-ControlSystem
2,253
Assets/Tools/ControlSystem/Scripts/Executor/ExecutorProcessBase/Editor/BaseProcessStepDrawer_Playable.cs
/* * @Author: wangyun * @CreateTime: 2022-12-15 12:39:59 659 * @LastEditor: wangyun * @EditTime: 2023-03-04 17:17:46 389 */ using UnityEngine; using UnityEngine.Playables; using UnityEditor; namespace Control { public partial class BaseProcessStepDrawer<TStep> { private void DrawPlayableCtrl() { PlayableDirector newObj = DrawCompFieldWithThisBtn<PlayableDirector>("导演", Target.obj); if (newObj != Target.obj) { Property.RecordForUndo("Obj"); Target.obj = newObj; } if (newObj != null) { int newCtrlType = EditorGUILayout.IntPopup( "操作", Target.iArguments[0], new [] { "播放", "停止", "暂停", "继续", "暂停或继续" }, new [] { 0, 1, 2, 3, 4 } ); if (newCtrlType != Target.iArguments[0]) { Property.RecordForUndo("IArguments"); Target.iArguments[0] = newCtrlType; } } } private void DrawPlayableGoto() { PlayableDirector newObj = DrawCompFieldWithThisBtn<PlayableDirector>("导演", Target.obj); if (newObj != Target.obj) { Property.RecordForUndo("Obj"); Target.obj = newObj; } if (newObj != null) { EditorGUILayout.BeginHorizontal(); float newTime = Target.bArguments[0] ? EditorGUILayout.Slider("进度", Target.fArguments[0], 0, 1) : Mathf.Max(EditorGUILayout.FloatField("进度", Target.fArguments[0]), 0); if (!Mathf.Approximately(newTime, Target.fArguments[0])) { Property.RecordForUndo("FArguments"); Target.fArguments[0] = newTime; } bool newIsPercent = DrawToggle(Target.bArguments[0], "%", BTN_WIDTH_OPTION); if (newIsPercent != Target.bArguments[0]) { Property.RecordForUndo("BArguments"); Target.bArguments[0] = newIsPercent; } GUILayoutOption width = GUILayout.Width(s_ContextWidth * 0.3F - 80F - 3F); EditorGUILayout.LabelField("", width); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("刷新", CustomEditorGUI.LabelWidthOption); bool newEvaluate = DrawToggle(Target.bArguments[1], Target.bArguments[1] ? "√" : "X", BTN_WIDTH_OPTION); if (newEvaluate != Target.bArguments[1]) { Property.RecordForUndo("BArguments"); Target.bArguments[1] = newEvaluate; } EditorGUILayout.EndHorizontal(); } } } }
1
0.914568
1
0.914568
game-dev
MEDIA
0.613693
game-dev,desktop-app
0.967452
1
0.967452
blendogames/thirtyflightsofloving
8,365
game/g_model.c
/* =========================================================================== Copyright (C) 1997-2001 Id Software, Inc. Copyright (C) 2000-2002 Mr. Hyde and Mad Dog This file is part of Lazarus Quake 2 Mod source code. Lazarus Quake 2 Mod 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 2 of the License, or (at your option) any later version. Lazarus Quake 2 Mod 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 Lazarus Quake 2 Mod source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #include "g_local.h" // // mappack stuff by mr. ed, modified extensively for Tremor by dwh // // Spawns a user defined model, you can specify whether its solid, if so how big the box is, and apply nearly // any effect to the entity. // // PLAYER set this if you want to use a player model // // Note : These flags override any frame settings you may have enterered // ANIM01 cycle between frames 0 and 1 at 2 hz // ANIM23 cycle between frames 2 and 3 at 2 hz // ANIM_ALL cycle through all frames at 2hz // ANIM_ALLFAST cycle through all frames at 10hz // // START_OFF Start inactive, when triggered display the model // TOGGLE Start active, when triggered become inactive // NO_MODEL Don't use a model. Usefull for placeing particle effects and // dynamic lights on their own // // "delay" = Combine with TOGGLE spawnflag to start off // "usermodel" = The model to load (models/ is already coded) // "startframe" = The starting frame : default 0 // "userframes" = The number of frames you want to display after startframe // "solidstate" = 1 : SOLID_NOT - not solid at all // 2 : SOLID_BBOX - solid and affected by gravity // 3 : NO DROP - solid but not affected by gravity // 4 : SOLID_NOT, but affect by gravity // // NOTE : if you want the model to be solid then you must enter vector values into the following fields : // "bleft" = the point that is at the bottom left of the models bounding box in a model editor // "tright" = the point that is at the top left of the models bounding box in a model editor // #define TOGGLE 2 #define PLAYER_MODEL 8 #define NO_MODEL 16 #define ANIM_ONCE 32 void model_spawn_use (edict_t *self, edict_t *other, edict_t *activator); void modelspawn_think (edict_t *self) { self->s.frame++; if (self->s.frame >= self->framenumbers) { self->s.frame = self->startframe; if (self->spawnflags & ANIM_ONCE) { model_spawn_use (self, world, world); return; } } self->nextthink = level.time + FRAMETIME; gi.linkentity(self); } void model_spawn_use (edict_t *self, edict_t *other, edict_t *activator) { if (self->delay) // we started off { self->svflags &= ~SVF_NOCLIENT; self->delay = 0; if (self->framenumbers > 1) { self->think = modelspawn_think; self->nextthink = level.time + FRAMETIME; } self->s.sound = self->noise_index; #ifdef LOOP_SOUND_ATTENUATION self->s.attenuation = self->attenuation; #endif } else // we started active { self->svflags |= SVF_NOCLIENT; self->delay = 1; self->use = model_spawn_use; self->think = NULL; self->nextthink = 0; self->s.sound = 0; } } void model_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point) { edict_t *e, *next; e = self->movewith_next; while (e) { next = e->movewith_next; if (e->solid == SOLID_NOT) { e->nextthink = 0; G_FreeEdict(e); } else BecomeExplosion1 (e); e = next; } BecomeExplosion1(self); } #define ANIM_MASK (EF_ANIM01|EF_ANIM23|EF_ANIM_ALL|EF_ANIM_ALLFAST) void SP_model_spawn (edict_t *ent) { char modelname[256]; // paranoia checks if ((!ent->usermodel) && !(ent->spawnflags & NO_MODEL) && !(ent->spawnflags & PLAYER_MODEL)) { gi.dprintf("%s without a model at %s\n", ent->classname, vtos(ent->s.origin)); G_FreeEdict(ent); return; } ent->class_id = ENTITY_MODEL_SPAWN; switch (ent->solidstate) { case 1 : ent->solid = SOLID_NOT; ent->movetype = MOVETYPE_NONE; break; case 2 : ent->solid = SOLID_BBOX; ent->movetype = MOVETYPE_TOSS; break; case 3 : ent->solid = SOLID_BBOX; ent->movetype = MOVETYPE_NONE; break; case 4 : ent->solid = SOLID_NOT; ent->movetype = MOVETYPE_TOSS; break; default: ent->solid = SOLID_NOT; ent->movetype = MOVETYPE_NONE; break; } if (ent->solid != SOLID_NOT ) { if (ent->health > 0) { ent->die = model_die; ent->takedamage = DAMAGE_YES; } } switch (ent->style) { case 1 : ent->s.effects |= EF_ANIM01; break; case 2 : ent->s.effects |= EF_ANIM23; break; case 3 : ent->s.effects |= EF_ANIM_ALL; break; case 4 : ent->s.effects |= EF_ANIM_ALLFAST; break; } // DWH: Rather than use one value (renderfx) we use the // actual values for effects and renderfx. All may // be combined. ent->s.effects |= ent->effects; ent->s.renderfx |= ent->renderfx; if (ent->startframe < 0) ent->startframe = 0; if (!ent->framenumbers) ent->framenumbers = 1; // Change framenumbers to last frame to play ent->framenumbers += ent->startframe; if (ent->bleft) { VectorCopy (ent->bleft, ent->mins); } else { if (ent->solid != SOLID_NOT) { gi.dprintf("%s solid with no bleft vector at %s\n", ent->classname, vtos(ent->s.origin)); ent->solid = SOLID_NOT; } } if (ent->tright) { VectorCopy (ent->tright, ent->maxs); } else { if (ent->solid != SOLID_NOT) { gi.dprintf("%s solid with no tright vector at %s\n", ent->classname, vtos(ent->s.origin)); ent->solid = SOLID_NOT; } } // if (ent->movewith && (ent->solid == SOLID_BBOX)) if (ent->movewith) ent->movetype = MOVETYPE_PUSH; if (ent->solid != SOLID_NOT) ent->clipmask = CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER; if (ent->spawnflags & NO_MODEL) { // For rendering effects to work, we MUST use a model ent->s.modelindex = gi.modelindex ("sprites/point.sp2"); ent->movetype = MOVETYPE_NOCLIP; } else { if (ent->spawnflags & PLAYER_MODEL) { if (!ent->usermodel || !strlen(ent->usermodel)) ent->s.modelindex = MAX_MODELS-1; else { if (strstr(ent->usermodel,"tris.md2")) Com_sprintf (modelname, sizeof(modelname), "players/%s", ent->usermodel); else Com_sprintf (modelname, sizeof(modelname), "players/%s/tris.md2", ent->usermodel); ent->s.modelindex = gi.modelindex(modelname); } } else { if (strstr(ent->usermodel,".sp2")) { // Knightmare- check for "sprites/" already in path if ( !strncmp(ent->usermodel, "sprites/", 8) ) Com_sprintf (modelname, sizeof(modelname), "%s", ent->usermodel); else Com_sprintf (modelname, sizeof(modelname), "sprites/%s", ent->usermodel); } else { // Knightmare- check for "models/" already in path if ( !strncmp(ent->usermodel, "models/", 7) ) Com_sprintf (modelname, sizeof(modelname), "%s", ent->usermodel); else Com_sprintf (modelname, sizeof(modelname), "models/%s", ent->usermodel); } ent->s.modelindex = gi.modelindex (modelname); } ent->s.frame = ent->startframe; } if (st.noise) ent->noise_index = gi.soundindex (st.noise); ent->s.sound = ent->noise_index; #ifdef LOOP_SOUND_ATTENUATION ent->s.attenuation = ent->attenuation; #endif if (ent->skinnum) // Knightmare- selectable skin ent->s.skinnum = ent->skinnum; if (ent->spawnflags & ANIM_ONCE) { ent->spawnflags |= TOGGLE; } if (ent->spawnflags & TOGGLE) { // Knightmare- allow starting off (but not for model_train) if ( (strcmp(ent->classname, "model_train") != 0) && (ent->delay != 0) ) { ent->delay = 1; ent->svflags |= SVF_NOCLIENT; } else { ent->delay = 0; } ent->use = model_spawn_use; } if ( !(ent->s.effects & ANIM_MASK) && (ent->framenumbers > 1) ) { ent->think = modelspawn_think; ent->nextthink = level.time + 2*FRAMETIME; } gi.linkentity (ent); }
1
0.788501
1
0.788501
game-dev
MEDIA
0.870496
game-dev
0.949851
1
0.949851
gawric/Unity-Client-for-L2J
3,826
l2-unity/Assets/Scripts/Camera/CameraCollisionDetection.cs
using UnityEngine; [System.Serializable] public class CameraCollisionDetection { [SerializeField] private LayerMask _collisionLayer; [SerializeField] private float _adjustedDistance; [SerializeField] private Transform _collisionObject; [SerializeField] private Vector2 _clipPlaneOffset = new Vector2(2f, 1f); [SerializeField] private bool _debug = false; private Camera _camera; private Transform _target; private Vector3 _offset; public float AdjustedDistance { get { return _adjustedDistance; } } public CameraCollisionDetection(Camera camera, Transform target, Vector3 cameraOffset, LayerMask collisionmask) { this._camera = camera; this._target = target; _offset = cameraOffset; _collisionLayer = collisionmask; } /* Calculate our near clip points */ public Vector3[] GetCameraClipPoints(float distance) { Vector3[] cameraClipPoints = new Vector3[5]; Quaternion camRot = _camera.transform.rotation; Vector3 desiredPos = camRot * (Vector3.forward * -distance) + _target.position + _offset; float z = _camera.nearClipPlane; float x = Mathf.Tan(_camera.fieldOfView / _clipPlaneOffset.x) * z; float y = x / _camera.aspect / _clipPlaneOffset.y; //top left cameraClipPoints[0] = (camRot * new Vector3(-x, y, z)) + desiredPos; //top right cameraClipPoints[1] = (camRot * new Vector3(x, y, z)) + desiredPos; //bottom left cameraClipPoints[2] = (camRot * new Vector3(-x, -y, z)) + desiredPos; //bottom right cameraClipPoints[3] = (camRot * new Vector3(x, -y, z)) + desiredPos; //camera position cameraClipPoints[4] = desiredPos - (_camera.transform.forward * 0.25f); return cameraClipPoints; } public Vector3[] GetCameraViewPortPoints() { Vector3[] cameraClipPoints = new Vector3[5]; Quaternion camRot = _camera.transform.rotation; Vector3 camPos = _camera.transform.position; float z = _camera.nearClipPlane; float x = Mathf.Tan(_camera.fieldOfView) * z; float y = x / _camera.aspect / _clipPlaneOffset.y; //top left cameraClipPoints[0] = (camRot * new Vector3(-x, y, z)) + camPos; //top right cameraClipPoints[1] = (camRot * new Vector3(x, y, z)) + camPos; //bottom left cameraClipPoints[2] = (camRot * new Vector3(-x, -y, z)) + camPos; //bottom right cameraClipPoints[3] = (camRot * new Vector3(x, -y, z)) + camPos; //camera position cameraClipPoints[4] = camPos - (_camera.transform.forward * 0.25f); return cameraClipPoints; } /* Cast a ray from the target to each clip points */ public void DetectCollision(float desiredDistance) { if(_camera == null) { return; } Vector3[] clipPoints = GetCameraClipPoints(desiredDistance); Vector3[] viewPoints = GetCameraViewPortPoints(); _adjustedDistance = desiredDistance; float distance = -1f; Transform hitObject = null; RaycastHit hit; for(int i = 0; i < clipPoints.Length; i++) { if(Physics.Linecast(_target.position + _offset, clipPoints[i], out hit, _collisionLayer)) { if(distance == -1f || hit.distance < distance) { distance = hit.distance; } hitObject = hit.transform; } if(_debug) { Debug.DrawLine(clipPoints[i], _target.position, Color.green); Debug.DrawLine(viewPoints[i], _target.position, Color.yellow); } } if(distance != -1f) { _adjustedDistance = distance; } _collisionObject = hitObject; } }
1
0.843796
1
0.843796
game-dev
MEDIA
0.577231
game-dev,graphics-rendering
0.956833
1
0.956833
darklordabc/Legends-of-Dota-Redux
2,615
src/game/scripts/vscripts/abilities/overflow/channel_earthquake/ability.lua
if channel_earthquake == nil then channel_earthquake = class({}) end LinkLuaModifier( "generic_lua_stun", "abilities/overflow/generic_stun.lua", LUA_MODIFIER_MOTION_NONE ) function channel_earthquake:OnSpellStart() self.point = self:GetCursorPosition() local randPos = RandomVector(RandomInt(0, self:GetSpecialValueFor("radius"))) + self.point self:Explosion(randPos) self.start_time = GameRules:GetGameTime() self.cc_interval = self:GetSpecialValueFor("think_interval") self.cc_timer = 0 end function channel_earthquake:GetAOERadius() return self:GetSpecialValueFor("radius") end function channel_earthquake:GetBehavior() local behav = DOTA_ABILITY_BEHAVIOR_POINT + DOTA_ABILITY_BEHAVIOR_CHANNELLED + DOTA_ABILITY_BEHAVIOR_AOE return behav end function channel_earthquake:OnChannelThink(flInterval) self.cc_timer = self.cc_timer + flInterval if self.cc_timer >= self.cc_interval then self.cc_timer = self.cc_timer - self.cc_interval self:CustomChannelThink() end end function channel_earthquake:CustomChannelThink() local randPos = RandomVector(RandomInt(9, self:GetSpecialValueFor("radius"))) + self.point self:Explosion(randPos) end function channel_earthquake:OnChannelFinish( bInterrupted ) self.point = nil end function channel_earthquake:Explosion(vPos) local hCaster = self:GetCaster() local particleName = "particles/units/heroes/hero_earth_spirit/espirit_spawn.vpcf" local stun_dur = self:GetSpecialValueFor("stun_duration") local aoe = self:GetSpecialValueFor("spot_radius") --silly field of view AddFOWViewer(hCaster:GetTeamNumber(), vPos, aoe, stun_dur, false) local expl = ParticleManager:CreateParticle( particleName, PATTACH_WORLDORIGIN, hCaster ) ParticleManager:SetParticleControl( expl, 0, vPos ) ParticleManager:SetParticleControl( expl, 1, vPos ) EmitSoundOnLocationWithCaster(self.point, "Hero_EarthShaker.Gravelmaw.Cast", hCaster ) local damage = { attacker = self:GetCaster(), damage = self:GetSpecialValueFor("damage"), damage_type = self:GetAbilityDamageType(), ability = self } local enemies = FindUnitsInRadius( hCaster:GetTeamNumber(), vPos, nil, aoe, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false ) if #enemies > 0 then for _,enemy in pairs(enemies) do if enemy ~= nil and ( not enemy:IsMagicImmune() ) and ( not enemy:IsInvulnerable() ) then enemy:AddNewModifier( self:GetCaster(), self, "generic_lua_stun", { duration = stun_dur , stacking = 1 } ) damage.victim = enemy ApplyDamage( damage ) end end end end
1
0.955772
1
0.955772
game-dev
MEDIA
0.974684
game-dev
0.94184
1
0.94184
lzk228/space-axolotl-14
1,572
Content.Client/AlertLevel/AlertLevelDisplaySystem.cs
using System.Linq; using Content.Shared.AlertLevel; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Shared.Utility; namespace Content.Client.AlertLevel; public sealed class AlertLevelDisplaySystem : EntitySystem { [Dependency] private readonly SpriteSystem _sprite = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<AlertLevelDisplayComponent, AppearanceChangeEvent>(OnAppearanceChange); } private void OnAppearanceChange(EntityUid uid, AlertLevelDisplayComponent alertLevelDisplay, ref AppearanceChangeEvent args) { if (args.Sprite == null) { return; } var layer = _sprite.LayerMapReserve((uid, args.Sprite), AlertLevelDisplay.Layer); if (args.AppearanceData.TryGetValue(AlertLevelDisplay.Powered, out var poweredObject)) { _sprite.LayerSetVisible((uid, args.Sprite), layer, poweredObject is true); } if (!args.AppearanceData.TryGetValue(AlertLevelDisplay.CurrentLevel, out var level)) { _sprite.LayerSetRsiState((uid, args.Sprite), layer, alertLevelDisplay.AlertVisuals.Values.First()); return; } if (alertLevelDisplay.AlertVisuals.TryGetValue((string)level, out var visual)) { _sprite.LayerSetRsiState((uid, args.Sprite), layer, visual); } else { _sprite.LayerSetRsiState((uid, args.Sprite), layer, alertLevelDisplay.AlertVisuals.Values.First()); } } }
1
0.936433
1
0.936433
game-dev
MEDIA
0.9158
game-dev
0.956578
1
0.956578
BAAI-Agents/Cradle
19,943
cradle/environment/skill_registry.py
"""Base class for Skill Registry.""" import os import inspect import base64 import re import ast import time from copy import deepcopy from typing import Type, AnyStr, List, Any, Dict, Tuple import numpy as np from cradle import constants from cradle.config import Config from cradle.log import Logger from cradle.utils.json_utils import load_json, save_json from cradle.utils.dict_utils import kget from cradle.environment.skill import Skill from cradle.environment.utils import serialize_skills, deserialize_skills from cradle.utils.check import is_valid_value from cradle.gameio.io_env import IOEnvironment from cradle.constants import * config = Config() logger = Logger() io_env = IOEnvironment() SKILLS = {} def register_skill(name): def decorator(skill): skill_name = name skill_function = skill skill_code = inspect.getsource(skill) # Remove unnecessary annotation in skill library if f"@register_skill(\"{name}\")\n" in skill_code: skill_code = skill_code.replace(f"@register_skill(\"{name}\")\n", "") skill_code_base64 = base64.b64encode(skill_code.encode('utf-8')).decode('utf-8') skill_ins = Skill(skill_name, skill_function, None, # skill_embedding skill_code, skill_code_base64) SKILLS[skill_name] = skill_ins return skill_ins return decorator class SkillRegistry(): """Base class for Skill Registry.""" def __init__(self, *args, skill_configs: dict[str, Any] = config.skill_configs, embedding_provider = None, **kwargs): super(SkillRegistry, self).__init__() self.skill_from_default = skill_configs[constants.SKILL_CONFIG_FROM_DEFAULT] self.skill_mode = skill_configs[constants.SKILL_CONFIG_MODE] self.skill_names_basic = skill_configs[constants.SKILL_CONFIG_NAMES_BASIC] self.skill_names_allow = skill_configs[constants.SKILL_CONFIG_NAMES_ALLOW] self.skill_names_deny = skill_configs[constants.SKILL_CONFIG_NAMES_DENY] skill_names_others = kget(skill_configs, constants.SKILL_CONFIG_NAMES_OTHERS, default=dict()) self.skill_names_movement = kget(skill_names_others, constants.SKILL_CONFIG_NAMES_MOVEMENT, default=[]) self.skill_names_map = kget(skill_names_others, constants.SKILL_CONFIG_NAMES_MAP, default=[]) self.skill_names_trade = kget(skill_names_others, constants.SKILL_CONFIG_NAMES_TRADE, default=[]) self.recent_skills = [] if skill_configs[constants.SKILL_CONFIG_REGISTERED_SKILLS] is not None: self.skill_registered = skill_configs[constants.SKILL_CONFIG_REGISTERED_SKILLS] else: self.skill_registered = SKILLS if self.skill_mode == constants.SKILL_LIB_MODE_BASIC: self.skill_library_filename = constants.SKILL_BASIC_LIB_FILE elif self.skill_mode == constants.SKILL_LIB_MODE_FULL: self.skill_library_filename = constants.SKILL_FULL_LIB_FILE else: self.skill_from_default = True self.embedding_provider = embedding_provider self.skills = {} os.makedirs(config.skill_local_path, exist_ok=True) if self.skill_from_default and os.path.exists(os.path.join(config.skill_local_path, self.skill_library_filename)): self.skills = self.load_skills_from_file(os.path.join(config.skill_local_path, self.skill_library_filename)) else: self.skills = self.load_skills_from_scripts() self.skills = self.filter_skills(self.skills) def set_embedding_provider(self, embedding_provider): self.embedding_provider = embedding_provider def get_embedding(self, skill_name, skill_doc): return np.array(self.embedding_provider.embed_query('{}: {}'.format(skill_name, skill_doc))) def load_skills_from_file(self, file_path) -> Dict[str, Skill]: logger.write(f"Loading skills from {file_path}") skill_local = load_json(file_path) skill_local = deserialize_skills(skill_local) skills = {} for skill_name in skill_local.keys(): skill_embedding = skill_local[skill_name].skill_embedding skill_code_base64 = base64.b64encode(skill_local[skill_name].skill_code.encode('utf-8')).decode('utf-8') regenerate_flag = False if skill_code_base64 != skill_local[skill_name].skill_code_base64: # The skill_code is modified regenerate_flag = True if not is_valid_value(skill_embedding): # The skill_embedding is invalid regenerate_flag = True if skill_name not in self.skill_registered.keys(): # The skill is not in the skill registry regenerate_flag = True if not regenerate_flag: logger.debug(f"No need to regenerate skill {skill_name}") skills[skill_name] = Skill(skill_name, self.skill_registered[skill_name].skill_function, skill_local[skill_name].skill_embedding, skill_local[skill_name].skill_code, skill_code_base64) else: # skill_code has been modified, we should recompute embedding logger.write(f"Regenerate skill {skill_name}") self.register_skill_from_code(skill_local[skill_name].skill_code) self.store_skills_to_file(file_path, skills) return skills def load_skills_from_scripts(self) -> Dict[str, Skill]: logger.write("Loading skills from scripts") skills = {} for skill_name in self.skill_registered.keys(): skill_embedding = self.skill_registered[skill_name].skill_embedding skill_code_base64 = base64.b64encode(self.skill_registered[skill_name].skill_code.encode('utf-8')).decode('utf-8') regenerate_flag = False if skill_code_base64 != self.skill_registered[skill_name].skill_code_base64: # The skill_code is modified regenerate_flag = True if not is_valid_value(skill_embedding): # The skill_embedding is invalid regenerate_flag = True if not regenerate_flag: logger.debug(f"No need to regenerate skill {skill_name}") skills[skill_name] = Skill(skill_name, self.skill_registered[skill_name].skill_function, self.skill_registered[skill_name].skill_embedding, self.skill_registered[skill_name].skill_code, skill_code_base64) else: # skill_code has been modified, we should recompute embedding logger.write(f"Regenerate skill {skill_name}") skills[skill_name] = Skill(skill_name, self.skill_registered[skill_name].skill_function, self.get_embedding(skill_name, inspect.getdoc(self.skill_registered[skill_name].skill_function)), self.skill_registered[skill_name].skill_code, skill_code_base64) self.store_skills_to_file(os.path.join(config.skill_local_path, self.skill_library_filename), skills) return skills def filter_skills(self, skills) -> Dict[str, Skill]: filtered_skills = {} if self.skill_mode == constants.SKILL_LIB_MODE_BASIC: for skill_name in self.skills: if skill_name in self.skill_names_basic: filtered_skills[skill_name] = self.skills[skill_name] elif self.skill_mode == constants.SKILL_LIB_MODE_FULL: filtered_skills = deepcopy(skills) else: filtered_skills = deepcopy(skills) return filtered_skills def convert_expression_to_skill(self, expression: str = "open_map()"): try: parsed = ast.parse(expression, mode='eval') if isinstance(parsed.body, ast.Call): skill_name, skill_params = self.extract_function_info(expression) return skill_name, skill_params elif isinstance(parsed.body, ast.List): skills_list = [] for call in parsed.body.elts: if isinstance(call, ast.Call): call_str = ast.unparse(call).strip() skill_name, skill_params = self.extract_function_info(call_str) skills_list.append((skill_name, skill_params)) else: raise ValueError("Input must be a list of function calls") return skills_list else: raise ValueError("Input must be a function call or a list of function calls") except SyntaxError as e: raise ValueError(f"Error parsing input: {e}") def extract_function_info(self, input_string: str = "open_map()"): pattern = re.compile(r'(\w+)\((.*?)\)') match = pattern.match(input_string) if match: function_name = match.group(1) raw_arguments = match.group(2) # To avoid simple errors based on faulty model output if raw_arguments is not None and len(raw_arguments) > 0: raw_arguments = raw_arguments.replace("=false", "=False").replace("=true", "=True") try: parsed_arguments = ast.parse(f"fake_func({raw_arguments})", mode='eval') except SyntaxError: raise ValueError("Invalid function call/arg format to parse.") arguments = {} for node in ast.walk(parsed_arguments): if isinstance(node, ast.keyword): arguments[node.arg] = ast.literal_eval(node.value) if len(raw_arguments) > 0 and len(arguments.keys()) == 0: raise ValueError("Call arguments not properly parsed!") return function_name, arguments else: raise ValueError("Invalid function call format string.") def convert_code_to_skill_info(self, skill_code: str): tree = ast.parse(skill_code) function_name = None arguments = {} # TODO: This is a very naive way to get the function name. We should improve this. for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): function_name = node.name return function_name, arguments def get_from_skill_library(self, skill_name: str, skill_library_with_code: bool = False) -> Dict: skill = self.skills[skill_name] skill_function = skill.skill_function docstring = inspect.getdoc(skill_function) skill_code = "" for item in self.skills: if item == skill_name: skill_code = self.skills[item].skill_code break if docstring: params = inspect.signature(skill_function).parameters if len(params) > 0: param_descriptions = {} for param in params.values(): name = param.name param_description = re.search(rf"- {name}: (.+).", docstring).group(1) param_descriptions[name] = param_description res = { "function_expression": f"{skill_name}({', '.join(params.keys())})", "description": docstring, "parameters": param_descriptions, } else: res = { "function_expression": f"{skill_name}()", "description": docstring, "parameters": {}, } else: res = None if skill_library_with_code and res is not None: res["code"] = skill_code return res def get_skill_code(self, skill: Any) -> Tuple[str, str]: info = None try: skill_name, _ = self.extract_function_info(skill) except: skill_name = skill skill_code = None for item in self.skills: if item == skill_name: skill_code = self.skills[item].skill_code break if skill_code is None: info = f"Skill '{skill_name}' not found in the registry." return skill_code, info def execute_skill(self, skill_name: str = "open_map", skill_params: Dict = None): try: if skill_name in self.skills: skill_function = self.skills[skill_name].skill_function skill_response = skill_function(**skill_params) else: raise ValueError(f"Function '{skill_name}' not found in the skill library.") except Exception as e: logger.error(f"Error executing skill {skill_name}: {e}") raise e return skill_response def execute_nop_skill(self): time.sleep(2) def register_skill_from_code(self, skill_code: str, overwrite = False) -> Tuple[bool, str]: """Register the skill function from the code string. Args: skill_code: the code of skill. overwrite: the flag indicates whether to overwrite the skill with the same name or not. Returns: bool: the true value means that there is no problem in the skill_code. The false value means that we may need to re-generate it. str: the detailed information about the bool. """ def lower_func_name(skill_code): skill_name, _ = self.convert_code_to_skill_info(skill_code) replaced_name = skill_name.lower() # To make sure the skills in .py files will not be overwritten. # The skills not in .py files can still be overwritten. if replaced_name in self.skills.keys(): replaced_name = replaced_name+'_generated' return skill_code.replace(skill_name, replaced_name) def check_param_description(skill) -> bool: docstring = inspect.getdoc(skill) if docstring: params = inspect.signature(skill).parameters if len(params) > 0: for param in params.values(): if not re.search(rf"- {param.name}: (.+).", docstring): return False return True else: return True else: return True def check_protection_conflict(skill): for word in self.skill_names_allow: if word in skill: return True for word in self.skill_names_deny: if word in skill: return False return True info = None if skill_code.count('(') < 2: info = "Skill code contains no functionality." logger.error(info) return True, info skill_code = lower_func_name(skill_code) skill_name, _ = self.convert_code_to_skill_info(skill_code) # Always avoid adding skills that are ambiguous with existing pre-defined ones. if check_protection_conflict(skill_name) == False: info = f"Skill '{skill_name}' conflicts with protected skills." for word in self.skill_names_deny: if word in skill_name: for protected_skill in self.skill_names_basic: if word in protected_skill: self.recent_skills.append(protected_skill) logger.write(info) return True, info if overwrite: if skill_name in self.skills: self.delete_skill(skill_name) logger.write(f"Skill '{skill_name}' will be overwritten.") if skill_name in self.skills: info = f"Skill '{skill_name}' already exists." logger.write(info) return True, info try: exec(skill_code) skill = eval(skill_name) except: info = "The skill code is invalid." logger.error(info) return False, info if check_param_description(skill) == False: info = "The format of parameter description is wrong." logger.error(info) return False, info skill_code_base64 = base64.b64encode(skill_code.encode('utf-8')).decode('utf-8') skill_ins = Skill(skill_name, skill, self.get_embedding(skill_name, inspect.getdoc(skill)), skill_code, skill_code_base64) self.skills[skill_name] = skill_ins self.recent_skills.append(skill_name) info = f"Skill '{skill_name}' has been registered." logger.write(info) return True, info def delete_skill(self, skill_name: str) -> None: try: skill_name, _ = self.extract_function_info(skill_name) except: skill_name = skill_name if skill_name in self.skills: del self.skills[skill_name] if skill_name in self.recent_skills: position = self.recent_skills.index(skill_name) self.recent_skills.pop(position) def retrieve_skills(self, query_task: str, skill_num: int, screen_type: str) -> List[str]: skill_num = min(skill_num, len(self.skills)) target_skills = [skill for skill in self.recent_skills] task_emb = np.array(self.embedding_provider.embed_query(query_task)) sorted_skills = sorted(self.skills.items(), key=lambda x: -np.dot(x[1].skill_embedding, task_emb)) for skill in sorted_skills: skill_name, skill = skill if len(target_skills) >= skill_num: break else: if skill_name not in target_skills: target_skills.append(skill_name) self.recent_skills = [] # Add required skills based on screen type if screen_type == constants.GENERAL_GAME_INTERFACE: target_skills += [skill for skill in self.skill_names_movement] elif screen_type == constants.TRADE_INTERFACE or screen_type == constants.SATCHEL_INTERFACE: target_skills += [skill for skill in self.skill_names_trade] elif screen_type == constants.MAP_INTERFACE: target_skills += [skill for skill in self.skill_names_map] return target_skills def register_available_skills(self, candidates:List[str]) -> None: for skill_key in candidates: if skill_key not in self.skills: logger.error(f"Skill '{skill_key}' does not exist.") for skill_key in list(self.skills.keys()): if skill_key not in candidates: del self.skills[skill_key] def get_all_skills(self) -> List[str]: return list(self.skills.keys()) def convert_str_to_func(self, skill_name, skill_local): exec(skill_local[skill_name].skill_code) skill = eval(skill_name) return skill def store_skills_to_file(self, file_path: str, skills: Dict[str, Skill]) -> None: serialized_skills = serialize_skills(skills) save_json(file_path, serialized_skills, indent=4)
1
0.680936
1
0.680936
game-dev
MEDIA
0.701476
game-dev
0.686782
1
0.686782
emscripten-core/emscripten
5,362
test/third_party/bullet/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SIMPLE_BROADPHASE_H #define BT_SIMPLE_BROADPHASE_H #include "btOverlappingPairCache.h" struct btSimpleBroadphaseProxy : public btBroadphaseProxy { int m_nextFree; // int m_handleId; btSimpleBroadphaseProxy() {}; btSimpleBroadphaseProxy(const btVector3& minpt,const btVector3& maxpt,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,void* multiSapProxy) :btBroadphaseProxy(minpt,maxpt,userPtr,collisionFilterGroup,collisionFilterMask,multiSapProxy) { (void)shapeType; } SIMD_FORCE_INLINE void SetNextFree(int next) {m_nextFree = next;} SIMD_FORCE_INLINE int GetNextFree() const {return m_nextFree;} }; ///The SimpleBroadphase is just a unit-test for btAxisSweep3, bt32BitAxisSweep3, or btDbvtBroadphase, so use those classes instead. ///It is a brute force aabb culling broadphase based on O(n^2) aabb checks class btSimpleBroadphase : public btBroadphaseInterface { protected: int m_numHandles; // number of active handles int m_maxHandles; // max number of handles int m_LastHandleIndex; btSimpleBroadphaseProxy* m_pHandles; // handles pool void* m_pHandlesRawPtr; int m_firstFreeHandle; // free handles list int allocHandle() { btAssert(m_numHandles < m_maxHandles); int freeHandle = m_firstFreeHandle; m_firstFreeHandle = m_pHandles[freeHandle].GetNextFree(); m_numHandles++; if(freeHandle > m_LastHandleIndex) { m_LastHandleIndex = freeHandle; } return freeHandle; } void freeHandle(btSimpleBroadphaseProxy* proxy) { int handle = int(proxy-m_pHandles); btAssert(handle >= 0 && handle < m_maxHandles); if(handle == m_LastHandleIndex) { m_LastHandleIndex--; } proxy->SetNextFree(m_firstFreeHandle); m_firstFreeHandle = handle; proxy->m_clientObject = 0; m_numHandles--; } btOverlappingPairCache* m_pairCache; bool m_ownsPairCache; int m_invalidPair; inline btSimpleBroadphaseProxy* getSimpleProxyFromProxy(btBroadphaseProxy* proxy) { btSimpleBroadphaseProxy* proxy0 = static_cast<btSimpleBroadphaseProxy*>(proxy); return proxy0; } inline const btSimpleBroadphaseProxy* getSimpleProxyFromProxy(btBroadphaseProxy* proxy) const { const btSimpleBroadphaseProxy* proxy0 = static_cast<const btSimpleBroadphaseProxy*>(proxy); return proxy0; } ///reset broadphase internal structures, to ensure determinism/reproducability virtual void resetPool(btDispatcher* dispatcher); void validate(); protected: public: btSimpleBroadphase(int maxProxies=16384,btOverlappingPairCache* overlappingPairCache=0); virtual ~btSimpleBroadphase(); static bool aabbOverlap(btSimpleBroadphaseProxy* proxy0,btSimpleBroadphaseProxy* proxy1); virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* multiSapProxy); virtual void calculateOverlappingPairs(btDispatcher* dispatcher); virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher); virtual void getAabb(btBroadphaseProxy* proxy,btVector3& aabbMin, btVector3& aabbMax ) const; virtual void rayTest(const btVector3& rayFrom,const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin=btVector3(0,0,0),const btVector3& aabbMax=btVector3(0,0,0)); virtual void aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback); btOverlappingPairCache* getOverlappingPairCache() { return m_pairCache; } const btOverlappingPairCache* getOverlappingPairCache() const { return m_pairCache; } bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame ///will add some transform later virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const { aabbMin.setValue(-BT_LARGE_FLOAT,-BT_LARGE_FLOAT,-BT_LARGE_FLOAT); aabbMax.setValue(BT_LARGE_FLOAT,BT_LARGE_FLOAT,BT_LARGE_FLOAT); } virtual void printStats() { // printf("btSimpleBroadphase.h\n"); // printf("numHandles = %d, maxHandles = %d\n",m_numHandles,m_maxHandles); } }; #endif //BT_SIMPLE_BROADPHASE_H
1
0.963879
1
0.963879
game-dev
MEDIA
0.900189
game-dev
0.982154
1
0.982154
StefanJo3107/ASCII-Rendering-Shader-in-Unity
7,953
ShaderLearning/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Runtime/TMP_UpdateManager.cs
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; #if UNITY_2019_1_OR_NEWER using UnityEngine.Rendering; #elif UNITY_2018_1_OR_NEWER using UnityEngine.Experimental.Rendering; #endif namespace TMPro { public class TMP_UpdateManager { private static TMP_UpdateManager s_Instance; private readonly List<TMP_Text> m_LayoutRebuildQueue = new List<TMP_Text>(); private Dictionary<int, int> m_LayoutQueueLookup = new Dictionary<int, int>(); private readonly List<TMP_Text> m_GraphicRebuildQueue = new List<TMP_Text>(); private Dictionary<int, int> m_GraphicQueueLookup = new Dictionary<int, int>(); private readonly List<TMP_Text> m_InternalUpdateQueue = new List<TMP_Text>(); private Dictionary<int, int> m_InternalUpdateLookup = new Dictionary<int, int>(); //private bool m_PerformingGraphicRebuild; //private bool m_PerformingLayoutRebuild; /// <summary> /// Get a singleton instance of the registry /// </summary> public static TMP_UpdateManager instance { get { if (TMP_UpdateManager.s_Instance == null) TMP_UpdateManager.s_Instance = new TMP_UpdateManager(); return TMP_UpdateManager.s_Instance; } } /// <summary> /// Register to receive rendering callbacks. /// </summary> protected TMP_UpdateManager() { Camera.onPreCull += OnCameraPreCull; #if UNITY_2019_1_OR_NEWER RenderPipelineManager.beginFrameRendering += OnBeginFrameRendering; #elif UNITY_2018_1_OR_NEWER RenderPipeline.beginFrameRendering += OnBeginFrameRendering; #endif } /// <summary> /// Function used as a replacement for LateUpdate() to handle SDF Scale updates and Legacy Animation updates. /// </summary> /// <param name="textObject"></param> internal static void RegisterTextObjectForUpdate(TMP_Text textObject) { TMP_UpdateManager.instance.InternalRegisterTextObjectForUpdate(textObject); } private void InternalRegisterTextObjectForUpdate(TMP_Text textObject) { int id = textObject.GetInstanceID(); if (this.m_InternalUpdateLookup.ContainsKey(id)) return; m_InternalUpdateLookup[id] = id; this.m_InternalUpdateQueue.Add(textObject); return; } /// <summary> /// Function to register elements which require a layout rebuild. /// </summary> /// <param name="element"></param> public static void RegisterTextElementForLayoutRebuild(TMP_Text element) { TMP_UpdateManager.instance.InternalRegisterTextElementForLayoutRebuild(element); } private bool InternalRegisterTextElementForLayoutRebuild(TMP_Text element) { int id = element.GetInstanceID(); if (this.m_LayoutQueueLookup.ContainsKey(id)) return false; m_LayoutQueueLookup[id] = id; this.m_LayoutRebuildQueue.Add(element); return true; } /// <summary> /// Function to register elements which require a layout rebuild. /// </summary> /// <param name="element"></param> public static void RegisterTextElementForGraphicRebuild(TMP_Text element) { TMP_UpdateManager.instance.InternalRegisterTextElementForGraphicRebuild(element); } private bool InternalRegisterTextElementForGraphicRebuild(TMP_Text element) { int id = element.GetInstanceID(); if (this.m_GraphicQueueLookup.ContainsKey(id)) return false; m_GraphicQueueLookup[id] = id; this.m_GraphicRebuildQueue.Add(element); return true; } /// <summary> /// Callback which occurs just before the Scriptable Render Pipeline (SRP) begins rendering. /// </summary> /// <param name="cameras"></param> #if UNITY_2019_1_OR_NEWER void OnBeginFrameRendering(ScriptableRenderContext renderContext, Camera[] cameras) #elif UNITY_2018_1_OR_NEWER void OnBeginFrameRendering(Camera[] cameras) #endif { // Exclude the PreRenderCamera #if UNITY_EDITOR if (cameras.Length == 1 && cameras[0].cameraType == CameraType.Preview) return; #endif DoRebuilds(); } /// <summary> /// Callback which occurs just before the cam is rendered. /// </summary> /// <param name="cam"></param> void OnCameraPreCull(Camera cam) { // Exclude the PreRenderCamera #if UNITY_EDITOR if (cam.cameraType == CameraType.Preview) return; #endif DoRebuilds(); } /// <summary> /// Process the rebuild requests in the rebuild queues. /// </summary> void DoRebuilds() { // Handle text objects the require an update either as a result of scale changes or legacy animation. for (int i = 0; i < m_InternalUpdateQueue.Count; i++) { m_InternalUpdateQueue[i].InternalUpdate(); } // Handle Layout Rebuild Phase for (int i = 0; i < m_LayoutRebuildQueue.Count; i++) { m_LayoutRebuildQueue[i].Rebuild(CanvasUpdate.Prelayout); } if (m_LayoutRebuildQueue.Count > 0) { m_LayoutRebuildQueue.Clear(); m_LayoutQueueLookup.Clear(); } // Handle Graphic Rebuild Phase for (int i = 0; i < m_GraphicRebuildQueue.Count; i++) { m_GraphicRebuildQueue[i].Rebuild(CanvasUpdate.PreRender); } // If there are no objects in the queue, we don't need to clear the lists again. if (m_GraphicRebuildQueue.Count > 0) { m_GraphicRebuildQueue.Clear(); m_GraphicQueueLookup.Clear(); } } internal static void UnRegisterTextObjectForUpdate(TMP_Text textObject) { TMP_UpdateManager.instance.InternalUnRegisterTextObjectForUpdate(textObject); } /// <summary> /// Function to unregister elements which no longer require a rebuild. /// </summary> /// <param name="element"></param> public static void UnRegisterTextElementForRebuild(TMP_Text element) { TMP_UpdateManager.instance.InternalUnRegisterTextElementForGraphicRebuild(element); TMP_UpdateManager.instance.InternalUnRegisterTextElementForLayoutRebuild(element); TMP_UpdateManager.instance.InternalUnRegisterTextObjectForUpdate(element); } private void InternalUnRegisterTextElementForGraphicRebuild(TMP_Text element) { int id = element.GetInstanceID(); TMP_UpdateManager.instance.m_GraphicRebuildQueue.Remove(element); m_GraphicQueueLookup.Remove(id); } private void InternalUnRegisterTextElementForLayoutRebuild(TMP_Text element) { int id = element.GetInstanceID(); TMP_UpdateManager.instance.m_LayoutRebuildQueue.Remove(element); m_LayoutQueueLookup.Remove(id); } private void InternalUnRegisterTextObjectForUpdate(TMP_Text textObject) { int id = textObject.GetInstanceID(); TMP_UpdateManager.instance.m_InternalUpdateQueue.Remove(textObject); m_InternalUpdateLookup.Remove(id); } } }
1
0.822245
1
0.822245
game-dev
MEDIA
0.525822
game-dev,graphics-rendering
0.955995
1
0.955995
tgstation/tgstation
2,331
code/datums/skills/fishing.dm
/** * skill associated with the fishing feature. It modifies the fishing minigame difficulty * and is gained each time one is completed. */ /datum/skill/fishing name = "Fishing" title = "Angler" desc = "How empty and alone you are on this barren Earth." modifiers = list(SKILL_VALUE_MODIFIER = list(1, 0, -1, -3, -5, -7, -10)) skill_item_path = /obj/item/clothing/head/soft/fishing_hat /datum/skill/fishing/New() . = ..() levelUpMessages[SKILL_LEVEL_NOVICE] = span_nicegreen("I'm starting to figure out what [name] really is! I can guess a fish size and weight at a glance.") levelUpMessages[SKILL_LEVEL_APPRENTICE] = span_nicegreen("I'm getting a little better at [name]! I can tell if a fish is hungry, dying and otherwise.") levelUpMessages[SKILL_LEVEL_JOURNEYMAN] = span_nicegreen("I feel like I've become quite proficient at [name]! I can tell what fishes I can catch at any given fishing spot.") levelUpMessages[SKILL_LEVEL_MASTER] = span_nicegreen("I've begun to truly understand the surprising depth behind [name]. As a master [title], I can guess what I'm going to catch now!") /datum/skill/fishing/level_gained(datum/mind/mind, new_level, old_level, silent) . = ..() if(new_level >= SKILL_LEVEL_NOVICE && old_level < SKILL_LEVEL_NOVICE) ADD_TRAIT(mind, TRAIT_EXAMINE_FISH, SKILL_TRAIT) if(new_level >= SKILL_LEVEL_APPRENTICE && old_level < SKILL_LEVEL_APPRENTICE) ADD_TRAIT(mind, TRAIT_EXAMINE_DEEPER_FISH, SKILL_TRAIT) if(new_level >= SKILL_LEVEL_JOURNEYMAN && old_level < SKILL_LEVEL_JOURNEYMAN) ADD_TRAIT(mind, TRAIT_EXAMINE_FISHING_SPOT, SKILL_TRAIT) if(new_level >= SKILL_LEVEL_MASTER && old_level < SKILL_LEVEL_MASTER) ADD_TRAIT(mind, TRAIT_REVEAL_FISH, SKILL_TRAIT) /datum/skill/fishing/level_lost(datum/mind/mind, new_level, old_level, silent) . = ..() if(old_level >= SKILL_LEVEL_MASTER && new_level < SKILL_LEVEL_MASTER) REMOVE_TRAIT(mind, TRAIT_REVEAL_FISH, SKILL_TRAIT) if(old_level >= SKILL_LEVEL_JOURNEYMAN && new_level < SKILL_LEVEL_JOURNEYMAN) REMOVE_TRAIT(mind, TRAIT_EXAMINE_FISHING_SPOT, SKILL_TRAIT) if(old_level >= SKILL_LEVEL_APPRENTICE && new_level < SKILL_LEVEL_APPRENTICE) REMOVE_TRAIT(mind, TRAIT_EXAMINE_DEEPER_FISH, SKILL_TRAIT) if(old_level >= SKILL_LEVEL_NOVICE && new_level < SKILL_LEVEL_NOVICE) REMOVE_TRAIT(mind, TRAIT_EXAMINE_FISH, SKILL_TRAIT)
1
0.741847
1
0.741847
game-dev
MEDIA
0.903753
game-dev
0.513928
1
0.513928
DeltaEngine/DeltaEngine
1,090
Samples/SideScroller/Tests/GameTests.cs
using DeltaEngine.Core; using DeltaEngine.Datatypes; using DeltaEngine.Entities; using DeltaEngine.Platforms; using DeltaEngine.Scenes.Controls; using NUnit.Framework; namespace SideScroller.Tests { public class GameTests : TestWithMocksOrVisually { [SetUp] public void CreateNewGame() { game = new Game(Resolve<Window>()); } private Game game; [Test] public void StartTheGame() { var startButton = (InteractiveButton)game.mainMenu.Controls[IndexOfStartButton]; startButton.Clicked.Invoke(); Assert.IsNotNull(game.player); } private const int IndexOfStartButton = 1; [Test] public void ExitGame() { var exitButton = (InteractiveButton)game.mainMenu.Controls[IndexOfExitButton]; exitButton.Clicked.Invoke(); } private const int IndexOfExitButton = 2; [Test] public void CreateEnemiesAFterPointInTime() { game.StartGame(); AdvanceTimeAndUpdateEntities(TimeToSpawnNewEnemy + 0.1f); Assert.AreEqual(1, EntitiesRunner.Current.GetEntitiesOfType<EnemyPlane>().Count); } private const float TimeToSpawnNewEnemy = 2; } }
1
0.845493
1
0.845493
game-dev
MEDIA
0.956061
game-dev
0.759872
1
0.759872
inamiy/Harvest-SwiftUI-Gallery
3,279
Harvest-SwiftUI-Gallery/Screens/Root.State.Current.swift
extension Root.State { /// Current example state as sum type where each state is not shared. enum Current { case intro case counter(Counter.State) case stopwatch(Stopwatch.State) case stateDiagram(StateDiagram.State) case todo(Todo.State) case github(GitHub.State) case lifegame(LifeGame.State) var example: Example { switch self { case .intro: return IntroExample() case .counter: return CounterExample() case .stopwatch: return StopwatchExample() case .stateDiagram: return StateDiagramExample() case .todo: return TodoExample() case .github: return GitHubExample() case .lifegame: return LifeGameExample() } } } } // MARK: - allEffectIDs extension Root.State.Current { /// Used for previous effects cancellation. var allEffectIDs: (Root.EffectID) -> Bool { switch self { case .stopwatch: return { $0.stopwatch != nil } case .github: return { $0.github != nil } default: return { _ in false } } } } // MARK: - get-set enum properties (for SwiftUI binding) // See also: https://www.pointfree.co/episodes/ep70-composable-state-management-action-pullbacks extension Root.State.Current { var counter: Counter.State? { get { guard case let .counter(value) = self else { return nil } return value } set { guard case .counter = self, let newValue = newValue else { return } self = .counter(newValue) } } var stopwatch: Stopwatch.State? { get { guard case let .stopwatch(value) = self else { return nil } return value } set { guard case .stopwatch = self, let newValue = newValue else { return } self = .stopwatch(newValue) } } var stateDiagram: StateDiagram.State? { get { guard case let .stateDiagram(value) = self else { return nil } return value } set { guard case .stateDiagram = self, let newValue = newValue else { return } self = .stateDiagram(newValue) } } var todo: Todo.State? { get { guard case let .todo(value) = self else { return nil } return value } set { guard case .todo = self, let newValue = newValue else { return } self = .todo(newValue) } } var github: GitHub.State? { get { guard case let .github(value) = self else { return nil } return value } set { guard case .github = self, let newValue = newValue else { return } self = .github(newValue) } } var lifegame: LifeGame.State? { get { guard case let .lifegame(value) = self else { return nil } return value } set { guard case .lifegame = self, let newValue = newValue else { return } self = .lifegame(newValue) } } }
1
0.816503
1
0.816503
game-dev
MEDIA
0.703974
game-dev,mobile
0.635655
1
0.635655
andrewnakas/OpenBrushVR
4,219
IOSTEST/Classes/Native/AssemblyU2DCSharpU2Dfirstpass_UnityEngine_XR_iOS_U4129824344.h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_ValueType3507792607.h" #include "AssemblyU2DCSharpU2Dfirstpass_UnityEngine_XR_iOS_A3616749745.h" #include "UnityEngine_UnityEngine_Matrix4x42933234003.h" #include "mscorlib_System_IntPtr2504060609.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.XR.iOS.UnityARHitTestResult struct UnityARHitTestResult_t4129824344 { public: // UnityEngine.XR.iOS.ARHitTestResultType UnityEngine.XR.iOS.UnityARHitTestResult::type int64_t ___type_0; // System.Double UnityEngine.XR.iOS.UnityARHitTestResult::distance double ___distance_1; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.UnityARHitTestResult::localTransform Matrix4x4_t2933234003 ___localTransform_2; // UnityEngine.Matrix4x4 UnityEngine.XR.iOS.UnityARHitTestResult::worldTransform Matrix4x4_t2933234003 ___worldTransform_3; // System.IntPtr UnityEngine.XR.iOS.UnityARHitTestResult::anchor IntPtr_t ___anchor_4; // System.Boolean UnityEngine.XR.iOS.UnityARHitTestResult::isValid bool ___isValid_5; public: inline static int32_t get_offset_of_type_0() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___type_0)); } inline int64_t get_type_0() const { return ___type_0; } inline int64_t* get_address_of_type_0() { return &___type_0; } inline void set_type_0(int64_t value) { ___type_0 = value; } inline static int32_t get_offset_of_distance_1() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___distance_1)); } inline double get_distance_1() const { return ___distance_1; } inline double* get_address_of_distance_1() { return &___distance_1; } inline void set_distance_1(double value) { ___distance_1 = value; } inline static int32_t get_offset_of_localTransform_2() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___localTransform_2)); } inline Matrix4x4_t2933234003 get_localTransform_2() const { return ___localTransform_2; } inline Matrix4x4_t2933234003 * get_address_of_localTransform_2() { return &___localTransform_2; } inline void set_localTransform_2(Matrix4x4_t2933234003 value) { ___localTransform_2 = value; } inline static int32_t get_offset_of_worldTransform_3() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___worldTransform_3)); } inline Matrix4x4_t2933234003 get_worldTransform_3() const { return ___worldTransform_3; } inline Matrix4x4_t2933234003 * get_address_of_worldTransform_3() { return &___worldTransform_3; } inline void set_worldTransform_3(Matrix4x4_t2933234003 value) { ___worldTransform_3 = value; } inline static int32_t get_offset_of_anchor_4() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___anchor_4)); } inline IntPtr_t get_anchor_4() const { return ___anchor_4; } inline IntPtr_t* get_address_of_anchor_4() { return &___anchor_4; } inline void set_anchor_4(IntPtr_t value) { ___anchor_4 = value; } inline static int32_t get_offset_of_isValid_5() { return static_cast<int32_t>(offsetof(UnityARHitTestResult_t4129824344, ___isValid_5)); } inline bool get_isValid_5() const { return ___isValid_5; } inline bool* get_address_of_isValid_5() { return &___isValid_5; } inline void set_isValid_5(bool value) { ___isValid_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.XR.iOS.UnityARHitTestResult struct UnityARHitTestResult_t4129824344_marshaled_pinvoke { int64_t ___type_0; double ___distance_1; Matrix4x4_t2933234003 ___localTransform_2; Matrix4x4_t2933234003 ___worldTransform_3; intptr_t ___anchor_4; int32_t ___isValid_5; }; // Native definition for COM marshalling of UnityEngine.XR.iOS.UnityARHitTestResult struct UnityARHitTestResult_t4129824344_marshaled_com { int64_t ___type_0; double ___distance_1; Matrix4x4_t2933234003 ___localTransform_2; Matrix4x4_t2933234003 ___worldTransform_3; intptr_t ___anchor_4; int32_t ___isValid_5; };
1
0.628166
1
0.628166
game-dev
MEDIA
0.520219
game-dev
0.52819
1
0.52819
quelsolaar/MergeSource
23,467
s_popup_detect.c
#include <math.h> #include <stdlib.h> #include "seduce.h" #include "s_draw_3d.h" extern void seduce_background_circle_draw(BInputState *input, float pos_x, float pos_y, uint splits, float timer, uint selected); extern void seduce_background_angle(BInputState *input, void *id, uint part, float pos_x, float pos_y, float angle_a, float angle_b, float timer); extern void seduce_widget_overlay_matrix(RMatrix *matrix); extern void seduce_object_3d_draw(BInputState *input, float pos_x, float pos_y, float pos_z, float scale, uint id, float fade, float *color); void seduce_popup_execute(BInputState *input, float pointer_x, float pointer_y, boolean button, boolean last_button, uint user_id, float time, void (*func)(BInputState *input, float time, void *user), void *user) { BInputState i; BInputPointerState pointer; i = *input; pointer.pointer_x = pointer_x; pointer.pointer_y = pointer_y; pointer.click_pointer_x[0] = pointer_x; pointer.click_pointer_y[0] = pointer_y; pointer.delta_pointer_x = 0; pointer.delta_pointer_y = 0; pointer.button[0] = button; pointer.last_button[0] = last_button; pointer.button_count = 1; pointer.name[0] = 0; pointer.user_id = user_id; i.pointers = &pointer; i.pointer_count = 1; i.axis_count = 0; func(&i, time, user); } typedef struct{ void *id; float timer; float pos[2]; // void (*func)(BInputState *input, float time, void *user); uint user_id; // void *user; boolean sticky; boolean active; }SeducePopupGrab; /* extern void seduce_element_popup_action_begin(float pos_x, float pos_y, boolean active); extern void seduce_element_popup_action_end(input); */ boolean seduce_popup_detect_mouse(BInputState *input, void *id, uint button, void (*func)(BInputState *input, float time, void *user), void *user) { static SeducePopupGrab *grab = NULL; float f, vec[2]; uint i, j, k; if(grab == NULL) { uint count; count = betray_support_functionality(B_SF_POINTER_COUNT_MAX); grab = malloc((sizeof *grab) * count); for(i = 0; i < count; i++) grab[i].active = FALSE; } if(input->mode == BAM_MAIN) { for(i = 0; i < input->pointer_count; i++) { if(grab[i].active) { grab[i].timer += input->delta_time; if(grab[i].timer > 1.0) grab[i].timer = 1.0; }else { grab[i].timer -= input->delta_time; if(grab[i].timer < 0.0) grab[i].timer = 0.0; } if(func != NULL && grab[i].timer > 0.001 && grab[i].id == id) func(input, grab[i].timer, user); } } if(input->mode == BAM_EVENT) { for(i = 0; i < input->pointer_count; i++) { if(input->pointers[i].button[button] && !input->pointers[i].last_button[button] && id == seduce_element_pointer_id(input, i, NULL)) { // for(j = 0; j < input->pointers[i].button_count && input->pointers[i].button[j] == (j == button); j++); // if(j < input->pointers[i].button_count) { grab[i].timer = 0.05; grab[i].user_id = input->pointers[i].user_id; grab[i].sticky = FALSE; grab[i].active = TRUE; grab[i].id = id; grab[i].pos[0] = input->pointers[i].pointer_x; grab[i].pos[1] = input->pointers[i].pointer_y; // seduce_background_particle_burst(input, grab[i].pos[0], grab[i].pos[1], 50, 1.0, S_PT_SURFACE); } } if(func != NULL && grab[i].timer > 0.001 && grab[i].id == id) { if(grab[i].sticky) seduce_popup_execute(input, input->pointers[i].pointer_x, input->pointers[i].pointer_y, input->pointers[i].button[0], input->pointers[i].last_button[0], grab[i].user_id, grab[i].timer, func, user); else seduce_popup_execute(input, input->pointers[i].pointer_x, input->pointers[i].pointer_y, !input->pointers[i].button[button], !input->pointers[i].last_button[button], grab[i].user_id, grab[i].timer, func, user); } if(!input->pointers[i].button[button] && input->pointers[i].last_button[button] && grab[i].id == id) { if(grab[i].timer < 0.99 && 0.01 * 0.01 > (input->pointers[i].pointer_x - input->pointers[i].click_pointer_x[button]) * (input->pointers[i].pointer_x - input->pointers[i].click_pointer_x[button]) + (input->pointers[i].pointer_y - input->pointers[i].click_pointer_y[button]) * (input->pointers[i].pointer_y - input->pointers[i].click_pointer_y[button])) grab[i].sticky = TRUE; else grab[i].active = FALSE; } } for(i = 0; i < input->pointer_count; i++) if(grab[i].sticky) for(j = 0; j < input->pointer_count; j++) if(!input->pointers[j].button[0] && input->pointers[j].last_button[0] && grab[i].id == id) grab[i].active = FALSE; } if(input->mode == BAM_DRAW) { for(i = 0; i < input->pointer_count; i++) { if(func != NULL && grab[i].timer > 0.001 && grab[i].id == id) { RMatrix overlay, *reset; reset = r_matrix_get(); seduce_widget_overlay_matrix(&overlay); r_matrix_push(&overlay); r_matrix_translate(&overlay, grab[i].pos[0], grab[i].pos[1], 0); // seduce_element_popup_action_begin(input, input->pointers[i].user_id); seduce_element_user_exclusive_begin(grab[i].user_id); if(grab[i].sticky) seduce_popup_execute(input, input->pointers[i].pointer_x, input->pointers[i].pointer_y, input->pointers[i].button[button], input->pointers[i].button[button], grab[i].user_id, grab[i].timer, func, user); else seduce_popup_execute(input, input->pointers[i].pointer_x, input->pointers[i].pointer_y, !input->pointers[i].button[button], !input->pointers[i].button[button], grab[i].user_id, grab[i].timer, func, user); seduce_element_user_exclusive_end(); // seduce_element_popup_action_end(input); r_matrix_set(reset); } } } for(i = 0; i < input->pointer_count; i++) if(grab[i].active && grab[i].id == id) return TRUE; return FALSE; } boolean seduce_popup_detect_axis(BInputState *input, uint button, void (*func)(BInputState *input, float time, void *user), void *user) { static SeducePopupGrab *users = NULL; float f, vec[2]; uint i, j, k, count, user_count; user_count = betray_support_functionality(B_SF_USER_COUNT_MAX); if(users == NULL) { users = malloc((sizeof *users) * user_count); for(i = 0; i < user_count; i++) users[i].active = FALSE; } if(input->mode == BAM_MAIN) { for(i = 0; i < user_count; i++) { if(users[i].active) { users[i].timer += input->delta_time * 4.0; if(users[i].timer > 1.0) users[i].timer = 1.0; }else { users[i].timer -= input->delta_time * 4.0; if(users[i].timer < 0.0) users[i].timer = 0.0; } if(func != NULL && users[i].timer > 0.001) func(input, users[i].timer, user); } } if(input->mode == BAM_EVENT) { for(i = 0; i < user_count; i++) { if(!users[i].active) { for(j = 0; j < input->button_event_count; j++) { if(input->button_event[j].user_id == i && input->button_event[j].state && input->button_event[j].button == button) { float pos[3]; users[i].timer = 0.05; users[i].user_id = input->button_event[j].user_id; users[i].sticky = FALSE; users[i].active = TRUE; seduce_element_selected_id(i, pos, NULL); users[i].pos[0] = pos[0]; users[i].pos[1] = pos[1]; } } } if(func != NULL) for(j = 0; j < input->button_event_count; j++) if(input->button_event[j].user_id == i && !input->button_event[j].state && input->button_event[j].button == button) users[i].active = FALSE; } } for(i = 0; i < user_count; i++) { if(func != NULL && users[i].timer > 0.001) { BInputAxisState *axis = NULL; BInputState fake_input; RMatrix overlay, *reset = NULL; uint primary; if(input->mode == BAM_DRAW) { reset = r_matrix_get(); seduce_widget_overlay_matrix(&overlay); r_matrix_push(&overlay); r_matrix_translate(&overlay, users[i].pos[0], users[i].pos[1], 0); } if(input->axis_count != 0) axis = malloc((sizeof *axis) * input->axis_count); fake_input = *input; fake_input.pointer_count = 0; fake_input.axis = axis; fake_input.button_event_count = 0; primary = seduce_element_primary_axis(input, i); for(j = 0; j < input->axis_count; j++) { axis[j] = input->axis[j]; if(j != primary) axis[j].axis[0] = axis[j].axis[1] = axis[j].axis[2] = 0; } for(j = 0; j < input->button_event_count; j++) { fake_input.button_event[fake_input.button_event_count] = input->button_event[j]; if(input->button_event[j].user_id == i && input->button_event[j].button == button && !input->button_event[j].state) { fake_input.button_event[fake_input.button_event_count].state = TRUE; fake_input.button_event[fake_input.button_event_count].button = BETRAY_BUTTON_FACE_A; } if(input->button_event[j].user_id == i) fake_input.button_event_count++; } seduce_element_user_exclusive_begin(i); func(&fake_input, users[i].timer, user); seduce_element_user_exclusive_end(); if(input->mode == BAM_DRAW) r_matrix_set(reset); if(input->axis_count != 0) free(axis); } if(input->mode == BAM_EVENT) if(func != NULL) for(j = 0; j < input->button_event_count; j++) if(input->button_event[j].user_id == i && !input->button_event[j].state && input->button_event[j].button == button) users[i].active = FALSE; } for(i = 0; i < user_count; i++) if(users[i].active) return TRUE; return FALSE; } /* typedef struct{ float timer; float pos[2]; void (*func)(BInputState *input, float time, void *user); void *user; boolean sticky; boolean active; }SeducePopupGrab; */ STypeInState seduce_popup_detect_button(BInputState *input, void *id,/* uint icon, */float pos_x, float pos_y, /*float scale, float time, */void (*func)(BInputState *input, float time, void *user), void *user, boolean displace/*, float *color*/) { static boolean *a_button, *a_button_last; static SeducePopupGrab *grab = NULL; float f, vec[2]; uint i, j, k, count, user_count, pointer_count; user_count = betray_support_functionality(B_SF_USER_COUNT_MAX); pointer_count = betray_support_functionality(B_SF_POINTER_COUNT_MAX); count = user_count + pointer_count; if(grab == NULL) { grab = malloc((sizeof *grab) * count); for(i = 0; i < count; i++) { grab[i].id = NULL; grab[i].active = FALSE; grab[i].timer = 0.0; } a_button = malloc((sizeof *a_button) * user_count); a_button_last = malloc((sizeof *a_button_last) * user_count); for(i = 0; i < user_count; i++) a_button[i] = a_button_last[i] = FALSE; } for(i = 0; i < count; i++) { RMatrix overlay, *reset; BInputPointerState *pointers = NULL; BInputState fake_input; if(input->mode == BAM_MAIN) { if(grab[i].active) { grab[i].timer += input->delta_time * 4.0; if(grab[i].timer > 1.0) grab[i].timer = 1.0; }else { grab[i].timer -= input->delta_time * 4.0; if(grab[i].timer < 0.0) grab[i].timer = 0.0; } } if(func != NULL && grab[i].timer > 0.001 && id == grab[i].id) { BInputAxisState *axis = NULL; uint primary; if(input->mode == BAM_DRAW) { float pos[3]; reset = r_matrix_get(); r_matrix_projection_screenf(reset, pos, pos_x, pos_y, 0); seduce_widget_overlay_matrix(&overlay); r_matrix_push(&overlay); if(displace) r_matrix_translate(&overlay, grab[i].pos[0], grab[i].pos[1], 0); r_matrix_scale(&overlay, 1.0, 1.0, 1.0); } fake_input = *input; if(input->pointer_count != 0) pointers = malloc((sizeof *pointers) * input->pointer_count); if(input->axis_count != 0) axis = malloc((sizeof *axis) * input->axis_count); fake_input.pointers = pointers; fake_input.pointer_count = 0; if(i < pointer_count) { pointers[fake_input.pointer_count] = input->pointers[i]; if(!grab[i].sticky) { for(k = 0; k < pointers[fake_input.pointer_count].button_count; k++) { pointers[fake_input.pointer_count].button[k] = !pointers[fake_input.pointer_count].button[k]; pointers[fake_input.pointer_count].last_button[k] = !pointers[fake_input.pointer_count].last_button[k]; } } fake_input.pointer_count++; } fake_input.axis = axis; primary = seduce_element_primary_axis(input, grab[i].user_id); for(j = 0; j < input->axis_count; j++) { axis[j] = input->axis[j]; if(j != primary) axis[j].axis[0] = axis[j].axis[1] = axis[j].axis[2] = 0; } fake_input.button_event_count = 0; for(j = 0; j < input->button_event_count; j++) { fake_input.button_event[fake_input.button_event_count] = input->button_event[j]; // if(!grab[i].sticky) if(input->button_event[j].user_id == grab[i].user_id && input->button_event[j].button == BETRAY_BUTTON_FACE_A && !input->button_event[j].state) fake_input.button_event[fake_input.button_event_count].state = TRUE; if(input->button_event[j].user_id == grab[i].user_id) fake_input.button_event_count++; } if(fake_input.pointers[i].button[0] && !fake_input.pointers[i].last_button[0]) j = 0; seduce_element_user_exclusive_begin(grab[i].user_id); func(&fake_input, grab[i].timer, user); seduce_element_user_exclusive_end(); if(input->mode == BAM_DRAW) r_matrix_set(reset); if(pointers != NULL) free(pointers); if(axis != NULL) free(axis); if(input->mode == BAM_DRAW) r_matrix_set(reset); } } if(input->mode == BAM_EVENT) { for(i = 0; i < input->pointer_count; i++) { if(grab[i].active && id == grab[i].id) { if(grab[i].sticky && input->pointers[i].button[0] && !input->pointers[i].last_button[0]) { grab[i].active = FALSE; return S_TIS_DONE; } if(!input->pointers[i].button[0] && input->pointers[i].last_button[0]) { if(!grab[i].sticky && (input->pointers[i].click_pointer_x[0] - input->pointers[i].pointer_x) * (input->pointers[i].click_pointer_x[0] - input->pointers[i].pointer_x) + (input->pointers[i].click_pointer_y[0] - input->pointers[i].pointer_y) * (input->pointers[i].click_pointer_y[0] - input->pointers[i].pointer_y) < 0.01 * 0.01) grab[i].sticky = TRUE; else { grab[i].active = FALSE; return S_TIS_DONE; } } /* if(grab[i].sticky && !input->pointers[i].button[0] && input->pointers[i].last_button[0]) { grab[i].active = FALSE; return S_TIS_DONE; }*/ } if(!grab[i].active) { if(input->pointers[i].button[0] && !input->pointers[i].last_button[0]) { if(id == seduce_element_pointer_id(input, i, NULL)) { grab[i].active = TRUE; grab[i].sticky = FALSE; grab[i].id = id; grab[i].timer = 0.3; grab[i].pos[0] = input->pointers[i].pointer_x; grab[i].pos[1] = input->pointers[i].pointer_y; grab[i].user_id = input->pointers[i].user_id; } } } } for(i = 0; i < input->user_count; i++) { uint part; if(id == seduce_element_selected_id(i, NULL, &part)) { for(j = 0; j < input->button_event_count; j++) if(input->button_event[j].button == BETRAY_BUTTON_FACE_A && input->button_event[j].user_id == i) break; if(j < input->button_event_count) { if(!input->button_event[j].state) { uint axis; axis = seduce_element_primary_axis(input, i); if(grab[i + pointer_count].sticky) { grab[i + pointer_count].active = FALSE; return S_TIS_DONE; } else if(axis == -1 || input->axis[axis].axis[0] * input->axis[axis].axis[0] + input->axis[axis].axis[1] * input->axis[axis].axis[1] > 0.01) { grab[i + pointer_count].active = FALSE; return S_TIS_DONE; } else grab[i + pointer_count].sticky = TRUE; } if(input->button_event[j].state && !grab[i + pointer_count].active) { grab[i + pointer_count].active = TRUE; grab[i + pointer_count].sticky = FALSE; grab[i + pointer_count].id = id; grab[i + pointer_count].timer = 0.1; grab[i + pointer_count].pos[0] = input->pointers[i].pointer_x; grab[i + pointer_count].pos[1] = input->pointers[i].pointer_y; grab[i + pointer_count].user_id = i; } } } } } for(i = 0; i < count; i++) if(grab[i].id == id && grab[i].active) return S_TIS_ACTIVE; return S_TIS_IDLE; } STypeInState seduce_popup_detect_icon(BInputState *input, void *id, uint icon, float pos_x, float pos_y, float scale, float time, void (*func)(BInputState *input, float time, void *user), void *user, boolean displace, float *color) { if(input->mode == BAM_DRAW && scale > 0.0) { SeduceLineObject *object = NULL; float *c, white[4] = {1, 1, 1, 1}, pos[3]; if(color == NULL) c = white; else c = color; scale *= 0.5; object = seduce_primitive_line_object_allocate(); seduce_primitive_line_add_3d(object, pos_x + scale * 0.75, pos_y, 0, pos_x + scale * -0.75, pos_y, 0, c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]); seduce_primitive_line_add_3d(object, pos_x + scale * 0.5, pos_y + scale * -0.5, 0, pos_x + scale * -0.5, pos_y + scale * -0.5, 0, c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]); seduce_primitive_line_add_3d(object, pos_x + scale * 0.5, pos_y + scale * 0.5, 0, pos_x + scale * -0.5, pos_y + scale * 0.5, 0, c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]); seduce_primitive_circle_add_3d(object, pos_x, pos_y, 0, 0, 1, 0, 0, 0, 1, scale, 0, 1, 0, scale, c[0], c[1], c[2], c[3], c[0], c[1], c[2], c[3]); seduce_primitive_line_draw(object, 1.0, 1.0, 1.0, 1.0); seduce_primitive_line_object_free(object); pos[0] = pos_x; pos[1] = pos_y; pos[2] = 0; seduce_element_add_point(input, id, 0, pos, scale); } // seduce_widget_button_icon(input, id, icon, pos_x, pos_y, scale, time, color); return seduce_popup_detect_button(input, id, pos_x, pos_y, func, user, displace); } STypeInState seduce_popup_detect_text(BInputState *input, void *id, float pos_x, float pos_y, float center, float size, float spacing, const char *text, void (*func)(BInputState *input, float time, void *user), void *user, boolean displace, float red, float green, float blue, float alpha, float red_select, float green_select, float blue_select, float alpha_select) { seduce_text_button(input, id, pos_x, pos_y, center, size, spacing, text, red, green, blue, alpha, red_select, green_select, blue_select, alpha_select); return seduce_popup_detect_button(input, id, pos_x, pos_y, func, user, displace); } typedef struct{ float timer; float pos[2]; void *id; uint user_id; boolean sticky; boolean active; uint reject[16]; uint reject_count; }SeducePopupMultiTouch; boolean seduce_popup_detect_multitouch(BInputState *input, void *id, uint finger_count, void (*func)(BInputState *input, float time, void *user), void *user) { static float *timers = NULL; static SeducePopupMultiTouch *users = NULL; static BInputPointerState *fake_pointers = NULL; float f, vec[2]; uint i, j, k, count, pointer_count, user_count; pointer_count = betray_support_functionality(B_SF_POINTER_COUNT_MAX); user_count = betray_support_functionality(B_SF_USER_COUNT_MAX); if(users == NULL) { users = malloc((sizeof *users) * user_count); for(i = 0; i < user_count; i++) { users[i].active = FALSE; users[i].reject_count = 0; } timers = malloc((sizeof *timers) * pointer_count); for(i = 0; i < pointer_count; i++) timers[i] = 0; fake_pointers = malloc((sizeof *fake_pointers) * user_count); } if(input->mode == BAM_MAIN) { for(i = 0; i < pointer_count; i++) timers[i] += input->delta_time; for(i = 0; i < user_count; i++) { if(users[i].active) { users[i].timer += input->delta_time * 4.0; if(users[i].timer > 1.0) users[i].timer = 1.0; }else { users[i].timer -= input->delta_time * 4.0; if(users[i].timer < 0.0) users[i].timer = 0.0; } } } if(input->mode == BAM_EVENT) { for(i = 0; i < user_count; i++) { if(!users[i].active) { float pos[2] = {0, 0}; for(j = users[i].reject_count = 0; j < input->pointer_count && users[i].reject_count < finger_count; j++) { if(input->pointers[j].button[0] && !input->pointers[j].last_button[0]) timers[j] = 0.0; if(input->pointers[j].user_id == i && input->pointers[j].button[0] && timers[j] < 0.5) { users[i].reject[users[i].reject_count++] = j; pos[0] += input->pointers[j].pointer_x; pos[1] += input->pointers[j].pointer_y; } } if(users[i].reject_count == finger_count) { k = 0; for(j = 1; j < users[i].reject_count; j++) if(timers[users[i].reject[j]] < timers[users[i].reject[k]]) k = j; if(id == seduce_element_pointer_id(input, users[i].reject[k], NULL)) { users[i].timer = 0.05; users[i].sticky = FALSE; users[i].active = TRUE; users[i].id = id; users[i].pos[0] = pos[0] / (float)users[i].reject_count; users[i].pos[1] = pos[1] / (float)users[i].reject_count; } } } } } for(i = 0; i < user_count; i++) { if(func != NULL && users[i].timer > 0.001 && users[i].id == id) { RMatrix overlay, *reset; BInputPointerState *pointers; BInputState fake_input; if(input->mode == BAM_DRAW) { BInputPointerState *save; reset = r_matrix_get(); seduce_widget_overlay_matrix(&overlay); r_matrix_push(&overlay); r_matrix_translate(&overlay, users[i].pos[0], users[i].pos[1], 0); } for(j = 0; j < users[i].reject_count; j++) { // for(k = 0; k < input->pointers[users[i].reject[j]].button_count && !input->pointers[users[i].reject[j]].button[0] && !input->pointers[users[i].reject[j]].last_button[0]; k++); if(users[i].reject[j] >= input->pointer_count || (!input->pointers[users[i].reject[j]].button[0] && !input->pointers[users[i].reject[j]].last_button[0])) users[i].reject[j--] = users[i].reject[--users[i].reject_count]; } fake_input = *input; pointers = malloc((sizeof *pointers) * input->pointer_count); fake_input.pointers = pointers; fake_input.pointer_count = 0; for(j = 0; j < input->pointer_count; j++) { for(k = 0; k < users[i].reject_count && users[i].reject[k] == j; k++); if(k == users[i].reject_count && input->pointers[j].user_id == i) { pointers[fake_input.pointer_count++] = input->pointers[j]; } } fake_input.axis_count = 0; seduce_element_user_exclusive_begin(users[i].user_id); func(&fake_input, users[i].timer, user); seduce_element_user_exclusive_end(); if(input->mode == BAM_DRAW) r_matrix_set(reset); free(pointers); } } if(input->mode == BAM_EVENT) { for(i = 0; i < user_count; i++) { if(func != NULL && users[i].id == id) { for(j = 0; j < input->pointer_count; j++) { if(!input->pointers[j].button[0] && !input->pointers[j].last_button[0]) for(k = 0; k < users[i].reject_count; k++) if(users[i].reject[k] == j) users[i].reject[k] = users[i].reject[--users[i].reject_count]; if(i == input->pointers[j].user_id && !input->pointers[j].button[0] && input->pointers[j].last_button[0]) { for(k = 0; k < users[i].reject_count; k++) if(users[i].reject[k] == j) break; if(k == users[i].reject_count) users[i].active = FALSE; } } } } } for(i = 0; i < user_count; i++) if(users[i].active && users[i].id == id) return TRUE; return FALSE; }
1
0.572301
1
0.572301
game-dev
MEDIA
0.439471
game-dev,desktop-app
0.896081
1
0.896081
mail2chromium/Android-Audio-Processing-Using-WebRTC
7,660
app/src/main/jni/webrtc/base/callback.h
// This file was GENERATED by command: // pump.py callback.h.pump // DO NOT EDIT BY HAND!!! /* * Copyright 2012 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // To generate callback.h from callback.h.pump, execute: // /home/build/google3/third_party/gtest/scripts/pump.py callback.h.pump // Callbacks are callable object containers. They can hold a function pointer // or a function object and behave like a value type. Internally, data is // reference-counted, making copies and pass-by-value inexpensive. // // Callbacks are typed using template arguments. The format is: // CallbackN<ReturnType, ParamType1, ..., ParamTypeN> // where N is the number of arguments supplied to the callable object. // Callbacks are invoked using operator(), just like a function or a function // object. Default-constructed callbacks are "empty," and executing an empty // callback does nothing. A callback can be made empty by assigning it from // a default-constructed callback. // // Callbacks are similar in purpose to std::function (which isn't available on // all platforms we support) and a lightweight alternative to sigslots. Since // they effectively hide the type of the object they call, they're useful in // breaking dependencies between objects that need to interact with one another. // Notably, they can hold the results of Bind(), std::bind*, etc, without // needing // to know the resulting object type of those calls. // // Sigslots, on the other hand, provide a fuller feature set, such as multiple // subscriptions to a signal, optional thread-safety, and lifetime tracking of // slots. When these features are needed, choose sigslots. // // Example: // int sqr(int x) { return x * x; } // struct AddK { // int k; // int operator()(int x) const { return x + k; } // } add_k = {5}; // // Callback1<int, int> my_callback; // cout << my_callback.empty() << endl; // true // // my_callback = Callback1<int, int>(&sqr); // cout << my_callback.empty() << endl; // false // cout << my_callback(3) << endl; // 9 // // my_callback = Callback1<int, int>(add_k); // cout << my_callback(10) << endl; // 15 // // my_callback = Callback1<int, int>(); // cout << my_callback.empty() << endl; // true #ifndef WEBRTC_BASE_CALLBACK_H_ #define WEBRTC_BASE_CALLBACK_H_ #include "webrtc/base/refcount.h" #include "webrtc/base/scoped_ref_ptr.h" namespace rtc { template <class R> class Callback0 { public: // Default copy operations are appropriate for this class. Callback0() {} template <class T> Callback0(const T& functor) : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {} R operator()() { if (empty()) return R(); return helper_->Run(); } bool empty() const { return !helper_; } private: struct Helper : RefCountInterface { virtual ~Helper() {} virtual R Run() = 0; }; template <class T> struct HelperImpl : Helper { explicit HelperImpl(const T& functor) : functor_(functor) {} virtual R Run() { return functor_(); } T functor_; }; scoped_refptr<Helper> helper_; }; template <class R, class P1> class Callback1 { public: // Default copy operations are appropriate for this class. Callback1() {} template <class T> Callback1(const T& functor) : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {} R operator()(P1 p1) { if (empty()) return R(); return helper_->Run(p1); } bool empty() const { return !helper_; } private: struct Helper : RefCountInterface { virtual ~Helper() {} virtual R Run(P1 p1) = 0; }; template <class T> struct HelperImpl : Helper { explicit HelperImpl(const T& functor) : functor_(functor) {} virtual R Run(P1 p1) { return functor_(p1); } T functor_; }; scoped_refptr<Helper> helper_; }; template <class R, class P1, class P2> class Callback2 { public: // Default copy operations are appropriate for this class. Callback2() {} template <class T> Callback2(const T& functor) : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {} R operator()(P1 p1, P2 p2) { if (empty()) return R(); return helper_->Run(p1, p2); } bool empty() const { return !helper_; } private: struct Helper : RefCountInterface { virtual ~Helper() {} virtual R Run(P1 p1, P2 p2) = 0; }; template <class T> struct HelperImpl : Helper { explicit HelperImpl(const T& functor) : functor_(functor) {} virtual R Run(P1 p1, P2 p2) { return functor_(p1, p2); } T functor_; }; scoped_refptr<Helper> helper_; }; template <class R, class P1, class P2, class P3> class Callback3 { public: // Default copy operations are appropriate for this class. Callback3() {} template <class T> Callback3(const T& functor) : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {} R operator()(P1 p1, P2 p2, P3 p3) { if (empty()) return R(); return helper_->Run(p1, p2, p3); } bool empty() const { return !helper_; } private: struct Helper : RefCountInterface { virtual ~Helper() {} virtual R Run(P1 p1, P2 p2, P3 p3) = 0; }; template <class T> struct HelperImpl : Helper { explicit HelperImpl(const T& functor) : functor_(functor) {} virtual R Run(P1 p1, P2 p2, P3 p3) { return functor_(p1, p2, p3); } T functor_; }; scoped_refptr<Helper> helper_; }; template <class R, class P1, class P2, class P3, class P4> class Callback4 { public: // Default copy operations are appropriate for this class. Callback4() {} template <class T> Callback4(const T& functor) : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {} R operator()(P1 p1, P2 p2, P3 p3, P4 p4) { if (empty()) return R(); return helper_->Run(p1, p2, p3, p4); } bool empty() const { return !helper_; } private: struct Helper : RefCountInterface { virtual ~Helper() {} virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4) = 0; }; template <class T> struct HelperImpl : Helper { explicit HelperImpl(const T& functor) : functor_(functor) {} virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4) { return functor_(p1, p2, p3, p4); } T functor_; }; scoped_refptr<Helper> helper_; }; template <class R, class P1, class P2, class P3, class P4, class P5> class Callback5 { public: // Default copy operations are appropriate for this class. Callback5() {} template <class T> Callback5(const T& functor) : helper_(new RefCountedObject< HelperImpl<T> >(functor)) {} R operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { if (empty()) return R(); return helper_->Run(p1, p2, p3, p4, p5); } bool empty() const { return !helper_; } private: struct Helper : RefCountInterface { virtual ~Helper() {} virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) = 0; }; template <class T> struct HelperImpl : Helper { explicit HelperImpl(const T& functor) : functor_(functor) {} virtual R Run(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { return functor_(p1, p2, p3, p4, p5); } T functor_; }; scoped_refptr<Helper> helper_; }; } // namespace rtc #endif // WEBRTC_BASE_CALLBACK_H_
1
0.957171
1
0.957171
game-dev
MEDIA
0.231751
game-dev
0.930635
1
0.930635
Squalr/Squally
4,761
Source/Engine/DeveloperMode/DeveloperModeController.cpp
#include "DeveloperModeController.h" #include "cocos/2d/CCActionInstant.h" #include "cocos/2d/CCActionInterval.h" #include "cocos/base/CCDirector.h" #include "cocos/base/CCInputEvents.h" #include "Engine/Events/DeveloperModeEvents.h" #include "Engine/GlobalDirector.h" #include "Engine/Localization/Localization.h" #include "Engine/Utils/MathUtils.h" using namespace cocos2d; DeveloperModeController* DeveloperModeController::Instance = nullptr; volatile bool DeveloperModeController::IsDeveloperBuild = true; int DeveloperModeController::MaxDebugLevel = 2; int DeveloperModeController::CurrentDebugLevel = 0; void DeveloperModeController::RegisterGlobalNode() { if (DeveloperModeController::Instance == nullptr) { // Register this class globally so that it can always listen for events GlobalDirector::getInstance()->RegisterGlobalNode(DeveloperModeController::getInstance()); } } DeveloperModeController* DeveloperModeController::getInstance() { if (DeveloperModeController::Instance == nullptr) { DeveloperModeController::Instance = new DeveloperModeController(); DeveloperModeController::Instance->autorelease(); } return DeveloperModeController::Instance; } DeveloperModeController::DeveloperModeController() { DeveloperModeController::CurrentDebugLevel = 0; } DeveloperModeController::~DeveloperModeController() { } void DeveloperModeController::onEnter() { super::onEnter(); } void DeveloperModeController::initializeListeners() { super::initializeListeners(); static LanguageType nextLanguage = LanguageType::ENGLISH; this->whenKeyPressed({ InputEvents::KeyCode::KEY_BACK_SLASH }, [=](InputEvents::KeyboardEventArgs* args) { if (!DeveloperModeController::IsDeveloperBuild) { return; } args->handle(); DeveloperModeController::CurrentDebugLevel = MathUtils::wrappingNormalize(DeveloperModeController::CurrentDebugLevel + 1, 0, DeveloperModeController::MaxDebugLevel); if (this->isDeveloperModeEnabled()) { DeveloperModeEvents::TriggerDeveloperModeModeEnable(DeveloperModeEvents::DeveloperModeEnableArgs(DeveloperModeController::CurrentDebugLevel)); } else { DeveloperModeEvents::TriggerDeveloperModeModeDisable(); } }); this->whenKeyPressed({ InputEvents::KeyCode::KEY_F1 }, [=](InputEvents::KeyboardEventArgs* args) { if (!DeveloperModeController::IsDeveloperBuild) { return; } args->handle(); this->stopAllActions(); }); this->whenKeyPressed({ InputEvents::KeyCode::KEY_F2 }, [=](InputEvents::KeyboardEventArgs* args) { if (!DeveloperModeController::IsDeveloperBuild) { return; } args->handle(); this->stopAllActions(); this->runAction(RepeatForever::create(Sequence::create( CallFunc::create([=]() { Localization::setLanguage(nextLanguage); nextLanguage = (LanguageType)(((int)nextLanguage + 1) % (int)LanguageType::LAST_LANGUAGE); }), DelayTime::create(1.0f), nullptr ))); }); this->whenKeyPressed({ InputEvents::KeyCode::KEY_F3 }, [=](InputEvents::KeyboardEventArgs* args) { if (!DeveloperModeController::IsDeveloperBuild) { return; } args->handle(); this->stopAllActions(); this->runAction(RepeatForever::create(Sequence::create( CallFunc::create([=]() { Localization::setLanguage(nextLanguage); nextLanguage = (LanguageType)(((int)nextLanguage + 1) % (int)LanguageType::LAST_LANGUAGE); }), DelayTime::create(0.75f), nullptr ))); }); this->whenKeyPressed({ InputEvents::KeyCode::KEY_F4 }, [=](InputEvents::KeyboardEventArgs* args) { if (!DeveloperModeController::IsDeveloperBuild) { return; } args->handle(); this->stopAllActions(); this->runAction(RepeatForever::create(Sequence::create( CallFunc::create([=]() { Localization::setLanguage(nextLanguage); nextLanguage = (LanguageType)(((int)nextLanguage + 1) % (int)LanguageType::LAST_LANGUAGE); }), DelayTime::create(0.5f), nullptr ))); }); this->whenKeyPressed({ InputEvents::KeyCode::KEY_F5 }, [=](InputEvents::KeyboardEventArgs* args) { if (!DeveloperModeController::IsDeveloperBuild) { return; } args->handle(); this->stopAllActions(); this->runAction(RepeatForever::create(Sequence::create( CallFunc::create([=]() { Localization::setLanguage(nextLanguage); nextLanguage = (LanguageType)(((int)nextLanguage + 1) % (int)LanguageType::LAST_LANGUAGE); }), DelayTime::create(0.25f), nullptr ))); }); } bool DeveloperModeController::isDeveloperModeEnabled() { return DeveloperModeController::CurrentDebugLevel > 0 && DeveloperModeController::CurrentDebugLevel <= DeveloperModeController::MaxDebugLevel; } int DeveloperModeController::getDebugLevel() { return DeveloperModeController::CurrentDebugLevel; }
1
0.657612
1
0.657612
game-dev
MEDIA
0.537502
game-dev,desktop-app
0.592726
1
0.592726
DaFuqs/Spectrum
1,599
src/main/java/de/dafuqs/spectrum/entity/predicates/EggLayingWoolyPigPredicate.java
package de.dafuqs.spectrum.entity.predicates; import com.mojang.serialization.*; import com.mojang.serialization.codecs.*; import de.dafuqs.spectrum.entity.*; import de.dafuqs.spectrum.entity.entity.*; import net.minecraft.advancements.critereon.*; import net.minecraft.server.level.*; import net.minecraft.world.entity.*; import net.minecraft.world.item.*; import net.minecraft.world.phys.*; import org.jetbrains.annotations.*; import java.util.*; public record EggLayingWoolyPigPredicate(Optional<DyeColor> color, Optional<Boolean> hatless, Optional<Boolean> sheared) implements EntitySubPredicate { public static final MapCodec<EggLayingWoolyPigPredicate> CODEC = RecordCodecBuilder.mapCodec((instance) -> instance.group( DyeColor.CODEC.optionalFieldOf("color").forGetter(EggLayingWoolyPigPredicate::color), Codec.BOOL.optionalFieldOf("hatless").forGetter(EggLayingWoolyPigPredicate::hatless), Codec.BOOL.optionalFieldOf("sheared").forGetter(EggLayingWoolyPigPredicate::sheared) ).apply(instance, EggLayingWoolyPigPredicate::new)); @Override public boolean matches(Entity entity, ServerLevel world, @Nullable Vec3 pos) { if (!(entity instanceof EggLayingWoolyPigEntity wooly)) { return false; } else { return (this.color.isEmpty() || this.color.get() == wooly.getColor()) && (this.hatless.isEmpty() || this.hatless.get() == wooly.isHatless()) && (this.sheared.isEmpty() || this.sheared.get() == wooly.isSheared()); } } @Override public MapCodec<EggLayingWoolyPigPredicate> codec() { return SpectrumEntitySubPredicateTypes.EGG_LAYING_WOOLY_PIG; } }
1
0.763873
1
0.763873
game-dev
MEDIA
0.887429
game-dev,testing-qa
0.734761
1
0.734761
Haruma-K/UnityDebugSheet
22,861
Assets/UnityDebugSheet/Runtime/Core/Scripts/DefaultDebugPageBase.cs
using System; using System.Collections.Generic; using UnityDebugSheet.Runtime.Core.Scripts.DefaultImpl; using UnityDebugSheet.Runtime.Core.Scripts.DefaultImpl.CellParts; using UnityDebugSheet.Runtime.Core.Scripts.DefaultImpl.Cells; using UnityEngine; using UnityEngine.UI; namespace UnityDebugSheet.Runtime.Core.Scripts { public abstract class DefaultDebugPageBase : DebugPageBase { public int AddLabel(string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, int priority = 0) { var useSubTextOrIcon = !string.IsNullOrEmpty(subText) || icon != null; var labelCellModel = new LabelCellModel(useSubTextOrIcon); labelCellModel.CellTexts.Text = text; labelCellModel.CellTexts.SubText = subText; if (textColor != null) labelCellModel.CellTexts.TextColor = textColor.Value; if (subTextColor != null) labelCellModel.CellTexts.SubTextColor = subTextColor.Value; labelCellModel.Icon.Sprite = icon; if (iconColor != null) labelCellModel.Icon.Color = iconColor.Value; return AddLabel(labelCellModel, priority); } public int AddLabel(LabelCellModel model, int priority = 0) { return AddItem(AssetKeys.LabelCell, model, priority); } public int AddButton(string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, bool showAllow = false, Action clicked = null, int priority = 0) { var useSubTextOrIcon = !string.IsNullOrEmpty(subText) || icon != null; var buttonCellModel = new ButtonCellModel(useSubTextOrIcon); buttonCellModel.CellTexts.Text = text; buttonCellModel.CellTexts.SubText = subText; if (textColor != null) buttonCellModel.CellTexts.TextColor = textColor.Value; if (subTextColor != null) buttonCellModel.CellTexts.SubTextColor = subTextColor.Value; buttonCellModel.Icon.Sprite = icon; if (iconColor != null) buttonCellModel.Icon.Color = iconColor.Value; buttonCellModel.ShowArrow = showAllow; if (clicked != null) buttonCellModel.Clicked += clicked; return AddButton(buttonCellModel, priority); } public int AddButton(ButtonCellModel model, int priority = 0) { return AddItem(AssetKeys.ButtonCell, model, priority); } public int AddButtonCollection(ButtonCollectionCellModel model, int priority = 0) { return AddItem(AssetKeys.ButtonCollectionCell, model, priority); } public int AddSwitch(bool value, string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, Action<bool> valueChanged = null, int priority = 0) { var useSubTextOrIcon = !string.IsNullOrEmpty(subText) || icon != null; var switchCellModel = new SwitchCellModel(useSubTextOrIcon); switchCellModel.CellTexts.Text = text; switchCellModel.CellTexts.SubText = subText; if (textColor != null) switchCellModel.CellTexts.TextColor = textColor.Value; if (subTextColor != null) switchCellModel.CellTexts.SubTextColor = subTextColor.Value; switchCellModel.Icon.Sprite = icon; if (iconColor != null) switchCellModel.Icon.Color = iconColor.Value; switchCellModel.Value = value; if (valueChanged != null) switchCellModel.ValueChanged += valueChanged; return AddSwitch(switchCellModel, priority); } public int AddSwitch(SwitchCellModel model, int priority = 0) { return AddItem(AssetKeys.SwitchCell, model, priority); } public int AddInputField(string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, string value = null, string placeholder = null, InputField.ContentType contentType = InputField.ContentType.Standard, Action<string> valueChanged = null, int priority = 0) { var useSubTextOrIcon = !string.IsNullOrEmpty(subText) || icon != null; var inputFieldCellModel = new InputFieldCellModel(useSubTextOrIcon); inputFieldCellModel.CellTexts.Text = text; inputFieldCellModel.CellTexts.SubText = subText; if (textColor != null) inputFieldCellModel.CellTexts.TextColor = textColor.Value; if (subTextColor != null) inputFieldCellModel.CellTexts.SubTextColor = subTextColor.Value; inputFieldCellModel.Icon.Sprite = icon; if (iconColor != null) inputFieldCellModel.Icon.Color = iconColor.Value; inputFieldCellModel.Placeholder = placeholder; inputFieldCellModel.Value = value; inputFieldCellModel.ContentType = contentType; if (valueChanged != null) inputFieldCellModel.ValueChanged += valueChanged; return AddInputField(inputFieldCellModel, priority); } public int AddInputField(InputFieldCellModel model, int priority = 0) { return AddItem(AssetKeys.InputFieldCell, model, priority); } public int AddSlider(float value, float minValue, float maxValue, string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, bool showValueText = true, string valueTextFormat = null, bool wholeNumbers = false, Action<float> valueChanged = null, int priority = 0) { var useSubTextOrIcon = !string.IsNullOrEmpty(subText) || icon != null; var sliderCellModel = new SliderCellModel(useSubTextOrIcon, minValue, maxValue); sliderCellModel.CellTexts.Text = text; sliderCellModel.CellTexts.SubText = subText; if (textColor != null) sliderCellModel.CellTexts.TextColor = textColor.Value; if (subTextColor != null) sliderCellModel.CellTexts.SubTextColor = subTextColor.Value; sliderCellModel.Icon.Sprite = icon; if (iconColor != null) sliderCellModel.Icon.Color = iconColor.Value; sliderCellModel.Value = value; sliderCellModel.ShowValueText = showValueText; sliderCellModel.ValueTextFormat = valueTextFormat; sliderCellModel.WholeNumbers = wholeNumbers; if (valueChanged != null) sliderCellModel.ValueChanged += valueChanged; return AddSlider(sliderCellModel, priority); } public int AddSlider(SliderCellModel model, int priority = 0) { return AddItem(AssetKeys.SliderCell, model, priority); } public int AddPicker(IEnumerable<string> options, int activeOptionIndex, string text, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, Action<int> activeOptionChanged = null, Action clicked = null, Action confirmed = null, int priority = 0) { var pickerCellModel = new PickerCellModel(); pickerCellModel.Text = text; if (textColor != null) pickerCellModel.TextColor = textColor.Value; if (subTextColor != null) pickerCellModel.SubTextColor = subTextColor.Value; pickerCellModel.Icon.Sprite = icon; if (iconColor != null) pickerCellModel.Icon.Color = iconColor.Value; pickerCellModel.SetOptions(options, activeOptionIndex); if (activeOptionChanged != null) pickerCellModel.ActiveOptionChanged += activeOptionChanged; if (clicked != null) pickerCellModel.Clicked += clicked; if (confirmed != null) pickerCellModel.Confirmed += confirmed; return AddPicker(pickerCellModel, priority); } public int AddPicker(PickerCellModel model, int priority = 0) { return AddItem(AssetKeys.PickerCell, model, priority); } public int AddEnumPicker(Enum activeValue, string text, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, Action<Enum> activeValueChanged = null, Action clicked = null, Action confirmed = null, int priority = 0) { var pickerCellModel = new EnumPickerCellModel(activeValue); pickerCellModel.Text = text; if (textColor != null) pickerCellModel.TextColor = textColor.Value; if (subTextColor != null) pickerCellModel.SubTextColor = subTextColor.Value; pickerCellModel.Icon.Sprite = icon; if (iconColor != null) pickerCellModel.Icon.Color = iconColor.Value; if (activeValueChanged != null) pickerCellModel.ActiveValueChanged += activeValueChanged; if (clicked != null) pickerCellModel.Clicked += clicked; if (confirmed != null) pickerCellModel.Confirmed += confirmed; return AddEnumPicker(pickerCellModel, priority); } public int AddEnumPicker(EnumPickerCellModel model, int priority = 0) { return AddItem(AssetKeys.EnumPickerCell, model, priority); } public int AddMultiPicker(IEnumerable<string> options, IEnumerable<int> activeOptionIndices, string text, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, Action<int, bool> optionStateChanged = null, Action clicked = null, Action confirmed = null, int priority = 0) { var pickerCellModel = new MultiPickerCellModel(); pickerCellModel.Text = text; if (textColor != null) pickerCellModel.TextColor = textColor.Value; if (subTextColor != null) pickerCellModel.SubTextColor = subTextColor.Value; pickerCellModel.Icon.Sprite = icon; if (iconColor != null) pickerCellModel.Icon.Color = iconColor.Value; pickerCellModel.SetOptions(options, activeOptionIndices); if (optionStateChanged != null) pickerCellModel.OptionStateChanged += optionStateChanged; if (clicked != null) pickerCellModel.Clicked += clicked; if (confirmed != null) pickerCellModel.Confirmed += confirmed; return AddMultiPicker(pickerCellModel, priority); } public int AddMultiPicker(MultiPickerCellModel model, int priority = 0) { return AddItem(AssetKeys.MultiPickerCell, model, priority); } public int AddEnumMultiPicker(Enum activeValue, string text, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, Action<Enum> activeValueChanged = null, Action clicked = null, Action confirmed = null, int priority = 0) { var pickerCellModel = new EnumMultiPickerCellModel(activeValue); pickerCellModel.Text = text; if (textColor != null) pickerCellModel.TextColor = textColor.Value; if (subTextColor != null) pickerCellModel.SubTextColor = subTextColor.Value; pickerCellModel.Icon.Sprite = icon; if (iconColor != null) pickerCellModel.Icon.Color = iconColor.Value; if (activeValueChanged != null) pickerCellModel.ActiveValueChanged += activeValueChanged; if (clicked != null) pickerCellModel.Clicked += clicked; if (confirmed != null) pickerCellModel.Confirmed += confirmed; return AddEnumMultiPicker(pickerCellModel, priority); } public int AddEnumMultiPicker(EnumMultiPickerCellModel model, int priority = 0) { return AddItem(AssetKeys.EnumMultiPickerCell, model, priority); } public int AddPickerOption(bool isOn, string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, Action<bool> toggled = null, int priority = 0) { var useSubTextOrIcon = !string.IsNullOrEmpty(subText) || icon != null; var pickerOptionModel = new PickerOptionCellModel(useSubTextOrIcon); pickerOptionModel.IsOn = isOn; pickerOptionModel.CellTexts.Text = text; pickerOptionModel.CellTexts.SubText = subText; if (textColor != null) pickerOptionModel.CellTexts.TextColor = textColor.Value; if (subTextColor != null) pickerOptionModel.CellTexts.SubTextColor = subTextColor.Value; pickerOptionModel.Icon.Sprite = icon; if (iconColor != null) pickerOptionModel.Icon.Color = iconColor.Value; if (toggled != null) pickerOptionModel.Toggled += toggled; return AddPickerOption(pickerOptionModel, priority); } public int AddSearchField(string placeholder = null, Action<string> valueChanged = null, Action<string> submitted = null, int priority = 0) { var searchFieldCellModel = new SearchFieldCellModel(); if (!string.IsNullOrEmpty(placeholder)) searchFieldCellModel.Placeholder = placeholder; if (valueChanged != null) searchFieldCellModel.ValueChanged += valueChanged; if (submitted != null) searchFieldCellModel.Submitted += submitted; return AddSearchField(searchFieldCellModel, priority); } public int AddSearchField(SearchFieldCellModel model, int priority = 0) { return AddItem(AssetKeys.SearchFieldCell, model, priority); } public int AddPickerOption(PickerOptionCellModel model, int priority = 0) { return AddItem(AssetKeys.PickerOption, model, priority); } public int AddPageLinkButton(string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, string titleOverride = null, Action<(string pageId, DebugPage page)> onLoad = null, string pageId = null, int priority = 0) { return AddPageLinkButton<DebugPage>(text, subText, textColor, subTextColor, icon, iconColor, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton(Type pageType, string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, string titleOverride = null, Action<(string pageId, DebugPageBase page)> onLoad = null, string pageId = null, int priority = 0) { var textModel = new CellTextsModel(); textModel.Text = text; textModel.SubText = subText; if (textColor != null) textModel.TextColor = textColor.Value; if (subTextColor != null) textModel.SubTextColor = subTextColor.Value; var iconModel = new CellIconModel(); iconModel.Sprite = icon; if (iconColor != null) iconModel.Color = iconColor.Value; return AddPageLinkButton(pageType, textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton<TPage>(string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, string titleOverride = null, Action<(string pageId, TPage page)> onLoad = null, string pageId = null, int priority = 0) where TPage : DebugPageBase { var textModel = new CellTextsModel(); textModel.Text = text; textModel.SubText = subText; if (textColor != null) textModel.TextColor = textColor.Value; if (subTextColor != null) textModel.SubTextColor = subTextColor.Value; var iconModel = new CellIconModel(); iconModel.Sprite = icon; if (iconColor != null) iconModel.Color = iconColor.Value; return AddPageLinkButton(textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton(CellTextsModel textModel, CellIconModel iconModel = null, string titleOverride = null, Action<(string pageId, DebugPage page)> onLoad = null, string pageId = null, int priority = 0) { return AddPageLinkButton<DebugPage>(textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton(Type pageType, CellTextsModel textModel, CellIconModel iconModel = null, string titleOverride = null, Action<(string pageId, DebugPageBase page)> onLoad = null, string pageId = null, int priority = 0) { return AddPageLinkButton(pageType, null, textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton<TPage>(CellTextsModel textModel, CellIconModel iconModel = null, string titleOverride = null, Action<(string pageId, TPage page)> onLoad = null, string pageId = null, int priority = 0) where TPage : DebugPageBase { return AddPageLinkButton(null, textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton(Type pageType, DebugPageBase prefab, string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, string titleOverride = null, Action<(string pageId, DebugPageBase page)> onLoad = null, string pageId = null, int priority = 0) { var textModel = new CellTextsModel(); textModel.Text = text; textModel.SubText = subText; if (textColor != null) textModel.TextColor = textColor.Value; if (subTextColor != null) textModel.SubTextColor = subTextColor.Value; var iconModel = new CellIconModel(); iconModel.Sprite = icon; if (iconColor != null) iconModel.Color = iconColor.Value; return AddPageLinkButton(pageType, prefab, textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton<TPage>(TPage prefab, string text, string subText = null, Color? textColor = null, Color? subTextColor = null, Sprite icon = null, Color? iconColor = null, string titleOverride = null, Action<(string pageId, TPage page)> onLoad = null, string pageId = null, int priority = 0) where TPage : DebugPageBase { var textModel = new CellTextsModel(); textModel.Text = text; textModel.SubText = subText; if (textColor != null) textModel.TextColor = textColor.Value; if (subTextColor != null) textModel.SubTextColor = subTextColor.Value; var iconModel = new CellIconModel(); iconModel.Sprite = icon; if (iconColor != null) iconModel.Color = iconColor.Value; return AddPageLinkButton(prefab, textModel, iconModel, titleOverride, onLoad, pageId, priority); } public int AddPageLinkButton(Type pageType, DebugPageBase prefab, CellTextsModel textModel, CellIconModel iconModel = null, string titleOverride = null, Action<(string pageId, DebugPageBase page)> onLoad = null, string pageId = null, int priority = 0) { var useSubText = textModel != null && !string.IsNullOrEmpty(textModel.SubText); var useIcon = iconModel != null && iconModel.Sprite != null; var useSubTextOrIcon = useSubText || useIcon; var buttonModel = new PageLinkButtonCellModel(useSubTextOrIcon); if (textModel != null) { buttonModel.CellTexts.Text = textModel.Text; buttonModel.CellTexts.TextColor = textModel.TextColor; buttonModel.CellTexts.SubText = textModel.SubText; buttonModel.CellTexts.SubTextColor = textModel.SubTextColor; } else { buttonModel.CellTexts.Text = pageType.Name; } if (iconModel != null) { buttonModel.Icon.Sprite = iconModel.Sprite; buttonModel.Icon.Color = iconModel.Color; } buttonModel.PageType = pageType; buttonModel.Prefab = prefab; buttonModel.PageTitleOverride = titleOverride; buttonModel.OnLoad += onLoad; buttonModel.ShowArrow = true; buttonModel.PageId = pageId; return AddPageLinkButton(buttonModel, priority); } public int AddPageLinkButton<TPage>(TPage prefab, CellTextsModel textModel, CellIconModel iconModel = null, string titleOverride = null, Action<(string pageId, TPage page)> onLoad = null, string pageId = null, int priority = 0) where TPage : DebugPageBase { var useSubText = textModel != null && !string.IsNullOrEmpty(textModel.SubText); var useIcon = iconModel != null && iconModel.Sprite != null; var useSubTextOrIcon = useSubText || useIcon; var buttonModel = new PageLinkButtonCellModel(useSubTextOrIcon); if (textModel != null) { buttonModel.CellTexts.Text = textModel.Text; buttonModel.CellTexts.TextColor = textModel.TextColor; buttonModel.CellTexts.SubText = textModel.SubText; buttonModel.CellTexts.SubTextColor = textModel.SubTextColor; } else { buttonModel.CellTexts.Text = nameof(TPage); } if (iconModel != null) { buttonModel.Icon.Sprite = iconModel.Sprite; buttonModel.Icon.Color = iconModel.Color; } buttonModel.PageType = typeof(TPage); buttonModel.Prefab = prefab; buttonModel.PageTitleOverride = titleOverride; buttonModel.OnLoad += x => onLoad?.Invoke((x.pageId, (TPage)x.page)); buttonModel.ShowArrow = true; buttonModel.PageId = pageId; return AddPageLinkButton(buttonModel, priority); } public int AddPageLinkButton(PageLinkButtonCellModel model, int priority = 0) { return AddItem(AssetKeys.PageLinkButtonCell, model, priority); } } }
1
0.784722
1
0.784722
game-dev
MEDIA
0.3695
game-dev
0.895994
1
0.895994
ronancpl/HeavenMS
4,672
tools/MapleCashCosmeticsFetcher/src/provider/MapleDataTool.java
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package provider; import java.awt.Point; import java.awt.image.BufferedImage; import provider.wz.MapleDataType; public class MapleDataTool { public static String getString(MapleData data) { return ((String) data.getData()); } public static String getString(MapleData data, String def) { if (data == null || data.getData() == null) { return def; } else { return ((String) data.getData()); } } public static String getString(String path, MapleData data) { return getString(data.getChildByPath(path)); } public static String getString(String path, MapleData data, String def) { return getString(data.getChildByPath(path), def); } public static double getDouble(MapleData data) { return ((Double) data.getData()).doubleValue(); } public static float getFloat(MapleData data) { return ((Float) data.getData()).floatValue(); } public static int getInt(MapleData data) { if (data == null || data.getData() == null) { return 0;// DEF? } return ((Integer) data.getData()).intValue(); } public static int getInt(String path, MapleData data) { return getInt(data.getChildByPath(path)); } public static int getIntConvert(MapleData data) { if (data.getType() == MapleDataType.STRING) { return Integer.parseInt(getString(data)); } else { return getInt(data); } } public static int getIntConvert(String path, MapleData data) { MapleData d = data.getChildByPath(path); if (d.getType() == MapleDataType.STRING) { return Integer.parseInt(getString(d)); } else { return getInt(d); } } public static int getInt(MapleData data, int def) { if (data == null || data.getData() == null) { return def; } else if (data.getType() == MapleDataType.STRING) { return Integer.parseInt(getString(data)); } else { return ((Integer) data.getData()).intValue(); } } public static int getInt(String path, MapleData data, int def) { return getInt(data.getChildByPath(path), def); } public static int getIntConvert(String path, MapleData data, int def) { MapleData d = data.getChildByPath(path); if (d == null) { return def; } if (d.getType() == MapleDataType.STRING) { try { return Integer.parseInt(getString(d)); } catch (NumberFormatException nfe) { nfe.printStackTrace(); return def; } } else { return getInt(d, def); } } public static BufferedImage getImage(MapleData data) { return ((MapleCanvas) data.getData()).getImage(); } public static Point getPoint(MapleData data) { return ((Point) data.getData()); } public static Point getPoint(String path, MapleData data) { return getPoint(data.getChildByPath(path)); } public static Point getPoint(String path, MapleData data, Point def) { final MapleData pointData = data.getChildByPath(path); if (pointData == null) { return def; } return getPoint(pointData); } public static String getFullDataPath(MapleData data) { String path = ""; MapleDataEntity myData = data; while (myData != null) { path = myData.getName() + "/" + path; myData = myData.getParent(); } return path.substring(0, path.length() - 1); } }
1
0.816566
1
0.816566
game-dev
MEDIA
0.183659
game-dev
0.829193
1
0.829193
leggedrobotics/se2_navigation
2,901
pure_pursuit_core/src/AdaptiveVelocityController.cpp
/* * AdaptiveVelocityController.cpp * * Created on: Apr 9, 2020 * Author: jelavice */ #include "pure_pursuit_core/velocity_control/AdaptiveVelocityController.hpp" #include <iostream> namespace pure_pursuit { std::string AdaptiveVelocityControllerParameters::asString() const { std::string ret; ret += "desired velocity (m/s): " + std::to_string(desiredVelocity_) + "\n"; ret += "distance to goal when braking starts (m): " + std::to_string(distanceToGoalWhenBrakingStarts_) + "\n"; ret += "max velocity rate of change (m/s2): " + std::to_string(maxVelocityRateOfChange_) + "\n"; ret += "timestep (sec): " + std::to_string(timestep_); return ret; } bool AdaptiveVelocityController::computeVelocity() { double referenceVelocity = 0.0; switch (drivingDirection_) { case DrivingDirection::FWD: { referenceVelocity = parameters_.desiredVelocity_; break; } case DrivingDirection::BCK: { referenceVelocity = -parameters_.desiredVelocity_; break; } } // should be path integral strictly speaking const double distanceToGoal = (currentRobotState_.pose_.position_ - currentPathSegment_.point_.back().position_).norm(); const double dWhenBrakingStarts = parameters_.distanceToGoalWhenBrakingStarts_; if (distanceToGoal <= dWhenBrakingStarts) { const double slope = parameters_.desiredVelocity_ / dWhenBrakingStarts; const double referenceVelocityMagnitude = slope * distanceToGoal; const double direction = sgn(referenceVelocity); referenceVelocity = direction * referenceVelocityMagnitude; } desiredLongitudinalVelocity_ = rateLimiter_.limitRateOfChange(referenceVelocity); return true; } void AdaptiveVelocityController::setParameters(const AdaptiveVelocityControllerParameters& parameters) { if (parameters.maxVelocityRateOfChange_ < 0) { throw std::runtime_error("maxVelocityRateOfChange_ is less than 0."); } if (parameters.timestep_ < 0) { throw std::runtime_error("timestep_ is less than 0."); } if (parameters.distanceToGoalWhenBrakingStarts_ < 0) { throw std::runtime_error("distanceToGoalWhenBrakingStarts_ is less than 0."); } parameters_ = parameters; rateLimiter_.setFallingRate(-parameters.maxVelocityRateOfChange_); rateLimiter_.setRisingRate(parameters.maxVelocityRateOfChange_); rateLimiter_.setTimestep(parameters.timestep_); } void AdaptiveVelocityController::updateCurrentPathSegment(const PathSegment& pathSegment) { BASE::updateCurrentPathSegment(pathSegment); rateLimiter_.reset(0.0); } std::unique_ptr<LongitudinalVelocityController> createAdaptiveVelocityController(const AdaptiveVelocityControllerParameters& parameters) { std::unique_ptr<AdaptiveVelocityController> controller = std::make_unique<AdaptiveVelocityController>(); controller->setParameters(parameters); return std::move(controller); } } /* namespace pure_pursuit */
1
0.819349
1
0.819349
game-dev
MEDIA
0.207873
game-dev
0.686078
1
0.686078
DeNA/DeClang
5,279
llvm/include/llvm/CodeGen/CommandFlags.h
//===-- CommandFlags.h - Command Line Flags Interface -----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains codegen-specific flags that are shared between different // command line tools. The tools "llc" and "opt" both use this file to prevent // flag duplication. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_COMMANDFLAGS_H #define LLVM_CODEGEN_COMMANDFLAGS_H #include "llvm/ADT/FloatingPointMode.h" #include "llvm/Support/CodeGen.h" #include "llvm/Target/TargetOptions.h" #include <optional> #include <string> #include <vector> namespace llvm { class Module; class AttrBuilder; class Function; class Triple; class TargetMachine; namespace codegen { std::string getMArch(); std::string getMCPU(); std::vector<std::string> getMAttrs(); Reloc::Model getRelocModel(); std::optional<Reloc::Model> getExplicitRelocModel(); ThreadModel::Model getThreadModel(); CodeModel::Model getCodeModel(); std::optional<CodeModel::Model> getExplicitCodeModel(); uint64_t getLargeDataThreshold(); std::optional<uint64_t> getExplicitLargeDataThreshold(); llvm::ExceptionHandling getExceptionModel(); std::optional<CodeGenFileType> getExplicitFileType(); CodeGenFileType getFileType(); FramePointerKind getFramePointerUsage(); bool getEnableUnsafeFPMath(); bool getEnableNoInfsFPMath(); bool getEnableNoNaNsFPMath(); bool getEnableNoSignedZerosFPMath(); bool getEnableApproxFuncFPMath(); bool getEnableNoTrappingFPMath(); DenormalMode::DenormalModeKind getDenormalFPMath(); DenormalMode::DenormalModeKind getDenormalFP32Math(); bool getEnableHonorSignDependentRoundingFPMath(); llvm::FloatABI::ABIType getFloatABIForCalls(); llvm::FPOpFusion::FPOpFusionMode getFuseFPOps(); SwiftAsyncFramePointerMode getSwiftAsyncFramePointer(); bool getDontPlaceZerosInBSS(); bool getEnableGuaranteedTailCallOpt(); bool getEnableAIXExtendedAltivecABI(); bool getDisableTailCalls(); bool getStackSymbolOrdering(); bool getStackRealign(); std::string getTrapFuncName(); bool getUseCtors(); bool getDisableIntegratedAS(); bool getDataSections(); std::optional<bool> getExplicitDataSections(); bool getFunctionSections(); std::optional<bool> getExplicitFunctionSections(); bool getIgnoreXCOFFVisibility(); bool getXCOFFTracebackTable(); std::string getBBSections(); unsigned getTLSSize(); bool getEmulatedTLS(); std::optional<bool> getExplicitEmulatedTLS(); bool getEnableTLSDESC(); std::optional<bool> getExplicitEnableTLSDESC(); bool getUniqueSectionNames(); bool getUniqueBasicBlockSectionNames(); bool getSeparateNamedSections(); llvm::EABI getEABIVersion(); llvm::DebuggerKind getDebuggerTuningOpt(); bool getEnableStackSizeSection(); bool getEnableAddrsig(); bool getEmitCallSiteInfo(); bool getEnableMachineFunctionSplitter(); bool getEnableDebugEntryValues(); bool getValueTrackingVariableLocations(); std::optional<bool> getExplicitValueTrackingVariableLocations(); bool getForceDwarfFrameSection(); bool getXRayFunctionIndex(); bool getDebugStrictDwarf(); unsigned getAlignLoops(); bool getJMCInstrument(); bool getXCOFFReadOnlyPointers(); /// Create this object with static storage to register codegen-related command /// line options. struct RegisterCodeGenFlags { RegisterCodeGenFlags(); }; bool getEnableBBAddrMap(); llvm::BasicBlockSection getBBSectionsMode(llvm::TargetOptions &Options); /// Common utility function tightly tied to the options listed here. Initializes /// a TargetOptions object with CodeGen flags and returns it. /// \p TheTriple is used to determine the default value for options if /// options are not explicitly specified. If those triple dependant options /// value do not have effect for your component, a default Triple() could be /// passed in. TargetOptions InitTargetOptionsFromCodeGenFlags(const llvm::Triple &TheTriple); std::string getCPUStr(); std::string getFeaturesStr(); std::vector<std::string> getFeatureList(); void renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val); /// Set function attributes of function \p F based on CPU, Features, and command /// line flags. void setFunctionAttributes(StringRef CPU, StringRef Features, Function &F); /// Set function attributes of functions in Module M based on CPU, /// Features, and command line flags. void setFunctionAttributes(StringRef CPU, StringRef Features, Module &M); /// Should value-tracking variable locations / instruction referencing be /// enabled by default for this triple? bool getDefaultValueTrackingVariableLocations(const llvm::Triple &T); /// Creates a TargetMachine instance with the options defined on the command /// line. This can be used for tools that do not need further customization of /// the TargetOptions. Expected<std::unique_ptr<TargetMachine>> createTargetMachineForTriple( StringRef TargetTriple, CodeGenOptLevel OptLevel = CodeGenOptLevel::Default); } // namespace codegen } // namespace llvm #endif // LLVM_CODEGEN_COMMANDFLAGS_H
1
0.944056
1
0.944056
game-dev
MEDIA
0.306796
game-dev
0.742677
1
0.742677
magefree/mage
3,104
Mage.Sets/src/mage/cards/i/InquisitorsFlail.java
package mage.cards.i; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.keyword.EquipAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.SubType; import mage.game.Game; import mage.game.events.DamageEvent; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.util.CardUtil; import java.util.UUID; /** * @author nantuko */ public final class InquisitorsFlail extends CardImpl { public InquisitorsFlail(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{2}"); this.subtype.add(SubType.EQUIPMENT); // If equipped creature would deal combat damage, it deals double that damage instead. // If another creature would deal combat damage to equipped creature, it deals double that damage to equipped creature instead. this.addAbility(new SimpleStaticAbility(new InquisitorsFlailEffect())); // Equip {2} this.addAbility(new EquipAbility(2, false)); } private InquisitorsFlail(final InquisitorsFlail card) { super(card); } @Override public InquisitorsFlail copy() { return new InquisitorsFlail(this); } } class InquisitorsFlailEffect extends ReplacementEffectImpl { InquisitorsFlailEffect() { super(Duration.WhileOnBattlefield, Outcome.Damage); staticText = "If equipped creature would deal combat damage, it deals double that damage instead.<br>" + "If another creature would deal combat damage to equipped creature, it deals double that damage to equipped creature instead"; } private InquisitorsFlailEffect(final InquisitorsFlailEffect effect) { super(effect); } @Override public InquisitorsFlailEffect copy() { return new InquisitorsFlailEffect(this); } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DAMAGE_PERMANENT || event.getType() == GameEvent.EventType.DAMAGE_PLAYER; } @Override public boolean applies(GameEvent event, Ability source, Game game) { if (((DamageEvent) event).isCombatDamage()) { Permanent equipment = game.getPermanent(source.getSourceId()); if (equipment != null && equipment.getAttachedTo() != null) { UUID attachedTo = equipment.getAttachedTo(); if (event.getSourceId().equals(attachedTo)) { return true; } else if (event.getTargetId().equals(attachedTo)) { return true; } } } return false; } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { event.setAmount(CardUtil.overflowMultiply(event.getAmount(), 2)); return false; } }
1
0.890225
1
0.890225
game-dev
MEDIA
0.98205
game-dev
0.916531
1
0.916531
lllyasviel/YGOProUnity_V2
6,178
Assets/NGUI/Scripts/Interaction/TypewriterEffect.cs
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2015 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using System.Text; using System.Collections.Generic; /// <summary> /// This script is able to fill in the label's text gradually, giving the effect of someone typing or fading in the content over time. /// </summary> [RequireComponent(typeof(UILabel))] [AddComponentMenu("NGUI/Interaction/Typewriter Effect")] public class TypewriterEffect : MonoBehaviour { static public TypewriterEffect current; struct FadeEntry { public int index; public string text; public float alpha; } /// <summary> /// How many characters will be printed per second. /// </summary> public int charsPerSecond = 20; /// <summary> /// How long it takes for each character to fade in. /// </summary> public float fadeInTime = 0f; /// <summary> /// How long to pause when a period is encountered (in seconds). /// </summary> public float delayOnPeriod = 0f; /// <summary> /// How long to pause when a new line character is encountered (in seconds). /// </summary> public float delayOnNewLine = 0f; /// <summary> /// If a scroll view is specified, its UpdatePosition() function will be called every time the text is updated. /// </summary> public UIScrollView scrollView; /// <summary> /// If set to 'true', the label's dimensions will be that of a fully faded-in content. /// </summary> public bool keepFullDimensions = false; /// <summary> /// Event delegate triggered when the typewriter effect finishes. /// </summary> public List<EventDelegate> onFinished = new List<EventDelegate>(); UILabel mLabel; string mFullText = ""; int mCurrentOffset = 0; float mNextChar = 0f; bool mReset = true; bool mActive = false; BetterList<FadeEntry> mFade = new BetterList<FadeEntry>(); /// <summary> /// Whether the typewriter effect is currently active or not. /// </summary> public bool isActive { get { return mActive; } } /// <summary> /// Reset the typewriter effect to the beginning of the label. /// </summary> public void ResetToBeginning () { Finish(); mReset = true; mActive = true; mNextChar = 0f; mCurrentOffset = 0; Update(); } /// <summary> /// Finish the typewriter operation and show all the text right away. /// </summary> public void Finish () { if (mActive) { mActive = false; if (!mReset) { mCurrentOffset = mFullText.Length; mFade.Clear(); mLabel.text = mFullText; } if (keepFullDimensions && scrollView != null) scrollView.UpdatePosition(); current = this; EventDelegate.Execute(onFinished); current = null; } } void OnEnable () { mReset = true; mActive = true; } void OnDisable () { Finish(); } void Update () { if (!mActive) return; if (mReset) { mCurrentOffset = 0; mReset = false; mLabel = GetComponent<UILabel>(); mFullText = mLabel.processedText; mFade.Clear(); if (keepFullDimensions && scrollView != null) scrollView.UpdatePosition(); } if (string.IsNullOrEmpty(mFullText)) return; while (mCurrentOffset < mFullText.Length && mNextChar <= RealTime.time) { int lastOffset = mCurrentOffset; charsPerSecond = Mathf.Max(1, charsPerSecond); // Automatically skip all symbols if (mLabel.supportEncoding) while (NGUIText.ParseSymbol(mFullText, ref mCurrentOffset)) { } ++mCurrentOffset; // Reached the end? We're done. if (mCurrentOffset > mFullText.Length) break; // Periods and end-of-line characters should pause for a longer time. float delay = 1f / charsPerSecond; char c = (lastOffset < mFullText.Length) ? mFullText[lastOffset] : '\n'; if (c == '\n') { delay += delayOnNewLine; } else if (lastOffset + 1 == mFullText.Length || mFullText[lastOffset + 1] <= ' ') { if (c == '.') { if (lastOffset + 2 < mFullText.Length && mFullText[lastOffset + 1] == '.' && mFullText[lastOffset + 2] == '.') { delay += delayOnPeriod * 3f; lastOffset += 2; } else delay += delayOnPeriod; } else if (c == '!' || c == '?') { delay += delayOnPeriod; } } if (mNextChar == 0f) { mNextChar = RealTime.time + delay; } else mNextChar += delay; if (fadeInTime != 0f) { // There is smooth fading involved FadeEntry fe = new FadeEntry(); fe.index = lastOffset; fe.alpha = 0f; fe.text = mFullText.Substring(lastOffset, mCurrentOffset - lastOffset); mFade.Add(fe); } else { // No smooth fading necessary mLabel.text = keepFullDimensions ? mFullText.Substring(0, mCurrentOffset) + "[00]" + mFullText.Substring(mCurrentOffset) : mFullText.Substring(0, mCurrentOffset); // If a scroll view was specified, update its position if (!keepFullDimensions && scrollView != null) scrollView.UpdatePosition(); } } // Alpha-based fading if (mCurrentOffset >= mFullText.Length) { mLabel.text = mFullText; current = this; EventDelegate.Execute(onFinished); current = null; mActive = false; } else if (mFade.size != 0) { for (int i = 0; i < mFade.size; ) { FadeEntry fe = mFade[i]; fe.alpha += RealTime.deltaTime / fadeInTime; if (fe.alpha < 1f) { mFade[i] = fe; ++i; } else mFade.RemoveAt(i); } if (mFade.size == 0) { if (keepFullDimensions) { mLabel.text = mFullText.Substring(0, mCurrentOffset) + "[00]" + mFullText.Substring(mCurrentOffset); } else mLabel.text = mFullText.Substring(0, mCurrentOffset); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mFade.size; ++i) { FadeEntry fe = mFade[i]; if (i == 0) { sb.Append(mFullText.Substring(0, fe.index)); } sb.Append('['); sb.Append(NGUIText.EncodeAlpha(fe.alpha)); sb.Append(']'); sb.Append(fe.text); } if (keepFullDimensions) { sb.Append("[00]"); sb.Append(mFullText.Substring(mCurrentOffset)); } mLabel.text = sb.ToString(); } } } }
1
0.736211
1
0.736211
game-dev
MEDIA
0.355732
game-dev
0.985842
1
0.985842
LeagueAkari/LeagueAkari
1,270
src/renderer/src-cd-timer-window/shards/index.ts
import { createManager } from '@renderer-shared/shards' import { AppCommonRenderer } from '@renderer-shared/shards/app-common' import { AkariIpcRenderer } from '@renderer-shared/shards/ipc' import { LeagueClientRenderer, LeagueClientRendererConfig } from '@renderer-shared/shards/league-client' import { LoggerRenderer } from '@renderer-shared/shards/logger' import { PiniaMobxUtilsRenderer } from '@renderer-shared/shards/pinia-mobx-utils' import { SettingUtilsRenderer } from '@renderer-shared/shards/setting-utils' import { SetupInAppScopeRenderer } from '@renderer-shared/shards/setup-in-app-scope' import { WindowManagerRenderer } from '@renderer-shared/shards/window-manager' const manager = createManager() manager.use(AkariIpcRenderer) manager.use(AppCommonRenderer) manager.use(LeagueClientRenderer, { // for better performance subscribeState: { gameData: true, gameflow: true, summoner: true, matchmaking: false, lobby: false, login: false, champSelect: false, chat: false, honor: false } } as LeagueClientRendererConfig) manager.use(LoggerRenderer) manager.use(PiniaMobxUtilsRenderer) manager.use(SettingUtilsRenderer) manager.use(SetupInAppScopeRenderer) manager.use(WindowManagerRenderer) export { manager }
1
0.597852
1
0.597852
game-dev
MEDIA
0.58819
game-dev
0.856501
1
0.856501
CCBlueX/LiquidBounce
7,977
src/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/scaffold/ScaffoldMovementPlanner.kt
/* * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce) * * Copyright (c) 2015 - 2025 CCBlueX * * LiquidBounce 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. * * LiquidBounce 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 LiquidBounce. If not, see <https://www.gnu.org/licenses/>. */ package net.ccbluex.liquidbounce.features.module.modules.world.scaffold import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug import net.ccbluex.liquidbounce.render.engine.type.Color4b import net.ccbluex.liquidbounce.utils.block.getState import net.ccbluex.liquidbounce.utils.block.targetfinding.BlockPlacementTarget import net.ccbluex.liquidbounce.utils.client.player import net.ccbluex.liquidbounce.utils.client.world import net.ccbluex.liquidbounce.utils.entity.getMovementDirectionOfInput import net.ccbluex.liquidbounce.utils.math.geometry.Line import net.ccbluex.liquidbounce.utils.math.toBlockPos import net.ccbluex.liquidbounce.utils.math.toVec3d import net.ccbluex.liquidbounce.utils.movement.DirectionalInput import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Box import net.minecraft.util.math.MathHelper import net.minecraft.util.math.Vec3d import kotlin.math.* object ScaffoldMovementPlanner { private const val MAX_LAST_PLACE_BLOCKS: Int = 4 private val lastPlacedBlocks = ArrayDeque<BlockPos>(MAX_LAST_PLACE_BLOCKS) private var lastPosition: BlockPos? = null /** * When using scaffold the player wants to follow the line and the scaffold should support them in doing so. * This function calculates this ideal line that the player should move on. */ fun getOptimalMovementLine(directionalInput: DirectionalInput): Line? { val direction = chooseDirection( getMovementDirectionOfInput( player.yaw, directionalInput, ), ) // Is this a good way to find the block center? val blockUnderPlayer = findBlockPlayerStandsOn() ?: return null val lastBlocksLine = fitLinesThroughLastPlacedBlocks() // If it makes sense to follow the last placed blocks, we lay the movement line through them, otherwise, we // don't consider them because the user probably wants to do something new val lineBaseBlock = if (lastBlocksLine != null && !divergesTooMuchFromDirection(lastBlocksLine, direction)) { lastBlocksLine.position } else { blockUnderPlayer.toVec3d() } // We try to make the player run on this line val optimalLine = Line(Vec3d(lineBaseBlock.x + 0.5, player.pos.y, lineBaseBlock.z + 0.5), direction) // Debug optimal line ModuleDebug.debugGeometry( ModuleScaffold, "optimalLine", ModuleDebug.DebuggedLine(optimalLine, if (lastBlocksLine == null) Color4b.RED else Color4b.GREEN) ) return optimalLine } private fun divergesTooMuchFromDirection(lastBlocksLine: Line, direction: Vec3d): Boolean { return acos(lastBlocksLine.direction.dotProduct(direction)).absoluteValue / Math.PI * 180 > 50.0 } /** * Tries to fit a line that goes through the last placed blocks. Currently only considers the last two. */ private fun fitLinesThroughLastPlacedBlocks(): Line? { // Take the last 2 blocks placed val lastPlacedBlocksToConsider = lastPlacedBlocks.subList( fromIndex = (lastPlacedBlocks.size - 2).coerceAtLeast(0), toIndex = (lastPlacedBlocks.size).coerceAtLeast(0), ) if (lastPlacedBlocksToConsider.size < 2) { return null } // Just debug stuff debugLastPlacedBlocks(lastPlacedBlocksToConsider) val avgPos = Vec3d.of(lastPlacedBlocksToConsider[0].add(lastPlacedBlocksToConsider[1])).multiply(0.5) val dir = Vec3d.of(lastPlacedBlocksToConsider[1].subtract(lastPlacedBlocksToConsider[0])).normalize() // Calculate the average direction of the last placed blocks return Line(avgPos, dir) } private fun debugLastPlacedBlocks(lastPlacedBlocksToConsider: MutableList<BlockPos>) { lastPlacedBlocksToConsider.forEachIndexed { idx, pos -> val alpha = ((1.0 - idx.toDouble() / lastPlacedBlocksToConsider.size.toDouble()) * 255.0).toInt() ModuleDebug.debugGeometry( ModuleScaffold, "lastPlacedBlock$idx", ModuleDebug.DebuggedBox(Box.from(pos.toVec3d()), Color4b(alpha, alpha, 255, 127)), ) } } /** * Find the block the player stands on. * It considers all blocks which the player's hitbox collides with and chooses one. If the player stands on the last * block this function returned, this block is preferred. */ private fun findBlockPlayerStandsOn(): BlockPos? { val offsetsToTry = arrayOf(0.301, 0.0, -0.301) // Contains the blocks which the player is currently supported by val candidates = mutableListOf<BlockPos>() for (xOffset in offsetsToTry) { for (zOffset in offsetsToTry) { val playerPos = player.pos.add(xOffset, -1.0, zOffset).toBlockPos() val isEmpty = playerPos.getState()?.getCollisionShape(world, BlockPos.ORIGIN)?.isEmpty ?: true if (!isEmpty) { candidates.add(playerPos) } } } // We want to keep the direction of the scaffold this.lastPlacedBlocks.lastOrNull()?.let { lastPlacedBlock -> if (lastPlacedBlock in candidates) { return lastPlacedBlock } } // Stabilize the heuristic if (lastPosition in candidates) { return lastPosition } // We have no reason to prefer a candidate so just pick any. val currPosition = candidates.firstOrNull() lastPosition = currPosition return currPosition } /** * The player can move in a lot of directions. But there are only 8 directions which make sense for scaffold to * follow (NORTH, NORTH_EAST, EAST, etc.). This function chooses such a direction based on the current angle. * i.e. if we were looking like 30° to the right, we would choose the direction NORTH_EAST (1.0, 0.0, 1.0). * And scaffold would move diagonally to the right. */ private fun chooseDirection(currentAngle: Float): Vec3d { // Transform the angle ([-180; 180]) to [0; 8] val currentDirection = currentAngle / 180.0 * 4 + 4 // Round the angle to the nearest integer, which represents the direction. val newDirectionNumber = round(currentDirection) // Do this transformation backwards, and we have an angle that follows one of the 8 directions. val newDirectionAngle = MathHelper.wrapDegrees((newDirectionNumber - 4) / 4.0 * 180.0 + 90.0) / 180.0 * PI return Vec3d(cos(newDirectionAngle), 0.0, sin(newDirectionAngle)) } /** * Remembers the last placed blocks and removes old ones. */ fun trackPlacedBlock(target: BlockPlacementTarget) { lastPlacedBlocks.add(target.placedBlock) while (lastPlacedBlocks.size > MAX_LAST_PLACE_BLOCKS) lastPlacedBlocks.removeFirst() } fun reset() { lastPosition = null this.lastPlacedBlocks.clear() } }
1
0.964912
1
0.964912
game-dev
MEDIA
0.741441
game-dev
0.985343
1
0.985343
markriedl/gaige
5,637
homework7/src/dk/itu/mario/engine/sprites/Mushroom.java
package dk.itu.mario.engine.sprites; import dk.itu.mario.engine.Art; import dk.itu.mario.scene.LevelScene; public class Mushroom extends Sprite { private static float GROUND_INERTIA = 0.89f; private static float AIR_INERTIA = 0.89f; private float runTime; private boolean onGround = false; private boolean mayJump = false; private int jumpTime = 0; private float xJumpSpeed; private float yJumpSpeed; private int width = 4; int height = 24; private LevelScene world; public int facing; public boolean avoidCliffs = false; private int life; public Mushroom(LevelScene world, int x, int y) { sheet = Art.items; this.x = x; this.y = y; this.world = world; xPicO = 8; yPicO = 15; yPic = 0; height = 12; facing = 1; wPic = hPic = 16; life = 0; } public void collideCheck() { float xMarioD = world.mario.x - x; float yMarioD = world.mario.y - y; float w = 16; if (xMarioD > -16 && xMarioD < 16) { if (yMarioD > -height && yMarioD < world.mario.height) { world.mario.getMushroom(); spriteContext.removeSprite(this); } } } public void move() { if (life<9) { layer = 0; y--; life++; return; } float sideWaysSpeed = 1.75f; layer = 1; // float sideWaysSpeed = onGround ? 2.5f : 1.2f; if (xa > 2) { facing = 1; } if (xa < -2) { facing = -1; } xa = facing * sideWaysSpeed; mayJump = (onGround); xFlipPic = facing == -1; runTime += (Math.abs(xa)) + 5; if (!move(xa, 0)) facing = -facing; onGround = false; move(0, ya); ya *= 0.85f; if (onGround) { xa *= GROUND_INERTIA; } else { xa *= AIR_INERTIA; } if (!onGround) { ya += 2; } } private boolean move(float xa, float ya) { while (xa > 8) { if (!move(8, 0)) return false; xa -= 8; } while (xa < -8) { if (!move(-8, 0)) return false; xa += 8; } while (ya > 8) { if (!move(0, 8)) return false; ya -= 8; } while (ya < -8) { if (!move(0, -8)) return false; ya += 8; } boolean collide = false; if (ya > 0) { if (isBlocking(x + xa - width, y + ya, xa, 0)) collide = true; else if (isBlocking(x + xa + width, y + ya, xa, 0)) collide = true; else if (isBlocking(x + xa - width, y + ya + 1, xa, ya)) collide = true; else if (isBlocking(x + xa + width, y + ya + 1, xa, ya)) collide = true; } if (ya < 0) { if (isBlocking(x + xa, y + ya - height, xa, ya)) collide = true; else if (collide || isBlocking(x + xa - width, y + ya - height, xa, ya)) collide = true; else if (collide || isBlocking(x + xa + width, y + ya - height, xa, ya)) collide = true; } if (xa > 0) { if (isBlocking(x + xa + width, y + ya - height, xa, ya)) collide = true; if (isBlocking(x + xa + width, y + ya - height / 2, xa, ya)) collide = true; if (isBlocking(x + xa + width, y + ya, xa, ya)) collide = true; if (avoidCliffs && onGround && !world.level.isBlocking((int) ((x + xa + width) / 16), (int) ((y) / 16 + 1), xa, 1)) collide = true; } if (xa < 0) { if (isBlocking(x + xa - width, y + ya - height, xa, ya)) collide = true; if (isBlocking(x + xa - width, y + ya - height / 2, xa, ya)) collide = true; if (isBlocking(x + xa - width, y + ya, xa, ya)) collide = true; if (avoidCliffs && onGround && !world.level.isBlocking((int) ((x + xa - width) / 16), (int) ((y) / 16 + 1), xa, 1)) collide = true; } if (collide) { if (xa < 0) { x = (int) ((x - width) / 16) * 16 + width; this.xa = 0; } if (xa > 0) { x = (int) ((x + width) / 16 + 1) * 16 - width - 1; this.xa = 0; } if (ya < 0) { y = (int) ((y - height) / 16) * 16 + height; jumpTime = 0; this.ya = 0; } if (ya > 0) { y = (int) (y / 16 + 1) * 16 - 1; onGround = true; } return false; } else { x += xa; y += ya; return true; } } private boolean isBlocking(float _x, float _y, float xa, float ya) { int x = (int) (_x / 16); int y = (int) (_y / 16); if (x == (int) (this.x / 16) && y == (int) (this.y / 16)) return false; boolean blocking = world.level.isBlocking(x, y, xa, ya); byte block = world.level.getBlock(x, y); return blocking; } public void bumpCheck(int xTile, int yTile) { if (x + width > xTile * 16 && x - width < xTile * 16 + 16 && yTile==(int)((y-1)/16)) { facing = -world.mario.facing; ya = -10; } } }
1
0.762573
1
0.762573
game-dev
MEDIA
0.521684
game-dev
0.978488
1
0.978488
ImLegiitXD/Dream-Advanced
3,638
dll/back/1.20/net/minecraft/server/commands/TeamMsgCommand.java
package net.minecraft.server.commands; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.tree.LiteralCommandNode; import java.util.List; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.MessageArgument; import net.minecraft.network.chat.ChatType; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.OutgoingChatMessage; import net.minecraft.network.chat.PlayerChatMessage; import net.minecraft.network.chat.Style; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; import net.minecraft.world.entity.Entity; import net.minecraft.world.scores.PlayerTeam; public class TeamMsgCommand { private static final Style SUGGEST_STYLE = Style.EMPTY.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.translatable("chat.type.team.hover"))).withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/teammsg ")); private static final SimpleCommandExceptionType ERROR_NOT_ON_TEAM = new SimpleCommandExceptionType(Component.translatable("commands.teammsg.failed.noteam")); public static void register(CommandDispatcher<CommandSourceStack> p_139000_) { LiteralCommandNode<CommandSourceStack> literalcommandnode = p_139000_.register(Commands.literal("teammsg").then(Commands.argument("message", MessageArgument.message()).executes((p_248184_) -> { CommandSourceStack commandsourcestack = p_248184_.getSource(); Entity entity = commandsourcestack.getEntityOrException(); PlayerTeam playerteam = (PlayerTeam)entity.getTeam(); if (playerteam == null) { throw ERROR_NOT_ON_TEAM.create(); } else { List<ServerPlayer> list = commandsourcestack.getServer().getPlayerList().getPlayers().stream().filter((p_288679_) -> { return p_288679_ == entity || p_288679_.getTeam() == playerteam; }).toList(); if (!list.isEmpty()) { MessageArgument.resolveChatMessage(p_248184_, "message", (p_248180_) -> { sendMessage(commandsourcestack, entity, playerteam, list, p_248180_); }); } return list.size(); } }))); p_139000_.register(Commands.literal("tm").redirect(literalcommandnode)); } private static void sendMessage(CommandSourceStack p_248778_, Entity p_248891_, PlayerTeam p_250504_, List<ServerPlayer> p_249706_, PlayerChatMessage p_249707_) { Component component = p_250504_.getFormattedDisplayName().withStyle(SUGGEST_STYLE); ChatType.Bound chattype$bound = ChatType.bind(ChatType.TEAM_MSG_COMMAND_INCOMING, p_248778_).withTargetName(component); ChatType.Bound chattype$bound1 = ChatType.bind(ChatType.TEAM_MSG_COMMAND_OUTGOING, p_248778_).withTargetName(component); OutgoingChatMessage outgoingchatmessage = OutgoingChatMessage.create(p_249707_); boolean flag = false; for(ServerPlayer serverplayer : p_249706_) { ChatType.Bound chattype$bound2 = serverplayer == p_248891_ ? chattype$bound1 : chattype$bound; boolean flag1 = p_248778_.shouldFilterMessageTo(serverplayer); serverplayer.sendChatMessage(outgoingchatmessage, flag1, chattype$bound2); flag |= flag1 && p_249707_.isFullyFiltered(); } if (flag) { p_248778_.sendSystemMessage(PlayerList.CHAT_FILTERED_FULL); } } }
1
0.765361
1
0.765361
game-dev
MEDIA
0.915357
game-dev
0.795952
1
0.795952
mrexodia/TitanHide
3,461
TitanHide_x64dbg/pluginsdk/yara/yara/arena.h
/* Copyright (c) 2013. The YARA Authors. 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. */ #ifndef YR_ARENA_H #define YR_ARENA_H #include <stddef.h> #include "integers.h" #include "stream.h" #define ARENA_FLAGS_FIXED_SIZE 1 #define ARENA_FLAGS_COALESCED 2 #define ARENA_FILE_VERSION 11 #define EOL ((size_t) -1) typedef struct _YR_RELOC { uint32_t offset; struct _YR_RELOC* next; } YR_RELOC; typedef struct _YR_ARENA_PAGE { uint8_t* new_address; uint8_t* address; size_t size; size_t used; YR_RELOC* reloc_list_head; YR_RELOC* reloc_list_tail; struct _YR_ARENA_PAGE* next; struct _YR_ARENA_PAGE* prev; } YR_ARENA_PAGE; typedef struct _YR_ARENA { int flags; YR_ARENA_PAGE* page_list_head; YR_ARENA_PAGE* current_page; } YR_ARENA; int yr_arena_create( size_t initial_size, int flags, YR_ARENA** arena); void yr_arena_destroy( YR_ARENA* arena); void* yr_arena_base_address( YR_ARENA* arena); void* yr_arena_next_address( YR_ARENA* arena, void* address, size_t offset); int yr_arena_coalesce( YR_ARENA* arena); int yr_arena_reserve_memory( YR_ARENA* arena, size_t size); int yr_arena_allocate_memory( YR_ARENA* arena, size_t size, void** allocated_memory); int yr_arena_allocate_struct( YR_ARENA* arena, size_t size, void** allocated_memory, ...); int yr_arena_make_relocatable( YR_ARENA* arena, void* base, ...); int yr_arena_write_data( YR_ARENA* arena, void* data, size_t size, void** written_data); int yr_arena_write_string( YR_ARENA* arena, const char* string, char** written_string); int yr_arena_append( YR_ARENA* target_arena, YR_ARENA* source_arena); int yr_arena_load_stream( YR_STREAM* stream, YR_ARENA** arena); int yr_arena_save_stream( YR_ARENA* arena, YR_STREAM* stream); int yr_arena_duplicate( YR_ARENA* arena, YR_ARENA** duplicated); void yr_arena_print( YR_ARENA* arena); #endif
1
0.694246
1
0.694246
game-dev
MEDIA
0.777883
game-dev
0.681168
1
0.681168
Fluorohydride/ygopro-scripts
3,633
c95493471.lua
--真超量機神王ブラスター・マグナ function c95493471.initial_effect(c) --link summon aux.AddLinkProcedure(c,aux.FilterBoolFunction(Card.IsLinkType,TYPE_EFFECT),2,99,c95493471.lcheck) c:EnableReviveLimit() --indes local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e1:SetCondition(c95493471.indcon) e1:SetValue(aux.indoval) c:RegisterEffect(e1) --draw local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(95493471,0)) e2:SetCategory(CATEGORY_DRAW) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c95493471.drcon) e2:SetTarget(c95493471.drtg) e2:SetOperation(c95493471.drop) c:RegisterEffect(e2) --to hand local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(95493471,0)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP) e3:SetCode(EVENT_DESTROYED) e3:SetCountLimit(1,95493471) e3:SetRange(LOCATION_MZONE) e3:SetCondition(c95493471.spcon) e3:SetTarget(c95493471.sptg) e3:SetOperation(c95493471.spop) c:RegisterEffect(e3) end function c95493471.lcheck(g) return g:IsExists(Card.IsLinkSetCard,1,nil,0xdc) end function c95493471.indcon(e) return e:GetHandler():IsSummonType(SUMMON_TYPE_LINK) end function c95493471.cfilter(c,lg,tp) return c:IsSetCard(0xdc) and c:IsType(TYPE_XYZ) and c:IsSummonLocation(LOCATION_EXTRA) and lg:IsContains(c) and not Duel.IsExistingMatchingCard(c95493471.drfilter,tp,LOCATION_MZONE,0,1,c,c:GetCode()) end function c95493471.drfilter(c,code) return c:IsFaceup() and c:IsCode(code) end function c95493471.drcon(e,tp,eg,ep,ev,re,r,rp) local lg=e:GetHandler():GetLinkedGroup() return eg:IsExists(c95493471.cfilter,1,nil,lg,tp) end function c95493471.drtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c95493471.drop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end function c95493471.cfilter2(c,tp,zone) local seq=c:GetPreviousSequence() if c:IsPreviousControler(1-tp) then seq=seq+16 end return c:IsPreviousLocation(LOCATION_MZONE) and bit.extract(zone,seq)~=0 and c:IsType(TYPE_XYZ) and (c:IsReason(REASON_BATTLE) or c:IsReason(REASON_EFFECT) and c:GetReasonPlayer()==1-tp) end function c95493471.spcon(e,tp,eg,ep,ev,re,r,rp) local zone=e:GetHandler():GetLinkedZone() local g=eg:Filter(c95493471.cfilter2,nil,tp,zone) local attr=0 for tc in aux.Next(g) do attr=attr|tc:GetOriginalAttribute() end e:SetLabel(attr) return #g>0 end function c95493471.spfilter(c,e,tp,attr) return c:IsSetCard(0xdc) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:GetOriginalAttribute()&attr>0 end function c95493471.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c95493471.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp,e:GetLabel()) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c95493471.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c95493471.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,e:GetLabel()) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
1
0.899342
1
0.899342
game-dev
MEDIA
0.949621
game-dev
0.97495
1
0.97495
Woprok/AOE4-AdvancedGameSettings
3,280
assets/scar/gameplay/statewars/ags_statewars_bonuses.scar
--------------------------------------------------------------------------------------------------- -- Authors: -- Relic -- Woprock -- -- Description: -- Enables certain units and gives certain upgrades to all players. --------------------------------------------------------------------------------------------------- AGS_STATEWARS_BONUSES_MODULE = "AGS_StatewarsBonuses" --------------------------------------------------------------------------------------------------- -- Delegates: --------------------------------------------------------------------------------------------------- Core_RegisterModule(AGS_STATEWARS_BONUSES_MODULE) function AGS_StatewarsBonuses_UpdateModuleSettings() AGS_Print("AGS_StatewarsBonuses_UpdateModuleSettings") if not AGS_GLOBAL_SETTINGS.StatewarsBonuses then Core_UnregisterModule(AGS_STATEWARS_BONUSES_MODULE) end end function AGS_StatewarsBonuses_PresetFinalize() AGS_Print("AGS_StatewarsBonuses_PresetFinalize") AGS_StatewarsBonuses_Apply() end --------------------------------------------------------------------------------------------------- -- Functions: --------------------------------------------------------------------------------------------------- function AGS_StatewarsBonuses_Apply() local repeater2 = "unit_repeater_crossbowman_2_chi" local repeater3 = "unit_repeater_crossbowman_3_chi" local lancer3 = "unit_firelancer_3_chi" local uprep3 = "upgrade_unit_repeater_crossbow_3_chi" for _, player in pairs(PLAYERS) do Player_SetEntityProductionAvailability(player.id, BP_GetEntityBlueprint(repeater2), ITEM_UNLOCKED) Player_SetEntityProductionAvailability(player.id, BP_GetEntityBlueprint(repeater3), ITEM_UNLOCKED) Player_SetEntityProductionAvailability(player.id, BP_GetEntityBlueprint(lancer3), ITEM_UNLOCKED) Player_SetSquadProductionAvailability(player.id, BP_GetSquadBlueprint(repeater2), ITEM_UNLOCKED) Player_SetSquadProductionAvailability(player.id, BP_GetSquadBlueprint(repeater3), ITEM_UNLOCKED) Player_SetSquadProductionAvailability(player.id, BP_GetSquadBlueprint(lancer3), ITEM_UNLOCKED) Player_SetUpgradeAvailability(player.id, BP_GetUpgradeBlueprint(uprep3), ITEM_UNLOCKED) AGS_ApplyUpgrade(player.id, "upgrade_unit_religious_tithe_barn_4_mon") AGS_ApplyUpgrade(player.id, "upgrade_unit_religious_tithe_barn_4_improved_mon") Player_SetUpgradeAvailability(player.id, BP_GetUpgradeBlueprint("upgrade_unit_religious_tithe_barn_4_sul"), ITEM_REMOVED) Player_SetUpgradeAvailability(player.id, BP_GetUpgradeBlueprint("upgrade_unit_religious_tithe_barn_4"), ITEM_REMOVED) AGS_ApplyUpgrade(player.id, "upgrade_unit_religious_sanctity_4_sul") AGS_ApplyUpgrade(player.id, "upgrade_cul_conversion_invuln_abb") Player_SetStateModelInt(player.id, "silk_road_requirement_tier_1_mon", 1000) Player_SetStateModelInt(player.id, "silk_road_requirement_tier_2_mon", 1000) Player_SetStateModelInt(player.id, "silk_road_requirement_tier_3_mon", 1000) Player_SetStateModelInt(player.id, "silk_road_requirement_tier_4_mon", 1000) Player_SetUpgradeAvailability(player.id, BP_GetUpgradeBlueprint("upgrade_trader_silkroad_stone_mon"), ITEM_REMOVED) Player_SetUpgradeAvailability(player.id, BP_GetUpgradeBlueprint("upgrade_trader_silkroad_stone_improved_mon"), ITEM_REMOVED) end end
1
0.807506
1
0.807506
game-dev
MEDIA
0.892814
game-dev
0.883592
1
0.883592
godotengine/godot
22,569
thirdparty/embree/kernels/builders/bvh_builder_msmblur_hair.h
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once #include "../bvh/bvh.h" #include "../geometry/primitive.h" #include "../builders/bvh_builder_msmblur.h" #include "../builders/heuristic_binning_array_aligned.h" #include "../builders/heuristic_binning_array_unaligned.h" #include "../builders/heuristic_timesplit_array.h" namespace embree { namespace isa { struct BVHBuilderHairMSMBlur { /*! settings for msmblur builder */ struct Settings { /*! default settings */ Settings () : branchingFactor(2), maxDepth(32), logBlockSize(0), minLeafSize(1), maxLeafSize(8) {} public: size_t branchingFactor; //!< branching factor of BVH to build size_t maxDepth; //!< maximum depth of BVH to build size_t logBlockSize; //!< log2 of blocksize for SAH heuristic size_t minLeafSize; //!< minimum size of a leaf size_t maxLeafSize; //!< maximum size of a leaf }; struct BuildRecord { public: __forceinline BuildRecord () {} __forceinline BuildRecord (size_t depth) : depth(depth) {} __forceinline BuildRecord (const SetMB& prims, size_t depth) : depth(depth), prims(prims) {} __forceinline size_t size() const { return prims.size(); } public: size_t depth; //!< depth of the root of this subtree SetMB prims; //!< the list of primitives }; template<typename NodeRef, typename RecalculatePrimRef, typename CreateAllocFunc, typename CreateAABBNodeMBFunc, typename SetAABBNodeMBFunc, typename CreateOBBNodeMBFunc, typename SetOBBNodeMBFunc, typename CreateLeafFunc, typename ProgressMonitor> class BuilderT { ALIGNED_CLASS_(16); static const size_t MAX_BRANCHING_FACTOR = 8; //!< maximum supported BVH branching factor static const size_t MIN_LARGE_LEAF_LEVELS = 8; //!< create balanced tree if we are that many levels before the maximum tree depth static const size_t SINGLE_THREADED_THRESHOLD = 4096; //!< threshold to switch to single threaded build typedef BVHNodeRecordMB<NodeRef> NodeRecordMB; typedef BVHNodeRecordMB4D<NodeRef> NodeRecordMB4D; typedef FastAllocator::CachedAllocator Allocator; typedef LocalChildListT<BuildRecord,MAX_BRANCHING_FACTOR> LocalChildList; typedef HeuristicMBlurTemporalSplit<PrimRefMB,RecalculatePrimRef,MBLUR_NUM_TEMPORAL_BINS> HeuristicTemporal; typedef HeuristicArrayBinningMB<PrimRefMB,MBLUR_NUM_OBJECT_BINS> HeuristicBinning; typedef UnalignedHeuristicArrayBinningMB<PrimRefMB,MBLUR_NUM_OBJECT_BINS> UnalignedHeuristicBinning; public: BuilderT (Scene* scene, const RecalculatePrimRef& recalculatePrimRef, const CreateAllocFunc& createAlloc, const CreateAABBNodeMBFunc& createAABBNodeMB, const SetAABBNodeMBFunc& setAABBNodeMB, const CreateOBBNodeMBFunc& createOBBNodeMB, const SetOBBNodeMBFunc& setOBBNodeMB, const CreateLeafFunc& createLeaf, const ProgressMonitor& progressMonitor, const Settings settings) : cfg(settings), scene(scene), recalculatePrimRef(recalculatePrimRef), createAlloc(createAlloc), createAABBNodeMB(createAABBNodeMB), setAABBNodeMB(setAABBNodeMB), createOBBNodeMB(createOBBNodeMB), setOBBNodeMB(setOBBNodeMB), createLeaf(createLeaf), progressMonitor(progressMonitor), unalignedHeuristic(scene), temporalSplitHeuristic(scene->device,recalculatePrimRef) {} private: /*! checks if all primitives are from the same geometry */ __forceinline bool sameGeometry(const SetMB& set) { mvector<PrimRefMB>& prims = *set.prims; unsigned int firstGeomID = prims[set.begin()].geomID(); for (size_t i=set.begin()+1; i<set.end(); i++) { if (prims[i].geomID() != firstGeomID){ return false; } } return true; } /*! performs some split if SAH approaches fail */ void splitFallback(const SetMB& set, SetMB& lset, SetMB& rset) { mvector<PrimRefMB>& prims = *set.prims; const size_t begin = set.begin(); const size_t end = set.end(); const size_t center = (begin + end)/2; PrimInfoMB linfo = empty; for (size_t i=begin; i<center; i++) linfo.add_primref(prims[i]); PrimInfoMB rinfo = empty; for (size_t i=center; i<end; i++) rinfo.add_primref(prims[i]); new (&lset) SetMB(linfo,set.prims,range<size_t>(begin,center),set.time_range); new (&rset) SetMB(rinfo,set.prims,range<size_t>(center,end ),set.time_range); } void splitByGeometry(const SetMB& set, SetMB& lset, SetMB& rset) { assert(set.size() > 1); const size_t begin = set.begin(); const size_t end = set.end(); PrimInfoMB linfo(empty); PrimInfoMB rinfo(empty); unsigned int geomID = (*set.prims)[begin].geomID(); size_t center = serial_partitioning(set.prims->data(),begin,end,linfo,rinfo, [&] ( const PrimRefMB& prim ) { return prim.geomID() == geomID; }, [ ] ( PrimInfoMB& a, const PrimRefMB& ref ) { a.add_primref(ref); }); new (&lset) SetMB(linfo,set.prims,range<size_t>(begin,center),set.time_range); new (&rset) SetMB(rinfo,set.prims,range<size_t>(center,end ),set.time_range); } /*! creates a large leaf that could be larger than supported by the BVH */ NodeRecordMB4D createLargeLeaf(BuildRecord& current, Allocator alloc) { /* this should never occur but is a fatal error */ if (current.depth > cfg.maxDepth) throw_RTCError(RTC_ERROR_UNKNOWN,"depth limit reached"); /* special case when directly creating leaf without any splits that could shrink time_range */ bool force_split = false; if (current.depth == 1 && current.size() > 0) { BBox1f c = empty; BBox1f p = current.prims.time_range; for (size_t i=current.prims.begin(); i<current.prims.end(); i++) { mvector<PrimRefMB>& prims = *current.prims.prims; c.extend(prims[i].time_range); } force_split = c.lower > p.lower || c.upper < p.upper; } /* create leaf for few primitives */ if (current.size() <= cfg.maxLeafSize && sameGeometry(current.prims) && !force_split) return createLeaf(current.prims,alloc); /* fill all children by always splitting the largest one */ LocalChildList children(current); NodeRecordMB4D values[MAX_BRANCHING_FACTOR]; do { /* find best child with largest bounding box area */ int bestChild = -1; size_t bestSize = 0; for (unsigned i=0; i<children.size(); i++) { /* ignore leaves as they cannot get split */ if (children[i].size() <= cfg.maxLeafSize && sameGeometry(children[i].prims) && !force_split) continue; force_split = false; /* remember child with largest size */ if (children[i].size() > bestSize) { bestSize = children[i].size(); bestChild = i; } } if (bestChild == -1) break; /*! split best child into left and right child */ BuildRecord left(current.depth+1); BuildRecord right(current.depth+1); if (!sameGeometry(children[bestChild].prims)) { splitByGeometry(children[bestChild].prims,left.prims,right.prims); } else { splitFallback(children[bestChild].prims,left.prims,right.prims); } children.split(bestChild,left,right,std::unique_ptr<mvector<PrimRefMB>>()); } while (children.size() < cfg.branchingFactor); /* detect time_ranges that have shrunken */ bool timesplit = false; for (size_t i=0; i<children.size(); i++) { const BBox1f c = children[i].prims.time_range; const BBox1f p = current.prims.time_range; timesplit |= c.lower > p.lower || c.upper < p.upper; } /* create node */ NodeRef node = createAABBNodeMB(children.children.data(),children.numChildren,alloc,timesplit); LBBox3fa bounds = empty; for (size_t i=0; i<children.size(); i++) { values[i] = createLargeLeaf(children[i],alloc); bounds.extend(values[i].lbounds); } setAABBNodeMB(current,children.children.data(),node,values,children.numChildren); if (timesplit) bounds = current.prims.linearBounds(recalculatePrimRef); return NodeRecordMB4D(node,bounds,current.prims.time_range); } /*! performs split */ std::unique_ptr<mvector<PrimRefMB>> split(const BuildRecord& current, BuildRecord& lrecord, BuildRecord& rrecord, bool& aligned, bool& timesplit) { /* variable to track the SAH of the best splitting approach */ float bestSAH = inf; const float leafSAH = current.prims.leafSAH(cfg.logBlockSize); /* perform standard binning in aligned space */ HeuristicBinning::Split alignedObjectSplit = alignedHeuristic.find(current.prims,cfg.logBlockSize); float alignedObjectSAH = alignedObjectSplit.splitSAH(); bestSAH = min(alignedObjectSAH,bestSAH); /* perform standard binning in unaligned space */ UnalignedHeuristicBinning::Split unalignedObjectSplit; LinearSpace3fa uspace; float unalignedObjectSAH = inf; if (alignedObjectSAH > 0.7f*leafSAH) { uspace = unalignedHeuristic.computeAlignedSpaceMB(scene,current.prims); const SetMB sset = current.prims.primInfo(recalculatePrimRef,uspace); unalignedObjectSplit = unalignedHeuristic.find(sset,cfg.logBlockSize,uspace); unalignedObjectSAH = 1.3f*unalignedObjectSplit.splitSAH(); // makes unaligned splits more expensive bestSAH = min(unalignedObjectSAH,bestSAH); } /* do temporal splits only if previous approaches failed to produce good SAH and the the time range is large enough */ float temporal_split_sah = inf; typename HeuristicTemporal::Split temporal_split; if (bestSAH > 0.5f*leafSAH) { if (current.prims.time_range.size() > 1.01f/float(current.prims.max_num_time_segments)) { temporal_split = temporalSplitHeuristic.find(current.prims,cfg.logBlockSize); temporal_split_sah = temporal_split.splitSAH(); bestSAH = min(temporal_split_sah,bestSAH); } } /* perform fallback split if SAH heuristics failed */ if (unlikely(!std::isfinite(bestSAH))) { current.prims.deterministic_order(); splitFallback(current.prims,lrecord.prims,rrecord.prims); } /* perform aligned split if this is best */ else if (likely(bestSAH == alignedObjectSAH)) { alignedHeuristic.split(alignedObjectSplit,current.prims,lrecord.prims,rrecord.prims); } /* perform unaligned split if this is best */ else if (likely(bestSAH == unalignedObjectSAH)) { unalignedHeuristic.split(unalignedObjectSplit,uspace,current.prims,lrecord.prims,rrecord.prims); aligned = false; } /* perform temporal split if this is best */ else if (likely(bestSAH == temporal_split_sah)) { timesplit = true; return temporalSplitHeuristic.split(temporal_split,current.prims,lrecord.prims,rrecord.prims); } else assert(false); return std::unique_ptr<mvector<PrimRefMB>>(); } /*! recursive build */ NodeRecordMB4D recurse(BuildRecord& current, Allocator alloc, bool toplevel) { /* get thread local allocator */ if (!alloc) alloc = createAlloc(); /* call memory monitor function to signal progress */ if (toplevel && current.size() <= SINGLE_THREADED_THRESHOLD) progressMonitor(current.size()); /* create leaf node */ if (current.depth+MIN_LARGE_LEAF_LEVELS >= cfg.maxDepth || current.size() <= cfg.minLeafSize) { current.prims.deterministic_order(); return createLargeLeaf(current,alloc); } /* fill all children by always splitting the one with the largest surface area */ NodeRecordMB4D values[MAX_BRANCHING_FACTOR]; LocalChildList children(current); bool aligned = true; bool timesplit = false; do { /* find best child with largest bounding box area */ ssize_t bestChild = -1; float bestArea = neg_inf; for (size_t i=0; i<children.size(); i++) { /* ignore leaves as they cannot get split */ if (children[i].size() <= cfg.minLeafSize) continue; /* remember child with largest area */ const float A = children[i].prims.halfArea(); if (A > bestArea) { bestArea = children[i].prims.halfArea(); bestChild = i; } } if (bestChild == -1) break; /*! split best child into left and right child */ BuildRecord left(current.depth+1); BuildRecord right(current.depth+1); std::unique_ptr<mvector<PrimRefMB>> new_vector = split(children[bestChild],left,right,aligned,timesplit); children.split(bestChild,left,right,std::move(new_vector)); } while (children.size() < cfg.branchingFactor); /* detect time_ranges that have shrunken */ for (size_t i=0; i<children.size(); i++) { const BBox1f c = children[i].prims.time_range; const BBox1f p = current.prims.time_range; timesplit |= c.lower > p.lower || c.upper < p.upper; } /* create time split node */ if (timesplit) { const NodeRef node = createAABBNodeMB(children.children.data(),children.numChildren,alloc,true); /* spawn tasks or ... */ if (current.size() > SINGLE_THREADED_THRESHOLD) { parallel_for(size_t(0), children.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { values[i] = recurse(children[i],nullptr,true); _mm_mfence(); // to allow non-temporal stores during build } }); } /* ... continue sequential */ else { for (size_t i=0; i<children.size(); i++) { values[i] = recurse(children[i],alloc,false); } } setAABBNodeMB(current,children.children.data(),node,values,children.numChildren); const LBBox3fa bounds = current.prims.linearBounds(recalculatePrimRef); return NodeRecordMB4D(node,bounds,current.prims.time_range); } /* create aligned node */ else if (aligned) { const NodeRef node = createAABBNodeMB(children.children.data(),children.numChildren,alloc,true); /* spawn tasks or ... */ if (current.size() > SINGLE_THREADED_THRESHOLD) { LBBox3fa cbounds[MAX_BRANCHING_FACTOR]; parallel_for(size_t(0), children.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { values[i] = recurse(children[i],nullptr,true); cbounds[i] = values[i].lbounds; _mm_mfence(); // to allow non-temporal stores during build } }); LBBox3fa bounds = empty; for (size_t i=0; i<children.size(); i++) bounds.extend(cbounds[i]); setAABBNodeMB(current,children.children.data(),node,values,children.numChildren); return NodeRecordMB4D(node,bounds,current.prims.time_range); } /* ... continue sequentially */ else { LBBox3fa bounds = empty; for (size_t i=0; i<children.size(); i++) { values[i] = recurse(children[i],alloc,false); bounds.extend(values[i].lbounds); } setAABBNodeMB(current,children.children.data(),node,values,children.numChildren); return NodeRecordMB4D(node,bounds,current.prims.time_range); } } /* create unaligned node */ else { const NodeRef node = createOBBNodeMB(alloc); /* spawn tasks or ... */ if (current.size() > SINGLE_THREADED_THRESHOLD) { parallel_for(size_t(0), children.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { const LinearSpace3fa space = unalignedHeuristic.computeAlignedSpaceMB(scene,children[i].prims); const LBBox3fa lbounds = children[i].prims.linearBounds(recalculatePrimRef,space); const auto child = recurse(children[i],nullptr,true); setOBBNodeMB(node,i,child.ref,space,lbounds,children[i].prims.time_range); _mm_mfence(); // to allow non-temporal stores during build } }); } /* ... continue sequentially */ else { for (size_t i=0; i<children.size(); i++) { const LinearSpace3fa space = unalignedHeuristic.computeAlignedSpaceMB(scene,children[i].prims); const LBBox3fa lbounds = children[i].prims.linearBounds(recalculatePrimRef,space); const auto child = recurse(children[i],alloc,false); setOBBNodeMB(node,i,child.ref,space,lbounds,children[i].prims.time_range); } } const LBBox3fa bounds = current.prims.linearBounds(recalculatePrimRef); return NodeRecordMB4D(node,bounds,current.prims.time_range); } } public: /*! entry point into builder */ NodeRecordMB4D operator() (mvector<PrimRefMB>& prims, const PrimInfoMB& pinfo) { BuildRecord record(SetMB(pinfo,&prims),1); auto root = recurse(record,nullptr,true); _mm_mfence(); // to allow non-temporal stores during build return root; } private: Settings cfg; Scene* scene; const RecalculatePrimRef& recalculatePrimRef; const CreateAllocFunc& createAlloc; const CreateAABBNodeMBFunc& createAABBNodeMB; const SetAABBNodeMBFunc& setAABBNodeMB; const CreateOBBNodeMBFunc& createOBBNodeMB; const SetOBBNodeMBFunc& setOBBNodeMB; const CreateLeafFunc& createLeaf; const ProgressMonitor& progressMonitor; private: HeuristicBinning alignedHeuristic; UnalignedHeuristicBinning unalignedHeuristic; HeuristicTemporal temporalSplitHeuristic; }; template<typename NodeRef, typename RecalculatePrimRef, typename CreateAllocFunc, typename CreateAABBNodeMBFunc, typename SetAABBNodeMBFunc, typename CreateOBBNodeMBFunc, typename SetOBBNodeMBFunc, typename CreateLeafFunc, typename ProgressMonitor> static BVHNodeRecordMB4D<NodeRef> build (Scene* scene, mvector<PrimRefMB>& prims, const PrimInfoMB& pinfo, const RecalculatePrimRef& recalculatePrimRef, const CreateAllocFunc& createAlloc, const CreateAABBNodeMBFunc& createAABBNodeMB, const SetAABBNodeMBFunc& setAABBNodeMB, const CreateOBBNodeMBFunc& createOBBNodeMB, const SetOBBNodeMBFunc& setOBBNodeMB, const CreateLeafFunc& createLeaf, const ProgressMonitor& progressMonitor, const Settings settings) { typedef BuilderT<NodeRef,RecalculatePrimRef,CreateAllocFunc, CreateAABBNodeMBFunc,SetAABBNodeMBFunc, CreateOBBNodeMBFunc,SetOBBNodeMBFunc, CreateLeafFunc,ProgressMonitor> Builder; Builder builder(scene,recalculatePrimRef,createAlloc, createAABBNodeMB,setAABBNodeMB, createOBBNodeMB,setOBBNodeMB, createLeaf,progressMonitor,settings); return builder(prims,pinfo); } }; } }
1
0.939232
1
0.939232
game-dev
MEDIA
0.257563
game-dev
0.966093
1
0.966093
EOS-team/EOS
1,856
src/embodied-intelligence/src/3D_human_pose_recognition/ios_sdk/UnityDEBUG/ForDebug/Library/PackageCache/com.unity.visualscripting@1.8.0/Runtime/VisualScripting.Core/Dependencies/FullSerializer/Converters/Unity/UnityEvent_Converter.cs
#if !NO_UNITY && UNITY_5_3_OR_NEWER using System; using UnityEngine; using UnityEngine.Events; namespace Unity.VisualScripting.FullSerializer { partial class fsConverterRegistrar { // Disable the converter for the time being. Unity's JsonUtility API // cannot be called from within a C# ISerializationCallbackReceiver // callback. // public static Internal.Converters.UnityEvent_Converter // Register_UnityEvent_Converter; } } namespace Unity.VisualScripting.FullSerializer.Internal.Converters { // The standard FS reflection converter has started causing Unity to crash // when processing UnityEvent. We can send the serialization through // JsonUtility which appears to work correctly instead. // // We have to support legacy serialization formats so importing works as // expected. public class UnityEvent_Converter : fsConverter { public override bool CanProcess(Type type) { return typeof(UnityEvent).Resolve().IsAssignableFrom(type.Resolve()) && type.Resolve().IsGenericType == false; } public override bool RequestCycleSupport(Type storageType) { return false; } public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { Type objectType = (Type)instance; fsResult result = fsResult.Success; instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); return result; } public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { fsResult result = fsResult.Success; serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance)); return result; } } } #endif
1
0.520853
1
0.520853
game-dev
MEDIA
0.410803
game-dev
0.692107
1
0.692107
Cyrus2D/Pyrus2D
1,291
lib/action/neck_turn_to_point.py
from pyrusgeom.vector_2d import Vector2D from lib.action.neck_scan_field import NeckScanField from lib.debug.debug import log from lib.player.soccer_action import NeckAction from typing import TYPE_CHECKING from lib.rcsc.server_param import ServerParam if TYPE_CHECKING: from lib.player.player_agent import PlayerAgent class NeckTurnToPoint(NeckAction): def __init__(self, point: Vector2D = None, points: list[Vector2D] = None): self._points: list[Vector2D] = [] if point: self._points.append(point) else: self._points = list(points) def execute(self, agent: 'PlayerAgent'): log.debug_client().add_message('TurnToPoint/') ef = agent.effector() wm = agent.world() SP = ServerParam.i() next_pos = ef.queued_next_self_pos() next_body = ef.queued_next_self_body() next_view_width = ef.queued_next_view_width().width()/2 for p in self._points: rel_pos = p - next_pos rel_angle = rel_pos.th() - next_body if rel_angle.abs() < SP.max_neck_angle() + next_view_width - 5.: return agent.do_turn_neck(rel_angle - agent.world().self().neck()) NeckScanField().execute(agent) return True
1
0.828205
1
0.828205
game-dev
MEDIA
0.251063
game-dev
0.88576
1
0.88576
StellariumMC/zen
2,520
src/main/kotlin/xyz/meowing/zen/features/hud/FatalTempoOverlay.kt
package xyz.meowing.zen.features.hud import xyz.meowing.zen.Zen import xyz.meowing.zen.config.ui.ConfigUI import xyz.meowing.zen.config.ui.types.ConfigElement import xyz.meowing.zen.config.ui.types.ElementType import xyz.meowing.zen.events.EntityEvent import xyz.meowing.zen.events.MouseEvent import xyz.meowing.zen.events.RenderEvent import xyz.meowing.zen.features.Feature import xyz.meowing.zen.hud.HUDManager import xyz.meowing.zen.utils.ItemUtils.extraAttributes import xyz.meowing.zen.utils.LoopUtils import xyz.meowing.zen.utils.Render2D @Zen.Module object FatalTempoOverlay : Feature("fataltempooverlay", true) { private val hits = mutableListOf<Long>() private var level = 0 private var currentPercent = 0 override fun addConfig(configUI: ConfigUI): ConfigUI { return configUI .addElement("HUD", "Fatal Tempo Overlay", ConfigElement( "fataltempooverlay", null, ElementType.Switch(false) ), isSectionToggle = true) } override fun initialize() { HUDManager.register("Fatal Tempo", "§eFatal Tempo: §a200%") register<EntityEvent.Interact> { checkFatal() } register<MouseEvent.Click> { event -> if (event.event.button == 0) checkFatal() } register<RenderEvent.Text> { if (HUDManager.isEnabled("Fatal Tempo")) render() } } private fun checkFatal() { val item = player?.heldItem ?: return val enchantments = item.extraAttributes?.getCompoundTag("enchantments") ?: return val ftLevel = enchantments.getInteger("ultimate_fatal_tempo") if (ftLevel <= 0) return level = ftLevel * if (item.displayName.contains("Terminator")) 3 else 1 val currentTime = System.currentTimeMillis() hits.add(currentTime) hits.removeAll { currentTime - it > 3000 } currentPercent = minOf(200, hits.size * level * 10) LoopUtils.setTimeout(3100) { hits.removeAll { System.currentTimeMillis() - it > 3000 } currentPercent = minOf(200, hits.size * level * 10) } } private fun render() { val x = HUDManager.getX("Fatal Tempo") val y = HUDManager.getY("Fatal Tempo") val scale = HUDManager.getScale("Fatal Tempo") val color = if (currentPercent > 0) "§a" else "§c" val text = "§eFatal Tempo: $color$currentPercent%" Render2D.renderString(text, x, y, scale) } }
1
0.928145
1
0.928145
game-dev
MEDIA
0.699546
game-dev
0.922526
1
0.922526
SourceEngine-CommunityEdition/source
1,246
game/server/hl2/item_suit.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// /* ===== item_suit.cpp ======================================================== handling for the player's suit. */ #include "cbase.h" #include "player.h" #include "gamerules.h" #include "items.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define SF_SUIT_SHORTLOGON 0x0001 class CItemSuit : public CItem { public: DECLARE_CLASS( CItemSuit, CItem ); void Spawn( void ) { Precache( ); SetModel( "models/items/hevsuit.mdl" ); BaseClass::Spawn( ); CollisionProp()->UseTriggerBounds( false, 0 ); } void Precache( void ) { PrecacheModel ("models/items/hevsuit.mdl"); } bool MyTouch( CBasePlayer *pPlayer ) { if ( pPlayer->IsSuitEquipped() ) return FALSE; if ( m_spawnflags & SF_SUIT_SHORTLOGON ) UTIL_EmitSoundSuit(pPlayer->edict(), "!HEV_A0"); // short version of suit logon, else UTIL_EmitSoundSuit(pPlayer->edict(), "!HEV_AAx"); // long version of suit logon pPlayer->EquipSuit(); return true; } }; LINK_ENTITY_TO_CLASS(item_suit, CItemSuit);
1
0.772764
1
0.772764
game-dev
MEDIA
0.923644
game-dev
0.694803
1
0.694803
DigiWorm0/LevelImposter
2,525
LevelImposter/Trigger/TriggerHandles/SabTriggerHandle.cs
namespace LevelImposter.Trigger; public class SabTriggerHandle : ITriggerHandle { public void OnTrigger(TriggerSignal signal) { // Only handle triggers on the client that triggered them var origin = signal.SourcePlayer; var isClient = origin == null || origin == PlayerControl.LocalPlayer; if (!isClient) return; // Handle sabotage triggers switch (signal.TriggerID) { case "startOxygen": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.LifeSupp, 128); break; case "startLights": byte switchBits = 4; for (var i = 0; i < 5; i++) if (BoolRange.Next()) switchBits |= (byte)(1 << i); ShipStatus.Instance.RpcUpdateSystem(SystemTypes.Electrical, (byte)(switchBits | 128)); break; case "startReactor": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.Reactor, 128); break; case "startComms": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.Comms, 128); break; case "startMixup": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.MushroomMixupSabotage, 1); break; case "endOxygen": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.LifeSupp, 16); break; case "endLights": var lights = ShipStatus.Instance.Systems[SystemTypes.Electrical].Cast<SwitchSystem>(); ShipStatus.Instance.RpcUpdateSystem(SystemTypes.Electrical, (byte)((lights.ExpectedSwitches ^ lights.ActualSwitches) | 128)); break; case "endReactor": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.Reactor, 16); break; case "endComms": ShipStatus.Instance.RpcUpdateSystem(SystemTypes.Comms, 0); break; case "endMixup": if (!ShipStatus.Instance.Systems.ContainsKey(SystemTypes.MushroomMixupSabotage)) return; var mixup = ShipStatus.Instance.Systems[SystemTypes.MushroomMixupSabotage] .Cast<MushroomMixupSabotageSystem>(); mixup.currentSecondsUntilHeal = 0.01f; mixup.IsDirty = true; // TODO: Transmit to other clients break; } } }
1
0.935097
1
0.935097
game-dev
MEDIA
0.446026
game-dev
0.959023
1
0.959023
EOS-team/EOS
7,573
src/embodied-intelligence/src/3D_human_pose_recognition/ios_sdk/UnityDEBUG/ForDebug/Library/PackageCache/com.unity.timeline@1.6.4/Editor/Undo/UndoExtensions.cs
using System.Collections.Generic; using UnityEditor.Timeline.Actions; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; using Object = UnityEngine.Object; namespace UnityEditor.Timeline { /// <summary> /// Use this class to record the state of a timeline or its components prior to modification. /// </summary> /// <remarks> /// These methods do not need to be used when adding or deleting tracks, clips or markers. /// Methods in the UnityEngine.Timeline namespace, such as <see cref="UnityEngine.Timeline.TimelineAsset.CreateTrack"/> /// or <see cref="UnityEngine.Timeline.TrackAsset.CreateDefaultClip"/> will apply the appropriate /// Undo calls when called in Editor. /// </remarks> public static class UndoExtensions { /// <summary> /// Records all items contained in an action context. Use this method to record all objects /// inside the context. /// </summary> /// <param name="context">The action context to record into the Undo system.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterContext(ActionContext context, string undoTitle) { using (var undo = new UndoScope(undoTitle)) { undo.Add(context.tracks); undo.Add(context.clips, true); undo.Add(context.markers); } } /// <summary> /// Records any changes done on the timeline after being called. This only applies /// to the timeline asset properties itself, and not any of the tracks or clips on the timeline /// </summary> /// <param name="asset">The timeline asset being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterTimeline(TimelineAsset asset, string undoTitle) { using (var undo = new UndoScope(undoTitle)) undo.AddObject(asset); } /// <summary> /// Records any changes done on the timeline after being called, including any changes /// to any clips, tracks and markers that occur on the timeline. /// </summary> /// <param name="asset">The timeline asset being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterCompleteTimeline(TimelineAsset asset, string undoTitle) { if (asset == null) return; using (var undo = new UndoScope(undoTitle)) { undo.AddObject(asset); undo.Add(asset.flattenedTracks); foreach (var t in asset.flattenedTracks) { undo.Add(t.GetClips(), true); undo.Add(t.GetMarkers()); } } } /// <summary> /// Records any changes done on the track after being called, including any changes /// to clips on the track, but not on markers or PlayableAssets attached to the clips. /// </summary> /// <param name="asset">The timeline track being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterTrack(TrackAsset asset, string undoTitle) { using (var undo = new UndoScope(undoTitle)) undo.AddObject(asset); } /// <summary> /// Records any changes done on the tracks after being called, including any changes /// to clips on the tracks, but not on markers or PlayableAssets attached to the clips. /// </summary> /// <param name="tracks">The timeline track being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterTracks(IEnumerable<TrackAsset> tracks, string undoTitle) { using (var undo = new UndoScope(undoTitle)) undo.Add(tracks); } /// <summary> /// Records any changes done on the clip after being called. /// </summary> /// <param name="clip">The timeline clip being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> /// <param name="includePlayableAsset">Set this value to true to also record changes on the attached playable asset.</param> public static void RegisterClip(TimelineClip clip, string undoTitle, bool includePlayableAsset = true) { using (var undo = new UndoScope(undoTitle)) { undo.AddClip(clip, includePlayableAsset); } } /// <summary> /// Records any changes done on the PlayableAsset after being called. /// </summary> /// <param name="asset">The timeline track being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterPlayableAsset(PlayableAsset asset, string undoTitle) { using (var undo = new UndoScope(undoTitle)) undo.AddObject(asset); } /// <summary> /// Records any changes done on the clips after being called. /// </summary> /// <param name="clips">The timeline clips being modified.</param> /// <param name="name">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> /// <param name="includePlayableAssets">Set this value to true to also record changes on the attached playable assets.</param> public static void RegisterClips(IEnumerable<TimelineClip> clips, string name, bool includePlayableAssets = true) { using (var undo = new UndoScope(name)) undo.Add(clips, includePlayableAssets); } /// <summary> /// Records any changes done on the Timeline Marker after being called. /// </summary> /// <param name="marker">The timeline clip being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterMarker(IMarker marker, string undoTitle) { using (var undo = new UndoScope(undoTitle)) { if (marker is Object o) undo.AddObject(o); else if (marker != null) undo.AddObject(marker.parent); } } /// <summary> /// Records any changes done on the Timeline Markers after being called. /// </summary> /// <param name="markers">The timeline clip being modified.</param> /// <param name="undoTitle">The title of the action to appear in the undo history (i.e. visible in the undo menu).</param> public static void RegisterMarkers(IEnumerable<IMarker> markers, string undoTitle) { using (var undo = new UndoScope(undoTitle)) undo.Add(markers); } } }
1
0.856309
1
0.856309
game-dev
MEDIA
0.584297
game-dev
0.866179
1
0.866179
Aussiemon/Darktide-Source-Code
1,250
dialogues/generated/psyker_male_c_zealot_male_a.lua
-- chunkname: @dialogues/generated/psyker_male_c_zealot_male_a.lua local psyker_male_c_zealot_male_a = { oval_bonding_conversation_condone_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_a__oval_bonding_conversation_condone_b_01", }, sound_events_duration = { [1] = 2.226958, }, randomize_indexes = {}, }, oval_bonding_conversation_condone_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_a__oval_bonding_conversation_condone_d_01", }, sound_events_duration = { [1] = 4.262292, }, randomize_indexes = {}, }, oval_bonding_conversation_cruelty_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_a__oval_bonding_conversation_cruelty_b_01", }, sound_events_duration = { [1] = 3.988708, }, randomize_indexes = {}, }, oval_bonding_conversation_cruelty_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_zealot_male_a__oval_bonding_conversation_cruelty_d_01", }, sound_events_duration = { [1] = 1.905188, }, randomize_indexes = {}, }, } return settings("psyker_male_c_zealot_male_a", psyker_male_c_zealot_male_a)
1
0.604189
1
0.604189
game-dev
MEDIA
0.693953
game-dev
0.84616
1
0.84616
geometer/FBReader-Android-2
3,997
fbreader/api/src/main/java/org/geometerplus/fbreader/book/Filter.java
/* * Copyright (C) 2007-2017 FBReader.ORG Limited <contact@fbreader.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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.fbreader.book; import java.util.List; public abstract class Filter { public abstract boolean matches(AbstractBook book); public final static class Empty extends Filter { public boolean matches(AbstractBook book) { return true; } } public final static class ByAuthor extends Filter { public final Author Author; public ByAuthor(Author author) { Author = author; } public boolean matches(AbstractBook book) { final List<Author> bookAuthors = book.authors(); return Author.NULL.equals(Author) ? bookAuthors.isEmpty() : bookAuthors.contains(Author); } } public final static class ByTag extends Filter { public final Tag Tag; public ByTag(Tag tag) { Tag = tag; } public boolean matches(AbstractBook book) { final List<Tag> bookTags = book.tags(); return Tag.NULL.equals(Tag) ? bookTags.isEmpty() : bookTags.contains(Tag); } } public final static class ByLabel extends Filter { public final String Label; public ByLabel(String label) { Label = label; } public boolean matches(AbstractBook book) { return book.hasLabel(Label); } } public final static class ByPattern extends Filter { public final String Pattern; public ByPattern(String pattern) { Pattern = pattern != null ? pattern.toLowerCase() : ""; } public boolean matches(AbstractBook book) { return book != null && !"".equals(Pattern) && book.matches(Pattern); } } public final static class ByTitlePrefix extends Filter { public final String Prefix; public ByTitlePrefix(String prefix) { Prefix = prefix != null ? prefix : ""; } public boolean matches(AbstractBook book) { return book != null && Prefix.equals(book.firstTitleLetter()); } } public final static class BySeries extends Filter { public final Series Series; public BySeries(Series series) { Series = series; } public boolean matches(AbstractBook book) { final SeriesInfo info = book.getSeriesInfo(); return info != null && Series.equals(info.Series); } } public final static class HasBookmark extends Filter { public boolean matches(AbstractBook book) { return book != null && book.HasBookmark; } } public final static class HasPhysicalFile extends Filter { public boolean matches(AbstractBook book) { return book != null && book.getPath().startsWith("/"); } } public final static class And extends Filter { public final Filter First; public final Filter Second; public And(Filter first, Filter second) { First = first; Second = second; } public boolean matches(AbstractBook book) { return First.matches(book) && Second.matches(book); } } public final static class Or extends Filter { public final Filter First; public final Filter Second; public Or(Filter first, Filter second) { First = first; Second = second; } public boolean matches(AbstractBook book) { return First.matches(book) || Second.matches(book); } } public final static class Not extends Filter { public final Filter Base; public Not(Filter base) { Base = base; } public boolean matches(AbstractBook book) { return !Base.matches(book); } } }
1
0.757749
1
0.757749
game-dev
MEDIA
0.562768
game-dev
0.780793
1
0.780793
eldexterr/ttyd64
9,952
map/src/sbk_13.mscr
% Script File: sbk_13.mscr % Decoded from: 0 to F00 (sbk_13) #define .NpcID:Pokey_00 00 #define .NpcID:Pokey_01 01 #define .NpcID:Bandit_02 02 #new:Function $Function_80240000 { 0: MTC1 R0, F0 4: ADDIU SP, SP, FFE0 8: MFC1 A1, F0 C: CLEAR A0 10: SW RA, 18 (SP) 14: SW R0, 14 (SP) 18: SWC1 F0, 10 (SP) 1C: COPY A2, A1 20: JAL ~Func:playFX_82 24: COPY A3, A1 28: LW RA, 18 (SP) 2C: LI V0, 2 30: JR RA 34: ADDIU SP, SP, 20 } PADDING: 80240038 to 80240040 (00000038 to 00000040) 00000000 00000000 #new:Function $Function_80240040 { 0: ADDIU SP, SP, FFD8 4: SW S3, 1C (SP) 8: COPY S3, A0 C: SW RA, 24 (SP) 10: SW S4, 20 (SP) 14: SW S2, 18 (SP) 18: SW S1, 14 (SP) 1C: SW S0, 10 (SP) 20: LW S0, C (S3) 24: BEQL A1, R0, .o9C 28: COPY A0, S3 2C: LW A1, 0 (S0) 30: JAL ~Func:get_variable 34: ADDIU S0, S0, 4 38: LW A1, 0 (S0) 3C: ADDIU S0, S0, 4 40: COPY A0, S3 44: JAL ~Func:get_variable 48: COPY S1, V0 4C: COPY S4, V0 50: LI V0, FFFF 54: LW S2, 0 (S0) 58: BNE S1, V0, .o6C 5C: LUI V0, EFE8 60: LW A0, 14C (S3) 64: BEQ R0, R0, .o80 68: NOP .o6C 6C: ORI V0, V0, 2080 70: SLT V0, S1, V0 74: BNE V0, R0, .o8C 78: COPY S0, S1 7C: COPY A0, S1 .o80 80: JAL ~Func:get_npc_unsafe 84: NOP 88: COPY S0, V0 .o8C 8C: SW S0, 70 (S3) 90: SW S4, 74 (S3) 94: SW S2, 78 (S3) 98: COPY A0, S3 .o9C 9C: LW S0, 70 (A0) A0: LW A1, 78 (A0) A4: JAL ~Func:get_variable A8: LW S4, 74 (A0) AC: BEQ V0, R0, .oE0 B0: LI V0, 2 B4: LWC1 F2, 3C (S0) B8: LIF F0, 30.0 C0: NOP C4: ADD.S F2, F2, F0 C8: LW A1, 38 (S0) CC: LW A3, 40 (S0) D0: MFC1 A2, F2 D4: JAL ~Func:set_item_entity_position D8: COPY A0, S4 DC: CLEAR V0 .oE0 E0: LW RA, 24 (SP) E4: LW S4, 20 (SP) E8: LW S3, 1C (SP) EC: LW S2, 18 (SP) F0: LW S1, 14 (SP) F4: LW S0, 10 (SP) F8: JR RA FC: ADDIU SP, SP, 28 } #new:Function $Function_80240140 { 0: LW V1, 148 (A0) 4: LI V0, 3 8: SB V0, B5 (V1) C: JR RA 10: LI V0, 2 } PADDING: 80240154 to 80240160 (00000154 to 00000160) 00000000 00000000 00000000 #new:EntryList $EntryList { ~Vec4f:Entry0 % -475.0 0.0 0.0 90.0 ~Vec4f:Entry1 % 475.0 0.0 0.0 270.0 ~Vec4f:Entry2 % 0.0 0.0 -475.0 180.0 ~Vec4f:Entry3 % 0.0 0.0 475.0 0.0 } #new:Header $Header { [MainScript] $Script_Main_EnterWalk [EntryList] $EntryList [EntryCount] 00000004 [Background] 80200000 [MapTattle] 0019006B } #new:Script $Script_ExitWalk_802401E0 { 0: SetGroup 0000001B C: Call UseExitHeading ( 0000003C ~Entry:Entry0 ) 20: Exec ExitWalk 2C: Call GotoMap ( $ASCII_80240EE0 00000001 ) % sbk_12 40: Wait 100` 4C: Return 54: End } #new:Script $Script_ExitWalk_8024023C { 0: SetGroup 0000001B C: Call UseExitHeading ( 0000003C ~Entry:Entry1 ) 20: Exec ExitWalk 2C: Call GotoMap ( $ASCII_80240EE8 00000000 ) % sbk_14 40: Wait 100` 4C: Return 54: End } #new:Script $Script_ExitWalk_80240298 { 0: SetGroup 0000001B C: Call UseExitHeading ( 0000003C ~Entry:Entry2 ) 20: Exec ExitWalk 2C: Call GotoMap ( $ASCII_80240EF0 00000003 ) % sbk_03 40: Wait 100` 4C: Return 54: End } #new:Script $Script_ExitWalk_802402F4 { 0: SetGroup 0000001B C: Call UseExitHeading ( 0000003C ~Entry:Entry3 ) 20: Exec ExitWalk 2C: Call GotoMap ( $ASCII_80240EF8 00000002 ) % sbk_23 40: Wait 100` 4C: Return 54: End } #new:Script $Script_80240350 { 0: Bind $Script_ExitWalk_802401E0 .Trigger:FloorAbove ~Collider:deiliw 00000001 00000000 1C: Bind $Script_ExitWalk_8024023C .Trigger:FloorAbove ~Collider:deilie 00000001 00000000 38: Bind $Script_ExitWalk_80240298 .Trigger:FloorAbove ~Collider:deilin 00000001 00000000 54: Bind $Script_ExitWalk_802402F4 .Trigger:FloorAbove ~Collider:deilis 00000001 00000000 70: Return 78: End } #new:Script_Main $Script_Main_EnterWalk { 0: Set *GB_WorldLocation .Location:DryDryDesert 10: Call SetSpriteShading ( .Shading:None ) 20: If *GB_StoryProgress == .Story:Ch2_GotPulseStone % FFFFFFC1 30: Call DisablePulseStone ( .False ) 40: EndIf 48: Call SetCamPerspective ( .Cam:Default 00000003 25` 16` 4096` ) 68: Call SetCamBGColor ( .Cam:Default 0` 0` 0` ) 84: Call SetCamEnabled ( .Cam:Default .True ) 98: Call SetCamLeadPlayer ( .Cam:Default .False ) AC: Call MakeNpcs ( .False $NpcGroupList_80240EA8 ) C0: Call $Function_80240000 ( ) CC: Call SetMusicTrack ( 00000000 .Song:DryDryDesert 00000000 00000008 ) E8: Set *Var0 $Script_80240350 F8: Exec EnterWalk 104: Return 10C: End } PADDING: 802404E4 to 802404F0 (000004E4 to 000004F0) 00000000 00000000 00000000 #new:Script $Script_802404F0 { 0: Set *VarA *Var0 10: Call GetNpcPos ( *VarA *Var1 *Var2 *Var3 ) 2C: Add *Var2 0000001E 3C: Call MakeItemEntity ( .Item:Coin *Var1 *Var2 *Var3 .ItemSpawnMode:Decoration 00000000 ) 60: Call $Function_80240040 ( *VarA *Var0 *AreaFlag[001] ) 78: Call RemoveItemEntity ( *Var0 ) 88: Return 90: End } #new:AISettings $AISettings_80240588 { 2.7 % move speed 45` % move time 30` % wait time 450.0 % alert radius 0.0 10` 8.3 % chase speed 180` 100` 550.0 % chase radius 100.0 1` } #new:Script $Script_NpcAI_802405B8 { 0: Call DoBasicAI ( $AISettings_80240588 ) 10: Return 18: End } #new:Script $Script_802405D8 { 0: Call GetBattleOutcome ( *Var0 ) 10: Switch *Var0 1C: Case == .Outcome:PlayerWon % 0 28: Call DoNpcDefeat ( ) 34: Case == .Outcome:PlayerFled % 2 40: Call 80045900 ( 00000000 ) 50: Case == .Outcome:EnemyFled % 3 5C: Call DisablePlayerInput ( .True ) 6C: Set *AreaFlag[001] .True 7C: Call SetNpcFlagBits ( .Npc:Self 00000040 .True ) 94: Call SetNpcAnimation ( .Npc:Self 00320002 ) A8: Call GetSelfNpcID ( *Var0 ) B8: Exec $Script_802404F0 C4: Call SetNpcJumpscale ( .Npc:Self *Fixed[1.0] ) D8: Call GetPlayerPos ( *Var7 *Var8 *Var9 ) F0: Add *Var7 00000014 100: Call NpcJump0 ( .Npc:Self *Var7 0` *Var9 6` ) 120: Add *Var7 00000014 130: Call NpcJump0 ( .Npc:Self *Var7 0` *Var9 6` ) 150: Call GetNpcYaw ( .Npc:Self *Var0 ) 164: Add *Var0 000000B4 174: Call InterpNpcYaw ( .Npc:Self *Var0 5` ) 18C: Call SetNpcAnimation ( .Npc:Self 00320008 ) 1A0: Wait 10` 1AC: Call SetNpcSpeed ( .Npc:Self *Fixed[16.0] ) 1C0: Add *Var7 000000C8 1D0: Call NpcMoveTo ( .Npc:Self *Var7 *Var9 0` ) 1EC: Set *AreaFlag[001] .False 1FC: Call DisablePlayerInput ( .False ) 20C: Call SetEnemyFlagBits ( .Npc:Self 00000010 00000001 ) 224: Call RemoveNpc ( .Npc:Self ) 234: EndSwitch 23C: Return 244: End } #new:NpcSettings $NpcSettings_80240824 { 00000000 001A0018 00000000 00000000 $Script_NpcAI_802405B8 80077F70 00000000 $Script_802405D8 00000000 00000000 00090005 } #new:AISettings $AISettings_80240850 { 1.8 % move speed 50` % move time 10` % wait time 250.0 % alert radius 0.0 2` 3.5 % chase speed 45` 6` 300.0 % chase radius 0.0 1` } #new:Script $Script_NpcAI_80240880 { 0: Call $Function_80240140 ( ) C: Call DoBasicAI ( $AISettings_80240850 ) 1C: Return 24: End } #new:NpcSettings $NpcSettings_802408AC { 00000000 0048000F 00000000 00000000 $Script_NpcAI_80240880 80077F70 00000000 8007809C 00000000 00000000 00090000 } #new:NpcGroup $NpcGroup_802408D8 { .NpcID:NPC_Pokey_00 $NpcSettings_802408AC ~Vec3f:NPC_Pokey_00 % -70 0 -60 00002C00 00000000 00000000 00000000 0000010E ~Items:15:DriedFruit:9:TastyTonic:1 ~HP:Standard:2 ~FP:Standard:2 ~CoinBonus:0:1 ~Movement:NPC_Pokey_00 ~AnimationTable:NPC_Pokey_00 % .Sprite:Pokey 00000001 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80240AC8 { .NpcID:NPC_Pokey_01 $NpcSettings_802408AC ~Vec3f:NPC_Pokey_01 % 120 0 -50 00002C00 00000000 00000000 00000000 0000010E ~Items:15:DriedFruit:9:TastyTonic:1 ~HP:Standard:2 ~FP:Standard:2 ~CoinBonus:0:1 ~Movement:NPC_Pokey_01 ~AnimationTable:NPC_Pokey_01 % .Sprite:Pokey 00000001 00000000 00000000 00000000 % no tattle string } #new:NpcGroup $NpcGroup_80240CB8 { .NpcID:NPC_Bandit_02 $NpcSettings_80240824 ~Vec3f:NPC_Bandit_02 % -200 0 230 00002C00 00000000 00000000 00000000 0000005A ~Items:5:HoneySyrup:A ~HP:Standard:2 ~FP:Standard:2 ~CoinBonus:1:3 ~Movement:NPC_Bandit_02 ~AnimationTable:NPC_Bandit_02 % .Sprite:Bandit 00000001 00000000 00000000 00000000 % no tattle string } #new:NpcGroupList $NpcGroupList_80240EA8 { 00000001 $NpcGroup_802408D8 0A040001 00000001 $NpcGroup_80240AC8 0A050001 00000001 $NpcGroup_80240CB8 0A0E0001 00000000 00000000 00000000 } PADDING: 80240ED8 to 80240EE0 (00000ED8 to 00000EE0) 00000000 00000000 #new:ASCII $ASCII_80240EE0 { "sbk_12" } #new:ASCII $ASCII_80240EE8 { "sbk_14" } #new:ASCII $ASCII_80240EF0 { "sbk_03" } #new:ASCII $ASCII_80240EF8 { "sbk_23" }
1
0.880421
1
0.880421
game-dev
MEDIA
0.972643
game-dev
0.840638
1
0.840638
swgemu/Core3
1,065
MMOCoreORB/src/server/zone/objects/creature/commands/CreateMissionElementCommand.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef CREATEMISSIONELEMENTCOMMAND_H_ #define CREATEMISSIONELEMENTCOMMAND_H_ #include "server/zone/managers/mission/MissionManager.h" class CreateMissionElementCommand : public QueueCommand { public: CreateMissionElementCommand(const String& name, ZoneProcessServer* server) : QueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { if (!checkStateMask(creature)) { return INVALIDSTATE; } if (!checkInvalidLocomotions(creature)) { return INVALIDLOCOMOTION; } if (!creature->isPlayerCreature()) { return GENERALERROR; } Reference<PlayerObject*> ghost = creature->getPlayerObject(); if (ghost == nullptr || !ghost->isPrivileged()) { return GENERALERROR; } //Try to create a mission NPC spawn point. creature->getZoneServer()->getMissionManager()->createSpawnPoint(creature, arguments.toString()); return SUCCESS; } }; #endif //CREATEMISSIONELEMENTCOMMAND_H_
1
0.960235
1
0.960235
game-dev
MEDIA
0.914466
game-dev
0.933552
1
0.933552
JohannesAutenrieb/MissileSimulation
8,331
Task 4-Control Gain Adjustment/Solution without Overshoot/Missile_Data.m
%/////////////////////////////////////////////////////////////////////////% % % % - Name: Missile_Data.m % % - Missile Parameters are defined % % % % - Created by Dr. C. H. Lee, 26/10/2018 % % % %/////////////////////////////////////////////////////////////////////////% %.. Global Variables global D l S Mass global I_xx I_yy I_zz I_TENSOR global XCG XREF ETA global Tbl_ALPHAT Tbl_MACH global Tbl_CX_0 Tbl_CX_ALPHAT Tbl_CX_DEL_EFF global Tbl_CY_PHIT Tbl_CY_DEL_Y global Tbl_CZ_0 Tbl_CZ_PHIT Tbl_CZ_DEL_P global Tbl_CL_ALPHAT Tbl_CL_P Tbl_CL_DEL_R global Tbl_CM_0 Tbl_CM_PHIT Tbl_CM_Q Tbl_CM_DEL_P global Tbl_CN_PHIT Tbl_CN_R Tbl_CN_DEL_Y global Wn_Act Zeta_Act global K_phi K_p global K_DC K_A global Omega_i K_R %.. Missile Configuration Data D = 0.150 ; % Missile diameter (m) l = 1.618 ; % Missile length (m) S = ( pi / 4 ) * D^2 ; % Missile area (m^2) Mass = 30.0 ; % Mass (kg) I_xx = 0.5 * Mass * ( D / 2 )^2 ; % Ixx Moment of Inertia (kg*m^2) I_yy = Mass * ( ( 1 / 12 ) * l^2 + ( 1 / 4 ) * ( D / 2 )^2 ) ; % Iyy moment of inertia (kg*m^2) I_zz = I_yy ; % Izz moment of inertia (kg*m^2) I_TENSOR = [ I_xx, 0.0, 0.0 ; % Moment of Inertia Tensor 0.0, I_yy, 0.0 ; 0.0, 0.0, I_zz ] ; ETA = 1; % Self defined Propulsion Efficiency XCG = 0.809 ; % Missile C.G. Point XREF = 0.809 ; % Missile Moment Reference Point %.. Actuator Parameters Wn_Act = 25.0 * 2 * pi ; % Natural Frequency (rad) Zeta_Act = 0.707 ; % Damping Ratio %.. Control Gains K_phi = 20.0 ; K_p = 0.01 ; K_DC = 0.96 ; K_A = 0.87; Omega_i = -0.11 ; K_R = 0.0254 ; %.. Missile Aerodynamics Data % Total Angle-of-Attack Table Tbl_ALPHAT = [ 0 4 8 12 16 ] ; % Size: 1x5, Unit: Deg % Mach Table Tbl_MACH = [ 0.2 0.3 0.4 0.5 0.6 0.7 ] ; % Size: 1x6 % Force Coefficent: CX_a Tbl_CX_0 = [ -0.3840 -0.3670 -0.3550 -0.3460 -0.3390 -0.3410 ] ; % Size: 1x6 (1 x Mach) Tbl_CX_ALPHAT = [ 0.0788 0.0752 0.0680 0.0573 0.0573 0.0573 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) Tbl_CX_DEL_EFF = [ -16.8080 -17.8585 -18.9090 -19.9595 -20.4847 -23.1110 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad^2) % Force Coefficient: CY_a Tbl_CY_PHIT = [ 0 0.0070 0.0819 0.2313 0.2992 ; % Size: 6x5 (Mach x Alphat) 0 -0.0055 -0.0123 0.0465 0.2165 ; 0 -0.0091 -0.0211 -0.0263 0.0947 ; 0 -0.0095 -0.0256 -0.0380 0.0588 ; 0 -0.0082 -0.0197 -0.0209 0.1315 ; 0 -0.0071 -0.0155 0.0151 0.1986 ] ; Tbl_CY_DEL_Y = [ 5.3056 5.7754 6.0504 6.3484 6.6921 7.5745 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) % Force Coefficient: CZ_a Tbl_CZ_0 = [ 0 -2.0680 -3.9700 -5.4250 -6.6810 ; % Size: 6x5 (Mach x Alphat) 0 -2.2120 -4.5150 -6.8060 -8.7160 ; 0 -2.2980 -4.7050 -7.1210 -9.4680 ; 0 -2.3980 -4.8930 -7.4010 -9.7670 ; 0 -2.5200 -5.0980 -7.6390 -9.9650 ; 0 -2.8400 -5.6970 -8.4430 -10.9750 ] ; Tbl_CZ_PHIT = [ 0 0.0089 0.1842 0.3041 0.2039 ; % Size: 6x5 (Mach x Alphat) 0 -0.0083 -0.0190 0.2455 0.5956 ; 0 -0.0128 -0.0227 0.0414 0.5061 ; 0 -0.0132 -0.0299 -0.0095 0.4190 ; 0 -0.0114 -0.0172 0.0701 0.5930 ; 0 -0.0096 -0.0150 0.1713 0.6371 ] ; Tbl_CZ_DEL_P = [ -5.3056 -5.7754 -6.0504 -6.3484 -6.6921 -7.5745 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) % Moment Coefficients: CL_a Tbl_CL_ALPHAT = [ -0.0988 -0.4859 -0.5870 -0.4802 -0.3334 -0.0210 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad^2) Tbl_CL_P = [ -17.9516 -19.6297 -20.9956 -22.5566 -24.5079 -28.6446 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) Tbl_CL_DEL_R = [ 5.2712 5.7640 6.1650 6.6234 7.1963 8.4110 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) % Moment Coefficients: CM_a Tbl_CM_0 = [ 0 -2.2250 -3.9280 -4.8580 -5.6940 ; % Size: 6x5 (Mach x Alphat) 0 -2.4400 -4.8390 -7.1140 -8.8060 ; 0 -2.5620 -5.1360 -7.7210 -10.1410 ; 0 -2.6960 -5.4180 -8.1510 -10.8370 ; 0 -2.8500 -5.6900 -8.5340 -11.0690 ; 0 -3.2270 -6.3940 -9.5510 -12.2020 ] ; Tbl_CM_PHIT = [ 0 -0.0024 -0.0898 -0.2360 -0.3546 ; % Size: 6x5 (Mach x Alphat) 0 0.0146 0.0788 0.2141 -0.0555 ; 0 0.0192 0.0986 0.2398 0.3490 ; 0 0.0203 0.0991 0.2130 0.4609 ; 0 0.0187 0.0925 0.2269 0.3662 ; 0 0.0167 0.0852 0.2257 0.3085 ] ; Tbl_CM_Q = [ -82.9643 -47.4409 -32.7732 -16.7304 -43.2010 -56.1499 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) Tbl_CM_DEL_P = [ -20.7182 -22.5631 -23.6059 -24.7632 -26.1269 -29.5646 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) % Moment Coefficients: CN_a Tbl_CN_PHIT = [ 0 0.0040 0.0098 0.1116 0.3049 ; % Size: 6x5 (Mach x Alphat) 0 -0.0083 -0.0512 -0.1318 -0.0988 ; 0 -0.0114 -0.0616 -0.1309 -0.2168 ; 0 -0.0118 -0.0628 -0.1283 -0.2441 ; 0 -0.0107 -0.0584 -0.1174 -0.2240 ; 0 -0.0093 -0.0551 -0.1103 -0.2245 ] ; Tbl_CN_R = [ -82.9643 -47.4409 -32.7732 -16.7304 -43.2010 -56.1499 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad) Tbl_CN_DEL_Y = [ -0.3616 -0.3938 -0.4120 -0.4322 -0.4560 -0.5160 ] ; % Size: 1x6 (1 x Mach), Unit: (1/rad)
1
0.638255
1
0.638255
game-dev
MEDIA
0.290972
game-dev
0.921675
1
0.921675
magefree/mage
3,698
Mage.Sets/src/mage/cards/e/EchoingDeeps.java
package mage.cards.e; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldAbility; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.CopyEffect; import mage.abilities.effects.common.TapSourceEffect; import mage.abilities.mana.ColorlessManaAbility; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.SubType; import mage.filter.FilterCard; import mage.game.Game; import mage.game.permanent.Permanent; import mage.game.permanent.PermanentCard; import mage.players.Player; import mage.target.Target; import mage.target.common.TargetCardInGraveyard; import mage.util.functions.CopyApplier; import java.util.UUID; /** * @author Susucr */ public final class EchoingDeeps extends CardImpl { public EchoingDeeps(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.LAND}, ""); this.subtype.add(SubType.CAVE); // You may have Echoing Deeps enter the battlefield tapped as a copy of any land card in a graveyard, except it's a Cave in addition to its other types. this.addAbility(new EntersBattlefieldAbility(new EchoingDeepsEffect(), true)); // {T}: Add {C}. this.addAbility(new ColorlessManaAbility()); } private EchoingDeeps(final EchoingDeeps card) { super(card); } @Override public EchoingDeeps copy() { return new EchoingDeeps(this); } } class EchoingDeepsEffect extends OneShotEffect { private static final FilterCard filter = new FilterCard("land card in a graveyard"); static { filter.add(CardType.LAND.getPredicate()); } EchoingDeepsEffect() { super(Outcome.Copy); staticText = "tapped as a copy of any land card in a graveyard, except it's a Cave in addition to its other types"; } private EchoingDeepsEffect(final EchoingDeepsEffect effect) { super(effect); } @Override public EchoingDeepsEffect copy() { return new EchoingDeepsEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); MageObject sourcePermanent = game.getPermanentEntering(source.getSourceId()); if (sourcePermanent == null) { sourcePermanent = game.getObject(source); } if (controller == null || sourcePermanent == null) { return false; } Target target = new TargetCardInGraveyard(0, 1, filter, false); controller.choose(Outcome.Copy, target, source, game); Card copyTo = game.getCard(target.getFirstTarget()); if (copyTo == null) { return false; } new TapSourceEffect(true).apply(game, source); Permanent newBluePrint = new PermanentCard(copyTo, source.getControllerId(), game); newBluePrint.assignNewId(); CopyApplier applier = new EchoingDeepsApplier(); applier.apply(game, newBluePrint, source, source.getSourceId()); CopyEffect copyEffect = new CopyEffect(Duration.WhileOnBattlefield, newBluePrint, source.getSourceId()); copyEffect.setApplier(applier); copyEffect.init(source, game); game.addEffect(copyEffect, source); return true; } } class EchoingDeepsApplier extends CopyApplier { @Override public boolean apply(Game game, MageObject blueprint, Ability source, UUID targetObjectId) { blueprint.addSubType(SubType.CAVE); return true; } }
1
0.987478
1
0.987478
game-dev
MEDIA
0.972384
game-dev
0.993617
1
0.993617
Testing-Game-SAD-2023/A13
4,951
T5-G2/t5/src/main/java/com/g2/game/GameModes/PartitaSingola.java
package com.g2.game.GameModes; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.g2.game.GameFactory.params.GameParams; import com.g2.game.GameFactory.params.PartitaSingolaParams; import com.g2.game.GameModes.Compile.CompileResult; import com.g2.interfaces.ServiceManager; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import testrobotchallenge.commons.models.opponent.GameMode; import testrobotchallenge.commons.models.opponent.OpponentDifficulty; import testrobotchallenge.commons.models.opponent.OpponentType; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") @Getter @Setter @ToString public class PartitaSingola extends GameLogic { @JsonIgnore private static final Logger logger = LoggerFactory.getLogger(PartitaSingola.class); @JsonProperty("userScore") private int userScore; @JsonProperty("robotScore") private int robotScore; @JsonProperty("remainingTime") private int remainingTime; public PartitaSingola(){ //Costruttore vuoto } //Questa classe si specializza in una partita singola basata sui turni, prende il nome di Partita Singola nella UI public PartitaSingola(ServiceManager serviceManager, Long PlayerID, String ClasseUT, OpponentType type_robot, OpponentDifficulty difficulty, GameMode gameMode, String testingClassCode) { super(serviceManager, PlayerID, ClasseUT, type_robot, difficulty, gameMode, testingClassCode); } public PartitaSingola(ServiceManager serviceManager, Long PlayerID, String ClasseUT, OpponentType type_robot, OpponentDifficulty difficulty, GameMode gamemode, String testingClassCode, int remainingTime) { super(serviceManager, PlayerID, ClasseUT, type_robot, difficulty, gamemode, testingClassCode); this.remainingTime = remainingTime; } @Override public void updateState(GameParams gameParams, CompileResult userCompileResult, CompileResult robotCompileResult) { if (!(gameParams instanceof PartitaSingolaParams)) throw new IllegalArgumentException("Impossibile aggiornare la logica corrente, i parametri ricevuti non son istanza di PartitaSingolaParams"); super.updateState(gameParams, userCompileResult, robotCompileResult); this.remainingTime = ((PartitaSingolaParams) gameParams).getRemainingTime(); } @Override public void NextTurn(CompileResult userCompileResult, CompileResult robotScore) { this.robotScore = GetScore(userCompileResult); this.userScore = GetScore(userCompileResult); CreateTurn(); logger.info("Created turn {} for game {}", this.getCurrentTurn(), this.getGameID()); EndTurn(userCompileResult); System.out.println("[GAME] Turn " + getCurrentTurn() + " played. User Score: " + userScore + ", Robot Score: " + robotScore); } @Override public Boolean isGameEnd() { return false; //il giocatore può fare quanti turni vuole quindi ritorno sempre false } @Override public Boolean isWinner(){ return userScore > 0 && robotScore > 0 && userScore >= robotScore; } @Override public int GetScore(CompileResult compileResult) { // Se loc è 0, il punteggio è sempre 0 int coverage = compileResult.getInstructionCoverage().getCovered(); if (coverage == 0) { return 0; } // Calcolo della percentuale int total = coverage + compileResult.getInstructionCoverage().getMissed(); double locPerc = (double) coverage / (double) total; return (int) Math.ceil(locPerc * 100); } @Override public Map<String, BiFunction<CompileResult, CompileResult, Boolean>> gameModeAchievements() { Map<String, BiFunction<CompileResult, CompileResult, Boolean>> verifyBeaten = new HashMap<>(); verifyBeaten.put("instructions", this::beatOnJacocoInstructionCoverage); verifyBeaten.put("instructionsAndWeakMutation", (user, robot) -> beatOnJacocoInstructionCoverage(user, robot) && beatOnEvosuiteWeakMutationCoverage(user, robot)); logger.info("gameModeAchievement: {}", verifyBeaten); return verifyBeaten; } private Boolean beatOnJacocoInstructionCoverage(CompileResult user, CompileResult robot) { return user.getInstructionCoverage().getCovered() > robot.getInstructionCoverage().getCovered(); } private Boolean beatOnEvosuiteWeakMutationCoverage(CompileResult user, CompileResult robot) { return user.getEvosuiteWeakMutation().getCovered() > robot.getEvosuiteWeakMutation().getCovered(); } }
1
0.81544
1
0.81544
game-dev
MEDIA
0.629132
game-dev,testing-qa
0.664513
1
0.664513
BarrierTrio/Cardsauce
2,132
items/vhs/ryansbabe.lua
local consumInfo = { name = "Ryan's Babe", key = 'ryansbabe', set = "VHS", cost = 3, alerted = true, config = { activation = true, activated = false, destroyed = false, extra = { runtime = 3, uses = 0, }, }, origin = 'rlm' } function consumInfo.loc_vars(self, info_queue, card) info_queue[#info_queue+1] = G.P_CENTERS.m_bonus info_queue[#info_queue+1] = {key = "vhs_activation", set = "Other"} info_queue[#info_queue+1] = {key = "csau_artistcredit", set = "Other", vars = { G.csau_team.yunkie } } return { vars = { card.ability.extra.runtime-card.ability.extra.uses } } end function consumInfo.calculate(self, card, context) if card.ability.activated and context.before and not card.debuff and not context.blueprint and G.FUNCS.hand_contains_rank(context.scoring_hand, {12}) then for i, v in ipairs(context.scoring_hand) do if v:get_id() == 12 and v.ability.effect == "Base" and not v.debuff and not card.ability.destroyed then v:set_ability(G.P_CENTERS.m_bonus, nil, true) G.E_MANAGER:add_event(Event({ func = function() v:juice_up() return true end })) end end return { message = localize('k_ryansbabe'), colour = G.C.CHIPS, card = card } end local bad_context = context.repetition or context.individual or context.blueprint if context.after and not card.ability.destroyed and card.ability.activated and not bad_context then card.ability.extra.uses = card.ability.extra.uses+1 if to_big(card.ability.extra.uses) >= to_big(card.ability.extra.runtime) then G.FUNCS.destroy_tape(card) card.ability.destroyed = true end end end function consumInfo.can_use(self, card) if to_big(#G.consumeables.cards) < to_big(G.consumeables.config.card_limit) or card.area == G.consumeables then return true end end return consumInfo
1
0.916506
1
0.916506
game-dev
MEDIA
0.951602
game-dev
0.97778
1
0.97778
3UR/Simpsons-Hit-Run
6,610
src/game/ai/vehicle/trafficai.h
//============================================================================= // Copyright (C) 2002 Radical Entertainment Ltd. All rights reserved. // // File: trafficai.h // // Description: Blahblahblah // // History: 09/09/2002 + Accel/Decel behavior -- Dusit Eakkachaichanvet // 06/08/2002 + Created -- Cary Brisebois // //============================================================================= #ifndef TRAFFICAI_H #define TRAFFICAI_H //======================================== // Nested Includes //======================================== #include <roads/intersection.h> #include <roads/lane.h> #include <roads/road.h> #include <worldsim/redbrick/vehiclecontroller/aivehiclecontroller.h> //======================================== // Forward References //======================================== class Vehicle; class TrafficAI : public AiVehicleController { public: // METHODS static const float SECONDS_LOOKAHEAD; static const float LOOKAHEAD_MIN; //What is the traffic AI up to? enum State { DEAD, DRIVING, WAITING_AT_INTERSECTION, WAITING_FOR_FREE_LANE, LANE_CHANGING, SPLINING, SWERVING, NUM_STATES }; //Which way does he want to turn? enum Direction { LEFT, RIGHT, STRAIGHT, NUM_DIRECTIONS }; //static const float LANE_CHANGE_DIST; TrafficAI( Vehicle* vehicle ); virtual ~TrafficAI(); void Init(); void Init( Vehicle* vehicle, Lane* lane, unsigned int laneIndex, RoadSegment* segment, unsigned int segmentIndex, float t, float mps ); void Update( float seconds ); State GetState() const; void SetState(State state); void SetLane( Lane* lane ); Lane* GetLane(); void SetLaneIndex( unsigned int index ); unsigned int GetLaneIndex() const; float GetLaneLength() const; void SetSegment( RoadSegment* segment ); RoadSegment* GetSegment() const; void SetSegmentIndex( unsigned int index ); unsigned int GetSegmentIndex() const; void SetLanePosition( float t ); float GetLanePosition(); void SetAISpeed( float mps ); float GetAISpeed() const; Direction DecideTurn(); void RegisterDebugInfo(); void UnregisterDebugInfo(); void RegisterAI(); void UnregisterAI(); void StartSwerving( bool swerveRight ); enum ObstacleType { OT_NOTHING = 0, OT_NONPLAYERVEHICLE = 1, OT_NONPLAYERCHARACTER = 2, OT_PLAYERCHARACTER = 3, OT_PLAYERVEHICLE = 4, OT_ENDOFROAD = 99 }; void CheckForObstacles( ObstacleType& objID, float& distFromObjSqr, void*& obj, bool& objOnMyRight ); public: // MEMBERS // Breaking architecture a bit. TrafficLocomotion is the one that // needs to detect when we're inside/outside an intersection. So we allow it // to set a TrafficAI flag in this instance. But how to ensure that only // TrafficLocomotion is allowed to call this function? Hence a small // breakage. void SetIsInIntersection( bool value ); Lane* mPrevLane; // for when we're in an intersection, it's the IN lane bool mIsActive : 1; bool mNeedToSuddenlyStop : 1; rmt::Vector mLookAheadPt; private: // MEMBERS State mState; State mPrevState; Direction mDirection; Lane* mLane; // curr lane when not in intersection, OUT lane when in intersection unsigned int mLaneIndex; float mLaneLength; RoadSegment* mSegment; unsigned int mSegmentIndex; float mT; //t float mAISpeed; //mps float mSecondsDriving; const Intersection* mPrevIntersection; float mStopForSomethingDecel; int mRenderHandle; float mSecondsSinceLastTriggeredImpedence; void* mLastThingThatImpededMe; float mSecondsSinceLaneChange; float mSecondsSwerving; float mOriginalMaxWheelTurnAngle; bool mIsInIntersection : 1; bool mSwervingLeft : 1; bool mSwerveHighBeamOn : 1; float mOriginalHeadlightScale; float mSecondsSwerveHighBeam; // used for waiting at intersection state rmt::Vector mEndOfRoadPos; private: // METHODS // returns triangular vertices of frustrum void GetFrustrum( const rmt::Vector& pos, const rmt::Vector& dir, rmt::Vector& leftFrustrumVertex, rmt::Vector& rightFrustrumVertex ); float GetGoSpeedMps(); bool AttemptLaneChange( ObstacleType foundSOMETHING, float distFromSOMETHINGSqr, void* SOMETHING ); void MaintainSpeed( float seconds ); void StopForSomething( float seconds, ObstacleType ID, float distSqr, void* obj ); void PerhapsTriggerImpedence( ObstacleType foundSOMETHING, float distSqr, void* SOMETHING ); void StopSwerving(); void Swerve(); float GetLookAheadDistance(); //Prevent wasteful constructor creation. TrafficAI( const TrafficAI& trafficai ); TrafficAI& operator=( const TrafficAI& trafficai ); }; //***************************************************************************** // // Inline Public Member Functions // //***************************************************************************** inline void TrafficAI::SetIsInIntersection( bool value ) { mIsInIntersection = value; } inline TrafficAI::State TrafficAI::GetState() const { return mState; } inline void TrafficAI::SetLane( Lane* lane ) { mPrevLane = mLane; mLane = lane; } inline Lane* TrafficAI::GetLane() { return mLane; } inline float TrafficAI::GetLaneLength() const { return mLaneLength; } inline void TrafficAI::SetLaneIndex( unsigned int index ) { mLaneIndex = index; } inline unsigned int TrafficAI::GetLaneIndex() const { return mLaneIndex; } inline void TrafficAI::SetSegment( RoadSegment* segment ) { mSegment = segment; } inline RoadSegment* TrafficAI::GetSegment() const { return mSegment; } inline unsigned int TrafficAI::GetSegmentIndex() const { return mSegmentIndex; } inline void TrafficAI::SetLanePosition( float t ) { mT = t; } inline float TrafficAI::GetLanePosition() { return mT; } inline void TrafficAI::SetState(State state) { mPrevState = mState; mState = state; //rDebugPrintf( "TrafficAI: Statechange: %d -> %d\n", mPrevState, mState ); } #endif //TRAFFICAI_H
1
0.909917
1
0.909917
game-dev
MEDIA
0.619283
game-dev
0.983059
1
0.983059
skadistats/clarity-examples
5,580
src/main/java/skadistats/clarity/examples/spawngroups/Main.java
package skadistats.clarity.examples.spawngroups; import com.google.protobuf.ByteString; import com.google.protobuf.ZeroCopy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import skadistats.clarity.io.Util; import skadistats.clarity.io.bitstream.BitStream; import skadistats.clarity.processor.entities.UsesEntities; import skadistats.clarity.processor.reader.OnMessage; import skadistats.clarity.processor.runner.SimpleRunner; import skadistats.clarity.source.MappedFileSource; import skadistats.clarity.util.LZSS; import skadistats.clarity.wire.shared.s2.proto.S2NetworkBaseTypes; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @UsesEntities public class Main { private final Logger log = LoggerFactory.getLogger(Main.class.getPackage().getClass()); private void parse(ByteString raw) throws IOException { BitStream bs = BitStream.createBitStream(raw); boolean isCompressed = bs.readBitFlag(); int size = bs.readUBitInt(24); byte[] data; if (isCompressed) { data = LZSS.unpack(bs); } else { data = new byte[size]; bs.readBitsIntoByteArray(data, size * 8); } bs = BitStream.createBitStream(ZeroCopy.wrap(data)); List<String> types = new ArrayList<>(); List<String> dirs = new ArrayList<>(); int nTypes = bs.readUBitInt(16); int nDirs = bs.readUBitInt(16); int nEntries = bs.readUBitInt(16); for (int i = 0; i < nTypes; i++) { types.add(bs.readString(Integer.MAX_VALUE)); } for (int i = 0; i < nDirs; i++) { dirs.add(bs.readString(Integer.MAX_VALUE)); } int bitsForType = Math.max(1, Util.calcBitsNeededFor(types.size() - 1)); int bitsForDir = Math.max(1, Util.calcBitsNeededFor(dirs.size() - 1)); System.out.format("\n\nbitsForType: %d, bitsForDir: %d, nEntries: %d\n", bitsForType, bitsForDir, nEntries); System.out.printf("dirs: %s\n", dirs); System.out.printf("types: %s\n", types); for (int i = 0; i < nEntries; i++) { int x = bs.readUBitInt(bitsForDir); String s = bs.readString(Integer.MAX_VALUE); int y = bs.readUBitInt(bitsForType); System.out.format("[%03d] %s%s.%s\n", i, dirs.get(x), s, types.get(y)); } System.out.format("finished %d/%d\n\n", bs.pos(), bs.len()); } private final Set<Integer> loaded = new LinkedHashSet<>(); private final Set<Integer> complete = new LinkedHashSet<>(); private final Set<Integer> created = new LinkedHashSet<>(); @OnMessage(S2NetworkBaseTypes.CNETMsg_SpawnGroup_Load.class) public void onLoad(S2NetworkBaseTypes.CNETMsg_SpawnGroup_Load message) throws IOException { System.out.println("LOAD ----------------------------------------------------------------------------------------------"); System.out.println(message); parse(message.getSpawngroupmanifest()); loaded.add(message.getSpawngrouphandle()); if (!message.getManifestincomplete()) { complete.add(message.getSpawngrouphandle()); } } @OnMessage(S2NetworkBaseTypes.CNETMsg_SpawnGroup_LoadCompleted.class) public void onLoadCompleted(S2NetworkBaseTypes.CNETMsg_SpawnGroup_LoadCompleted message) { System.out.println("LOADCOMPLETED ----------------------------------------------------------------------------------------------"); System.out.println(message); } @OnMessage(S2NetworkBaseTypes.CNETMsg_SpawnGroup_ManifestUpdate.class) public void onManifestUpdate(S2NetworkBaseTypes.CNETMsg_SpawnGroup_ManifestUpdate message) throws IOException { System.out.println("MANIFEST UPDATE ----------------------------------------------------------------------------------------------"); System.out.println(message); parse(message.getSpawngroupmanifest()); if (!message.getManifestincomplete()) { complete.add(message.getSpawngrouphandle()); } } @OnMessage(S2NetworkBaseTypes.CNETMsg_SpawnGroup_SetCreationTick.class) public void onSetCreationTick(S2NetworkBaseTypes.CNETMsg_SpawnGroup_SetCreationTick message) { System.out.println("SET CREATION TICK ----------------------------------------------------------------------------------------------"); System.out.println(message); created.add(message.getSpawngrouphandle()); } @OnMessage(S2NetworkBaseTypes.CNETMsg_SpawnGroup_Unload.class) public void onUnload(S2NetworkBaseTypes.CNETMsg_SpawnGroup_Unload message) { System.out.println("UNLOAD ----------------------------------------------------------------------------------------------"); System.out.println(message); } public void run(String[] args) throws Exception { new SimpleRunner(new MappedFileSource(args[0])).runWith(this); System.out.println("LOADED " + loaded); System.out.println("COMPLETED " + complete); System.out.println("CREATED " + created); HashSet<Integer> lbnc = new HashSet<>(loaded); lbnc.removeAll(created); System.out.println("LOADED BUT NOT CREATED " + lbnc); lbnc = new HashSet<>(loaded); lbnc.removeAll(complete); System.out.println("LOADED BUT NOT COMPLETED " + lbnc); } public static void main(String[] args) throws Exception { new Main().run(args); } }
1
0.81242
1
0.81242
game-dev
MEDIA
0.628422
game-dev,networking
0.899305
1
0.899305
Hex27/TerraformGenerator
5,544
common/src/main/java/org/terraform/structure/pillager/outpost/OutpostStakeCage.java
package org.terraform.structure.pillager.outpost; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; import org.terraform.biome.BiomeBank; import org.terraform.coregen.populatordata.PopulatorDataAbstract; import org.terraform.data.SimpleBlock; import org.terraform.data.Wall; import org.terraform.structure.room.CubeRoom; import org.terraform.structure.room.RoomPopulatorAbstract; import org.terraform.utils.BlockUtils; import org.terraform.utils.GenUtils; import org.terraform.utils.WoodUtils; import org.terraform.utils.WoodUtils.WoodType; import org.terraform.utils.version.V_1_19; import org.terraform.utils.version.Version; import java.util.Map.Entry; import java.util.Random; public class OutpostStakeCage extends RoomPopulatorAbstract { private final BiomeBank biome; private final Material[] stakeGravel; public OutpostStakeCage(Random rand, boolean forceSpawn, boolean unique, BiomeBank biome, Material... stakeGravel) { super(rand, forceSpawn, unique); this.biome = biome; this.stakeGravel = stakeGravel; } public void populate(@NotNull PopulatorDataAbstract data, @NotNull CubeRoom room) { Material fenceMat = WoodUtils.getWoodForBiome(biome, WoodType.FENCE); Material plankMat = WoodUtils.getWoodForBiome(biome, WoodType.PLANKS); int[] lowerCorner = room.getLowerCorner(2); int[] upperCorner = room.getUpperCorner(2); int highestHeight = 0; for (int nx = lowerCorner[0]; nx <= upperCorner[0]; nx++) { for (int nz = lowerCorner[1]; nz <= upperCorner[1]; nz++) { SimpleBlock target = new SimpleBlock(data, nx, 0, nz); int y = target.getGroundOrSeaLevel().getY(); if (y > highestHeight) { highestHeight = y; } target.lsetType(plankMat); new Wall(target).downUntilSolid(rand, fenceMat); } } for (Entry<Wall, Integer> entry : room.getFourWalls(data, 2).entrySet()) { Wall w = entry.getKey().getGroundOrSeaLevel().getUp(); for (int i = 0; i < entry.getValue(); i++) { int baseHeight = 4 + highestHeight - w.getY(); if (i % 2 == 0) { spawnOneStake(rand, baseHeight, w.get()); } else { int fenceHeight = baseHeight + 2 + rand.nextInt(3); w.RPillar(fenceHeight, rand, fenceMat); w.CorrectMultipleFacing(fenceHeight); } w = w.getLeft().getGroundOrSeaLevel().getUp(); } } if (Version.VERSION.isAtLeast(Version.v1_19_4)) { // Spawn the mob. switch (rand.nextInt(3)) { case 0: // Iron Golem data.addEntity(room.getX(), new SimpleBlock(data, room.getX(), room.getY(), room.getZ()).getGroundOrDry().getY() + 1, room.getZ(), EntityType.IRON_GOLEM ); break; case 1: // Allay (1 to 3) for (int i = 0; i < 1 + rand.nextInt(3); i++) { data.addEntity( room.getX(), new SimpleBlock(data, room.getX(), room.getY(), room.getZ()).getGroundOrDry().getY() + 1, room.getZ(), V_1_19.ALLAY ); } // If spawning allays, a roof must be added to the cage. for (int nx = lowerCorner[0]; nx <= upperCorner[0]; nx++) { for (int nz = lowerCorner[1]; nz <= upperCorner[1]; nz++) { int baseHeight = 6 + highestHeight; SimpleBlock target = new SimpleBlock(data, nx, baseHeight, nz); target.setType(plankMat); } } break; case 2: // Nothing break; } } else { if (rand.nextBoolean()) { data.addEntity( room.getX(), new SimpleBlock(data, room.getX(), room.getY(), room.getZ()).getGroundOrDry().getY() + 1, room.getZ(), EntityType.IRON_GOLEM ); } } } public void spawnOneStake(@NotNull Random rand, int baseHeight, @NotNull SimpleBlock base) { WoodType type = new WoodType[] {WoodType.LOG, WoodType.STRIPPED_LOG}[rand.nextInt(2)]; int h = baseHeight + GenUtils.randInt(1, 3); for (BlockFace face : BlockUtils.directBlockFaces) { if (rand.nextBoolean()) { base.getRelative(face).setType(stakeGravel); } } new Wall(base).Pillar(h, rand, WoodUtils.getWoodForBiome(biome, type)); new Wall(base.getRelative(0, h, 0)).Pillar( GenUtils.randInt(2, 3), rand, WoodUtils.getWoodForBiome(biome, WoodType.FENCE) ); } @Override public boolean canPopulate(CubeRoom room) { return true; } }
1
0.804512
1
0.804512
game-dev
MEDIA
0.8332
game-dev
0.838688
1
0.838688
caligari87/ObAddon
7,431
src/modules/zdoom_frozsoul_sound.lua
---------------------------------------------------------------- -- MODULE: ZDoom Ambient Sound Addon ---------------------------------------------------------------- -- -- Copyright (C) 2019-2020 MsrSgtShooterPerson -- Copyright (C) 2019-2020 Frozsoul -- -- 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. -- ------------------------------------------------------------------- -- Special thanks to Scionox for assisting with the preliminary build! --------------------------------- -- How to add your own sounds: -- --------------------------------- -- DECORATE and SNDINFO code are all generated by Oblige. -- Go to zdoom_sounds.lua to add new data to the table. -- Each new entry added means Oblige will generate a SNDINFO -- chunk as well as decorate code for each entry. -- Thing ID's are dynamically assigned based on the -- PARAM.snd_start_id selected on the module. -- The module also handles the actual replacement of sound spot -- specials (thing 8185) in prefab WAD's with the appropriate -- sound. See gtd_pic_tec_controlroom fab WAD and Lua def as an example. -- In order to specify what sound to replace a sound spot with, -- declare a "sound" field in the prefab Lua def. The sound field -- can contain a single string pertaining to a sound name in the -- sound data table, or list of names and probabilities whereas -- Oblige will randomly pick between each. -- The actual sound files (OGG, WAV, MP3 etc.) are NOT part of -- the module and are instead contained in a separate WAD file -- to be loaded separately during play. gui.import("zdoom_sounds.lua") ZDOOM_SOUND = {} ZDOOM_SOUND.ACTOR_ID_OFFSET_CHOICES = { "20000", _("20000"), "22000", _("22000"), "24000", _("24000"), "26000", _("26000"), "28000", _("28000"), "30000", _("30000"), } ZDOOM_SOUND.SOUND_ACTOR_DENSITY = 5 ZDOOM_SOUND.DEFAULT_A_PLAYSOUND_ARGS = "CHAN_AUTO, 1, true" ZDOOM_SOUND.TEMPLATES = { DEC = [[actor ACTORNAME IDNUM { +THRUACTORS +NOBLOCKMAP +NOSECTOR +DONTSPLASH Scale 0 Radius 4 Height 4 States { Spawn: CAND A 1 A_PlaySound("SOUNDNAME", ARGHS) Loop } } ]] } function ZDOOM_SOUND.build_lumps() local offset_count = tonumber(PARAM.snd_start_id) local sndtable = table.deep_copy(ZDOOM_SOUND_DEFS) SCRIPTS.SOUND_DEC = "" SCRIPTS.SNDINFO = "" table.name_up(sndtable) for _,sound in pairs(sndtable) do ZDOOM_SOUND_DEFS[_].id = offset_count -- build DECORATE chunk local dec_chunk = ZDOOM_SOUND.TEMPLATES.DEC dec_chunk = string.gsub(dec_chunk, "ACTORNAME", sound.name) dec_chunk = string.gsub(dec_chunk, "IDNUM", offset_count) dec_chunk = string.gsub(dec_chunk, "SOUNDNAME", sound.lump) if sound.args then dec_chunk = string.gsub(dec_chunk, "ARGHS", sound.args) else dec_chunk = string.gsub(dec_chunk, "ARGHS", ZDOOM_SOUND.DEFAULT_A_PLAYSOUND_ARGS) end SCRIPTS.SOUND_DEC = SCRIPTS.SOUND_DEC .. dec_chunk .. "\n\n" -- build SNDINFO chunk local sndinfo_chunk = sound.lump .. " " .. sound.lump .. "\n" if sound.flags then sndinfo_chunk = sndinfo_chunk .. " " .. sound.flags .. "\n" end SCRIPTS.SNDINFO = SCRIPTS.SNDINFO .. sndinfo_chunk .. "\n" offset_count = offset_count + 1 end end function ZDOOM_SOUND.populate_level_ambience() if not PARAM.ambient_sounds then return end if LEVEL.prebuilt then return end local level_sound_table = ZDOOM_SOUNDSCAPES[LEVEL.theme_name] if not level_sound_table then gui.printf("WARNING: No sounds at all for theme " .. LEVEL.theme_name .. ".\n") return end each R in LEVEL.rooms do local room_env = "" -- resolve room environment -- parks, caves, and steets will override -- the contents of building and outdoors room_env = R:get_env() if R.is_street then room_env = "street" end each A in R.areas do if (A.mode == "floor" or A.mode == "liquid") or (R.is_park or R.is_cave) then each S in A.seeds do local pick_sound local sound_table = level_sound_table[room_env] local no_sound = false local outdoor_theme if rand.odds(5) then -- then pick the sound if room_env == "building" then if not table.empty(sound_table) then pick_sound = rand.key_by_probs(sound_table) else gui.printf("WARNING: No sound for " .. LEVEL.theme_name .. " indoor.\n") no_sound = true end else -- special treatment for outdoor and outdoor-ish rooms -- as they may be controlled by the Epic environment themes outdoor_theme = LEVEL.outdoor_theme if not outdoor_theme then outdoor_theme = "temperate" end if not table.empty(sound_table[outdoor_theme]) then pick_sound = rand.key_by_probs(sound_table[outdoor_theme]) else gui.printf("WARNING: No sound for " .. LEVEL.theme_name .. " " .. outdoor_theme .. " " .. room_env .. ".\n") no_sound = true end end local final_z if S.area then if S.area.ceil_h then final_z = S.area.ceil_h elseif S.area.zone.sky_h then final_z = S.area.zone.sky_h else final_z = 0 end end if not no_sound then local E = { x = S.mid_x y = S.mid_y z = final_z - 8 id = ZDOOM_SOUND_DEFS[pick_sound].id } raw_add_entity(E) end end end end end end end function ZDOOM_SOUND.setup(self) gui.printf("\n--== Ambient Sound Addons module active ==--\n\n") for name,opt in pairs(self.options) do local value = self.options[name].value PARAM[name] = value end PARAM.ambient_sounds = true ZDOOM_SOUND.build_lumps() end OB_MODULES["zdoom_ambient_sound"] = { label = _("ZDoom: Ambient Sounds") game = "doomish" side = "left" priority = 69 engine = { zdoom=1, gzdoom=1 } hooks = { setup = ZDOOM_SOUND.setup end_level = ZDOOM_SOUND.populate_level_ambience } options = { snd_start_id = { name = "snd_start_id" label=("DoomEdNum Offset") choices=ZDOOM_SOUND.ACTOR_ID_OFFSET_CHOICES tooltip = "Selects the starting thing ID for generating ambient sound actors. Use only if " .. "you are playing a mod using conflicting Editor Numbers. If you don't know what this is " .. "this setting is best left as-is." default = "20000" } } tooltip = "Adds ambient sound things to fabs, room themes, and environments (WIP)." .. "Needs an accompanying sound pack containing corresponding sound files to be included with your Doom launcher." }
1
0.89699
1
0.89699
game-dev
MEDIA
0.854581
game-dev
0.732625
1
0.732625
pafuhana1213/KawaiiPhysics
9,305
Plugins/KawaiiPhysics/Source/KawaiiPhysics/Private/KawaiiPhysicsExternalForce.cpp
// Copyright 2019-2025 pafuhana1213. All Rights Reserved. #include "KawaiiPhysicsExternalForce.h" #include "SceneInterface.h" #include "GameFramework/Character.h" #include "GameFramework/CharacterMovementComponent.h" #include UE_INLINE_GENERATED_CPP_BY_NAME(KawaiiPhysicsExternalForce) DECLARE_CYCLE_STAT(TEXT("KawaiiPhysics_ExternalForce_Basic_Apply"), STAT_KawaiiPhysics_ExternalForce_Basic_Apply, STATGROUP_Anim); DECLARE_CYCLE_STAT(TEXT("KawaiiPhysics_ExternalForce_Gravity_Apply"), STAT_KawaiiPhysics_ExternalForce_Gravity_Apply, STATGROUP_Anim); DECLARE_CYCLE_STAT(TEXT("KawaiiPhysics_ExternalForce_Curve_Apply"), STAT_KawaiiPhysics_ExternalForce_Curve_Apply, STATGROUP_Anim); DECLARE_CYCLE_STAT(TEXT("KawaiiPhysics_ExternalForce_Wind_Apply"), STAT_KawaiiPhysics_ExternalForce_Wind_Apply, STATGROUP_Anim); /// /// Basic /// void FKawaiiPhysics_ExternalForce_Basic::PreApply(FAnimNode_KawaiiPhysics& Node, const USkeletalMeshComponent* SkelComp) { Super::PreApply(Node, SkelComp); PrevTime = Time; Time += Node.DeltaTime; if (Interval > 0.0f) { if (Time > Interval) { Force = ForceDir * RandomizedForceScale; Time = FMath::Fmod(Time, Interval); } else { Force = FVector::ZeroVector; } } else { Force = ForceDir * RandomizedForceScale; } if (ExternalForceSpace == EExternalForceSpace::WorldSpace && Node.SimulationSpace != EKawaiiPhysicsSimulationSpace::WorldSpace) { Force = ComponentTransform.InverseTransformVector(Force); } } void FKawaiiPhysics_ExternalForce_Basic::Apply(FKawaiiPhysicsModifyBone& Bone, FAnimNode_KawaiiPhysics& Node, const FComponentSpacePoseContext& PoseContext, const FTransform& BoneTM) { if (!CanApply(Bone)) { return; } SCOPE_CYCLE_COUNTER(STAT_KawaiiPhysics_ExternalForce_Basic_Apply); float ForceRate = 1.0f; if (const auto Curve = ForceRateByBoneLengthRate.GetRichCurve(); !Curve->IsEmpty()) { ForceRate = Curve->Eval(Bone.LengthRateFromRoot); } if (ExternalForceSpace == EExternalForceSpace::BoneSpace) { const FVector BoneForce = BoneTM.TransformVector(Force); Bone.Location += BoneForce * ForceRate * Node.DeltaTime; #if ENABLE_ANIM_DEBUG BoneForceMap.Add(Bone.BoneRef.BoneName, BoneForce); #endif } else { Bone.Location += Force * ForceRate * Node.DeltaTime; #if ENABLE_ANIM_DEBUG BoneForceMap.Add(Bone.BoneRef.BoneName, Force * ForceRate); #endif } } /// /// Gravity /// void FKawaiiPhysics_ExternalForce_Gravity::PreApply(FAnimNode_KawaiiPhysics& Node, const USkeletalMeshComponent* SkelComp) { Super::PreApply(Node, SkelComp); Force = bUseOverrideGravityDirection ? OverrideGravityDirection : FVector(0, 0, -1.0f); // For Character's Custom Gravity Direction if (const ACharacter* Character = Cast<ACharacter>(SkelComp->GetOwner())) { #if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3 if (bUseCharacterGravityDirection) { Force = Character->GetGravityDirection(); } #endif if (bUseCharacterGravityScale) { if (const UCharacterMovementComponent* CharacterMovementComponent = Character-> GetCharacterMovement()) { Force *= CharacterMovementComponent->GetGravityZ(); } } } Force *= RandomizedForceScale; if (Node.SimulationSpace != EKawaiiPhysicsSimulationSpace::WorldSpace) { Force = ComponentTransform.InverseTransformVector(Force); } } void FKawaiiPhysics_ExternalForce_Gravity::Apply(FKawaiiPhysicsModifyBone& Bone, FAnimNode_KawaiiPhysics& Node, const FComponentSpacePoseContext& PoseContext, const FTransform& BoneTM) { if (!CanApply(Bone)) { return; } SCOPE_CYCLE_COUNTER(STAT_KawaiiPhysics_ExternalForce_Gravity_Apply); float ForceRate = 1.0f; if (const auto Curve = ForceRateByBoneLengthRate.GetRichCurve(); !Curve->IsEmpty()) { ForceRate = Curve->Eval(Bone.LengthRateFromRoot); } Bone.Location += 0.5f * Force * ForceRate * Node.DeltaTime * Node.DeltaTime; #if ENABLE_ANIM_DEBUG BoneForceMap.Add(Bone.BoneRef.BoneName, Force * ForceRate); AnimDrawDebug(Bone, Node, PoseContext); #endif } /// /// Curve /// void FKawaiiPhysics_ExternalForce_Curve::InitMaxCurveTime() { if (const FRichCurve* CurveX = ForceCurve.GetRichCurve(0); CurveX && !CurveX->IsEmpty()) { MaxCurveTime = FMath::Max(MaxCurveTime, CurveX->GetLastKey().Time); } if (const FRichCurve* CurveY = ForceCurve.GetRichCurve(1); CurveY && !CurveY->IsEmpty()) { MaxCurveTime = FMath::Max(MaxCurveTime, CurveY->GetLastKey().Time); } if (const FRichCurve* CurveZ = ForceCurve.GetRichCurve(2); CurveZ && !CurveZ->IsEmpty()) { MaxCurveTime = FMath::Max(MaxCurveTime, CurveZ->GetLastKey().Time); } } void FKawaiiPhysics_ExternalForce_Curve::Initialize(const FAnimationInitializeContext& Context) { FKawaiiPhysics_ExternalForce::Initialize(Context); InitMaxCurveTime(); } void FKawaiiPhysics_ExternalForce_Curve::PreApply(FAnimNode_KawaiiPhysics& Node, const USkeletalMeshComponent* SkelComp) { Super::PreApply(Node, SkelComp); #if WITH_EDITOR InitMaxCurveTime(); #endif PrevTime = Time; if (CurveEvaluateType == EExternalForceCurveEvaluateType::Single) { Time += Node.DeltaTime * TimeScale; if (MaxCurveTime > 0 && Time > MaxCurveTime) { Time = FMath::Fmod(Time, MaxCurveTime); } Force = ForceCurve.GetValue(Time) * RandomizedForceScale; } else { TArray<FVector> CurveValues; const float SubStep = Node.DeltaTime * TimeScale / SubstepCount; for (int i = 0; i < SubstepCount; ++i) { Time += SubStep; if (MaxCurveTime > 0 && Time > MaxCurveTime) { Time = FMath::Fmod(Time, MaxCurveTime); } CurveValues.Add(ForceCurve.GetValue(Time)); } Force = FVector::ZeroVector; switch (CurveEvaluateType) { case EExternalForceCurveEvaluateType::Average: for (const auto& CurveValue : CurveValues) { Force += CurveValue; } Force /= static_cast<float>(SubstepCount); break; case EExternalForceCurveEvaluateType::Max: Force = FVector(FLT_MIN); for (const auto& CurveValue : CurveValues) { Force = FVector::Max(Force, CurveValue); } break; case EExternalForceCurveEvaluateType::Min: Force = FVector(FLT_MAX); for (const auto& CurveValue : CurveValues) { Force = FVector::Min(Force, CurveValue); } break; default: break; } Force *= RandomizedForceScale; } if (ExternalForceSpace == EExternalForceSpace::WorldSpace && Node.SimulationSpace != EKawaiiPhysicsSimulationSpace::WorldSpace) { Force = ComponentTransform.InverseTransformVector(Force); } } void FKawaiiPhysics_ExternalForce_Curve::Apply(FKawaiiPhysicsModifyBone& Bone, FAnimNode_KawaiiPhysics& Node, const FComponentSpacePoseContext& PoseContext, const FTransform& BoneTM) { if (!CanApply(Bone)) { return; } SCOPE_CYCLE_COUNTER(STAT_KawaiiPhysics_ExternalForce_Curve_Apply); float ForceRate = 1.0f; if (const auto Curve = ForceRateByBoneLengthRate.GetRichCurve(); !Curve->IsEmpty()) { ForceRate = Curve->Eval(Bone.LengthRateFromRoot); } if (ExternalForceSpace == EExternalForceSpace::BoneSpace) { const FVector BoneForce = BoneTM.TransformVector(Force); Bone.Location += BoneForce * ForceRate * Node.DeltaTime; #if ENABLE_ANIM_DEBUG BoneForceMap.Add(Bone.BoneRef.BoneName, BoneForce * ForceRate); #endif } else { Bone.Location += Force * ForceRate * Node.DeltaTime; #if ENABLE_ANIM_DEBUG BoneForceMap.Add(Bone.BoneRef.BoneName, Force * ForceRate); #endif } #if ENABLE_ANIM_DEBUG AnimDrawDebug(Bone, Node, PoseContext); #endif } void FKawaiiPhysics_ExternalForce_Wind::PreApply(FAnimNode_KawaiiPhysics& Node, const USkeletalMeshComponent* SkelComp) { Super::PreApply(Node, SkelComp); World = SkelComp ? SkelComp->GetWorld() : nullptr; } void FKawaiiPhysics_ExternalForce_Wind::Apply(FKawaiiPhysicsModifyBone& Bone, FAnimNode_KawaiiPhysics& Node, const FComponentSpacePoseContext& PoseContext, const FTransform& BoneTM) { const FSceneInterface* Scene = World && World->Scene ? World->Scene : nullptr; if (!CanApply(Bone) || !Scene) { return; } SCOPE_CYCLE_COUNTER(STAT_KawaiiPhysics_ExternalForce_Wind_Apply); float ForceRate = 1.0f; if (const auto Curve = ForceRateByBoneLengthRate.GetRichCurve(); !Curve->IsEmpty()) { ForceRate = Curve->Eval(Bone.LengthRateFromRoot); } FVector WindDirection = FVector::ZeroVector; float WindSpeed, WindMinGust, WindMaxGust = 0.0f; Scene->GetWindParameters(ComponentTransform.TransformPosition(Bone.PoseLocation), WindDirection, WindSpeed, WindMinGust, WindMaxGust); if (Node.SimulationSpace != EKawaiiPhysicsSimulationSpace::WorldSpace) { WindDirection = ComponentTransform.InverseTransformVector(WindDirection); } WindDirection *= WindSpeed; Bone.Location += WindDirection * ForceRate * RandomizedForceScale * Node.DeltaTime; #if ENABLE_ANIM_DEBUG BoneForceMap.Add(Bone.BoneRef.BoneName, WindDirection * ForceRate * RandomizedForceScale); AnimDrawDebug(Bone, Node, PoseContext); #endif }
1
0.879565
1
0.879565
game-dev
MEDIA
0.923396
game-dev
0.907302
1
0.907302
WhoCraft/TardisRefined
7,791
common/src/main/java/whocraft/tardis_refined/common/tardis/TardisArchitectureHandler.java
package whocraft.tardis_refined.common.tardis; import net.minecraft.core.BlockPos; import net.minecraft.nbt.NbtUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.phys.AABB; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import whocraft.tardis_refined.TardisRefined; import whocraft.tardis_refined.common.block.door.BulkHeadDoorBlock; import whocraft.tardis_refined.common.blockentity.door.TardisInternalDoor; import whocraft.tardis_refined.common.capability.tardis.TardisLevelOperator; import whocraft.tardis_refined.common.entity.ControlEntity; import whocraft.tardis_refined.common.tardis.themes.DesktopTheme; import whocraft.tardis_refined.constants.TardisDimensionConstants; import whocraft.tardis_refined.registry.TRBlockRegistry; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import static whocraft.tardis_refined.common.tardis.manager.TardisInteriorManager.STATIC_CORRIDOR_POSITION; // Responsible for all the tedious generation of the desktop; public class TardisArchitectureHandler { public static Logger LOGGER = LogManager.getLogger("TardisRefined/TardisArchitectureHandler"); public static final BlockPos DESKTOP_CENTER_POS = new BlockPos(0, 100, 0); public static final BlockPos EYE_OF_HARMONY_PLACEMENT = new BlockPos(991, 41, 31); public static String currentArsStage = "one"; public static void generateDesktop(ServerLevel operator, DesktopTheme theme) { LOGGER.debug("Attempting to generate desktop theme: {} for TARDIS.", theme.getIdentifier()); // Fill the area out. BlockPos corner = new BlockPos(TardisDimensionConstants.TARDIS_CENTER_POS.getX() - TardisDimensionConstants.DESKTOP_RADIUS, TardisDimensionConstants.TARDIS_ROOT_GENERATION_MIN_HEIGHT, TardisDimensionConstants.TARDIS_CENTER_POS.getZ() - TardisDimensionConstants.DESKTOP_RADIUS); BlockPos farCorner = new BlockPos(TardisDimensionConstants.TARDIS_CENTER_POS.getX() + TardisDimensionConstants.DESKTOP_RADIUS, TardisDimensionConstants.TARDIS_ROOT_GENERATION_MAX_HEIGHT, TardisDimensionConstants.TARDIS_CENTER_POS.getZ() + TardisDimensionConstants.DESKTOP_RADIUS); if (theme != TardisDesktops.DEFAULT_OVERGROWN_THEME) { for (BlockPos pos : BlockPos.betweenClosed(corner, farCorner)) { if (operator.getBlockState(pos) != TRBlockRegistry.FOOLS_STONE.get().defaultBlockState()) { operator.setBlock(pos, TRBlockRegistry.FOOLS_STONE.get().defaultBlockState(), Block.UPDATE_ALL); } } } List<ItemEntity> itemEntities = operator.getLevel().getEntitiesOfClass(ItemEntity.class, new AABB(corner, farCorner)); List<ControlEntity> controlEntities = operator.getLevel().getEntitiesOfClass(ControlEntity.class, new AABB(corner, farCorner)); List<Entity> entitiesForDeath = new ArrayList<>(itemEntities); entitiesForDeath.addAll(controlEntities); entitiesForDeath.forEach(Entity::discard); //Don't teleport entities to a hard coded coordinate, that causes hanging entity out of world issues. In other cases, if another mod defines that coordinate as a safe area (possible) that will mean the entities never get killed. Optional<StructureTemplate> structureNBT = operator.getLevel().getStructureManager().get(theme.getStructureLocation()); structureNBT.ifPresent(structure -> { BlockPos offsetPosition = calculateArcOffset(structure, DESKTOP_CENTER_POS); structure.placeInWorld(operator.getLevel(), offsetPosition, offsetPosition, new StructurePlaceSettings(), operator.getLevel().random, Block.UPDATE_IMMEDIATE); // Assign the door from the created structure. setInteriorDoorFromStructure(structure, operator); buildAirlockEntranceFromStructure(structure, operator); }); } public static void buildAirlockEntranceFromStructure(StructureTemplate template, ServerLevel level) { BlockPos minPos = calculateArcOffset(template, DESKTOP_CENTER_POS); BlockPos maxPos = new BlockPos(minPos.getX() + template.getSize().getX(), minPos.getY() + template.getSize().getY(), minPos.getZ() + template.getSize().getZ()); for (BlockPos pos : BlockPos.betweenClosed(minPos, maxPos)) { if (level.getBlockState(pos).getBlock() == TRBlockRegistry.AIR_LOCK_GENERATION_BLOCK.get()) { TardisLevelOperator.get(level).ifPresent(cap -> { Optional<StructureTemplate> structureNBT = level.getLevel().getStructureManager().get(new ResourceLocation(TardisRefined.MODID, "corridors/airlock_entrance")); structureNBT.ifPresent(structure -> { BlockPos offsetPosition = new BlockPos(3, 2, 0); structure.placeInWorld(level.getLevel(), pos.subtract(offsetPosition), pos.subtract(offsetPosition), new StructurePlaceSettings(), level.getLevel().random, 2); cap.getInteriorManager().setCorridorAirlockCenter(pos.south(2)); level.setBlock(pos, level.getBlockState(pos).setValue(BulkHeadDoorBlock.LOCKED, false), 2); }); }); return; } } } public static void generateArsTree(TardisLevelOperator tardisLevelOperator, ServerLevel level) { if (!currentArsStage.equals("one") && Objects.equals(tardisLevelOperator.getUpgradeHandler().getProgressLevel(), currentArsStage)) return; currentArsStage = tardisLevelOperator.getUpgradeHandler().getProgressLevel(); Optional<StructureTemplate> structureNBT = level.getLevel().getStructureManager().get(new ResourceLocation(TardisRefined.MODID, "rooms/ars/room_ars_stage_" + currentArsStage)); structureNBT.ifPresent(structure -> { structure.placeInWorld(level.getLevel(), TardisDimensionConstants.ARS_TREE_PLACEMENT_POS, TardisDimensionConstants.ARS_TREE_PLACEMENT_POS, new StructurePlaceSettings(), level.getLevel().random, Block.UPDATE_ALL); }); } public static boolean setInteriorDoorFromStructure(StructureTemplate template, ServerLevel level) { BlockPos minPos = calculateArcOffset(template, DESKTOP_CENTER_POS); BlockPos maxPos = new BlockPos(minPos.getX() + template.getSize().getX(), minPos.getY() + template.getSize().getY(), minPos.getZ() + template.getSize().getZ()); //First set the internal door to null so that we aren't caching the previous desktop's internal door TardisLevelOperator.get(level).ifPresent(cap -> cap.setInternalDoor(null)); for (BlockPos pos : BlockPos.betweenClosed(minPos, maxPos)) { if (level.getBlockEntity(pos) instanceof TardisInternalDoor internalDoor) { TardisLevelOperator.get(level).ifPresent(cap -> cap.setInternalDoor(internalDoor)); return true; } } return false; } public static BlockPos calculateArcOffset(StructureTemplate structureTemplate, BlockPos centerPos) { return new BlockPos(centerPos.getX() - structureTemplate.getSize().getX() / 2, centerPos.getY() - structureTemplate.getSize().getY() / 2, centerPos.getZ() - structureTemplate.getSize().getZ() / 2); } }
1
0.80313
1
0.80313
game-dev
MEDIA
0.727051
game-dev
0.89975
1
0.89975
TrashboxBobylev/Summoning-Pixel-Dungeon
1,821
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/particles/StenchParticle.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2022 Evan Debenham * * Summoning Pixel Dungeon * Copyright (C) 2019-2022 TrashboxBobylev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.effects.particles; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.particles.Emitter.Factory; import com.watabou.noosa.particles.PixelParticle; import com.watabou.utils.Random; public class StenchParticle extends PixelParticle { public static final Factory FACTORY = new Factory() { @Override public void emit( Emitter emitter, int index, float x, float y ) { ((StenchParticle)emitter.recycle( StenchParticle.class )).reset( x, y ); } }; public StenchParticle() { super(); color( 0x1d4636 ); acc.set( 0, -40 ); } public void reset( float x, float y ) { revive(); this.x = x; this.y = y; left = lifespan = Random.Float( 0.6f, 1f ); speed.set( Random.Float( -4, +4 ), Random.Float( -8, +8 ) ); } @Override public void update() { super.update(); float p = left / lifespan; am = p > 0.8f ? 2 - 2*p : p * 0.5f; size( 16 - p * 8 ); } }
1
0.824673
1
0.824673
game-dev
MEDIA
0.973902
game-dev
0.952107
1
0.952107