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
rbei-etas/busmaster
9,970
Sources/BUSMASTER/TXWindow/LINTxMsgItem.cpp
/* * 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 <http://www.gnu.org/licenses/>. */ /** * \file LINTxMsgItem.cpp * \author Robin G.K. * \copyright Copyright (c) 2011, Robert Bosch Engineering and Business Solutions. All rights reserved. */ #pragma once #include "LINTxMsgItem.h" #include "LINDefines.h" CLINTxMsgItem::CLINTxMsgItem() { MsgDetails.pchData = new unsigned char[defLIN_MSG_DLC_MAX]; memset(MsgDetails.pchData, 0xFF, sizeof(unsigned char)*defLIN_MSG_DLC_MAX); } CLINTxMsgItem::~CLINTxMsgItem() { if (nullptr != MsgDetails.pchData) { delete MsgDetails.pchData; MsgDetails.pchData = nullptr; } } std::string CLINTxMsgItem::strGetValueAtTag(xmlNodePtr pxmlNodePtr, const std::string& strTag) { std::string strValue = ""; xmlChar* pchPathMsg = (xmlChar*)strTag.c_str(); xmlXPathObjectPtr pObjectPath = xmlUtils::pGetChildNodes(pxmlNodePtr, pchPathMsg); if (pObjectPath != nullptr) { xmlNodeSetPtr pNodeSet = pObjectPath->nodesetval; if (nullptr != pNodeSet) { xmlNodePtr pNode = pNodeSet->nodeTab[0]; //Take First One only xmlChar* key = xmlNodeListGetString(pNode->doc, pNode->xmlChildrenNode, 1); strValue = ((char*)key); } } return strValue; } void CLINTxMsgItem::vGetPhysicalValueFactor(ISignal* pSignal, double& dScale) { if (nullptr != pSignal) { ICoding* pCoding = nullptr; if (EC_SUCCESS == pSignal->GetEncoding(&pCoding)) { if (nullptr != pCoding) { LINCompuMethods ouCompuProps; pCoding->GetProperties(ouCompuProps); if (ouCompuProps.m_ouPhysicalValueList.size() > 0) { std::list<PhysicalValue>::iterator itrPhyValue = ouCompuProps.m_ouPhysicalValueList.begin(); if (itrPhyValue != ouCompuProps.m_ouPhysicalValueList.end()) { dScale = itrPhyValue->m_dFactor; } } } } } } bool CLINTxMsgItem::sortByStartBit(const SIG_DETAILS& lhs, const SIG_DETAILS& rhs) { return lhs.Signal.second.m_nStartBit < rhs.Signal.second.m_nStartBit; } int CLINTxMsgItem::GetMsgName(IBMNetWorkGetService* pouIBMNetwork, bool bIshex, std::string& strMsgName) { int hResult = S_FALSE; IFrame* pIFrame = nullptr; if (nullptr == pouIBMNetwork) { return hResult; } pouIBMNetwork->GetFrame(LIN, MsgDetails.nChannel - 1, MsgDetails.nMsgId, nullptr, &pIFrame); if (nullptr != pIFrame) { hResult = S_OK; pIFrame->GetName(strMsgName); } else { hResult = S_OK; char chValue[1024]; if (bIshex == false) { sprintf_s(chValue, 1024, "%d", MsgDetails.nMsgId); } else { sprintf_s(chValue, 1024, "0x%X", MsgDetails.nMsgId); } strMsgName = chValue; } return hResult; } int CLINTxMsgItem::SetMsgConfig(xmlNodePtr pxmlNodePtr) { int hResult = S_FALSE; if (nullptr == pxmlNodePtr) { return hResult; } //Name //MsgDetails.strMsgName = strGetValueAtTag(pxmlNodePtr, DEF_NAME); //Channel MsgDetails.nChannel = atoi(strGetValueAtTag(pxmlNodePtr, DEF_CHANNEL).c_str()); //MsgId MsgDetails.nMsgId = atoi(strGetValueAtTag(pxmlNodePtr, DEF_MESSAGE_ID).c_str()); //Msg Type MsgDetails.nMsgType = atoi(strGetValueAtTag(pxmlNodePtr, DEF_MESSAGE_TYPE).c_str()); //Msg DLC MsgDetails.nDLC = atoi(strGetValueAtTag(pxmlNodePtr, DEF_DLC).c_str()); //Msg Databytes std::string strDataBytes = strGetValueAtTag(pxmlNodePtr, DEF_DATABYTES).c_str(); char* pch; pch = strtok((char*)strDataBytes.c_str(), " ,.-"); int i = 0; while (pch != nullptr) { MsgDetails.pchData[i] = atoi(pch); pch = strtok(nullptr, " ,.-"); i++; } //Repetition TxDetails.nActualTimer = atoi(strGetValueAtTag(pxmlNodePtr, DEF_REPETION).c_str()); TxDetails.nCurrentTimerVal = TxDetails.nActualTimer; //TimerEnabled TxDetails.m_bTimerEnabled = true; if (0 == std::strcmp(strGetValueAtTag(pxmlNodePtr, DEF_REPETITION_ENABLED).c_str(), "FALSE")) { TxDetails.m_bTimerEnabled = false; } //Key Value TxDetails.m_chKeyVal = strGetValueAtTag(pxmlNodePtr, DEF_KEY_VAL)[0]; //Key Value Enabled TxDetails.bKeyEnabled = true; if (0 == std::strcmp(strGetValueAtTag(pxmlNodePtr, DEF_KEY_ENABLED).c_str(), "FALSE")) { TxDetails.bKeyEnabled = false; } return hResult; } int CLINTxMsgItem::GetMsgConfig(xmlNodePtr pxmlNodePtr) { int hResult = S_FALSE; if (nullptr != pxmlNodePtr) { hResult = S_OK; char pchData[1024]; //Name //xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_NAME, BAD_CAST MsgDetails.strMsgName.c_str()); //Channel sprintf(pchData, "%d", MsgDetails.nChannel); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_CHANNEL, BAD_CAST pchData); //Message Id sprintf(pchData, "%d", MsgDetails.nMsgId); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_MSG_ID, BAD_CAST pchData); //Checksum Type -- Currently not used but reserved for future. sprintf(pchData, "%d", 0); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_LIN_MESSAGE_CHECKSUM, BAD_CAST pchData); //Message Type sprintf(pchData, "%d", MsgDetails.nMsgType); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_MESSAGE_TYPE, BAD_CAST pchData); //DLC sprintf(pchData, "%d", MsgDetails.nDLC); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_DLC, BAD_CAST pchData); //Data Bytes std::string strDatabytes; sprintf(pchData, "%d", MsgDetails.pchData[0]); strDatabytes = pchData; for (int i = 1; i < MsgDetails.nDLC; i++) { sprintf(pchData, ",%d", MsgDetails.pchData[i]); strDatabytes.append(pchData); } xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_DATABYTES, BAD_CAST strDatabytes.c_str()); //Repetition sprintf(pchData, "%d", TxDetails.nActualTimer); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_REPETION, BAD_CAST pchData); //Repetition Enabled if (true == TxDetails.m_bTimerEnabled) { xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_REPETITION_ENABLED, BAD_CAST "TRUE"); } else { xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_REPETITION_ENABLED, BAD_CAST "FALSE"); } //Key sprintf(pchData, "%c", TxDetails.m_chKeyVal); xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_KEY_VAL, BAD_CAST pchData); //Key Enabled if (true == TxDetails.bKeyEnabled) { xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_KEY_ENABLED, BAD_CAST "TRUE"); } else { xmlNewChild(pxmlNodePtr, nullptr, BAD_CAST DEF_KEY_ENABLED, BAD_CAST "FALSE"); } } return hResult; } int CLINTxMsgItem::SetOldMsgConfig(xmlNodePtr pxmlNodePtr) { //This function is Not Applicable for LIN. SetMsgConfig(pxmlNodePtr); return S_OK; } int CLINTxMsgItem::GetSignalList(IBMNetWorkGetService* pouIBMNetwork, bool bIsHex, std::list<SIG_DETAILS>& lstSigDetails) { int hResult = S_FALSE; std::map<ISignal*, SignalInstanse> mapSignal; std::list<InterpreteSignals> lstSignalInterprete; if (MsgDetails.nChannel < 0 || MsgDetails.nChannel > CHANNEL_ALLOWED) { return hResult; } if (nullptr == pouIBMNetwork) { return hResult; } IFrame* ouFrameStruct = nullptr; CString omStrMsgName = ""; pouIBMNetwork->GetFrame(LIN, MsgDetails.nChannel - 1, MsgDetails.nMsgId, nullptr, &ouFrameStruct); if (nullptr != ouFrameStruct) { hResult = S_OK; ouFrameStruct->GetSignalList(mapSignal); ouFrameStruct->InterpretSignals(MsgDetails.pchData, MsgDetails.nDLC, lstSignalInterprete, bIsHex); } auto itrSigItp = lstSignalInterprete.begin(); auto itrSignal = mapSignal.begin(); SIG_DETAILS ouSigDetails; double dScale = 0; for (; itrSigItp != lstSignalInterprete.end() && itrSignal != mapSignal.end(); ++itrSigItp, ++itrSignal) { ouSigDetails.SignalInterprete = *itrSigItp; ouSigDetails.Signal = *itrSignal; vGetPhysicalValueFactor(itrSignal->first, dScale); if (dScale > 0) { ouSigDetails.dPhyFactor = dScale; } else { ouSigDetails.dPhyFactor = 1; } lstSigDetails.push_back(ouSigDetails); } //Sort by start bit. lstSigDetails.sort(CLINTxMsgItem::sortByStartBit); } int CLINTxMsgItem::GetSignal(IBMNetWorkGetService* pouIBMNetwork, bool bIsHex, std::string strSigName, SIG_DETAILS& ouSignalDetails) { int hResult = S_FALSE; std::list<SIG_DETAILS> lstSigDetails; GetSignalList(pouIBMNetwork, bIsHex, lstSigDetails); std::string strName = ""; for (auto itr : lstSigDetails) { itr.Signal.first->GetName(strName); if (strName == strSigName) { hResult = S_OK; ouSignalDetails = itr; } } return hResult; }
0
0.949596
1
0.949596
game-dev
MEDIA
0.269084
game-dev
0.797276
1
0.797276
KiltMC/Kilt
7,513
src/main/java/xyz/bluspring/kilt/forgeinjects/world/level/block/BlockInject.java
// TRACKED HASH: cfca572d6c2e46ca49cb8ffbdda7f12c0d1c4d30 package xyz.bluspring.kilt.forgeinjects.world.level.block; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import com.llamalad7.mixinextras.sugar.Local; import net.fabricmc.api.EnvType; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.IdMapper; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.Entity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.extensions.common.IClientBlockExtensions; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.PlantType; import net.minecraftforge.common.extensions.IForgeBlock; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import xyz.bluspring.kilt.helpers.mixin.CreateStatic; import xyz.bluspring.kilt.injections.client.renderer.RenderPropertiesInjection; import xyz.bluspring.kilt.injections.world.level.LevelInjection; import java.util.concurrent.atomic.AtomicBoolean; @Mixin(Block.class) public abstract class BlockInject implements IForgeBlock, RenderPropertiesInjection<IClientBlockExtensions> { @Shadow @Final @Mutable public static IdMapper<BlockState> BLOCK_STATE_REGISTRY; @Unique private Object renderProperties; @Inject(method = "<clinit>", at = @At("TAIL")) private static void kilt$useGameDataStateIdMap(CallbackInfo ci) { //BLOCK_STATE_REGISTRY = GameData.getBlockStateIDMap(); } @Inject(at = @At("TAIL"), method = "<init>") public void kilt$initClient(BlockBehaviour.Properties properties, CallbackInfo ci) { if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { this.initializeClient((extensionProperties) -> { renderProperties = extensionProperties; }); } } @ModifyExpressionValue(at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;skipRendering(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/Direction;)Z"), method = "shouldRenderFace") private static boolean kilt$handleRenderFace(boolean original, @Local(argsOnly = true) BlockState blockState, @Local(ordinal = 1) BlockState blockState2, @Local(argsOnly = true) Direction direction, @Local(argsOnly = true) BlockGetter blockGetter, @Local(argsOnly = true, ordinal = 0) BlockPos blockPos) { return original || (blockState.supportsExternalFaceHiding() && blockState2.hidesNeighborFace(blockGetter, blockPos, blockState, direction.getOpposite())); } @Unique private static final AtomicBoolean kilt$dropXp = new AtomicBoolean(false); @ModifyArg(method = "dropResources(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/entity/BlockEntity;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/item/ItemStack;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;spawnAfterBreak(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/item/ItemStack;Z)V")) private static boolean kilt$dropResourcesXp(boolean original) { if (!original) return true; return kilt$dropXp.getAndSet(false); } @CreateStatic private static void dropResources(BlockState state, Level level, BlockPos pos, @Nullable BlockEntity blockEntity, @Nullable Entity entity, ItemStack tool, boolean dropXp) { kilt$dropXp.set(dropXp); Block.dropResources(state, level, pos, blockEntity, entity, tool); kilt$dropXp.set(false); } @ModifyExpressionValue(at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/GameRules;getBoolean(Lnet/minecraft/world/level/GameRules$Key;)Z", ordinal = 0), method = "popResource(Lnet/minecraft/world/level/Level;Ljava/util/function/Supplier;Lnet/minecraft/world/item/ItemStack;)V") private static boolean kilt$checkRestoringBlockSnapshots(boolean original, @Local(argsOnly = true) Level level) { return original && !((LevelInjection) level).kilt$getRestoringBlockSnapshots(); } @ModifyExpressionValue(at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/GameRules;getBoolean(Lnet/minecraft/world/level/GameRules$Key;)Z"), method = "popExperience") private boolean kilt$checkRestoringBlockSnapshots(boolean original, @Local(argsOnly = true) ServerLevel level) { return original && !((LevelInjection) level).kilt$getRestoringBlockSnapshots(); } @Override public Object getRenderPropertiesInternal() { return renderProperties; } @Override public boolean canSustainPlant(BlockState state, BlockGetter level, BlockPos pos, Direction facing, IPlantable plantable) { BlockState plant = plantable.getPlant(level, pos.relative(facing)); PlantType type = plantable.getPlantType(level, pos.relative(facing)); if (plant.getBlock() == Blocks.CACTUS) return state.is(Blocks.CACTUS) || state.is(BlockTags.SAND); if (plant.getBlock() == Blocks.SUGAR_CANE && (Object) this == Blocks.SUGAR_CANE) return true; if (plantable instanceof BushBlock && ((BushBlock) plantable).mayPlaceOn(state, level, pos)) return true; if (PlantType.DESERT.equals(type)) { return state.is(BlockTags.SAND) || (Object) this == Blocks.TERRACOTTA || (Object) this instanceof GlazedTerracottaBlock; } else if (PlantType.NETHER.equals(type)) { return (Object) this == Blocks.SOUL_SAND; } else if (PlantType.CROP.equals(type)) { return state.is(Blocks.FARMLAND); } else if (PlantType.CAVE.equals(type)) { return state.isFaceSturdy(level, pos, Direction.UP); } else if (PlantType.PLAINS.equals(type)) { return state.is(BlockTags.DIRT) || (Object) this == Blocks.FARMLAND; } else if (PlantType.WATER.equals(type)) { return (state.is(Blocks.WATER) || state.getBlock() instanceof IceBlock) && level.getFluidState(pos.relative(facing)).isEmpty(); } else if (PlantType.BEACH.equals(type)) { boolean isBeach = state.is(BlockTags.DIRT) || state.is(BlockTags.SAND); boolean hasWater = false; for (Direction face : Direction.Plane.HORIZONTAL) { BlockState adjacentBlockState = level.getBlockState(pos.relative(face)); var adjacentFluidState = level.getFluidState(pos.relative(face)); hasWater = hasWater || adjacentBlockState.is(Blocks.FROSTED_ICE) || adjacentFluidState.is(net.minecraft.tags.FluidTags.WATER); if (hasWater) break; } return isBeach && hasWater; } return false; } }
0
0.910962
1
0.910962
game-dev
MEDIA
0.999461
game-dev
0.938444
1
0.938444
mirror/reactos
5,200
reactos/include/ndk/dbgktypes.h
/*++ NDK Version: 0098 Copyright (c) Alex Ionescu. All rights reserved. Header Name: dbgktypes.h Abstract: Type definitions for the User Mode Debugging Facility. Author: Alex Ionescu (alexi@tinykrnl.org) - Updated - 27-Feb-2006 --*/ #ifndef _DBGKTYPES_H #define _DBGKTYPES_H // // Dependencies // #include <umtypes.h> #include <lpctypes.h> // // Debug Object Access Masks // #define DEBUG_OBJECT_WAIT_STATE_CHANGE 0x0001 #define DEBUG_OBJECT_ADD_REMOVE_PROCESS 0x0002 #define DEBUG_OBJECT_SET_INFORMATION 0x0004 #define DEBUG_OBJECT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x0F) // // Debug Event Flags // #define DEBUG_EVENT_READ (0x01) #define DEBUG_EVENT_NOWAIT (0x02) #define DEBUG_EVENT_INACTIVE (0x04) #define DEBUG_EVENT_RELEASE (0x08) #define DEBUG_EVENT_PROTECT_FAILED (0x10) #define DEBUG_EVENT_SUSPEND (0x20) // // NtCreateDebugObject Flags // #define DBGK_KILL_PROCESS_ON_EXIT (0x1) #define DBGK_ALL_FLAGS (DBGK_KILL_PROCESS_ON_EXIT) // // Debug Object Information Classes for NtQueryDebugObject // typedef enum _DEBUGOBJECTINFOCLASS { DebugObjectUnusedInformation, DebugObjectKillProcessOnExitInformation } DEBUGOBJECTINFOCLASS, *PDEBUGOBJECTINFOCLASS; // // Debug Message API Number // typedef enum _DBGKM_APINUMBER { DbgKmExceptionApi = 0, DbgKmCreateThreadApi = 1, DbgKmCreateProcessApi = 2, DbgKmExitThreadApi = 3, DbgKmExitProcessApi = 4, DbgKmLoadDllApi = 5, DbgKmUnloadDllApi = 6, DbgKmErrorReportApi = 7, DbgKmMaxApiNumber = 8, } DBGKM_APINUMBER; // // Debug Object Information Structures // typedef struct _DEBUG_OBJECT_KILL_PROCESS_ON_EXIT_INFORMATION { ULONG KillProcessOnExit; } DEBUG_OBJECT_KILL_PROCESS_ON_EXIT_INFORMATION, *PDEBUG_OBJECT_KILL_PROCESS_ON_EXIT_INFORMATION; #ifndef NTOS_MODE_USER // // Debug Object // typedef struct _DEBUG_OBJECT { KEVENT EventsPresent; FAST_MUTEX Mutex; LIST_ENTRY EventList; union { ULONG Flags; struct { UCHAR DebuggerInactive:1; UCHAR KillProcessOnExit:1; }; }; } DEBUG_OBJECT, *PDEBUG_OBJECT; #endif // // Debug States // typedef enum _DBG_STATE { DbgIdle, DbgReplyPending, DbgCreateThreadStateChange, DbgCreateProcessStateChange, DbgExitThreadStateChange, DbgExitProcessStateChange, DbgExceptionStateChange, DbgBreakpointStateChange, DbgSingleStepStateChange, DbgLoadDllStateChange, DbgUnloadDllStateChange } DBG_STATE, *PDBG_STATE; // // Debug Message Structures // typedef struct _DBGKM_EXCEPTION { EXCEPTION_RECORD ExceptionRecord; ULONG FirstChance; } DBGKM_EXCEPTION, *PDBGKM_EXCEPTION; typedef struct _DBGKM_CREATE_THREAD { ULONG SubSystemKey; PVOID StartAddress; } DBGKM_CREATE_THREAD, *PDBGKM_CREATE_THREAD; typedef struct _DBGKM_CREATE_PROCESS { ULONG SubSystemKey; HANDLE FileHandle; PVOID BaseOfImage; ULONG DebugInfoFileOffset; ULONG DebugInfoSize; DBGKM_CREATE_THREAD InitialThread; } DBGKM_CREATE_PROCESS, *PDBGKM_CREATE_PROCESS; typedef struct _DBGKM_EXIT_THREAD { NTSTATUS ExitStatus; } DBGKM_EXIT_THREAD, *PDBGKM_EXIT_THREAD; typedef struct _DBGKM_EXIT_PROCESS { NTSTATUS ExitStatus; } DBGKM_EXIT_PROCESS, *PDBGKM_EXIT_PROCESS; typedef struct _DBGKM_LOAD_DLL { HANDLE FileHandle; PVOID BaseOfDll; ULONG DebugInfoFileOffset; ULONG DebugInfoSize; PVOID NamePointer; } DBGKM_LOAD_DLL, *PDBGKM_LOAD_DLL; typedef struct _DBGKM_UNLOAD_DLL { PVOID BaseAddress; } DBGKM_UNLOAD_DLL, *PDBGKM_UNLOAD_DLL; // // User-Mode Debug State Change Structure // typedef struct _DBGUI_WAIT_STATE_CHANGE { DBG_STATE NewState; CLIENT_ID AppClientId; union { struct { HANDLE HandleToThread; DBGKM_CREATE_THREAD NewThread; } CreateThread; struct { HANDLE HandleToProcess; HANDLE HandleToThread; DBGKM_CREATE_PROCESS NewProcess; } CreateProcessInfo; DBGKM_EXIT_THREAD ExitThread; DBGKM_EXIT_PROCESS ExitProcess; DBGKM_EXCEPTION Exception; DBGKM_LOAD_DLL LoadDll; DBGKM_UNLOAD_DLL UnloadDll; } StateInfo; } DBGUI_WAIT_STATE_CHANGE, *PDBGUI_WAIT_STATE_CHANGE; // // LPC Debug Message // typedef struct _DBGKM_MSG { PORT_MESSAGE h; DBGKM_APINUMBER ApiNumber; NTSTATUS ReturnedStatus; union { DBGKM_EXCEPTION Exception; DBGKM_CREATE_THREAD CreateThread; DBGKM_CREATE_PROCESS CreateProcess; DBGKM_EXIT_THREAD ExitThread; DBGKM_EXIT_PROCESS ExitProcess; DBGKM_LOAD_DLL LoadDll; DBGKM_UNLOAD_DLL UnloadDll; }; } DBGKM_MSG, *PDBGKM_MSG; #ifndef NTOS_MODE_USER // // Debug Event // typedef struct _DEBUG_EVENT { LIST_ENTRY EventList; KEVENT ContinueEvent; CLIENT_ID ClientId; PEPROCESS Process; PETHREAD Thread; NTSTATUS Status; ULONG Flags; PETHREAD BackoutThread; DBGKM_MSG ApiMsg; } DEBUG_EVENT, *PDEBUG_EVENT; #endif #endif
0
0.761548
1
0.761548
game-dev
MEDIA
0.393108
game-dev
0.667871
1
0.667871
defold/defold
7,931
external/box2d_v2/Box2D/Dynamics/Contacts/b2Contact.cpp
/* * 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. */ #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2CircleContact.h> #include <Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2PolygonContact.h> #include <Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h> #include <Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h> #include <Box2D/Dynamics/Contacts/b2GridAndPolygonContact.h> #include <Box2D/Dynamics/Contacts/b2GridAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2ContactSolver.h> #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2TimeOfImpact.h> #include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Common/b2BlockAllocator.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2World.h> b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; bool b2Contact::s_initialized = false; void b2Contact::InitializeRegisters() { AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); // Defold additions AddType(b2GridAndPolygonContact::Create, b2GridAndPolygonContact::Destroy, b2Shape::e_grid, b2Shape::e_polygon); AddType(b2GridAndCircleContact::Create, b2GridAndCircleContact::Destroy, b2Shape::e_grid, b2Shape::e_circle); } void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, b2Shape::Type type1, b2Shape::Type type2) { b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); s_registers[type1][type2].createFcn = createFcn; s_registers[type1][type2].destroyFcn = destoryFcn; s_registers[type1][type2].primary = true; if (type1 != type2) { s_registers[type2][type1].createFcn = createFcn; s_registers[type2][type1].destroyFcn = destoryFcn; s_registers[type2][type1].primary = false; } } b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) { if (s_initialized == false) { InitializeRegisters(); s_initialized = true; } b2Shape::Type type1 = fixtureA->GetType(); b2Shape::Type type2 = fixtureB->GetType(); b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; if (createFcn) { if (s_registers[type1][type2].primary) { return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); } else { return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); } } else { return NULL; } } void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { b2Assert(s_initialized == true); if (contact->m_manifold.pointCount > 0) { contact->GetFixtureA()->GetBody()->SetAwake(true); contact->GetFixtureB()->GetBody()->SetAwake(true); } b2Shape::Type typeA = contact->GetFixtureA()->GetType(); b2Shape::Type typeB = contact->GetFixtureB()->GetType(); b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; destroyFcn(contact, allocator); } b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) { m_flags = e_enabledFlag; m_fixtureA = fA; m_fixtureB = fB; m_indexA = indexA; m_indexB = indexB; m_manifold.pointCount = 0; m_prev = NULL; m_next = NULL; m_nodeA.contact = NULL; m_nodeA.prev = NULL; m_nodeA.next = NULL; m_nodeA.other = NULL; m_nodeB.contact = NULL; m_nodeB.prev = NULL; m_nodeB.next = NULL; m_nodeB.other = NULL; m_toiCount = 0; m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); } // Update the contact manifold and touching status. // Note: do not assume the fixture AABBs are overlapping or are valid. void b2Contact::Update(b2ContactListener* listener) { b2Manifold oldManifold = m_manifold; // Re-enable this contact. m_flags |= e_enabledFlag; bool touching = false; bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; bool sensorA = m_fixtureA->IsSensor(); bool sensorB = m_fixtureB->IsSensor(); bool sensor = sensorA || sensorB; b2Body* bodyA = m_fixtureA->GetBody(); b2Body* bodyB = m_fixtureB->GetBody(); const b2Transform& xfA = bodyA->GetTransform(); const b2Transform& xfB = bodyB->GetTransform(); // Is this contact a sensor? if (sensor) { const b2Shape* shapeA = m_fixtureA->GetShape(); const b2Shape* shapeB = m_fixtureB->GetShape(); // Defold mod, Fake manifold update to test grid, not currently involved in overlap-test (b2Distance.cpp:83) if (shapeA->m_type == b2Shape::e_grid || shapeB->m_type == b2Shape::e_grid) { Evaluate(&m_manifold, xfA, xfB); touching = m_manifold.pointCount > 0; } else { touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); } // Sensors don't generate manifolds. m_manifold.pointCount = 0; } else { Evaluate(&m_manifold, xfA, xfB); touching = m_manifold.pointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. for (int32 i = 0; i < m_manifold.pointCount; ++i) { b2ManifoldPoint* mp2 = m_manifold.points + i; mp2->normalImpulse = 0.0f; mp2->tangentImpulse = 0.0f; b2ContactID id2 = mp2->id; for (int32 j = 0; j < oldManifold.pointCount; ++j) { b2ManifoldPoint* mp1 = oldManifold.points + j; if (mp1->id.key == id2.key) { mp2->normalImpulse = mp1->normalImpulse; mp2->tangentImpulse = mp1->tangentImpulse; break; } } } if (touching != wasTouching) { bodyA->SetAwake(true); bodyB->SetAwake(true); } } if (touching) { m_flags |= e_touchingFlag; } else { m_flags &= ~e_touchingFlag; } if (wasTouching == false && touching == true && listener) { listener->BeginContact(this); } if (wasTouching == true && touching == false && listener) { listener->EndContact(this); } if (sensor == false && touching && listener) { listener->PreSolve(this, &oldManifold); } }
0
0.980391
1
0.980391
game-dev
MEDIA
0.736662
game-dev
0.97634
1
0.97634
SNMetamorph/PrimeXT
81,375
server/physx/physx_impl.cpp
/* physx_impl.cpp - part of PhysX physics engine implementation Copyright (C) 2012 Uncle Mike Copyright (C) 2022 SNMetamorph 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. */ #ifdef USE_PHYSICS_ENGINE #include <PxConfig.h> #include "physx_impl.h" #include "saverestore.h" #include "client.h" #include "bspfile.h" #include "triangleapi.h" #include "studio.h" #include "pm_defs.h" #include "pm_movevars.h" #include "animation.h" #include "trace.h" #include "game.h" #include "build.h" #include "error_stream.h" #include "event_handler.h" #include "assert_handler.h" #include "debug_renderer.h" #include "contact_modify_callback.h" #include "collision_filter_data.h" #include "decomposed_shape.h" #include "meshdesc_factory.h" #include "crclib.h" #include <PxMat33.h> #include <PxMat44.h> #include <vector> #include <thread> #include <sstream> #if defined (HAS_PHYSIC_VEHICLE) #include "NxVehicle.h" #include "vehicles/NxParser.h" #endif constexpr float k_PaddingFactor = 0.49f; constexpr float k_DensityFactor = 0.05f; constexpr float k_WaterDensity = 0.030f; constexpr float k_WaterLinearDragFactor = 500.f; constexpr float k_WaterAngularDragFactor = 1.0f; constexpr uint32_t k_SolverIterationCount = 4; constexpr double k_SimulationStepSize = 1.0 / 100.0; using namespace physx; CPhysicPhysX g_physicPhysX; IPhysicLayer *WorldPhysic = &g_physicPhysX; CPhysicPhysX::CPhysicPhysX() { m_pPhysics = nullptr; m_pFoundation = nullptr; m_pDispatcher = nullptr; m_pScene = nullptr; m_pWorldModel = nullptr; m_pSceneMesh = nullptr; m_pSceneActor = nullptr; m_pDefaultMaterial = nullptr; m_pConveyorMaterial = nullptr; m_pCooking = nullptr; m_pVisualDebugger = nullptr; m_fLoaded = false; m_fDisableWarning = false; m_fWorldChanged = false; m_traceStateChanges = false; m_flAccumulator = 0.0; m_szMapName[0] = '\0'; p_speeds_msg[0] = '\0'; m_debugRenderer = std::make_unique<DebugRenderer>(); m_eventHandler = std::make_unique<EventHandler>(); m_contactModifyCallback = std::make_unique<ContactModifyCallback>(); } void CPhysicPhysX :: InitPhysic( void ) { if( m_pPhysics ) { ALERT( at_error, "InitPhysic: physics already initalized\n" ); return; } if( g_allow_physx != NULL && g_allow_physx->value == 0.0f ) { ALERT( at_console, "InitPhysic: PhysX support is disabled by user.\n" ); GameInitNullPhysics (); return; } m_pFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, m_Allocator, m_errorCallback); if (!m_pFoundation) { ALERT(at_error, "InitPhysic: failed to create foundation\n"); GameInitNullPhysics(); return; } PxTolerancesScale scale; scale.length = 39.3701; // typical length of an object scale.speed = 800.0; // typical speed of an object, gravity*1s is a reasonable choice if (DebugEnabled()) { m_pVisualDebugger = PxCreatePvd(*m_pFoundation); PxPvdTransport *transport = PxDefaultPvdSocketTransportCreate("127.0.0.1", 5425, 300); m_pVisualDebugger->connect(*transport, PxPvdInstrumentationFlag::eALL); } m_pPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *m_pFoundation, scale, false, m_pVisualDebugger); m_pDispatcher = PxDefaultCpuDispatcherCreate(std::thread::hardware_concurrency()); if (!m_pPhysics) { ALERT( at_error, "InitPhysic: failed to initalize physics engine\n" ); GameInitNullPhysics(); return; } m_pCooking = PxCreateCooking(PX_PHYSICS_VERSION, *m_pFoundation, PxCookingParams(scale)); if (!m_pCooking) { ALERT( at_warning, "InitPhysic: failed to initalize cooking library\n" ); } PxSetAssertHandler(m_assertHandler); if (!PxInitExtensions(*m_pPhysics, m_pVisualDebugger)) { ALERT( at_warning, "InitPhysic: failed to initalize extensions\n" ); } // create a scene PxSceneDesc sceneDesc(scale); sceneDesc.simulationEventCallback = m_eventHandler.get(); sceneDesc.contactModifyCallback = m_contactModifyCallback.get(); sceneDesc.gravity = PxVec3(0.0f, 0.0f, -800.0f); sceneDesc.flags = PxSceneFlag::eENABLE_CCD; sceneDesc.cpuDispatcher = m_pDispatcher; sceneDesc.filterShader = []( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) -> PxFilterFlags { if (PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1)) { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; return PxFilterFlag::eDEFAULT; } pairFlags = PxPairFlag::eCONTACT_DEFAULT | PxPairFlag::eDETECT_CCD_CONTACT | PxPairFlag::eNOTIFY_TOUCH_CCD | PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::eCONTACT_EVENT_POSE; CollisionFilterData fd1(filterData0); CollisionFilterData fd2(filterData1); if (fd1.HasConveyorFlag() || fd2.HasConveyorFlag()) { pairFlags |= PxPairFlag::eMODIFY_CONTACTS; } return PxFilterFlag::eDEFAULT; }; m_worldBounds.minimum = PxVec3(-32768, -32768, -32768); m_worldBounds.maximum = PxVec3(32768, 32768, 32768); sceneDesc.sanityBounds = m_worldBounds; m_pScene = m_pPhysics->createScene(sceneDesc); if (DebugEnabled()) { PxPvdSceneClient *pvdClient = m_pScene->getScenePvdClient(); m_pScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); // disable on release build because performance impact m_pScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 1.0f); m_pScene->setVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT, 1.0f); m_pScene->setVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL, 1.0f); m_pScene->setVisualizationParameter(PxVisualizationParameter::eBODY_AXES, 1.0f); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } } m_pDefaultMaterial = m_pPhysics->createMaterial(0.5f, 0.5f, 0.0f); m_pConveyorMaterial = m_pPhysics->createMaterial(1.0f, 1.0f, 0.0f); } void CPhysicPhysX :: FreePhysic( void ) { if (m_pScene) m_pScene->release(); if (m_pCooking) m_pCooking->release(); if (m_pDispatcher) m_pDispatcher->release(); if (m_pPhysics) m_pPhysics->release(); if (m_pVisualDebugger) { PxPvdTransport *transport = m_pVisualDebugger->getTransport(); m_pVisualDebugger->release(); if (transport) { transport->release(); } } PxCloseExtensions(); if (m_pFoundation) m_pFoundation->release(); m_pScene = nullptr; m_pCooking = nullptr; m_pPhysics = nullptr; m_pVisualDebugger = nullptr; m_pFoundation = nullptr; } void CPhysicPhysX :: Update( float flTimeDelta ) { if( !m_pScene || GET_SERVER_STATE() != SERVER_ACTIVE ) return; if( g_psv_gravity ) { // clamp gravity if( g_psv_gravity->value < 0.0f ) CVAR_SET_FLOAT( "sv_gravity", 0.0f ); if( g_psv_gravity->value > 800.0f ) CVAR_SET_FLOAT( "sv_gravity", 800.0f ); PxVec3 gravity = m_pScene->getGravity(); if( gravity.z != -( g_psv_gravity->value )) { ALERT( at_aiconsole, "gravity changed from %g to %g\n", gravity.z, -(g_psv_gravity->value)); gravity.z = -(g_psv_gravity->value); m_pScene->setGravity( gravity ); } } HandleEvents(); m_flAccumulator += flTimeDelta; while (m_flAccumulator > k_SimulationStepSize) { m_flAccumulator -= k_SimulationStepSize; m_pScene->simulate(k_SimulationStepSize); m_pScene->fetchResults(true); } } void CPhysicPhysX :: EndFrame( void ) { if( !m_pScene || GET_SERVER_STATE() != SERVER_ACTIVE ) return; // fill physics stats if( !p_speeds || p_speeds->value <= 0.0f ) return; PxSimulationStatistics stats; m_pScene->getSimulationStatistics( stats ); switch( (int)p_speeds->value ) { case 1: Q_snprintf(p_speeds_msg, sizeof(p_speeds_msg), "%3i active dynamic bodies\n%3i static bodies\n%3i dynamic bodies", stats.nbActiveDynamicBodies, stats.nbStaticBodies, stats.nbDynamicBodies ); break; } } void CPhysicPhysX :: RemoveBody( edict_t *pEdict ) { if( !m_pScene || !pEdict || pEdict->free ) return; // scene purge all the objects automatically CBaseEntity *pEntity = CBaseEntity::Instance( pEdict ); PxActor *pActor = ActorFromEntity( pEntity ); if (pActor) { m_pScene->removeActor(*pActor); pActor->release(); } pEntity->m_pUserData = nullptr; } PxConvexMesh *CPhysicPhysX :: ConvexMeshFromBmodel( entvars_t *pev, int modelindex ) { if( !m_pCooking ) return NULL; // don't spam console about missed NxCooking.dll if( modelindex == 1 ) { ALERT( at_error, "ConvexMeshFromBmodel: can't create convex hull from worldmodel\n" ); return NULL; // don't create rigidbody from world } model_t *bmodel; // get a world struct if(( bmodel = (model_t *)MODEL_HANDLE( modelindex )) == NULL ) { ALERT( at_error, "ConvexMeshFromBmodel: unbale to fetch model pointer %i\n", modelindex ); return NULL; } if( bmodel->nummodelsurfaces <= 0 ) { ALERT( at_aiconsole, "ConvexMeshFromBmodel: %s has no visible surfaces\n", bmodel->name ); m_fDisableWarning = TRUE; return NULL; } int numVerts = 0, totalVerts = 0; PxConvexMesh *pHull = NULL; msurface_t *psurf; Vector *verts; int i, j; // compute vertexes count psurf = &bmodel->surfaces[bmodel->firstmodelsurface]; for( i = 0; i < bmodel->nummodelsurfaces; i++, psurf++ ) totalVerts += psurf->numedges; // create a temp vertices array verts = new Vector[totalVerts]; psurf = &bmodel->surfaces[bmodel->firstmodelsurface]; for( i = 0; i < bmodel->nummodelsurfaces; i++, psurf++ ) { for( j = 0; j < psurf->numedges; j++ ) { int e = bmodel->surfedges[psurf->firstedge+j]; int v = (e > 0) ? bmodel->edges[e].v[0] : bmodel->edges[-e].v[1]; verts[numVerts++] = bmodel->vertexes[v].position; } } PxConvexMeshDesc meshDesc; meshDesc.points.data = verts; meshDesc.points.stride = sizeof(Vector); meshDesc.points.count = numVerts; meshDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; MemoryWriteBuffer outputBuffer; bool status = m_pCooking->cookConvexMesh(meshDesc, outputBuffer); delete [] verts; if( !status ) { ALERT( at_error, "failed to create convex mesh from %s\n", bmodel->name ); return NULL; } MemoryReadBuffer inputBuffer(outputBuffer.getData(), outputBuffer.getSize()); pHull = m_pPhysics->createConvexMesh(inputBuffer); if( !pHull ) ALERT( at_error, "failed to create convex mesh from %s\n", bmodel->name ); return pHull; } PxTriangleMesh *CPhysicPhysX :: TriangleMeshFromBmodel( entvars_t *pev, int modelindex ) { if( !m_pCooking ) return NULL; // don't spam console about missed NxCooking.dll if( modelindex == 1 ) { ALERT( at_error, "TriangleMeshFromBmodel: can't create triangle mesh from worldmodel\n" ); return NULL; // don't create rigidbody from world } model_t *bmodel; // get a world struct if(( bmodel = (model_t *)MODEL_HANDLE( modelindex )) == NULL ) { ALERT( at_error, "TriangleMeshFromBmodel: unable to fetch model pointer %i\n", modelindex ); return NULL; } if( bmodel->nummodelsurfaces <= 0 ) { ALERT( at_aiconsole, "TriangleMeshFromBmodel: %s has no visible surfaces\n", bmodel->name ); m_fDisableWarning = TRUE; return NULL; } // don't build hulls for water if( FBitSet( bmodel->flags, MODEL_LIQUID )) { m_fDisableWarning = TRUE; return NULL; } int i, numElems = 0, totalElems = 0; PxTriangleMesh *pMesh = NULL; msurface_t *psurf; // compute vertexes count for( i = 0; i < bmodel->nummodelsurfaces; i++ ) { psurf = &bmodel->surfaces[bmodel->firstmodelsurface + i]; totalElems += (psurf->numedges - 2); } // create a temp indices array PxU32 *indices = new PxU32[totalElems * 3]; for( i = 0; i < bmodel->nummodelsurfaces; i++ ) { msurface_t *face = &bmodel->surfaces[bmodel->firstmodelsurface + i]; bool reverse = (face->flags & SURF_PLANEBACK) ? true : false; int k = face->firstedge; // build the triangles from polygons for( int j = 0; j < face->numedges - 2; j++ ) { indices[numElems*3+0] = ConvertEdgeToIndex( bmodel, k ); indices[numElems*3+1] = ConvertEdgeToIndex( bmodel, k + j + 2 ); indices[numElems*3+2] = ConvertEdgeToIndex( bmodel, k + j + 1 ); numElems++; } } PxTriangleMeshDesc meshDesc; meshDesc.points.count = bmodel->numvertexes; meshDesc.points.stride = sizeof(mvertex_t); meshDesc.points.data = (const PxVec3*)&(bmodel->vertexes[0].position); // pointer to all vertices in the map meshDesc.triangles.count = numElems; meshDesc.triangles.stride = 3 * sizeof(PxU32); meshDesc.triangles.data = indices; meshDesc.flags = (PxMeshFlags)0; #ifdef _DEBUG // mesh should be validated before cooked without the mesh cleaning bool res = m_pCooking->validateTriangleMesh(meshDesc); PX_ASSERT(res); #endif MemoryWriteBuffer outputBuffer; bool status = m_pCooking->cookTriangleMesh(meshDesc, outputBuffer); delete [] indices; if( !status ) { ALERT( at_error, "failed to create triangle mesh from %s\n", bmodel->name ); return NULL; } MemoryReadBuffer inputBuffer(outputBuffer.getData(), outputBuffer.getSize()); pMesh = m_pPhysics->createTriangleMesh(inputBuffer); if( !pMesh ) ALERT( at_error, "failed to create triangle mesh from %s\n", bmodel->name ); return pMesh; } void CPhysicPhysX :: StudioCalcBoneQuaterion( mstudiobone_t *pbone, mstudioanim_t *panim, Vector4D &q ) { mstudioanimvalue_t *panimvalue; Radian angle; for( int j = 0; j < 3; j++ ) { if( !panim || panim->offset[j+3] == 0 ) { angle[j] = pbone->value[j+3]; // default; } else { panimvalue = (mstudioanimvalue_t *)((byte *)panim + panim->offset[j+3]); angle[j] = panimvalue[1].value; angle[j] = pbone->value[j+3] + angle[j] * pbone->scale[j+3]; } } AngleQuaternion( angle, q ); } void CPhysicPhysX :: StudioCalcBonePosition( mstudiobone_t *pbone, mstudioanim_t *panim, Vector &pos ) { mstudioanimvalue_t *panimvalue; for( int j = 0; j < 3; j++ ) { pos[j] = pbone->value[j]; // default; if( panim && panim->offset[j] != 0 ) { panimvalue = (mstudioanimvalue_t *)((byte *)panim + panim->offset[j]); pos[j] += panimvalue[1].value * pbone->scale[j]; } } } clipfile::GeometryType CPhysicPhysX::ShapeTypeToGeomType(PxGeometryType::Enum geomType) { switch (geomType) { case PxGeometryType::eCONVEXMESH: return clipfile::GeometryType::CookedConvexHull; case PxGeometryType::eTRIANGLEMESH: return clipfile::GeometryType::CookedTriangleMesh; case PxGeometryType::eBOX: return clipfile::GeometryType::CookedBox; default: return clipfile::GeometryType::Unknown; } } PxConvexMesh *CPhysicPhysX :: ConvexMeshFromStudio( entvars_t *pev, int modelindex, int32_t body, int32_t skin ) { if( UTIL_GetModelType( modelindex ) != mod_studio ) { ALERT( at_error, "CollisionFromStudio: not a studio model\n" ); return NULL; } model_t *smodel = (model_t *)MODEL_HANDLE( modelindex ); studiohdr_t *phdr = (studiohdr_t *)smodel->cache.data; if( !phdr || phdr->numbones < 1 ) { ALERT( at_error, "CollisionFromStudio: bad model header\n" ); return NULL; } PxConvexMesh *pHull = NULL; fs::Path cacheFileName; uint32_t modelStateHash = GetHashForModelState(smodel, body, skin); CacheNameForModel(smodel, cacheFileName, modelStateHash, ".hull"); if (CheckFileTimes(smodel->name, cacheFileName.string().c_str())) { // hull is never than studiomodel. Trying to load it UserStream cacheFileStream(cacheFileName.string().c_str(), true); pHull = m_pPhysics->createConvexMesh(cacheFileStream); if( !pHull ) { // we failed to loading existed hull and can't cooking new :( if( m_pCooking == NULL ) return NULL; // don't spam console about missed nxCooking.dll // trying to rebuild hull ALERT( at_error, "Convex mesh for %s is corrupted. Rebuilding...\n", smodel->name ); } else { // all is ok return pHull; } } else { // can't cooking new hull because nxCooking.dll is missed if( m_pCooking == NULL ) return NULL; // don't spam console about missed nxCooking.dll // trying to rebuild hull ALERT( at_console, "Convex mesh for %s is out of Date. Rebuilding...\n", smodel->name ); } // at this point nxCooking instance is always valid // compute default pose for building mesh from mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)phdr + phdr->seqindex); mstudioseqgroup_t *pseqgroup = (mstudioseqgroup_t *)((byte *)phdr + phdr->seqgroupindex) + pseqdesc->seqgroup; // sanity check if( pseqdesc->seqgroup != 0 ) { ALERT( at_error, "CollisionFromStudio: bad sequence group (must be 0)\n" ); return NULL; } mstudioanim_t *panim = (mstudioanim_t *)((byte *)phdr + pseqgroup->data + pseqdesc->animindex); mstudiobone_t *pbone = (mstudiobone_t *)((byte *)phdr + phdr->boneindex); static Vector pos[MAXSTUDIOBONES]; static Vector4D q[MAXSTUDIOBONES]; for( int i = 0; i < phdr->numbones; i++, pbone++, panim++ ) { StudioCalcBoneQuaterion( pbone, panim, q[i] ); StudioCalcBonePosition( pbone, panim, pos[i] ); } pbone = (mstudiobone_t *)((byte *)phdr + phdr->boneindex); matrix4x4 transform, bonematrix, bonetransform[MAXSTUDIOBONES]; transform.Identity(); // compute bones for default anim for( int i = 0; i < phdr->numbones; i++ ) { // initialize bonematrix bonematrix = matrix3x4( pos[i], q[i] ); if( pbone[i].parent == -1 ) bonetransform[i] = transform.ConcatTransforms( bonematrix ); else bonetransform[i] = bonetransform[pbone[i].parent].ConcatTransforms( bonematrix ); } mstudiobodyparts_t *pbodypart = (mstudiobodyparts_t *)((byte *)phdr + phdr->bodypartindex); mstudiomodel_t *psubmodel = (mstudiomodel_t *)((byte *)phdr + pbodypart->modelindex); Vector *pstudioverts = (Vector *)((byte *)phdr + psubmodel->vertindex); Vector *m_verts = new Vector[psubmodel->numverts]; byte *pvertbone = ((byte *)phdr + psubmodel->vertinfoindex); Vector *verts = new Vector[psubmodel->numverts * 8]; // allocate temporary vertices array PxU32 *indices = new PxU32[psubmodel->numverts * 24]; int numVerts = 0, numElems = 0; Vector tmp; // setup all the vertices for( int i = 0; i < psubmodel->numverts; i++ ) m_verts[i] = bonetransform[pvertbone[i]].VectorTransform( pstudioverts[i] ); for( int j = 0; j < psubmodel->nummesh; j++ ) { int i; mstudiomesh_t *pmesh = (mstudiomesh_t *)((byte *)phdr + psubmodel->meshindex) + j; short *ptricmds = (short *)((byte *)phdr + pmesh->triindex); while( i = *( ptricmds++ )) { int vertexState = 0; qboolean tri_strip; if( i < 0 ) { tri_strip = false; i = -i; } else tri_strip = true; for( ; i > 0; i--, ptricmds += 4 ) { // build in indices if( vertexState++ < 3 ) { indices[numElems++] = numVerts; } else if( tri_strip ) { // flip triangles between clockwise and counter clockwise if( vertexState & 1 ) { // draw triangle [n-2 n-1 n] indices[numElems++] = numVerts - 2; indices[numElems++] = numVerts - 1; indices[numElems++] = numVerts; } else { // draw triangle [n-1 n-2 n] indices[numElems++] = numVerts - 1; indices[numElems++] = numVerts - 2; indices[numElems++] = numVerts; } } else { // draw triangle fan [0 n-1 n] indices[numElems++] = numVerts - ( vertexState - 1 ); indices[numElems++] = numVerts - 1; indices[numElems++] = numVerts; } verts[numVerts++] = m_verts[ptricmds[0]]; } } } PxConvexMeshDesc meshDesc; meshDesc.indices.count = numElems / 3; meshDesc.indices.data = indices; meshDesc.indices.stride = 3 * sizeof( PxU32 ); meshDesc.points.count = numVerts; meshDesc.points.data = verts; meshDesc.points.stride = sizeof(Vector); meshDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; UserStream outputFileStream(cacheFileName.string().c_str(), false); bool status = m_pCooking->cookConvexMesh(meshDesc, outputFileStream); delete [] verts; delete [] m_verts; delete [] indices; if( !status ) { ALERT( at_error, "failed to create convex mesh from %s\n", smodel->name ); return NULL; } UserStream inputFileStream(cacheFileName.string().c_str(), true); pHull = m_pPhysics->createConvexMesh(inputFileStream); if( !pHull ) ALERT( at_error, "failed to create convex mesh from %s\n", smodel->name ); return pHull; } PxTriangleMesh *CPhysicPhysX::TriangleMeshFromStudio(entvars_t *pev, int modelindex, int32_t body, int32_t skin) { if (UTIL_GetModelType(modelindex) != mod_studio) { ALERT(at_error, "TriangleMeshFromStudio: not a studio model\n"); return NULL; } model_t *smodel = (model_t *)MODEL_HANDLE(modelindex); studiohdr_t *phdr = (studiohdr_t *)smodel->cache.data; int solidMeshes = 0; if (!phdr || phdr->numbones < 1) { ALERT(at_error, "TriangleMeshFromStudio: bad model header\n"); return NULL; } mstudiotexture_t *ptexture = (mstudiotexture_t *)((byte *)phdr + phdr->textureindex); for (int i = 0; i < phdr->numtextures; i++) { // skip this mesh it's probably foliage or somewhat if (ptexture[i].flags & STUDIO_NF_MASKED) continue; solidMeshes++; } // model is non-solid if (!solidMeshes) { m_fDisableWarning = TRUE; return NULL; } PxTriangleMesh *pMesh = NULL; fs::Path cacheFilePath; uint32_t modelStateHash = GetHashForModelState(smodel, body, skin); CacheNameForModel(smodel, cacheFilePath, modelStateHash, ".mesh"); if (CheckFileTimes(smodel->name, cacheFilePath.string().c_str()) && !m_fWorldChanged) { // hull is never than studiomodel. Trying to load it UserStream cacheFileStream(cacheFilePath.string().c_str(), true); pMesh = m_pPhysics->createTriangleMesh(cacheFileStream); if (!pMesh) { // we failed to loading existed hull and can't cooking new :( if (m_pCooking == NULL) return NULL; // don't spam console about missed nxCooking.dll // trying to rebuild hull ALERT(at_error, "Triangle mesh for %s is corrupted. Rebuilding...\n", smodel->name); } else { // all is ok return pMesh; } } else { // can't cooking new hull because nxCooking.dll is missed if (m_pCooking == NULL) return NULL; // don't spam console about missed nxCooking.dll // trying to rebuild hull ALERT(at_console, "Triangle mesh for %s is out of Date. Rebuilding...\n", smodel->name); } // at this point nxCooking instance is always valid // compute default pose for building mesh from mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)phdr + phdr->seqindex); mstudioseqgroup_t *pseqgroup = (mstudioseqgroup_t *)((byte *)phdr + phdr->seqgroupindex) + pseqdesc->seqgroup; // sanity check if (pseqdesc->seqgroup != 0) { ALERT(at_error, "TriangleMeshFromStudio: bad sequence group (must be 0)\n"); return NULL; } mstudioanim_t *panim = (mstudioanim_t *)((byte *)phdr + pseqgroup->data + pseqdesc->animindex); mstudiobone_t *pbone = (mstudiobone_t *)((byte *)phdr + phdr->boneindex); static Vector pos[MAXSTUDIOBONES]; static Vector4D q[MAXSTUDIOBONES]; for (int i = 0; i < phdr->numbones; i++, pbone++, panim++) { StudioCalcBoneQuaterion(pbone, panim, q[i]); StudioCalcBonePosition(pbone, panim, pos[i]); } pbone = (mstudiobone_t *)((byte *)phdr + phdr->boneindex); matrix4x4 transform, bonematrix, bonetransform[MAXSTUDIOBONES]; transform.Identity(); // compute bones for default anim for (int i = 0; i < phdr->numbones; i++) { // initialize bonematrix bonematrix = matrix3x4(pos[i], q[i]); if (pbone[i].parent == -1) bonetransform[i] = transform.ConcatTransforms(bonematrix); else bonetransform[i] = bonetransform[pbone[i].parent].ConcatTransforms(bonematrix); } int colliderBodygroup = pev->body; int totalVertSize = 0; for (int i = 0; i < phdr->numbodyparts; i++) { mstudiobodyparts_t *pbodypart = (mstudiobodyparts_t *)((byte *)phdr + phdr->bodypartindex) + i; int32_t index = (pev->body / pbodypart->base) % pbodypart->nummodels; mstudiomodel_t *psubmodel = (mstudiomodel_t *)((byte *)phdr + pbodypart->modelindex) + index; totalVertSize += psubmodel->numverts; } Vector *verts = new Vector[totalVertSize * 8]; // allocate temporary vertices array PxU32 *indices = new PxU32[totalVertSize * 24]; int32_t skinNumber = bound( 0, pev->skin, phdr->numskinfamilies ); int numVerts = 0, numElems = 0; Vector tmp; for (int k = 0; k < phdr->numbodyparts; k++) { int i; mstudiobodyparts_t *pbodypart = (mstudiobodyparts_t *)((byte *)phdr + phdr->bodypartindex) + k; int32_t index = (pev->body / pbodypart->base) % pbodypart->nummodels; mstudiomodel_t *psubmodel = (mstudiomodel_t *)((byte *)phdr + pbodypart->modelindex) + index; Vector *pstudioverts = (Vector *)((byte *)phdr + psubmodel->vertindex); Vector *m_verts = new Vector[psubmodel->numverts]; byte *pvertbone = ((byte *)phdr + psubmodel->vertinfoindex); // setup all the vertices for (i = 0; i < psubmodel->numverts; i++) { m_verts[i] = bonetransform[pvertbone[i]].VectorTransform(pstudioverts[i]); } ptexture = (mstudiotexture_t *)((byte *)phdr + phdr->textureindex); short *pskinref = (short *)((byte *)phdr + phdr->skinindex); if (skinNumber != 0 && skinNumber < phdr->numskinfamilies) pskinref += (skinNumber * phdr->numskinref); for (int j = 0; j < psubmodel->nummesh; j++) { mstudiomesh_t *pmesh = (mstudiomesh_t *)((byte *)phdr + psubmodel->meshindex) + j; short *ptricmds = (short *)((byte *)phdr + pmesh->triindex); if (phdr->numtextures != 0 && phdr->textureindex != 0) { // skip this mesh it's probably foliage or somewhat if (ptexture[pskinref[pmesh->skinref]].flags & STUDIO_NF_MASKED) continue; } while (i = *(ptricmds++)) { int vertexState = 0; bool tri_strip; if (i < 0) { tri_strip = false; i = -i; } else tri_strip = true; for (; i > 0; i--, ptricmds += 4) { // build in indices if (vertexState++ < 3) { indices[numElems++] = numVerts; } else if (tri_strip) { // flip triangles between clockwise and counter clockwise if (vertexState & 1) { // draw triangle [n-2 n-1 n] indices[numElems++] = numVerts - 2; indices[numElems++] = numVerts - 1; indices[numElems++] = numVerts; } else { // draw triangle [n-1 n-2 n] indices[numElems++] = numVerts - 1; indices[numElems++] = numVerts - 2; indices[numElems++] = numVerts; } } else { // draw triangle fan [0 n-1 n] indices[numElems++] = numVerts - (vertexState - 1); indices[numElems++] = numVerts - 1; indices[numElems++] = numVerts; } // verts[numVerts++] = m_verts[ptricmds[0]]; verts[numVerts] = m_verts[ptricmds[0]]; numVerts++; } } } delete[] m_verts; } PxTriangleMeshDesc meshDesc; meshDesc.triangles.data = indices; meshDesc.triangles.count = numElems / 3; meshDesc.triangles.stride = 3 * sizeof(PxU32); meshDesc.points.data = verts; meshDesc.points.count = numVerts; meshDesc.points.stride = sizeof(Vector); meshDesc.flags = PxMeshFlag::eFLIPNORMALS; #ifdef _DEBUG // mesh should be validated before cooked without the mesh cleaning bool res = m_pCooking->validateTriangleMesh(meshDesc); PX_ASSERT(res); #endif UserStream outputFileStream(cacheFilePath.string().c_str(), false); bool status = m_pCooking->cookTriangleMesh(meshDesc, outputFileStream); delete[] verts; delete[] indices; if (!status) { ALERT(at_error, "failed to create triangle mesh from %s\n", smodel->name); return NULL; } UserStream inputFileStream(cacheFilePath.string().c_str(), true); pMesh = m_pPhysics->createTriangleMesh(inputFileStream); if (!pMesh) ALERT(at_error, "failed to create triangle mesh from %s\n", smodel->name); return pMesh; } PxConvexMesh *CPhysicPhysX :: ConvexMeshFromEntity( CBaseEntity *pObject ) { if( !pObject || !m_pPhysics ) return NULL; // check for bspmodel model_t *model = (model_t *)MODEL_HANDLE( pObject->pev->modelindex ); if( !model || model->type == mod_bad ) { ALERT( at_aiconsole, "ConvexMeshFromEntity: entity %s has NULL model\n", pObject->GetClassname( )); return NULL; } PxConvexMesh *pCollision = NULL; // call the apropriate loader switch( model->type ) { case mod_brush: pCollision = ConvexMeshFromBmodel( pObject->pev, pObject->pev->modelindex ); break; case mod_studio: pCollision = ConvexMeshFromStudio( pObject->pev, pObject->pev->modelindex, pObject->pev->body, pObject->pev->skin ); break; } if( !pCollision && !m_fDisableWarning ) ALERT( at_warning, "ConvexMeshFromEntity: %i has missing collision\n", pObject->pev->modelindex ); m_fDisableWarning = FALSE; return pCollision; } PxTriangleMesh *CPhysicPhysX :: TriangleMeshFromEntity( CBaseEntity *pObject ) { if( !pObject || !m_pPhysics ) return NULL; // check for bspmodel model_t *model = (model_t *)MODEL_HANDLE( pObject->pev->modelindex ); if( !model || model->type == mod_bad ) { ALERT( at_aiconsole, "TriangleMeshFromEntity: entity %s has NULL model\n", pObject->GetClassname( )); return NULL; } PxTriangleMesh *pCollision = NULL; // call the apropriate loader switch( model->type ) { case mod_brush: pCollision = TriangleMeshFromBmodel( pObject->pev, pObject->pev->modelindex ); break; case mod_studio: pCollision = TriangleMeshFromStudio( pObject->pev, pObject->pev->modelindex, pObject->pev->body, pObject->pev->skin ); break; } if( !pCollision && !m_fDisableWarning ) ALERT( at_warning, "TriangleMeshFromEntity: %s has missing collision\n", pObject->GetClassname( )); m_fDisableWarning = FALSE; return pCollision; } PxActor *CPhysicPhysX :: ActorFromEntity( CBaseEntity *pObject ) { if( FNullEnt( pObject ) || !pObject->m_pUserData ) return NULL; #if defined (HAS_PHYSIC_VEHICLE) if( pObject->m_iActorType == ACTOR_VEHICLE ) { NxVehicle *pVehicle = (NxVehicle *)pObject->m_pUserData; return pVehicle->getActor(); } #endif return (PxActor *)pObject->m_pUserData; } physx::PxBounds3 CPhysicPhysX::GetIntersectionBounds(const physx::PxBounds3 &a, const physx::PxBounds3 &b) { if (!a.intersects(b)) { return PxBounds3::empty(); } PxBounds3 result; result.minimum.x = std::max(a.minimum.x, b.minimum.x); result.minimum.y = std::max(a.minimum.y, b.minimum.y); result.minimum.z = std::max(a.minimum.z, b.minimum.z); result.maximum.x = std::min(a.maximum.x, b.maximum.x); result.maximum.y = std::min(a.maximum.y, b.maximum.y); result.maximum.z = std::min(a.maximum.z, b.maximum.z); return result; } CBaseEntity *CPhysicPhysX :: EntityFromActor( PxActor *pObject ) { if( !pObject || !pObject->userData ) return NULL; return CBaseEntity::Instance( (edict_t *)pObject->userData ); } bool CPhysicPhysX::CheckCollision(physx::PxRigidActor *pActor) { std::vector<PxShape*> shapes; if (pActor->getNbShapes() > 0) { shapes.resize(pActor->getNbShapes()); pActor->getShapes(&shapes[0], shapes.size()); for (PxShape *shape : shapes) { if (shape->getFlags() & PxShapeFlag::eSIMULATION_SHAPE) { return true; } } } return false; } void CPhysicPhysX::ToggleCollision(physx::PxRigidActor *pActor, bool enabled) { std::vector<PxShape*> shapes; shapes.resize(pActor->getNbShapes()); pActor->getShapes(&shapes[0], shapes.size()); if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: ToggleCollision( actor = %x, state = %s )\n", pActor, enabled ? "true" : "false"); } for (PxShape *shape : shapes) { bool collisionState = shape->getFlags() & PxShapeFlag::eSIMULATION_SHAPE; if (collisionState != enabled) { // change state only if it's different, to avoid useless write access to API shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, enabled); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, enabled); } } } void *CPhysicPhysX :: CreateBodyFromEntity( CBaseEntity *pObject ) { PxConvexMesh *pCollision = ConvexMeshFromEntity(pObject); if (!pCollision) return NULL; PxRigidDynamic *pActor = m_pPhysics->createRigidDynamic(PxTransform(PxIdentity)); PxMeshScale scale(pObject->GetScale()); PxShape *pShape = PxRigidActorExt::createExclusiveShape(*pActor, PxConvexMeshGeometry(pCollision, scale), *m_pDefaultMaterial); if (!pActor) { ALERT(at_error, "failed to create rigidbody from entity %s\n", pObject->GetClassname()); return NULL; } float mat[16]; float maxVelocity = CVAR_GET_FLOAT("sv_maxvelocity"); matrix4x4(pObject->GetAbsOrigin(), pObject->GetAbsAngles(), 1.0f).CopyToArray(mat); PxTransform pose = PxTransform(PxMat44(mat)); pActor->setGlobalPose(pose); pActor->setName(pObject->GetClassname()); pActor->setSolverIterationCounts(k_SolverIterationCount); pActor->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); pActor->setLinearVelocity(pObject->GetLocalVelocity()); pActor->setAngularVelocity(pObject->GetLocalAvelocity()); pActor->setMaxLinearVelocity(maxVelocity); pActor->setMaxAngularVelocity(720.0); pActor->userData = pObject->edict(); PxRigidBodyExt::updateMassAndInertia(*pActor, k_DensityFactor); m_pScene->addActor(*pActor); pObject->m_iActorType = ACTOR_DYNAMIC; pObject->m_pUserData = pActor; return pActor; } /* ================= CreateBoxFromEntity used for characters: clients and monsters ================= */ void *CPhysicPhysX :: CreateBoxFromEntity( CBaseEntity *pObject ) { PxBoxGeometry boxGeometry; boxGeometry.halfExtents = pObject->pev->size * k_PaddingFactor; PxRigidDynamic *pActor = m_pPhysics->createRigidDynamic(PxTransform(PxIdentity)); PxShape *pShape = PxRigidActorExt::createExclusiveShape(*pActor, boxGeometry, *m_pDefaultMaterial); if (!pActor) { ALERT( at_error, "failed to create rigidbody from entity %s\n", pObject->GetClassname()); return NULL; } Vector origin = (pObject->IsMonster()) ? Vector( 0, 0, pObject->pev->maxs.z / 2.0f ) : g_vecZero; origin += pObject->GetAbsOrigin(); PxTransform pose = PxTransform(origin); pActor->setName(pObject->GetClassname()); pActor->setGlobalPose(pose); pActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); pActor->userData = pObject->edict(); m_pScene->addActor(*pActor); pObject->m_iActorType = ACTOR_CHARACTER; pObject->m_pUserData = pActor; return pActor; } void *CPhysicPhysX::CreateKinematicBodyFromEntity(CBaseEntity *pObject) { PxTriangleMesh *pCollision = TriangleMeshFromEntity(pObject); if (!pCollision) return NULL; PxRigidDynamic *pActor = m_pPhysics->createRigidDynamic(PxTransform(PxIdentity)); if (!pActor) { ALERT(at_error, "failed to create kinematic from entity %s\n", pObject->GetClassname()); return NULL; } if (!UTIL_CanRotate(pObject)) { // entity missed origin-brush pActor->setRigidDynamicLockFlags( PxRigidDynamicLockFlag::eLOCK_ANGULAR_X | PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y | PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z); } float mat[16]; matrix4x4(pObject->GetAbsOrigin(), pObject->GetAbsAngles(), 1.0f).CopyToArray(mat); PxTransform pose = PxTransform(PxMat44(mat)); pActor->setName(pObject->GetClassname()); pActor->setGlobalPose(pose); pActor->setSolverIterationCounts(k_SolverIterationCount); pActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); pActor->userData = pObject->edict(); PxMeshScale scale(pObject->GetScale()); PxShape *pShape = PxRigidActorExt::createExclusiveShape(*pActor, PxTriangleMeshGeometry(pCollision, scale), *m_pDefaultMaterial); m_pScene->addActor(*pActor); pObject->m_iActorType = ACTOR_KINEMATIC; pObject->m_pUserData = pActor; return pActor; } void *CPhysicPhysX :: CreateStaticBodyFromEntity( CBaseEntity *pObject ) { PxTriangleMesh *pCollision = TriangleMeshFromEntity( pObject ); if( !pCollision ) return NULL; float mat[16]; matrix4x4(pObject->GetAbsOrigin(), pObject->GetAbsAngles(), 1.0f).CopyToArray(mat); bool conveyorEntity = FBitSet(pObject->pev->flags, FL_CONVEYOR); PxTransform pose = PxTransform(PxMat44(mat)); PxMeshScale scale(pObject->GetScale()); PxMaterial *material = conveyorEntity ? m_pConveyorMaterial : m_pDefaultMaterial; PxRigidStatic *pActor = m_pPhysics->createRigidStatic(pose); PxShape *pShape = PxRigidActorExt::createExclusiveShape(*pActor, PxTriangleMeshGeometry(pCollision, scale), *material); if( !pActor ) { ALERT( at_error, "failed to create static from entity %s\n", pObject->GetClassname( )); return NULL; } if (conveyorEntity) { CollisionFilterData filterData; filterData.SetConveyorFlag(true); pShape->setSimulationFilterData(filterData.ToNativeType()); } pActor->setName( pObject->GetClassname( )); pActor->userData = pObject->edict(); m_pScene->addActor(*pActor); pObject->m_iActorType = ACTOR_STATIC; pObject->m_pUserData = pActor; return pActor; } void *CPhysicPhysX::CreateTriggerFromEntity(CBaseEntity *pEntity) { PxBoxGeometry boxGeometry; boxGeometry.halfExtents = pEntity->pev->size / 2.0f; Vector centerOrigin = pEntity->pev->mins + pEntity->pev->size / 2.0f; PxRigidStatic *pActor = m_pPhysics->createRigidStatic(PxTransform(centerOrigin)); PxShape *pShape = PxRigidActorExt::createExclusiveShape(*pActor, boxGeometry, *m_pDefaultMaterial); if (!pActor) { ALERT( at_error, "failed to create trigger actor from entity %s\n", pEntity->GetClassname()); return NULL; } pShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); pShape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, true); pActor->setName(pEntity->GetClassname()); pActor->userData = pEntity->edict(); m_pScene->addActor(*pActor); pEntity->m_iActorType = ACTOR_TRIGGER; pEntity->m_pUserData = pActor; return pActor; } void *CPhysicPhysX :: CreateVehicle( CBaseEntity *pObject, string_t scriptName ) { #if defined (HAS_PHYSIC_VEHICLE) NxBoxShapeDesc boxShapes[MAXSTUDIOBONES]; vehicleparams_t vehicleParams; NxVehicleDesc vehicleDesc; int i, j, index; int wheel_count; Vector wheel_pos; if( UTIL_GetModelType( pObject->pev->modelindex ) != mod_studio ) { ALERT( at_error, "CreateVehicle: not a studio model\n" ); return NULL; } if( !ParseVehicleScript( STRING( scriptName ), vehicleParams )) { ALERT( at_error, "CreateVehicle: couldn't load %s\n", STRING( scriptName )); return NULL; } model_t *smodel = (model_t *)MODEL_HANDLE( pObject->pev->modelindex ); studiohdr_t *phdr = (studiohdr_t *)smodel->cache.data; if( !phdr || phdr->numbones < 1 ) { ALERT( at_error, "CreateVehicle: bad model header\n" ); return NULL; } // compute default pose for building mesh from mstudioseqdesc_t *pseqdesc = (mstudioseqdesc_t *)((byte *)phdr + phdr->seqindex); mstudioseqgroup_t *pseqgroup = (mstudioseqgroup_t *)((byte *)phdr + phdr->seqgroupindex) + pseqdesc->seqgroup; mstudioattachment_t *pattachment = (mstudioattachment_t *) ((byte *)phdr + phdr->attachmentindex); mstudioanim_t *panim = (mstudioanim_t *)((byte *)phdr + pseqgroup->data + pseqdesc->animindex); mstudiobone_t *pbone = (mstudiobone_t *)((byte *)phdr + phdr->boneindex); static Vector pos[MAXSTUDIOBONES]; static Vector4D q[MAXSTUDIOBONES]; for( i = 0; i < phdr->numbones; i++, pbone++, panim++ ) { StudioCalcBoneQuaterion( pbone, panim, q[i] ); StudioCalcBonePosition( pbone, panim, pos[i] ); } pbone = (mstudiobone_t *)((byte *)phdr + phdr->boneindex); matrix4x4 transform, bonematrix, bonetransform[MAXSTUDIOBONES]; transform.Identity(); // compute bones for default anim for( i = 0; i < phdr->numbones; i++ ) { // initialize bonematrix bonematrix = matrix3x4( pos[i], q[i] ); if( pbone[i].parent == -1 ) bonetransform[i] = transform.ConcatTransforms( bonematrix ); else bonetransform[i] = bonetransform[pbone[i].parent].ConcatTransforms( bonematrix ); } // create body vehicle from hitboxes for( i = 0; i < phdr->numhitboxes; i++ ) { mstudiobbox_t *pbbox = (mstudiobbox_t *)((byte *)phdr + phdr->hitboxindex); vec3_t tmp, p[8], mins, maxs, size, pos; ClearBounds( mins , maxs ); for( j = 0; j < 8; j++ ) { tmp[0] = (j & 1) ? pbbox[i].bbmin[0] : pbbox[i].bbmax[0]; tmp[1] = (j & 2) ? pbbox[i].bbmin[1] : pbbox[i].bbmax[1]; tmp[2] = (j & 4) ? pbbox[i].bbmin[2] : pbbox[i].bbmax[2]; p[j] = bonetransform[pbbox[i].bone].VectorTransform( tmp ); AddPointToBounds( p[j], mins, maxs ); } boxShapes[i].dimensions.set( NxVec3( maxs - mins ) * 0.5 ); // half-size boxShapes[i].localPose.t.set( NxVec3(( mins + maxs ) * 0.5f )); // origin vehicleDesc.carShapes.pushBack( &boxShapes[i] ); } vehicleDesc.mass = 1200.0f; vehicleDesc.digitalSteeringDelta = 0.04f; vehicleDesc.steeringMaxAngle = 30.0f; vehicleDesc.motorForce = 3500.0f; vehicleDesc.centerOfMass.set( -24, 0, -16 ); vehicleDesc.maxVelocity = 60.0f; float scale = 32.0f; NxVehicleMotorDesc motorDesc; NxVehicleGearDesc gearDesc; NxWheelDesc wheelDesc[VEHICLE_MAX_WHEEL_COUNT]; NxReal wheelRadius = 20.0f; gearDesc.setToCorvette(); motorDesc.setToCorvette(); vehicleDesc.motorDesc = &motorDesc; vehicleDesc.gearDesc = &gearDesc; // setup wheels for( i = wheel_count = 0; i < vehicleParams.axleCount; i++ ) { axleparams_t *axle = &vehicleParams.axles[i]; for( j = 0; j < axle->wheelsPerAxle; j++ ) { wheelparams_t *wheel = &axle->wheels[j]; NxU32 flags = NX_WF_USE_WHEELSHAPE; wheelDesc[wheel_count].wheelApproximation = 10; wheelDesc[wheel_count].wheelRadius = wheel->radius; wheelDesc[wheel_count].wheelWidth = 0.1f * scale; // FIXME wheelDesc[wheel_count].wheelSuspension = axle->suspension.springHeight; wheelDesc[wheel_count].springRestitution = axle->suspension.springConstant; wheelDesc[wheel_count].springDamping = axle->suspension.springDamping; wheelDesc[wheel_count].springBias = axle->suspension.springDampingCompression; wheelDesc[wheel_count].maxBrakeForce = axle->suspension.brakeForce; wheelDesc[wheel_count].frictionToFront = wheel->frontFriction; wheelDesc[wheel_count].frictionToSide = wheel->sideFriction; wheelDesc[wheel_count].wheelPoseParamIndex = pObject->LookupPoseParameter( wheel->wheelName ); wheelDesc[wheel_count].suspensionPoseParamIndex = pObject->LookupPoseParameter( wheel->suspensionName ); // set wheel flags if( axle->steerable ) SetBits( flags, NX_WF_STEERABLE_INPUT ); if( axle->driven ) SetBits( flags, NX_WF_ACCELERATED ); if( axle->affectBrake ) SetBits( flags, NX_WF_AFFECTED_BY_HANDBRAKE ); wheelDesc[wheel_count].wheelFlags = flags; // set wheel position if(( index = FindAttachmentByName( phdr, wheel->attachmentName )) != -1 ) { wheel_pos = bonetransform[pattachment[index].bone].VectorTransform( pattachment[i].org ); wheelDesc[wheel_count].position.set( NxVec3( wheel_pos )); } vehicleDesc.carWheels.pushBack( &wheelDesc[wheel_count] ); wheel_count++; } } vehicleDesc.steeringSteerPoint.set( 1.8 * scale, 0, 0 ); vehicleDesc.steeringTurnPoint.set( -1.5 * scale, 0, 0 ); NxVehicle *pVehicle = NxVehicle :: createVehicle( m_pScene, pObject, &vehicleDesc ); if( !pVehicle ) { ALERT( at_error, "failed to create vehicle from entity %s\n", pObject->GetClassname( )); return NULL; } // get steer controller index pVehicle->steerPoseParamIndex = pObject->LookupPoseParameter( vehicleParams.steering.steeringName ); NxActor *pActor = pVehicle->getActor(); if( !pActor ) { ALERT( at_error, "failed to create vehicle from entity %s\n", pObject->GetClassname( )); delete pVehicle; return NULL; } pActor->setName( pObject->GetClassname( )); NxMat34 pose; float mat[16]; matrix4x4( pObject->GetAbsOrigin(), pObject->GetAbsAngles(), 1.0f ).CopyToArray( mat ); pose.setColumnMajor44( mat ); pActor->setGlobalPose( pose ); pActor->setLinearVelocity( pObject->GetLocalVelocity() ); pActor->setAngularVelocity( pObject->GetLocalAvelocity() ); return pVehicle; #else return NULL; #endif } void CPhysicPhysX :: UpdateVehicle( CBaseEntity *pObject ) { #if defined (HAS_PHYSIC_VEHICLE) if( !pObject || pObject->m_iActorType != ACTOR_VEHICLE ) return; NxVehicle *pVehicle = (NxVehicle *)pObject->m_pUserData; for( NxU32 i = 0; i < pVehicle->getNbWheels(); i++ ) { NxWheel *pWheel = (NxWheel *)pVehicle->getWheel( i ); pObject->SetPoseParameter( pWheel->wheelPoseParamIndex, -pWheel->getRollAngle( )); pObject->SetPoseParameter( pWheel->suspensionPoseParamIndex, pWheel->getSuspensionHeight( )); } CBaseEntity *pDriver = pObject->GetVehicleDriver(); if( pDriver != NULL ) { bool left = !!FBitSet( pDriver->pev->button, IN_MOVELEFT ); bool right = !!FBitSet( pDriver->pev->button, IN_MOVERIGHT ); bool forward = !!FBitSet( pDriver->pev->button, IN_FORWARD ); bool backward = !!FBitSet( pDriver->pev->button, IN_BACK ); bool handBrake = !!FBitSet( pDriver->pev->button, IN_JUMP ); NxReal steering = 0; if( left && !right) steering = -1; else if (right && !left) steering = 1; NxReal acceleration = 0; if (forward && !backward) acceleration = -1; else if (backward && !forward) acceleration = 1; pVehicle->control( steering, false, acceleration, false, handBrake ); pObject->SetPoseParameter( pVehicle->steerPoseParamIndex, pVehicle->getSteeringAngle() ); } pVehicle->updateVehicle( gpGlobals->frametime ); #endif } bool CPhysicPhysX::UpdateEntityTransform( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) return false; PxRigidDynamic *pDynamicActor = pActor->is<PxRigidDynamic>(); if (!pDynamicActor || pDynamicActor->isSleeping()) return false; PxTransform pose = pDynamicActor->getGlobalPose(); matrix4x4 m( PxMat44(pose).front() ); Vector angles = m.GetAngles(); Vector origin = m.GetOrigin(); // store actor velocities too pEntity->SetLocalVelocity( pDynamicActor->getLinearVelocity() ); pEntity->SetLocalAvelocity( pDynamicActor->getAngularVelocity() ); Vector vecPrevOrigin = pEntity->GetAbsOrigin(); pEntity->SetLocalAngles( angles ); pEntity->SetLocalOrigin( origin ); pEntity->RelinkEntity( TRUE, &vecPrevOrigin ); return true; } bool CPhysicPhysX :: UpdateActorPos( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) return false; PxRigidActor *pRigidActor = pActor->is<PxRigidActor>(); if (!pRigidActor) return false; float mat[16]; matrix4x4 m( pEntity->GetAbsOrigin(), pEntity->GetAbsAngles(), 1.0f ); m.CopyToArray( mat ); PxTransform pose = PxTransform(PxMat44(mat)); pRigidActor->setGlobalPose( pose ); PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); if (!(pRigidDynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) { pRigidDynamic->setLinearVelocity( pEntity->GetLocalVelocity() ); pRigidDynamic->setAngularVelocity( pEntity->GetLocalAvelocity() ); } return true; } bool CPhysicPhysX :: IsBodySleeping( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) return false; PxRigidDynamic *pDynamicActor = pActor->is<PxRigidDynamic>(); if (!pDynamicActor) return false; return pDynamicActor->isSleeping(); } void CPhysicPhysX :: UpdateEntityAABB( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity( pEntity ); if (!pActor) return; PxRigidActor *pRigidActor = pActor->is<PxRigidActor>(); if (!pRigidActor || pRigidActor->getNbShapes() <= 0) return; PxBounds3 actorBounds = pRigidActor->getWorldBounds(); ClearBounds( pEntity->pev->absmin, pEntity->pev->absmax ); AddPointToBounds( actorBounds.minimum, pEntity->pev->absmin, pEntity->pev->absmax ); AddPointToBounds( actorBounds.maximum, pEntity->pev->absmin, pEntity->pev->absmax ); pEntity->pev->mins = pEntity->pev->absmin - pEntity->pev->origin; pEntity->pev->maxs = pEntity->pev->absmax - pEntity->pev->origin; pEntity->pev->size = pEntity->pev->maxs - pEntity->pev->mins; } /* =============== PHYSICS SAVE\RESTORE SYSTEM =============== */ // list of variables that needs to be saved how it will be saved /* // actor description NxMat34 globalPose; pev->origin, pev->angles const NxBodyDesc* body; not needs NxReal density; constant (???) NxU32 flags; m_iActorFlags; NxActorGroup group; pev->groupinfo (???). NxU32 contactReportFlags; not needs (already set by scene rules) NxU16 forceFieldMaterial; not needs (not used) void* userData; not needs (automatically restored) const char* name; not needs (automatically restored) NxCompartment *compartment; not needs (not used) NxActorDescType type; not needs (automatically restored) // body description NxMat34 massLocalPose; not needs (probably automatically recomputed on apply shape) NxVec3 massSpaceInertia; not needs (probably automatically recomputed on apply shape) NxReal mass; not needs (probably automatically recomputed on apply shape) NxVec3 linearVelocity; pev->velocity NxVec3 angularVelocity; pev->avelocity NxReal wakeUpCounter; not needs (use default) NxReal linearDamping; not needs (use default) NxReal angularDamping; not needs (use default) NxReal maxAngularVelocity; not needs (already set by scene rules) NxReal CCDMotionThreshold; not needs (use default) NxU32 flags; m_iBodyFlags; NxReal sleepLinearVelocity; not needs (already set by scene rules) NxReal sleepAngularVelocity; not needs (already set by scene rules) NxU32 solverIterationCount; not needs (use default) NxReal sleepEnergyThreshold; not needs (use default) NxReal sleepDamping; not needs (use default) NxReal contactReportThreshold; not needs (use default) */ /* =============== SaveBody collect all the info from generic actor =============== */ void CPhysicPhysX :: SaveBody( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) { ALERT(at_warning, "SaveBody: physic entity %i missed actor!\n", pEntity->m_iActorType); return; } PxRigidActor *pRigidActor = pActor->is<PxRigidActor>(); if (!pRigidActor) { ALERT(at_warning, "SaveBody: physic entity %i missed rigid actor!\n", pEntity->m_iActorType); return; } PxShape *shape; PxFilterData filterData; PxRigidDynamic *pRigidBody = pRigidActor->is<PxRigidDynamic>(); if (pRigidActor->getShapes(&shape, 1)) { filterData = shape->getSimulationFilterData(); } // filter data get and stored only for one shape, but it can be more than one // assumed that all attached shapes have same filter data pEntity->m_iFilterData[0] = filterData.word0; pEntity->m_iFilterData[1] = filterData.word1; pEntity->m_iFilterData[2] = filterData.word2; pEntity->m_iFilterData[3] = filterData.word3; pEntity->m_iActorFlags = pRigidActor->getActorFlags(); if (pRigidBody) { pEntity->m_iBodyFlags = pRigidBody->getRigidBodyFlags(); pEntity->m_flBodyMass = pRigidBody->getMass(); pEntity->m_fFreezed = pRigidBody->isSleeping(); } else { pEntity->m_iBodyFlags = 0; pEntity->m_flBodyMass = 0.0f; pEntity->m_fFreezed = false; } if (pEntity->m_iActorType == ACTOR_DYNAMIC) { // update movement variables UpdateEntityTransform(pEntity); } } /* =============== RestoreBody re-create shape, apply physic params =============== */ void *CPhysicPhysX :: RestoreBody( CBaseEntity *pEntity ) { // physics not initialized? if (!m_pScene) return NULL; PxShape *pShape; PxRigidActor *pActor; PxTransform pose; Vector angles = pEntity->GetAbsAngles(); PxMeshScale scale(pEntity->GetScale()); if (pEntity->m_iActorType == ACTOR_CHARACTER) { angles = g_vecZero; // no angles for NPC and client } float mat[16]; matrix4x4 m(pEntity->GetAbsOrigin(), angles, 1.0f); m.CopyToArray(mat); pose = PxTransform(PxMat44(mat)); if (pEntity->m_iActorType == ACTOR_STATIC) { pActor = m_pPhysics->createRigidStatic(pose); } else { pActor = m_pPhysics->createRigidDynamic(pose); } if (!pActor) { ALERT(at_error, "RestoreBody: unbale to create actor with type (%i)\n", pEntity->m_iActorType); return NULL; } PxRigidDynamic *pRigidBody = pActor->is<PxRigidDynamic>(); if (pEntity->m_iActorType == ACTOR_KINEMATIC) { // set kinematic flag before shape creating, this is required by design pRigidBody->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); } switch (pEntity->m_iActorType) { case ACTOR_DYNAMIC: { PxConvexMesh *convexMesh = ConvexMeshFromEntity(pEntity); if (!convexMesh) { ALERT(at_error, "RestoreBody: failed to create convex mesh\n"); return NULL; } pShape = PxRigidActorExt::createExclusiveShape(*pActor, PxConvexMeshGeometry(convexMesh, scale), *m_pDefaultMaterial); break; } case ACTOR_CHARACTER: { PxBoxGeometry box; box.halfExtents = pEntity->pev->size * k_PaddingFactor; pShape = PxRigidActorExt::createExclusiveShape(*pActor, box, *m_pDefaultMaterial); break; } case ACTOR_KINEMATIC: case ACTOR_STATIC: { PxTriangleMesh *triangleMesh = TriangleMeshFromEntity(pEntity); if (!triangleMesh) { ALERT(at_error, "RestoreBody: failed to create triangle mesh\n"); return NULL; } PxMaterial *pMaterial = m_pDefaultMaterial; if (pEntity->pev->flags & FL_CONVEYOR) { pMaterial = m_pConveyorMaterial; } pShape = PxRigidActorExt::createExclusiveShape(*pActor, PxTriangleMeshGeometry(triangleMesh, scale), *pMaterial); break; } default: { ALERT(at_error, "RestoreBody: invalid actor type %i\n", pEntity->m_iActorType); return NULL; } } if (!pShape) { ALERT(at_error, "RestoreBody: failed to create shape\n"); return NULL; } PxFilterData filterData; filterData.word0 = pEntity->m_iFilterData[0]; filterData.word1 = pEntity->m_iFilterData[1]; filterData.word2 = pEntity->m_iFilterData[2]; filterData.word3 = pEntity->m_iFilterData[3]; pShape->setSimulationFilterData(filterData); // fill in actor description if (pEntity->m_iActorType != ACTOR_STATIC) { pRigidBody->setRigidBodyFlags(static_cast<PxRigidBodyFlags>(pEntity->m_iBodyFlags)); pRigidBody->setMass(pEntity->m_flBodyMass); pRigidBody->setSolverIterationCounts(k_SolverIterationCount); if (pEntity->m_iActorType != ACTOR_KINEMATIC) { pRigidBody->setLinearVelocity(pEntity->GetAbsVelocity()); pRigidBody->setAngularVelocity(pEntity->GetAbsAvelocity()); } PxRigidBodyExt::updateMassAndInertia(*pRigidBody, k_DensityFactor); if (pEntity->m_fFreezed && pEntity->m_iActorType == ACTOR_DYNAMIC) { pRigidBody->putToSleep(); } } pActor->userData = pEntity->edict(); pActor->setActorFlags(static_cast<PxActorFlags>(pEntity->m_iActorFlags)); pActor->setName(pEntity->GetClassname()); pEntity->m_pUserData = pActor; m_pScene->addActor(*pActor); return pActor; } void CPhysicPhysX :: SetAngles( CBaseEntity *pEntity, const Vector &angles ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: SetAngles( entity = %x, angles = (%.2f, %.2f, %.2f) )\n", pEntity, angles.x, angles.y, angles.z); } matrix3x3 m(angles); PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); PxTransform transform = pRigidDynamic->getGlobalPose(); transform.q = PxQuat(PxMat33( m )); pRigidDynamic->setGlobalPose(transform); } void CPhysicPhysX :: SetOrigin( CBaseEntity *pEntity, const Vector &origin ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: SetOrigin( entity = %x, origin = (%.2f, %.2f, %.2f) )\n", pEntity, origin.x, origin.y, origin.z); } PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); PxTransform transform = pRigidDynamic->getGlobalPose(); transform.p = origin; pRigidDynamic->setGlobalPose(transform); } void CPhysicPhysX :: SetVelocity( CBaseEntity *pEntity, const Vector &velocity ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: SetVelocity( entity = %x, velocity = (%.2f, %.2f, %.2f) )\n", pEntity, velocity.x, velocity.y, velocity.z); } PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); pRigidDynamic->setLinearVelocity( velocity ); } void CPhysicPhysX :: SetAvelocity( CBaseEntity *pEntity, const Vector &velocity ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: SetAvelocity( entity = %x, velocity = (%.2f, %.2f, %.2f) )\n", pEntity, velocity.x, velocity.y, velocity.z); } PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); pRigidDynamic->setAngularVelocity( velocity ); } void CPhysicPhysX :: MoveObject( CBaseEntity *pEntity, const Vector &finalPos ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: MoveObject( entity = %x, finalPos = (%.2f, %.2f, %.2f) )\n", pEntity, finalPos.x, finalPos.y, finalPos.z); } PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); PxTransform pose = pRigidDynamic->getGlobalPose(); pose.p = finalPos; pRigidDynamic->setKinematicTarget(pose); } void CPhysicPhysX :: RotateObject( CBaseEntity *pEntity, const Vector &finalAngle ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: RotateObject( entity = %x, finalAngle = (%.2f, %.2f, %.2f) )\n", pEntity, finalAngle.x, finalAngle.y, finalAngle.z); } PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); PxTransform pose = pRigidDynamic->getGlobalPose(); matrix3x3 m(finalAngle); pose.q = PxQuat(PxMat33(m)); pRigidDynamic->setKinematicTarget(pose); } void CPhysicPhysX :: SetLinearMomentum( CBaseEntity *pEntity, const Vector &velocity ) { PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) return; PxRigidDynamic *pRigidDynamic = pActor->is<PxRigidDynamic>(); pRigidDynamic->setForceAndTorque(velocity, PxVec3(0.f), PxForceMode::eIMPULSE); } void CPhysicPhysX :: AddImpulse( CBaseEntity *pEntity, const Vector &impulse, const Vector &position, float factor ) { PxActor *pActor = ActorFromEntity( pEntity ); if (!pActor) return; PxRigidBody *pRigidBody = pActor->is<PxRigidBody>(); PxF32 coeff = (1000.0f / pRigidBody->getMass()) * factor; // prevent to apply too much impulse if (pRigidBody->getMass() < 8.0f) { coeff *= 0.0001f; } PxRigidBodyExt::addForceAtPos(*pRigidBody, PxVec3(impulse * coeff), position, PxForceMode::eIMPULSE); } void CPhysicPhysX :: AddForce( CBaseEntity *pEntity, const Vector &force ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; PxRigidBody *pRigidBody = pActor->is<PxRigidBody>(); pRigidBody->addForce(force); } int CPhysicPhysX :: FLoadTree( char *szMapName ) { if( !szMapName || !*szMapName || !m_pPhysics ) return 0; if( m_fLoaded ) { if( !Q_stricmp( szMapName, m_szMapName )) { // stay on same map - no reload return 1; } if (m_pSceneActor) m_pSceneActor->release(); m_pSceneActor = NULL; if (m_pSceneMesh) m_pSceneMesh->release(); m_pSceneMesh = NULL; m_fLoaded = FALSE; // trying to load new collision tree } // save off mapname strcpy(m_szMapName, szMapName); char szHullFilename[MAX_PATH]; Q_snprintf( szHullFilename, sizeof( szHullFilename ), "cache/maps/%s.bin", szMapName ); UserStream cacheFileStream(szHullFilename, true); m_pSceneMesh = m_pPhysics->createTriangleMesh(cacheFileStream); m_fWorldChanged = FALSE; return (m_pSceneMesh != NULL) ? TRUE : FALSE; } int CPhysicPhysX :: CheckBINFile( char *szMapName ) { if( !szMapName || !*szMapName || !m_pPhysics ) return FALSE; char szBspFilename[MAX_PATH]; char szHullFilename[MAX_PATH]; Q_snprintf( szBspFilename, sizeof( szBspFilename ), "maps/%s.bsp", szMapName ); Q_snprintf( szHullFilename, sizeof( szHullFilename ), "cache/maps/%s.bin", szMapName ); BOOL retValue = TRUE; int iCompare; if ( COMPARE_FILE_TIME( szBspFilename, szHullFilename, &iCompare )) { if( iCompare > 0 ) { // BSP file is newer. ALERT ( at_console, ".BIN file will be updated\n\n" ); retValue = FALSE; } } else { retValue = FALSE; } return retValue; } void CPhysicPhysX::CacheNameForModel( model_t *model, fs::Path &hullfile, uint32_t hash, const char *suffix ) { if (!model->name || model->name[0] == '\0') return; std::stringstream stream; std::string pathStr = model->name; pathStr.erase(0, pathStr.find_first_of("/\\") + 1); fs::Path modelPath = pathStr; stream << std::nouppercase << std::setfill('0') << std::setw(8) << std::hex << hash; hullfile = "cache" / modelPath.parent_path() / (modelPath.stem().string() + "_" + stream.str() + suffix); } uint32_t CPhysicPhysX::GetHashForModelState( model_t *model, int32_t body, int32_t skin ) { uint32_t hash; CRC32_Init(&hash); CRC32_ProcessBuffer(&hash, &body, sizeof(body)); CRC32_ProcessBuffer(&hash, &skin, sizeof(skin)); CRC32_ProcessBuffer(&hash, &model->modelCRC, sizeof(model->modelCRC)); return CRC32_Final(hash); } //----------------------------------------------------------------------------- // hulls - convex hulls cooked with NxCookingConvexMesh routine and stored into cache\*.hull // meshes - triangle meshes cooked with NxCookingTriangleMesh routine and stored into cache\*.mesh //----------------------------------------------------------------------------- int CPhysicPhysX :: CheckFileTimes( const char *szFile1, const char *szFile2 ) { if( !szFile1 || !*szFile1 || !szFile2 || !*szFile2 ) return FALSE; BOOL retValue = TRUE; int iCompare; if ( COMPARE_FILE_TIME( (char *)szFile1, (char *)szFile2, &iCompare )) { if( iCompare > 0 ) { // MDL file is newer. retValue = FALSE; } } else { retValue = FALSE; } return retValue; } bool CPhysicPhysX::DebugEnabled() const { return g_engfuncs.CheckParm("-physxdebug", nullptr) != 0; } bool CPhysicPhysX::TracingStateChanges(PxActor *actor) const { if (DebugEnabled() && m_traceStateChanges) { return strcmp(actor->getName(), "func_physbox") == 0 || strcmp(actor->getName(), "env_physbox") == 0; } return false; } void CPhysicPhysX::HandleEvents() { auto &touchEventsQueue = m_eventHandler->getTouchEventsQueue(); while (!touchEventsQueue.empty()) { auto &touchEvent = touchEventsQueue.front(); edict_t *e1 = reinterpret_cast<edict_t*>(touchEvent.first->userData); edict_t *e2 = reinterpret_cast<edict_t*>(touchEvent.second->userData); DispatchTouch(e1, e2); touchEventsQueue.pop(); } auto &waterContactPairs = m_eventHandler->getWaterContactPairs(); for (const auto &pair : waterContactPairs) { edict_t *entity = reinterpret_cast<edict_t*>(pair.objectActor->userData); physx::PxRigidDynamic *dynamicActor = pair.objectActor->is<PxRigidDynamic>(); physx::PxRigidStatic *triggerActor = pair.waterTriggerActor->is<PxRigidStatic>(); if (!FBitSet(dynamicActor->getRigidBodyFlags(), PxRigidBodyFlag::eKINEMATIC)) { PxBounds3 objectBounds = dynamicActor->getWorldBounds(); PxBounds3 waterBounds = triggerActor->getWorldBounds(); PxBounds3 intersectionBounds = GetIntersectionBounds(objectBounds, waterBounds); if (!intersectionBounds.isEmpty()) { PxVec3 intersectionSizes = intersectionBounds.getDimensions(); float displacedVolume = intersectionSizes.x * intersectionSizes.y * intersectionSizes.z; PxVec3 byoyancyForce = displacedVolume * k_WaterDensity * -PxVec3(0.f, 0.f, -g_psv_gravity->value); dynamicActor->addForce(byoyancyForce); // in practice this velocity should be relative to water shape, since water can be moved PxVec3 velocityDir = dynamicActor->getLinearVelocity();// -triggerActor->getLinearVelocity(); float velocityMag = velocityDir.normalizeSafe(); PxVec3 linearDragForce = k_WaterLinearDragFactor * k_WaterDensity * velocityMag * velocityMag * -velocityDir; dynamicActor->addForce(linearDragForce); PxVec3 angularDragForce = k_WaterAngularDragFactor * displacedVolume * -dynamicActor->getAngularVelocity(); dynamicActor->addTorque(angularDragForce); } } } } //----------------------------------------------------------------------------- // assume m_pWorldModel is valid //----------------------------------------------------------------------------- int CPhysicPhysX :: ConvertEdgeToIndex( model_t *model, int edge ) { int e = model->surfedges[edge]; return (e > 0) ? model->edges[e].v[0] : model->edges[-e].v[1]; } int CPhysicPhysX :: BuildCollisionTree( char *szMapName ) { if( !m_pPhysics ) return FALSE; // get a world struct if(( m_pWorldModel = (model_t *)MODEL_HANDLE( 1 )) == NULL ) { ALERT( at_error, "BuildCollisionTree: unbale to fetch world pointer %s\n", szMapName ); return FALSE; } if (m_pSceneActor) m_pSceneActor->release(); m_pSceneActor = NULL; if (m_pSceneMesh) m_pSceneMesh->release(); m_pSceneMesh = NULL; // save off mapname Q_strcpy( m_szMapName, szMapName ); ALERT( at_console, "Tree Collision out of Date. Rebuilding...\n" ); // convert world from polygons to tri-list int i, numElems = 0, totalElems = 0; msurface_t *psurf; // compute vertexes count for( i = 0; i < m_pWorldModel->nummodelsurfaces; i++ ) { psurf = &m_pWorldModel->surfaces[m_pWorldModel->firstmodelsurface + i]; if( psurf->flags & ( SURF_DRAWTURB|SURF_DRAWSKY )) continue; totalElems += (psurf->numedges - 2); } PxU32 *indices = new PxU32[totalElems * 3]; for( i = 0; i < m_pWorldModel->nummodelsurfaces; i++ ) { psurf = &m_pWorldModel->surfaces[m_pWorldModel->firstmodelsurface + i]; int k = psurf->firstedge; // don't create collision for water if( psurf->flags & ( SURF_DRAWTURB|SURF_DRAWSKY )) continue; for( int j = 0; j < psurf->numedges - 2; j++ ) { indices[numElems*3+0] = ConvertEdgeToIndex( m_pWorldModel, k ); indices[numElems*3+1] = ConvertEdgeToIndex( m_pWorldModel, k + j + 2 ); indices[numElems*3+2] = ConvertEdgeToIndex( m_pWorldModel, k + j + 1 ); numElems++; } } PX_ASSERT( totalElems == numElems ); // build physical model PxTriangleMeshDesc levelDesc; levelDesc.points.count = m_pWorldModel->numvertexes; levelDesc.points.data = (const PxVec3*)&(m_pWorldModel->vertexes[0].position); levelDesc.points.stride = sizeof(mvertex_t); levelDesc.triangles.count = numElems; levelDesc.triangles.data = indices; levelDesc.triangles.stride = 3 * sizeof(PxU32); levelDesc.flags = (PxMeshFlags)0; char szHullFilename[MAX_PATH]; Q_snprintf( szHullFilename, sizeof( szHullFilename ), "cache/maps/%s.bin", szMapName ); if (m_pCooking) { UserStream outputFileStream(szHullFilename, false); bool status = m_pCooking->cookTriangleMesh(levelDesc, outputFileStream); } delete [] indices; UserStream inputFileStream(szHullFilename, true); m_pSceneMesh = m_pPhysics->createTriangleMesh(inputFileStream); m_fWorldChanged = TRUE; return (m_pSceneMesh != NULL) ? TRUE : FALSE; } void CPhysicPhysX::SetupWorld(void) { if (m_pSceneActor) return; // already loaded if (!m_pSceneMesh) { ALERT(at_error, "*collision tree not ready!\n"); return; } // get a world struct if ((m_pWorldModel = (model_t *)MODEL_HANDLE(1)) == NULL) { ALERT(at_error, "SetupWorld: unbale to fetch world pointer %s\n", m_szMapName); return; } PxRigidStatic *pActor = m_pPhysics->createRigidStatic(PxTransform(PxVec3(PxZero), PxQuat(PxIdentity))); PxShape *pShape = PxRigidActorExt::createExclusiveShape(*pActor, PxTriangleMeshGeometry(m_pSceneMesh), *m_pDefaultMaterial); pActor->setName(g_pWorld->GetClassname()); pActor->userData = g_pWorld->edict(); m_pScene->addActor(*pActor); m_pSceneActor = pActor; m_fLoaded = true; m_worldBounds = pActor->getWorldBounds(); } void CPhysicPhysX :: DebugDraw( void ) { if( !m_pPhysics || !m_pScene ) return; m_debugRenderer->RenderData(m_pScene->getRenderBuffer()); } /* =============== P_SpeedsMessage =============== */ bool CPhysicPhysX :: P_SpeedsMessage( char *out, size_t size ) { if( !p_speeds || p_speeds->value <= 0.0f ) return false; if( !out || !size ) return false; Q_strncpy( out, p_speeds_msg, size ); return true; } /* ================ SCR_RSpeeds ================ */ void CPhysicPhysX :: DrawPSpeeds( void ) { char msg[1024]; int iScrWidth = CVAR_GET_FLOAT( "width" ); if( P_SpeedsMessage( msg, sizeof( msg ))) { int x, y, height; char *p, *start, *end; x = iScrWidth - 320; y = 128; DrawConsoleStringLen( NULL, NULL, &height ); DrawSetTextColor( 1.0f, 1.0f, 1.0f ); p = start = msg; do { end = Q_strchr( p, '\n' ); if( end ) msg[end-start] = '\0'; DrawConsoleString( x, y, p ); y += height; if( end ) p = end + 1; else break; } while( 1 ); } } void CPhysicPhysX :: FreeAllBodies() { if( !m_pScene ) return; PxActorTypeFlags actorFlags = ( PxActorTypeFlag::eRIGID_STATIC | PxActorTypeFlag::eRIGID_DYNAMIC ); std::vector<PxActor*> actors; actors.assign(m_pScene->getNbActors(actorFlags), nullptr); m_pScene->getActors(actorFlags, actors.data(), actors.size() * sizeof(actors[0])); // throw all bodies for (PxActor *actor : actors) { CBaseEntity *entity = EntityFromActor( actor ); if (entity) { entity->m_pUserData = nullptr; } m_pScene->removeActor(*actor); actor->release(); } m_pSceneActor = NULL; } void CPhysicPhysX :: TeleportCharacter( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; PxRigidBody *pRigidBody = pActor->is<PxRigidBody>(); if (pRigidBody->getNbShapes() <= 0) return; PxShape *pShape; pRigidBody->getShapes(&pShape, sizeof(pShape)); // get only first shape, but it can be several Vector vecOffset = (pEntity->IsMonster()) ? Vector( 0, 0, pEntity->pev->maxs.z / 2.0f ) : g_vecZero; if (pShape->getGeometryType() == PxGeometryType::eBOX) { PxBoxGeometry &box = pShape->getGeometry().box(); PxTransform pose = pRigidBody->getGlobalPose(); box.halfExtents = pEntity->pev->size * k_PaddingFactor; pose.p = (pEntity->GetAbsOrigin() + vecOffset); pRigidBody->setGlobalPose(pose); } else { ALERT(at_error, "TeleportCharacter: shape geometry type is not a box\n"); } } void CPhysicPhysX :: TeleportActor( CBaseEntity *pEntity ) { PxActor *pActor = ActorFromEntity( pEntity ); if (!pActor) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: TeleportActor( entity = %x )\n", pEntity); } PxRigidBody *pRigidBody = pActor->is<PxRigidBody>(); matrix4x4 m(pEntity->GetAbsOrigin(), pEntity->GetAbsAngles(), 1.0f); PxTransform pose = PxTransform(PxMat44(m)); pRigidBody->setGlobalPose( pose ); } void CPhysicPhysX :: MoveCharacter( CBaseEntity *pEntity ) { if (!pEntity || pEntity->m_vecOldPosition == pEntity->pev->origin) return; PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) return; PxRigidDynamic *pRigidBody = pActor->is<PxRigidDynamic>(); if (pRigidBody->getNbShapes() <= 0) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: MoveCharacter( entity = %x, from = (%.2f, %.2f, %.2f), to = (%.2f, %.2f, %.2f) )\n", pEntity, pEntity->m_vecOldPosition.x, pEntity->m_vecOldPosition.y, pEntity->m_vecOldPosition.z, pEntity->pev->origin.x, pEntity->pev->origin.y, pEntity->pev->origin.z ); } PxShape *pShape; pRigidBody->getShapes(&pShape, sizeof(pShape)); // get only first shape, but it can be several if (pEntity->IsPlayer()) { // if we're in NOCLIP or FLY (ladder climbing) mode - disable collisions if (pEntity->pev->movetype != MOVETYPE_WALK) ToggleCollision(pRigidBody, false); else ToggleCollision(pRigidBody, true); } UpdateCharacterBounds(pEntity, pShape); Vector vecOffset = (pEntity->IsMonster()) ? Vector(0, 0, pEntity->pev->maxs.z / 2.0f) : g_vecZero; PxTransform pose = pRigidBody->getGlobalPose(); pose.p = (pEntity->GetAbsOrigin() + vecOffset); pRigidBody->setKinematicTarget(pose); pEntity->m_vecOldPosition = pEntity->GetAbsOrigin(); // update old position } void CPhysicPhysX::UpdateCharacterBounds(CBaseEntity *pEntity, PxShape *pShape) { if (pEntity->pev->size == pEntity->m_vecOldBounds) return; PxBoxGeometry box; box.halfExtents = pEntity->pev->size * k_PaddingFactor; pShape->setGeometry(box); pEntity->m_vecOldBounds = pEntity->pev->size; } void CPhysicPhysX :: MoveKinematic( CBaseEntity *pEntity ) { if( !pEntity || ( pEntity->pev->movetype != MOVETYPE_PUSH && pEntity->pev->movetype != MOVETYPE_PUSHSTEP )) return; // probably not a mover PxActor *pActor = ActorFromEntity( pEntity ); if( !pActor ) return; PxRigidDynamic *pRigidBody = pActor->is<PxRigidDynamic>(); if (pRigidBody->getNbShapes() <= 0) return; if( pEntity->pev->solid == SOLID_NOT || pEntity->pev->solid == SOLID_TRIGGER ) ToggleCollision(pRigidBody, false); else ToggleCollision(pRigidBody, true); PxTransform pose; matrix4x4 m( pEntity->GetAbsOrigin(), pEntity->GetAbsAngles( ), 1.0f ); // complex move for kinematic entities pose = PxTransform(PxMat44(m)); pRigidBody->setKinematicTarget( pose ); } void CPhysicPhysX :: EnableCollision( CBaseEntity *pEntity, int fEnable ) { PxActor *pActor = ActorFromEntity(pEntity); if (!pActor) return; PxRigidDynamic *pRigidBody = pActor->is<PxRigidDynamic>(); if (pRigidBody->getNbShapes() <= 0) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: EnableCollision( entity = %x, state = %s )\n", pEntity, fEnable ? "true" : "false"); } if (fEnable) { ToggleCollision(pRigidBody, true); pActor->setActorFlag(PxActorFlag::eVISUALIZATION, true); } else { ToggleCollision(pRigidBody, false); pActor->setActorFlag(PxActorFlag::eVISUALIZATION, false); } } void CPhysicPhysX :: MakeKinematic( CBaseEntity *pEntity, int fEnable ) { PxActor *pActor = ActorFromEntity( pEntity ); if (!pActor) return; PxRigidBody *pRigidBody = pActor->is<PxRigidBody>(); if (!pRigidBody || pRigidBody->getNbShapes() <= 0) return; if (TracingStateChanges(pActor)) { ALERT(at_console, "PhysX: MakeKinematic( entity = %x, state = %s )\n", pEntity, fEnable ? "true" : "false"); } if (fEnable) pRigidBody->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); else pRigidBody->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, false); } void CPhysicPhysX :: SweepTest( CBaseEntity *pTouch, const Vector &start, const Vector &mins, const Vector &maxs, const Vector &end, trace_t *tr ) { PxActor *pActor = ActorFromEntity( pTouch ); if (!pActor) { // bad actor? tr->allsolid = false; return; } PxRigidActor *pRigidActor = pActor->is<PxRigidActor>(); if (!pRigidActor || pRigidActor->getNbShapes() <= 0 || !CheckCollision(pRigidActor)) { // bad actor? tr->allsolid = false; return; } Vector trace_mins, trace_maxs; UTIL_MoveBounds(start, mins, maxs, end, trace_mins, trace_maxs); // NOTE: pmove code completely ignore a bounds checking. So we need to do it here if (!BoundsIntersect(trace_mins, trace_maxs, pTouch->pev->absmin, pTouch->pev->absmax)) { tr->allsolid = false; return; } DecomposedShape shape; model_t *mod = (model_t *)MODEL_HANDLE(pTouch->pev->modelindex); auto &meshDescFactory = CMeshDescFactory::Instance(); clipfile::GeometryType geomType = ShapeTypeToGeomType(shape.GetGeometryType(pRigidActor)); CMeshDesc &cookedMesh = meshDescFactory.CreateObject(pTouch->pev->modelindex, pTouch->pev->body, pTouch->pev->skin, geomType); if (!cookedMesh.GetMesh()) { const bool presentInCache = cookedMesh.PresentInCache(); if (!presentInCache) { // update cache or build from scratch Vector triangle[3]; if (!shape.Triangulate(pRigidActor)) { // failed to triangulate, unsupported mesh type, so skip them tr->allsolid = false; return; } cookedMesh.SetDebugName(pTouch->GetModel()); cookedMesh.InitMeshBuild(shape.GetTrianglesCount()); // FIXME: store all meshes as local and use capsule instead of bbox const auto &indexBuffer = shape.GetIndexBuffer(); const auto &vertexBuffer = shape.GetVertexBuffer(); for (size_t i = 0; i < shape.GetTrianglesCount(); i++) { uint32_t i0 = indexBuffer[3 * i]; uint32_t i1 = indexBuffer[3 * i + 1]; uint32_t i2 = indexBuffer[3 * i + 2]; vec3_t v0 = vertexBuffer[i0]; vec3_t v1 = vertexBuffer[i1]; vec3_t v2 = vertexBuffer[i2]; triangle[0] = v0; triangle[1] = v1; triangle[2] = v2; cookedMesh.AddMeshTrinagle(triangle); } } else { cookedMesh.LoadFromCacheFile(); } if (!cookedMesh.FinishMeshBuild()) { ALERT(at_error, "failed to build cooked mesh from %s\n", pTouch->GetModel()); tr->allsolid = false; return; } else { if (!presentInCache) { cookedMesh.SaveToCacheFile(); } cookedMesh.FreeMeshBuild(); } } mmesh_t *pMesh; areanode_t *pHeadNode; int32_t meshBody, meshSkin; if (mod->type == mod_studio && FBitSet(gpGlobals->trace_flags, FTRACE_MATERIAL_TRACE)) { CMeshDesc &originalMesh = meshDescFactory.CreateObject(pTouch->pev->modelindex, pTouch->pev->body, pTouch->pev->skin, clipfile::GeometryType::Original); if (!originalMesh.GetMesh()) { originalMesh.StudioConstructMesh(); if (!originalMesh.GetMesh()) { ALERT(at_error, "failed to build original mesh from %s\n", pTouch->GetModel()); } } meshBody = originalMesh.GetBody(); meshSkin = originalMesh.GetSkin(); pMesh = originalMesh.GetMesh(); pHeadNode = originalMesh.GetHeadNode(); } else { meshBody = cookedMesh.GetBody(); meshSkin = cookedMesh.GetSkin(); pMesh = cookedMesh.GetMesh(); pHeadNode = cookedMesh.GetHeadNode(); } TraceMesh trm; trm.SetTraceMesh(pMesh, pHeadNode, pTouch->pev->modelindex, meshBody, meshSkin); trm.SetMeshOrientation(pTouch->pev->origin, pTouch->pev->angles, pTouch->GetScale()); trm.SetupTrace(start, mins, maxs, end, tr); if (trm.DoTrace()) { if( tr->fraction < 1.0f || tr->startsolid ) tr->ent = pTouch->edict(); tr->materialHash = COM_GetMaterialHash(trm.GetLastHitSurface()); } } void CPhysicPhysX :: SweepEntity( CBaseEntity *pEntity, const Vector &start, const Vector &end, TraceResult *tr ) { // make trace default memset( tr, 0, sizeof( *tr )); tr->flFraction = 1.0f; tr->vecEndPos = end; PxActor *pActor = ActorFromEntity( pEntity ); if (!pActor) return; PxRigidActor *pRigidActor = pActor->is<PxRigidActor>(); if (!pRigidActor || pRigidActor->getNbShapes() <= 0 || pEntity->pev->solid == SOLID_NOT) return; // only dynamic solid objects can be traced // test for stuck entity into another if (start == end) { Vector triangle[3], dirs[3]; PxTransform globalPose = pRigidActor->getGlobalPose(); DecomposedShape shape; if (!shape.Triangulate(pRigidActor)) { return; // failed to triangulate } const auto &indexBuffer = shape.GetIndexBuffer(); const auto &vertexBuffer = shape.GetVertexBuffer(); for (size_t i = 0; i < shape.GetTrianglesCount(); i++) { uint32_t i0 = indexBuffer[3 * i]; uint32_t i1 = indexBuffer[3 * i + 1]; uint32_t i2 = indexBuffer[3 * i + 2]; vec3_t v0 = vertexBuffer[i0]; vec3_t v1 = vertexBuffer[i1]; vec3_t v2 = vertexBuffer[i2]; // transform triangles from local to world space triangle[0] = globalPose.transform(v0); triangle[1] = globalPose.transform(v1); triangle[2] = globalPose.transform(v2); for (size_t j = 0; j < 3; j++) { dirs[j] = globalPose.p - triangle[j]; triangle[j] += dirs[j] * -2.0f; UTIL_TraceLine(triangle[j], triangle[j], ignore_monsters, pEntity->edict(), tr); if (tr->fStartSolid) return; // one of points in solid } } return; } // compute motion Vector vecDir = end - start; float flLength = vecDir.Length(); vecDir = vecDir.Normalize(); // setup trace box PxBoxGeometry testBox; PxTransform initialPose = pRigidActor->getGlobalPose(); initialPose.p = pEntity->Center(); // does we really need to do this? testBox.halfExtents = pEntity->pev->size * k_PaddingFactor; // make a linear sweep through the world // we need to disable collision here to avoid touching same actor as we trying to sweep PxSweepBuffer sweepResult; bool hitOccured = m_pScene->sweep(testBox, initialPose, vecDir, flLength, sweepResult, PxHitFlag::eNORMAL); if (!hitOccured || sweepResult.getNbAnyHits() < 1) return; // no intersection const PxSweepHit &hit = sweepResult.getAnyHit(0); if (hit.distance > flLength || !hit.actor) return; // hit missed // compute fraction tr->flFraction = (hit.distance / flLength); tr->flFraction = bound( 0.0f, tr->flFraction, 1.0f ); VectorLerp( start, tr->flFraction, end, tr->vecEndPos ); CBaseEntity *pHit = EntityFromActor( hit.actor ); if (pHit) { tr->pHit = pHit->edict(); } tr->vecPlaneNormal = hit.normal; tr->flPlaneDist = DotProduct( tr->vecEndPos, tr->vecPlaneNormal ); float flDot = DotProduct( vecDir, tr->vecPlaneNormal ); float moveDot = Q_round( flDot, 0.1f ); // FIXME: this is incorrect. Find a better method? if(( tr->flFraction < 0.1f ) && ( moveDot < 0.0f )) tr->fAllSolid = true; } #endif // USE_PHYSICS_ENGINE
0
0.953048
1
0.953048
game-dev
MEDIA
0.683945
game-dev,graphics-rendering
0.85628
1
0.85628
RickMcConney/PenPlotter
8,476
Marlin/ArduinoAddons/Arduino_1.x.x/hardware/Melzi/cores/arduino/WString.h
/* WString.h - String library for Wiring & Arduino ...mostly rewritten by Paul Stoffregen... Copyright (c) 2009-10 Hernando Barragan. All right reserved. Copyright 2011, Paul Stoffregen, paul@pjrc.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef String_class_h #define String_class_h #ifdef __cplusplus #include <stdlib.h> #include <string.h> #include <ctype.h> #include <avr/pgmspace.h> // When compiling programs with this class, the following gcc parameters // dramatically increase performance and memory (RAM) efficiency, typically // with little or no increase in code size. // -felide-constructors // -std=c++0x class __FlashStringHelper; #define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal))) // An inherited class for holding the result of a concatenation. These // result objects are assumed to be writable by subsequent concatenations. class StringSumHelper; // The string class class String { // use a function pointer to allow for "if (s)" without the // complications of an operator bool(). for more information, see: // http://www.artima.com/cppsource/safebool.html typedef void (String::*StringIfHelperType)() const; void StringIfHelper() const {} public: // constructors // creates a copy of the initial value. // if the initial value is null or invalid, or if memory allocation // fails, the string will be marked as invalid (i.e. "if (s)" will // be false). String(const char *cstr = ""); String(const String &str); #ifdef __GXX_EXPERIMENTAL_CXX0X__ String(String &&rval); String(StringSumHelper &&rval); #endif explicit String(char c); explicit String(unsigned char, unsigned char base=10); explicit String(int, unsigned char base=10); explicit String(unsigned int, unsigned char base=10); explicit String(long, unsigned char base=10); explicit String(unsigned long, unsigned char base=10); ~String(void); // memory management // return true on success, false on failure (in which case, the string // is left unchanged). reserve(0), if successful, will validate an // invalid string (i.e., "if (s)" will be true afterwards) unsigned char reserve(unsigned int size); inline unsigned int length(void) const {return len;} // creates a copy of the assigned value. if the value is null or // invalid, or if the memory allocation fails, the string will be // marked as invalid ("if (s)" will be false). String & operator = (const String &rhs); String & operator = (const char *cstr); #ifdef __GXX_EXPERIMENTAL_CXX0X__ String & operator = (String &&rval); String & operator = (StringSumHelper &&rval); #endif // concatenate (works w/ built-in types) // returns true on success, false on failure (in which case, the string // is left unchanged). if the argument is null or invalid, the // concatenation is considered unsucessful. unsigned char concat(const String &str); unsigned char concat(const char *cstr); unsigned char concat(char c); unsigned char concat(unsigned char c); unsigned char concat(int num); unsigned char concat(unsigned int num); unsigned char concat(long num); unsigned char concat(unsigned long num); // if there's not enough memory for the concatenated value, the string // will be left unchanged (but this isn't signalled in any way) String & operator += (const String &rhs) {concat(rhs); return (*this);} String & operator += (const char *cstr) {concat(cstr); return (*this);} String & operator += (char c) {concat(c); return (*this);} String & operator += (unsigned char num) {concat(num); return (*this);} String & operator += (int num) {concat(num); return (*this);} String & operator += (unsigned int num) {concat(num); return (*this);} String & operator += (long num) {concat(num); return (*this);} String & operator += (unsigned long num) {concat(num); return (*this);} friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs); friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr); friend StringSumHelper & operator + (const StringSumHelper &lhs, char c); friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num); friend StringSumHelper & operator + (const StringSumHelper &lhs, int num); friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num); friend StringSumHelper & operator + (const StringSumHelper &lhs, long num); friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num); // comparison (only works w/ Strings and "strings") operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; } int compareTo(const String &s) const; unsigned char equals(const String &s) const; unsigned char equals(const char *cstr) const; unsigned char operator == (const String &rhs) const {return equals(rhs);} unsigned char operator == (const char *cstr) const {return equals(cstr);} unsigned char operator != (const String &rhs) const {return !equals(rhs);} unsigned char operator != (const char *cstr) const {return !equals(cstr);} unsigned char operator < (const String &rhs) const; unsigned char operator > (const String &rhs) const; unsigned char operator <= (const String &rhs) const; unsigned char operator >= (const String &rhs) const; unsigned char equalsIgnoreCase(const String &s) const; unsigned char startsWith( const String &prefix) const; unsigned char startsWith(const String &prefix, unsigned int offset) const; unsigned char endsWith(const String &suffix) const; // character acccess char charAt(unsigned int index) const; void setCharAt(unsigned int index, char c); char operator [] (unsigned int index) const; char& operator [] (unsigned int index); void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const; void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const {getBytes((unsigned char *)buf, bufsize, index);} // search int indexOf( char ch ) const; int indexOf( char ch, unsigned int fromIndex ) const; int indexOf( const String &str ) const; int indexOf( const String &str, unsigned int fromIndex ) const; int lastIndexOf( char ch ) const; int lastIndexOf( char ch, unsigned int fromIndex ) const; int lastIndexOf( const String &str ) const; int lastIndexOf( const String &str, unsigned int fromIndex ) const; String substring( unsigned int beginIndex ) const; String substring( unsigned int beginIndex, unsigned int endIndex ) const; // modification void replace(char find, char replace); void replace(const String& find, const String& replace); void toLowerCase(void); void toUpperCase(void); void trim(void); // parsing/conversion long toInt(void) const; protected: char *buffer; // the actual char array unsigned int capacity; // the array length minus one (for the '\0') unsigned int len; // the String length (not counting the '\0') unsigned char flags; // unused, for future features protected: void init(void); void invalidate(void); unsigned char changeBuffer(unsigned int maxStrLen); unsigned char concat(const char *cstr, unsigned int length); // copy and move String & copy(const char *cstr, unsigned int length); #ifdef __GXX_EXPERIMENTAL_CXX0X__ void move(String &rhs); #endif }; class StringSumHelper : public String { public: StringSumHelper(const String &s) : String(s) {} StringSumHelper(const char *p) : String(p) {} StringSumHelper(char c) : String(c) {} StringSumHelper(unsigned char num) : String(num) {} StringSumHelper(int num) : String(num) {} StringSumHelper(unsigned int num) : String(num) {} StringSumHelper(long num) : String(num) {} StringSumHelper(unsigned long num) : String(num) {} }; #endif // __cplusplus #endif // String_class_h
0
0.90033
1
0.90033
game-dev
MEDIA
0.222753
game-dev
0.707062
1
0.707062
Steamodded/smods
2,816
lovely/hand_limit.toml
[manifest] version = "1.0.0" dump_lua = true priority = -10 # Add starting params [[patches]] [patches.pattern] target = 'functions/misc_functions.lua' match_indent = true position = 'before' pattern = ''' consumable_slots = 2, ''' payload = ''' play_limit = 5, discard_limit = 5, no_limit = '', ''' # Reset visual indicators [[patches]] [patches.pattern] target = 'game.lua' match_indent = true position = 'after' pattern = ''' self.GAME = saveTable and saveTable.GAME or self:init_game_object() ''' payload = ''' SMODS.update_hand_limit_text(true, true) ''' # Change hand limit [[patches]] [patches.pattern] target = 'functions/button_callbacks.lua' match_indent = true position = 'at' pattern = ''' if #G.hand.highlighted <= 0 or G.GAME.blind.block_play or #G.hand.highlighted > 5 then ''' payload = ''' if #G.hand.highlighted <= 0 or G.GAME.blind.block_play or #G.hand.highlighted > math.max(G.GAME.starting_params.play_limit, 1) then ''' # Change discard limit [[patches]] [patches.pattern] target = 'functions/button_callbacks.lua' match_indent = true position = 'at' pattern = ''' if G.GAME.current_round.discards_left <= 0 or #G.hand.highlighted <= 0 then ''' payload = ''' if G.GAME.current_round.discards_left <= 0 or #G.hand.highlighted <= 0 or #G.hand.highlighted > math.max(G.GAME.starting_params.discard_limit, 0) then ''' # Add play limit indicator to UI [[patches]] [patches.pattern] target = 'functions/UI_definitions.lua' match_indent = true position = 'after' pattern = ''' {n=G.UIT.R, config={align = "bcm", padding = 0}, nodes={ {n=G.UIT.T, config={text = localize('b_play_hand'), scale = text_scale, colour = G.C.UI.TEXT_LIGHT, focus_args = {button = 'x', orientation = 'bm'}, func = 'set_button_pip'}} }}, ''' payload = ''' {n=G.UIT.R, config={align = "bcm", padding = 0}, nodes = { {n=G.UIT.T, config={ref_table = SMODS.hand_limit_strings, ref_value = 'play', scale = text_scale * 0.65, colour = G.C.UI.TEXT_LIGHT}} }}, ''' # Add discard limit indicator to UI [[patches]] [patches.pattern] target = 'functions/UI_definitions.lua' match_indent = true position = 'at' pattern = ''' {n=G.UIT.R, config={align = "cm", padding = 0}, nodes={ {n=G.UIT.T, config={text = localize('b_discard'), scale = text_scale, colour = G.C.UI.TEXT_LIGHT, focus_args = {button = 'y', orientation = 'bm'}, func = 'set_button_pip'}} }}''' payload = ''' {n=G.UIT.R, config={align = "cm", padding = 0}, nodes={ {n=G.UIT.T, config={text = localize('b_discard'), scale = text_scale, colour = G.C.UI.TEXT_LIGHT, focus_args = {button = 'y', orientation = 'bm'}, func = 'set_button_pip'}} }}, {n=G.UIT.R, config={align = "cm", padding = 0}, nodes={ {n=G.UIT.T, config={ref_table = SMODS.hand_limit_strings, ref_value = 'discard', scale = text_scale * 0.65, colour = G.C.UI.TEXT_LIGHT}} }}, '''
0
0.908053
1
0.908053
game-dev
MEDIA
0.722125
game-dev,testing-qa
0.827921
1
0.827921
Team-EnderIO/EnderIO
10,914
enderio/src/main/java/com/enderio/enderio/foundation/block/entity/PoweredMachineBlockEntity.java
package com.enderio.enderio.foundation.block.entity; import com.enderio.enderio.api.UseOnly; import com.enderio.enderio.api.capacitor.CapacitorData; import com.enderio.enderio.api.capacitor.CapacitorScalable; import com.enderio.enderio.api.io.energy.EnergyIOMode; import com.enderio.enderio.content.capacitors.CapacitorItem; import com.enderio.enderio.foundation.MachineNBTKeys; import com.enderio.enderio.foundation.block.entity.flags.CapacitorSupport; import com.enderio.enderio.foundation.energy.PoweredMachineEnergyStorage; import com.enderio.enderio.foundation.inventory.MachineInventory; import com.enderio.enderio.foundation.state.MachineState; import com.enderio.enderio.init.EIODataComponents; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.HolderLookup; import net.minecraft.core.component.DataComponentMap; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.IntTag; import net.minecraft.nbt.Tag; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.neoforged.fml.LogicalSide; import net.neoforged.neoforge.capabilities.Capabilities; import net.neoforged.neoforge.capabilities.ICapabilityProvider; import net.neoforged.neoforge.energy.IEnergyStorage; public abstract class PoweredMachineBlockEntity extends MachineBlockEntity implements MachineInstallable { public static final ICapabilityProvider<PoweredMachineBlockEntity, Direction, IEnergyStorage> ENERGY_STORAGE_PROVIDER = ( be, side) -> side == null ? be.energyStorage : be.energyStorage.getSided(side); private final CapacitorSupport capacitorSupport; private CapacitorData capacitorData = CapacitorData.NONE; private boolean isCapacitorDataDirty; private final EnergyIOMode energyIOMode; private final CapacitorScalable scalableEnergyCapacity; private final CapacitorScalable scalableMaxEnergyUse; private final PoweredMachineEnergyStorage energyStorage; public PoweredMachineBlockEntity(BlockEntityType<?> type, BlockPos worldPosition, BlockState blockState, boolean isIoConfigMutable, CapacitorSupport capacitorSupport, EnergyIOMode energyIOMode, CapacitorScalable scalableEnergyCapacity, CapacitorScalable scalableMaxEnergyUse) { super(type, worldPosition, blockState, isIoConfigMutable); this.capacitorSupport = capacitorSupport; this.energyIOMode = energyIOMode; this.scalableEnergyCapacity = scalableEnergyCapacity; this.scalableMaxEnergyUse = scalableMaxEnergyUse; // Sanity check for capacitors. if (supportsCapacitor() && (!hasInventory() || !getInventory().layout().supportsCapacitor())) { throw new IllegalStateException( "A machine which accepts a capacitor must have an inventory with a capacitor slot!"); } energyStorage = createEnergyStorage(); } // TODO: Temporary to support the primitive alloy smelter in its current form. @Deprecated(forRemoval = true, since = "7.1") protected PoweredMachineEnergyStorage createEnergyStorage() { return new PoweredMachineEnergyStorage(this); } @Override public void onLoad() { super.onLoad(); updatePowerState(); updateCapacitorState(); } @Override public void setLevel(Level level) { super.setLevel(level); updatePowerState(); updateCapacitorState(); } @Override public void setChanged() { super.setChanged(); updatePowerState(); } @Override protected void onInventoryContentsChanged(int slot) { super.onInventoryContentsChanged(slot); updateCapacitorData(); } // region Energy Storage public PoweredMachineEnergyStorage getEnergyStorage() { return energyStorage; } @UseOnly(LogicalSide.CLIENT) public final void clientSetEnergyStored(int energyStored) { energyStorage.setEnergyStored(energyStored); } public final boolean hasEnergy() { // If the machine has no capacitor, you cannot interact with it's energy storage if (requiresCapacitor() && !isCapacitorInstalled()) { return false; } return energyStorage.getEnergyStored() > 0; } public final int getMaxEnergyStored() { // TODO: Scalable might need redesigned to just scale directly... return scalableEnergyCapacity.scaleI(this::getCapacitorData).get(); } public final int getMaxEnergyUse() { return scalableMaxEnergyUse.scaleI(this::getCapacitorData).get(); } public final EnergyIOMode energyIOMode() { return energyIOMode; } private void updatePowerState() { updateMachineState(MachineState.NO_POWER, energyStorage.getEnergyStored() <= 0); } // region Distribution @Override protected int distributeResourcesInterval() { return energyIOMode.canOutput() ? 1 : super.distributeResourcesInterval(); } @Override protected void distributeResources(Direction side) { super.distributeResources(side); if (energyIOMode.canOutput() && getIOMode(side).canPush()) { distributeEnergy(side); } } private void distributeEnergy(Direction side) { // Get the other energy handler IEnergyStorage otherHandler = getNeighbouringCapability(Capabilities.EnergyStorage.BLOCK, side); if (otherHandler == null) { return; } // If the other handler can receive power transmit ours if (otherHandler.canReceive()) { int energyToReceive = energyStorage.extractEnergy(Integer.MAX_VALUE, true); int received = otherHandler.receiveEnergy(energyToReceive, false); energyStorage.extractEnergy(received, false); } } // endregion // endregion // region Capacitor public final CapacitorSupport capacitorSupport() { return capacitorSupport; } public final boolean supportsCapacitor() { return capacitorSupport != CapacitorSupport.NONE; } public final boolean requiresCapacitor() { return capacitorSupport == CapacitorSupport.REQUIRED; } public boolean isCapacitorInstalled() { if (!supportsCapacitor()) { // TODO: Should this be an exception because we do not support capacitors? return false; } if (level != null && level.isClientSide()) { return !getCapacitorItem().isEmpty(); } if (isCapacitorDataDirty) { updateCapacitorData(); } return !capacitorData.equals(CapacitorData.NONE); } @UseOnly(LogicalSide.SERVER) public CapacitorData getCapacitorData() { if (!supportsCapacitor()) { throw new IllegalStateException("Unable to get capacitor data, this machine does not support capacitors!"); } if (isCapacitorDataDirty) { updateCapacitorData(); } return capacitorData; } public final ItemStack getCapacitorItem() { MachineInventory inventory = getInventory(); if (inventory == null) { return ItemStack.EMPTY; } return inventory.getStackInSlot(inventory.layout().getCapacitorSlot()); } public final int getCapacitorSlotIndex() { if (!hasInventory()) { throw new IllegalStateException("Attempt to get capacitor slot for machine with no inventory!"); } var layout = getInventory().layout(); if (!layout.supportsCapacitor()) { throw new IllegalStateException("Unable to get capacitor slot index, inventory has no capacitor slot."); } return layout.getCapacitorSlot(); } protected void updateCapacitorData() { isCapacitorDataDirty = false; if (supportsCapacitor()) { capacitorData = getCapacitorItem().getOrDefault(EIODataComponents.CAPACITOR_DATA, CapacitorData.NONE); updateCapacitorState(); } } private void updateCapacitorState() { updateMachineState(MachineState.NO_CAPACITOR, supportsCapacitor() && !isCapacitorInstalled()); } // region MachineInstallable Implementation @Override public InteractionResult tryItemInstall(ItemStack stack, UseOnContext context) { if (stack.getItem() instanceof CapacitorItem && supportsCapacitor() && !isCapacitorInstalled()) { MachineInventory inventory = getInventory(); if (inventory != null) { inventory.setStackInSlot(inventory.layout().getCapacitorSlot(), stack.copyWithCount(1)); stack.shrink(1); return InteractionResult.sidedSuccess(context.getLevel().isClientSide()); } } return InteractionResult.PASS; } // endregion // endregion // region Serialization @Override protected void saveAdditional(CompoundTag tag, HolderLookup.Provider registries) { super.saveAdditional(tag, registries); tag.put(MachineNBTKeys.ENERGY_STORED, energyStorage.serializeNBT(registries)); } @Override protected void loadAdditional(CompoundTag tag, HolderLookup.Provider registries) { super.loadAdditional(tag, registries); if (tag.contains(MachineNBTKeys.ENERGY_STORED, Tag.TAG_INT)) { energyStorage.deserializeNBT(registries, (IntTag) tag.get(MachineNBTKeys.ENERGY_STORED)); } else if (tag.contains(MachineNBTKeys.ENERGY, Tag.TAG_COMPOUND)) { // SUPPORT LEGACY STORAGE FORMAT CompoundTag energyTag = tag.getCompound(MachineNBTKeys.ENERGY); if (energyTag.contains(MachineNBTKeys.ENERGY_STORED)) { energyStorage.setEnergyStored(energyTag.getInt(MachineNBTKeys.ENERGY_STORED)); } } updateCapacitorData(); } @Override protected void applyImplicitComponents(DataComponentInput componentInput) { super.applyImplicitComponents(componentInput); energyStorage.setEnergyStored(componentInput.getOrDefault(EIODataComponents.ENERGY, 0)); } @Override protected void collectImplicitComponents(DataComponentMap.Builder components) { super.collectImplicitComponents(components); components.set(EIODataComponents.ENERGY, energyStorage.getEnergyStored()); } @Override public void removeComponentsFromTag(CompoundTag tag) { super.removeComponentsFromTag(tag); tag.remove(MachineNBTKeys.ENERGY_STORED); } // endregion }
0
0.914878
1
0.914878
game-dev
MEDIA
0.865376
game-dev
0.930692
1
0.930692
BG-Software-LLC/SuperiorSkyblock2
1,131
src/main/java/com/bgsoftware/superiorskyblock/config/section/IslandNamesSection.java
package com.bgsoftware.superiorskyblock.config.section; import com.bgsoftware.superiorskyblock.api.config.SettingsManager; import com.bgsoftware.superiorskyblock.config.SettingsContainerHolder; import java.util.List; public class IslandNamesSection extends SettingsContainerHolder implements SettingsManager.IslandNames { @Override public boolean isRequiredForCreation() { return getContainer().islandNamesRequiredForCreation; } @Override public int getMaxLength() { return getContainer().islandNamesMaxLength; } @Override public int getMinLength() { return getContainer().islandNamesMinLength; } @Override public List<String> getFilteredNames() { return getContainer().filteredIslandNames; } @Override public boolean isColorSupport() { return getContainer().islandNamesColorSupport; } @Override public boolean isIslandTop() { return getContainer().islandNamesIslandTop; } @Override public boolean isPreventPlayerNames() { return getContainer().islandNamesPreventPlayerNames; } }
0
0.887148
1
0.887148
game-dev
MEDIA
0.410667
game-dev
0.843477
1
0.843477
soopercool101/BrawlCrate
5,806
BrawlLib/SSBB/ResourceNodes/Archives/MRGNode.cs
using BrawlLib.Internal; using BrawlLib.SSBB.Types; using System; using System.IO; namespace BrawlLib.SSBB.ResourceNodes { public unsafe class MRGNode : ResourceNode { internal MRGHeader* Header => (MRGHeader*) WorkingUncompressed.Address; public override ResourceType ResourceFileType => ResourceType.MRG; public override void OnPopulate() { uint numFiles = 0; MRGFileHeader* entry = Header->First; for (int i = 0; i < (numFiles = Header->_numFiles); i++, entry = entry->Next) { if (NodeFactory.FromAddress(this, Header + entry->Data, entry->Length) == null) { new ARCEntryNode().Initialize(this, Header + entry->Data, entry->Length); } } } public override void Initialize(ResourceNode parent, DataSource origSource, DataSource uncompSource) { base.Initialize(parent, origSource, uncompSource); } public override bool OnInitialize() { base.OnInitialize(); _name = Path.GetFileNameWithoutExtension(_origPath); return Header->_numFiles > 0; } public void ExtractToFolder(string outFolder) { if (!Directory.Exists(outFolder)) { Directory.CreateDirectory(outFolder); } foreach (ARCEntryNode entry in Children) { if (entry is ARCNode) { ((ARCNode) entry).ExtractToFolder(Path.Combine(outFolder, entry.Name)); } else { (entry as BRRESNode)?.ExportToFolder(outFolder); } } } public void ReplaceFromFolder(string inFolder) { DirectoryInfo dir = new DirectoryInfo(inFolder); FileInfo[] files; DirectoryInfo[] dirs; foreach (ARCEntryNode entry in Children) { if (entry is ARCNode) { dirs = dir.GetDirectories(entry.Name); if (dirs.Length > 0) { ((ARCNode) entry).ReplaceFromFolder(dirs[0].FullName); continue; } } else { (entry as BRRESNode)?.ReplaceFromFolder(inFolder); } //Find file name for entry files = dir.GetFiles(entry.Name + ".*"); if (files.Length > 0) { entry.Replace(files[0].FullName); continue; } } } private int offset; public override int OnCalculateSize(bool force) { int size = offset = 0x20 + Children.Count * 0x20; foreach (ResourceNode node in Children) { size += node.CalculateSize(force); } return size; } public override void OnRebuild(VoidPtr address, int size, bool force) { MRGHeader* header = (MRGHeader*) address; *header = new MRGHeader((uint) Children.Count); MRGFileHeader* entry = header->First; foreach (ARCEntryNode node in Children) { *entry = new MRGFileHeader(node._calcSize, offset); node.Rebuild(header + entry->Data, node._calcSize, force); offset += node._calcSize; entry = entry->Next; } } public void ExportAsARC(string path) { ARCNode node = new ARCNode { _children = _children, Name = _name }; node.Export(path); } public override void Export(string outPath) { if (outPath.EndsWith(".pac", StringComparison.OrdinalIgnoreCase) || outPath.EndsWith(".pcs", StringComparison.OrdinalIgnoreCase) || outPath.EndsWith(".pair", StringComparison.OrdinalIgnoreCase)) { ExportAsARC(outPath); } else { base.Export(outPath); } } //internal static ResourceNode TryParse(DataSource source, ResourceNode parent) //{ // buint* addr = (buint*)source.Address; // //if (addr[0] >= source.Length) // // return null; // for (int i = 0; i < 7; i++) // if (addr[i + 1] != 0) // return null; // uint headerSize = 0x20 + 0x20 * addr[0]; // //if (headerSize >= source.Length) // // return null; // uint prevOff = headerSize; // uint prevSize = 0; // //if (prevSize >= source.Length) // // return null; // uint count = addr[0]; // for (int i = 0; i < 2; i++) // { // int file = i * 8 + 8; // uint c = addr[file]; // uint l = (prevOff + prevSize) + (uint)(i == 0 ? 0 : 0x20); // if (/*c >= source.Length || */c != l) // return null; // prevOff = addr[file]; // prevSize = addr[file + 1]; // for (int x = 0; x < 6; x++) // if (addr[x + 2] != 0) // return null; // //if (i == count - 1) // // if (prevOff + prevSize != source.Length) // // return null; // } // return new MRGNode(); //} } }
0
0.921575
1
0.921575
game-dev
MEDIA
0.429822
game-dev,cli-devtools
0.986202
1
0.986202
holycake/mhsj
4,981
std/char/npcs.c
// npc.c #include <command.h> #define MAX_OPPENENT 4 inherit CHARACTER; inherit F_CLEAN_UP; object carry_object(string file) { object ob; if( file->query_unique() ) { if(clonep()) { // only the cloned copy can have unique item. if( !objectp(ob = new(file->clone_file())) ) return 0; } else { // master copy can't have the unique item. // mon 4/5/98 if(!file->query("replace_file") || !objectp(ob = new(file->query("replace_file")))) return 0; } } else if( !objectp(ob = new(file)) ) return 0; ob->move(this_object()); return ob; } object add_money(string type, int amount) { object ob; ob = carry_object("/obj/money/" + type); if( !ob ) return 0; ob->set_amount(amount); } int accept_fight(object who) { string att; att = query("attitude"); if( is_fighting() ) switch(att) { case "heroism": command("say 哼!出招吧!\n"); break; default: command("say 想倚多为胜,这不是欺人太甚吗!\n"); return 0; } if( (int)query("gin") * 100 / (int)query("max_gin") >= 90 && (int)query("kee") * 100 / (int)query("max_kee") >= 90 && (int)query("sen") * 100 / (int)query("max_sen") >= 90 ) { switch(att) { case "friendly": command("say " + RANK_D->query_self(this_object()) + "怎么可能是" + RANK_D->query_respect(who) + "的对手?\n"); return 0; case "aggressive": case "killer": command("say 哼!出招吧!\n"); break; default: if( !is_fighting() ) command("say 既然" + RANK_D->query_respect(who) + "赐教," + RANK_D->query_self(this_object()) + "只好奉陪。\n"); } return 1; } else return 0; } // This function is called by the reset() of the room that creates this // npc. When this function is called, it means the room demand the npc // to return its startroom. int return_home(object home) { object* enemy_list; int i, flag=0; // Are we at home already? if( !environment() || environment()==home ) return 1; // Are we able to leave? if( !living(this_object()) || this_object()->query_temp("no_return") ) return 0; //added by mon. 7/17/97 // modified by tool if( is_fighting() ) { enemy_list = query_enemy(); for(i=0; i<sizeof(enemy_list); ++i) { if(!enemy_list[i]) continue; if( sizeof(enemy_list[i]->query_enemy()) > MAX_OPPENENT ) { message("vision", "\n"+this_object()->name() + "纵身向后一跃,拱手道:阁下武艺不凡,佩服,佩服!咱们后会有期!\n\n", environment(), this_object()); enemy_list[i]->remove_killer( this_object() ); remove_enemy( enemy_list[i] ); flag = 1; break; } } if( !flag ) return 0; } // Leave for home now. message("vision", this_object()->name() + "急急忙忙地离开了。\n", environment(), this_object()); return move(home); } // This is the chat function dispatcher. If you use function type chat // message, you can either define your own functions or use the default // ones. int chat() { string *msg; int chance, rnd; if( !environment() ) return 0; if( !chance = (int)query(is_fighting()? "chat_chance_combat": "chat_chance") ) return 0; if( arrayp(msg = query(is_fighting()? "chat_msg_combat": "chat_msg"))) { if( random(100) < chance ) { rnd = random(sizeof(msg)); if( stringp(msg[rnd]) ) say(msg[rnd]); else if( functionp(msg[rnd]) ) return evaluate(msg[rnd]); } return 1; } } // Default chat function: Let the npc random move to another room. int random_move() { mapping exits; string *dirs; int size; //added by mon 8/31/97 if( !mapp(exits = environment()->query("exits")) ) return 0; dirs = keys(exits); size=sizeof(dirs); if(size>0) return command("go " + dirs[random(size)]); else return 0; } // Default chat function: Let the npc cast his/her enabled spells void cast_spell(string spell) { string spell_skill; if( stringp(spell_skill = query_skill_mapped("spells"))) SKILL_D(spell_skill)->cast_spell(this_object(), spell); } // Default chat function: Let the npc exert his/her enabled force int exert_function(string func) { string force_skill; if( stringp(force_skill = query_skill_mapped("force"))) SKILL_D(force_skill)->exert_function(this_object(), func); } // Default chat function: Let the npc perform special action with // his/her enabled martial art int perform_action(string skill, string action) { object weapon=this_object()->query_temp("weapon"); string weapon_skill,martial_skill; if (!weapon) weapon_skill="unarmed"; else { if (weapon->query("use_apply_skill")) weapon_skill=weapon->query("apply/skill_type"); else weapon_skill=weapon->query("skill_type"); } martial_skill = query_skill_mapped(skill); // tell_room(environment(),weapon_skill+" "+skill+"\n"); // if( stringp(martial_skill) ) // weapon checking is added here. if( stringp(martial_skill) && skill==weapon_skill) return SKILL_D(martial_skill)->perform_action(this_object(), action); }
0
0.948814
1
0.948814
game-dev
MEDIA
0.98004
game-dev
0.939318
1
0.939318
opentibiabr/otservbr-global-archived
11,827
data/npc/scripts/gnomilly.lua
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local talkState = {} local levels = {25, 49} function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if msgcontains(msg, 'job') then return npcHandler:say('I\'m the officer responsible for this area. I give out missions, accept mission reports and oversee our defences.', cid) end if msgcontains(msg, 'gnome') then return npcHandler:say('We are the only protectors of the world against the enemies below. With small stature comes great responsibilities, as they say.', cid) end if msgcontains(msg, 'area') then return npcHandler:say({ "On these levels we found evidence of some monumental battle that has taken place here centuries ago. We also found some grave sites, but oddly enough no clues of any form of settlement. ...", "Some evidence we have found suggests that at least one of the battles here was fought for many, many years. People came here, lived here, fought here and died here. ...", "The battles continued until someone or something literally ploughed through the battlefields, turning everything upside down. All this killing and death soaked the area with negative energy. ...", "Necromantic forces are running wild all over the place and we are hard-pressed to drive all these undead, spirits and ghosts, away from the Spike. ...", "Unless we can secure that area somehow, the Spike operation is threatened to become crippled by the constant attacks of the undead. ...", "The whole growing downwards could come to a halt, leaving us exposed to even more attacks, counter attacks, and giving the enemy time to prepare their defences. There's a lot to do for aspiring adventurers." }, cid) end if msgcontains(msg, 'mission') then if player:getLevel() > levels[2] then npcHandler:say('Sorry, but no! Your expertise could be put to better use elsewhere. Here awaits you no challenge. You are desperately needed in the deeper levels of the Spike. Report there immediately. ', cid) else npcHandler:say('I can offer you several missions: to recharge our ghost {pacifiers}, to {release} the spiritual anger, to {track} an evil presence and to {kill} some demon skeletons.', cid) end return end if msgcontains(msg, 'report') then talkState[cid] = 'report' return npcHandler:say('What mission do you want to report about: recharging the ghost {pacifiers}, the {release} of the spiritual anger, about {tracking} an evil presence and the {killing} of demon skeletons?', cid) end if talkState[cid] == 'report' then if msgcontains(msg, 'pacifiers') then if player:getStorageValue(SPIKE_UPPER_PACIFIER_MAIN) == -1 then npcHandler:say('You have not started that mission.', cid) elseif player:getStorageValue(SPIKE_UPPER_PACIFIER_MAIN) == 7 then npcHandler:say('You have done well. Here, take your reward.', cid) player:addFamePoint() player:addExperience(1000, true) player:setStorageValue(SPIKE_UPPER_PACIFIER_MAIN, -1) player:setStorageValue(SPIKE_UPPER_PACIFIER_DAILY, 86400) else npcHandler:say('Gnowful! Take the resonance charger and use it on seven of the pacifiers in the cave.', cid) end elseif msgcontains(msg, 'release') then if player:getStorageValue(SPIKE_UPPER_MOUND_MAIN) == -1 then npcHandler:say('You have not started that mission.', cid) elseif player:getStorageValue(SPIKE_UPPER_MOUND_MAIN) == 4 then npcHandler:say('You have done well. Here, take your reward.', cid) player:addFamePoint() player:addExperience(1000, true) player:setStorageValue(SPIKE_UPPER_MOUND_MAIN, -1) player:setStorageValue(SPIKE_UPPER_MOUND_DAILY, 86400) else npcHandler:say('Gnowful! Take the spirit shovel use it on four graves in the cave system.', cid) end elseif msgcontains(msg, 'tracking') then if player:getStorageValue(SPIKE_UPPER_TRACK_MAIN) == -1 then npcHandler:say('You have not started that mission.', cid) elseif player:getStorageValue(SPIKE_UPPER_TRACK_MAIN) == 3 then npcHandler:say('You have done well. Here, take your reward.', cid) player:addFamePoint() player:addExperience(1000, true) player:setStorageValue(SPIKE_UPPER_TRACK_MAIN, -1) player:setStorageValue(SPIKE_UPPER_TRACK_DAILY, 86400) else npcHandler:say('Gnowful! Take the tracking device in the caves and locate the residual spirit energy.', cid) end elseif msgcontains(msg, 'killing') then if player:getStorageValue(SPIKE_UPPER_KILL_MAIN) == -1 then npcHandler:say('You have not started that mission.', cid) elseif player:getStorageValue(SPIKE_UPPER_KILL_MAIN) == 7 then npcHandler:say('You have done well. Here, take your reward.', cid) player:addFamePoint() player:addExperience(1000, true) player:setStorageValue(SPIKE_UPPER_KILL_MAIN, -1) player:setStorageValue(SPIKE_UPPER_KILL_DAILY, 86400) else npcHandler:say('Gnowful! Just go out to the caves and kill at least seven demon skeletons.', cid) end else npcHandler:say('That\'s not a valid mission name.', cid) end talkState[cid] = nil return end --[[/////////////////// ////GHOST PACIFIERS//// /////////////////////]] if msgcontains(msg, 'pacifiers') then if player:getStorageValue(SPIKE_UPPER_PACIFIER_DAILY) >= os.time() then return npcHandler:say('Sorry, you have to wait ' .. string.diff(player:getStorageValue(SPIKE_UPPER_PACIFIER_DAILY)-os.time()) .. ' before this task gets available again.', cid) end if (player:getLevel() < levels[1]) or (player:getLevel() > levels[2]) then return npcHandler:say('Sorry, you are not on the required range of levels [' .. levels[1] ..'-' .. levels[2] ..'].', cid) end if player:getStorageValue(SPIKE_UPPER_PACIFIER_MAIN) == -1 then npcHandler:say({'We need you to recharge our ghost pacifiers. They are placed at several strategic points in the caves around us and should be easy to find. Your mission would be to charge seven of them.', 'If you are interested, I can give you some more {information} about it. Are you willing to accept this mission?'}, cid) talkState[cid] = 'pacifiers' else npcHandler:say('You have already started that mission.', cid) end end if talkState[cid] == 'pacifiers' then if msgcontains(msg, 'yes') then player:addItem(21554, 1) player:setStorageValue(SPIKE_UPPER_PACIFIER_MAIN, 0) npcHandler:say('Gnometastic! Take this resonance charger and use it on seven of the pacifiers in the cave. If you lose the charger, you\'ll have to bring your own. Gnomux sells all the equipment that is required for our missions.', cid) talkState[cid] = nil elseif msgcontains(msg, 'no') then npcHandler:say('Ok then.', cid) talkState[cid] = nil end end --[[/////////////////// ////SPIRIT RELEASE///// /////////////////////]] if msgcontains(msg, 'release') then if player:getStorageValue(SPIKE_UPPER_MOUND_DAILY) >= os.time() then return npcHandler:say('Sorry, you have to wait ' .. string.diff(player:getStorageValue(SPIKE_UPPER_MOUND_DAILY)-os.time()) .. ' before this task gets available again.', cid) end if (player:getLevel() < levels[1]) or (player:getLevel() > levels[2]) then return npcHandler:say('Sorry, you are not on the required range of levels [' .. levels[1] ..'-' .. levels[2] ..'].', cid) end if player:getStorageValue(SPIKE_UPPER_MOUND_MAIN) == -1 then npcHandler:say('Your task would be to use a spirit shovel to release some spirit\'s anger from graves that can be found all around here. If you are interested, I can give you some more information about it. Are you willing to accept this mission?', cid) talkState[cid] = 'release' else npcHandler:say('You have already started that mission.', cid) end end if talkState[cid] == 'release' then if msgcontains(msg, 'yes') then player:addItem(21553, 1) player:setStorageValue(SPIKE_UPPER_MOUND_MAIN, 0) npcHandler:say('Gnometastic! Take this spirit shovel and use it on four graves in the cave system. If you lose the shovel you\'ll have to bring your own. Gnomux sells all the equipment that is required for our missions.', cid) talkState[cid] = nil elseif msgcontains(msg, 'no') then npcHandler:say('Ok then.', cid) talkState[cid] = nil end end --[[///////////////// ////TRACK GHOSTS///// ///////////////////]] if msgcontains(msg, 'track') then if player:getStorageValue(SPIKE_UPPER_TRACK_DAILY) >= os.time() then return npcHandler:say('Sorry, you have to wait ' .. string.diff(player:getStorageValue(SPIKE_UPPER_TRACK_DAILY)-os.time()) .. ' before this task gets available again.', cid) end if (player:getLevel() < levels[1]) or (player:getLevel() > levels[2]) then return npcHandler:say('Sorry, you are not on the required range of levels [' .. levels[1] ..'-' .. levels[2] ..'].', cid) end if player:getStorageValue(SPIKE_UPPER_TRACK_MAIN) == -1 then npcHandler:say({'You\'d be given the highly important task to track down an enormously malevolent spiritual presence in the cave system. Use your tracking device to find out how close you are to the presence.','Use that information to find the residual energy and use the tracker there. If you are interested, I can give you some more information about it. Are you willing to accept this mission?'}, cid) talkState[cid] = 'track' else npcHandler:say('You have already started that mission.', cid) end end if talkState[cid] == 'track' then if msgcontains(msg, 'yes') then GHOST_DETECTOR_MAP[player:getGuid()] = Position.getFreeSand() player:addItem(21555, 1) player:setStorageValue(SPIKE_UPPER_TRACK_MAIN, 0) npcHandler:say('Gnometastic! Use this tracking device in the caves and locate the residual spirit energy. If you lose the tracking device, you\'ll have to bring your own. Gnomux sells all the equipment that is required for our missions.', cid) talkState[cid] = nil elseif msgcontains(msg, 'no') then npcHandler:say('Ok then.', cid) talkState[cid] = nil end end --[[///////// ////KILL///// ///////////]] if msgcontains(msg, 'kill') then if player:getStorageValue(SPIKE_UPPER_KILL_DAILY) >= os.time() then return npcHandler:say('Sorry, you have to wait ' .. string.diff(player:getStorageValue(SPIKE_UPPER_KILL_DAILY)-os.time()) .. ' before this task gets available again.', cid) end if (player:getLevel() < levels[1]) or (player:getLevel() > levels[2]) then return npcHandler:say('Sorry, you are not on the required range of levels [' .. levels[1] ..'-' .. levels[2] ..'].', cid) end if player:getStorageValue(SPIKE_UPPER_KILL_MAIN) == -1 then npcHandler:say('We need someone to reduce the steadily growing number of demon skeletons in the caves. If you are interested, I can give you some more information about it. Are you willing to accept this mission?', cid) talkState[cid] = 'kill' else npcHandler:say('You have already started that mission.', cid) end end if talkState[cid] == 'kill' then if msgcontains(msg, 'yes') then player:setStorageValue(SPIKE_UPPER_KILL_MAIN, 0) npcHandler:say('Gnometastic! Just go out and kill them. You should find more of them than you like.', cid) talkState[cid] = nil elseif msgcontains(msg, 'no') then npcHandler:say('Ok then.', cid) talkState[cid] = nil end end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
0
0.979891
1
0.979891
game-dev
MEDIA
0.99133
game-dev
0.994205
1
0.994205
acidicoala/SmokeAPI
31,082
res/steamworks/152/headers/steam/isteamremotestorage.h
//====== Copyright � 1996-2008, Valve Corporation, All rights reserved. ======= // // Purpose: public interface to user remote file storage in Steam // //============================================================================= #ifndef ISTEAMREMOTESTORAGE_H #define ISTEAMREMOTESTORAGE_H #ifdef _WIN32 #pragma once #endif #include "steam_api_common.h" //----------------------------------------------------------------------------- // Purpose: Defines the largest allowed file size. Cloud files cannot be written // in a single chunk over 100MB (and cannot be over 200MB total.) //----------------------------------------------------------------------------- const uint32 k_unMaxCloudFileChunkSize = 100 * 1024 * 1024; //----------------------------------------------------------------------------- // Purpose: Structure that contains an array of const char * strings and the number of those strings //----------------------------------------------------------------------------- #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx #endif struct SteamParamStringArray_t { const char ** m_ppStrings; int32 m_nNumStrings; }; #pragma pack( pop ) // A handle to a piece of user generated content typedef uint64 UGCHandle_t; typedef uint64 PublishedFileUpdateHandle_t; typedef uint64 PublishedFileId_t; const PublishedFileId_t k_PublishedFileIdInvalid = 0; const UGCHandle_t k_UGCHandleInvalid = 0xffffffffffffffffull; const PublishedFileUpdateHandle_t k_PublishedFileUpdateHandleInvalid = 0xffffffffffffffffull; // Handle for writing to Steam Cloud typedef uint64 UGCFileWriteStreamHandle_t; const UGCFileWriteStreamHandle_t k_UGCFileStreamHandleInvalid = 0xffffffffffffffffull; const uint32 k_cchPublishedDocumentTitleMax = 128 + 1; const uint32 k_cchPublishedDocumentDescriptionMax = 8000; const uint32 k_cchPublishedDocumentChangeDescriptionMax = 8000; const uint32 k_unEnumeratePublishedFilesMaxResults = 50; const uint32 k_cchTagListMax = 1024 + 1; const uint32 k_cchFilenameMax = 260; const uint32 k_cchPublishedFileURLMax = 256; enum ERemoteStoragePlatform { k_ERemoteStoragePlatformNone = 0, k_ERemoteStoragePlatformWindows = (1 << 0), k_ERemoteStoragePlatformOSX = (1 << 1), k_ERemoteStoragePlatformPS3 = (1 << 2), k_ERemoteStoragePlatformLinux = (1 << 3), k_ERemoteStoragePlatformSwitch = (1 << 4), k_ERemoteStoragePlatformAndroid = (1 << 5), k_ERemoteStoragePlatformIOS = (1 << 6), // NB we get one more before we need to widen some things k_ERemoteStoragePlatformAll = 0xffffffff }; enum ERemoteStoragePublishedFileVisibility { k_ERemoteStoragePublishedFileVisibilityPublic = 0, k_ERemoteStoragePublishedFileVisibilityFriendsOnly = 1, k_ERemoteStoragePublishedFileVisibilityPrivate = 2, k_ERemoteStoragePublishedFileVisibilityUnlisted = 3, }; enum EWorkshopFileType { k_EWorkshopFileTypeFirst = 0, k_EWorkshopFileTypeCommunity = 0, // normal Workshop item that can be subscribed to k_EWorkshopFileTypeMicrotransaction = 1, // Workshop item that is meant to be voted on for the purpose of selling in-game k_EWorkshopFileTypeCollection = 2, // a collection of Workshop or Greenlight items k_EWorkshopFileTypeArt = 3, // artwork k_EWorkshopFileTypeVideo = 4, // external video k_EWorkshopFileTypeScreenshot = 5, // screenshot k_EWorkshopFileTypeGame = 6, // Greenlight game entry k_EWorkshopFileTypeSoftware = 7, // Greenlight software entry k_EWorkshopFileTypeConcept = 8, // Greenlight concept k_EWorkshopFileTypeWebGuide = 9, // Steam web guide k_EWorkshopFileTypeIntegratedGuide = 10, // application integrated guide k_EWorkshopFileTypeMerch = 11, // Workshop merchandise meant to be voted on for the purpose of being sold k_EWorkshopFileTypeControllerBinding = 12, // Steam Controller bindings k_EWorkshopFileTypeSteamworksAccessInvite = 13, // internal k_EWorkshopFileTypeSteamVideo = 14, // Steam video k_EWorkshopFileTypeGameManagedItem = 15, // managed completely by the game, not the user, and not shown on the web // Update k_EWorkshopFileTypeMax if you add values. k_EWorkshopFileTypeMax = 16 }; enum EWorkshopVote { k_EWorkshopVoteUnvoted = 0, k_EWorkshopVoteFor = 1, k_EWorkshopVoteAgainst = 2, k_EWorkshopVoteLater = 3, }; enum EWorkshopFileAction { k_EWorkshopFileActionPlayed = 0, k_EWorkshopFileActionCompleted = 1, }; enum EWorkshopEnumerationType { k_EWorkshopEnumerationTypeRankedByVote = 0, k_EWorkshopEnumerationTypeRecent = 1, k_EWorkshopEnumerationTypeTrending = 2, k_EWorkshopEnumerationTypeFavoritesOfFriends = 3, k_EWorkshopEnumerationTypeVotedByFriends = 4, k_EWorkshopEnumerationTypeContentByFriends = 5, k_EWorkshopEnumerationTypeRecentFromFollowedUsers = 6, }; enum EWorkshopVideoProvider { k_EWorkshopVideoProviderNone = 0, k_EWorkshopVideoProviderYoutube = 1 }; enum EUGCReadAction { // Keeps the file handle open unless the last byte is read. You can use this when reading large files (over 100MB) in sequential chunks. // If the last byte is read, this will behave the same as k_EUGCRead_Close. Otherwise, it behaves the same as k_EUGCRead_ContinueReading. // This value maintains the same behavior as before the EUGCReadAction parameter was introduced. k_EUGCRead_ContinueReadingUntilFinished = 0, // Keeps the file handle open. Use this when using UGCRead to seek to different parts of the file. // When you are done seeking around the file, make a final call with k_EUGCRead_Close to close it. k_EUGCRead_ContinueReading = 1, // Frees the file handle. Use this when you're done reading the content. // To read the file from Steam again you will need to call UGCDownload again. k_EUGCRead_Close = 2, }; enum ERemoteStorageLocalFileChange { k_ERemoteStorageLocalFileChange_Invalid = 0, // The file was updated from another device k_ERemoteStorageLocalFileChange_FileUpdated = 1, // The file was deleted by another device k_ERemoteStorageLocalFileChange_FileDeleted = 2, }; enum ERemoteStorageFilePathType { k_ERemoteStorageFilePathType_Invalid = 0, // The file is directly accessed by the game and this is the full path k_ERemoteStorageFilePathType_Absolute = 1, // The file is accessed via the ISteamRemoteStorage API and this is the filename k_ERemoteStorageFilePathType_APIFilename = 2, }; //----------------------------------------------------------------------------- // Purpose: Functions for accessing, reading and writing files stored remotely // and cached locally //----------------------------------------------------------------------------- class ISteamRemoteStorage { public: // NOTE // // Filenames are case-insensitive, and will be converted to lowercase automatically. // So "foo.bar" and "Foo.bar" are the same file, and if you write "Foo.bar" then // iterate the files, the filename returned will be "foo.bar". // // file operations virtual bool FileWrite( const char *pchFile, const void *pvData, int32 cubData ) = 0; virtual int32 FileRead( const char *pchFile, void *pvData, int32 cubDataToRead ) = 0; STEAM_CALL_RESULT( RemoteStorageFileWriteAsyncComplete_t ) virtual SteamAPICall_t FileWriteAsync( const char *pchFile, const void *pvData, uint32 cubData ) = 0; STEAM_CALL_RESULT( RemoteStorageFileReadAsyncComplete_t ) virtual SteamAPICall_t FileReadAsync( const char *pchFile, uint32 nOffset, uint32 cubToRead ) = 0; virtual bool FileReadAsyncComplete( SteamAPICall_t hReadCall, void *pvBuffer, uint32 cubToRead ) = 0; virtual bool FileForget( const char *pchFile ) = 0; virtual bool FileDelete( const char *pchFile ) = 0; STEAM_CALL_RESULT( RemoteStorageFileShareResult_t ) virtual SteamAPICall_t FileShare( const char *pchFile ) = 0; virtual bool SetSyncPlatforms( const char *pchFile, ERemoteStoragePlatform eRemoteStoragePlatform ) = 0; // file operations that cause network IO virtual UGCFileWriteStreamHandle_t FileWriteStreamOpen( const char *pchFile ) = 0; virtual bool FileWriteStreamWriteChunk( UGCFileWriteStreamHandle_t writeHandle, const void *pvData, int32 cubData ) = 0; virtual bool FileWriteStreamClose( UGCFileWriteStreamHandle_t writeHandle ) = 0; virtual bool FileWriteStreamCancel( UGCFileWriteStreamHandle_t writeHandle ) = 0; // file information virtual bool FileExists( const char *pchFile ) = 0; virtual bool FilePersisted( const char *pchFile ) = 0; virtual int32 GetFileSize( const char *pchFile ) = 0; virtual int64 GetFileTimestamp( const char *pchFile ) = 0; virtual ERemoteStoragePlatform GetSyncPlatforms( const char *pchFile ) = 0; // iteration virtual int32 GetFileCount() = 0; virtual const char *GetFileNameAndSize( int iFile, int32 *pnFileSizeInBytes ) = 0; // configuration management virtual bool GetQuota( uint64 *pnTotalBytes, uint64 *puAvailableBytes ) = 0; virtual bool IsCloudEnabledForAccount() = 0; virtual bool IsCloudEnabledForApp() = 0; virtual void SetCloudEnabledForApp( bool bEnabled ) = 0; // user generated content // Downloads a UGC file. A priority value of 0 will download the file immediately, // otherwise it will wait to download the file until all downloads with a lower priority // value are completed. Downloads with equal priority will occur simultaneously. STEAM_CALL_RESULT( RemoteStorageDownloadUGCResult_t ) virtual SteamAPICall_t UGCDownload( UGCHandle_t hContent, uint32 unPriority ) = 0; // Gets the amount of data downloaded so far for a piece of content. pnBytesExpected can be 0 if function returns false // or if the transfer hasn't started yet, so be careful to check for that before dividing to get a percentage virtual bool GetUGCDownloadProgress( UGCHandle_t hContent, int32 *pnBytesDownloaded, int32 *pnBytesExpected ) = 0; // Gets metadata for a file after it has been downloaded. This is the same metadata given in the RemoteStorageDownloadUGCResult_t call result virtual bool GetUGCDetails( UGCHandle_t hContent, AppId_t *pnAppID, STEAM_OUT_STRING() char **ppchName, int32 *pnFileSizeInBytes, STEAM_OUT_STRUCT() CSteamID *pSteamIDOwner ) = 0; // After download, gets the content of the file. // Small files can be read all at once by calling this function with an offset of 0 and cubDataToRead equal to the size of the file. // Larger files can be read in chunks to reduce memory usage (since both sides of the IPC client and the game itself must allocate // enough memory for each chunk). Once the last byte is read, the file is implicitly closed and further calls to UGCRead will fail // unless UGCDownload is called again. // For especially large files (anything over 100MB) it is a requirement that the file is read in chunks. virtual int32 UGCRead( UGCHandle_t hContent, void *pvData, int32 cubDataToRead, uint32 cOffset, EUGCReadAction eAction ) = 0; // Functions to iterate through UGC that has finished downloading but has not yet been read via UGCRead() virtual int32 GetCachedUGCCount() = 0; virtual UGCHandle_t GetCachedUGCHandle( int32 iCachedContent ) = 0; // publishing UGC STEAM_CALL_RESULT( RemoteStoragePublishFileProgress_t ) virtual SteamAPICall_t PublishWorkshopFile( const char *pchFile, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags, EWorkshopFileType eWorkshopFileType ) = 0; virtual PublishedFileUpdateHandle_t CreatePublishedFileUpdateRequest( PublishedFileId_t unPublishedFileId ) = 0; virtual bool UpdatePublishedFileFile( PublishedFileUpdateHandle_t updateHandle, const char *pchFile ) = 0; virtual bool UpdatePublishedFilePreviewFile( PublishedFileUpdateHandle_t updateHandle, const char *pchPreviewFile ) = 0; virtual bool UpdatePublishedFileTitle( PublishedFileUpdateHandle_t updateHandle, const char *pchTitle ) = 0; virtual bool UpdatePublishedFileDescription( PublishedFileUpdateHandle_t updateHandle, const char *pchDescription ) = 0; virtual bool UpdatePublishedFileVisibility( PublishedFileUpdateHandle_t updateHandle, ERemoteStoragePublishedFileVisibility eVisibility ) = 0; virtual bool UpdatePublishedFileTags( PublishedFileUpdateHandle_t updateHandle, SteamParamStringArray_t *pTags ) = 0; STEAM_CALL_RESULT( RemoteStorageUpdatePublishedFileResult_t ) virtual SteamAPICall_t CommitPublishedFileUpdate( PublishedFileUpdateHandle_t updateHandle ) = 0; // Gets published file details for the given publishedfileid. If unMaxSecondsOld is greater than 0, // cached data may be returned, depending on how long ago it was cached. A value of 0 will force a refresh. // A value of k_WorkshopForceLoadPublishedFileDetailsFromCache will use cached data if it exists, no matter how old it is. STEAM_CALL_RESULT( RemoteStorageGetPublishedFileDetailsResult_t ) virtual SteamAPICall_t GetPublishedFileDetails( PublishedFileId_t unPublishedFileId, uint32 unMaxSecondsOld ) = 0; STEAM_CALL_RESULT( RemoteStorageDeletePublishedFileResult_t ) virtual SteamAPICall_t DeletePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; // enumerate the files that the current user published with this app STEAM_CALL_RESULT( RemoteStorageEnumerateUserPublishedFilesResult_t ) virtual SteamAPICall_t EnumerateUserPublishedFiles( uint32 unStartIndex ) = 0; STEAM_CALL_RESULT( RemoteStorageSubscribePublishedFileResult_t ) virtual SteamAPICall_t SubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; STEAM_CALL_RESULT( RemoteStorageEnumerateUserSubscribedFilesResult_t ) virtual SteamAPICall_t EnumerateUserSubscribedFiles( uint32 unStartIndex ) = 0; STEAM_CALL_RESULT( RemoteStorageUnsubscribePublishedFileResult_t ) virtual SteamAPICall_t UnsubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; virtual bool UpdatePublishedFileSetChangeDescription( PublishedFileUpdateHandle_t updateHandle, const char *pchChangeDescription ) = 0; STEAM_CALL_RESULT( RemoteStorageGetPublishedItemVoteDetailsResult_t ) virtual SteamAPICall_t GetPublishedItemVoteDetails( PublishedFileId_t unPublishedFileId ) = 0; STEAM_CALL_RESULT( RemoteStorageUpdateUserPublishedItemVoteResult_t ) virtual SteamAPICall_t UpdateUserPublishedItemVote( PublishedFileId_t unPublishedFileId, bool bVoteUp ) = 0; STEAM_CALL_RESULT( RemoteStorageGetPublishedItemVoteDetailsResult_t ) virtual SteamAPICall_t GetUserPublishedItemVoteDetails( PublishedFileId_t unPublishedFileId ) = 0; STEAM_CALL_RESULT( RemoteStorageEnumerateUserPublishedFilesResult_t ) virtual SteamAPICall_t EnumerateUserSharedWorkshopFiles( CSteamID steamId, uint32 unStartIndex, SteamParamStringArray_t *pRequiredTags, SteamParamStringArray_t *pExcludedTags ) = 0; STEAM_CALL_RESULT( RemoteStoragePublishFileProgress_t ) virtual SteamAPICall_t PublishVideo( EWorkshopVideoProvider eVideoProvider, const char *pchVideoAccount, const char *pchVideoIdentifier, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags ) = 0; STEAM_CALL_RESULT( RemoteStorageSetUserPublishedFileActionResult_t ) virtual SteamAPICall_t SetUserPublishedFileAction( PublishedFileId_t unPublishedFileId, EWorkshopFileAction eAction ) = 0; STEAM_CALL_RESULT( RemoteStorageEnumeratePublishedFilesByUserActionResult_t ) virtual SteamAPICall_t EnumeratePublishedFilesByUserAction( EWorkshopFileAction eAction, uint32 unStartIndex ) = 0; // this method enumerates the public view of workshop files STEAM_CALL_RESULT( RemoteStorageEnumerateWorkshopFilesResult_t ) virtual SteamAPICall_t EnumeratePublishedWorkshopFiles( EWorkshopEnumerationType eEnumerationType, uint32 unStartIndex, uint32 unCount, uint32 unDays, SteamParamStringArray_t *pTags, SteamParamStringArray_t *pUserTags ) = 0; STEAM_CALL_RESULT( RemoteStorageDownloadUGCResult_t ) virtual SteamAPICall_t UGCDownloadToLocation( UGCHandle_t hContent, const char *pchLocation, uint32 unPriority ) = 0; // Cloud dynamic state change notification virtual int32 GetLocalFileChangeCount() = 0; virtual const char *GetLocalFileChange( int iFile, ERemoteStorageLocalFileChange *pEChangeType, ERemoteStorageFilePathType *pEFilePathType ) = 0; // Indicate to Steam the beginning / end of a set of local file // operations - for example, writing a game save that requires updating two files. virtual bool BeginFileWriteBatch() = 0; virtual bool EndFileWriteBatch() = 0; }; #define STEAMREMOTESTORAGE_INTERFACE_VERSION "STEAMREMOTESTORAGE_INTERFACE_VERSION016" // Global interface accessor inline ISteamRemoteStorage *SteamRemoteStorage(); STEAM_DEFINE_USER_INTERFACE_ACCESSOR( ISteamRemoteStorage *, SteamRemoteStorage, STEAMREMOTESTORAGE_INTERFACE_VERSION ); // callbacks #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx #endif // // IMPORTANT! k_iClientRemoteStorageCallbacks 1 through 6 are used, see iclientremotestorage.h // //----------------------------------------------------------------------------- // Purpose: The result of a call to FileShare() //----------------------------------------------------------------------------- struct RemoteStorageFileShareResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 7 }; EResult m_eResult; // The result of the operation UGCHandle_t m_hFile; // The handle that can be shared with users and features char m_rgchFilename[k_cchFilenameMax]; // The name of the file that was shared }; // k_iClientRemoteStorageCallbacks + 8 is deprecated! Do not reuse //----------------------------------------------------------------------------- // Purpose: The result of a call to PublishFile() //----------------------------------------------------------------------------- struct RemoteStoragePublishFileResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 9 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; bool m_bUserNeedsToAcceptWorkshopLegalAgreement; }; // k_iClientRemoteStorageCallbacks + 10 is deprecated! Do not reuse //----------------------------------------------------------------------------- // Purpose: The result of a call to DeletePublishedFile() //----------------------------------------------------------------------------- struct RemoteStorageDeletePublishedFileResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 11 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to EnumerateUserPublishedFiles() //----------------------------------------------------------------------------- struct RemoteStorageEnumerateUserPublishedFilesResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 12 }; EResult m_eResult; // The result of the operation. int32 m_nResultsReturned; int32 m_nTotalResultCount; PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to SubscribePublishedFile() //----------------------------------------------------------------------------- struct RemoteStorageSubscribePublishedFileResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 13 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to EnumerateSubscribePublishedFiles() //----------------------------------------------------------------------------- struct RemoteStorageEnumerateUserSubscribedFilesResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 14 }; EResult m_eResult; // The result of the operation. int32 m_nResultsReturned; int32 m_nTotalResultCount; PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; uint32 m_rgRTimeSubscribed[ k_unEnumeratePublishedFilesMaxResults ]; }; #if defined(VALVE_CALLBACK_PACK_SMALL) VALVE_COMPILE_TIME_ASSERT( sizeof( RemoteStorageEnumerateUserSubscribedFilesResult_t ) == (1 + 1 + 1 + 50 + 100) * 4 ); #elif defined(VALVE_CALLBACK_PACK_LARGE) VALVE_COMPILE_TIME_ASSERT( sizeof( RemoteStorageEnumerateUserSubscribedFilesResult_t ) == (1 + 1 + 1 + 50 + 100) * 4 + 4 ); #else #warning You must first include steam_api_common.h #endif //----------------------------------------------------------------------------- // Purpose: The result of a call to UnsubscribePublishedFile() //----------------------------------------------------------------------------- struct RemoteStorageUnsubscribePublishedFileResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 15 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to CommitPublishedFileUpdate() //----------------------------------------------------------------------------- struct RemoteStorageUpdatePublishedFileResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 16 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; bool m_bUserNeedsToAcceptWorkshopLegalAgreement; }; //----------------------------------------------------------------------------- // Purpose: The result of a call to UGCDownload() //----------------------------------------------------------------------------- struct RemoteStorageDownloadUGCResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 17 }; EResult m_eResult; // The result of the operation. UGCHandle_t m_hFile; // The handle to the file that was attempted to be downloaded. AppId_t m_nAppID; // ID of the app that created this file. int32 m_nSizeInBytes; // The size of the file that was downloaded, in bytes. char m_pchFileName[k_cchFilenameMax]; // The name of the file that was downloaded. uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. }; //----------------------------------------------------------------------------- // Purpose: The result of a call to GetPublishedFileDetails() //----------------------------------------------------------------------------- struct RemoteStorageGetPublishedFileDetailsResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 18 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; AppId_t m_nCreatorAppID; // ID of the app that created this file. AppId_t m_nConsumerAppID; // ID of the app that will consume this file. char m_rgchTitle[k_cchPublishedDocumentTitleMax]; // title of document char m_rgchDescription[k_cchPublishedDocumentDescriptionMax]; // description of document UGCHandle_t m_hFile; // The handle of the primary file UGCHandle_t m_hPreviewFile; // The handle of the preview file uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. uint32 m_rtimeCreated; // time when the published file was created uint32 m_rtimeUpdated; // time when the published file was last updated ERemoteStoragePublishedFileVisibility m_eVisibility; bool m_bBanned; char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer char m_pchFileName[k_cchFilenameMax]; // The name of the primary file int32 m_nFileSize; // Size of the primary file int32 m_nPreviewFileSize; // Size of the preview file char m_rgchURL[k_cchPublishedFileURLMax]; // URL (for a video or a website) EWorkshopFileType m_eFileType; // Type of the file bool m_bAcceptedForUse; // developer has specifically flagged this item as accepted in the Workshop }; struct RemoteStorageEnumerateWorkshopFilesResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 19 }; EResult m_eResult; int32 m_nResultsReturned; int32 m_nTotalResultCount; PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; float m_rgScore[ k_unEnumeratePublishedFilesMaxResults ]; AppId_t m_nAppId; uint32 m_unStartIndex; }; //----------------------------------------------------------------------------- // Purpose: The result of GetPublishedItemVoteDetails //----------------------------------------------------------------------------- struct RemoteStorageGetPublishedItemVoteDetailsResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 20 }; EResult m_eResult; PublishedFileId_t m_unPublishedFileId; int32 m_nVotesFor; int32 m_nVotesAgainst; int32 m_nReports; float m_fScore; }; //----------------------------------------------------------------------------- // Purpose: User subscribed to a file for the app (from within the app or on the web) //----------------------------------------------------------------------------- struct RemoteStoragePublishedFileSubscribed_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 21 }; PublishedFileId_t m_nPublishedFileId; // The published file id AppId_t m_nAppID; // ID of the app that will consume this file. }; //----------------------------------------------------------------------------- // Purpose: User unsubscribed from a file for the app (from within the app or on the web) //----------------------------------------------------------------------------- struct RemoteStoragePublishedFileUnsubscribed_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 22 }; PublishedFileId_t m_nPublishedFileId; // The published file id AppId_t m_nAppID; // ID of the app that will consume this file. }; //----------------------------------------------------------------------------- // Purpose: Published file that a user owns was deleted (from within the app or the web) //----------------------------------------------------------------------------- struct RemoteStoragePublishedFileDeleted_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 23 }; PublishedFileId_t m_nPublishedFileId; // The published file id AppId_t m_nAppID; // ID of the app that will consume this file. }; //----------------------------------------------------------------------------- // Purpose: The result of a call to UpdateUserPublishedItemVote() //----------------------------------------------------------------------------- struct RemoteStorageUpdateUserPublishedItemVoteResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 24 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; // The published file id }; //----------------------------------------------------------------------------- // Purpose: The result of a call to GetUserPublishedItemVoteDetails() //----------------------------------------------------------------------------- struct RemoteStorageUserVoteDetails_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 25 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; // The published file id EWorkshopVote m_eVote; // what the user voted }; struct RemoteStorageEnumerateUserSharedWorkshopFilesResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 26 }; EResult m_eResult; // The result of the operation. int32 m_nResultsReturned; int32 m_nTotalResultCount; PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; }; struct RemoteStorageSetUserPublishedFileActionResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 27 }; EResult m_eResult; // The result of the operation. PublishedFileId_t m_nPublishedFileId; // The published file id EWorkshopFileAction m_eAction; // the action that was attempted }; struct RemoteStorageEnumeratePublishedFilesByUserActionResult_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 28 }; EResult m_eResult; // The result of the operation. EWorkshopFileAction m_eAction; // the action that was filtered on int32 m_nResultsReturned; int32 m_nTotalResultCount; PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; uint32 m_rgRTimeUpdated[ k_unEnumeratePublishedFilesMaxResults ]; }; //----------------------------------------------------------------------------- // Purpose: Called periodically while a PublishWorkshopFile is in progress //----------------------------------------------------------------------------- struct RemoteStoragePublishFileProgress_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 29 }; double m_dPercentFile; bool m_bPreview; }; //----------------------------------------------------------------------------- // Purpose: Called when the content for a published file is updated //----------------------------------------------------------------------------- struct RemoteStoragePublishedFileUpdated_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 30 }; PublishedFileId_t m_nPublishedFileId; // The published file id AppId_t m_nAppID; // ID of the app that will consume this file. uint64 m_ulUnused; // not used anymore }; //----------------------------------------------------------------------------- // Purpose: Called when a FileWriteAsync completes //----------------------------------------------------------------------------- struct RemoteStorageFileWriteAsyncComplete_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 31 }; EResult m_eResult; // result }; //----------------------------------------------------------------------------- // Purpose: Called when a FileReadAsync completes //----------------------------------------------------------------------------- struct RemoteStorageFileReadAsyncComplete_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 32 }; SteamAPICall_t m_hFileReadAsync; // call handle of the async read which was made EResult m_eResult; // result uint32 m_nOffset; // offset in the file this read was at uint32 m_cubRead; // amount read - will the <= the amount requested }; //----------------------------------------------------------------------------- // Purpose: one or more files for this app have changed locally after syncing // to remote session changes // Note: only posted if this happens DURING the local app session //----------------------------------------------------------------------------- STEAM_CALLBACK_BEGIN( RemoteStorageLocalFileChange_t, k_iClientRemoteStorageCallbacks + 33 ) STEAM_CALLBACK_END( 0 ) #pragma pack( pop ) #endif // ISTEAMREMOTESTORAGE_H
0
0.984644
1
0.984644
game-dev
MEDIA
0.822832
game-dev
0.787917
1
0.787917
plaaosert/stupid
3,887
TunnelsOfGlembo/Garbage/damnation/damnation.js
const snd_squeak1 = new Audio("squeaks/1.ogg"); const snd_squeak2 = new Audio("squeaks/2.ogg"); const snd_squeak3 = new Audio("squeaks/3.ogg"); const snd_squeak4 = new Audio("squeaks/4.ogg"); const snd_squeak5 = new Audio("squeaks/5.ogg"); const snd_damn = new Audio("squeaks/damn.mp3"); const snd_explosion = new Audio("squeaks/explosion.ogg"); const snd_clank = new Audio("squeaks/clank.ogg"); var hash = document.location.hash.split(":"); function squeak() { //include another check here so it updates in realtime hash = document.location.hash.split(":"); if (hash[0] == "#DAMN" || hash[0] == "#DAMNATION") { snd_damn.cloneNode().play(); } else { let x = Math.floor(Math.random() * 5) + 1; switch(x) { case 1: snd_squeak1.cloneNode().play(); return case 2: snd_squeak2.cloneNode().play(); return case 3: snd_squeak3.cloneNode().play(); return case 4: snd_squeak4.cloneNode().play(); return case 5: snd_squeak5.cloneNode().play(); return default: console.log("Failed to find a valid sound."); snd_squeak1.cloneNode().play(); return } } } const pukeko_template = document.querySelector(".pukeko"); var pukekos = []; var purge_ready = false; function new_pukeko(x_override = null, y_override = null, no_sound = false, type_override = null) { if (pukekos.length > 1000) { console.log("PUKEKO SINGULARITY ACHIEVED. ANNIHILATION IMMINENT"); purge_pukekos(); return } let screenWidth = window.innerWidth + 40; let screenHeight = window.innerHeight + 20; fresh_pukeko = new pukeko(0,0, type_override); pukekos.push(fresh_pukeko); let pukeko_node = pukeko_template.cloneNode(true); pukeko_node.querySelector(".pukeko_speech").textContent = fresh_pukeko.quote; pukeko_node.querySelector(".pukeko_bubble").setAttribute("class", "pukeko_bubble " + fresh_pukeko.box_colour); pukeko_node.querySelector(".pukeko_image").src = fresh_pukeko.sprite; document.getElementById("pukeko_space").appendChild(pukeko_node); let pukeko_box = pukeko_node.getBoundingClientRect() if (x_override != null) { fresh_pukeko.pos_x = x_override; } else { fresh_pukeko.pos_x = Math.floor(Math.random() * (screenWidth - pukeko_box.width)); } if (y_override != null) { fresh_pukeko.pos_y = y_override; } else { fresh_pukeko.pos_y = Math.floor(Math.random() * (screenHeight - pukeko_box.height)); } pukeko_node.setAttribute("style", "top:"+fresh_pukeko.pos_y+"px; left:"+fresh_pukeko.pos_x+"px"); if (no_sound == false) { squeak(); } if (pukekos.length >= 50 && purge_ready != true) { snd_clank.cloneNode().play(); document.getElementById("purge").style.display = "block"; purge_ready = true; } } function debug_pukeko(amt) { if (amt > 1000 || pukekos.length + amt > 1000) { console.log("TOO MUCH!!!!!!!!!!! (greater than 1000)"); return } console.log("DAMN!!!!!! "+amt+" PUKEKOS INCOMING!!!!!!!!!!"); for (let i = 0; i < amt; i++) { new_pukeko(null,null,true); } } //this entire city must be purged function purge_pukekos() { let plagued_pukekos = document.getElementsByClassName("pukeko"); snd_explosion.cloneNode().play(); snd_damn.cloneNode().play(); for (let i = pukekos.length; i > 0; --i) { plagued_pukekos[i].remove(); } pukekos = []; document.getElementById("purge").style.display = "none"; new_pukeko(); purge_ready = false; console.log("IT IS DONE."); } if (hash[0] == "#DAMNATION") { console.log("DAMNATION!!!! MODE ACTIVE!!! GOOD LUCK!!!"); (function () { var interval = 2000; timer = function() { interval -= 20; new_pukeko(); console.log("DAMNATION AT "+interval+"ms"); interval = interval < 120 ? 120 : interval; if (pukekos.length < 1000) { setTimeout(timer, interval); } else { console.log("DAMNATION COMPLETE!!!!!!"); return } }; timer(); })(); } else { console.log("DAMN!!!!") new_pukeko(); }
0
0.711774
1
0.711774
game-dev
MEDIA
0.857428
game-dev
0.671441
1
0.671441
AscEmu/AscEmu
3,902
src/world/Movement/MovementDefines.cpp
/* Copyright (c) 2014-2025 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #include "MovementDefines.h" #include "LocationVector.h" #include "Objects/MovementInfo.hpp" #if VERSION_STRING >= Cata #include "Logging/Logger.hpp" #endif #define CONTACT_DISTANCE 0.5f ////////////////////////////////////////////////////////////////////////////////////////// // ChaseRange ChaseRange::ChaseRange(float range) : MinRange(range > CONTACT_DISTANCE ? 0 : range - CONTACT_DISTANCE), MinTolerance(range), MaxRange(range + CONTACT_DISTANCE), MaxTolerance(range) { } ChaseRange::ChaseRange(float _minRange, float _maxRange) : MinRange(_minRange), MinTolerance(std::min(_minRange + CONTACT_DISTANCE, (_minRange + _maxRange) / 2)), MaxRange(_maxRange), MaxTolerance(std::max(_maxRange - CONTACT_DISTANCE, MinTolerance)) { } ChaseRange::ChaseRange(float _minRange, float _minTolerance, float _maxTolerance, float _maxRange) : MinRange(_minRange), MinTolerance(_minTolerance), MaxRange(_maxRange), MaxTolerance(_maxTolerance) { } ////////////////////////////////////////////////////////////////////////////////////////// // ChaseAngle ChaseAngle::ChaseAngle(float angle, float _tolerance/* = M_PI_4*/) : RelativeAngle(normalizeOrientation(angle)), Tolerance(_tolerance) { } float ChaseAngle::upperBound() const { return normalizeOrientation(RelativeAngle + Tolerance); } float ChaseAngle::lowerBound() const { return normalizeOrientation(RelativeAngle - Tolerance); } bool ChaseAngle::isAngleOkay(float relativeAngle) const { float const diff = std::abs(relativeAngle - RelativeAngle); return (std::min(diff, float(2 * M_PI) - diff) <= Tolerance); } #if VERSION_STRING >= Cata void ExtraMovementStatusElement::readNextElement(ByteBuffer& packet) { MovementStatusElements const element = _elements[_index++]; switch (element) { case MSEGuidBit0: case MSEGuidBit1: case MSEGuidBit2: case MSEGuidBit3: case MSEGuidBit4: case MSEGuidBit5: case MSEGuidBit6: case MSEGuidBit7: Data.guid[element - MSEGuidBit0] = packet.readBit(); break; case MSEGuidByte0: case MSEGuidByte1: case MSEGuidByte2: case MSEGuidByte3: case MSEGuidByte4: case MSEGuidByte5: case MSEGuidByte6: case MSEGuidByte7: packet.ReadByteSeq(Data.guid[element - MSEGuidByte0]); break; case MSEExtraFloat: packet >> Data.floatData; break; case MSEExtraInt8: packet >> Data.byteData; break; default: sLogger.failure("Incorrect extraMovementStatusElement sequence {} detected", element); break; } } void ExtraMovementStatusElement::writeNextElement(ByteBuffer& packet) { MovementStatusElements const element = _elements[_index++]; switch (element) { case MSEGuidBit0: case MSEGuidBit1: case MSEGuidBit2: case MSEGuidBit3: case MSEGuidBit4: case MSEGuidBit5: case MSEGuidBit6: case MSEGuidBit7: packet.writeBit(Data.guid[element - MSEGuidBit0]); break; case MSEGuidByte0: case MSEGuidByte1: case MSEGuidByte2: case MSEGuidByte3: case MSEGuidByte4: case MSEGuidByte5: case MSEGuidByte6: case MSEGuidByte7: packet.WriteByteSeq(Data.guid[element - MSEGuidByte0]); break; case MSEExtraFloat: packet << Data.floatData; break; case MSEExtraInt8: packet << Data.byteData; break; default: sLogger.failure("Incorrect extraMovementStatusElement sequence {} detected", element); break; } } #endif
0
0.900897
1
0.900897
game-dev
MEDIA
0.596579
game-dev
0.996863
1
0.996863
Mixinors/Astromine
2,866
src/main/java/com/github/mixinors/astromine/common/block/utility/PumpBlock.java
/* * MIT License * * Copyright (c) 2020 - 2022 Mixinors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.mixinors.astromine.common.block.utility; import com.github.mixinors.astromine.common.block.base.HorizontalFacingBlockWithEntity; import com.github.mixinors.astromine.common.block.entity.utility.PumpBlockEntity; import com.github.mixinors.astromine.common.comparator.ComparatorMode; import com.github.mixinors.astromine.common.screen.handler.utility.PumpScreenHandler; import net.minecraft.block.BlockState; import net.minecraft.block.entity.BlockEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.network.PacketByteBuf; import net.minecraft.screen.ScreenHandler; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class PumpBlock extends HorizontalFacingBlockWithEntity { public PumpBlock(Settings settings) { super(settings); } @Override public SavedData getSavedDataForDroppedItem() { return FLUID_MACHINE; } @Override public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new PumpBlockEntity(pos, state); } @Override public boolean hasScreenHandler() { return true; } @Override public ScreenHandler createScreenHandler(BlockState state, World world, BlockPos pos, int syncId, PlayerInventory playerInventory, PlayerEntity player) { return new PumpScreenHandler(syncId, playerInventory.player, pos); } @Override public void populateScreenHandlerBuffer(BlockState state, World world, BlockPos pos, ServerPlayerEntity player, PacketByteBuf buffer) { buffer.writeBlockPos(pos); } @Override protected ComparatorMode getComparatorMode() { return ComparatorMode.FLUIDS; } }
0
0.601582
1
0.601582
game-dev
MEDIA
0.995255
game-dev
0.549299
1
0.549299
amslabtech/dynamic_obstacle_avoidance_planner
2,019
src/path_to_local_goal.cpp
#include <ros/ros.h> #include <nav_msgs/Path.h> #include <tf/transform_listener.h> #include <tf/tf.h> #include <geometry_msgs/TransformStamped.h> double GOAL_DISTANCE; nav_msgs::Path path; void path_callback(const nav_msgs::PathConstPtr& msg) { path = *msg; } double calcurate_distance(geometry_msgs::Pose, geometry_msgs::Pose); int main(int argc, char** argv) { ros::init(argc, argv, "path_to_local_goal"); ros::NodeHandle nh; ros::NodeHandle local_nh("~"); local_nh.getParam("GOAL_DISTANCE", GOAL_DISTANCE); ros::Publisher goal_pub = nh.advertise<geometry_msgs::PoseStamped>("/goal", 100); ros::Subscriber path_sub = nh.subscribe("/path", 100, path_callback); tf::TransformListener listener; tf::StampedTransform _transform; geometry_msgs::TransformStamped transform; geometry_msgs::PoseStamped odometry; ros::Rate loop_rate(10); while(ros::ok()){ bool transformed = false; try{ listener.lookupTransform("odom", "base_link", ros::Time(0), _transform); tf::transformStampedTFToMsg(_transform, transform); odometry.header = transform.header; odometry.pose.position.x = transform.transform.translation.x; odometry.pose.position.y = transform.transform.translation.y; odometry.pose.position.z = transform.transform.translation.z; odometry.pose.orientation = transform.transform.rotation; transformed = true; }catch(tf::TransformException ex){ ROS_ERROR("%s", ex.what()); } if(!path.poses.empty() && transformed){ for(int i=path.poses.size()-1;i>=0;i--){ if(calcurate_distance(path.poses[i].pose, odometry.pose) < GOAL_DISTANCE){ goal_pub.publish(path.poses[i]); break; } } } loop_rate.sleep(); ros::spinOnce(); } return 0; } double calcurate_distance(geometry_msgs::Pose a, geometry_msgs::Pose b) { return sqrt((a.position.x - b.position.x) * (a.position.x - b.position.x) + (a.position.y - b.position.y) * (a.position.y - b.position.y)); }
0
0.842344
1
0.842344
game-dev
MEDIA
0.254401
game-dev
0.950488
1
0.950488
alphayellow1/AlphaYellowWidescreenFixes
9,138
source/fixes/CabelasBigGameHunter2008TrophyBucksFOVFix/dllmain.cpp
// Include necessary headers #include "stdafx.h" #include "helper.hpp" #include <spdlog/spdlog.h> #include <spdlog/sinks/basic_file_sink.h> #include <inipp/inipp.h> #include <safetyhook.hpp> #include <vector> #include <map> #include <windows.h> #include <psapi.h> // For GetModuleInformation #include <fstream> #include <filesystem> #include <cmath> // For atanf, tanf #include <sstream> #include <cstring> #include <iomanip> #include <cstdint> #include <iostream> #define spdlog_confparse(var) spdlog::info("Config Parse: {}: {}", #var, var) HMODULE exeModule = GetModuleHandle(NULL); HMODULE thisModule; HMODULE dllModule2 = nullptr; HMODULE dllModule3 = nullptr; // Fix details std::string sFixName = "CabelasBigGameHunter2008TrophyBucksFOVFix"; std::string sFixVersion = "1.1"; std::filesystem::path sFixPath; // Ini inipp::Ini<char> ini; std::string sConfigFile = sFixName + ".ini"; // Logger std::shared_ptr<spdlog::logger> logger; std::string sLogFile = sFixName + ".log"; std::filesystem::path sExePath; std::string sExeName; // Constants constexpr float fOldAspectRatio = 4.0f / 3.0f; // Ini variables bool bFixActive; // Variables int iCurrentResX; int iCurrentResY; float fNewAspectRatio; float fFOVFactor; float fAspectRatioScale; float fNewCameraFOV; uint32_t iInsideCar; // Game detection enum class Game { CBGH2008TB, Unknown }; struct GameInfo { std::string GameTitle; std::string ExeName; }; const std::map<Game, GameInfo> kGames = { {Game::CBGH2008TB, {"Cabela's Big Game Hunter 2008 Trophy Bucks", "Ctb.exe"}}, }; const GameInfo* game = nullptr; Game eGameType = Game::Unknown; void Logging() { // Get path to DLL WCHAR dllPath[_MAX_PATH] = { 0 }; GetModuleFileNameW(thisModule, dllPath, MAX_PATH); sFixPath = dllPath; sFixPath = sFixPath.remove_filename(); // Get game name and exe path WCHAR exePathW[_MAX_PATH] = { 0 }; GetModuleFileNameW(exeModule, exePathW, MAX_PATH); sExePath = exePathW; sExeName = sExePath.filename().string(); sExePath = sExePath.remove_filename(); // Spdlog initialization try { logger = spdlog::basic_logger_st(sFixName.c_str(), sExePath.string() + "\\" + sLogFile, true); spdlog::set_default_logger(logger); spdlog::flush_on(spdlog::level::debug); spdlog::set_level(spdlog::level::debug); // Enable debug level logging spdlog::info("----------"); spdlog::info("{:s} v{:s} loaded.", sFixName.c_str(), sFixVersion.c_str()); spdlog::info("----------"); spdlog::info("Log file: {}", sExePath.string() + "\\" + sLogFile); spdlog::info("----------"); spdlog::info("Module Name: {0:s}", sExeName.c_str()); spdlog::info("Module Path: {0:s}", sExePath.string()); spdlog::info("Module Address: 0x{0:X}", (uintptr_t)exeModule); spdlog::info("----------"); spdlog::info("DLL has been successfully loaded."); } catch (const spdlog::spdlog_ex& ex) { AllocConsole(); FILE* dummy; freopen_s(&dummy, "CONOUT$", "w", stdout); std::cout << "Log initialization failed: " << ex.what() << std::endl; FreeLibraryAndExitThread(thisModule, 1); } } void Configuration() { // Inipp initialization std::ifstream iniFile(sFixPath.string() + "\\" + sConfigFile); if (!iniFile) { AllocConsole(); FILE* dummy; freopen_s(&dummy, "CONOUT$", "w", stdout); std::cout << sFixName.c_str() << " v" << sFixVersion.c_str() << " loaded." << std::endl; std::cout << "ERROR: Could not locate config file." << std::endl; std::cout << "ERROR: Make sure " << sConfigFile.c_str() << " is located in " << sFixPath.string().c_str() << std::endl; spdlog::shutdown(); FreeLibraryAndExitThread(thisModule, 1); } else { spdlog::info("Config file: {}", sFixPath.string() + "\\" + sConfigFile); ini.parse(iniFile); } // Parse config ini.strip_trailing_comments(); spdlog::info("----------"); // Load settings from ini inipp::get_value(ini.sections["FOVFix"], "Enabled", bFixActive); spdlog_confparse(bFixActive); // Load resolution from ini inipp::get_value(ini.sections["Settings"], "Width", iCurrentResX); inipp::get_value(ini.sections["Settings"], "Height", iCurrentResY); inipp::get_value(ini.sections["Settings"], "FOVFactor", fFOVFactor); spdlog_confparse(iCurrentResX); spdlog_confparse(iCurrentResY); spdlog_confparse(fFOVFactor); // If resolution not specified, use desktop resolution if (iCurrentResX <= 0 || iCurrentResY <= 0) { spdlog::info("Resolution not specified in ini file. Using desktop resolution."); // Implement Util::GetPhysicalDesktopDimensions() accordingly auto desktopDimensions = Util::GetPhysicalDesktopDimensions(); iCurrentResX = desktopDimensions.first; iCurrentResY = desktopDimensions.second; spdlog_confparse(iCurrentResX); spdlog_confparse(iCurrentResY); } spdlog::info("----------"); } bool DetectGame() { bool bGameFound = false; for (const auto& [type, info] : kGames) { if (Util::stringcmp_caseless(info.ExeName, sExeName)) { spdlog::info("Detected game: {:s} ({:s})", info.GameTitle, sExeName); spdlog::info("----------"); eGameType = type; game = &info; bGameFound = true; break; } } if (bGameFound == false) { spdlog::error("Failed to detect supported game, {:s} isn't supported by the fix.", sExeName); return false; } while ((dllModule2 = GetModuleHandleA("EngineDll8r.dll")) == nullptr) { spdlog::warn("EngineDll8r.dll not loaded yet. Waiting..."); Sleep(100); } spdlog::info("Successfully obtained handle for EngineDll8r.dll: 0x{:X}", reinterpret_cast<uintptr_t>(dllModule2)); while ((dllModule3 = GetModuleHandleA("GameDll8r.dll")) == nullptr) { spdlog::warn("GameDll8r.dll not loaded yet. Waiting..."); Sleep(100); } spdlog::info("Successfully obtained handle for GameDll8r.dll: 0x{:X}", reinterpret_cast<uintptr_t>(dllModule3)); return true; } static SafetyHookMid CameraFOVInstructionHook{}; void CameraFOVInstructionMidHook(SafetyHookContext& ctx) { float& fCurrentCameraFOV = *reinterpret_cast<float*>(ctx.edi + 0xD0); if (fCurrentCameraFOV == 60.0f || fCurrentCameraFOV == 59.98499298f) { fNewCameraFOV = Maths::CalculateNewFOV_DegBased(fCurrentCameraFOV, fAspectRatioScale) * fFOVFactor; } else { fNewCameraFOV = Maths::CalculateNewFOV_DegBased(fCurrentCameraFOV, fAspectRatioScale); } _asm { fld dword ptr ds:[fNewCameraFOV] } } void FOVFix() { if (eGameType == Game::CBGH2008TB && bFixActive == true) { fNewAspectRatio = static_cast<float>(iCurrentResX) / static_cast<float>(iCurrentResY); fAspectRatioScale = fNewAspectRatio / fOldAspectRatio; std::uint8_t* CameraFOVInstructionScanResult = Memory::PatternScan(dllModule2, "D9 87 D0 00 00 00 DC 0D ?? ?? ?? ??"); if (CameraFOVInstructionScanResult) { spdlog::info("Camera FOV Instruction: Address is EngineDll8r.dll+{:x}", CameraFOVInstructionScanResult - (std::uint8_t*)dllModule2); Memory::PatchBytes(CameraFOVInstructionScanResult, "\x90\x90\x90\x90\x90\x90", 6); CameraFOVInstructionHook = safetyhook::create_mid(CameraFOVInstructionScanResult, CameraFOVInstructionMidHook); } else { spdlog::error("Failed to locate camera FOV instruction memory address."); return; } std::uint8_t* AspectRatioInstruction1ScanResult = Memory::PatternScan(dllModule2, "D8 8F D4 00 00 00 D8 B7 D8 00 00 00 D9 9F E0 00 00 00"); if (AspectRatioInstruction1ScanResult) { spdlog::info("Aspect Ratio Instruction 1: Address is EngineDll8r.dll+{:x}", AspectRatioInstruction1ScanResult - (std::uint8_t*)dllModule2); static SafetyHookMid AspectRatioInstruction1MidHook{}; AspectRatioInstruction1MidHook = safetyhook::create_mid(AspectRatioInstruction1ScanResult, [](SafetyHookContext& ctx) { *reinterpret_cast<float*>(ctx.edi + 0xD4) = 0.75f / fAspectRatioScale; }); } else { spdlog::error("Failed to locate first aspect ratio instruction memory address."); return; } std::uint8_t* AspectRatioInstruction2ScanResult = Memory::PatternScan(dllModule2, "D8 B7 D8 00 00 00 D9 9F E0 00 00 00 D9 EE D8 97 EC 00 00 00 DF E0"); if (AspectRatioInstruction2ScanResult) { spdlog::info("Aspect Ratio Instruction 2: Address is EngineDll8r.dll+{:x}", AspectRatioInstruction2ScanResult - (std::uint8_t*)dllModule2); static SafetyHookMid AspectRatioInstruction2MidHook{}; AspectRatioInstruction2MidHook = safetyhook::create_mid(AspectRatioInstruction2ScanResult, [](SafetyHookContext& ctx) { *reinterpret_cast<float*>(ctx.edi + 0xD8) = 1.0f; }); } else { spdlog::error("Failed to locate second aspect ratio instruction memory address."); return; } } } DWORD __stdcall Main(void*) { Logging(); Configuration(); if (DetectGame()) { FOVFix(); } return TRUE; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { thisModule = hModule; HANDLE mainHandle = CreateThread(NULL, 0, Main, 0, NULL, 0); if (mainHandle) { SetThreadPriority(mainHandle, THREAD_PRIORITY_HIGHEST); CloseHandle(mainHandle); } break; } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
0
0.974535
1
0.974535
game-dev
MEDIA
0.347694
game-dev
0.908844
1
0.908844
plooshi/CelestiaGS
9,311
SDK/SettingsListEntry_Action_parameters.hpp
#pragma once /* * SDK generated by Dumper-7 * * https://github.com/Encryqed/Dumper-7 */ // Package: SettingsListEntry_Action #include "Basic.hpp" #include "SlateCore_structs.hpp" namespace SDK::Params { // Function SettingsListEntry_Action.SettingsListEntry_Action_C.ExecuteUbergraph_SettingsListEntry_Action // 0x0158 (0x0158 - 0x0000) struct SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action final { public: int32 EntryPoint; // 0x0000(0x0004)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) bool CallFunc_IsUsingTouch_ReturnValue; // 0x0004(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor) uint8 Pad_4AF6[0x3]; // 0x0005(0x0003)(Fixing Size After Last Property [ Dumper-7 ]) class UIconTextButton_C* K2Node_DynamicCast_AsIcon_Text_Button; // 0x0008(0x0008)(ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) bool K2Node_DynamicCast_bSuccess; // 0x0010(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor) uint8 Pad_4AF7[0x7]; // 0x0011(0x0007)(Fixing Size After Last Property [ Dumper-7 ]) class FText K2Node_Event_ActionText; // 0x0018(0x0018)(ConstParm) struct FGeometry K2Node_Event_MyGeometry; // 0x0030(0x0038)(IsPlainOldData, NoDestructor) struct FPointerEvent K2Node_Event_MouseEvent_1; // 0x0068(0x0070)(ConstParm) class UUMGSequencePlayer* CallFunc_PlayAnimationReverse_ReturnValue; // 0x00D8(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) class UUMGSequencePlayer* CallFunc_PlayAnimationForward_ReturnValue; // 0x00E0(0x0008)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FPointerEvent K2Node_Event_MouseEvent; // 0x00E8(0x0070)(ConstParm) }; static_assert(alignof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action) == 0x000008, "Wrong alignment on SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action"); static_assert(sizeof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action) == 0x000158, "Wrong size on SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, EntryPoint) == 0x000000, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::EntryPoint' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, CallFunc_IsUsingTouch_ReturnValue) == 0x000004, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::CallFunc_IsUsingTouch_ReturnValue' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, K2Node_DynamicCast_AsIcon_Text_Button) == 0x000008, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::K2Node_DynamicCast_AsIcon_Text_Button' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, K2Node_DynamicCast_bSuccess) == 0x000010, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::K2Node_DynamicCast_bSuccess' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, K2Node_Event_ActionText) == 0x000018, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::K2Node_Event_ActionText' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, K2Node_Event_MyGeometry) == 0x000030, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::K2Node_Event_MyGeometry' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, K2Node_Event_MouseEvent_1) == 0x000068, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::K2Node_Event_MouseEvent_1' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, CallFunc_PlayAnimationReverse_ReturnValue) == 0x0000D8, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::CallFunc_PlayAnimationReverse_ReturnValue' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, CallFunc_PlayAnimationForward_ReturnValue) == 0x0000E0, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::CallFunc_PlayAnimationForward_ReturnValue' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action, K2Node_Event_MouseEvent) == 0x0000E8, "Member 'SettingsListEntry_Action_C_ExecuteUbergraph_SettingsListEntry_Action::K2Node_Event_MouseEvent' has a wrong offset!"); // Function SettingsListEntry_Action.SettingsListEntry_Action_C.OnMouseLeave // 0x0070 (0x0070 - 0x0000) struct SettingsListEntry_Action_C_OnMouseLeave final { public: struct FPointerEvent MouseEvent; // 0x0000(0x0070)(ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) }; static_assert(alignof(SettingsListEntry_Action_C_OnMouseLeave) == 0x000008, "Wrong alignment on SettingsListEntry_Action_C_OnMouseLeave"); static_assert(sizeof(SettingsListEntry_Action_C_OnMouseLeave) == 0x000070, "Wrong size on SettingsListEntry_Action_C_OnMouseLeave"); static_assert(offsetof(SettingsListEntry_Action_C_OnMouseLeave, MouseEvent) == 0x000000, "Member 'SettingsListEntry_Action_C_OnMouseLeave::MouseEvent' has a wrong offset!"); // Function SettingsListEntry_Action.SettingsListEntry_Action_C.OnMouseEnter // 0x00A8 (0x00A8 - 0x0000) struct SettingsListEntry_Action_C_OnMouseEnter final { public: struct FGeometry MyGeometry; // 0x0000(0x0038)(BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor) struct FPointerEvent MouseEvent; // 0x0038(0x0070)(ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) }; static_assert(alignof(SettingsListEntry_Action_C_OnMouseEnter) == 0x000008, "Wrong alignment on SettingsListEntry_Action_C_OnMouseEnter"); static_assert(sizeof(SettingsListEntry_Action_C_OnMouseEnter) == 0x0000A8, "Wrong size on SettingsListEntry_Action_C_OnMouseEnter"); static_assert(offsetof(SettingsListEntry_Action_C_OnMouseEnter, MyGeometry) == 0x000000, "Member 'SettingsListEntry_Action_C_OnMouseEnter::MyGeometry' has a wrong offset!"); static_assert(offsetof(SettingsListEntry_Action_C_OnMouseEnter, MouseEvent) == 0x000038, "Member 'SettingsListEntry_Action_C_OnMouseEnter::MouseEvent' has a wrong offset!"); // Function SettingsListEntry_Action.SettingsListEntry_Action_C.OnSettingAssigned // 0x0018 (0x0018 - 0x0000) struct SettingsListEntry_Action_C_OnSettingAssigned final { public: class FText ActionText; // 0x0000(0x0018)(ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) }; static_assert(alignof(SettingsListEntry_Action_C_OnSettingAssigned) == 0x000008, "Wrong alignment on SettingsListEntry_Action_C_OnSettingAssigned"); static_assert(sizeof(SettingsListEntry_Action_C_OnSettingAssigned) == 0x000018, "Wrong size on SettingsListEntry_Action_C_OnSettingAssigned"); static_assert(offsetof(SettingsListEntry_Action_C_OnSettingAssigned, ActionText) == 0x000000, "Member 'SettingsListEntry_Action_C_OnSettingAssigned::ActionText' has a wrong offset!"); // Function SettingsListEntry_Action.SettingsListEntry_Action_C.GetPrimaryGamepadFocusWidget // 0x0008 (0x0008 - 0x0000) struct SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget final { public: class UWidget* ReturnValue; // 0x0000(0x0008)(Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; static_assert(alignof(SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget) == 0x000008, "Wrong alignment on SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget"); static_assert(sizeof(SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget) == 0x000008, "Wrong size on SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget"); static_assert(offsetof(SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget, ReturnValue) == 0x000000, "Member 'SettingsListEntry_Action_C_GetPrimaryGamepadFocusWidget::ReturnValue' has a wrong offset!"); }
0
0.896958
1
0.896958
game-dev
MEDIA
0.659592
game-dev
0.705165
1
0.705165
oot-pc-port/oot-pc-port
24,411
asm/non_matchings/overlays/actors/ovl_En_Syateki_Niw/func_80B11E78.s
glabel func_80B11E78 /* 00588 80B11E78 27BDFF78 */ addiu $sp, $sp, 0xFF78 ## $sp = FFFFFF78 /* 0058C 80B11E7C 3C0F80B1 */ lui $t7, %hi(D_80B13698) ## $t7 = 80B10000 /* 00590 80B11E80 AFBF0034 */ sw $ra, 0x0034($sp) /* 00594 80B11E84 AFB00030 */ sw $s0, 0x0030($sp) /* 00598 80B11E88 AFA5008C */ sw $a1, 0x008C($sp) /* 0059C 80B11E8C 25EF3698 */ addiu $t7, $t7, %lo(D_80B13698) ## $t7 = 80B13698 /* 005A0 80B11E90 8DF90000 */ lw $t9, 0x0000($t7) ## 80B13698 /* 005A4 80B11E94 27AE007C */ addiu $t6, $sp, 0x007C ## $t6 = FFFFFFF4 /* 005A8 80B11E98 8DF80004 */ lw $t8, 0x0004($t7) ## 80B1369C /* 005AC 80B11E9C ADD90000 */ sw $t9, 0x0000($t6) ## FFFFFFF4 /* 005B0 80B11EA0 8DF90008 */ lw $t9, 0x0008($t7) ## 80B136A0 /* 005B4 80B11EA4 3C0980B1 */ lui $t1, %hi(D_80B136A4) ## $t1 = 80B10000 /* 005B8 80B11EA8 252936A4 */ addiu $t1, $t1, %lo(D_80B136A4) ## $t1 = 80B136A4 /* 005BC 80B11EAC ADD80004 */ sw $t8, 0x0004($t6) ## FFFFFFF8 /* 005C0 80B11EB0 ADD90008 */ sw $t9, 0x0008($t6) ## FFFFFFFC /* 005C4 80B11EB4 8D2B0000 */ lw $t3, 0x0000($t1) ## 80B136A4 /* 005C8 80B11EB8 27A80070 */ addiu $t0, $sp, 0x0070 ## $t0 = FFFFFFE8 /* 005CC 80B11EBC 8D2A0004 */ lw $t2, 0x0004($t1) ## 80B136A8 /* 005D0 80B11EC0 AD0B0000 */ sw $t3, 0x0000($t0) ## FFFFFFE8 /* 005D4 80B11EC4 8D2B0008 */ lw $t3, 0x0008($t1) ## 80B136AC /* 005D8 80B11EC8 AD0A0004 */ sw $t2, 0x0004($t0) ## FFFFFFEC /* 005DC 80B11ECC 3C0C80B1 */ lui $t4, %hi(D_80B136B0) ## $t4 = 80B10000 /* 005E0 80B11ED0 AD0B0008 */ sw $t3, 0x0008($t0) ## FFFFFFF0 /* 005E4 80B11ED4 3C0D80B1 */ lui $t5, %hi(D_80B136B4) ## $t5 = 80B10000 /* 005E8 80B11ED8 8D8C36B0 */ lw $t4, %lo(D_80B136B0)($t4) /* 005EC 80B11EDC 8DAD36B4 */ lw $t5, %lo(D_80B136B4)($t5) /* 005F0 80B11EE0 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 005F4 80B11EE4 AFAC006C */ sw $t4, 0x006C($sp) /* 005F8 80B11EE8 AFAD0068 */ sw $t5, 0x0068($sp) /* 005FC 80B11EEC 848E029C */ lh $t6, 0x029C($a0) ## 0000029C /* 00600 80B11EF0 51C0000E */ beql $t6, $zero, .L80B11F2C /* 00604 80B11EF4 A7A0004A */ sh $zero, 0x004A($sp) /* 00608 80B11EF8 848F029E */ lh $t7, 0x029E($a0) ## 0000029E /* 0060C 80B11EFC 55E0000B */ bnel $t7, $zero, .L80B11F2C /* 00610 80B11F00 A7A0004A */ sh $zero, 0x004A($sp) /* 00614 80B11F04 94980088 */ lhu $t8, 0x0088($a0) ## 00000088 /* 00618 80B11F08 3C0880B1 */ lui $t0, %hi(func_80B123A8) ## $t0 = 80B10000 /* 0061C 80B11F0C 250823A8 */ addiu $t0, $t0, %lo(func_80B123A8) ## $t0 = 80B123A8 /* 00620 80B11F10 33190001 */ andi $t9, $t8, 0x0001 ## $t9 = 00000000 /* 00624 80B11F14 53200005 */ beql $t9, $zero, .L80B11F2C /* 00628 80B11F18 A7A0004A */ sh $zero, 0x004A($sp) /* 0062C 80B11F1C A480029C */ sh $zero, 0x029C($a0) ## 0000029C /* 00630 80B11F20 1000011C */ beq $zero, $zero, .L80B12394 /* 00634 80B11F24 AC880250 */ sw $t0, 0x0250($a0) ## 00000250 /* 00638 80B11F28 A7A0004A */ sh $zero, 0x004A($sp) .L80B11F2C: /* 0063C 80B11F2C 8609025E */ lh $t1, 0x025E($s0) ## 0000025E /* 00640 80B11F30 5520009F */ bnel $t1, $zero, .L80B121B0 /* 00644 80B11F34 860D025C */ lh $t5, 0x025C($s0) ## 0000025C /* 00648 80B11F38 860A025C */ lh $t2, 0x025C($s0) ## 0000025C /* 0064C 80B11F3C 5540009C */ bnel $t2, $zero, .L80B121B0 /* 00650 80B11F40 860D025C */ lh $t5, 0x025C($s0) ## 0000025C /* 00654 80B11F44 860B0294 */ lh $t3, 0x0294($s0) ## 00000294 /* 00658 80B11F48 256C0001 */ addiu $t4, $t3, 0x0001 ## $t4 = 00000001 /* 0065C 80B11F4C A60C0294 */ sh $t4, 0x0294($s0) ## 00000294 /* 00660 80B11F50 860D0294 */ lh $t5, 0x0294($s0) ## 00000294 /* 00664 80B11F54 29A10008 */ slti $at, $t5, 0x0008 /* 00668 80B11F58 1420007A */ bne $at, $zero, .L80B12144 /* 0066C 80B11F5C 3C0141F0 */ lui $at, 0x41F0 ## $at = 41F00000 /* 00670 80B11F60 44816000 */ mtc1 $at, $f12 ## $f12 = 30.00 /* 00674 80B11F64 0C00CFBE */ jal Math_Rand_ZeroFloat /* 00678 80B11F68 00000000 */ nop /* 0067C 80B11F6C 4600010D */ trunc.w.s $f4, $f0 /* 00680 80B11F70 3C0180B1 */ lui $at, %hi(D_80B137CC) ## $at = 80B10000 /* 00684 80B11F74 440F2000 */ mfc1 $t7, $f4 /* 00688 80B11F78 00000000 */ nop /* 0068C 80B11F7C A60F025E */ sh $t7, 0x025E($s0) ## 0000025E /* 00690 80B11F80 0C00CFBE */ jal Math_Rand_ZeroFloat /* 00694 80B11F84 C42C37CC */ lwc1 $f12, %lo(D_80B137CC)($at) /* 00698 80B11F88 4600018D */ trunc.w.s $f6, $f0 /* 0069C 80B11F8C 8602029E */ lh $v0, 0x029E($s0) ## 0000029E /* 006A0 80B11F90 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 006A4 80B11F94 44193000 */ mfc1 $t9, $f6 /* 006A8 80B11F98 10400006 */ beq $v0, $zero, .L80B11FB4 /* 006AC 80B11F9C A6190294 */ sh $t9, 0x0294($s0) ## 00000294 /* 006B0 80B11FA0 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001 /* 006B4 80B11FA4 50410042 */ beql $v0, $at, .L80B120B0 /* 006B8 80B11FA8 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 006BC 80B11FAC 10000080 */ beq $zero, $zero, .L80B121B0 /* 006C0 80B11FB0 860D025C */ lh $t5, 0x025C($s0) ## 0000025C .L80B11FB4: /* 006C4 80B11FB4 44816000 */ mtc1 $at, $f12 ## $f12 = 50.00 /* 006C8 80B11FB8 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 006CC 80B11FBC 00000000 */ nop /* 006D0 80B11FC0 44804000 */ mtc1 $zero, $f8 ## $f8 = 0.00 /* 006D4 80B11FC4 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 006D8 80B11FC8 44816000 */ mtc1 $at, $f12 ## $f12 = 100.00 /* 006DC 80B11FCC 4608003C */ c.lt.s $f0, $f8 /* 006E0 80B11FD0 00000000 */ nop /* 006E4 80B11FD4 45020004 */ bc1fl .L80B11FE8 /* 006E8 80B11FD8 460C0380 */ add.s $f14, $f0, $f12 /* 006EC 80B11FDC 10000002 */ beq $zero, $zero, .L80B11FE8 /* 006F0 80B11FE0 460C0381 */ sub.s $f14, $f0, $f12 /* 006F4 80B11FE4 460C0380 */ add.s $f14, $f0, $f12 .L80B11FE8: /* 006F8 80B11FE8 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 006FC 80B11FEC E7AE0050 */ swc1 $f14, 0x0050($sp) /* 00700 80B11FF0 44805000 */ mtc1 $zero, $f10 ## $f10 = 0.00 /* 00704 80B11FF4 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 00708 80B11FF8 44816000 */ mtc1 $at, $f12 ## $f12 = 100.00 /* 0070C 80B11FFC 460A003C */ c.lt.s $f0, $f10 /* 00710 80B12000 C7AE0050 */ lwc1 $f14, 0x0050($sp) /* 00714 80B12004 45020004 */ bc1fl .L80B12018 /* 00718 80B12008 460C0080 */ add.s $f2, $f0, $f12 /* 0071C 80B1200C 10000002 */ beq $zero, $zero, .L80B12018 /* 00720 80B12010 460C0081 */ sub.s $f2, $f0, $f12 /* 00724 80B12014 460C0080 */ add.s $f2, $f0, $f12 .L80B12018: /* 00728 80B12018 C61002DC */ lwc1 $f16, 0x02DC($s0) ## 000002DC /* 0072C 80B1201C 3C01C316 */ lui $at, 0xC316 ## $at = C3160000 /* 00730 80B12020 44816000 */ mtc1 $at, $f12 ## $f12 = -150.00 /* 00734 80B12024 460E8000 */ add.s $f0, $f16, $f14 /* 00738 80B12028 C61202E4 */ lwc1 $f18, 0x02E4($s0) ## 000002E4 /* 0073C 80B1202C 3C014316 */ lui $at, 0x4316 ## $at = 43160000 /* 00740 80B12030 460C003C */ c.lt.s $f0, $f12 /* 00744 80B12034 E60002E8 */ swc1 $f0, 0x02E8($s0) ## 000002E8 /* 00748 80B12038 46029100 */ add.s $f4, $f18, $f2 /* 0074C 80B1203C 44810000 */ mtc1 $at, $f0 ## $f0 = 150.00 /* 00750 80B12040 3C01C270 */ lui $at, 0xC270 ## $at = C2700000 /* 00754 80B12044 45000002 */ bc1f .L80B12050 /* 00758 80B12048 E60402F0 */ swc1 $f4, 0x02F0($s0) ## 000002F0 /* 0075C 80B1204C E60C02E8 */ swc1 $f12, 0x02E8($s0) ## 000002E8 .L80B12050: /* 00760 80B12050 C60602E8 */ lwc1 $f6, 0x02E8($s0) ## 000002E8 /* 00764 80B12054 44811000 */ mtc1 $at, $f2 ## $f2 = -60.00 /* 00768 80B12058 3C01C220 */ lui $at, 0xC220 ## $at = C2200000 /* 0076C 80B1205C 4606003C */ c.lt.s $f0, $f6 /* 00770 80B12060 00000000 */ nop /* 00774 80B12064 45020003 */ bc1fl .L80B12074 /* 00778 80B12068 C60002F0 */ lwc1 $f0, 0x02F0($s0) ## 000002F0 /* 0077C 80B1206C E60002E8 */ swc1 $f0, 0x02E8($s0) ## 000002E8 /* 00780 80B12070 C60002F0 */ lwc1 $f0, 0x02F0($s0) ## 000002F0 .L80B12074: /* 00784 80B12074 4602003C */ c.lt.s $f0, $f2 /* 00788 80B12078 00000000 */ nop /* 0078C 80B1207C 45020004 */ bc1fl .L80B12090 /* 00790 80B12080 44811000 */ mtc1 $at, $f2 ## $f2 = -40.00 /* 00794 80B12084 E60202F0 */ swc1 $f2, 0x02F0($s0) ## 000002F0 /* 00798 80B12088 C60002F0 */ lwc1 $f0, 0x02F0($s0) ## 000002F0 /* 0079C 80B1208C 44811000 */ mtc1 $at, $f2 ## $f2 = -40.00 .L80B12090: /* 007A0 80B12090 00000000 */ nop /* 007A4 80B12094 4600103C */ c.lt.s $f2, $f0 /* 007A8 80B12098 00000000 */ nop /* 007AC 80B1209C 45020044 */ bc1fl .L80B121B0 /* 007B0 80B120A0 860D025C */ lh $t5, 0x025C($s0) ## 0000025C /* 007B4 80B120A4 10000041 */ beq $zero, $zero, .L80B121AC /* 007B8 80B120A8 E60202F0 */ swc1 $f2, 0x02F0($s0) ## 000002F0 /* 007BC 80B120AC 3C014248 */ lui $at, 0x4248 ## $at = 42480000 .L80B120B0: /* 007C0 80B120B0 44816000 */ mtc1 $at, $f12 ## $f12 = 50.00 /* 007C4 80B120B4 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 007C8 80B120B8 00000000 */ nop /* 007CC 80B120BC 44804000 */ mtc1 $zero, $f8 ## $f8 = 0.00 /* 007D0 80B120C0 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 007D4 80B120C4 44811000 */ mtc1 $at, $f2 ## $f2 = 50.00 /* 007D8 80B120C8 4608003C */ c.lt.s $f0, $f8 /* 007DC 80B120CC 3C0141F0 */ lui $at, 0x41F0 ## $at = 41F00000 /* 007E0 80B120D0 44816000 */ mtc1 $at, $f12 ## $f12 = 30.00 /* 007E4 80B120D4 45020004 */ bc1fl .L80B120E8 /* 007E8 80B120D8 46020380 */ add.s $f14, $f0, $f2 /* 007EC 80B120DC 10000002 */ beq $zero, $zero, .L80B120E8 /* 007F0 80B120E0 46020381 */ sub.s $f14, $f0, $f2 /* 007F4 80B120E4 46020380 */ add.s $f14, $f0, $f2 .L80B120E8: /* 007F8 80B120E8 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 007FC 80B120EC E7AE0050 */ swc1 $f14, 0x0050($sp) /* 00800 80B120F0 44805000 */ mtc1 $zero, $f10 ## $f10 = 0.00 /* 00804 80B120F4 C7AE0050 */ lwc1 $f14, 0x0050($sp) /* 00808 80B120F8 3C0141F0 */ lui $at, 0x41F0 ## $at = 41F00000 /* 0080C 80B120FC 460A003C */ c.lt.s $f0, $f10 /* 00810 80B12100 00000000 */ nop /* 00814 80B12104 45020006 */ bc1fl .L80B12120 /* 00818 80B12108 44819000 */ mtc1 $at, $f18 ## $f18 = 30.00 /* 0081C 80B1210C 3C0141F0 */ lui $at, 0x41F0 ## $at = 41F00000 /* 00820 80B12110 44818000 */ mtc1 $at, $f16 ## $f16 = 30.00 /* 00824 80B12114 10000004 */ beq $zero, $zero, .L80B12128 /* 00828 80B12118 46100081 */ sub.s $f2, $f0, $f16 /* 0082C 80B1211C 44819000 */ mtc1 $at, $f18 ## $f18 = 30.00 .L80B12120: /* 00830 80B12120 00000000 */ nop /* 00834 80B12124 46120080 */ add.s $f2, $f0, $f18 .L80B12128: /* 00838 80B12128 C60402DC */ lwc1 $f4, 0x02DC($s0) ## 000002DC /* 0083C 80B1212C C60802E4 */ lwc1 $f8, 0x02E4($s0) ## 000002E4 /* 00840 80B12130 460E2180 */ add.s $f6, $f4, $f14 /* 00844 80B12134 46024280 */ add.s $f10, $f8, $f2 /* 00848 80B12138 E60602E8 */ swc1 $f6, 0x02E8($s0) ## 000002E8 /* 0084C 80B1213C 1000001B */ beq $zero, $zero, .L80B121AC /* 00850 80B12140 E60A02F0 */ swc1 $f10, 0x02F0($s0) ## 000002F0 .L80B12144: /* 00854 80B12144 96090088 */ lhu $t1, 0x0088($s0) ## 00000088 /* 00858 80B12148 24080004 */ addiu $t0, $zero, 0x0004 ## $t0 = 00000004 /* 0085C 80B1214C A608025C */ sh $t0, 0x025C($s0) ## 0000025C /* 00860 80B12150 312A0001 */ andi $t2, $t1, 0x0001 ## $t2 = 00000000 /* 00864 80B12154 11400015 */ beq $t2, $zero, .L80B121AC /* 00868 80B12158 3C014020 */ lui $at, 0x4020 ## $at = 40200000 /* 0086C 80B1215C 44818000 */ mtc1 $at, $f16 ## $f16 = 2.50 /* 00870 80B12160 3C014120 */ lui $at, 0x4120 ## $at = 41200000 /* 00874 80B12164 44816000 */ mtc1 $at, $f12 ## $f12 = 10.00 /* 00878 80B12168 0C00CFBE */ jal Math_Rand_ZeroFloat /* 0087C 80B1216C E6100060 */ swc1 $f16, 0x0060($s0) ## 00000060 /* 00880 80B12170 3C013F80 */ lui $at, 0x3F80 ## $at = 3F800000 /* 00884 80B12174 44819000 */ mtc1 $at, $f18 ## $f18 = 1.00 /* 00888 80B12178 00000000 */ nop /* 0088C 80B1217C 4612003C */ c.lt.s $f0, $f18 /* 00890 80B12180 00000000 */ nop /* 00894 80B12184 4502000A */ bc1fl .L80B121B0 /* 00898 80B12188 860D025C */ lh $t5, 0x025C($s0) ## 0000025C /* 0089C 80B1218C 860B029E */ lh $t3, 0x029E($s0) ## 0000029E /* 008A0 80B12190 3C014120 */ lui $at, 0x4120 ## $at = 41200000 /* 008A4 80B12194 55600006 */ bnel $t3, $zero, .L80B121B0 /* 008A8 80B12198 860D025C */ lh $t5, 0x025C($s0) ## 0000025C /* 008AC 80B1219C 44812000 */ mtc1 $at, $f4 ## $f4 = 10.00 /* 008B0 80B121A0 240C000C */ addiu $t4, $zero, 0x000C ## $t4 = 0000000C /* 008B4 80B121A4 A60C025C */ sh $t4, 0x025C($s0) ## 0000025C /* 008B8 80B121A8 E6040060 */ swc1 $f4, 0x0060($s0) ## 00000060 .L80B121AC: /* 008BC 80B121AC 860D025C */ lh $t5, 0x025C($s0) ## 0000025C .L80B121B0: /* 008C0 80B121B0 240E0001 */ addiu $t6, $zero, 0x0001 ## $t6 = 00000001 /* 008C4 80B121B4 26040024 */ addiu $a0, $s0, 0x0024 ## $a0 = 00000024 /* 008C8 80B121B8 11A00048 */ beq $t5, $zero, .L80B122DC /* 008CC 80B121BC 3C063F80 */ lui $a2, 0x3F80 ## $a2 = 3F800000 /* 008D0 80B121C0 A7AE004A */ sh $t6, 0x004A($sp) /* 008D4 80B121C4 8E0702CC */ lw $a3, 0x02CC($s0) ## 000002CC /* 008D8 80B121C8 0C01E107 */ jal Math_SmoothScaleMaxF /* 008DC 80B121CC 8E0502E8 */ lw $a1, 0x02E8($s0) ## 000002E8 /* 008E0 80B121D0 2604002C */ addiu $a0, $s0, 0x002C ## $a0 = 0000002C /* 008E4 80B121D4 8E0502F0 */ lw $a1, 0x02F0($s0) ## 000002F0 /* 008E8 80B121D8 3C063F80 */ lui $a2, 0x3F80 ## $a2 = 3F800000 /* 008EC 80B121DC 0C01E107 */ jal Math_SmoothScaleMaxF /* 008F0 80B121E0 8E0702CC */ lw $a3, 0x02CC($s0) ## 000002CC /* 008F4 80B121E4 3C073E99 */ lui $a3, 0x3E99 ## $a3 = 3E990000 /* 008F8 80B121E8 34E7999A */ ori $a3, $a3, 0x999A ## $a3 = 3E99999A /* 008FC 80B121EC 260402CC */ addiu $a0, $s0, 0x02CC ## $a0 = 000002CC /* 00900 80B121F0 3C054040 */ lui $a1, 0x4040 ## $a1 = 40400000 /* 00904 80B121F4 0C01E107 */ jal Math_SmoothScaleMaxF /* 00908 80B121F8 3C063F80 */ lui $a2, 0x3F80 ## $a2 = 3F800000 /* 0090C 80B121FC C60602E8 */ lwc1 $f6, 0x02E8($s0) ## 000002E8 /* 00910 80B12200 C6080024 */ lwc1 $f8, 0x0024($s0) ## 00000024 /* 00914 80B12204 3C014120 */ lui $at, 0x4120 ## $at = 41200000 /* 00918 80B12208 44811000 */ mtc1 $at, $f2 ## $f2 = 10.00 /* 0091C 80B1220C 46083301 */ sub.s $f12, $f6, $f8 /* 00920 80B12210 C60A02F0 */ lwc1 $f10, 0x02F0($s0) ## 000002F0 /* 00924 80B12214 C610002C */ lwc1 $f16, 0x002C($s0) ## 0000002C /* 00928 80B12218 46006005 */ abs.s $f0, $f12 /* 0092C 80B1221C 46105381 */ sub.s $f14, $f10, $f16 /* 00930 80B12220 4602003C */ c.lt.s $f0, $f2 /* 00934 80B12224 46007005 */ abs.s $f0, $f14 /* 00938 80B12228 45020004 */ bc1fl .L80B1223C /* 0093C 80B1222C 4602003C */ c.lt.s $f0, $f2 /* 00940 80B12230 44806000 */ mtc1 $zero, $f12 ## $f12 = 0.00 /* 00944 80B12234 00000000 */ nop /* 00948 80B12238 4602003C */ c.lt.s $f0, $f2 .L80B1223C: /* 0094C 80B1223C 44800000 */ mtc1 $zero, $f0 ## $f0 = 0.00 /* 00950 80B12240 45020004 */ bc1fl .L80B12254 /* 00954 80B12244 46006032 */ c.eq.s $f12, $f0 /* 00958 80B12248 44807000 */ mtc1 $zero, $f14 ## $f14 = 0.00 /* 0095C 80B1224C 00000000 */ nop /* 00960 80B12250 46006032 */ c.eq.s $f12, $f0 .L80B12254: /* 00964 80B12254 00000000 */ nop /* 00968 80B12258 45000007 */ bc1f .L80B12278 /* 0096C 80B1225C 00000000 */ nop /* 00970 80B12260 46007032 */ c.eq.s $f14, $f0 /* 00974 80B12264 240F0007 */ addiu $t7, $zero, 0x0007 ## $t7 = 00000007 /* 00978 80B12268 45000003 */ bc1f .L80B12278 /* 0097C 80B1226C 00000000 */ nop /* 00980 80B12270 A600025C */ sh $zero, 0x025C($s0) ## 0000025C /* 00984 80B12274 A60F0294 */ sh $t7, 0x0294($s0) ## 00000294 .L80B12278: /* 00988 80B12278 0C03F494 */ jal func_800FD250 /* 0098C 80B1227C 00000000 */ nop /* 00990 80B12280 3C0180B1 */ lui $at, %hi(D_80B137D0) ## $at = 80B10000 /* 00994 80B12284 C43237D0 */ lwc1 $f18, %lo(D_80B137D0)($at) /* 00998 80B12288 C60802D0 */ lwc1 $f8, 0x02D0($s0) ## 000002D0 /* 0099C 80B1228C AFA00010 */ sw $zero, 0x0010($sp) /* 009A0 80B12290 46120102 */ mul.s $f4, $f0, $f18 /* 009A4 80B12294 4600428D */ trunc.w.s $f10, $f8 /* 009A8 80B12298 26040032 */ addiu $a0, $s0, 0x0032 ## $a0 = 00000032 /* 009AC 80B1229C 24060003 */ addiu $a2, $zero, 0x0003 ## $a2 = 00000003 /* 009B0 80B122A0 44075000 */ mfc1 $a3, $f10 /* 009B4 80B122A4 4600218D */ trunc.w.s $f6, $f4 /* 009B8 80B122A8 00073C00 */ sll $a3, $a3, 16 /* 009BC 80B122AC 00073C03 */ sra $a3, $a3, 16 /* 009C0 80B122B0 44053000 */ mfc1 $a1, $f6 /* 009C4 80B122B4 00000000 */ nop /* 009C8 80B122B8 00052C00 */ sll $a1, $a1, 16 /* 009CC 80B122BC 0C01E1A7 */ jal Math_SmoothScaleMaxMinS /* 009D0 80B122C0 00052C03 */ sra $a1, $a1, 16 /* 009D4 80B122C4 3C05461C */ lui $a1, 0x461C ## $a1 = 461C0000 /* 009D8 80B122C8 34A54000 */ ori $a1, $a1, 0x4000 ## $a1 = 461C4000 /* 009DC 80B122CC 260402D0 */ addiu $a0, $s0, 0x02D0 ## $a0 = 000002D0 /* 009E0 80B122D0 3C063F80 */ lui $a2, 0x3F80 ## $a2 = 3F800000 /* 009E4 80B122D4 0C01E107 */ jal Math_SmoothScaleMaxF /* 009E8 80B122D8 3C07447A */ lui $a3, 0x447A ## $a3 = 447A0000 .L80B122DC: /* 009EC 80B122DC 86080260 */ lh $t0, 0x0260($s0) ## 00000260 /* 009F0 80B122E0 8FA9008C */ lw $t1, 0x008C($sp) /* 009F4 80B122E4 3C0A0001 */ lui $t2, 0x0001 ## $t2 = 00010000 /* 009F8 80B122E8 15000007 */ bne $t0, $zero, .L80B12308 /* 009FC 80B122EC 01495021 */ addu $t2, $t2, $t1 /* 00A00 80B122F0 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 00A04 80B122F4 8FA5008C */ lw $a1, 0x008C($sp) /* 00A08 80B122F8 0C2C46A5 */ jal func_80B11A94 /* 00A0C 80B122FC 87A6004A */ lh $a2, 0x004A($sp) /* 00A10 80B12300 10000025 */ beq $zero, $zero, .L80B12398 /* 00A14 80B12304 8FBF0034 */ lw $ra, 0x0034($sp) .L80B12308: /* 00A18 80B12308 8D4A1DE4 */ lw $t2, 0x1DE4($t2) ## 00001DE4 /* 00A1C 80B1230C 3C0140A0 */ lui $at, 0x40A0 ## $at = 40A00000 /* 00A20 80B12310 260C0024 */ addiu $t4, $s0, 0x0024 ## $t4 = 00000024 /* 00A24 80B12314 314B0003 */ andi $t3, $t2, 0x0003 ## $t3 = 00000000 /* 00A28 80B12318 5560001F */ bnel $t3, $zero, .L80B12398 /* 00A2C 80B1231C 8FBF0034 */ lw $ra, 0x0034($sp) /* 00A30 80B12320 44816000 */ mtc1 $at, $f12 ## $f12 = 5.00 /* 00A34 80B12324 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 00A38 80B12328 AFAC003C */ sw $t4, 0x003C($sp) /* 00A3C 80B1232C 3C0180B1 */ lui $at, %hi(D_80B137D4) ## $at = 80B10000 /* 00A40 80B12330 C43037D4 */ lwc1 $f16, %lo(D_80B137D4)($at) /* 00A44 80B12334 8FAD003C */ lw $t5, 0x003C($sp) /* 00A48 80B12338 E7A00080 */ swc1 $f0, 0x0080($sp) /* 00A4C 80B1233C E7B00074 */ swc1 $f16, 0x0074($sp) /* 00A50 80B12340 8DAF0000 */ lw $t7, 0x0000($t5) ## 00000000 /* 00A54 80B12344 27A5005C */ addiu $a1, $sp, 0x005C ## $a1 = FFFFFFD4 /* 00A58 80B12348 27B8006C */ addiu $t8, $sp, 0x006C ## $t8 = FFFFFFE4 /* 00A5C 80B1234C ACAF0000 */ sw $t7, 0x0000($a1) ## FFFFFFD4 /* 00A60 80B12350 8DAE0004 */ lw $t6, 0x0004($t5) ## 00000004 /* 00A64 80B12354 27B90068 */ addiu $t9, $sp, 0x0068 ## $t9 = FFFFFFE0 /* 00A68 80B12358 24080258 */ addiu $t0, $zero, 0x0258 ## $t0 = 00000258 /* 00A6C 80B1235C ACAE0004 */ sw $t6, 0x0004($a1) ## FFFFFFD8 /* 00A70 80B12360 8DAF0008 */ lw $t7, 0x0008($t5) ## 00000008 /* 00A74 80B12364 24090028 */ addiu $t1, $zero, 0x0028 ## $t1 = 00000028 /* 00A78 80B12368 240A001E */ addiu $t2, $zero, 0x001E ## $t2 = 0000001E /* 00A7C 80B1236C ACAF0008 */ sw $t7, 0x0008($a1) ## FFFFFFDC /* 00A80 80B12370 AFAA0020 */ sw $t2, 0x0020($sp) /* 00A84 80B12374 AFA9001C */ sw $t1, 0x001C($sp) /* 00A88 80B12378 AFA80018 */ sw $t0, 0x0018($sp) /* 00A8C 80B1237C AFB90014 */ sw $t9, 0x0014($sp) /* 00A90 80B12380 AFB80010 */ sw $t8, 0x0010($sp) /* 00A94 80B12384 8FA4008C */ lw $a0, 0x008C($sp) /* 00A98 80B12388 27A6007C */ addiu $a2, $sp, 0x007C ## $a2 = FFFFFFF4 /* 00A9C 80B1238C 0C00A0DB */ jal func_8002836C /* 00AA0 80B12390 27A70070 */ addiu $a3, $sp, 0x0070 ## $a3 = FFFFFFE8 .L80B12394: /* 00AA4 80B12394 8FBF0034 */ lw $ra, 0x0034($sp) .L80B12398: /* 00AA8 80B12398 8FB00030 */ lw $s0, 0x0030($sp) /* 00AAC 80B1239C 27BD0088 */ addiu $sp, $sp, 0x0088 ## $sp = 00000000 /* 00AB0 80B123A0 03E00008 */ jr $ra /* 00AB4 80B123A4 00000000 */ nop
0
0.706101
1
0.706101
game-dev
MEDIA
0.905752
game-dev
0.674457
1
0.674457
SkytAsul/BeautyQuests
1,909
v1_19_R3/src/main/java/fr/skytasul/quests/utils/nms/v1_19_R3.java
package fr.skytasul.quests.utils.nms; import java.util.List; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import net.minecraft.core.Holder.Reference; import net.minecraft.core.HolderLookup.RegistryLookup; import net.minecraft.core.registries.Registries; import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.world.InteractionHand; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.Property; public class v1_19_R3 extends NMS{ @Override public void openBookInHand(Player p) { ClientboundOpenBookPacket packet = new ClientboundOpenBookPacket(InteractionHand.MAIN_HAND); ((CraftPlayer) p).getHandle().connection.send(packet); } @Override public double entityNameplateHeight(Entity en) { return en.getHeight(); } @Override public List<String> getAvailableBlockProperties(Material material) { RegistryLookup<Block> blockRegistry = MinecraftServer.getServer().registryAccess().lookupOrThrow(Registries.BLOCK); Reference<Block> block = blockRegistry .getOrThrow(ResourceKey.create(Registries.BLOCK, new ResourceLocation(material.getKey().getKey()))); StateDefinition<Block, BlockState> stateList = block.value().getStateDefinition(); return stateList.getProperties().stream().map(Property::getName).toList(); } @Override public List<String> getAvailableBlockTags() { return MinecraftServer.getServer().registryAccess().lookupOrThrow(Registries.BLOCK).listTags() .map(x -> x.key().location().toString()).toList(); } }
0
0.663942
1
0.663942
game-dev
MEDIA
0.994564
game-dev
0.819102
1
0.819102
magefree/mage
2,348
Mage.Sets/src/mage/cards/d/DualCasting.java
package mage.cards.d; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.ColoredManaCost; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.CopyTargetStackObjectEffect; import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.FilterSpell; import mage.filter.predicate.Predicates; import mage.target.TargetPermanent; import mage.target.TargetSpell; import mage.target.common.TargetCreaturePermanent; /** * * @author Loki */ public final class DualCasting extends CardImpl { private static final FilterSpell filter = new FilterSpell("instant or sorcery spell you control"); static { filter.add(Predicates.or( CardType.INSTANT.getPredicate(), CardType.SORCERY.getPredicate())); filter.add(TargetController.YOU.getControllerPredicate()); } public DualCasting(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{R}"); this.subtype.add(SubType.AURA); // Enchant creature TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.AddAbility)); Ability ability = new EnchantAbility(auraTarget); this.addAbility(ability); // Enchanted creature has "{R}, {tap}: Copy target instant or sorcery spell you control. You may choose new targets for the copy." ability = new SimpleActivatedAbility(new CopyTargetStackObjectEffect(), new ColoredManaCost(ColoredManaSymbol.R)); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetSpell(filter)); this.addAbility(new SimpleStaticAbility(new GainAbilityAttachedEffect(ability, AttachmentType.AURA))); } private DualCasting(final DualCasting card) { super(card); } @Override public DualCasting copy() { return new DualCasting(this); } }
0
0.943545
1
0.943545
game-dev
MEDIA
0.95712
game-dev
0.985582
1
0.985582
JoshParnell/ltheory-old
7,317
src/liblt/Game/Task/Goto.cpp
#include "../Tasks.h" #include "Component/Interior.h" #include "Component/MotionControl.h" #include "Component/Navigable.h" #include "Game/Conditions.h" #include "Game/Items.h" #include "Game/Messages.h" #include "Game/Player.h" #include "LTE/Pool.h" #include "LTE/SDFs.h" #include "LTE/StackFrame.h" #include "LTE/Debug.h" namespace { typedef Reference<struct PathNodeT> PathNode; AutoClass(Edge, PathNode, node, float, cost) Edge() {} }; AutoClassDerived(PathNodeT, RefCounted, Object, object, Position, pos, float, distance, bool, visited, Vector<Edge>, edges, PathNode, prev) POOLED_TYPE PathNodeT() {} PathNodeT(Object const& object) : object(object), pos(object->GetPos()), distance(FLT_MAX), visited(false) {} }; typedef Reference<struct PathT> Path; AutoClassDerived(PathT, RefCounted, Vector<Object>, nodes) PathT() {} }; Path Path_Create( Object const& system, Object const& start, Object const& end) { Vector<PathNode> nodes; PathNode startNode = new PathNodeT(start); PathNode endNode = new PathNodeT(end); nodes.push(startNode); nodes.push(endNode); startNode->distance = 0; /* Construct path nodes. */ { Map<ObjectID, PathNode> idMap; for (InteriorIterator it = Object_GetInteriorObjects(system); it.HasMore(); it.Advance()) { Object const& object = it.Get(); ComponentNavigable* nav = object->GetNavigable(); if (nav) { PathNode node = new PathNodeT(object); idMap[object->GetID()] = node; nodes.push(node); } } /* Connect edges. */ for (size_t i = 0; i < nodes.size(); ++i) { PathNode const& node = nodes[i]; /* Flying between nodes. */ for (size_t j = 0; j < nodes.size(); ++j) { if (i == j) continue; PathNode const& other = nodes[j]; node->edges.push(Edge(other, Length(other->pos - node->pos))); } /* Using special nodes. */ ComponentNavigable* nav = node->object->GetNavigable(); if (!nav) continue; for (size_t j = 0; j < nav->nodes.size(); ++j) { NavigableNode const& navNode = nav->nodes[j]; /* Only consider connections in the same container! */ if (navNode.dest->GetContainer() == system) node->edges.push(Edge(idMap[navNode.dest->GetID()], navNode.cost)); } } } while (nodes.size()) { /* Pick closest node. */ PathNode minNode; for (size_t i = 0; i < nodes.size(); ++i) { PathNode const& node = nodes[i]; if (!minNode || node->distance < minNode->distance) minNode = node; } if (minNode == endNode) break; nodes.remove(minNode); /* Propagate distances through edges. */ for (size_t i = 0; i < minNode->edges.size(); ++i) { Edge const& edge = minNode->edges[i]; float distance = minNode->distance + edge.cost; if (distance < edge.node->distance) { edge.node->distance = distance; edge.node->prev = minNode; } } } /* No path was found. */ if (!endNode->prev) return nullptr; Path path = new PathT; for (PathNode node = endNode; node && node != startNode; node = node->prev) path->nodes.push(node->object); return path; } AutoClass(TaskGotoInstance, Path, path, bool, flying) TaskGotoInstance() : flying(true) {} void Advance() { if (path->nodes.size()) path->nodes.pop(); } Object GetNext() const { return (path && path->nodes.size()) ? path->nodes.back() : nullptr; } void Reset() { path = nullptr; flying = true; } }; AutoClassDerived(TaskGoto, TaskT, Task_Goto_Args, args) DERIVED_TYPE_EX(TaskGoto) POOLED_TYPE TaskGoto() {} String GetName() const { return "Goto"; } Capability GetRateFactor() const { return Capability_Motion(1); } Object GetTarget() const { return args.target; } bool IsFinished(Object const& self, Data const&) const { return Condition_Nearby(self, args.target, args.distance); } void OnBegin(Object const& self, Data& data) { data = TaskGotoInstance(); } void OnMessage(Object const& self, Data& data, Data& m) { if (m.type == Type_Get<MessageWaypoint>()) { TaskGotoInstance& it = data.Convert<TaskGotoInstance>(); if (it.flying) { /* Huh?? How did I get a waypoint during flight? */ it.Reset(); return; } MessageWaypoint const& message = m.Convert<MessageWaypoint>(); while (it.path->nodes.size() && it.path->nodes.back() != message.location) it.Advance(); if (it.GetNext() == message.location) { it.Advance(); /* Check if we want to break out of the nav path. */ Object next = it.GetNext(); if (next && !message.location->GetNavigable()->ConnectsTo(next)) message.location->Send(MessageStopUsing(self)); } else { /* Bad waypoint? */ it.Reset(); return; } } else if (m.type == Type_Get<MessageEjected>()) { TaskGotoInstance& it = data.Convert<TaskGotoInstance>(); it.flying = true; } } void OnUpdate(Object const& self, float dt, Data& data) { AUTO_FRAME; TaskGotoInstance& it = data.Convert<TaskGotoInstance>(); /* If we're not in the same container, need to figure out how to get * to the other one. */ if (args.target->GetContainer() != self->GetContainer()) { /* We're in an immediate sub-container. */ if (args.target->GetContainer() == self->GetContainer()->GetContainer()) { if (self->GetContainer()->GetDockable()) self->GetContainer()->Undock(self); else { /* This case does not exist yet. It's possible that it could, * though (pocket universes, for example). */ } } else { /* This is where we will need to handle intersystem travel. */ /* CRITICAL. */ } } /* Else, we need to find the fastest way to get there in-system. */ else { if (!it.path) { it.path = Path_Create(self->GetContainer().t, self, args.target); it.flying = true; } /* Move toward the next node. */ { Object nextNode = it.GetNext(); if (nextNode) { self->Broadcast(MessageBoost()); self->GetMotionControl()->elements.push( SDF_Sphere(nextNode->GetCenter(), 1.0f)); if (Length(nextNode->GetPos() - self->GetPos()) < 512.0f) { if (nextNode->GetNavigable()) { Object target = it.path->nodes[it.path->nodes.size() - 2]; nextNode->Send(MessageStartUsing(self, target)); it.flying = false; } else { it.Advance(); } } } } } } }; } DefineFunction(Task_Goto) { return new TaskGoto(args); }
0
0.948301
1
0.948301
game-dev
MEDIA
0.228831
game-dev
0.975505
1
0.975505
Ayfri/Kore
7,628
website/src/jsMain/kotlin/io/github/ayfri/kore/website/components/index/HeroSection.kt
package io.github.ayfri.kore.website.components.index import androidx.compose.runtime.Composable import com.varabyte.kobweb.compose.css.* import io.github.ayfri.kore.website.GITHUB_LINK import io.github.ayfri.kore.website.GlobalStyle import io.github.ayfri.kore.website.components.common.CodeBlock import io.github.ayfri.kore.website.components.common.LinkButton import io.github.ayfri.kore.website.components.common.Tab import io.github.ayfri.kore.website.components.common.Tabs import io.github.ayfri.kore.website.utils.* import org.jetbrains.compose.web.css.* import org.jetbrains.compose.web.css.AlignItems import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.H1 import org.jetbrains.compose.web.dom.Section import org.jetbrains.compose.web.dom.Text // language=kotlin const val PRESENTATION_CODE = """ fun main() { val datapack = dataPack("test") { function("display_text") { tellraw(allPlayers(), textComponent("Hello World!")) } recipes { craftingShaped("enchanted_golden_apple") { pattern( "GGG", "GAG", "GGG" ) key("G", Items.GOLD_BLOCK) key("A", Items.APPLE) result(Items.ENCHANTED_GOLDEN_APPLE) } } function("tp_random_entity_to_entity") { val entityName = "test" val entity = allEntities(limitToOne = true) { name = entityName } summon(Entities.CREEPER, vec3(), nbt { this["CustomName"] = textComponent("Hello World!") }) execute { asTarget(allEntities { limit = 3 sort = Sort.RANDOM }) ifCondition { score(self(), "test") lessThan 10 } run { teleport(entity) } } } pack { description = textComponent("Datapack test for ", Color.GOLD) + text("Kore", Color.AQUA) { bold = true } } } datapack.generateZip() } """ // language=kotlin const val PRESENTATION_CODE_HELPERS = """ fun scoreboardDisplayDatapack() = dataPack("scoreboard_display") { val randomEntityUUID = randomUUID() val scoreName = "score" // use a marker entity to hold the score val scoreHolderEntity = allEntities(limitToOne = true) { nbt = nbt { putNbtCompound("data") { this["UUID"] = randomEntityUUID.uuid.toString() } } } load { ScoreboardDisplay.resetAll() // create the entity summon(EntityTypes.MARKER) { putNbtCompound("data") { this["UUID"] = randomEntityUUID.uuid.toString() } } // create the score scoreboard.objectives.add(scoreName) scoreboard.player(scoreHolderEntity) { set(scoreName, 0) } } tick { // recreate the scoreboard display each tick so that it's dynamic scoreboardDisplay("minigame") { displayName = textComponent("✪ Mini-game ✪", Color.GOLD) // some fake lines for the example appendLine("Game: Mini-game") appendLine("IP: 127.0.0.1") appendLine("Players: 10/20") appendLine("------------------") // display the score appendLine(textComponent("Score: ")) { customScoreEntity = scoreHolderEntity customScoreObjective = scoreName } emptyLine() appendLine("HyKore server 3.1.0") // hide values except the score hideValues(1..<5) hideValues(6..lines.size) } } } """ // language=kotlin const val PRESENTATION_CODE_EXTERNAL = """ data object VanillaTweaksCreate { val VANILLA_TWEAKS_SPAWN_NAMESPACE = "spawn" context(Function) fun checkX() = function(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, "check_x") context(Function) fun checkZ() = function(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, "check_z") context(Function) fun config() = function(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, "config") context(Function) fun decrementCooldown() = function(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, "decrement_cooldown") context(Function) fun decrementCooldowns() = function(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, "decrement_cooldowns") // ... context(Function) fun uninstall() = function(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, "restore_command_feedback") // Note : You could also use FunctionArgument instead, but you'll have instead to call the function explicitly. fun loadedPredicate() = PredicateArgument.invoke(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, name = "loaded") fun validSpawnLocationTag() = TagArgument.invoke(namespace = VANILLA_TWEAKS_SPAWN_NAMESPACE, name = "blocks/valid_spawn_location") } fun main() { val datapack = dataPack("vanilla_tweaks_spawn") { function("check_coordinates") { VanillaTweaksCreate.checkX() VanillaTweaksCreate.checkZ() } function("config_if_loaded") { execute { ifCondition(VanillaTweaksCreate.loadedPredicate()) run { VanillaTweaksCreate.config() } } } } } """ @Composable fun HeroSection() { Style(HeroSectionStyle) Section({ classes(HeroSectionStyle.heroSection) }) { H1({ classes(HeroSectionStyle.title) }) { Text("Rethink your datapack development experience with") Span("Kore") } P( """ Kore is a modern, open-source, and easy-to-use Kotlin library for Minecraft datapack development. You can use it to create your own Minecraft Datapacks, and without the need to write a single line of JSON or MCFunction. """.trimIndent(), HeroSectionStyle.subTitle ) Div({ classes(HeroSectionStyle.actions) }) { LinkButton("Get Started", "https://ayfri.com/articles/kore-introduction/", classes = arrayOf("primary")) LinkButton("GitHub", GITHUB_LINK) } val tabs = listOf( Tab( name = "index.kt", content = { CodeBlock(PRESENTATION_CODE.trimIndent(), "kotlin") } ), Tab( name = "customScoreboard.kt", content = { CodeBlock(PRESENTATION_CODE_HELPERS.trimIndent(), "kotlin") } ), Tab( name = "externalDatapack.kt", content = { CodeBlock(PRESENTATION_CODE_EXTERNAL.trimIndent(), "kotlin") } ), ) Tabs(tabs, className = HeroSectionStyle.tabs, contentClassName = HeroSectionStyle.tabContent) } } object HeroSectionStyle : StyleSheet() { init { smMax(child(className("code-toolbar"), type("pre"))) { fontSize(0.8.cssRem) } } val titleFontSize = 4.cssRem val heroSection by style { alignItems(AlignItems.Center) display(DisplayStyle.Flex) flexDirection(FlexDirection.Column) textAlign(TextAlign.Center) "p" style { color(GlobalStyle.altTextColor) fontSize(1.2.cssRem) } mdMax(self) { "p" style { fontSize(1.05.cssRem) marginBottom(2.cssRem) } } } val title by style { fontSize(titleFontSize) fontWeight(FontWeight.Bold) letterSpacing((-1.5).px) maxWidth(80.percent) marginY(4.cssRem) "span" style { fontWeight(FontWeight.Black) marginLeft(titleFontSize / 4) textGradient(GlobalStyle.logoLeftColor, GlobalStyle.logoRightColor) } lgMax(self) { fontSize(3.cssRem) } mdMax(self) { fontSize(2.8.cssRem) maxWidth(92.percent) } } val subTitle by style { maxWidth(85.percent) mdMax(self) { maxWidth(92.percent) } } val actions by style { display(DisplayStyle.Flex) flexDirection(FlexDirection.Row) gap(1.cssRem) "a" + className("primary") style { backgroundColor(GlobalStyle.buttonBackgroundColor) hover(self) style { backgroundColor(GlobalStyle.buttonBackgroundColorHover) } } mdMax(child(self, type("a"))) { fontSize(1.2.cssRem) } } val tabs by style { marginY(4.cssRem) height(37.5.cssRem) width(60.percent) xlMax(self) { height(32.cssRem) width(85.percent) } mdMax(self) { height(35.cssRem) width(90.percent) } } val tabContent by style { backgroundColor(GlobalStyle.secondaryBackgroundColor) height(100.percent) width(100.percent) } }
0
0.934799
1
0.934799
game-dev
MEDIA
0.877678
game-dev
0.969075
1
0.969075
gedoor/MyBookshelf
1,018
app/src/main/java/com/kunfei/bookshelf/utils/FileStack.java
package com.kunfei.bookshelf.utils; import java.io.File; import java.util.List; /** * Created by newbiechen on 17-5-28. */ public class FileStack { private Node node = null; private int count = 0; public void push(FileSnapshot fileSnapshot) { if (fileSnapshot == null) return; Node fileNode = new Node(); fileNode.fileSnapshot = fileSnapshot; fileNode.next = node; node = fileNode; ++count; } public FileSnapshot pop() { Node fileNode = node; if (fileNode == null) return null; FileSnapshot fileSnapshot = fileNode.fileSnapshot; node = fileNode.next; --count; return fileSnapshot; } public int getSize() { return count; } //文件快照 public static class FileSnapshot { public String filePath; public List<File> files; public int scrollOffset; } //节点 public class Node { FileSnapshot fileSnapshot; Node next; } }
0
0.658555
1
0.658555
game-dev
MEDIA
0.544882
game-dev
0.587364
1
0.587364
ImLegiitXD/Ambient
4,949
src/main/java/net/minecraft/item/crafting/FurnaceRecipes.java
package net.minecraft.item.crafting; import com.google.common.collect.Maps; import net.minecraft.block.Block; import net.minecraft.block.BlockStoneBrick; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemFishFood; import net.minecraft.item.ItemStack; import java.util.Map; import java.util.Map.Entry; public class FurnaceRecipes { private static final FurnaceRecipes smeltingBase = new FurnaceRecipes(); private final Map<ItemStack, ItemStack> smeltingList = Maps.newHashMap(); private final Map<ItemStack, Float> experienceList = Maps.newHashMap(); public static FurnaceRecipes instance() { return smeltingBase; } private FurnaceRecipes() { this.addSmeltingRecipeForBlock(Blocks.iron_ore, new ItemStack(Items.iron_ingot), 0.7F); this.addSmeltingRecipeForBlock(Blocks.gold_ore, new ItemStack(Items.gold_ingot), 1.0F); this.addSmeltingRecipeForBlock(Blocks.diamond_ore, new ItemStack(Items.diamond), 1.0F); this.addSmeltingRecipeForBlock(Blocks.sand, new ItemStack(Blocks.glass), 0.1F); this.addSmelting(Items.porkchop, new ItemStack(Items.cooked_porkchop), 0.35F); this.addSmelting(Items.beef, new ItemStack(Items.cooked_beef), 0.35F); this.addSmelting(Items.chicken, new ItemStack(Items.cooked_chicken), 0.35F); this.addSmelting(Items.rabbit, new ItemStack(Items.cooked_rabbit), 0.35F); this.addSmelting(Items.mutton, new ItemStack(Items.cooked_mutton), 0.35F); this.addSmeltingRecipeForBlock(Blocks.cobblestone, new ItemStack(Blocks.stone), 0.1F); this.addSmeltingRecipe(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.DEFAULT_META), new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.CRACKED_META), 0.1F); this.addSmelting(Items.clay_ball, new ItemStack(Items.brick), 0.3F); this.addSmeltingRecipeForBlock(Blocks.clay, new ItemStack(Blocks.hardened_clay), 0.35F); this.addSmeltingRecipeForBlock(Blocks.cactus, new ItemStack(Items.dye, 1, EnumDyeColor.GREEN.getDyeDamage()), 0.2F); this.addSmeltingRecipeForBlock(Blocks.log, new ItemStack(Items.coal, 1, 1), 0.15F); this.addSmeltingRecipeForBlock(Blocks.log2, new ItemStack(Items.coal, 1, 1), 0.15F); this.addSmeltingRecipeForBlock(Blocks.emerald_ore, new ItemStack(Items.emerald), 1.0F); this.addSmelting(Items.potato, new ItemStack(Items.baked_potato), 0.35F); this.addSmeltingRecipeForBlock(Blocks.netherrack, new ItemStack(Items.netherbrick), 0.1F); this.addSmeltingRecipe(new ItemStack(Blocks.sponge, 1, 1), new ItemStack(Blocks.sponge, 1, 0), 0.15F); for (ItemFishFood.FishType itemfishfood$fishtype : ItemFishFood.FishType.values()) { if (itemfishfood$fishtype.canCook()) { this.addSmeltingRecipe(new ItemStack(Items.fish, 1, itemfishfood$fishtype.getMetadata()), new ItemStack(Items.cooked_fish, 1, itemfishfood$fishtype.getMetadata()), 0.35F); } } this.addSmeltingRecipeForBlock(Blocks.coal_ore, new ItemStack(Items.coal), 0.1F); this.addSmeltingRecipeForBlock(Blocks.redstone_ore, new ItemStack(Items.redstone), 0.7F); this.addSmeltingRecipeForBlock(Blocks.lapis_ore, new ItemStack(Items.dye, 1, EnumDyeColor.BLUE.getDyeDamage()), 0.2F); this.addSmeltingRecipeForBlock(Blocks.quartz_ore, new ItemStack(Items.quartz), 0.2F); } public void addSmeltingRecipeForBlock(Block input, ItemStack stack, float experience) { this.addSmelting(Item.getItemFromBlock(input), stack, experience); } public void addSmelting(Item input, ItemStack stack, float experience) { this.addSmeltingRecipe(new ItemStack(input, 1, 32767), stack, experience); } public void addSmeltingRecipe(ItemStack input, ItemStack stack, float experience) { this.smeltingList.put(input, stack); this.experienceList.put(stack, experience); } public ItemStack getSmeltingResult(ItemStack stack) { for (Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) { if (this.compareItemStacks(stack, entry.getKey())) { return entry.getValue(); } } return null; } private boolean compareItemStacks(ItemStack stack1, ItemStack stack2) { return stack2.getItem() == stack1.getItem() && (stack2.getMetadata() == 32767 || stack2.getMetadata() == stack1.getMetadata()); } public Map<ItemStack, ItemStack> getSmeltingList() { return this.smeltingList; } public float getSmeltingExperience(ItemStack stack) { for (Entry<ItemStack, Float> entry : this.experienceList.entrySet()) { if (this.compareItemStacks(stack, entry.getKey())) { return entry.getValue(); } } return 0.0F; } }
0
0.626725
1
0.626725
game-dev
MEDIA
0.99973
game-dev
0.91314
1
0.91314
tcheeric/nostr-java
1,333
nostr-java-event/src/main/java/nostr/event/tag/HashtagTag.java
package nostr.event.tag; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; import nostr.base.annotation.Key; import nostr.base.annotation.Tag; import nostr.event.BaseTag; /** * @author eric */ @Builder @Data @EqualsAndHashCode(callSuper = true) @Tag(code = "t", nip = 12) @NoArgsConstructor @AllArgsConstructor public class HashtagTag extends BaseTag { @Key @JsonProperty("t") private String hashTag; public static <T extends BaseTag> T deserialize(@NonNull JsonNode node) { HashtagTag tag = new HashtagTag(); setRequiredField(node.get(1), (n, t) -> tag.setHashTag(n.asText()), tag); return (T) tag; } public static HashtagTag updateFields(@NonNull GenericTag genericTag) { if (!"t".equals(genericTag.getCode())) { throw new IllegalArgumentException("Invalid tag code for HashtagTag"); } if (genericTag.getAttributes().size() != 1) { throw new IllegalArgumentException("Invalid number of attributes for HashtagTag"); } HashtagTag tag = new HashtagTag(); tag.setHashTag(genericTag.getAttributes().get(0).value().toString()); return tag; } }
0
0.674056
1
0.674056
game-dev
MEDIA
0.621626
game-dev
0.578705
1
0.578705
11011010/BFA-Frankenstein-Core
35,657
src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp
/* * Copyright (C) 2020 BfaCore * * 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/>. */ /* ScriptData SDName: Bloodmyst_Isle SD%Complete: 80 SDComment: Quest support: 9670 SDCategory: Bloodmyst Isle EndScriptData */ /* ContentData npc_webbed_creature EndContentData */ #include "ScriptMgr.h" #include "CellImpl.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "MotionMaster.h" #include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" #include "ScriptedEscortAI.h" /*###### ## npc_webbed_creature ######*/ //possible creatures to be spawned uint32 const possibleSpawns[31] = {17322, 17661, 17496, 17522, 17340, 17352, 17333, 17524, 17654, 17348, 17339, 17345, 17359, 17353, 17336, 17550, 17330, 17701, 17321, 17325, 17320, 17683, 17342, 17715, 17334, 17341, 17338, 17337, 17346, 17344, 17327}; enum WebbedCreature { NPC_EXPEDITION_RESEARCHER = 17681 }; class npc_webbed_creature : public CreatureScript { public: npc_webbed_creature() : CreatureScript("npc_webbed_creature") { } struct npc_webbed_creatureAI : public NullCreatureAI { npc_webbed_creatureAI(Creature* creature) : NullCreatureAI(creature) { } void Reset() override { } void EnterCombat(Unit* /*who*/) override { } void AttackStart(Unit* /*who*/) override { } void MoveInLineOfSight(Unit* /*who*/) override { } void JustDied(Unit* killer) override { uint32 spawnCreatureID = 0; switch (urand(0, 2)) { case 0: if (Player* player = killer->ToPlayer()) player->KilledMonsterCredit(NPC_EXPEDITION_RESEARCHER); spawnCreatureID = NPC_EXPEDITION_RESEARCHER; break; case 1: case 2: spawnCreatureID = possibleSpawns[urand(0, 30)]; break; } me->SummonCreature(spawnCreatureID, 0.0f, 0.0f, 0.0f, me->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_webbed_creatureAI(creature); } }; /*###### ## Quest 9759: Ending Their World ######*/ enum EndingTheirWorldMisc { SAY_SIRONAS_1 = 0, SAY_LEGOSO_1 = 0, SAY_LEGOSO_2 = 1, SAY_LEGOSO_3 = 2, SAY_LEGOSO_4 = 3, SAY_LEGOSO_5 = 4, SAY_LEGOSO_6 = 5, SAY_LEGOSO_7 = 6, SAY_LEGOSO_8 = 7, SAY_LEGOSO_9 = 8, SAY_LEGOSO_10 = 9, SAY_LEGOSO_11 = 10, SAY_LEGOSO_12 = 11, SAY_LEGOSO_13 = 12, SAY_LEGOSO_14 = 13, SAY_LEGOSO_15 = 14, SAY_LEGOSO_16 = 15, SAY_LEGOSO_17 = 16, SAY_LEGOSO_18 = 17, SAY_LEGOSO_19 = 18, SAY_LEGOSO_20 = 19, SAY_LEGOSO_21 = 20, SPELL_BLOODMYST_TESLA = 31611, SPELL_SIRONAS_CHANNELING = 31612, SPELL_UPPERCUT = 10966, SPELL_IMMOLATE = 12742, SPELL_CURSE_OF_BLOOD = 8282, SPELL_FROST_SHOCK = 8056, SPELL_HEALING_SURGE = 8004, SPELL_SEARING_TOTEM = 38116, SPELL_STRENGTH_OF_EARTH_TOTEM = 31633, NPC_SIRONAS = 17678, NPC_BLOODMYST_TESLA_COIL = 17979, NPC_LEGOSO = 17982, GO_DRAENEI_EXPLOSIVES_1 = 182088, GO_DRAENEI_EXPLOSIVES_2 = 182091, GO_FIRE_EXPLOSION = 182071, ACTION_SIRONAS_CHANNEL_START = 1, ACTION_SIRONAS_CHANNEL_STOP = 2, ACTION_LEGOSO_SIRONAS_KILLED = 1, EVENT_UPPERCUT = 1, EVENT_IMMOLATE = 2, EVENT_CURSE_OF_BLOOD = 3, EVENT_FROST_SHOCK = 1, EVENT_HEALING_SURGE = 2, EVENT_SEARING_TOTEM = 3, EVENT_STRENGTH_OF_EARTH_TOTEM = 4, WP_START = 1, WP_EXPLOSIVES_FIRST_POINT = 21, WP_EXPLOSIVES_FIRST_PLANT = 22, WP_EXPLOSIVES_FIRST_RUNOFF = 23, WP_EXPLOSIVES_FIRST_DETONATE = 24, WP_DEBUG_1 = 25, WP_DEBUG_2 = 26, WP_SIRONAS_HILL = 33, WP_EXPLOSIVES_SECOND_BATTLEROAR = 35, WP_EXPLOSIVES_SECOND_PLANT = 39, WP_EXPLOSIVES_SECOND_DETONATE = 40, PHASE_NONE = 0, PHASE_CONTINUE = -1, PHASE_WP_26 = 1, PHASE_WP_22 = 2, PHASE_PLANT_FIRST_KNEEL = 3, PHASE_PLANT_FIRST_STAND = 4, PHASE_PLANT_FIRST_WORK = 5, PHASE_PLANT_FIRST_FINISH = 6, PHASE_PLANT_FIRST_TIMER_1 = 7, PHASE_PLANT_FIRST_TIMER_2 = 8, PHASE_PLANT_FIRST_TIMER_3 = 9, PHASE_PLANT_FIRST_DETONATE = 10, PHASE_PLANT_FIRST_SPEECH = 11, PHASE_PLANT_FIRST_ROTATE = 12, PHASE_PLANT_FIRST_POINT = 13, PHASE_FEEL_SIRONAS_1 = 14, PHASE_FEEL_SIRONAS_2 = 15, PHASE_MEET_SIRONAS_ROAR = 16, PHASE_MEET_SIRONAS_TURN = 17, PHASE_MEET_SIRONAS_SPEECH = 18, PHASE_PLANT_SECOND_KNEEL = 19, PHASE_PLANT_SECOND_SPEECH = 20, PHASE_PLANT_SECOND_STAND = 21, PHASE_PLANT_SECOND_FINISH = 22, PHASE_PLANT_SECOND_WAIT = 23, PHASE_PLANT_SECOND_TIMER_1 = 24, PHASE_PLANT_SECOND_TIMER_2 = 25, PHASE_PLANT_SECOND_TIMER_3 = 26, PHASE_PLANT_SECOND_DETONATE = 27, PHASE_FIGHT_SIRONAS_STOP = 28, PHASE_FIGHT_SIRONAS_SPEECH_1 = 29, PHASE_FIGHT_SIRONAS_SPEECH_2 = 30, PHASE_FIGHT_SIRONAS_START = 31, PHASE_SIRONAS_SLAIN_SPEECH_1 = 32, PHASE_SIRONAS_SLAIN_EMOTE_1 = 33, PHASE_SIRONAS_SLAIN_EMOTE_2 = 34, PHASE_SIRONAS_SLAIN_SPEECH_2 = 35, DATA_EVENT_STARTER_GUID = 0, MAX_EXPLOSIVES = 5, QUEST_ENDING_THEIR_WORLD = 9759 }; Position const ExplosivesPos[2][MAX_EXPLOSIVES] = { { { -1954.946f, -10654.714f, 110.448f }, { -1956.331f, -10654.494f, 110.869f }, { -1955.906f, -10656.221f, 110.791f }, { -1957.294f, -10656.000f, 111.219f }, { -1954.462f, -10656.451f, 110.404f } }, { { -1915.137f, -10583.651f, 178.365f }, { -1914.006f, -10582.964f, 178.471f }, { -1912.717f, -10582.398f, 178.658f }, { -1915.056f, -10582.251f, 178.162f }, { -1913.883f, -10581.778f, 178.346f } } }; /*###### ## npc_sironas ######*/ class npc_sironas : public CreatureScript { public: npc_sironas() : CreatureScript("npc_sironas") { } struct npc_sironasAI : public ScriptedAI { npc_sironasAI(Creature* creature) : ScriptedAI(creature) { } void Reset() override { _events.Reset(); me->SetDisplayFromModel(1); } void EnterCombat(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_UPPERCUT, 15 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_IMMOLATE, 10 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_CURSE_OF_BLOOD, 5 * IN_MILLISECONDS); } void JustDied(Unit* killer) override { me->SetObjectScale(1.0f); _events.Reset(); if (Creature* legoso = me->FindNearestCreature(NPC_LEGOSO, SIZE_OF_GRIDS)) { for (Group* group : me->GetLootRecipientGroups()) { if (killer->GetGUID() == legoso->GetGUID() || (group && group->IsMember(killer->GetGUID())) || killer->GetGUID() == legoso->AI()->GetGUID(DATA_EVENT_STARTER_GUID)) { legoso->AI()->DoAction(ACTION_LEGOSO_SIRONAS_KILLED); break; } } } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_UPPERCUT: DoCastVictim(SPELL_UPPERCUT); _events.ScheduleEvent(EVENT_UPPERCUT, urand(10, 12) * IN_MILLISECONDS); break; case EVENT_IMMOLATE: DoCastVictim(SPELL_IMMOLATE); _events.ScheduleEvent(EVENT_IMMOLATE, urand(15, 20) * IN_MILLISECONDS); break; case EVENT_CURSE_OF_BLOOD: DoCastVictim(SPELL_CURSE_OF_BLOOD); _events.ScheduleEvent(EVENT_CURSE_OF_BLOOD, urand(20, 25) * IN_MILLISECONDS); break; default: break; } } DoMeleeAttackIfReady(); } void DoAction(int32 param) override { switch (param) { case ACTION_SIRONAS_CHANNEL_START: { DoCast(me, SPELL_SIRONAS_CHANNELING); std::list<Creature*> BeamList; me->GetCreatureListWithEntryInGrid(BeamList, NPC_BLOODMYST_TESLA_COIL, SIZE_OF_GRIDS); if (!BeamList.empty()) for (std::list<Creature*>::iterator itr = BeamList.begin(); itr != BeamList.end(); ++itr) (*itr)->CastSpell(*itr, SPELL_BLOODMYST_TESLA); break; } case ACTION_SIRONAS_CHANNEL_STOP: { me->InterruptNonMeleeSpells(true, SPELL_SIRONAS_CHANNELING); std::list<Creature*> creatureList; GetCreatureListWithEntryInGrid(creatureList, me, NPC_BLOODMYST_TESLA_COIL, 500.0f); if (!creatureList.empty()) for (std::list<Creature*>::iterator itr = creatureList.begin(); itr != creatureList.end(); ++itr) (*itr)->InterruptNonMeleeSpells(true, SPELL_BLOODMYST_TESLA); } default: break; } } private: EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_sironasAI(creature); } }; /*###### ## npc_demolitionist_legoso ######*/ class npc_demolitionist_legoso : public CreatureScript { public: npc_demolitionist_legoso() : CreatureScript("npc_demolitionist_legoso") { } struct npc_demolitionist_legosoAI : public npc_escortAI { npc_demolitionist_legosoAI(Creature* creature) : npc_escortAI(creature) { Initialize(); } void Initialize() { _phase = PHASE_NONE; _moveTimer = 0; } void sQuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_ENDING_THEIR_WORLD) { SetGUID(player->GetGUID(), DATA_EVENT_STARTER_GUID); Start(true, true, player->GetGUID(), quest); } } ObjectGuid GetGUID(int32 type) const override { if (type == DATA_EVENT_STARTER_GUID) return _eventStarterGuid; return ObjectGuid::Empty; } void SetGUID(ObjectGuid guid, int32 type) override { switch (type) { case DATA_EVENT_STARTER_GUID: _eventStarterGuid = guid; break; default: break; } } void Reset() override { me->SetCanDualWield(true); Initialize(); _events.Reset(); _events.ScheduleEvent(EVENT_FROST_SHOCK, 1 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_HEALING_SURGE, 5 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_SEARING_TOTEM, 15 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_STRENGTH_OF_EARTH_TOTEM, 20 * IN_MILLISECONDS); } void UpdateAI(uint32 diff) override { _events.Update(diff); if (UpdateVictim()) { while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_FROST_SHOCK: DoCastVictim(SPELL_FROST_SHOCK); _events.DelayEvents(1 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_FROST_SHOCK, urand(10, 15) * IN_MILLISECONDS); break; case EVENT_SEARING_TOTEM: DoCast(me, SPELL_SEARING_TOTEM); _events.DelayEvents(1 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_SEARING_TOTEM, urand(110, 130) * IN_MILLISECONDS); break; case EVENT_STRENGTH_OF_EARTH_TOTEM: DoCast(me, SPELL_STRENGTH_OF_EARTH_TOTEM); _events.DelayEvents(1 * IN_MILLISECONDS); _events.ScheduleEvent(EVENT_STRENGTH_OF_EARTH_TOTEM, urand(110, 130) * IN_MILLISECONDS); break; case EVENT_HEALING_SURGE: { Unit* target = nullptr; if (me->GetHealthPct() < 85) target = me; else if (Player* player = GetPlayerForEscort()) if (player->GetHealthPct() < 85) target = player; if (target) { DoCast(target, SPELL_HEALING_SURGE); _events.ScheduleEvent(EVENT_HEALING_SURGE, 10 * IN_MILLISECONDS); } else _events.ScheduleEvent(EVENT_HEALING_SURGE, 2 * IN_MILLISECONDS); break; } default: break; } } DoMeleeAttackIfReady(); } if (HasEscortState(STATE_ESCORT_NONE)) return; npc_escortAI::UpdateAI(diff); if (_phase) { if (_moveTimer <= diff) { switch (_phase) { case PHASE_WP_26: //debug skip path to point 26, buggy path calculation me->GetMotionMaster()->MovePoint(WP_DEBUG_2, -2021.77f, -10648.8f, 129.903f, false); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; case PHASE_CONTINUE: // continue escort SetEscortPaused(false); _moveTimer = 0 * IN_MILLISECONDS; _phase = PHASE_NONE; break; case PHASE_WP_22: //debug skip path to point 22, buggy path calculation me->GetMotionMaster()->MovePoint(WP_EXPLOSIVES_FIRST_PLANT, -1958.026f, -10660.465f, 111.547f, false); Talk(SAY_LEGOSO_3); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_KNEEL; break; case PHASE_PLANT_FIRST_KNEEL: // plant first explosives stage 1 kneel me->SetStandState(UNIT_STAND_STATE_KNEEL); _moveTimer = 10 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_STAND; break; case PHASE_PLANT_FIRST_STAND: // plant first explosives stage 1 stand me->SetStandState(UNIT_STAND_STATE_STAND); _moveTimer = 0.5f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_PLANT_FIRST_WORK; break; case PHASE_PLANT_FIRST_WORK: // plant first explosives stage 2 work Talk(SAY_LEGOSO_4); _moveTimer = 17.5f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_PLANT_FIRST_FINISH; break; case PHASE_PLANT_FIRST_FINISH: // plant first explosives finish _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i], QuaternionData(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } me->HandleEmoteCommand(EMOTE_ONESHOT_NONE); // reset anim state // force runoff movement so he will not screw up next waypoint me->GetMotionMaster()->MovePoint(WP_EXPLOSIVES_FIRST_RUNOFF, -1955.6f, -10669.8f, 110.65f, false); Talk(SAY_LEGOSO_5); _moveTimer = 1.5f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_CONTINUE; break; case PHASE_PLANT_FIRST_TIMER_1: // first explosives detonate timer 1 Talk(SAY_LEGOSO_6); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_TIMER_2; break; case PHASE_PLANT_FIRST_TIMER_2: // first explosives detonate timer 2 Talk(SAY_LEGOSO_7); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_TIMER_3; break; case PHASE_PLANT_FIRST_TIMER_3: // first explosives detonate timer 3 Talk(SAY_LEGOSO_8); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_DETONATE; break; case PHASE_PLANT_FIRST_DETONATE: // first explosives detonate finish for (GuidList::iterator itr = _explosivesGuids.begin(); itr != _explosivesGuids.end(); ++itr) { if (GameObject* explosive = ObjectAccessor::GetGameObject(*me, *itr)) me->RemoveGameObject(explosive, true); } _explosivesGuids.clear(); me->HandleEmoteCommand(EMOTE_ONESHOT_CHEER); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_SPEECH; break; case PHASE_PLANT_FIRST_SPEECH: // after detonation 1 speech Talk(SAY_LEGOSO_9); _moveTimer = 4 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_ROTATE; break; case PHASE_PLANT_FIRST_ROTATE: // after detonation 1 rotate to next point me->SetFacingTo(2.272f); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_POINT; break; case PHASE_PLANT_FIRST_POINT: // after detonation 1 send point anim and go on to next point me->HandleEmoteCommand(EMOTE_ONESHOT_POINT); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; case PHASE_FEEL_SIRONAS_1: // legoso exclamation before sironas 1.1 Talk(SAY_LEGOSO_10); _moveTimer = 4 * IN_MILLISECONDS; _phase = PHASE_FEEL_SIRONAS_2; break; case PHASE_FEEL_SIRONAS_2: // legoso exclamation before sironas 1.2 Talk(SAY_LEGOSO_11); _moveTimer = 4 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; case PHASE_MEET_SIRONAS_ROAR: // legoso exclamation before sironas 2.1 Talk(SAY_LEGOSO_12); _moveTimer = 4 * IN_MILLISECONDS; _phase = PHASE_MEET_SIRONAS_TURN; break; case PHASE_MEET_SIRONAS_TURN: // legoso exclamation before sironas 2.2 if (Player* player = GetPlayerForEscort()) me->SetFacingToObject(player); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_MEET_SIRONAS_SPEECH; break; case PHASE_MEET_SIRONAS_SPEECH: // legoso exclamation before sironas 2.3 Talk(SAY_LEGOSO_13); _moveTimer = 7 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; case PHASE_PLANT_SECOND_KNEEL: // plant second explosives stage 1 kneel me->SetStandState(UNIT_STAND_STATE_KNEEL); _moveTimer = 11 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_SPEECH; break; case PHASE_PLANT_SECOND_SPEECH: // plant second explosives stage 2 kneel Talk(SAY_LEGOSO_14); _moveTimer = 13 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_STAND; break; case PHASE_PLANT_SECOND_STAND: // plant second explosives finish me->SetStandState(UNIT_STAND_STATE_STAND); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_FINISH; break; case PHASE_PLANT_SECOND_FINISH: // plant second explosives finish - create explosives _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i], QuaternionData(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } Talk(SAY_LEGOSO_15); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_WAIT; break; case PHASE_PLANT_SECOND_WAIT: // plant second explosives finish - proceed to next point _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; case PHASE_PLANT_SECOND_TIMER_1: // second explosives detonate timer 1 Talk(SAY_LEGOSO_16); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_TIMER_2; break; case PHASE_PLANT_SECOND_TIMER_2: // second explosives detonate timer 2 Talk(SAY_LEGOSO_17); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_TIMER_3; break; case PHASE_PLANT_SECOND_TIMER_3: // second explosives detonate timer 3 Talk(SAY_LEGOSO_18); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_DETONATE; break; case PHASE_PLANT_SECOND_DETONATE: // second explosives detonate finish for (GuidList::iterator itr = _explosivesGuids.begin(); itr != _explosivesGuids.end(); ++itr) { if (GameObject* explosive = ObjectAccessor::GetGameObject(*me, *itr)) me->RemoveGameObject(explosive, true); } _explosivesGuids.clear(); if (Creature* sironas = me->FindNearestCreature(NPC_SIRONAS, SIZE_OF_GRIDS)) { sironas->RemoveUnitFlag(UnitFlags(UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC)); me->SetFacingToObject(sironas); } _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_FIGHT_SIRONAS_STOP; break; case PHASE_FIGHT_SIRONAS_STOP: // sironas channel stop if (Creature* sironas = me->FindNearestCreature(NPC_SIRONAS, SIZE_OF_GRIDS)) sironas->AI()->DoAction(ACTION_SIRONAS_CHANNEL_STOP); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_FIGHT_SIRONAS_SPEECH_1; break; case PHASE_FIGHT_SIRONAS_SPEECH_1: // sironas exclamation before aggro if (Creature* sironas = me->FindNearestCreature(NPC_SIRONAS, SIZE_OF_GRIDS)) sironas->AI()->Talk(SAY_SIRONAS_1); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_FIGHT_SIRONAS_SPEECH_2; break; case PHASE_FIGHT_SIRONAS_SPEECH_2: // legoso exclamation before aggro if (Creature* sironas = me->FindNearestCreature(NPC_SIRONAS, SIZE_OF_GRIDS)) sironas->SetObjectScale(3.0f); Talk(SAY_LEGOSO_19); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_FIGHT_SIRONAS_START; break; case PHASE_FIGHT_SIRONAS_START: // legoso exclamation at aggro if (Creature* sironas = me->FindNearestCreature(NPC_SIRONAS, SIZE_OF_GRIDS)) { Unit* target = GetPlayerForEscort(); if (!target) target = me; target->AddThreat(sironas, 0.001f); sironas->Attack(target, true); sironas->GetMotionMaster()->MoveChase(target); } _moveTimer = 10 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; case PHASE_SIRONAS_SLAIN_SPEECH_1: // legoso exclamation after battle - stage 1.1 Talk(SAY_LEGOSO_20); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_SIRONAS_SLAIN_EMOTE_1; break; case PHASE_SIRONAS_SLAIN_EMOTE_1: // legoso exclamation after battle - stage 1.2 me->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_SIRONAS_SLAIN_EMOTE_2; break; case PHASE_SIRONAS_SLAIN_EMOTE_2: // legoso exclamation after battle - stage 1.3 if (Player* player = GetPlayerForEscort()) player->GroupEventHappens(QUEST_ENDING_THEIR_WORLD, me); me->HandleEmoteCommand(EMOTE_ONESHOT_CHEER); _moveTimer = 5 * IN_MILLISECONDS; _phase = PHASE_SIRONAS_SLAIN_SPEECH_2; break; case PHASE_SIRONAS_SLAIN_SPEECH_2: // legoso exclamation after battle - stage 2 Talk(SAY_LEGOSO_21); _moveTimer = 30 * IN_MILLISECONDS; _phase = PHASE_CONTINUE; break; default: break; } } else if (!me->IsInCombat()) _moveTimer -= diff; } } void WaypointReached(uint32 waypointId) override { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case WP_START: SetEscortPaused(true); me->SetFacingToObject(player); Talk(SAY_LEGOSO_1); _moveTimer = 2.5f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_CONTINUE; break; case WP_EXPLOSIVES_FIRST_POINT: SetEscortPaused(true); Talk(SAY_LEGOSO_2); _moveTimer = 8 * IN_MILLISECONDS; _phase = PHASE_WP_22; break; case WP_EXPLOSIVES_FIRST_PLANT: me->SetFacingTo(1.46f); break; case WP_EXPLOSIVES_FIRST_DETONATE: SetEscortPaused(true); me->SetFacingTo(1.05f); _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_PLANT_FIRST_TIMER_1; break; case WP_DEBUG_1: SetEscortPaused(true); _moveTimer = 0.5f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_WP_26; break; case WP_SIRONAS_HILL: { SetEscortPaused(true); //Find Sironas and make it respawn if needed Creature* sironas = nullptr; Trinity::AllCreaturesOfEntryInRange check(me, NPC_SIRONAS, SIZE_OF_GRIDS); Trinity::CreatureSearcher<Trinity::AllCreaturesOfEntryInRange> searcher(me, sironas, check); Cell::VisitAllObjects(me, searcher, SIZE_OF_GRIDS); if (sironas) { if (!sironas->IsAlive()) sironas->Respawn(true); sironas->AI()->DoAction(ACTION_SIRONAS_CHANNEL_START); me->SetFacingToObject(sironas); } _moveTimer = 1 * IN_MILLISECONDS; _phase = PHASE_FEEL_SIRONAS_1; break; } case WP_EXPLOSIVES_SECOND_BATTLEROAR: SetEscortPaused(true); _moveTimer = 0.2f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_MEET_SIRONAS_ROAR; break; case WP_EXPLOSIVES_SECOND_PLANT: SetEscortPaused(true); _moveTimer = 0.5f * AsUnderlyingType(IN_MILLISECONDS); _phase = PHASE_PLANT_SECOND_KNEEL; break; case WP_EXPLOSIVES_SECOND_DETONATE: SetEscortPaused(true); me->SetFacingTo(5.7f); _moveTimer = 2 * IN_MILLISECONDS; _phase = PHASE_PLANT_SECOND_TIMER_1; break; default: break; } } void DoAction(int32 param) override { switch (param) { case ACTION_LEGOSO_SIRONAS_KILLED: _phase = PHASE_SIRONAS_SLAIN_SPEECH_1; _moveTimer = 5 * IN_MILLISECONDS; break; default: break; } } private: int8 _phase; uint32 _moveTimer; ObjectGuid _eventStarterGuid; GuidList _explosivesGuids; EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return new npc_demolitionist_legosoAI(creature); } }; //24318 class item_sample_water_flask_24318 : public ItemScript { public: item_sample_water_flask_24318() : ItemScript("item_sample_water_flask_24318") { } enum eItem { QUEST_DONT_DRINK_THE_WATER = 9748, SPELL_BLOODMYST_WATER_SAMPLE = 31549, }; bool OnUse(Player* plr, Item* /*item*/, SpellCastTargets const& targets, ObjectGuid /*castId*/) override { if (plr->GetQuestStatus(QUEST_DONT_DRINK_THE_WATER) == QUEST_STATUS_INCOMPLETE && plr->GetAreaId() == 3906) { plr->GetScheduler().Schedule(6s, [this, plr] (TaskContext context) { plr->ForceCompleteQuest(QUEST_DONT_DRINK_THE_WATER); }); } return true; } }; void AddSC_bloodmyst_isle() { new npc_webbed_creature(); new npc_sironas(); new npc_demolitionist_legoso(); new item_sample_water_flask_24318(); }
0
0.978954
1
0.978954
game-dev
MEDIA
0.995354
game-dev
0.789612
1
0.789612
GenaSG/UnityUnetMovement
3,340
Scripts/Inventory.cs
using UnityEngine; using System.Collections; using UnityEngine.Networking; using System.Collections.Generic; public struct PickupInfo{ public int itemIndex; public int itemAmmo; } [NetworkSettings(channel=0,sendInterval=0.05f)] public class Inventory : NetworkBehaviour { public int maxSlotsCount = 6; public int _currentSlot = 0; public ItemScript[] _availableItems;//Array of available items specific to this entity public SyncListInt _slots= new SyncListInt ();//List of item index to sync over network [SyncVar] private int _syncSlot;//Selected slot private int _input; private int _lastSlot = -1; private bool _holster = false; public void GiveItem(PickupInfo itemInfo){ if (hasAuthority) { //Create all slots if not created yet if(_slots.Count < maxSlotsCount){ for(int i =0;i < maxSlotsCount;i++){ _slots.Add(-1); } //if it is a first item switch to it _currentSlot = _availableItems[itemInfo.itemIndex].slot; _syncSlot = _currentSlot; Rpc_FirstItem(_currentSlot); } if(_slots[_availableItems[itemInfo.itemIndex].slot] == itemInfo.itemIndex){ //Add ammo only if item already is in inventory _availableItems[itemInfo.itemIndex].GiveAmmo(itemInfo.itemAmmo); }else{ //Add item and ammo _slots[_availableItems[itemInfo.itemIndex].slot] = itemInfo.itemIndex; _availableItems[itemInfo.itemIndex].GiveAmmo(itemInfo.itemAmmo); } } } //Needed to switch client to first item [ClientRpc] void Rpc_FirstItem(int slot){ _currentSlot = slot; } void LateUpdate(){ if (isLocalPlayer) { //Get player inputs GetInputs (); //Checking if it's possible to switch to new slot if (_slots.Count > 0 && _input < _slots.Count && _slots [_input] >= 0 && _availableItems [_slots [_input]]) { _currentSlot = _input; } if (hasAuthority) { _syncSlot = _currentSlot; } else { Cmd_SetSlot (_currentSlot); } } else { if(!hasAuthority){ _currentSlot = _syncSlot; } } //Actual switching if (_holster) { if (_availableItems [_slots [_currentSlot]].selected){ _availableItems [_slots [_currentSlot]].Deselect (); } } else { if ( _slots.Count > 0 && _currentSlot < _slots.Count && _availableItems [_slots [_currentSlot]]) { //Disabling last item if (_lastSlot >= 0 && _lastSlot != _currentSlot) { if (_availableItems [_slots [_lastSlot]].selected) { _availableItems [_slots [_lastSlot]].Deselect (); } else { _lastSlot = _currentSlot; } } else { _lastSlot = _currentSlot; } //Enabling new item if (!_availableItems [_slots [_currentSlot]].selected) { _availableItems [_slots [_currentSlot]].Select (); } } } } void GetInputs(){ if (Input.GetButtonDown ("Slot1")) { _input = 0; } else if (Input.GetButtonDown ("Slot2")) { _input = 1; } else if (Input.GetButtonDown ("Slot3")) { _input = 2; } else if (Input.GetButtonDown ("Slot4")) { _input = 3; } else if (Input.GetButtonDown ("Slot5")) { _input = 4; } else if (Input.GetButtonDown ("Slot6")) { _input = 5; } if (Input.GetButtonDown ("Holster")) { _holster = !_holster; } } [Command(channel=0)] void Cmd_SetSlot(int input){ if (!isLocalPlayer && hasAuthority) { _currentSlot = input; _syncSlot = _currentSlot; } } }
0
0.759384
1
0.759384
game-dev
MEDIA
0.780259
game-dev
0.954217
1
0.954217
s-oram/Grace
4,864
Delphi/Third Party/EasyEffect/EasyEffectFilters/eeFilters.EnvFollowerA.pas
unit eeFilters.EnvFollowerA; interface uses VamLib.MoreTypes; type TEnvFollowerA = class private fSampleRate : integer; fAttackTime : single; fReleaseTime : single; procedure SetAttackTime(const Value: single); procedure SetReleaseTime(const Value: single); procedure SetSampleRate(const Value: integer); protected DecayEnvLevel : single; EnvLevel : single; QuickAttackCoefficient : single; AttackCoefficient : single; ReleaseCoefficient : single; public constructor Create; destructor Destroy; override; function Step(const In1: single) : single; inline; procedure Process(In1:PSingle; const SampleFrames : integer); overload; inline; procedure Process(In1, Out1:PSingle; const SampleFrames : integer); overload; inline; property AttackTime : single read fAttackTime write SetAttackTime; //milliseconds. property ReleaseTime : single read fReleaseTime write SetReleaseTime; //milliseconds. property SampleRate : integer read fSampleRate write SetSampleRate; end; implementation { TEnvelopeFollower } constructor TEnvFollowerA.Create; begin EnvLevel := 0; SampleRate := 44100; fAttackTime := 0; fReleaseTime := 0; AttackTime := 0; ReleaseTime := 0.1; DecayEnvLevel := 0; end; destructor TEnvFollowerA.Destroy; begin inherited; end; procedure TEnvFollowerA.SetAttackTime(const Value: single); var tau:double; begin if Value > 0 then begin fAttackTime := Value; tau := Value / 1000; AttackCoefficient := 1 - exp( -1.0 / (tau*sampleRate)); if AttackCoefficient > 1 then AttackCoefficient := 1; end else begin AttackCoefficient := 1; end; end; procedure TEnvFollowerA.SetReleaseTime(const Value: single); var tau:double; begin if Value > 0 then begin fReleaseTime := Value; tau := Value / 1000; ReleaseCoefficient := 1 - exp( -1.0 / (tau*sampleRate)); if ReleaseCoefficient > 1 then ReleaseCoefficient := 1; end else begin end; end; procedure TEnvFollowerA.SetSampleRate(const Value: integer); var Time:single; tau:double; begin fSampleRate := Value; Time := 0.001; tau := Time / 1000; QuickAttackCoefficient := 1 - exp( -1.0 / (tau*sampleRate)); end; function TEnvFollowerA.Step(const In1: single): single; var x1:single; begin x1 := abs(In1); //The envelope uses a two stage detection process. //The first stage is an envelope follower with a quick attack and the correct decay time. //The second stage uses the proper attack coefficient and rises until it meets the first envelope. //First stage... if x1 > DecayEnvLevel then DecayEnvLevel := DecayEnvLevel + (x1 - DecayEnvLevel) * QuickAttackCoefficient else DecayEnvLevel := DecayEnvLevel + (x1 - DecayEnvLevel) * ReleaseCoefficient; //Second stage... if (DecayEnvLevel > EnvLevel) then EnvLevel := EnvLevel + (DecayEnvLevel - EnvLevel) * AttackCoefficient else EnvLevel := DecayEnvLevel; result := EnvLevel; end; procedure TEnvFollowerA.Process(In1: PSingle; const SampleFrames: integer); var x1:single; c1: Integer; begin for c1 := 0 to SampleFrames-1 do begin x1 := abs(In1^); //The envelope uses a two stage detection process. //The first stage is an envelope follower with a quick attack and the correct decay time. //The second stage uses the proper attack coefficient and rises until it meets the first envelope. //First stage... if x1 > DecayEnvLevel then DecayEnvLevel := DecayEnvLevel + (x1 - DecayEnvLevel) * QuickAttackCoefficient else DecayEnvLevel := DecayEnvLevel + (x1 - DecayEnvLevel) * ReleaseCoefficient; //Second stage... if (DecayEnvLevel > EnvLevel) then EnvLevel := EnvLevel + (DecayEnvLevel - EnvLevel) * AttackCoefficient else EnvLevel := DecayEnvLevel; In1^ := EnvLevel; inc(In1); end; end; procedure TEnvFollowerA.Process(In1, Out1: PSingle; const SampleFrames: integer); var x1:single; c1: Integer; begin for c1 := 0 to SampleFrames-1 do begin x1 := abs(In1^); //The envelope uses a two stage detection process. //The first stage is an envelope follower with a quick attack and the correct decay time. //The second stage uses the proper attack coefficient and rises until it meets the first envelope. //First stage... if x1 > DecayEnvLevel then DecayEnvLevel := DecayEnvLevel + (x1 - DecayEnvLevel) * QuickAttackCoefficient else DecayEnvLevel := DecayEnvLevel + (x1 - DecayEnvLevel) * ReleaseCoefficient; //Second stage... if (DecayEnvLevel > EnvLevel) then EnvLevel := EnvLevel + (DecayEnvLevel - EnvLevel) * AttackCoefficient else EnvLevel := DecayEnvLevel; Out1^ := EnvLevel; inc(In1); inc(Out1); end; end; end.
0
0.841787
1
0.841787
game-dev
MEDIA
0.569292
game-dev
0.855762
1
0.855762
organization/Kookie
2,227
app/src/main/kotlin/be/zvz/kookie/world/SimpleChunkManager.kt
/** * * _ __ _ _ * | |/ /___ ___ | | _(_) ___ * | ' // _ \ / _ \| |/ / |/ _ \ * | . \ (_) | (_) | <| | __/ * |_|\_\___/ \___/|_|\_\_|\___| * * A server software for Minecraft: Bedrock Edition * * Copyright (C) 2021 organization 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. */ package be.zvz.kookie.world import be.zvz.kookie.block.Block import be.zvz.kookie.block.BlockFactory import be.zvz.kookie.block.VanillaBlocks import be.zvz.kookie.world.format.Chunk import com.koloboke.collect.map.hash.HashLongObjMaps open class SimpleChunkManager( override var minY: Int, override var maxY: Int ) : ChunkManager { protected val chunks: MutableMap<Long, Chunk> = HashLongObjMaps.newMutableMap() override fun getBlockAt(x: Int, y: Int, z: Int): Block { if (isInWorld(x, y, z)) { getChunk(x shr 4, z shr 4)?.let { chunk -> return BlockFactory.fromFullBlock(chunk.getFullBlock(x and 0xf, y, z and 0xf)) } } return VanillaBlocks.AIR.block } override fun setBlockAt(x: Int, y: Int, z: Int, block: Block) { val chunk = getChunk(x shr 4, z shr 4) if (chunk === null) { throw IllegalArgumentException( "Cannot set block at coordinates x=$x,y=$y,z=$z," + "terrain is not loaded or out of bounds" ) } chunk.setFullBlock(x and 0xf, y, z and 0xf, block.getFullId()) } override fun getChunk(chunkX: Int, chunkZ: Int): Chunk? = chunks[World.chunkHash(chunkX, chunkZ)] override fun setChunk(chunkX: Int, chunkZ: Int, chunk: Chunk) { chunks[World.chunkHash(chunkX, chunkZ)] = chunk } fun cleanChunks() { chunks.clear() } /** * Do not check x and z are within the range of Int. * Because the Int type guarantees it. */ override fun isInWorld(x: Int, y: Int, z: Int): Boolean = y in minY..maxY fun isInWorld(y: Int): Boolean = y in minY..maxY }
0
0.747575
1
0.747575
game-dev
MEDIA
0.89383
game-dev
0.604943
1
0.604943
TeamChocoQuest/ChocolateQuestRepoured
6,990
src/main/java/team/cqr/cqrepoured/util/BlockPlacingHelper.java
package team.cqr.cqrepoured.util; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos.MutableBlockPos; import net.minecraft.world.World; import net.minecraft.world.WorldType; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.util.BlockSnapshot; import team.cqr.cqrepoured.CQRMain; import team.cqr.cqrepoured.config.CQRConfig; import team.cqr.cqrepoured.world.structure.generation.generation.GeneratableDungeon; public class BlockPlacingHelper { private static final MutableBlockPos MUTABLE = new MutableBlockPos(); public static boolean setBlockStates(World world, int chunkX, int chunkY, int chunkZ, GeneratableDungeon dungeon, IBlockInfo blockInfo) { if (world.isOutsideBuildHeight(MUTABLE.setPos(chunkX << 4, chunkY << 4, chunkZ << 4))) { return false; } if (!world.isRemote && world.getWorldInfo().getTerrainType() == WorldType.DEBUG_ALL_BLOCK_STATES) { return false; } Chunk chunk = null; ExtendedBlockStorage blockStorage = null; if (!CQRMain.isPhosphorInstalled && !CQRConfig.advanced.instantLightUpdates) { chunk = world.getChunk(chunkX, chunkZ); blockStorage = chunk.getBlockStorageArray()[chunkY]; if (blockStorage == Chunk.NULL_BLOCK_STORAGE) { blockStorage = new ExtendedBlockStorage(chunkY << 4, world.provider.hasSkyLight()); chunk.getBlockStorageArray()[chunkY] = blockStorage; if (!blockInfo.place(world, chunk, blockStorage, dungeon)) { chunk.getBlockStorageArray()[chunkY] = null; return false; } return true; } } return blockInfo.place(world, chunk, blockStorage, dungeon); } @FunctionalInterface public interface IBlockInfo { boolean place(World world, Chunk chunk, ExtendedBlockStorage blockStorage, GeneratableDungeon dungeon); } public static boolean setBlockState(World world, BlockPos pos, IBlockState state, @Nullable TileEntity tileEntity, int flags, GeneratableDungeon dungeon) { if (CQRMain.isPhosphorInstalled || CQRConfig.advanced.instantLightUpdates) { if (!world.setBlockState(pos, state, flags)) { return false; } if (tileEntity != null) { world.setTileEntity(pos, tileEntity); tileEntity.updateContainingBlockInfo(); } return true; } if (world.isOutsideBuildHeight(pos)) { return false; } if (!world.isRemote && world.getWorldInfo().getTerrainType() == WorldType.DEBUG_ALL_BLOCK_STATES) { return false; } Chunk chunk = world.getChunk(pos); ExtendedBlockStorage blockStorage = chunk.getBlockStorageArray()[pos.getY() >> 4]; if (blockStorage == Chunk.NULL_BLOCK_STORAGE) { if (state == Blocks.AIR.getDefaultState()) { return false; } blockStorage = new ExtendedBlockStorage(pos.getY() >> 4 << 4, world.provider.hasSkyLight()); chunk.getBlockStorageArray()[pos.getY() >> 4] = blockStorage; } return setBlockState(world, chunk, blockStorage, pos, state, tileEntity, flags, dungeon); } public static boolean setBlockState(World world, Chunk chunk, ExtendedBlockStorage blockStorage, BlockPos pos, IBlockState state, @Nullable TileEntity tileEntity, int flags, GeneratableDungeon dungeon) { if (CQRMain.isPhosphorInstalled || CQRConfig.advanced.instantLightUpdates) { if (!world.setBlockState(pos, state, flags)) { return false; } if (tileEntity != null) { world.setTileEntity(pos, tileEntity); tileEntity.updateContainingBlockInfo(); } return true; } int oldLight = blockStorage.get(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15).getLightValue(world, pos); if (!setBlockState(world, chunk, blockStorage, pos, state, tileEntity, flags)) { return false; } if (oldLight > 0) { dungeon.markRemovedLight(pos.getX(), pos.getY(), pos.getZ(), oldLight); } return true; } public static boolean setBlockState(World world, Chunk chunk, ExtendedBlockStorage blockStorage, BlockPos pos, IBlockState state, @Nullable TileEntity tileEntity, int flags) { IBlockState oldState = setBlockState(world, chunk, blockStorage, pos, state, tileEntity); if (oldState == null) { return false; } if (!world.isRemote && world.captureBlockSnapshots) { world.capturedBlockSnapshots.add(new BlockSnapshot(world, pos.toImmutable(), oldState, flags)); } else { world.markAndNotifyBlock(pos, chunk, oldState, state, flags); } return true; } @Nullable private static IBlockState setBlockState(World world, Chunk chunk, ExtendedBlockStorage blockStorage, BlockPos pos, IBlockState state, @Nullable TileEntity tileEntity) { int x = pos.getX() & 15; int y = pos.getY() & 15; int z = pos.getZ() & 15; IBlockState oldState = setBlockState(blockStorage, x, y, z, state); if (oldState == null) { return null; } int l = z << 4 | x; if (pos.getY() >= chunk.precipitationHeightMap[l] - 1) { chunk.precipitationHeightMap[l] = -999; } Block block = state.getBlock(); Block oldBlock = oldState.getBlock(); if (!world.isRemote && oldBlock != block) { oldBlock.breakBlock(world, pos, oldState); } if (oldBlock.hasTileEntity(oldState)) { TileEntity te = chunk.getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK); if (te != null && te.shouldRefresh(world, pos, oldState, state)) { world.removeTileEntity(pos); } } if (!world.isRemote && block != oldBlock && (!world.captureBlockSnapshots || block.hasTileEntity(state))) { // block.onBlockAdded(world, pos, state); } if (block.hasTileEntity(state)) { if (tileEntity != null) { world.setTileEntity(pos, tileEntity); tileEntity.updateContainingBlockInfo(); } else { TileEntity te = chunk.getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK); if (te == null) { te = block.createTileEntity(world, state); world.setTileEntity(pos, te); } if (te != null) { te.updateContainingBlockInfo(); } } } chunk.markDirty(); return oldState; } @Nullable private static IBlockState setBlockState(ExtendedBlockStorage blockStorage, int x, int y, int z, IBlockState state) { if (state instanceof IExtendedBlockState) { state = ((IExtendedBlockState) state).getClean(); } IBlockState oldState = blockStorage.getData().get(x, y, z); if (state == oldState) { return null; } Block block = state.getBlock(); Block oldBlock = oldState.getBlock(); if (oldBlock != Blocks.AIR) { blockStorage.blockRefCount -= 1; if (oldBlock.getTickRandomly()) { blockStorage.tickRefCount -= 1; } } if (block != Blocks.AIR) { blockStorage.blockRefCount += 1; if (block.getTickRandomly()) { blockStorage.tickRefCount += 1; } } blockStorage.getData().set(x, y, z, state); return oldState; } }
0
0.96802
1
0.96802
game-dev
MEDIA
0.989068
game-dev
0.976422
1
0.976422
mig1023/seeker
4,925
Seeker/Seeker/Gamebook/Ants/Actions.cs
using System; using System.Collections.Generic; using System.Linq; namespace Seeker.Gamebook.Ants { class Actions : Prototypes.Actions, Abstract.IActions { public override List<string> AdditionalStatus() { List<string> statusLines = new List<string> { $"Количество: {Character.Protagonist.Quantity}", $"Прирост: {Character.Protagonist.Increase}" }; string government = String.Empty; foreach (string name in Constants.Government.Keys) { if (Game.Option.IsTriggered(name)) government = name; } if (!String.IsNullOrEmpty(government)) statusLines.Insert(0, $"Правит: {government}"); if (Character.Protagonist.Defence > 0) statusLines.Add($"Защита: {Character.Protagonist.Defence}"); if (Character.Protagonist.EnemyHitpoints > 0) statusLines.Add($"{Character.Protagonist.EnemyName}: {Character.Protagonist.EnemyHitpoints}"); return statusLines; } public override bool Availability(string option) { if (String.IsNullOrEmpty(option)) { return true; } else if (option.Contains("|")) { return option.Split('|').Where(x => Game.Option.IsTriggered(x.Trim())).Count() > 0; } else { foreach (string oneOption in option.Split(',')) { if (oneOption.Contains(">") || oneOption.Contains("<") || oneOption.Contains("=")) { int level = Game.Services.LevelParse(oneOption); if (oneOption.Contains("ДАЙС =") && !Character.Protagonist.Dice[level]) return false; if (oneOption.Contains("КОЛИЧЕСТВО >=") && (level > Character.Protagonist.Quantity)) return false; if (oneOption.Contains("КОЛИЧЕСТВО <") && (level <= Character.Protagonist.Quantity)) return false; if (oneOption.Contains("ВРАГ >=") && (level > Character.Protagonist.EnemyHitpoints)) return false; if (oneOption.Contains("ВРАГ <") && (level <= Character.Protagonist.EnemyHitpoints)) return false; if (oneOption.Contains("ЗАЩИТА >=") && (level > Character.Protagonist.Defence)) return false; if (oneOption.Contains("СТАРТ =") && (Character.Protagonist.Start != level)) return false; } else if (oneOption.Contains("!")) { if (Game.Option.IsTriggered(oneOption.Replace("!", String.Empty).Trim())) return false; } else if (!Game.Option.IsTriggered(oneOption.Trim())) { return false; } } return true; } } public List<string> Result() { List<string> results = new List<string>(); bool queen = Game.Option.IsTriggered("Королева Антуанетта Плодовитая"); bool prince = Game.Option.IsTriggered("Принц Мурадин Крылатый"); bool soldier = Game.Option.IsTriggered("Солдат Руф Твердожвалый"); List<string> ending = queen || prince || soldier ? Constants.EndingOne : Constants.EndingTwo; foreach (string endingLine in Constants.EndingOne) results.Add(endingLine.Replace(';', ',')); results.Add(String.Empty); int speed = 300 - Character.Protagonist.Time; string line = String.Empty; foreach (KeyValuePair<string, int> timelist in Constants.Rating.OrderBy(x => x.Value)) { if (speed < timelist.Value) { break; } else { line = timelist.Key; } } List<string> resultLines = line.Split('!').ToList(); results.Add($"{resultLines[0]}!"); results.Add($"BIG|BOLD|{resultLines[1].Trim()}"); return results; } public List<string> Changes() { List<string> changes = new List<string>(); foreach (string head in Constants.Government.Keys) { if (Game.Option.IsTriggered(head)) changes.Add(Constants.Government[head]); } return changes; } } }
0
0.891515
1
0.891515
game-dev
MEDIA
0.834669
game-dev
0.942469
1
0.942469
newhoryzon/farmers-delight-fabric
1,998
src/main/java/com/nhoryzon/mc/farmersdelight/event/CuttingBoardEventListener.java
package com.nhoryzon.mc.farmersdelight.event; import com.nhoryzon.mc.farmersdelight.entity.block.CuttingBoardBlockEntity; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.minecraft.block.entity.BlockEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.ShearsItem; import net.minecraft.item.ToolItem; import net.minecraft.item.TridentItem; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class CuttingBoardEventListener implements UseBlockCallback { public static final CuttingBoardEventListener INSTANCE = new CuttingBoardEventListener(); private CuttingBoardEventListener() { // Non-instantiable listener } @Override public ActionResult interact(PlayerEntity player, World world, Hand hand, BlockHitResult hitResult) { BlockPos pos = hitResult.getBlockPos(); BlockEntity blockEntity = world.getBlockEntity(pos); ItemStack heldItem = player.getStackInHand(hand); if (player.isSneaking() && blockEntity instanceof CuttingBoardBlockEntity cuttingBoardBlockEntity && !heldItem.isEmpty() && (heldItem.getItem() instanceof ToolItem || heldItem.getItem() instanceof TridentItem || heldItem.getItem() instanceof ShearsItem)) { boolean success = cuttingBoardBlockEntity.carveToolOnBoard(player.getAbilities().creativeMode ? heldItem.copy() : heldItem); if (success) { world.playSound(null, pos.getX(), pos.getY(), pos.getZ(), SoundEvents.BLOCK_WOOD_PLACE, SoundCategory.BLOCKS, 1.f, .8f); return ActionResult.SUCCESS; } } return ActionResult.PASS; } }
0
0.854637
1
0.854637
game-dev
MEDIA
0.999541
game-dev
0.978866
1
0.978866
dilmerv/MetaInteractionSDKDemos
9,314
Assets/Oculus/AudioManager/Scripts/Audio/SoundFX.cs
using UnityEngine; using UnityEngine.Audio; namespace OVR { public enum SoundFXNext { Random = 0, Sequential = 1, } public enum FreqHint { None = 0, Wide = 1, Narrow = 2, } public enum SoundPriority { VeryLow = -2, Low = -1, Default = 0, High = 1, VeryHigh = 2, } [System.Serializable] public class OSPProps { public OSPProps() { enableSpatialization = false; useFastOverride = false; gain = 0.0f; enableInvSquare = false; volumetric = 0.0f; invSquareFalloff = new Vector2( 1.0f, 25.0f ); } [Tooltip( "Set to true to play the sound FX spatialized with binaural HRTF, default = false")] public bool enableSpatialization = false; [Tooltip( "Play the sound FX with reflections, default = false")] public bool useFastOverride = false; [Tooltip( "Boost the gain on the spatialized sound FX, default = 0.0")] [Range( 0.0f, 24.0f )] public float gain = 0.0f; [Tooltip("Enable Inverse Square attenuation curve, default = false")] public bool enableInvSquare = false; [Tooltip("Change the sound from point source (0.0f) to a spherical volume, default = 0.0")] [Range(0.0f, 1000.0f)] public float volumetric = 0.0f; [Tooltip("Set the near and far falloff value for the OSP attenuation curve, default = 1.0")] [MinMax ( 1.0f, 25.0f, 0.0f, 250.0f )] public Vector2 invSquareFalloff = new Vector2( 1.0f, 25.0f ); } /* ----------------------- SoundFX ----------------------- */ [System.Serializable] public class SoundFX { public SoundFX() { playback = SoundFXNext.Random; volume = 1.0f; pitchVariance = Vector2.one; falloffDistance = new Vector2( 1.0f, 25.0f ); falloffCurve = AudioRolloffMode.Linear; volumeFalloffCurve = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } ); reverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } ); spread = 0.0f; pctChanceToPlay = 1.0f; priority = SoundPriority.Default; delay = Vector2.zero; looping = false; ospProps = new OSPProps(); } [Tooltip( "Each sound FX should have a unique name")] public string name = string.Empty; [Tooltip( "Sound diversity playback option when multiple audio clips are defined, default = Random")] public SoundFXNext playback = SoundFXNext.Random; [Tooltip( "Default volume for this sound FX, default = 1.0")] [Range (0.0f, 1.0f)] public float volume = 1.0f; [Tooltip( "Random pitch variance each time a sound FX is played, default = 1.0 (none)")] [MinMax ( 1.0f, 1.0f, 0.0f, 2.0f )] public Vector2 pitchVariance = Vector2.one; [Tooltip( "Falloff distance for the sound FX, default = 1m min to 25m max")] [MinMax ( 1.0f, 25.0f, 0.0f, 250.0f )] public Vector2 falloffDistance = new Vector2( 1.0f, 25.0f ); [Tooltip( "Volume falloff curve - sets how the sound FX attenuates over distance, default = Linear")] public AudioRolloffMode falloffCurve = AudioRolloffMode.Linear; [Tooltip( "Defines the custom volume falloff curve")] public AnimationCurve volumeFalloffCurve = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } ); [Tooltip( "The amount by which the signal from the AudioSource will be mixed into the global reverb associated with the Reverb Zones | Valid range is 0.0 - 1.1, default = 1.0" )] public AnimationCurve reverbZoneMix = new AnimationCurve( new Keyframe[2] { new Keyframe( 0f, 1.0f ), new Keyframe( 1f, 1f ) } ); [Tooltip( "Sets the spread angle (in degrees) of a 3d stereo or multichannel sound in speaker space, default = 0")] [Range (0.0f, 360.0f)] public float spread = 0.0f; [Tooltip( "The percentage chance that this sound FX will play | 0.0 = none, 1.0 = 100%, default = 1.0")] [Range (0.0f, 1.0f)] public float pctChanceToPlay = 1.0f; [Tooltip( "Sets the priority for this sound to play and/or to override a currently playing sound FX, default = Default")] public SoundPriority priority = SoundPriority.Default; [Tooltip( "Specifies the default delay when this sound FX is played, default = 0.0 secs")] [MinMax ( 0.0f, 0.0f, 0.0f, 2.0f )] public Vector2 delay = Vector2.zero; // this overrides any delay passed into PlaySound() or PlaySoundAt() [Tooltip( "Set to true for the sound to loop continuously, default = false")] public bool looping = false; public OSPProps ospProps = new OSPProps(); [Tooltip( "List of the audio clips assigned to this sound FX")] public AudioClip[] soundClips = new AudioClip[1]; // editor only - unfortunately if we set it not to serialize, we can't query it from the editor public bool visibilityToggle = false; // runtime vars [System.NonSerialized] private SoundGroup soundGroup = null; private int lastIdx = -1; private int playingIdx = -1; public int Length { get { return soundClips.Length; } } public bool IsValid { get { return ( ( soundClips.Length != 0 ) && ( soundClips[0] != null ) ); } } public SoundGroup Group { get { return soundGroup; } set { soundGroup = value; } } public float MaxFalloffDistSquared { get { return falloffDistance.y * falloffDistance.y; } } public float GroupVolumeOverride { get { return ( soundGroup != null ) ? soundGroup.volumeOverride : 1.0f; } } /* ----------------------- GetClip() ----------------------- */ public AudioClip GetClip() { if ( soundClips.Length == 0 ) { return null; } else if ( soundClips.Length == 1 ) { return soundClips[0]; } if ( playback == SoundFXNext.Random ) { // random, but don't pick the last one int idx = Random.Range( 0, soundClips.Length ); while ( idx == lastIdx ) { idx = Random.Range( 0, soundClips.Length ); } lastIdx = idx; return soundClips[idx]; } else { // sequential if ( ++lastIdx >= soundClips.Length ) { lastIdx = 0; } return soundClips[lastIdx]; } } /* ----------------------- GetMixerGroup() ----------------------- */ public AudioMixerGroup GetMixerGroup( AudioMixerGroup defaultMixerGroup ) { if ( soundGroup != null ) { return ( soundGroup.mixerGroup != null ) ? soundGroup.mixerGroup : defaultMixerGroup; } return defaultMixerGroup; } /* ----------------------- ReachedGroupPlayLimit() ----------------------- */ public bool ReachedGroupPlayLimit() { if ( soundGroup != null ) { return !soundGroup.CanPlaySound(); } return false; } /* ----------------------- GetClipLength() ----------------------- */ public float GetClipLength( int idx ) { if ( ( idx == -1 ) || ( soundClips.Length == 0 ) || ( idx >= soundClips.Length ) || ( soundClips[idx] == null ) ) { return 0.0f; } else { return soundClips[idx].length; } } /* ----------------------- GetPitch() ----------------------- */ public float GetPitch() { return Random.Range( pitchVariance.x, pitchVariance.y ); } /* ----------------------- PlaySound() ----------------------- */ public int PlaySound( float delaySecs = 0.0f ) { playingIdx = -1; if ( !IsValid ) { return playingIdx; } // check the random chance to play here to save the function calls if ( ( pctChanceToPlay > 0.99f ) || ( Random.value < pctChanceToPlay ) ) { if ( delay.y > 0.0f ) { delaySecs = Random.Range( delay.x, delay.y ); } playingIdx = AudioManager.PlaySound( this, EmitterChannel.Any, delaySecs ); } return playingIdx; } /* ----------------------- PlaySoundAt() ----------------------- */ public int PlaySoundAt( Vector3 pos, float delaySecs = 0.0f, float volumeOverride = 1.0f, float pitchMultiplier = 1.0f ) { playingIdx = -1; if ( !IsValid ) { return playingIdx; } // check the random chance to play here to save the function calls if ( ( pctChanceToPlay > 0.99f ) || ( Random.value < pctChanceToPlay ) ) { if ( delay.y > 0.0f ) { delaySecs = Random.Range( delay.x, delay.y ); } playingIdx = AudioManager.PlaySoundAt( pos, this, EmitterChannel.Any, delaySecs, volumeOverride, pitchMultiplier ); } return playingIdx; } /* ----------------------- SetOnFinished() get a callback when the sound is finished playing ----------------------- */ public void SetOnFinished( System.Action onFinished ) { if ( playingIdx > -1 ) { AudioManager.SetOnFinished( playingIdx, onFinished ); } } /* ----------------------- SetOnFinished() get a callback with an object parameter when the sound is finished playing ----------------------- */ public void SetOnFinished( System.Action<object> onFinished, object obj ) { if ( playingIdx > -1 ) { AudioManager.SetOnFinished( playingIdx, onFinished, obj ); } } /* ----------------------- StopSound() ----------------------- */ public bool StopSound() { bool stopped = false; if (playingIdx > -1){ stopped = AudioManager.StopSound(playingIdx); playingIdx = -1; } return stopped; } /* ----------------------- AttachToParent() ----------------------- */ public void AttachToParent( Transform parent) { if (playingIdx > -1) { AudioManager.AttachSoundToParent(playingIdx, parent); } } /* ----------------------- DetachFromParent() ----------------------- */ public void DetachFromParent() { if (playingIdx > -1) { AudioManager.DetachSoundFromParent(playingIdx); } } } } // namespace OVR
0
0.888414
1
0.888414
game-dev
MEDIA
0.870388
game-dev,audio-video-media
0.972382
1
0.972382
fulpstation/fulpstation
8,914
code/game/objects/items/surgery_tray.dm
/** * Surgery Trays * A storage object that displays tools in its contents based on tier, better tools are more visible. * Can be folded up and carried. Click it to draw a random tool. */ /obj/item/surgery_tray name = "surgery tray" desc = "A Deforest brand medical cart. It is a folding model, meaning the wheels on the bottom can be retracted and the body used as a tray." icon = 'icons/obj/medical/medicart.dmi' icon_state = "tray" w_class = WEIGHT_CLASS_BULKY slowdown = 1 item_flags = SLOWS_WHILE_IN_HAND pass_flags = NONE /// If true we're currently portable var/is_portable = TRUE /// List of contents to populate with in populatecontents() var/list/starting_items = list() /// Fills the tray with items it should contain on creation /obj/item/surgery_tray/proc/populate_contents() for(var/obj in starting_items) new obj(src) update_appearance(UPDATE_ICON) return /obj/item/surgery_tray/Initialize(mapload, effect_spawner = FALSE) . = ..() AddElement(/datum/element/drag_pickup) create_storage(storage_type = /datum/storage/surgery_tray) populate_contents() register_context() set_tray_mode(is_portable) /obj/item/surgery_tray/add_context(atom/source, list/context, obj/item/held_item, mob/user) . = ..() context[SCREENTIP_CONTEXT_LMB] = "Take a random tool" context[SCREENTIP_CONTEXT_RMB] = "Take a specific tool" return CONTEXTUAL_SCREENTIP_SET /obj/item/surgery_tray/update_icon_state() . = ..() icon_state = is_portable ? "tray" : "medicart" /obj/item/surgery_tray/update_desc() . = ..() if(is_portable) desc = "The wheels and bottom storage of this medical cart have been stowed away, \ leaving a cumbersome tray in its place." else desc = initial(desc) /obj/item/surgery_tray/examine(mob/living/carbon/human/user) . = ..() . += is_portable \ ? span_notice("You can click and drag it to yourself to pick it up, then use it in your hand to make it a cart!") \ : span_notice("You can click and drag it to yourself to turn it into a tray!") . += span_notice("The top is <b>screwed</b> on.") /obj/item/surgery_tray/update_overlays() . = ..() // assoc list of all overlays, key = the item generating the overlay, value = the overlay string var/list/surgery_overlays = list() // assoc list of tool behaviors to fastest toolspeed of that type we already have // easy way for us to check if there are any lower quality tools within var/list/recorded_tool_speeds = list() // handle drapes separately so they're always on the bottom if (locate(/obj/item/surgical_drapes) in contents) . += "drapes" // compile all the overlays from items inside us for(var/obj/item/surgery_tool in src) // the overlay we will use if we want to display this one var/actual_overlay = surgery_tool.get_surgery_tool_overlay(tray_extended = !is_portable) if (isnull(actual_overlay)) continue // nothing to see here // if we don't have tool behaviour then just record the overlay if(!length(surgery_tool.get_all_tool_behaviours())) surgery_overlays[surgery_tool] = actual_overlay continue // if we have at least one tool behaviour, check if we already recorded a faster one for (var/surgery_tool_type in surgery_tool.get_all_tool_behaviours()) var/highest_speed = LAZYACCESS(recorded_tool_speeds, surgery_tool_type) || INFINITY // bigger number = slower if(surgery_tool.toolspeed > highest_speed) continue // the existing tool was worse than us, ditch it surgery_overlays -= surgery_tool_type LAZYSET(recorded_tool_speeds, surgery_tool_type, surgery_tool.toolspeed) surgery_overlays[surgery_tool_type] = actual_overlay for(var/surgery_tool in surgery_overlays) . |= surgery_overlays[surgery_tool] ///Sets the surgery tray's deployment state. Silent if user is null. /obj/item/surgery_tray/proc/set_tray_mode(new_mode, mob/user) is_portable = new_mode density = !is_portable if(user) user.visible_message(span_notice("[user] [is_portable ? "retracts" : "extends"] [src]'s wheels."), span_notice("You [is_portable ? "retract" : "extend"] [src]'s wheels.")) if(is_portable) interaction_flags_item |= INTERACT_ITEM_ATTACK_HAND_PICKUP passtable_on(src, type) RemoveElement(/datum/element/noisy_movement) else interaction_flags_item &= ~INTERACT_ITEM_ATTACK_HAND_PICKUP passtable_off(src, type) AddElement(/datum/element/noisy_movement) update_appearance() /obj/item/surgery_tray/equipped(mob/user, slot, initial) . = ..() if(!is_portable) set_tray_mode(TRUE, user) /obj/item/surgery_tray/attack_self(mob/user, modifiers) . = ..() if(.) return var/turf/open/placement_turf = get_turf(user) if(isgroundlessturf(placement_turf) || isclosedturf(placement_turf)) balloon_alert(user, "can't deploy!") return TRUE if(!user.transferItemToLoc(src, placement_turf)) balloon_alert(user, "tray stuck!") return TRUE set_tray_mode(FALSE, user) return /obj/item/surgery_tray/attack_hand(mob/living/user) if(!user.can_perform_action(src, NEED_HANDS)) return ..() if(!length(contents)) balloon_alert(user, "empty!") else var/obj/item/grabbies = pick(contents) if(atom_storage.remove_single(user, grabbies, drop_location())) user.put_in_hands(grabbies) return TRUE /obj/item/surgery_tray/screwdriver_act_secondary(mob/living/user, obj/item/tool) . = ..() tool.play_tool_sound(src) to_chat(user, span_notice("You begin taking apart [src].")) if(!tool.use_tool(src, user, 1 SECONDS)) return deconstruct(TRUE) to_chat(user, span_notice("[src] has been taken apart.")) /obj/item/surgery_tray/dump_contents() var/atom/drop_point = drop_location() for(var/atom/movable/tool as anything in contents) tool.forceMove(drop_point) /obj/item/surgery_tray/atom_deconstruct(disassembled = TRUE) dump_contents() new /obj/item/stack/rods(drop_location(), 2) new /obj/item/stack/sheet/mineral/silver(drop_location()) /obj/item/surgery_tray/deployed is_portable = FALSE /obj/item/surgery_tray/full starting_items = list( /obj/item/blood_filter, /obj/item/bonesetter, /obj/item/cautery, /obj/item/circular_saw, /obj/item/clothing/mask/surgical, /obj/item/hemostat, /obj/item/razor/surgery, /obj/item/retractor, /obj/item/scalpel, /obj/item/stack/medical/bone_gel, /obj/item/stack/sticky_tape/surgical, /obj/item/surgical_drapes, /obj/item/surgicaldrill, ) /obj/item/surgery_tray/full/deployed is_portable = FALSE /obj/item/surgery_tray/full/morgue name = "autopsy tray" desc = "A Deforest brand surgery tray, made for use in morgues. It is a folding model, \ meaning the wheels on the bottom can be extended outwards, making it a cart." starting_items = list( /obj/item/blood_filter, /obj/item/bonesetter, /obj/item/cautery/cruel, /obj/item/circular_saw, /obj/item/clothing/mask/surgical, /obj/item/hemostat/cruel, /obj/item/razor/surgery, /obj/item/retractor/cruel, /obj/item/scalpel/cruel, /obj/item/stack/medical/bone_gel, /obj/item/stack/sticky_tape/surgical, /obj/item/surgical_drapes, /obj/item/surgicaldrill, ) /obj/item/surgery_tray/full/morgue/deployed is_portable = FALSE /// Surgery tray with advanced tools for debug /obj/item/surgery_tray/full/advanced starting_items = list( /obj/item/scalpel/advanced, /obj/item/retractor/advanced, /obj/item/cautery/advanced, /obj/item/surgical_drapes, /obj/item/reagent_containers/medigel/sterilizine, /obj/item/bonesetter, /obj/item/blood_filter, /obj/item/stack/medical/bone_gel, /obj/item/stack/sticky_tape/surgical, /obj/item/clothing/mask/surgical, ) /obj/effect/spawner/surgery_tray name = "surgery tray spawner" icon = 'icons/obj/medical/medicart.dmi' icon_state = "tray" /// Tray to usually spawn in. var/tray_to_spawn = /obj/item/surgery_tray /// Toolbox to sometimes replace the above tray with. var/rare_toolbox_replacement = /obj/item/storage/toolbox/medical /// Chance for replacement var/toolbox_chance = 1 /obj/effect/spawner/surgery_tray/Initialize(mapload) . = ..() if(prob(toolbox_chance)) new rare_toolbox_replacement(loc) return new tray_to_spawn(loc, TRUE) /obj/effect/spawner/surgery_tray/full name = "full surgery tray spawner" icon_state = "tray" tray_to_spawn = /obj/item/surgery_tray/full rare_toolbox_replacement = /obj/item/storage/toolbox/medical/full /obj/effect/spawner/surgery_tray/full/deployed name = "full deployed tray spawner" icon_state = "medicart" tray_to_spawn = /obj/item/surgery_tray/full /obj/effect/spawner/surgery_tray/full/morgue name = "full autopsy tray spawner" icon_state = "tray" tray_to_spawn = /obj/item/surgery_tray/full/morgue rare_toolbox_replacement = /obj/item/storage/toolbox/medical/coroner toolbox_chance = 3 // tray is rarer, so toolbox is more common /obj/effect/spawner/surgery_tray/full/morgue/deployed name = "full deployed autopsy tray spawner" icon_state = "medicart" tray_to_spawn = /obj/item/surgery_tray/full/morgue/deployed
0
0.686832
1
0.686832
game-dev
MEDIA
0.801314
game-dev
0.914799
1
0.914799
AlessioDP/Parties
1,669
bukkit/src/main/java/com/alessiodp/parties/bukkit/addons/external/PlaceholderAPIHandler.java
package com.alessiodp.parties.bukkit.addons.external; import com.alessiodp.core.common.configuration.Constants; import com.alessiodp.parties.common.PartiesPlugin; import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import com.alessiodp.parties.bukkit.addons.external.hooks.PAPIHook; import org.jetbrains.annotations.NotNull; import java.util.UUID; @RequiredArgsConstructor public class PlaceholderAPIHandler { @NotNull private final PartiesPlugin plugin; private static final String ADDON_NAME = "PlaceholderAPI"; private static boolean firstTime = true; private static boolean active; private static PAPIHook hook; public void init() { if (active) { // Already active, print hooked then return plugin.getLoggerManager().log(String.format(Constants.DEBUG_ADDON_HOOKED, ADDON_NAME), true); return; } if (firstTime) { firstTime = false; // Register PAPI only one time, this is called by server thread on startup (async not supported) if (Bukkit.getPluginManager().isPluginEnabled(ADDON_NAME)) { hook = new PAPIHook(plugin); if (hook.register()) { active = true; plugin.getLoggerManager().log(String.format(Constants.DEBUG_ADDON_HOOKED, ADDON_NAME), true); } } } } public static String getPlaceholders(UUID uuid, String message) { String ret = message; if (active && hook != null) ret = hook.parsePlaceholders(Bukkit.getOfflinePlayer(uuid), message); return ret; } public static String formatRawPlaceholder(UUID uuid, String placeholder) { if (active && hook != null) return hook.parsePlaceholders(Bukkit.getOfflinePlayer(uuid), placeholder); return null; } }
0
0.736644
1
0.736644
game-dev
MEDIA
0.932423
game-dev
0.559474
1
0.559474
Lothrazar/Cyclic
4,906
src/main/java/com/lothrazar/cyclic/block/generatorfluid/RecipeGeneratorFluid.java
package com.lothrazar.cyclic.block.generatorfluid; import java.util.List; import com.google.gson.JsonObject; import com.lothrazar.cyclic.ModCyclic; import com.lothrazar.cyclic.registry.CyclicRecipeType; import com.lothrazar.library.recipe.ingredient.EnergyIngredient; import com.lothrazar.library.recipe.ingredient.FluidTagIngredient; import com.lothrazar.library.util.RecipeUtil; import net.minecraft.core.NonNullList; import net.minecraft.core.RegistryAccess; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.registries.ForgeRegistries; public class RecipeGeneratorFluid implements Recipe<TileGeneratorFluid> { private final ResourceLocation id; private NonNullList<Ingredient> ingredients = NonNullList.create(); public final FluidTagIngredient fluidIng; private final EnergyIngredient energy; public RecipeGeneratorFluid(ResourceLocation id, FluidTagIngredient in, EnergyIngredient energy) { this.id = id; this.fluidIng = in; this.energy = energy; } @Override public boolean isSpecial() { return true; } @Override public ItemStack assemble(TileGeneratorFluid inv, RegistryAccess ra) { return ItemStack.EMPTY; } @Override public boolean canCraftInDimensions(int width, int height) { return true; } @Override public ItemStack getResultItem(RegistryAccess ra) { return ItemStack.EMPTY; } @Override public ResourceLocation getId() { return id; } // @Override public FluidStack getRecipeFluid() { return fluidIng.getFluidStack(); } public List<Fluid> getFluidsFromTag() { TagKey<Fluid> tag = ForgeRegistries.FLUIDS.tags().createTagKey(new ResourceLocation(this.fluidIng.getTag())); List<Fluid> list = ForgeRegistries.FLUIDS.tags().getTag(tag).stream().toList(); return list; } @Override public boolean matches(TileGeneratorFluid inv, Level worldIn) { try { TileGeneratorFluid tile = inv; return RecipeUtil.matchFluid(tile.getFluid(), this.fluidIng); } catch (ClassCastException e) { return false; } } public boolean matches(ItemStack current, Ingredient ing) { if (ing == Ingredient.EMPTY) { //it must be empty return current.isEmpty(); } if (current.isEmpty()) { return ing == Ingredient.EMPTY; } return ing.test(current); } public ItemStack[] ingredientAt(int slot) { Ingredient ing = ingredients.get(slot); return ing.getItems(); } @Override public NonNullList<Ingredient> getIngredients() { return ingredients; } @Override public RecipeType<?> getType() { return CyclicRecipeType.GENERATOR_FLUID.get(); } @Override public RecipeSerializer<?> getSerializer() { return CyclicRecipeType.GENERATOR_FLUID_S.get(); } public int getTicks() { return energy.getTicks(); } public int getRfpertick() { return energy.getRfPertick(); } public int getRfTotal() { return this.getRfpertick() * this.getTicks(); } public static class SerializeGenerateFluid implements RecipeSerializer<RecipeGeneratorFluid> { public SerializeGenerateFluid() {} /** * The fluid stuff i was helped out a ton by looking at this https://github.com/mekanism/Mekanism/blob/921d10be54f97518c1f0cb5a6fc64bf47d5e6773/src/api/java/mekanism/api/SerializerHelper.java#L129 */ @Override public RecipeGeneratorFluid fromJson(ResourceLocation recipeId, JsonObject json) { RecipeGeneratorFluid r = null; try { // Ingredient inputFirst = Ingredient.deserialize(JSONUtils.getJsonObject(json, "fuel")); FluidTagIngredient fs = RecipeUtil.parseFluid(json, "fuel"); r = new RecipeGeneratorFluid(recipeId, fs, new EnergyIngredient(json)); } catch (Exception e) { ModCyclic.LOGGER.error("Error loading recipe " + recipeId, e); } return r; } @Override public RecipeGeneratorFluid fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { return new RecipeGeneratorFluid(recipeId, FluidTagIngredient.readFromPacket(buffer), new EnergyIngredient(buffer.readInt(), buffer.readInt())); } @Override public void toNetwork(FriendlyByteBuf buffer, RecipeGeneratorFluid recipe) { recipe.fluidIng.writeToPacket(buffer); buffer.writeInt(recipe.energy.getRfPertick()); buffer.writeInt(recipe.energy.getTicks()); } } }
0
0.889587
1
0.889587
game-dev
MEDIA
0.996409
game-dev
0.930275
1
0.930275
simeonpilgrim/coab
3,154
Classes/GeoBlock.cs
using System; using System.Collections.Generic; using System.Text; namespace Classes { public class GeoBlock { byte[] data; public MapInfo[,] maps; public void LoadData(byte[] _data) { data = new byte[0x400]; System.Array.Copy(_data, 2, data, 0, 0x400); maps = new MapInfo[16, 16]; for (int y = 0; y < 16; y++) { for (int x = 0; x < 16; x++) { maps[y, x] = new MapInfo(data, x, y); } } } } public class WallDefs { const int maxBlocks = 3; public WallDefBlock[] blocks = new WallDefBlock[maxBlocks]; public WallDefs() { blocks[0] = new WallDefBlock(); blocks[1] = new WallDefBlock(); blocks[2] = new WallDefBlock(); } public void LoadData(int baseSet, byte[] _data) { int offset = 0; for (int i = 0; i < (_data.Length / 780); i++) { blocks[baseSet + i - 1].LoadData(_data, offset); offset += 780; } } public void BlockOffset(int set, int offset) { blocks[set - 1].Offset(offset); } } public class WallDefBlock { byte[,] data = new byte[5, 156]; public void LoadData(byte[] _data, int offset) { for (int y = 0; y < 5; y++) { for (int x = 0; x < 156; x++) { data[y, x] = _data[offset++]; } } } public int Id(int y, int x) { return data[y, x]; } public void Offset(int off) { for (int y = 0; y < 5; y++) { for (int x = 0; x < 156; x++) { if (data[y, x] >= 0x2D) { data[y, x] += (byte)off; } } } } } public class MapInfo { public byte wall_type_dir_0; public byte wall_type_dir_2; public byte wall_type_dir_4; public byte wall_type_dir_6; public byte x2; public byte x3_dir_0; public byte x3_dir_2; public byte x3_dir_4; public byte x3_dir_6; internal MapInfo(byte[] data, int map_x, int map_y) { int map_y_x16 = map_y << 4; wall_type_dir_0 = (byte)((data[map_x + map_y_x16] >> 4) & 0x0f); wall_type_dir_2 = (byte)((data[map_x + map_y_x16]) & 0x0f); wall_type_dir_4 = (byte)((data[0x100 + map_x + map_y_x16] >> 4) & 0x0f); wall_type_dir_6 = (byte)((data[0x100 + map_x + map_y_x16]) & 0x0f); x2 = data[0x200 + map_y_x16 + map_x]; byte b = data[0x300 + map_y_x16 + map_x]; x3_dir_6 = (byte)((b >> 6) & 3); x3_dir_4 = (byte)((b >> 4) & 3); x3_dir_2 = (byte)((b >> 2) & 3); x3_dir_0 = (byte)(b & 3); } } }
0
0.76936
1
0.76936
game-dev
MEDIA
0.796295
game-dev
0.76519
1
0.76519
buxx/OpenCombat
1,998
battle_server/src/runner/victory.rs
use battle_core::{ config::END_MORALE, game::{flag::FlagOwnership, Side}, state::battle::{ message::BattleStateMessage, phase::{EndReason, Phase, Victorious}, }, }; use super::{message::RunnerMessage, Runner}; impl Runner { pub fn tick_victory(&self) -> Vec<RunnerMessage> { puffin::profile_scope!("tick_victory"); if self.battle_state.frame_i() % self.config.victory_update_freq() == 0 { // Victory by morale if self.battle_state.a_morale().0 <= END_MORALE { return vec![RunnerMessage::BattleState(BattleStateMessage::SetPhase( Phase::End(Victorious(Side::B), EndReason::Morale), ))]; } if self.battle_state.b_morale().0 <= END_MORALE { return vec![RunnerMessage::BattleState(BattleStateMessage::SetPhase( Phase::End(Victorious(Side::A), EndReason::Morale), ))]; } // Victory by flags if !self.battle_state.flags().ownerships().is_empty() { if self .battle_state .flags() .ownerships() .iter() .all(|(_, o)| o == &FlagOwnership::A) { return vec![RunnerMessage::BattleState(BattleStateMessage::SetPhase( Phase::End(Victorious(Side::A), EndReason::Flags), ))]; } if self .battle_state .flags() .ownerships() .iter() .all(|(_, o)| o == &FlagOwnership::B) { return vec![RunnerMessage::BattleState(BattleStateMessage::SetPhase( Phase::End(Victorious(Side::B), EndReason::Flags), ))]; } } } vec![] } }
0
0.707859
1
0.707859
game-dev
MEDIA
0.952445
game-dev
0.969498
1
0.969498
blendogames/SkinDeep
3,124
d3xp/bc_trigger_sneeze.cpp
#include "trigger.h" #include "Player.h" #include "ai/AI.h" #include "bc_trigger_sneeze.h" //Sneeze trigger. Fires off every 300 ms. const int AI_TOUCH_DESPAWNDELAY = 1500; //after AI touches it, make it despawn after XXX ms. We despawn it so that the AI doesn't just get stuck in the same cloud for a long time. But we want the cloud to visually hang around for at least a short time. const int DESPAWN_PARTICLETIME = 3000; //how long it takes for particles to despawn. This is dependent on the particle durations in the .prt file. const int UPDATETIME = 300; CLASS_DECLARATION(idTrigger_Multi, idTrigger_sneeze) EVENT(EV_Touch, idTrigger_sneeze::Event_Touch) END_CLASS idTrigger_sneeze::idTrigger_sneeze() { } void idTrigger_sneeze::Spawn() { idTrigger_Multi::Spawn(); lastUpdatetime = 0; multiplier = spawnArgs.GetFloat("multiplier", "1"); maxlifetime = gameLocal.time + spawnArgs.GetInt("spewLifetime"); //Particle fx. particleEmitter = NULL; idDict splashArgs; splashArgs.Set("model", spawnArgs.GetString("spewParticle", "pepperburst01.prt")); splashArgs.Set("start_off", "1"); splashArgs.SetVector("origin", this->GetPhysics()->GetOrigin()); particleEmitter = static_cast<idFuncEmitter *>(gameLocal.SpawnEntityType(idFuncEmitter::Type, &splashArgs)); particleEmitter->SetActive(true); active = true; touchedByAI = false; } void idTrigger_sneeze::Save(idSaveGame* savefile) const { savefile->WriteInt( lastUpdatetime ); // int lastUpdatetime savefile->WriteFloat( multiplier ); // float multiplier savefile->WriteObject( particleEmitter ); // idFuncEmitter * particleEmitter savefile->WriteInt( maxlifetime ); // int maxlifetime savefile->WriteBool( active ); // bool active savefile->WriteBool( touchedByAI ); // bool touchedByAI } void idTrigger_sneeze::Restore(idRestoreGame* savefile) { savefile->ReadInt( lastUpdatetime ); // int lastUpdatetime savefile->ReadFloat( multiplier ); // float multiplier savefile->ReadObject( CastClassPtrRef(particleEmitter) ); // idFuncEmitter * particleEmitter savefile->ReadInt( maxlifetime ); // int maxlifetime savefile->ReadBool( active ); // bool active savefile->ReadBool( touchedByAI ); // bool touchedByAI } void idTrigger_sneeze::Event_Touch(idEntity* other, trace_t* trace) { if (other->IsType(idAI::Type) && static_cast<idAI*>(other)->team == TEAM_ENEMY) { //do the special Stun Damage. static_cast<idAI *>(other)->StartStunState("damage_sneeze"); if (!touchedByAI) { touchedByAI = true; maxlifetime = min(gameLocal.time + AI_TOUCH_DESPAWNDELAY, maxlifetime); } } if (!other->IsType(idPlayer::Type)) return; if (lastUpdatetime > gameLocal.time) return; lastUpdatetime = gameLocal.time + UPDATETIME; ((idPlayer *)other)->SetSneezeDelta(false, multiplier); } void idTrigger_sneeze::Think() { if (gameLocal.time > maxlifetime) { Despawn(); } } void idTrigger_sneeze::Despawn() { if (!active) return; active = false; particleEmitter->SetActive(false); particleEmitter->PostEventMS(&EV_Remove, DESPAWN_PARTICLETIME); particleEmitter = nullptr; this->PostEventMS(&EV_Remove, 0); }
0
0.911578
1
0.911578
game-dev
MEDIA
0.94967
game-dev
0.995021
1
0.995021
overte-org/overte
2,953
script-archive/drylake/helicopter.js
var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/helicopter.fbx?v3"; var animationURL = "https://s3.amazonaws.com/hifi-public/eric/models/bladeAnimation.fbx?v7"; var spawnPosition = { x: 1031, y: 145, z: 1041 }; var speed = 0; var helicopterSound = SoundCache.getSound("https://hifi-public.s3.amazonaws.com/ryan/helicopter.L.wav"); var audioInjector = Audio.playSound(helicopterSound, { volume: 0.3, loop: true }); // These constants define the Spotlight position and orientation relative to the model var MODEL_LIGHT_POSITION = { x: 2, y: 0, z: -5 }; var MODEL_LIGHT_ROTATION = Quat.angleAxis(-90, { x: 1, y: 0, z: 0 }); // Evaluate the world light entity positions and orientations from the model ones function evalLightWorldTransform(modelPos, modelRot) { return { p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, MODEL_LIGHT_POSITION)), q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION) }; } var helicopter = Entities.addEntity({ type: "Model", name: "Helicopter", modelURL: modelURL, animation: { url: animationURL, running: true, fps: 180 }, dimensions: { x: 12.13, y: 3.14, z: 9.92 }, position: spawnPosition, }); var spotlight = Entities.addEntity({ type: "Light", name: "helicopter light", intensity: 2, color: { red: 200, green: 200, blue: 255 }, intensity: 1, dimensions: { x: 2, y: 2, z: 200 }, exponent: 0.01, cutoff: 10, isSpotlight: true }); var debugLight = Entities.addEntity({ type: "Box", dimensions: { x: .1, y: .1, z: .3 }, color: { red: 200, green: 200, blue: 0 } }); function cleanup() { Entities.deleteEntity(debugLight); Entities.deleteEntity(helicopter); Entities.deleteEntity(spotlight); } function update() { var modelProperties = Entities.getEntityProperties(helicopter, ['position', 'rotation']); var lightTransform = evalLightWorldTransform(modelProperties.position, modelProperties.rotation); Entities.editEntity(spotlight, { position: lightTransform.p, rotation: lightTransform.q }); Entities.editEntity(debugLight, { position: lightTransform.p, rotation: lightTransform.q }); audioInjector.setOptions({ position: modelProperties.position, }); //Move forward var newRotation = Quat.multiply(modelProperties.rotation, { x: 0, y: .002, z: 0, w: 1 }) var newPosition = Vec3.sum(modelProperties.position, Vec3.multiply(speed, Quat.getFront(modelProperties.rotation))); Entities.editEntity(helicopter, { position: newPosition, rotation: newRotation }) } Script.update.connect(update); Script.scriptEnding.connect(cleanup);
0
0.668639
1
0.668639
game-dev
MEDIA
0.733543
game-dev,graphics-rendering
0.96553
1
0.96553
bates64/papermario-dx
9,362
src/world/area_omo/omo_10/train.c
#include "omo_10.h" #include "../common/ToyTrain.inc.c" #include "../common/TrainStationSwitches.inc.c" Vec2i N(D_80243AC0_DDB470) = { 10, -105 }; s32 N(D_80243AC8_DDB478)[] = { Float(-2.266), Float(-209.494), Float(90.0), Float(124.202), Float(-209.494), Float(262.5), Float(-245.336), Float(479.165), Float(-503.546), -1, -1, -1 }; EvtScript N(D_80243AF8_DDB4A8) = { Call(FadeOutMusic, 0, 3000) Call(DisablePlayerInput, TRUE) Call(DisablePartnerAI, 0) Call(SetNpcAnimation, NPC_PARTNER, PARTNER_ANIM_IDLE) Wait(10) Call(DisablePlayerPhysics, TRUE) Exec(N(EVS_TrainUnk_C)) Set(AB_OMO_5, 3) Set(LVar0, Ref(N(D_80243AC8_DDB478))) ExecWait(N(EVS_TrainUnk_D)) Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_o961, COLLIDER_FLAGS_UPPER_MASK) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_80243AC8_DDB478))) Set(MV_TrainUnk_02, 1) Set(MF_TrainUnk_00, TRUE) Label(10) IfLt(MV_TrainPos, 350) Wait(1) Goto(10) EndIf Call(GotoMap, Ref("omo_16"), omo_16_ENTRY_0) Set(GB_OMO_TrainDestination, 3) Wait(100) Return End }; s32 N(D_80243C68_DDB618)[] = { Float(-2.266), Float(-209.494), Float(270.0), Float(-128.733), Float(-209.494), Float(-262.5), Float(-245.336), Float(-353.418), Float(-353.688), Float(-479.165), Float(-503.546), -1, -1, -1 }; EvtScript N(D_80243CA0_DDB650) = { Call(FadeOutMusic, 0, 3000) Call(DisablePlayerInput, TRUE) Call(DisablePartnerAI, 0) Call(SetNpcAnimation, NPC_PARTNER, PARTNER_ANIM_IDLE) Wait(10) Call(DisablePlayerPhysics, TRUE) Exec(N(EVS_TrainUnk_C)) Set(AB_OMO_5, 3) Set(LVar0, Ref(N(D_80243C68_DDB618))) ExecWait(N(EVS_TrainUnk_D)) Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_o961, COLLIDER_FLAGS_UPPER_MASK) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_80243C68_DDB618))) Set(MV_TrainUnk_02, 1) Set(MF_TrainUnk_00, TRUE) Label(10) IfGt(MV_TrainPos, -350) Wait(1) Goto(10) EndIf Call(GotoMap, Ref("omo_16"), omo_16_ENTRY_1) Set(GB_OMO_TrainDestination, 2) Wait(100) Return End }; s32 N(D_80243E10_DDB7C0)[] = { Float(414.885), Float(-426.942), Float(219.92), Float(353.553), Float(-353.553), Float(262.5), Float(-245.336), Float(124.202), Float(-209.494), Float(-42.27), Float(-209.49), -1, -1, -1 }; s32 N(D_80243E48_DDB7F8)[] = { Float(414.885), Float(-426.942), Float(219.92), Float(353.553), Float(-353.553), Float(262.5), Float(-245.336), Float(124.202), Float(-209.494), Float(-128.733), Float(-209.494), Float(-262.5), Float(-245.336), Float(-353.418), Float(-353.688), Float(-479.165), Float(-503.546), -1, -1, -1 }; EvtScript N(D_80243E98_DDB848) = { Call(DisablePlayerInput, TRUE) Call(DisablePlayerPhysics, TRUE) Call(SetPlayerActionState, ACTION_STATE_LAND) Call(DisablePartnerAI, 0) Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_o961, COLLIDER_FLAGS_UPPER_MASK) IfEq(AB_OMO_6, 3) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_80243E10_DDB7C0))) Set(MV_TrainUnk_02, 2) Exec(N(EVS_Scene_RideTrain)) Set(MF_TrainUnk_00, TRUE) Wait(1) ExecGetTID(N(EVS_TrainUnk_A), LVarB) Label(10) IfEq(MF_TrainUnk_00, TRUE) Wait(1) Goto(10) EndIf Wait(20) KillThread(LVarB) Exec(N(EVS_TrainUnk_B)) Call(EnableCameraFollowPlayerY) Set(LVar9, Ref(N(D_80243AC0_DDB470))) ExecWait(N(EVS_TrainUnk_E)) Call(SpeakToPlayer, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0011) Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_CLEAR_BITS, COLLIDER_o961, COLLIDER_FLAGS_UPPER_MASK) Call(DisablePlayerPhysics, FALSE) Call(EnablePartnerAI) Call(DisablePlayerInput, FALSE) Else Exec(N(EVS_TrainUnk_A)) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_80243E48_DDB7F8))) Set(MV_TrainUnk_02, 0) Exec(N(EVS_Scene_RideTrain)) Set(MF_TrainUnk_00, TRUE) Wait(1) Exec(N(EVS_TrainUnk_H)) Label(20) IfGt(MV_TrainPos, -350) Wait(1) Goto(20) EndIf Call(GotoMap, Ref("omo_16"), omo_16_ENTRY_1) Set(GB_OMO_TrainDestination, 2) Wait(100) EndIf Return End }; s32 N(D_80244150_DDBB00)[] = { Float(-414.885), Float(-426.942), Float(140.075), Float(-353.418), Float(-353.688), Float(-262.5), Float(-245.336), Float(-128.733), Float(-209.494), Float(37.73), Float(-209.49), -1, -1, -1 }; s32 N(D_80244188_DDBB38)[] = { Float(-414.885), Float(-426.942), Float(140.075), Float(-353.418), Float(-353.688), Float(-262.5), Float(-245.336), Float(-128.733), Float(-209.494), Float(124.202), Float(-209.494), Float(262.5), Float(-245.336), Float(479.165), Float(-503.546), -1, -1, -1 }; EvtScript N(D_802441D0_DDBB80) = { Call(DisablePlayerInput, TRUE) Call(DisablePlayerPhysics, TRUE) Call(SetPlayerActionState, ACTION_STATE_LAND) Call(DisablePartnerAI, 0) Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_o961, COLLIDER_FLAGS_UPPER_MASK) IfEq(AB_OMO_6, 3) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_80244150_DDBB00))) Set(MV_TrainUnk_02, 2) Exec(N(EVS_Scene_RideTrain)) Set(MF_TrainUnk_00, TRUE) Wait(1) ExecGetTID(N(EVS_TrainUnk_A), LVarB) Label(10) IfEq(MF_TrainUnk_00, TRUE) Wait(1) Goto(10) EndIf Wait(20) KillThread(LVarB) Exec(N(EVS_TrainUnk_B)) Call(EnableCameraFollowPlayerY) Set(LVar9, Ref(N(D_80243AC0_DDB470))) ExecWait(N(EVS_TrainUnk_E)) Call(SpeakToPlayer, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0011) Call(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_CLEAR_BITS, COLLIDER_o961, COLLIDER_FLAGS_UPPER_MASK) Call(DisablePlayerPhysics, FALSE) Call(EnablePartnerAI) Call(DisablePlayerInput, FALSE) Else Exec(N(EVS_TrainUnk_A)) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_80244188_DDBB38))) Set(MV_TrainUnk_02, 0) Exec(N(EVS_Scene_RideTrain)) Set(MF_TrainUnk_00, TRUE) Wait(1) Exec(N(EVS_TrainUnk_H)) Label(20) IfLt(MV_TrainPos, 350) Wait(1) Goto(20) EndIf Call(GotoMap, Ref("omo_16"), omo_16_ENTRY_0) Set(GB_OMO_TrainDestination, 3) Wait(100) EndIf Return End }; s32 N(D_80244488_DDBE38)[] = { 2, 1, 0, }; s32 N(D_80244494_DDBE44)[] = { 0, 1, 2, }; EvtScript N(D_802444A0_DDBE50) = { IfEq(MF_EitherSwitchPressed, FALSE) Call(SpeakToPlayer, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0006) Else IfEq(AF_OMO_UsingRightSwitch, FALSE) Call(SpeakToPlayer, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0007) Call(ShowChoice, MSG_Choice_0043) IfNe(LVar0, 3) Call(CloseMessage) UseBuf(Ref(N(D_80244488_DDBE38))) Add(LVar0, 1) Loop(LVar0) BufRead1(LVar1) EndLoop Set(AB_OMO_6, LVar1) ExecWait(N(D_80243CA0_DDB650)) Else Call(ContinueSpeech, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0008) EndIf Else Call(SpeakToPlayer, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0007) Call(ShowChoice, MSG_Choice_0042) IfNe(LVar0, 3) Call(CloseMessage) UseBuf(Ref(N(D_80244494_DDBE44))) Add(LVar0, 1) Loop(LVar0) BufRead1(LVar1) EndLoop Set(AB_OMO_6, LVar1) ExecWait(N(D_80243AF8_DDB4A8)) Else Call(ContinueSpeech, NPC_Conductor, ANIM_TrainToad_Talk, ANIM_TrainToad_Idle, 0, MSG_CH4_0008) EndIf EndIf EndIf Return End }; s32 N(D_802446B8_DDC068)[] = { Float(-2.266), Float(-209.494), Float(90.0), -1, -1, -1 }; EvtScript N(EVS_SetupTrain) = { ExecWait(N(EVS_SetupSwitches)) Call(GetLoadType, LVar1) IfEq(LVar1, 1) Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_802446B8_DDC068))) Set(MV_TrainUnk_02, 0) Exec(N(EVS_Scene_RideTrain)) Set(MF_TrainUnk_00, TRUE) Else Call(GetEntryID, LVar0) Switch(LVar0) CaseEq(omo_10_ENTRY_2) Exec(N(D_802441D0_DDBB80)) CaseEq(omo_10_ENTRY_3) Exec(N(D_80243E98_DDB848)) CaseDefault Set(MV_TrainUnk_00, 0) Set(MV_TrainUnk_01, Ref(N(D_802446B8_DDC068))) Set(MV_TrainUnk_02, 0) Exec(N(EVS_Scene_RideTrain)) Set(MF_TrainUnk_00, TRUE) EndSwitch EndIf Return End };
0
0.864376
1
0.864376
game-dev
MEDIA
0.73691
game-dev
0.838741
1
0.838741
RedpointGames/uet
14,224
UET/Redpoint.Uefs.Daemon.PackageFs/CachingStorage/CachingPackageFs.cs
namespace Redpoint.Uefs.Daemon.PackageFs.CachingStorage { using Microsoft.Extensions.Logging; using Redpoint.Hashing; using Redpoint.Uefs.Daemon.PackageFs.Tagging; using Redpoint.Uefs.Daemon.RemoteStorage; using Redpoint.Uefs.Protocol; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization.Metadata; internal abstract class CachingPackageFs : IPackageFs { private readonly ILogger _logger; private readonly string _vfsmountStoragePath; private readonly string _cacheStoragePath; private readonly string _infoStoragePath; private readonly string _tagStoragePath; private Dictionary<string, CachingInfoJson> _currentInfos = new Dictionary<string, CachingInfoJson>(); private Dictionary<string, PackageStorageTag> _tagReferences = new Dictionary<string, PackageStorageTag>(); protected CachingPackageFs( ILogger logger, string storagePath) { _logger = logger; _vfsmountStoragePath = Path.Combine( storagePath, "hostpkgs", "vfsmount"); Directory.CreateDirectory(_vfsmountStoragePath); _cacheStoragePath = Path.Combine( storagePath, "hostpkgs", "cache"); Directory.CreateDirectory(_cacheStoragePath); _infoStoragePath = Path.Combine( storagePath, "hostpkgs", "info"); Directory.CreateDirectory(_infoStoragePath); _tagStoragePath = Path.Combine( storagePath, "hostpkgs", "tags"); Directory.CreateDirectory(_tagStoragePath); } protected void Init() { PurgeDanglingPackages(); // Load all of the tags. foreach (var file in new DirectoryInfo(_tagStoragePath).GetFiles()) { if (file.Extension == ".tag") { var info = JsonSerializer.Deserialize(File.ReadAllText(file.FullName).Trim(), PackageFsInternalJsonSerializerContext.Default.PackageStorageTag); if (File.Exists(Path.Combine(_infoStoragePath, info!.Hash + ".info"))) { string tagHash = Hash.Sha256AsHexString(info!.Tag, Encoding.UTF8); if (tagHash == Path.GetFileNameWithoutExtension(file.Name)) { _tagReferences.Add(tagHash, info); } } else { // Invalid tag, delete it. File.Delete(file.FullName); } } } // Load all of the info objects. foreach (var file in new DirectoryInfo(_infoStoragePath).GetFiles()) { if (file.Extension == ".info") { var info = JsonSerializer.Deserialize(File.ReadAllText(file.FullName).Trim(), PackageFsInternalJsonSerializerContext.Default.CachingInfoJson); var hash = Path.GetFileNameWithoutExtension(file.Name); _currentInfos.Add(hash, info!); } } // Mount the implementation. The implementation is expected // to call GetVFSMountPath(). Mount(); } protected string GetVFSMountPath() { return _vfsmountStoragePath; } protected abstract void Mount(); protected abstract void Unmount(); public void Dispose() { _logger.LogInformation($"CachingPackageFs is being disposed!"); // Unmount the implementation. Unmount(); } public async Task<string> PullAsync<T>( IRemoteStorageBlobFactory remoteStorageBlobFactory, string remoteStorageType, T remoteStorageReference, JsonTypeInfo<T> remoteStorageTypeInfo, string packageDigest, string extension, string tagHash, string tag, Action releaseGlobalPullLock, Action<Action<PollingResponse>, string?> updatePollingResponse) { // Check to see if we already have this package on disk. var normalizedPackageHash = packageDigest.Replace(":", "_", StringComparison.Ordinal); if (_currentInfos.ContainsKey(normalizedPackageHash) && File.Exists(Path.Combine(_infoStoragePath, normalizedPackageHash + ".info"))) { // We do. Check if we need to update our tag data. if (_tagReferences.TryGetValue(tagHash, out var tagHashValue) && File.Exists(Path.Combine(_tagStoragePath, tagHash + ".tag"))) { if (tagHashValue.Hash != normalizedPackageHash) { // Update the tag information on disk. tagHashValue.Hash = normalizedPackageHash; await File.WriteAllTextAsync( Path.Combine(_tagStoragePath, tagHash + ".tag"), JsonSerializer.Serialize( tagHashValue, PackageFsInternalJsonSerializerContext.Default.PackageStorageTag)).ConfigureAwait(false); } } else { // Add our new tag reference. _tagReferences[tagHash] = new PackageStorageTag { Tag = tag, Hash = normalizedPackageHash, }; await File.WriteAllTextAsync( Path.Combine(_tagStoragePath, tagHash + ".tag"), JsonSerializer.Serialize( _tagReferences[tagHash], PackageFsInternalJsonSerializerContext.Default.PackageStorageTag)).ConfigureAwait(false); } var earlyResultPath = Path.Combine(_vfsmountStoragePath, normalizedPackageHash + extension); updatePollingResponse( x => { x.CompleteForPackage(earlyResultPath, normalizedPackageHash); }, earlyResultPath); _logger.LogInformation($"skipping pull for {tag}, the on-disk copy is already up-to-date"); return earlyResultPath; } // If we already have this tag hash, delete it as it's now out of date. if (_tagReferences.ContainsKey(tagHash)) { if (File.Exists(Path.Combine(_tagStoragePath, tagHash + ".tag"))) { File.Delete(Path.Combine(_tagStoragePath, tagHash + ".tag")); } _tagReferences.Remove(tagHash); } // Clean up any unused cache files (those that aren't referenced by anything), in case // we need to get more space on disk. PurgeDanglingPackages(); // Store the info so the caching layer can get it on-demand. _logger.LogInformation($"need to configure '{normalizedPackageHash}' as it does not exist on disk"); var infoTargetPath = Path.Combine(_infoStoragePath, normalizedPackageHash + ".info"); long length; using (var blob = remoteStorageBlobFactory.Open()) { length = blob.Length; } var info = new CachingInfoJson { Type = remoteStorageType, SerializedObject = JsonSerializer.Serialize(remoteStorageReference, remoteStorageTypeInfo), Length = length }; await File.WriteAllTextAsync( infoTargetPath, JsonSerializer.Serialize( info, PackageFsInternalJsonSerializerContext.Default.CachingInfoJson)).ConfigureAwait(false); // We now have this info on disk. _currentInfos.Add(normalizedPackageHash, info); _tagReferences[tagHash] = new PackageStorageTag { Hash = normalizedPackageHash, Tag = tag }; await File.WriteAllTextAsync( Path.Combine(_tagStoragePath, tagHash + ".tag"), JsonSerializer.Serialize( _tagReferences[tagHash], PackageFsInternalJsonSerializerContext.Default.PackageStorageTag)).ConfigureAwait(false); // Return the finished operation. var resultPath = Path.Combine(_vfsmountStoragePath, normalizedPackageHash + extension); updatePollingResponse( x => { x.CompleteForPackageWithLength(resultPath, normalizedPackageHash, length); }, resultPath); return resultPath; } public async Task VerifyAsync( bool isFixing, Action releaseGlobalPullLock, Action<Action<PollingResponse>> updatePollingResponse) { var cachedInfos = _currentInfos.ToArray(); releaseGlobalPullLock(); updatePollingResponse(x => { x.VerifyingPackages(cachedInfos.Length); }); for (int v = 0; v < cachedInfos.Length; v++) { var info = cachedInfos[v]; updatePollingResponse(x => { x.VerifyingPackage(v); }); var didError = false; await Task.Run(async () => { try { if (!(await VerifyPackageAsync(isFixing, info.Key, info.Value, updatePollingResponse).ConfigureAwait(false))) { didError = true; } } catch (Exception ex) { updatePollingResponse(x => { x.Error($"Exception while verifying {info.Key}: {ex}"); }); didError = true; } }).ConfigureAwait(false); if (didError) { return; } } updatePollingResponse(x => { x.CompleteForVerifying(); }); } protected abstract Task<bool> VerifyPackageAsync( bool isFixing, string normalizedPackageHash, CachingInfoJson info, Action<Action<PollingResponse>> updatePollingResponse); private void PurgeDanglingPackages() { // Scan all of the tags. var tagReferences = new Dictionary<string, PackageStorageTag>(); foreach (var file in new DirectoryInfo(_tagStoragePath).GetFiles()) { if (file.Extension == ".tag") { var info = JsonSerializer.Deserialize( File.ReadAllText(file.FullName).Trim(), PackageFsInternalJsonSerializerContext.Default.PackageStorageTag); if (File.Exists(Path.Combine(_infoStoragePath, info!.Hash + ".info"))) { string tagHash = Hash.Sha256AsHexString(info!.Tag, Encoding.UTF8); if (tagHash == Path.GetFileNameWithoutExtension(file.Name)) { tagReferences.Add(tagHash, info); } } else { // Invalid tag, delete it. _logger.LogInformation($"Automatically deleted invalid tag: {file.FullName}"); File.Delete(file.FullName); } } } // Scan all of the infos. These hold the actual remote storage data for the images // the tags point to. var infoReferences = new Dictionary<string, CachingInfoJson>(); var infoHashes = new HashSet<string>(); foreach (var file in new DirectoryInfo(_infoStoragePath).GetFiles()) { if (file.Extension == ".info") { var info = JsonSerializer.Deserialize( File.ReadAllText(file.FullName).Trim(), PackageFsInternalJsonSerializerContext.Default.CachingInfoJson); var hash = Path.GetFileNameWithoutExtension(file.Name); infoReferences.Add(hash, info!); infoHashes.Add(hash); } } // Scan all of the cached data. Any data or index files that don't have a filename // that matches the info hashes gets deleted. var filesToDelete = new List<string>(); foreach (var file in new DirectoryInfo(_cacheStoragePath).GetFiles()) { if (file.Extension == ".data" || file.Extension == ".index") { var hash = Path.GetFileNameWithoutExtension(file.Name); if (!infoHashes.Contains(hash)) { filesToDelete.Add(file.FullName); } } } foreach (var fileToDelete in filesToDelete) { _logger.LogInformation($"Automatically deleted dangling file: {fileToDelete}"); File.Delete(fileToDelete); } } } }
0
0.960723
1
0.960723
game-dev
MEDIA
0.220401
game-dev
0.907775
1
0.907775
fulpstation/fulpstation
3,241
code/datums/saymode.dm
/datum/saymode var/key var/mode //Return FALSE if you have handled the message. Otherwise, return TRUE and saycode will continue doing saycode things. //user = whoever said the message //message = the message //language = the language. /datum/saymode/proc/handle_message(mob/living/user, message, datum/language/language) return TRUE /datum/saymode/changeling key = MODE_KEY_CHANGELING mode = MODE_CHANGELING /datum/saymode/changeling/handle_message(mob/living/user, message, datum/language/language) //we can send the message if(!user.mind) return FALSE if(user.mind.has_antag_datum(/datum/antagonist/fallen_changeling)) to_chat(user, span_changeling("<b>We're cut off from the hivemind! We've lost everything! EVERYTHING!!</b>")) return FALSE var/datum/antagonist/changeling/ling_sender = IS_CHANGELING(user) if(!ling_sender) return FALSE if(HAS_TRAIT(user, TRAIT_CHANGELING_HIVEMIND_MUTE)) to_chat(user, span_warning("The poison in the air hinders our ability to interact with the hivemind.")) return FALSE user.log_talk(message, LOG_SAY, tag="changeling [ling_sender.changelingID]") var/msg = span_changeling("<b>[ling_sender.changelingID]:</b> [message]") //the recipients can receive the message for(var/datum/antagonist/changeling/ling_receiver in GLOB.antagonists) if(!ling_receiver.owner) continue var/mob/living/ling_mob = ling_receiver.owner.current //removes types that override the presence of being changeling (for example, borged lings still can't hivemind chat) if(!isliving(ling_mob) || issilicon(ling_mob) || isbrain(ling_mob)) continue // can't receive messages on the hivemind right now if(HAS_TRAIT(ling_mob, TRAIT_CHANGELING_HIVEMIND_MUTE)) continue to_chat(ling_mob, msg, type = MESSAGE_TYPE_RADIO, avoid_highlighting = ling_mob == user) for(var/mob/dead/ghost as anything in GLOB.dead_mob_list) to_chat(ghost, "[FOLLOW_LINK(ghost, user)] [msg]", type = MESSAGE_TYPE_RADIO) return FALSE /datum/saymode/xeno key = "a" mode = MODE_ALIEN /datum/saymode/xeno/handle_message(mob/living/user, message, datum/language/language) if(user.hivecheck()) user.alien_talk(message) return FALSE /datum/saymode/vocalcords key = MODE_KEY_VOCALCORDS mode = MODE_VOCALCORDS /datum/saymode/vocalcords/handle_message(mob/living/user, message, datum/language/language) if(iscarbon(user)) var/mob/living/carbon/C = user var/obj/item/organ/vocal_cords/V = C.get_organ_slot(ORGAN_SLOT_VOICE) if(V?.can_speak_with()) V.handle_speech(message) //message V.speak_with(message) //action return FALSE /datum/saymode/binary //everything that uses .b (silicons, drones) key = MODE_KEY_BINARY mode = MODE_BINARY /datum/saymode/binary/handle_message(mob/living/user, message, datum/language/language) if(isdrone(user)) var/mob/living/basic/drone/drone_user = user drone_user.drone_chat(message) return FALSE if(user.binarycheck()) user.robot_talk(message) return FALSE return FALSE /datum/saymode/holopad key = "h" mode = MODE_HOLOPAD /datum/saymode/holopad/handle_message(mob/living/user, message, datum/language/language) if(isAI(user)) var/mob/living/silicon/ai/AI = user AI.holopad_talk(message, language) return FALSE return TRUE
0
0.660888
1
0.660888
game-dev
MEDIA
0.93994
game-dev
0.792778
1
0.792778
twilight-rs/twilight
11,337
twilight-cache-inmemory/src/model/member.rs
use std::ops::Deref; use serde::Serialize; use twilight_model::{ application::interaction::InteractionMember, gateway::payload::incoming::MemberUpdate, guild::{Member, MemberFlags, PartialMember}, id::{ marker::{RoleMarker, UserMarker}, Id, }, util::{ImageHash, Timestamp}, }; use crate::CacheableMember; /// Computed components required to complete a full cached interaction member /// by implementing [`CacheableMember`]. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ComputedInteractionMember { /// Member's guild avatar. pub avatar: Option<ImageHash>, /// Whether the member is deafened in a voice channel. pub deaf: Option<bool>, /// Member that performed the interaction. pub interaction_member: InteractionMember, /// Whether the member is muted in a voice channel. pub mute: Option<bool>, /// ID of the user relating to the member. pub user_id: Id<UserMarker>, } impl Deref for ComputedInteractionMember { type Target = InteractionMember; fn deref(&self) -> &Self::Target { &self.interaction_member } } /// Represents a cached [`Member`]. /// /// [`Member`]: twilight_model::guild::Member #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CachedMember { pub(crate) avatar: Option<ImageHash>, pub(crate) communication_disabled_until: Option<Timestamp>, pub(crate) deaf: Option<bool>, pub(crate) flags: MemberFlags, pub(crate) joined_at: Option<Timestamp>, pub(crate) mute: Option<bool>, pub(crate) nick: Option<String>, pub(crate) pending: bool, pub(crate) premium_since: Option<Timestamp>, pub(crate) roles: Vec<Id<RoleMarker>>, pub(crate) user_id: Id<UserMarker>, } impl CachedMember { /// Member's guild avatar. pub const fn avatar(&self) -> Option<ImageHash> { self.avatar } /// When the user can resume communication in a guild again. /// /// Checking if this value is [`Some`] is not enough to know if a used is currently /// timed out as Discord doesn't send any events when the timeout expires, and /// therefore the cache is not updated accordingly. You should ensure that the /// provided [`Timestamp`] is not in the past. See [discord-api-docs#4269]. /// /// [discord-api-docs#4269]: https://github.com/discord/discord-api-docs/issues/4269 pub const fn communication_disabled_until(&self) -> Option<Timestamp> { self.communication_disabled_until } /// Whether the member is deafened in a voice channel. pub const fn deaf(&self) -> Option<bool> { self.deaf } /// Flags for the member. /// /// Defaults to an empty bitfield. pub const fn flags(&self) -> MemberFlags { self.flags } /// [`Timestamp`] of this member's join date. pub const fn joined_at(&self) -> Option<Timestamp> { self.joined_at } /// Whether the member is muted in a voice channel. pub const fn mute(&self) -> Option<bool> { self.mute } /// Nickname of the member. pub fn nick(&self) -> Option<&str> { self.nick.as_deref() } /// Whether the member has not yet passed the guild's Membership Screening /// requirements. pub const fn pending(&self) -> bool { self.pending } /// [`Timestamp`] of the date the member boosted the guild. pub const fn premium_since(&self) -> Option<Timestamp> { self.premium_since } /// List of role IDs this member has. #[allow(clippy::missing_const_for_fn)] pub fn roles(&self) -> &[Id<RoleMarker>] { &self.roles } /// ID of the user relating to the member. pub const fn user_id(&self) -> Id<UserMarker> { self.user_id } } impl From<Member> for CachedMember { fn from(member: Member) -> Self { let Member { avatar, communication_disabled_until, deaf, flags, joined_at, mute, nick, pending, premium_since, roles, user, } = member; Self { avatar, communication_disabled_until, deaf: Some(deaf), flags, joined_at, mute: Some(mute), nick, pending, premium_since, roles, user_id: user.id, } } } impl From<ComputedInteractionMember> for CachedMember { fn from(member: ComputedInteractionMember) -> Self { let ComputedInteractionMember { avatar, deaf, mute, user_id, interaction_member, } = member; let InteractionMember { avatar: _, communication_disabled_until, flags, joined_at, nick, pending, permissions: _, premium_since, roles, } = interaction_member; Self { avatar, communication_disabled_until, deaf, flags, joined_at, mute, nick, pending, premium_since, roles, user_id, } } } impl From<(Id<UserMarker>, PartialMember)> for CachedMember { fn from((user_id, member): (Id<UserMarker>, PartialMember)) -> Self { let PartialMember { avatar, communication_disabled_until, deaf, flags, joined_at, mute, nick, permissions: _, premium_since, roles, user, } = member; Self { avatar, communication_disabled_until, deaf: Some(deaf), flags, joined_at, mute: Some(mute), nick, pending: false, premium_since, roles, user_id: user.map_or(user_id, |user| user.id), } } } impl PartialEq<Member> for CachedMember { fn eq(&self, other: &Member) -> bool { self.avatar == other.avatar && self.communication_disabled_until == other.communication_disabled_until && self.deaf == Some(other.deaf) && self.joined_at == other.joined_at && self.mute == Some(other.mute) && self.nick == other.nick && self.pending == other.pending && self.premium_since == other.premium_since && self.roles == other.roles && self.user_id == other.user.id } } impl PartialEq<PartialMember> for CachedMember { fn eq(&self, other: &PartialMember) -> bool { self.communication_disabled_until == other.communication_disabled_until && self.deaf == Some(other.deaf) && self.joined_at == other.joined_at && self.mute == Some(other.mute) && self.nick == other.nick && self.premium_since == other.premium_since && self.roles == other.roles } } impl PartialEq<InteractionMember> for CachedMember { fn eq(&self, other: &InteractionMember) -> bool { self.joined_at == other.joined_at && self.nick == other.nick && self.premium_since == other.premium_since && self.roles == other.roles } } impl CacheableMember for CachedMember { fn roles(&self) -> &[Id<RoleMarker>] { &self.roles } #[cfg(feature = "permission-calculator")] fn communication_disabled_until(&self) -> Option<Timestamp> { self.communication_disabled_until } fn avatar(&self) -> Option<ImageHash> { self.avatar } fn deaf(&self) -> Option<bool> { self.deaf } fn mute(&self) -> Option<bool> { self.mute } fn update_with_member_update(&mut self, member_update: &MemberUpdate) { self.avatar = member_update.avatar; self.deaf = member_update.deaf.or_else(|| self.deaf()); self.mute = member_update.mute.or_else(|| self.mute()); self.nick.clone_from(&member_update.nick); self.roles.clone_from(&member_update.roles); self.joined_at = member_update.joined_at; self.pending = member_update.pending; self.communication_disabled_until = member_update.communication_disabled_until; } } #[cfg(test)] mod tests { use super::CachedMember; use static_assertions::assert_fields; use twilight_model::{ guild::{Member, MemberFlags, PartialMember}, id::Id, user::User, util::Timestamp, }; assert_fields!( CachedMember: deaf, joined_at, mute, nick, pending, premium_since, roles, user_id ); fn cached_member() -> CachedMember { let joined_at = Some(Timestamp::from_secs(1_632_072_645).expect("non zero")); let flags = MemberFlags::BYPASSES_VERIFICATION | MemberFlags::DID_REJOIN; CachedMember { avatar: None, communication_disabled_until: None, deaf: Some(false), flags, joined_at, mute: Some(true), nick: Some("member nick".to_owned()), pending: false, premium_since: None, roles: Vec::new(), user_id: user().id, } } fn user() -> User { User { accent_color: None, avatar: None, avatar_decoration: None, avatar_decoration_data: None, banner: None, bot: false, discriminator: 1, email: None, flags: None, global_name: Some("test".to_owned()), id: Id::new(1), locale: None, mfa_enabled: None, name: "bar".to_owned(), premium_type: None, public_flags: None, system: None, verified: None, } } #[test] fn eq_member() { let joined_at = Some(Timestamp::from_secs(1_632_072_645).expect("non zero")); let flags = MemberFlags::BYPASSES_VERIFICATION | MemberFlags::DID_REJOIN; let member = Member { avatar: None, communication_disabled_until: None, deaf: false, flags, joined_at, mute: true, nick: Some("member nick".to_owned()), pending: false, premium_since: None, roles: Vec::new(), user: user(), }; assert_eq!(cached_member(), member); } #[test] fn eq_partial_member() { let joined_at = Some(Timestamp::from_secs(1_632_072_645).expect("non zero")); let flags = MemberFlags::BYPASSES_VERIFICATION | MemberFlags::DID_REJOIN; let member = PartialMember { avatar: None, communication_disabled_until: None, deaf: false, flags, joined_at, mute: true, nick: Some("member nick".to_owned()), permissions: None, premium_since: None, roles: Vec::new(), user: None, }; assert_eq!(cached_member(), member); } }
0
0.677625
1
0.677625
game-dev
MEDIA
0.354623
game-dev
0.932067
1
0.932067
MockBukkit/MockBukkit
19,065
src/main/java/org/mockbukkit/mockbukkit/inventory/InventoryMock.java
package org.mockbukkit.mockbukkit.inventory; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.HumanEntity; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mockbukkit.mockbukkit.MockBukkit; import org.mockbukkit.mockbukkit.entity.EntityMock; import org.mockbukkit.mockbukkit.exception.UnimplementedOperationException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * Mock implementation of an {@link Inventory}. */ public class InventoryMock implements Inventory { private static final int MAX_STACK_SIZE = 64; private final ItemStack @NotNull [] items; private final @Nullable InventoryHolder holder; private final @NotNull InventoryType type; private final @NotNull List<HumanEntity> viewers = new ArrayList<>(); private int maxStackSize = MAX_STACK_SIZE; private @Nullable Component customTitle; /** * Constructs a new {@link InventoryMock} for the given holder, with a specific size and {@link InventoryType}. * * @param holder The holder of the inventory. * @param size The size of the inventory. Must be 2, or a multiple of 9 between 9 and 54. * @param type The type of the inventory. */ public InventoryMock(@Nullable InventoryHolder holder, int size, @NotNull InventoryType type) { Preconditions.checkArgument(size > 0, "Inventory size has to be > 0"); Preconditions.checkNotNull(type, "The InventoryType must not be null!"); this.holder = holder; this.type = type; items = new ItemStack[size]; } /** * Constructs a new {@link InventoryMock} for the given holder with a specific {@link InventoryType}. * The size will be {@link InventoryType#getDefaultSize()}. * * @param holder The holder of the inventory. * @param type The type of the inventory. */ public InventoryMock(@Nullable InventoryHolder holder, @NotNull InventoryType type) { Preconditions.checkNotNull(type, "The InventoryType must not be null!"); this.holder = holder; this.type = type; items = new ItemStack[type.getDefaultSize()]; } protected InventoryMock(InventoryMock inventory) { this.holder = inventory.getHolder(); this.type = inventory.getType(); this.items = new ItemStack[inventory.getSize()]; setMaxStackSize(inventory.getMaxStackSize()); setContents(inventory.getContents()); setCustomTitle(inventory.getCustomTitle()); } /** * Copy constructor. Holder is copied by reference, inventory contents are cloned. * * @param other Inventory to copy. */ public InventoryMock(@NotNull Inventory other) { this.holder = other.getHolder(); this.type = other.getType(); this.items = new ItemStack[other.getSize()]; this.setContents(other.getContents()); } /** * Asserts that a certain condition is true for all items, even {@code nulls}, in this inventory. * * @param condition The condition to check for. */ @Deprecated(forRemoval = true) public void assertTrueForAll(@NotNull Predicate<ItemStack> condition) { for (ItemStack item : items) { assertTrue(condition.test(item)); } } /** * Assets that a certain condition is true for all items in this inventory that aren't null. * * @param condition The condition to check for. */ @Deprecated(forRemoval = true) public void assertTrueForNonNulls(@NotNull Predicate<ItemStack> condition) { assertTrueForAll(itemstack -> itemstack == null || condition.test(itemstack)); } /** * Asserts that a certain condition is true for at least one item in this inventory. It will skip any null items. * * @param condition The condition to check for. */ @Deprecated(forRemoval = true) public void assertTrueForSome(@NotNull Predicate<ItemStack> condition) { for (ItemStack item : items) { if (item != null && condition.test(item)) { return; } } fail("Condition was not met for any items"); } /** * Asserts that the inventory contains at least one itemstack that is compatible with the given itemstack. * * @param item The itemstack to compare everything to. */ @Deprecated(forRemoval = true) public void assertContainsAny(@NotNull ItemStack item) { assertTrueForSome(item::isSimilar); } /** * Asserts that the inventory contains at least a specific amount of items that are compatible with the given * itemstack. * * @param item The itemstack to search for. * @param amount The minimum amount of items that one should have. */ @Deprecated(forRemoval = true) public void assertContainsAtLeast(@NotNull ItemStack item, int amount) { int n = getNumberOfItems(item); String message = String.format("Inventory contains only <%d> but expected at least <%d>", n, amount); assertTrue(n >= amount, message); } /** * Get the number of times a certain item is in the inventory. * * @param item The item to check for. * @return The number of times the item is present in this inventory. */ public int getNumberOfItems(@NotNull ItemStack item) { int amount = 0; for (ItemStack itemstack : items) { if (itemstack != null && item.isSimilar(itemstack)) { amount += itemstack.getAmount(); } } return amount; } /** * Adds a viewer to this inventory. * * @param viewer The viewer to add. */ public void addViewer(@NotNull HumanEntity viewer) { Preconditions.checkNotNull(viewer, "The viewer must not be null!"); viewers.add(viewer); } /** * Adds the given viewers to this inventory. * * @param viewers The viewers to add. */ public void addViewers(@NotNull HumanEntity... viewers) { addViewers(List.of(viewers)); } /** * Adds the given viewers to this inventory. * * @param viewers The {@link List} of viewers to add. */ public void addViewers(@NotNull List<HumanEntity> viewers) { for (HumanEntity viewer : viewers) { Preconditions.checkNotNull(viewer, "The viewer must not be null!"); addViewer(viewer); } } /** * Removes a viewer from this inventory. * * @param viewer The viewer to remove. */ public void removeViewer(@NotNull HumanEntity viewer) { Preconditions.checkNotNull(viewer, "The viewer must not be null!"); viewers.remove(viewer); } @Override public int getSize() { return items.length; } @Override public ItemStack getItem(int index) { return items[index] == null ? null : ItemStackMirror.create(items[index]); } @Override public void setItem(int index, @Nullable ItemStack item) { items[index] = item == null ? null : item.clone(); } /** * Adds a single item to the inventory. Returns whatever item it couldn't add. * * @param item The item to add. * @return The remaining stack that couldn't be added. If it's empty it just returns {@code null}. */ @Nullable public ItemStack addItem(@NotNull ItemStack item) { final int itemMaxStackSize = Math.min(item.getMaxStackSize(), this.maxStackSize); item = item.clone(); for (int i = 0; i < items.length; i++) { ItemStack oItem = items[i]; if (oItem == null) { int toAdd = Math.min(item.getAmount(), itemMaxStackSize); items[i] = item.clone(); items[i].setAmount(toAdd); item.setAmount(item.getAmount() - toAdd); } else { final int oItemMaxStackSize = Math.min(oItem.getMaxStackSize(), this.maxStackSize); if (item.isSimilar(oItem) && oItem.getAmount() < oItemMaxStackSize) { int toAdd = Math.min(item.getAmount(), oItemMaxStackSize - oItem.getAmount()); oItem.setAmount(oItem.getAmount() + toAdd); item.setAmount(item.getAmount() - toAdd); } } if (item.getAmount() == 0) { return null; } } return item; } @Override public @NotNull HashMap<Integer, ItemStack> addItem(ItemStack @NotNull ... items) throws IllegalArgumentException { HashMap<Integer, ItemStack> notSaved = new HashMap<>(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; ItemStack left = addItem(item); if (left != null) { notSaved.put(i, left); } } return notSaved; } @Override public ItemStack @NotNull [] getContents() { return Arrays.stream(items) .map(item -> (item == null || item.isEmpty()) ? null : ItemStackMirror.create(item)) .toArray(ItemStack[]::new); } @Override public void setContents(ItemStack @NotNull [] items) { for (int i = 0; i < getSize(); i++) { if (i < items.length && items[i] != null) { this.items[i] = items[i].clone(); } else { this.items[i] = null; } } } @Override public @Nullable InventoryHolder getHolder() { return holder; } @Override public @Nullable InventoryHolder getHolder(boolean useSnapshot) { //TODO Auto-generated method stub throw new UnimplementedOperationException(); } @Override public @NotNull ListIterator<ItemStack> iterator() { List<ItemStack> list = stream().collect(Collectors.toList()); return list.listIterator(); } public @NotNull Stream<ItemStack> stream() { return Arrays.stream(items).filter(Objects::nonNull); } @Override public @NotNull InventoryType getType() { return type; } @Override public int getMaxStackSize() { return maxStackSize; } @Override public void setMaxStackSize(int size) { // The following checks aren't done in CraftBukkit, but are a fair sanity check. if (size < 1) { throw new IllegalArgumentException("Max stack size cannot be lower than 1"); } if (size > 127) { throw new IllegalArgumentException("Stack sizes larger than 127 may get clipped"); } maxStackSize = size; } @Override public @NotNull HashMap<Integer, ItemStack> removeItem(ItemStack... items) throws IllegalArgumentException { Preconditions.checkNotNull(items, "Items cannot be null"); HashMap<Integer, ItemStack> leftover = new HashMap<>(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; int toDelete = item.getAmount(); while (toDelete > 0) { int first = first(item, false); // Drat! we don't have this type in the inventory if (first == -1) { item.setAmount(toDelete); leftover.put(i, item); break; } ItemStack itemStack = getItem(first); int amount = itemStack.getAmount(); if (amount <= toDelete) { toDelete -= amount; // clear the slot, all used up clear(first); } else { // split the stack and store itemStack.setAmount(amount - toDelete); setItem(first, itemStack); toDelete = 0; } } } return leftover; } @Override public @NotNull HashMap<Integer, ItemStack> removeItemAnySlot(@NotNull ItemStack... items) throws IllegalArgumentException { //TODO Auto-generated method stub throw new UnimplementedOperationException(); } @Override public ItemStack @NotNull [] getStorageContents() { return getContents(); } @Override public void setStorageContents(ItemStack @NotNull [] items) throws IllegalArgumentException { setContents(items); } @Override public boolean contains(@Nullable Material material) throws IllegalArgumentException { if (material == null) { throw new IllegalArgumentException("Material cannot be null."); } for (ItemStack itemStack : this.getContents()) { if (itemStack != null && itemStack.getType() == material) { return true; } } return false; } @Override public boolean contains(ItemStack item) { return contains(Objects.requireNonNull(item).getType()); } @Override public boolean contains(@Nullable Material material, int amount) throws IllegalArgumentException { if (material == null) { throw new IllegalArgumentException("Material cannot be null."); } return amount < 1 || getNumberOfItems(new ItemStackMock(material)) == amount; } @Override public boolean contains(@NotNull ItemStack item, int amount) { return getNumberOfItems(item) == amount; } @Override public boolean containsAtLeast(@NotNull ItemStack item, int amount) { return getNumberOfItems(item) >= amount; } @Override public @NotNull HashMap<Integer, ? extends ItemStack> all(@NotNull Material material) throws IllegalArgumentException { Preconditions.checkNotNull(material, "Material cannot be null"); HashMap<Integer, ItemStack> slots = new HashMap<>(); ItemStack[] items = this.getStorageContents(); for (int i = 0; i < items.length; i++) { if (items[i] != null && items[i].getType() == material) { slots.put(i, items[i]); } } return slots; } @Override public @NotNull HashMap<Integer, ? extends ItemStack> all(@Nullable ItemStack item) { HashMap<Integer, ItemStack> slots = new HashMap<>(); if (item != null) { ItemStack[] contents = this.getStorageContents(); for (int i = 0; i < contents.length; i++) { if (item.equals(contents[i])) { slots.put(i, contents[i]); } } } return slots; } @Override public int first(@NotNull Material material) throws IllegalArgumentException { Preconditions.checkNotNull(material, "Material cannot be null"); ItemStack[] contents = this.getStorageContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && contents[i].getType() == material) { return i; } } return -1; } @Override public int first(@NotNull ItemStack item) { if (item == null) { return -1; } ItemStack[] contents = this.getStorageContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && item.equals(contents[i])) { return i; } } return -1; } private int first(@NotNull ItemStack item, boolean withAmount) { Preconditions.checkNotNull(item, "ItemStack cannot be null"); ItemStack[] inventory = this.getStorageContents(); for (int i = 0; i < inventory.length; i++) { if (inventory[i] == null) { continue; } if (withAmount ? item.equals(inventory[i]) : item.isSimilar(inventory[i])) { return i; } } return -1; } @Override public int firstEmpty() { for (int i = 0; i < getSize(); i++) { if (items[i] == null || items[i].getType() == Material.AIR) { return i; } } return -1; } @Override public void remove(@NotNull Material material) throws IllegalArgumentException { Preconditions.checkNotNull(material, "Material cannot be null"); ItemStack[] contents = this.getStorageContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && contents[i].getType() == material) { this.clear(i); } } } @Override public void remove(@NotNull ItemStack item) { ItemStack[] contents = this.getStorageContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && contents[i].equals(item)) { this.clear(i); } } } @Override public void clear(int index) { items[index] = null; } @Override public void clear() { Arrays.fill(items, null); } @Override public int close() { int count = this.viewers.size(); Lists.newArrayList(this.viewers).forEach(HumanEntity::closeInventory); return count; } @Override public @NotNull List<HumanEntity> getViewers() { return this.viewers; } @Override public @NotNull ListIterator<ItemStack> iterator(int index) { // TODO Auto-generated method stub throw new UnimplementedOperationException(); } @Override public Location getLocation() { if (getHolder() instanceof EntityMock entity) { return entity.getLocation(); } var worlds = Bukkit.getWorlds(); World world; if (worlds.isEmpty()) { world = MockBukkit.getMock().addSimpleWorld("world"); } else { world = worlds.getFirst(); } return world.getSpawnLocation(); } @Override public boolean isEmpty() { for (int i = 0; i < getSize(); i++) { if (items[i] != null && items[i].getType() != Material.AIR) { return false; } } return true; } /** * Creates a snapshot of the inventory. * * @return An inventory snapshot. */ @NotNull @ApiStatus.Internal public Inventory getSnapshot() { if (InventoryMock.class.equals(getClass())) { return new InventoryMock(this); } else { throw new UnimplementedOperationException(String.format("%s does not implement method getSnapshot", this.getClass().getSimpleName())); } } /** * Get the name for this inventory. * Uses the value in {@link #getCustomTitle()} if set, otherwise * uses the default name for the inventory type. * * @return The inventory name. * @see InventoryMock#getCustomTitle() * @see InventoryType#defaultTitle() */ @ApiStatus.Internal public @NotNull Component getTitle() { Component custom = getCustomTitle(); if (custom != null) { return custom; } return getType().defaultTitle(); } /** * Get the custom title to be used in this inventory when set. * * @return The title to be used, or {@code null}. */ @ApiStatus.Internal public @Nullable Component getCustomTitle() { return customTitle; } /** * Set the custom title to be used in this inventory. * * @param customTitle The title to be used, or {@code null}. */ @ApiStatus.Internal public void setCustomTitle(@Nullable Component customTitle) { this.customTitle = customTitle; } /** * Check if two inventories are identical. * <p> * An inventory is considered as identical if the following properties match: * <ul> * <li>Has the same inventory type.</li> * <li>Has the same inventory holder.</li> * <li>Has the same items and quantities.</li> * <li>Has the same maximum stack size.</li> * <li>Has the same custom title</li> * </ul> * * @param inventory The other inventory to compare. * @return {@code true} when identical, otherwise {@code false} */ @ApiStatus.Internal public boolean isIdentical(@Nullable Inventory inventory) { if (!(inventory instanceof InventoryMock that)) { return false; } return maxStackSize == that.maxStackSize && Objects.deepEquals(items, that.items) && Objects.equals(holder, that.holder) && type == that.type && Objects.equals(customTitle, that.customTitle); } @Override public String toString() { return "InventoryMock{" + "type=" + type + ", maxStackSize=" + maxStackSize + ", holder=" + (holder != null ? Objects.toIdentityString(holder) : null) + ", viewers=" + viewers.size() + ", items=" + Arrays.toString(items) + '}'; } }
0
0.932136
1
0.932136
game-dev
MEDIA
0.948719
game-dev
0.900546
1
0.900546
RobinSchmidt/RS-MET
3,868
Libraries/JUCE/modules/juce_box2d/box2d/Collision/b2Distance.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_DISTANCE_H #define B2_DISTANCE_H #include "../Common/b2Math.h" class b2Shape; /// A distance proxy is used by the GJK algorithm. /// It encapsulates any shape. struct b2DistanceProxy { b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} /// Initialize the proxy using the given shape. The shape /// must remain in scope while the proxy is in use. void Set(const b2Shape* shape, juce::int32 index); /// Get the supporting vertex index in the given direction. juce::int32 GetSupport(const b2Vec2& d) const; /// Get the supporting vertex in the given direction. const b2Vec2& GetSupportVertex(const b2Vec2& d) const; /// Get the vertex count. juce::int32 GetVertexCount() const; /// Get a vertex by index. Used by b2Distance. const b2Vec2& GetVertex(juce::int32 index) const; b2Vec2 m_buffer[2]; const b2Vec2* m_vertices; juce::int32 m_count; float32 m_radius; }; /// Used to warm start b2Distance. /// Set count to zero on first call. struct b2SimplexCache { float32 metric; ///< length or area juce::uint16 count; juce::uint8 indexA[3]; ///< vertices on shape A juce::uint8 indexB[3]; ///< vertices on shape B }; /// Input for b2Distance. /// You have to option to use the shape radii /// in the computation. Even struct b2DistanceInput { b2DistanceProxy proxyA; b2DistanceProxy proxyB; b2Transform transformA; b2Transform transformB; bool useRadii; }; /// Output for b2Distance. struct b2DistanceOutput { b2Vec2 pointA; ///< closest point on shapeA b2Vec2 pointB; ///< closest point on shapeB float32 distance; juce::int32 iterations; ///< number of GJK iterations used }; /// Compute the closest points between two shapes. Supports any combination of: /// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. /// On the first call set b2SimplexCache.count to zero. void b2Distance(b2DistanceOutput* output, b2SimplexCache* cache, const b2DistanceInput* input); ////////////////////////////////////////////////////////////////////////// inline juce::int32 b2DistanceProxy::GetVertexCount() const { return m_count; } inline const b2Vec2& b2DistanceProxy::GetVertex(juce::int32 index) const { b2Assert(0 <= index && index < m_count); return m_vertices[index]; } inline juce::int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const { juce::int32 bestIndex = 0; float32 bestValue = b2Dot(m_vertices[0], d); for (juce::int32 i = 1; i < m_count; ++i) { float32 value = b2Dot(m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; } inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const { juce::int32 bestIndex = 0; float32 bestValue = b2Dot(m_vertices[0], d); for (juce::int32 i = 1; i < m_count; ++i) { float32 value = b2Dot(m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return m_vertices[bestIndex]; } #endif
0
0.803565
1
0.803565
game-dev
MEDIA
0.434681
game-dev
0.934508
1
0.934508
OGSR/OGSR-Engine
1,051
ogsr_engine/xrGame/ui/UILine.h
// File: UILine.h // Description: Single text line // Created: 11.03.2005 // Author: Serge Vynnycheko // Mail: narrator@gsc-game.kiev.ua // // Copyright 2005 GSC Game World #pragma once #include "UISubLine.h" #include "../HUDManager.h" #include "UIColorAnimatorWrapper.h" // Attention! Destructor is not virtual. // if you want to inherit this class then make _coresponding_ changes class CUILine { friend class CUILines; public: CUILine(); CUILine(const CUILine& other); ~CUILine(); CUILine& operator=(const CUILine& other); void AddSubLine(const xr_string& str, u32 color); void AddSubLine(xr_string&& str, u32 color); void AddSubLine(const CUISubLine* subLine); void Clear(); void ProcessNewLines(); void ProcessSpaces(); void Draw(CGameFont* pFont, float x, float y, float max_w) const; bool IsEmpty() const { return m_subLines.empty(); } protected: int GetSize(); const CUILine* GetEmptyLine(); xr_vector<CUISubLine> m_subLines; CUILine* m_tmpLine; };
0
0.861407
1
0.861407
game-dev
MEDIA
0.708868
game-dev
0.629646
1
0.629646
EphemeralSpace/ephemeral-space
4,805
Content.Server/Anomaly/Effects/TechAnomalySystem.cs
using Content.Server.Anomaly.Components; using Content.Server.Beam; using Content.Server.DeviceLinking.Systems; using Content.Shared.Anomaly.Components; using Content.Shared.DeviceLinking; using Content.Shared.Emag.Systems; using Robust.Shared.Random; using Robust.Shared.Timing; namespace Content.Server.Anomaly.Effects; public sealed class TechAnomalySystem : EntitySystem { [Dependency] private readonly DeviceLinkSystem _signal = default!; [Dependency] private readonly EntityLookupSystem _lookup = default!; [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly BeamSystem _beam = default!; [Dependency] private readonly IGameTiming _timing = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<TechAnomalyComponent, MapInitEvent>(OnTechMapInit); SubscribeLocalEvent<TechAnomalyComponent, AnomalyPulseEvent>(OnPulse); SubscribeLocalEvent<TechAnomalyComponent, AnomalySupercriticalEvent>(OnSupercritical); SubscribeLocalEvent<TechAnomalyComponent, AnomalyStabilityChangedEvent>(OnStabilityChanged); } private void OnTechMapInit(Entity<TechAnomalyComponent> ent, ref MapInitEvent args) { ent.Comp.NextTimer = _timing.CurTime; } public override void Update(float frameTime) { base.Update(frameTime); var query = EntityQueryEnumerator<TechAnomalyComponent, AnomalyComponent>(); while (query.MoveNext(out var uid, out var tech, out var anom)) { if (_timing.CurTime < tech.NextTimer) continue; tech.NextTimer += TimeSpan.FromSeconds(tech.TimerFrequency); _signal.InvokePort(uid, tech.TimerPort); } } private void OnStabilityChanged(Entity<TechAnomalyComponent> tech, ref AnomalyStabilityChangedEvent args) { var links = MathHelper.Lerp(tech.Comp.LinkCountPerPulse.Min, tech.Comp.LinkCountPerPulse.Max, args.Severity); CreateNewRandomLink(tech, (int)links); } private void CreateNewRandomLink(Entity<TechAnomalyComponent> tech, int count) { if (!TryComp<AnomalyComponent>(tech, out var anomaly)) return; if (!TryComp<DeviceLinkSourceComponent>(tech, out var sourceComp)) return; var range = MathHelper.Lerp(tech.Comp.LinkRadius.Min, tech.Comp.LinkRadius.Max, anomaly.Severity); var devices = _lookup.GetEntitiesInRange<DeviceLinkSinkComponent>(Transform(tech).Coordinates, range); if (devices.Count < 1) return; for (var i = 0; i < count; i++) { var device = _random.Pick(devices); CreateNewLink(tech, (tech, sourceComp), device); } } private void CreateNewLink(Entity<TechAnomalyComponent> tech, Entity<DeviceLinkSourceComponent> source, Entity<DeviceLinkSinkComponent> target) { var sourcePort = _random.Pick(source.Comp.Ports); var sinkPort = _random.Pick(target.Comp.Ports); _signal.SaveLinks(null, source, target,new() { (sourcePort, sinkPort), }); _beam.TryCreateBeam(source, target, tech.Comp.LinkBeamProto); } private void OnSupercritical(Entity<TechAnomalyComponent> tech, ref AnomalySupercriticalEvent args) { // We remove the component so that the anomaly does not bind itself to other devices before self destroy. RemComp<DeviceLinkSourceComponent>(tech); var sources = _lookup.GetEntitiesInRange<DeviceLinkSourceComponent>(Transform(tech).Coordinates, tech.Comp.LinkRadius.Max); var sinks = _lookup.GetEntitiesInRange<DeviceLinkSinkComponent>(Transform(tech).Coordinates, tech.Comp.LinkRadius.Max); for (var i = 0; i < tech.Comp.LinkCountSupercritical; i++) { if (sources.Count < 1) return; if (sinks.Count < 1) return; var source = _random.Pick(sources); sources.Remove(source); var sink = _random.Pick(sinks); sinks.Remove(sink); if (_random.Prob(tech.Comp.EmagSupercritProbability)) { var sourceEv = new GotEmaggedEvent(tech, EmagType.Access | EmagType.Interaction); RaiseLocalEvent(source, ref sourceEv); var sinkEv = new GotEmaggedEvent(tech, EmagType.Access | EmagType.Interaction); RaiseLocalEvent(sink, ref sinkEv); } CreateNewLink(tech, source, sink); } } private void OnPulse(Entity<TechAnomalyComponent> tech, ref AnomalyPulseEvent args) { _signal.InvokePort(tech, tech.Comp.PulsePort); } }
0
0.893062
1
0.893062
game-dev
MEDIA
0.975351
game-dev
0.969347
1
0.969347
ismail0234/Subnautica-Below-Zero-Multiplayer
3,664
Subnautica.Server/Processors/Vehicle/SeaTruckFabricatorModuleProcessor.cs
namespace Subnautica.Server.Processors.Vehicle { using System.Linq; using Server.Core; using Subnautica.Network.Models.Core; using Subnautica.Server.Abstracts.Processors; using Metadata = Subnautica.Network.Models.Metadata; using ServerModel = Subnautica.Network.Models.Server; using WorldEntityModel = Subnautica.Network.Models.WorldEntity.DynamicEntityComponents; public class SeaTruckFabricatorModuleProcessor : NormalProcessor { /** * * Gelen veriyi işler * * @author Ismail <ismaiil_0234@hotmail.com> * */ public override bool OnExecute(AuthorizationProfile profile, NetworkPacket networkPacket) { var packet = networkPacket.GetPacket<ServerModel.SeaTruckFabricatorModuleArgs>(); if (packet == null) { return this.SendEmptyPacketErrorLog(networkPacket); } var storageContainer = this.GetStorageContainer(packet.UniqueId); if (storageContainer == null) { return false; } if (packet.IsSignProcess) { if (packet.IsSignSelect) { if (Server.Instance.Logices.Interact.IsBlocked(packet.UniqueId, profile.UniqueId)) { return false; } Server.Instance.Logices.Interact.AddBlock(profile.UniqueId, packet.UniqueId, true); } else { if (storageContainer.Sign == null) { storageContainer.Sign = new Metadata.Sign(); } storageContainer.Sign.Text = packet.SignText; storageContainer.Sign.ColorIndex = packet.SignColorIndex; profile.SendPacketToOtherClients(packet); } } else { if (Server.Instance.Logices.Interact.IsBlocked(packet.UniqueId, profile.UniqueId)) { return false; } if (packet.IsAdded) { if (Server.Instance.Logices.Storage.TryPickupItem(packet.WorldPickupItem, storageContainer, profile.InventoryItems)) { profile.SendPacketToAllClient(packet); } } else { if (Server.Instance.Logices.Storage.TryPickupItem(packet.WorldPickupItem, profile.InventoryItems, storageContainer)) { profile.SendPacketToAllClient(packet); } } } return true; } /** * * Saklama kabını döner. * * @author Ismail <ismaiil_0234@hotmail.com> * */ private Metadata.StorageContainer GetStorageContainer(string lockerId) { foreach (var item in Server.Instance.Storages.World.Storage.DynamicEntities.Where(q => q.TechType == TechType.SeaTruckFabricatorModule).ToList()) { var component = item.Component.GetComponent<WorldEntityModel.SeaTruckFabricatorModule>(); var locker = component.Lockers.Where(q => q.UniqueId == lockerId).FirstOrDefault(); if (locker != null) { return locker.StorageContainer; } } return null; } } }
0
0.906486
1
0.906486
game-dev
MEDIA
0.402697
game-dev
0.86514
1
0.86514
evemuproject/evemu_incursion
1,244
playertools/evemon/src/Tools/XmlGenerator/Bag.cs
using System.Collections.Generic; namespace EVEMon.XmlGenerator { /// <summary> /// A dictionary-based implementation. /// </summary> /// <typeparam name="T"></typeparam> public sealed class Bag<T> : IEnumerable<T> where T : IHasID { private Dictionary<int, T> m_items; public Bag() { m_items = new Dictionary<int, T>(); } public Bag(IndexedList<T> list) : this() { foreach (var item in list.Items) { m_items[item.ID] = item; } } public bool HasValue(int id) { return m_items.ContainsKey(id); } public T this[int id] { get { return m_items[id]; } private set { m_items[id] = value; } } public IEnumerator<T> GetEnumerator() { foreach (var T in m_items.Values) { yield return T; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
0
0.821373
1
0.821373
game-dev
MEDIA
0.298136
game-dev
0.870338
1
0.870338
MiniPlaceholders/MiniPlaceholders
2,066
api/src/jmh/java/io/github/miniplaceholders/jmh/PlaceholderBenchmark.java
package io.github.miniplaceholders.jmh; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import io.github.miniplaceholders.api.Expansion; import io.github.miniplaceholders.api.MiniPlaceholders; @SuppressWarnings("unused") @State(Scope.Benchmark) public class PlaceholderBenchmark { @Benchmark public void placeholderBench() { BenchAudience player = new BenchAudience("4drian3d"); Expansion.Builder expansion = Expansion.builder("benchmark") .audiencePlaceholder( BenchAudience.class, "name", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text(aud.getName())) ) .audiencePlaceholder( BenchAudience.class, "uuid", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text(aud.getUUID().toString())) ) .audiencePlaceholder( "tablistfooter", (aud, queue, ctx) -> Tag.selfClosingInserting(Component.text("footer")) ); Expansion expansionBuilded = expansion.build(); expansionBuilded.register(); final TagResolver resolvers = MiniPlaceholders.audiencePlaceholders(); MiniMessage.miniMessage().deserialize("Player Name: <benchmark_name>", player, resolvers); } @Benchmark public void singleBench() { Expansion.builder("single") .globalPlaceholder("servername", (queue, ctx) -> Tag.selfClosingInserting(Component.text("Peruviankkit"))) .build() .register(); TagResolver resolvers = MiniPlaceholders.globalPlaceholders(); MiniMessage.miniMessage().deserialize("Server name: <single_servername>", resolvers); } }
0
0.806762
1
0.806762
game-dev
MEDIA
0.735293
game-dev
0.784889
1
0.784889
DangoRyn/UnityGameFramework_HybridCLR
2,696
Assets/GameFramework/Libraries/GameFramework/Download/DownloadAgentHelperUpdateBytesEventArgs.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ namespace GameFramework.Download { /// <summary> /// 下载代理辅助器更新数据流事件。 /// </summary> public sealed class DownloadAgentHelperUpdateBytesEventArgs : GameFrameworkEventArgs { private byte[] m_Bytes; /// <summary> /// 初始化下载代理辅助器更新数据流事件的新实例。 /// </summary> public DownloadAgentHelperUpdateBytesEventArgs() { m_Bytes = null; Offset = 0; Length = 0; } /// <summary> /// 获取数据流的偏移。 /// </summary> public int Offset { get; private set; } /// <summary> /// 获取数据流的长度。 /// </summary> public int Length { get; private set; } /// <summary> /// 创建下载代理辅助器更新数据流事件。 /// </summary> /// <param name="bytes">下载的数据流。</param> /// <param name="offset">数据流的偏移。</param> /// <param name="length">数据流的长度。</param> /// <returns>创建的下载代理辅助器更新数据流事件。</returns> public static DownloadAgentHelperUpdateBytesEventArgs Create(byte[] bytes, int offset, int length) { if (bytes == null) { throw new GameFrameworkException("Bytes is invalid."); } if (offset < 0 || offset >= bytes.Length) { throw new GameFrameworkException("Offset is invalid."); } if (length <= 0 || offset + length > bytes.Length) { throw new GameFrameworkException("Length is invalid."); } DownloadAgentHelperUpdateBytesEventArgs downloadAgentHelperUpdateBytesEventArgs = ReferencePool.Acquire<DownloadAgentHelperUpdateBytesEventArgs>(); downloadAgentHelperUpdateBytesEventArgs.m_Bytes = bytes; downloadAgentHelperUpdateBytesEventArgs.Offset = offset; downloadAgentHelperUpdateBytesEventArgs.Length = length; return downloadAgentHelperUpdateBytesEventArgs; } /// <summary> /// 清理下载代理辅助器更新数据流事件。 /// </summary> public override void Clear() { m_Bytes = null; Offset = 0; Length = 0; } /// <summary> /// 获取下载的数据流。 /// </summary> public byte[] GetBytes() { return m_Bytes; } } }
0
0.709604
1
0.709604
game-dev
MEDIA
0.64685
game-dev
0.754242
1
0.754242
Monkestation/Monkestation2.0
7,755
code/modules/mob/living/carbon/human/human_stripping.dm
#define INTERNALS_TOGGLE_DELAY (4 SECONDS) #define POCKET_EQUIP_DELAY (1 SECONDS) GLOBAL_LIST_INIT(strippable_human_items, create_strippable_list(list( /datum/strippable_item/mob_item_slot/head, /datum/strippable_item/mob_item_slot/back, /datum/strippable_item/mob_item_slot/mask, /datum/strippable_item/mob_item_slot/neck, /datum/strippable_item/mob_item_slot/eyes, /datum/strippable_item/mob_item_slot/ears, /datum/strippable_item/mob_item_slot/jumpsuit, /datum/strippable_item/mob_item_slot/suit, /datum/strippable_item/mob_item_slot/gloves, /datum/strippable_item/mob_item_slot/feet, /datum/strippable_item/mob_item_slot/suit_storage, /datum/strippable_item/mob_item_slot/id, /datum/strippable_item/mob_item_slot/belt, /datum/strippable_item/mob_item_slot/pocket/left, /datum/strippable_item/mob_item_slot/pocket/right, /datum/strippable_item/hand/left, /datum/strippable_item/hand/right, /datum/strippable_item/mob_item_slot/handcuffs, /datum/strippable_item/mob_item_slot/legcuffs, ))) /mob/living/carbon/human/proc/should_strip(mob/user) if (user.pulling != src || user.grab_state != GRAB_AGGRESSIVE) return TRUE if (ishuman(user)) var/mob/living/carbon/human/human_user = user return !human_user.can_be_firemanned(src) return TRUE /datum/strippable_item/mob_item_slot/eyes key = STRIPPABLE_ITEM_EYES item_slot = ITEM_SLOT_EYES /datum/strippable_item/mob_item_slot/ears key = STRIPPABLE_ITEM_EARS item_slot = ITEM_SLOT_EARS /datum/strippable_item/mob_item_slot/jumpsuit key = STRIPPABLE_ITEM_JUMPSUIT item_slot = ITEM_SLOT_ICLOTHING /datum/strippable_item/mob_item_slot/jumpsuit/get_alternate_action(atom/source, mob/user) var/obj/item/clothing/under/jumpsuit = get_item(source) if (!istype(jumpsuit)) return null return jumpsuit?.can_adjust ? "adjust_jumpsuit" : null /datum/strippable_item/mob_item_slot/jumpsuit/alternate_action(atom/source, mob/user) if (!..()) return var/obj/item/clothing/under/jumpsuit = get_item(source) if (!istype(jumpsuit)) return null to_chat(source, "<span class='notice'>[user] is trying to adjust your [jumpsuit.name].") if (!do_after(user, (jumpsuit.strip_delay * 0.5), source)) return to_chat(source, "<span class='notice'>[user] successfully adjusted your [jumpsuit.name].") jumpsuit.toggle_jumpsuit_adjust() if (!ismob(source)) return var/mob/mob_source = source mob_source.update_worn_undersuit() mob_source.update_body() /datum/strippable_item/mob_item_slot/suit key = STRIPPABLE_ITEM_SUIT item_slot = ITEM_SLOT_OCLOTHING /datum/strippable_item/mob_item_slot/gloves key = STRIPPABLE_ITEM_GLOVES item_slot = ITEM_SLOT_GLOVES /datum/strippable_item/mob_item_slot/feet key = STRIPPABLE_ITEM_FEET item_slot = ITEM_SLOT_FEET /datum/strippable_item/mob_item_slot/feet/get_alternate_action(atom/source, mob/user) var/obj/item/clothing/shoes/shoes = get_item(source) if (!istype(shoes) || !shoes.can_be_tied) return null switch (shoes.tied) if (SHOES_UNTIED) return "knot" if (SHOES_TIED) return "untie" if (SHOES_KNOTTED) return "unknot" /datum/strippable_item/mob_item_slot/feet/alternate_action(atom/source, mob/user) if(!..()) return var/obj/item/clothing/shoes/shoes = get_item(source) if (!istype(shoes)) return shoes.handle_tying(user) /datum/strippable_item/mob_item_slot/suit_storage key = STRIPPABLE_ITEM_SUIT_STORAGE item_slot = ITEM_SLOT_SUITSTORE /datum/strippable_item/mob_item_slot/suit_storage/get_alternate_action(atom/source, mob/user) return get_strippable_alternate_action_internals(get_item(source), source) /datum/strippable_item/mob_item_slot/suit_storage/alternate_action(atom/source, mob/user) if (!..()) return strippable_alternate_action_internals(get_item(source), source, user) /datum/strippable_item/mob_item_slot/id key = STRIPPABLE_ITEM_ID item_slot = ITEM_SLOT_ID /datum/strippable_item/mob_item_slot/belt key = STRIPPABLE_ITEM_BELT item_slot = ITEM_SLOT_BELT /datum/strippable_item/mob_item_slot/belt/get_alternate_action(atom/source, mob/user) return get_strippable_alternate_action_internals(get_item(source), source) /datum/strippable_item/mob_item_slot/belt/alternate_action(atom/source, mob/user) if (!..()) return strippable_alternate_action_internals(get_item(source), source, user) /datum/strippable_item/mob_item_slot/pocket /// Which pocket we're referencing. Used for visible text. var/pocket_side /datum/strippable_item/mob_item_slot/pocket/get_obscuring(atom/source) return isnull(get_item(source)) \ ? STRIPPABLE_OBSCURING_NONE \ : STRIPPABLE_OBSCURING_HIDDEN /datum/strippable_item/mob_item_slot/pocket/get_equip_delay(obj/item/equipping) return POCKET_EQUIP_DELAY /datum/strippable_item/mob_item_slot/pocket/start_equip(atom/source, obj/item/equipping, mob/user) . = ..() if (!.) warn_owner(source) /datum/strippable_item/mob_item_slot/pocket/start_unequip(atom/source, mob/user) var/obj/item/item = get_item(source) if (isnull(item)) return FALSE to_chat(user, span_notice("You try to empty [source]'s [pocket_side] pocket.")) user.log_message("is pickpocketing [key_name(source)] of [item] ([pocket_side])", LOG_ATTACK, color="red") source.log_message("is being pickpocketed of [item] by [key_name(user)] ([pocket_side])", LOG_VICTIM, color="orange", log_globally=FALSE) item.add_fingerprint(src) var/result = start_unequip_mob(item, source, user, strip_delay = POCKET_STRIP_DELAY, hidden = TRUE) if (!result) warn_owner(source) return result /datum/strippable_item/mob_item_slot/pocket/proc/warn_owner(atom/owner) to_chat(owner, span_warning("You feel your [pocket_side] pocket being fumbled with!")) /datum/strippable_item/mob_item_slot/pocket/left key = STRIPPABLE_ITEM_LPOCKET item_slot = ITEM_SLOT_LPOCKET pocket_side = "left" /datum/strippable_item/mob_item_slot/pocket/right key = STRIPPABLE_ITEM_RPOCKET item_slot = ITEM_SLOT_RPOCKET pocket_side = "right" /proc/get_strippable_alternate_action_internals(obj/item/item, atom/source) if (!iscarbon(source)) return var/mob/living/carbon/carbon_source = source if (carbon_source.can_breathe_internals() && istype(item, /obj/item/tank)) if(carbon_source.internal != item) return "enable_internals" else return "disable_internals" /proc/strippable_alternate_action_internals(obj/item/item, atom/source, mob/user) var/obj/item/tank/tank = item if (!istype(tank)) return var/mob/living/carbon/carbon_source = source if (!istype(carbon_source)) return if (!carbon_source.can_breathe_internals()) return carbon_source.visible_message( span_danger("[user] tries to [(carbon_source.internal != item) ? "open" : "close"] the valve on [source]'s [item.name]."), span_userdanger("[user] tries to [(carbon_source.internal != item) ? "open" : "close"] the valve on your [item.name]."), ignored_mobs = user, ) to_chat(user, span_notice("You try to [(carbon_source.internal != item) ? "open" : "close"] the valve on [source]'s [item.name]...")) if(!do_after(user, INTERNALS_TOGGLE_DELAY, carbon_source)) return if (carbon_source.internal == item) carbon_source.close_internals() // This isn't meant to be FALSE, it correlates to the item's name. else if (!QDELETED(item)) if(!carbon_source.try_open_internals(item)) return carbon_source.visible_message( span_danger("[user] [isnull(carbon_source.internal) ? "closes": "opens"] the valve on [source]'s [item.name]."), span_userdanger("[user] [isnull(carbon_source.internal) ? "closes": "opens"] the valve on your [item.name]."), ignored_mobs = user, ) to_chat(user, span_notice("You [isnull(carbon_source.internal) ? "close" : "open"] the valve on [source]'s [item.name].")) #undef INTERNALS_TOGGLE_DELAY #undef POCKET_EQUIP_DELAY
0
0.890913
1
0.890913
game-dev
MEDIA
0.996088
game-dev
0.917773
1
0.917773
jaames/playnote-studio
2,672
Source/scenes/Home.lua
HomeScreen = {} class('HomeScreen').extends(ScreenBase) function HomeScreen:init() HomeScreen.super.init(self) self.focus = FocusController(self) self.hasPlayedIntro = false sounds:prepareSfx({'intro'}) end function HomeScreen:setupSprites() local viewButton = Button(PLAYDATE_W / 2, PLAYDATE_H - 60, 196, 48, '%HOME_VIEW%') viewButton.autoWidth = true viewButton:setIcon('./gfx/icon_view') viewButton:setAnchor('center', 'top') viewButton:onClick(function () sceneManager:push('notelist', sceneManager.kTransitionFade) end) self.viewButton = viewButton local settingsButton = Button(PLAYDATE_W + 6, -8, 128, 44, '%HOME_SETTINGS%') settingsButton.variant = 'settings' settingsButton.autoWidth = true settingsButton:setIcon('./gfx/icon_settings') settingsButton:setAnchor('right', 'top') settingsButton:onClick(function () sceneManager:push('settings', sceneManager.kTransitionFade) end) self.settingsButton = settingsButton self.clock = Clock(4, 4, 156, 28) self.homeLogo = HomeLogo(52, 50) self.focus:setFocus(viewButton, true) return {viewButton, settingsButton, self.clock, self.homeLogo} end function HomeScreen:enter() if not self.hasPlayedIntro then self.hasPlayedIntro = true playdate.timer.performAfterDelay(200, function () sounds:playSfxThenRelease('intro') end) end end function HomeScreen:afterEnter() -- check if the C extention has been loaded -- imo it's fine for this message to not be localised, you should only come across it in the simulator if PpmPlayer == nil then local errMsg = [[  Native extension error Playnote Studio probably hasn't been compiled for this platform, sorry! If you want to try compiling it yourself, the source code can be found at github.com/jaames/playnote-studio]] dialog:error(errMsg, 100) end end function HomeScreen:drawBg(x, y, w, h) grid:draw(x, y, w, h) end function HomeScreen:updateTransitionIn(t, fromScreen) if fromScreen == nil then local p = playdate.easingFunctions.outBack(t - 0.5, -70, 70, 0.5) local l = playdate.easingFunctions.outBack(t, 50, -50, 1) self.clock:offsetByY(p) self.settingsButton:offsetByY(p) self.viewButton:offsetByY(0 - p) self.homeLogo:offsetByY(l) else local p = playdate.easingFunctions.outQuad(t, -60, 60, 1) self.clock:offsetByY(p) self.settingsButton:offsetByY(p) self.viewButton:offsetByY(0 - p) end end function HomeScreen:updateTransitionOut(t, toScreen) local p = playdate.easingFunctions.inQuad(t, 0, -60, 1) self.clock:offsetByY(p) self.settingsButton:offsetByY(p) self.viewButton:offsetByY(-p) end return HomeScreen
0
0.792396
1
0.792396
game-dev
MEDIA
0.829423
game-dev
0.936756
1
0.936756
shedaniel/RoughlyEnoughItems
10,571
runtime/src/main/java/me/shedaniel/rei/impl/client/gui/widget/basewidgets/LabelWidget.java
/* * This file is licensed under the MIT License, part of Roughly Enough Items. * Copyright (c) 2018, 2019, 2020, 2021, 2022, 2023 shedaniel * * 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 me.shedaniel.rei.impl.client.gui.widget.basewidgets; import me.shedaniel.clothconfig2.api.LazyResettable; import me.shedaniel.clothconfig2.api.animator.ValueAnimator; import me.shedaniel.clothconfig2.api.animator.ValueProvider; import me.shedaniel.math.Color; import me.shedaniel.math.Point; import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.client.REIRuntime; import me.shedaniel.rei.api.client.gui.widgets.Label; import me.shedaniel.rei.api.client.gui.widgets.Tooltip; import me.shedaniel.rei.api.client.gui.widgets.Widgets; import me.shedaniel.rei.impl.client.gui.text.TextTransformations; import net.minecraft.client.gui.ComponentPath; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.navigation.FocusNavigationEvent; import net.minecraft.locale.Language; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.FormattedText; import net.minecraft.util.FormattedCharSequence; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public final class LabelWidget extends Label { private boolean hovered = false; private boolean focused = false; private boolean clickable = false; private int horizontalAlignment = Label.CENTER; private boolean hasShadow = true; private boolean focusable = true; private ValueProvider<Color> color = ValueAnimator.ofColor() .withConvention(() -> Color.ofTransparent(REIRuntime.getInstance().isDarkThemeEnabled() ? 0xFFBBBBBB : -1), 50); private ValueProvider<Color> hoveredColor = ValueAnimator.ofColor() .withConvention(() -> Color.ofTransparent(REIRuntime.getInstance().isDarkThemeEnabled() ? -1 : 0xFF66FFCC), 50); private final ValueProvider<Color> finalColor = ValueAnimator.ofColor() .withConvention(() -> { if (!hovered) { return color.value(); } return hoveredColor.value(); }, ValueAnimator.typicalTransitionTime() / 2); private Point point; @Nullable private Function<Label, @Nullable Component[]> tooltip; @Nullable private Consumer<Label> onClick; @Nullable private BiConsumer<GuiGraphics, Label> onRender; private FormattedText text; private boolean rainbow; private final LazyResettable<FormattedCharSequence> orderedText = new LazyResettable<>(() -> Language.getInstance().getVisualOrder(getMessage())); public LabelWidget(Point point, FormattedText text) { Objects.requireNonNull(this.point = point); Objects.requireNonNull(this.text = text); } @Override public final boolean isClickable() { return clickable; } @Override public final void setClickable(boolean clickable) { this.clickable = clickable; } @Nullable @Override public final Consumer<Label> getOnClick() { return onClick; } @Override public final void setOnClick(@Nullable Consumer<Label> onClick) { this.onClick = onClick; } @Nullable @Override public final BiConsumer<GuiGraphics, Label> getOnRender() { return onRender; } @Override public final void setOnRender(@Nullable BiConsumer<GuiGraphics, Label> onRender) { this.onRender = onRender; } @Override public final boolean isFocusable() { return focusable; } @Override public final void setFocusable(boolean focusable) { this.focusable = focusable; } @Override @Nullable public final Component[] getTooltipLines() { if (tooltip == null) return null; return tooltip.apply(this); } @Override public final void setTooltipFunction(@Nullable Function<Label, @Nullable Component[]> tooltip) { this.tooltip = tooltip; } @Override public final int getHorizontalAlignment() { return horizontalAlignment; } @Override public final void setHorizontalAlignment(int horizontalAlignment) { this.horizontalAlignment = horizontalAlignment; } @Override public final boolean hasShadow() { return hasShadow; } @Override public final void setShadow(boolean hasShadow) { this.hasShadow = hasShadow; } @Override public final int getColor() { return color.value().getColor(); } @Override public final void setColor(int color) { this.color = ValueProvider.constant(Color.ofTransparent(color)); this.finalColor.completeImmediately(); } @Override public Label color(int lightModeColor, int darkModeColor) { this.color = ValueAnimator.ofColor() .withConvention(() -> Color.ofTransparent(REIRuntime.getInstance().isDarkThemeEnabled() ? darkModeColor : lightModeColor), ValueAnimator.typicalTransitionTime()); this.color.completeImmediately(); this.finalColor.completeImmediately(); return this; } @Override public final int getHoveredColor() { return hoveredColor.value().getColor(); } @Override public final void setHoveredColor(int hoveredColor) { this.hoveredColor = ValueProvider.constant(Color.ofTransparent(hoveredColor)); this.finalColor.completeImmediately(); } @Override public final Point getPoint() { return point; } @Override public final void setPoint(Point point) { this.point = Objects.requireNonNull(point); } @Override public FormattedText getMessage() { return text; } @Override public void setMessage(FormattedText message) { this.text = Objects.requireNonNull(message); this.orderedText.reset(); } @Override public void setRainbow(boolean rainbow) { this.rainbow = rainbow; } @Override public final Rectangle getBounds() { int width = font.width(text); Point point = getPoint(); if (getHorizontalAlignment() == LEFT_ALIGNED) return new Rectangle(point.x - 1, point.y - 5, width + 2, 14); if (getHorizontalAlignment() == RIGHT_ALIGNED) return new Rectangle(point.x - width - 1, point.y - 5, width + 2, 14); return new Rectangle(point.x - width / 2 - 1, point.y - 5, width + 2, 14); } @Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { this.color.update(delta); this.hoveredColor.update(delta); this.finalColor.update(delta); if (getOnRender() != null) getOnRender().accept(graphics, this); int color = finalColor.value().getColor(); hovered = isClickable() && isHovered(mouseX, mouseY); Point pos = getPoint(); FormattedCharSequence sequence = orderedText.get(); if (rainbow) sequence = TextTransformations.applyRainbow(sequence, pos.x, pos.y); int width = font.width(sequence); switch (getHorizontalAlignment()) { case LEFT_ALIGNED: graphics.drawString(font, sequence, pos.x, pos.y, color, hasShadow()); break; case RIGHT_ALIGNED: graphics.drawString(font, sequence, pos.x - width, pos.y, color, hasShadow()); break; case CENTER: default: graphics.drawString(font, sequence, (int) (pos.x - width / 2f), pos.y, color, hasShadow()); break; } if (isHovered(mouseX, mouseY)) { Component[] tooltip = getTooltipLines(); if (tooltip != null) { if (!focused && containsMouse(mouseX, mouseY)) Tooltip.create(tooltip).queue(); else if (focused) Tooltip.create(point, tooltip).queue(); } } } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (button == 0 && isClickable() && containsMouse(mouseX, mouseY)) { Widgets.produceClickSound(); if (onClick != null) onClick.accept(this); return true; } return false; } @Override public boolean keyPressed(int int_1, int int_2, int int_3) { if (!isClickable() || !isFocusable() || !focused) return false; if (int_1 != 257 && int_1 != 32 && int_1 != 335) return false; Widgets.produceClickSound(); if (onClick != null) onClick.accept(this); return true; } @Nullable @Override public ComponentPath nextFocusPath(FocusNavigationEvent event) { return isClickable() && focusable ? ComponentPath.leaf(this) : null; } public boolean isHovered(int mouseX, int mouseY) { return containsMouse(mouseX, mouseY) || focused; } @Override public List<? extends GuiEventListener> children() { return Collections.emptyList(); } }
0
0.922218
1
0.922218
game-dev
MEDIA
0.896746
game-dev
0.982515
1
0.982515
Ayfri/Kore
1,809
kore/src/main/kotlin/io/github/ayfri/kore/features/worldgen/configuredfeature/configurations/tree/rootprovider/MangroveRootPlacer.kt
package io.github.ayfri.kore.features.worldgen.configuredfeature.configurations.tree.rootprovider import io.github.ayfri.kore.arguments.types.BlockOrTagArgument import io.github.ayfri.kore.features.worldgen.configuredfeature.blockstateprovider.BlockStateProvider import io.github.ayfri.kore.features.worldgen.configuredfeature.blockstateprovider.simpleStateProvider import io.github.ayfri.kore.features.worldgen.intproviders.IntProvider import io.github.ayfri.kore.features.worldgen.intproviders.constant import io.github.ayfri.kore.serializers.InlinableList import kotlinx.serialization.Serializable @Serializable data class MangroveRootPlacer( override var rootProvider: BlockStateProvider = simpleStateProvider(), override var trunkOffsetY: IntProvider = constant(0), override var aboveRootProvider: AboveRootPlacement? = null, var mangroveRootPlacement: MangroveRootPlacement = MangroveRootPlacement(), ) : RootPlacer() @Serializable data class MangroveRootPlacement( var maxRootWidth: Int = 0, var maxRootLength: Int = 0, var randomSkewChance: Double = 0.0, var canGrowTrough: InlinableList<BlockOrTagArgument> = emptyList(), var muddyRootsIn: InlinableList<BlockOrTagArgument> = emptyList(), var muddyRootsProvider: BlockStateProvider = simpleStateProvider(), ) fun mangroveRootPlacer( rootProvider: BlockStateProvider = simpleStateProvider(), trunkOffsetY: IntProvider = constant(0), aboveRootProvider: AboveRootPlacement? = null, mangroveRootPlacement: MangroveRootPlacement = MangroveRootPlacement(), block: MangroveRootPlacer.() -> Unit = {}, ) = MangroveRootPlacer(rootProvider, trunkOffsetY, aboveRootProvider, mangroveRootPlacement).apply(block) fun MangroveRootPlacer.mangroveRootPlacement(block: MangroveRootPlacement.() -> Unit = {}) = MangroveRootPlacement().apply(block)
0
0.828635
1
0.828635
game-dev
MEDIA
0.715069
game-dev,mobile
0.595756
1
0.595756
RealityStop/Bolt.Addons.Community
1,206
Editor/Code/Generators/Nodes/Other/GetGraphsGenerator.cs
#if VISUAL_SCRIPTING_1_7 using System; using Unity.VisualScripting.Community.Libraries.CSharp; using Unity.VisualScripting.Community.Libraries.Humility; namespace Unity.VisualScripting.Community { public abstract class GetGraphsGenerator<TGraph, TGraphAsset, TMachine> : NodeGenerator<GetGraphs<TGraph, TGraphAsset, TMachine>> where TGraph : class, IGraph, new() where TGraphAsset : Macro<TGraph> where TMachine : Machine<TGraph, TGraphAsset> { public GetGraphsGenerator(Unit unit) : base(unit) { NameSpaces = "Unity.VisualScripting.Community"; } public override string GenerateValue(ValueOutput output, ControlGenerationData data) { if (output == Unit.graphList) { string goExpr = GenerateValue(Unit.gameObject, data); var builder = Unit.CreateClickableString(); builder.InvokeMember(typeof(CSharpUtility), "GetGraphs", new Type[] { typeof(TGraph), typeof(TGraphAsset), typeof(TMachine) }, false, p1 => p1.Ignore(goExpr)); return builder; } return base.GenerateValue(output, data); } } } #endif
0
0.805516
1
0.805516
game-dev
MEDIA
0.548705
game-dev
0.902646
1
0.902646
soda-auto/soda-sim
20,495
Source/RuntimeEditor/Private/RuntimeEditorUtils.cpp
// Copyright 2023 SODA.AUTO UK LTD. All Rights Reserved. #include "RuntimeEditorUtils.h" #include "HAL/FileManager.h" #include "Widgets/Layout/SSpacer.h" #include "SodaStyleSet.h" #include "Widgets/Input/SHyperlink.h" #include "RuntimeDocumentation/IDocumentation.h" #include "RuntimeMetaData.h" #include "AssetRegistry/AssetRegistryModule.h" #include "Misc/ConfigCacheIni.h" #include "Components/SceneComponent.h" #include "Blueprint/BlueprintSupport.h" #include "Engine/BlueprintGeneratedClass.h" #include "Engine/Blueprint.h" #include "Misc/PackageName.h" #include "AssetRegistry/AssetData.h" namespace FRuntimeEditorUtils { //------------------------------------------------------------------------------ FString GetDocumentationPage(const UClass* Class) { return (Class ? FString::Printf( TEXT("Shared/Types/%s%s"), Class->GetPrefixCPP(), *Class->GetName() ) : FString()); } //------------------------------------------------------------------------------ FString GetDocumentationExcerpt(const UClass* Class) { return (Class ? FString::Printf( TEXT("%s%s"), Class->GetPrefixCPP(), *Class->GetName() ) : FString()); } //------------------------------------------------------------------------------ TSharedRef<SToolTip> GetTooltip(const UClass* Class) { const bool bShowShortTooltips = true; return (Class ? GetTooltip(Class, FRuntimeMetaData::GetToolTipText(Class, bShowShortTooltips)) : SNew(SToolTip)); //return (Class ? GetTooltip(Class, FText::GetEmpty()) : SNew(SToolTip)); } //------------------------------------------------------------------------------ TSharedRef<SToolTip> GetTooltip(const UClass* Class, const TAttribute<FText>& OverrideText) { return (Class ? soda::IDocumentation::Get()->CreateToolTip(OverrideText, nullptr, GetDocumentationPage(Class), GetDocumentationExcerpt(Class)) : SNew(SToolTip)); //return (Class ? CreateDocToolTip(OverrideText, nullptr) : SNew(SToolTip)); } //------------------------------------------------------------------------------ UClass* GetClassFromString(const FString& ClassName) { if (ClassName.IsEmpty() || ClassName == TEXT("None")) { return nullptr; } UClass* Class = nullptr; if (!FPackageName::IsShortPackageName(ClassName)) { Class = FindObject<UClass>(nullptr, *ClassName); } else { Class = FindFirstObject<UClass>(*ClassName, EFindFirstObjectOptions::None, ELogVerbosity::Warning, TEXT("FEditorClassUtils::GetClassFromString")); } if (!Class) { Class = LoadObject<UClass>(nullptr, *ClassName); } return Class; } //------------------------------------------------------------------------------ bool ValidateActorName(const FText& InName, FText& OutErrorMessage) { FText TrimmedLabel = FText::TrimPrecedingAndTrailing(InName); if (TrimmedLabel.IsEmpty()) { OutErrorMessage = FText::FromString(TEXT("Names cannot be left blank")); return false; } if (TrimmedLabel.ToString().Len() >= NAME_SIZE) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("CharCount"), NAME_SIZE); OutErrorMessage = FText::Format(FText::FromString(TEXT("Names must be less than {CharCount} characters long.")), Arguments); return false; } if (FName(*TrimmedLabel.ToString()) == NAME_None) { OutErrorMessage = FText::FromString(TEXT("\"None\" is a reserved term and cannot be used for actor names")); return false; } return true; } //------------------------------------------------------------------------------ FText GetCategoryText(const FField* InField) { static const FTextKey CategoryLocalizationNamespace = TEXT("UObjectCategory"); static const FName CategoryMetaDataKey = TEXT("Category"); if (InField) { const FString& NativeCategory = FRuntimeMetaData::GetMetaData(InField, CategoryMetaDataKey); if (!NativeCategory.IsEmpty()) { FText LocalizedCategory; if (!FText::FindText(CategoryLocalizationNamespace, NativeCategory, /*OUT*/LocalizedCategory, &NativeCategory)) { LocalizedCategory = FText::AsCultureInvariant(NativeCategory); } return LocalizedCategory; } } return FText::GetEmpty(); } //------------------------------------------------------------------------------ FText GetCategoryText(const UField* InField) { static const FTextKey CategoryLocalizationNamespace = TEXT("UObjectCategory"); static const FName CategoryMetaDataKey = TEXT("Category"); if (InField) { const FString& NativeCategory = FRuntimeMetaData::GetMetaData(InField, CategoryMetaDataKey); if (!NativeCategory.IsEmpty()) { FText LocalizedCategory; if (!FText::FindText(CategoryLocalizationNamespace, NativeCategory, /*OUT*/LocalizedCategory, &NativeCategory)) { LocalizedCategory = FText::AsCultureInvariant(NativeCategory); } return LocalizedCategory; } } return FText::GetEmpty(); } //------------------------------------------------------------------------------ FString GetCategory(const FField* InField) { return GetCategoryText(InField).ToString(); } //------------------------------------------------------------------------------ FString GetCategory(const UField* InField) { return GetCategoryText(InField).ToString(); } //------------------------------------------------------------------------------ FName GetCategoryFName(const FField* InField) { static const FName CategoryKey(TEXT("Category")); const FField* CurrentField = InField; FString CategoryString; while (CurrentField != nullptr && CategoryString.IsEmpty()) { CategoryString = FRuntimeMetaData::GetMetaData(CurrentField, CategoryKey); CurrentField = CurrentField->GetOwner<FField>(); } if (!CategoryString.IsEmpty()) { return FName(*CategoryString); } return NAME_None; } //------------------------------------------------------------------------------ FName GetCategoryFName(const UField* InField) { static const FName CategoryKey(TEXT("Category")); if (InField && FRuntimeMetaData::HasMetaData(InField, CategoryKey)) { return FName(FRuntimeMetaData::GetMetaData(InField, CategoryKey)); } return NAME_None; } //------------------------------------------------------------------------------ bool CanCreateBlueprintOfClass(const UClass* Class) { bool bCanCreateBlueprint = false; if (Class) { bool bAllowDerivedBlueprints = false; GConfig->GetBool(TEXT("Kismet"), TEXT("AllowDerivedBlueprints"), /*out*/ bAllowDerivedBlueprints, GEngineIni); #if WITH_EDITORONLY_DATA bCanCreateBlueprint = !Class->HasAnyClassFlags(CLASS_Deprecated) && !Class->HasAnyClassFlags(CLASS_NewerVersionExists) && (!Class->ClassGeneratedBy || (bAllowDerivedBlueprints && !IsClassABlueprintSkeleton(Class))); #else bCanCreateBlueprint = !Class->HasAnyClassFlags(CLASS_Deprecated) && !Class->HasAnyClassFlags(CLASS_NewerVersionExists) && (/*!Class->ClassGeneratedBy ||*/ (bAllowDerivedBlueprints /*&& !IsClassABlueprintSkeleton(Class)*/)); #endif const bool bIsBPGC = (Cast<UBlueprintGeneratedClass>(Class) != nullptr); const bool bIsValidClass = /*Class->GetBoolMetaDataHierarchical(FBlueprintMetadata::MD_IsBlueprintBase)*/ /*||*/ (Class == UObject::StaticClass()) || (Class->HasAnyClassFlags(CLASS_CompiledFromBlueprint) || Class == USceneComponent::StaticClass() || Class == UActorComponent::StaticClass()) || bIsBPGC; // BPs are always considered inheritable bCanCreateBlueprint &= bIsValidClass; } return bCanCreateBlueprint; } //------------------------------------------------------------------------------ FString GetFriendlyName(const FProperty* Property, UStruct* OwnerStruct/* = NULL*/) { // first, try to pull the friendly name from the loc file check(Property); UStruct* RealOwnerStruct = Property->GetOwnerStruct(); if (OwnerStruct == NULL) { OwnerStruct = RealOwnerStruct; } checkSlow(OwnerStruct); FText FoundText; bool DidFindText = false; UStruct* CurrentStruct = OwnerStruct; do { FString PropertyPathName = Property->GetPathName(CurrentStruct); DidFindText = FText::FindText(*CurrentStruct->GetName(), *(PropertyPathName + TEXT(".FriendlyName")), /*OUT*/FoundText); CurrentStruct = CurrentStruct->GetSuperStruct(); } while (CurrentStruct != NULL && CurrentStruct->IsChildOf(RealOwnerStruct) && !DidFindText); if (!DidFindText) { const FString& DefaultFriendlyName = FRuntimeMetaData::GetMetaData(Property, TEXT("DisplayName")); if (DefaultFriendlyName.IsEmpty()) { const bool bIsBool = CastField<const FBoolProperty>(Property) != NULL; return FName::NameToDisplayString(Property->GetName(), bIsBool); } return DefaultFriendlyName; } return FoundText.ToString(); } //------------------------------------------------------------------------------ bool IsCategoryHiddenFromClass(const UStruct* Class, const FText& Category) { return IsCategoryHiddenFromClass(Class, Category.ToString()); } //------------------------------------------------------------------------------ bool IsCategoryHiddenFromClass(const UStruct* Class, const FString& Category) { TArray<FString> ClassHideCategories; GetClassHideCategories(Class, ClassHideCategories); return IsCategoryHiddenFromClass(ClassHideCategories, Class, Category); } //------------------------------------------------------------------------------ bool IsCategoryHiddenFromClass(const TArray<FString>& ClassHideCategories, const UStruct* Class, const FString& Category) { bool bIsHidden = false; // run the category through sanitization so we can ensure compares will hit const FString DisplayCategory = GetCategoryDisplayString(Category); for (const FString& HideCategory : ClassHideCategories) { bIsHidden = (HideCategory == DisplayCategory); if (bIsHidden) { TArray<FString> ClassShowCategories; GetClassShowCategories(Class, ClassShowCategories); // if they hid it, and showed it... favor showing (could be a shown in a sub-class, and hid in a super) bIsHidden = (ClassShowCategories.Find(DisplayCategory) == INDEX_NONE); } else // see if the category's root is hidden { TArray<FString> SubCategoryList; DisplayCategory.ParseIntoArray(SubCategoryList, TEXT("|"), /*InCullEmpty =*/true); FString FullSubCategoryPath; for (const FString& SubCategory : SubCategoryList) { FullSubCategoryPath += SubCategory; if ((HideCategory == SubCategory) || (HideCategory == FullSubCategoryPath)) { TArray<FString> ClassShowCategories; GetClassShowCategories(Class, ClassShowCategories); // if they hid it, and showed it... favor showing (could be a shown in a sub-class, and hid in a super) bIsHidden = (ClassShowCategories.Find(DisplayCategory) == INDEX_NONE); } FullSubCategoryPath += "|"; } } if (bIsHidden) { break; } } return bIsHidden; } //------------------------------------------------------------------------------ void GetClassHideCategories(const UStruct* Class, TArray<FString>& CategoriesOut, bool bHomogenize) { CategoriesOut.Empty(); if (FRuntimeMetaData::HasMetaData(Class, TEXT("HideCategories"))) { const FString& HideCategories = FRuntimeMetaData::GetMetaData(Class, TEXT("HideCategories")); HideCategories.ParseIntoArray(CategoriesOut, TEXT(" "), /*InCullEmpty =*/true); if (bHomogenize) { for (FString& Category : CategoriesOut) { Category = GetCategoryDisplayString(Category); } } } } //------------------------------------------------------------------------------ FText GetCategoryDisplayString(const FText& UnsanitizedCategory) { return FText::FromString(GetCategoryDisplayString(UnsanitizedCategory.ToString())); } //------------------------------------------------------------------------------ FString GetCategoryDisplayString(const FString& UnsanitizedCategory) { FString DisplayString = UnsanitizedCategory; int32 KeyIndex = INDEX_NONE; do { KeyIndex = DisplayString.Find(TEXT("{"), ESearchCase::CaseSensitive, ESearchDir::FromStart, KeyIndex); if (KeyIndex != INDEX_NONE) { int32 EndIndex = DisplayString.Find(TEXT("}"), ESearchCase::CaseSensitive, ESearchDir::FromStart, KeyIndex); if (EndIndex != INDEX_NONE) { FString ToReplaceStr(EndIndex + 1 - KeyIndex, *DisplayString + KeyIndex); FString ReplacementStr; int32 KeyLen = EndIndex - (KeyIndex + 1); if (KeyLen > 0) { FString Key(KeyLen, *DisplayString + KeyIndex + 1); Key.TrimStartInline(); ReplacementStr = GetCategory(*Key).ToString(); } DisplayString.ReplaceInline(*ToReplaceStr, *ReplacementStr); } KeyIndex = EndIndex; } } while (KeyIndex != INDEX_NONE); DisplayString = FName::NameToDisplayString(DisplayString, /*bIsBool =*/false); DisplayString.ReplaceInline(TEXT("| "), TEXT("|"), ESearchCase::CaseSensitive); return DisplayString; } //------------------------------------------------------------------------------ void GetClassShowCategories(const UStruct* Class, TArray<FString>& CategoriesOut) { CategoriesOut.Empty(); if (FRuntimeMetaData::HasMetaData(Class, TEXT("ShowCategories"))) { const FString& ShowCategories = FRuntimeMetaData::GetMetaData(Class, TEXT("ShowCategories")); ShowCategories.ParseIntoArray(CategoriesOut, TEXT(" "), /*InCullEmpty =*/true); for (FString& Category : CategoriesOut) { Category = GetCategoryDisplayString(FText::FromString(Category)).ToString(); } } } //------------------------------------------------------------------------------ const FText& GetCategory(const FString& Key) { /* if (FEditorCategoryUtilsImpl::FCategoryInfo const* FoundCategory = GetCategoryTable().Find(Key)) { return FoundCategory->DisplayName; } */ return FText::GetEmpty(); } //------------------------------------------------------------------------------ /* TSharedRef< class SToolTip > CreateDocToolTip(const TAttribute<FText>& Text, const TSharedPtr<SWidget>& OverrideContent, const FString& Link, const FString& ExcerptName) { return SNew(SToolTip) [ SNew(SVerticalBox) + SVerticalBox::Slot() [ SNew(STextBlock) .Text(FText::FromString("TODO!!!")) ] ]; } */ //------------------------------------------------------------------------------ /* TSharedRef< class SToolTip > CreateDocToolTip(const TAttribute<FText>& Text, const TSharedRef<SWidget>& OverrideContent, const TSharedPtr<SVerticalBox>& DocVerticalBox, const FString& Link, const FString& ExcerptName) { return SNew(SToolTip) [ SNew(SVerticalBox) + SVerticalBox::Slot() [ SNew(STextBlock) .Text(FText::FromString("TODO!!!")) ] ]; } */ //------------------------------------------------------------------------------ FTopLevelAssetPath GetClassPathNameFromAssetTag(const FAssetData& InAssetData) { const FString GeneratedClassPath = InAssetData.GetTagValueRef<FString>(FBlueprintTags::GeneratedClassPath); return FTopLevelAssetPath(FPackageName::ExportTextPathToObjectPath(FStringView(GeneratedClassPath))); } //------------------------------------------------------------------------------ FTopLevelAssetPath GetClassPathNameFromAsset(const FAssetData& InAssetData, bool bGenerateClassPathIfMissing /*= false*/) { bool bIsBPGC = false; const bool bIsBP = IsBlueprintAsset(InAssetData, &bIsBPGC); if (bIsBPGC) { return FTopLevelAssetPath(InAssetData.GetSoftObjectPath().GetAssetPath()); } else if (bIsBP) { FTopLevelAssetPath ClassPath = GetClassPathNameFromAssetTag(InAssetData); if (bGenerateClassPathIfMissing && ClassPath.IsNull()) { FString ClassPathString = InAssetData.GetObjectPathString(); ClassPathString += TEXT("_C"); ClassPath = FTopLevelAssetPath(ClassPathString); } return ClassPath; } return FTopLevelAssetPath(); } //------------------------------------------------------------------------------ bool IsBlueprintAsset(const FAssetData& InAssetData, bool* bOutIsBPGC /*= nullptr*/) { bool bIsBP = (InAssetData.AssetClassPath == UBlueprint::StaticClass()->GetClassPathName()); bool bIsBPGC = (InAssetData.AssetClassPath == UBlueprintGeneratedClass::StaticClass()->GetClassPathName()); if (!bIsBP && !bIsBPGC) { IAssetRegistry& AssetRegistry = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(AssetRegistryConstants::ModuleName).Get(); TArray<FTopLevelAssetPath> AncestorClassNames; AssetRegistry.GetAncestorClassNames(InAssetData.AssetClassPath, AncestorClassNames); if (AncestorClassNames.Contains(UBlueprint::StaticClass()->GetClassPathName())) { bIsBP = true; } else if (AncestorClassNames.Contains(UBlueprintGeneratedClass::StaticClass()->GetClassPathName())) { bIsBPGC = true; } } if (bOutIsBPGC) { *bOutIsBPGC = bIsBPGC; } return bIsBP || bIsBPGC; } //------------------------------------------------------------------------------ void GetImplementedInterfaceClassPathsFromAsset(const struct FAssetData& InAssetData, TArray<FString>& OutClassPaths) { if (!InAssetData.IsValid()) { return; } const FString ImplementedInterfaces = InAssetData.GetTagValueRef<FString>(FBlueprintTags::ImplementedInterfaces); if (!ImplementedInterfaces.IsEmpty()) { // Parse string like "((Interface=Class'"/Script/VPBookmark.VPBookmarkProvider"'),(Interface=Class'"/Script/VPUtilities.VPContextMenuProvider"'))" // We don't want to actually resolve the hard ref so do some manual parsing FString FullInterface; FString CurrentString = *ImplementedInterfaces; while (CurrentString.Split(TEXT("Interface="), nullptr, &FullInterface)) { // Cutoff at next ) int32 RightParen = INDEX_NONE; if (FullInterface.FindChar(TCHAR(')'), RightParen)) { // Keep parsing CurrentString = FullInterface.Mid(RightParen); // Strip class name FullInterface = *FPackageName::ExportTextPathToObjectPath(FullInterface.Left(RightParen)); // Handle quotes FString InterfacePath; const TCHAR* NewBuffer = FPropertyHelpers::ReadToken(*FullInterface, InterfacePath, true); if (NewBuffer) { OutClassPaths.Add(InterfacePath); } } } } } //------------------------------------------------------------------------------ bool IsClassABlueprintSkeleton(const UClass* Class) { // Find generating blueprint for a class #if WITH_EDITORONLY_DATA UBlueprint* GeneratingBP = Cast<UBlueprint>(Class->ClassGeneratedBy); if (GeneratingBP && GeneratingBP->SkeletonGeneratedClass) { return (Class == GeneratingBP->SkeletonGeneratedClass) && (GeneratingBP->SkeletonGeneratedClass != GeneratingBP->GeneratedClass); } #endif return Class->HasAnyFlags(RF_Transient) && Class->HasAnyClassFlags(CLASS_CompiledFromBlueprint); } //------------------------------------------------------------------------------ FString GetDisplayNameHelper(const UObject& Object) { const UClass* Class = Cast<const UClass>(&Object); if (Class && !Class->HasAnyClassFlags(CLASS_Native)) { FString Name = Object.GetName(); Name.RemoveFromEnd(TEXT("_C")); Name.RemoveFromStart(TEXT("SKEL_")); return Name; } //if (auto Property = dynamic_cast<const FProperty*>(&Object)) //{ // return Property->GetAuthoredName(); //} return Object.GetName(); } //------------------------------------------------------------------------------ FString GetDisplayNameHelper(const FField& Object) { if (const FProperty* Property = CastField<FProperty>(&Object)) { if (auto OwnerStruct = Property->GetOwnerStruct()) { return OwnerStruct->GetAuthoredNameForField(Property); } } return Object.GetName(); } //------------------------------------------------------------------------------ TSharedRef< class SWidget > MakeWidget_HackTooltip(FMultiBoxBuilder& MultiBoxBuilder, FMultiBox::FOnMakeMultiBoxBuilderOverride* InMakeMultiBoxBuilderOverride, TAttribute<float> InMaxHeight) { class SMultiBoxWidget_HackTooltip : public SMultiBoxWidget { virtual bool OnVisualizeTooltip(const TSharedPtr<SWidget>& TooltipContent) override { return false; } }; TSharedRef< SMultiBoxWidget > NewMultiBoxWidget = SNew(SMultiBoxWidget_HackTooltip); // Set whether this box should be searched NewMultiBoxWidget->SetSearchable(false); // Assign ourselves to the MultiBox widget NewMultiBoxWidget->SetMultiBox(MultiBoxBuilder.GetMultiBox()); // Set the maximum height the MultiBox widget should be NewMultiBoxWidget->SetMaxHeight(InMaxHeight); if ((InMakeMultiBoxBuilderOverride != nullptr) && (InMakeMultiBoxBuilderOverride->IsBound())) { TSharedRef<FMultiBox> ThisMultiBox = MultiBoxBuilder.GetMultiBox(); InMakeMultiBoxBuilderOverride->Execute(ThisMultiBox, NewMultiBoxWidget); } else { // Build up the widget NewMultiBoxWidget->BuildMultiBoxWidget(); } return NewMultiBoxWidget; } }
0
0.990229
1
0.990229
game-dev
MEDIA
0.468067
game-dev
0.979515
1
0.979515
embeddedt/ModernFix
3,621
forge/src/main/java/org/embeddedt/modernfix/forge/mixin/perf/dynamic_resources/ItemModelMesherForgeMixin.java
package org.embeddedt.modernfix.forge.mixin.perf.dynamic_resources; import net.minecraft.client.renderer.ItemModelShaper; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelManager; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraftforge.client.model.ForgeItemModelShaper; import net.minecraftforge.registries.ForgeRegistries; import org.embeddedt.modernfix.annotation.ClientOnlyMixin; import org.embeddedt.modernfix.dynamicresources.DynamicModelCache; import org.embeddedt.modernfix.dynamicresources.ModelLocationCache; import org.embeddedt.modernfix.util.ItemMesherMap; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.HashMap; import java.util.Map; @Mixin(ForgeItemModelShaper.class) @ClientOnlyMixin public abstract class ItemModelMesherForgeMixin extends ItemModelShaper { @Shadow(remap = false) @Final @Mutable private Map<Holder.Reference<Item>, ModelResourceLocation> locations; private Map<Holder.Reference<Item>, ModelResourceLocation> overrideLocations; private final DynamicModelCache<Holder.Reference<Item>> mfix$modelCache = new DynamicModelCache<>(k -> this.mfix$getModelSlow((Holder.Reference<Item>)k), true); public ItemModelMesherForgeMixin(ModelManager arg) { super(arg); } private static final ModelResourceLocation SENTINEL = new ModelResourceLocation(new ResourceLocation("modernfix", "sentinel"), "sentinel"); @Inject(method = "<init>", at = @At("RETURN")) private void replaceLocationMap(CallbackInfo ci) { overrideLocations = new HashMap<>(); // need to replace this map because mods query locations through it locations = new ItemMesherMap<>(this::mfix$getLocationForge); } @Unique private ModelResourceLocation mfix$getLocationForge(Holder.Reference<Item> item) { ModelResourceLocation map = overrideLocations.getOrDefault(item, SENTINEL); if(map == SENTINEL) { /* generate the appropriate location from our cache */ map = ModelLocationCache.get(item.get()); } return map; } private BakedModel mfix$getModelSlow(Holder.Reference<Item> key) { ModelResourceLocation map = mfix$getLocationForge(key); return map == null ? null : getModelManager().getModel(map); } /** * @author embeddedt * @reason Get the stored location for that item and meta, and get the model * from that location from the model manager. **/ @Overwrite @Override public BakedModel getItemModel(Item item) { return this.mfix$modelCache.get(ForgeRegistries.ITEMS.getDelegateOrThrow(item)); } /** * @author embeddedt * @reason Don't get all models during init (with dynamic loading, that would * generate them all). Just store location instead. **/ @Overwrite @Override public void register(Item item, ModelResourceLocation location) { overrideLocations.put(ForgeRegistries.ITEMS.getDelegateOrThrow(item), location); } /** * @author embeddedt * @reason Disable cache rebuilding (with dynamic loading, that would generate * all models). **/ @Overwrite @Override public void rebuildCache() { this.mfix$modelCache.clear(); } }
0
0.929096
1
0.929096
game-dev
MEDIA
0.915363
game-dev
0.85151
1
0.85151
leggedrobotics/free_gait
2,490
free_gait_core/include/free_gait_core/leg_motion/EndEffectorMotionBase.hpp
/* * EndEffectorMotionBase.hpp * * Created on: Oct 21, 2015 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #pragma once // Free Gait #include "free_gait_core/leg_motion/LegMotionBase.hpp" #include <free_gait_core/TypeDefs.hpp> // STD #include <string> #include <memory> namespace free_gait { /*! * Base class for end effector motion. */ class EndEffectorMotionBase : public LegMotionBase { public: /*! * Constructor. */ EndEffectorMotionBase(LegMotionBase::Type type, LimbEnum limb); /*! * Destructor. */ virtual ~EndEffectorMotionBase(); /*! * Returns the type of the leg motion trajectory. * @return the type of the leg motion trajectory. */ LegMotionBase::TrajectoryType getTrajectoryType() const; /*! * Update the trajectory with the foot start position. * Do this to avoid jumps of the swing leg. * @param footStartPosition the start position of the foot in the trajectoryFrameId_ frame. * @return true if successful, false otherwise. */ virtual void updateStartPosition(const Position& startPosition); virtual void updateStartVelocity(const LinearVelocity& startVelocity); virtual void updateStartAcceleration(const LinearAcceleration& startAcceleration); virtual void updateStartForce(const Force& startForce); /*! * Evaluate the swing foot position at a given swing phase value. * @param phase the swing phase value. * @return the position of the foot on the swing trajectory. */ virtual const Position evaluatePosition(const double time) const; virtual const LinearVelocity evaluateVelocity(const double time) const; virtual const LinearAcceleration evaluateAcceleration(const double time) const; virtual const Force evaluateForce(const double time) const; /*! * Return the target (end position) of the swing trajectory. * @return the target. */ virtual const Position getTargetPosition() const; virtual const LinearVelocity getTargetVelocity() const; /*! * Returns the frame id of the trajectory. * @return the frame id. */ virtual const std::string& getFrameId(const ControlLevel& controlLevel) const; /*! * Print the contents to console for debugging. * @param out the output stream. * @param swingTrajectory the swing trajectory to debug. * @return the resulting output stream. */ friend std::ostream& operator << (std::ostream& out, const LegMotionBase& legMotion); }; } /* namespace */
0
0.921434
1
0.921434
game-dev
MEDIA
0.30163
game-dev
0.81651
1
0.81651
IJEMIN/Unity-Programming-Essence-2021
3,394
19/Done/Zombie Multiplayer/Assets/Photon/PhotonUnityNetworking/UtilityScripts/UI/TabViewManager.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TabViewManager.cs" company="Exit Games GmbH"> // Part of: PunCockpit // </copyright> // <summary> // Simple Management for Tabs, it requires a ToggleGroup, and then for each Tab, a Unique Name, the related Toggle and its associated RectTransform View // this manager handles Tab views activation and deactivation, and provides a Unity Event Callback when a tab was selected. // </summary> // <author>developer@exitgames.com</author> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; namespace Photon.Pun.UtilityScripts { /// <summary> /// Tab view manager. Handles Tab views activation and deactivation, and provides a Unity Event Callback when a tab was selected. /// </summary> public class TabViewManager : MonoBehaviour { /// <summary> /// Tab change event. /// </summary> [System.Serializable] public class TabChangeEvent : UnityEvent<string> { } [Serializable] public class Tab { public string ID = ""; public Toggle Toggle; public RectTransform View; } /// <summary> /// The toggle group component target. /// </summary> public ToggleGroup ToggleGroup; /// <summary> /// all the tabs for this group /// </summary> public Tab[] Tabs; /// <summary> /// The on tab changed Event. /// </summary> public TabChangeEvent OnTabChanged; protected Tab CurrentTab; Dictionary<Toggle, Tab> Tab_lut; void Start() { Tab_lut = new Dictionary<Toggle, Tab>(); foreach (Tab _tab in this.Tabs) { Tab_lut[_tab.Toggle] = _tab; _tab.View.gameObject.SetActive(_tab.Toggle.isOn); if (_tab.Toggle.isOn) { CurrentTab = _tab; } _tab.Toggle.onValueChanged.AddListener((isSelected) => { if (!isSelected) { return; } OnTabSelected(_tab); }); } } /// <summary> /// Selects a given tab. /// </summary> /// <param name="id">Tab Id</param> public void SelectTab(string id) { foreach (Tab _t in Tabs) { if (_t.ID == id) { _t.Toggle.isOn = true; return; } } } /// <summary> /// final method for a tab selection routine /// </summary> /// <param name="tab">Tab.</param> void OnTabSelected(Tab tab) { CurrentTab.View.gameObject.SetActive(false); CurrentTab = Tab_lut[ToggleGroup.ActiveToggles().FirstOrDefault()]; CurrentTab.View.gameObject.SetActive(true); OnTabChanged.Invoke(CurrentTab.ID); } } }
0
0.833883
1
0.833883
game-dev
MEDIA
0.771597
game-dev
0.832124
1
0.832124
lukasmonk/lucaschess
4,511
Engines/Linux64/rodentII/src/timer.cpp
#include <stdio.h> #include "timer.h" #include <math.h> #include "rodent.h" #include "param.h" #if defined(_WIN32) || defined(_WIN64) # include <windows.h> #else # include <unistd.h> # include <sys/time.h> #endif void sTimer::SetSpeed(int elo) { // TODO: should belong to cParam nps_limit = 0; Param.eval_blur = 0; if (Param.fl_weakening) { nps_limit = EloToSpeed(elo); Param.eval_blur = EloToBlur(elo); } } void sTimer::Clear(void) { iteration_time = MAX_INT; adjustement = 0; smart_management = 0; SetData(MAX_DEPTH, 64); allocated_time = -1; SetData(W_TIME,-1); SetData(B_TIME,-1); SetData(W_INC, 0); SetData(B_INC, 0); SetData(MOVE_TIME, 0); SetData(MAX_NODES, 0); SetData(MOVES_TO_GO, 40); SetData(FLAG_INFINITE, 0); } void sTimer::OnOldRootMove(void) { if (smart_management) { adjustement -= 1; if (adjustement < -30) adjustement = -30; } } void sTimer::OnNewRootMove(void) { if (smart_management) { adjustement += 3; if (adjustement > 30) adjustement = 30; } } void sTimer::OnFailLow(void) { if (smart_management) { if (adjustement < 0) adjustement = 0; } } void sTimer::SetStartTime(void) { start_time = GetMS(); } int sTimer::BulletCorrection(int time) { if (time < 200) return (time * 23) / 32; else if (time < 400) return (time * 26) / 32; else if (time < 1200) return (time * 29) / 32; else return time; } void sTimer::SetMoveTiming(void) { // User-defined time per move, no tricks available if ( data[MOVE_TIME] ) { allocated_time = data[MOVE_TIME]; return; } // We are operating within some time limit. There is some scope for using // remaining time in a clever way, but current implementation focuses // on staying out of trouble: counteracting the GUI lag and being careful // under the incremental time control near the end of the game. if (data[TIME] >= 0) { if (data[MOVES_TO_GO] == 1) data[TIME] -= Min(1000, data[TIME] / 10); allocated_time = ( data[TIME] + data[INC] * ( data[MOVES_TO_GO] - 1)) / data[MOVES_TO_GO]; // Is it safe to use more advanced time management heuristics? // (i.e. to modify base thinking time based on how often root // move changes ) if (2 * allocated_time < data[TIME]) smart_management = 1; // make a percentage correction to playing speed (unless too risky) if (smart_management) { allocated_time *= time_percentage; allocated_time /= 100; } // assign less time per move on extremely short time controls allocated_time = BulletCorrection(allocated_time); // while in time trouble, try to save a bit on increment if (allocated_time < data[INC] ) allocated_time -= ( (data[INC] * 4) / 5); // ensure that our limit does not exceed total time available if (allocated_time > data[TIME]) allocated_time = data[TIME]; // safeguard against a lag allocated_time -= 10; // ensure that we have non-zero time if (allocated_time < 1) allocated_time = 1; } } void sTimer::SetIterationTiming(void) { if (allocated_time > 0) iteration_time = ( (allocated_time * 3) / 4 ); else iteration_time = MAX_INT; // assign less time per iteration on extremely short time controls iteration_time = BulletCorrection(iteration_time); } int sTimer::FinishIteration(void) { return (GetElapsedTime() >= iteration_time && !pondering && !data[FLAG_INFINITE]); } int sTimer::GetMS(void) { #if defined(_WIN32) || defined(_WIN64) return GetTickCount(); // bugbug:drc GetTickCount() wraps once every 50 days, causeing time control to go insane. Don't use this. #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; #endif } int sTimer::GetElapsedTime(void) { return (GetMS() - start_time); } int sTimer::IsInfiniteMode(void) { return( data[FLAG_INFINITE] ); } int sTimer::TimeHasElapsed(void) { return (GetElapsedTime() >= (allocated_time * (100 + adjustement) / 100) ); } int sTimer::GetData(int slot) { return data[slot]; } void sTimer::SetData(int slot, int val) { data[slot] = val; } void sTimer::SetSideData(int side) { data[TIME] = side == WC ? GetData(W_TIME) : GetData(B_TIME); data[INC] = side == WC ? GetData(W_INC) : GetData(B_INC); } void sTimer::WasteTime(int miliseconds) { #if defined(_WIN32) || defined(_WIN64) Sleep(miliseconds); #else usleep(miliseconds * 1000); #endif } void sTimer::Init(void) { nps_limit = 0; special_mode = 0; }
0
0.850957
1
0.850957
game-dev
MEDIA
0.246158
game-dev
0.986809
1
0.986809
shuboc/LeetCode-2
3,879
Python/dungeon-game.py
# Time: O(m * n) # Space: O(m + n) # # The demons had captured the princess (P) and imprisoned her # in the bottom-right corner of a dungeon. T # he dungeon consists of M x N rooms laid out in a 2D grid. # Our valiant knight (K) was initially positioned in the top-left room # and must fight his way through the dungeon to rescue the princess. # # The knight has an initial health point represented by a positive integer. # If at any point his health point drops to 0 or below, he dies immediately. # # Some of the rooms are guarded by demons, # so the knight loses health (negative integers) upon entering these rooms; # other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). # # In order to reach the princess as quickly as possible, # the knight decides to move only rightward or downward in each step. # # # Write a function to determine the knight's minimum initial health # so that he is able to rescue the princess. # # For example, given the dungeon below, the initial health of # the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. # # Notes: # # The knight's health has no upper bound. # Any room can contain threats or power-ups, even the first room the knight enters # and the bottom-right room where the princess is imprisoned. # class Solution: # @param dungeon, a list of lists of integers # @return a integer def calculateMinimumHP(self, dungeon): DP = [float("inf") for _ in dungeon[0]] DP[-1] = 1 for i in reversed(xrange(len(dungeon))): DP[-1] = max(DP[-1] - dungeon[i][-1], 1) for j in reversed(xrange(len(dungeon[i]) - 1)): min_HP_on_exit = min(DP[j], DP[j + 1]) DP[j] = max(min_HP_on_exit - dungeon[i][j], 1) return DP[0] # Time: O(m * n logk), where k is the possible maximum sum of loses # Space: O(m + n) class Solution2: # @param dungeon, a list of lists of integers # @return a integer def calculateMinimumHP(self, dungeon): maximum_loses = 0 for rooms in dungeon: for room in rooms: if room < 0: maximum_loses += abs(room) return self.binarySearch(dungeon, maximum_loses) def binarySearch(self, dungeon, maximum_loses): start, end = 1, maximum_loses + 1 result = 0 while start < end: mid = start + (end - start) / 2 if self.DP(dungeon, mid): end = mid else: start = mid + 1 return start def DP(self, dungeon, HP): remain_HP = [0 for _ in dungeon[0]] remain_HP[0] = HP + dungeon[0][0] for j in xrange(1, len(remain_HP)): if remain_HP[j - 1] > 0: remain_HP[j] = max(remain_HP[j - 1] + dungeon[0][j], 0) for i in xrange(1, len(dungeon)): if remain_HP[0] > 0: remain_HP[0] = max(remain_HP[0] + dungeon[i][0], 0) else: remain_HP[0] = 0 for j in xrange(1, len(remain_HP)): remain = 0 if remain_HP[j - 1] > 0: remain = max(remain_HP[j - 1] + dungeon[i][j], remain) if remain_HP[j] > 0: remain = max(remain_HP[j] + dungeon[i][j], remain) remain_HP[j] = remain return remain_HP[-1] > 0 if __name__ == "__main__": dungeon = [[ -2, -3, 3], \ [ -5, -10, 1], \ [ 10, 30, -5]] print Solution().calculateMinimumHP(dungeon) dungeon = [[ -200]] print Solution().calculateMinimumHP(dungeon) dungeon = [[0, -3]] print Solution().calculateMinimumHP(dungeon)
0
0.607525
1
0.607525
game-dev
MEDIA
0.65034
uncategorized,game-dev
0.885223
1
0.885223
HbmMods/Hbm-s-Nuclear-Tech-GIT
1,829
src/main/java/com/hbm/inventory/container/ContainerNukeMan.java
package com.hbm.inventory.container; import com.hbm.tileentity.bomb.TileEntityNukeMan; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerNukeMan extends Container { private TileEntityNukeMan nukeMan; public ContainerNukeMan(InventoryPlayer invPlayer, TileEntityNukeMan tedf) { nukeMan = tedf; this.addSlotToContainer(new Slot(tedf, 0, 26, 35)); this.addSlotToContainer(new Slot(tedf, 1, 8, 17)); this.addSlotToContainer(new Slot(tedf, 2, 44, 17)); this.addSlotToContainer(new Slot(tedf, 3, 8, 53)); this.addSlotToContainer(new Slot(tedf, 4, 44, 53)); this.addSlotToContainer(new Slot(tedf, 5, 98, 35)); for(int i = 0; i < 3; i++) { for(int j = 0; j < 9; j++) { this.addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } for(int i = 0; i < 9; i++) { this.addSlotToContainer(new Slot(invPlayer, i, 8 + i * 18, 142)); } } @Override public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int par2) { ItemStack var3 = null; Slot var4 = (Slot) this.inventorySlots.get(par2); if (var4 != null && var4.getHasStack()) { ItemStack var5 = var4.getStack(); var3 = var5.copy(); if (par2 <= 5) { if (!this.mergeItemStack(var5, 6, this.inventorySlots.size(), true)) { return null; } } else { return null; } if (var5.stackSize == 0) { var4.putStack((ItemStack) null); } else { var4.onSlotChanged(); } } return var3; } @Override public boolean canInteractWith(EntityPlayer player) { return nukeMan.isUseableByPlayer(player); } }
0
0.671706
1
0.671706
game-dev
MEDIA
0.994837
game-dev
0.951266
1
0.951266
ascott18/TellMeWhen
2,084
Components/IconTypes/IconType_swingtimer/Config.xml
<Ui> <Frame name="TellMeWhen_AutoshootSwingTimerTip" inherits="TellMeWhen_OptionsModuleContainer" virtual="true"> <Size y="50"/> <Layers> <Layer level="ARTWORK"> <FontString parentKey="Text" wordwrap="true" inherits="GameFontHighlightSmall"> <Anchors> <Anchor point="TOP" y="-10"/> </Anchors> </FontString> </Layer> </Layers> <Frames> <Button parentKey="ApplySettings" inherits="TellMeWhen_ButtonTemplate"> <Size y="15"/> <Anchors> <Anchor point="BOTTOM" y="8"/> </Anchors> <Scripts> <OnLoad> self:SetFrameLevel(self:GetParent():GetFrameLevel() + 4) </OnLoad> <OnClick> local ics = TMW.CI.ics ics.Type = "cooldown" ics.Name = self:GetParent().spellIdToApply or 75 ics.BarDisplay_BarGCD = true ics.ClockGCD = true TMW.IE:LoadIcon(1) </OnClick> </Scripts> </Button> </Frames> <Scripts> <OnLoad> TMW:CInit(self) self:SetTitle(TMW.GetSpellName(75)) self.Text:SetText(TMW.L["ICONTYPE_SWINGTIMER_TIP"]) self:CScriptAdd("PanelSetup", function(self, panel, panelInfo) local settings = self:GetSettingTable() local supplementalData = panelInfo.supplementalData local spellID = supplementalData.spellID local name = TMW.GetSpellName(spellID) local descriptiveName = supplementalData.descriptiveName or name self.spellIdToApply = spellID self:SetTitle(descriptiveName) self.Text:SetText(TMW.L["ICONTYPE_SWINGTIMER_TIP"]:format( descriptiveName, TMW.L["ICONMENU_SPELLCOOLDOWN"], TMW.L["ICONMENU_SPELLCOOLDOWN"], name, spellID )) self.ApplySettings:SetText(TMW.L["ICONTYPE_SWINGTIMER_TIP_APPLYSETTINGS"]:format( descriptiveName )) self.ApplySettings:SetWidth(self.ApplySettings:GetTextWidth() + 15) self.Text:SetWidth(self:GetWidth() - 15) self:SetHeight(self.Text:GetStringHeight() + 43) end) </OnLoad> <OnSizeChanged> self:SetHeight(self.Text:GetStringHeight() + 43) </OnSizeChanged> </Scripts> </Frame> </Ui>
0
0.895422
1
0.895422
game-dev
MEDIA
0.677723
game-dev
0.948129
1
0.948129
viridia/quill_v1
2,084
src/view/view_named.rs
use crate::node_span::NodeSpan; use crate::{BuildContext, View}; use bevy::prelude::*; // A wrapper view which applies styles to the output of an inner view. pub struct ViewNamed<'a, V: View> { inner: V, name: &'a str, } impl<'a, V: View> ViewNamed<'a, V> { pub fn new(inner: V, name: &'a str) -> Self { Self { inner, name } } fn set_name(&self, nodes: &NodeSpan, bc: &mut BuildContext) { match nodes { NodeSpan::Empty => (), NodeSpan::Node(entity) => { let em = &mut bc.entity_mut(*entity); em.insert(Name::new(self.name.to_string())); } NodeSpan::Fragment(ref nodes) => { for node in nodes.iter() { // Recurse self.set_name(node, bc); } } } } } impl<'a, V: View> View for ViewNamed<'a, V> { type State = V::State; fn nodes(&self, bc: &BuildContext, state: &Self::State) -> NodeSpan { self.inner.nodes(bc, state) } fn build(&self, bc: &mut BuildContext) -> Self::State { let state = self.inner.build(bc); self.set_name(&self.nodes(bc, &state), bc); state } fn update(&self, bc: &mut BuildContext, state: &mut Self::State) { self.inner.update(bc, state); // Don't think we need to update on rebuild // self.set_name(&mut self.nodes(bc, state), bc); } fn assemble(&self, bc: &mut BuildContext, state: &mut Self::State) -> NodeSpan { self.inner.assemble(bc, state) } fn raze(&self, world: &mut World, state: &mut Self::State) { self.inner.raze(world, state); } } impl<'a, V: View> Clone for ViewNamed<'a, V> where V: Clone, { fn clone(&self) -> Self { Self { inner: self.inner.clone(), name: self.name, } } } impl<'a, V: View> PartialEq for ViewNamed<'a, V> where V: PartialEq, { fn eq(&self, other: &Self) -> bool { self.inner == other.inner && self.name == other.name } }
0
0.871979
1
0.871979
game-dev
MEDIA
0.544046
game-dev
0.846232
1
0.846232
reinterpretcat/utymap
1,640
unity/demo/Assets/Scripts/Scenes/Map/Spaces/SurfaceSpace.cs
using Assets.Scripts.Core.Plugins; using Assets.Scripts.Scenes.Map.Animations; using Assets.Scripts.Scenes.Map.Gestures; using Assets.Scripts.Scenes.Map.Plugins; using Assets.Scripts.Scenes.Map.Tiling; using UnityEngine; using UtyMap.Unity; namespace Assets.Scripts.Scenes.Map.Spaces { internal sealed class SurfaceSpace : Space { private readonly SurfaceTileController _tileController; /// <inheritdoc /> public override SpaceAnimator Animator { get; protected set; } public SurfaceSpace(SurfaceTileController tileController, SurfaceGestureStrategy gestureStrategy, Transform surface, MaterialProvider materialProvider) : base(tileController, gestureStrategy, surface, materialProvider) { _tileController = tileController; Animator = new SurfaceAnimator(tileController); } protected override void OnEnter(GeoCoordinate coordinate, bool isFromTop) { Camera.GetComponent<Skybox>().material = MaterialProvider.GetSharedMaterial(@"Skyboxes/Surface/Skybox"); Camera.transform.localRotation = Quaternion.Euler(90, 0, 0); Light.transform.localRotation = Quaternion.Euler(90, 0, 0); Pivot.localPosition = new Vector3(0, isFromTop ? TileController.HeightRange.Maximum : TileController.HeightRange.Minimum, 0); // surface specific _tileController.MoveGeoOrigin(coordinate); TileController.Update(Target); } protected override void OnExit() { } } }
0
0.830014
1
0.830014
game-dev
MEDIA
0.809703
game-dev,graphics-rendering
0.743329
1
0.743329
bates64/papermario-dx
3,543
src/battle/move/jump/jump_charge_1.c
#include "common.h" #include "script_api/battle.h" #include "battle/action_cmd/jump.h" #include "effects.h" #include "sprite/player.h" #define NAMESPACE battle_move_jump_charge_1 #include "battle/common/move/JumpSupport.inc.c" #include "world/common/todo/IsJumpMaxCharged.inc.c" BSS b32 N(HasCharged); API_CALLABLE(N(func_802A1108_74D678)) { Bytecode* args = script->ptrReadPos; BattleStatus* battleStatus = &gBattleStatus; s32 var1 = evt_get_variable(script, *args++); s32 var2 = evt_get_variable(script, *args++); s32 var3 = evt_get_variable(script, *args++); fx_stat_change(1, var1, var2, var3, 1.0f, 60); N(HasCharged) = FALSE; if (battleStatus->jumpCharge > 0) { N(HasCharged) = TRUE; } battleStatus->jumpCharge += 2; if (battleStatus->jumpCharge > 99) { battleStatus->jumpCharge = 99; } battleStatus->hammerCharge = 0; battleStatus->flags1 |= BS_FLAGS1_JUMP_CHARGED; battleStatus->flags1 &= ~BS_FLAGS1_HAMMER_CHARGED; return ApiStatus_DONE2; } #include "world/common/todo/UnkMoveFunc2.inc.c" API_CALLABLE(N(GetChargeMessage)) { if (!N(HasCharged)) { script->varTable[0] = BTL_MSG_CHARGE_JUMP; } else { script->varTable[0] = BTL_MSG_CHARGE_JUMP_MORE; } return ApiStatus_DONE2; } EvtScript N(EVS_UseMove_Unimplemented) = { Return End }; EvtScript N(EVS_UseMove) = { Call(UseBattleCamPreset, BTL_CAM_PLAYER_CHARGE_UP) Wait(10) ChildThread Call(PlaySoundAtActor, ACTOR_PLAYER, SOUND_PLAYER_CHARGE) Wait(8) Call(PlaySoundAtActor, ACTOR_PLAYER, SOUND_PLAYER_CHARGE) Wait(8) EndChildThread Call(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_FightingStance) Call(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) Call(N(UnkMoveFunc2), LVar0, LVar1, LVar2, Float(1.2)) Wait(3) Call(N(UnkMoveFunc2), LVar0, LVar1, LVar2, Float(0.8)) Wait(30) Call(UseBattleCamPreset, BTL_CAM_DEFAULT) Call(MoveBattleCamOver, 5) Call(N(IsJumpMaxCharged)) IfEq(LVar0, 0) Call(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) Add(LVar0, 10) Add(LVar1, 25) Add(LVar2, 5) Call(N(func_802A1108_74D678), LVar0, LVar1, LVar2) Call(PlaySoundAtActor, ACTOR_PLAYER, SOUND_CHARGE_UP) Wait(4) Call(PlaySoundAtActor, ACTOR_PLAYER, SOUND_LONG_PLAYER_JUMP) Call(SetActorJumpGravity, ACTOR_PLAYER, Float(1.0)) Call(SetActorSpeed, ACTOR_PLAYER, Float(1.0)) Call(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) Call(SetJumpAnimations, ACTOR_PLAYER, 0, ANIM_Mario1_Jump, ANIM_Mario1_Fall, ANIM_Mario1_Land) Call(SetGoalPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) Call(PlayerHopToGoal, 20, 0, 0) Call(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Land) Wait(4) Call(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Idle) Call(UseIdleAnimation, ACTOR_PLAYER, TRUE) Call(N(GetChargeMessage)) Call(ShowVariableMessageBox, LVar0, 60, 2) Else Call(ShowMessageBox, BTL_MSG_CANT_CHARGE, 60) EndIf Label(0) Wait(1) Call(IsMessageBoxDisplayed, LVar0) IfEq(LVar0, TRUE) Goto(0) EndIf Call(UseIdleAnimation, ACTOR_PLAYER, FALSE) Call(SetGoalToHome, ACTOR_PLAYER) Call(SetActorSpeed, ACTOR_PLAYER, Float(8.0)) Call(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Run) Call(PlayerRunToGoal, 0) Call(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Idle) Return End };
0
0.782502
1
0.782502
game-dev
MEDIA
0.975713
game-dev
0.782629
1
0.782629
Michal78900/MapEditorReborn
2,406
MapEditorReborn/API/Features/Objects/IndicatorObject.cs
// ----------------------------------------------------------------------- // <copyright file="IndicatorObject.cs" company="MapEditorReborn"> // Copyright (c) MapEditorReborn. All rights reserved. // Licensed under the CC BY-SA 3.0 license. // </copyright> // ----------------------------------------------------------------------- namespace MapEditorReborn.API.Features.Objects { using System.Collections.Generic; using AdminToys; using Exiled.API.Features.Toys; using MEC; using UnityEngine; /// <summary> /// Component added to spawned IndicatorObject. /// </summary> public class IndicatorObject : MapEditorObject { /// <summary> /// Initializes the <see cref="IndicatorObject"/>. /// </summary> /// <param name="mapEditorObject">The <see cref="MapEditorObject"/> which this indicator will indicate.</param> /// <returns>Instance of this component.</returns> public IndicatorObject Init(MapEditorObject mapEditorObject) { AttachedMapEditorObject = mapEditorObject; mapEditorObject.AttachedIndicator = this; if (TryGetComponent(out PrimitiveObjectToy primitive)) { Timing.RunCoroutine(BlinkingIndicator(Primitive.Get(primitive)).CancelWith(gameObject)); primitive.enabled = true; } return this; } /// <summary> /// <see cref="MapEditorObject"/> that is attached to this object. /// </summary> public MapEditorObject AttachedMapEditorObject; public override bool IsRotatable => false; public override bool IsScalable => false; private IEnumerator<float> BlinkingIndicator(Primitive primitive) { while (true) { while (primitive.Color.a > 0f) { primitive.Color = new Color(primitive.Color.r, primitive.Color.g, primitive.Color.b, primitive.Color.a - 0.1f); yield return Timing.WaitForSeconds(0.1f); } while (primitive.Color.a < 0.9f) { primitive.Color = new Color(primitive.Color.r, primitive.Color.g, primitive.Color.b, primitive.Color.a + 0.1f); yield return Timing.WaitForSeconds(0.1f); } } } } }
0
0.772013
1
0.772013
game-dev
MEDIA
0.951305
game-dev
0.836131
1
0.836131
andersonfreitas/opengl-tutorial-org
14,374
external/bullet-2.81-rev2613/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //#define DISABLE_BVH #include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h" #include "BulletCollision/CollisionShapes/btOptimizedBvh.h" #include "LinearMath/btSerializer.h" ///Bvh Concave triangle mesh is a static-triangle mesh shape with Bounding Volume Hierarchy optimization. ///Uses an interface to access the triangles to allow for sharing graphics/physics triangles. btBvhTriangleMeshShape::btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh) :btTriangleMeshShape(meshInterface), m_bvh(0), m_triangleInfoMap(0), m_useQuantizedAabbCompression(useQuantizedAabbCompression), m_ownsBvh(false) { m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE; //construct bvh from meshInterface #ifndef DISABLE_BVH if (buildBvh) { buildOptimizedBvh(); } #endif //DISABLE_BVH } btBvhTriangleMeshShape::btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,bool buildBvh) :btTriangleMeshShape(meshInterface), m_bvh(0), m_triangleInfoMap(0), m_useQuantizedAabbCompression(useQuantizedAabbCompression), m_ownsBvh(false) { m_shapeType = TRIANGLE_MESH_SHAPE_PROXYTYPE; //construct bvh from meshInterface #ifndef DISABLE_BVH if (buildBvh) { void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); m_bvh = new (mem) btOptimizedBvh(); m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax); m_ownsBvh = true; } #endif //DISABLE_BVH } void btBvhTriangleMeshShape::partialRefitTree(const btVector3& aabbMin,const btVector3& aabbMax) { m_bvh->refitPartial( m_meshInterface,aabbMin,aabbMax ); m_localAabbMin.setMin(aabbMin); m_localAabbMax.setMax(aabbMax); } void btBvhTriangleMeshShape::refitTree(const btVector3& aabbMin,const btVector3& aabbMax) { m_bvh->refit( m_meshInterface, aabbMin,aabbMax ); recalcLocalAabb(); } btBvhTriangleMeshShape::~btBvhTriangleMeshShape() { if (m_ownsBvh) { m_bvh->~btOptimizedBvh(); btAlignedFree(m_bvh); } } void btBvhTriangleMeshShape::performRaycast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget) { struct MyNodeOverlapCallback : public btNodeOverlapCallback { btStridingMeshInterface* m_meshInterface; btTriangleCallback* m_callback; MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) :m_meshInterface(meshInterface), m_callback(callback) { } virtual void processNode(int nodeSubPart, int nodeTriangleIndex) { btVector3 m_triangle[3]; const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart); unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; if (type == PHY_FLOAT) { float* graphicsbase = (float*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); } else { double* graphicsbase = (double*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(btScalar(graphicsbase[0])*meshScaling.getX(),btScalar(graphicsbase[1])*meshScaling.getY(),btScalar(graphicsbase[2])*meshScaling.getZ()); } } /* Perform ray vs. triangle collision here */ m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } }; MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); m_bvh->reportRayOverlappingNodex(&myNodeCallback,raySource,rayTarget); } void btBvhTriangleMeshShape::performConvexcast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax) { struct MyNodeOverlapCallback : public btNodeOverlapCallback { btStridingMeshInterface* m_meshInterface; btTriangleCallback* m_callback; MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) :m_meshInterface(meshInterface), m_callback(callback) { } virtual void processNode(int nodeSubPart, int nodeTriangleIndex) { btVector3 m_triangle[3]; const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart); unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; if (type == PHY_FLOAT) { float* graphicsbase = (float*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); } else { double* graphicsbase = (double*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3(btScalar(graphicsbase[0])*meshScaling.getX(),btScalar(graphicsbase[1])*meshScaling.getY(),btScalar(graphicsbase[2])*meshScaling.getZ()); } } /* Perform ray vs. triangle collision here */ m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } }; MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); m_bvh->reportBoxCastOverlappingNodex (&myNodeCallback, raySource, rayTarget, aabbMin, aabbMax); } //perform bvh tree traversal and report overlapping triangles to 'callback' void btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const { #ifdef DISABLE_BVH //brute force traverse all triangles btTriangleMeshShape::processAllTriangles(callback,aabbMin,aabbMax); #else //first get all the nodes struct MyNodeOverlapCallback : public btNodeOverlapCallback { btStridingMeshInterface* m_meshInterface; btTriangleCallback* m_callback; btVector3 m_triangle[3]; MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) :m_meshInterface(meshInterface), m_callback(callback) { } virtual void processNode(int nodeSubPart, int nodeTriangleIndex) { const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase, numverts, type, stride, &indexbase, indexstride, numfaces, indicestype, nodeSubPart); unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT||indicestype==PHY_UCHAR); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:indicestype==PHY_INTEGER?gfxbase[j]:((unsigned char*)gfxbase)[j]; #ifdef DEBUG_TRIANGLE_MESH printf("%d ,",graphicsindex); #endif //DEBUG_TRIANGLE_MESH if (type == PHY_FLOAT) { float* graphicsbase = (float*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3( graphicsbase[0]*meshScaling.getX(), graphicsbase[1]*meshScaling.getY(), graphicsbase[2]*meshScaling.getZ()); } else { double* graphicsbase = (double*)(vertexbase+graphicsindex*stride); m_triangle[j] = btVector3( btScalar(graphicsbase[0])*meshScaling.getX(), btScalar(graphicsbase[1])*meshScaling.getY(), btScalar(graphicsbase[2])*meshScaling.getZ()); } #ifdef DEBUG_TRIANGLE_MESH printf("triangle vertices:%f,%f,%f\n",triangle[j].x(),triangle[j].y(),triangle[j].z()); #endif //DEBUG_TRIANGLE_MESH } m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } }; MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); m_bvh->reportAabbOverlappingNodex(&myNodeCallback,aabbMin,aabbMax); #endif//DISABLE_BVH } void btBvhTriangleMeshShape::setLocalScaling(const btVector3& scaling) { if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) { btTriangleMeshShape::setLocalScaling(scaling); buildOptimizedBvh(); } } void btBvhTriangleMeshShape::buildOptimizedBvh() { if (m_ownsBvh) { m_bvh->~btOptimizedBvh(); btAlignedFree(m_bvh); } ///m_localAabbMin/m_localAabbMax is already re-calculated in btTriangleMeshShape. We could just scale aabb, but this needs some more work void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); m_bvh = new(mem) btOptimizedBvh(); //rebuild the bvh... m_bvh->build(m_meshInterface,m_useQuantizedAabbCompression,m_localAabbMin,m_localAabbMax); m_ownsBvh = true; } void btBvhTriangleMeshShape::setOptimizedBvh(btOptimizedBvh* bvh, const btVector3& scaling) { btAssert(!m_bvh); btAssert(!m_ownsBvh); m_bvh = bvh; m_ownsBvh = false; // update the scaling without rebuilding the bvh if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) { btTriangleMeshShape::setLocalScaling(scaling); } } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btBvhTriangleMeshShape::serialize(void* dataBuffer, btSerializer* serializer) const { btTriangleMeshShapeData* trimeshData = (btTriangleMeshShapeData*) dataBuffer; btCollisionShape::serialize(&trimeshData->m_collisionShapeData,serializer); m_meshInterface->serialize(&trimeshData->m_meshInterface, serializer); trimeshData->m_collisionMargin = float(m_collisionMargin); if (m_bvh && !(serializer->getSerializationFlags()&BT_SERIALIZE_NO_BVH)) { void* chunk = serializer->findPointer(m_bvh); if (chunk) { #ifdef BT_USE_DOUBLE_PRECISION trimeshData->m_quantizedDoubleBvh = (btQuantizedBvhData*)chunk; trimeshData->m_quantizedFloatBvh = 0; #else trimeshData->m_quantizedFloatBvh = (btQuantizedBvhData*)chunk; trimeshData->m_quantizedDoubleBvh= 0; #endif //BT_USE_DOUBLE_PRECISION } else { #ifdef BT_USE_DOUBLE_PRECISION trimeshData->m_quantizedDoubleBvh = (btQuantizedBvhData*)serializer->getUniquePointer(m_bvh); trimeshData->m_quantizedFloatBvh = 0; #else trimeshData->m_quantizedFloatBvh = (btQuantizedBvhData*)serializer->getUniquePointer(m_bvh); trimeshData->m_quantizedDoubleBvh= 0; #endif //BT_USE_DOUBLE_PRECISION int sz = m_bvh->calculateSerializeBufferSizeNew(); btChunk* chunk = serializer->allocate(sz,1); const char* structType = m_bvh->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_QUANTIZED_BVH_CODE,m_bvh); } } else { trimeshData->m_quantizedFloatBvh = 0; trimeshData->m_quantizedDoubleBvh = 0; } if (m_triangleInfoMap && !(serializer->getSerializationFlags()&BT_SERIALIZE_NO_TRIANGLEINFOMAP)) { void* chunk = serializer->findPointer(m_triangleInfoMap); if (chunk) { trimeshData->m_triangleInfoMap = (btTriangleInfoMapData*)chunk; } else { trimeshData->m_triangleInfoMap = (btTriangleInfoMapData*)serializer->getUniquePointer(m_triangleInfoMap); int sz = m_triangleInfoMap->calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(sz,1); const char* structType = m_triangleInfoMap->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_TRIANLGE_INFO_MAP,m_triangleInfoMap); } } else { trimeshData->m_triangleInfoMap = 0; } return "btTriangleMeshShapeData"; } void btBvhTriangleMeshShape::serializeSingleBvh(btSerializer* serializer) const { if (m_bvh) { int len = m_bvh->calculateSerializeBufferSizeNew(); //make sure not to use calculateSerializeBufferSize because it is used for in-place btChunk* chunk = serializer->allocate(len,1); const char* structType = m_bvh->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_QUANTIZED_BVH_CODE,(void*)m_bvh); } } void btBvhTriangleMeshShape::serializeSingleTriangleInfoMap(btSerializer* serializer) const { if (m_triangleInfoMap) { int len = m_triangleInfoMap->calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(len,1); const char* structType = m_triangleInfoMap->serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_TRIANLGE_INFO_MAP,(void*)m_triangleInfoMap); } }
0
0.972979
1
0.972979
game-dev
MEDIA
0.78118
game-dev,graphics-rendering
0.988464
1
0.988464
isledecomp/isle-portable
27,087
LEGO1/lego/legoomni/src/common/legocharactermanager.cpp
#include "legocharactermanager.h" #include "3dmanager/lego3dmanager.h" #include "legoactors.h" #include "legoanimactor.h" #include "legobuildingmanager.h" #include "legoextraactor.h" #include "legogamestate.h" #include "legoplantmanager.h" #include "legovideomanager.h" #include "misc.h" #include "misc/legocontainer.h" #include "misc/legostorage.h" #include "mxmisc.h" #include "mxvariabletable.h" #include "realtime/realtime.h" #include "roi/legolod.h" #include "viewmanager/viewmanager.h" #include <SDL3/SDL_stdinc.h> #include <assert.h> #include <stdio.h> #include <vec.h> DECOMP_SIZE_ASSERT(LegoCharacter, 0x08) DECOMP_SIZE_ASSERT(LegoCharacterManager, 0x08) DECOMP_SIZE_ASSERT(CustomizeAnimFileVariable, 0x24) // GLOBAL: LEGO1 0x100fc4d0 MxU32 LegoCharacterManager::g_maxMove = 4; // GLOBAL: LEGO1 0x100fc4d4 MxU32 LegoCharacterManager::g_maxSound = 9; // GLOBAL: LEGO1 0x100fc4e0 MxU32 g_characterAnimationId = 10; // GLOBAL: LEGO1 0x100fc4e4 char* LegoCharacterManager::g_customizeAnimFile = NULL; // GLOBAL: LEGO1 0x100fc4d8 MxU32 g_characterSoundIdOffset = 50; // GLOBAL: LEGO1 0x100fc4dc MxU32 g_characterSoundIdMoodOffset = 66; // GLOBAL: LEGO1 0x100fc4e8 MxU32 g_headTextureCounter = 0; // GLOBAL: LEGO1 0x100fc4ec MxU32 g_infohatVariantCounter = 2; // GLOBAL: LEGO1 0x100fc4f0 MxU32 g_autoRoiCounter = 0; // GLOBAL: LEGO1 0x10104f20 LegoActorInfo g_actorInfo[66]; // FUNCTION: LEGO1 0x10082a20 // FUNCTION: BETA10 0x10073c60 LegoCharacterManager::LegoCharacterManager() { m_characters = new LegoCharacterMap(); Init(); // DECOMP: inlined here in BETA10 m_customizeAnimFile = new CustomizeAnimFileVariable("CUSTOMIZE_ANIM_FILE"); VariableTable()->SetVariable(m_customizeAnimFile); } // FUNCTION: LEGO1 0x10083180 // FUNCTION: BETA10 0x10073dad LegoCharacterManager::~LegoCharacterManager() { LegoCharacter* character = NULL; LegoCharacterMap::iterator it; for (it = m_characters->begin(); it != m_characters->end(); it++) { character = (*it).second; RemoveROI(character->m_roi); delete[] (*it).first; delete (*it).second; } delete m_characters; delete[] g_customizeAnimFile; } // FUNCTION: LEGO1 0x10083270 void LegoCharacterManager::Init() { for (MxS32 i = 0; i < sizeOfArray(g_actorInfo); i++) { g_actorInfo[i] = g_actorInfoInit[i]; } } // FUNCTION: LEGO1 0x100832a0 void LegoCharacterManager::ReleaseAllActors() { for (MxS32 i = 0; i < sizeOfArray(g_actorInfo); i++) { LegoActorInfo* info = GetActorInfo(g_actorInfo[i].m_name); if (info != NULL) { LegoExtraActor* actor = info->m_actor; if (actor != NULL && actor->IsA("LegoExtraActor")) { LegoROI* roi = g_actorInfo[i].m_roi; MxU32 refCount = GetRefCount(roi); while (refCount != 0) { ReleaseActor(roi); refCount = GetRefCount(roi); } } } } } // FUNCTION: LEGO1 0x10083310 MxResult LegoCharacterManager::Write(LegoStorage* p_storage) { MxResult result = FAILURE; for (MxS32 i = 0; i < sizeOfArray(g_actorInfo); i++) { LegoActorInfo* info = &g_actorInfo[i]; if (p_storage->Write(&info->m_sound, sizeof(info->m_sound)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_move, sizeof(info->m_move)) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_mood, sizeof(info->m_mood)) != SUCCESS) { goto done; } if (p_storage->Write( &info->m_parts[c_infohatPart].m_partNameIndex, sizeof(info->m_parts[c_infohatPart].m_partNameIndex) ) != SUCCESS) { goto done; } if (p_storage->Write( &info->m_parts[c_infohatPart].m_nameIndex, sizeof(info->m_parts[c_infohatPart].m_nameIndex) ) != SUCCESS) { goto done; } if (p_storage->Write( &info->m_parts[c_infogronPart].m_nameIndex, sizeof(info->m_parts[c_infogronPart].m_nameIndex) ) != SUCCESS) { goto done; } if (p_storage->Write( &info->m_parts[c_armlftPart].m_nameIndex, sizeof(info->m_parts[c_armlftPart].m_nameIndex) ) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_parts[c_armrtPart].m_nameIndex, sizeof(info->m_parts[c_armrtPart].m_nameIndex)) != SUCCESS) { goto done; } if (p_storage->Write( &info->m_parts[c_leglftPart].m_nameIndex, sizeof(info->m_parts[c_leglftPart].m_nameIndex) ) != SUCCESS) { goto done; } if (p_storage->Write(&info->m_parts[c_legrtPart].m_nameIndex, sizeof(info->m_parts[c_legrtPart].m_nameIndex)) != SUCCESS) { goto done; } } result = SUCCESS; done: return result; } // FUNCTION: LEGO1 0x100833f0 MxResult LegoCharacterManager::Read(LegoStorage* p_storage) { MxResult result = FAILURE; for (MxS32 i = 0; i < sizeOfArray(g_actorInfo); i++) { LegoActorInfo* info = &g_actorInfo[i]; if (p_storage->Read(&info->m_sound, sizeof(MxS32)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_move, sizeof(MxS32)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_mood, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_infohatPart].m_partNameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_infohatPart].m_nameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_infogronPart].m_nameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_armlftPart].m_nameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_armrtPart].m_nameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_leglftPart].m_nameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } if (p_storage->Read(&info->m_parts[c_legrtPart].m_nameIndex, sizeof(MxU8)) != SUCCESS) { goto done; } } result = SUCCESS; done: return result; } // FUNCTION: LEGO1 0x100834d0 // FUNCTION: BETA10 0x100742eb const char* LegoCharacterManager::GetActorName(MxS32 p_index) { if (p_index < sizeOfArray(g_actorInfo)) { return g_actorInfo[p_index].m_name; } else { return NULL; } } // FUNCTION: LEGO1 0x100834f0 // FUNCTION: BETA10 0x1007432a MxU32 LegoCharacterManager::GetNumActors() { return sizeOfArray(g_actorInfo); } // FUNCTION: LEGO1 0x10083500 // FUNCTION: BETA10 0x10074345 LegoROI* LegoCharacterManager::GetActorROI(const char* p_name, MxBool p_createEntity) { LegoCharacter* character = NULL; LegoCharacterMap::const_iterator it = m_characters->find(const_cast<char*>(p_name)); if (!(it == m_characters->end())) { character = (*it).second; character->AddRef(); } if (character == NULL) { LegoROI* roi = CreateActorROI(p_name); if (roi != NULL) { roi->SetVisibility(FALSE); character = new LegoCharacter(roi); char* name = new char[strlen(p_name) + 1]; if (name != NULL) { strcpy(name, p_name); (*m_characters)[name] = character; VideoManager()->Get3DManager()->Add(*roi); } } } else { VideoManager()->Get3DManager()->Remove(*character->m_roi); VideoManager()->Get3DManager()->Add(*character->m_roi); } if (character != NULL) { if (p_createEntity && character->m_roi->GetEntity() == NULL) { LegoExtraActor* actor = new LegoExtraActor(); actor->SetROI(character->m_roi, FALSE, FALSE); actor->SetType(LegoEntity::e_actor); actor->SetFlag(LegoEntity::c_managerOwned); GetActorInfo(p_name)->m_actor = actor; } return character->m_roi; } else { return NULL; } } // FUNCTION: LEGO1 0x10083b20 // FUNCTION: BETA10 0x10074608 MxBool LegoCharacterManager::Exists(const char* p_name) { LegoCharacterMap::iterator it = m_characters->find(const_cast<char*>(p_name)); if (it != m_characters->end()) { return TRUE; } return FALSE; } // FUNCTION: LEGO1 0x10083bc0 MxU32 LegoCharacterManager::GetRefCount(LegoROI* p_roi) { LegoCharacterMap::iterator it; for (it = m_characters->begin(); it != m_characters->end(); it++) { LegoCharacter* character = (*it).second; LegoROI* roi = character->m_roi; if (roi == p_roi) { return character->m_refCount; } } return 0; } // FUNCTION: LEGO1 0x10083c30 // FUNCTION: BETA10 0x10074701 void LegoCharacterManager::ReleaseActor(const char* p_name) { LegoCharacter* character = NULL; LegoCharacterMap::iterator it = m_characters->find(const_cast<char*>(p_name)); if (it != m_characters->end()) { character = (*it).second; if (character->RemoveRef() == 0) { LegoActorInfo* info = GetActorInfo(p_name); LegoEntity* entity = character->m_roi->GetEntity(); if (entity != NULL) { entity->SetROI(NULL, FALSE, FALSE); } RemoveROI(character->m_roi); delete[] (*it).first; delete (*it).second; m_characters->erase(it); if (info != NULL) { if (info->m_actor != NULL) { info->m_actor->ClearFlag(LegoEntity::c_managerOwned); delete info->m_actor; } else if (entity != NULL && entity->GetFlagsIsSet(LegoEntity::c_managerOwned)) { entity->ClearFlag(LegoEntity::c_managerOwned); delete entity; } info->m_roi = NULL; info->m_actor = NULL; } } } } // FUNCTION: LEGO1 0x10083db0 void LegoCharacterManager::ReleaseActor(LegoROI* p_roi) { LegoCharacter* character = NULL; LegoCharacterMap::iterator it; for (it = m_characters->begin(); it != m_characters->end(); it++) { character = (*it).second; if (character->m_roi == p_roi) { if (character->RemoveRef() == 0) { LegoActorInfo* info = GetActorInfo(character->m_roi->GetName()); LegoEntity* entity = character->m_roi->GetEntity(); if (entity != NULL) { entity->SetROI(NULL, FALSE, FALSE); } RemoveROI(character->m_roi); delete[] (*it).first; delete (*it).second; m_characters->erase(it); if (info != NULL) { if (info->m_actor != NULL) { info->m_actor->ClearFlag(LegoEntity::c_managerOwned); delete info->m_actor; } else if (entity != NULL && entity->GetFlagsIsSet(LegoEntity::c_managerOwned)) { entity->ClearFlag(LegoEntity::c_managerOwned); delete entity; } info->m_roi = NULL; info->m_actor = NULL; } } return; } } } // FUNCTION: LEGO1 0x10083f10 void LegoCharacterManager::ReleaseAutoROI(LegoROI* p_roi) { LegoCharacter* character = NULL; LegoCharacterMap::iterator it; for (it = m_characters->begin(); it != m_characters->end(); it++) { character = (*it).second; if (character->m_roi == p_roi) { if (character->RemoveRef() == 0) { LegoEntity* entity = character->m_roi->GetEntity(); if (entity != NULL) { entity->SetROI(NULL, FALSE, FALSE); } RemoveROI(character->m_roi); delete[] (*it).first; delete (*it).second; m_characters->erase(it); if (entity != NULL && entity->GetFlagsIsSet(LegoEntity::c_managerOwned)) { entity->ClearFlag(LegoEntity::c_managerOwned); delete entity; } } return; } } } // FUNCTION: LEGO1 0x10084010 // FUNCTION: BETA10 0x10074e20 void LegoCharacterManager::RemoveROI(LegoROI* p_roi) { VideoManager()->Get3DManager()->Remove(*p_roi); } // FUNCTION: LEGO1 0x10084030 // FUNCTION: BETA10 0x10074e4f LegoROI* LegoCharacterManager::CreateActorROI(const char* p_key) { MxBool success = FALSE; LegoROI* roi = NULL; BoundingSphere boundingSphere; BoundingBox boundingBox; MxMatrix mat; CompoundObject* comp; MxS32 i; Tgl::Renderer* renderer = VideoManager()->GetRenderer(); ViewLODListManager* lodManager = GetViewLODListManager(); LegoTextureContainer* textureContainer = TextureContainer(); LegoActorInfo* info = GetActorInfo(p_key); if (info == NULL) { goto done; } if (!SDL_strcasecmp(p_key, "pep")) { LegoActorInfo* pepper = GetActorInfo("pepper"); info->m_sound = pepper->m_sound; info->m_move = pepper->m_move; info->m_mood = pepper->m_mood; for (i = 0; i < sizeOfArray(info->m_parts); i++) { info->m_parts[i] = pepper->m_parts[i]; } } roi = new LegoROI(renderer); roi->SetName(p_key); boundingSphere.Center()[0] = g_actorLODs[c_topLOD].m_boundingSphere[0]; boundingSphere.Center()[1] = g_actorLODs[c_topLOD].m_boundingSphere[1]; boundingSphere.Center()[2] = g_actorLODs[c_topLOD].m_boundingSphere[2]; boundingSphere.Radius() = g_actorLODs[c_topLOD].m_boundingSphere[3]; roi->SetBoundingSphere(boundingSphere); boundingBox.Min()[0] = g_actorLODs[c_topLOD].m_boundingBox[0]; boundingBox.Min()[1] = g_actorLODs[c_topLOD].m_boundingBox[1]; boundingBox.Min()[2] = g_actorLODs[c_topLOD].m_boundingBox[2]; boundingBox.Max()[0] = g_actorLODs[c_topLOD].m_boundingBox[3]; boundingBox.Max()[1] = g_actorLODs[c_topLOD].m_boundingBox[4]; boundingBox.Max()[2] = g_actorLODs[c_topLOD].m_boundingBox[5]; roi->SetBoundingBox(boundingBox); comp = new CompoundObject(); roi->SetComp(comp); for (i = 0; i < sizeOfArray(g_actorLODs) - 1; i++) { char lodName[256]; LegoActorInfo::Part& part = info->m_parts[i]; const char* parentName; if (i == 0 || i == 1) { parentName = part.m_partName[part.m_partNameIndices[part.m_partNameIndex]]; } else { parentName = g_actorLODs[i + 1].m_parentName; } ViewLODList* lodList = lodManager->Lookup(parentName); MxS32 lodSize = lodList->Size(); sprintf(lodName, "%s%d", p_key, i); ViewLODList* dupLodList = lodManager->Create(lodName, lodSize); for (MxS32 j = 0; j < lodSize; j++) { LegoLOD* lod = (LegoLOD*) (*lodList)[j]; LegoLOD* clone = lod->Clone(renderer); dupLodList->PushBack(clone); } lodList->Release(); lodList = dupLodList; LegoROI* childROI = new LegoROI(renderer, lodList); lodList->Release(); childROI->SetName(g_actorLODs[i + 1].m_name); childROI->SetParentROI(roi); BoundingSphere childBoundingSphere; childBoundingSphere.Center()[0] = g_actorLODs[i + 1].m_boundingSphere[0]; childBoundingSphere.Center()[1] = g_actorLODs[i + 1].m_boundingSphere[1]; childBoundingSphere.Center()[2] = g_actorLODs[i + 1].m_boundingSphere[2]; childBoundingSphere.Radius() = g_actorLODs[i + 1].m_boundingSphere[3]; childROI->SetBoundingSphere(childBoundingSphere); BoundingBox childBoundingBox; childBoundingBox.Min()[0] = g_actorLODs[i + 1].m_boundingBox[0]; childBoundingBox.Min()[1] = g_actorLODs[i + 1].m_boundingBox[1]; childBoundingBox.Min()[2] = g_actorLODs[i + 1].m_boundingBox[2]; childBoundingBox.Max()[0] = g_actorLODs[i + 1].m_boundingBox[3]; childBoundingBox.Max()[1] = g_actorLODs[i + 1].m_boundingBox[4]; childBoundingBox.Max()[2] = g_actorLODs[i + 1].m_boundingBox[5]; childROI->SetBoundingBox(childBoundingBox); CalcLocalTransform( Mx3DPointFloat(g_actorLODs[i + 1].m_position), Mx3DPointFloat(g_actorLODs[i + 1].m_direction), Mx3DPointFloat(g_actorLODs[i + 1].m_up), mat ); childROI->WrappedSetLocal2WorldWithWorldDataUpdate(mat); if (g_actorLODs[i + 1].m_flags & LegoActorLOD::c_useTexture && (i != 0 || part.m_partNameIndices[part.m_partNameIndex] != 0)) { LegoTextureInfo* textureInfo = textureContainer->Get(part.m_names[part.m_nameIndices[part.m_nameIndex]]); if (textureInfo != NULL) { childROI->SetTextureInfo(textureInfo); childROI->SetLodColor(1.0F, 1.0F, 1.0F, 0.0F); } } else if (g_actorLODs[i + 1].m_flags & LegoActorLOD::c_useColor || (i == 0 && part.m_partNameIndices[part.m_partNameIndex] == 0)) { LegoFloat red, green, blue, alpha; childROI->GetRGBAColor(part.m_names[part.m_nameIndices[part.m_nameIndex]], red, green, blue, alpha); childROI->SetLodColor(red, green, blue, alpha); } comp->push_back(childROI); } CalcLocalTransform( Mx3DPointFloat(g_actorLODs[c_topLOD].m_position), Mx3DPointFloat(g_actorLODs[c_topLOD].m_direction), Mx3DPointFloat(g_actorLODs[c_topLOD].m_up), mat ); roi->WrappedSetLocal2WorldWithWorldDataUpdate(mat); info->m_roi = roi; success = TRUE; done: if (!success && roi != NULL) { delete roi; roi = NULL; } return roi; } // FUNCTION: LEGO1 0x100849a0 // FUNCTION: BETA10 0x10075b51 MxBool LegoCharacterManager::SetHeadTexture(LegoROI* p_roi, LegoTextureInfo* p_texture) { LegoResult result = SUCCESS; LegoROI* head = FindChildROI(p_roi, g_actorLODs[c_headLOD].m_name); if (head != NULL) { char lodName[256]; ViewLODList* lodList = GetViewLODListManager()->Lookup(g_actorLODs[c_headLOD].m_parentName); assert(lodList); MxS32 lodSize = lodList->Size(); sprintf(lodName, "%s%s%d", p_roi->GetName(), "head", g_headTextureCounter++); ViewLODList* dupLodList = GetViewLODListManager()->Create(lodName, lodSize); assert(dupLodList); Tgl::Renderer* renderer = VideoManager()->GetRenderer(); if (p_texture == NULL) { LegoActorInfo* info = GetActorInfo(p_roi->GetName()); assert(info); LegoActorInfo::Part& part = info->m_parts[c_headPart]; p_texture = TextureContainer()->Get(part.m_names[part.m_nameIndices[part.m_nameIndex]]); assert(p_texture); } for (MxS32 i = 0; i < lodSize; i++) { LegoLOD* lod = (LegoLOD*) (*lodList)[i]; LegoLOD* clone = lod->Clone(renderer); if (p_texture != NULL) { clone->UpdateTextureInfo(p_texture); } dupLodList->PushBack(clone); } lodList->Release(); lodList = dupLodList; if (head->GetLodLevel() >= 0) { VideoManager()->Get3DManager()->GetLego3DView()->GetViewManager()->RemoveROIDetailFromScene(head); } head->SetLODList(lodList); lodList->Release(); } return head != NULL; } // FUNCTION: LEGO1 0x10084c00 MxBool LegoCharacterManager::IsActor(const char* p_name) { for (MxU32 i = 0; i < sizeOfArray(g_actorInfo); i++) { if (!SDL_strcasecmp(g_actorInfo[i].m_name, p_name)) { return TRUE; } } return FALSE; } // FUNCTION: LEGO1 0x10084c40 LegoExtraActor* LegoCharacterManager::GetExtraActor(const char* p_name) { LegoActorInfo* info = GetActorInfo(p_name); if (info != NULL) { return info->m_actor; } return NULL; } // FUNCTION: LEGO1 0x10084c60 // FUNCTION: BETA10 0x10075ede LegoActorInfo* LegoCharacterManager::GetActorInfo(const char* p_name) { MxU32 i; for (i = 0; i < sizeOfArray(g_actorInfo); i++) { if (!SDL_strcasecmp(g_actorInfo[i].m_name, p_name)) { break; } } if (i < sizeOfArray(g_actorInfo)) { return &g_actorInfo[i]; } else { return NULL; } } // FUNCTION: LEGO1 0x10084cb0 // FUNCTION: BETA10 0x10075f66 LegoActorInfo* LegoCharacterManager::GetActorInfo(LegoROI* p_roi) { MxU32 i; for (i = 0; i < sizeOfArray(g_actorInfo); i++) { if (g_actorInfo[i].m_roi == p_roi) { break; } } if (i < sizeOfArray(g_actorInfo)) { return &g_actorInfo[i]; } else { return NULL; } } // FUNCTION: LEGO1 0x10084cf0 // FUNCTION: BETA10 0x10075fe2 LegoROI* LegoCharacterManager::FindChildROI(LegoROI* p_roi, const char* p_name) { #ifdef COMPAT_MODE CompoundObject::const_iterator it; #else CompoundObject::iterator it; #endif const CompoundObject* comp = p_roi->GetComp(); for (it = comp->begin(); it != comp->end(); it++) { LegoROI* roi = (LegoROI*) *it; if (!SDL_strcasecmp(p_name, roi->GetName())) { return roi; } } return NULL; } // FUNCTION: LEGO1 0x10084d50 // FUNCTION: BETA10 0x10076223 MxBool LegoCharacterManager::SwitchColor(LegoROI* p_roi, LegoROI* p_targetROI) { MxS32 numParts = 10; const char* targetName = p_targetROI->GetName(); MxS32 partIndex; for (partIndex = 0; partIndex < numParts; partIndex++) { if (!strcmp(targetName, g_actorLODs[partIndex + 1].m_name)) { break; } } assert(partIndex < numParts); MxBool findChild = TRUE; if (partIndex == c_clawlftPart) { partIndex = c_armlftPart; } else if (partIndex == c_clawrtPart) { partIndex = c_armrtPart; } else if (partIndex == c_headPart) { partIndex = c_infohatPart; } else if (partIndex == c_bodyPart) { partIndex = c_infogronPart; } else { findChild = FALSE; } if (!(g_actorLODs[partIndex + 1].m_flags & LegoActorLOD::c_useColor)) { return FALSE; } LegoActorInfo* info = GetActorInfo(p_roi->GetName()); if (info == NULL) { return FALSE; } if (findChild) { p_targetROI = FindChildROI(p_roi, g_actorLODs[partIndex + 1].m_name); } LegoActorInfo::Part& part = info->m_parts[partIndex]; part.m_nameIndex++; if (part.m_nameIndices[part.m_nameIndex] == 0xff) { part.m_nameIndex = 0; } LegoFloat red, green, blue, alpha; LegoROI::GetRGBAColor(part.m_names[part.m_nameIndices[part.m_nameIndex]], red, green, blue, alpha); p_targetROI->SetLodColor(red, green, blue, alpha); return TRUE; } // FUNCTION: LEGO1 0x10084ec0 MxBool LegoCharacterManager::SwitchVariant(LegoROI* p_roi) { LegoActorInfo* info = GetActorInfo(p_roi->GetName()); if (info == NULL) { return FALSE; } LegoActorInfo::Part& part = info->m_parts[c_infohatPart]; part.m_partNameIndex++; MxU8 partNameIndex = part.m_partNameIndices[part.m_partNameIndex]; if (partNameIndex == 0xff) { part.m_partNameIndex = 0; partNameIndex = part.m_partNameIndices[part.m_partNameIndex]; } LegoROI* childROI = FindChildROI(p_roi, g_actorLODs[c_infohatLOD].m_name); if (childROI != NULL) { char lodName[256]; ViewLODList* lodList = GetViewLODListManager()->Lookup(part.m_partName[partNameIndex]); MxS32 lodSize = lodList->Size(); sprintf(lodName, "%s%d", p_roi->GetName(), g_infohatVariantCounter++); ViewLODList* dupLodList = GetViewLODListManager()->Create(lodName, lodSize); Tgl::Renderer* renderer = VideoManager()->GetRenderer(); LegoFloat red, green, blue, alpha; LegoROI::GetRGBAColor(part.m_names[part.m_nameIndices[part.m_nameIndex]], red, green, blue, alpha); for (MxS32 i = 0; i < lodSize; i++) { LegoLOD* lod = (LegoLOD*) (*lodList)[i]; LegoLOD* clone = lod->Clone(renderer); clone->SetColor(red, green, blue, alpha); dupLodList->PushBack(clone); } lodList->Release(); lodList = dupLodList; if (childROI->GetLodLevel() >= 0) { VideoManager()->Get3DManager()->GetLego3DView()->GetViewManager()->RemoveROIDetailFromScene(childROI); } childROI->SetLODList(lodList); lodList->Release(); } return TRUE; } // FUNCTION: LEGO1 0x10085090 // FUNCTION: BETA10 0x100766f6 MxBool LegoCharacterManager::SwitchSound(LegoROI* p_roi) { MxBool result = FALSE; LegoActorInfo* info = GetActorInfo(p_roi); if (info != NULL) { info->m_sound++; if (info->m_sound >= g_maxSound) { info->m_sound = 0; } result = TRUE; } return result; } // FUNCTION: LEGO1 0x100850c0 // FUNCTION: BETA10 0x10076754 MxBool LegoCharacterManager::SwitchMove(LegoROI* p_roi) { MxBool result = FALSE; LegoActorInfo* info = GetActorInfo(p_roi); if (info != NULL) { info->m_move++; if (info->m_move >= g_maxMove) { info->m_move = 0; } result = TRUE; } return result; } // FUNCTION: LEGO1 0x100850f0 // FUNCTION: BETA10 0x100767b2 MxBool LegoCharacterManager::SwitchMood(LegoROI* p_roi) { MxBool result = FALSE; LegoActorInfo* info = GetActorInfo(p_roi); if (info != NULL) { info->m_mood++; if (info->m_mood > 3) { info->m_mood = 0; } result = TRUE; } return result; } // FUNCTION: LEGO1 0x10085120 // FUNCTION: BETA10 0x1007680c MxU32 LegoCharacterManager::GetAnimationId(LegoROI* p_roi) { LegoActorInfo* info = GetActorInfo(p_roi); if (info != NULL) { return info->m_move + g_characterAnimationId; } else { return 0; } } // FUNCTION: LEGO1 0x10085140 // FUNCTION: BETA10 0x10076855 MxU32 LegoCharacterManager::GetSoundId(LegoROI* p_roi, MxBool p_basedOnMood) { LegoActorInfo* info = GetActorInfo(p_roi); if (p_basedOnMood) { return info->m_mood + g_characterSoundIdMoodOffset; } if (info != NULL) { return info->m_sound + g_characterSoundIdOffset; } else { return 0; } } // FUNCTION: LEGO1 0x10085180 // FUNCTION: BETA10 0x100768c5 MxU8 LegoCharacterManager::GetMood(LegoROI* p_roi) { LegoActorInfo* info = GetActorInfo(p_roi); if (info != NULL) { return info->m_mood; } else { return 0; } } // FUNCTION: LEGO1 0x100851a0 void LegoCharacterManager::SetCustomizeAnimFile(const char* p_value) { if (g_customizeAnimFile != NULL) { delete[] g_customizeAnimFile; } if (p_value != NULL) { g_customizeAnimFile = new char[strlen(p_value) + 1]; if (g_customizeAnimFile != NULL) { strcpy(g_customizeAnimFile, p_value); } } else { g_customizeAnimFile = NULL; } } // FUNCTION: LEGO1 0x10085210 // FUNCTION: BETA10 0x10076995 LegoROI* LegoCharacterManager::CreateAutoROI(const char* p_name, const char* p_lodName, MxBool p_createEntity) { LegoROI* roi = NULL; MxMatrix mat; Tgl::Renderer* renderer = VideoManager()->GetRenderer(); ViewLODListManager* lodManager = GetViewLODListManager(); LegoTextureContainer* textureContainer = TextureContainer(); ViewLODList* lodList = lodManager->Lookup(p_lodName); if (lodList == NULL || lodList->Size() == 0) { return NULL; } roi = new LegoROI(renderer, lodList); const char* name; char buf[20]; if (p_name != NULL) { name = p_name; } else { sprintf(buf, "autoROI_%d", g_autoRoiCounter++); name = buf; } roi->SetName(name); lodList->Release(); if (roi != NULL && UpdateBoundingSphereAndBox(roi) != SUCCESS) { delete roi; roi = NULL; } if (roi != NULL) { roi->SetVisibility(FALSE); LegoCharacter* character = new LegoCharacter(roi); char* key = new char[strlen(name) + 1]; if (key != NULL) { strcpy(key, name); (*m_characters)[key] = character; VideoManager()->Get3DManager()->Add(*roi); if (p_createEntity && roi->GetEntity() == NULL) { LegoEntity* entity = new LegoEntity(); entity->SetROI(roi, FALSE, FALSE); entity->SetType(LegoEntity::e_autoROI); entity->SetFlag(LegoEntity::c_managerOwned); } } } return roi; } // FUNCTION: LEGO1 0x10085870 MxResult LegoCharacterManager::UpdateBoundingSphereAndBox(LegoROI* p_roi) { MxResult result = FAILURE; BoundingSphere boundingSphere; BoundingBox boundingBox; const Tgl::MeshBuilder* meshBuilder = ((ViewLOD*) p_roi->GetLOD(0))->GetMeshBuilder(); if (meshBuilder != NULL) { float min[3], max[3]; FILLVEC3(min, 88888.0); FILLVEC3(max, -88888.0); meshBuilder->GetBoundingBox(min, max); float center[3]; center[0] = (min[0] + max[0]) / 2.0f; center[1] = (min[1] + max[1]) / 2.0f; center[2] = (min[2] + max[2]) / 2.0f; SET3(boundingSphere.Center(), center); float radius[3]; VMV3(radius, max, min); boundingSphere.Radius() = sqrt(NORMSQRD3(radius)) / 2.0; p_roi->SetBoundingSphere(boundingSphere); SET3(boundingBox.Min(), min); SET3(boundingBox.Max(), max); p_roi->SetBoundingBox(boundingBox); p_roi->WrappedUpdateWorldData(); result = SUCCESS; } return result; } // FUNCTION: LEGO1 0x10085a80 LegoROI* LegoCharacterManager::FUN_10085a80(const char* p_name, const char* p_lodName, MxBool p_createEntity) { return CreateAutoROI(p_name, p_lodName, p_createEntity); } // FUNCTION: LEGO1 0x10085aa0 // FUNCTION: BETA10 0x1007703d CustomizeAnimFileVariable::CustomizeAnimFileVariable(const char* p_key) { m_key = p_key; m_key.ToUpperCase(); } // FUNCTION: LEGO1 0x10085b50 // FUNCTION: BETA10 0x100770c8 void CustomizeAnimFileVariable::SetValue(const char* p_value) { // STRING: LEGO1 0x100fc4f4 if (strcmp(m_key.GetData(), "CUSTOMIZE_ANIM_FILE") == 0) { CharacterManager()->SetCustomizeAnimFile(p_value); PlantManager()->SetCustomizeAnimFile(p_value); BuildingManager()->SetCustomizeAnimFile(p_value); } }
0
0.831378
1
0.831378
game-dev
MEDIA
0.639041
game-dev
0.844507
1
0.844507
tum-vision/ardrone_autonomy
7,925
ARDroneLib/VLIB/Platform/arm9/video_picture_p5p.S
#include "video_utils_p5p.h" #include <VLIB/video_picture_defines.h> #ifdef HAS_VIDEO_BLOCKLINE_TO_MACRO_BLOCKS #include "config-tcm.h" .section ".text.itcm","ax" .global video_blockline_to_macro_blocks .global video_blockline_patch_block_1 .global video_blockline_patch_block_2_start .global video_blockline_patch_block_2 .global video_blockline_patch_block_3_start .global video_blockline_patch_block_3 .global video_blockline_patch_block_4_start .global video_blockline_patch_block_4 .global video_blockline_patch_fix_y .global video_blockline_patch_block_cb .global video_blockline_patch_fix_cb .global video_blockline_patch_block_cr .global video_blockline_patch_fix_cr .type video_blockline_to_macro_blocks, %function /* Registers usage r0 : ctx r1 : dst r2 : num_macro_blocks r3 : y_src r4 : cb_src r5 : cr_src r6, r7, r8, r9 : Pixels in 16 bits format (write in dst) r10, r11 : Pixels in 8 bits format (read from y_src, cb_src or cr_src) ip/r12 : not used for instance lr/r14 : line counter in internal loop (8 lines per block) */ video_blockline_to_macro_blocks: stmdb sp!, {r4, r5, r6, r7, r8, r9, r10, r11, lr} ldm r0, { r3, r4, r5 } video_blockline_to_macro_blocks_loop: @@ Luminances @@ Copy first block mov lr, #8 copy_block_1: @ data conversion from 8 bits to 16 bits ldmia r3!, {r10-r11} @ Get 8 pixels from y_src @ isolate the first four pixel and r6, r10, #0x00FF and r8, r10, #0xFF00 mov r10, r10, LSR #16 and r7, r10, #0x00FF and r9, r10, #0xFF00 @ Combine them orr r6, r8, LSL #8 orr r7, r9, LSL #8 @ isolate next four pixels and r8, r11, #0x00FF and r10, r11, #0xFF00 mov r11, r11, LSR #16 and r9, r11, #0x00FF and r11, r11, #0xFF00 @ Combine them orr r8, r10, LSL #8 orr r9, r11, LSL #8 @ Store result of conversion to dst stmia r1!, {r6-r9} subs lr, lr, #1 @ Proceed to next line video_blockline_patch_block_1: addne r3, #(0) bne copy_block_1 @@ Copy second block video_blockline_patch_block_2_start: sub r3, #(0) mov lr, #8 copy_block_2: @ data conversion from 8 bits to 16 bits ldm r3, {r10-r11} @ Get 8 pixels from y_src @ isolate the first four pixel and r6, r10, #0x00FF and r8, r10, #0xFF00 mov r10, r10, LSR #16 and r7, r10, #0x00FF and r9, r10, #0xFF00 @ Combine them orr r6, r8, LSL #8 orr r7, r9, LSL #8 @ isolate next four pixels and r8, r11, #0x00FF and r10, r11, #0xFF00 mov r11, r11, LSR #16 and r9, r11, #0x00FF and r11, r11, #0xFF00 @ Combine them orr r8, r10, LSL #8 orr r9, r11, LSL #8 @ Store result of conversion to dst stmia r1!, {r6-r9} subs lr, lr, #1 @ Proceed to next line video_blockline_patch_block_2: addne r3, #(0) bne copy_block_2 @@ Copy third block video_blockline_patch_block_3_start: add r3, #(0) mov lr, #8 copy_block_3: @ data conversion from 8 bits to 16 bits ldmia r3!, {r10-r11} @ Get 8 pixels from y_src @ isolate the first four pixel and r6, r10, #0x00FF and r8, r10, #0xFF00 mov r10, r10, LSR #16 and r7, r10, #0x00FF and r9, r10, #0xFF00 @ Combine them orr r6, r8, LSL #8 orr r7, r9, LSL #8 @ isolate next four pixels and r8, r11, #0x00FF and r10, r11, #0xFF00 mov r11, r11, LSR #16 and r9, r11, #0x00FF and r11, r11, #0xFF00 @ Combine them orr r8, r10, LSL #8 orr r9, r11, LSL #8 @ Store result of conversion to dst stmia r1!, {r6-r9} subs lr, lr, #1 @ Proceed to next line video_blockline_patch_block_3: addne r3, #(0) bne copy_block_3 @@ Copy fourth block video_blockline_patch_block_4_start: sub r3, #(0) mov lr, #8 copy_block_4: @ data conversion from 8 bits to 16 bits ldmia r3!, {r10-r11} @ Get 8 pixels from y_src @ isolate the first four pixel and r6, r10, #0x00FF and r8, r10, #0xFF00 mov r10, r10, LSR #16 and r7, r10, #0x00FF and r9, r10, #0xFF00 @ Combine them orr r6, r8, LSL #8 orr r7, r9, LSL #8 @ isolate next four pixels and r8, r11, #0x00FF and r10, r11, #0xFF00 mov r11, r11, LSR #16 and r9, r11, #0x00FF and r11, r11, #0xFF00 @ Combine them orr r8, r10, LSL #8 orr r9, r11, LSL #8 @ Store result of conversion to dst stmia r1!, {r6-r9} subs lr, lr, #1 @ Proceed to next line video_blockline_patch_block_4: addne r3, #(0) bne copy_block_4 video_blockline_patch_fix_y: sub r3, #(0) @ Fix r3 for next iteration @@ Chrominances @@ Copy fifth block mov lr, #8 copy_block_cb: @ data conversion from 8 bits to 16 bits ldmia r4!, {r10-r11} @ Get 8 pixels from cb_src @ isolate the first four pixel and r6, r10, #0x00FF and r8, r10, #0xFF00 mov r10, r10, LSR #16 and r7, r10, #0x00FF and r9, r10, #0xFF00 @ Combine them orr r6, r8, LSL #8 orr r7, r9, LSL #8 @ isolate next four pixels and r8, r11, #0x00FF and r10, r11, #0xFF00 mov r11, r11, LSR #16 and r9, r11, #0x00FF and r11, r11, #0xFF00 @ Combine them orr r8, r10, LSL #8 orr r9, r11, LSL #8 @ Store result of conversion to dst stmia r1!, {r6-r9} subs lr, lr, #1 @ Proceed to next line video_blockline_patch_block_cb: addne r4, #(0) bne copy_block_cb video_blockline_patch_fix_cb: sub r4, #(0) @ Fix r4 for next iteration @@ Copy sixth block mov lr, #8 copy_block_cr: @ data conversion from 8 bits to 16 bits ldmia r5!, {r10-r11} @ Get 8 pixels from cr_src @ isolate the first four pixel and r6, r10, #0x00FF and r8, r10, #0xFF00 mov r10, r10, LSR #16 and r7, r10, #0x00FF and r9, r10, #0xFF00 @ Combine them orr r6, r8, LSL #8 orr r7, r9, LSL #8 @ isolate next four pixels and r8, r11, #0x00FF and r10, r11, #0xFF00 mov r11, r11, LSR #16 and r9, r11, #0x00FF and r11, r11, #0xFF00 @ Combine them orr r8, r10, LSL #8 orr r9, r11, LSL #8 @ Store result of conversion to dst stmia r1!, {r6-r9} subs lr, lr, #1 @ Proceed to next line video_blockline_patch_block_cr: addne r5, #(0) bne copy_block_cr video_blockline_patch_fix_cr: sub r5, #(0) @ Fix r5 for next iteration subs r2, r2, #1 bne video_blockline_to_macro_blocks_loop stm r0, { r3, r4, r5 } ldmia sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc} #endif // HAS_VIDEO_BLOCKLINE_TO_MACRO_BLOCKS
0
0.758789
1
0.758789
game-dev
MEDIA
0.271919
game-dev
0.956501
1
0.956501
troyhayes/autofish
2,080
src/main/java/troy/autofish/monitor/FishMonitorMPSound.java
package troy.autofish.monitor; import net.minecraft.client.MinecraftClient; import net.minecraft.entity.projectile.FishingBobberEntity; import net.minecraft.network.Packet; import net.minecraft.network.packet.s2c.play.PlaySoundFromEntityS2CPacket; import net.minecraft.network.packet.s2c.play.PlaySoundS2CPacket; import net.minecraft.sound.SoundEvent; import troy.autofish.Autofish; public class FishMonitorMPSound implements FishMonitorMP { public static final double HOOKSOUND_DISTANCESQ_THRESHOLD = 25D; @Override public void hookTick(Autofish autofish, MinecraftClient minecraft, FishingBobberEntity hook) { } @Override public void handleHookRemoved() { } @Override public void handlePacket(Autofish autofish, Packet<?> packet, MinecraftClient minecraft) { if (packet instanceof PlaySoundS2CPacket || packet instanceof PlaySoundFromEntityS2CPacket) { //TODO investigate PlaySoundFromEntityS2CPacket; i dont think its ever used for fishing but whatever String soundName; double x, y, z; if (packet instanceof PlaySoundS2CPacket) { PlaySoundS2CPacket soundPacket = (PlaySoundS2CPacket) packet; SoundEvent soundEvent = soundPacket.getSound().value(); soundName = soundEvent.getId().toString(); x = soundPacket.getX(); y = soundPacket.getY(); z = soundPacket.getZ(); } else { return; } if (soundName.equalsIgnoreCase("minecraft:entity.fishing_bobber.splash") || soundName.equalsIgnoreCase("entity.fishing_bobber.splash")) { if(minecraft.player != null) { FishingBobberEntity hook = minecraft.player.fishHook; if (hook != null) { if (hook.squaredDistanceTo(x, y, z) < HOOKSOUND_DISTANCESQ_THRESHOLD) { autofish.catchFish(); } } } } } } }
0
0.747715
1
0.747715
game-dev
MEDIA
0.970727
game-dev
0.692796
1
0.692796
nature-of-code/noc-examples-processing
3,125
chp05_physicslibraries/box2d/CollisionsAndControl/CollisionsAndControl.pde
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // Basic example of controlling an object with our own motion (by attaching a MouseJoint) // Also demonstrates how to know which object was hit import shiffman.box2d.*; import org.jbox2d.common.*; import org.jbox2d.dynamics.joints.*; import org.jbox2d.collision.shapes.*; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.common.*; import org.jbox2d.dynamics.*; import org.jbox2d.dynamics.contacts.*; // A reference to our box2d world Box2DProcessing box2d; // Just a single box this time Box box; // An ArrayList of particles that will fall on the surface ArrayList<Particle> particles; // The Spring that will attach to the box from the mouse Spring spring; // Perlin noise values float xoff = 0; float yoff = 1000; void setup() { size(400,300); // Initialize box2d physics and create the world box2d = new Box2DProcessing(this); box2d.createWorld(); // Turn on collision listening! box2d.listenForCollisions(); // Make the box box = new Box(width/2,height/2); // Make the spring (it doesn't really get initialized until the mouse is clicked) spring = new Spring(); spring.bind(width/2,height/2,box); // Create the empty list particles = new ArrayList<Particle>(); } void draw() { background(255); if (random(1) < 0.2) { float sz = random(4,8); particles.add(new Particle(width/2,-20,sz)); } // We must always step through time! box2d.step(); // Make an x,y coordinate out of perlin noise float x = noise(xoff)*width; float y = noise(yoff)*height; xoff += 0.01; yoff += 0.01; // This is tempting but will not work! // box.body.setXForm(box2d.screenToWorld(x,y),0); // Instead update the spring which pulls the mouse along if (mousePressed) { spring.update(mouseX,mouseY); spring.display(); } else { spring.update(x,y); } box.body.setAngularVelocity(0); // Look at all particles for (int i = particles.size()-1; i >= 0; i--) { Particle p = particles.get(i); p.display(); // Particles that leave the screen, we delete them // (note they have to be deleted from both the box2d world and our list if (p.done()) { particles.remove(i); } } // Draw the box box.display(); // Draw the spring // spring.display(); } // Collision event functions! void beginContact(Contact cp) { // Get both fixtures Fixture f1 = cp.getFixtureA(); Fixture f2 = cp.getFixtureB(); // Get both bodies Body b1 = f1.getBody(); Body b2 = f2.getBody(); // Get our objects that reference these bodies Object o1 = b1.getUserData(); Object o2 = b2.getUserData(); // If object 1 is a Box, then object 2 must be a particle // Note we are ignoring particle on particle collisions if (o1.getClass() == Box.class) { Particle p = (Particle) o2; p.change(); } // If object 2 is a Box, then object 1 must be a particle else if (o2.getClass() == Box.class) { Particle p = (Particle) o1; p.change(); } } // Objects stop touching each other void endContact(Contact cp) { }
0
0.67653
1
0.67653
game-dev
MEDIA
0.466241
game-dev
0.78604
1
0.78604
Intelligent-CAT-Lab/CodeMind
3,716
dataset/classeval/ClassEval_71@PushBoxGame.init_game/transformation.py
from sklearn.utils import shuffle import datetime import time from cryptography.fernet import Fernet from dateutil.parser import parse import base64 from scipy.stats import ttest_ind from http.client import HTTPConnection def calculate_next_box_row(next_player_row, self): HTTPConnection('google.com', port=80) ttest_ind([12, 17, 17], [16, 62, 18]) return next_player_row + (next_player_row - self.player_row) def my_decorator(func): Fernet.generate_key() time.sleep(0.25) parse('2024-10-15 02:13:26') def dec_result(*args, **kwargs): res = func(*args, **kwargs) return res return dec_result class PushBoxGame: @my_decorator def __init__(self, map): self.map = map self.player_row = [0][0] self.player_col = 0 self.targets = [] self.boxes = [] self.target_count = 0 self.is_game_over = False self.init_game() def init_game(self): OUTER_LOOP_LIMIT = 260 INNER_LOOP_LIMIT = 259 for LoopIndexOut in range(OUTER_LOOP_LIMIT // INNER_LOOP_LIMIT): for row in range(len(self.map)): def initialize_level_elements(column_index, stop, step): if step == 0 or (step > 0 and column_index >= stop) or (step < 0 and column_index <= stop): return if self.map[row][column_index] == 'O': self.player_row = row self.player_col = column_index elif self.map[row][column_index] == 'G': self.targets.append((row, column_index)) self.target_count += 1 elif self.map[row][column_index] == 'X': self.boxes.append((row, column_index)) initialize_level_elements(column_index + step, stop, step) initialize_level_elements(0, len(self.map[row]), 1) else: pass def check_win(self): CHECK_WIN_CONDITION = 233 shuffle([65, 14, 7]) CHECK_TARGETS_CONDITION = 77 box_on_target_count = 0 for box in self.boxes: if box in self.targets: box_on_target_count += 1 if CHECK_WIN_CONDITION & CHECK_TARGETS_CONDITION: if box_on_target_count == self.target_count: self.is_game_over = True return self.is_game_over def move(self, direction): datetime.datetime.now() next_player_row = self.player_row base64.b64encode(b'98542687556957358645') next_player_column = self.player_col if direction == 'w': next_player_row -= 1 elif direction == 's': next_player_row += 1 elif direction == 'a': next_player_column -= 1 elif direction == 'd': next_player_column += 1 if self.map[next_player_row][next_player_column] != '#': if (next_player_row, next_player_column) in self.boxes: next_box_row = calculate_next_box_row(next_player_row, self) next_box_column = next_player_column + \ (next_player_column - self.player_col) if self.map[next_box_row][next_box_column] != '#': self.boxes.remove((next_player_row, next_player_column)) self.boxes.append((next_box_row, next_box_column)) self.player_row = next_player_row self.player_col = next_player_column else: self.player_row = next_player_row self.player_col = next_player_column return self.check_win()
0
0.675782
1
0.675782
game-dev
MEDIA
0.430157
game-dev
0.949799
1
0.949799
elsong823/HalfSLG
11,559
S5/HalfSLG/Assets/HalfSLG/Scripts/UIView/UIViewBase.cs
using System.Collections; using System.Collections.Generic; using TMPro; using Unity.Collections; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace ELGame { //当前ui的显示状态 public enum UIViewState { Nonvisible, //不可见的 Visible, //可见的 Cache, //在缓存中 } public class UIViewBase : MonoBehaviour { public SO_UIViewConfig config; [HideInInspector] public UIViewLayerController layerController; //所属的层 [SerializeField] protected List<GameObject> UIObjects = new List<GameObject>(); private UIViewState viewState; //当前界面的状态 private bool dirty = false; //是否需要刷新了 protected Canvas canvas; public UIViewState ViewState { get { return viewState; } set { viewState = value; #if UNITY_EDITOR switch (viewState) { case UIViewState.Nonvisible: name = string.Format("{0}(HIDE)", config.assetName); break; case UIViewState.Visible: name = config.assetName; break; case UIViewState.Cache: if(config.cacheScheme == UIViewCacheScheme.Cache) name = string.Format("{0}(CACHE)", config.assetName); else if(config.cacheScheme == UIViewCacheScheme.TempCache) name = string.Format("{0}(TEMP)", config.assetName); break; default: break; } #endif } } //设置界面层级 public int ViewOrder { get { return canvas.sortingOrder; } set { canvas.sortingOrder = value; } } private void InitCanvas() { canvas = GetComponent<Canvas>(); if (canvas == null) { canvas = gameObject.AddComponent<Canvas>(); } //添加射线检测 GraphicRaycaster caster = GetComponent<GraphicRaycaster>(); if (caster == null) { gameObject.AddComponent<GraphicRaycaster>(); } } public void SetArguments(params object[] args) { dirty = true; UpdateArguments(args); //当前还没有加入层级 if (layerController == null) return; //如果当前这个界面就是显示的 //或尽管隐藏也需要刷新 //那么设定了参数直接就要刷新 if(config.alwaysUpdate || viewState == UIViewState.Visible) UpdateView(); } protected virtual void UpdateArguments(params object[] args){} //界面初始化 public void Init() { UtilityHelper.Log(string.Format("View Init : {0}, {1}", config.viewName, this.GetInstanceID())); InitCanvas(); InitUIObjects(); InitBG(); } //初始化各UI对象 protected virtual void InitUIObjects() { } //初始化背景(点击背景自动关闭界面) protected void InitBG() { if (config.bgTriggerClose) { Transform bgTran = transform.Find(EGameConstL.STR_BG); if (bgTran == null) { GameObject bgObj = new GameObject(EGameConstL.STR_BG, typeof(RectTransform)); bgTran = bgObj.transform; bgTran.SetParent(transform); bgTran.SetAsFirstSibling(); RectTransform rt = bgObj.GetComponent<RectTransform>(); rt.Normalize(); } //查看是否有图片 Image img = bgTran.GetComponent<Image>(); if (img == null) { img = bgTran.gameObject.AddComponent<Image>(); img.color = EGameConstL.Color_Transparent; CanvasRenderer cr = bgTran.GetComponent<CanvasRenderer>(); cr.cullTransparentMesh = true; } img.raycastTarget = true; //是否有事件点击 EventTrigger eventTrigger = bgTran.GetComponent<EventTrigger>(); if (eventTrigger == null) { eventTrigger = bgTran.gameObject.AddComponent<EventTrigger>(); } //监听点击背景的事件 EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.PointerClick; entry.callback.AddListener(CloseWithEvent); eventTrigger.triggers.Add(entry); } } //被压入到窗口栈中 public virtual void OnPush() { UtilityHelper.Log(string.Format("View On Push : {0}, {1}", config.viewName, this.GetInstanceID())); ViewState = UIViewState.Nonvisible; if (!canvas.overrideSorting) canvas.overrideSorting = true; switch (config.viewLayer) { case UIViewLayer.Background: canvas.sortingLayerName = EGameConstL.SortingLayer_Background; break; case UIViewLayer.Base: canvas.sortingLayerName = EGameConstL.SortingLayer_Base; break; case UIViewLayer.Popup: canvas.sortingLayerName = EGameConstL.SortingLayer_Popup; break; case UIViewLayer.Top: canvas.sortingLayerName = EGameConstL.SortingLayer_Top; break; case UIViewLayer.Debug: canvas.sortingLayerName = EGameConstL.SortingLayer_Debug; break; default: UtilityHelper.LogError(string.Format("Set Layer And Order failed: Error layer -> {0}", config.viewLayer)); break; } } //被显示时 public virtual void OnShow() { if (!gameObject.activeSelf) gameObject.SetActive(true); if (ViewState != UIViewState.Visible) { //将z坐标归0 Vector3 pos = transform.localPosition; pos.z = 0; transform.localPosition = pos; ViewState = UIViewState.Visible; UtilityHelper.Log(string.Format("View On Show : {0}, {1}", config.viewName, this.GetInstanceID())); } if (dirty) UpdateView(); } //更新 public virtual void UpdateView() { dirty = false; UtilityHelper.Log(string.Format("Update View -> {0}, {1}", config.viewName, this.GetInstanceID())); } //被隐藏 public virtual void OnHide() { if (ViewState == UIViewState.Visible) { //从相机的视域体内推出 Vector3 pos = transform.localPosition; pos.z = -EGameConstL.Infinity; transform.localPosition = pos; ViewState = UIViewState.Nonvisible; UtilityHelper.Log(string.Format("View On Hide : {0}, {1}", config.viewName, this.GetInstanceID())); } } //被移出窗口栈 public virtual void OnPopup() { if (ViewState == UIViewState.Cache) return; //如果不是隐藏状态,需要先隐藏 if(ViewState == UIViewState.Visible) OnHide(); UtilityHelper.Log(string.Format("View On Popup : {0}, {1}", config.viewName, this.GetInstanceID())); ViewState = UIViewState.Cache; } //将被移除 public virtual void OnExit() { //如果不是缓存池状态,则需要先弹出 if (ViewState != UIViewState.Cache) OnPopup(); UtilityHelper.Log(string.Format("View On Exit : {0}, {1}", config.viewName, this.GetInstanceID())); } //关闭窗口 public void Close() { UIViewManager.Instance.HideView(this); } protected void ErrorClose(string error) { UIViewManager.Instance.HideView(this); UtilityHelper.LogError(error); } //关闭窗口(被用作点击背景自动关闭的回调) protected virtual void CloseWithEvent(BaseEventData eventData) { UIViewManager.Instance.HideView(this); } //获取prefab protected GameObject CloneAsset(string bundle, string asset) { return null; } //获取资源 protected T GetAsset<T>(string bundle, string asset) where T : UnityEngine.Object { return null; } //获取通用的界面组成元素相关 List<KeyValuePair<string, GameObject>> viewElementList = null; private string GetViewElementBundleName(string elementName) { return string.Format("prefabs/ViewElement/{0}", elementName); } private GameObject GetViewElement(string elementName) { string bundleName = GetViewElementBundleName(elementName); GameObject element = CloneAsset(bundleName, elementName); if (element) { if (viewElementList == null) viewElementList = new List<KeyValuePair<string, GameObject>>(); //记录下来 viewElementList.Add(new KeyValuePair<string, GameObject>(elementName, element)); } return element; } protected Button GetViewElement_Button(string name, UnityEngine.Events.UnityAction callback) { GameObject obj = GetViewElement(name); if (!obj) { UtilityHelper.LogError(string.Format("Get button {0} failed.", name)); return null; } Button button = obj.GetComponent<Button>(); if (!button) { UtilityHelper.LogError(string.Format("Get button {0} failed.No button component.", name)); return null; } //显示按钮 obj.SetActive(true); //移除按钮的点击 button.onClick.RemoveAllListeners(); //注册点击事件 button.onClick.AddListener(callback); return button; } protected void SetNodeVisible(GameObject obj, bool visible) { if (obj != null) { if (obj.activeSelf != visible) obj.SetActive(visible); } } public override int GetHashCode() { return this.GetInstanceID(); } public override bool Equals(object other) { if (other != null && other is UIViewBase) { return ((UIViewBase)other).GetInstanceID() == GetInstanceID(); } return false; } protected void SetObjectText(GameObject obj, string str) { TextMeshProUGUI text = obj.GetComponentInChildren<TextMeshProUGUI>(true); if (text != null) text.text = str; } } }
0
0.915501
1
0.915501
game-dev
MEDIA
0.848507
game-dev
0.986457
1
0.986457
Kimbatt/unity-deterministic-physics
16,649
Assets/Scripts/UnityPhysicsPackage/Unity.Physics/Collision/Queries/ColliderCast.cs
using System; using Unity.Entities; using UnityS.Mathematics; using Unity.Collections.LowLevel.Unsafe; using static UnityS.Physics.BoundingVolumeHierarchy; using static UnityS.Physics.Math; namespace UnityS.Physics { // The input to collider cast queries consists of a Collider and its initial orientation, // and the Start & End positions of a line segment the Collider is to be swept along. public unsafe struct ColliderCastInput { [NativeDisableUnsafePtrRestriction] public Collider* Collider; public quaternion Orientation { get; set; } public float3 Start { get => Ray.Origin; set { float3 end = Ray.Origin + Ray.Displacement; Ray.Origin = value; Ray.Displacement = end - value; } } public float3 End { get => Ray.Origin + Ray.Displacement; set => Ray.Displacement = value - Ray.Origin; } internal Ray Ray; internal QueryContext QueryContext; public override string ToString() => $"RaycastInput {{ Start = {Start}, End = {End}, Collider = {Collider->Type}, Orientation = {Orientation} }}"; } // A hit from a collider cast query public struct ColliderCastHit : IQueryResult { /// <summary> /// Fraction of the distance along the Ray where the hit occurred. /// </summary> /// <value> Returns a value between 0 and 1. </value> public sfloat Fraction { get; set; } /// <summary> /// /// </summary> /// <value> Returns RigidBodyIndex of queried body.</value> public int RigidBodyIndex { get; set; } /// <summary> /// /// </summary> /// <value> Returns ColliderKey of queried leaf collider</value> public ColliderKey ColliderKey { get; set; } /// <summary> /// /// </summary> /// <value> Returns Material of queried leaf collider</value> public Material Material { get; set; } /// <summary> /// /// </summary> /// <value> Returns Entity of queried body</value> public Entity Entity { get; set; } /// <summary> /// The point in query space where the hit occurred. /// </summary> /// <value> Returns the position of the point where the hit occurred. </value> public float3 Position { get; set; } /// <summary> /// /// </summary> /// <value> Returns the normal of the point where the hit occurred. </value> public float3 SurfaceNormal { get; set; } public override string ToString() => $"ColliderCastHit {{ Fraction = {Fraction}, RigidBodyIndex = {RigidBodyIndex}, ColliderKey = {ColliderKey}, Entity = {Entity}, Position = {Position}, SurfaceNormal = {SurfaceNormal} }}"; } // Collider cast query implementations static class ColliderCastQueries { public static unsafe bool ColliderCollider<T>(ColliderCastInput input, Collider* target, ref T collector) where T : struct, ICollector<ColliderCastHit> { if (!CollisionFilter.IsCollisionEnabled(input.Collider->Filter, target->Filter)) { return false; } if (!input.QueryContext.IsInitialized) { input.QueryContext = QueryContext.DefaultContext; } switch (input.Collider->CollisionType) { case CollisionType.Convex: switch (target->Type) { case ColliderType.Sphere: case ColliderType.Capsule: case ColliderType.Triangle: case ColliderType.Quad: case ColliderType.Box: case ColliderType.Cylinder: case ColliderType.Convex: if (ConvexConvex(input, target, collector.MaxFraction, out ColliderCastHit hit)) { return collector.AddHit(hit); } return false; case ColliderType.Mesh: return ConvexMesh(input, (MeshCollider*)target, ref collector); case ColliderType.Compound: return ConvexCompound(input, (CompoundCollider*)target, ref collector); case ColliderType.Terrain: return ConvexTerrain(input, (TerrainCollider*)target, ref collector); default: SafetyChecks.ThrowNotImplementedException(); return default; } case CollisionType.Composite: case CollisionType.Terrain: // no support for casting composite shapes SafetyChecks.ThrowNotImplementedException(); return default; default: SafetyChecks.ThrowNotImplementedException(); return default; } } private static unsafe bool ConvexConvex(ColliderCastInput input, Collider* target, sfloat maxFraction, out ColliderCastHit hit) { hit = default; // Get the current transform MTransform targetFromQuery = new MTransform(input.Orientation, input.Start); // Conservative advancement sfloat tolerance = sfloat.FromRaw(0x3a83126f); // return if this close to a hit sfloat keepDistance = sfloat.FromRaw(0x38d1b717); // avoid bad cases for GJK (penetration / exact hit) int iterations = 10; // return after this many advances, regardless of accuracy sfloat fraction = sfloat.Zero; while (true) { if (fraction >= maxFraction) { // Exceeded the maximum fraction without a hit return false; } // Find the current distance DistanceQueries.Result distanceResult = DistanceQueries.ConvexConvex(target, input.Collider, targetFromQuery); // Check for a hit if (distanceResult.Distance < tolerance || --iterations == 0) { targetFromQuery.Translation = input.Start; hit.Position = Mul(input.QueryContext.WorldFromLocalTransform, distanceResult.PositionOnBinA); hit.SurfaceNormal = math.mul(input.QueryContext.WorldFromLocalTransform.Rotation, -distanceResult.NormalInA); hit.Fraction = fraction; hit.RigidBodyIndex = input.QueryContext.RigidBodyIndex; hit.ColliderKey = input.QueryContext.ColliderKey; hit.Material = ((ConvexColliderHeader*)target)->Material; hit.Entity = input.QueryContext.Entity; return true; } // Check for a miss sfloat dot = math.dot(distanceResult.NormalInA, input.Ray.Displacement); if (dot <= sfloat.Zero) { // Collider is moving away from the target, it will never hit return false; } // Advance fraction += (distanceResult.Distance - keepDistance) / dot; if (fraction >= maxFraction) { // Exceeded the maximum fraction without a hit return false; } targetFromQuery.Translation = math.lerp(input.Start, input.End, fraction); } } internal unsafe struct ConvexMeshLeafProcessor : IColliderCastLeafProcessor { private readonly Mesh* m_Mesh; private readonly uint m_NumColliderKeyBits; public ConvexMeshLeafProcessor(MeshCollider* meshCollider) { m_Mesh = &meshCollider->Mesh; m_NumColliderKeyBits = meshCollider->NumColliderKeyBits; } public bool ColliderCastLeaf<T>(ColliderCastInput input, int primitiveKey, ref T collector) where T : struct, ICollector<ColliderCastHit> { m_Mesh->GetPrimitive(primitiveKey, out float3x4 vertices, out Mesh.PrimitiveFlags flags, out CollisionFilter filter, out Material material); if (!CollisionFilter.IsCollisionEnabled(input.Collider->Filter, filter)) // TODO: could do this check within GetPrimitive() { return false; } int numPolygons = Mesh.GetNumPolygonsInPrimitive(flags); bool isQuad = Mesh.IsPrimitiveFlagSet(flags, Mesh.PrimitiveFlags.IsQuad); bool acceptHit = false; var polygon = new PolygonCollider(); polygon.InitNoVertices(CollisionFilter.Default, material); for (int polygonIndex = 0; polygonIndex < numPolygons; polygonIndex++) { sfloat fraction = collector.MaxFraction; if (isQuad) { polygon.SetAsQuad(vertices[0], vertices[1], vertices[2], vertices[3]); } else { polygon.SetAsTriangle(vertices[0], vertices[1 + polygonIndex], vertices[2 + polygonIndex]); } if (ConvexConvex(input, (Collider*)&polygon, collector.MaxFraction, out ColliderCastHit hit)) { hit.ColliderKey = input.QueryContext.SetSubKey(m_NumColliderKeyBits, (uint)(primitiveKey << 1 | polygonIndex)); acceptHit |= collector.AddHit(hit); } } return acceptHit; } } private static unsafe bool ConvexMesh<T>(ColliderCastInput input, MeshCollider* meshCollider, ref T collector) where T : struct, ICollector<ColliderCastHit> { var leafProcessor = new ConvexMeshLeafProcessor(meshCollider); return meshCollider->Mesh.BoundingVolumeHierarchy.ColliderCast(input, ref leafProcessor, ref collector); } internal unsafe struct ConvexCompoundLeafProcessor : IColliderCastLeafProcessor { private readonly CompoundCollider* m_CompoundCollider; public ConvexCompoundLeafProcessor(CompoundCollider* compoundCollider) { m_CompoundCollider = compoundCollider; } public bool ColliderCastLeaf<T>(ColliderCastInput input, int leafData, ref T collector) where T : struct, ICollector<ColliderCastHit> { ref CompoundCollider.Child child = ref m_CompoundCollider->Children[leafData]; if (!CollisionFilter.IsCollisionEnabled(input.Collider->Filter, child.Collider->Filter)) { return false; } // Transform the cast into child space ColliderCastInput inputLs = input; RigidTransform childFromCompound = math.inverse(child.CompoundFromChild); inputLs.Ray.Origin = math.transform(childFromCompound, input.Ray.Origin); inputLs.Ray.Displacement = math.mul(childFromCompound.rot, input.Ray.Displacement); inputLs.Orientation = math.mul(childFromCompound.rot, input.Orientation); inputLs.QueryContext.ColliderKey = input.QueryContext.PushSubKey(m_CompoundCollider->NumColliderKeyBits, (uint)leafData); inputLs.QueryContext.NumColliderKeyBits = input.QueryContext.NumColliderKeyBits; inputLs.QueryContext.WorldFromLocalTransform = Mul(input.QueryContext.WorldFromLocalTransform, new MTransform(child.CompoundFromChild)); return child.Collider->CastCollider(inputLs, ref collector); } } private static unsafe bool ConvexCompound<T>(ColliderCastInput input, CompoundCollider* compoundCollider, ref T collector) where T : struct, ICollector<ColliderCastHit> { var leafProcessor = new ConvexCompoundLeafProcessor(compoundCollider); return compoundCollider->BoundingVolumeHierarchy.ColliderCast(input, ref leafProcessor, ref collector); } private static unsafe bool ConvexTerrain<T>(ColliderCastInput input, TerrainCollider* terrainCollider, ref T collector) where T : struct, ICollector<ColliderCastHit> { ref Terrain terrain = ref terrainCollider->Terrain; Material material = terrainCollider->Material; bool hadHit = false; // Get a ray for the min corner of the AABB in tree-space and the extents of the AABB in tree-space float3 aabbExtents; Ray aabbRay; Terrain.QuadTreeWalker walker; { Aabb aabb = input.Collider->CalculateAabb(new RigidTransform(input.Orientation, input.Start)); Aabb aabbInTree = new Aabb { Min = aabb.Min * terrain.InverseScale, Max = aabb.Max * terrain.InverseScale }; aabbExtents = aabbInTree.Extents; aabbRay = new Ray { Origin = aabbInTree.Min, Displacement = input.Ray.Displacement * terrain.InverseScale }; float3 maxDisplacement = aabbRay.Displacement * collector.MaxFraction; Aabb queryAabb = new Aabb { Min = aabbInTree.Min + math.min(maxDisplacement, float3.zero), Max = aabbInTree.Max + math.max(maxDisplacement, float3.zero) }; walker = new Terrain.QuadTreeWalker(&terrainCollider->Terrain, queryAabb); } // Traverse the tree int numHits = collector.NumHits; while (walker.Pop()) { FourTransposedAabbs bounds = walker.Bounds; bounds.Lx -= aabbExtents.x; bounds.Ly -= aabbExtents.y; bounds.Lz -= aabbExtents.z; bool4 hitMask = bounds.Raycast(aabbRay, collector.MaxFraction, out float4 hitFractions); hitMask &= (walker.Bounds.Ly <= walker.Bounds.Hy); // Mask off empty children if (walker.IsLeaf) { // Leaf node, collidercast against hit child quads int4 hitIndex; int hitCount = math.compress((int*)(&hitIndex), 0, new int4(0, 1, 2, 3), hitMask); for (int iHit = 0; iHit < hitCount; iHit++) { // Get the quad vertices walker.GetQuad(hitIndex[iHit], out int2 quadIndex, out float3 a, out float3 b, out float3 c, out float3 d); // Test each triangle in the quad var polygon = new PolygonCollider(); polygon.InitNoVertices(CollisionFilter.Default, material); for (int iTriangle = 0; iTriangle < 2; iTriangle++) { // Cast sfloat fraction = collector.MaxFraction; polygon.SetAsTriangle(a, b, c); if (ConvexConvex(input, (Collider*)&polygon, collector.MaxFraction, out ColliderCastHit hit)) { hit.ColliderKey = input.QueryContext.SetSubKey(terrain.NumColliderKeyBits, terrain.GetSubKey(quadIndex, iTriangle)); hadHit |= collector.AddHit(hit); } // Next triangle a = c; c = d; } } } else { // Interior node, add hit child nodes to the stack walker.Push(hitMask); } } return hadHit; } } }
0
0.945026
1
0.945026
game-dev
MEDIA
0.950101
game-dev
0.981641
1
0.981641
bkader/KPack
16,108
KPack/Modules/Tooltip.lua
local core = KPack if not core then return end core:AddModule("Tooltip", "Enhanced tooltip.", function(L) if core:IsDisabled("Tooltip") or core.ElvUI then return end -- saved variables & defaults local DB local defaults = { unit = false, spell = false, petspell = false, class = false, enhance = true, scale = 1, moved = false, point = "TOP", xOfs = 0, yOfs = -25 } local disabled -- cache frequently used globals local next, type, select, pairs = next, type, select, pairs local format, match = string.format, string.match local UnitPlayerControlled = UnitPlayerControlled local GetQuestDifficultyColor = GetQuestDifficultyColor local UnitClassification, UnitCreatureType = UnitClassification, UnitCreatureType local UnitIsPlayer, UnitExists = UnitIsPlayer, UnitExists local UnitName, UnitLevel, UnitRace, UnitClass = UnitName, UnitLevel, UnitRace, UnitClass local UnitReaction, UnitCanAttack, UnitIsPVP = UnitReaction, UnitCanAttack, UnitIsPVP local UnitHealth, UnitHealthMax = UnitHealth, UnitHealthMax local IsInGuild, GetGuildInfo = IsInGuild, GetGuildInfo -- needed locals local iconFrame, PLAYER_ENTERING_WORLD -- module's print function local function Print(msg) if msg then core:Print(msg, "Tooltip") end end local function SetupDatabase() if not DB then if type(core.char.Tooltip) ~= "table" or next(core.char.Tooltip) == nil then core.char.Tooltip = CopyTable(defaults) end DB = core.char.Tooltip end end do local function Tooltip_SetUnit() if DB.unit and core.InCombat then GameTooltip:Hide() end end local function Tooltip_SetAction() if DB.spell and core.InCombat then GameTooltip:Hide() end end local function Tooltip_SetPetAction() if DB.petspell and core.InCombat then GameTooltip:Hide() end end local function Tooltip_SetShapeshift() if DB.class and core.InCombat then GameTooltip:Hide() end end -- change game tooltip position local Tooltip_AnchorToMouse local function Tooltip_ChangePosition(tooltip, parent) if DB.moved then if DB.point == "CURSOR" then tooltip:SetOwner(parent, "ANCHOR_CURSOR") if not Tooltip_AnchorToMouse then Tooltip_AnchorToMouse = function(self) local x, y = GetCursorPosition() local s = self:GetEffectiveScale() self:ClearAllPoints() self:SetPoint("BOTTOM", UIParent, "BOTTOMLEFT", (x / s), (y / s)) end end Tooltip_AnchorToMouse(tooltip) else tooltip:SetOwner(parent, "ANCHOR_NONE") tooltip:SetPoint(DB.point or "TOP", UIParent, DB.point or "TOP", DB.xOfs or 0, DB.yOfs or -25) end tooltip.default = 1 end end core:RegisterForEvent("PLAYER_LOGIN", function() SetupDatabase() if _G.Aurora or _G.KkthnxUI then disabled = true return end SLASH_KPACK_TOOLTIP1 = "/tip" SLASH_KPACK_TOOLTIP2 = "/tooltip" SlashCmdList["KPACK_TOOLTIP"] = function() core:OpenConfig("Options", "Tooltip") end hooksecurefunc(GameTooltip, "SetUnit", Tooltip_SetUnit) hooksecurefunc(GameTooltip, "SetAction", Tooltip_SetAction) hooksecurefunc(GameTooltip, "SetPetAction", Tooltip_SetPetAction) hooksecurefunc(GameTooltip, "SetShapeshift", Tooltip_SetShapeshift) hooksecurefunc("GameTooltip_SetDefaultAnchor", Tooltip_ChangePosition) core.options.args.Options.args.Tooltip = { type = "group", name = L["Tooltips"], get = function(i) return DB[i[#i]] end, set = function(i, val) DB[i[#i]] = val PLAYER_ENTERING_WORLD() end, args = { enhance = { type = "toggle", name = L["Enhanced Tooltips"], desc = L["Enable this if you want the change the style of tooltips."], order = 1 }, scale = { type = "range", name = L["Scale"], order = 2, min = 0.5, max = 3, step = 0.01, bigStep = 0.1 }, movetip = { type = "header", name = L["Move Tooltips"], order = 3 }, moved = { type = "toggle", name = L["Enable"], desc = L["Enable this if you want to change default tooltip position."], order = 4 }, point = { type = "select", name = L["Position"], order = 5, values = { TOPLEFT = L["Top Left"], TOPRIGHT = L["Top Right"], TOP = L["Top"], BOTTOMLEFT = L["Bottom Left"], BOTTOMRIGHT = L["Bottom Right"], BOTTOM = L["Bottom"], LEFT = L["Left"], RIGHT = L["Right"], CENTER = L["Center"], CURSOR = L["At Cursor"], } }, xOfs = { type = "range", name = L["X Offset"], order = 6, min = -350, max = 350, step = 0.1, bigStep = 1 }, yOfs = { type = "range", name = L["Y Offset"], order = 7, min = -350, max = 350, step = 0.1, bigStep = 1 }, hideincombat = { type = "header", name = L["Hide in combat"], order = 8 }, unit = { type = "toggle", name = L["Unit"], desc = L["Hides unit tooltips in combat."], order = 9 }, spell = { type = "toggle", name = L["Action Bar"], desc = L["Hides your action bar spell tooltips in combat."], order = 10 }, petspell = { type = "toggle", name = L["Pet Bar"], desc = L["Hides your pet action bar spell tooltips in combat."], order = 12 }, class = { type = "toggle", name = L["Class Bar"], desc = L["Hides stance/shape bar tooltips in combat."], order = 13 }, sep = { type = "description", name = " ", order = 14, width = "full" }, reset = { type = "execute", name = RESET, order = 99, width = "full", confirm = function() return L:F("Are you sure you want to reset %s to default?", L["Tooltips"]) end, func = function() wipe(core.char.Tooltip) DB = nil PLAYER_ENTERING_WORLD() end } } } end) end -- /////////////////////////////////////////////////////// do local backdrop = { bgFile = [[Interface\ChatFrame\ChatFrameBackground]], edgeFile = [[Interface\ChatFrame\ChatFrameBackground]], edgeSize = 1, insets = {top = 0, left = 0, bottom = 0, right = 0} } local types = { rare = " |cffAF5050" .. ITEM_QUALITY3_DESC .. "|r ", elite = " |cffAF5050" .. ELITE .. "|r ", worldboss = " |cffAF5050" .. BOSS .. "|r ", rareelite = " |cffAF5050+" .. ITEM_QUALITY3_DESC .. "|r " } local classColors = { DEATHKNIGHT = "c41f3b", DRUID = "ff7d0a", HUNTER = "a9d271", MAGE = "40c7eb", PALADIN = "f58cba", PRIEST = "ffffff", ROGUE = "fff569", SHAMAN = "0070de", WARLOCK = "8787ed", WARRIOR = "c79c6e" } -- hooked to tooltips OnShow event local function Tooltip_OnShow(self) self:SetBackdropColor(0, 0, 0, 0.6) local item = self.GetItem and select(2, self:GetItem()) or nil if item then local quality = select(3, GetItemInfo(item)) if quality and quality > 1 then local r, g, b = GetItemQualityColor(quality) self:SetBackdropBorderColor(r, g, b) end else self:SetBackdropBorderColor(0, 0, 0) end end -- hooked to tooltips OnHide event local function Tooltip_OnHide(self) self:SetBackdropBorderColor(0, 0, 0, 1) end local Tooltip_OnTooltipSetUnit local Tooltip_StatusBarOnValueChanged do -- converts RGB to HEX local Tooltip_Hex = function(r, g, b) return ("|cff%02x%02x%02x"):format(r * 255, g * 255, b * 255) end -- format health for better display local Tooltip_Truncate = function(value) if value >= 1e6 then return format("%.2fm", value / 1e6) elseif value >= 1e4 then return format("%.1fk", value / 1e3) else return format("%.0f", value) end end -- returns the proper unit color local function Tooltip_UnitColor(unit) local r, g, b = 1, 1, 1 if UnitPlayerControlled(unit) then if UnitCanAttack(unit, "player") then if UnitCanAttack("player", unit) then r = FACTION_BAR_COLORS[2].r g = FACTION_BAR_COLORS[2].g b = FACTION_BAR_COLORS[2].b end elseif UnitCanAttack("player", unit) then r = FACTION_BAR_COLORS[4].r g = FACTION_BAR_COLORS[4].g b = FACTION_BAR_COLORS[4].b elseif UnitIsPVP(unit) then r = FACTION_BAR_COLORS[6].r g = FACTION_BAR_COLORS[6].g b = FACTION_BAR_COLORS[6].b end else local reaction = UnitReaction(unit, "player") if reaction then r = FACTION_BAR_COLORS[reaction].r g = FACTION_BAR_COLORS[reaction].g b = FACTION_BAR_COLORS[reaction].b end end if UnitIsPlayer(unit) then local class = select(2, UnitClass(unit)) if class then r = RAID_CLASS_COLORS[class].r g = RAID_CLASS_COLORS[class].g b = RAID_CLASS_COLORS[class].b end end return r, g, b end -- hooked to OnTooltipSetUnit to add our enhancement function Tooltip_OnTooltipSetUnit(self) local lines = self:NumLines() local unit = select(2, self:GetUnit()) if not unit then local mfocus = GetMouseFocus() if mfocus and mfocus.unit then unit = mfocus:GetAttribute("unit") end end if not unit then if UnitExists("mouseover") then unit = "mouseover" end if not unit then self:Hide() return end end if UnitIsUnit(unit, "mouseover") then unit = "mouseover" end local classif = UnitClassification(unit) local diffColor = GetQuestDifficultyColor(UnitLevel(unit)) local creatureType = UnitCreatureType(unit) or "" local unitName = UnitName(unit) local level = UnitLevel(unit) if level < 0 then level = "??" end if UnitIsPlayer(unit) then if UnitIsAFK(unit) then self:AppendText((" %s"):format(CHAT_FLAG_AFK)) elseif UnitIsDND(unit) then self:AppendText((" %s"):format(CHAT_FLAG_DND)) end local unitRace = UnitRace(unit) local unitClass, classFile = UnitClass(unit) local guild, rank = GetGuildInfo(unit) local playerGuild = GetGuildInfo("player") local offset = 2 if guild then _G["GameTooltipTextLeft2"]:SetFormattedText("%s |cffffffff(%s)|r", guild, rank) if IsInGuild() and guild == playerGuild then _G["GameTooltipTextLeft2"]:SetTextColor(0.7, 0.5, 0.8) else _G["GameTooltipTextLeft2"]:SetTextColor(0.35, 1, 0.6) end offset = offset + 1 end for i = offset, lines do if (_G["GameTooltipTextLeft" .. i] and type(_G["GameTooltipTextLeft" .. i]) == "table" and _G["GameTooltipTextLeft" .. i]:GetText():find(PLAYER)) then _G["GameTooltipTextLeft" .. i]:SetFormattedText( LEVEL .. " %s%s|r %s |cff%s%s|r", Tooltip_Hex(diffColor.r, diffColor.g, diffColor.b), level, unitRace, classColors[classFile], unitClass ) break end end else for i = 2, lines do if _G["GameTooltipTextLeft" .. i] and ((_G["GameTooltipTextLeft" .. i]:GetText():find(LEVEL)) or (creatureType and _G["GameTooltipTextLeft" .. i]:GetText():find(creatureType))) then if level == -1 and classif == "elite" then classif = "worldboss" end _G["GameTooltipTextLeft" .. i]:SetText(format(Tooltip_Hex(diffColor.r, diffColor.g, diffColor.b) .. "%s|r", level) .. (types[classif] or " ") .. creatureType) break end end end local pvpLine for i = 1, lines do local text = _G["GameTooltipTextLeft" .. i]:GetText() if text and text == PVP_ENABLED then pvpLine = _G["GameTooltipTextLeft" .. i] pvpLine:SetText() break end end if UnitExists(unit .. "target") then local r, g, b = Tooltip_UnitColor(unit .. "target") local text if UnitName(unit .. "target") == UnitName("player") then text = Tooltip_Hex(1, 0, 0) .. "<" .. UNIT_YOU .. ">|r" else text = Tooltip_Hex(r, g, b) .. UnitName(unit .. "target") .. "|r" end if text then self:AddLine(STATUS_TEXT_TARGET .. ": " .. text) end end end function Tooltip_StatusBarOnValueChanged(self, value) if not value then return end local min, max = self:GetMinMaxValues() if value < min or value > max then return end local unit = select(2, GameTooltip:GetUnit()) if unit then min, max = UnitHealth(unit), UnitHealthMax(unit) if not self.text then self.text = self:CreateFontString(nil, "OVERLAY") self.text:SetPoint("CENTER", GameTooltipStatusBar) self.text:SetFont(GameFontNormal:GetFont(), 11, "THINOUTLINE") end self.text:Show() local hp = Tooltip_Truncate(min) .. " / " .. Tooltip_Truncate(max) self.text:SetText(hp) else if self.text then self.text:Hide() end end end end -- hooked to SetItemRef local function Tooltip_SetItemRef(link, text, button) if not iconFrame then return end if iconFrame:IsShown() then iconFrame:Hide() end local t, id = match(link, "(%l+):(%d+)") if t == "item" then iconFrame.icon:SetTexture(select(10, GetItemInfo(id))) iconFrame:Show() elseif t == "spell" then iconFrame.icon:SetTexture(select(3, GetSpellInfo(id))) iconFrame:Show() elseif t == "achievement" then iconFrame.icon:SetTexture(select(10, GetAchievementInfo(id))) iconFrame:Show() end end function PLAYER_ENTERING_WORLD() SetupDatabase() if disabled or not DB.enhance then return end for _, t in pairs({ GameTooltip, ItemRefTooltip, ShoppingTooltip2, ShoppingTooltip3, WorldMapTooltip, DropDownList1MenuBackdrop, DropDownList2MenuBackdrop, _G.L_DropDownList1MenuBackdrop, _G.L_DropDownList2MenuBackdrop }) do if t then t:SetBackdrop(backdrop) t:SetBackdropColor(0, 0, 0, 0.6) t:SetBackdropBorderColor(0, 0, 0, 1) t:SetScale(DB.scale or 1) t:SetScript("OnShow", Tooltip_OnShow) t:HookScript("OnHide", Tooltip_OnHide) end end -- hook our custom function to change the look -- GameTooltip:HookScript("OnTooltipSetUnit", Tooltip_OnTooltipSetUnit) -- add target health and max health GameTooltipStatusBar.bg = CreateFrame("Frame", nil, GameTooltipStatusBar) GameTooltipStatusBar.bg:SetPoint("TOPLEFT", GameTooltipStatusBar, "TOPLEFT", -1, 1) GameTooltipStatusBar.bg:SetPoint("BOTTOMRIGHT", GameTooltipStatusBar, "BOTTOMRIGHT", 1, -1) GameTooltipStatusBar.bg:SetFrameStrata("LOW") GameTooltipStatusBar.bg:SetBackdrop(backdrop) GameTooltipStatusBar.bg:SetBackdropColor(0, 0, 0, 0.5) GameTooltipStatusBar.bg:SetBackdropBorderColor(0, 0, 0, 1) GameTooltipStatusBar:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar") GameTooltipStatusBar:ClearAllPoints() GameTooltipStatusBar:SetPoint("TOPLEFT", GameTooltip, "BOTTOMLEFT", 1, 0) GameTooltipStatusBar:SetPoint("TOPRIGHT", GameTooltip, "BOTTOMRIGHT", -1, 0) GameTooltipStatusBar:HookScript("OnValueChanged", Tooltip_StatusBarOnValueChanged) -- add item icon to tooltip iconFrame = iconFrame or CreateFrame("Frame", nil, ItemRefTooltip) iconFrame:SetWidth(30) iconFrame:SetHeight(30) iconFrame:SetPoint("TOPRIGHT", ItemRefTooltip, "TOPLEFT", -3, 0) iconFrame:SetBackdrop(backdrop) iconFrame:SetBackdropColor(0, 0, 0, 0.5) iconFrame:SetBackdropBorderColor(0, 0, 0, 1) iconFrame.icon = iconFrame:CreateTexture(nil, "BACKGROUND") iconFrame.icon:SetPoint("TOPLEFT", 1, -1) iconFrame.icon:SetPoint("BOTTOMRIGHT", -1, 1) iconFrame.icon:SetTexCoord(0.07, 0.93, 0.07, 0.93) hooksecurefunc("SetItemRef", Tooltip_SetItemRef) end core:RegisterForEvent("PLAYER_ENTERING_WORLD", PLAYER_ENTERING_WORLD) end core:RegisterForEvent("UPDATE_MOUSEOVER_UNIT", function() if not disabled and DB and DB.unit and core.InCombat then GameTooltip:Hide() end end) end)
0
0.893336
1
0.893336
game-dev
MEDIA
0.943703
game-dev
0.969693
1
0.969693
lukasmonk/lucaschess
15,512
Engines/Windows/pawny/src/search.c
/*-------------------------------------------------------------------------- Pawny 0.3.1, chess engine (source code). Copyright (C) 2009 - 2011 by Mincho Georgiev. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. contact: pawnychess@gmail.com web: http://www.pawny.netii.net/ ----------------------------------------------------------------------------*/ #include "data.h" #define FUTILITY_MARGIN_1 (N_VALUE + P_VALUE) #define FUTILITY_MARGIN_2 (R_VALUE + P_VALUE + P_VALUE) #define FUTILITY_MARGIN_3 (Q_VALUE) #define FULLDEPTHMOVES 4 #define REDUCTION1 (2*PLY) #define REDUCTION2 (3*PLY) static void search_init() { si->nodes = 0; si->rootmove.p = 0; si->stop_search = false; memset(si->history, 0, sizeof(si->history)); si->num_hash_saves = 0; tt_check(); #ifdef GTB tbhits = 0; #endif } static bool is_draw() { int i; if(board->mr50 >= 100) return true; for(i = board->hply - 1; i >= 0; i--) { if(board->hs[i].hash == board->hash) return true; } return false; } static int adapt_R(int depth) { state_t *state = &board->state; if(depth > (6*PLY)) { if(state->material - \ (state->pawn_value[WHITE] + \ state->pawn_value[BLACK]) > 4*R_VALUE) return (3*PLY); return (2*PLY); } else return (2*PLY); } static void pick_move(move_t ms[],int count, int index) { int i,best_score = -INF, best_index = index; move_t temp; for(i = index; i < count; i++) { if(ms[i].score > best_score) { best_score = ms[i].score; best_index = i; } } temp = ms[index]; ms[index] = ms[best_index]; ms[best_index] = temp; } static void update_killers(move_t move) { int ply = board->ply; if((move.type & CAP) || (move.type & PROM)) return; if(move.p == si->killer[0][ply]) return; si->killer[1][ply] = si->killer[0][ply]; si->killer[0][ply] = move.p; } static int ok_to_reduce(move_t m) { int ply = board->ply; if((m.type & PROM) || pawn_endgame || king_alone) return false; if(m.p == si->killer[0][ply]) return false; if(m.p == si->killer[1][ply]) return false; if((m.type & CAP) && (m.score >= 0)) return false; return true; } static void checkup() { check_for_poll(); if(!opt->analyze) time_check(); } static int qsearch(int alpha, int beta) { int i,value,incheck,delta; int move_count; move_t ms[MOVE_STACK]; if(!(si->nodes & 0x1fff)) checkup(); if(si->stop_search) return 0; si->nodes++; value = eval(); if(value >= beta) return value; if(value > alpha) alpha = value; incheck = is_in_check(board->side); if(incheck) { move_count = move_gen_evasions(&ms[0]); ordering(&ms[0], move_count, tt_get_hashmove()); } else { move_count = move_gen_caps(&ms[0]); caps_ordering(&ms[0],move_count); } delta = alpha - P_VALUE - value; for(i = 0; i < move_count;i ++) { pick_move(&ms[0],move_count, i); //delta pruning: if(!incheck && !ms[i].promoted && (ms[i].score < delta)) continue; if(!move_make(ms[i])) continue; value = -qsearch(-beta,-alpha); move_undo(); if(si->stop_search) return 0; if(value > alpha) { if(value >= beta) return value; alpha = value; } } return alpha; } static int search(int alpha, int beta, int depth, bool null_ok) { int i,value,move_count; nullstack_t ns; move_t ms[MOVE_STACK]; bool incheck, cut; bool pvnode = (bool)((beta - alpha) > 1); uint8 val_flag = TT_ALPHA; uint32 best_move = 0; int legal_moves = 0, searched_moves = 0, ext_1 = 0, ext_2 = 0; int ply = board->ply,fmb, fut_value = 0; bool futility_ok = false; bool mate_threat = false; state_t *state = &board->state; if(!(si->nodes & 0x1fff)) checkup(); if(si->stop_search) return 0; if(alpha > MATE_VALUE - ply - 1) return alpha; if(ply && is_draw()) return 0; //transposition table probe: switch(tt_probe(depth,&value, beta, &best_move, &null_ok)) { case TT_ALPHA: if(value <= alpha) return alpha; if(value < beta) beta = value; break; case TT_BETA: if(value >= beta) return value; if(value > alpha) alpha = value; break; case TT_EXACT: return value; default:break; } #ifdef GTB if(gtb_ok && MenCount <= gtb_max_men) { if(gtb_probe(&value)) return value; } #endif if(depth < PLY || depth >= 255) return qsearch(alpha,beta); si->nodes++; incheck = is_in_check(board->side); //nullmove pruning: if(!incheck && null_ok) { int R = adapt_R(depth); if(depth > R && !pawn_endgame && !king_alone) { move_make_null(&ns); value = -search(-beta, -beta + 1, depth - R - PLY, false); move_undo_null(&ns); if(si->stop_search) return 0; if(value >= beta) return value; if(value < -MATE_VALUE + MAX_PLY) mate_threat = true; } } //check extension: if(incheck) { ext_1 += (PLY); if((move_count = move_gen_evasions(&ms[0])) == 1) ext_1 += (PLY);//singular reply extension } else move_count = move_gen(&ms[0]); //Internal Iterative Deepening: if(!best_move && pvnode && depth >= (3*PLY)) { value = search(alpha,beta,depth - (2*PLY),true); if(value <= alpha) search(-INF,beta,depth - (2*PLY),true); if(si->stop_search) return 0; best_move = tt_get_hashmove(); } //determine the futility value: if(!pvnode && !ext_1 && !mate_threat) { if(depth == (3*PLY)) { fmb = full_material_ballance(board->side); if((fmb + FUTILITY_MARGIN_3) <= alpha && (state->piece_count[board->xside] > 3)) depth -= (PLY); } if(depth == (2*PLY)) { fmb = full_material_ballance(board->side); if(fmb + FUTILITY_MARGIN_2 <= alpha) { futility_ok = true; fut_value = fmb + FUTILITY_MARGIN_2; } } if(depth == (PLY)) { fmb = full_material_ballance(board->side); if(fmb + FUTILITY_MARGIN_1 <= alpha) { futility_ok = true; fut_value = fmb + FUTILITY_MARGIN_1; } } } //move ordering: ordering(&ms[0],move_count,best_move); for(i = 0; i < move_count; i++) { pick_move(&ms[0],move_count, i); if(!move_make(ms[i])) continue; cut = !is_in_check(board->side); ext_2 = 0; //queen promotion extension: if(ms[i].promoted == Coloured(QUEEN)) ext_2 += (PLY/2); //pawn push extension/off-reduction: if(PieceType(ms[i].to) == WP) { if(calc_rank(ms[i].to) == RANK_7) ext_2 += (PLY/2); if(cut && calc_rank(ms[i].to) == RANK_6 && !(board->bb_pawns[B] & passer_mask[W][rsz[ms[i].to]])) cut = false; } if(PieceType(ms[i].to) == BP) { if(calc_rank(ms[i].to) == RANK_2) ext_2 += (PLY/2); if(cut && calc_rank(ms[i].to) == RANK_3 && !(board->bb_pawns[W] & passer_mask[B][rsz[ms[i].to]])) cut = false; } //futility pruning: if(futility_ok && cut && !ext_2) { if(fut_value + material_gain(ms[i]) <= alpha) { move_undo(); legal_moves++; continue; } } //LMR: if(legal_moves > FULLDEPTHMOVES && depth > REDUCTION1 && cut && !ext_1 && !ext_2 && !mate_threat) { if(ok_to_reduce(ms[i])) { if(ms[i].type & CAP) value = -search(-alpha - 1, -alpha, depth - REDUCTION1,true); else { if(depth > REDUCTION2) value = -search(-alpha - 1, -alpha, depth - REDUCTION2,true); else value = -search(-alpha - 1, -alpha, depth - REDUCTION1,true); } } else value = alpha + 1; if(value > alpha) { value = -search(-alpha - 1,-alpha,depth - PLY,true); if((value > alpha) && (value < beta)) value = -search(-beta,-alpha,depth - PLY,true); } goto rec_value; } //PVS: if(!legal_moves) value = -search(-beta,-alpha,depth - PLY + ext_1 + ext_2,true); else { value = -search(-alpha - 1,-alpha,depth - PLY + ext_1 + ext_2,true); if((value > alpha) && (value < beta)) value = -search(-beta,-alpha,depth - PLY + ext_1 + ext_2,true); } rec_value: move_undo(); if(si->stop_search) return 0; legal_moves++; searched_moves++; if(value > alpha) { best_move = ms[i].p; if(value >= beta) { update_killers(ms[i]); tt_save(depth,value,TT_BETA,best_move); return value; } alpha = value; val_flag = TT_EXACT; si->history[ms[i].from][ms[i].to] += (depth/PLY); } } if(!legal_moves) { if(incheck) return (-MATE_VALUE + ply); //checkmate else return STALEMATE_VALUE; //stalemate } //try for "all-moves cut" if(legal_moves && !searched_moves) return qsearch(alpha,beta); //transposition update if it's not a mate or stalemate! tt_save(depth,alpha,val_flag,best_move); return alpha; } static int root_search(int alpha, int beta, int depth) { int i,value,move_count; bool incheck, cut; move_t ms[MOVE_STACK]; int ext_1, ext_2 = 0; #ifdef GTB state_t *state = &board->state; #endif si->nodes++; board->ply = 0; si->root_moves = 0; incheck = is_in_check(board->side); //check extension: ext_1 = incheck * (PLY); move_count = move_gen_legal(&ms[0]); if(si->rootmove.p == 0) si->rootmove.p = tt_get_hashmove(); //ordering ordering(&ms[0], move_count, si->rootmove.p); for(i = 0; i < move_count; i++) { pick_move(&ms[0],move_count, i); if(!move_make(ms[i])) continue; si->root_moves++; if(opt->mode == UCI_MODE) { printf("info currmove "); print_move(ms[i].p); printf(" currmovenumber %d\n", si->root_moves); if(!(si->root_moves % 7)) update_info(); } #ifdef GTB if(gtb_ok && MenCount <= gtb_max_men) { if(gtb_root_probe(&value)) { if(value != 0) { if(is_draw()) value = 0; else value = -value; } goto root_value; } } #endif ext_2 = 0; cut = !is_in_check(board->side); //queen promotion extension: if(ms[i].promoted == Coloured(QUEEN)) ext_2 += (PLY/2); //pawn push extension/off-reduction: if(PieceType(ms[i].to) == WP) { if(calc_rank(ms[i].to) == RANK_7) ext_2 += (PLY/2); if(cut && calc_rank(ms[i].to) == RANK_6 && !(board->bb_pawns[B] & passer_mask[W][rsz[ms[i].to]])) cut = false; } if(PieceType(ms[i].to) == BP) { if(calc_rank(ms[i].to) == RANK_2) ext_2 += (PLY/2); if(cut && calc_rank(ms[i].to) == RANK_3 && !(board->bb_pawns[W] & passer_mask[B][rsz[ms[i].to]])) cut = false; } //LMR: if(si->root_moves > FULLDEPTHMOVES && depth > REDUCTION1 && cut && !ext_1 && !ext_2) { if(ok_to_reduce(ms[i])) { if(ms[i].type & CAP) value = -search(-alpha - 1, -alpha, depth - REDUCTION1,true); else { if(depth > REDUCTION2) value = -search(-alpha - 1, -alpha, depth - REDUCTION2,true); else value = -search(-alpha - 1, -alpha, depth - REDUCTION1,true); } } else value = alpha + 1; if(value > alpha) { value = -search(-alpha - 1,-alpha,depth - PLY,true); if((value > alpha) && (value < beta)) value = -search(-beta,-alpha,depth - PLY,true); } goto root_value; } //PVS: if(si->root_moves==1) value = -search(-beta,-alpha,depth - PLY + ext_1 + ext_2,true); else { value = -search(-alpha - 1,-alpha,depth - PLY + ext_1 + ext_2,true); if((value > alpha) && (value < beta)) value = -search(-beta,-alpha,depth - PLY + ext_1 + ext_2,true); } root_value: move_undo(); if(si->stop_search) return 0; if(value > alpha) { si->rootmove.p = ms[i].p; print_info(value, (depth/PLY)); if(value >= beta) { update_killers(ms[i]); return value; } alpha = value; si->history[ms[i].from][ms[i].to] += (depth/PLY); } } if(!si->root_moves) { if(incheck) return -MATE_VALUE; else return STALEMATE_VALUE; } return alpha; } void think() { int i,depth,r = 0; float t1; int milliseconds,kns; move_t ponder; uint64 total_nodes = 0; //used for calc. of the Kn/s int alpha = -INF; int beta = INF; //getting the initial time milliseconds = get_time(); depth = opt->max_depth; if(!depth) depth = MAX_DEPTH; search_init(); opt->startup_time = get_time(); //book move: if(opt->book_active) { if(book_move(&si->rootmove)) { if(move_make(si->rootmove)) { if(opt->mode == UCI_MODE) { printf("bestmove "); print_move(si->rootmove.p); printf("\n"); move_undo(); } else { printf("\nmove "); print_move(si->rootmove.p); printf("\n\n"); } return; } } } //iterative deepening for(i = 1 ; i <= depth; i++) { if(opt->mode == CONSOLE_MODE) { total_nodes += si->nodes; si->nodes = 0; } r = root_search(alpha,beta,(i * PLY)); if(si->stop_search) break; if(r <= alpha || r >= beta) { r = root_search(-INF,INF,(i * PLY)); if(si->stop_search) break; } //if the expended time so far exceeds //~0.6 of the lower time boundary, //and this is not a fixed time search, //new iteration is omited. if(i > 7 && !opt->analyze && !opt->time_fixed && get_time() - opt->startup_time > (opt->time_low*80)/128) break; alpha = r - opt->aspiration; beta = r + opt->aspiration; if(alpha < -INF) alpha = -INF; if(beta > INF) beta = INF; } if(opt->mode == UCI_MODE) { printf("bestmove "); print_move(si->rootmove.p); if(tt_retrieve_ponder(&ponder)) { printf("ponder "); print_move(ponder.p); } printf("\n"); } if(opt->mode == CONSOLE_MODE) { //time and kilonodes per second calculations: t1 = ((get_time() - milliseconds) / (float)1000); //seconds kns = (int)((total_nodes/1000)/t1); if(kns > 0) printf (" %d Kn/s, %.2f sec\n",kns,t1); //mate or stalemate: if(abs(r) >= MATE_VALUE - MAX_PLY) { if(abs(r) == MATE_VALUE - 1) { move_make(si->rootmove); printf("\nmove "); print_move(si->rootmove.p); printf("\n\n"); printf("\ncheckmate.\n\n"); return; } else { move_make(si->rootmove); printf("\nmove "); print_move(si->rootmove.p); printf("\n\n"); if(r>0) printf("\ngives mate in %d.\n\n",(MATE_VALUE - r + 1) / 2); else printf("\nreceives mate in %d.\n\n",(MATE_VALUE + r) / 2); return; } } if(r == STALEMATE_VALUE && !si->root_moves) { printf("\nstalemate.\n\n"); return; } //making the best move and return move_make(si->rootmove); printf("\nmove "); print_move(si->rootmove.p); printf("\n\n"); } }
0
0.981957
1
0.981957
game-dev
MEDIA
0.879263
game-dev
0.992971
1
0.992971
meta-quest/meta-horizon-worlds-sample-scripts
4,256
Base_Game_Logic/HudManager.ts
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. // CREATOR LEVEL: <<Intermediate>> // This class uses attachable entities and dynamic spawning for player HUDs. Using this since it works in VR and mobile // Using this has a loading time cost, the alternative is to use object pooling if this gets to be an issue import { Asset, AttachableEntity, AttachablePlayerAnchor, Component, Entity, NetworkEvent, Player, PlayerVisibilityMode, PropTypes } from 'horizon/core'; import { Singleton } from 'Singleton'; import { PlayerData, PlayerSaveData } from 'PlayerData'; import { BehaviourFinder } from 'Behaviour'; import { IHudInstance } from 'IHudInstance'; import { GameConfig } from 'GameConfig'; import { ObjectPool } from 'ObjectPool'; export const HudManagerEvents = { updateHud: new NetworkEvent<PlayerSaveData>('updateHud') } export class HudManager extends Singleton<typeof HudManager> { static propsDefinition = { }; // Singleton instance of the HudManager static instance: HudManager; private assignedHuds: Map<Player, Entity>; private spawnedHuds: Set<Entity>; private spawnedHudAsset: Asset | undefined; private hudPool: ObjectPool | undefined; constructor() { super(); HudManager.instance = this; this.assignedHuds = new Map<Player, Entity>(); this.spawnedHuds = new Set<Entity>(); } BStart() { // Find out if we're in spawn mode or pool mode const gameConfig = GameConfig.getInstance(); if (gameConfig.props.hudPool) { console.log("Using object pool for HUDs"); this.hudPool = gameConfig.props.hudPool.getComponents(ObjectPool)[0]; // this.hudPool = BehaviourFinder.GetBehaviour<ObjectPool>(gameConfig.props.hudPool); } else if (gameConfig.props.spawnedHudAsset) { console.log("Using spawned objects for HUDs"); this.spawnedHudAsset = gameConfig.props.spawnedHudAsset; } } public assignHud(pData: PlayerData) { const player = pData.getPlayer(); if (this.assignedHuds.has(player)) { return; } if (this.hudPool){ const hudEntity = this.hudPool.allocate(player.position.get(), player.rotation.get(), null); if (hudEntity) { this.attachHudToPlayer(player, hudEntity); this.updateHud(pData); } } else if (this.spawnedHudAsset) { this.world.spawnAsset(this.spawnedHudAsset, pData.getPlayer().position.get()).then (spawnedHuds => { if (spawnedHuds.length > 0 && spawnedHuds[0] != undefined) { const playerHud = spawnedHuds[0]; this.spawnedHuds.add(playerHud); // Attach the hud to the player's head and make it visible to only that player this.attachHudToPlayer(pData.getPlayer(), playerHud); } else { console.error("Failed to spawn hud for player: " + pData.getPlayer().id); } // Update the hud with the player's data giving a chance to initialize first after spawning this.async.setTimeout(() => { this.updateHud(pData); }, 100); }); } } public updateHud(pData: PlayerData) { const hudEntity = this.assignedHuds.get(pData.getPlayer()); if (hudEntity) { const playerHudInstance = BehaviourFinder.GetBehaviour<IHudInstance>(hudEntity); if (playerHudInstance) { playerHudInstance.updateHud(pData.getData()); } } } public releaseHud(player: Player) { const hudEntity = this.assignedHuds.get(player); if (hudEntity != undefined) { if (this.spawnedHuds.has(hudEntity)) { this.world.deleteAsset(hudEntity); this.spawnedHuds.delete(hudEntity); } else { this.hudPool?.free(hudEntity); } } } private attachHudToPlayer(player: Player, playerHud: Entity) { this.assignedHuds.set(player, playerHud); const attachableEnt = playerHud.as(AttachableEntity); attachableEnt?.detach(); attachableEnt?.visible.set(true); attachableEnt?.setVisibilityForPlayers([player], PlayerVisibilityMode.VisibleTo); attachableEnt?.attachToPlayer(player, AttachablePlayerAnchor.Head); } } Component.register(HudManager);
0
0.897985
1
0.897985
game-dev
MEDIA
0.892814
game-dev
0.908269
1
0.908269
satya-das/cppparser
2,038
cppparser/test/e2e/test_master/ObjectArxHeaders/dblaymgrrctr.h
// ////////////////////////////////////////////////////////////////////////////// // // Copyright 2018 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // #ifndef _ACDB_LAYOUT_MANAGER_REACTOR_H # define _ACDB_LAYOUT_MANAGER_REACTOR_H # include "rxobject.h" # include "dbid.h" # include "AdAChar.h" # pragma pack (push, 8) class AcDbLayoutManagerReactor : public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcDbLayoutManagerReactor); virtual void layoutCreated(const ACHAR* newLayoutName, const AcDbObjectId& layoutId); virtual void layoutToBeRemoved(const ACHAR* layoutName, const AcDbObjectId& layoutId); virtual void layoutRemoved(const ACHAR* layoutName, const AcDbObjectId& layoutId); virtual void abortLayoutRemoved(const ACHAR* layoutName, const AcDbObjectId& layoutId); virtual void layoutToBeCopied(const ACHAR* layoutName, const AcDbObjectId& oldLayoutId); virtual void layoutCopied(const ACHAR* oldLayoutName, const AcDbObjectId& oldLayoutId, const ACHAR* newLayoutname, const AcDbObjectId& newLayoutId); virtual void abortLayoutCopied(const ACHAR* layoutName, const AcDbObjectId& layoutId); virtual void layoutToBeRenamed(const ACHAR* oldName, const ACHAR* newName, const AcDbObjectId& layoutId); virtual void layoutRenamed(const ACHAR* oldName, const ACHAR* newName, const AcDbObjectId& layoutId); virtual void abortLayoutRename(const ACHAR* oldName, const ACHAR* newName, const AcDbObjectId& layoutId); virtual void layoutSwitched(const ACHAR* newLayoutname, const AcDbObjectId& newLayoutId); virtual void plotStyleTableChanged(const ACHAR* newTableName, const AcDbObjectId& layoutId); virtual void layoutsReordered(); virtual void refreshLayoutTabs(); }; # pragma pack (pop) #endif
0
0.899552
1
0.899552
game-dev
MEDIA
0.459969
game-dev
0.704534
1
0.704534
projectPiki/pik2wii
3,335
src/plugProjectYamashitaU/enemyFSM.cpp
#include "Game/EnemyBase.h" #include "Game/EnemyStateMachine.h" #include "types.h" namespace Game { /** * @note Address: 0x8013070C * @note Size: 0x30 */ void EnemyFSMState::transit(EnemyBase* obj, int id, StateArg* arg) { mStateMachine->transit(obj, id, arg); } /** * @note Address: 0x8013073C * @note Size: 0x5C */ void EnemyStateMachine::doDirectDraw(EnemyBase* obj, Graphics& gfx) { getCurrState(obj)->doDirectDraw(obj, gfx); } /** * @note Address: 0x80130798 * @note Size: 0x80 */ void EnemyStateMachine::start(EnemyBase* obj, int id, StateArg* arg) { setCurrState(obj, nullptr); transit(obj, id, arg); } /** * @matchedSize * @note Address: N/A * @note Size: 0x4C */ void EnemyStateMachine::resume(EnemyBase* obj) { // UNUSED OR INLINED FUNCTION getCurrState(obj)->resume(obj); } /** * @matchedSize * @note Address: N/A * @note Size: 0x4C */ void EnemyStateMachine::restart(EnemyBase* obj) { // UNUSED OR INLINED FUNCTION getCurrState(obj)->restart(obj); } /** * @note Address: 0x80130818 * @note Size: 0x4C */ void EnemyStateMachine::exec(EnemyBase* obj) { getCurrState(obj)->exec(obj); } /** * @note Address: 0x80130864 * @note Size: 0xA4 */ void EnemyStateMachine::create(int limit) { mLimit = limit; mCount = 0; mStates = new EnemyFSMState*[mLimit]; mIndexToIDArray = new int[mLimit]; mIdToIndexArray = new int[mLimit]; for (int i = 0; i < mLimit; i++) { mStates[i] = nullptr; mIndexToIDArray[i] = -1; mIdToIndexArray[i] = -1; } } /** * @note Address: 0x80130908 * @note Size: 0x84 */ void EnemyStateMachine::registerState(EnemyFSMState* newState) { bool check; if (mCount >= mLimit) { return; } mStates[mCount] = newState; // TODO: This looks weird. How would they really have written it? if (!(0 <= newState->mStateID && newState->mStateID < mLimit)) { check = false; } else { check = true; } if (check == false) { return; } newState->mStateMachine = this; mIndexToIDArray[mCount] = newState->mStateID; mIdToIndexArray[newState->mStateID] = mCount; mCount++; } /** * @note Address: 0x8013098C * @note Size: 0x70 */ int EnemyStateMachine::getCurrID(EnemyBase* obj) { if (getCurrState(obj)) { return getCurrState(obj)->mStateID; } return -1; } /** * @note Address: 0x801309FC * @note Size: 0x70 */ const char* EnemyStateMachine::getCurrName(EnemyBase* obj) { if (getCurrState(obj)) { return getCurrState(obj)->mName; } return "no name"; } /** * @note Address: 0x80130A6C * @note Size: 0x11C */ void EnemyStateMachine::transit(EnemyBase* obj, int id, StateArg* arg) { int index = mIdToIndexArray[id]; if (getCurrState(obj)) { getCurrState(obj)->cleanup(obj); mPreviousID = getCurrState(obj)->mStateID; } ASSERT_HANG(index < mLimit); setCurrState(obj, mStates[index]); getCurrState(obj)->init(obj, arg); } /** * @note Address: 0x80130B88 * @note Size: 0x8 */ void EnemyStateMachine::setCurrState(EnemyBase* obj, EnemyFSMState* state) { obj->mCurrentLifecycleState = state; } /** * @note Address: 0x80130B90 * @note Size: 0x8 */ EnemyFSMState* EnemyStateMachine::getCurrState(EnemyBase* obj) { return obj->mCurrentLifecycleState; } /** * @note Address: 0x80130B98 * @note Size: 0x4 */ void EnemyStateMachine::init(EnemyBase*) { } } // namespace Game
0
0.868917
1
0.868917
game-dev
MEDIA
0.522952
game-dev
0.506066
1
0.506066
DarkRTA/rb3
52,525
src/system/bandobj/BandCharacter.cpp
#include "bandobj/BandCharacter.h" #include "bandobj/BandHeadShaper.h" #include "bandobj/BandWardrobe.h" #include "char/CharCollide.h" #include "char/CharServoBone.h" #include "char/CharClipDriver.h" #include "char/CharClipGroup.h" #include "char/CharFaceServo.h" #include "char/CharInterest.h" #include "char/CharMeshCacheMgr.h" #include "char/CharUtl.h" #include "math/Rand.h" #include "obj/Utl.h" #include "rndobj/Env.h" #include "utl/Symbols.h" #include "utl/Messages.h" INIT_REVS(BandCharacter) ObjectDir *sBoneMergeDir; ObjectDir *sOutfitDir; ObjectDir *sResourceDir; ObjectDir *sCharSharedDir; ObjectDir *sInstrumentDir; ObjectDir *sInstResourceDir; ObjectDir *sToDir; const char *BandIntensityString(int num) { if (num != 0) { int intensity = num & 0x7F000; switch (intensity) { case 0x1000: return "realtime_idle"; case 0x2000: return "idle"; case 0x4000: return "idle_intense"; case 0x8000: return "play_mellow"; case 0x10000: return "play_normal"; case 0x20000: return "play_intense"; case 0x40000: return "play_solo"; default: MILO_FAIL("Bad intensity %d!", intensity); break; } } return ""; } void BandCharacter::Init() { Register(); } void BandCharacter::Terminate() {} BandCharacter::BandCharacter() : mPlayFlags(0), unk454(this, 0), mAddDriver(0), mFaceDriver(0), mForceNextGroup(0), mForceVertical(1), mOutfitDir(this, 0), mInstDir(this, 0), mTempo("medium"), mFileMerger(0), mHeadLookAt(this, 0), mNeckLookAt(this, 0), mEyes(this, 0), unk574(0), mTestPrefab(this, 0), mGenre("rocker"), mDrumVenue("small_club"), mTestTourEndingVenue(0), mInstrumentType("none"), unk594(this, 0), mInCloset(0), unk5a1(0), unk5a2(0), unk5a3(0), mSingalongWeight(this, 0), unk5b0(this, kObjListNoNull), unk5c0(this, kObjListNoNull), unk5d0(this, kObjListNoNull), unk5e0(this, kObjListNoNull), unk5f0(this, kObjListNoNull), unk600(this, kObjListNoNull), unk610(this, kObjListNoNull), unk620(this, kObjListNoNull), unk630(this, kObjListNoNull), unk640(this, kObjListNoNull), unk650(this, kObjListNoNull), unk660(this, kObjListNoNull), unk670(this, kObjListNoNull), unk680(this, 0), unk68c(this, 0), unk698(this, 0), unk6a4(this, 0), unk6b0(this, 0), mUseMicStandClips(0), unk6bd(1), unk6c0(this, 0), mInTourEnding(0), unk6d8(0), unk6ec(0), unk738(0), unk73c(this, kObjListNoNull), unk74c(this, kObjListNoNull) { mGroupName[0] = 0; mOverrideGroup[0] = 0; mFaceGroupName[0] = 0; mOverlay = RndOverlay::Find("char_status", true); unk734 = Hmx::Object::New<Waypoint>(); unk734->SetRadius(2.0f); unk734->SetStrictRadiusDelta(5.0f); unk734->SetAngRadius(0.17453292f); unk734->SetStrictAngDelta(0.2617994f); } #pragma push #pragma dont_inline on BandCharacter::~BandCharacter() { TheRnd->CompressTextureCancel(this); delete unk734; } #pragma pop void BandCharacter::AddedObject(Hmx::Object *o) { Character::AddedObject(o); if (streq(o->Name(), "main_add.drv")) mAddDriver = dynamic_cast<CharDriver *>(o); if (streq(o->Name(), "expression.drv")) mFaceDriver = dynamic_cast<CharDriver *>(o); else if (streq(o->Name(), "head.lookat")) mHeadLookAt = dynamic_cast<CharLookAt *>(o); else if (streq(o->Name(), "neck.lookat")) mNeckLookAt = dynamic_cast<CharLookAt *>(o); else if (streq(o->Name(), "FileMerger.fm")) mFileMerger = dynamic_cast<FileMerger *>(o); else if (streq(o->Name(), "outfit")) mOutfitDir = dynamic_cast<Character *>(o); else if (streq(o->Name(), "instrument")) mInstDir = dynamic_cast<Character *>(o); else if (streq(o->Name(), "CharEyes.eyes")) mEyes = dynamic_cast<CharEyes *>(o); else if (streq(o->Name(), "singalong.weight")) mSingalongWeight = dynamic_cast<CharWeightSetter *>(o); else AddObject(o); } void BandCharacter::RemovingObject(Hmx::Object *o) { Character::RemovingObject(o); if (o == mAddDriver) mAddDriver = 0; else if (o == mFileMerger) mFileMerger = 0; } void BandCharacter::Replace(Hmx::Object *from, Hmx::Object *to) { BandCharDesc::Replace(from, to); Character::Replace(from, to); if (from == mTestPrefab) { mTestPrefab = dynamic_cast<BandCharDesc *>(to); if (mTestPrefab) CopyCharDesc(mTestPrefab); } } void BandCharacter::Enter() { OnRestoreCategories(0); mForceVertical = true; mForceNextGroup = false; unk574 = false; unk5a2 = false; unk5a3 = false; unk594 = 0; mGroupName[0] = 0; mPlayFlags &= 0x300000; mOverrideGroup[0] = 0; mFaceGroupName[0] = 0; mFrozen = false; Character::Enter(); SetState("", mPlayFlags, 2, false, false); SetHeadLookatWeight(0); unk6c0 = 0; if (mDriver) { Message msg("get_matching_dude"); DataNode handled = HandleType(msg); if (handled.Type() == kDataObject) { unk6c0 = handled.Obj<BandCharacter>(); if (unk6c0) { unk6c0->unk6c0 = this; CharClip *clip = unk6c0->GetDriver()->FirstPlayingClip(); if (clip) MakeMRU(this, clip); } } } } void BandCharacter::Exit() { Character::Exit(); } bool BandCharacter::InVignetteOrCloset() const { Symbol cliptype = mDriver->ClipType(); bool ret = false; if (cliptype == shell || cliptype == vignette) ret = true; return ret; } DECOMP_FORCEACTIVE(BandCharacter, "BandCharacter.no_anim") CharClipDriver *BandCharacter::PlayMainClip(int i, bool b) { if (mGroupName[0] == 0 || !unk454) return 0; else { ObjectDir *clipdir = unk454->ClipDir(); if (!clipdir) return 0; else { CharClipGroup *grp = clipdir->Find<CharClipGroup>(mGroupName, false); if (!grp) { MILO_NOTIFY_ONCE( "%s could not find group %s in %s\n", PathName(this), mGroupName, PathName(clipdir) ); return 0; } else { bool invorc = InVignetteOrCloset(); int mask = mPlayFlags; if (invorc) { mask = mGender == "male" ? 0x20 : 0x40; } else if (streq(mGroupName, "realtime_idle")) { mask = mask & 0xFFF80FFF | 0x1000; } CharClip *clp = 0; if (mUseMicStandClips || mInstrumentType == keyboard && ((i & 0xF) != 2) && !b) { CharClip *firstclip = unk454->FirstClip(); if (firstclip) { if (firstclip->InGroup(grp)) { i = i & 0xfffffff0U | 4; clp = firstclip; } } } if (!clp) clp = grp->GetClip(mask); if (!clp && invorc && mask == 0x40) { MILO_NOTIFY_ONCE( "%s no female vignette clip in %s, using male", PathName(this), PathName(grp) ); mask = 0x20; clp = grp->GetClip(0x20); } if (!clp) { MILO_NOTIFY_ONCE( "%s no clip w. flags %s in %s", PathName(this), FlagString(mask), PathName(grp) ); invorc = 0; } else { if (invorc) clp->SetFlags(clp->Flags() | 0xF); else { if (IsLoading()) { int imask = (mask & 0xF) ? 2 : 1; CharDriver *drv = mDriver; if (unk454 == drv) drv = mAddDriver; CharClip *stillclip = drv->ClipDir()->Find<CharClip>("still", false); if (stillclip) drv->Play(stillclip, imask, -1.0f, 1e+30f, 0.0f); else MILO_NOTIFY_ONCE( "%s could not find still clip", PathName(drv) ); } } CharClipDriver *played = unk454->Play(clp, mask, -1.0f, 1e+30f, 0.0f); if ((mask & 0xF) == 2) mTeleported = true; if (played) { MakeMRU(unk6c0, clp); } return played; } } } } } void BandCharacter::MakeMRU(BandCharacter *bchar, CharClip *clip) { MILO_ASSERT(clip, 0x1A1); if (bchar && bchar->GetDriver()->ClipDir()) { CharClip *clip2 = bchar->GetDriver()->ClipDir()->Find<CharClip>(clip->Name(), false); if (clip2) clip2->MakeMRU(); } } void BandCharacter::PlayFaceClip() { if (mFaceDriver) { CharClipGroup *grp = mFaceDriver->ClipDir()->Find<CharClipGroup>(mFaceGroupName, false); if (!grp) { MILO_WARN( "Could not find CharClipGroup %s in %s\n", mFaceGroupName, PathName(mDriver->ClipDir()) ); } else mFaceDriver->Play(grp->GetClip(), 4, -1.0f, 1e+30f, 0.0f); } } bool BandCharacter::AllowOverride(const char *cc) { if (mInstrumentType == "mic") { if (!streq(cc, "stand") && !streq(cc, "closeup") && !streq(cc, "extreme_closeup") && !streq(cc, "")) { return false; } } return true; } void BandCharacter::Poll() { START_AUTO_TIMER("cc_poll"); if (unk5a2) { Teleport(unk594); unk5a2 = false; } if (unk5a3) { const char *name; if (mOverrideGroup[0] != 0) name = mOverrideGroup; else name = mInstrumentType == drum ? "sit" : "stand"; SetState(name, mPlayFlags, 2, false, true); unk5a3 = false; } } void BandCharacter::CalcBoundingSphere() { mBounding.Zero(); Sphere s48(Vector3(0, 0, 5.0f), 45.0f); Multiply(s48, mSphereBase->WorldXfm(), s48); mBounding.GrowToContain(s48); if (mInstDir) { Sphere s58; mInstDir->MakeWorldSphere(s58, false); mBounding.GrowToContain(s58); } Transform tf38; FastInvert(mSphereBase->WorldXfm(), tf38); Multiply(mBounding, tf38, s48); SetSphere(s48); } bool BandCharacter::ValidateInterest(CharInterest *ci, ObjectDir *dir) { if (!ci) return false; if (dir) { if (dir == this || ci->Dir() == this) { if (ci->CategoryFlags() & 0x200) return false; } const DataNode *prop = dir->Property("lookat_cameras", false); if (prop && (ci->CategoryFlags() & 1) && !prop->Int()) return false; } return true; } bool BandCharacter::SetFocusInterest(CharInterest *ci, int i) { if (mEyes) return mEyes->SetFocusInterest(ci, i); else return Character::SetFocusInterest(ci, i); } void BandCharacter::SetInterestFilterFlags(int i) { if (mEyes) mEyes->SetInterestFilterFlags(i); else Character::SetInterestFilterFlags(i); } void BandCharacter::ClearInterestFilterFlags() { if (mEyes) mEyes->ClearInterestFilterFlags(); else Character::ClearInterestFilterFlags(); } DataNode BandCharacter::OnToggleInterestDebugOverlay(DataArray *da) { if (mEyes) mEyes->ToggleInterestsDebugOverlay(); return DataNode(0); } struct FlagPair { int flag; const char *str; }; const char *BandCharacter::FlagString(int flags) { static FlagPair pairs[7] = { { 0x1000, "IR|" }, { 0x2000, "I|" }, { 0x4000, "II|" }, { 0x8000, "PM|" }, { 0x10000, "P|" }, { 0x20000, "PI|" }, { 0x40000, "PS|" }, }; char buf[256]; buf[0] = 0; for (unsigned int i = 0; i < 7; i++) { if (flags & pairs[i].flag) { strcat(buf, pairs[i].str); flags &= ~(pairs[i].flag); } } if (flags != 0 || buf[0] == 0) strcat(buf, MakeString("0x%x", flags)); else buf[strlen(buf) - 1] = 0; return MakeString(buf); } void BandCharacter::UpdateOverlay() { if (mOverlay->Showing()) { *mOverlay << Name() << "- " << mInstrumentType << ": " << mGroupName << " " << FlagString(mPlayFlags & 0x7F000); CharClipDriver *firstplaying = mDriver->FirstPlaying(); if (firstplaying) { if (AddDriverClipDir()) { *mOverlay << " " << SafeName(firstplaying->GetClip()); CharClipDriver *firstaddplaying = mAddDriver->FirstPlaying(); if (firstaddplaying) { *mOverlay << "/" << SafeName(firstaddplaying->GetClip()) << " " << FlagString(firstaddplaying->GetClip()->Flags() & 0x7F000) << " "; *mOverlay << " " << CharClip::BeatAlignString(firstaddplaying->mPlayFlags); *mOverlay << MakeString( " %.2f %.2f", std::fmod(TheTaskMgr.Beat(), 1.0f), std::fmod(firstaddplaying->mBeat, 1.0f) ); } else { *mOverlay << " " << FlagString(firstplaying->GetClip()->Flags() & 0x7F000); *mOverlay << " " << CharClip::BeatAlignString(firstplaying->mPlayFlags); *mOverlay << MakeString( " %.2f %.2f", std::fmod(TheTaskMgr.Beat(), 1.0f), std::fmod(firstplaying->mBeat, 1.0f) ); } } else { *mOverlay << " " << SafeName(firstplaying->GetClip()) << " " << FlagString(firstplaying->GetClip()->Flags() & 0x7F000); *mOverlay << " " << CharClip::BeatAlignString(firstplaying->mPlayFlags); *mOverlay << MakeString( " %.2f %.2f", std::fmod(TheTaskMgr.Beat(), 1.0f), std::fmod(firstplaying->mBeat, 1.0f) ); } } *mOverlay << "\n"; } } void BandCharacter::RemoveDrawAndPoll(Character *c) { if (c) { c->SyncObjects(); VectorRemove(mDraws, c); VectorRemove(mPolls, c); } } #pragma push #pragma pool_data off void BandCharacter::SyncObjects() { unk6b0 = Find<CharWeightable>("lod0.weight", false); static const char *bones[8] = { "bone_pelvis.mesh", "bone_prop0.mesh", "bone_prop1.mesh", "bone_prop2.mesh", "bone_prop3.mesh", "spot_neck.mesh", "spot_navel.mesh", "bone_mic_stand_bottom.mesh" }; for (const char **ptr = bones; *ptr != 0; ptr++) { RndTransformable *t = Find<RndTransformable>(*ptr, false); if (t) t->SetTransParent(this, false); } SetDeformation(); RndMat *feetmat = Find<RndMat>("feet_socks_skin.mat", false); if (feetmat) { RndMat *legmat = mOutfitDir->Find<RndMat>("legs_socks_swap.mat", false); if (legmat) feetmat->Copy(legmat, kCopyDeep); else { RndMat *skinmat = Find<RndMat>("feet_skin.mat", false); if (skinmat) feetmat->Copy(skinmat, kCopyDeep); } } unk5e0.sort(ByRadius()); // iVar4 = *(int *)(this + 0x5e4); // if ((iVar4 != 0) && (*(int *)(iVar4 + 4) != 0)) { // piVar12 = *(int **)(iVar4 + 8); // for (piVar3 = (int *)piVar12[2]; piVar11 = piVar3, piVar3 != piVar12; piVar3 = // (int *)piVar3[2 ]) // { // for (; piVar11 != piVar12; piVar11 = (int *)piVar11[1]) { // iVar4 = *piVar11; // iVar5 = *(int *)piVar11[1]; // if (*(float *)(iVar5 + 0x178) <= *(float *)(iVar4 + 0x178)) break; // *piVar11 = iVar5; // *(int *)piVar11[1] = iVar4; // } // } // } for (ObjPtrList<CharHair, ObjectDir>::iterator it = unk5f0.begin(); it != unk5f0.end(); ++it) { (*it)->Hookup(unk5e0); } Character::SyncObjects(); for (ObjPtrList<CharBoneOffset, ObjectDir>::iterator it = unk640.begin(); it != unk640.end(); ++it) { (*it)->ApplyToLocal(); mOutfitDir->RemoveFromPoll(*it); } RemoveDrawAndPoll(mOutfitDir); RemoveDrawAndPoll(mInstDir); if (!mInCloset) { for (ObjPtrList<OutfitConfig, ObjectDir>::iterator it = unk620.begin(); it != unk620.end(); ++it) { (*it)->CompressTextures(); } while (!unk610.empty()) { RndMeshDeform *df = unk610.front(); if (!df->Mesh()) MILO_FAIL("BandCharacter::SyncObjects() - character missing mesh data."); df->Mesh()->SetKeepMeshData(false); delete df; } while (!unk600.empty()) { delete unk600.front(); } for (ObjPtrList<CharCollide, ObjectDir>::iterator it = unk5e0.begin(); it != unk5e0.end(); ++it) { (*it)->ClearMesh(); } } CharMeshHide::HideAll(unk5b0, -(mDriver->ClipType() == "vignette") & 0x2000); if (InVignetteOrCloset()) { CharClipDriver *first = mDriver->FirstPlaying(); if (first && mGroupName[0] != 0) { int mask = mGender == "male" ? 0x20 : 0x40; } } const char *eyedfname = mGender == "male" ? "eyesdeform_male.anim" : "eyesdeform_female.anim"; RndPropAnim *panim = Find<RndPropAnim>(eyedfname, false); if (panim) { int numeyeshapes = BandHeadShaper::sEyeNum; if ((int)panim->EndFrame() != numeyeshapes) MILO_NOTIFY_ONCE( "%s must have a frame for each eye shape. It currently has %d frames, but there are %d eye shapes", eyedfname, (int)panim->EndFrame(), BandHeadShaper::sEyeNum ); if (!DataVariable("eyetweaker.loadedsettings").Int()) { panim->SetFrame(mHead.mEye, 1.0f); } } else MILO_NOTIFY_ONCE( "Can't find eye settings prop anim %s. This is required to set range of motion and lid tracking for each eye shape.", eyedfname ); } #pragma pop float sDrawOrder = -1.0f; void BandCharacter::SetClipTypes(Symbol s1, Symbol s2) { if (mDriver) { mDriver->SetClipType(s2); if (BoneServo()) { BoneServo()->SetClipType(s1); } } } SAVE_OBJ(BandCharacter, 0x3EB) BEGIN_LOADS(BandCharacter) PreLoad(bs); PostLoad(bs); END_LOADS void BandCharacter::PreLoad(BinStream &bs) { LOAD_REVS(bs); ASSERT_REVS(8, 0); Character::PreLoad(bs); int hashsize = (mHashTable.mNumEntries + 20) * 2; int strsize = mStringTable.UsedSize(); Reserve(hashsize, strsize + 440); } void BandCharacter::PostLoad(BinStream &bs) { Character::PostLoad(bs); if (gLoadingProxyFromDisk) { BandCharDescTest test; test.Load(bs); } else BandCharDesc::Load(bs); bs >> mPlayFlags; bs >> mTempo; if (gRev < 6) { if (gRev < 4) { int i; bs >> i; if (gRev < 3) { Symbol s; bs >> s; } } Symbol s; bs >> s; } if (gRev > 6) bs >> mDrumVenue; if (gRev != 0) mTestPrefab.Load(bs, true, BandCharDesc::GetPrefabs()); if (gRev == 2 || gRev == 3 || gRev == 4) { bool b; bs >> b; } if (gRev > 7) { if (gLoadingProxyFromDisk) { Symbol s; bs >> s; } else bs >> mInstrumentType; } } BEGIN_COPYS(BandCharacter) COPY_SUPERCLASS(Character) COPY_SUPERCLASS(BandCharDesc) CREATE_COPY(BandCharacter) BEGIN_COPYING_MEMBERS COPY_MEMBER(mPlayFlags) COPY_MEMBER(mTempo) COPY_MEMBER(mDrumVenue) COPY_MEMBER(mTestPrefab) COPY_MEMBER(mInstrumentType) END_COPYING_MEMBERS END_COPYS void BandCharacter::CollideList(const Segment &seg, std::list<Collision> &colls) { if (CollideSphere(seg)) { if (IsProxy()) RndDrawable::CollideList(seg, colls); else { if (mOutfitDir) mOutfitDir->CollideListSubParts(seg, colls); if (mInstDir) mInstDir->CollideListSubParts(seg, colls); RndDir::CollideList(seg, colls); } } } RndDrawable *BandCharacter::CollideShowing(const Segment &s, float &f, Plane &pl) { if (mOutfitDir->CollideShowing(s, f, pl)) return this; else return RndDir::CollideShowing(s, f, pl); } void BandCharacter::DrawShowing() { if (!unk6bd || !IsLoading()) { if (DataVariable("bandcharacter.show_spheres").Int()) { } Character::DrawShowing(); static DataNode &n = DataVariable("bandcharacter.show_slot"); if (n.Int()) { Transform &headxfm = CharUtlFindBoneTrans("bone_head", this)->WorldXfm(); MakeString("slot%d pos%d"); } } } void BandCharacter::Teleport(Waypoint *way) { Character::Teleport(way); unk594 = way; if (mOutfitDir) mOutfitDir->mTeleported = true; } void BandCharacter::SetTempoGenreVenue(Symbol s1, Symbol s2, const char *cc) { mTempo = s1; mGenre = s2; mDrumVenue = NameToDrumVenue(cc); if (strstr(cc, "big_club")) mTestTourEndingVenue = "big_club"; else if (strstr(cc, "arena")) mTestTourEndingVenue = "arena"; else if (strstr(cc, "festival")) mTestTourEndingVenue = "festival"; } void BandCharacter::DrawLodOrShadowMode(int i, DrawMode mode) { Character::DrawLodOrShadow(i, mode); if (mode == kCharDrawTranslucent) { mOutfitDir->DrawLodOrShadow(i, mode); if (!unk574) mInstDir->DrawLodOrShadow(i, mode); } else { if (!unk574) mInstDir->DrawLodOrShadow(i, mode); mOutfitDir->DrawLodOrShadow(i, mode); } } void BandCharacter::DrawLodOrShadow(int i, Character::DrawMode mode) { RndEnvironTracker tracker(mEnv, &WorldXfm().v); mInstDir->SetEnv(nullptr); mOutfitDir->SetEnv(nullptr); if (mode & 5) { DrawLodOrShadowMode(i, (DrawMode)(mode & 0xfffffffd)); } if (mode & 2) { DrawLodOrShadowMode(i, (DrawMode)2); } } float BandCharacter::ComputeScreenSize(RndCam *cam) { if (mOutfitDir) return mOutfitDir->ComputeScreenSize(cam); else return 0; } void BandCharacter::StartLoad(bool b1, bool b2, bool b3) { bool b4 = false; if (!mInCloset) { if (b2 || (unk224 & 7)) b4 = true; } bool bvar1 = mInCloset; unk5a1 = b4; mInCloset = b2; if (bvar1 && !b2) b3 = true; if (!IsLoading() || !unk6bd || b3) { b4 = false; if (unk5a1 || b3) b4 = true; unk6bd = b4; } if (!mFileMerger->StartLoad(b1) && (mInCloset || (bvar1 && !mInCloset))) { mFileMerger->Select("blank", FilePath(""), true); mFileMerger->StartLoad(b1); } } #pragma push #pragma pool_data off #pragma dont_inline on void BandCharacter::AddObject(Hmx::Object *o) { static Symbol ikScale("CharIKScale"); static Symbol ikHand("CharIKHand"); static Symbol collide("CharCollide"); static Symbol charCuff("CharCuff"); static Symbol charHair("CharHair"); static Symbol meshDeform("MeshDeform"); static Symbol charBoneOffset("CharBoneOffset"); static Symbol outfitConfig("OutfitConfig"); static Symbol charMeshHide("CharMeshHide"); static Symbol ikMidi("CharIKMidi"); static Symbol cdMidi("CharDriverMidi"); static Symbol khMidi("CharKeyHandMidi"); Symbol name = o->ClassName(); if (name == ikScale) unk5c0.push_back(dynamic_cast<CharIKScale *>(o)); else if (name == ikHand) unk5d0.push_back(dynamic_cast<CharIKHand *>(o)); else if (name == collide) unk5e0.push_back(dynamic_cast<CharCollide *>(o)); else if (name == charHair) { CharHair *h = dynamic_cast<CharHair *>(o); h->SetManagedHookup(true); unk5f0.push_back(h); } else if (name == charCuff) unk600.push_back(dynamic_cast<CharCuff *>(o)); else if (name == meshDeform) { RndMeshDeform *md = dynamic_cast<RndMeshDeform *>(o); if (!md->Mesh()) MILO_FAIL("RndMeshDeform(%s) has no deform mesh.", md->Name()); unk610.push_back(md); } else if (name == outfitConfig) { OutfitConfig *cfg = dynamic_cast<OutfitConfig *>(o); unk738 |= cfg->OverlayFlags(); unk620.push_back(cfg); } else if (name == charBoneOffset) unk640.push_back(dynamic_cast<CharBoneOffset *>(o)); else if (name == charMeshHide) unk5b0.push_back(dynamic_cast<CharMeshHide *>(o)); else if (name == ikMidi) unk650.push_back(dynamic_cast<CharIKMidi *>(o)); else if (name == cdMidi) unk660.push_back(dynamic_cast<CharDriverMidi *>(o)); else if (name == khMidi) unk670.push_back(dynamic_cast<CharKeyHandMidi *>(o)); } #pragma pop void BandCharacter::AddOverlays(BandPatchMesh &mesh) { for (ObjPtrList<OutfitConfig, ObjectDir>::iterator it = unk620.begin(); it != unk620.end(); ++it) { for (ObjVector<OutfitConfig::Overlay>::iterator oit = (*it)->mOverlays.begin(); oit != (*it)->mOverlays.end(); ++oit) { if ((*oit).mCategory & mesh.mCategory) { mesh.ConstructQuad((*oit).mTexture); } } } } void BandCharacter::DeformHead(SyncMeshCB *cb) { if (mOutfitDir) { RndMesh *mesh = mOutfitDir->Find<RndMesh>("head.mesh", false); if (mesh) { BandHeadShaper shaper; if (!shaper.Start(this, mGender, mesh, cb, false)) return; else mHead.SetShape(shaper); } } } void BandCharacter::SyncOutfitConfig(OutfitConfig *cfg) { char buf[256]; strcpy(buf, cfg->Name()); char *dot = strchr(buf, '.'); MILO_ASSERT(dot, 0x5EA); int colors[7]; *dot = 0; Symbol sym(buf); if (sym == eyes) { colors[3] = 0; colors[4] = 0; colors[5] = 0; colors[3] = mHead.mEyeColor; cfg->SetColors(&colors[3]); } else if (sym == skin || sym == heads) { colors[0] = 0; colors[1] = 0; colors[2] = 0; colors[0] = mSkinColor; cfg->SetColors(colors); } else { BandCharDesc::OutfitPiece *piece = mOutfit.GetPiece(sym); if (piece) cfg->SetColors(piece->mColors); else { BandCharDesc::OutfitPiece *instpiece = mInstruments.GetPiece(sym); if (instpiece) cfg->SetColors(instpiece->mColors); else cfg->Recompose(); } } if (sym == skin) { OutfitConfig::SetSkinTextures(this, mOutfitDir, this); if (unk738) { cfg->RecomposePatches(unk738); unk738 = 0; } } } void BandCharacter::SetDeformation() { CharClip *clip = BandCharDesc::GetDeformClip(mGender); if (clip) { CharBonesMeshes meshes; meshes.SetName("tmp_bones", this); clip->StuffBones(meshes); clip->ScaleDown(meshes, 0); clip->ScaleAdd(meshes, 1, 0, 0); meshes.PoseMeshes(); if (LOADMGR_EDITMODE && BoneServo()) { BoneServo()->AcquirePose(); } for (ObjPtrList<CharIKScale, ObjectDir>::iterator it = unk5c0.begin(); it != unk5c0.end(); ++it) { (*it)->CaptureBefore(); } CharMeshCacheMgr *mgr = new CharMeshCacheMgr(); mgr->Disable(!mInCloset); for (ObjPtrList<RndMesh, ObjectDir>::iterator it = unk73c.begin(); it != unk73c.end(); ++it) { mgr->SyncMesh(*it, 0xBF); } DeformHead(mgr); for (ObjPtrList<CharCuff, ObjectDir>::iterator it = unk600.begin(); it != unk600.end(); ++it) { (*it)->Deform(mgr, mFileMerger); } unk73c.clear(); mgr->StuffMeshes(unk73c); clip->ScaleDown(meshes, 0); float weights[18]; ComputeDeformWeights(weights); for (int i = 0; i < 18; i++) { clip->ScaleAdd(meshes, weights[i], i, 0); } meshes.PoseMeshes(); for (ObjPtrList<RndMeshDeform, ObjectDir>::iterator it = unk610.begin(); it != unk610.end(); ++it) { (*it)->Reskin(mgr, (unk224 >> 1) & 1); } for (ObjPtrList<CharCollide, ObjectDir>::iterator it = unk5e0.begin(); it != unk5e0.end(); ++it) { CharCollide *col = *it; RndMesh *colmesh = col->mMesh; if (colmesh && mgr->HasMesh(colmesh)) { col->Deform(); } } for (ObjPtrList<CharIKScale, ObjectDir>::iterator it = unk5c0.begin(); it != unk5c0.end(); ++it) { (*it)->CaptureAfter(); } for (ObjPtrList<CharIKHand, ObjectDir>::iterator it = unk5d0.begin(); it != unk5d0.end(); ++it) { (*it)->MeasureLengths(); } for (ObjPtrList<OutfitConfig, ObjectDir>::iterator it = unk620.begin(); it != unk620.end(); ++it) { SyncOutfitConfig(*it); (*it)->ApplyAO(mgr); } delete mgr; unk224 &= 0xfffffffd; // i think this might be a bitfield } } void BandCharacter::PlayGroup( const char *cc, bool b, int i, float f, TaskUnits u, Symbol s ) { if (mOverrideGroup[0] != 0 && AllowOverride(cc)) { cc = mOverrideGroup; f = 0; } if (*cc) { bool b528 = mForceNextGroup; bool b3 = false; unk5a3 = false; mForceNextGroup = false; if ((b | b528) || f != 0) { b3 = true; } CharClipDriver *driver = SetState(cc, mPlayFlags, i, b3, true); if (driver) { mFrozen = false; driver->SetBeatOffset(f, u, s); } if (BoneServo()->mRegulate && !mTeleported) { Teleport(BoneServo()->mRegulate); } } } CharLipSyncDriver *BandCharacter::GetLipSyncDriver() { return Find<CharLipSyncDriver>("song.lipdrv", false); } DECOMP_FORCEACTIVE( BandCharacter, "BandCharacter::SetFaceOverrideClip couldn't find clip named %s for %s\n", "BandCharacter::SetFaceOverrideClip couldnt find lip sync driver for %s\n", "!mFileMerger->IsLoading()", "head" ) void BandCharacter::SetHeadLookatWeight(float f) { if (mHeadLookAt) { mHeadLookAt->SetWeight(f); if (mNeckLookAt) mNeckLookAt->SetWeight(f * 0.5f); } } bool BandCharacter::SetPrefab(BandCharDesc *desc) { mTestPrefab = desc; if (mTestPrefab) CopyCharDesc(mTestPrefab); return unk224; } void BandCharacter::ClearDircuts() { mDircuts.clear(); } bool BandCharacter::AddDircut(Symbol s1, Symbol s2, int i) { Symbol animinst = BandCharDesc::GetAnimInstrument(mInstrumentType); FilePath fp; bool ismale = mGender != "female"; int mask = 0x8000; if (!ismale) mask = 0x4000; if (i & mask) { fp.Set( FileRoot(), MakeString("char/main/anim/%s/dircut/%s/%s_%s.milo", animinst, mGender, s1, s2) ); } else { fp.Set( FileRoot(), MakeString("char/main/anim/%s/dircut/%s/%s.milo", animinst, mGender, s1) ); } return AddDircut(fp); } bool BandCharacter::AddDircut(const FilePath &f) { MILO_ASSERT(!f.empty(), 0x794); // more } void BandCharacter::SetDircuts() { int maxNum = mFileMerger->FindMergerIndex("directed_cut_0", true); MILO_ASSERT(maxNum < 32, 0x7AE); } int BandCharacter::GetShotFlags(Symbol s) { BandCharDesc::CharInstrumentType ty = BandCharDesc::GetInstrumentFromSym(mInstrumentType); if (ty >= BandCharDesc::kNumInstruments) return 0; else { DataArray *arr = BandWardrobe::GetGroupArray(ty); for (int i = 0; i < arr->Size(); i++) { if (arr->Array(i)->Sym(0) == s) { return arr->Array(i)->Int(1); } } } return 0; } void BandCharacter::SetContext(Symbol s) { CharWeightable *w = Find<CharWeightable>("venue.weight", false); if (w) w->SetWeight(s == "venue"); CharWeightable *cw = Find<CharWeightable>("closet.weight", false); if (cw) cw->SetWeight(s == "closet"); mOverrideGroup[0] = 0; int hideallint = 0; if (s == "vignette") { SetClipTypes(s, s); hideallint = 0x2000; mDriver->SetBlendWidth(1.0f); } else if (s == "closet") { SetClipTypes("shell", "shell"); mDriver->SetBlendWidth(2.0f); } else if (s == "venue") { ObjectDir *clipsdir = Find<ObjectDir>("body_clips", true); mDriver->SetClips(clipsdir); mDriver->SetBlendWidth(1.0f); switch (BandCharDesc::GetInstrumentFromSym(mInstrumentType)) { case kGuitar: case kBass: SetClipTypes("guitar_all", "guitar_body"); break; case kDrum: SetClipTypes("drum_all", "drum_body"); break; case kMic: SetClipTypes("mic_body", "mic_body"); break; case kKeyboard: SetClipTypes("keyboard_all", "keyboard_body"); break; default: break; } HandleType(on_set_instrument_clip_types_msg); } else { MILO_WARN("%s illegal context %s", PathName(this), s); } CharMeshHide::HideAll(unk5b0, hideallint); } void ReplaceSubdir(ObjectDir *d1, ObjectDir *d2) { for (int i = 0; i < d1->mSubDirs.size(); i++) { ObjDirPtr<ObjectDir> dPtr(d1->mSubDirs[i].Ptr()); d1->RemoveSubDir(dPtr); } ObjDirPtr<ObjectDir> dPtr(d2); d1->AppendSubDir(dPtr); } void BandCharacter::SetVisemes() { ObjectDir *visemedir = Find<ObjectDir>("visemes", false); if (visemedir) { ObjectDir *viseme = BandHeadShaper::GetViseme(mGender, false); if (viseme) ReplaceSubdir(visemedir, viseme); CharLipSyncDriver *lsdriver = Find<CharLipSyncDriver>("song.lipdrv", false); if (lsdriver) lsdriver->SetClips(visemedir); CharFaceServo *servo = Find<CharFaceServo>("face.faceservo", false); if (servo) servo->SetClips(visemedir); } ObjectDir *vignettedir = Find<ObjectDir>("vignette_visemes", false); if (vignettedir) { ObjectDir *viseme = BandHeadShaper::GetViseme(mGender, true); if (viseme) ReplaceSubdir(vignettedir, viseme); CharLipSyncDriver *lsdriver = Find<CharLipSyncDriver>("vignette.lipdrv", false); if (lsdriver) lsdriver->SetClips(vignettedir); } } void BandCharacter::SetGroupName(const char *name) { strcpy(mGroupName, name); } OutfitConfig *BandCharacter::GetOutfitConfig(const char *cc) { ObjectDir *pObjectDir; if (strcmp(cc, "guitar.cfg") == 0 || strcmp(cc, "bass.cfg") == 0 || strcmp(cc, "drum.cfg") == 0 || strcmp(cc, "mic.cfg") == 0 || strcmp(cc, "keyboard.cfg") == 0) { pObjectDir = mInstDir; } else pObjectDir = mOutfitDir; MILO_ASSERT(pObjectDir, 0x8AD); return pObjectDir->Find<OutfitConfig>(cc, false); } RndTex *BandCharacter::GetPatchTex(Patch &patch) { static Message get_patch_tex("get_patch_tex", DataNode(0), DataNode(0)); get_patch_tex[0] = DataNode(patch.mTexture); get_patch_tex[1] = DataNode(patch.mMeshName); const DataNode &handled = HandleType(get_patch_tex); if (handled.Type() == kDataUnhandled || !handled.Obj<RndTex>()) { if (!mPrefab.Null()) { return Find<RndTex>(MakeString("prefab_art%02d.tex", patch.mTexture), false); } else if (LOADMGR_EDITMODE) return Find<RndTex>("patchtest.tex", false); else return 0; } return handled.Obj<RndTex>(); } RndMesh *BandCharacter::GetPatchMesh(Patch &patch) { ObjectDir *dir = this; if (patch.mCategory & 0x2E00) { dir = mInstDir; } return dir->Find<RndMesh>(patch.mMeshName.c_str(), false); } RndTex *BandCharacter::GetBandLogo() { if (LOADMGR_EDITMODE) { return TheRnd->GetNullTexture(); } else { RndTex *ret; DataNode handled = HandleType(get_band_logo_msg); if (handled.Type() == kDataObject) { ret = handled.Obj<RndTex>(); } else ret = 0; return ret; } } void BandCharacter::Compress(RndTex *tex, bool b) { tex->Compress(b); } void BandCharacter::TextureCompressed(int i) { std::list<int>::iterator it; for (it = mCompressedTextureIDs.begin(); it != mCompressedTextureIDs.end() && *it != i; ++it) ; if (it == mCompressedTextureIDs.end()) MILO_WARN("%s Could not find compress texture id %d\n", PathName(this), i); else mCompressedTextureIDs.erase(it); } void BandCharacter::RecomposePatches(BandCharDesc *desc, int i) { CopyCharDesc(desc); if (!mInCloset) { unk224 |= 1; StartLoad(true, mInCloset, true); } else { for (ObjPtrList<OutfitConfig, ObjectDir>::iterator it = unk620.begin(); it != unk620.end(); ++it) { (*it)->RecomposePatches(i); } } } void BandCharacter::SetInstrumentType(Symbol s) { if (s != mInstrumentType) { mInstrumentType = s; SetChanged(8); } } void BandCharacter::ClearGroup() { SetState("", mPlayFlags, 1, false, false); mGroupName[0] = 0; if (mDriver) mDriver->Clear(); if (mAddDriver) mAddDriver->Clear(); } void BandCharacter::MiloReload() { StartLoad(false, mInCloset, false); } void BandCharacter::SetLipSync(CharLipSync *sync) { CharLipSyncDriver *driver = Find<CharLipSyncDriver>("song.lipdrv", false); if (driver) { driver->mSongOwner = 0; driver->SetLipSync(sync); } } void BandCharacter::SetSongOwner(CharLipSyncDriver *driver) { CharLipSyncDriver *drvr = Find<CharLipSyncDriver>("song.lipdrv", false); if (drvr) { drvr->mSongOwner = driver; drvr->SetLipSync(Find<CharLipSync>("blinktrack.lipsync", false)); drvr->mSongOffset = RandomFloat(0, 1000.0f); } } void BandCharacter::SetSingalong(float f) { if (mSingalongWeight) mSingalongWeight->SetWeight(f); } #pragma push #pragma dont_inline on BEGIN_HANDLERS(BandCharacter) HANDLE_EXPR(get_play_flags, mPlayFlags) HANDLE(play_group, OnPlayGroup) HANDLE(group_override, OnGroupOverride) HANDLE(change_face_group, OnChangeFaceGroup) HANDLE_ACTION(clear_group, ClearGroup()) HANDLE(set_play, OnSetPlay) HANDLE_ACTION( start_load, StartLoad(_msg->Int(2), _msg->Size() > 3 ? _msg->Int(3) : mInCloset, false) ) HANDLE_EXPR(is_loading, IsLoading()) HANDLE_EXPR(flag_string, FlagString(_msg->Int(2))) HANDLE(cam_teleport, OnCamTeleport) HANDLE(closet_teleport, OnClosetTeleport) HANDLE(install_filter, OnInstallFilter) HANDLE(pre_clear, OnPreClear) HANDLE(copy_prefab, OnCopyPrefab) HANDLE(save_prefab, OnSavePrefab) HANDLE(set_file_merger, OnSetFileMerger) HANDLE_EXPR(list_dircuts, OnListDircuts()) HANDLE(load_dircut, OnLoadDircut) HANDLE_ACTION(set_context, SetContext(_msg->Sym(2))) HANDLE_ACTION(save_from_closet, SavePrefabFromCloset()) HANDLE_ACTION(set_singalong, SetSingalong(_msg->Float(2))) HANDLE(on_post_merge, OnPostMerge) HANDLE(hide_categories, OnHideCategories) HANDLE(restore_categories, OnRestoreCategories) HANDLE_ACTION(game_over, GameOver()) #ifdef MILO_DEBUG HANDLE(toggle_interests_overlay, OnToggleInterestDebugOverlay) #endif HANDLE(list_drum_venues, OnListDrumVenues) HANDLE(portrait_begin, OnPortraitBegin) HANDLE(portrait_end, OnPortraitEnd) HANDLE_SUPERCLASS(BandCharDesc) HANDLE_SUPERCLASS(Character) HANDLE_CHECK(0x9A6) END_HANDLERS #pragma pop void BandCharacter::GameOver() { for (ObjPtrList<CharIKMidi, ObjectDir>::iterator it = unk650.begin(); it != unk650.end(); ++it) { CharIKMidi *cur = *it; cur->Handle(Message("game_over"), true); } for (ObjPtrList<CharDriverMidi, ObjectDir>::iterator it = unk660.begin(); it != unk660.end(); ++it) { CharDriverMidi *cur = *it; cur->Handle(Message("game_over"), true); } for (ObjPtrList<CharKeyHandMidi, ObjectDir>::iterator it = unk670.begin(); it != unk670.end(); ++it) { CharKeyHandMidi *cur = *it; cur->Handle(Message("game_over"), true); } } DataNode BandCharacter::OnListDircuts() { int mask = 0x3E00; if (mGender == "female") { if (mGenre == "banger") mask |= 0x4; else if (mGenre == "dramatic") mask |= 0x2; else if (mGenre == "rocker") mask |= 0x1; else if (mGenre == "spazz") mask |= 8; } else { if (mGenre == "banger") mask |= 0x40; else if (mGenre == "dramatic") mask |= 0x20; else if (mGenre == "rocker") mask |= 0x10; else if (mGenre == "spazz") mask |= 0x80; } return ListAnimGroups(mask); } DataNode BandCharacter::OnLoadDircut(DataArray *da) { Symbol sym = da->Sym(2); if (sym == "") { return DataNode(0); } else { ClearDircuts(); return DataNode(AddDircut(sym, mGenre, GetShotFlags(sym))); } } DataNode BandCharacter::OnPlayGroup(DataArray *da) { bool b6 = false; if (da->Size() > 3) b6 = da->Int(3); bool b1 = false; if (da->Size() > 4) b1 = da->Int(4); float f7 = 0; int i5 = 0; Symbol s; if (da->Size() > 5) { f7 = da->Float(5); i5 = da->Int(6); s = da->Sym(7); } int i3 = 2; if (b1) i3 = 1; PlayGroup(da->Str(2), b6, i3, f7, (TaskUnits)i5, s); return DataNode(0); } DataNode BandCharacter::OnGroupOverride(DataArray *da) { strcpy(mOverrideGroup, da->Str(2)); mForceNextGroup = true; return DataNode(0); } DataNode BandCharacter::OnSetPlay(DataArray *da) { SetState(mGroupName, mPlayFlags & 0xFFF80FFF | da->Int(2), 3, false, false); return DataNode(0); } DataNode BandCharacter::OnClosetTeleport(DataArray *da) { unk734->DirtyLocalXfm() = LocalXfm(); Teleport(unk734); unk5a2 = false; return DataNode(0); } DataNode BandCharacter::OnCamTeleport(DataArray *da) { if (da->Int(2)) { Teleport(unk594); } else { Waypoint *w = unk594; Teleport(0); unk594 = w; unk5a2 = false; } return DataNode(0); } DataNode BandCharacter::OnChangeFaceGroup(DataArray *da) { if (!mFaceDriver || !mFaceDriver->ClipDir()) return DataNode(0); else if (strcmp(mFaceGroupName, da->Str(2)) != 0) { strcpy(mFaceGroupName, da->Str(2)); PlayFaceClip(); } return DataNode(0); } void ReplaceRefs(Hmx::Object *, Hmx::Object *mine) { MILO_ASSERT(mine, 0xA72); } MergeFilter::Action BandCharacter::FilterSubdir(ObjectDir *o1, ObjectDir *) { return DefaultSubdirAction(o1, mFileMerger->mSubdirs); } DataNode BandCharacter::OnInstallFilter(DataArray *da) { sBoneMergeDir = 0; sOutfitDir = da->Obj<ObjectDir>(2); sToDir = da->Obj<ObjectDir>(3); sInstrumentDir = da->Obj<ObjectDir>(4); const char *bodyparts[] = { "hair", "glasses", "facehair", "earrings", "piercings", "eyebrows", "wrist", "torso", "head", "legs", "feet", "rings", "hands" }; return DataNode(0); } DataNode BandCharacter::OnPreClear(DataArray *da) { Symbol sym = da->Sym(2); FileMerger *fm = da->Obj<FileMerger>(3); static Symbol ocn("OutfitConfig"); return DataNode(0); } void BandCharacter::SavePrefabFromCloset() { MILO_ASSERT(0, 0xB95); } DataNode BandCharacter::OnSavePrefab(DataArray *da) { if (mTestPrefab) mTestPrefab->CopyCharDesc(this); return DataNode(0); } DataNode BandCharacter::OnCopyPrefab(DataArray *da) { if (mTestPrefab) CopyCharDesc(mTestPrefab); return DataNode(0); } // just here temporarily until we match the corresponding funcs these strings belong to DECOMP_FORCEACTIVE( BandCharacter, "Mesh", "%s is being merged into", "mine->Dir() == this", "bone_", "exo_", "world.wind", "instruments can only have one subdir, which is the resource or colorpalettes.milo", "bone_pelvis.mesh", "outfits can only have one subdir, which is the resource" ) DataNode BandCharacter::OnSetFileMerger(DataArray *da) { FilePathTracker tracker(FileRoot()); SetVisemes(); unk224 &= 0xfffffff2; if (!mFileMerger) return DataNode(0); FilePath fp70; if (!mPrefab.Null()) fp70.SetRoot(MakeString("char/main/prefab/%s.milo", mPrefab)); mFileMerger->Select("prefab", fp70, unk5a1); const char *bodyparts[14] = { "head", "eyebrows", "torso", "legs", "hands", "wrist", "rings", "feet", "hair", "facehair", "earrings", "glasses", "piercings", 0 }; for (int i = 0; bodyparts[i] != 0; i++) { FilePath fp7c; MakeOutfitPath(bodyparts[i], fp7c); mFileMerger->Select(bodyparts[i], fp7c, unk5a1); } for (int i = 0; i < 5; i++) { mFileMerger->Select(BandCharDesc::GetInstrumentSym(i), FilePath(0), false); } FilePath fp88(""); FilePath fp94(""); FilePath fpa0(""); FilePath fpac(""); FilePath fpb8(""); FilePath fpc4(""); FilePath fpd0(""); FilePath fpdc(""); FilePath fpe8(""); FilePath fpf4(""); mPlayFlags &= 0xffcfffff; Symbol animinst = BandCharDesc::GetAnimInstrument(mInstrumentType); BandCharDesc::CharInstrumentType ty = BandCharDesc::GetInstrumentFromSym(mInstrumentType); if (ty == BandCharDesc::kGuitar) mPlayFlags |= 0x100000; else if (ty == BandCharDesc::kBass) mPlayFlags |= 0x200000; if (ty != BandCharDesc::kNumInstruments) { if (!mGenre.Null() && !mTempo.Null()) { if (ty == BandCharacter::kMic) { mUseMicStandClips = mGenre != "banger"; } fp94.SetRoot(MakeString( "char/main/anim/%s/body/%s/realtime_%s.milo", animinst, mGender, mGenre )); fpa0.SetRoot(MakeString( "char/main/anim/%s/body/%s/%s_%s.milo", animinst, mGender, mTempo, mGenre )); if (ty == BandCharDesc::kDrum) { fpac.SetRoot(MakeString( "char/main/anim/%s/body_add/%s/%s_%s.milo", animinst, mGender, mTempo, mGenre )); fpb8.SetRoot(MakeString( "char/main/anim/%s/body_add/%s/body_add_base.milo", animinst, mGender )); } } switch (ty) { case BandCharDesc::kGuitar: case BandCharDesc::kBass: fp88.SetRoot("char/main/rigging/guitar_rh.milo"); if (mGender == "female") fpf4.SetRoot("char/main/anim/rigging/guitar/fret_left_female.milo"); else fpf4.SetRoot("char/main/anim/rigging/guitar/fret_left.milo"); break; case BandCharDesc::kDrum: fp88.SetRoot("char/main/rigging/drum.milo"); fpc4.SetRoot( MakeString("char/main/anim/rigging/drum/stick_left_%s.milo", mGender) ); fpd0.SetRoot( MakeString("char/main/anim/rigging/drum/stick_right_%s.milo", mGender) ); if (mGender == "female") { fpdc.SetRoot("char/main/anim/rigging/drum/pedal_right_female.milo"); fpe8.SetRoot("char/main/anim/rigging/drum/pedal_left_female.milo"); } else { fpdc.SetRoot("char/main/anim/rigging/drum/pedal_right.milo"); fpe8.SetRoot("char/main/anim/rigging/drum/pedal_left.milo"); } break; case BandCharDesc::kMic: fp88.SetRoot("char/main/rigging/vocal.milo"); break; case BandCharDesc::kKeyboard: fp88.SetRoot("char/main/rigging/keyboard.milo"); break; default: MILO_FAIL("new instrument type added but not supported"); break; } if (ty != BandCharDesc::kDrum || !mDrumVenue.Null()) { FilePath fp100(""); MakeInstrumentPath(mInstrumentType, mDrumVenue, fp100); mFileMerger->Select(mInstrumentType, fp100, unk5a1); } } if (mInTourEnding && !mTestTourEndingVenue.Null()) { FilePath fp10c(MakeString( "char/main/anim/%s/finale/%s/%s/tour_endings.milo", animinst, mGender, mTestTourEndingVenue )); mFileMerger->Select("tour_ending_clips", fp10c, false); } else { if (LOADMGR_EDITMODE && !mTestTourEndingVenue.Null()) { FilePath fp118(MakeString( "char/main/anim/%s/finale/%s/%s/tour_endings.milo", animinst, mGender, mTestTourEndingVenue )); mFileMerger->Select("tour_ending_clips", fp118, false); } else { mFileMerger->Select("tour_ending_clips", FilePath(""), false); } } mFileMerger->Select("rigging", fp88, false); mFileMerger->Select("body_realtime_clips", fp94, false); mFileMerger->Select("body_tempo_clips", fpa0, false); mFileMerger->Select("body_add_clips", fpac, false); mFileMerger->Select("body_add_base", fpb8, false); mFileMerger->Select("stick_left", fpc4, false); mFileMerger->Select("stick_right", fpd0, false); mFileMerger->Select("drum_pedal_right", fpdc, false); mFileMerger->Select("drum_pedal_left", fpe8, false); mFileMerger->Select("guitar_fret", fpf4, false); SetDircuts(); unk5a1 = false; return DataNode(0); } BEGIN_PROPSYNCS(BandCharacter) SYNC_PROP(tempo, mTempo) SYNC_PROP(genre, mGenre) SYNC_PROP(drum_venue, mDrumVenue) SYNC_PROP(force_vertical, mForceVertical) SYNC_PROP_SET(instrument_type, mInstrumentType, SetInstrumentType(_val.Sym())) SYNC_PROP_SET(group_name, mGroupName, SetGroupName(_val.Str())) SYNC_PROP_SET( head_lookat_weight, mHeadLookAt ? mHeadLookAt->Weight() : 0, SetHeadLookatWeight(_val.Float()) ) SYNC_PROP_SET(in_closet, mInCloset, StartLoad(false, _val.Int(), false)) SYNC_PROP(test_prefab, mTestPrefab) SYNC_PROP(use_mic_stand_clips, mUseMicStandClips) SYNC_PROP(in_tour_ending, mInTourEnding) SYNC_PROP(test_tour_ending_venue, mTestTourEndingVenue) SYNC_SUPERCLASS(BandCharDesc) SYNC_SUPERCLASS(Character) END_PROPSYNCS
0
0.971611
1
0.971611
game-dev
MEDIA
0.867113
game-dev
0.991911
1
0.991911
ManaPlus/ManaPlus
1,461
src/resources/db/questdb.h
/* * The ManaPlus Client * Copyright (C) 2013-2019 The ManaPlus Developers * Copyright (C) 2019-2022 Andrei Karas * * This file is part of The ManaPlus Client. * * 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 * 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/>. */ #ifndef RESOURCES_DB_QUESTDB_H #define RESOURCES_DB_QUESTDB_H #include "enums/simpletypes/skiperror.h" #include "utils/vector.h" #include "resources/questvar.h" #include <string> #include "localconsts.h" struct QuestEffect; struct QuestItem; namespace QuestDb { void load(); void loadXmlFile(const std::string &fileName, const SkipError skipError); void unload(); NpcQuestVarMap *getVars(); std::map<int, STD_VECTOR<QuestItem*> > *getQuests(); STD_VECTOR<QuestEffect*> *getAllEffects(); std::string getName(const int id); } // namespace QuestDb #endif // RESOURCES_DB_QUESTDB_H
0
0.928342
1
0.928342
game-dev
MEDIA
0.778018
game-dev
0.551254
1
0.551254
moai/moai-dev
34,797
src/moai-sim/MOAISim.cpp
// Copyright (c) 2010-2017 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moai-sim/MOAIDebugLines.h> #include <moai-sim/MOAIGfxMgr.h> #include <moai-sim/MOAINodeMgr.h> #include <moai-sim/MOAISim.h> #include <moai-sim/MOAITextureBase.h> #include <moai-sim/MOAIRenderMgr.h> #if defined(_WIN32) #include <windows.h> #include <Psapi.h> #elif defined(__APPLE__) //&& defined(TARGET_IPHONE_SIMULATOR) // Not sure if using mach API is disallowed in the app store. :/ #include <mach/mach.h> #include <unistd.h> #elif defined (__QNX__) #include <unistd.h> #elif defined (__EMSCRIPTEN__) #include <unistd.h> #elif defined (ANDROID) #include <unistd.h> #endif #define LUA_GC_FUNC_NAME "collectgarbage" //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @lua clearLoopFlags @text Uses the mask provided to clear the loop flags. @opt number mask Default value is 0xffffffff. @out nil */ int MOAISim::_clearLoopFlags ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mLoopFlags &= ~state.GetValue < u32 >( 1, 0xffffffff ); return 0; } //----------------------------------------------------------------// /** @lua crash @text Crashes Moai with a null pointer dereference. @out nil */ int MOAISim::_crash ( lua_State* L ) { UNUSED(L); int *p = NULL; (*p) = 0; return 0; } //----------------------------------------------------------------// int MOAISim::_collectgarbage ( lua_State* L ) { UNUSED ( L ); printf ( "WARNING: 'collectgarbage' replaced by MOAISim. Use MOAISim's 'forceGC', 'setGCStep' and 'setGCActive' instead.\n" ); return 0; } //----------------------------------------------------------------// /** @lua enterFullscreenMode @text Enters fullscreen mode on the device if possible. @out nil */ int MOAISim::_enterFullscreenMode ( lua_State* L ) { MOAILuaState state ( L ); EnterFullscreenModeFunc func = MOAISim::Get ().GetEnterFullscreenModeFunc (); if ( func ) { func (); } return 0; } //----------------------------------------------------------------// /** @lua exitFullscreenMode @text Exits fullscreen mode on the device if possible. @out nil */ int MOAISim::_exitFullscreenMode ( lua_State* L ) { MOAILuaState state ( L ); ExitFullscreenModeFunc func = MOAISim::Get ().GetExitFullscreenModeFunc (); if ( func ) { func (); } return 0; } //----------------------------------------------------------------// // TODO: deprecate int MOAISim::_forceGC ( lua_State* L ) { UNUSED ( L ); MOAILuaRuntime::Get ().ForceGarbageCollection (); return 0; } //----------------------------------------------------------------// /** @lua framesToTime @text Converts the number of frames to time passed in seconds. @in number frames The number of frames. @out number time The equivalent number of seconds for the specified number of frames. */ int MOAISim::_framesToTime ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; float frames = state.GetValue < float >( 1, 0.0f ); MOAISim& sim = MOAISim::Get (); lua_pushnumber ( state, frames * sim.mStep ); return 1; } //----------------------------------------------------------------// /** @lua getActionMgr @text Get the sim's action tree. This is the 'global' action tree that all newly started actions are automatically added. @out MOAIActionTree actionMgr */ int MOAISim::_getActionMgr ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().GetActionMgr ().PushLuaUserdata ( state ); return 1; } //----------------------------------------------------------------// /** @lua getDeviceTime @text Gets the raw device clock. This is a replacement for Lua's os.time (). @out number time The device clock time in seconds. */ int MOAISim::_getDeviceTime ( lua_State* L ) { lua_pushnumber ( L, ZLDeviceTime::GetTimeInSeconds ()); return 1; } //----------------------------------------------------------------// /** @lua getElapsedTime @text Gets the number of seconds elapsed since the application was started. @out number time The number of elapsed seconds. */ int MOAISim::_getElapsedTime ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().mSimTime ); return 1; } //----------------------------------------------------------------// /** @lua getLoopFlags @text Returns the current loop flags. @out number mask */ int MOAISim::_getLoopFlags ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().mLoopFlags ); return 1; } //----------------------------------------------------------------// /** @lua getLuaObjectCount @text Gets the total number of objects in memory that inherit MOAILuaObject. Count includes objects that are not bound to the Lua runtime. @out number count */ int MOAISim::_getLuaObjectCount ( lua_State* L ) { lua_pushnumber ( L, ( lua_Number )MOAILuaRuntime::Get ().GetObjectCount ()); return 1; } //----------------------------------------------------------------// /** @lua getMemoryUsage @text Get the current amount of memory used by MOAI and its subsystems. This will attempt to return reasonable estimates where exact values cannot be obtained. Some fields represent informational fields (i.e. are not double counted in the total, but present to assist debugging) and may be only available on certain platforms (e.g. Windows, etc). These fields begin with a '_' character. @out table usage The breakdown of each subsystem's memory usage, in bytes. There is also a "total" field that contains the summed value. */ int MOAISim::_getMemoryUsage ( lua_State* L ) { float divisor = 1.0f; if( lua_type(L, 1) == LUA_TSTRING ) { cc8* str = lua_tostring(L, 1); if( str[0] == 'k' || str[0] == 'K' ) divisor = 1024.0f; else if( str[0] == 'm' || str[0] == 'M' ) divisor = 1024.0f * 1024.0f; else if( str[0] == 'b' || str[0] == 'B' ) divisor = 1.0f; } size_t total = 0; lua_newtable(L); size_t count; count = MOAILuaRuntime::Get().GetMemoryUsage (); lua_pushnumber(L, count / divisor); lua_setfield(L, -2, "lua"); total += count; // This is informational only (i.e. don't double count with the previous field). // see: http://pgl.yoyo.org/luai/i/lua_gc int luabytes = lua_gc ( L, LUA_GCCOUNT, 0 ) * 1024 + lua_gc ( L, LUA_GCCOUNTB, 0 ); lua_pushnumber ( L, luabytes / divisor ); lua_setfield ( L, -2, "_luagc_count" ); count = MOAIGfxMgr::Get ().GetTextureMemoryUsage (); lua_pushnumber ( L, count / divisor ); lua_setfield ( L, -2, "texture" ); total += count; #if defined(_WIN32) PROCESS_MEMORY_COUNTERS pmc; // Print the process identifier. if ( GetProcessMemoryInfo ( GetCurrentProcess (), &pmc, sizeof ( pmc ))) { lua_pushnumber ( L, pmc.PagefileUsage / divisor ); lua_setfield ( L, -2, "_sys_vs" ); lua_pushnumber ( L, pmc.WorkingSetSize / divisor ); lua_setfield ( L, -2, "_sys_rss" ); } #elif defined(__APPLE__) //&& defined(TARGET_IPHONE_SIMULATOR) // Tricky undocumented mach polling of memory struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; kern_return_t kr = task_info ( mach_task_self (), TASK_BASIC_INFO, reinterpret_cast < task_info_t >( &t_info ), &t_info_count ); // Most likely cause for failure: |task| is a zombie. if( kr == KERN_SUCCESS ) { lua_pushnumber ( L, t_info.virtual_size / divisor ); lua_setfield ( L, -2, "_sys_vs" ); lua_pushnumber ( L, t_info.resident_size / divisor ); lua_setfield ( L, -2, "_sys_rss" ); } #endif lua_pushnumber ( L, total / divisor ); lua_setfield ( L, -2, "total" ); return 1; } //----------------------------------------------------------------// /** @lua getMemoryUsagePlain @text Returns lua and texture memory usage measured by MOAI subsystems. This function tries to avoid allocations to minimize skewing the results. Suitable for realtime memory monitoring. @out number lua memory usage in bytes @out number texture memory usage in bytes */ int MOAISim::_getMemoryUsagePlain ( lua_State *L ) { size_t lua = MOAILuaRuntime::Get().GetMemoryUsage (); size_t tex = MOAIGfxMgr::Get ().GetTextureMemoryUsage (); lua_pushnumber ( L, ( lua_Number )lua ); lua_pushnumber ( L, ( lua_Number )tex ); return 2; } //----------------------------------------------------------------// /** @lua getPerformance @text Returns an estimated frames per second and other performance counters based on measurements taken at every render. @out number fps Estimated frames per second. @out number seconds Last ActionTree update duration @out number seconds Last NodeMgr update duration @out number seconds Last sim duration @out number seconds Last render duration */ int MOAISim::_getPerformance ( lua_State* L ) { MOAISim& device = MOAISim::Get (); MOAIRenderMgr& renderMgr = MOAIRenderMgr::Get (); lua_pushnumber ( L, device.mFrameRate ); lua_pushnumber ( L, device.mLastActionTreeTime ); lua_pushnumber ( L, device.mLastNodeMgrTime ); lua_pushnumber ( L, device.mSimDuration ); lua_pushnumber ( L, renderMgr.GetRenderDuration ()); return 5; } //----------------------------------------------------------------// /** @lua getStep @text Gets the amount of time (in seconds) that it takes for one frame to pass. @out number size The size of the frame; the time it takes for one frame to pass. */ int MOAISim::_getStep ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().GetStep ()); return 1; } //----------------------------------------------------------------// /** @lua getStepCount @text Gets the number of times the sim was stepped since the application was started. @out number steps The number of times the sim was stepped. */ int MOAISim::_getStepCount ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().mStepCount ); return 1; } //----------------------------------------------------------------// /** @lua hideCursor @text Hides system cursor. @out nil */ int MOAISim::_hideCursor ( lua_State* L ) { MOAILuaState state ( L ); HideCursorFunc func = MOAISim::Get ().GetHideCursorFunc (); if ( func ) { func (); } return 0; } //----------------------------------------------------------------// /** @lua openWindow @text Opens a new window for the application to render on. This must be called before any rendering can be done, and it must only be called once. @in string title The title of the window. @in number width The width of the window in pixels. @in number height The height of the window in pixels. @out nil */ int MOAISim::_openWindow ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "SNN" )) return 0; cc8* title = lua_tostring ( state, 1 ); u32 width = state.GetValue < u32 >( 2, 320 ); u32 height = state.GetValue < u32 >( 3, 480 ); OpenWindowFunc openWindow = MOAISim::Get ().GetOpenWindowFunc (); if ( openWindow ) { MOAIGfxMgr::Get ().SetBufferSize ( width, height ); openWindow ( title, width, height ); } return 0; } //----------------------------------------------------------------// /** @lua pauseTimer @text Pauses or unpauses the device timer, preventing any visual updates (rendering) while paused. @in boolean pause Whether the device timer should be paused. @out nil */ int MOAISim::_pauseTimer ( lua_State* L ) { MOAILuaState state ( L ); bool pause = state.GetValue < bool >( 1, true ); if ( pause ) { MOAISim::Get ().Pause (); } else { MOAISim::Get ().Resume (); } return 0; } //----------------------------------------------------------------// /** @lua setBoostThreshold @text Sets the boost threshold, a scalar applied to step. If the gap between simulation time and device time is greater than the step size multiplied by the boost threshold and MOAISim.SIM_LOOP_ALLOW_BOOST is set in the loop flags, then the simulation is updated once with a large, variable step to make up the entire gap. @opt number boostThreshold Default value is DEFAULT_BOOST_THRESHOLD. @out nil */ int MOAISim::_setBoostThreshold ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mBoostThreshold = state.GetValue < double >( 1, DEFAULT_BOOST_THRESHOLD ); return 0; } //----------------------------------------------------------------// /** @lua setCpuBudget @text Sets the amount of time (given in simulation steps) to allow for updating the simulation. @in number budget Default value is DEFAULT_CPU_BUDGET. @out nil */ int MOAISim::_setCpuBudget ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mCpuBudget = state.GetValue < u32 >( 1, DEFAULT_CPU_BUDGET ); return 0; } //----------------------------------------------------------------// /** @lua setGCActive @text Enable incremental garbage collection. @in boolean active Default value is false. @out nil */ int MOAISim::_setGCActive ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mGCActive = state.GetValue < bool >( 1, false ); return 0; } //----------------------------------------------------------------// /** @lua setGCStep @text Sets a step to use when running the incremental gc each frame. @in number step @out nil */ int MOAISim::_setGCStep ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mGCStep = state.GetValue < u32 >( 1, 0 ); return 0; } //----------------------------------------------------------------// /** @lua setLongDelayThreshold @text Sets the long delay threshold. If the simulation step falls behind the given threshold, the deficit will be dropped: the simulation will neither spin nor boost to catch up. @opt number longDelayThreshold Default value is DEFAULT_LONG_DELAY_THRESHOLD. @out nil */ int MOAISim::_setLongDelayThreshold ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mLongDelayThreshold = state.GetValue < double >( 1, DEFAULT_LONG_DELAY_THRESHOLD ); return 0; } //----------------------------------------------------------------// /** @lua setLoopFlags @text Fine tune behavior of the simulation loop. MOAISim.SIM_LOOP_ALLOW_SPIN will allow the simulation step to run multiple times per update to try and catch up with device time, but will abort if processing the simulation exceeds the configured step time. MOAISim.SIM_LOOP_ALLOW_BOOST will permit a *variable* update step if simulation time falls too far behind device time (based on the boost threshold). Be warned: this can wreak havoc with physics and stepwise animation or game AI. Three presets are provided: MOAISim.LOOP_FLAGS_DEFAULT, MOAISim.LOOP_FLAGS_FIXED, and MOAISim.LOOP_FLAGS_MULTISTEP. @opt number flags Mask or a combination of MOAISim.SIM_LOOP_FORCE_STEP, MOAISim.SIM_LOOP_ALLOW_BOOST, MOAISim.SIM_LOOP_ALLOW_SPIN, MOAISim.SIM_LOOP_NO_DEFICIT, MOAISim.SIM_LOOP_NO_SURPLUS, MOAISim.SIM_LOOP_RESET_CLOCK. Default value is 0. @out nil */ int MOAISim::_setLoopFlags ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mLoopFlags |= state.GetValue < u32 >( 1, 0 ); return 0; } //----------------------------------------------------------------// /** @lua setLuaAllocLogEnabled @text Toggles log messages from Lua allocator. @opt boolean enable Default value is 'false.' @out nil */ int MOAISim::_setLuaAllocLogEnabled ( lua_State* L ) { MOAILuaState state ( L ); MOAILuaRuntime::Get ().SetAllocLogEnabled ( state.GetValue < bool >( 1, false )); return 0; } //----------------------------------------------------------------// /** @lua setStep @text Sets the size of each simulation step (in seconds). @in number step The step size. Default value is 1 / DEFAULT_STEPS_PER_SECOND. @out nil */ int MOAISim::_setStep ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().SetStep ( state.GetValue < double >( 1, 1.0 / ( double )DEFAULT_STEPS_PER_SECOND )); return 0; } //----------------------------------------------------------------// /** @lua setStepMultiplier @text Runs the simulation multiple times per step (but with a fixed step size). This is used to speed up the simulation without providing a larger step size (which could destabilize physics simulation). @in number count Default value is DEFAULT_STEP_MULTIPLIER. @out nil */ int MOAISim::_setStepMultiplier ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mStepMultiplier = state.GetValue < u32 >( 1, DEFAULT_STEP_MULTIPLIER ); return 0; } //----------------------------------------------------------------// /** @lua setStepSmoothing @text Average delta time over N last frames. This is useful to filter out momentary single-frame spikes. Can make difference even in fixed step setup (helps to avoids double steps). @in number count Number of frames. Default is 0 (no smoothing). @out nil */ int MOAISim::_setStepSmoothing ( lua_State *L ) { MOAILuaState state ( L ); u32 size = state.GetValue < u32 >( 1, 0 ); MOAISim& device = MOAISim::Get (); device.mSmoothBuffer.Init ( size ); device.mSmoothBuffer.Fill ( device.mStep ); device.mSmoothIdx = 0; return 0; } //----------------------------------------------------------------// /** @lua setTimerError @text Sets the tolerance for timer error. This is a multiplier of step. Timer error tolerance is step * timerError. @in number timerError Default value is 0.0. @out nil */ int MOAISim::_setTimerError ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mTimerError = state.GetValue < double >( 1, 0.0 ); return 0; } //----------------------------------------------------------------// /** @lua setTraceback @text Sets the function to call when a traceback occurs in Lua @in function callback Function to execute when the traceback occurs @out nil */ int MOAISim::_setTraceback ( lua_State* L ) { UNUSED ( L ); MOAILuaRuntime::Get ().GetTracebackRef ().SetRef ( MOAILuaRuntime::Get ().GetMainState(), 1 ); return 0; } //----------------------------------------------------------------// /** @lua setTextInputRect @text Sets text input rect. @out nil */ int MOAISim::_setTextInputRect ( lua_State* L ) { MOAILuaState state ( L ); ZLIntRect rect = state.GetRect< int >( 1 ); rect.Bless(); SetTextInputRectFunc func = MOAISim::Get ().GetSetTextInputRectFunc (); if ( func ) { func ( rect.mXMin, rect.mYMin, rect.mXMax, rect.mYMax ); } return 0; } //----------------------------------------------------------------// /** @lua showCursor @text Shows system cursor. @out nil */ int MOAISim::_showCursor ( lua_State* L ) { MOAILuaState state ( L ); ShowCursorFunc func = MOAISim::Get ().GetShowCursorFunc (); if ( func ) { func (); } return 0; } //----------------------------------------------------------------// /** @lua timeToFrames @text Converts the number of time passed in seconds to frames. @in number time The number of seconds. @out number frames The equivalent number of frames for the specified number of seconds. */ int MOAISim::_timeToFrames ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; float time = state.GetValue < float >( 1, 0.0f ); MOAISim& device = MOAISim::Get (); lua_pushnumber ( state, time / device.mStep ); return 1; } //================================================================// // DOXYGEN //================================================================// #ifdef DOXYGEN //----------------------------------------------------------------// /** @lua clearRenderStack @text Alias for MOAIRenderMgr.clearRenderStack (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE. @out nil */ int MOAISim::_clearRenderStack ( lua_State* L ) { } //----------------------------------------------------------------// /** @lua popRenderPass @text Alias for MOAIRenderMgr.popRenderPass (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE. @out nil */ int MOAISim::_popRenderPass ( lua_State* L ) { } //----------------------------------------------------------------// /** @lua pushRenderPass @text Alias for MOAIRenderMgr.pushRenderPass (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE. @in MOAIDrawable renderable @out nil */ int MOAISim::_pushRenderPass ( lua_State* L ) { } //----------------------------------------------------------------// /** @lua removeRenderPass @text Alias for MOAIRenderMgr.removeRenderPass (). THIS METHOD IS DEPRECATED AND WILL BE REMOVED IN A FUTURE RELEASE. @in MOAIDrawable renderable @out nil */ int MOAISim::_removeRenderPass ( lua_State* L ) { } #endif //================================================================// // MOAISim //================================================================// //----------------------------------------------------------------// MOAISim::MOAISim () : mLoopState ( START ), mStep ( 1.0 / ( double )DEFAULT_STEPS_PER_SECOND ), mSimTime ( 0.0 ), mRealTime ( 0.0 ), mFrameTime ( 0.0 ), mPauseTime ( 0.0 ), mStepCount ( 0 ), mFrameRate ( 0.0f ), mFrameRateIdx ( 0 ), mNodeMgrTime ( 0.0 ), mActionTreeTime ( 0.0 ), mLastNodeMgrTime ( 0.0 ), mLastActionTreeTime ( 0.0 ), mLoopFlags ( LOOP_FLAGS_DEFAULT ), mBoostThreshold ( DEFAULT_BOOST_THRESHOLD ), mLongDelayThreshold ( DEFAULT_LONG_DELAY_THRESHOLD ), mCpuBudget ( DEFAULT_CPU_BUDGET ), mStepMultiplier ( DEFAULT_STEP_MULTIPLIER ), mTimerError ( 0.0 ), mSimDuration ( 1.0 / 60.0 ), mEnterFullscreenModeFunc ( 0 ), mExitFullscreenModeFunc ( 0 ), mOpenWindowFunc ( 0 ), mSetSimStepFunc ( 0 ), mShowCursorFunc ( 0 ), mHideCursorFunc ( 0 ), mGCActive ( true ), mSmoothIdx ( 0 ), mGCStep ( 0 ) { RTTI_SINGLE ( MOAIGlobalEventSource ) for ( u32 i = 0; i < FPS_BUFFER_SIZE; ++i ) { this->mFrameRateBuffer [ i ] = 0.0f; } this->mFrameTime = ZLDeviceTime::GetTimeInSeconds (); this->mActionMgr.Set ( *this, new MOAIActionTree ()); this->mActionTree.Set ( *this, new MOAIActionTree ()); this->mActionMgr->Start ( this->mActionTree->GetDefaultParent (), false ); } //----------------------------------------------------------------// MOAISim::~MOAISim () { this->mActionMgr.Set ( *this, 0 ); this->mActionTree.Set ( *this, 0 ); } //----------------------------------------------------------------// double MOAISim::MeasureFrameRate () { double frameTime = ZLDeviceTime::GetTimeInSeconds (); double delay = frameTime - this->mFrameTime; this->mFrameTime = frameTime; if ( delay > 0.0 ) { float sample = ( float )( 1.0 / delay ); this->mFrameRateBuffer [ this->mFrameRateIdx++ ] = sample; this->mFrameRateIdx %= FPS_BUFFER_SIZE; sample = 0.0f; for ( u32 i = 0; i < FPS_BUFFER_SIZE; ++i ) { sample += this->mFrameRateBuffer [ i ]; } this->mFrameRate = sample / ( float )FPS_BUFFER_SIZE; } return delay; } //----------------------------------------------------------------// void MOAISim::OnGlobalsFinalize () { this->InvokeListener ( EVENT_FINALIZE ); } //----------------------------------------------------------------// void MOAISim::ResetPerformanceTimers () { this->mLastActionTreeTime = this->mActionTreeTime; this->mLastNodeMgrTime = this->mNodeMgrTime; this->mNodeMgrTime = 0.0; this->mActionTreeTime = 0.0; } //----------------------------------------------------------------// void MOAISim::Pause () { if ( this->mLoopState != PAUSED ) { this->InvokeListener ( EVENT_PAUSE ); this->mLoopState = PAUSED; this->mPauseTime = ZLDeviceTime::GetTimeInSeconds (); } } //----------------------------------------------------------------// void MOAISim::RegisterLuaClass ( MOAILuaState& state ) { MOAIGlobalEventSource::RegisterLuaClass ( state ); state.SetField ( -1, "EVENT_FINALIZE", ( u32 )EVENT_FINALIZE ); state.SetField ( -1, "EVENT_PAUSE", ( u32 )EVENT_PAUSE ); state.SetField ( -1, "EVENT_RESUME", ( u32 )EVENT_RESUME ); state.SetField ( -1, "EVENT_STEP", ( u32 )EVENT_STEP ); state.SetField ( -1, "SIM_LOOP_FORCE_STEP", ( u32 )SIM_LOOP_FORCE_STEP ); state.SetField ( -1, "SIM_LOOP_ALLOW_BOOST", ( u32 )SIM_LOOP_ALLOW_BOOST ); state.SetField ( -1, "SIM_LOOP_ALLOW_SPIN", ( u32 )SIM_LOOP_ALLOW_SPIN ); state.SetField ( -1, "SIM_LOOP_NO_DEFICIT", ( u32 )SIM_LOOP_NO_DEFICIT ); state.SetField ( -1, "SIM_LOOP_NO_SURPLUS", ( u32 )SIM_LOOP_NO_SURPLUS ); state.SetField ( -1, "SIM_LOOP_RESET_CLOCK", ( u32 )SIM_LOOP_RESET_CLOCK ); state.SetField ( -1, "SIM_LOOP_ALLOW_SOAK", ( u32 )SIM_LOOP_ALLOW_SOAK ); state.SetField ( -1, "LOOP_FLAGS_DEFAULT", ( u32 )LOOP_FLAGS_DEFAULT ); state.SetField ( -1, "LOOP_FLAGS_FIXED", ( u32 )LOOP_FLAGS_FIXED ); state.SetField ( -1, "LOOP_FLAGS_MULTISTEP", ( u32 )LOOP_FLAGS_MULTISTEP ); state.SetField ( -1, "LOOP_FLAGS_SOAK", ( u32 )LOOP_FLAGS_SOAK ); state.SetField ( -1, "DEFAULT_STEPS_PER_SECOND", ( u32 )DEFAULT_STEPS_PER_SECOND ); state.SetField ( -1, "DEFAULT_BOOST_THRESHOLD", ( u32 )DEFAULT_BOOST_THRESHOLD ); state.SetField ( -1, "DEFAULT_LONG_DELAY_THRESHOLD", ( u32 )DEFAULT_LONG_DELAY_THRESHOLD ); state.SetField ( -1, "DEFAULT_CPU_BUDGET", ( u32 )DEFAULT_CPU_BUDGET ); state.SetField ( -1, "DEFAULT_STEP_MULTIPLIER", ( u32 )DEFAULT_STEP_MULTIPLIER ); luaL_Reg regTable [] = { { "clearLoopFlags", _clearLoopFlags }, { "crash", _crash }, { "enterFullscreenMode", _enterFullscreenMode }, { "exitFullscreenMode", _exitFullscreenMode }, { "forceGC", _forceGC }, { "framesToTime", _framesToTime }, { "getActionMgr", _getActionMgr }, { "getDeviceTime", _getDeviceTime }, { "getElapsedTime", _getElapsedTime }, { "getListener", &MOAIGlobalEventSource::_getListener < MOAISim > }, { "getLoopFlags", _getLoopFlags }, { "getLuaObjectCount", _getLuaObjectCount }, { "getMemoryUsage", _getMemoryUsage }, { "getMemoryUsagePlain", _getMemoryUsagePlain }, { "getPerformance", _getPerformance }, { "getStep", _getStep }, { "getStepCount", _getStepCount }, { "hideCursor", _hideCursor }, { "openWindow", _openWindow }, { "pauseTimer", _pauseTimer }, { "setBoostThreshold", _setBoostThreshold }, { "setCpuBudget", _setCpuBudget}, { "setGCActive", _setGCActive }, { "setGCStep", _setGCStep }, { "setListener", &MOAIGlobalEventSource::_setListener < MOAISim > }, { "setLongDelayThreshold", _setLongDelayThreshold }, { "setLoopFlags", _setLoopFlags }, { "setLuaAllocLogEnabled", _setLuaAllocLogEnabled }, { "setStep", _setStep }, { "setStepMultiplier", _setStepMultiplier }, { "setStepSmoothing", _setStepSmoothing }, { "setTimerError", _setTimerError }, { "setTraceback", _setTraceback }, { "setTextInputRect", _setTextInputRect }, { "showCursor", _showCursor }, { "timeToFrames", _timeToFrames }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAISim::RegisterLuaFuncs ( MOAILuaState& state ) { UNUSED ( state ); } //----------------------------------------------------------------// void MOAISim::Resume () { if ( this->mLoopState == PAUSED ) { double skip = ZLDeviceTime::GetTimeInSeconds () - this->mPauseTime; MOAIInputMgr::Get ().FlushEvents ( skip ); this->InvokeListener ( EVENT_RESUME ); this->mLoopState = START; } } //----------------------------------------------------------------// void MOAISim::SetStep ( double step ) { if ( this->mStep != step ) { this->mStep = step; if ( this->mSetSimStepFunc ) { this->mSetSimStepFunc ( step ); } } } //----------------------------------------------------------------// double MOAISim::SmoothStep ( double step ) { if ( this->mSmoothBuffer.Size () == 0 ) { return step; } size_t size = this->mSmoothBuffer.Size (); this->mSmoothBuffer [ this->mSmoothIdx++ ] = step; this->mSmoothIdx %= size; u32 count = 0; double sum = 0.0; for ( size_t i = 0; i < size; ++i ) { double dt = this->mSmoothBuffer [ i ]; // Ignore long delay steps if ( !( this->mLoopFlags & SIM_LOOP_LONG_DELAY ) || ( dt < this->mStep * this->mLongDelayThreshold )) { count++; sum += dt; } } return ( count > 0 ) ? sum / count : step; } //----------------------------------------------------------------// double MOAISim::StepSim ( double step, u32 multiplier ) { double time = ZLDeviceTime::GetTimeInSeconds (); MOAIScopedLuaState state = MOAILuaRuntime::Get ().State (); for ( u32 s = 0; s < multiplier; ++s ) { lua_gc ( state, LUA_GCSTOP, 0 ); MOAITestMgr::Get ().Step (); this->InvokeListener ( EVENT_STEP ); double t = ZLDeviceTime::GetTimeInSeconds (); MOAIInputMgr::Get ().Update ( step ); this->mActionTree->Update ( step ); this->mActionTreeTime = this->mActionTreeTime + ZLDeviceTime::GetTimeInSeconds () - t; t = ZLDeviceTime::GetTimeInSeconds (); MOAINodeMgr::Get ().Update (); this->mNodeMgrTime = this->mNodeMgrTime + ZLDeviceTime::GetTimeInSeconds () - t; this->mSimTime += step; this->mStepCount++; if ( this->mGCActive ) { // empty the userdata cache MOAILuaRuntime::Get ().PurgeUserdataCache (); // crank the garbage collector lua_gc ( state, LUA_GCSTEP, this->mGCStep ); } } return ZLDeviceTime::GetTimeInSeconds () - time; } //----------------------------------------------------------------// void MOAISim::Update () { MOAIScopedLuaState state = MOAILuaRuntime::Get ().State (); if ( !this->mLuaGCFunc ) { lua_getglobal ( state, LUA_GC_FUNC_NAME ); this->mLuaGCFunc.SetRef ( *this, state, -1 ); lua_pop ( state, 1 ); lua_pushcfunction ( state, _collectgarbage ); lua_setglobal ( state, LUA_GC_FUNC_NAME ); } // Measure performance double simStartTime = ZLDeviceTime::GetTimeInSeconds (); double interval = this->MeasureFrameRate (); this->ResetPerformanceTimers (); MOAIMainThreadTaskSubscriber::Get ().Publish (); // try to account for timer error if ( this->mTimerError != 0.0 ) { double steps = interval / this->mStep; double integer = floor ( steps ); double decimal = steps - integer; if ( decimal <= this->mTimerError ) { interval = this->mStep * integer; } else if ( decimal >= ( 1.0 - this->mTimerError )) { interval = this->mStep * ( integer + 1.0 ); } } interval = this->SmoothStep ( interval ); // actual device time elapsed since starting or restarting the sim this->mRealTime += interval; // bail if we're paused if ( this->mLoopState == PAUSED ) { return; } // the reset clock flag warps the sim time ahead to match real time just once, then autoclears // this means there will be no time deficit or attempted catch-up // if spinning is not allowed, also clear prevent any time deficit if ( this->mLoopFlags & SIM_LOOP_RESET_CLOCK ) { this->mLoopState = START; this->mLoopFlags &= ~SIM_LOOP_RESET_CLOCK; } // 'budget' will be used to measure the actual CPU time each sim step takes to proces // initialize budget to limit time spent updating when the sim has fallen behind realtime // this prevents a scenario where the sim falls behind but loops forever when attempting to catch up due to // the update itself taking too long and increading the gap between real and target time double budget = this->mStep * this->mCpuBudget; // reset sim time on start if ( this->mLoopState == START ) { this->mRealTime = this->mSimTime; this->mLoopState = RUNNING; // perform an empty step to initialize the sim // subtract the elapsed CPU time from the budget budget -= this->StepSim ( 0.0, 1 ); } // 'gap' is the time left to make up between sim time and real time // i.e. the time deficit double gap = this->mRealTime - this->mSimTime; // long delay lets us ignore gaps bigger than a certain threshold if (( this->mLoopFlags & SIM_LOOP_LONG_DELAY ) && ( gap > ( this->mStep * this->mLongDelayThreshold ))) { budget -= this->StepSim ( this->mStep, 1 ); gap = 0.0f; this->mRealTime = this->mSimTime; } // boost mode allows the sim to perform a large, variable-sized step to // make up the entire time deficit - but only if the sim has fallen behind // by a certain threshold (given in number of frames) // we only boost if we've fallen behind the number of steps given by boost threshold if ( !(( this->mLoopFlags & SIM_LOOP_ALLOW_BOOST ) && ( gap > ( this->mStep * this->mBoostThreshold )))) { // budget -= this->StepSim ( gap, 1 ); // gap = 0.0f; // } // else { // we didn't boost, so process steps normally... // perform a single step only if the time deficit is greater than step time // in other words, at least one interval of step time has elapsed in real time // so we need to catch up if (( this->mLoopFlags & SIM_LOOP_FORCE_STEP ) || (( this->mStep <= gap ) && ( budget > 0.0 ))) { budget -= this->StepSim ( this->mStep, this->mStepMultiplier ); gap -= this->mStep * ( double )this->mStepMultiplier; } // spin mode allows us to attempt to close the time deficit by using our // budget to run additional sim steps // of course, if the sim takes an excessively long time to process // we may never catch up... if ( this->mLoopFlags & SIM_LOOP_ALLOW_SPIN ) { while (( this->mStep <= gap ) && ( budget > 0.0 )) { budget -= this->StepSim ( this->mStep, this->mStepMultiplier ); gap -= this->mStep * ( double )this->mStepMultiplier; } } // Will use up the remaining 'frame' budget, e.g if step size 1 / 30, it will // spin/sleep until this time has passed inside this update if ( this->mLoopFlags & SIM_LOOP_ALLOW_SOAK ) { double startTime = ZLDeviceTime::GetTimeInSeconds (); double remainingTime = budget - ( this->mStep * ( DEFAULT_CPU_BUDGET - 1 ) ); // using 2ms buffer zone for sleeps while ( ( remainingTime - ( ZLDeviceTime::GetTimeInSeconds() - startTime ) > 0.002 )) { #ifndef MOAI_OS_WINDOWS usleep ( 1000 ); #else // WARNING: sleep on windows is not quite as precise Sleep ( 1 ); #endif } } } // if real time is more than a step ahead of sim time (for whatever reason), wait up if (( this->mLoopFlags & SIM_LOOP_NO_DEFICIT ) && (( this->mRealTime - this->mSimTime ) >= this->mStep )) { this->mRealTime = this->mSimTime; } // if real time is behind sim time (for whatever reason), catch up if (( this->mLoopFlags & SIM_LOOP_NO_SURPLUS ) && ( this->mRealTime < this->mSimTime )) { this->mRealTime = this->mSimTime; } // Measure performance double simEndTime = ZLDeviceTime::GetTimeInSeconds (); this->mSimDuration = simEndTime - simStartTime; }
0
0.94697
1
0.94697
game-dev
MEDIA
0.50911
game-dev
0.940576
1
0.940576
Pursue525/Nattalie-1.12.2
1,340
src/net/minecraft/client/renderer/entity/RenderHorse.java
package net.minecraft.client.renderer.entity; import com.google.common.collect.Maps; import java.util.Map; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelHorse; import net.minecraft.client.renderer.texture.LayeredTexture; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.util.ResourceLocation; public class RenderHorse extends RenderLiving<EntityHorse> { private static final Map<String, ResourceLocation> LAYERED_LOCATION_CACHE = Maps.<String, ResourceLocation>newHashMap(); public RenderHorse(RenderManager p_i47205_1_) { super(p_i47205_1_, new ModelHorse(), 0.75F); } /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityHorse entity) { String s = entity.getHorseTexture(); ResourceLocation resourcelocation = LAYERED_LOCATION_CACHE.get(s); if (resourcelocation == null) { resourcelocation = new ResourceLocation(s); Minecraft.getMinecraft().getTextureManager().loadTexture(resourcelocation, new LayeredTexture(entity.getVariantTexturePaths())); LAYERED_LOCATION_CACHE.put(s, resourcelocation); } return resourcelocation; } }
0
0.739278
1
0.739278
game-dev
MEDIA
0.893577
game-dev,graphics-rendering
0.812272
1
0.812272
winstxnhdw/lc-hax
1,877
lc-hax/Scripts/Helpers/CreateComponent.cs
using System.Collections.Generic; using UnityEngine; static partial class Helper { static Dictionary<string, Queue<Component>> ComponentPools { get; } = []; static T CreateComponent<T>(string name) where T : Component => new GameObject(name).AddComponent<T>(); /// <summary> /// Attaches a component to a created game object. /// </summary> /// <returns>the created component</returns> internal static T CreateComponent<T>() where T : Component => new GameObject().AddComponent<T>(); /// <summary> /// Creates a component and adds it to a queue. /// Used to restrict the total number of existing component(s) belonging to a pool. /// </summary> /// <returns>the created component</returns> internal static T CreateComponent<T>(string poolName, int poolSize = 1) where T : Component { T gameObject = Helper.CreateComponent<T>(poolName); if (!Helper.ComponentPools.TryGetValue(poolName, out Queue<Component> pool)) { pool = new Queue<Component>(poolSize); Helper.ComponentPools[poolName] = pool; } if (pool.Count == poolSize) { GameObject.Destroy(pool.Dequeue()); } pool.Enqueue(gameObject); return gameObject; } /// <summary> /// Similar to `CreateComponent`, but for components that are implicitly toggleable. /// If the component already exists, no component is created and null is returned. /// </summary> /// <returns>a component if it has been created, null otherwise</returns> internal static T? CreateToggleableComponent<T>(string poolName) where T : Component { if (!Helper.ComponentPools.TryGetValue(poolName, out Queue<Component> pool)) { return Helper.CreateComponent<T>(poolName); } GameObject.Destroy(pool.Dequeue()); return null; } }
0
0.786523
1
0.786523
game-dev
MEDIA
0.964589
game-dev
0.899927
1
0.899927
PaperMC/Paper
2,032
paper-server/src/main/java/io/papermc/paper/configuration/type/fallback/FallbackValueSerializer.java
package io.papermc.paper.configuration.type.fallback; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import java.util.function.Supplier; import net.minecraft.server.MinecraftServer; import org.spigotmc.SpigotWorldConfig; import org.spongepowered.configurate.serialize.ScalarSerializer; import org.spongepowered.configurate.serialize.SerializationException; import static io.leangen.geantyref.GenericTypeReflector.erase; public class FallbackValueSerializer extends ScalarSerializer<FallbackValue> { private static final Map<Class<?>, FallbackCreator<?>> REGISTRY = new HashMap<>(); static { REGISTRY.put(ArrowDespawnRate.class, ArrowDespawnRate::new); REGISTRY.put(AutosavePeriod.class, AutosavePeriod::new); } FallbackValueSerializer(Map<FallbackValue.ContextKey<?>, Object> contextMap) { super(FallbackValue.class); this.contextMap = contextMap; } @FunctionalInterface private interface FallbackCreator<T extends FallbackValue> { T create(Map<FallbackValue.ContextKey<?>, Object> context, Object value) throws SerializationException; } private final Map<FallbackValue.ContextKey<?>, Object> contextMap; @Override public FallbackValue deserialize(Type type, Object obj) throws SerializationException { final FallbackCreator<?> creator = REGISTRY.get(erase(type)); if (creator == null) { throw new SerializationException(type + " does not have a FallbackCreator registered"); } return creator.create(this.contextMap, obj); } @Override protected Object serialize(FallbackValue item, Predicate<Class<?>> typeSupported) { return item.serialize(); } public static FallbackValueSerializer create(SpigotWorldConfig config, Supplier<MinecraftServer> server) { return new FallbackValueSerializer(Map.of(FallbackValue.SPIGOT_WORLD_CONFIG, config, FallbackValue.MINECRAFT_SERVER, server)); } }
0
0.924868
1
0.924868
game-dev
MEDIA
0.928669
game-dev
0.777386
1
0.777386
followingthefasciaplane/source-engine-diff-check
3,238
misc/engine/enginestats.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef ENGINESTATS_H #define ENGINESTATS_H #ifdef _WIN32 #pragma once #endif #include "utlvector.h" #include "sysexternal.h" #include "filesystem.h" // FileHandle_t define enum EngineTimedStatId_t { ENGINE_STATS_FRAME_TIME, ENGINE_STATS_FPS, // this is calculated at EndFrame! ENGINE_STATS_FPS_VARIABILITY, ENGINE_STATS_NUM_TIMED_STATS, }; class CEngineStats { public: CEngineStats(); // // stats input // void BeginRun( void ); // Advances the next frame for the stats... void NextFrame(); void BeginFrame( void ); // Timed stat gathering void BeginTimedStat( EngineTimedStatId_t stat ); void EndTimedStat( EngineTimedStatId_t stat ); // Adds to a timed stat... void AddToTimedStat( EngineTimedStatId_t stat, float time ); // Slams a timed stat void SetTimedStat( EngineTimedStatId_t stat, float time ); // returns timed stats double TimedStatInFrame( EngineTimedStatId_t stat ) const; double TotalTimedStat( EngineTimedStatId_t stat ) const; void BeginDrawWorld( void ); void EndDrawWorld( void ); void EndFrame( void ); void EndRun( void ); void PauseStats( bool bPaused ); // // stats output // call these outside of a BeginFrame/EndFrame pair // double GetRunTime( void ); void SetFrameTime( float flFrameTime ) { m_flFrameTime = flFrameTime; } void SetFPSVariability( float flFPSVariability ) { m_flFPSVariability = flFPSVariability; } int FrameCount() const { return m_totalNumFrames; } void EnableVProfStatsRecording( const char *pFileName ); private: void ComputeFrameTimeStats( void ); // How many frames worth of data have we logged? int m_totalNumFrames; // run timing data double m_runStartTime; double m_runEndTime; struct StatGroupInfo_t { double m_StatFrameTime[ENGINE_STATS_NUM_TIMED_STATS]; double m_StatStartTime[ENGINE_STATS_NUM_TIMED_STATS]; double m_TotalStatTime[ENGINE_STATS_NUM_TIMED_STATS]; }; StatGroupInfo_t m_StatGroup; bool m_InFrame; bool m_bPaused; bool m_bInRun; float m_flFrameTime; float m_flFPSVariability; char m_szVProfStatsFileName[MAX_PATH]; }; //----------------------------------------------------------------------------- // Inlined stat gathering methods //----------------------------------------------------------------------------- inline void CEngineStats::BeginTimedStat( EngineTimedStatId_t stat ) { if (m_InFrame) { m_StatGroup.m_StatStartTime[stat] = Sys_FloatTime(); } } inline void CEngineStats::EndTimedStat( EngineTimedStatId_t stat ) { if (m_InFrame) { float dt = (float)Sys_FloatTime() - (float)(m_StatGroup.m_StatStartTime[stat]); m_StatGroup.m_StatFrameTime[stat] += dt; } } // Adds to a timed stat... inline void CEngineStats::AddToTimedStat( EngineTimedStatId_t stat, float dt ) { if (m_InFrame) { m_StatGroup.m_StatFrameTime[stat] += dt; } } // Slams a timed stat inline void CEngineStats::SetTimedStat( EngineTimedStatId_t stat, float time ) { m_StatGroup.m_StatFrameTime[stat] = time; } extern CEngineStats g_EngineStats; #endif // ENGINESTATS_H
0
0.966068
1
0.966068
game-dev
MEDIA
0.50201
game-dev
0.795206
1
0.795206
Sigma-Skidder-Team/SigmaRemap
5,313
src/main/java/mapped/Class9008.java
package mapped; import com.google.common.collect.Maps; import java.util.Map; import java.util.Optional; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.TextFormatting; public class Class9008 { public static final Map<String, Class9008> field41188 = Maps.newHashMap(); public static final Class9008 field41189 = new Class9008("dummy"); public static final Class9008 field41190 = new Class9008("trigger"); public static final Class9008 field41191 = new Class9008("deathCount"); public static final Class9008 field41192 = new Class9008("playerKillCount"); public static final Class9008 field41193 = new Class9008("totalKillCount"); public static final Class9008 field41194 = new Class9008("health", true, Class2316.field15869); public static final Class9008 field41195 = new Class9008("food", true, Class2316.field15868); public static final Class9008 field41196 = new Class9008("air", true, Class2316.field15868); public static final Class9008 field41197 = new Class9008("armor", true, Class2316.field15868); public static final Class9008 field41198 = new Class9008("xp", true, Class2316.field15868); public static final Class9008 field41199 = new Class9008("level", true, Class2316.field15868); public static final Class9008[] field41200 = new Class9008[]{ new Class9008("teamkill." + TextFormatting.BLACK.getFriendlyName()), new Class9008("teamkill." + TextFormatting.DARK_BLUE.getFriendlyName()), new Class9008("teamkill." + TextFormatting.DARK_GREEN.getFriendlyName()), new Class9008("teamkill." + TextFormatting.DARK_AQUA.getFriendlyName()), new Class9008("teamkill." + TextFormatting.DARK_RED.getFriendlyName()), new Class9008("teamkill." + TextFormatting.DARK_PURPLE.getFriendlyName()), new Class9008("teamkill." + TextFormatting.GOLD.getFriendlyName()), new Class9008("teamkill." + TextFormatting.GRAY.getFriendlyName()), new Class9008("teamkill." + TextFormatting.DARK_GRAY.getFriendlyName()), new Class9008("teamkill." + TextFormatting.BLUE.getFriendlyName()), new Class9008("teamkill." + TextFormatting.GREEN.getFriendlyName()), new Class9008("teamkill." + TextFormatting.AQUA.getFriendlyName()), new Class9008("teamkill." + TextFormatting.RED.getFriendlyName()), new Class9008("teamkill." + TextFormatting.LIGHT_PURPLE.getFriendlyName()), new Class9008("teamkill." + TextFormatting.YELLOW.getFriendlyName()), new Class9008("teamkill." + TextFormatting.WHITE.getFriendlyName()) }; public static final Class9008[] field41201 = new Class9008[]{ new Class9008("killedByTeam." + TextFormatting.BLACK.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.DARK_BLUE.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.DARK_GREEN.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.DARK_AQUA.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.DARK_RED.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.DARK_PURPLE.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.GOLD.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.GRAY.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.DARK_GRAY.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.BLUE.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.GREEN.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.AQUA.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.RED.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.LIGHT_PURPLE.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.YELLOW.getFriendlyName()), new Class9008("killedByTeam." + TextFormatting.WHITE.getFriendlyName()) }; private final String field41202; private final boolean field41203; private final Class2316 field41204; public Class9008(String var1) { this(var1, false, Class2316.field15868); } public Class9008(String var1, boolean var2, Class2316 var3) { this.field41202 = var1; this.field41203 = var2; this.field41204 = var3; field41188.put(var1, this); } public static Optional<Class9008> method33278(String var0) { if (!field41188.containsKey(var0)) { int var3 = var0.indexOf(58); return var3 >= 0 ? Registry.field16088 .method9187(ResourceLocation.method8288(var0.substring(0, var3), '.')) .<Class9008>flatMap(var2 -> method33279((Class49<?>)var2, ResourceLocation.method8288(var0.substring(var3 + 1), '.'))) : Optional.<Class9008>empty(); } else { return Optional.<Class9008>of(field41188.get(var0)); } } private static <T> Optional<Class9008> method33279(Class49<T> var0, ResourceLocation var1) { return var0.method171().method9187(var1).<Class9008>map(var0::method172); } public String method33280() { return this.field41202; } public boolean isReadOnly() { return this.field41203; } public Class2316 method33282() { return this.field41204; } }
0
0.521533
1
0.521533
game-dev
MEDIA
0.641246
game-dev
0.897689
1
0.897689
00-Evan/shattered-pixel-dungeon
3,358
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/melee/Whip.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2025 Evan Debenham * * 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.items.weapon.melee; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.utils.Callback; import java.util.ArrayList; public class Whip extends MeleeWeapon { { image = ItemSpriteSheet.WHIP; hitSound = Assets.Sounds.HIT; hitSoundPitch = 1.1f; tier = 3; RCH = 3; //lots of extra reach } @Override public int max(int lvl) { return 5*(tier) + //15 base, down from 20 lvl*(tier); //+3 per level, down from +4 } @Override protected void duelistAbility(Hero hero, Integer target) { ArrayList<Char> targets = new ArrayList<>(); Char closest = null; hero.belongings.abilityWeapon = this; for (Char ch : Actor.chars()){ if (ch.alignment == Char.Alignment.ENEMY && !hero.isCharmedBy(ch) && Dungeon.level.heroFOV[ch.pos] && hero.canAttack(ch)){ targets.add(ch); if (closest == null || Dungeon.level.trueDistance(hero.pos, closest.pos) > Dungeon.level.trueDistance(hero.pos, ch.pos)){ closest = ch; } } } hero.belongings.abilityWeapon = null; if (targets.isEmpty()) { GLog.w(Messages.get(this, "ability_no_target")); return; } throwSound(); Char finalClosest = closest; hero.sprite.attack(hero.pos, new Callback() { @Override public void call() { beforeAbilityUsed(hero, finalClosest); for (Char ch : targets) { //ability does no extra damage hero.attack(ch, 1, 0, Char.INFINITE_ACCURACY); if (!ch.isAlive()){ onAbilityKill(hero, ch); } } Invisibility.dispel(); hero.spendAndNext(hero.attackDelay()); afterAbilityUsed(hero); } }); } @Override public String abilityInfo() { if (levelKnown){ return Messages.get(this, "ability_desc", augment.damageFactor(min()), augment.damageFactor(max())); } else { return Messages.get(this, "typical_ability_desc", min(0), max(0)); } } public String upgradeAbilityStat(int level){ return augment.damageFactor(min(level)) + "-" + augment.damageFactor(max(level)); } }
0
0.824974
1
0.824974
game-dev
MEDIA
0.988644
game-dev
0.952945
1
0.952945
followingthefasciaplane/source-engine-diff-check
5,506
misc/game/shared/portal/paint_stream_shared.cpp
//========= Copyright 1996-2009, Valve Corporation, All rights reserved. ============// // //=============================================================================// #include "cbase.h" #include "paint_stream_shared.h" #include "paint_stream_manager.h" #include <functional> #include <algorithm> #include "paint_power_user.h" #include "vstdlib/jobthread.h" #ifdef CLIENT_DLL #include "collisionutils.h" #include "c_paint_stream.h" #include "c_paintblob.h" #else #include "paint_stream.h" #include "cpaintblob.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define VPROF_BUDGETGROUP_PAINTBLOB _T("Paintblob") ConVar max_sound_channels_per_paint_stream("max_sound_channels_per_paint_stream", "7", FCVAR_REPLICATED | FCVAR_CHEAT); IMPLEMENT_SHAREDCLASS_DT( CPaintStream ) SharedProp( m_sharedBlobData ) SharedProp( m_sharedBlobDataMutex ) END_SHARED_TABLE() void CPaintStream::UpdateOnRemove() { RemoveAllPaintBlobs(); BaseClass::UpdateOnRemove(); } void CPaintStream::RemoveAllPaintBlobs( void ) { #ifdef CLIENT_DLL RemoveFromLeafSystem(); #endif } unsigned int CPaintStream::GetBlobsCount() const { return m_blobs.Count(); } CPaintBlob* CPaintStream::GetBlob( int id ) { return m_blobs[id]; } struct ShouldNotDeleteBlob_t : std::unary_function< CPaintBlob*, bool > { inline bool operator()( const CPaintBlob* pBlob ) const { return !pBlob->ShouldDeleteThis(); } }; void CPaintStream::RemoveDeadBlobs() { CPaintBlob** begin = GetBegin( m_blobs ); CPaintBlob** end = GetEnd( m_blobs ); CPaintBlob** middle = std::partition( begin, end, ShouldNotDeleteBlob_t() ); for( CPaintBlob** i = middle; i != end; ++i ) { PaintStreamManager.FreeBlob( *i ); } int numRemoved = end - middle; m_blobs.RemoveMultipleFromTail( numRemoved ); } struct TimeElapsed : public std::unary_function<TimeStamp, bool> { TimeStamp m_CurrentTime; TimeElapsed( TimeStamp currentTime ) : m_CurrentTime( currentTime ) {} inline bool operator()( TimeStamp time ) const { return time <= m_CurrentTime; } }; void CPaintStream::QueuePaintEffect() { #ifdef GAME_DLL // if not listen server, don't do anything if ( engine->IsDedicatedServer() ) return; #else // if we are listen server, don't do anything on client if ( engine->IsClientLocalToActiveServer() ) return; #endif // Update how many channels are in use TimeElapsed timeElapsedPred( gpGlobals->curtime ); TimeStamp* begin = m_UsedChannelTimestamps.Base(); TimeStamp* end = begin + m_UsedChannelTimestamps.Count(); TimeStamp* newEnd = std::remove_if( begin, end, timeElapsedPred ); m_UsedChannelTimestamps.RemoveMultipleFromTail( end - newEnd ); // Try to queue up effects for each impact that occurred PaintImpactEffect const impactEffect = (m_nRenderMode == BLOB_RENDER_BLOBULATOR) ? PAINT_STREAM_IMPACT_EFFECT : PAINT_DRIP_IMPACT_EFFECT; int const maxChannels = max_sound_channels_per_paint_stream.GetInt(); CUtlVectorFixedGrowable<Vector, 32> soundPositions; for ( int i = 0; i < m_blobs.Count(); ++i ) { CPaintBlob *pBlob = m_blobs[i]; if ( pBlob->ShouldPlayEffect() && !pBlob->IsSilent() ) { PaintStreamManager.CreatePaintImpactParticles( pBlob->GetPosition(), pBlob->GetContactNormal(), m_nPaintType ); if( pBlob->ShouldPlaySound() ) soundPositions.AddToTail( pBlob->GetPosition() ); } } if( soundPositions.Count() != 0 ) PaintStreamManager.PlayMultiplePaintImpactSounds( m_UsedChannelTimestamps, maxChannels, soundPositions, impactEffect ); } void CPaintStream::PreUpdateBlobs() { RemoveDeadBlobs(); DebugDrawBlobs(); } void CPaintStream::PostUpdateBlobs() { RemoveTeleportedThisFrameBlobs(); UpdateRenderBoundsAndOriginWorldspace(); QueuePaintEffect(); #ifdef GAME_DLL AddPaintToDatabase(); UpdateBlobSharedData(); #endif // reset blobs teleported this frame flag ResetBlobsTeleportedThisFrame(); } const Vector& CPaintStream::WorldAlignMins() const { return m_vCachedWorldMins; } const Vector& CPaintStream::WorldAlignMaxs() const { return m_vCachedWorldMaxs; } struct TeleportedThisFrameBlob_t : std::unary_function< CPaintBlob*, bool > { TeleportedThisFrameBlob_t( int nMaxTeleportationCount ) : m_nMaxTeleportationCount( nMaxTeleportationCount ) { } inline bool operator()( const CPaintBlob* pBlob ) const { return pBlob->HasBlobTeleportedThisFrame() && ( pBlob->GetTeleportationCount() >= m_nMaxTeleportationCount ); } int m_nMaxTeleportationCount; }; //----------------------------------------------------------------------------------------------- // Purpose: Remove blobs that have teleported this frame if the stream reaches max blob count //----------------------------------------------------------------------------------------------- void CPaintStream::RemoveTeleportedThisFrameBlobs() { if ( m_nRenderMode == BLOB_RENDER_FAST_SPHERE ) { Assert( m_blobs.Count() <= m_nMaxBlobCount ); if ( m_blobs.Count() == m_nMaxBlobCount ) { CPaintBlob** begin = GetBegin( m_blobs ); CPaintBlob** end = GetEnd( m_blobs ); CPaintBlob** middle = std::partition( begin, end, TeleportedThisFrameBlob_t( 4 ) ); for( CPaintBlob** i = begin; i != middle; ++i ) { PaintStreamManager.FreeBlob( *i ); } int numRemoved = middle - begin; m_blobs.RemoveMultipleFromHead( numRemoved ); } } } void CPaintStream::ResetBlobsTeleportedThisFrame() { for ( int i=0; i<m_blobs.Count(); ++i ) { m_blobs[i]->SetBlobTeleportedThisFrame( false ); } }
0
0.897837
1
0.897837
game-dev
MEDIA
0.534382
game-dev,graphics-rendering
0.976832
1
0.976832
osudroid/osu-droid
1,924
src/com/rian/osu/beatmap/sections/BeatmapGeneral.kt
package com.rian.osu.beatmap.sections import com.rian.osu.beatmap.constants.BeatmapCountdown import com.rian.osu.beatmap.constants.SampleBank /** * Contains general information about a beatmap. */ data class BeatmapGeneral( /** * The location of the audio file relative to the beatmapset file. */ @JvmField var audioFilename: String = "", /** * The amount of milliseconds of silence before the audio starts playing. */ @JvmField var audioLeadIn: Int = 0, /** * The time in milliseconds when the audio preview should start. * * If -1, the audio should begin playing at 40% of its length. */ @JvmField var previewTime: Int = -1, /** * The speed of the countdown before the first hit object. */ @JvmField var countdown: BeatmapCountdown = BeatmapCountdown.Normal, /** * The sample bank that will be used if timing points do not override it. */ @JvmField var sampleBank: SampleBank = SampleBank.Normal, /** * The sample volume that will be used if timing points do not override it. */ @JvmField var sampleVolume: Int = 100, /** * The multiplier for the threshold in time where hit objects * placed close together stack, ranging from 0 to 1. */ @JvmField var stackLeniency: Float = 0.7f, /** * Whether breaks have a letterboxing effect. */ @JvmField var letterboxInBreaks: Boolean = false, /** * The game mode this beatmap represents. */ @JvmField var mode: Int = 0, /** * Whether sound samples will change rate when playing with rate-adjusting mods. */ @JvmField var samplesMatchPlaybackRate: Boolean = false, /** * Whether a warning about flashing colours should be shown at the beginning of the beatmap. */ @JvmField var epilepsyWarning: Boolean = false )
0
0.828466
1
0.828466
game-dev
MEDIA
0.873561
game-dev
0.506856
1
0.506856
stride-tasks/stride
5,560
crates/database/src/operation/difference.rs
use std::{collections::HashSet, hash::Hash}; use stride_core::task::Task; use crate::operation::{Operation, OperationKind}; pub(crate) enum DifferenceType { Addition, Deletion, } pub(crate) fn difference_between<'a, T>( previous: &'a [T], current: &'a [T], ) -> Vec<(&'a T, DifferenceType)> where T: Eq + Hash, { if current != previous { return Vec::new(); } let previous = previous.iter().collect::<HashSet<_>>(); let current = current.iter().collect::<HashSet<_>>(); previous .difference(&current) .map(|value| (*value, DifferenceType::Deletion)) .chain( current .difference(&previous) .map(|value| (*value, DifferenceType::Addition)), ) .collect() } #[allow(clippy::too_many_lines)] fn push_operations_diff_task_common(current: &Task, previous: &Task, ops: &mut Vec<Operation>) { if current.status != previous.status { ops.push( OperationKind::TaskModifyStatus { id: current.uuid, new: current.status, old: previous.status, } .with_now(), ); } if current.active != previous.active { ops.push( OperationKind::TaskModifyActive { id: current.uuid, new: current.active, old: previous.active, } .with_now(), ); } if current.modified != previous.modified { ops.push( OperationKind::TaskModifyModified { id: current.uuid, new: current.modified, old: previous.modified, } .with_now(), ); } if current.due != previous.due { ops.push( OperationKind::TaskModifyDue { id: current.uuid, new: current.due, old: previous.due, } .with_now(), ); } if current.wait != previous.wait { ops.push( OperationKind::TaskModifyWait { id: current.uuid, new: current.wait, old: previous.wait, } .with_now(), ); } if current.project != previous.project { ops.push( OperationKind::TaskModifyProject { id: current.uuid, new: current.project.clone().map(String::into_boxed_str), old: previous.project.clone().map(String::into_boxed_str), } .with_now(), ); } if current.priority != previous.priority { ops.push( OperationKind::TaskModifyPriority { id: current.uuid, new: current.priority, old: previous.priority, } .with_now(), ); } for (tag, ty) in difference_between(&previous.tags, &current.tags) { let kind = match ty { DifferenceType::Addition => OperationKind::TaskModifyAddTag { id: current.uuid, tag: tag.clone().into(), }, DifferenceType::Deletion => OperationKind::TaskModifyRemoveTag { id: current.uuid, tag: tag.clone().into(), }, }; ops.push(kind.with_now()); } for (annotation, ty) in difference_between(&previous.annotations, &current.annotations) { let kind = match ty { DifferenceType::Addition => OperationKind::TaskModifyAddAnnotation { id: current.uuid, annotation: annotation.clone().into(), }, DifferenceType::Deletion => OperationKind::TaskModifyRemoveAnnotation { id: current.uuid, annotation: annotation.clone().into(), }, }; ops.push(kind.with_now()); } for (uda, ty) in difference_between(&previous.udas, &current.udas) { let kind = match ty { DifferenceType::Addition => OperationKind::TaskModifyAddUda { id: current.uuid, uda: uda.clone().into(), }, DifferenceType::Deletion => OperationKind::TaskModifyRemoveUda { id: current.uuid, uda: uda.clone().into(), }, }; ops.push(kind.with_now()); } } pub(crate) fn push_operations_diff_task(current: &Task, previous: &Task, ops: &mut Vec<Operation>) { if current.title != previous.title { ops.push( OperationKind::TaskModifyTitle { id: current.uuid, new: current.title.clone().into_boxed_str(), old: previous.title.clone().into_boxed_str(), } .with_now(), ); } if current.entry != previous.entry { ops.push( OperationKind::TaskModifyEntry { id: current.uuid, new: current.entry, old: previous.entry, } .with_now(), ); } push_operations_diff_task_common(current, previous, ops); } pub(crate) fn push_operations_diff_task_with_default(current: &Task, ops: &mut Vec<Operation>) { ops.push( OperationKind::TaskCreate { id: current.uuid, title: current.title.clone().into(), } .with_now(), ); let previous = Task::default(); push_operations_diff_task_common(current, &previous, ops); // task.depends; }
0
0.679125
1
0.679125
game-dev
MEDIA
0.360729
game-dev
0.887705
1
0.887705
ServUO/ServUO
1,564
Scripts/Items/Artifacts/Equipment/Clothing/EmbroideredOakLeafCloak.cs
using System; using Server.Engines.Craft; namespace Server.Items { public class EmbroideredOakLeafCloak : BaseOuterTorso, IRepairable { public CraftSystem RepairSystem { get { return DefTailoring.CraftSystem; } } public override bool IsArtifact { get { return true; } } [Constructable] public EmbroideredOakLeafCloak() : base(0x2684) { Hue = 0x483; StrRequirement = 0; SkillBonuses.Skill_1_Name = SkillName.Stealth; SkillBonuses.Skill_1_Value = 5; } public EmbroideredOakLeafCloak(Serial serial) : base(serial) { } public override int LabelNumber { get { return 1094901; } }// Embroidered Oak Leaf Cloak [Replica] public override int InitMinHits { get { return 150; } } public override int InitMaxHits { get { return 150; } } public override bool CanFortify { get { return false; } } 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(); } } }
0
0.886788
1
0.886788
game-dev
MEDIA
0.364585
game-dev
0.930396
1
0.930396
neparij/katawa-shoujo-agb
4,203
include/ks_huge_bg.h
/** * ----------------------------------------------------------------------------- * File: ks_huge_bg.h * Description: Header file for the huge background instance * Author: neparij (Nikolai Laptev) * Project: Katawa Shoujo - Game Boy Advance * License: Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International * Creation Date: 2025-05-29 * ----------------------------------------------------------------------------- */ #ifndef KS_HUGE_BG_H #define KS_HUGE_BG_H #include "bn_log.h" #include "ks_huge_bgs_manager.h" #include "bn_regular_bg_ptr.h" #include "bn_size.h" #include "bn_span.h" #include "bn_tile.h" #define WIDTH_BLOCKS 30 // 240 pixels / 8 pixels per tile #define HEIGHT_BLOCKS 20 // 160 pixels / 8 pixels per tile #define TILES_COUNT ((WIDTH_BLOCKS * HEIGHT_BLOCKS) + (WIDTH_BLOCKS + HEIGHT_BLOCKS) + 1) #define TILES_COUNT_BPP8 (TILES_COUNT * 2) namespace ks { class huge_bg_item; class huge_bg { public: ~huge_bg(); [[nodiscard]] static huge_bg create(const huge_bg_item &item); [[nodiscard]] static huge_bg create(bn::fixed x, bn::fixed y, const huge_bg_item &item); [[nodiscard]] bn::regular_bg_ptr regular_bg_ptr() const { return _wrapped_bg_ptr; } [[nodiscard]] bn::size map_dimensions() const { return _map_dimensions; } huge_bg(huge_bg &&other) noexcept : huge_bg(other._wrapped_bg_ptr, other._map_dimensions, other._map_data, other._tiles_data, other._map_vram, other._tiles_vram) { // *this = bn::move(other); *this = other; } huge_bg(const huge_bg &&other) noexcept : huge_bg(other._wrapped_bg_ptr, other._map_dimensions, other._map_data, other._tiles_data, other._map_vram, other._tiles_vram) { // *this = bn::move(other); *this = other; } // // Copy constructor. // huge_bg(const huge_bg& other); // Copy assignment operator. huge_bg& operator=(const huge_bg& other); [[nodiscard]] bn::fixed_point position() const; void update(); private: bn::regular_bg_ptr _wrapped_bg_ptr; bn::size _map_dimensions; const uint16_t *_map_data; const uint8_t *_tiles_data; bn::span<unsigned short>::iterator _map_vram; bn::span<bn::tile>::iterator _tiles_vram; int x_offset, y_offset; int previous_x_offset, previous_y_offset; bool initialized; explicit huge_bg(const bn::regular_bg_ptr &handle, const bn::size &map_dimensions, const uint16_t *map_data, const uint8_t *tiles_data, const bn::span<unsigned short>::iterator map_vram, const bn::span<bn::tile>::iterator tiles_vram) : _wrapped_bg_ptr(handle), _map_dimensions(map_dimensions), _map_data(map_data), _tiles_data(tiles_data), _map_vram(map_vram), _tiles_vram(tiles_vram) { x_offset = y_offset = 0; previous_x_offset = previous_y_offset = 0; initialized = false; huge_bgs_manager::push(this); update(); } }; } #endif //KS_HUGE_BG_H
0
0.844574
1
0.844574
game-dev
MEDIA
0.57593
game-dev,graphics-rendering
0.596371
1
0.596371
aishimeth2135/Toram_Grimoire
10,536
src/lib/Skill/Skill/SkillElement.ts
import { markRaw } from 'vue' import Grimoire from '@/shared/Grimoire' import { StatComputed } from '@/lib/Character/Stat' import { StatTypes } from '@/lib/Character/Stat' import { SkillBranchNames, SkillTypes } from './enums' abstract class SkillNode { abstract parent: SkillNode | null } abstract class SkillElement extends SkillNode { id: number name: string abstract get index(): number constructor(id: number, name: string) { super() this.id = id this.name = name } } class SkillRoot extends SkillNode { parent: null skillTreeCategorys: SkillTreeCategory[] constructor() { super() this.parent = null this.skillTreeCategorys = markRaw([]) } get index() { return -1 } appendSkillTreeCategory(id: number, name: string) { const el = markRaw(new SkillTreeCategory(this, id, name)) this.skillTreeCategorys.push(el) return el } findSkillById(skillId: string): Skill | null { let find: Skill | null = null this.skillTreeCategorys.some(stc => { return stc.skillTrees.some(st => { const skill = st.skills.find(sk => sk.skillId === skillId) if (skill) { find = skill return true } return false }) }) return find } findSkillByName(skillName: string): Skill | null { let find: Skill | null = null this.skillTreeCategorys.some(stc => { return stc.skillTrees.some(st => { const skill = st.skills.find(sk => sk.name === skillName) if (skill) { find = skill return true } return false }) }) return find } } class SkillTreeCategory extends SkillElement { parent: SkillRoot skillTrees: SkillTree[] constructor(sr: SkillRoot, id: number, name: string) { super(id, name) this.parent = sr this.skillTrees = markRaw([]) } get index() { return this.parent.skillTreeCategorys.indexOf(this) } appendSkillTree(id: number, name: string) { const el = markRaw(new SkillTree(this, id, name)) this.skillTrees.push(el) return el } } class SkillTree extends SkillElement { parent: SkillTreeCategory skills: Skill[] attrs: { simulatorFlag: boolean } drawTreeCode: string readonly skillTreeId: string constructor(stc: SkillTreeCategory, id: number, name: string) { super(id, name) this.parent = stc this.skills = markRaw([]) this.drawTreeCode = '' this.attrs = markRaw({ simulatorFlag: false, }) this.skillTreeId = `${this.parent.id}-${this.id}` } get index() { return this.parent.skillTrees.indexOf(this) } init(dtc: string) { this.drawTreeCode = dtc } appendSkill(id: number, name: string) { const el = markRaw(new Skill(this, id, name)) this.skills.push(el) return el } } abstract class SkillBase extends SkillElement { parent: SkillTree caption: string previous: number drawOrder: number constructor(st: SkillTree, id: number, name: string, caption: string = '') { super(id, name) this.parent = st this.caption = caption this.previous = -1 this.drawOrder = id } init(pre: number, drawOrder: number) { this.previous = pre this.drawOrder = drawOrder } } class Skill extends SkillBase { effects: SkillEffect[] defaultEffect!: SkillEffect types: SkillTypes[] readonly skillId: string constructor(st: SkillTree, id: number, name: string, caption: string = '') { super(st, id, name, caption) this.effects = [] this.skillId = `${this.parent.parent.id}-${this.parent.id}-${this.id}` this.types = [] } get index() { return this.parent.skills.indexOf(this) } initTypes() { if (this.effects.some(eft => eft.branches.some(bch => bch.name === SkillBranchNames.Passive))) { this.types.push(SkillTypes.Passive) } else { this.types.push(SkillTypes.Active) } if (this.effects.some(eft => eft.branches.some(bch => bch.name === SkillBranchNames.Damage))) { this.types.push(SkillTypes.Damage) } } appendSkillEffect(main: number, sub: number, body: number) { const el = markRaw(new SkillEffect(this, this.effects.length, main, sub, body)) this.effects.push(el) return el } appendSkillEffectHistory(effectId: number, date: string): SkillEffectHistory | void { const effect = this.effects.find(eft => eft.effectId === effectId) if (!effect) { console.warn( `[SkillEffect.appendSkillEffectHistory] can not find target effect with id: ${effectId}.`, this.effects ) return } return effect.appendHistory(date) } setDefaultEffect(sef: SkillEffect) { this.defaultEffect = sef return this } } class SkillEffectBase extends SkillNode { parent: Skill branches: SkillBranch[] constructor(skill: Skill) { super() this.parent = skill this.branches = markRaw([]) } appendSkillBranch(id: number, name: SkillBranchNames) { const el = markRaw(new SkillBranch(this, id, name)) this.branches.push(el) return el } appendSkillBranchFrom(branch: SkillBranch) { const el = markRaw(branch.clone()) this.branches.push(el) return el } } interface SkillEffectBasicProps { mpCost: string | null range: string | null skillType: number | null inCombo: number | null actionTime: number | null castingTime: string | null } class SkillEffect extends SkillEffectBase { effectId: number basicProps: SkillEffectBasicProps historys: SkillEffectHistory[] mainWeapon: number subWeapon: number bodyArmor: number // 0: or, 1: and equipmentOperator: 0 | 1 constructor(skill: Skill, effectId: number, main: number, sub: number, body: number) { super(skill) this.effectId = effectId this.historys = [] this.basicProps = markRaw({ mpCost: '0', range: '0', skillType: 0, inCombo: 0, actionTime: 3, castingTime: '0', }) this.mainWeapon = main this.subWeapon = sub this.bodyArmor = body this.equipmentOperator = 0 } appendHistory(date: string): SkillEffectHistory { const history = new SkillEffectHistory(this, date) this.historys.push(history) return history } } class SkillEffectHistory extends SkillEffectBase { readonly date: string readonly parentEffect: SkillEffect constructor(skillEffect: SkillEffect, date: string) { super(skillEffect.parent) this.date = date this.parentEffect = skillEffect } } class SkillBranch extends SkillNode { parent: SkillEffectBase // id of branch. -1 means no define id: number // type of branch name: SkillBranchNames props: Map<string, string> stats: StatComputed[] constructor(sef: SkillEffectBase, id: number, name: SkillBranchNames) { super() this.parent = sef this.id = id this.name = name this.props = markRaw(new Map()) this.stats = markRaw([]) } get isEmpty() { return this.props.size === 0 && this.stats.length === 0 } hasId(): boolean { return this.id !== -1 } appendProp(name: string, value: string, valueSub?: string) { if (valueSub) { const [prop, subProp] = name.split('.') name = prop + valueSub + (subProp ? `.${subProp}` : '') } this.props.set(name, value) return this } appendStat(baseId: string, value: string, tail: string): StatComputed | null { const type = (() => { if (tail === '%') { return StatTypes.Multiplier } if (tail === '~') { return StatTypes.Total } return StatTypes.Constant })() const statBase = Grimoire.Character.findStatBase(baseId) if (!statBase) { return null } const stat = markRaw(statBase.createStatComputed(type, value)) this.stats.push(stat) return stat } clone(): SkillBranch { const newBranch = new SkillBranch(this.parent, this.id, this.name) newBranch.props = markRaw(new Map(this.props)) newBranch.stats = markRaw(this.stats.map(stat => stat.clone())) return newBranch } } class LevelSkillTree { base: SkillTree levelSkills: LevelSkill[] constructor(st: SkillTree) { this.base = st this.levelSkills = [] } appendLevelSkill(skill: Skill) { const el = new LevelSkill(this, skill) this.levelSkills.push(el) return el } skillPointCost() { return this.levelSkills.reduce((cur, skill) => cur + skill.level(), 0) } starGemSkillPoint() { return this.levelSkills.reduce( (cur, skill) => cur + Math.max(0, skill.starGemLevel() - skill.level()), 0 ) } } class LevelSkill { parent: LevelSkillTree base: Skill private _level: number private _starGemLevel: number constructor(st: LevelSkillTree, skill: Skill) { this.parent = st this.base = skill this._level = 0 this._starGemLevel = 0 } level(value?: number) { if (typeof value === 'number') { value = Math.max(0, Math.min(10, value)) this._level = value } return this._level } addLevel(value: number) { this.level(this._level + value) return this._level } updateTree(forward = false) { if (!forward) { let current: LevelSkill = this as LevelSkill while (current.base.previous !== -1) { const pre = current.parent.levelSkills.find(sk => sk.base.id === current.base.previous) if (!pre) { break } current = pre if (current.level() < 5) { current.level(5) } } } else if (forward && this.level() < 5) { const stk: LevelSkill[] = [this] while (stk.length !== 0) { const current = stk.pop() as LevelSkill this.parent.levelSkills.forEach(skill => { if (skill.base.previous === current.base.id) { stk.push(skill) if (skill.level() > 0) { skill.level(0) } } }) } } } starGemLevel(value?: number) { if (typeof value === 'number') { value = Math.max(0, Math.min(10, value)) this._starGemLevel = value } return this._starGemLevel } addStarGemLevel(value: number) { this.starGemLevel(this._starGemLevel + value) return this._starGemLevel } get id() { return this.base.id } } export { SkillElement, SkillRoot, SkillTreeCategory, SkillTree, Skill, SkillEffect, SkillBranch, LevelSkillTree, LevelSkill, SkillEffectHistory, } export type { SkillEffectBase, SkillEffectBasicProps }
0
0.800553
1
0.800553
game-dev
MEDIA
0.818817
game-dev
0.9369
1
0.9369
DangoRyn/UnityGameFramework_HybridCLR
1,416
Assets/GameMain/Scripts/Editor/DataTableGenerator/DataTableProcessor.SingleProcessor.cs
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using System.IO; namespace Game.Editor.DataTableTools { public sealed partial class DataTableProcessor { private sealed class SingleProcessor : GenericDataProcessor<float> { public override bool IsSystem { get { return true; } } public override string LanguageKeyword { get { return "float"; } } public override string[] GetTypeStrings() { return new string[] { "float", "single", "system.single" }; } public override float Parse(string value) { return float.Parse(value); } public override void WriteToStream(DataTableProcessor dataTableProcessor, BinaryWriter binaryWriter, string value) { binaryWriter.Write(Parse(value)); } } } }
0
0.595955
1
0.595955
game-dev
MEDIA
0.942924
game-dev
0.620381
1
0.620381