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
mrdav30/LockstepRTSEngine
2,162
Assets/Core/Game/Abilities/Extra/SelectionRing/SelectionRingController.cs
using UnityEngine; using System.Collections; using FastCollections; namespace RTSLockstep { public class SelectionRingController : Ability { [SerializeField] private SelectionRing _ringTemplate; [SerializeField] private float _ringRadiusOffset = -2; [SerializeField] private Vector3 _ringPosition; SelectionRing RingTemplate { get { return _ringTemplate; } } public SelectionRing RingObject {get; private set;} public float Size {get; private set;} protected override void OnSetup() { Agent.OnSelectedChange += HandleSelectedChange; Agent.OnHighlightedChange += HandleHighlightedChange; RingObject = GameObject.Instantiate(_ringTemplate.gameObject).GetComponent<SelectionRing>(); Size = (Agent.SelectionRadius + _ringRadiusOffset) * 2; RingObject.Setup(Size); RingObject.transform.parent = this.transform; RingObject.transform.localPosition = _ringPosition; } public void HandleSelectedChange() { if (ReplayManager.IsPlayingBack) { return; } if (!Agent.IsSelected) { if (Agent.IsHighlighted) { RingObject.SetState(SelectionRingState.Highlighted); } else { RingObject.SetState(SelectionRingState.None); } } else { // play selected sound RingObject.SetState(SelectionRingState.Selected); } } public void HandleHighlightedChange() { if (ReplayManager.IsPlayingBack) { return; } if (Agent.IsHighlighted) { if (Agent.IsSelected) { } else { RingObject.SetState(SelectionRingState.Highlighted); } } else { if (!Agent.IsSelected) { RingObject.SetState(SelectionRingState.None); } } } } }
412
0.877493
1
0.877493
game-dev
MEDIA
0.256854
game-dev
0.952868
1
0.952868
Tropicraft/Tropicraft
4,820
src/main/java/net/tropicraft/core/common/entity/ai/ashen/EntityAIMeleeAndRangedAttack.java
package net.tropicraft.core.common.entity.ai.ashen; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.monster.RangedAttackMob; import net.minecraft.world.item.ItemStack; import net.tropicraft.core.common.entity.hostile.AshenEntity; import net.tropicraft.core.common.item.AshenMaskItem; import javax.annotation.Nullable; import java.util.EnumSet; public class EntityAIMeleeAndRangedAttack extends Goal { /** * The entity the AI instance has been applied to */ private final AshenEntity entityHost; /** * The entity (as a RangedAttackMob) the AI instance has been applied to. */ private final RangedAttackMob rangedAttackEntityHost; @Nullable private LivingEntity attackTarget; /** * A decrementing tick that spawns a ranged attack once this value reaches 0. It is then set back to the * maxRangedAttackTime. */ private int rangedAttackTime; private final double entityMoveSpeed; private int seeTime; private final int maxMeleeAttackTime; /** * The maximum time the AI has to wait before peforming another ranged attack. */ private final int maxRangedAttackTime; private final float shootCutoffRange; private final float shootCutoffRangeSqr; private float meleeHitRange = 2.0f; public EntityAIMeleeAndRangedAttack(AshenEntity attacker, double movespeed, int maxMeleeAttackTime, int maxRangedAttackTime, float maxAttackDistanceIn) { this(attacker, movespeed, maxMeleeAttackTime, maxRangedAttackTime, maxAttackDistanceIn, 2.0f); } public EntityAIMeleeAndRangedAttack(AshenEntity attacker, double movespeed, int maxMeleeAttackTime, int maxRangedAttackTime, float maxAttackDistanceIn, float meleeHitRange) { rangedAttackTime = -1; rangedAttackEntityHost = attacker; entityHost = attacker; entityMoveSpeed = movespeed; this.maxMeleeAttackTime = maxMeleeAttackTime; this.maxRangedAttackTime = maxRangedAttackTime; shootCutoffRange = maxAttackDistanceIn; shootCutoffRangeSqr = maxAttackDistanceIn * maxAttackDistanceIn; this.meleeHitRange = meleeHitRange; setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); } @Override public boolean canUse() { LivingEntity entitylivingbase = entityHost.getLastHurtByMob(); if (entitylivingbase == null) { return false; } else { attackTarget = entitylivingbase; return true; } } @Override public boolean canContinueToUse() { return canUse() || !entityHost.getNavigation().isDone(); } @Override public void stop() { attackTarget = null; seeTime = 0; rangedAttackTime = -1; } @Override public void tick() { if (attackTarget != null) { ItemStack headGear = attackTarget.getItemBySlot(EquipmentSlot.HEAD); if (headGear.getItem() instanceof AshenMaskItem) { return; } } double d0 = entityHost.distanceToSqr(attackTarget.getX(), attackTarget.getBoundingBox().minY, attackTarget.getZ()); boolean flag = entityHost.getSensing().hasLineOfSight(attackTarget); if (flag) { ++seeTime; } else { seeTime = 0; } if (d0 <= (double) shootCutoffRangeSqr && seeTime >= 20) { //this.entityHost.getNavigation().clearPathEntity(); } else { //this.entityHost.getNavigation().tryMoveToEntityLiving(this.attackTarget, this.entityMoveSpeed); } if (seeTime >= 20) { entityHost.getNavigation().moveTo(attackTarget, entityMoveSpeed); } entityHost.getLookControl().setLookAt(attackTarget, 30.0f, 30.0f); float f; //System.out.println(rangedAttackTime); if (--rangedAttackTime <= 0) { f = Mth.sqrt((float) d0) / shootCutoffRange; float f1 = f; if (f < 0.1f) { f1 = 0.1f; } if (f1 > 1.0f) { f1 = 1.0f; } if (d0 >= (double) shootCutoffRange * (double) shootCutoffRange) { rangedAttackEntityHost.performRangedAttack(attackTarget, f1); rangedAttackTime = maxRangedAttackTime; } else if (d0 <= meleeHitRange * meleeHitRange) { entityHost.doHurtTarget(getServerLevel(entityHost), attackTarget); entityHost.swing(InteractionHand.MAIN_HAND); rangedAttackTime = maxMeleeAttackTime; } } } }
412
0.926153
1
0.926153
game-dev
MEDIA
0.979238
game-dev
0.94211
1
0.94211
OpenMW/openmw
3,705
components/esm4/loadbptd.hpp
/* Copyright (C) 2019, 2020 cc9cii 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. cc9cii cc9c@iinet.net.au Much of the information on the data structures are based on the information from Tes4Mod:Mod_File_Format and Tes5Mod:File_Formats but also refined by trial & error. See http://en.uesp.net/wiki for details. */ #ifndef ESM4_BPTD_H #define ESM4_BPTD_H #include <cstdint> #include <string> #include <vector> #include <components/esm/defs.hpp> #include <components/esm/formid.hpp> namespace ESM4 { class Reader; class Writer; struct BodyPartData { #pragma pack(push, 1) struct BPND { float damageMult; // Severable // IK Data // IK Data - Biped Data // Explodable // IK Data - Is Head // IK Data - Headtracking // To Hit Chance - Absolute std::uint8_t flags; // Torso // Head // Eye // LookAt // Fly Grab // Saddle std::uint8_t partType; std::uint8_t healthPercent; std::int8_t actorValue; //(Actor Values) std::uint8_t toHitChance; std::uint8_t explExplosionChance; // % std::uint16_t explDebrisCount; ESM::FormId32 explDebris; ESM::FormId32 explExplosion; float trackingMaxAngle; float explDebrisScale; std::int32_t sevDebrisCount; ESM::FormId32 sevDebris; ESM::FormId32 sevExplosion; float sevDebrisScale; // Struct - Gore Effects Positioning float transX; float transY; float transZ; float rotX; float rotY; float rotZ; ESM::FormId32 sevImpactDataSet; ESM::FormId32 explImpactDataSet; uint8_t sevDecalCount; uint8_t explDecalCount; uint16_t Unknown; float limbReplacementScale; }; #pragma pack(pop) struct BodyPart { std::string mPartName; std::string mNodeName; std::string mVATSTarget; std::string mIKStartNode; BPND mData; std::string mLimbReplacementModel; std::string mGoreEffectsTarget; void clear(); }; ESM::FormId mId; // from the header std::uint32_t mFlags; // from the header, see enum type RecordFlag for details std::string mEditorId; std::string mFullName; std::string mModel; std::vector<BodyPart> mBodyParts; void load(ESM4::Reader& reader); // void save(ESM4::Writer& writer) const; // void blank(); static constexpr ESM::RecNameInts sRecordId = ESM::RecNameInts::REC_BPTD4; }; } #endif // ESM4_BPTD_H
412
0.908569
1
0.908569
game-dev
MEDIA
0.291554
game-dev
0.599568
1
0.599568
SDHK/WorldTreeFramework
2,075
UnityTool/Analysis/ProjectGeneratorSetting.cs
/**************************************** * 作者:闪电黑客 * 日期:2025/6/13 14:42 * 描述: */ using System; using System.Collections.Generic; namespace WorldTree.SourceGenerator { /// <summary> /// 生成器设置 /// </summary> public static class ProjectConfigHelper { public static HashSet<Type> CoreConfigs = new() { typeof(BranchSupplementGeneratorRun) , typeof(INodeProxyGeneratorRun), typeof(NodeExtensionMethodGeneratorRun), typeof(NodeBranchHelperGeneratorRun), typeof(RuleClassGeneratorRun), typeof(RuleSupplementGeneratorRun), typeof(RuleMethodGeneratorRun), typeof(RuleExtensionMethodGeneratorRun), typeof(TreeCopyGeneratorRun), typeof(TreeDataSerializeGeneratorRun), typeof(TreePackSerializeGeneratorRun), }; public static HashSet<Type> UnityCoreConfigs = new() { typeof(INodeProxyGeneratorRun), typeof(RuleSupplementGeneratorRun), typeof(RuleMethodGeneratorRun), typeof(TreeCopyGeneratorRun), typeof(TreeDataSerializeGeneratorRun), typeof(TreePackSerializeGeneratorRun), }; public static HashSet<Type> NodeConfigs = new() { typeof(INodeProxyGeneratorRun), typeof(RuleSupplementGeneratorRun), typeof(TreeCopyGeneratorRun), typeof(TreeDataSerializeGeneratorRun), typeof(TreePackSerializeGeneratorRun), }; public static HashSet<Type> RuleConfigs = new() { typeof(RuleMethodGeneratorRun), }; } /// <summary> /// Unity环境配置 /// </summary> public class ProjectGeneratorSetting : ProjectGeneratorsConfig { public ProjectGeneratorSetting() { ArgumentCount = 5; Add("WorldTree.Core", ProjectConfigHelper.CoreConfigs); Add("WorldTree.ModuleNode", ProjectConfigHelper.NodeConfigs); Add("WorldTree.ModuleRule", ProjectConfigHelper.RuleConfigs); Add("WorldTree.UnityCore", ProjectConfigHelper.UnityCoreConfigs); Add("WorldTree.Node", ProjectConfigHelper.NodeConfigs); Add("WorldTree.Rule", ProjectConfigHelper.RuleConfigs); Add("WorldTree.UnityNode", ProjectConfigHelper.NodeConfigs); Add("WorldTree.UnityRule", ProjectConfigHelper.RuleConfigs); } } }
412
0.841911
1
0.841911
game-dev
MEDIA
0.771874
game-dev
0.780638
1
0.780638
LandSandBoat/server
1,137
scripts/actions/mobskills/pet_hydro_breath.lua
----------------------------------- -- Hydro Breath -- Family: Pet Wyverns -- Description: Deals Water breath damage to enemies within a fan-shaped area originating from the caster. ----------------------------------- ---@type TMobSkill local mobskillObject = {} mobskillObject.onMobSkillCheck = function(target, mob, skill) return 0 end mobskillObject.onMobWeaponSkill = function(target, mob, skill) local params = {} params.percentMultipier = 0.13 params.element = xi.element.WATER params.damageCap = 400 -- TODO: Capture cap. params.bonusDamage = 0 params.mAccuracyBonus = { 0, 0, 0 } params.resistStat = xi.mod.INT local damage = xi.mobskills.mobBreathMove(mob, target, skill, params) damage = xi.mobskills.mobFinalAdjustments(damage, mob, skill, target, xi.attackType.BREATH, xi.damageType.WATER, xi.mobskills.shadowBehavior.IGNORE_SHADOWS, 1) if not xi.mobskills.hasMissMessage(mob, target, skill, damage) then target:takeDamage(damage, mob, xi.attackType.BREATH, xi.damageType.WATER) end return damage end return mobskillObject
412
0.887819
1
0.887819
game-dev
MEDIA
0.977936
game-dev
0.754468
1
0.754468
unrealcv/unrealcv
2,934
Source/UnrealCV/UnrealCV.Build.cs
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. using System.IO; using System.Collections.Generic; // An engine version independent configuration class public class UnrealcvBuildConfig { public List<string> PrivateIncludePaths = new List<string>(); public List<string> PublicIncludePaths = new List<string>(); public List<string> PublicDependencyModuleNames = new List<string>(); public List<string> EditorPrivateDependencyModuleNames = new List<string>(); public List<string> DynamicallyLoadedModuleNames = new List<string>(); public UnrealcvBuildConfig(string EnginePath) { PublicIncludePaths.AddRange( new string[] { } ); PrivateIncludePaths.AddRange( new string[] { "UnrealCV/Private", "UnrealCV/Private/Actor", "UnrealCV/Public/Actor", "UnrealCV/Public/BPFunctionLib", "UnrealCV/Public/Component", "UnrealCV/Public/Controller", "UnrealCV/Public/Sensor", "UnrealCV/Public/Sensor/CameraSensor", "UnrealCV/Public/Server", "UnrealCV/Public/Utils" } ); PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "RenderCore", "Networking", "Sockets", "Slate", "ImageWrapper", "CinematicCamera", "Projects", // Support IPluginManager "RHI", // Support low-level RHI operation "Json", }); EditorPrivateDependencyModuleNames.AddRange( new string[] { "UnrealEd", // To support GetGameWorld // This is only available for Editor build } ); DynamicallyLoadedModuleNames.AddRange( new string[] { "Renderer" } ); } } namespace UnrealBuildTool.Rules { public class UnrealCV: ModuleRules { // ReadOnlyTargetRules for version > 4.15 public UnrealCV(ReadOnlyTargetRules Target) : base(Target) // 4.16 or better { //bEnforceIWYU = true; //bFasterWithoutUnity = true; PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; // This trick is from https://answers.unrealengine.com/questions/258689/how-to-include-private-header-files-of-other-modul.html // string EnginePath = Path.GetFullPath(BuildConfigurationTarget.RelativeEnginePath); string EnginePath = Path.GetFullPath(Target.RelativeEnginePath); UnrealcvBuildConfig BuildConfig = new UnrealcvBuildConfig(EnginePath); PublicIncludePaths = BuildConfig.PublicIncludePaths; PrivateIncludePaths = BuildConfig.PrivateIncludePaths; PublicDependencyModuleNames = BuildConfig.PublicDependencyModuleNames; DynamicallyLoadedModuleNames = BuildConfig.DynamicallyLoadedModuleNames; // PrivateDependency only available in Private folder // Reference: https://answers.unrealengine.com/questions/23384/what-is-the-difference-between-publicdependencymod.html // if (UEBuildConfiguration.bBuildEditor == true) if (Target.bBuildEditor == true) { PrivateDependencyModuleNames = BuildConfig.EditorPrivateDependencyModuleNames; } } } }
412
0.87394
1
0.87394
game-dev
MEDIA
0.728077
game-dev
0.513346
1
0.513346
AcademySoftwareFoundation/OpenRV
2,553
src/lib/app/TwkApp/EventTable.cpp
//****************************************************************************** // Copyright (c) 2004 Tweak Inc. // All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // //****************************************************************************** #include <TwkApp/EventTable.h> #include <iostream> #include <algorithm> namespace TwkApp { using namespace std; using namespace TwkUtil; EventTable::EventTable(const string& name) : m_name(name) , m_mode(0) { m_bbox.makeInfinite(); } EventTable::EventTable(const char* name) : m_name(name) , m_mode(0) { m_bbox.makeInfinite(); } EventTable::~EventTable() { clear(); } void EventTable::bind(const std::string& event, Action* action) { unbind(event); m_map[event] = action; } void EventTable::bindRegex(const std::string& eventRegex, Action* action) { unbindRegex(eventRegex); m_reBindings.push_back(RegExBinding(eventRegex, action)); } void EventTable::unbind(const std::string& event) { BindingMap::iterator i = m_map.find(event); if (i != m_map.end()) { delete (*i).second; m_map.erase(i); } } void EventTable::unbindRegex(const std::string& eventRegex) { for (int i = 0; i < m_reBindings.size(); i++) { if (m_reBindings[i].first.pattern() == eventRegex) { m_reBindings.erase(m_reBindings.begin() + i); i--; } } } static void deleteAction(EventTable::Binding& b) { delete b.second; } void EventTable::clear() { for_each(m_map.begin(), m_map.end(), deleteAction); m_map.clear(); for (int i = 0; i < m_reBindings.size(); i++) { delete m_reBindings[i].second; } m_reBindings.clear(); } const Action* EventTable::query(const string& event) const { BindingMap::const_iterator i = m_map.find(event); if (i != m_map.end()) { return (*i).second; } else if (m_reBindings.empty()) { return 0; } else { for (int i = 0; i < m_reBindings.size(); i++) { if (Match(m_reBindings[i].first, event)) { return m_reBindings[i].second; } } } return 0; } } // namespace TwkApp
412
0.841279
1
0.841279
game-dev
MEDIA
0.533796
game-dev
0.892049
1
0.892049
kokole/SteamItemDropIdler
11,998
SteamItemDropIdler/Open Steamworks/Open Steamworks/MatchmakingCommon.h
//========================== Open Steamworks ================================ // // This file is part of the Open Steamworks project. All individuals associated // with this project do not claim ownership of the contents // // The code, comments, and all related files, projects, resources, // redistributables included with this project are Copyright Valve Corporation. // Additionally, Valve, the Valve logo, Half-Life, the Half-Life logo, the // Lambda logo, Steam, the Steam logo, Team Fortress, the Team Fortress logo, // Opposing Force, Day of Defeat, the Day of Defeat logo, Counter-Strike, the // Counter-Strike logo, Source, the Source logo, and Counter-Strike Condition // Zero are trademarks and or registered trademarks of Valve Corporation. // All other trademarks are property of their respective owners. // //============================================================================= #ifndef MATCHMAKINGCOMMON_H #define MATCHMAKINGCOMMON_H #ifdef _WIN32 #pragma once #endif #include "FriendsCommon.h" #define CLIENTMATCHMAKING_INTERFACE_VERSION "CLIENTMATCHMAKING_INTERFACE_VERSION001" #define STEAMMATCHMAKING_INTERFACE_VERSION_001 "SteamMatchMaking001" #define STEAMMATCHMAKING_INTERFACE_VERSION_002 "SteamMatchMaking002" #define STEAMMATCHMAKING_INTERFACE_VERSION_003 "SteamMatchMaking003" #define STEAMMATCHMAKING_INTERFACE_VERSION_004 "SteamMatchMaking004" #define STEAMMATCHMAKING_INTERFACE_VERSION_005 "SteamMatchMaking005" #define STEAMMATCHMAKING_INTERFACE_VERSION_006 "SteamMatchMaking006" #define STEAMMATCHMAKING_INTERFACE_VERSION_007 "SteamMatchMaking007" #define STEAMMATCHMAKING_INTERFACE_VERSION_008 "SteamMatchMaking008" #define STEAMMATCHMAKING_INTERFACE_VERSION_009 "SteamMatchMaking009" // lobby search filter tools enum ELobbyComparison { k_ELobbyComparisonEqualToOrLessThan = -2, k_ELobbyComparisonLessThan = -1, k_ELobbyComparisonEqual = 0, k_ELobbyComparisonGreaterThan = 1, k_ELobbyComparisonEqualToOrGreaterThan = 2, k_ELobbyComparisonNotEqual = 3, }; // lobby search distance enum ELobbyDistanceFilter { k_ELobbyDistanceFilterClose, // only lobbies in the same immediate region will be returned k_ELobbyDistanceFilterDefault, // only lobbies in the same region or close, but looking further if the current region has infrequent lobby activity (the default) k_ELobbyDistanceFilterFar, // for games that don't have many latency requirements, will return lobbies about half-way around the globe k_ELobbyDistanceFilterWorldwide, // no filtering, will match lobbies as far as India to NY (not recommended, expect multiple seconds of latency between the clients) }; // maximum number of characters a lobby metadata key can be #define k_nMaxLobbyKeyLength 255 typedef int HServerQuery; const int HSERVERQUERY_INVALID = 0xffffffff; // game server flags const uint32 k_unFavoriteFlagNone = 0x00; const uint32 k_unFavoriteFlagFavorite = 0x01; // this game favorite entry is for the favorites list const uint32 k_unFavoriteFlagHistory = 0x02; // this game favorite entry is for the history list #pragma pack( push, 8 ) //----------------------------------------------------------------------------- // Purpose: a server was added/removed from the favorites list, you should refresh now //----------------------------------------------------------------------------- struct FavoritesListChangedOld_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 1 }; }; //----------------------------------------------------------------------------- // Purpose: a server was added/removed from the favorites list, you should refresh now //----------------------------------------------------------------------------- struct FavoritesListChanged_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 2 }; uint32 m_nIP; // an IP of 0 means reload the whole list, any other value means just one server uint32 m_nQueryPort; uint32 m_nConnPort; AppId_t m_nAppID; uint32 m_nFlags; bool m_bAdd; // true if this is adding the entry, otherwise it is a remove }; //----------------------------------------------------------------------------- // Purpose: Someone has invited you to join a Lobby // normally you don't need to do anything with this, since // the Steam UI will also display a '<user> has invited you to the lobby, join?' dialog // // if the user outside a game chooses to join, your game will be launched with the parameter "+connect_lobby <64-bit lobby id>", // or with the callback GameLobbyJoinRequested_t if they're already in-game //----------------------------------------------------------------------------- struct LobbyInvite_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 3 }; CSteamID m_ulSteamIDUser; // Steam ID of the person making the invite CSteamID m_ulSteamIDLobby; // Steam ID of the Lobby CGameID m_ulGameID; // GameID of the Lobby }; //----------------------------------------------------------------------------- // Purpose: Sent on entering a lobby, or on failing to enter // m_EChatRoomEnterResponse will be set to k_EChatRoomEnterResponseSuccess on success, // or a higher value on failure (see enum EChatRoomEnterResponse) //----------------------------------------------------------------------------- struct LobbyEnter_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 4 }; CSteamID m_ulSteamIDLobby; // SteamID of the Lobby you have entered EChatPermission m_rgfChatPermissions; // Permissions of the current user bool m_bLocked; // If true, then only invited users may join EChatRoomEnterResponse m_EChatRoomEnterResponse; // EChatRoomEnterResponse }; //----------------------------------------------------------------------------- // Purpose: The lobby metadata has changed // if m_ulSteamIDMember is the steamID of a lobby member, use GetLobbyMemberData() to access per-user details // if m_ulSteamIDMember == m_ulSteamIDLobby, use GetLobbyData() to access lobby metadata //----------------------------------------------------------------------------- struct LobbyDataUpdate_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 5 }; CSteamID m_ulSteamIDLobby; // steamID of the Lobby CSteamID m_ulSteamIDMember; // steamID of the member whose data changed, or the room itself uint8 m_bSuccess; }; //----------------------------------------------------------------------------- // Purpose: The lobby chat room state has changed // this is usually sent when a user has joined or left the lobby //----------------------------------------------------------------------------- struct LobbyChatUpdate_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 6 }; CSteamID m_ulSteamIDLobby; // Lobby ID CSteamID m_ulSteamIDUserChanged; // user who's status in the lobby just changed - can be recipient CSteamID m_ulSteamIDMakingChange; // Chat member who made the change (different from SteamIDUserChange if kicking, muting, etc.) // for example, if one user kicks another from the lobby, this will be set to the id of the user who initiated the kick EChatMemberStateChange m_rgfChatMemberStateChange; // bitfield of EChatMemberStateChange values }; //----------------------------------------------------------------------------- // Purpose: A chat message for this lobby has been sent // use GetLobbyChatEntry( m_iChatID ) to retrieve the contents of this message //----------------------------------------------------------------------------- struct LobbyChatMsg_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 7 }; uint64 m_ulSteamIDLobby; // the lobby id this is in uint64 m_ulSteamIDUser; // steamID of the user who has sent this message uint8 m_eChatEntryType; // type of message uint32 m_iChatID; // index of the chat entry to lookup }; //----------------------------------------------------------------------------- // Purpose: There's a change of Admin in this Lobby //----------------------------------------------------------------------------- struct OBSOLETE_CALLBACK LobbyAdminChange_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 8 }; CSteamID m_ulSteamIDLobby; CSteamID m_ulSteamIDNewAdmin; }; //----------------------------------------------------------------------------- // Purpose: A game created a game for all the members of the lobby to join, // as triggered by a SetLobbyGameServer() // it's up to the individual clients to take action on this; the usual // game behavior is to leave the lobby and connect to the specified game server //----------------------------------------------------------------------------- struct LobbyGameCreated_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 9 }; CSteamID m_ulSteamIDLobby; // the lobby we were in CSteamID m_ulSteamIDGameServer; // the new game server that has been created or found for the lobby members uint32 m_unIP; // IP & Port of the game server (if any) uint16 m_usPort; }; //----------------------------------------------------------------------------- // Purpose: Number of matching lobbies found // iterate the returned lobbies with GetLobbyByIndex(), from values 0 to m_nLobbiesMatching-1 //----------------------------------------------------------------------------- struct LobbyMatchList_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 10 }; uint32 m_nLobbiesMatching; // Number of lobbies that matched search criteria and we have SteamIDs for }; //----------------------------------------------------------------------------- // Purpose: Called when the lobby is being forcefully closed // lobby details functions will no longer be updated //----------------------------------------------------------------------------- struct LobbyClosing_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 11 }; CSteamID m_ulSteamIDLobby; // Lobby }; //----------------------------------------------------------------------------- // Purpose: posted if a user is forcefully removed from a lobby // can occur if a user loses connection to Steam //----------------------------------------------------------------------------- struct LobbyKicked_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 12 }; uint64 m_ulSteamIDLobby; // Lobby uint64 m_ulSteamIDAdmin; // User who kicked you - possibly the ID of the lobby itself uint8 m_bKickedDueToDisconnect; // true if you were kicked from the lobby due to the user losing connection to Steam (currently always true) }; //----------------------------------------------------------------------------- // Purpose: Result of our request to create a Lobby // m_eResult == k_EResultOK on success // at this point, the local user may not have finishing joining this lobby; // game code should wait until the subsequent LobbyEnter_t callback is received //----------------------------------------------------------------------------- struct LobbyCreated_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 13 }; EResult m_eResult; // k_EResultOK - the lobby was successfully created // k_EResultNoConnection - your Steam client doesn't have a connection to the back-end // k_EResultTimeout - you the message to the Steam servers, but it didn't respond // k_EResultFail - the server responded, but with an unknown internal error // k_EResultAccessDenied - your game isn't set to allow lobbies, or your client does haven't rights to play the game // k_EResultLimitExceeded - your game client has created too many lobbies uint64 m_ulSteamIDLobby; // chat room, zero if failed }; struct RequestFriendsLobbiesResponse_t { enum { k_iCallback = k_iSteamMatchmakingCallbacks + 14 }; uint64 m_ulSteamIDFriend; uint64 m_ulSteamIDLobby; int m_cResultIndex; int m_cResultsTotal; }; struct GMSQueryResult_t { uint32 uServerIP; uint32 uServerPort; int32 nAuthPlayers; }; struct PingSample_t { // TODO: Reverse this struct #ifdef _S4N_ int m_iPadding; #endif }; #pragma pack( pop ) #endif // MATCHMAKINGCOMMON_H
412
0.581225
1
0.581225
game-dev
MEDIA
0.836744
game-dev,networking
0.614907
1
0.614907
HANON-games/Shiden
2,273
Source/ShidenCore/Public/Sample/ShidenSaveMenuInterface.h
// Copyright (c) 2025 HANON. All Rights Reserved. #pragma once #include "UObject/Interface.h" #include "ShidenSaveMenuInterface.generated.h" /* * This is an interface used in the sample implementation. * It is not referenced from the core implementation of Shiden, so it is not necessarily required to use it. */ UINTERFACE(MinimalAPI, Blueprintable) class UShidenSaveMenuInterface : public UInterface { GENERATED_BODY() }; DECLARE_DYNAMIC_DELEGATE_OneParam(FOnSaveSlotSelectedDelegate, const FString&, SlotName); DECLARE_DYNAMIC_DELEGATE_OneParam(FOnLoadSlotSelectedDelegate, const FString&, SlotName); class SHIDENCORE_API IShidenSaveMenuInterface { GENERATED_BODY() public: /** * Initializes the save menu widget with a callback delegate for save slot selection. * @param OnSaveSlotSelected Delegate called when a save slot is selected for saving */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget", meta = (AutoCreateRefTerm = "OnSaveCompleted")) void InitSaveMenu(const FOnSaveSlotSelectedDelegate& OnSaveSlotSelected); /** * Initializes the load menu widget with a callback delegate for load slot selection. * @param OnLoadSlotSelected Delegate called when a save slot is selected for loading */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget", meta = (AutoCreateRefTerm = "OnLoadCompleted")) void InitLoadMenu(const FOnLoadSlotSelectedDelegate& OnLoadSlotSelected); /** * Saves the current game state to the specified save slot. * @param SlotName The name of the save slot to save to */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget") void SaveToSlot(const FString& SlotName); /** * Loads game state from the specified save slot. * @param SlotName The name of the save slot to load from */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget") void LoadFromSlot(const FString& SlotName); /** * Deletes the save data in the specified save slot. * @param SlotName The name of the save slot to delete */ UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Shiden Visual Novel|Widget") void DeleteSlot(const FString& SlotName); };
412
0.945743
1
0.945743
game-dev
MEDIA
0.716457
game-dev
0.851513
1
0.851513
hutian23/ETScript
1,354
Unity/Assets/Scripts/Codes/HotfixView/Client/Demo/Battle/ScriptHandler/Main/Function_EnableAirMoveX_BBScriptHandler.cs
using System.Text.RegularExpressions; namespace ET.Client { [FriendOf(typeof(AirMoveXComponent))] public class Function_EnableAirMoveX_BBScriptHandler : BBScriptHandler { public override string GetOPType() { return "EnableAirMoveX"; } //EnableAirMove: 水平移动速度, 启动 / 关闭 //EnableAirMove: MoveX, Enable; public override async ETTask<Status> Handle(BBParser parser, BBScriptData data, ETCancellationToken token) { Match match = Regex.Match(data.opLine, @"EnableAirMoveX: (?<MoveX>.*?), (?<Enable>\w+);"); if (!match.Success) { ScriptHelper.ScripMatchError(data.opLine); return Status.Failed; } if (!long.TryParse(match.Groups["MoveX"].Value, out long moveX)) { Log.Error($"cannot format {match.Groups["MoveX"].Value} to long"); return Status.Failed; } //1. 初始化 parser.RemoveComponent<AirMoveXComponent>(); //2. 启动AirMove协程 if (match.Groups["Enable"].Value.Equals("true")) { parser.AddComponent<AirMoveXComponent, float>(moveX / 10000f, true); } await ETTask.CompletedTask; return Status.Success; } } }
412
0.887971
1
0.887971
game-dev
MEDIA
0.385246
game-dev
0.932109
1
0.932109
beyond-aion/aion-server
2,042
game-server/src/com/aionemu/gameserver/network/aion/serverpackets/SM_ABNORMAL_EFFECT.java
package com.aionemu.gameserver.network.aion.serverpackets; import java.util.Collection; import java.util.stream.Collectors; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.AionConnection; import com.aionemu.gameserver.network.aion.AionServerPacket; import com.aionemu.gameserver.skillengine.model.Effect; import com.aionemu.gameserver.skillengine.model.SkillTargetSlot; /** * @author ATracer */ public class SM_ABNORMAL_EFFECT extends AionServerPacket { private Creature effected; private int effectType; private int abnormals; private Collection<Effect> filtered; private int slots; public SM_ABNORMAL_EFFECT(Creature effected) { this(effected, effected.getEffectController().getAbnormals(), effected.getEffectController().getAbnormalEffects(), SkillTargetSlot.FULLSLOTS); } public SM_ABNORMAL_EFFECT(Creature effected, int abnormals, Collection<Effect> effects, int slots) { this.effected = effected; this.abnormals = abnormals; this.filtered = slots == SkillTargetSlot.FULLSLOTS ? effects : effects.stream().filter(e -> (slots & e.getTargetSlot().getId()) != 0).collect(Collectors.toList()); this.slots = slots; this.effectType = effected instanceof Player ? 2 : 1; } @Override @SuppressWarnings("fallthrough") protected void writeImpl(AionConnection con) { writeD(effected.getObjectId()); writeC(effectType); // unk writeD(0); // TODO time writeD(abnormals); // unk writeD(0); // unk writeC(slots); // 4.5 writeH(filtered.size()); // effects size for (Effect effect : filtered) { switch (effectType) { case 2: writeD(effect.getEffectorId()); // fall-through on purpose case 1: writeH(effect.getSkillId()); writeC(effect.getSkillLevel()); writeC(effect.getTargetSlot().ordinal()); writeD(effect.getRemainingTimeToDisplay()); break; default: writeH(effect.getSkillId()); writeC(effect.getSkillLevel()); } } } }
412
0.877476
1
0.877476
game-dev
MEDIA
0.946338
game-dev
0.973352
1
0.973352
oot-pc-port/oot-pc-port
69,628
asm/non_matchings/overlays/actors/ovl_Boss_Goma/func_80917D98.s
glabel func_80917D98 /* 02388 80917D98 27BDFF40 */ addiu $sp, $sp, 0xFF40 ## $sp = FFFFFF40 /* 0238C 80917D9C 3C0F8092 */ lui $t7, %hi(D_8091B2D8) ## $t7 = 80920000 /* 02390 80917DA0 AFBF0044 */ sw $ra, 0x0044($sp) /* 02394 80917DA4 AFB30040 */ sw $s3, 0x0040($sp) /* 02398 80917DA8 AFB2003C */ sw $s2, 0x003C($sp) /* 0239C 80917DAC AFB10038 */ sw $s1, 0x0038($sp) /* 023A0 80917DB0 AFB00034 */ sw $s0, 0x0034($sp) /* 023A4 80917DB4 25EFB2D8 */ addiu $t7, $t7, %lo(D_8091B2D8) ## $t7 = 8091B2D8 /* 023A8 80917DB8 8DF90000 */ lw $t9, 0x0000($t7) ## 8091B2D8 /* 023AC 80917DBC 27AE00A8 */ addiu $t6, $sp, 0x00A8 ## $t6 = FFFFFFE8 /* 023B0 80917DC0 8DF80004 */ lw $t8, 0x0004($t7) ## 8091B2DC /* 023B4 80917DC4 ADD90000 */ sw $t9, 0x0000($t6) ## FFFFFFE8 /* 023B8 80917DC8 8DF90008 */ lw $t9, 0x0008($t7) ## 8091B2E0 /* 023BC 80917DCC 3C098092 */ lui $t1, %hi(D_8091B2E4) ## $t1 = 80920000 /* 023C0 80917DD0 2529B2E4 */ addiu $t1, $t1, %lo(D_8091B2E4) ## $t1 = 8091B2E4 /* 023C4 80917DD4 ADD80004 */ sw $t8, 0x0004($t6) ## FFFFFFEC /* 023C8 80917DD8 ADD90008 */ sw $t9, 0x0008($t6) ## FFFFFFF0 /* 023CC 80917DDC 8D2B0000 */ lw $t3, 0x0000($t1) ## 8091B2E4 /* 023D0 80917DE0 27A8009C */ addiu $t0, $sp, 0x009C ## $t0 = FFFFFFDC /* 023D4 80917DE4 8D2A0004 */ lw $t2, 0x0004($t1) ## 8091B2E8 /* 023D8 80917DE8 AD0B0000 */ sw $t3, 0x0000($t0) ## FFFFFFDC /* 023DC 80917DEC 8D2B0008 */ lw $t3, 0x0008($t1) ## 8091B2EC /* 023E0 80917DF0 AD0A0004 */ sw $t2, 0x0004($t0) ## FFFFFFE0 /* 023E4 80917DF4 3C0C8092 */ lui $t4, %hi(D_8091B2F0) ## $t4 = 80920000 /* 023E8 80917DF8 AD0B0008 */ sw $t3, 0x0008($t0) ## FFFFFFE4 /* 023EC 80917DFC 3C0D8092 */ lui $t5, %hi(D_8091B2F4) ## $t5 = 80920000 /* 023F0 80917E00 8D8CB2F0 */ lw $t4, %lo(D_8091B2F0)($t4) /* 023F4 80917E04 8DADB2F4 */ lw $t5, %lo(D_8091B2F4)($t5) /* 023F8 80917E08 3C0F8092 */ lui $t7, %hi(D_8091B2F8) ## $t7 = 80920000 /* 023FC 80917E0C 25EFB2F8 */ addiu $t7, $t7, %lo(D_8091B2F8) ## $t7 = 8091B2F8 /* 02400 80917E10 AFAC0098 */ sw $t4, 0x0098($sp) /* 02404 80917E14 AFAD0094 */ sw $t5, 0x0094($sp) /* 02408 80917E18 8DF90000 */ lw $t9, 0x0000($t7) ## 8091B2F8 /* 0240C 80917E1C 27AE0088 */ addiu $t6, $sp, 0x0088 ## $t6 = FFFFFFC8 /* 02410 80917E20 8DF80004 */ lw $t8, 0x0004($t7) ## 8091B2FC /* 02414 80917E24 ADD90000 */ sw $t9, 0x0000($t6) ## FFFFFFC8 /* 02418 80917E28 8DF90008 */ lw $t9, 0x0008($t7) ## 8091B300 /* 0241C 80917E2C 3C098092 */ lui $t1, %hi(D_8091B304) ## $t1 = 80920000 /* 02420 80917E30 2529B304 */ addiu $t1, $t1, %lo(D_8091B304) ## $t1 = 8091B304 /* 02424 80917E34 ADD80004 */ sw $t8, 0x0004($t6) ## FFFFFFCC /* 02428 80917E38 ADD90008 */ sw $t9, 0x0008($t6) ## FFFFFFD0 /* 0242C 80917E3C 8D2B0000 */ lw $t3, 0x0000($t1) ## 8091B304 /* 02430 80917E40 27A8007C */ addiu $t0, $sp, 0x007C ## $t0 = FFFFFFBC /* 02434 80917E44 8D2A0004 */ lw $t2, 0x0004($t1) ## 8091B308 /* 02438 80917E48 AD0B0000 */ sw $t3, 0x0000($t0) ## FFFFFFBC /* 0243C 80917E4C 8D2B0008 */ lw $t3, 0x0008($t1) ## 8091B30C /* 02440 80917E50 AD0A0004 */ sw $t2, 0x0004($t0) ## FFFFFFC0 /* 02444 80917E54 00809025 */ or $s2, $a0, $zero ## $s2 = 00000000 /* 02448 80917E58 AD0B0008 */ sw $t3, 0x0008($t0) ## FFFFFFC4 /* 0244C 80917E5C 8CAC1C44 */ lw $t4, 0x1C44($a1) ## 00001C44 /* 02450 80917E60 2490014C */ addiu $s0, $a0, 0x014C ## $s0 = 0000014C /* 02454 80917E64 00A09825 */ or $s3, $a1, $zero ## $s3 = 00000000 /* 02458 80917E68 02002025 */ or $a0, $s0, $zero ## $a0 = 0000014C /* 0245C 80917E6C 0C02927F */ jal SkelAnime_FrameUpdateMatrix /* 02460 80917E70 AFAC0068 */ sw $t4, 0x0068($sp) /* 02464 80917E74 264400B4 */ addiu $a0, $s2, 0x00B4 ## $a0 = 000000B4 /* 02468 80917E78 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 0246C 80917E7C 24060002 */ addiu $a2, $zero, 0x0002 ## $a2 = 00000002 /* 02470 80917E80 0C01E1EF */ jal Math_SmoothScaleMaxS /* 02474 80917E84 24070BB8 */ addiu $a3, $zero, 0x0BB8 ## $a3 = 00000BB8 /* 02478 80917E88 02002025 */ or $a0, $s0, $zero ## $a0 = 0000014C /* 0247C 80917E8C 0C0295B2 */ jal func_800A56C8 /* 02480 80917E90 3C0542D6 */ lui $a1, 0x42D6 ## $a1 = 42D60000 /* 02484 80917E94 1040000A */ beq $v0, $zero, .L80917EC0 /* 02488 80917E98 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000 /* 0248C 80917E9C 02602825 */ or $a1, $s3, $zero ## $a1 = 00000000 /* 02490 80917EA0 00003025 */ or $a2, $zero, $zero ## $a2 = 00000000 /* 02494 80917EA4 0C24577E */ jal func_80915DF8 /* 02498 80917EA8 24070008 */ addiu $a3, $zero, 0x0008 ## $a3 = 00000008 /* 0249C 80917EAC 44806000 */ mtc1 $zero, $f12 ## $f12 = 0.00 /* 024A0 80917EB0 24050096 */ addiu $a1, $zero, 0x0096 ## $a1 = 00000096 /* 024A4 80917EB4 24060014 */ addiu $a2, $zero, 0x0014 ## $a2 = 00000014 /* 024A8 80917EB8 0C02A7DB */ jal func_800A9F6C /* 024AC 80917EBC 24070014 */ addiu $a3, $zero, 0x0014 ## $a3 = 00000014 .L80917EC0: /* 024B0 80917EC0 864201D2 */ lh $v0, 0x01D2($s2) ## 000001D2 /* 024B4 80917EC4 240D0002 */ addiu $t5, $zero, 0x0002 ## $t5 = 00000002 /* 024B8 80917EC8 240E0001 */ addiu $t6, $zero, 0x0001 ## $t6 = 00000001 /* 024BC 80917ECC 240103E9 */ addiu $at, $zero, 0x03E9 ## $at = 000003E9 /* 024C0 80917ED0 A64D01B8 */ sh $t5, 0x01B8($s2) ## 000001B8 /* 024C4 80917ED4 14410012 */ bne $v0, $at, .L80917F20 /* 024C8 80917ED8 A64E01B4 */ sh $t6, 0x01B4($s2) ## 000001B4 /* 024CC 80917EDC 3C028092 */ lui $v0, %hi(D_8091B244) ## $v0 = 80920000 /* 024D0 80917EE0 2442B244 */ addiu $v0, $v0, %lo(D_8091B244) ## $v0 = 8091B244 /* 024D4 80917EE4 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 /* 024D8 80917EE8 24030001 */ addiu $v1, $zero, 0x0001 ## $v1 = 00000001 /* 024DC 80917EEC 00517821 */ addu $t7, $v0, $s1 .L80917EF0: /* 024E0 80917EF0 91F80000 */ lbu $t8, 0x0000($t7) ## 00000000 /* 024E4 80917EF4 0251C821 */ addu $t9, $s2, $s1 /* 024E8 80917EF8 53000003 */ beql $t8, $zero, .L80917F08 /* 024EC 80917EFC 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000001 /* 024F0 80917F00 A3230758 */ sb $v1, 0x0758($t9) ## 00000758 /* 024F4 80917F04 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000002 .L80917F08: /* 024F8 80917F08 00118C00 */ sll $s1, $s1, 16 /* 024FC 80917F0C 00118C03 */ sra $s1, $s1, 16 /* 02500 80917F10 2A21005A */ slti $at, $s1, 0x005A /* 02504 80917F14 5420FFF6 */ bnel $at, $zero, .L80917EF0 /* 02508 80917F18 00517821 */ addu $t7, $v0, $s1 /* 0250C 80917F1C 864201D2 */ lh $v0, 0x01D2($s2) ## 000001D2 .L80917F20: /* 02510 80917F20 284104B0 */ slti $at, $v0, 0x04B0 /* 02514 80917F24 10200008 */ beq $at, $zero, .L80917F48 /* 02518 80917F28 2841044D */ slti $at, $v0, 0x044D /* 0251C 80917F2C 14200006 */ bne $at, $zero, .L80917F48 /* 02520 80917F30 30480007 */ andi $t0, $v0, 0x0007 ## $t0 = 00000004 /* 02524 80917F34 15000004 */ bne $t0, $zero, .L80917F48 /* 02528 80917F38 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 0252C 80917F3C 0C00A66B */ jal func_800299AC /* 02530 80917F40 26450038 */ addiu $a1, $s2, 0x0038 ## $a1 = 00000038 /* 02534 80917F44 864201D2 */ lh $v0, 0x01D2($s2) ## 000001D2 .L80917F48: /* 02538 80917F48 28410438 */ slti $at, $v0, 0x0438 /* 0253C 80917F4C 5020009B */ beql $at, $zero, .L809181BC /* 02540 80917F50 864201D0 */ lh $v0, 0x01D0($s2) ## 000001D0 /* 02544 80917F54 864901D0 */ lh $t1, 0x01D0($s2) ## 000001D0 /* 02548 80917F58 29210003 */ slti $at, $t1, 0x0003 /* 0254C 80917F5C 10200096 */ beq $at, $zero, .L809181B8 /* 02550 80917F60 2841042E */ slti $at, $v0, 0x042E /* 02554 80917F64 10200003 */ beq $at, $zero, .L80917F74 /* 02558 80917F68 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000 /* 0255C 80917F6C 0C00BE0A */ jal Audio_PlayActorSound2 /* 02560 80917F70 2405301C */ addiu $a1, $zero, 0x301C ## $a1 = 0000301C .L80917F74: /* 02564 80917F74 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 .L80917F78: /* 02568 80917F78 0C03F66B */ jal Math_Rand_ZeroOne ## Rand.Next() float /* 0256C 80917F7C 00000000 */ nop /* 02570 80917F80 3C0142AA */ lui $at, 0x42AA ## $at = 42AA0000 /* 02574 80917F84 44812000 */ mtc1 $at, $f4 ## $f4 = 85.00 /* 02578 80917F88 3C018092 */ lui $at, %hi(D_8091B52C) ## $at = 80920000 /* 0257C 80917F8C C430B52C */ lwc1 $f16, %lo(D_8091B52C)($at) /* 02580 80917F90 46040182 */ mul.s $f6, $f0, $f4 /* 02584 80917F94 3C0141A0 */ lui $at, 0x41A0 ## $at = 41A00000 /* 02588 80917F98 4600320D */ trunc.w.s $f8, $f6 /* 0258C 80917F9C 44024000 */ mfc1 $v0, $f8 /* 02590 80917FA0 00000000 */ nop /* 02594 80917FA4 00025C00 */ sll $t3, $v0, 16 /* 02598 80917FA8 000B6403 */ sra $t4, $t3, 16 /* 0259C 80917FAC 000C6880 */ sll $t5, $t4, 2 /* 025A0 80917FB0 01AC6823 */ subu $t5, $t5, $t4 /* 025A4 80917FB4 000D6880 */ sll $t5, $t5, 2 /* 025A8 80917FB8 024D7021 */ addu $t6, $s2, $t5 /* 025AC 80917FBC C5CA02AC */ lwc1 $f10, 0x02AC($t6) ## 000002AC /* 025B0 80917FC0 00021C00 */ sll $v1, $v0, 16 /* 025B4 80917FC4 00031C03 */ sra $v1, $v1, 16 /* 025B8 80917FC8 4610503C */ c.lt.s $f10, $f16 /* 025BC 80917FCC 00000000 */ nop /* 025C0 80917FD0 45020028 */ bc1fl .L80918074 /* 025C4 80917FD4 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000001 /* 025C8 80917FD8 44816000 */ mtc1 $at, $f12 ## $f12 = 20.00 /* 025CC 80917FDC 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 025D0 80917FE0 A7A300B6 */ sh $v1, 0x00B6($sp) /* 025D4 80917FE4 87A300B6 */ lh $v1, 0x00B6($sp) /* 025D8 80917FE8 3C014120 */ lui $at, 0x4120 ## $at = 41200000 /* 025DC 80917FEC 44816000 */ mtc1 $at, $f12 ## $f12 = 10.00 /* 025E0 80917FF0 00037880 */ sll $t7, $v1, 2 /* 025E4 80917FF4 01E37823 */ subu $t7, $t7, $v1 /* 025E8 80917FF8 000F7880 */ sll $t7, $t7, 2 /* 025EC 80917FFC 024F8021 */ addu $s0, $s2, $t7 /* 025F0 80918000 C61202A8 */ lwc1 $f18, 0x02A8($s0) ## 000003F4 /* 025F4 80918004 46009100 */ add.s $f4, $f18, $f0 /* 025F8 80918008 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 025FC 8091800C E7A40070 */ swc1 $f4, 0x0070($sp) /* 02600 80918010 C60602AC */ lwc1 $f6, 0x02AC($s0) ## 000003F8 /* 02604 80918014 3C0141A0 */ lui $at, 0x41A0 ## $at = 41A00000 /* 02608 80918018 44816000 */ mtc1 $at, $f12 ## $f12 = 20.00 /* 0260C 8091801C 46003200 */ add.s $f8, $f6, $f0 /* 02610 80918020 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 02614 80918024 E7A80074 */ swc1 $f8, 0x0074($sp) /* 02618 80918028 C60A02B0 */ lwc1 $f10, 0x02B0($s0) ## 000003FC /* 0261C 8091802C 27B80098 */ addiu $t8, $sp, 0x0098 ## $t8 = FFFFFFD8 /* 02620 80918030 27B90094 */ addiu $t9, $sp, 0x0094 ## $t9 = FFFFFFD4 /* 02624 80918034 46005400 */ add.s $f16, $f10, $f0 /* 02628 80918038 240801F4 */ addiu $t0, $zero, 0x01F4 ## $t0 = 000001F4 /* 0262C 8091803C 2409000A */ addiu $t1, $zero, 0x000A ## $t1 = 0000000A /* 02630 80918040 240A000A */ addiu $t2, $zero, 0x000A ## $t2 = 0000000A /* 02634 80918044 E7B00078 */ swc1 $f16, 0x0078($sp) /* 02638 80918048 AFAA0020 */ sw $t2, 0x0020($sp) /* 0263C 8091804C AFA9001C */ sw $t1, 0x001C($sp) /* 02640 80918050 AFA80018 */ sw $t0, 0x0018($sp) /* 02644 80918054 AFB90014 */ sw $t9, 0x0014($sp) /* 02648 80918058 AFB80010 */ sw $t8, 0x0010($sp) /* 0264C 8091805C 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02650 80918060 27A50070 */ addiu $a1, $sp, 0x0070 ## $a1 = FFFFFFB0 /* 02654 80918064 27A600A8 */ addiu $a2, $sp, 0x00A8 ## $a2 = FFFFFFE8 /* 02658 80918068 0C00A0DB */ jal func_8002836C /* 0265C 8091806C 27A7009C */ addiu $a3, $sp, 0x009C ## $a3 = FFFFFFDC /* 02660 80918070 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000002 .L80918074: /* 02664 80918074 00118C00 */ sll $s1, $s1, 16 /* 02668 80918078 00118C03 */ sra $s1, $s1, 16 /* 0266C 8091807C 2A210004 */ slti $at, $s1, 0x0004 /* 02670 80918080 1420FFBD */ bne $at, $zero, .L80917F78 /* 02674 80918084 00000000 */ nop /* 02678 80918088 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 .L8091808C: /* 0267C 8091808C 0C03F66B */ jal Math_Rand_ZeroOne ## Rand.Next() float /* 02680 80918090 00000000 */ nop /* 02684 80918094 3C0142AA */ lui $at, 0x42AA ## $at = 42AA0000 /* 02688 80918098 44819000 */ mtc1 $at, $f18 ## $f18 = 85.00 /* 0268C 8091809C 3C018092 */ lui $at, %hi(D_8091B530) ## $at = 80920000 /* 02690 809180A0 C42AB530 */ lwc1 $f10, %lo(D_8091B530)($at) /* 02694 809180A4 46120102 */ mul.s $f4, $f0, $f18 /* 02698 809180A8 3C0141A0 */ lui $at, 0x41A0 ## $at = 41A00000 /* 0269C 809180AC 4600218D */ trunc.w.s $f6, $f4 /* 026A0 809180B0 44023000 */ mfc1 $v0, $f6 /* 026A4 809180B4 00000000 */ nop /* 026A8 809180B8 00026400 */ sll $t4, $v0, 16 /* 026AC 809180BC 000C6C03 */ sra $t5, $t4, 16 /* 026B0 809180C0 000D7080 */ sll $t6, $t5, 2 /* 026B4 809180C4 01CD7023 */ subu $t6, $t6, $t5 /* 026B8 809180C8 000E7080 */ sll $t6, $t6, 2 /* 026BC 809180CC 024E7821 */ addu $t7, $s2, $t6 /* 026C0 809180D0 C5E802AC */ lwc1 $f8, 0x02AC($t7) ## 000002AC /* 026C4 809180D4 00021C00 */ sll $v1, $v0, 16 /* 026C8 809180D8 00031C03 */ sra $v1, $v1, 16 /* 026CC 809180DC 460A403C */ c.lt.s $f8, $f10 /* 026D0 809180E0 00000000 */ nop /* 026D4 809180E4 4502002F */ bc1fl .L809181A4 /* 026D8 809180E8 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000001 /* 026DC 809180EC 44816000 */ mtc1 $at, $f12 ## $f12 = 20.00 /* 026E0 809180F0 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 026E4 809180F4 A7A300B6 */ sh $v1, 0x00B6($sp) /* 026E8 809180F8 87A300B6 */ lh $v1, 0x00B6($sp) /* 026EC 809180FC 3C014120 */ lui $at, 0x4120 ## $at = 41200000 /* 026F0 80918100 44816000 */ mtc1 $at, $f12 ## $f12 = 10.00 /* 026F4 80918104 0003C080 */ sll $t8, $v1, 2 /* 026F8 80918108 0303C023 */ subu $t8, $t8, $v1 /* 026FC 8091810C 0018C080 */ sll $t8, $t8, 2 /* 02700 80918110 02588021 */ addu $s0, $s2, $t8 /* 02704 80918114 C61002A8 */ lwc1 $f16, 0x02A8($s0) ## 000003F4 /* 02708 80918118 46008480 */ add.s $f18, $f16, $f0 /* 0270C 8091811C 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 02710 80918120 E7B20070 */ swc1 $f18, 0x0070($sp) /* 02714 80918124 C60402AC */ lwc1 $f4, 0x02AC($s0) ## 000003F8 /* 02718 80918128 3C0141A0 */ lui $at, 0x41A0 ## $at = 41A00000 /* 0271C 8091812C 44816000 */ mtc1 $at, $f12 ## $f12 = 20.00 /* 02720 80918130 46002180 */ add.s $f6, $f4, $f0 /* 02724 80918134 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 02728 80918138 E7A60074 */ swc1 $f6, 0x0074($sp) /* 0272C 8091813C C60802B0 */ lwc1 $f8, 0x02B0($s0) ## 000003FC /* 02730 80918140 46004280 */ add.s $f10, $f8, $f0 /* 02734 80918144 0C03F66B */ jal Math_Rand_ZeroOne ## Rand.Next() float /* 02738 80918148 E7AA0078 */ swc1 $f10, 0x0078($sp) /* 0273C 8091814C 3C0140A0 */ lui $at, 0x40A0 ## $at = 40A00000 /* 02740 80918150 44818000 */ mtc1 $at, $f16 ## $f16 = 5.00 /* 02744 80918154 240CFFFF */ addiu $t4, $zero, 0xFFFF ## $t4 = FFFFFFFF /* 02748 80918158 240D000A */ addiu $t5, $zero, 0x000A ## $t5 = 0000000A /* 0274C 8091815C 46100482 */ mul.s $f18, $f0, $f16 /* 02750 80918160 AFAD001C */ sw $t5, 0x001C($sp) /* 02754 80918164 AFAC0018 */ sw $t4, 0x0018($sp) /* 02758 80918168 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 0275C 8091816C 27A50070 */ addiu $a1, $sp, 0x0070 ## $a1 = FFFFFFB0 /* 02760 80918170 27A60088 */ addiu $a2, $sp, 0x0088 ## $a2 = FFFFFFC8 /* 02764 80918174 27A7007C */ addiu $a3, $sp, 0x007C ## $a3 = FFFFFFBC /* 02768 80918178 4600910D */ trunc.w.s $f4, $f18 /* 0276C 8091817C AFA00010 */ sw $zero, 0x0010($sp) /* 02770 80918180 AFA00020 */ sw $zero, 0x0020($sp) /* 02774 80918184 44082000 */ mfc1 $t0, $f4 /* 02778 80918188 00000000 */ nop /* 0277C 8091818C 00084C00 */ sll $t1, $t0, 16 /* 02780 80918190 00095403 */ sra $t2, $t1, 16 /* 02784 80918194 254B000A */ addiu $t3, $t2, 0x000A ## $t3 = 0000000A /* 02788 80918198 0C00A5C9 */ jal func_80029724 /* 0278C 8091819C AFAB0014 */ sw $t3, 0x0014($sp) /* 02790 809181A0 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000002 .L809181A4: /* 02794 809181A4 00118C00 */ sll $s1, $s1, 16 /* 02798 809181A8 00118C03 */ sra $s1, $s1, 16 /* 0279C 809181AC 2A21000F */ slti $at, $s1, 0x000F /* 027A0 809181B0 1420FFB6 */ bne $at, $zero, .L8091808C /* 027A4 809181B4 00000000 */ nop .L809181B8: /* 027A8 809181B8 864201D0 */ lh $v0, 0x01D0($s2) ## 000001D0 .L809181BC: /* 027AC 809181BC 1040000B */ beq $v0, $zero, .L809181EC /* 027B0 809181C0 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001 /* 027B4 809181C4 1041003E */ beq $v0, $at, .L809182C0 /* 027B8 809181C8 24010002 */ addiu $at, $zero, 0x0002 ## $at = 00000002 /* 027BC 809181CC 104100FB */ beq $v0, $at, .L809185BC /* 027C0 809181D0 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 027C4 809181D4 24010003 */ addiu $at, $zero, 0x0003 ## $at = 00000003 /* 027C8 809181D8 104101CE */ beq $v0, $at, .L80918914 /* 027CC 809181DC 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 /* 027D0 809181E0 3C010001 */ lui $at, 0x0001 ## $at = 00010000 /* 027D4 809181E4 10000216 */ beq $zero, $zero, .L80918A40 /* 027D8 809181E8 02611821 */ addu $v1, $s3, $at .L809181EC: /* 027DC 809181EC 240E0001 */ addiu $t6, $zero, 0x0001 ## $t6 = 00000001 /* 027E0 809181F0 A64E01D0 */ sh $t6, 0x01D0($s2) ## 000001D0 /* 027E4 809181F4 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 027E8 809181F8 0C019148 */ jal func_80064520 /* 027EC 809181FC 26651D64 */ addiu $a1, $s3, 0x1D64 ## $a1 = 00001D64 /* 027F0 80918200 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 027F4 80918204 02402825 */ or $a1, $s2, $zero ## $a1 = 00000000 /* 027F8 80918208 0C00B7D5 */ jal func_8002DF54 /* 027FC 8091820C 24060001 */ addiu $a2, $zero, 0x0001 ## $a2 = 00000001 /* 02800 80918210 0C03008C */ jal func_800C0230 /* 02804 80918214 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02808 80918218 A64201BC */ sh $v0, 0x01BC($s2) ## 000001BC /* 0280C 8091821C 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02810 80918220 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 02814 80918224 0C0300C5 */ jal func_800C0314 /* 02818 80918228 24060003 */ addiu $a2, $zero, 0x0003 ## $a2 = 00000003 /* 0281C 8091822C 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02820 80918230 864501BC */ lh $a1, 0x01BC($s2) ## 000001BC /* 02824 80918234 0C0300C5 */ jal func_800C0314 /* 02828 80918238 24060007 */ addiu $a2, $zero, 0x0007 ## $a2 = 00000007 /* 0282C 8091823C 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02830 80918240 0C030129 */ jal func_800C04A4 /* 02834 80918244 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 02838 80918248 C446005C */ lwc1 $f6, 0x005C($v0) ## 0000005C /* 0283C 8091824C E6460290 */ swc1 $f6, 0x0290($s2) ## 00000290 /* 02840 80918250 C4480060 */ lwc1 $f8, 0x0060($v0) ## 00000060 /* 02844 80918254 C6460290 */ lwc1 $f6, 0x0290($s2) ## 00000290 /* 02848 80918258 E6480294 */ swc1 $f8, 0x0294($s2) ## 00000294 /* 0284C 8091825C C44A0064 */ lwc1 $f10, 0x0064($v0) ## 00000064 /* 02850 80918260 C6480024 */ lwc1 $f8, 0x0024($s2) ## 00000024 /* 02854 80918264 E64A0298 */ swc1 $f10, 0x0298($s2) ## 00000298 /* 02858 80918268 C4500050 */ lwc1 $f16, 0x0050($v0) ## 00000050 /* 0285C 8091826C 46083301 */ sub.s $f12, $f6, $f8 /* 02860 80918270 C64A0298 */ lwc1 $f10, 0x0298($s2) ## 00000298 /* 02864 80918274 E650029C */ swc1 $f16, 0x029C($s2) ## 0000029C /* 02868 80918278 C4520054 */ lwc1 $f18, 0x0054($v0) ## 00000054 /* 0286C 8091827C C650002C */ lwc1 $f16, 0x002C($s2) ## 0000002C /* 02870 80918280 E65202A0 */ swc1 $f18, 0x02A0($s2) ## 000002A0 /* 02874 80918284 46105381 */ sub.s $f14, $f10, $f16 /* 02878 80918288 C4440058 */ lwc1 $f4, 0x0058($v0) ## 00000058 /* 0287C 8091828C 460C6482 */ mul.s $f18, $f12, $f12 /* 02880 80918290 E64402A4 */ swc1 $f4, 0x02A4($s2) ## 000002A4 /* 02884 80918294 460E7102 */ mul.s $f4, $f14, $f14 /* 02888 80918298 46049000 */ add.s $f0, $f18, $f4 /* 0288C 8091829C 46000004 */ sqrt.s $f0, $f0 /* 02890 809182A0 0C03F494 */ jal func_800FD250 /* 02894 809182A4 E6400228 */ swc1 $f0, 0x0228($s2) ## 00000228 /* 02898 809182A8 240F010E */ addiu $t7, $zero, 0x010E ## $t7 = 0000010E /* 0289C 809182AC 3C010001 */ lui $at, 0x0001 ## $at = 00010000 /* 028A0 809182B0 E640022C */ swc1 $f0, 0x022C($s2) ## 0000022C /* 028A4 809182B4 A64F01D4 */ sh $t7, 0x01D4($s2) ## 000001D4 /* 028A8 809182B8 100001E1 */ beq $zero, $zero, .L80918A40 /* 028AC 809182BC 02611821 */ addu $v1, $s3, $at .L809182C0: /* 028B0 809182C0 0C01DE1C */ jal Math_Sins ## sins? /* 028B4 809182C4 864400B6 */ lh $a0, 0x00B6($s2) ## 000000B6 /* 028B8 809182C8 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 028BC 809182CC 44813000 */ mtc1 $at, $f6 ## $f6 = 100.00 /* 028C0 809182D0 00000000 */ nop /* 028C4 809182D4 46060202 */ mul.s $f8, $f0, $f6 /* 028C8 809182D8 E7A800BC */ swc1 $f8, 0x00BC($sp) /* 028CC 809182DC 0C01DE0D */ jal Math_Coss ## coss? /* 028D0 809182E0 864400B6 */ lh $a0, 0x00B6($s2) ## 000000B6 /* 028D4 809182E4 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 028D8 809182E8 44815000 */ mtc1 $at, $f10 ## $f10 = 100.00 /* 028DC 809182EC C7AC00BC */ lwc1 $f12, 0x00BC($sp) /* 028E0 809182F0 C6500024 */ lwc1 $f16, 0x0024($s2) ## 00000024 /* 028E4 809182F4 460A0382 */ mul.s $f14, $f0, $f10 /* 028E8 809182F8 8FA40068 */ lw $a0, 0x0068($sp) /* 028EC 809182FC 460C8480 */ add.s $f18, $f16, $f12 /* 028F0 80918300 3C063F00 */ lui $a2, 0x3F00 ## $a2 = 3F000000 /* 028F4 80918304 3C0740A0 */ lui $a3, 0x40A0 ## $a3 = 40A00000 /* 028F8 80918308 24840024 */ addiu $a0, $a0, 0x0024 ## $a0 = 00000024 /* 028FC 8091830C 44059000 */ mfc1 $a1, $f18 /* 02900 80918310 0C01E107 */ jal Math_SmoothScaleMaxF /* 02904 80918314 E7AE00B8 */ swc1 $f14, 0x00B8($sp) /* 02908 80918318 C7AE00B8 */ lwc1 $f14, 0x00B8($sp) /* 0290C 8091831C C644002C */ lwc1 $f4, 0x002C($s2) ## 0000002C /* 02910 80918320 8FA40068 */ lw $a0, 0x0068($sp) /* 02914 80918324 3C063F00 */ lui $a2, 0x3F00 ## $a2 = 3F000000 /* 02918 80918328 460E2180 */ add.s $f6, $f4, $f14 /* 0291C 8091832C 3C0740A0 */ lui $a3, 0x40A0 ## $a3 = 40A00000 /* 02920 80918330 2484002C */ addiu $a0, $a0, 0x002C ## $a0 = 0000002C /* 02924 80918334 44053000 */ mfc1 $a1, $f6 /* 02928 80918338 0C01E107 */ jal Math_SmoothScaleMaxF /* 0292C 8091833C 00000000 */ nop /* 02930 80918340 864201D2 */ lh $v0, 0x01D2($s2) ## 000001D2 /* 02934 80918344 28410438 */ slti $at, $v0, 0x0438 /* 02938 80918348 10200014 */ beq $at, $zero, .L8091839C /* 0293C 8091834C 24180001 */ addiu $t8, $zero, 0x0001 ## $t8 = 00000001 /* 02940 80918350 3C108092 */ lui $s0, %hi(D_8091B044) ## $s0 = 80920000 /* 02944 80918354 A65801C2 */ sh $t8, 0x01C2($s2) ## 000001C2 /* 02948 80918358 2610B044 */ addiu $s0, $s0, %lo(D_8091B044) ## $s0 = 8091B044 /* 0294C 8091835C 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 /* 02950 80918360 02002025 */ or $a0, $s0, $zero ## $a0 = 8091B044 .L80918364: /* 02954 80918364 0C2456A5 */ jal func_80915A94 /* 02958 80918368 864501C0 */ lh $a1, 0x01C0($s2) ## 000001C0 /* 0295C 8091836C 864201C0 */ lh $v0, 0x01C0($s2) ## 000001C0 /* 02960 80918370 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000001 /* 02964 80918374 00118C00 */ sll $s1, $s1, 16 /* 02968 80918378 28410100 */ slti $at, $v0, 0x0100 /* 0296C 8091837C 10200003 */ beq $at, $zero, .L8091838C /* 02970 80918380 00118C03 */ sra $s1, $s1, 16 /* 02974 80918384 24590001 */ addiu $t9, $v0, 0x0001 ## $t9 = 00000001 /* 02978 80918388 A65901C0 */ sh $t9, 0x01C0($s2) ## 000001C0 .L8091838C: /* 0297C 8091838C 2A210004 */ slti $at, $s1, 0x0004 /* 02980 80918390 5420FFF4 */ bnel $at, $zero, .L80918364 /* 02984 80918394 02002025 */ or $a0, $s0, $zero ## $a0 = 8091B044 /* 02988 80918398 864201D2 */ lh $v0, 0x01D2($s2) ## 000001D2 .L8091839C: /* 0298C 8091839C 2841042E */ slti $at, $v0, 0x042E /* 02990 809183A0 1020000F */ beq $at, $zero, .L809183E0 /* 02994 809183A4 00000000 */ nop /* 02998 809183A8 86480194 */ lh $t0, 0x0194($s2) ## 00000194 /* 0299C 809183AC 31090003 */ andi $t1, $t0, 0x0003 ## $t1 = 00000000 /* 029A0 809183B0 1520000B */ bne $t1, $zero, .L809183E0 /* 029A4 809183B4 00000000 */ nop /* 029A8 809183B8 0C03F66B */ jal Math_Rand_ZeroOne ## Rand.Next() float /* 029AC 809183BC 00000000 */ nop /* 029B0 809183C0 3C013F00 */ lui $at, 0x3F00 ## $at = 3F000000 /* 029B4 809183C4 44814000 */ mtc1 $at, $f8 ## $f8 = 0.50 /* 029B8 809183C8 240A0003 */ addiu $t2, $zero, 0x0003 ## $t2 = 00000003 /* 029BC 809183CC 4608003C */ c.lt.s $f0, $f8 /* 029C0 809183D0 00000000 */ nop /* 029C4 809183D4 45000002 */ bc1f .L809183E0 /* 029C8 809183D8 00000000 */ nop /* 029CC 809183DC A64A01C4 */ sh $t2, 0x01C4($s2) ## 000001C4 .L809183E0: /* 029D0 809183E0 3C018092 */ lui $at, %hi(D_8091B534) ## $at = 80920000 /* 029D4 809183E4 C430B534 */ lwc1 $f16, %lo(D_8091B534)($at) /* 029D8 809183E8 C64A022C */ lwc1 $f10, 0x022C($s2) ## 0000022C /* 029DC 809183EC 3C063DCC */ lui $a2, 0x3DCC ## $a2 = 3DCC0000 /* 029E0 809183F0 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3DCCCCCD /* 029E4 809183F4 46105480 */ add.s $f18, $f10, $f16 /* 029E8 809183F8 26440228 */ addiu $a0, $s2, 0x0228 ## $a0 = 00000228 /* 029EC 809183FC 3C054316 */ lui $a1, 0x4316 ## $a1 = 43160000 /* 029F0 80918400 3C0740A0 */ lui $a3, 0x40A0 ## $a3 = 40A00000 /* 029F4 80918404 0C01E107 */ jal Math_SmoothScaleMaxF /* 029F8 80918408 E652022C */ swc1 $f18, 0x022C($s2) ## 0000022C /* 029FC 8091840C 0C0400A4 */ jal sinf /* 02A00 80918410 C64C022C */ lwc1 $f12, 0x022C($s2) ## 0000022C /* 02A04 80918414 C6440228 */ lwc1 $f4, 0x0228($s2) ## 00000228 /* 02A08 80918418 46002182 */ mul.s $f6, $f4, $f0 /* 02A0C 8091841C E7A600BC */ swc1 $f6, 0x00BC($sp) /* 02A10 80918420 0C041184 */ jal cosf /* 02A14 80918424 C64C022C */ lwc1 $f12, 0x022C($s2) ## 0000022C /* 02A18 80918428 C6480228 */ lwc1 $f8, 0x0228($s2) ## 00000228 /* 02A1C 8091842C C7AC00BC */ lwc1 $f12, 0x00BC($sp) /* 02A20 80918430 C64A0024 */ lwc1 $f10, 0x0024($s2) ## 00000024 /* 02A24 80918434 46004382 */ mul.s $f14, $f8, $f0 /* 02A28 80918438 3C018092 */ lui $at, %hi(D_8091B538) ## $at = 80920000 /* 02A2C 8091843C 460C5400 */ add.s $f16, $f10, $f12 /* 02A30 80918440 C432B538 */ lwc1 $f18, %lo(D_8091B538)($at) /* 02A34 80918444 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02A38 80918448 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02A3C 8091844C 44058000 */ mfc1 $a1, $f16 /* 02A40 80918450 E7AE00B8 */ swc1 $f14, 0x00B8($sp) /* 02A44 80918454 26440290 */ addiu $a0, $s2, 0x0290 ## $a0 = 00000290 /* 02A48 80918458 3C074248 */ lui $a3, 0x4248 ## $a3 = 42480000 /* 02A4C 8091845C 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02A50 80918460 E7B20010 */ swc1 $f18, 0x0010($sp) /* 02A54 80918464 3C0141A0 */ lui $at, 0x41A0 ## $at = 41A00000 /* 02A58 80918468 44813000 */ mtc1 $at, $f6 ## $f6 = 20.00 /* 02A5C 8091846C C6440028 */ lwc1 $f4, 0x0028($s2) ## 00000028 /* 02A60 80918470 3C018092 */ lui $at, %hi(D_8091B53C) ## $at = 80920000 /* 02A64 80918474 C42AB53C */ lwc1 $f10, %lo(D_8091B53C)($at) /* 02A68 80918478 46062200 */ add.s $f8, $f4, $f6 /* 02A6C 8091847C 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02A70 80918480 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02A74 80918484 26440294 */ addiu $a0, $s2, 0x0294 ## $a0 = 00000294 /* 02A78 80918488 44054000 */ mfc1 $a1, $f8 /* 02A7C 8091848C 3C074248 */ lui $a3, 0x4248 ## $a3 = 42480000 /* 02A80 80918490 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02A84 80918494 E7AA0010 */ swc1 $f10, 0x0010($sp) /* 02A88 80918498 C7AE00B8 */ lwc1 $f14, 0x00B8($sp) /* 02A8C 8091849C C650002C */ lwc1 $f16, 0x002C($s2) ## 0000002C /* 02A90 809184A0 3C018092 */ lui $at, %hi(D_8091B540) ## $at = 80920000 /* 02A94 809184A4 C424B540 */ lwc1 $f4, %lo(D_8091B540)($at) /* 02A98 809184A8 460E8480 */ add.s $f18, $f16, $f14 /* 02A9C 809184AC 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02AA0 809184B0 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02AA4 809184B4 26440298 */ addiu $a0, $s2, 0x0298 ## $a0 = 00000298 /* 02AA8 809184B8 44059000 */ mfc1 $a1, $f18 /* 02AAC 809184BC 3C074248 */ lui $a3, 0x4248 ## $a3 = 42480000 /* 02AB0 809184C0 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02AB4 809184C4 E7A40010 */ swc1 $f4, 0x0010($sp) /* 02AB8 809184C8 3C018092 */ lui $at, %hi(D_8091B544) ## $at = 80920000 /* 02ABC 809184CC C426B544 */ lwc1 $f6, %lo(D_8091B544)($at) /* 02AC0 809184D0 8E45026C */ lw $a1, 0x026C($s2) ## 0000026C /* 02AC4 809184D4 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02AC8 809184D8 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02ACC 809184DC 2644029C */ addiu $a0, $s2, 0x029C ## $a0 = 0000029C /* 02AD0 809184E0 3C074248 */ lui $a3, 0x4248 ## $a3 = 42480000 /* 02AD4 809184E4 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02AD8 809184E8 E7A60010 */ swc1 $f6, 0x0010($sp) /* 02ADC 809184EC 3C018092 */ lui $at, %hi(D_8091B548) ## $at = 80920000 /* 02AE0 809184F0 C428B548 */ lwc1 $f8, %lo(D_8091B548)($at) /* 02AE4 809184F4 8E45003C */ lw $a1, 0x003C($s2) ## 0000003C /* 02AE8 809184F8 264402A0 */ addiu $a0, $s2, 0x02A0 ## $a0 = 000002A0 /* 02AEC 809184FC 3C063F00 */ lui $a2, 0x3F00 ## $a2 = 3F000000 /* 02AF0 80918500 3C0742C8 */ lui $a3, 0x42C8 ## $a3 = 42C80000 /* 02AF4 80918504 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02AF8 80918508 E7A80010 */ swc1 $f8, 0x0010($sp) /* 02AFC 8091850C 3C018092 */ lui $at, %hi(D_8091B54C) ## $at = 80920000 /* 02B00 80918510 C42AB54C */ lwc1 $f10, %lo(D_8091B54C)($at) /* 02B04 80918514 8E450274 */ lw $a1, 0x0274($s2) ## 00000274 /* 02B08 80918518 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02B0C 8091851C 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02B10 80918520 264402A4 */ addiu $a0, $s2, 0x02A4 ## $a0 = 000002A4 /* 02B14 80918524 3C074248 */ lui $a3, 0x4248 ## $a3 = 42480000 /* 02B18 80918528 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02B1C 8091852C E7AA0010 */ swc1 $f10, 0x0010($sp) /* 02B20 80918530 864201D4 */ lh $v0, 0x01D4($s2) ## 000001D4 /* 02B24 80918534 24010050 */ addiu $at, $zero, 0x0050 ## $at = 00000050 /* 02B28 80918538 14410004 */ bne $v0, $at, .L8091854C /* 02B2C 8091853C 00000000 */ nop /* 02B30 80918540 0C03E803 */ jal Audio_SetBGM /* 02B34 80918544 24040021 */ addiu $a0, $zero, 0x0021 ## $a0 = 00000021 /* 02B38 80918548 864201D4 */ lh $v0, 0x01D4($s2) ## 000001D4 .L8091854C: /* 02B3C 8091854C 14400018 */ bne $v0, $zero, .L809185B0 /* 02B40 80918550 240B0002 */ addiu $t3, $zero, 0x0002 ## $t3 = 00000002 /* 02B44 80918554 A64B01D0 */ sh $t3, 0x01D0($s2) ## 000001D0 /* 02B48 80918558 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02B4C 8091855C 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 02B50 80918560 0C0300C5 */ jal func_800C0314 /* 02B54 80918564 24060003 */ addiu $a2, $zero, 0x0003 ## $a2 = 00000003 /* 02B58 80918568 44808000 */ mtc1 $zero, $f16 ## $f16 = 0.00 /* 02B5C 8091856C C6520028 */ lwc1 $f18, 0x0028($s2) ## 00000028 /* 02B60 80918570 240C0046 */ addiu $t4, $zero, 0x0046 ## $t4 = 00000046 /* 02B64 80918574 A64C01D4 */ sh $t4, 0x01D4($s2) ## 000001D4 /* 02B68 80918578 A64001C0 */ sh $zero, 0x01C0($s2) ## 000001C0 /* 02B6C 8091857C 8E470024 */ lw $a3, 0x0024($s2) ## 00000024 /* 02B70 80918580 E6500220 */ swc1 $f16, 0x0220($s2) ## 00000220 /* 02B74 80918584 E7B20010 */ swc1 $f18, 0x0010($sp) /* 02B78 80918588 C644002C */ lwc1 $f4, 0x002C($s2) ## 0000002C /* 02B7C 8091858C AFA00024 */ sw $zero, 0x0024($sp) /* 02B80 80918590 AFA00020 */ sw $zero, 0x0020($sp) /* 02B84 80918594 AFA0001C */ sw $zero, 0x001C($sp) /* 02B88 80918598 AFA00018 */ sw $zero, 0x0018($sp) /* 02B8C 8091859C 26641C24 */ addiu $a0, $s3, 0x1C24 ## $a0 = 00001C24 /* 02B90 809185A0 02602825 */ or $a1, $s3, $zero ## $a1 = 00000000 /* 02B94 809185A4 2406005F */ addiu $a2, $zero, 0x005F ## $a2 = 0000005F /* 02B98 809185A8 0C00C7D4 */ jal Actor_Spawn ## ActorSpawn /* 02B9C 809185AC E7A40014 */ swc1 $f4, 0x0014($sp) .L809185B0: /* 02BA0 809185B0 3C010001 */ lui $at, 0x0001 ## $at = 00010000 /* 02BA4 809185B4 10000122 */ beq $zero, $zero, .L80918A40 /* 02BA8 809185B8 02611821 */ addu $v1, $s3, $at .L809185BC: /* 02BAC 809185BC 0C030129 */ jal func_800C04A4 /* 02BB0 809185C0 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 02BB4 809185C4 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 02BB8 809185C8 44814000 */ mtc1 $at, $f8 ## $f8 = 50.00 /* 02BBC 809185CC C6460220 */ lwc1 $f6, 0x0220($s2) ## 00000220 /* 02BC0 809185D0 3C018092 */ lui $at, %hi(D_8091B550) ## $at = 80920000 /* 02BC4 809185D4 C430B550 */ lwc1 $f16, %lo(D_8091B550)($at) /* 02BC8 809185D8 46083282 */ mul.s $f10, $f6, $f8 /* 02BCC 809185DC 8C45005C */ lw $a1, 0x005C($v0) ## 0000005C /* 02BD0 809185E0 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02BD4 809185E4 00408025 */ or $s0, $v0, $zero ## $s0 = 00000000 /* 02BD8 809185E8 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02BDC 809185EC 26440290 */ addiu $a0, $s2, 0x0290 ## $a0 = 00000290 /* 02BE0 809185F0 E7B00010 */ swc1 $f16, 0x0010($sp) /* 02BE4 809185F4 44075000 */ mfc1 $a3, $f10 /* 02BE8 809185F8 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02BEC 809185FC 00000000 */ nop /* 02BF0 80918600 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 02BF4 80918604 44812000 */ mtc1 $at, $f4 ## $f4 = 50.00 /* 02BF8 80918608 C6520220 */ lwc1 $f18, 0x0220($s2) ## 00000220 /* 02BFC 8091860C 3C018092 */ lui $at, %hi(D_8091B554) ## $at = 80920000 /* 02C00 80918610 C428B554 */ lwc1 $f8, %lo(D_8091B554)($at) /* 02C04 80918614 46049182 */ mul.s $f6, $f18, $f4 /* 02C08 80918618 8E050060 */ lw $a1, 0x0060($s0) ## 00000060 /* 02C0C 8091861C 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02C10 80918620 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02C14 80918624 26440294 */ addiu $a0, $s2, 0x0294 ## $a0 = 00000294 /* 02C18 80918628 E7A80010 */ swc1 $f8, 0x0010($sp) /* 02C1C 8091862C 44073000 */ mfc1 $a3, $f6 /* 02C20 80918630 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02C24 80918634 00000000 */ nop /* 02C28 80918638 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 02C2C 8091863C 44818000 */ mtc1 $at, $f16 ## $f16 = 50.00 /* 02C30 80918640 C64A0220 */ lwc1 $f10, 0x0220($s2) ## 00000220 /* 02C34 80918644 3C018092 */ lui $at, %hi(D_8091B558) ## $at = 80920000 /* 02C38 80918648 C424B558 */ lwc1 $f4, %lo(D_8091B558)($at) /* 02C3C 8091864C 46105482 */ mul.s $f18, $f10, $f16 /* 02C40 80918650 8E050064 */ lw $a1, 0x0064($s0) ## 00000064 /* 02C44 80918654 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02C48 80918658 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02C4C 8091865C 26440298 */ addiu $a0, $s2, 0x0298 ## $a0 = 00000298 /* 02C50 80918660 E7A40010 */ swc1 $f4, 0x0010($sp) /* 02C54 80918664 44079000 */ mfc1 $a3, $f18 /* 02C58 80918668 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02C5C 8091866C 00000000 */ nop /* 02C60 80918670 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 02C64 80918674 44814000 */ mtc1 $at, $f8 ## $f8 = 50.00 /* 02C68 80918678 C6460220 */ lwc1 $f6, 0x0220($s2) ## 00000220 /* 02C6C 8091867C 3C018092 */ lui $at, %hi(D_8091B55C) ## $at = 80920000 /* 02C70 80918680 C430B55C */ lwc1 $f16, %lo(D_8091B55C)($at) /* 02C74 80918684 46083282 */ mul.s $f10, $f6, $f8 /* 02C78 80918688 8E050050 */ lw $a1, 0x0050($s0) ## 00000050 /* 02C7C 8091868C 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02C80 80918690 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02C84 80918694 2644029C */ addiu $a0, $s2, 0x029C ## $a0 = 0000029C /* 02C88 80918698 E7B00010 */ swc1 $f16, 0x0010($sp) /* 02C8C 8091869C 44075000 */ mfc1 $a3, $f10 /* 02C90 809186A0 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02C94 809186A4 00000000 */ nop /* 02C98 809186A8 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 02C9C 809186AC 44812000 */ mtc1 $at, $f4 ## $f4 = 50.00 /* 02CA0 809186B0 C6520220 */ lwc1 $f18, 0x0220($s2) ## 00000220 /* 02CA4 809186B4 3C018092 */ lui $at, %hi(D_8091B560) ## $at = 80920000 /* 02CA8 809186B8 C428B560 */ lwc1 $f8, %lo(D_8091B560)($at) /* 02CAC 809186BC 46049182 */ mul.s $f6, $f18, $f4 /* 02CB0 809186C0 8E050054 */ lw $a1, 0x0054($s0) ## 00000054 /* 02CB4 809186C4 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02CB8 809186C8 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02CBC 809186CC 264402A0 */ addiu $a0, $s2, 0x02A0 ## $a0 = 000002A0 /* 02CC0 809186D0 E7A80010 */ swc1 $f8, 0x0010($sp) /* 02CC4 809186D4 44073000 */ mfc1 $a3, $f6 /* 02CC8 809186D8 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02CCC 809186DC 00000000 */ nop /* 02CD0 809186E0 3C014248 */ lui $at, 0x4248 ## $at = 42480000 /* 02CD4 809186E4 44818000 */ mtc1 $at, $f16 ## $f16 = 50.00 /* 02CD8 809186E8 C64A0220 */ lwc1 $f10, 0x0220($s2) ## 00000220 /* 02CDC 809186EC 3C018092 */ lui $at, %hi(D_8091B564) ## $at = 80920000 /* 02CE0 809186F0 C424B564 */ lwc1 $f4, %lo(D_8091B564)($at) /* 02CE4 809186F4 46105482 */ mul.s $f18, $f10, $f16 /* 02CE8 809186F8 8E050058 */ lw $a1, 0x0058($s0) ## 00000058 /* 02CEC 809186FC 3C063E4C */ lui $a2, 0x3E4C ## $a2 = 3E4C0000 /* 02CF0 80918700 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3E4CCCCD /* 02CF4 80918704 264402A4 */ addiu $a0, $s2, 0x02A4 ## $a0 = 000002A4 /* 02CF8 80918708 E7A40010 */ swc1 $f4, 0x0010($sp) /* 02CFC 8091870C 44079000 */ mfc1 $a3, $f18 /* 02D00 80918710 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02D04 80918714 00000000 */ nop /* 02D08 80918718 3C013F80 */ lui $at, 0x3F80 ## $at = 3F800000 /* 02D0C 8091871C 44811000 */ mtc1 $at, $f2 ## $f2 = 1.00 /* 02D10 80918720 44803000 */ mtc1 $zero, $f6 ## $f6 = 0.00 /* 02D14 80918724 3C073CA3 */ lui $a3, 0x3CA3 ## $a3 = 3CA30000 /* 02D18 80918728 44051000 */ mfc1 $a1, $f2 /* 02D1C 8091872C 44061000 */ mfc1 $a2, $f2 /* 02D20 80918730 34E7D70A */ ori $a3, $a3, 0xD70A ## $a3 = 3CA3D70A /* 02D24 80918734 26440220 */ addiu $a0, $s2, 0x0220 ## $a0 = 00000220 /* 02D28 80918738 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02D2C 8091873C E7A60010 */ swc1 $f6, 0x0010($sp) /* 02D30 80918740 864D01D4 */ lh $t5, 0x01D4($s2) ## 000001D4 /* 02D34 80918744 3C0F8092 */ lui $t7, %hi(D_8091B310) ## $t7 = 80920000 /* 02D38 80918748 25EFB310 */ addiu $t7, $t7, %lo(D_8091B310) ## $t7 = 8091B310 /* 02D3C 8091874C 15A0005A */ bne $t5, $zero, .L809188B8 /* 02D40 80918750 27AE005C */ addiu $t6, $sp, 0x005C ## $t6 = FFFFFF9C /* 02D44 80918754 8DF90000 */ lw $t9, 0x0000($t7) ## 8091B310 /* 02D48 80918758 8DF80004 */ lw $t8, 0x0004($t7) ## 8091B314 /* 02D4C 8091875C 2408001E */ addiu $t0, $zero, 0x001E ## $t0 = 0000001E /* 02D50 80918760 ADD90000 */ sw $t9, 0x0000($t6) ## FFFFFF9C /* 02D54 80918764 8DF90008 */ lw $t9, 0x0008($t7) ## 8091B318 /* 02D58 80918768 ADD80004 */ sw $t8, 0x0004($t6) ## FFFFFFA0 /* 02D5C 8091876C 24090003 */ addiu $t1, $zero, 0x0003 ## $t1 = 00000003 /* 02D60 80918770 ADD90008 */ sw $t9, 0x0008($t6) ## FFFFFFA4 /* 02D64 80918774 A64801D4 */ sh $t0, 0x01D4($s2) ## 000001D4 /* 02D68 80918778 A64901D0 */ sh $t1, 0x01D0($s2) ## 000001D0 /* 02D6C 8091877C 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 .L80918780: /* 02D70 80918780 8FA20068 */ lw $v0, 0x0068($sp) /* 02D74 80918784 C7A8005C */ lwc1 $f8, 0x005C($sp) /* 02D78 80918788 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000 /* 02D7C 8091878C C44A0024 */ lwc1 $f10, 0x0024($v0) ## 00000024 /* 02D80 80918790 44811000 */ mtc1 $at, $f2 ## $f2 = 100.00 /* 02D84 80918794 C7B00064 */ lwc1 $f16, 0x0064($sp) /* 02D88 80918798 460A4001 */ sub.s $f0, $f8, $f10 /* 02D8C 8091879C C7AA0064 */ lwc1 $f10, 0x0064($sp) /* 02D90 809187A0 C7A4005C */ lwc1 $f4, 0x005C($sp) /* 02D94 809187A4 46000005 */ abs.s $f0, $f0 /* 02D98 809187A8 4602003C */ c.lt.s $f0, $f2 /* 02D9C 809187AC 00000000 */ nop /* 02DA0 809187B0 45020009 */ bc1fl .L809187D8 /* 02DA4 809187B4 C6460024 */ lwc1 $f6, 0x0024($s2) ## 00000024 /* 02DA8 809187B8 C452002C */ lwc1 $f18, 0x002C($v0) ## 0000002C /* 02DAC 809187BC 46128001 */ sub.s $f0, $f16, $f18 /* 02DB0 809187C0 46000005 */ abs.s $f0, $f0 /* 02DB4 809187C4 4602003C */ c.lt.s $f0, $f2 /* 02DB8 809187C8 00000000 */ nop /* 02DBC 809187CC 45030013 */ bc1tl .L8091881C /* 02DC0 809187D0 3C0143C8 */ lui $at, 0x43C8 ## $at = 43C80000 /* 02DC4 809187D4 C6460024 */ lwc1 $f6, 0x0024($s2) ## 00000024 .L809187D8: /* 02DC8 809187D8 3C014316 */ lui $at, 0x4316 ## $at = 43160000 /* 02DCC 809187DC 44814000 */ mtc1 $at, $f8 ## $f8 = 150.00 /* 02DD0 809187E0 46062001 */ sub.s $f0, $f4, $f6 /* 02DD4 809187E4 46000005 */ abs.s $f0, $f0 /* 02DD8 809187E8 4608003C */ c.lt.s $f0, $f8 /* 02DDC 809187EC 00000000 */ nop /* 02DE0 809187F0 4502001E */ bc1fl .L8091886C /* 02DE4 809187F4 C7B0005C */ lwc1 $f16, 0x005C($sp) /* 02DE8 809187F8 C650002C */ lwc1 $f16, 0x002C($s2) ## 0000002C /* 02DEC 809187FC 3C014316 */ lui $at, 0x4316 ## $at = 43160000 /* 02DF0 80918800 44819000 */ mtc1 $at, $f18 ## $f18 = 150.00 /* 02DF4 80918804 46105001 */ sub.s $f0, $f10, $f16 /* 02DF8 80918808 46000005 */ abs.s $f0, $f0 /* 02DFC 8091880C 4612003C */ c.lt.s $f0, $f18 /* 02E00 80918810 00000000 */ nop /* 02E04 80918814 45000014 */ bc1f .L80918868 /* 02E08 80918818 3C0143C8 */ lui $at, 0x43C8 ## $at = 43C80000 .L8091881C: /* 02E0C 8091881C 44816000 */ mtc1 $at, $f12 ## $f12 = 400.00 /* 02E10 80918820 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 02E14 80918824 00000000 */ nop /* 02E18 80918828 3C01C316 */ lui $at, 0xC316 ## $at = C3160000 /* 02E1C 8091882C 44812000 */ mtc1 $at, $f4 ## $f4 = -150.00 /* 02E20 80918830 3C0143C8 */ lui $at, 0x43C8 ## $at = 43C80000 /* 02E24 80918834 44816000 */ mtc1 $at, $f12 ## $f12 = 400.00 /* 02E28 80918838 46040180 */ add.s $f6, $f0, $f4 /* 02E2C 8091883C 0C00CFC8 */ jal Math_Rand_CenteredFloat /* 02E30 80918840 E7A6005C */ swc1 $f6, 0x005C($sp) /* 02E34 80918844 3C01C3AF */ lui $at, 0xC3AF ## $at = C3AF0000 /* 02E38 80918848 44814000 */ mtc1 $at, $f8 ## $f8 = -350.00 /* 02E3C 8091884C 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000001 /* 02E40 80918850 00118C00 */ sll $s1, $s1, 16 /* 02E44 80918854 46080280 */ add.s $f10, $f0, $f8 /* 02E48 80918858 00118C03 */ sra $s1, $s1, 16 /* 02E4C 8091885C 2A212710 */ slti $at, $s1, 0x2710 /* 02E50 80918860 1420FFC7 */ bne $at, $zero, .L80918780 /* 02E54 80918864 E7AA0064 */ swc1 $f10, 0x0064($sp) .L80918868: /* 02E58 80918868 C7B0005C */ lwc1 $f16, 0x005C($sp) .L8091886C: /* 02E5C 8091886C C7A40064 */ lwc1 $f4, 0x0064($sp) /* 02E60 80918870 26641C24 */ addiu $a0, $s3, 0x1C24 ## $a0 = 00001C24 /* 02E64 80918874 E7B00010 */ swc1 $f16, 0x0010($sp) /* 02E68 80918878 C6520028 */ lwc1 $f18, 0x0028($s2) ## 00000028 /* 02E6C 8091887C AFA00028 */ sw $zero, 0x0028($sp) /* 02E70 80918880 AFA00024 */ sw $zero, 0x0024($sp) /* 02E74 80918884 AFA00020 */ sw $zero, 0x0020($sp) /* 02E78 80918888 AFA0001C */ sw $zero, 0x001C($sp) /* 02E7C 8091888C 02402825 */ or $a1, $s2, $zero ## $a1 = 00000000 /* 02E80 80918890 02603025 */ or $a2, $s3, $zero ## $a2 = 00000000 /* 02E84 80918894 2407005D */ addiu $a3, $zero, 0x005D ## $a3 = 0000005D /* 02E88 80918898 E7A40018 */ swc1 $f4, 0x0018($sp) /* 02E8C 8091889C 0C00C916 */ jal Actor_SpawnAttached /* 02E90 809188A0 E7B20014 */ swc1 $f18, 0x0014($sp) /* 02E94 809188A4 3C050001 */ lui $a1, 0x0001 ## $a1 = 00010000 /* 02E98 809188A8 00B32821 */ addu $a1, $a1, $s3 /* 02E9C 809188AC 80A51CBC */ lb $a1, 0x1CBC($a1) ## 00011CBC /* 02EA0 809188B0 0C00B33C */ jal Flags_SetClear /* 02EA4 809188B4 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 .L809188B8: /* 02EA8 809188B8 3C010001 */ lui $at, 0x0001 ## $at = 00010000 /* 02EAC 809188BC 3C108092 */ lui $s0, %hi(D_8091B144) ## $s0 = 80920000 /* 02EB0 809188C0 2610B144 */ addiu $s0, $s0, %lo(D_8091B144) ## $s0 = 8091B144 /* 02EB4 809188C4 02611821 */ addu $v1, $s3, $at /* 02EB8 809188C8 00008825 */ or $s1, $zero, $zero ## $s1 = 00000000 /* 02EBC 809188CC 864501C0 */ lh $a1, 0x01C0($s2) ## 000001C0 .L809188D0: /* 02EC0 809188D0 AFA30048 */ sw $v1, 0x0048($sp) /* 02EC4 809188D4 0C2456A5 */ jal func_80915A94 /* 02EC8 809188D8 02002025 */ or $a0, $s0, $zero ## $a0 = 8091B144 /* 02ECC 809188DC 864201C0 */ lh $v0, 0x01C0($s2) ## 000001C0 /* 02ED0 809188E0 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000001 /* 02ED4 809188E4 00118C00 */ sll $s1, $s1, 16 /* 02ED8 809188E8 28410100 */ slti $at, $v0, 0x0100 /* 02EDC 809188EC 10200003 */ beq $at, $zero, .L809188FC /* 02EE0 809188F0 8FA30048 */ lw $v1, 0x0048($sp) /* 02EE4 809188F4 244A0001 */ addiu $t2, $v0, 0x0001 ## $t2 = 00000001 /* 02EE8 809188F8 A64A01C0 */ sh $t2, 0x01C0($s2) ## 000001C0 .L809188FC: /* 02EEC 809188FC 00118C03 */ sra $s1, $s1, 16 /* 02EF0 80918900 2A210004 */ slti $at, $s1, 0x0004 /* 02EF4 80918904 5420FFF2 */ bnel $at, $zero, .L809188D0 /* 02EF8 80918908 864501C0 */ lh $a1, 0x01C0($s2) ## 000001C0 /* 02EFC 8091890C 1000004D */ beq $zero, $zero, .L80918A44 /* 02F00 80918910 864501BC */ lh $a1, 0x01BC($s2) ## 000001BC .L80918914: /* 02F04 80918914 3C108092 */ lui $s0, %hi(D_8091B144) ## $s0 = 80920000 /* 02F08 80918918 2610B144 */ addiu $s0, $s0, %lo(D_8091B144) ## $s0 = 8091B144 /* 02F0C 8091891C 02002025 */ or $a0, $s0, $zero ## $a0 = 8091B144 .L80918920: /* 02F10 80918920 0C2456A5 */ jal func_80915A94 /* 02F14 80918924 864501C0 */ lh $a1, 0x01C0($s2) ## 000001C0 /* 02F18 80918928 864201C0 */ lh $v0, 0x01C0($s2) ## 000001C0 /* 02F1C 8091892C 26310001 */ addiu $s1, $s1, 0x0001 ## $s1 = 00000002 /* 02F20 80918930 00118C00 */ sll $s1, $s1, 16 /* 02F24 80918934 28410100 */ slti $at, $v0, 0x0100 /* 02F28 80918938 10200003 */ beq $at, $zero, .L80918948 /* 02F2C 8091893C 00118C03 */ sra $s1, $s1, 16 /* 02F30 80918940 244B0001 */ addiu $t3, $v0, 0x0001 ## $t3 = 00000001 /* 02F34 80918944 A64B01C0 */ sh $t3, 0x01C0($s2) ## 000001C0 .L80918948: /* 02F38 80918948 2A210004 */ slti $at, $s1, 0x0004 /* 02F3C 8091894C 5420FFF4 */ bnel $at, $zero, .L80918920 /* 02F40 80918950 02002025 */ or $a0, $s0, $zero ## $a0 = 8091B144 /* 02F44 80918954 864C01D4 */ lh $t4, 0x01D4($s2) ## 000001D4 /* 02F48 80918958 3C013F80 */ lui $at, 0x3F80 ## $at = 3F800000 /* 02F4C 8091895C 26440054 */ addiu $a0, $s2, 0x0054 ## $a0 = 00000054 /* 02F50 80918960 15800035 */ bne $t4, $zero, .L80918A38 /* 02F54 80918964 24050000 */ addiu $a1, $zero, 0x0000 ## $a1 = 00000000 /* 02F58 80918968 44811000 */ mtc1 $at, $f2 ## $f2 = 1.00 /* 02F5C 8091896C 44803000 */ mtc1 $zero, $f6 ## $f6 = 0.00 /* 02F60 80918970 3C073A44 */ lui $a3, 0x3A44 ## $a3 = 3A440000 /* 02F64 80918974 44061000 */ mfc1 $a2, $f2 /* 02F68 80918978 34E79BA6 */ ori $a3, $a3, 0x9BA6 ## $a3 = 3A449BA6 /* 02F6C 8091897C 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 02F70 80918980 E7A60010 */ swc1 $f6, 0x0010($sp) /* 02F74 80918984 3C018092 */ lui $at, %hi(D_8091B568) ## $at = 80920000 /* 02F78 80918988 C428B568 */ lwc1 $f8, %lo(D_8091B568)($at) /* 02F7C 8091898C 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02F80 80918990 4608003E */ c.le.s $f0, $f8 /* 02F84 80918994 00000000 */ nop /* 02F88 80918998 45020025 */ bc1fl .L80918A30 /* 02F8C 8091899C C6400054 */ lwc1 $f0, 0x0054($s2) ## 00000054 /* 02F90 809189A0 0C030129 */ jal func_800C04A4 /* 02F94 809189A4 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000 /* 02F98 809189A8 26430290 */ addiu $v1, $s2, 0x0290 ## $v1 = 00000290 /* 02F9C 809189AC 8C6E0000 */ lw $t6, 0x0000($v1) ## 00000290 /* 02FA0 809189B0 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02FA4 809189B4 00003025 */ or $a2, $zero, $zero ## $a2 = 00000000 /* 02FA8 809189B8 AC4E005C */ sw $t6, 0x005C($v0) ## 0000005C /* 02FAC 809189BC 8C6D0004 */ lw $t5, 0x0004($v1) ## 00000294 /* 02FB0 809189C0 AC4D0060 */ sw $t5, 0x0060($v0) ## 00000060 /* 02FB4 809189C4 8C6E0008 */ lw $t6, 0x0008($v1) ## 00000298 /* 02FB8 809189C8 AC4E0064 */ sw $t6, 0x0064($v0) ## 00000064 /* 02FBC 809189CC 8C780000 */ lw $t8, 0x0000($v1) ## 00000290 /* 02FC0 809189D0 AC580074 */ sw $t8, 0x0074($v0) ## 00000074 /* 02FC4 809189D4 8C6F0004 */ lw $t7, 0x0004($v1) ## 00000294 /* 02FC8 809189D8 AC4F0078 */ sw $t7, 0x0078($v0) ## 00000078 /* 02FCC 809189DC 8C780008 */ lw $t8, 0x0008($v1) ## 00000298 /* 02FD0 809189E0 AC58007C */ sw $t8, 0x007C($v0) ## 0000007C /* 02FD4 809189E4 8E48029C */ lw $t0, 0x029C($s2) ## 0000029C /* 02FD8 809189E8 AC480050 */ sw $t0, 0x0050($v0) ## 00000050 /* 02FDC 809189EC 8E5902A0 */ lw $t9, 0x02A0($s2) ## 000002A0 /* 02FE0 809189F0 AC590054 */ sw $t9, 0x0054($v0) ## 00000054 /* 02FE4 809189F4 8E4802A4 */ lw $t0, 0x02A4($s2) ## 000002A4 /* 02FE8 809189F8 AC480058 */ sw $t0, 0x0058($v0) ## 00000058 /* 02FEC 809189FC 0C03022B */ jal func_800C08AC /* 02FF0 80918A00 864501BC */ lh $a1, 0x01BC($s2) ## 000001BC /* 02FF4 80918A04 A64001BC */ sh $zero, 0x01BC($s2) ## 000001BC /* 02FF8 80918A08 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 02FFC 80918A0C 0C01914D */ jal func_80064534 /* 03000 80918A10 26651D64 */ addiu $a1, $s3, 0x1D64 ## $a1 = 00001D64 /* 03004 80918A14 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 03008 80918A18 02402825 */ or $a1, $s2, $zero ## $a1 = 00000000 /* 0300C 80918A1C 0C00B7D5 */ jal func_8002DF54 /* 03010 80918A20 24060007 */ addiu $a2, $zero, 0x0007 ## $a2 = 00000007 /* 03014 80918A24 0C00B55C */ jal Actor_Kill /* 03018 80918A28 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000 /* 0301C 80918A2C C6400054 */ lwc1 $f0, 0x0054($s2) ## 00000054 .L80918A30: /* 03020 80918A30 E6400058 */ swc1 $f0, 0x0058($s2) ## 00000058 /* 03024 80918A34 E6400050 */ swc1 $f0, 0x0050($s2) ## 00000050 .L80918A38: /* 03028 80918A38 3C010001 */ lui $at, 0x0001 ## $at = 00010000 /* 0302C 80918A3C 02611821 */ addu $v1, $s3, $at .L80918A40: /* 03030 80918A40 864501BC */ lh $a1, 0x01BC($s2) ## 000001BC .L80918A44: /* 03034 80918A44 10A00006 */ beq $a1, $zero, .L80918A60 /* 03038 80918A48 02602025 */ or $a0, $s3, $zero ## $a0 = 00000000 /* 0303C 80918A4C 2646029C */ addiu $a2, $s2, 0x029C ## $a2 = 0000029C /* 03040 80918A50 26470290 */ addiu $a3, $s2, 0x0290 ## $a3 = 00000290 /* 03044 80918A54 0C030136 */ jal func_800C04D8 /* 03048 80918A58 AFA30048 */ sw $v1, 0x0048($sp) /* 0304C 80918A5C 8FA30048 */ lw $v1, 0x0048($sp) .L80918A60: /* 03050 80918A60 864201C4 */ lh $v0, 0x01C4($s2) ## 000001C4 /* 03054 80918A64 10400015 */ beq $v0, $zero, .L80918ABC /* 03058 80918A68 2449FFFF */ addiu $t1, $v0, 0xFFFF ## $t1 = FFFFFFFF /* 0305C 80918A6C A64901C4 */ sh $t1, 0x01C4($s2) ## 000001C4 /* 03060 80918A70 846A0AB0 */ lh $t2, 0x0AB0($v1) ## 00000AB0 /* 03064 80918A74 846C0AB2 */ lh $t4, 0x0AB2($v1) ## 00000AB2 /* 03068 80918A78 846E0AB4 */ lh $t6, 0x0AB4($v1) ## 00000AB4 /* 0306C 80918A7C 254B0028 */ addiu $t3, $t2, 0x0028 ## $t3 = 00000028 /* 03070 80918A80 84780ABC */ lh $t8, 0x0ABC($v1) ## 00000ABC /* 03074 80918A84 84680ABE */ lh $t0, 0x0ABE($v1) ## 00000ABE /* 03078 80918A88 846A0AC0 */ lh $t2, 0x0AC0($v1) ## 00000AC0 /* 0307C 80918A8C A46B0AB0 */ sh $t3, 0x0AB0($v1) ## 00000AB0 /* 03080 80918A90 258D0028 */ addiu $t5, $t4, 0x0028 ## $t5 = 00000028 /* 03084 80918A94 25CF0050 */ addiu $t7, $t6, 0x0050 ## $t7 = 00000050 /* 03088 80918A98 2719000A */ addiu $t9, $t8, 0x000A ## $t9 = 0000000A /* 0308C 80918A9C 2509000A */ addiu $t1, $t0, 0x000A ## $t1 = 0000000A /* 03090 80918AA0 254B0014 */ addiu $t3, $t2, 0x0014 ## $t3 = 00000014 /* 03094 80918AA4 A46D0AB2 */ sh $t5, 0x0AB2($v1) ## 00000AB2 /* 03098 80918AA8 A46F0AB4 */ sh $t7, 0x0AB4($v1) ## 00000AB4 /* 0309C 80918AAC A4790ABC */ sh $t9, 0x0ABC($v1) ## 00000ABC /* 030A0 80918AB0 A4690ABE */ sh $t1, 0x0ABE($v1) ## 00000ABE /* 030A4 80918AB4 10000013 */ beq $zero, $zero, .L80918B04 /* 030A8 80918AB8 A46B0AC0 */ sh $t3, 0x0AC0($v1) ## 00000AC0 .L80918ABC: /* 030AC 80918ABC 846C0AB0 */ lh $t4, 0x0AB0($v1) ## 00000AB0 /* 030B0 80918AC0 846E0AB2 */ lh $t6, 0x0AB2($v1) ## 00000AB2 /* 030B4 80918AC4 84780AB4 */ lh $t8, 0x0AB4($v1) ## 00000AB4 /* 030B8 80918AC8 258DFFEC */ addiu $t5, $t4, 0xFFEC ## $t5 = FFFFFFEC /* 030BC 80918ACC 84680ABC */ lh $t0, 0x0ABC($v1) ## 00000ABC /* 030C0 80918AD0 846A0ABE */ lh $t2, 0x0ABE($v1) ## 00000ABE /* 030C4 80918AD4 846C0AC0 */ lh $t4, 0x0AC0($v1) ## 00000AC0 /* 030C8 80918AD8 A46D0AB0 */ sh $t5, 0x0AB0($v1) ## 00000AB0 /* 030CC 80918ADC 25CFFFEC */ addiu $t7, $t6, 0xFFEC ## $t7 = FFFFFFEC /* 030D0 80918AE0 2719FFD8 */ addiu $t9, $t8, 0xFFD8 ## $t9 = FFFFFFD8 /* 030D4 80918AE4 2509FFFB */ addiu $t1, $t0, 0xFFFB ## $t1 = FFFFFFFB /* 030D8 80918AE8 254BFFFB */ addiu $t3, $t2, 0xFFFB ## $t3 = FFFFFFFB /* 030DC 80918AEC 258DFFF6 */ addiu $t5, $t4, 0xFFF6 ## $t5 = FFFFFFF6 /* 030E0 80918AF0 A46F0AB2 */ sh $t7, 0x0AB2($v1) ## 00000AB2 /* 030E4 80918AF4 A4790AB4 */ sh $t9, 0x0AB4($v1) ## 00000AB4 /* 030E8 80918AF8 A4690ABC */ sh $t1, 0x0ABC($v1) ## 00000ABC /* 030EC 80918AFC A46B0ABE */ sh $t3, 0x0ABE($v1) ## 00000ABE /* 030F0 80918B00 A46D0AC0 */ sh $t5, 0x0AC0($v1) ## 00000AC0 .L80918B04: /* 030F4 80918B04 846E0AB0 */ lh $t6, 0x0AB0($v1) ## 00000AB0 /* 030F8 80918B08 29C100C9 */ slti $at, $t6, 0x00C9 /* 030FC 80918B0C 14200002 */ bne $at, $zero, .L80918B18 /* 03100 80918B10 240200C8 */ addiu $v0, $zero, 0x00C8 ## $v0 = 000000C8 /* 03104 80918B14 A4620AB0 */ sh $v0, 0x0AB0($v1) ## 00000AB0 .L80918B18: /* 03108 80918B18 846F0AB2 */ lh $t7, 0x0AB2($v1) ## 00000AB2 /* 0310C 80918B1C 240200C8 */ addiu $v0, $zero, 0x00C8 ## $v0 = 000000C8 /* 03110 80918B20 29E100C9 */ slti $at, $t7, 0x00C9 /* 03114 80918B24 54200003 */ bnel $at, $zero, .L80918B34 /* 03118 80918B28 84780AB4 */ lh $t8, 0x0AB4($v1) ## 00000AB4 /* 0311C 80918B2C A4620AB2 */ sh $v0, 0x0AB2($v1) ## 00000AB2 /* 03120 80918B30 84780AB4 */ lh $t8, 0x0AB4($v1) ## 00000AB4 .L80918B34: /* 03124 80918B34 2B0100C9 */ slti $at, $t8, 0x00C9 /* 03128 80918B38 54200003 */ bnel $at, $zero, .L80918B48 /* 0312C 80918B3C 84790ABC */ lh $t9, 0x0ABC($v1) ## 00000ABC /* 03130 80918B40 A4620AB4 */ sh $v0, 0x0AB4($v1) ## 00000AB4 /* 03134 80918B44 84790ABC */ lh $t9, 0x0ABC($v1) ## 00000ABC .L80918B48: /* 03138 80918B48 24080046 */ addiu $t0, $zero, 0x0046 ## $t0 = 00000046 /* 0313C 80918B4C 240A0046 */ addiu $t2, $zero, 0x0046 ## $t2 = 00000046 /* 03140 80918B50 2B210047 */ slti $at, $t9, 0x0047 /* 03144 80918B54 54200003 */ bnel $at, $zero, .L80918B64 /* 03148 80918B58 84690ABE */ lh $t1, 0x0ABE($v1) ## 00000ABE /* 0314C 80918B5C A4680ABC */ sh $t0, 0x0ABC($v1) ## 00000ABC /* 03150 80918B60 84690ABE */ lh $t1, 0x0ABE($v1) ## 00000ABE .L80918B64: /* 03154 80918B64 240C008C */ addiu $t4, $zero, 0x008C ## $t4 = 0000008C /* 03158 80918B68 29210047 */ slti $at, $t1, 0x0047 /* 0315C 80918B6C 54200003 */ bnel $at, $zero, .L80918B7C /* 03160 80918B70 846B0AC0 */ lh $t3, 0x0AC0($v1) ## 00000AC0 /* 03164 80918B74 A46A0ABE */ sh $t2, 0x0ABE($v1) ## 00000ABE /* 03168 80918B78 846B0AC0 */ lh $t3, 0x0AC0($v1) ## 00000AC0 .L80918B7C: /* 0316C 80918B7C 2961008D */ slti $at, $t3, 0x008D /* 03170 80918B80 54200003 */ bnel $at, $zero, .L80918B90 /* 03174 80918B84 846D0AB0 */ lh $t5, 0x0AB0($v1) ## 00000AB0 /* 03178 80918B88 A46C0AC0 */ sh $t4, 0x0AC0($v1) ## 00000AC0 /* 0317C 80918B8C 846D0AB0 */ lh $t5, 0x0AB0($v1) ## 00000AB0 .L80918B90: /* 03180 80918B90 05A30003 */ bgezl $t5, .L80918BA0 /* 03184 80918B94 846E0AB2 */ lh $t6, 0x0AB2($v1) ## 00000AB2 /* 03188 80918B98 A4600AB0 */ sh $zero, 0x0AB0($v1) ## 00000AB0 /* 0318C 80918B9C 846E0AB2 */ lh $t6, 0x0AB2($v1) ## 00000AB2 .L80918BA0: /* 03190 80918BA0 05C30003 */ bgezl $t6, .L80918BB0 /* 03194 80918BA4 846F0AB4 */ lh $t7, 0x0AB4($v1) ## 00000AB4 /* 03198 80918BA8 A4600AB2 */ sh $zero, 0x0AB2($v1) ## 00000AB2 /* 0319C 80918BAC 846F0AB4 */ lh $t7, 0x0AB4($v1) ## 00000AB4 .L80918BB0: /* 031A0 80918BB0 05E30003 */ bgezl $t7, .L80918BC0 /* 031A4 80918BB4 84780ABC */ lh $t8, 0x0ABC($v1) ## 00000ABC /* 031A8 80918BB8 A4600AB4 */ sh $zero, 0x0AB4($v1) ## 00000AB4 /* 031AC 80918BBC 84780ABC */ lh $t8, 0x0ABC($v1) ## 00000ABC .L80918BC0: /* 031B0 80918BC0 07030003 */ bgezl $t8, .L80918BD0 /* 031B4 80918BC4 84790ABE */ lh $t9, 0x0ABE($v1) ## 00000ABE /* 031B8 80918BC8 A4600ABC */ sh $zero, 0x0ABC($v1) ## 00000ABC /* 031BC 80918BCC 84790ABE */ lh $t9, 0x0ABE($v1) ## 00000ABE .L80918BD0: /* 031C0 80918BD0 07230003 */ bgezl $t9, .L80918BE0 /* 031C4 80918BD4 84680AC0 */ lh $t0, 0x0AC0($v1) ## 00000AC0 /* 031C8 80918BD8 A4600ABE */ sh $zero, 0x0ABE($v1) ## 00000ABE /* 031CC 80918BDC 84680AC0 */ lh $t0, 0x0AC0($v1) ## 00000AC0 .L80918BE0: /* 031D0 80918BE0 05030003 */ bgezl $t0, .L80918BF0 /* 031D4 80918BE4 8FBF0044 */ lw $ra, 0x0044($sp) /* 031D8 80918BE8 A4600AC0 */ sh $zero, 0x0AC0($v1) ## 00000AC0 /* 031DC 80918BEC 8FBF0044 */ lw $ra, 0x0044($sp) .L80918BF0: /* 031E0 80918BF0 8FB00034 */ lw $s0, 0x0034($sp) /* 031E4 80918BF4 8FB10038 */ lw $s1, 0x0038($sp) /* 031E8 80918BF8 8FB2003C */ lw $s2, 0x003C($sp) /* 031EC 80918BFC 8FB30040 */ lw $s3, 0x0040($sp) /* 031F0 80918C00 03E00008 */ jr $ra /* 031F4 80918C04 27BD00C0 */ addiu $sp, $sp, 0x00C0 ## $sp = 00000000
412
0.668027
1
0.668027
game-dev
MEDIA
0.981418
game-dev
0.673599
1
0.673599
ldtteam/minecolonies
2,919
src/main/java/com/minecolonies/api/advancements/AbstractCriterionTrigger.java
package com.minecolonies.api.advancements; import com.google.common.collect.Maps; import net.minecraft.advancements.CriterionTrigger; import net.minecraft.advancements.CriterionTriggerInstance; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.PlayerAdvancements; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.function.Function; /** * The base class of a Trigger that tracks listeners and defines criterion * related to the trigger, and how that is fetched from JSON * @param <T> the class of the individual listener that will perform the trigger * @param <U> the criterion the individual listener is checking */ public abstract class AbstractCriterionTrigger<T extends CriterionListeners<U>, U extends CriterionTriggerInstance> implements CriterionTrigger<U> { /** The designation for this trigger. Used by JSON advancement data. */ private final ResourceLocation id; /** The factory method to create a listener each time this trigger is utilised */ private final Function<PlayerAdvancements, T> createNew; /** A map tracking each of the listeners */ private final Map<PlayerAdvancements, T> listeners = Maps.newHashMap(); /** * The trigger constructor that will define the trigger to be called * @param id the designation for this trigger. Used by JSON. * @param createNew the factory method for the listener */ protected AbstractCriterionTrigger(ResourceLocation id, Function<PlayerAdvancements, T> createNew) { this.id = id; this.createNew = createNew; } @NotNull @Override public ResourceLocation getId() { return id; } @Override public void addPlayerListener(@NotNull PlayerAdvancements playerAdvancements, @NotNull Listener<U> listener) { T listeners = this.listeners.get(playerAdvancements); if (listeners == null) { listeners = createNew.apply(playerAdvancements); this.listeners.put(playerAdvancements, listeners); } listeners.add(listener); } @Override public void removePlayerListener(@NotNull PlayerAdvancements playerAdvancements, @NotNull Listener<U> listener) { final T listeners = this.listeners.get(playerAdvancements); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { this.listeners.remove(playerAdvancements); } } } @Nullable protected T getListeners(PlayerAdvancements playerAdvancements) { return this.listeners.get(playerAdvancements); } @Override public void removePlayerListeners(@NotNull PlayerAdvancements playerAdvancements) { this.listeners.remove(playerAdvancements); } }
412
0.832955
1
0.832955
game-dev
MEDIA
0.705555
game-dev
0.686077
1
0.686077
NeuralHarbour/LLM-Based-3D-Avatar-Assistant
2,496
Client Side/Assets/UniGLTF/Runtime/UniHumanoid/ForceUniqueName.cs
using System; using System.Collections.Generic; using UnityEngine; namespace UniHumanoid { class ForceUniqueName { HashSet<string> m_uniqueNameSet = new HashSet<string>(); int m_counter = 1; public static void Process(Transform root) { var uniqueName = new ForceUniqueName(); var transforms = root.GetComponentsInChildren<Transform>(); foreach (var t in transforms) { uniqueName.RenameIfDupName(t); } } public void RenameIfDupName(Transform t) { if (!m_uniqueNameSet.Contains(t.name)) { m_uniqueNameSet.Add(t.name); return; } if (t.parent != null && t.childCount == 0) { /// AvatarBuilder:BuildHumanAvatar で同名の Transform があるとエラーになる。 /// /// AvatarBuilder 'GLTF': Ambiguous Transform '32/root/torso_1/torso_2/torso_3/torso_4/torso_5/torso_6/torso_7/neck_1/neck_2/head/ENDSITE' and '32/root/torso_1/torso_2/torso_3/torso_4/torso_5/torso_6/torso_7/l_shoulder/l_up_arm/l_low_arm/l_hand/ENDSITE' found in hierarchy for human bone 'Head'. Transform name mapped to a human bone must be unique. /// UnityEngine.AvatarBuilder:BuildHumanAvatar (UnityEngine.GameObject,UnityEngine.HumanDescription) /// UniHumanoid.AvatarDescription:CreateAvatar (UnityEngine.Transform) /// /// 主に BVH の EndSite 由来の GameObject 名が重複することへの対策 /// ex: parent-ENDSITE var newName = $"{t.parent.name}-{t.name}"; if (!m_uniqueNameSet.Contains(newName)) { Debug.LogWarning($"force rename !!: {t.name} => {newName}"); t.name = newName; m_uniqueNameSet.Add(newName); return; } } // 連番 for (int i = 0; i < 100; ++i) { // ex: name.1 var newName = $"{t.name}{m_counter++}"; if (!m_uniqueNameSet.Contains(newName)) { Debug.LogWarning($"force rename: {t.name} => {newName}", t); t.name = newName; m_uniqueNameSet.Add(newName); return; } } throw new NotImplementedException(); } } }
412
0.86239
1
0.86239
game-dev
MEDIA
0.915051
game-dev
0.970343
1
0.970343
mellinoe/ge
3,543
src/BEPU/BEPUphysics/DeactivationManagement/ISimulationIslandConnection.cs
using BEPUutilities.DataStructures; namespace BEPUphysics.DeactivationManagement { ///<summary> /// Defines an object which connects simulation islands together. ///</summary> public interface ISimulationIslandConnection { ///<summary> /// Gets or sets the deactivation member that owns this connection. ///</summary> DeactivationManager DeactivationManager { get; set; } ///<summary> /// Gets the simulation island members associated with this connection. ///</summary> ReadOnlyList<SimulationIslandMember> ConnectedMembers { get; } ///<summary> /// Adds references to the connection to all connected members. ///</summary> void AddReferencesToConnectedMembers(); ///<summary> /// Removes references to the connection from all connected members. ///</summary> void RemoveReferencesFromConnectedMembers(); //When connections are modified, simulation island needs to be updated. //Could have a custom collection that shoots off events when it is changed, or otherwise notifies... //But then again, whatever is doing the changing can do the notification without a custom collection. //It would need to call merge/trysplit.. Not everything has the ability to change connections, but some do. //Leave it up to the implementors :) //When "Added," it attempts to merge the simulation islands of its connected members. //When "Removed," it attempts to split the simulation islands of its connected members. //The SimulationIslandConnection is not itself a thing that is added/removed to a set somewhere. //It is a description of some object. The act of 'adding' a simulation island connection is completed in full by //merging simulation islands and the associated bookkeeping- there does not need to be a list anywhere. //Likewise, removing a simulation island is completed in full by the split attempt. //However, whatever is doing the management of things that happen to be ISimulationIslandConnections must know how to deal with them. //(Using the SimulationIsland.Merge, TrySplit methods). //This leaves a lot of responsibility in the implementation's hands. //Maybe this is just fine. Consider that this isn't exactly a common situation. //Known, in-engine scenarios: //Constraints //Collision Pairs. //When constraints are added or removed to the space (or maybe more directly the solver, to unify with cp's), the merge happens. //When they are removed from the space, the split happens. //All SolverItems are also simulation connections, which is why it makes sense to do it at the solver time.... HOWEVER... //It is possible to have a simulation island connection that isn't a solver item at all. Think particle collision. //In the particle case, the engine doesn't 'know' anything about the type- it's 100% custom. //The OnAdditionToSpace methods come in handy. Particle collision says, well, the system won't do it for me since I'm not going to be added to the solver. //So instead, whatever the thing is that handles the 'force application' part of the particle system would perform the necessary simulation island management. //Sidenote: The particle collision system would, in practice, probably just be a Solver item with 1 iteration. } }
412
0.92223
1
0.92223
game-dev
MEDIA
0.708367
game-dev,networking
0.772875
1
0.772875
SagaciousG/ETPlugins
1,673
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/AI/AIDispatcherComponentSystem.cs
using System; namespace ET { [FriendOf(typeof(AIDispatcherComponent))] public static class AIDispatcherComponentSystem { [ObjectSystem] public class AIDispatcherComponentAwakeSystem: AwakeSystem<AIDispatcherComponent> { protected override void Awake(AIDispatcherComponent self) { AIDispatcherComponent.Instance = self; self.Load(); } } [ObjectSystem] public class AIDispatcherComponentLoadSystem: LoadSystem<AIDispatcherComponent> { protected override void Load(AIDispatcherComponent self) { self.Load(); } } [ObjectSystem] public class AIDispatcherComponentDestroySystem: DestroySystem<AIDispatcherComponent> { protected override void Destroy(AIDispatcherComponent self) { self.AIHandlers.Clear(); AIDispatcherComponent.Instance = null; } } private static void Load(this AIDispatcherComponent self) { self.AIHandlers.Clear(); var types = EventSystem.Instance.GetTypes(typeof (AIHandlerAttribute)); foreach (Type type in types) { AAIHandler aaiHandler = Activator.CreateInstance(type) as AAIHandler; if (aaiHandler == null) { Log.Error($"robot ai is not AAIHandler: {type.Name}"); continue; } self.AIHandlers.Add(type.Name, aaiHandler); } } } }
412
0.663131
1
0.663131
game-dev
MEDIA
0.653234
game-dev
0.531357
1
0.531357
ReikaKalseki/ChromatiCraft
11,176
GUI/Tile/GuiCrystalMusic.java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2017 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.ChromatiCraft.GUI.Tile; import java.util.HashMap; import org.lwjgl.opengl.GL11; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; import Reika.ChromatiCraft.ChromatiCraft; import Reika.ChromatiCraft.Auxiliary.CrystalMusicManager; import Reika.ChromatiCraft.Base.GuiChromaBase; import Reika.ChromatiCraft.Registry.ChromaPackets; import Reika.ChromatiCraft.Registry.ChromaSounds; import Reika.ChromatiCraft.Registry.CrystalElement; import Reika.ChromatiCraft.TileEntity.Decoration.TileEntityCrystalMusic; import Reika.DragonAPI.Base.CoreContainer; import Reika.DragonAPI.Instantiable.GUI.CustomSoundGuiButton.CustomSoundImagedGuiButton; import Reika.DragonAPI.Instantiable.GUI.PianoWheel; import Reika.DragonAPI.Instantiable.GUI.PianoWheel.PianoGui; import Reika.DragonAPI.Libraries.IO.ReikaPacketHelper; import Reika.DragonAPI.Libraries.IO.ReikaSoundHelper; import Reika.DragonAPI.Libraries.IO.ReikaTextureHelper; import Reika.DragonAPI.Libraries.Java.ReikaGLHelper.BlendMode; import Reika.DragonAPI.Libraries.Java.ReikaJavaLibrary; import Reika.DragonAPI.Libraries.MathSci.ReikaMusicHelper.MusicKey; import Reika.DragonAPI.Libraries.MathSci.ReikaMusicHelper.Note; import Reika.DragonAPI.Libraries.Rendering.ReikaGuiAPI; public class GuiCrystalMusic extends GuiChromaBase implements PianoGui { private final TileEntityCrystalMusic music; private PianoWheel wheel; private int channel = 0; private boolean rest = false; private int activeNote; private int length; private Pages page = Pages.KEYS; private GuiTextField input; private GuiTextField ticksPer; private int midiTickRate; private int midiBPM; private static final HashMap<Note, Integer> colors = new HashMap(); static { colors.put(Note.C, CrystalElement.BLACK.getColor()); colors.put(Note.CSHARP, CrystalElement.RED.getColor()); colors.put(Note.D, CrystalElement.ORANGE.getColor()); colors.put(Note.EFLAT, CrystalElement.CYAN.getColor()); colors.put(Note.E, CrystalElement.YELLOW.getColor()); colors.put(Note.F, CrystalElement.LIME.getColor()); colors.put(Note.FSHARP, CrystalElement.GREEN.getColor()); colors.put(Note.G, CrystalElement.BLUE.getColor()); colors.put(Note.GSHARP, CrystalElement.MAGENTA.getColor()); colors.put(Note.A, CrystalElement.PURPLE.getColor()); colors.put(Note.BFLAT, CrystalElement.LIGHTBLUE.getColor()); colors.put(Note.B, CrystalElement.PINK.getColor()); } public GuiCrystalMusic(EntityPlayer ep, TileEntityCrystalMusic te) { super(new CoreContainer(ep, te), ep, te); music = te; xSize = 240; ySize = 190; activeNote = 3; //qtr length = this.getNoteLength(activeNote); } @Override public void initGui() { super.initGui(); int j = (width - xSize) / 2; int k = (height - ySize) / 2; int r = 72; wheel = new PianoWheel(this, MusicKey.C3, 4, r, j+xSize/2, k+ySize/2+4, false); String file = "Textures/GUIs/musicoverlay.png"; buttonList.add(new CustomSoundImagedGuiButton(4, j+4, k+4, 19, 20, page == Pages.MIDI ? 209 : 228, 116, file, ChromatiCraft.class, this).setTooltip("Mode")); if (page == Pages.KEYS) { buttonList.add(new CustomSoundImagedGuiButton(0, j+4, k+4+20, 19, 20, 228, 136, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(1, j+23, k+4+20, 19, 20, 228, 156, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(6, j+42, k+4+20, 19, 20, 209, 156, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(2, j+4, k+4+40, 28, 20, 228, 196, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(3, j+32, k+4+40, 21, 20, 228, 176, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(9, j+4, k+4+120, 26, 20, music.isBasslineEnabled() ? 221 : 195, 57, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(7, j+4, k+4+140, 19, 19, music.isPaused() ? 209 : 228, 77, file, ChromatiCraft.class, this)); buttonList.add(new CustomSoundImagedGuiButton(8, j+23, k+4+140, 19, 19, 228, 97, file, ChromatiCraft.class, this)); } else { buttonList.add(new CustomSoundImagedGuiButton(5, j+4, k+4+20, 19, 20, 209, 136, file, ChromatiCraft.class, this)); } if (page == Pages.KEYS) { for (int i = 0; i < 6; i++) { int col = i%3; int row = i/3; int u = 60+col*20; int v = 216+row*20; if (rest) { u += 120; } if (i == activeNote) { u -= 60; } buttonList.add(new CustomSoundImagedGuiButton(50+i, j+48+4+r*2+8, k+ySize/2+(i-3)*20, 20, 20, u, v, file, ChromatiCraft.class, this)); } } if (page == Pages.KEYS) { int dx = (xSize-16*12)/2; for (int i = 0; i < 16; i++) { int u = 0+i*12; int v = i == channel ? 204 : 192; buttonList.add(new CustomSoundImagedGuiButton(16+i, j+dx+i*12, k+ySize-12-4, 12, 12, u, v, file, ChromatiCraft.class, this)); } } if (page == Pages.MIDI) { input = new GuiTextField(fontRendererObj, j+8, k+82, xSize-16, 16); input.setMaxStringLength(128); input.setFocused(false); input.setText(""); ticksPer = new GuiTextField(fontRendererObj, j+xSize/2+7, k+126, fontRendererObj.getStringWidth("60")*2, 16); ticksPer.setMaxStringLength(2); ticksPer.setFocused(false); ticksPer.setText("9"); } } @Override protected void actionPerformed(GuiButton b) { if (b.id == 0) { ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICCLEAR.ordinal(), music); } else if (b.id == 1) { ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICCLEARCHANNEL.ordinal(), music, channel); } else if (b.id == 2) { rest = !rest; } else if (b.id == 3) { music.dispatchDemo(); //in case serverside does not have functioning MIDI environment ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICDEMO.ordinal(), music); } else if (b.id == 4) { page = page.otherPage(); } else if (b.id == 5) { if (music.loadLocalMIDI(input.getText(), midiTickRate)) { ReikaSoundHelper.playClientSound(ChromaSounds.CAST, player, 1, 1); } else { ReikaSoundHelper.playClientSound(ChromaSounds.ERROR, player, 1, 1); } return; //prevent reinit and textbox clear } else if (b.id == 6) { ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICBKSP.ordinal(), music, channel); } else if (b.id == 7) { music.togglePause(); ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICPAUSE.ordinal(), music); } else if (b.id == 8) { ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICSTOP.ordinal(), music); } else if (b.id == 9) { music.toggleBass(); ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICBASS.ordinal(), music); } else if (b.id >= 16 && b.id < 32) { channel = b.id-16; } else if (b.id >= 50 && b.id < 56) { activeNote = b.id-50; length = this.getNoteLength(activeNote); } this.initGui(); } private int getNoteLength(int idx) { switch(idx) { case 0: return 48; case 1: return 36; case 2: return 24; case 3: return 12; case 4: return 6; case 5: return 3; default: return 0; } } @Override protected void mouseClicked(int x, int y, int b) { super.mouseClicked(x, y, b); if (page == Pages.KEYS) wheel.mouseClicked(b, x, y); else if (page == Pages.MIDI) { input.mouseClicked(x, y, b); ticksPer.mouseClicked(x, y, b); } } @Override protected void keyTyped(char c, int i){ if (i != mc.gameSettings.keyBindInventory.getKeyCode() && (input == null || !input.isFocused())) super.keyTyped(c, i); if (page == Pages.MIDI) { input.textboxKeyTyped(c, i); ticksPer.textboxKeyTyped(c, i); } } @Override public void updateScreen() { super.updateScreen(); if (page == Pages.MIDI && ticksPer != null) { midiTickRate = ReikaJavaLibrary.safeIntParse(ticksPer.getText()); midiTickRate = MathHelper.clamp_int(midiTickRate, 4, 60); midiBPM = 120*9/midiTickRate; //120 @ 9 } } @Override protected void drawGuiContainerForegroundLayer(int par1, int par2) { super.drawGuiContainerForegroundLayer(par1, par2); //fontRendererObj = Minecraft.getMinecraft().fontRenderer; int j = (width - xSize) / 2; int k = (height - ySize) / 2; } @Override protected void drawGuiContainerBackgroundLayer(float p, int a, int b) { super.drawGuiContainerBackgroundLayer(p, a, b); int j = (width - xSize) / 2; int k = (height - ySize) / 2; if (page == Pages.KEYS) { wheel.draw(false, false, false); GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); GL11.glEnable(GL11.GL_BLEND); BlendMode.DEFAULT.apply(); GL11.glDisable(GL11.GL_ALPHA_TEST); ReikaTextureHelper.bindTexture(ChromatiCraft.class, "Textures/GUIs/musicoverlay.png"); this.drawTexturedModalRect(wheel.originX-wheel.radius-16, wheel.originY-wheel.radius-16, 0, 0, 176, 176); GL11.glPopAttrib(); } else if (page == Pages.MIDI) { input.drawTextBox(); ticksPer.drawTextBox(); if (!input.isFocused()) { int d = input.getCursorPosition(); //fontRendererObj.drawStringWithShadow(file.substring(d, Math.min(file.length(), 37+d)), posX+10, posY+ySize-15, 0xaaaaaa); } ReikaGuiAPI.instance.drawCenteredStringNoShadow(fontRendererObj, "Select a MIDI file. Be sure to include the drive", j+xSize/2+1, k+60, 0xffffff); ReikaGuiAPI.instance.drawCenteredStringNoShadow(fontRendererObj, "letter and file extension and use \"/\", not \"\\\".", j+xSize/2+1, k+70, 0xffffff); ReikaGuiAPI.instance.drawCenteredStringNoShadow(fontRendererObj, "MC Ticks Per Beat: ", j+xSize/2+1-43, k+130, 0xffffff); fontRendererObj.drawString("("+midiBPM+" bpm)", j+xSize/2+1+37, k+130, 0xffffff); } } @Override public String getGuiTexture() { return "music"; } @Override public void onKeyPressed(MusicKey key) { ReikaSoundHelper.playClientSound(ChromaSounds.DING, player, 1, (float)CrystalMusicManager.instance.getPitchFactor(key)); for (CrystalElement e : CrystalMusicManager.instance.getColorsWithKey(key)) { music.playCrystal(music.worldObj, music.xCoord, music.yCoord, music.zCoord, e, length, key); } ReikaPacketHelper.sendPacketToServer(ChromatiCraft.packetChannel, ChromaPackets.MUSICNOTE.ordinal(), music, channel, key.ordinal(), length, rest ? 1 : 0); } @Override public int getColor(MusicKey key) { return colors.get(key.getNote()); } private static enum Pages { KEYS(), MIDI(); private Pages otherPage() { return this == KEYS ? MIDI : KEYS; } } }
412
0.901755
1
0.901755
game-dev
MEDIA
0.738791
game-dev,desktop-app
0.993842
1
0.993842
DuinOS/FreeRTOS
6,775
FreeRTOS/Demo/PPC440_Xilinx_Virtex5_GCC/__xps/system.gui
<SETTINGS> <SET CLASS="PROJECT" DISPLAYMODE="TREE" VIEW_ID="BUSINTERFACE"> <HEADERS HSCROLL="0" VSCROLL="0"> <VARIABLE COL_INDEX="0" COL_WIDTH="189" IS_VISIBLE="TRUE" VIEWDISP="Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="1" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Bus Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="2" IS_VISIBLE="FALSE" VIEWDISP="Bus Standard" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="3" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="IP Type" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="4" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="IP Version" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="5" COL_WIDTH="227" IS_VISIBLE="TRUE" VIEWDISP="IP Classification" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="6" IS_VISIBLE="FALSE" VIEWDISP="Type" VIEWTYPE="HEADER"/> </HEADERS> <SPLITTERS COLLAPSIBLE="1" HANDLEWIDTH="4" MARKER="255" ORIENTATION="1" RESIZE="1" SIZES="120,687,306" VERSION="0"/> <STATUS> <SELECTIONS/> </STATUS> </SET> <SET CLASS="PROJECT" DISPLAYMODE="FLAT" VIEW_ID="BUSINTERFACE"> <HEADERS> <VARIABLE COL_INDEX="0" IS_VISIBLE="TRUE" VIEWDISP="Instance" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="1" IS_VISIBLE="TRUE" VIEWDISP="Bus Interface" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="2" IS_VISIBLE="TRUE" VIEWDISP="Bus Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="3" IS_VISIBLE="FALSE" VIEWDISP="Bus Standard" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="4" IS_VISIBLE="TRUE" VIEWDISP="IP Type" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="5" IS_VISIBLE="TRUE" VIEWDISP="IP Version" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="6" IS_VISIBLE="TRUE" VIEWDISP="IP Classification" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="7" IS_VISIBLE="FALSE" VIEWDISP="Type" VIEWTYPE="HEADER"/> </HEADERS> <SPLITTERS COLLAPSIBLE="1" HANDLEWIDTH="4" MARKER="255" ORIENTATION="1" RESIZE="1" SIZES="180,450,180" VERSION="0"/> </SET> <SET CLASS="PROJECT" DISPLAYMODE="TREE" VIEW_ID="PORT"> <HEADERS HSCROLL="0" VSCROLL="0"> <VARIABLE COL_INDEX="0" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="1" COL_WIDTH="231" IS_VISIBLE="TRUE" VIEWDISP="Net" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="2" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Direction" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="3" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Range" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="4" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Class" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="5" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Frequency" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="6" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Reset Polarity" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="7" COL_WIDTH="100" IS_VISIBLE="TRUE" VIEWDISP="Sensitivity" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="8" COL_WIDTH="25" IS_VISIBLE="TRUE" VIEWDISP="IP Type" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="9" IS_VISIBLE="FALSE" VIEWDISP="IP Version" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="10" IS_VISIBLE="TRUE" VIEWDISP="IP Classification" VIEWTYPE="HEADER"/> </HEADERS> <SPLITTERS COLLAPSIBLE="1" HANDLEWIDTH="4" MARKER="255" ORIENTATION="1" RESIZE="1" SIZES="0,586,143" VERSION="0"/> </SET> <SET CLASS="PROJECT" DISPLAYMODE="FLAT" VIEW_ID="PORT"> <HEADERS> <VARIABLE COL_INDEX="0" IS_VISIBLE="TRUE" VIEWDISP="Instance" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="1" IS_VISIBLE="TRUE" VIEWDISP="Port Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="2" IS_VISIBLE="TRUE" VIEWDISP="Net" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="3" IS_VISIBLE="TRUE" VIEWDISP="Direction" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="4" IS_VISIBLE="TRUE" VIEWDISP="Range" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="5" IS_VISIBLE="TRUE" VIEWDISP="Class" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="6" IS_VISIBLE="TRUE" VIEWDISP="Frequency" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="7" IS_VISIBLE="TRUE" VIEWDISP="Reset Polarity" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="8" IS_VISIBLE="TRUE" VIEWDISP="Sensitivity" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="9" IS_VISIBLE="TRUE" VIEWDISP="IP Type" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="10" IS_VISIBLE="FALSE" VIEWDISP="IP Version" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="11" IS_VISIBLE="TRUE" VIEWDISP="IP Classification" VIEWTYPE="HEADER"/> </HEADERS> <SPLITTERS COLLAPSIBLE="1" HANDLEWIDTH="4" MARKER="255" ORIENTATION="1" RESIZE="1" SIZES="0,630,180" VERSION="0"/> </SET> <SET CLASS="PROJECT" DISPLAYMODE="TREE" VIEW_ID="ADDRESS"> <HEADERS> <VARIABLE COL_INDEX="0" IS_VISIBLE="TRUE" VIEWDISP="Instance" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="1" IS_VISIBLE="TRUE" VIEWDISP="Base Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="2" IS_VISIBLE="TRUE" VIEWDISP="Base Address" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="3" IS_VISIBLE="TRUE" VIEWDISP="High Address" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="4" IS_VISIBLE="TRUE" VIEWDISP="Size" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="5" IS_VISIBLE="TRUE" VIEWDISP="Bus Interface(s)" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="6" IS_VISIBLE="TRUE" VIEWDISP="Bus Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="7" IS_VISIBLE="TRUE" VIEWDISP="ICache" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="8" IS_VISIBLE="TRUE" VIEWDISP="DCache" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="9" IS_VISIBLE="TRUE" VIEWDISP="IP Type" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="10" IS_VISIBLE="TRUE" VIEWDISP="IP Version" VIEWTYPE="HEADER"/> </HEADERS> </SET> <SET CLASS="PROJECT" DISPLAYMODE="FLAT" VIEW_ID="ADDRESS"> <HEADERS> <VARIABLE COL_INDEX="0" IS_VISIBLE="TRUE" VIEWDISP="Instance" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="1" IS_VISIBLE="TRUE" VIEWDISP="Base Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="2" IS_VISIBLE="TRUE" VIEWDISP="Base Address" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="3" IS_VISIBLE="TRUE" VIEWDISP="High Address" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="4" IS_VISIBLE="TRUE" VIEWDISP="Size" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="5" IS_VISIBLE="TRUE" VIEWDISP="Bus Interface(s)" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="6" IS_VISIBLE="TRUE" VIEWDISP="Bus Name" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="7" IS_VISIBLE="TRUE" VIEWDISP="ICache" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="8" IS_VISIBLE="TRUE" VIEWDISP="DCache" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="9" IS_VISIBLE="TRUE" VIEWDISP="IP Type" VIEWTYPE="HEADER"/> <VARIABLE COL_INDEX="10" IS_VISIBLE="TRUE" VIEWDISP="IP Version" VIEWTYPE="HEADER"/> </HEADERS> </SET> </SETTINGS>
412
0.599115
1
0.599115
game-dev
MEDIA
0.206914
game-dev
0.546159
1
0.546159
Secrets-of-Sosaria/World
1,538
Data/Scripts/Items/Magical/God/Armor/Studded/LevelStuddedBustierArms.cs
using System; using Server.Items; namespace Server.Items { [FlipableAttribute( 0x1c0c, 0x1c0d )] public class LevelStuddedBustierArms : BaseLevelArmor { public override int BasePhysicalResistance{ get{ return 2; } } public override int BaseFireResistance{ get{ return 4; } } public override int BaseColdResistance{ get{ return 3; } } public override int BasePoisonResistance{ get{ return 3; } } public override int BaseEnergyResistance{ get{ return 4; } } public override int InitMinHits{ get{ return 35; } } public override int InitMaxHits{ get{ return 45; } } public override int AosStrReq{ get{ return 35; } } public override int OldStrReq{ get{ return 35; } } public override int ArmorBase{ get{ return 16; } } public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Studded; } } public override CraftResource DefaultResource{ get{ return CraftResource.RegularLeather; } } public override ArmorMeditationAllowance DefMedAllowance{ get{ return ArmorMeditationAllowance.Half; } } public override bool AllowMaleWearer{ get{ return false; } } [Constructable] public LevelStuddedBustierArms() : base( 0x1C0C ) { Weight = 1.0; } public LevelStuddedBustierArms( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
412
0.819612
1
0.819612
game-dev
MEDIA
0.822497
game-dev
0.844692
1
0.844692
KairuiLiu/ThreeCraft
1,944
src/controller/MultiPlay/players.ts
import * as THREE from 'three'; import Player from '../../core/player'; import { skinsMap } from '../../core/loader'; import { config } from '../config'; class PlayersController { players: Player[]; scene: THREE.Scene; playerNames: string[]; constructor() { this.players = []; this.playerNames = []; } update(name: string, pos: THREE.Vector3, reward: THREE.Euler) { this.players.forEach(d => { if (!d) return; if (Math.abs(d.position.x - config.state.posX) > config.renderer.stageSize / 2 || Math.abs(d.position.z - config.state.posZ) > config.renderer.stageSize / 2) d.player.visible = false; else d.player.visible = true; }); const idx = this.playerNames.findIndex(d => d === name); if (idx === -1) return; pos && this.players[idx].setPosition(pos); reward && this.players[idx].setRotation(reward); (pos || reward) && this.players[idx].update(); } init(roomId, scene: THREE.Scene, playerNames: string[]) { const st = Number.parseInt(roomId, 36); this.scene = scene; this.players = playerNames.map((d, i) => (d === null ? null : new Player({ idx: (st + i) % skinsMap.length, pos: new THREE.Vector3(0, 0, 0), reward: new THREE.Euler(0, 0, 0, 'YXZ') }))); this.playerNames = [...playerNames]; this.addScene(); } addScene() { this.players.forEach(d => { d && this.scene.add(d.player); }); } removeAll() { this.playerNames = []; this.players.forEach(d => { if (d === null) return; this.scene.remove(d.player); d.player.remove(); d = null; }); this.players = []; } removePlayer(playerName) { const idx = this.playerNames.findIndex(d => d === playerName); if (idx === -1) return; this.playerNames[idx] = null; this.scene.remove(this.players[idx].player); this.players[idx].player.remove(); this.players[idx] = null; } render() { this.players.forEach(d => { if (d === null) return; d.update(); }); } } export default PlayersController;
412
0.813496
1
0.813496
game-dev
MEDIA
0.565227
game-dev
0.937153
1
0.937153
derailed-dash/advent-of-code
22,098
src/AoC_2015/d22_wizards_factories_dataclass_generators/spell_casting.py
""" Author: Darren Date: 09/04/2021 Solving https://adventofcode.com/2015/day/22 Solution: Wizard class overrides Player class. Spell class has a factory method, to create instances of Spell, passing in SpellType dataclasss instances. Part 1: We need to find the combination of attacks that uses the least mana. We use a generator to yield successive attack combos. - The generator is infinite, so we need an exit condition. For each combo, we play the game and store the mana used. - Games are considered lost if the opponent wins, or a given spell combo is invalid (e.g. not enough mana). - As we yield the next combo, we skip any combos that have the same starting sequence as a previous game. - And we skip a combo that has a cost that is greater than a previous attack combo. - Caching the sorted attack_combo_lookup str reduces the overall time by about half. - If we've previously won with an attack of length n, and we couldn't find a better result with attack of length n+1, we're unlikely to find a better solution. So exit here. It works, but it requires a combo with 12 attacks for the lowest mana win. With 5 different attacks, this means 5**12 attack sequences, i.e. 244m different attack combos. This approach currently takes half an hour. Part 2: Simply deduct one hit point for every player turn in a game. This reduces the number of winning games. Fortunately, still solved with attack sequences with 12 attacks. """ from __future__ import annotations from enum import Enum from functools import cache import logging import time from math import ceil from dataclasses import dataclass from os import path from typing import Iterable import aoc_common.aoc_commons as ac locations = ac.get_locations(__file__) logger = ac.retrieve_console_logger(locations.script_name) logger.setLevel(logging.INFO) # td.setup_file_logging(logger, folder=locations.output_dir) BOSS_FILE = "boss_stats.txt" class Player: """A player has three key attributes: hit_points (life) - When this reaches 0, the player has been defeated damage - Attack strength armor - Attack defence Damage done per attack = this player's damage - opponent's armor. (With a min of 1.) Hit_points are decremented by an enemy attack. """ def __init__(self, name: str, hit_points: int, damage: int, armor: int): self._name = name self._hit_points = hit_points self._damage = damage self._armor = armor @property def name(self) -> str: return self._name @property def hit_points(self) -> int: return self._hit_points @property def armor(self) -> int: return self._armor @property def damage(self) -> int: return self._damage def take_hit(self, loss: int): """ Remove this hit from the current hit points """ self._hit_points -= loss def is_alive(self) -> bool: return self._hit_points > 0 def _damage_inflicted_on_opponent(self, other_player: Player) -> int: """Damage inflicted in an attack. Given by this player's damage minus other player's armor. Returns: damage inflicted per attack """ return max(self._damage - other_player.armor, 1) def get_attacks_needed(self, other_player: Player) -> int: """ The number of attacks needed for this player to defeat the other player. """ return ceil(other_player.hit_points / self._damage_inflicted_on_opponent(other_player)) def will_defeat(self, other_player: Player) -> bool: """ Determine if this player will win a fight with an opponent. I.e. if this player needs fewer (or same) attacks than the opponent. Assumes this player always goes first. """ return (self.get_attacks_needed(other_player) <= other_player.get_attacks_needed(self)) def attack(self, other_player: Player): """ Perform an attack on another player, inflicting damage """ attack_damage = self._damage_inflicted_on_opponent(other_player) other_player.take_hit(attack_damage) def __str__(self): return self.__repr__() def __repr__(self): return f"Player: {self._name}, hit points={self._hit_points}, damage={self._damage}, armor={self._armor}" @dataclass class SpellAttributes: """ Define the attributes of a Spell """ name: str mana_cost: int effect_duration: int is_effect: bool heal: int damage: int armor: int mana_regen: int delay_start: int class SpellType(Enum): """ Possible spell types. Any given spell_type.value will return an instance of SpellAttributes. """ MAGIC_MISSILES = SpellAttributes('MAGIC_MISSILES', 53, 0, False, 0, 4, 0, 0, 0) DRAIN = SpellAttributes('DRAIN', 73, 0, False, 2, 2, 0, 0, 0) SHIELD = SpellAttributes('SHIELD', 113, 6, True, 0, 0, 7, 0, 0) POISON = SpellAttributes('POISON', 173, 6, True, 0, 3, 0, 0, 0) RECHARGE = SpellAttributes('RECHARGE', 229, 5, True, 0, 0, 0, 101, 0) spell_key_lookup = { 0: SpellType.MAGIC_MISSILES, # 53 1: SpellType.DRAIN, # 73 2: SpellType.SHIELD, # 113 3: SpellType.POISON, # 173 4: SpellType.RECHARGE # 229 } spell_costs = {spell_key: spell_key_lookup[spell_key].value.mana_cost for spell_key, spell_type in spell_key_lookup.items()} @dataclass class Spell: """ Spells should be created using create_spell_by_type() factory method. Spells have a number of attributes. Of note: - effects last for multiple turns, and apply on both player and opponent turns. - duration is the number of turns an effect lasts for - mana is the cost of the spell """ name: str mana_cost: int effect_duration: int is_effect: bool heal: int = 0 damage: int = 0 armor: int = 0 mana_regen: int = 0 delay_start: int = 0 effect_applied_count = 0 # track how long an effect has been running @classmethod def check_spell_castable(cls, spell_type: SpellType, wiz: Wizard): """ Determine if this Wizard can cast this spell. Spell can only be cast if the wizard has sufficient mana, and if the spell is not already active. Raises: ValueError: If the spell is not castable Returns: [bool]: True if castable """ # not enough mana if wiz.mana < spell_type.value.mana_cost: raise ValueError(f"Not enough mana for {spell_type}. " \ f"Need {spell_type.value.mana_cost}, have {wiz.mana}.") # spell already active if spell_type in wiz.get_active_effects(): raise ValueError(f"Spell {spell_type} already active.") return True @classmethod def create_spell_by_type(cls, spell_type: SpellType): # Unpack the spell_type.value, which will be a SpellAttributes class # Get all the values, and unpack them, to pass into the factory method. attrs_dict = vars(spell_type.value) return cls(*attrs_dict.values()) def __repr__(self) -> str: return f"Spell: {self.name}, cost: {self.mana_cost}, " \ f"is effect: {self.is_effect}, remaining duration: {self.effect_duration}" def increment_effect_applied_count(self): self.effect_applied_count += 1 class Wizard(Player): """ Extends Player. Also has attribute 'mana', which powers spells. Wizard has no armor (except when provided by spells) and no inherent damage (except from spells). For each wizard turn, we must cast_spell() and apply_effects(). On each opponent's turn, we must apply_effects(). """ def __init__(self, name: str, hit_points: int, mana: int, damage: int = 0, armor: int = 0): """ Wizards have 0 mundane armor or damage. Args: name (str): Wizard name hit_points (int): Total life. mana (int): Used to power spells. damage (int, optional): mundane damage. Defaults to 0. armor (int, optional): mundane armor. Defaults to 0. """ super().__init__(name, hit_points, damage, armor) self._mana = mana # store currently active effects, where key = spell constant, and value = spell self._active_effects: dict[str, Spell] = {} @property def mana(self): return self._mana def use_mana(self, mana_used: int): if mana_used > self._mana: raise ValueError("Not enough mana!") self._mana -= mana_used def get_active_effects(self): return self._active_effects def take_turn(self, spell_key, other_player: Player) -> int: """ This player takes a turn. This means: casting a spell, applying any effects, and fading any expired effects Args: spell_key (str): The spell key, from SpellFactory.SpellConstants other_player (Player): The opponent Returns: int: The mana consumed by this turn """ self._turn(other_player) mana_consumed = self.cast_spell(spell_key, other_player) return mana_consumed def _turn(self, other_player: Player): self.apply_effects(other_player) self.fade_effects() def opponent_takes_turn(self, other_player: Player): """ An opponent takes their turn. (Not the wizard.) We must apply any Wizard effects on their turn (and fade), before their attack. This method does not include their attack. Args: other_player (Player): [description] """ self._turn(other_player) def cast_spell(self, spell_type: SpellType, other_player: Player) -> int: """ Casts a spell. - If spell is not an effect, it applies once. - Otherwise, it applies for the spell's duration, on both player and opponent turns. Args: spell_type (SpellType): a SpellType constant. other_player (Player): The player to cast against Returns: [int]: Mana consumed """ Spell.check_spell_castable(spell_type, self) # can this wizard cast this spell? spell = Spell.create_spell_by_type(spell_type) try: self.use_mana(spell.mana_cost) except ValueError as err: raise ValueError(f"Unable to cast {spell_type}: Not enough mana! " \ f"Needed {spell.mana_cost}; have {self._mana}.") from err logger.debug("%s casted %s", self._name, spell) if spell.is_effect: # add to active effects, apply later # this might replace a fading effect self._active_effects[spell_type.name] = spell else: # apply now. # opponent's armor counts for nothing against a magical attack attack_damage = spell.damage if attack_damage: logger.debug("%s attack. Inflicting damage: %s.", self._name, attack_damage) other_player.take_hit(attack_damage) heal = spell.heal if heal: logger.debug("%s: healing by %s.", self._name, heal) self._hit_points += heal return spell.mana_cost def fade_effects(self): effects_to_remove = [] for effect_name, effect in self._active_effects.items(): if effect.effect_applied_count >= effect.effect_duration: logger.debug("%s: fading effect %s", self._name, effect_name) if effect.armor: # restore armor to pre-effect levels self._armor -= effect.armor # Now we've faded the effect, flag it for removal effects_to_remove.append(effect_name) # now remove any effects flagged for removal for effect_name in effects_to_remove: self._active_effects.pop(effect_name) def apply_effects(self, other_player: Player): """ Apply effects in the active_effects dict. Args: other_player (Player): The opponent """ for effect_name, effect in self._active_effects.items(): # if effect should be active if we've used it fewer times than the duration if effect.effect_applied_count < effect.effect_duration: effect.increment_effect_applied_count() if logger.getEffectiveLevel() == logging.DEBUG: logger.debug("%s: applying effect %s, leaving %d turns.", self._name, effect_name, effect.effect_duration - effect.effect_applied_count) if effect.armor: if effect.effect_applied_count == 1: # increment armor on first use, and persist this level until the effect fades self._armor += effect.armor if effect.damage: other_player.take_hit(effect.damage) if effect.mana_regen: self._mana += effect.mana_regen def attack(self, other_player: Player): """ A Wizard cannot perform a mundane attack. Use cast_spell() instead. """ raise NotImplementedError("Wizards cast spells") def __repr__(self): return f"{self._name} (Wizard): hit points={self._hit_points}, " \ f"damage={self._damage}, armor={self._armor}, mana={self._mana}" def attack_combos_generator(count_different_attacks: int) -> Iterable[str]: """ Generator that returns the next attack combo. Pass in the number of different attack types. E.g. with 5 different attacks, it will generate... 0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, etc """ i = 0 while True: # convert i to base-n (where n is the number of attacks we can choose from) yield ac.to_base_n(i, count_different_attacks) i += 1 @cache # I think there are only about 3000 different sorted attacks def get_combo_mana_cost(attack_combo_lookup: str) -> int: """ Pass in attack combo lookup str, and return the cost of this attack combo. Ideally, the attack combo lookup should be sorted, because cost doesn't care about attack order; and providing a sorted value, we can use a cache. """ return sum(spell_costs[int(attack)] for attack in attack_combo_lookup) def main(): # boss stats are determined by an input file with open(path.join(locations.input_dir, BOSS_FILE), mode="rt") as f: boss_hit_points, boss_damage = process_boss_input(f.read().splitlines()) actual_boss = Player("Actual Boss", hit_points=boss_hit_points, damage=boss_damage, armor=0) test_boss = Player("Test Boss", hit_points=40, damage=10, armor=0) # test boss, which only requires 7 attacks player = Wizard("Bob", hit_points=50, mana=500) # winning_games, least_winning_mana = try_combos(test_boss, player, 11) winning_games, least_winning_mana = try_combos(actual_boss, player) message = "Winning solutions:\n" + "\n".join(f"Mana: {k}, Attack: {v}" for k, v in winning_games.items()) logger.info(message) logger.info("We found %d winning solutions. Lowest mana cost was %d.", len(winning_games), least_winning_mana) def try_combos(boss_stats: Player, plyr_stats: Wizard): logger.info(boss_stats) logger.info(plyr_stats) winning_games = {} least_winning_mana = 2500 # ball park of what will likely be larger than winning solution ignore_combo = "9999999" player_has_won = False last_attack_len = 0 # This is an infinite generator, so we need an exit condition for attack_combo_lookup in attack_combos_generator(len(spell_key_lookup)): # play the game with this attack combo # since attack combos are returned sequentially, # we can ignore any that start with the same attacks as the last failed combo. if attack_combo_lookup.startswith(ignore_combo): continue # determine if the cost of the current attack is going to be more than an existing # winning solution. (Sort it, so we can cache the attack cost.) sorted_attack = ''.join(sorted(attack_combo_lookup)) if get_combo_mana_cost(sorted_attack) >= least_winning_mana: continue # Much faster than a deep copy boss = Player(boss_stats.name, boss_stats.hit_points, boss_stats.damage, boss_stats.armor) player = Wizard(plyr_stats.name, plyr_stats.hit_points, plyr_stats.mana) if player_has_won and logger.getEffectiveLevel() == logging.DEBUG: logger.debug("Best winning attack: %s. Total mana: %s. Current attack: %s", winning_games[least_winning_mana], least_winning_mana, attack_combo_lookup) else: logger.debug("Current attack: %s", attack_combo_lookup) player_won, mana_consumed, rounds_started = play_game( attack_combo_lookup, player, boss, hard_mode=True, mana_target=least_winning_mana) if player_won: player_has_won = True winning_games[mana_consumed] = attack_combo_lookup least_winning_mana = min(mana_consumed, least_winning_mana) logger.info("Found a winning solution, with attack %s consuming %d", attack_combo_lookup, mana_consumed) attack_len = len(attack_combo_lookup) if (attack_len > last_attack_len): if player_has_won: # We can't play forever. Assume that if the last attack length didn't yield a better result # then we're not going to find a better solution. if len(attack_combo_lookup) > len(winning_games[least_winning_mana]) + 1: logger.info("Probably not getting any better. Exiting.") break # We're done! logger.info("Trying attacks of length %d", attack_len) last_attack_len = attack_len # we can ingore any attacks that start with the same attacks as what we tried last time ignore_combo = attack_combo_lookup[0:rounds_started] return winning_games, least_winning_mana def play_game(attack_combo_lookup: str, player: Wizard, boss: Player, hard_mode=False, **kwargs) -> tuple[bool, int, int]: """ Play a game, given a player (Wizard) and an opponent (boss) Args: attacks (list[str]): List of spells to cast, from SpellFactory.SpellConstants player (Wizard): A Wizard boss (Player): A mundane opponent hard_mode (Bool): Whether each player turn automatically loses 1 hit point mana_target (int): optional arg, that specifies a max mana consumed value which triggers a return Returns: tuple[bool, int, int]: player won, mana consumed, number of rounds """ # Convert the attack combo to a list of spells. E.g. convert '00002320' # to [<SpellType.MAGIC_MISSILES: ..., <SpellType.MAGIC_MISSILES: ..., # ... <SpellType.SHIELD: ..., <SpellType.MAGIC_MISSILES: ... >] attacks = [spell_key_lookup[int(attack)] for attack in attack_combo_lookup] game_round = 1 current_player = player other_player = boss mana_consumed: int = 0 mana_target = kwargs.get('mana_target', None) while (player.hit_points > 0 and boss.hit_points > 0): if current_player == player: # player (wizard) attack if logger.getEffectiveLevel() == logging.DEBUG: logger.debug("") logger.debug("Round %s...", game_round) logger.debug("%s's turn:", current_player.name) if hard_mode: logger.debug("Hard mode hit. Player hit points reduced by 1.") player.take_hit(1) if player.hit_points <= 0: logger.debug("Hard mode killed %s", boss.name) continue try: mana_consumed += player.take_turn(attacks[game_round-1], boss) if mana_target and mana_consumed > mana_target: logger.debug('Mana target %s exceeded; mana consumed=%s.', mana_target, mana_consumed) return False, mana_consumed, game_round except ValueError as err: logger.debug(err) return False, mana_consumed, game_round except IndexError: logger.debug("No more attacks left.") return False, mana_consumed, game_round else: logger.debug("%s's turn:", current_player.name) # effects apply before opponent attacks player.opponent_takes_turn(boss) if boss.hit_points <= 0: logger.debug("Effects killed %s!", boss.name) continue boss.attack(other_player) game_round += 1 if logger.getEffectiveLevel() == logging.DEBUG: logger.debug("End of turn: %s", player) logger.debug("End of turn: %s", boss) # swap players current_player, other_player = other_player, current_player player_won = player.hit_points > 0 return player_won, mana_consumed, game_round def process_boss_input(data:list[str]) -> tuple: """ Process boss file input and return tuple of hit_points, damage Returns: tuple: hit_points, damage """ boss = {} for line in data: key, val = line.strip().split(":") boss[key] = int(val) return boss['Hit Points'], boss['Damage'] if __name__ == "__main__": t1 = time.perf_counter() main() logger.info("Final cache size: %d", get_combo_mana_cost.cache_info().currsize) t2 = time.perf_counter() logger.info("Execution time: %.3f seconds", t2 - t1)
412
0.932198
1
0.932198
game-dev
MEDIA
0.949552
game-dev
0.962778
1
0.962778
glKarin/com.n0n3m4.diii4a
12,773
Q3E/src/main/jni/doom3/neo/idlib/bv/Bounds.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../precompiled.h" #pragma hdrstop idBounds bounds_zero(vec3_zero, vec3_zero); /* ============ idBounds::GetRadius ============ */ float idBounds::GetRadius(void) const { int i; float total, b0, b1; total = 0.0f; for (i = 0; i < 3; i++) { b0 = (float)idMath::Fabs(b[0][i]); b1 = (float)idMath::Fabs(b[1][i]); if (b0 > b1) { total += b0 * b0; } else { total += b1 * b1; } } return idMath::Sqrt(total); } /* ============ idBounds::GetRadius ============ */ float idBounds::GetRadius(const idVec3 &center) const { int i; float total, b0, b1; total = 0.0f; for (i = 0; i < 3; i++) { b0 = (float)idMath::Fabs(center[i] - b[0][i]); b1 = (float)idMath::Fabs(b[1][i] - center[i]); if (b0 > b1) { total += b0 * b0; } else { total += b1 * b1; } } return idMath::Sqrt(total); } /* ================ idBounds::PlaneDistance ================ */ float idBounds::PlaneDistance(const idPlane &plane) const { idVec3 center; float d1, d2; center = (b[0] + b[1]) * 0.5f; d1 = plane.Distance(center); d2 = idMath::Fabs((b[1][0] - center[0]) * plane.Normal()[0]) + idMath::Fabs((b[1][1] - center[1]) * plane.Normal()[1]) + idMath::Fabs((b[1][2] - center[2]) * plane.Normal()[2]); if (d1 - d2 > 0.0f) { return d1 - d2; } if (d1 + d2 < 0.0f) { return d1 + d2; } return 0.0f; } /* ================ idBounds::PlaneSide ================ */ int idBounds::PlaneSide(const idPlane &plane, const float epsilon) const { idVec3 center; float d1, d2; center = (b[0] + b[1]) * 0.5f; d1 = plane.Distance(center); d2 = idMath::Fabs((b[1][0] - center[0]) * plane.Normal()[0]) + idMath::Fabs((b[1][1] - center[1]) * plane.Normal()[1]) + idMath::Fabs((b[1][2] - center[2]) * plane.Normal()[2]); if (d1 - d2 > epsilon) { return PLANESIDE_FRONT; } if (d1 + d2 < -epsilon) { return PLANESIDE_BACK; } return PLANESIDE_CROSS; } /* ============ idBounds::LineIntersection Returns true if the line intersects the bounds between the start and end point. ============ */ bool idBounds::LineIntersection(const idVec3 &start, const idVec3 &end) const { float ld[3]; idVec3 center = (b[0] + b[1]) * 0.5f; idVec3 extents = b[1] - center; idVec3 lineDir = 0.5f * (end - start); idVec3 lineCenter = start + lineDir; idVec3 dir = lineCenter - center; ld[0] = idMath::Fabs(lineDir[0]); if (idMath::Fabs(dir[0]) > extents[0] + ld[0]) { return false; } ld[1] = idMath::Fabs(lineDir[1]); if (idMath::Fabs(dir[1]) > extents[1] + ld[1]) { return false; } ld[2] = idMath::Fabs(lineDir[2]); if (idMath::Fabs(dir[2]) > extents[2] + ld[2]) { return false; } idVec3 cross = lineDir.Cross(dir); if (idMath::Fabs(cross[0]) > extents[1] * ld[2] + extents[2] * ld[1]) { return false; } if (idMath::Fabs(cross[1]) > extents[0] * ld[2] + extents[2] * ld[0]) { return false; } if (idMath::Fabs(cross[2]) > extents[0] * ld[1] + extents[1] * ld[0]) { return false; } return true; } /* ============ idBounds::RayIntersection Returns true if the ray intersects the bounds. The ray can intersect the bounds in both directions from the start point. If start is inside the bounds it is considered an intersection with scale = 0 ============ */ bool idBounds::RayIntersection(const idVec3 &start, const idVec3 &dir, float &scale) const { int i, ax0, ax1, ax2, side, inside; float f; idVec3 hit; ax0 = -1; inside = 0; for (i = 0; i < 3; i++) { if (start[i] < b[0][i]) { side = 0; } else if (start[i] > b[1][i]) { side = 1; } else { inside++; continue; } if (dir[i] == 0.0f) { continue; } f = (start[i] - b[side][i]); if (ax0 < 0 || idMath::Fabs(f) > idMath::Fabs(scale * dir[i])) { scale = - (f / dir[i]); ax0 = i; } } if (ax0 < 0) { scale = 0.0f; // return true if the start point is inside the bounds return (inside == 3); } ax1 = (ax0+1)%3; ax2 = (ax0+2)%3; hit[ax1] = start[ax1] + scale * dir[ax1]; hit[ax2] = start[ax2] + scale * dir[ax2]; return (hit[ax1] >= b[0][ax1] && hit[ax1] <= b[1][ax1] && hit[ax2] >= b[0][ax2] && hit[ax2] <= b[1][ax2]); } /* ============ idBounds::FromTransformedBounds ============ */ void idBounds::FromTransformedBounds(const idBounds &bounds, const idVec3 &origin, const idMat3 &axis) { int i; idVec3 center, extents, rotatedExtents; center = (bounds[0] + bounds[1]) * 0.5f; extents = bounds[1] - center; for (i = 0; i < 3; i++) { rotatedExtents[i] = idMath::Fabs(extents[0] * axis[0][i]) + idMath::Fabs(extents[1] * axis[1][i]) + idMath::Fabs(extents[2] * axis[2][i]); } center = origin + center * axis; b[0] = center - rotatedExtents; b[1] = center + rotatedExtents; } /* ============ idBounds::FromPoints Most tight bounds for a point set. ============ */ void idBounds::FromPoints(const idVec3 *points, const int numPoints) { SIMDProcessor->MinMax(b[0], b[1], points, numPoints); } /* ============ idBounds::FromPointTranslation Most tight bounds for the translational movement of the given point. ============ */ void idBounds::FromPointTranslation(const idVec3 &point, const idVec3 &translation) { int i; for (i = 0; i < 3; i++) { if (translation[i] < 0.0f) { b[0][i] = point[i] + translation[i]; b[1][i] = point[i]; } else { b[0][i] = point[i]; b[1][i] = point[i] + translation[i]; } } } /* ============ idBounds::FromBoundsTranslation Most tight bounds for the translational movement of the given bounds. ============ */ void idBounds::FromBoundsTranslation(const idBounds &bounds, const idVec3 &origin, const idMat3 &axis, const idVec3 &translation) { int i; if (axis.IsRotated()) { FromTransformedBounds(bounds, origin, axis); } else { b[0] = bounds[0] + origin; b[1] = bounds[1] + origin; } for (i = 0; i < 3; i++) { if (translation[i] < 0.0f) { b[0][i] += translation[i]; } else { b[1][i] += translation[i]; } } } /* ================ BoundsForPointRotation only for rotations < 180 degrees ================ */ idBounds BoundsForPointRotation(const idVec3 &start, const idRotation &rotation) { int i; float radiusSqr; idVec3 v1, v2; idVec3 origin, axis, end; idBounds bounds; end = start * rotation; axis = rotation.GetVec(); origin = rotation.GetOrigin() + axis * (axis * (start - rotation.GetOrigin())); radiusSqr = (start - origin).LengthSqr(); v1 = (start - origin).Cross(axis); v2 = (end - origin).Cross(axis); for (i = 0; i < 3; i++) { // if the derivative changes sign along this axis during the rotation from start to end if ((v1[i] > 0.0f && v2[i] < 0.0f) || (v1[i] < 0.0f && v2[i] > 0.0f)) { if ((0.5f *(start[i] + end[i]) - origin[i]) > 0.0f) { bounds[0][i] = Min(start[i], end[i]); #ifdef _RAVEN // rvlib // RAVEN BEGIN bounds[1][i] = origin[i]; if( axis[i] * axis[i] < 1.0f ) { bounds[1][i] += idMath::Sqrt( radiusSqr * ( 1.0f - axis[i] * axis[i] ) ); } // RAVEN END #else bounds[1][i] = origin[i] + idMath::Sqrt(radiusSqr * (1.0f - axis[i] * axis[i])); #endif } else { #ifdef _RAVEN // rvlib // RAVEN BEGIN bounds[0][i] = origin[i]; if( axis[i] * axis[i] < 1.0f ) { bounds[0][i] -= idMath::Sqrt( radiusSqr * ( 1.0f - axis[i] * axis[i] ) ); } // RAVEN END #else bounds[0][i] = origin[i] - idMath::Sqrt(radiusSqr * (1.0f - axis[i] * axis[i])); #endif bounds[1][i] = Max(start[i], end[i]); } } else if (start[i] > end[i]) { bounds[0][i] = end[i]; bounds[1][i] = start[i]; } else { bounds[0][i] = start[i]; bounds[1][i] = end[i]; } } return bounds; } /* ============ idBounds::FromPointRotation Most tight bounds for the rotational movement of the given point. ============ */ void idBounds::FromPointRotation(const idVec3 &point, const idRotation &rotation) { float radius; if (idMath::Fabs(rotation.GetAngle()) < 180.0f) { (*this) = BoundsForPointRotation(point, rotation); } else { radius = (point - rotation.GetOrigin()).Length(); // FIXME: these bounds are usually way larger b[0].Set(-radius, -radius, -radius); b[1].Set(radius, radius, radius); } } /* ============ idBounds::FromBoundsRotation Most tight bounds for the rotational movement of the given bounds. ============ */ void idBounds::FromBoundsRotation(const idBounds &bounds, const idVec3 &origin, const idMat3 &axis, const idRotation &rotation) { int i; float radius; idVec3 point; idBounds rBounds; if (idMath::Fabs(rotation.GetAngle()) < 180.0f) { (*this) = BoundsForPointRotation(bounds[0] * axis + origin, rotation); for (i = 1; i < 8; i++) { point[0] = bounds[(i^(i>>1))&1][0]; point[1] = bounds[(i>>1)&1][1]; point[2] = bounds[(i>>2)&1][2]; (*this) += BoundsForPointRotation(point * axis + origin, rotation); } } else { point = (bounds[1] - bounds[0]) * 0.5f; radius = (bounds[1] - point).Length() + (point - rotation.GetOrigin()).Length(); // FIXME: these bounds are usually way larger b[0].Set(-radius, -radius, -radius); b[1].Set(radius, radius, radius); } } /* ============ idBounds::ToPoints Bounds -1 -20 -300, 1 20 300 P0: -1 -20 -300 Left-Forward-Bottom P1: 1 -20 -300 Right-Forward-Bottom P2: 1 20 -300 Right-Backward-Bottom P3: -1 20 -300 Left-Backward-Bottom P4: -1 -20 300 Left-Forward-Top P5: 1 -20 300 Right-Forward-Top P6: 1 20 300 Right-Backward-Top P7: -1 20 300 Left-Backward-Top maxs P7 ---------- P6 / | / | / | / | P4 --+------- P5 | | | | | | P3 -------+--- P2 | / | / | / | / P0 ---------- P1 mins ============ */ void idBounds::ToPoints(idVec3 points[8]) const { for (int i = 0; i < 8; i++) { points[i][0] = b[(i^(i>>1))&1][0]; points[i][1] = b[(i>>1)&1][1]; points[i][2] = b[(i>>2)&1][2]; } } #ifdef _RAVEN // jscott: for BSE attenuation /* ================ idBounds::ShortestDistance ================ */ float idBounds::ShortestDistance( const idVec3 &point ) const { int i; float delta, distance; if( ContainsPoint( point ) ) { return( 0.0f ); } distance = 0.0f; for( i = 0; i < 3; i++ ) { if( point[i] < b[0][i] ) { delta = b[0][i] - point[i]; distance += delta * delta; } else if ( point[i] > b[1][i] ) { delta = point[i] - b[1][i]; distance += delta * delta; } } return( idMath::Sqrt( distance ) ); } // abahr: idVec3 idBounds::FindEdgePoint( const idVec3& dir ) const { return FindEdgePoint( GetCenter(), dir ); } idVec3 idBounds::FindEdgePoint( const idVec3& start, const idVec3& dir ) const { idVec3 center( GetCenter() ); float radius = GetRadius( center ); idVec3 point( start + dir * radius ); float scale = 0.0f; RayIntersection( point, -dir, scale ); idVec3 p = point + -dir * scale; return p; } idVec3 idBounds::FindVectorToEdge( const idVec3& dir ) const { return idVec3( FindVectorToEdge(GetCenter(), dir) ); } idVec3 idBounds::FindVectorToEdge( const idVec3& start, const idVec3& dir ) const { return idVec3( FindEdgePoint(start, dir) - start ); } #endif
412
0.943678
1
0.943678
game-dev
MEDIA
0.553085
game-dev,graphics-rendering
0.994069
1
0.994069
Frodo45127/rpfm
2,478
rpfm_lib/src/files/tile_database/tile_set/mod.rs
//---------------------------------------------------------------------------// // Copyright (c) 2017-2024 Ismael Gutiérrez González. All rights reserved. // // This file is part of the Rusted PackFile Manager (RPFM) project, // which can be found here: https://github.com/Frodo45127/rpfm. // // This file is licensed under the MIT license, which can be found here: // https://github.com/Frodo45127/rpfm/blob/master/LICENSE. //---------------------------------------------------------------------------// use getset::*; use serde_derive::{Serialize, Deserialize}; use crate::binary::{ReadBytes, WriteBytes}; use crate::error::{Result, RLibError}; use crate::files::{Decodeable, EncodeableExtraData, Encodeable}; use super::*; mod v1; //---------------------------------------------------------------------------// // Enum & Structs //---------------------------------------------------------------------------// #[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)] #[getset(get = "pub", get_mut = "pub", set = "pub")] pub struct TileSet { serialise_version: u16, name: String, linking_tile: String, shared_geometry: String, also_place_tile_set: String, link_as_set: String, red: f32, green: f32, blue: f32, } //---------------------------------------------------------------------------// // Implementation of TileSet //---------------------------------------------------------------------------// impl Decodeable for TileSet { fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> { let mut decoded = Self::default(); decoded.serialise_version = data.read_u16()?; match decoded.serialise_version { 1 => decoded.read_v1(data, extra_data)?, _ => return Err(RLibError::DecodingFastBinUnsupportedVersion(String::from("TileSet"), decoded.serialise_version)), } Ok(decoded) } } impl Encodeable for TileSet { fn encode<W: WriteBytes>(&mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData>) -> Result<()> { buffer.write_u16(self.serialise_version)?; match self.serialise_version { 1 => self.write_v1(buffer, extra_data)?, _ => return Err(RLibError::EncodingFastBinUnsupportedVersion(String::from("TileSet"), self.serialise_version)), } Ok(()) } }
412
0.80176
1
0.80176
game-dev
MEDIA
0.192729
game-dev
0.921387
1
0.921387
CitizensDev/CitizensAPI
22,727
src/main/java/net/citizensnpcs/api/npc/NPC.java
package net.citizensnpcs.api.npc; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.ItemStack; import com.google.common.base.Optional; import com.google.common.reflect.TypeToken; import net.citizensnpcs.api.ai.GoalController; import net.citizensnpcs.api.ai.Navigator; import net.citizensnpcs.api.ai.speech.SpeechController; import net.citizensnpcs.api.astar.Agent; import net.citizensnpcs.api.event.DespawnReason; import net.citizensnpcs.api.event.NPCDespawnEvent; import net.citizensnpcs.api.event.NPCRemoveByCommandSenderEvent; import net.citizensnpcs.api.event.SpawnReason; import net.citizensnpcs.api.npc.BlockBreaker.BlockBreakerConfiguration; import net.citizensnpcs.api.trait.Trait; import net.citizensnpcs.api.trait.TraitFactory; import net.citizensnpcs.api.trait.trait.PlayerFilter; import net.citizensnpcs.api.util.BoundingBox; import net.citizensnpcs.api.util.DataKey; import net.kyori.adventure.text.Component; /** * Represents an NPC with optional {@link Trait}s. */ public interface NPC extends Agent, Cloneable { /** * Adds a {@link Runnable} that will run every tick. Note that removal is not yet supported. * * @param runnable * Runnable to be added */ public void addRunnable(Runnable runnable); /** * Adds a trait to this NPC. This will use the {@link TraitFactory} defined for this NPC to construct and attach a * trait using {@link #addTrait(Trait)}. * * @param trait * The class of the trait to add */ public void addTrait(Class<? extends Trait> trait); /** * Adds a trait to this NPC. * * @param trait * Trait to add */ public void addTrait(Trait trait); /** * @return A clone of the NPC. May not be an exact copy depending on the {@link Trait}s installed. */ public NPC clone(); /** * @return A clone of the NPC. May not be an exact copy depending on the {@link Trait}s installed. */ public NPC copy(); /** * @return The metadata store of this NPC. */ public MetadataStore data(); /** * Despawns this NPC. This is equivalent to calling {@link #despawn(DespawnReason)} with * {@link DespawnReason#PLUGIN}. * * @return Whether this NPC was able to despawn */ default boolean despawn() { return despawn(DespawnReason.PLUGIN); } /** * Despawns this NPC. * * @param reason * The reason for despawning, for use in {@link NPCDespawnEvent} * @return Whether this NPC was able to despawn */ public boolean despawn(DespawnReason reason); /** * Permanently removes this NPC and all data about it from the registry it's attached to. */ public void destroy(); /** * Permanently removes this NPC and all data about it from the registry it's attached to. * * @param source * The source of the removal */ default void destroy(CommandSender source) { Bukkit.getPluginManager().callEvent(new NPCRemoveByCommandSenderEvent(this, source)); destroy(); } /** * Faces a given {@link Location} if the NPC is spawned. */ public void faceLocation(Location location); /** * Creates a {@link BlockBreaker} that allows you to break blocks using the Minecraft breaking algorithm. */ public BlockBreaker getBlockBreaker(Block targetBlock, BlockBreakerConfiguration config); /** * Gets the default {@link GoalController} of this NPC. * * @return Default goal controller */ public GoalController getDefaultGoalController(); /** * Gets the default {@link SpeechController} of this NPC. * * @return Default speech controller */ public SpeechController getDefaultSpeechController(); /** * Gets the Bukkit entity associated with this NPC. This may be <code>null</code> if {@link #isSpawned()} is false. * * @return Entity associated with this NPC */ public Entity getEntity(); /** * Gets the full name of this NPC. * * @return Full name of this NPC */ public String getFullName(); /** * Gets the unique ID of this NPC. This is not guaranteed to be globally unique across server sessions. * * @return ID of this NPC */ public int getId(); /** * @see #setItemProvider(Supplier) */ public Supplier<ItemStack> getItemProvider(); /** * For certain mob types (currently, Players) it is beneficial to change the UUID slightly to signal to the client * that the mob is an NPC not a real mob. This will return {@link #getUniqueId()} with the necessary changes for the * current mob type. * * @return The client unique ID. */ public UUID getMinecraftUniqueId(); /** * Gets the name of this NPC with color codes stripped. * * @return Stripped name of this NPC */ public String getName(); /** * @return The {@link Navigator} of this NPC. */ public Navigator getNavigator(); /** * Gets a trait from the given class. If the NPC does not currently have the trait then it will be created and * attached using {@link #addTrait(Class)} . * * @param trait * Trait to get * @return Trait with the given name */ public <T extends Trait> T getOrAddTrait(Class<T> trait); /** * @return The {@link NPCRegistry} that created this NPC. */ public NPCRegistry getOwningRegistry(); String getRawName(); /** * If the NPC is not spawned, then this method will return the last known location, or null if it has never been * spawned. Otherwise, it is equivalent to calling <code>npc.getBukkitEntity().getLocation()</code>. * * @return The stored location, or <code>null</code> if none was found. */ public Location getStoredLocation(); /** * Gets a trait from the given class. If the NPC does not currently have the trait then it will be created and * attached using {@link #addTrait(Class)} . * * @param trait * Trait class * @return Trait with the given class * * @deprecated for intransparent naming. Use {@link #getOrAddTrait(Class)} for the same behavior. */ @Deprecated public <T extends Trait> T getTrait(Class<T> trait); /** * Gets the trait instance with the given class. If the NPC does not currently have the trait, <code>null</code> * will be returned. * * @param trait * Trait class * @return Trait with the given class */ public <T extends Trait> T getTraitNullable(Class<T> trait); /** * Gets the trait instance with the given class. If the NPC does not currently have the trait, * <code>Optional.absent()</code> will be returned. * * @param trait * Trait class * @return Trait with the given class */ public default <T extends Trait> Optional<T> getTraitOptional(Class<T> trait) { return Optional.<T> fromNullable(getTraitNullable(trait)); } /** * Returns the currently attached {@link Trait}s * * @return An Iterable of the current traits */ public Iterable<Trait> getTraits(); /** * Gets the unique id of this NPC. This is guaranteed to be unique for all NPCs. * * @return The unique id */ public UUID getUniqueId(); /** * Checks if this NPC has the given trait. * * @param trait * Trait to check * @return Whether this NPC has the given trait */ public boolean hasTrait(Class<? extends Trait> trait); /** * Returns whether this NPC is flyable or not. * * @return Whether this NPC is flyable */ default boolean isFlyable() { return data().get(NPC.Metadata.FLYABLE, false); } /** * Returns whether the given player can see the NPC (i.e. receive packets about it). * * @param player * The player to check * @return Whether the NPC is hidden from the player */ default boolean isHiddenFrom(Player player) { PlayerFilter filter = getTraitNullable(PlayerFilter.class); return filter != null ? filter.isHidden(player) : false; } /** * Gets whether this NPC is protected from damage, movement and other events that players and mobs use to change the * entity state of the NPC. * * @return Whether this NPC is protected */ default boolean isProtected() { return data().get(NPC.Metadata.DEFAULT_PROTECTED, true); } /** * Gets whether this NPC is pushable by fluids. * * @return Whether this NPC is pushable by fluids */ default boolean isPushableByFluids() { return data().get(NPC.Metadata.FLUID_PUSHABLE, !isProtected()); } /** * Gets whether this NPC is currently spawned. * * @return Whether this NPC is spawned */ public boolean isSpawned(); public boolean isUpdating(NPCUpdate update); /** * Loads the {@link NPC} from the given {@link DataKey}. This reloads all traits, respawns the NPC and sets it up * for execution. Should not be called often. * * @param key * The root data key */ public void load(DataKey key); /** * Removes a trait from this NPC. * * @param trait * Trait to remove */ public void removeTrait(Class<? extends Trait> trait); public boolean requiresNameHologram(); /** * Saves the {@link NPC} to the given {@link DataKey}. This includes all metadata, traits, and spawn information * that will allow it to respawn at a later time via {@link #load(DataKey)}. * * @param key * The root data key */ public void save(DataKey key); public void scheduleUpdate(NPCUpdate update); /** * Sets whether to always use a name hologram instead of the in-built Minecraft name. * * @param use * Whether to use a hologram */ default void setAlwaysUseNameHologram(boolean use) { data().setPersistent(NPC.Metadata.ALWAYS_USE_NAME_HOLOGRAM, use); } /** * Sets the {@link EntityType} of this NPC. The NPC will respawned if currently spawned, or will remain despawned * otherwise. * * @param type * The new mob type */ public void setBukkitEntityType(EntityType type); /** * Sets whether this NPC is <tt>flyable</tt> or not. Note that this is intended for normally <em>ground-based</em> * entities only - it will generally have no effect on mob types that were originally flyable. * * @param flyable * Should the NPC be flyable? */ default void setFlyable(boolean flyable) { data().setPersistent(NPC.Metadata.FLYABLE, flyable); } /** * For item-type NPCs, set a {@link Supplier} of the {@link ItemStack} to use when spawning the NPC. * * @param supplier * The supplier */ public void setItemProvider(Supplier<ItemStack> supplier); /** * Set the destination location to walk towards in a straight line using Minecraft movement. Should be called every * tick. * * @param destination * The destination {@link Location} */ public void setMoveDestination(Location destination); /** * Sets the name of this NPC. * * @param name * Name to give this NPC */ public void setName(String name); /** * A helper method to set the NPC as protected or not protected from damage/entity target events. Equivalent to * <code>npc.data().set(NPC.Metadata#DEFAULT_PROTECTED_METADATA, isProtected);</code> * * @param isProtected * Whether the NPC should be protected */ default void setProtected(boolean isProtected) { data().setPersistent(NPC.Metadata.DEFAULT_PROTECTED, isProtected); } public void setSneaking(boolean sneaking); /** * Set the NPC to use Minecraft AI where possible. Note that the NPC may not always behave exactly like a Minecraft * mob would because of additional Citizens APIs. */ default void setUseMinecraftAI(boolean use) { data().setPersistent(NPC.Metadata.USE_MINECRAFT_AI, use); } boolean shouldRemoveFromPlayerList(); /** * @return Whether to remove the NPC from the tablist. Only applicable for {@link Player}-type NPCs. */ public boolean shouldRemoveFromTabList(); /** * Attempts to spawn this NPC. * * @param location * Location to spawn this NPC * @return Whether this NPC was able to spawn at the location */ default boolean spawn(Location location) { return spawn(location, SpawnReason.PLUGIN); } /** * Attempts to spawn this NPC. * * @param location * Location to spawn this NPC * @param reason * Reason for spawning * @return Whether this NPC was able to spawn at the location */ default boolean spawn(Location location, SpawnReason reason) { return spawn(location, SpawnReason.PLUGIN, null); } /** * Attempts to spawn this NPC. * * @param at * Location to spawn this NPC * @param reason * Reason for spawning * @param callback * The callback to run once entity is spawned * @return Whether this NPC was able to spawn at the location */ public boolean spawn(Location at, SpawnReason reason, Consumer<Entity> callback); /** * An alternative to <code>npc.getEntity().getLocation()</code> that teleports passengers as well. * * @param location * The destination location * @param cause * The cause for teleporting */ public void teleport(Location location, TeleportCause cause); /** * Whether the NPC is currently set to use Minecraft AI. Defaults to false. */ default boolean useMinecraftAI() { return data().get(NPC.Metadata.USE_MINECRAFT_AI, false); } public enum Metadata { /** The activation range. Integer, defaults to the server's configured activation range. */ ACTIVATION_RANGE("activation-range", Integer.class), AGGRESSIVE("entity-aggressive", Boolean.class), ALWAYS_USE_NAME_HOLOGRAM("always-use-name-hologram", Boolean.class), /** * The Minecraft ambient sound played. */ AMBIENT_SOUND("ambient-sound", String.class), @SuppressWarnings("serial") BOUNDING_BOX_FUNCTION("bounding-box-function", new TypeToken<Supplier<BoundingBox>>() { }, false), /** * Whether the NPC is collidable with Players or not. */ COLLIDABLE("collidable", Boolean.class), /** * Whether the NPC can damage other Entities. */ DAMAGE_OTHERS("damage-others", Boolean.class), /** * The Minecraft sound played when the NPC dies. String - Minecraft sound name. */ DEATH_SOUND("death-sound", String.class), /** * Whether the NPC is 'protected' i.e. invulnerable to damage. */ DEFAULT_PROTECTED("protected", Boolean.class), /** * Whether to disable the default stuck action (teleport to destination is default). */ DISABLE_DEFAULT_STUCK_ACTION("disable-default-stuck-action", Boolean.class), /** * Whether the NPC drops its inventory after death. */ DROPS_ITEMS("drops-items", Boolean.class), /** * Whether the NPC is pushable by fluids. */ FLUID_PUSHABLE("fluid-pushable", Boolean.class), /** * Whether the NPC is 'flyable' i.e. will fly when pathfinding. */ FLYABLE("flyable", Boolean.class), /** Forces a singular packet update. */ FORCE_PACKET_UPDATE("force-packet-update", Boolean.class), /** * Whether the NPC is currently glowing. */ GLOWING("glowing", Boolean.class), HOLOGRAM_RENDERER("hologram-renderer", TypeToken.of(Object.class), false), /** * The Minecraft sound to play when hurt. */ HURT_SOUND("hurt-sound", String.class), /** * The Item amount. */ ITEM_AMOUNT("item-type-amount", Integer.class), /** * The Item data. */ ITEM_DATA("item-type-data", Byte.class), /** * The Item ID. String. */ ITEM_ID("item-type-id", String.class), @SuppressWarnings("serial") JUMP_POWER_SUPPLIER("jump-power-supplier", new TypeToken<Function<NPC, Float>>() { }, false), /** * Whether to keep chunk loaded. */ KEEP_CHUNK_LOADED("keep-chunk-loaded", Boolean.class), /** Simple knockback toggle. Not set by default. */ KNOCKBACK("knockback", Boolean.class), /** * Whether the NPC is leashable. */ LEASH_PROTECTED("protected-leash", Boolean.class), /** * The Minecart item offset as defined by Minecraft. {@link Minecart#setDisplayBlockOffset(int)} */ MINECART_OFFSET("minecart-item-offset", Integer.class), /** * Whether the NPC's nameplate should be visible. */ NAMEPLATE_VISIBLE("nameplate-visible", TypeToken.of(Boolean.class), false), /** Internal use only */ NPC_SPAWNING_IN_PROGRESS("citizens-internal-spawning-npc", Boolean.class), /** * The packet update delay in ticks. Defaults to setting value. */ PACKET_UPDATE_DELAY("packet-update-delay", Integer.class), /** * Whether to open doors while pathfinding. */ PATHFINDER_OPEN_DOORS("pathfinder-open-doors", Boolean.class), /** * Whether to pick up items. Defaults to !isProtected(). */ PICKUP_ITEMS("pickup-items", Boolean.class), /** * Whether to remove players from the player list. Defaults to true. */ REMOVE_FROM_PLAYERLIST("removefromplayerlist", Boolean.class), /** Whether to remove the NPC from the tablist. Defaults to the value in config.yml */ REMOVE_FROM_TABLIST("removefromtablist", Boolean.class), /** * Whether to reset entity pitch to <code>0</code> every tick (default Minecraft behaviour). Defaults to false. */ RESET_PITCH_ON_TICK("reset-pitch-on-tick", Boolean.class), /** * Whether to reset NPC yaw on spawn. Defaults to the config value (true by default). */ RESET_YAW_ON_SPAWN("reset-yaw-on-spawn", Boolean.class), /** * The Integer delay to respawn in ticks after death. Only works if non-zero. */ RESPAWN_DELAY("respawn-delay", Integer.class), /** * The fake NPC scoreboard team name because Minecraft requires a team name. Usually will be a random UUID in * String form. */ SCOREBOARD_FAKE_TEAM_NAME("fake-scoreboard-team-name", String.class), /** * Whether to save / persist across server restarts. */ SHOULD_SAVE("should-save", Boolean.class), /** * Whether to suppress sounds. */ SILENT("silent-sounds", Boolean.class), /** * The initial no damage ticks on spawn, defaults to 20. Integer */ SPAWN_NODAMAGE_TICKS("spawn-nodamage-ticks", Integer.class), /** * Whether to allow swimming. Boolean. */ SWIM("swim", Boolean.class), TEXT_DISPLAY_COMPONENT("text-display-component", TypeToken.of(Component.class), false), /** * The tracking distance for packets. Defaults to the default tracking distance defined by the server */ TRACKING_RANGE("tracking-distance", Integer.class), /** * Whether to use Minecraft AI. */ USE_MINECRAFT_AI("minecraft-ai", Boolean.class), /** * Whether player is actively using held item. Defaults to false. */ USING_HELD_ITEM("using-held-item", Boolean.class), /** * Whether player is actively using offhand item. Defaults to false. */ USING_OFFHAND_ITEM("using-offhand-item", Boolean.class), /** * Whether to block Minecraft villager trades. Defaults to true. */ VILLAGER_BLOCK_TRADES("villager-trades", Boolean.class), /** * Speed modifier in water, percentage. */ WATER_SPEED_MODIFIER("water-speed-modifier", Float.class); private final String key; private final boolean strict; private final TypeToken<?> type; Metadata(String key, Class<?> type) { this(key, TypeToken.of(type), true); } Metadata(String key, TypeToken<?> type) { this(key, type, true); } Metadata(String key, TypeToken<?> type, boolean strict) { this.key = key; this.type = type; this.strict = strict; } public boolean accepts(Class<? extends Object> clazz) { return !strict || type.isSupertypeOf(clazz); } public String getKey() { return key; } public TypeToken<?> getType() { return type; } public static Metadata byKey(String name) { for (Metadata v : NPC.Metadata.values()) { if (v.key.equals(name)) return v; } return null; } public static Metadata byName(String name) { try { return valueOf(name); } catch (IllegalArgumentException iae) { return null; } } } public enum NPCUpdate { PACKET; } }
412
0.783043
1
0.783043
game-dev
MEDIA
0.921871
game-dev
0.771736
1
0.771736
mattgodbolt/reddog
5,631
dreamcast/reddog/game/strats/multibot.dst
// type 1 is normal and type 0 is for the raft or train PARAMINT type 0 DEFINE SPEED 0.8 DEFINE X_FIRE 5.0 DEFINE Y_FIRE 3.0 DEFINE Z_FIRE 3.0 DEFINE MOVE_FACT 3.0 DEFINE SHOCK_SIZE 0.8 DEFINE SHOCK_WIDTH 3.0 DEFINE TWOWAY_MAX_SPEED 1.0 LOCALFLOAT tx LOCALFLOAT ty LOCALFLOAT tz LOCALFLOAT time LOCALINT fire LOCALINT pin LOCALINT Lightning LOCALFLOAT fireTime LOCALFLOAT tempf LOCALFLOAT twoWaySpeed LOCALFLOAT twoWayAcc STATE Init MyFlag = MyFlag | STRATCOLL | ENEMY | TARGETABLE | LOWCOLL OBJECT>ENEMIES\MultiBot RegisterCollision() TRIGSET>SpecularMadness EVERY 1 time = 0.0 fire = 0 health = 200.0 pin = 0.0 twoWaySpeed = 0 twoWayAcc = 0.05 fireTime = 0.0 TRIGSET>Firing EVERY 1 InitPath() InitSplineData() IF (type = 1) STAT>HoverBotTwoWayStart ELSE STAT>HoverBotOneWayStart ENDIF ENDSTATE LOCALFLOAT SPECAMOUNT TRIGGER SpecularMadness UpdateTrigFlag(TRIG_ALWAYS_RUN) IF ((MyFlag & HITSTRAT) AND (CollWithFlag & BULLETTYPE)) SPECAMOUNT = 1.0 ENDIF IF (SPECAMOUNT > 0) MyFlag2 = MyFlag2 | SPECULAR SetSpecularColour(0, SPECAMOUNT,SPECAMOUNT,SPECAMOUNT) SPECAMOUNT = SPECAMOUNT - 0.1 ELSE SPECAMOUNT = 0 MyFlag2 = MyFlag2 & LNOT(SPECULAR) ENDIF TRIGFIN ENDTRIGGER TRIGGER Firing IF (health > 0.0) IF (fire > 0) fireTime = fireTime + 1.0 IF (fireTime > 10.0) fire = fire + 1 fireTime = 0.0 ENDIF MyStratToWorld(0.0, Y_FIRE, 0.0) tx = CheckX ty = CheckY tz = CheckZ IF (fire < 13) IMMLOOP (fire) tempf = RandRange(0.0, 12.0) pin = TOINT(tempf) IF (pin = 0) MyStratToWorld(-X_FIRE, Y_FIRE, 0.0) ENDIF IF (pin = 1) MyStratToWorld(X_FIRE, Y_FIRE, 0.0) ENDIF IF (pin = 2) MyStratToWorld(0.0, Y_FIRE, Z_FIRE) ENDIF IF (pin = 3) MyStratToWorld(0.0, Y_FIRE, -Z_FIRE) ENDIF IF (pin = 4) MyStratToWorld(-X_FIRE, Y_FIRE, -Z_FIRE) ENDIF IF (pin = 5) MyStratToWorld(-X_FIRE, Y_FIRE, Z_FIRE) ENDIF IF (pin = 6) MyStratToWorld(X_FIRE, Y_FIRE, -Z_FIRE) ENDIF IF (pin = 7) MyStratToWorld(X_FIRE, Y_FIRE, Z_FIRE) ENDIF IF (pin = 8) MyStratToWorld(1.9 * X_FIRE, Y_FIRE, 0.0) ENDIF IF (pin = 9) MyStratToWorld(-1.9 * X_FIRE, Y_FIRE, 0.0) ENDIF IF (pin = 10) MyStratToWorld(0.0, Y_FIRE, 1.6 * Z_FIRE) ENDIF IF (pin = 11) MyStratToWorld(0.0, Y_FIRE, 1.6 * -Z_FIRE) ENDIF IF (pin = 13) MyStratToWorld(0.0, Y_FIRE, 0.0) ENDIF DrawShock(CheckX, CheckY, CheckZ, tx, ty, tz, SHOCK_SIZE, 1.0, 1.0) tx = CheckX ty = CheckY tz = CheckZ IMMENDLOOP ENDIF IF ((fire = 13) AND (PlayerHealth > 0.0)) Lightning = DrawLightning (0, -X_FIRE, Y_FIRE, 0.0, Lightning,0) Lightning = DrawLightning (0, X_FIRE, Y_FIRE, 0.0, Lightning,0) Lightning = DrawLightning (0, 0.0, Y_FIRE, Z_FIRE, Lightning,0) Lightning = DrawLightning (0, 0.0, Y_FIRE, -Z_FIRE, Lightning,0) PlayerHealth = PlayerHealth - 3.0 ENDIF IF (fire = 14) fireTime = 0 fire = 0 ENDIF ENDIF ENDIF ENDSTATE STATE HoverBotOneWayStart IF (health <= 0.0) STAT>Die ENDIF time = time + 0.1 MoveAlongPath(SPEED) x = x + (Ssin(time * 0.6) * MOVE_FACT) y = y + (Ssin(time * 1.2) * MOVE_FACT) z = z + (Ssin(time * 0.8) * MOVE_FACT) PointToXY(DogX, DogY, DogZ) IF (fire = 0) IF (NearPlayerXY(50)) IF (RandRange(0.0, 50.0) < 1.0) fire = 1 ENDIF ENDIF ENDIF ENDSTATE STATE HoverBotTwoWayStart IF (health <= 0.0) STAT>Die ENDIF time = time + 0.1 IF (!NearPlayerXY(49)) MoveAlongPath(twoWaySpeed) IF (twoWaySpeed < TWOWAY_MAX_SPEED) twoWaySpeed = twoWaySpeed + twoWayAcc ENDIF ELSE IF (NearPlayerXY(40)) MoveAlongPath(twoWaySpeed) IF (twoWaySpeed > -TWOWAY_MAX_SPEED) twoWaySpeed = twoWaySpeed - twoWayAcc ENDIF ELSE twoWaySpeed = twoWaySpeed * 0.9 MoveAlongPath(twoWaySpeed) ENDIF ENDIF x = x + (Ssin(time * 0.6) * MOVE_FACT) y = y + (Ssin(time * 1.2) * MOVE_FACT) z = z + (Ssin(time * 0.8) * MOVE_FACT) PointToXY(DogX, DogY, DogZ) IF (fire = 0) IF (NearPlayerXY(50)) IF (RandRange(0.0, 50.0) < 1.0) fire = 1 ENDIF ENDIF ENDIF ENDSTATE STATE Die CREATE SPAWN_BLASTEXP 0, 0, 0, 0, 0, 0, 0 SetGlobalParamInt(0, 0) SetGlobalParamInt(1, type) CREATE SPAWN_MultiBotChild 0, 0, 0, 0, 0, 0, 0 SetGlobalParamInt(0, 1) SetGlobalParamInt(1, type) CREATE SPAWN_MultiBotChild 0, 0, 0, 0, 0, 0, 0 SetGlobalParamInt(0, 2) SetGlobalParamInt(1, type) CREATE SPAWN_MultiBotChild 0, 0, 0, 0, 0, 0, 0 SetGlobalParamInt(0, 3) SetGlobalParamInt(1, type) CREATE SPAWN_MultiBotChild 0, 0, 0, 0, 0, 0, 0 SetGlobalParamInt(0, 0) MyVar = 0.0 MyFlag = MyFlag | NODISP MyFlag = MyFlag & LNOT(TARGETABLE | STRATCOLL) IF (type = 1) STAT>TwoWayContinue ELSE STAT>OneWayContinue ENDIF ENDSTATE STATE OneWayContinue MoveAlongPath(SPEED) PointToXY(DogX, DogY, DogZ) IF (MyVar = 4.0) Delete() ENDIF ENDSTATE STATE TwoWayContinue IF (!NearPlayerXY(49)) MoveAlongPath(twoWaySpeed) IF (twoWaySpeed < TWOWAY_MAX_SPEED) twoWaySpeed = twoWaySpeed + twoWayAcc ENDIF ELSE IF (NearPlayerXY(40)) MoveAlongPath(twoWaySpeed) IF (twoWaySpeed > -TWOWAY_MAX_SPEED) twoWaySpeed = twoWaySpeed - twoWayAcc ENDIF ELSE twoWaySpeed = twoWaySpeed * 0.9 MoveAlongPath(twoWaySpeed) ENDIF ENDIF time = time + 0.1 x = x + (Ssin(time * 0.6) * MOVE_FACT) y = y + (Ssin(time * 1.2) * MOVE_FACT) z = z + (Ssin(time * 0.8) * MOVE_FACT) PointToXY(DogX, DogY, DogZ) IF (MyVar = 4.0) Delete() ENDIF ENDSTATE
412
0.713988
1
0.713988
game-dev
MEDIA
0.90722
game-dev
0.890223
1
0.890223
MATTYOneInc/AionEncomBase_Java8
5,186
AL-Game/src/com/aionemu/gameserver/network/aion/clientpackets/CM_HOUSE_TELEPORT.java
/* * * Encom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Encom 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Encom. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.network.aion.clientpackets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.aionemu.commons.utils.Rnd; import com.aionemu.gameserver.model.TeleportAnimation; import com.aionemu.gameserver.model.gameobjects.VisibleObject; import com.aionemu.gameserver.model.gameobjects.player.Friend; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.house.House; import com.aionemu.gameserver.model.house.HousePermissions; import com.aionemu.gameserver.model.team.legion.Legion; import com.aionemu.gameserver.model.templates.housing.HouseAddress; import com.aionemu.gameserver.network.aion.AionClientPacket; import com.aionemu.gameserver.network.aion.AionConnection.State; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.services.HousingService; import com.aionemu.gameserver.services.instance.InstanceService; import com.aionemu.gameserver.services.teleport.TeleportService2; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.world.World; import com.aionemu.gameserver.world.WorldMapInstance; public class CM_HOUSE_TELEPORT extends AionClientPacket { int actionId; int playerId1; int playerId2; public CM_HOUSE_TELEPORT(int opcode, State state, State... restStates) { super(opcode, state, restStates); } @Override protected void readImpl() { actionId = readC(); playerId1 = readD(); playerId2 = readD(); } @Override protected void runImpl() { Player player1 = World.getInstance().findPlayer(playerId1); if (player1 == null || !player1.isOnline()) { return; } House house = null; if (actionId == 1) { playerId2 = playerId1; } else if (actionId == 3) { List<Integer> relationIds = new ArrayList<Integer>(); Iterator<Friend> friends = player1.getFriendList().iterator(); int address = 0; while (friends.hasNext()) { int friendId = friends.next().getOid(); address = HousingService.getInstance().getPlayerAddress(friendId); if (address != 0) { house = HousingService.getInstance().getPlayerStudio(friendId); if (house == null) { house = HousingService.getInstance().getHouseByAddress(address); } if (house.getDoorState() == HousePermissions.DOOR_CLOSED || house.getLevelRestrict() > player1.getLevel()) { continue; } relationIds.add(friendId); } } Legion legion = player1.getLegion(); if (legion != null) { for (int memberId : legion.getLegionMembers()) { address = HousingService.getInstance().getPlayerAddress(memberId); if (address != 0) { house = HousingService.getInstance().getPlayerStudio(memberId); if (house == null) { house = HousingService.getInstance().getHouseByAddress(address); } if (house.getDoorState() == HousePermissions.DOOR_CLOSED || house.getLevelRestrict() > player1.getLevel()) { continue; } relationIds.add(memberId); } } } if (relationIds.size() == 0) { PacketSendUtility.sendPacket(player1, SM_SYSTEM_MESSAGE.STR_MSG_NO_RELATIONSHIP_RECENTLY); return; } playerId2 = relationIds.get(Rnd.get(relationIds.size())); } if (playerId2 == 0) { return; } house = HousingService.getInstance().getPlayerStudio(playerId2); HouseAddress address = null; int instanceId = 0; if (house != null) { address = house.getAddress(); WorldMapInstance instance = InstanceService.getPersonalInstance(address.getMapId(), playerId2); if (instance == null) { instance = InstanceService.getNextAvailableInstance(address.getMapId(), playerId2); } instanceId = instance.getInstanceId(); InstanceService.registerPlayerWithInstance(instance, player1); } else { int addressId = HousingService.getInstance().getPlayerAddress(playerId2); house = HousingService.getInstance().getHouseByAddress(addressId); if (house == null || house.getLevelRestrict() > player1.getLevel()) { return; } address = house.getAddress(); instanceId = house.getInstanceId(); } VisibleObject target = player1.getTarget(); if (target != null) { PacketSendUtility.sendPacket(player1, new SM_DIALOG_WINDOW(target.getObjectId(), 0)); } TeleportService2.teleportTo(player1, address.getMapId(), instanceId, address.getX(), address.getY(), address.getZ(), (byte) 0, TeleportAnimation.BEAM_ANIMATION); } }
412
0.691665
1
0.691665
game-dev
MEDIA
0.820673
game-dev
0.817674
1
0.817674
Dzierzan/OpenSA
4,088
OpenRA.Mods.OpenSA/Warheads/FireFragmentWarhead.cs
#region Copyright & License Information /* * Copyright The OpenSA Developers (see CREDITS) * This file is part of OpenSA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using System; using System.Linq; using OpenRA.GameRules; using OpenRA.Mods.Common.Traits; using OpenRA.Mods.Common.Warheads; using OpenRA.Traits; namespace OpenRA.Mods.OpenSA.Warheads { [Desc("Allows to fire a weapon to a directly specified target position relative to the warhead explosion.")] public class FireFragmentWarhead : Warhead, IRulesetLoaded<WeaponInfo> { [WeaponReference] [FieldLoader.Require] [Desc("Has to be defined in weapons.yaml as well.")] public readonly string Weapon = null; [Desc("Percentual chance the fragment is fired.")] public readonly int Chance = 100; [Desc("Target offsets relative to warhead explosion.")] public readonly WVec[] Offsets = { new WVec(0, 0, 0) }; [Desc("If set, Offset's Z value will be used as absolute height instead of explosion height.")] public readonly bool UseZOffsetAsAbsoluteHeight = false; [Desc("Should the weapons be fired around the intended target or at the explosion's epicenter.")] public readonly bool AroundTarget = false; [Desc("Rotate the fragment weapon based on the impact orientation.")] public readonly bool Rotate = false; WeaponInfo weapon; public void RulesetLoaded(Ruleset rules, WeaponInfo info) { if (!rules.Weapons.TryGetValue(Weapon.ToLowerInvariant(), out weapon)) throw new YamlException($"Weapons Ruleset does not contain an entry '{Weapon.ToLowerInvariant()}'"); } public override void DoImpact(in Target target, WarheadArgs args) { var firedBy = args.SourceActor; if (!target.IsValidFor(firedBy)) return; var world = firedBy.World; var map = world.Map; if (Chance < world.SharedRandom.Next(100)) return; var epicenter = AroundTarget && args.WeaponTarget.Type != TargetType.Invalid ? args.WeaponTarget.CenterPosition : target.CenterPosition; foreach (var offset in Offsets) { var targetVector = offset; if (Rotate && args.ImpactOrientation != WRot.None) targetVector = targetVector.Rotate(args.ImpactOrientation); var fragmentTargetPosition = epicenter + targetVector; if (UseZOffsetAsAbsoluteHeight) { fragmentTargetPosition = new WPos(fragmentTargetPosition.X, fragmentTargetPosition.Y, world.Map.CenterOfCell(world.Map.CellContaining(fragmentTargetPosition)).Z + offset.Z); } var targetPostion = target.CenterPosition; var fragmentTarget = Target.FromPos(fragmentTargetPosition); var fragmentFacing = (fragmentTargetPosition - target.CenterPosition).Yaw; var projectileArgs = new ProjectileArgs { Weapon = weapon, Facing = fragmentFacing, CurrentMuzzleFacing = () => fragmentFacing, DamageModifiers = args.DamageModifiers, InaccuracyModifiers = !firedBy.IsDead ? firedBy.TraitsImplementing<IInaccuracyModifier>() .Select(a => a.GetInaccuracyModifier()).ToArray() : Array.Empty<int>(), RangeModifiers = !firedBy.IsDead ? firedBy.TraitsImplementing<IRangeModifier>() .Select(a => a.GetRangeModifier()).ToArray() : Array.Empty<int>(), Source = targetPostion, CurrentSource = () => targetPostion, SourceActor = firedBy, GuidedTarget = fragmentTarget, PassiveTarget = fragmentTargetPosition }; if (projectileArgs.Weapon.Projectile != null) { var projectile = projectileArgs.Weapon.Projectile.Create(projectileArgs); if (projectile != null) firedBy.World.AddFrameEndTask(w => w.Add(projectile)); if (projectileArgs.Weapon.Report != null && projectileArgs.Weapon.Report.Any()) Game.Sound.Play(SoundType.World, projectileArgs.Weapon.Report.Random(firedBy.World.SharedRandom), target.CenterPosition); } } } } }
412
0.969616
1
0.969616
game-dev
MEDIA
0.921548
game-dev
0.71867
1
0.71867
amethyst/rustrogueliketutorial
2,921
chapter-60-caverns3/src/map_builders/door_placement.rs
use super::{MetaMapBuilder, BuilderMap, TileType }; use rltk::RandomNumberGenerator; pub struct DoorPlacement {} impl MetaMapBuilder for DoorPlacement { #[allow(dead_code)] fn build_map(&mut self, rng: &mut rltk::RandomNumberGenerator, build_data : &mut BuilderMap) { self.doors(rng, build_data); } } impl DoorPlacement { #[allow(dead_code)] pub fn new() -> Box<DoorPlacement> { Box::new(DoorPlacement{ }) } fn door_possible(&self, build_data : &mut BuilderMap, idx : usize) -> bool { let mut blocked = false; for spawn in build_data.spawn_list.iter() { if spawn.0 == idx { blocked = true; } } if blocked { return false; } let x = (idx % build_data.map.width as usize) as i32; let y = (idx / build_data.map.width as usize) as i32; // Check for east-west door possibility if build_data.map.tiles[idx] == TileType::Floor && (x > 1 && build_data.map.tiles[idx-1] == TileType::Floor) && (x < build_data.map.width-2 && build_data.map.tiles[idx+1] == TileType::Floor) && (y > 1 && build_data.map.tiles[idx - build_data.map.width as usize] == TileType::Wall) && (y < build_data.map.height-2 && build_data.map.tiles[idx + build_data.map.width as usize] == TileType::Wall) { return true; } // Check for north-south door possibility if build_data.map.tiles[idx] == TileType::Floor && (x > 1 && build_data.map.tiles[idx-1] == TileType::Wall) && (x < build_data.map.width-2 && build_data.map.tiles[idx+1] == TileType::Wall) && (y > 1 && build_data.map.tiles[idx - build_data.map.width as usize] == TileType::Floor) && (y < build_data.map.height-2 && build_data.map.tiles[idx + build_data.map.width as usize] == TileType::Floor) { return true; } false } fn doors(&mut self, rng : &mut RandomNumberGenerator, build_data : &mut BuilderMap) { if let Some(halls_original) = &build_data.corridors { let halls = halls_original.clone(); // To avoid nested borrowing for hall in halls.iter() { if hall.len() > 2 { // We aren't interested in tiny corridors if self.door_possible(build_data, hall[0]) { build_data.spawn_list.push((hall[0], "Door".to_string())); } } } } else { // There are no corridors - scan for possible places let tiles = build_data.map.tiles.clone(); for (i, tile) in tiles.iter().enumerate() { if *tile == TileType::Floor && self.door_possible(build_data, i) && rng.roll_dice(1,3)==1 { build_data.spawn_list.push((i, "Door".to_string())); } } } } }
412
0.888363
1
0.888363
game-dev
MEDIA
0.92109
game-dev
0.931168
1
0.931168
baileyholl/Ars-Nouveau
13,019
src/main/java/com/hollingsworth/arsnouveau/client/container/StorageTerminalMenu.java
package com.hollingsworth.arsnouveau.client.container; import com.hollingsworth.arsnouveau.common.block.tile.StorageLecternTile; import com.hollingsworth.arsnouveau.common.network.Networking; import com.hollingsworth.arsnouveau.common.network.ServerToClientStoragePacket; import com.hollingsworth.arsnouveau.common.network.SetTerminalSettingsPacket; import com.hollingsworth.arsnouveau.common.network.UpdateStorageItemsPacket; import com.hollingsworth.arsnouveau.setup.registry.MenuRegistry; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.StackedContents; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.RecipeBookMenu; import net.minecraft.world.inventory.RecipeBookType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.RecipeHolder; import javax.annotation.Nullable; import java.util.*; public class StorageTerminalMenu extends RecipeBookMenu<CraftingInput, CraftingRecipe> { protected StorageLecternTile te; protected int playerSlotsStart; protected List<SlotStorage> storageSlotList = new ArrayList<>(); public List<StoredItemStack> itemList = new ArrayList<>(); protected Inventory pinv; public String search; public Map<StoredItemStack, StoredItemStack> itemMap = new HashMap<>(); boolean sentSettings = false; public Map<UUID, String> tabs = new HashMap<>(); public StorageTerminalMenu(int id, Inventory inv, StorageLecternTile te) { this(MenuRegistry.STORAGE.get(), id, inv, te); this.addPlayerSlots(inv, 8, 120); } public StorageTerminalMenu(MenuType<?> type, int id, Inventory inv, StorageLecternTile te) { super(type, id); this.te = te; this.pinv = inv; addStorageSlots(false); } public StorageTerminalMenu(MenuType<?> type, int id, Inventory inv) { this(type, id, inv, null); } protected void addPlayerSlots(Inventory playerInventory, int x, int y) { this.playerSlotsStart = slots.size() - 1; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { addSlot(new Slot(playerInventory, j + i * 9 + 9, x + j * 18, y + i * 18)); } } for (int i = 0; i < 9; ++i) { addSlot(new Slot(playerInventory, i, x + i * 18, y + 58)); } } public void addStorageSlots(boolean expanded) { int lines = 7; boolean shouldAdd = storageSlotList.isEmpty(); for (int i = 0; i < lines; ++i) { for (int j = 0; j < 9; ++j) { int index = i * 9 + j; if (shouldAdd) { storageSlotList.add(new SlotStorage(this.te, index, 13 + j * 18, 21 + i * 18, expanded || i < 3)); } else { storageSlotList.get(index).show = expanded || i < 3; } } } } @Override public boolean stillValid(Player playerIn) { return te != null && te.canInteractWith(playerIn); } public final void setSlotContents(int id, StoredItemStack stack) { storageSlotList.get(id).setStack(stack); } public final SlotStorage getSlotByID(int id) { return storageSlotList.get(id); } public enum SlotAction { PULL_OR_PUSH_STACK, PULL_ONE, SPACE_CLICK, SHIFT_PULL, GET_HALF, GET_QUARTER //CRAFT } private Object2LongMap<StoredItemStack> itemLongMap = new Object2LongOpenHashMap<>(); @Override public void broadcastChanges() { if (te == null) { return; } Map<StoredItemStack, Long> itemsCount = te.getStacks(tabs.get(pinv.player.getUUID())); List<StoredItemStack> toWrite = new ArrayList<>(); Set<StoredItemStack> found = new HashSet<>(); itemsCount.forEach((s, c) -> { long pc = this.itemLongMap.getLong(s); if (pc != 0L) found.add(s); if (pc != c) { toWrite.add(new StoredItemStack(s.getStack(), c)); } }); this.itemLongMap.forEach((s, c) -> { if (!found.contains(s)) toWrite.add(new StoredItemStack(s.getStack(), 0L)); }); this.itemLongMap.clear(); this.itemLongMap.putAll(itemsCount); if (!toWrite.isEmpty()) { Networking.sendToPlayerClient(new UpdateStorageItemsPacket(toWrite), (ServerPlayer) pinv.player); } if (!sentSettings) { Networking.sendToPlayerClient(new SetTerminalSettingsPacket(te.sortSettings, null), (ServerPlayer) pinv.player); Networking.sendToPlayerClient(new ServerToClientStoragePacket(te.getLastSearch(pinv.player), te.getTabNames()), (ServerPlayer) pinv.player); sentSettings = true; } super.broadcastChanges(); } @Override public final ItemStack quickMoveStack(Player playerIn, int index) { if (slots.size() <= index) return ItemStack.EMPTY; if (index > playerSlotsStart && te != null) { if (slots.get(index) != null && slots.get(index).hasItem()) { Slot slot = slots.get(index); ItemStack slotStack = slot.getItem(); StoredItemStack c = te.pushStack(new StoredItemStack(slotStack, slotStack.getCount()), tabs.get(playerIn.getUUID())); ItemStack itemstack = c != null ? c.getActualStack() : ItemStack.EMPTY; slot.set(itemstack); if (!playerIn.level.isClientSide) broadcastChanges(); } } else { if (playerIn instanceof ServerPlayer serverPlayer) { return shiftClickItems(serverPlayer, index); } } return ItemStack.EMPTY; } protected ItemStack shiftClickItems(ServerPlayer playerIn, int index) { return ItemStack.EMPTY; } @Override public void fillCraftSlotsStackedContents(StackedContents itemHelperIn) { } @Override public void clearCraftingContent() { } @Override public boolean recipeMatches(RecipeHolder pRecipe) { return false; } @Override public int getResultSlotIndex() { return 0; } @Override public int getGridWidth() { return 0; } @Override public int getGridHeight() { return 0; } @Override public int getSize() { return 0; } public void updateItems(List<StoredItemStack> stacks) { if (stacks.isEmpty()) { return; } stacks.forEach(s -> { if (s.getQuantity() == 0) { this.itemMap.remove(s); } else { this.itemMap.put(s, s); } }); itemList = new ArrayList<>(itemMap.values()); pinv.setChanged(); } public final void receiveServerSearchString(String searchString) { if (!searchString.isEmpty()) search = searchString; } public void receiveClientSearch(ServerPlayer sender, String search) { te.setLastSearch(sender, search); } public void receiveSettings(ServerPlayer sender, SortSettings settings, String selectedTab) { this.tabs.put(sender.getUUID(), selectedTab); te.setSorting(settings); } @Override public RecipeBookType getRecipeBookType() { return RecipeBookType.CRAFTING; } @Override public boolean shouldMoveToInventory(int p_150635_) { return false; } public void onInteract(ServerPlayer player, @Nullable StoredItemStack clicked, SlotAction act, boolean pullOne) { player.resetLastActionTime(); if (act == SlotAction.SPACE_CLICK) { for (int i = playerSlotsStart + 1; i < playerSlotsStart + 28; i++) { quickMoveStack(player, i); } } else { String selectedTab = tabs.get(player.getUUID()); if (act == SlotAction.PULL_OR_PUSH_STACK) { ItemStack stack = getCarried(); if (!stack.isEmpty()) { StoredItemStack rem = te.pushStack(new StoredItemStack(stack), selectedTab); ItemStack itemstack = rem == null ? ItemStack.EMPTY : rem.getActualStack(); setCarried(itemstack); } else { if (clicked == null) return; StoredItemStack pulled = te.pullStack(clicked, clicked.getMaxStackSize(), selectedTab); if (pulled != null) { setCarried(pulled.getActualStack()); } } } else if (act == SlotAction.PULL_ONE) { ItemStack stack = getCarried(); if (clicked == null) return; if (pullOne) { StoredItemStack pulled = te.pullStack(clicked, 1, selectedTab); if (pulled != null) { ItemStack itemstack = pulled.getActualStack(); this.moveItemStackTo(itemstack, playerSlotsStart + 1, this.slots.size(), true); if (itemstack.getCount() > 0) te.pushOrDrop(itemstack, selectedTab); player.getInventory().setChanged(); } } else { if (!stack.isEmpty()) { if (ItemStack.isSameItemSameComponents(stack, clicked.getStack()) && stack.getCount() + 1 <= stack.getMaxStackSize()) { StoredItemStack pulled = te.pullStack(clicked, 1, selectedTab); if (pulled != null) { stack.grow(1); } } } else { StoredItemStack pulled = te.pullStack(clicked, 1, selectedTab); if (pulled != null) { setCarried(pulled.getActualStack()); } } } } else if (act == SlotAction.GET_HALF) { ItemStack stack = getCarried(); if (!stack.isEmpty()) { ItemStack stack1 = stack.split(Math.max(Math.min(stack.getCount(), stack.getMaxStackSize()) / 2, 1)); ItemStack itemstack = te.pushStack(stack1, selectedTab); stack.grow(!itemstack.isEmpty() ? itemstack.getCount() : 0); setCarried(stack); } else { if (clicked == null) { return; } StoredItemStack pulled = te.pullStack(clicked, (int) Math.max(Math.min(clicked.getQuantity() / 2, clicked.getMaxStackSize() / 2), 1), selectedTab); if (pulled != null) { setCarried(pulled.getActualStack()); } } } else if (act == SlotAction.GET_QUARTER) { ItemStack stack = getCarried(); if (!stack.isEmpty()) { ItemStack stack1 = stack.split(Math.max(Math.min(stack.getCount(), stack.getMaxStackSize()) / 4, 1)); ItemStack itemstack = te.pushStack(stack1, selectedTab); stack.grow(!itemstack.isEmpty() ? itemstack.getCount() : 0); setCarried(stack); } else { if (clicked == null) return; long maxCount = 64; for (StoredItemStack e : itemList) { if (e.equals(clicked)) maxCount = e.getQuantity(); } StoredItemStack pulled = te.pullStack(clicked, (int) Math.max(Math.min(maxCount, clicked.getMaxStackSize()) / 4, 1), selectedTab); if (pulled != null) { setCarried(pulled.getActualStack()); } } } else { if (clicked == null) return; StoredItemStack pulled = te.pullStack(clicked, clicked.getMaxStackSize(), selectedTab); if (pulled != null) { ItemStack itemstack = pulled.getActualStack(); this.moveItemStackTo(itemstack, playerSlotsStart + 1, this.slots.size(), true); if (itemstack.getCount() > 0) { te.pushOrDrop(itemstack, selectedTab); } player.getInventory().setChanged(); } } } } }
412
0.973117
1
0.973117
game-dev
MEDIA
0.991073
game-dev
0.995983
1
0.995983
project-topaz/topaz
10,999
scripts/zones/Aht_Urhgan_Whitegate/Zone.lua
----------------------------------- -- -- Zone: Aht_Urhgan_Whitegate (50) -- ----------------------------------- local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs") require("scripts/globals/settings") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/quests") require("scripts/globals/status") require("scripts/globals/titles") require("scripts/globals/zone") ----------------------------------- function onInitialize(zone) zone:registerRegion(1, 57, -1, -70, 62, 1, -65) -- Sets Mark for "Got It All" Quest cutscene. zone:registerRegion(2, -96, -7, 121, -64, -5, 137) -- Sets Mark for "Vanishing Act" Quest cutscene. zone:registerRegion(3, 14, -7, -65, 37, -2, -41) -- TOAU Mission 1 CS area zone:registerRegion(4, 75, -3, 25, 90, 1, 59) zone:registerRegion(5, 73, -7, -137, 95, -3, -115) -- entering Shaharat Teahouse end function onZoneIn(player, prevZone) local cs = -1 if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then if (prevZone == tpz.zone.OPEN_SEA_ROUTE_TO_AL_ZAHBI) then cs = 201 elseif (prevZone == tpz.zone.SILVER_SEA_ROUTE_TO_AL_ZAHBI) then cs = 204 elseif (prevZone == tpz.zone.SILVER_SEA_ROUTE_TO_NASHMAU) then cs = 204 else -- MOG HOUSE EXIT local position = math.random(1, 5) - 83 player:setPos(-100, 0, position, 0) end end if (player:getCurrentMission(TOAU) == tpz.mission.id.toau.STIRRINGS_OF_WAR and player:getCharVar("AhtUrganStatus") == 0 and player:getCharVar("TOAUM38_STARTDAY") ~= VanadielDayOfTheYear() and player:needToZone() == false) then cs = 3220 end return cs end function afterZoneIn(player) player:entityVisualPacket("1pb1") end function onRegionEnter(player, region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Cutscene for Got It All quest. if (player:getCharVar("gotitallCS") == 5) then player:startEvent(526) end end, [2] = function (x) -- CS for Vanishing Act Quest if (player:getCharVar("vanishingactCS") == 3) then player:startEvent(44) end end, [3] = function (x) -- TOAU Mission 1 if (player:getCurrentMission(TOAU)== tpz.mission.id.toau.LAND_OF_SACRED_SERPENTS) then player:startEvent(3000, 0, 0, 0, 0, 0, 0, 0, 0, 0) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.A_MERCENARY_LIFE and player:needToZone() == false) then if (prevZone ~= tpz.zone.AHT_URHGAN_WHITEGATE) then player:startEvent(3050, 3, 3, 3, 3, 3, 3, 3, 3, 0) end elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.FINDERS_KEEPERS) then player:startEvent(3093) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.SOCIAL_GRACES) then player:startEvent(3095) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.FOILED_AMBITION and player:getCharVar("TOAUM23_STARTDAY") ~= VanadielDayOfTheYear() and player:needToZone() == false) then player:startEvent(3097, 0, 0, 0, 0, 0, 0, 0, 0, 0) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.PLAYING_THE_PART and player:getCharVar("TOAUM24_STARTDAY") ~= VanadielDayOfTheYear() and player:needToZone() == false) then player:startEvent(3110) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.PATH_OF_BLOOD) then player:startEvent(3131, 1, 1, 1, 1, 1, 1, 1, 1) end end, [4] = function (x) -- AH mission if (player:getCurrentMission(TOAU)== tpz.mission.id.toau.KNIGHT_OF_GOLD and player:getCharVar("AhtUrganStatus") == 2) then player:startEvent(3024, 0, 0, 0, 0, 0, 0, 0, 0, 0) elseif (player:getCurrentMission(TOAU)== tpz.mission.id.toau.BASTION_OF_KNOWLEDGE) then player:startEvent(3112) end end, [5] = function (x) -- AH mission if (player:getCurrentMission(TOAU)== tpz.mission.id.toau.KNIGHT_OF_GOLD and player:getCharVar("AhtUrganStatus") == 3) then player:startEvent(3026, 0, 0, 0, 0, 0, 0, 0, 0, 0) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.WESTERLY_WINDS and player:getCharVar("AhtUrganStatus") == 0) then player:startEvent(3027, 0, 0, 0, 0, 0, 0, 0, 0, 0) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.SWEETS_FOR_THE_SOUL) then player:startEvent(3092) elseif (player:getCurrentMission(TOAU) == tpz.mission.id.toau.STIRRINGS_OF_WAR and player:getCharVar("AhtUrganStatus") == 1) then player:startEvent(3136, 0, 0, 0, 0, 0, 0, 0, 0, 0) elseif (player:getQuestStatus(AHT_URHGAN, tpz.quest.id.ahtUrhgan.NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_COMPLETED and player:getQuestStatus(AHT_URHGAN, tpz.quest.id.ahtUrhgan.AGAINST_ALL_ODDS) == QUEST_AVAILABLE and player:getMainJob() == tpz.job.COR and player:getMainLvl() >= AF3_QUEST_LEVEL) then player:startEvent(797) end end, } end function onRegionLeave(player, region) end function onTransportEvent(player, transport) if (transport == 46 or transport == 47) then player:startEvent(200) elseif (transport == 58 or transport == 59) then player:startEvent(203) end end function onEventUpdate(player, csid, option) if (csid == 3050 and option == 1) then if (player:getLocalVar("A_MERCENARY_LIFE") == 0) then player:setLocalVar("A_MERCENARY_LIFE", 1) player:updateEvent(1, 0, 0, 0, 0, 0, 0, 0) else player:updateEvent(3, 0, 0, 0, 0, 0, 0, 0) end elseif (csid == 3050 and option == 2) then if (player:getLocalVar("A_MERCENARY_LIFE") == 0) then player:setLocalVar("A_MERCENARY_LIFE", 1) player:updateEvent(2, 0, 0, 0, 0, 0, 0, 0) else player:updateEvent(3, 0, 0, 0, 0, 0, 0, 0) end end end function onEventFinish(player, csid, option) if (csid == 44) then player:setCharVar("vanishingactCS", 4) player:setPos(-80, -6, 122, 5) elseif (csid == 200) then player:setPos(0, -2, 0, 0, 47) elseif (csid == 201) then player:setPos(-11, 2, -142, 192) elseif (csid == 203) then player:setPos(0, -2, 0, 0, 58) elseif (csid == 204) then player:setPos(11, 2, 142, 64) elseif (csid == 526) then player:setCharVar("gotitallCS", 6) player:setPos(60, 0, -71, 38) elseif (csid == 3000) then player:addKeyItem(tpz.ki.SUPPLIES_PACKAGE) player:completeMission(TOAU, tpz.mission.id.toau.LAND_OF_SACRED_SERPENTS) player:addMission(TOAU, tpz.mission.id.toau.IMMORTAL_SENTRIES) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.SUPPLIES_PACKAGE) elseif (csid == 3024) then player:setCharVar("AhtUrganStatus", 3) elseif (csid == 3026) then player:setCharVar("AhtUrganStatus", 0) player:addKeyItem(tpz.ki.RAILLEFALS_LETTER) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.RAILLEFALS_LETTER) player:completeMission(TOAU, tpz.mission.id.toau.KNIGHT_OF_GOLD) player:addMission(TOAU, tpz.mission.id.toau.CONFESSIONS_OF_ROYALTY) elseif (csid == 3027) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 2185) else player:setCharVar("AhtUrganStatus", 1) player:addKeyItem(tpz.ki.RAILLEFALS_NOTE) player:setTitle(tpz.title.AGENT_OF_THE_ALLIED_FORCES) player:addItem(2185, 1) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.RAILLEFALS_NOTE) player:messageSpecial(ID.text.ITEM_OBTAINED, 2185) end elseif (csid == 3050) then player:completeMission(TOAU, tpz.mission.id.toau.A_MERCENARY_LIFE) player:addMission(TOAU, tpz.mission.id.toau.UNDERSEA_SCOUTING) elseif (csid == 3092) then player:completeMission(TOAU, tpz.mission.id.toau.SWEETS_FOR_THE_SOUL) player:addMission(TOAU, tpz.mission.id.toau.TEAHOUSE_TUMULT) elseif (csid == 3093) then player:completeMission(TOAU, tpz.mission.id.toau.FINDERS_KEEPERS) player:setTitle(tpz.title.KARABABAS_BODYGUARD) player:addMission(TOAU, tpz.mission.id.toau.SHIELD_OF_DIPLOMACY) elseif (csid == 3095) then player:completeMission(TOAU, tpz.mission.id.toau.SOCIAL_GRACES) player:needToZone(true) player:setCharVar("TOAUM23_STARTDAY", VanadielDayOfTheYear()) player:addMission(TOAU, tpz.mission.id.toau.FOILED_AMBITION) elseif (csid == 3097) then player:completeMission(TOAU, tpz.mission.id.toau.FOILED_AMBITION) player:setTitle(tpz.title.KARABABAS_SECRET_AGENT) player:addItem(2187, 5) player:setCharVar("TOAUM23_STARTDAY", 0) player:needToZone(true) player:setCharVar("TOAUM24_STARTDAY", VanadielDayOfTheYear()) player:addMission(TOAU, tpz.mission.id.toau.PLAYING_THE_PART) elseif (csid == 3110) then player:completeMission(TOAU, tpz.mission.id.toau.PLAYING_THE_PART) player:setCharVar("TOAUM24_STARTDAY", 0) player:addMission(TOAU, tpz.mission.id.toau.SEAL_OF_THE_SERPENT) elseif (csid == 3112) then player:completeMission(TOAU, tpz.mission.id.toau.BASTION_OF_KNOWLEDGE) player:setTitle(tpz.title.APHMAUS_MERCENARY) player:addMission(TOAU, tpz.mission.id.toau.PUPPET_IN_PERIL) elseif (csid == 3131) then player:completeMission(TOAU, tpz.mission.id.toau.PATH_OF_BLOOD) player:needToZone(true) player:setCharVar("TOAUM38_STARTDAY", VanadielDayOfTheYear()) player:addMission(TOAU, tpz.mission.id.toau.STIRRINGS_OF_WAR) elseif (csid == 3220) then player:setCharVar("TOAUM38_STARTDAY", 0) player:setCharVar("AhtUrganStatus", 1) elseif (csid == 3136) then player:completeMission(TOAU, tpz.mission.id.toau.STIRRINGS_OF_WAR) player:setCharVar("AhtUrganStatus", 0) player:addKeyItem(tpz.ki.ALLIED_COUNCIL_SUMMONS) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.ALLIED_COUNCIL_SUMMONS) player:addMission(TOAU, tpz.mission.id.toau.ALLIED_RUMBLINGS) elseif (csid == 797) then player:setCharVar("AgainstAllOdds", 1) -- Set For Corsair BCNM player:addQuest(AHT_URHGAN, tpz.quest.id.ahtUrhgan.AGAINST_ALL_ODDS) -- Start of af 3 not completed yet player:addKeyItem(tpz.ki.LIFE_FLOAT) -- BCNM KEY ITEM TO ENTER BCNM player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.LIFE_FLOAT) end end
412
0.867933
1
0.867933
game-dev
MEDIA
0.990746
game-dev
0.894033
1
0.894033
hannibal002/SkyHanni
16,052
src/main/java/at/hannibal2/skyhanni/api/enoughupdates/ItemResolutionQuery.kt
package at.hannibal2.skyhanni.api.enoughupdates import at.hannibal2.skyhanni.api.event.HandleEvent import at.hannibal2.skyhanni.config.ConfigManager import at.hannibal2.skyhanni.data.jsonobjects.repo.ItemsJson import at.hannibal2.skyhanni.events.RepositoryReloadEvent import at.hannibal2.skyhanni.skyhannimodule.SkyHanniModule import at.hannibal2.skyhanni.test.command.ErrorManager import at.hannibal2.skyhanni.utils.InventoryUtils import at.hannibal2.skyhanni.utils.ItemUtils import at.hannibal2.skyhanni.utils.ItemUtils.extraAttributes import at.hannibal2.skyhanni.utils.ItemUtils.getLore import at.hannibal2.skyhanni.utils.NumberUtil.romanToDecimal import at.hannibal2.skyhanni.utils.RegexUtils.firstMatcher import at.hannibal2.skyhanni.utils.RegexUtils.matchMatcher import at.hannibal2.skyhanni.utils.StringUtils.cleanString import at.hannibal2.skyhanni.utils.StringUtils.removeColor import at.hannibal2.skyhanni.utils.UtilsPatterns import com.google.gson.JsonObject import net.minecraft.client.Minecraft import net.minecraft.client.gui.GuiScreen import net.minecraft.client.gui.inventory.GuiChest import net.minecraft.init.Items import net.minecraft.inventory.ContainerChest import net.minecraft.inventory.IInventory import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import java.util.regex.Matcher //#if MC > 1.21 //$$ import net.minecraft.component.ComponentMap //#endif // Code taken from NotEnoughUpdates class ItemResolutionQuery { //#if MC < 1.21 private var compound: NBTTagCompound? = null //#else //$$ private var compound: ComponentMap? = null //#endif private var itemType: Item? = null private var knownInternalName: String? = null private var guiContext: GuiScreen? = null @SkyHanniModule companion object { private val petPattern = ".*(\\[Lvl .*] )§(.).*".toPattern() val petRarities = listOf("COMMON", "UNCOMMON", "RARE", "EPIC", "LEGENDARY", "MYTHIC") private val BAZAAR_ENCHANTMENT_PATTERN = "ENCHANTMENT_(\\D*)_(\\d+)".toPattern() private var renamedEnchantments: Map<String, String> = mapOf() private var shardNameOverrides: Map<String, String> = mapOf() @HandleEvent fun onRepoReload(event: RepositoryReloadEvent) { val data = event.getConstant<ItemsJson>("Items") renamedEnchantments = data.renamedEnchantments shardNameOverrides = data.shardNameOverrides } fun transformHypixelBazaarToNeuItemId(hypixelId: String): String { ItemUtils.bazaarOverrides[hypixelId]?.let { return it } val matcher = BAZAAR_ENCHANTMENT_PATTERN.matcher(hypixelId) if (matcher.matches()) { return matcher.group(1) + ";" + matcher.group(2) } return hypixelId.replace(":", "-") } fun findInternalNameByDisplayName(displayName: String, mayBeMangled: Boolean): String? { return filterInternalNameCandidates( findInternalNameCandidatesForDisplayName(displayName), displayName, mayBeMangled, ) } private fun filterInternalNameCandidates( candidateInternalNames: Collection<String>, displayName: String, mayBeMangled: Boolean, ): String? { var itemName = displayName val isPet = itemName.contains("[Lvl ") var petRarity: String? = null if (isPet) { val matcher: Matcher = petPattern.matcher(itemName) if (matcher.matches()) { itemName = itemName.replace(matcher.group(1), "").replace("✦", "").trim() petRarity = matcher.group(2) } } val cleanDisplayName = itemName.removeColor() var bestMatch: String? = null var bestMatchLength = -1 for (internalName in candidateInternalNames) { val unCleanItemDisplayName: String = EnoughUpdatesManager.getDisplayName(internalName) var cleanItemDisplayName = unCleanItemDisplayName.removeColor() if (cleanItemDisplayName.isEmpty()) continue if (isPet) { if (!cleanItemDisplayName.contains("[Lvl {LVL}] ")) continue cleanItemDisplayName = cleanItemDisplayName.replace("[Lvl {LVL}] ", "") val matcher: Matcher = petPattern.matcher(unCleanItemDisplayName) if (matcher.matches()) { if (matcher.group(2) != petRarity) { continue } } } val isMangledMatch = mayBeMangled && !cleanDisplayName.contains(cleanItemDisplayName) val isExactMatch = !mayBeMangled && cleanItemDisplayName != cleanDisplayName if (isMangledMatch || isExactMatch) { continue } if (cleanItemDisplayName.length > bestMatchLength) { bestMatchLength = cleanItemDisplayName.length bestMatch = internalName } } return bestMatch } private fun findInternalNameCandidatesForDisplayName(displayName: String): Set<String> { val isPet = displayName.contains("[Lvl ") val cleanDisplayName = displayName.cleanString() val titleWordMap = EnoughUpdatesManager.titleWordMap val candidates = HashSet<String>() for (partialDisplayName in cleanDisplayName.split(" ")) { if (partialDisplayName.isEmpty()) continue if (!titleWordMap.containsKey(partialDisplayName)) continue val c: Set<String> = titleWordMap[partialDisplayName]?.keys ?: continue for (s in c) { if (isPet && !s.contains(";")) continue candidates.add(s) } } return candidates } fun resolveEnchantmentByName(displayName: String): String? = UtilsPatterns.enchantmentNamePattern.matchMatcher(displayName) { val name = group("name").trim().replace("'", "") val ultimate = group("format").lowercase().contains("§l") val prefix = if (ultimate && name != "Ultimate Wise" && name != "Ultimate Jerry") "ULTIMATE_" else "" val cleanedEnchantName = name.renamedEnchantmentCheck().replace(" ", "_").replace("-", "_").uppercase() "$prefix$cleanedEnchantName;${group("level").romanToDecimal()}".uppercase() } private fun String.renamedEnchantmentCheck(): String = renamedEnchantments[this] ?: this fun attributeNameToInternalName(attributeName: String): String? { var fixedAttributeName = attributeName.uppercase().replace(" ", "_") fixedAttributeName = shardNameOverrides[fixedAttributeName] ?: fixedAttributeName val shardName = "SHARD_$fixedAttributeName" return ItemUtils.bazaarOverrides[shardName] } } fun withItemStack(stack: ItemStack): ItemResolutionQuery { this.itemType = stack.item this.compound = stack.tagCompound return this } fun withKnownInternalName(internalName: String): ItemResolutionQuery { this.knownInternalName = internalName return this } fun withCurrentGuiContext(): ItemResolutionQuery { this.guiContext = Minecraft.getMinecraft().currentScreen return this } fun resolveInternalName(): String? { knownInternalName?.let { return it } var resolvedName = resolveFromSkyblock() resolvedName = if (resolvedName == null) { resolveContextualName() } else { when (resolvedName) { "PET" -> resolvePetName() "RUNE", "UNIQUE_RUNE" -> resolveRuneName() "ENCHANTED_BOOK" -> resolveEnchantedBookNameFromNBT() "PARTY_HAT_CRAB", "PARTY_HAT_CRAB_ANIMATED" -> resolveCrabHatName() "ABICASE" -> resolvePhoneCase() "PARTY_HAT_SLOTH" -> resolveSlothHatName() "POTION" -> resolvePotionName() "BALLOON_HAT_2024", "BALLOON_HAT_2025" -> resolveBalloonHatName() "ATTRIBUTE_SHARD" -> resolveAttributeShardName() else -> resolvedName } } return resolvedName } private fun resolvePetName(): String? { val petInfo = getExtraAttributes().getString("petInfo") if (petInfo.isNullOrEmpty()) return null try { val petInfoObject = ConfigManager.gson.fromJson(petInfo, JsonObject::class.java) val petId = petInfoObject["type"].asString val petTier = petInfoObject["tier"].asString val rarityIndex = petRarities.indexOf(petTier) return petId.uppercase() + ";" + rarityIndex } catch (e: Exception) { ErrorManager.logErrorWithData( e, "Error while resolving pet information", "petInfo" to petInfo, ) return null } } private fun resolveRuneName(): String? { val runes = getExtraAttributes().getCompoundTag("runes") val runeName = runes.keySet.singleOrNull() if (runeName.isNullOrEmpty()) return null return runeName.uppercase() + "_RUNE;" + runes.getInteger(runeName) } private fun resolveEnchantedBookNameFromNBT(): String? { val enchantments = getExtraAttributes().getCompoundTag("enchantments") val enchantName = enchantments.keySet.singleOrNull() if (enchantName.isNullOrEmpty()) return null return enchantName.uppercase() + ";" + enchantments.getInteger(enchantName) } private fun resolveCrabHatName(): String { val crabHatYear = getExtraAttributes().getInteger("party_hat_year") val color = getExtraAttributes().getString("party_hat_color") return "PARTY_HAT_CRAB_" + color.uppercase() + (if (crabHatYear == 2022) "_ANIMATED" else "") } private fun resolvePhoneCase(): String { val model = getExtraAttributes().getString("model") return "ABICASE_" + model.uppercase() } private fun resolveSlothHatName(): String { val emoji = getExtraAttributes().getString("party_hat_emoji") return "PARTY_HAT_SLOTH_" + emoji.uppercase() } private fun resolvePotionName(): String { val potion = getExtraAttributes().getString("potion") val potionLvl = getExtraAttributes().getInteger("potion_level") val potionName = getExtraAttributes().getString("potion_name").replace(" ", "_") val potionType = getExtraAttributes().getString("potion_type") return if (potionName.isNotEmpty()) { "POTION_" + potionName.uppercase() + ";" + potionLvl } else if (!potion.isNullOrEmpty()) { "POTION_" + potion.uppercase() + ";" + potionLvl } else if (!potionType.isNullOrEmpty()) { "POTION_" + potionType.uppercase() } else { "WATER_BOTTLE" } } private fun resolveBalloonHatName(): String { val color = getExtraAttributes().getString("party_hat_color") val balloonHatYear = getExtraAttributes().getInteger("party_hat_year") return "BALLOON_HAT_" + balloonHatYear + "_" + color.uppercase() } private fun resolveAttributeShardName(): String? { val attributes = getExtraAttributes().getCompoundTag("attributes") val attributeName = attributes.keySet.singleOrNull() if (attributeName.isNullOrEmpty()) return null return "ATTRIBUTE_SHARD_" + attributeName.uppercase() + ";" + attributes.getInteger(attributeName) } private fun resolveItemInCatacombsRngMeter(): String? { val lore = compound.getLore() if (lore.size > 16) { val s = lore[15] if (s == "§7Selected Drop") { val displayName = lore[16] return findInternalNameByDisplayName(displayName, false) } } return null } private fun resolveItemInAttributeMenu(lore: List<String>): String? { UtilsPatterns.attributeSourcePattern.firstMatcher(lore) { return attributeNameToInternalName(group("source")) } return null } private fun resolveItemInHuntingBoxMenu(displayName: String): String? { return attributeNameToInternalName(displayName.removeColor()) } private fun resolveContextualName(): String? { val chest = guiContext as? GuiChest ?: return null val inventorySlots = chest.inventorySlots as ContainerChest val guiName = InventoryUtils.openInventoryName() val isOnBazaar: Boolean = isBazaar(inventorySlots.lowerChestInventory) var displayName: String = ItemUtils.getDisplayName(compound) ?: return null displayName = displayName.removePrefix("§6§lSELL ").removePrefix("§a§lBUY ") if (itemType === Items.enchanted_book && isOnBazaar && compound != null) { return resolveEnchantmentByName(displayName) } if (itemType === Items.skull && displayName.contains("Essence")) { findInternalNameByDisplayName(displayName, false)?.let { return it } } if (displayName.endsWith("Enchanted Book") && guiName.startsWith("Superpairs")) { for (loreLine in compound.getLore()) { val enchantmentIdCandidate = resolveEnchantmentByName(loreLine) if (enchantmentIdCandidate != null) return enchantmentIdCandidate } return null } if (guiName == "Catacombs RNG Meter") { return resolveItemInCatacombsRngMeter() } if (guiName.startsWith("Choose Pet")) { return findInternalNameByDisplayName(displayName, false) } if (guiName.endsWith("Experimentation Table RNG")) { return resolveEnchantmentByName(displayName) } if (guiName == "Attribute Menu") { return resolveItemInAttributeMenu(compound.getLore()) } if (guiName == "Hunting Box" || guiName == "Fusion Box" || guiName == "Shard Fusion") { return resolveItemInHuntingBoxMenu(displayName) } if (guiName == "Confirm Fusion") { return resolveItemInHuntingBoxMenu(compound.getLore().firstOrNull() ?: return null) } if (guiName == "Dye Compendium") { return findInternalNameByDisplayName(displayName, false) } return null } private fun isBazaar(chest: IInventory): Boolean { if (InventoryUtils.openInventoryName().startsWith("Bazaar ➜ ")) { return true } val bazaarSlot = chest.sizeInventory - 5 if (bazaarSlot < 0) return false val stackInSlot = chest.getStackInSlot(bazaarSlot) ?: return false if (stackInSlot.stackSize == 0) return false val lore: List<String> = stackInSlot.getLore() return lore.contains("§7To Bazaar") } private fun getExtraAttributes(): NBTTagCompound = compound?.extraAttributes ?: NBTTagCompound() private fun resolveFromSkyblock(): String? { val internalName = getExtraAttributes().getString("id") if (internalName.isNullOrEmpty()) return null return internalName.uppercase().replace(":", "-") } private fun resolveToItemListJson(): JsonObject? { val internalName = resolveInternalName() ?: return null return EnoughUpdatesManager.getItemById(internalName) } fun resolveToItemStack(): ItemStack? { val json = resolveToItemListJson() ?: return null return EnoughUpdatesManager.jsonToStack(json) } }
412
0.908379
1
0.908379
game-dev
MEDIA
0.784139
game-dev
0.964854
1
0.964854
InQuest/ThreatIngestor
7,191
tests/test_operators.py
import unittest import threatingestor.operators import threatingestor.artifacts class TestOperators(unittest.TestCase): def test_default_artifact_types_is_empty(self): self.assertEqual(threatingestor.operators.Operator().artifact_types, []) def test_handle_artifact_raises_not_implemented(self): with self.assertRaises(NotImplementedError): threatingestor.operators.Operator().handle_artifact(None) def test_process_includes_only_artifact_types(self): threatingestor.operators.Operator.handle_artifact = lambda x, y: x.artifacts.append(y) operator = threatingestor.operators.Operator() operator.artifact_types = [threatingestor.artifacts.Domain] operator.artifacts = [] artifact_list = [ threatingestor.artifacts.IPAddress('21.21.21.21', '', ''), threatingestor.artifacts.Domain('test.com', '', ''), threatingestor.artifacts.URL('http://example.com', '', ''), threatingestor.artifacts.Domain('example.com', '', ''), ] operator.process(artifact_list) self.assertTrue(all([isinstance(x, threatingestor.artifacts.Domain) for x in operator.artifacts])) self.assertEqual(len(operator.artifacts), 2) operator.artifact_types = [threatingestor.artifacts.IPAddress, threatingestor.artifacts.URL] operator.artifacts = [] operator.process(artifact_list) self.assertTrue(all([isinstance(x, threatingestor.artifacts.IPAddress) or isinstance(x, threatingestor.artifacts.URL) for x in operator.artifacts])) self.assertEqual(len(operator.artifacts), 2) def test_artifact_types_are_set_if_passed_in(self): artifact_types = [threatingestor.artifacts.IPAddress, threatingestor.artifacts.URL] self.assertEqual(threatingestor.operators.Operator(artifact_types=artifact_types).artifact_types, artifact_types) def test_process_includes_artifact_iff_filter_matches(self): threatingestor.operators.Operator.handle_artifact = lambda x, y: x.artifacts.append(y) operator = threatingestor.operators.Operator(filter_string='example.com') operator.artifact_types = [threatingestor.artifacts.Domain, threatingestor.artifacts.IPAddress, threatingestor.artifacts.URL] operator.artifacts = [] artifact_list = [ threatingestor.artifacts.IPAddress('21.21.21.21', '', ''), threatingestor.artifacts.Domain('test.com', '', ''), threatingestor.artifacts.URL('http://example.com', '', ''), threatingestor.artifacts.Domain('example.com', '', ''), ] operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 2) self.assertNotIn(artifact_list[0], operator.artifacts) self.assertNotIn(artifact_list[1], operator.artifacts) self.assertIn(artifact_list[2], operator.artifacts) self.assertIn(artifact_list[3], operator.artifacts) operator.artifacts = [] operator.filter_string = '21' operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 1) self.assertIn(artifact_list[0], operator.artifacts) self.assertNotIn(artifact_list[1], operator.artifacts) self.assertNotIn(artifact_list[2], operator.artifacts) self.assertNotIn(artifact_list[3], operator.artifacts) operator.artifacts = [] operator.filter_string = '' operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 4) self.assertIn(artifact_list[0], operator.artifacts) self.assertIn(artifact_list[1], operator.artifacts) self.assertIn(artifact_list[2], operator.artifacts) self.assertIn(artifact_list[3], operator.artifacts) operator.artifacts = [] operator.filter_string = 'is_domain' operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 1) self.assertNotIn(artifact_list[0], operator.artifacts) self.assertNotIn(artifact_list[1], operator.artifacts) self.assertIn(artifact_list[2], operator.artifacts) self.assertNotIn(artifact_list[3], operator.artifacts) def test_process_includes_artifact_iff_source_name_is_allowed_or_allowed_is_empty(self): threatingestor.operators.Operator.handle_artifact = lambda x, y: x.artifacts.append(y) operator = threatingestor.operators.Operator() operator.artifact_types = [threatingestor.artifacts.Domain, threatingestor.artifacts.IPAddress, threatingestor.artifacts.URL] operator.artifacts = [] artifact_list = [ threatingestor.artifacts.IPAddress('21.21.21.21', 'source-1'), threatingestor.artifacts.Domain('test.com', 'source-1'), threatingestor.artifacts.URL('http://example.com', 'source-2'), threatingestor.artifacts.Domain('example.com', 'source-3'), ] operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 4) self.assertIn(artifact_list[0], operator.artifacts) self.assertIn(artifact_list[1], operator.artifacts) self.assertIn(artifact_list[2], operator.artifacts) self.assertIn(artifact_list[3], operator.artifacts) operator.artifacts = [] operator.allowed_sources = ['source-1'] operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 2) self.assertIn(artifact_list[0], operator.artifacts) self.assertIn(artifact_list[1], operator.artifacts) self.assertNotIn(artifact_list[2], operator.artifacts) self.assertNotIn(artifact_list[3], operator.artifacts) operator.artifacts = [] operator.allowed_sources = ['source-2', 'source-3'] operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 2) self.assertNotIn(artifact_list[0], operator.artifacts) self.assertNotIn(artifact_list[1], operator.artifacts) self.assertIn(artifact_list[2], operator.artifacts) self.assertIn(artifact_list[3], operator.artifacts) def test_regex_allowed_sources(self): threatingestor.operators.Operator.handle_artifact = lambda x, y: x.artifacts.append(y) operator = threatingestor.operators.Operator(allowed_sources=['source-.*']) operator.artifact_types = [threatingestor.artifacts.Domain, threatingestor.artifacts.IPAddress, threatingestor.artifacts.URL] operator.artifacts = [] artifact_list = [ threatingestor.artifacts.IPAddress('21.21.21.21', 'source-1'), threatingestor.artifacts.Domain('test.com', 'source-1'), threatingestor.artifacts.URL('http://example.com', 'source-2'), threatingestor.artifacts.Domain('example.com', 'test-3'), ] operator.process(artifact_list) self.assertEqual(len(operator.artifacts), 3) self.assertIn(artifact_list[0], operator.artifacts) self.assertIn(artifact_list[1], operator.artifacts) self.assertIn(artifact_list[2], operator.artifacts) self.assertNotIn(artifact_list[3], operator.artifacts)
412
0.833278
1
0.833278
game-dev
MEDIA
0.725896
game-dev
0.62416
1
0.62416
XCharts-Team/XCharts-Demo
10,048
Packages/XCharts/Runtime/Internal/XCSettings.cs
using System; using System.Collections.Generic; using System.IO; using UnityEngine; #if dUI_TextMeshPro using TMPro; #endif #if UNITY_EDITOR using UnityEditor; #endif namespace XCharts.Runtime { [Serializable] #if UNITY_2018_3 [ExcludeFromPresetAttribute] #endif public class XCSettings : ScriptableObject { public readonly static string THEME_ASSET_NAME_PREFIX = "XCTheme-"; public readonly static string THEME_ASSET_FOLDER = "Assets/XCharts/Resources"; [SerializeField] private Lang m_Lang = null; [SerializeField] private Font m_Font = null; #if dUI_TextMeshPro [SerializeField] private TMP_FontAsset m_TMPFont = null; #endif [SerializeField][Range(1, 200)] private int m_FontSizeLv1 = 28; [SerializeField][Range(1, 200)] private int m_FontSizeLv2 = 24; [SerializeField][Range(1, 200)] private int m_FontSizeLv3 = 20; [SerializeField][Range(1, 200)] private int m_FontSizeLv4 = 18; [SerializeField] private LineStyle.Type m_AxisLineType = LineStyle.Type.Solid; [SerializeField][Range(0, 20)] private float m_AxisLineWidth = 0.8f; [SerializeField] private LineStyle.Type m_AxisSplitLineType = LineStyle.Type.Solid; [SerializeField][Range(0, 20)] private float m_AxisSplitLineWidth = 0.8f; [SerializeField][Range(0, 20)] private float m_AxisTickWidth = 0.8f; [SerializeField][Range(0, 20)] private float m_AxisTickLength = 5f; [SerializeField][Range(0, 200)] private float m_GaugeAxisLineWidth = 15f; [SerializeField][Range(0, 20)] private float m_GaugeAxisSplitLineWidth = 0.8f; [SerializeField][Range(0, 20)] private float m_GaugeAxisSplitLineLength = 15f; [SerializeField][Range(0, 20)] private float m_GaugeAxisTickWidth = 0.8f; [SerializeField][Range(0, 20)] private float m_GaugeAxisTickLength = 5f; [SerializeField][Range(0, 20)] private float m_TootipLineWidth = 0.8f; [SerializeField][Range(0, 20)] private float m_DataZoomBorderWidth = 0.5f; [SerializeField][Range(0, 20)] private float m_DataZoomDataLineWidth = 0.5f; [SerializeField][Range(0, 20)] private float m_VisualMapBorderWidth = 0f; [SerializeField][Range(0, 20)] private float m_SerieLineWidth = 1.8f; [SerializeField][Range(0, 200)] private float m_SerieLineSymbolSize = 5f; [SerializeField][Range(0, 200)] private float m_SerieScatterSymbolSize = 20f; [SerializeField][Range(0, 200)] private float m_SerieSelectedRate = 1.3f; [SerializeField][Range(0, 10)] private float m_SerieCandlestickBorderWidth = 1f; [SerializeField] private bool m_EditorShowAllListData = false; [SerializeField][Range(1, 20)] protected int m_MaxPainter = 10; [SerializeField][Range(1, 10)] protected float m_LineSmoothStyle = 3f; [SerializeField][Range(1f, 20)] protected float m_LineSmoothness = 2f; [SerializeField][Range(1f, 20)] protected float m_LineSegmentDistance = 3f; [SerializeField][Range(1, 10)] protected float m_CicleSmoothness = 2f; [SerializeField][Range(10, 50)] protected float m_VisualMapTriangeLen = 20f; [SerializeField] protected List<Theme> m_CustomThemes = new List<Theme>(); public static Lang lang { get { return Instance.m_Lang; } } public static Font font { get { return Instance.m_Font; } } #if dUI_TextMeshPro public static TMP_FontAsset tmpFont { get { return Instance.m_TMPFont; } } #endif /// <summary> /// 一级字体大小。 /// </summary> public static int fontSizeLv1 { get { return Instance.m_FontSizeLv1; } } public static int fontSizeLv2 { get { return Instance.m_FontSizeLv2; } } public static int fontSizeLv3 { get { return Instance.m_FontSizeLv3; } } public static int fontSizeLv4 { get { return Instance.m_FontSizeLv4; } } public static LineStyle.Type axisLineType { get { return Instance.m_AxisLineType; } } public static float axisLineWidth { get { return Instance.m_AxisLineWidth; } } public static LineStyle.Type axisSplitLineType { get { return Instance.m_AxisSplitLineType; } } public static float axisSplitLineWidth { get { return Instance.m_AxisSplitLineWidth; } } public static float axisTickWidth { get { return Instance.m_AxisTickWidth; } } public static float axisTickLength { get { return Instance.m_AxisTickLength; } } public static float gaugeAxisLineWidth { get { return Instance.m_GaugeAxisLineWidth; } } public static float gaugeAxisSplitLineWidth { get { return Instance.m_GaugeAxisSplitLineWidth; } } public static float gaugeAxisSplitLineLength { get { return Instance.m_GaugeAxisSplitLineLength; } } public static float gaugeAxisTickWidth { get { return Instance.m_GaugeAxisTickWidth; } } public static float gaugeAxisTickLength { get { return Instance.m_GaugeAxisTickLength; } } public static float tootipLineWidth { get { return Instance.m_TootipLineWidth; } } public static float dataZoomBorderWidth { get { return Instance.m_DataZoomBorderWidth; } } public static float dataZoomDataLineWidth { get { return Instance.m_DataZoomDataLineWidth; } } public static float visualMapBorderWidth { get { return Instance.m_VisualMapBorderWidth; } } #region serie public static float serieLineWidth { get { return Instance.m_SerieLineWidth; } } public static float serieLineSymbolSize { get { return Instance.m_SerieLineSymbolSize; } } public static float serieScatterSymbolSize { get { return Instance.m_SerieScatterSymbolSize; } } public static float serieSelectedRate { get { return Instance.m_SerieSelectedRate; } } public static float serieCandlestickBorderWidth { get { return Instance.m_SerieCandlestickBorderWidth; } } #endregion #region editor public static bool editorShowAllListData { get { return Instance.m_EditorShowAllListData; } } #endregion #region graphic public static int maxPainter { get { return Instance.m_MaxPainter; } } public static float lineSmoothStyle { get { return Instance.m_LineSmoothStyle; } } public static float lineSmoothness { get { return Instance.m_LineSmoothness; } } public static float lineSegmentDistance { get { return Instance.m_LineSegmentDistance; } } public static float cicleSmoothness { get { return Instance.m_CicleSmoothness; } } public static float visualMapTriangeLen { get { return Instance.m_VisualMapTriangeLen; } } #endregion public static List<Theme> customThemes { get { return Instance.m_CustomThemes; } } private static XCSettings s_Instance; public static XCSettings Instance { get { if (s_Instance == null) { s_Instance = Resources.Load<XCSettings>("XCSettings"); #if UNITY_EDITOR if (s_Instance == null) { var assetPath = GetSettingAssetPath(); if (string.IsNullOrEmpty(assetPath)) XCResourceImporterWindow.ShowPackageImporterWindow(); else s_Instance = AssetDatabase.LoadAssetAtPath<XCSettings>(assetPath); } else { if (s_Instance.m_Lang == null) s_Instance.m_Lang = Resources.Load<Lang>("XCLang-EN"); if (s_Instance.m_Lang == null) s_Instance.m_Lang = ScriptableObject.CreateInstance<Lang>(); if (s_Instance.m_Font == null) s_Instance.m_Font = Resources.GetBuiltinResource<Font>("Arial.ttf"); #if dUI_TextMeshPro if (s_Instance.m_TMPFont == null) s_Instance.m_TMPFont = Resources.Load<TMP_FontAsset>("LiberationSans SDF"); #endif } #endif } return s_Instance; } } #if UNITY_EDITOR public static bool ExistAssetFile() { return System.IO.File.Exists("Assets/XCharts/Resources/XCSettings.asset"); } public static string GetSettingAssetPath() { var path = "Assets/XCharts/Resources/XCSettings.asset"; if (File.Exists(path)) return path; var dir = Application.dataPath; string[] matchingPaths = Directory.GetDirectories(dir); foreach (var match in matchingPaths) { if (match.Contains("XCharts")) { var jsonPath = string.Format("{0}/package.json", match); if (File.Exists(jsonPath)) { var jsonText = File.ReadAllText(jsonPath); if (jsonText.Contains("\"displayName\": \"XCharts\"")) { path = string.Format("{0}/Resources/XCSettings.asset", match.Replace('\\', '/')); if (File.Exists(path)) return path.Substring(path.IndexOf("/Assets/") + 1); } } } } return null; } #endif public static bool AddCustomTheme(Theme theme) { if (theme == null) return false; if (Instance == null || Instance.m_CustomThemes == null) return false; if (!Instance.m_CustomThemes.Contains(theme)) { Instance.m_CustomThemes.Add(theme); #if UNITY_EDITOR EditorUtility.SetDirty(Instance); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); #endif return true; } return false; } } }
412
0.717958
1
0.717958
game-dev
MEDIA
0.838937
game-dev
0.872733
1
0.872733
graalvm/graal-jvmci-8
10,803
src/share/vm/runtime/jniHandles.hpp
/* * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_RUNTIME_JNIHANDLES_HPP #define SHARE_VM_RUNTIME_JNIHANDLES_HPP #include "runtime/handles.hpp" #include "utilities/top.hpp" class JNIHandleBlock; // Interface for creating and resolving local/global JNI handles class JNIHandles : AllStatic { friend class VMStructs; private: static JNIHandleBlock* _global_handles; // First global handle block static JNIHandleBlock* _weak_global_handles; // First weak global handle block static oop _deleted_handle; // Sentinel marking deleted handles inline static bool is_jweak(jobject handle); inline static oop& jobject_ref(jobject handle); // NOT jweak! inline static oop& jweak_ref(jobject handle); template<bool external_guard> inline static oop guard_value(oop value); template<bool external_guard> inline static oop resolve_impl(jobject handle); template<bool external_guard> static oop resolve_jweak(jweak handle); public: // Low tag bit in jobject used to distinguish a jweak. jweak is // type equivalent to jobject, but there are places where we need to // be able to distinguish jweak values from other jobjects, and // is_weak_global_handle is unsuitable for performance reasons. To // provide such a test we add weak_tag_value to the (aligned) byte // address designated by the jobject to produce the corresponding // jweak. Accessing the value of a jobject must account for it // being a possibly offset jweak. static const uintptr_t weak_tag_size = 1; static const uintptr_t weak_tag_alignment = (1u << weak_tag_size); static const uintptr_t weak_tag_mask = weak_tag_alignment - 1; static const int weak_tag_value = 1; // Resolve handle into oop inline static oop resolve(jobject handle); // Resolve externally provided handle into oop with some guards inline static oop resolve_external_guard(jobject handle); // Resolve handle into oop, result guaranteed not to be null inline static oop resolve_non_null(jobject handle); // Local handles static jobject make_local(oop obj); static jobject make_local(JNIEnv* env, oop obj); // Fast version when env is known static jobject make_local(Thread* thread, oop obj); // Even faster version when current thread is known inline static void destroy_local(jobject handle); // Global handles static jobject make_global(Handle obj); static void destroy_global(jobject handle); // Weak global handles static jobject make_weak_global(Handle obj); static void destroy_weak_global(jobject handle); // Sentinel marking deleted handles in block. Note that we cannot store NULL as // the sentinel, since clearing weak global JNI refs are done by storing NULL in // the handle. The handle may not be reused before destroy_weak_global is called. static oop deleted_handle() { return _deleted_handle; } // Initialization static void initialize(); // Debugging static void print_on(outputStream* st); static void print() { print_on(tty); } static void verify(); static bool is_local_handle(Thread* thread, jobject handle); static bool is_frame_handle(JavaThread* thr, jobject obj); static bool is_global_handle(jobject handle); static bool is_weak_global_handle(jobject handle); static long global_handle_memory_usage(); static long weak_global_handle_memory_usage(); // Garbage collection support(global handles only, local handles are traversed from thread) // Traversal of regular global handles static void oops_do(OopClosure* f); // Traversal of weak global handles. Unreachable oops are cleared. static void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f); // Traversal of weak global handles. static void weak_oops_do(OopClosure* f); }; // JNI handle blocks holding local/global JNI handles class JNIHandleBlock : public CHeapObj<mtInternal> { friend class VMStructs; friend class CppInterpreter; private: enum SomeConstants { block_size_in_oops = 32 // Number of handles per handle block }; oop _handles[block_size_in_oops]; // The handles int _top; // Index of next unused handle JNIHandleBlock* _next; // Link to next block // The following instance variables are only used by the first block in a chain. // Having two types of blocks complicates the code and the space overhead in negligble. JNIHandleBlock* _last; // Last block in use JNIHandleBlock* _pop_frame_link; // Block to restore on PopLocalFrame call oop* _free_list; // Handle free list int _allocate_before_rebuild; // Number of blocks to allocate before rebuilding free list // Check JNI, "planned capacity" for current frame (or push/ensure) size_t _planned_capacity; #ifndef PRODUCT JNIHandleBlock* _block_list_link; // Link for list below static JNIHandleBlock* _block_list; // List of all allocated blocks (for debugging only) #endif static JNIHandleBlock* _block_free_list; // Free list of currently unused blocks static int _blocks_allocated; // For debugging/printing // Fill block with bad_handle values void zap(); protected: // No more handles in both the current and following blocks void clear() { _top = 0; } private: // Free list computation void rebuild_free_list(); public: // Handle allocation jobject allocate_handle(oop obj); // Block allocation and block free list management static JNIHandleBlock* allocate_block(Thread* thread = NULL); static void release_block(JNIHandleBlock* block, Thread* thread = NULL); // JNI PushLocalFrame/PopLocalFrame support JNIHandleBlock* pop_frame_link() const { return _pop_frame_link; } void set_pop_frame_link(JNIHandleBlock* block) { _pop_frame_link = block; } // Stub generator support static int top_offset_in_bytes() { return offset_of(JNIHandleBlock, _top); } // Garbage collection support // Traversal of regular handles void oops_do(OopClosure* f); // Traversal of weak handles. Unreachable oops are cleared. void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f); // Checked JNI support void set_planned_capacity(size_t planned_capacity) { _planned_capacity = planned_capacity; } const size_t get_planned_capacity() { return _planned_capacity; } const size_t get_number_of_live_handles(); // Debugging bool chain_contains(jobject handle) const; // Does this block or following blocks contain handle bool contains(jobject handle) const; // Does this block contain handle int length() const; // Length of chain starting with this block long memory_usage() const; #ifndef PRODUCT static bool any_contains(jobject handle); // Does any block currently in use contain handle static void print_statistics(); #endif }; inline bool JNIHandles::is_jweak(jobject handle) { STATIC_ASSERT(weak_tag_size == 1); STATIC_ASSERT(weak_tag_value == 1); return (reinterpret_cast<uintptr_t>(handle) & weak_tag_mask) != 0; } inline oop& JNIHandles::jobject_ref(jobject handle) { assert(!is_jweak(handle), "precondition"); return *reinterpret_cast<oop*>(handle); } inline oop& JNIHandles::jweak_ref(jobject handle) { assert(is_jweak(handle), "precondition"); char* ptr = reinterpret_cast<char*>(handle) - weak_tag_value; return *reinterpret_cast<oop*>(ptr); } // external_guard is true if called from resolve_external_guard. // Treat deleted (and possibly zapped) as NULL for external_guard, // else as (asserted) error. template<bool external_guard> inline oop JNIHandles::guard_value(oop value) { if (!external_guard) { assert(value != badJNIHandle, "Pointing to zapped jni handle area"); assert(value != deleted_handle(), "Used a deleted global handle"); } else if ((value == badJNIHandle) || (value == deleted_handle())) { value = NULL; } return value; } // external_guard is true if called from resolve_external_guard. template<bool external_guard> inline oop JNIHandles::resolve_impl(jobject handle) { assert(handle != NULL, "precondition"); oop result; if (is_jweak(handle)) { // Unlikely result = resolve_jweak<external_guard>(handle); } else { result = jobject_ref(handle); // Construction of jobjects canonicalize a null value into a null // jobject, so for non-jweak the pointee should never be null. assert(external_guard || result != NULL, "Invalid value read from jni handle"); result = guard_value<external_guard>(result); } return result; } inline oop JNIHandles::resolve(jobject handle) { oop result = NULL; if (handle != NULL) { result = resolve_impl<false /* external_guard */ >(handle); } return result; } // Resolve some erroneous cases to NULL, rather than treating them as // possibly unchecked errors. In particular, deleted handles are // treated as NULL (though a deleted and later reallocated handle // isn't detected). inline oop JNIHandles::resolve_external_guard(jobject handle) { oop result = NULL; if (handle != NULL) { result = resolve_impl<true /* external_guard */ >(handle); } return result; } inline oop JNIHandles::resolve_non_null(jobject handle) { assert(handle != NULL, "JNI handle should not be null"); oop result = resolve_impl<false /* external_guard */ >(handle); assert(result != NULL, "NULL read from jni handle"); return result; } inline void JNIHandles::destroy_local(jobject handle) { if (handle != NULL) { jobject_ref(handle) = deleted_handle(); } } #endif // SHARE_VM_RUNTIME_JNIHANDLES_HPP
412
0.882273
1
0.882273
game-dev
MEDIA
0.638129
game-dev
0.760967
1
0.760967
TheFunny/ArisuAutoSweeper
1,624
tasks/bounty/ui.py
from module.base.timer import Timer from module.logger import logger from module.ocr.ocr import DigitCounter from tasks.base.ui import UI from tasks.bounty.assets.assets_bounty import * from tasks.stage.list import StageList from tasks.stage.sweep import StageSweep BOUNTY_LIST = StageList('BountyList') BOUNTY_SWEEP = StageSweep('BountySweep', 6) class BountyUI(UI): def select_bounty(self, dest_enter: ButtonWrapper, dest_check: ButtonWrapper): timer = Timer(5, 10).start() while 1: self.device.screenshot() self.appear_then_click(dest_enter, interval=1) if self.appear(dest_check): return True if timer.reached(): return False def enter_stage(self, index: int) -> bool: if not index: index = BOUNTY_LIST.insight_max_sweepable_index(self) if BOUNTY_LIST.select_index_enter(self, index): return True return False def do_sweep(self, num: int) -> bool: if BOUNTY_SWEEP.do_sweep(self, num=num): return True return False def get_ticket(self): """ Page: in: page_bounty """ if not self.appear(CHECK_BOUNTY): logger.warning('OCR failed due to invalid page') return False ticket, _, total = DigitCounter(OCR_TICKET).ocr_single_line(self.device.image) if total == 0: logger.warning('Invalid ticket') return False logger.attr('BountyTicket', ticket) self.config.stored.BountyTicket.set(ticket) return True
412
0.849851
1
0.849851
game-dev
MEDIA
0.411985
game-dev
0.805769
1
0.805769
IJEMIN/Unity-Programming-Essence
2,260
15/Zombie/Assets/Scripts/ItemSpawner.cs
using UnityEngine; using UnityEngine.AI; // 내비메쉬 관련 코드 // 주기적으로 아이템을 플레이어 근처에 생성하는 스크립트 public class ItemSpawner : MonoBehaviour { public GameObject[] items; // 생성할 아이템들 public Transform playerTransform; // 플레이어의 트랜스폼 public float maxDistance = 5f; // 플레이어 위치로부터 아이템이 배치될 최대 반경 public float timeBetSpawnMax = 7f; // 최대 시간 간격 public float timeBetSpawnMin = 2f; // 최소 시간 간격 private float timeBetSpawn; // 생성 간격 private float lastSpawnTime; // 마지막 생성 시점 private void Start() { // 생성 간격과 마지막 생성 시점 초기화 timeBetSpawn = Random.Range(timeBetSpawnMin, timeBetSpawnMax); lastSpawnTime = 0; } // 주기적으로 아이템 생성 처리 실행 private void Update() { // 현재 시점이 마지막 생성 시점에서 생성 주기 이상 지남 // && 플레이어 캐릭터가 존재함 if (Time.time >= lastSpawnTime + timeBetSpawn && playerTransform != null) { // 마지막 생성 시간 갱신 lastSpawnTime = Time.time; // 생성 주기를 랜덤으로 변경 timeBetSpawn = Random.Range(timeBetSpawnMin, timeBetSpawnMax); // 아이템 생성 실행 Spawn(); } } // 실제 아이템 생성 처리 private void Spawn() { // 플레이어 근처에서 내비메시 위의 랜덤 위치 가져오기 Vector3 spawnPosition = GetRandomPointOnNavMesh(playerTransform.position, maxDistance); // 바닥에서 0.5만큼 위로 올리기 spawnPosition += Vector3.up * 0.5f; // 아이템 중 하나를 무작위로 골라 랜덤 위치에 생성 GameObject selectedItem = items[Random.Range(0, items.Length)]; GameObject item = Instantiate(selectedItem, spawnPosition, Quaternion.identity); // 생성된 아이템을 5초 뒤에 파괴 Destroy(item, 5f); } // 내비메시 위의 랜덤한 위치를 반환하는 메서드 // center를 중심으로 distance 반경 안에서 랜덤한 위치를 찾는다 private Vector3 GetRandomPointOnNavMesh(Vector3 center, float distance) { // center를 중심으로 반지름이 maxDistance인 구 안에서의 랜덤한 위치 하나를 저장 // Random.insideUnitSphere는 반지름이 1인 구 안에서의 랜덤한 한 점을 반환하는 프로퍼티 Vector3 randomPos = Random.insideUnitSphere * distance + center; // 내비메시 샘플링의 결과 정보를 저장하는 변수 NavMeshHit hit; // maxDistance 반경 안에서, randomPos에 가장 가까운 내비메시 위의 한 점을 찾음 NavMesh.SamplePosition(randomPos, out hit, distance, NavMesh.AllAreas); // 찾은 점 반환 return hit.position; } }
412
0.62992
1
0.62992
game-dev
MEDIA
0.899925
game-dev
0.779227
1
0.779227
LordOfDragons/dragengine
2,448
src/modules/combined/fbx/src/shared/property/fbxPropertyInteger.h
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * 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. */ #ifndef _FBXPROPERTYINTEGER_H_ #define _FBXPROPERTYINTEGER_H_ #include "../fbxProperty.h" /** * \brief FBX property integer. */ class fbxPropertyInteger : public fbxProperty{ private: int pValue; public: /** \name Constructors and Destructors */ /*@{*/ /** \brief Create property. */ fbxPropertyInteger(); /** \brief Load property. */ fbxPropertyInteger( decBaseFileReader &reader ); protected: /** \brief Clean up property. */ virtual ~fbxPropertyInteger(); /*@}*/ public: /** \name Constructors and Destructors */ /*@{*/ /** \brief Value. */ inline int GetValue() const{ return pValue; } /** \brief Set value. */ void SetValue( int value ); /** \brief Casting throwing exception if wrong type. */ virtual fbxPropertyInteger &CastInteger(); /** \brief Get values as specific type if possible. */ virtual bool GetValueAsBool() const; virtual int GetValueAsInt() const; virtual int64_t GetValueAsLong() const; virtual float GetValueAsFloat() const; virtual double GetValueAsDouble() const; /** \brief Save to file. */ virtual void Save( decBaseFileWriter &writer ); /** \brief Debug print property structure. */ virtual void DebugPrintStructure( deBaseModule &logger, const decString &prefix ) const; /*@}*/ }; #endif
412
0.902775
1
0.902775
game-dev
MEDIA
0.478512
game-dev
0.561349
1
0.561349
Cytoid/Cytoid
4,278
Assets/Packages/Coffee/UIExtensions/UIEffect/Scripts/UIHsvModifier.cs
using UnityEngine; using UnityEngine.Serialization; using UnityEngine.UI; namespace Coffee.UIExtensions { /// <summary> /// HSV Modifier. /// </summary> [AddComponentMenu("UI/UIEffect/UIHsvModifier", 4)] public class UIHsvModifier : UIEffectBase { //################################ // Constant or Static Members. //################################ public const string shaderName = "UI/Hidden/UI-Effect-HSV"; static readonly ParameterTexture _ptex = new ParameterTexture(7, 128, "_ParamTex"); //################################ // Serialize Members. //################################ [Header("Target")] [Tooltip("Target color to affect hsv shift.")] [SerializeField] [ColorUsage(false)] Color m_TargetColor = Color.red; [Tooltip("Color range to affect hsv shift [0 ~ 1].")] [SerializeField] [Range(0, 1)] float m_Range = 0.1f; [Header("Adjustment")] [Tooltip("Hue shift [-0.5 ~ 0.5].")] [SerializeField] [Range(-0.5f, 0.5f)] float m_Hue; [Tooltip("Saturation shift [-0.5 ~ 0.5].")] [SerializeField] [Range(-0.5f, 0.5f)] float m_Saturation; [Tooltip("Value shift [-0.5 ~ 0.5].")] [SerializeField] [Range(-0.5f, 0.5f)] float m_Value; //################################ // Public Members. //################################ /// <summary> /// Target color to affect hsv shift. /// </summary> public Color targetColor { get { return m_TargetColor; } set { if (m_TargetColor != value) { m_TargetColor = value; SetDirty(); } } } /// <summary> /// Color range to affect hsv shift [0 ~ 1]. /// </summary> public float range { get { return m_Range; } set { value = Mathf.Clamp(value, 0, 1); if (!Mathf.Approximately(m_Range, value)) { m_Range = value; SetDirty(); } } } /// <summary> /// Saturation shift [-0.5 ~ 0.5]. /// </summary> public float saturation { get { return m_Saturation; } set { value = Mathf.Clamp(value, -0.5f, 0.5f); if (!Mathf.Approximately(m_Saturation, value)) { m_Saturation = value; SetDirty(); } } } /// <summary> /// Value shift [-0.5 ~ 0.5]. /// </summary> public float value { get { return m_Value; } set { value = Mathf.Clamp(value, -0.5f, 0.5f); if (!Mathf.Approximately(m_Value, value)) { m_Value = value; SetDirty(); } } } /// <summary> /// Hue shift [-0.5 ~ 0.5]. /// </summary> public float hue { get { return m_Hue; } set { value = Mathf.Clamp(value, -0.5f, 0.5f); if (!Mathf.Approximately(m_Hue, value)) { m_Hue = value; SetDirty(); } } } /// <summary> /// Gets the parameter texture. /// </summary> public override ParameterTexture ptex { get { return _ptex; } } #if UNITY_EDITOR protected override Material GetMaterial() { if (isTMPro) { return null; } return MaterialResolver.GetOrGenerateMaterialVariant(Shader.Find(shaderName)); } #endif /// <summary> /// Modifies the mesh. /// </summary> public override void ModifyMesh(VertexHelper vh) { if (!isActiveAndEnabled) return; float normalizedIndex = ptex.GetNormalizedIndex(this); UIVertex vertex = default(UIVertex); int count = vh.currentVertCount; for (int i = 0; i < count; i++) { vh.PopulateUIVertex(ref vertex, i); vertex.uv0 = new Vector2( Packer.ToFloat(vertex.uv0.x, vertex.uv0.y), normalizedIndex ); vh.SetUIVertex(vertex, i); } } protected override void SetDirty() { float h, s, v; Color.RGBToHSV(m_TargetColor, out h, out s, out v); foreach (var m in materials) { ptex.RegisterMaterial (m); } ptex.SetData(this, 0, h); // param1.x : target hue ptex.SetData(this, 1, s); // param1.y : target saturation ptex.SetData(this, 2, v); // param1.z : target value ptex.SetData(this, 3, m_Range); // param1.w : target range ptex.SetData(this, 4, m_Hue + 0.5f); // param2.x : hue shift ptex.SetData(this, 5, m_Saturation + 0.5f); // param2.y : saturation shift ptex.SetData(this, 6, m_Value + 0.5f); // param2.z : value shift } //################################ // Private Members. //################################ } }
412
0.811218
1
0.811218
game-dev
MEDIA
0.654948
game-dev,graphics-rendering
0.600991
1
0.600991
Benimatic/twilightforest
2,604
src/main/java/twilightforest/client/GuiTFCinderFurnace.java
package twilightforest.client; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ContainerFurnace; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import org.lwjgl.opengl.GL11; import twilightforest.inventory.ContainerTFCinderFurnace; import twilightforest.tileentity.TileEntityTFCinderFurnace; @SideOnly(Side.CLIENT) public class GuiTFCinderFurnace extends GuiContainer { private static final ResourceLocation furnaceGuiTextures = new ResourceLocation("textures/gui/container/furnace.png"); private TileEntityTFCinderFurnace tileFurnace; public GuiTFCinderFurnace(InventoryPlayer inventory, TileEntityTFCinderFurnace furnace) { super(new ContainerTFCinderFurnace(inventory, furnace)); this.tileFurnace = furnace; } public GuiTFCinderFurnace(InventoryPlayer inventory, World world, int x, int y, int z) { this(inventory, (TileEntityTFCinderFurnace)world.getTileEntity(x, y, z)); } /** * Draw the foreground layer for the GuiContainer (everything in front of the items) */ protected void drawGuiContainerForegroundLayer(int p_146979_1_, int p_146979_2_) { String s = this.tileFurnace.hasCustomInventoryName() ? this.tileFurnace.getInventoryName() : I18n.format(this.tileFurnace.getInventoryName(), new Object[0]); this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, 4210752); } protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.mc.getTextureManager().bindTexture(furnaceGuiTextures); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize); if (this.tileFurnace.isBurning()) { int i1 = this.tileFurnace.getBurnTimeRemainingScaled(13); this.drawTexturedModalRect(k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 1); i1 = this.tileFurnace.getCookProgressScaled(24); this.drawTexturedModalRect(k + 79, l + 34, 176, 14, i1 + 1, 16); } } }
412
0.770795
1
0.770795
game-dev
MEDIA
0.959607
game-dev
0.786785
1
0.786785
fuse-open/fuselibs
21,920
Source/Fuse.Triggers/Trigger.uno
using Uno; using Uno.Collections; using Uno.UX; using Fuse.Animations; using Fuse.Triggers.Actions; namespace Fuse.Triggers { public enum TriggerBypassMode { /** Changes in state during the root frame are handled as bypass, with special exceptions. */ Standard, /** All changes are treated as normal and nothing is bypassed. */ Never, /** Only changes during the rooting frame are handled as bypass, without special exceptions. */ Rooting, /** Deprecated: 2017-07-21 For possible backwards compatibilty, like Standard but excludes the check for layout bypass. This mode should not be used. */ ExceptLayout, } public enum TriggerPlayState { /** Not playing at the moment */ Stopped, /** Playing backwards */ Backward, /** Playing forward */ Forward, /** Something is seeking forward on the trigger */ SeekBackward, /** Something is seeking backward on the trigger */ SeekForward, } /* There are a series of high-level actions, such as `Activate` and their implementations `DirectActivate` and `BypassActivate`. In most cases the high-level function should be called (ex. `activate`). It will appropriately bypass, or progress normally, base on the rooting and bypass state of the trigger. They can also safely be called at any time (even when not rooted), but they will just be ignored in that case (on the expectation that OnRooted will call them again correctly). The `Direct...` and `Bypass...` functions should be called only under special circumstances. They must be properly guarded for rooting and bypass state -- thus can lead to exceptions if not called correctly. */ /** Triggers are the main tools for interaction response, transitions and animation in Fuse. @topic Triggers and animation Triggers are objects that can be used in UX markup that detect events, gestures, other user input or changes of state in your app, and performs animations and actions in response. When a trigger is *activated*, it performs a *timeline of actions* based on what objects you put inside the trigger tag. Triggers can contain the following types of child-nodes in UX Markup: * @Animators that animate properties, transforms or effects when the trigger is active * @Actions that perform actions with permanent effects, or call back to JavaScript when the trigger activates. * @Nodes (visuals, behaviors, other triggers) that are added to the parent visual while the trigger is active. * @Resources (nodes marked with `ux:Key="your_key"`), which overrides `{Resource your_key}` for the parent scope while the trigger is active. > See the [remarks section](#section-remarks) at the bottom of this page for more information ## Available triggers in Fuse [subclass Fuse.Triggers.Trigger] @remarks Docs/TriggersRemarks.md */ public abstract class Trigger: NodeGroupBase, IUnwrappedPlayerFeedback { bool _isStarted; Action _doneAction; bool _doneOn; TriggerAnimationState _animState; TriggerAnimation _animation; List<TriggerAction> _actions; TriggerPlayState _lastPlayState = TriggerPlayState.Stopped; //special mode for Timeline to be in "started" state at Progress==0 internal bool _startAtZero = false; TriggerBypassMode _bypass = TriggerBypassMode.Standard; /** Specifies how changes in state are handled while initializing and rooting the trigger. In some cases, a trigger is rooted to the visual tree while in its active state. In these cases, one could expect one of two things to happen; 1. the animation plays from the start as soon as the trigger is rooted. 2. the trigger jumps instantly to the end of the animation. One can use the `Bypass` property to differentiate between these. The default is `Bypass="Standard"`, which corresponds to case 2. If one wants the effect of case 2, one can use `Bypass="Never"` instead. */ public TriggerBypassMode Bypass { get { return _bypass; } set { _bypass = value; if (value == TriggerBypassMode.ExceptLayout && !_warnBypass) { Fuse.Diagnostics.Deprecated( "ExceptLayout mode indicates a problem in trigger expecations and should no tbe used", this ); _warnBypass = true; //once is enough } } } static bool _warnBypass; /** The animation associated with this trigger. This object is created automatically when animators, actions etc. are added to the trigger. @advanced */ public TriggerAnimation Animation { get { if (_animation == null) _animation = new TriggerAnimation(); return _animation; } set { _animation = value; } } /** Specifies a multiplier to the elapsed time for animation playback. */ public double TimeMultiplier { get { return Animation.TimeMultiplier; } set { Animation.TimeMultiplier = value; } } /** Stretches the duration of the animation to fill up this period of time. */ public double StretchDuration { get { return Animation.StretchDuration; } set { Animation.StretchDuration = value; } } /** Specifies an explicit backward animation instead of using the implied backward animation of the animators involved. Be aware that actions are not part of the animation. Triggers normally use the same animators when deactivating as they do when they activate. There are however animations that require a different set of animators when animating back from the active state. For this purpose one can bind a new set of animators to the `BackwardAnimation` property like so: ```xml <Panel Width="100" Height="100" Color="#00b2ee"> <WhilePressed> <Rotate Degrees="90" Duration="0.5" /> <Scale Factor="1.5" Duration="1" Easing="QuadraticInOut" /> <TriggerAnimation ux:Binding="BackwardAnimation"> <Scale Factor="1.5" Duration="1" Easing="QuadraticInOut" /> </TriggerAnimation> </WhilePressed> </Panel> ```xml In this example, the @Panel only rotates when pressed. When the pointer is released, it does not animate back. Note that the effect of the animators are still reversed. The only difference is that they loose their duration. */ public TriggerAnimation BackwardAnimation { get { return Animation.Backward; } set { Animation.Backward = value; } } /** `true` if there is an explicit backward animation. */ public bool HasBackwardAnimation { get { return Animation.HasBackward; } } /** If there is a transition between forward/backward playback and two timeilnes are being used (implicit or explicit) this specifies the cross-fade time. */ public double CrossFadeDuration { get { return Animation.CrossFadeDuration; } set { Animation.CrossFadeDuration = value; } } [UXContent] public IList<Animator> Animators { get { return Animation.Animators; } } public bool HasAnimators { get { return _animation != null && _animation.HasAnimators; } } [UXContent] /** A list of actions that execute with the trigger. These may react on simple direction changes, or at specific time offsets. */ public IList<TriggerAction> Actions { get { if (_actions == null) _actions = new List<TriggerAction>(); return _actions; } } public bool HasActions { get { return _actions != null && _actions.Count > 0; } } void SetDone(Action done, bool on) { _doneOn = on; _doneAction = done; } /** The current progress of the trigger. Triggers are defined over a progress range from 0...1. How a trigger plays over its progress depends on the type of trigger. A trigger at 0 progress is completely deactivated. Content added via the trigger is removed at this time. Any progress above 0 will have the content added. Certain animators may delay the removal of content until their animation is completed. */ public double Progress { get { if (_animState != null) return _animState.Progress; return 0; } } static Selector ProgressName = "Progress"; //negative backwards, postiive forwards, 0 was stopped. This variable just watches //playback and does not influence it void SetPlayState(TriggerPlayState next) { if (next == _lastPlayState) return; _lastPlayState = next; OnPlayStateChanged(next); if (next == TriggerPlayState.Stopped || _actions == null) return; //play direction based triggers var dir = IsForward(next) ? TriggerWhen.Forward : TriggerWhen.Backward; for (int i=0; i < _actions.Count; ++i) { var action = _actions[i]; if (action.IsProgressTriggered) continue; if (action.When == dir || action.When == TriggerWhen.ForwardAndBackward) AddDeferredAction(action); } } class DeferredItem { public TriggerAction Action; public Node Node; public void Perform() { Action.PerformFromNode(Node); } } void AddDeferredAction(TriggerAction i) { UpdateManager.AddDeferredAction( new DeferredItem{ Action = i, Node = this }.Perform ); } protected virtual void OnPlayStateChanged(TriggerPlayState state) { } //mortoray: I'm undecided on just making this public, nothing should really need it public protected internal TriggerPlayState PlayState { get { return _lastPlayState; } } void IBasePlayerFeedback.OnPlaybackDone(object s) { SetPlayState(TriggerPlayState.Stopped); if (_animState == null) { Fuse.Diagnostics.InternalError( "Trigger.OnPlaybackdone called with _animState == null", this ); return; } //defer action to end since it may alter our state Action perform = null; if (_doneAction != null) { if ( (_doneOn && _animState.ProgressFullOn) || (!_doneOn && _animState.ProgressFullOff) ) { perform = _doneAction; } _doneAction = null; } //check in case we had a forced stop (_animState is cleaned, thus no more feedback) CleanupStableState(); if (perform != null) perform(); } void IBasePlayerFeedback.OnStable(object s) { CleanupStableState(); } void CleanupStableState() { if (_animState == null || !_animState.IsStable) return; if (_animState.ProgressFullOff && !_startAtZero) CleanupState(); } protected void Start() { if (!_isStarted) { if (!IsRootingStarted) { Fuse.Diagnostics.UserError("Warning: Trigger.uno - Trigger started prior to being rooted: ", this ); return; } _isStarted = true; UseContent = true; PlayActions(TriggerWhen.Start); } } void PlayActions(TriggerWhen when) { if (_actions != null) { for (int i=0; i < _actions.Count; ++i) { var act = _actions[i]; //TODO: these are sync, not like PlayState/Progress change actions. This is perhaps not //a good idea, but was required for the Navigation preparation stuff (which likely //needs to chagne anyway) if (act.When == when) act.PerformFromNode(this); } } } protected void Stop(bool force = false) { if (_startAtZero && !force) return; if (_isStarted) { PlayActions(TriggerWhen.Stop); UseContent = false; _isStarted = false; } } bool ShouldIgnore { get { return !IsRootingStarted; } } /** Determines whether an operation should be done in bypass mode. This is used by all the high-level functions to determine whether the `Direct...` or `Bypass...` method is called. */ bool ShouldBypass { get { if (Bypass == TriggerBypassMode.Never) return false; //pretend we were already rooted for preserved frames if (IsPreservedRootFrame && Bypass != TriggerBypassMode.Rooting) return false; if (_noLayoutFrame == UpdateManager.FrameIndex && Bypass != TriggerBypassMode.ExceptLayout) return true; if (Node.IsRootCapture(_rootCaptureIndex)) return true; else _rootCaptureIndex = 0; return !IsRootingCompleted; } } int _noLayoutFrame = -1; /** Indicates the trigger is bound to the layout of a visual. This will keep the trigger in Bypass mode until after the first layout of the element is obtained. This is required since layout does not happen in the same root grouping/update phase as the creation of the element, yet not having a layout should qualify as part of the rooting period. A trigger that deals with layout should call this during its rooting. */ protected void RequireLayout(Visual visual) { if (visual == null || !visual.HasMarginBox) _noLayoutFrame = UpdateManager.FrameIndex; } /** Activates the trigger (target progress of 1). This uses the appropriate Direct or Bypass operation. */ protected void Activate(Action done = null) { if (ShouldIgnore) return; if (ShouldBypass) BypassActivate(); else DirectActivate(done); } protected void BypassActivate() { BypassSeek(1); //must also play to get open ended animations running PlayOn(); } protected void DirectActivate(Action done = null) { PlayEnd(true, done); } /** Deactivates the trigger (target progress of 0). This uses the appropriate Direct or Bypass operation. */ protected void Deactivate() { if (ShouldIgnore) return; if (ShouldBypass) BypassDeactivate(); else DirectDeactivate(); } protected void DirectDeactivate() { //TODO: Maybe `Stop` should be implied when we reach 0 progress PlayEnd(false, StopAction); } protected void BypassDeactivate() { BypassSeek(0); DirectDeactivate(); } void StopAction() { Stop(); } /** Plays the trigger to progress 1 then back to 0. This is intended for use in event/pulse-ilke triggers such as `Clicked`. */ protected void Pulse() { if (ShouldIgnore) return; //emulate pause to force direction based tirggers to trigger on a pulse SetPlayState(TriggerPlayState.Stopped); DirectActivate(DirectDeactivate); } /** Plays the trigger starting at progress=1 down to 0. This is a special pulse for inverted animation triggers such as `AddingAnimation`. */ protected void PulseBackward() { if (ShouldIgnore) return; BypassActivate(); DirectDeactivate(); } protected void InversePulse() { PlayEnd(false,PlayOn); } void PlayOn() { PlayEnd(true); } /** Play the trigger from where it currently is to the end. @param on whether to play to progress=1 (true) or to progress=0 (false) @param done an action to execute when the progress reaches the desired state (is done) */ protected void PlayEnd(bool on, Action done = null) { if (on) Start(); SetDone(done, on); // direction must be forced in case something activaties/deactivates without an intervening frame. // OnProgressUpdate will be called, but with 0 progress. Check progress though to avoid double // activation at end while stopped. if ( (on && Progress < 1) || (!on && Progress >0 ) || _lastPlayState != TriggerPlayState.Stopped ) SetPlayState( on ? TriggerPlayState.Forward : TriggerPlayState.Backward ); //this optimization here is vitally important otherwise you have hundreds of triggers in app //repeatedly creating the _animState just to deactivate it. if (!on && Progress <= 0 && _animState == null) { if (done != null) done(); _doneAction = null; } else if (EnsureState(on ? 1 : 0)) _animState.PlayEnd(on); } void CleanupState() { if (_animState != null) { _animState.Dispose(); _animState = null; } } void CreateState() { CleanupState(); EnsureAnimationLength(); _animState = Animation.CreateState(Parent); _animState.Feedback = this; } //return true if there is a state to update bool EnsureState(double progress) { if (progress > 0 || _startAtZero) { if (_animState == null)// && (HasActions || HasAnimators)) CreateState(); } return _animState != null; } void EnsureAnimationLength() { if (!HasActions) return; var animFore = Animation.GetAnimatorsDuration(AnimationVariant.Forward); var animBack = Animation.GetAnimatorsDuration(AnimationVariant.Backward); //find max action timings double actFore = 0; double actBack = 0; for (int i=0; i < _actions.Count; ++i) { var action = _actions[i]; var when = action.Delay; if (action.When == TriggerWhen.Forward || action.When == TriggerWhen.ForwardAndBackward) actFore = Math.Max(when,actFore); if (action.When == TriggerWhen.Backward || action.When == TriggerWhen.ForwardAndBackward) actBack = Math.Max(when,actBack); } if (actFore <= animFore && actBack <= animBack) return; var n = new Nothing(); n.Delay = actFore; n.DelayBack = actBack; Animators.Add(n); if (HasBackwardAnimation) { n = new Nothing(); n.Delay = actBack; BackwardAnimation.Animators.Add(n); } } protected void RecreateAnimationState() { if (_animState != null) CreateState(); } protected virtual void OnProgressChanged() { } TriggerPlayState WhatDirection(double diff, bool animating) { if (animating) return diff > 0 ? TriggerPlayState.Forward : diff < 0 ? TriggerPlayState.Backward : TriggerPlayState.Stopped; return diff > 0 ? TriggerPlayState.SeekForward : diff < 0 ? TriggerPlayState.SeekBackward : TriggerPlayState.Stopped; } bool IsForward(TriggerPlayState ps) { return ps == TriggerPlayState.Forward || ps == TriggerPlayState.SeekForward; } bool IsBackward(TriggerPlayState ps) { return ps == TriggerPlayState.Backward || ps == TriggerPlayState.SeekBackward; } //allows the Timeline setter to set the origin inside SetProgress/OnProgressChanged. It's kind of a hack, but //the alternative would somehow be to track the entire origin throughout the animation layers, just for //the one use-case of Timeline. Sender is not needed in the non-Timeline case since Trigger.Progress does //not have a setter. internal bool _suppressPropertyChangedProgress = false; void IUnwrappedPlayerFeedback.OnProgressUpdated(object s, double prev, double cur, PlayerFeedbackFlags flags) { var diff = cur - prev; SetPlayState(WhatDirection(diff, flags.HasFlag(PlayerFeedbackFlags.Animated))); OnProgressChanged(); if (!_suppressPropertyChangedProgress) OnPropertyChanged(ProgressName); if (_actions == null) return; var dir = diff > 0 ? TriggerWhen.Forward : TriggerWhen.Backward; for (int i=0; i < _actions.Count; ++i) { var action = _actions[i]; if (!action.IsProgressTriggered) continue; var tp = action.ProgressWhen( (float)_animState.CurrentAnimatorsDuration ); var call = dir == TriggerWhen.Forward ? (tp >= prev && tp < cur) || (tp == 1 && cur == 1) : (tp <= prev && tp > cur) || (tp == 0 && cur == 0); if (call && (action.When == TriggerWhen.ForwardAndBackward || action.When == dir)) AddDeferredAction(action); } } /** Plays to a specific progress with the given animation variant. Playing follows the duration of time according to the animators in the trigger. Actions are executed appropriately. */ protected void PlayTo(double progress, AnimationVariant variant = AnimationVariant.Forward) { //force state change even if it never actually animates if (progress > Progress) SetPlayState( TriggerPlayState.Forward ); else if (progress < Progress) SetPlayState( TriggerPlayState.Backward ); if (EnsureState(progress)) _animState.PlayToProgress(progress, variant, TriggerAnimationState.SeekFlags.ForcePlayer); } /** Seeks to a specific progress with the given animation variant. Time is skipped over in seek and the animator's jump directly to the target progress. In non-bypass mode the actions will still be triggered (this is important to support user seeking operations on gestures). In bypass mode the actions will be skipped. */ protected void Seek(double progress, AnimationVariant direction = AnimationVariant.Forward) { if (ShouldIgnore) return; if (ShouldBypass) BypassSeek(progress, direction); else DirectSeek(progress, direction); } protected void DirectSeek(double progress, AnimationVariant direction = AnimationVariant.Forward) { SeekImpl(progress, direction, TriggerAnimationState.SeekFlags.ForcePlayer); } protected void BypassSeek(double progress, AnimationVariant direction = AnimationVariant.Forward) { SeekImpl(progress, direction, TriggerAnimationState.SeekFlags.ForcePlayer | TriggerAnimationState.SeekFlags.BypassUpdate ); } void SeekImpl(double progress, AnimationVariant direction, TriggerAnimationState.SeekFlags flags) { if( progress > 0 ) Start(); else Stop(); if (EnsureState(progress)) _animState.SeekProgress(progress, direction,flags); } int _rootCaptureIndex = 0; double _rootProgress; TriggerPlayState _rootPlayState; protected override void OnRooted() { base.OnRooted(); _rootCaptureIndex = Node.RootCaptureIndex; if (IsPreservedRootFrame) { BypassSeek(_rootProgress); if (_rootPlayState != TriggerPlayState.Stopped) PlayEnd(_rootPlayState == TriggerPlayState.Forward ? true : false, _doneAction ); } else { _lastPlayState = TriggerPlayState.Stopped; _doneAction = null; _doneOn = false; if (_startAtZero) { Start(); EnsureState(0); } } } internal override void OnPreserveRootFrame() { base.OnPreserveRootFrame(); _rootProgress = Progress; _rootPlayState = _lastPlayState; } protected override void OnUnrooted() { Stop(true); CleanupState(); UnrootActions(); base.OnUnrooted(); } void UnrootActions() { if (_actions == null) return; for (int i=0; i < _actions.Count; ++i) _actions[i].Unroot(); } } }
412
0.97781
1
0.97781
game-dev
MEDIA
0.972311
game-dev
0.897811
1
0.897811
Waterdish/Shipwright-Android
14,099
soh/src/overlays/actors/ovl_Bg_Ganon_Otyuka/z_bg_ganon_otyuka.c
/* * File: z_bg_ganon_otyka.c * Overlay: ovl_Bg_Ganon_Otyka * Description: Falling Platform (Ganondorf Fight) */ #include "z_bg_ganon_otyuka.h" #include "overlays/actors/ovl_Boss_Ganon/z_boss_ganon.h" #include "vt.h" #include "soh/frame_interpolation.h" #define FLAGS (ACTOR_FLAG_UPDATE_CULLING_DISABLED | ACTOR_FLAG_DRAW_CULLING_DISABLED) typedef enum { /* 0x00 */ FLASH_NONE, /* 0x01 */ FLASH_GROW, /* 0x02 */ FLASH_SHRINK } FlashState; void BgGanonOtyuka_Init(Actor* thisx, PlayState* play); void BgGanonOtyuka_Destroy(Actor* thisx, PlayState* play); void BgGanonOtyuka_Update(Actor* thisx, PlayState* play); void BgGanonOtyuka_Draw(Actor* thisx, PlayState* play); void BgGanonOtyuka_WaitToFall(BgGanonOtyuka* this, PlayState* play); void BgGanonOtyuka_Fall(BgGanonOtyuka* this, PlayState* play); void BgGanonOtyuka_DoNothing(Actor* thisx, PlayState* play); const ActorInit Bg_Ganon_Otyuka_InitVars = { ACTOR_BG_GANON_OTYUKA, ACTORCAT_PROP, FLAGS, OBJECT_GANON, sizeof(BgGanonOtyuka), (ActorFunc)BgGanonOtyuka_Init, (ActorFunc)BgGanonOtyuka_Destroy, (ActorFunc)BgGanonOtyuka_Update, (ActorFunc)BgGanonOtyuka_Draw, NULL, }; static InitChainEntry sInitChain[] = { ICHAIN_VEC3F_DIV1000(scale, 1000, ICHAIN_STOP), }; static u8 sSides[] = { OTYUKA_SIDE_EAST, OTYUKA_SIDE_WEST, OTYUKA_SIDE_SOUTH, OTYUKA_SIDE_NORTH }; static Vec3f D_80876A68[] = { { 120.0f, 0.0f, 0.0f }, { -120.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 120.0f }, { 0.0f, 0.0f, -120.0f }, }; static Color_RGBA8 sDustPrimColor = { 60, 60, 0, 0 }; static Color_RGBA8 sDustEnvColor = { 50, 20, 0, 0 }; static Vec3f sSideCenters[] = { { 60.0f, 0.0f, 0.0f }, { -60.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 60.0f }, { 0.0f, 0.0f, -60.0f }, }; static f32 sSideAngles[] = { M_PI / 2, -M_PI / 2, 0.0f, M_PI }; #include "overlays/ovl_Bg_Ganon_Otyuka/ovl_Bg_Ganon_Otyuka.h" void BgGanonOtyuka_Init(Actor* thisx, PlayState* play2) { BgGanonOtyuka* this = (BgGanonOtyuka*)thisx; PlayState* play = play2; CollisionHeader* colHeader = NULL; Actor_ProcessInitChain(thisx, sInitChain); DynaPolyActor_Init(&this->dyna, DPM_UNK); CollisionHeader_GetVirtual(&sCol, &colHeader); this->dyna.bgId = DynaPoly_SetBgActor(play, &play->colCtx.dyna, thisx, colHeader); if (thisx->params != 0x23) { thisx->draw = NULL; this->actionFunc = BgGanonOtyuka_WaitToFall; } else { thisx->update = BgGanonOtyuka_DoNothing; } } void BgGanonOtyuka_Destroy(Actor* thisx, PlayState* play2) { BgGanonOtyuka* this = (BgGanonOtyuka*)thisx; PlayState* play = play2; DynaPoly_DeleteBgActor(play, &play->colCtx.dyna, this->dyna.bgId); osSyncPrintf(VT_FGCOL(GREEN)); osSyncPrintf("WHY !!!!!!!!!!!!!!!!\n"); osSyncPrintf(VT_RST); } void BgGanonOtyuka_WaitToFall(BgGanonOtyuka* this, PlayState* play) { Actor* thisx = &this->dyna.actor; Actor* prop; BgGanonOtyuka* platform; f32 dx; f32 dy; f32 dz; Vec3f center; s16 i; if (this->isFalling || ((play->actorCtx.unk_02 != 0) && (this->dyna.actor.xyzDistToPlayerSq < 4900.0f))) { osSyncPrintf("OTC O 1\n"); for (i = 0; i < ARRAY_COUNT(D_80876A68); i++) { prop = play->actorCtx.actorLists[ACTORCAT_PROP].head; while (prop != NULL) { if ((prop == thisx) || (prop->id != ACTOR_BG_GANON_OTYUKA)) { prop = prop->next; continue; } platform = (BgGanonOtyuka*)prop; dx = platform->dyna.actor.world.pos.x - this->dyna.actor.world.pos.x + D_80876A68[i].x; dy = platform->dyna.actor.world.pos.y - this->dyna.actor.world.pos.y; dz = platform->dyna.actor.world.pos.z - this->dyna.actor.world.pos.z + D_80876A68[i].z; if ((fabsf(dx) < 10.0f) && (fabsf(dy) < 10.0f) && (fabsf(dz) < 10.0f)) { platform->visibleSides |= sSides[i]; break; } else { prop = prop->next; } } } osSyncPrintf("OTC O 2\n"); for (i = 0; i < ARRAY_COUNT(D_80876A68); i++) { center.x = this->dyna.actor.world.pos.x + D_80876A68[i].x; center.y = this->dyna.actor.world.pos.y; center.z = this->dyna.actor.world.pos.z + D_80876A68[i].z; if (BgCheck_SphVsFirstPoly(&play->colCtx, &center, 50.0f)) { this->unwalledSides |= sSides[i]; } } osSyncPrintf("OTC O 3\n"); this->actionFunc = BgGanonOtyuka_Fall; this->isFalling = true; this->dropTimer = 20; this->flashState = FLASH_GROW; this->flashTimer = 0; this->flashPrimColorR = 255.0f; this->flashPrimColorG = 255.0f; this->flashPrimColorB = 255.0f; this->flashEnvColorR = 255.0f; this->flashEnvColorG = 255.0f; this->flashEnvColorB = 0.0f; } } void BgGanonOtyuka_Fall(BgGanonOtyuka* this, PlayState* play) { Player* player = GET_PLAYER(play); s16 i; Vec3f pos; Vec3f velocity; Vec3f accel; osSyncPrintf("MODE DOWN\n"); if (this->flashState == FLASH_GROW) { Math_ApproachF(&this->flashPrimColorB, 170.0f, 1.0f, 8.5f); Math_ApproachF(&this->flashEnvColorR, 120.0f, 1.0f, 13.5f); Math_ApproachF(&this->flashYScale, 2.5f, 1.0f, 0.25f); if (this->flashYScale == 2.5f) { this->flashState = FLASH_SHRINK; } } else if (this->flashState == FLASH_SHRINK) { Math_ApproachF(&this->flashPrimColorG, 0.0f, 1.0f, 25.5f); Math_ApproachF(&this->flashEnvColorR, 0.0f, 1.0f, 12.0f); Math_ApproachF(&this->flashEnvColorG, 0.0f, 1.0f, 25.5f); Math_ApproachZeroF(&this->flashYScale, 1.0f, 0.25f); if (this->flashYScale == 0.0f) { this->flashState = FLASH_NONE; } } if (this->dropTimer == 0) { this->flashYScale = 0.0f; Math_ApproachF(&this->dyna.actor.world.pos.y, -1000.0f, 1.0f, this->dyna.actor.speedXZ); Math_ApproachF(&this->dyna.actor.speedXZ, 100.0f, 1.0f, 2.0f); if (!(this->unwalledSides & OTYUKA_SIDE_EAST)) { this->dyna.actor.shape.rot.z -= (s16)(this->dyna.actor.speedXZ * 30.0f); } if (!(this->unwalledSides & OTYUKA_SIDE_WEST)) { this->dyna.actor.shape.rot.z += (s16)(this->dyna.actor.speedXZ * 30.0f); } if (!(this->unwalledSides & OTYUKA_SIDE_SOUTH)) { this->dyna.actor.shape.rot.x += (s16)(this->dyna.actor.speedXZ * 30.0f); } if (!(this->unwalledSides & OTYUKA_SIDE_NORTH)) { this->dyna.actor.shape.rot.x -= (s16)(this->dyna.actor.speedXZ * 30.0f); } if (this->dyna.actor.world.pos.y < -750.0f) { if (player->actor.world.pos.y < -400.0f) { accel.x = accel.z = 0.0f; accel.y = 0.1f; velocity.x = velocity.y = velocity.z = 0.0f; for (i = 0; i < 30; i++) { pos.x = Rand_CenteredFloat(150.0f) + this->dyna.actor.world.pos.x; pos.y = Rand_ZeroFloat(60.0f) + -750.0f; pos.z = Rand_CenteredFloat(150.0f) + this->dyna.actor.world.pos.z; func_8002836C(play, &pos, &velocity, &accel, &sDustPrimColor, &sDustEnvColor, (s16)Rand_ZeroFloat(100.0f) + 250, 5, (s16)Rand_ZeroFloat(5.0f) + 15); } func_80033DB8(play, 10, 15); SoundSource_PlaySfxAtFixedWorldPos(play, &this->dyna.actor.world.pos, 40, NA_SE_EV_BOX_BREAK); } Actor_Kill(&this->dyna.actor); } } else { if (this->dropTimer == 1) { Audio_PlaySoundGeneral(NA_SE_EV_STONEDOOR_STOP, &this->dyna.actor.projectedPos, 4, &gSfxDefaultFreqAndVolScale, &gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb); } else { Audio_PlaySoundGeneral(NA_SE_EV_BLOCKSINK - SFX_FLAG, &this->dyna.actor.projectedPos, 4, &gSfxDefaultFreqAndVolScale, &gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb); } Math_ApproachF(&this->dyna.actor.world.pos.y, -1000.0f, 1.0f, this->dyna.actor.speedXZ); Math_ApproachF(&this->dyna.actor.speedXZ, 100.0f, 1.0f, 0.1f); } osSyncPrintf("MODE DOWN END\n"); } void BgGanonOtyuka_DoNothing(Actor* thisx, PlayState* play) { } void BgGanonOtyuka_Update(Actor* thisx, PlayState* play) { BgGanonOtyuka* this = (BgGanonOtyuka*)thisx; this->actionFunc(this, play); this->flashTimer++; if (this->dropTimer != 0) { this->dropTimer--; } } void BgGanonOtyuka_Draw(Actor* thisx, PlayState* play) { BgGanonOtyuka* this = (BgGanonOtyuka*)thisx; s16 i; Gfx* phi_s2; Gfx* phi_s1; Camera* camera = Play_GetCamera(play, 0); Actor* actor; BgGanonOtyuka* platform; BossGanon* ganondorf; f32 spBC = -30.0f; OPEN_DISPS(play->state.gfxCtx); actor = play->actorCtx.actorLists[ACTORCAT_BOSS].head; while (actor != NULL) { if (actor->id == ACTOR_BOSS_GANON) { ganondorf = (BossGanon*)actor; if (ganondorf->actor.params == 0) { if (ganondorf->unk_198 != 0) { spBC = -2000.0f; } break; } } actor = actor->next; } Gfx_SetupDL_25Opa(play->state.gfxCtx); gSPDisplayList(POLY_OPA_DISP++, sPlatformMaterialDL); actor = play->actorCtx.actorLists[ACTORCAT_PROP].head; while (actor != NULL) { if (actor->id == ACTOR_BG_GANON_OTYUKA) { platform = (BgGanonOtyuka*)actor; if (platform->dyna.actor.projectedPos.z > spBC) { FrameInterpolation_RecordOpenChild(platform, 0); if (camera->eye.y > platform->dyna.actor.world.pos.y) { phi_s2 = sPlatformTopDL; } else { phi_s2 = sPlatformBottomDL; } Matrix_Translate(platform->dyna.actor.world.pos.x, platform->dyna.actor.world.pos.y, platform->dyna.actor.world.pos.z, MTXMODE_NEW); phi_s1 = NULL; if (platform->isFalling) { Matrix_RotateX((platform->dyna.actor.shape.rot.x / (f32)0x8000) * M_PI, MTXMODE_APPLY); Matrix_RotateZ((platform->dyna.actor.shape.rot.z / (f32)0x8000) * M_PI, MTXMODE_APPLY); if (camera->eye.y > platform->dyna.actor.world.pos.y) { phi_s1 = sPlatformBottomDL; } else { phi_s1 = sPlatformTopDL; } } gSPMatrix(POLY_OPA_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); gSPDisplayList(POLY_OPA_DISP++, phi_s2); if (phi_s1 != NULL) { gSPDisplayList(POLY_OPA_DISP++, phi_s1); } for (i = 0; i < ARRAY_COUNT(sSides); i++) { if ((platform->visibleSides & sSides[i]) || 1) { // || 1 for frame interpolation Matrix_Push(); Matrix_Translate(sSideCenters[i].x, 0.0f, sSideCenters[i].z, MTXMODE_APPLY); Matrix_RotateY(sSideAngles[i], MTXMODE_APPLY); gSPMatrix(POLY_OPA_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); gSPDisplayList(POLY_OPA_DISP++, sPlatformSideDL); Matrix_Pop(); } } FrameInterpolation_RecordCloseChild(); } } actor = actor->next; } Gfx_SetupDL_25Xlu(play->state.gfxCtx); actor = play->actorCtx.actorLists[ACTORCAT_PROP].head; while (actor != NULL) { if (actor->id == ACTOR_BG_GANON_OTYUKA) { platform = (BgGanonOtyuka*)actor; if ((platform->dyna.actor.projectedPos.z > -30.0f) && (platform->flashState != FLASH_NONE)) { FrameInterpolation_RecordOpenChild(platform, 0); gSPSegment(POLY_XLU_DISP++, 0x08, Gfx_TwoTexScroll(play->state.gfxCtx, 0, platform->flashTimer * 4, 0, 32, 64, 1, platform->flashTimer * 4, 0, 32, 64)); gDPPipeSync(POLY_XLU_DISP++); gDPSetPrimColor(POLY_XLU_DISP++, 0, 0, platform->flashPrimColorR, platform->flashPrimColorG, platform->flashPrimColorB, 0); gDPSetEnvColor(POLY_XLU_DISP++, platform->flashEnvColorR, platform->flashEnvColorG, platform->flashEnvColorB, 128); Matrix_Translate(platform->dyna.actor.world.pos.x, 0.0f, platform->dyna.actor.world.pos.z, MTXMODE_NEW); for (i = 0; i < ARRAY_COUNT(sSides); i++) { if ((platform->unwalledSides & sSides[i]) || 1) { // || 1 for frame interpolation Matrix_Push(); Matrix_Translate(sSideCenters[i].x, 0.0f, sSideCenters[i].z, MTXMODE_APPLY); Matrix_RotateY(sSideAngles[i], MTXMODE_APPLY); Matrix_Scale(0.3f, platform->flashYScale * 0.3f, 0.3f, MTXMODE_APPLY); gSPMatrix(POLY_XLU_DISP++, MATRIX_NEWMTX(play->state.gfxCtx), G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW); gSPDisplayList(POLY_XLU_DISP++, sFlashDL); Matrix_Pop(); } } FrameInterpolation_RecordCloseChild(); } } actor = actor->next; } CLOSE_DISPS(play->state.gfxCtx); }
412
0.783504
1
0.783504
game-dev
MEDIA
0.919993
game-dev
0.981404
1
0.981404
Kaedrin/nwn2cc
1,427
NWN2 WIP/Override/override_latest/Scripts/cmi_s0_tripvinec.NSS
//:://///////////////////////////////////////////// //:: Trip Vine - Heartbeat //:: cmi_s0_tripvine //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: January 23, 2010 //::////////////////////////////////////////////// #include "X0_I0_SPELLS" #include "x2_inc_spellhook" #include "cmi_ginc_spells" void main() { int nDC = GetSpellSaveDC(); if (nDC >= 100) { nDC = GetLocalInt(GetAreaOfEffectCreator(), "DC2102"); if (nDC == 0) nDC = 15; } //Declare major variables object oTarget; effect eKD = EffectKnockdown(); effect eVis = EffectVisualEffect(VFX_DUR_WEB); effect eLink = EffectLinkEffects(eKD, eVis); oTarget = GetFirstInPersistentObject(); while(GetIsObjectValid(oTarget)) { if (spellsIsTarget(oTarget, SPELL_TARGET_SELECTIVEHOSTILE, GetAreaOfEffectCreator())) { if( (GetCreatureFlag(oTarget, CREATURE_VAR_IS_INCORPOREAL) != TRUE) ) // AFW-OEI 05/01/2006: Woodland Stride no longer protects from spells. { if(!MySavingThrow(SAVING_THROW_REFLEX, oTarget, nDC)) { //Fire cast spell at event for the target SignalEvent(oTarget, EventSpellCastAt(GetAreaOfEffectCreator(), SPELL_BRIAR_WEB)); //Entangle effect and Web VFX impact ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, oTarget, RoundsToSeconds(1)); } } } oTarget = GetNextInPersistentObject(); } }
412
0.717353
1
0.717353
game-dev
MEDIA
0.886687
game-dev
0.913014
1
0.913014
DeanRoddey/CQC
5,125
Source/AllProjects/CoreTech/CQCIR/CQCIR_BlasterCmd.hpp
// // FILE NAME: CQCIR_BlasterCmd.hpp // // AUTHOR: Dean Roddey // // CREATED: 02/23/2002 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This class represents a single IR command mapping. It includes the name // of the command, which is the key (e.g. Play, Stop, Power, etc...), and // the IR data string that we send to the blaster when this command is // invoked. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TIRBlasterCmd // PREFIX: irbc // --------------------------------------------------------------------------- class CQCIREXPORT TIRBlasterCmd : public TObject, public MStreamable { public : // ------------------------------------------------------------------- // Public, static methods // ------------------------------------------------------------------- static const TString& strKey ( const TIRBlasterCmd& irbcSrc ); // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TIRBlasterCmd(); TIRBlasterCmd ( const TString& strName ); TIRBlasterCmd ( const TString& strName , const TMemBuf& mbufData , const tCIDLib::TCard4 c4Len ); TIRBlasterCmd ( const TString& strName , const tCIDLib::TSCh* const pchData ); TIRBlasterCmd(const TIRBlasterCmd&) = default; TIRBlasterCmd(TIRBlasterCmd&&) = default; ~TIRBlasterCmd(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TIRBlasterCmd& operator=(const TIRBlasterCmd&) = default; TIRBlasterCmd& operator=(TIRBlasterCmd&&) = default; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TCard4 c4DataLen() const; tCIDLib::TVoid FormatData ( TString& strToFill ) const; const TMemBuf& mbufData() const; const TString& strName() const; const TString& strName ( const TString& strNew ); tCIDLib::TVoid Set ( const TString& strNew , const TString& strData ); tCIDLib::TVoid SetData ( const TMemBuf& mbufData , const tCIDLib::TCard4 c4Len ); protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid StreamFrom ( TBinInStream& strmToReadFrom ) final; tCIDLib::TVoid StreamTo ( TBinOutStream& strmToWriteTo ) const final; private : // ------------------------------------------------------------------- // Private data members // // m_c4DataLen // The length of data in the data buffer, i.e. the number of // bytes that make up the IR command. // // m_mbufData // A buffer of data for this IR command. m_c4DataLen tells // us how many bytes we have, since they can vary in length. // // m_strName // The name of the command. This is the key field, and it is case // sensitive. You should always be consistent about using common // names for common actions, i.e. always use Play or Stop for // those common operations. This will will it easier for a user // to change to a new device, since the commands will be the same, // and just the device name needs to change. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4DataLen; THeapBuf m_mbufData; TString m_strName; // ------------------------------------------------------------------- // Magic Macros // ------------------------------------------------------------------- RTTIDefs(TIRBlasterCmd,TObject) }; #pragma CIDLIB_POPPACK
412
0.930627
1
0.930627
game-dev
MEDIA
0.349021
game-dev
0.86943
1
0.86943
kurtekat/shaiya-episode-6
10,315
sdev/src/user_equipment.cpp
#include <array> #include <ranges> #include <util/util.h> #include <shaiya/include/common/ItemTypes.h> #include <shaiya/include/network/game/outgoing/0300.h> #include "include/main.h" #include "include/shaiya/include/CItem.h" #include "include/shaiya/include/CUser.h" #include "include/shaiya/include/ItemInfo.h" #include "include/shaiya/include/NetworkHelper.h" using namespace shaiya; namespace user_equipment { bool enable_slot(CUser* user, CItem* item, ItemInfo* itemInfo, int equipmentSlot) { auto itemType = static_cast<ItemType>(itemInfo->type); auto realType = itemInfo->realType; switch (equipmentSlot) { case EquipmentSlot::Helmet: return realType == RealType::Helmet; case EquipmentSlot::UpperArmor: return realType == RealType::UpperArmor; case EquipmentSlot::LowerArmor: return realType == RealType::LowerArmor; case EquipmentSlot::Gloves: return realType == RealType::Gloves; case EquipmentSlot::Boots: return realType == RealType::Boots; case EquipmentSlot::Weapon: { if (CItem::IsWeapon(item)) { if (!user->inventory[0][EquipmentSlot::Shield]) return true; if (CItem::IsOneHandWeapon(item)) return true; } return false; } case EquipmentSlot::Shield: { if (realType == RealType::Shield) { auto& item = user->inventory[0][EquipmentSlot::Weapon]; if (!item) return true; if (CItem::IsOneHandWeapon(item)) return true; } return false; } case EquipmentSlot::Cloak: return realType == RealType::Cloak; case EquipmentSlot::Necklace: return realType == RealType::Necklace; case EquipmentSlot::Ring1: case EquipmentSlot::Ring2: return realType == RealType::Ring; case EquipmentSlot::Bracelet1: case EquipmentSlot::Bracelet2: return realType == RealType::Bracelet; case EquipmentSlot::Vehicle: return itemType == ItemType::Vehicle; case EquipmentSlot::Pet: return itemType == ItemType::Pet; case EquipmentSlot::Costume: return itemType == ItemType::Costume; case EquipmentSlot::Wings: return itemType == ItemType::Wings; default: break; } return false; } void init(CUser* user) { user->initStatusFlag = true; for (const auto& [slot, item] : std::views::enumerate( std::as_const(user->inventory[0]))) { if (!item) continue; if (slot < EquipmentSlot::Vehicle) user->itemQualityEx[slot] = item->quality; CUser::ItemEquipmentAdd(user, item, slot); } user->initStatusFlag = false; CUser::SetAttack(user); } /// <summary> /// Sends packet 0x307 (6.4) to the user. /// </summary> void send_0x307(CUser* user, CUser* target) { GameGetInfoUserItemsOutgoing<GetInfoItemUnit_EP5, 17> outgoing{}; outgoing.itemCount = 0; for (const auto& [slot, item] : std::views::enumerate( std::as_const(target->inventory[0]))) { if (!item) continue; if (std::cmp_greater_equal(slot, outgoing.itemList.size())) break; if (slot < EquipmentSlot::Wings) { GetInfoItemUnit_EP5 item0307{}; item0307.slot = slot; item0307.type = item->type; item0307.typeId = item->typeId; if (slot < EquipmentSlot::Vehicle) item0307.quality = item->quality; item0307.gems = item->gems; item0307.craftName = item->craftName; outgoing.itemList[outgoing.itemCount] = item0307; ++outgoing.itemCount; } } int length = outgoing.baseLength + (outgoing.itemCount * sizeof(GetInfoItemUnit_EP5)); NetworkHelper::Send(user, &outgoing, length); } } unsigned u0x46846B = 0x46846B; unsigned u0x468535 = 0x468535; void __declspec(naked) naked_0x468385() { __asm { pushad push eax // slot push esi // itemInfo push ebx // item push edi // user call user_equipment::enable_slot add esp,0x10 test al,al popad je _0x468535 jmp u0x46846B _0x468535: jmp u0x468535 } } unsigned u0x46153E = 0x46153E; void __declspec(naked) naked_0x4614E3() { __asm { pushad push esi // user call user_equipment::init add esp,0x4 popad jmp u0x46153E } } unsigned u0x477E02 = 0x477E02; void __declspec(naked) naked_0x477D4F() { __asm { pushad push eax // target push edi // user call user_equipment::send_0x307 add esp,0x8 popad jmp u0x477E02 } } void hook::user_equipment() { // CUser::EnableEquipment (switch) util::detour((void*)0x468385, naked_0x468385, 9); // CUser::InitEquipment util::detour((void*)0x4614E3, naked_0x4614E3, 6); // CUser::PacketGetInfo case 0x307 util::detour((void*)0x477D4F, naked_0x477D4F, 7); // CUser::InitEquipment (overload) util::write_memory((void*)0x4615B3, max_equipment_slot, 1); // CUser::ItemBagToBag util::write_memory((void*)0x46862D, max_equipment_slot, 1); util::write_memory((void*)0x468722, max_equipment_slot, 1); util::write_memory((void*)0x4688B0, max_equipment_slot, 1); util::write_memory((void*)0x468955, max_equipment_slot, 1); util::write_memory((void*)0x468A2B, max_equipment_slot, 1); util::write_memory((void*)0x468B5D, max_equipment_slot, 1); // CUser::ClearEquipment util::write_memory((void*)0x46BCCF, max_equipment_slot, 1); // CUser::PacketAdminCmdD (0xF901) // The client does not support more than 13 items (thanks, xarel) //util::write_memory((void*)0x482896, max_equipment_slot, 1); // user->itemQualityLv[0] (0x199 to 0x62A0) std::array<uint8_t, 2> a00{ 0xA0, 0x62 }; // CUser::ItemEquipmentAdd util::write_memory((void*)0x46166A, &a00, 2); util::write_memory((void*)0x4617FB, &a00, 2); util::write_memory((void*)0x46194C, &a00, 2); util::write_memory((void*)0x461962, &a00, 2); // CUser::ItemEquipmentRem util::write_memory((void*)0x461ED4, &a00, 2); util::write_memory((void*)0x461EEA, &a00, 2); util::write_memory((void*)0x462662, &a00, 2); // CUser::ItemEquipmentAttackAdd util::write_memory((void*)0x462DD9, &a00, 2); util::write_memory((void*)0x462DEF, &a00, 2); util::write_memory((void*)0x462E51, &a00, 2); util::write_memory((void*)0x462E67, &a00, 2); util::write_memory((void*)0x462E8C, &a00, 2); util::write_memory((void*)0x462EA2, &a00, 2); // CUser::QualityDec util::write_memory((void*)0x4682DE, &a00, 2); util::write_memory((void*)0x468305, &a00, 2); // CUser::ItemGeMRemoveAll util::write_memory((void*)0x4703CB, &a00, 2); util::write_memory((void*)0x4703E1, &a00, 2); util::write_memory((void*)0x470428, &a00, 2); util::write_memory((void*)0x471438, &a00, 2); util::write_memory((void*)0x471450, &a00, 2); util::write_memory((void*)0x471497, &a00, 2); util::write_memory((void*)0x471E3A, &a00, 2); util::write_memory((void*)0x471E5F, &a00, 2); util::write_memory((void*)0x4720AC, &a00, 2); util::write_memory((void*)0x4720E7, &a00, 2); util::write_memory((void*)0x47395E, &a00, 2); util::write_memory((void*)0x47398F, &a00, 2); // user->itemQuality[0] (0x1A6 to 0x62B8) std::array<uint8_t, 2> a01{ 0xB8, 0x62 }; // CUser::ItemDropByUserDeath util::write_memory((void*)0x46754C, &a01, 2); util::write_memory((void*)0x467587, &a01, 2); // CUser::ItemDropByMobDeath util::write_memory((void*)0x46798C, &a01, 2); util::write_memory((void*)0x4679C7, &a01, 2); // CUser::ItemBagToBag util::write_memory((void*)0x468665, &a01, 2); util::write_memory((void*)0x4686B6, &a01, 2); util::write_memory((void*)0x4687CB, &a01, 2); util::write_memory((void*)0x468813, &a01, 2); util::write_memory((void*)0x468996, &a01, 2); util::write_memory((void*)0x468A6A, &a01, 2); util::write_memory((void*)0x468ABA, &a01, 2); // CUser::ItemDrop util::write_memory((void*)0x469C64, &a01, 2); util::write_memory((void*)0x469CA4, &a01, 2); // CUser::ItemRemove util::write_memory((void*)0x46C2DC, &a01, 2); util::write_memory((void*)0x46C317, &a01, 2); // CUser::ItemRemoveFree util::write_memory((void*)0x46C50C, &a01, 2); util::write_memory((void*)0x46C547, &a01, 2); // CUser::ItemLapisianAdd util::write_memory((void*)0x46D3D8, &a01, 2); util::write_memory((void*)0x46D413, &a01, 2); // CUser::ItemRemake util::write_memory((void*)0x46DB52, &a01, 2); util::write_memory((void*)0x46DB99, &a01, 2); // CUser::ItemGemAdd util::write_memory((void*)0x46EDE7, &a01, 2); util::write_memory((void*)0x46EE22, &a01, 2); // CUser::ItemGemRemoveAll util::write_memory((void*)0x470A32, &a01, 2); util::write_memory((void*)0x470A78, &a01, 2); // CUser::ItemGemRemovePos util::write_memory((void*)0x4718B1, &a01, 2); util::write_memory((void*)0x4718F1, &a01, 2); // CUser::ItemRepair util::write_memory((void*)0x471DC5, &a01, 2); util::write_memory((void*)0x472092, &a01, 2); // CUser::ItemUse util::write_memory((void*)0x473912, &a01, 2); // CUser::SendDBAgentCharGetInfo util::write_memory((void*)0x47AE7B, &a01, 2); // user->itemQualityLv[5] (0x19E to 0x62A5) std::array<uint8_t, 2> a02{ 0xA5, 0x62 }; util::write_memory((void*)0x4621F0, &a02, 2); util::write_memory((void*)0x462205, &a02, 2); util::write_memory((void*)0x4732C0, &a02, 2); util::write_memory((void*)0x4732ED, &a02, 2); }
412
0.940552
1
0.940552
game-dev
MEDIA
0.656027
game-dev
0.68774
1
0.68774
alliedmodders/hl2sdk
28,940
game/server/phys_controller.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "entitylist.h" #include "physics.h" #include "vphysics/constraints.h" #include "physics_saverestore.h" #include "phys_controller.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define SF_THRUST_STARTACTIVE 0x0001 #define SF_THRUST_FORCE 0x0002 #define SF_THRUST_TORQUE 0x0004 #define SF_THRUST_LOCAL_ORIENTATION 0x0008 #define SF_THRUST_MASS_INDEPENDENT 0x0010 #define SF_THRUST_IGNORE_POS 0x0020 class CPhysThruster; //----------------------------------------------------------------------------- // Purpose: This class only implements the IMotionEvent-specific behavior // It keeps track of the forces so they can be integrated //----------------------------------------------------------------------------- class CConstantForceController : public IMotionEvent { DECLARE_SIMPLE_DATADESC(); public: void Init( IMotionEvent::simresult_e controlType ) { m_controlType = controlType; } void SetConstantForce( const Vector &linear, const AngularImpulse &angular ); void ScaleConstantForce( float scale ); IMotionEvent::simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ); IMotionEvent::simresult_e m_controlType; Vector m_linear; AngularImpulse m_angular; Vector m_linearSave; AngularImpulse m_angularSave; }; BEGIN_SIMPLE_DATADESC( CConstantForceController ) DEFINE_FIELD( m_controlType, FIELD_INTEGER ), DEFINE_FIELD( m_linear, FIELD_VECTOR ), DEFINE_FIELD( m_angular, FIELD_VECTOR ), DEFINE_FIELD( m_linearSave, FIELD_VECTOR ), DEFINE_FIELD( m_angularSave, FIELD_VECTOR ), END_DATADESC() void CConstantForceController::SetConstantForce( const Vector &linear, const AngularImpulse &angular ) { m_linear = linear; m_angular = angular; // cache these for scaling later m_linearSave = linear; m_angularSave = angular; } void CConstantForceController::ScaleConstantForce( float scale ) { m_linear = m_linearSave * scale; m_angular = m_angularSave * scale; } IMotionEvent::simresult_e CConstantForceController::Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) { linear = m_linear; angular = m_angular; return m_controlType; } // UNDONE: Make these logical entities //----------------------------------------------------------------------------- // Purpose: This is a general entity that has a force/motion controller that // simply integrates a constant linear/angular acceleration //----------------------------------------------------------------------------- abstract_class CPhysForce : public CPointEntity { public: DECLARE_CLASS( CPhysForce, CPointEntity ); CPhysForce(); ~CPhysForce(); DECLARE_DATADESC(); virtual void OnRestore( ); void Spawn( void ); void Activate( void ); void ForceOn( void ); void ForceOff( void ); void ActivateForce( void ); // Input handlers void InputActivate( inputdata_t &inputdata ); void InputDeactivate( inputdata_t &inputdata ); void InputForceScale( inputdata_t &inputdata ); void SaveForce( void ); void ScaleForce( float scale ); // MUST IMPLEMENT THIS IN DERIVED CLASS virtual void SetupForces( IPhysicsObject *pPhys, Vector &linear, AngularImpulse &angular ) = 0; // optional virtual void OnActivate( void ) {} protected: IPhysicsMotionController *m_pController; string_t m_nameAttach; float m_force; float m_forceTime; EHANDLE m_attachedObject; bool m_wasRestored; CConstantForceController m_integrator; }; BEGIN_DATADESC( CPhysForce ) DEFINE_PHYSPTR( m_pController ), DEFINE_KEYFIELD( m_nameAttach, FIELD_STRING, "attach1" ), DEFINE_KEYFIELD( m_force, FIELD_FLOAT, "force" ), DEFINE_KEYFIELD( m_forceTime, FIELD_FLOAT, "forcetime" ), DEFINE_FIELD( m_attachedObject, FIELD_EHANDLE ), //DEFINE_FIELD( m_wasRestored, FIELD_BOOLEAN ), // NOTE: DO NOT save/load this - it's used to detect loads DEFINE_EMBEDDED( m_integrator ), DEFINE_INPUTFUNC( FIELD_VOID, "Activate", InputActivate ), DEFINE_INPUTFUNC( FIELD_VOID, "Deactivate", InputDeactivate ), DEFINE_INPUTFUNC( FIELD_FLOAT, "scale", InputForceScale ), // Function Pointers DEFINE_FUNCTION( ForceOff ), END_DATADESC() CPhysForce::CPhysForce( void ) { m_pController = NULL; m_wasRestored = false; } CPhysForce::~CPhysForce() { if ( m_pController ) { physenv->DestroyMotionController( m_pController ); } } void CPhysForce::Spawn( void ) { if ( m_spawnflags & SF_THRUST_LOCAL_ORIENTATION ) { m_integrator.Init( IMotionEvent::SIM_LOCAL_ACCELERATION ); } else { m_integrator.Init( IMotionEvent::SIM_GLOBAL_ACCELERATION ); } } void CPhysForce::OnRestore( ) { BaseClass::OnRestore(); if ( m_pController ) { m_pController->SetEventHandler( &m_integrator ); } m_wasRestored = true; } void CPhysForce::Activate( void ) { BaseClass::Activate(); if ( m_pController ) { m_pController->WakeObjects(); } if ( m_wasRestored ) return; if ( m_attachedObject == NULL ) { m_attachedObject = gEntList.FindEntityByName( NULL, m_nameAttach ); } // Let the derived class set up before we throw the switch OnActivate(); if ( m_spawnflags & SF_THRUST_STARTACTIVE ) { ForceOn(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPhysForce::InputActivate( inputdata_t &inputdata ) { ForceOn(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPhysForce::InputDeactivate( inputdata_t &inputdata ) { ForceOff(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPhysForce::InputForceScale( inputdata_t &inputdata ) { ScaleForce( inputdata.value.Float() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPhysForce::ForceOn( void ) { if ( m_pController ) return; ActivateForce(); if ( m_forceTime ) { SetNextThink( gpGlobals->curtime + m_forceTime ); SetThink( &CPhysForce::ForceOff ); } } void CPhysForce::ActivateForce( void ) { IPhysicsObject *pPhys = NULL; if ( m_attachedObject ) { pPhys = m_attachedObject->VPhysicsGetObject(); } if ( !pPhys ) return; Vector linear; AngularImpulse angular; SetupForces( pPhys, linear, angular ); m_integrator.SetConstantForce( linear, angular ); m_pController = physenv->CreateMotionController( &m_integrator ); m_pController->AttachObject( pPhys, true ); // Make sure the object is simulated pPhys->Wake(); } void CPhysForce::ForceOff( void ) { if ( !m_pController ) return; physenv->DestroyMotionController( m_pController ); m_pController = NULL; SetThink( NULL ); SetNextThink( TICK_NEVER_THINK ); IPhysicsObject *pPhys = NULL; if ( m_attachedObject ) { pPhys = m_attachedObject->VPhysicsGetObject(); if ( pPhys ) { pPhys->Wake(); } } } void CPhysForce::ScaleForce( float scale ) { if ( !m_pController ) ForceOn(); m_integrator.ScaleConstantForce( scale ); m_pController->WakeObjects(); } //----------------------------------------------------------------------------- // Purpose: A rocket-engine/thruster based on the force controller above // Calculate the force (and optional torque) that the engine would create //----------------------------------------------------------------------------- class CPhysThruster : public CPhysForce { DECLARE_CLASS( CPhysThruster, CPhysForce ); public: DECLARE_DATADESC(); virtual void OnActivate( void ); virtual void SetupForces( IPhysicsObject *pPhys, Vector &linear, AngularImpulse &angular ); private: Vector m_localOrigin; }; LINK_ENTITY_TO_CLASS( phys_thruster, CPhysThruster ); BEGIN_DATADESC( CPhysThruster ) DEFINE_FIELD( m_localOrigin, FIELD_VECTOR ), END_DATADESC() void CPhysThruster::OnActivate( void ) { if ( m_attachedObject != NULL ) { matrix3x4_t worldToAttached, thrusterToAttached; MatrixInvert( m_attachedObject->EntityToWorldTransform(), worldToAttached ); ConcatTransforms( worldToAttached, EntityToWorldTransform(), thrusterToAttached ); MatrixGetColumn( thrusterToAttached, 3, m_localOrigin ); if ( HasSpawnFlags( SF_THRUST_LOCAL_ORIENTATION ) ) { QAngle angles; MatrixAngles( thrusterToAttached, angles ); SetLocalAngles( angles ); } // maintain the local relationship with this entity // it may move before the thruster is activated if ( HasSpawnFlags( SF_THRUST_IGNORE_POS ) ) { m_localOrigin.Init(); } } } // utility function to duplicate this call in local space void CalculateVelocityOffsetLocal( IPhysicsObject *pPhys, const Vector &forceLocal, const Vector &positionLocal, Vector &outVelLocal, AngularImpulse &outAngular ) { Vector posWorld, forceWorld; pPhys->LocalToWorld( &posWorld, positionLocal ); pPhys->LocalToWorldVector( &forceWorld, forceLocal ); Vector velWorld; pPhys->CalculateVelocityOffset( forceWorld, posWorld, &velWorld, &outAngular ); pPhys->WorldToLocalVector( &outVelLocal, velWorld ); } void CPhysThruster::SetupForces( IPhysicsObject *pPhys, Vector &linear, AngularImpulse &angular ) { Vector thrustVector; AngleVectors( GetLocalAngles(), &thrustVector ); thrustVector *= m_force; // multiply the force by mass (it's actually just an acceleration) if ( m_spawnflags & SF_THRUST_MASS_INDEPENDENT ) { thrustVector *= pPhys->GetMass(); } if ( m_spawnflags & SF_THRUST_LOCAL_ORIENTATION ) { CalculateVelocityOffsetLocal( pPhys, thrustVector, m_localOrigin, linear, angular ); } else { Vector position; VectorTransform( m_localOrigin, m_attachedObject->EntityToWorldTransform(), position ); pPhys->CalculateVelocityOffset( thrustVector, position, &linear, &angular ); } if ( !(m_spawnflags & SF_THRUST_FORCE) ) { // clear out force linear.Init(); } if ( !(m_spawnflags & SF_THRUST_TORQUE) ) { // clear out torque angular.Init(); } } //----------------------------------------------------------------------------- // Purpose: A controllable motor - exerts torque //----------------------------------------------------------------------------- class CPhysTorque : public CPhysForce { DECLARE_CLASS( CPhysTorque, CPhysForce ); public: DECLARE_DATADESC(); void Spawn( void ); virtual void SetupForces( IPhysicsObject *pPhys, Vector &linear, AngularImpulse &angular ); private: Vector m_axis; }; BEGIN_DATADESC( CPhysTorque ) DEFINE_KEYFIELD( m_axis, FIELD_VECTOR, "axis" ), END_DATADESC() LINK_ENTITY_TO_CLASS( phys_torque, CPhysTorque ); void CPhysTorque::Spawn( void ) { // force spawnflags to agree with implementation of this class m_spawnflags |= SF_THRUST_TORQUE | SF_THRUST_MASS_INDEPENDENT; m_spawnflags &= ~SF_THRUST_FORCE; m_axis -= GetAbsOrigin(); VectorNormalize(m_axis); UTIL_SnapDirectionToAxis( m_axis ); BaseClass::Spawn(); } void CPhysTorque::SetupForces( IPhysicsObject *pPhys, Vector &linear, AngularImpulse &angular ) { // clear out force linear.Init(); matrix3x4_t matrix; pPhys->GetPositionMatrix( &matrix ); // transform motor axis to local space Vector axis_ls; VectorIRotate( m_axis, matrix, axis_ls ); // Set torque to be around selected axis angular = axis_ls * m_force; } //----------------------------------------------------------------------------- // Purpose: This class only implements the IMotionEvent-specific behavior // It keeps track of the forces so they can be integrated //----------------------------------------------------------------------------- class CMotorController : public IMotionEvent { DECLARE_SIMPLE_DATADESC(); public: IMotionEvent::simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ); float m_speed; float m_maxTorque; Vector m_axis; float m_inertiaFactor; float m_lastSpeed; float m_lastAcceleration; float m_lastForce; float m_restistanceDamping; }; BEGIN_SIMPLE_DATADESC( CMotorController ) DEFINE_FIELD( m_speed, FIELD_FLOAT ), DEFINE_FIELD( m_maxTorque, FIELD_FLOAT ), DEFINE_KEYFIELD( m_axis, FIELD_VECTOR, "axis" ), DEFINE_KEYFIELD( m_inertiaFactor, FIELD_FLOAT, "inertiafactor" ), DEFINE_FIELD( m_lastSpeed, FIELD_FLOAT ), DEFINE_FIELD( m_lastAcceleration, FIELD_FLOAT ), DEFINE_FIELD( m_lastForce, FIELD_FLOAT ), DEFINE_FIELD( m_restistanceDamping, FIELD_FLOAT ), END_DATADESC() IMotionEvent::simresult_e CMotorController::Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) { linear = vec3_origin; angular = vec3_origin; if ( m_speed == 0 ) return SIM_NOTHING; matrix3x4_t matrix; pObject->GetPositionMatrix( &matrix ); AngularImpulse currentRotAxis; // currentRotAxis is in local space pObject->GetVelocity( NULL, &currentRotAxis ); // transform motor axis to local space Vector motorAxis_ls; VectorIRotate( m_axis, matrix, motorAxis_ls ); float currentSpeed = DotProduct( currentRotAxis, motorAxis_ls ); float inertia = DotProductAbs( pObject->GetInertia(), motorAxis_ls ); // compute absolute acceleration, don't integrate over the timestep float accel = m_speed - currentSpeed; float rotForce = accel * inertia * m_inertiaFactor; // BUGBUG: This heuristic is a little flaky // UNDONE: Make a better heuristic for speed control if ( fabsf(m_lastAcceleration) > 0 ) { float deltaSpeed = currentSpeed - m_lastSpeed; // make sure they are going the same way if ( deltaSpeed * accel > 0 ) { float factor = deltaSpeed / m_lastAcceleration; factor = 1 - clamp( factor, 0.f, 1.f ); rotForce += m_lastForce * factor * m_restistanceDamping; } else { if ( currentSpeed != 0 ) { // have we reached a steady state that isn't our target? float increase = deltaSpeed / m_lastAcceleration; if ( fabsf(increase) < 0.05 ) { rotForce += m_lastForce * m_restistanceDamping; } } } } // ------------------------------------------------------- if ( m_maxTorque != 0 ) { if ( rotForce > m_maxTorque ) { rotForce = m_maxTorque; } else if ( rotForce < -m_maxTorque ) { rotForce = -m_maxTorque; } } m_lastForce = rotForce; m_lastAcceleration = (rotForce / inertia); m_lastSpeed = currentSpeed; // this is in local space angular = motorAxis_ls * rotForce; return SIM_LOCAL_FORCE; } #define SF_MOTOR_START_ON 0x0001 // starts on by default #define SF_MOTOR_NOCOLLIDE 0x0002 // don't collide with world geometry #define SF_MOTOR_HINGE 0x0004 // motor also acts as a hinge constraining the object to this axis // NOTE: THIS DOESN'T WORK YET #define SF_MOTOR_LOCAL 0x0008 // Maintain local relationship with the attached object class CPhysMotor : public CLogicalEntity { DECLARE_CLASS( CPhysMotor, CLogicalEntity ); public: ~CPhysMotor(); DECLARE_DATADESC(); void Spawn( void ); void Activate( void ); void Think( void ); void TurnOn( void ); void TargetSpeedChanged( void ); void OnRestore(); void InputSetTargetSpeed( inputdata_t &inputdata ); void InputTurnOn( inputdata_t &inputdata ); void InputTurnOff( inputdata_t &inputdata ); void CalculateAcceleration(); string_t m_nameAttach; EHANDLE m_attachedObject; float m_spinUp; float m_additionalAcceleration; float m_angularAcceleration; float m_lastTime; // FIXME: can we remove m_flSpeed from CBaseEntity? //float m_flSpeed; IPhysicsConstraint *m_pHinge; IPhysicsMotionController *m_pController; CMotorController m_motor; }; BEGIN_DATADESC( CPhysMotor ) DEFINE_KEYFIELD( m_nameAttach, FIELD_STRING, "attach1" ), DEFINE_FIELD( m_attachedObject, FIELD_EHANDLE ), DEFINE_KEYFIELD( m_spinUp, FIELD_FLOAT, "spinup" ), DEFINE_KEYFIELD( m_additionalAcceleration, FIELD_FLOAT, "addangaccel" ), DEFINE_FIELD( m_angularAcceleration, FIELD_FLOAT ), DEFINE_FIELD( m_lastTime, FIELD_TIME ), DEFINE_PHYSPTR( m_pHinge ), DEFINE_PHYSPTR( m_pController ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetSpeed", InputSetTargetSpeed ), DEFINE_INPUTFUNC( FIELD_VOID, "TurnOn", InputTurnOn ), DEFINE_INPUTFUNC( FIELD_VOID, "TurnOff", InputTurnOff ), DEFINE_EMBEDDED( m_motor ), END_DATADESC() LINK_ENTITY_TO_CLASS( phys_motor, CPhysMotor ); void CPhysMotor::CalculateAcceleration() { if ( m_spinUp ) { m_angularAcceleration = fabsf(m_flSpeed / m_spinUp); } else { m_angularAcceleration = fabsf(m_flSpeed); } } //----------------------------------------------------------------------------- // Purpose: Input handler that sets a speed to spin up or down to. //----------------------------------------------------------------------------- void CPhysMotor::InputSetTargetSpeed( inputdata_t &inputdata ) { if ( m_flSpeed == inputdata.value.Float() ) return; m_flSpeed = inputdata.value.Float(); TargetSpeedChanged(); CalculateAcceleration(); } void CPhysMotor::TargetSpeedChanged( void ) { SetNextThink( gpGlobals->curtime ); m_lastTime = gpGlobals->curtime; m_pController->WakeObjects(); } //------------------------------------------------------------------------------ // Purpose: Input handler that turns the motor on. //------------------------------------------------------------------------------ void CPhysMotor::InputTurnOn( inputdata_t &inputdata ) { TurnOn(); } //------------------------------------------------------------------------------ // Purpose: Input handler that turns the motor off. //------------------------------------------------------------------------------ void CPhysMotor::InputTurnOff( inputdata_t &inputdata ) { m_motor.m_speed = 0; SetNextThink( TICK_NEVER_THINK ); } CPhysMotor::~CPhysMotor() { if ( m_attachedObject && m_pHinge ) { IPhysicsObject *pPhys = m_attachedObject->VPhysicsGetObject(); if ( pPhys ) { PhysClearGameFlags(pPhys, FVPHYSICS_NO_PLAYER_PICKUP); } } physenv->DestroyConstraint( m_pHinge ); physenv->DestroyMotionController( m_pController ); } void CPhysMotor::Spawn( void ) { m_motor.m_axis -= GetLocalOrigin(); float axisLength = VectorNormalize(m_motor.m_axis); // double check that the axis is at least a unit long. If not, warn and self-destruct. if ( axisLength > 1.0f ) { UTIL_SnapDirectionToAxis( m_motor.m_axis ); } else { Warning("phys_motor %s does not have a valid axis helper, and self-destructed!\n", GetDebugName()); m_motor.m_speed = 0; SetNextThink( TICK_NEVER_THINK ); UTIL_Remove(this); } } void CPhysMotor::TurnOn( void ) { CBaseEntity *pAttached = m_attachedObject; if ( !pAttached ) return; IPhysicsObject *pPhys = pAttached->VPhysicsGetObject(); if ( pPhys ) { m_pController->WakeObjects(); // If the current speed is zero, the objects can run a tick without getting torque'd and go back to sleep // so force a think now and have some acceleration happen before the controller gets called. m_lastTime = gpGlobals->curtime - TICK_INTERVAL; Think(); } } void CPhysMotor::Activate( void ) { BaseClass::Activate(); // This gets called after all objects spawn and after all objects restore if ( m_attachedObject == NULL ) { CBaseEntity *pAttach = gEntList.FindEntityByName( NULL, m_nameAttach ); if ( pAttach && pAttach->GetMoveType() == MOVETYPE_VPHYSICS ) { m_attachedObject = pAttach; IPhysicsObject *pPhys = m_attachedObject->VPhysicsGetObject(); CalculateAcceleration(); matrix3x4_t matrix; pPhys->GetPositionMatrix( &matrix ); Vector motorAxis_ls; VectorIRotate( m_motor.m_axis, matrix, motorAxis_ls ); float inertia = DotProductAbs( pPhys->GetInertia(), motorAxis_ls ); m_motor.m_maxTorque = inertia * m_motor.m_inertiaFactor * (m_angularAcceleration + m_additionalAcceleration); m_motor.m_restistanceDamping = 1.0f; } } if ( m_attachedObject ) { IPhysicsObject *pPhys = m_attachedObject->VPhysicsGetObject(); // create a hinge constraint for this object? if ( m_spawnflags & SF_MOTOR_HINGE ) { // UNDONE: Don't do this on restore? if ( !m_pHinge ) { constraint_hingeparams_t hingeParams; hingeParams.Defaults(); hingeParams.worldAxisDirection = m_motor.m_axis; hingeParams.worldPosition = GetLocalOrigin(); m_pHinge = physenv->CreateHingeConstraint( g_PhysWorldObject, pPhys, NULL, hingeParams ); m_pHinge->SetGameData( (void *)this ); // can't grab this object PhysSetGameFlags(pPhys, FVPHYSICS_NO_PLAYER_PICKUP); } if ( m_spawnflags & SF_MOTOR_NOCOLLIDE ) { PhysDisableEntityCollisions( g_PhysWorldObject, pPhys ); } } else { m_pHinge = NULL; } // NOTE: On restore, this path isn't run because m_pController will not be NULL if ( !m_pController ) { m_pController = physenv->CreateMotionController( &m_motor ); m_pController->AttachObject( m_attachedObject->VPhysicsGetObject(), false ); if ( m_spawnflags & SF_MOTOR_START_ON ) { TurnOn(); } } } } void CPhysMotor::OnRestore() { BaseClass::OnRestore(); // Need to do this on restore since there's no good way to save this if ( m_pController ) { m_pController->SetEventHandler( &m_motor ); } } void CPhysMotor::Think( void ) { // angular acceleration is always positive - it should be treated as a magnitude - the controller // will apply it in the proper direction Assert(m_angularAcceleration>=0); m_motor.m_speed = UTIL_Approach( m_flSpeed, m_motor.m_speed, m_angularAcceleration*(gpGlobals->curtime-m_lastTime) ); m_lastTime = gpGlobals->curtime; if ( m_motor.m_speed != m_flSpeed ) { SetNextThink( gpGlobals->curtime ); } } //====================================================================================== // KEEPUPRIGHT CONTROLLER //====================================================================================== class CKeepUpright : public CPointEntity, public IMotionEvent { DECLARE_CLASS( CKeepUpright, CPointEntity ); public: DECLARE_DATADESC(); CKeepUpright(); ~CKeepUpright(); void Spawn(); void Activate(); // IMotionEvent virtual simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ); // Inputs void InputTurnOn( inputdata_t &inputdata ) { m_bActive = true; } void InputTurnOff( inputdata_t &inputdata ) { m_bActive = false; } void InputSetAngularLimit( inputdata_t &inputdata ) { m_angularLimit = inputdata.value.Float(); } private: friend CBaseEntity *CreateKeepUpright( const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, float flAngularLimit, bool bActive ); Vector m_worldGoalAxis; Vector m_localTestAxis; IPhysicsMotionController *m_pController; string_t m_nameAttach; EHANDLE m_attachedObject; float m_angularLimit; bool m_bActive; bool m_bDampAllRotation; }; #define SF_KEEPUPRIGHT_START_INACTIVE 0x0001 LINK_ENTITY_TO_CLASS( phys_keepupright, CKeepUpright ); BEGIN_DATADESC( CKeepUpright ) DEFINE_FIELD( m_worldGoalAxis, FIELD_VECTOR ), DEFINE_FIELD( m_localTestAxis, FIELD_VECTOR ), DEFINE_PHYSPTR( m_pController ), DEFINE_KEYFIELD( m_nameAttach, FIELD_STRING, "attach1" ), DEFINE_FIELD( m_attachedObject, FIELD_EHANDLE ), DEFINE_KEYFIELD( m_angularLimit, FIELD_FLOAT, "angularlimit" ), DEFINE_FIELD( m_bActive, FIELD_BOOLEAN ), DEFINE_FIELD( m_bDampAllRotation, FIELD_BOOLEAN ), DEFINE_INPUTFUNC( FIELD_VOID, "TurnOn", InputTurnOn ), DEFINE_INPUTFUNC( FIELD_VOID, "TurnOff", InputTurnOff ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetAngularLimit", InputSetAngularLimit ), END_DATADESC() CKeepUpright::CKeepUpright() { // by default, recover from up to 15 degrees / sec angular velocity m_angularLimit = 15; m_attachedObject = NULL; m_bDampAllRotation = false; } CKeepUpright::~CKeepUpright() { if ( m_pController ) { physenv->DestroyMotionController( m_pController ); m_pController = NULL; } } void CKeepUpright::Spawn() { // align the object's local Z axis m_localTestAxis.Init( 0, 0, 1 ); // Use our Up axis so mapmakers can orient us arbitrarily GetVectors( NULL, NULL, &m_worldGoalAxis ); SetMoveType( MOVETYPE_NONE ); if ( m_spawnflags & SF_KEEPUPRIGHT_START_INACTIVE ) { m_bActive = false; } else { m_bActive = true; } } void CKeepUpright::Activate() { BaseClass::Activate(); if ( !m_pController ) { // This case occurs when spawning IPhysicsObject *pPhys; if ( m_attachedObject ) { pPhys = m_attachedObject->VPhysicsGetObject(); } else { pPhys = FindPhysicsObjectByName( STRING(m_nameAttach), this ); } if ( !pPhys ) { UTIL_Remove(this); return; } // HACKHACK: Due to changes in the vehicle simulator the keepupright controller used in coast_01 is unstable // force it to have perfect damping to compensate. // detect it using the hack of angular limit == 150, attached to a vehicle // Fixing it in the code is the simplest course of action presently #ifdef HL2_DLL if ( m_angularLimit == 150.0f ) { CBaseEntity *pEntity = static_cast<CBaseEntity *>(pPhys->GetGameData()); if ( pEntity && pEntity->GetServerVehicle() && Q_stristr( gpGlobals->mapname.ToCStr(), "d2_coast_01" ) ) { m_bDampAllRotation = true; } } #endif m_pController = physenv->CreateMotionController( (IMotionEvent *)this ); m_pController->AttachObject( pPhys, false ); } else { // This case occurs when restoring m_pController->SetEventHandler( this ); } } //----------------------------------------------------------------------------- // Purpose: Use this to spawn a keepupright controller via code instead of map-placed //----------------------------------------------------------------------------- CBaseEntity *CreateKeepUpright( const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, float flAngularLimit, bool bActive ) { CKeepUpright *pKeepUpright = (CKeepUpright*)CBaseEntity::Create( "phys_keepupright", vecOrigin, vecAngles, pOwner ); if ( pKeepUpright ) { pKeepUpright->m_attachedObject = pOwner; pKeepUpright->m_angularLimit = flAngularLimit; if ( !bActive ) { pKeepUpright->AddSpawnFlags( SF_KEEPUPRIGHT_START_INACTIVE ); } pKeepUpright->Spawn(); pKeepUpright->Activate(); } return pKeepUpright; } IMotionEvent::simresult_e CKeepUpright::Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) { if ( !m_bActive ) return SIM_NOTHING; linear.Init(); AngularImpulse angVel; pObject->GetVelocity( NULL, &angVel ); matrix3x4_t matrix; // get the object's local to world transform pObject->GetPositionMatrix( &matrix ); // Get the alignment axis in object space Vector currentLocalTargetAxis; VectorIRotate( m_worldGoalAxis, matrix, currentLocalTargetAxis ); float invDeltaTime = (1/deltaTime); if ( m_bDampAllRotation ) { angular = ComputeRotSpeedToAlignAxes( m_localTestAxis, currentLocalTargetAxis, angVel, 0, invDeltaTime, m_angularLimit ); angular -= angVel; angular *= invDeltaTime; return SIM_LOCAL_ACCELERATION; } angular = ComputeRotSpeedToAlignAxes( m_localTestAxis, currentLocalTargetAxis, angVel, 1.0, invDeltaTime, m_angularLimit ); angular *= invDeltaTime; #if 0 Vector position, out, worldAxis; MatrixGetColumn( matrix, 3, position ); out = angular * 0.1; VectorRotate( m_localTestAxis, matrix, worldAxis ); NDebugOverlay::Line( position, position + worldAxis * 100, 255, 0, 0, 0, 0 ); NDebugOverlay::Line( position, position + m_worldGoalAxis * 100, 255, 0, 0, 0, 0 ); NDebugOverlay::Line( position, position + out, 255, 255, 0, 0, 0 ); #endif return SIM_LOCAL_ACCELERATION; } // computes the torque necessary to align testAxis with alignAxis AngularImpulse ComputeRotSpeedToAlignAxes( const Vector &testAxis, const Vector &alignAxis, const AngularImpulse &currentSpeed, float damping, float scale, float maxSpeed ) { Vector rotationAxis = CrossProduct( testAxis, alignAxis ); // atan2() is well defined, so do a Dot & Cross instead of asin(Cross) float cosine = DotProduct( testAxis, alignAxis ); float sine = VectorNormalize( rotationAxis ); float angle = atan2( sine, cosine ); angle = RAD2DEG(angle); AngularImpulse angular = rotationAxis * scale * angle; angular -= rotationAxis * damping * DotProduct( currentSpeed, rotationAxis ); float len = VectorNormalize( angular ); if ( len > maxSpeed ) { len = maxSpeed; } return angular * len; }
412
0.947238
1
0.947238
game-dev
MEDIA
0.989102
game-dev
0.742026
1
0.742026
DRE2N/DungeonsXL
3,387
core/src/main/java/de/erethon/dungeonsxl/mob/DMobListener.java
/* * Copyright (C) 2012-2023 Frank Baumann * * 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 de.erethon.dungeonsxl.mob; import de.erethon.caliburn.mob.VanillaMob; import de.erethon.dungeonsxl.DungeonsXL; import de.erethon.dungeonsxl.api.world.GameWorld; import de.erethon.dungeonsxl.api.world.InstanceWorld; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.PiglinAbstract; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityCombustByEntityEvent; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDeathEvent; /** * @author Daniel Saukel, Frank Baumann */ public class DMobListener implements Listener { private DungeonsXL plugin; public DMobListener(DungeonsXL plugin) { this.plugin = plugin; } @EventHandler public void onCreatureSpawn(CreatureSpawnEvent event) { World world = event.getLocation().getWorld(); InstanceWorld instance = plugin.getInstanceWorld(world); if (instance == null) { return; } switch (event.getSpawnReason()) { case CHUNK_GEN: case JOCKEY: case MOUNT: case NATURAL: event.setCancelled(true); return; } VanillaMob vm = VanillaMob.get(event.getEntityType()); if (vm == VanillaMob.PIGLIN || vm == VanillaMob.PIGLIN_BRUTE) { ((PiglinAbstract) event.getEntity()).setImmuneToZombification(true); } } @EventHandler public void onEntityDeath(EntityDeathEvent event) { World world = event.getEntity().getWorld(); if (event.getEntity() instanceof LivingEntity) { LivingEntity entity = event.getEntity(); GameWorld gameWorld = plugin.getGameWorld(world); if (gameWorld != null) { if (gameWorld.isPlaying()) { DMob dMob = (DMob) plugin.getDungeonMob(entity); if (dMob != null) { dMob.onDeath(plugin, event); } } } } } // Prevent undead combustion from the sun. @EventHandler public void onEntityCombust(EntityCombustEvent event) { if (event instanceof EntityCombustByEntityEvent) { return; } Entity entity = event.getEntity(); if ((entity instanceof Skeleton || entity instanceof Zombie) && plugin.getGameWorld(entity.getWorld()) != null) { event.setCancelled(true); } } }
412
0.859518
1
0.859518
game-dev
MEDIA
0.961066
game-dev
0.803818
1
0.803818
mbbill/JSC.js
2,706
Source/JavaScriptCore/dfg/DFGBlockMap.h
/* * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #if ENABLE(DFG_JIT) #include "DFGBasicBlock.h" namespace JSC { namespace DFG { class Graph; template<typename T> class BlockMap { WTF_MAKE_FAST_ALLOCATED; public: BlockMap() { } BlockMap(Graph&); BlockIndex size() const { return m_vector.size(); } T& atIndex(BlockIndex blockIndex) { return m_vector[blockIndex]; } const T& atIndex(BlockIndex blockIndex) const { return m_vector[blockIndex]; } T& at(BlockIndex blockIndex) { return m_vector[blockIndex]; } const T& at(BlockIndex blockIndex) const { return m_vector[blockIndex]; } T& at(BasicBlock* block) { return m_vector[block->index]; } const T& at(BasicBlock* block) const { return m_vector[block->index]; } T& operator[](BlockIndex blockIndex) { return m_vector[blockIndex]; } const T& operator[](BlockIndex blockIndex) const { return m_vector[blockIndex]; } T& operator[](BasicBlock* block) { return m_vector[block->index]; } const T& operator[](BasicBlock* block) const { return m_vector[block->index]; } private: Vector<T> m_vector; }; } } // namespace JSC::DFG #endif // ENABLE(DFG_JIT)
412
0.901988
1
0.901988
game-dev
MEDIA
0.398916
game-dev
0.72733
1
0.72733
DiplomacyTeam/Bannerlord.Diplomacy
6,395
src/Bannerlord.Diplomacy/CampaignBehaviors/AllianceBehavior.cs
using Diplomacy.DiplomaticAction.Alliance; using Diplomacy.DiplomaticAction.WarPeace; using Diplomacy.Events; using Diplomacy.Extensions; using System.Linq; using TaleWorlds.CampaignSystem; using TaleWorlds.CampaignSystem.Actions; using TaleWorlds.Core; using TaleWorlds.Library; using TaleWorlds.Localization; namespace Diplomacy.CampaignBehaviors { internal sealed class AllianceBehavior : CampaignBehaviorBase { public override void RegisterEvents() { CampaignEvents.DailyTickClanEvent.AddNonSerializedListener(this, DailyTickClan); #if v100 || v101 || v102 || v103 DiplomacyEvents.WarDeclared.AddNonSerializedListener(this, WarDeclared); #else CampaignEvents.WarDeclared.AddNonSerializedListener(this, WarDeclared); #endif DiplomacyEvents.AllianceFormed.AddNonSerializedListener(this, AllianceFormed); } public override void SyncData(IDataStore dataStore) { } private void AllianceFormed(AllianceEvent allianceFormedEvent) { var txt = new TextObject("{=PdN5g5ub}{KINGDOM} has formed an alliance with {OTHER_KINGDOM}!"); txt.SetTextVariable("KINGDOM", allianceFormedEvent.Kingdom.Name); txt.SetTextVariable("OTHER_KINGDOM", allianceFormedEvent.OtherKingdom.Name); var txtRendered = txt.ToString(); if (allianceFormedEvent.Kingdom == Clan.PlayerClan.Kingdom || allianceFormedEvent.OtherKingdom == Clan.PlayerClan.Kingdom) { InformationManager.ShowInquiry( new InquiryData(new TextObject("{=qIa19an4}Alliance Formed").ToString(), txtRendered, true, false, GameTexts.FindText("str_ok").ToString(), null, null, null)); } else InformationManager.DisplayMessage(new InformationMessage(txtRendered, SubModule.StdTextColor)); } #if v100 || v101 || v102 || v103 private void WarDeclared(WarDeclaredEvent warDeclaredEvent) { if (!warDeclaredEvent.IsProvoked && warDeclaredEvent.Faction is Kingdom attacker && warDeclaredEvent.ProvocatorFaction is Kingdom defender) { SupportAlliedKingdom(defender, attacker); } } #else private void WarDeclared(IFaction faction1, IFaction faction2, DeclareWarAction.DeclareWarDetail declareWarDetail) { if (declareWarDetail != DeclareWarAction.DeclareWarDetail.CausedByPlayerHostility && faction1 is Kingdom attacker && faction2 is Kingdom defender) { SupportAlliedKingdom(defender, attacker); } } #endif private void SupportAlliedKingdom(Kingdom kingdom, Kingdom kingdomToDeclareWarOn) { var allies = KingdomExtensions.AllActiveKingdoms.Where(k => kingdom != k && FactionManager.IsAlliedWithFaction(kingdom, k)); foreach (var ally in allies) { if (!DeclareWarConditions.Instance.CanApply(ally, kingdomToDeclareWarOn, bypassCosts: true)) continue; #if v100 || v101 || v102 || v103 DeclareWarAction.ApplyDeclareWarOverProvocation(ally, kingdomToDeclareWarOn); #else DeclareWarAction.ApplyByKingdomDecision(ally, kingdomToDeclareWarOn); #endif var txt = new TextObject("{=UDC8eW7s}{ALLIED_KINGDOM} is joining their ally, {KINGDOM}, in the war against {ENEMY_KINGDOM}."); txt.SetTextVariable("ALLIED_KINGDOM", ally.Name); txt.SetTextVariable("KINGDOM", kingdom.Name); txt.SetTextVariable("ENEMY_KINGDOM", kingdomToDeclareWarOn.Name); InformationManager.DisplayMessage(new InformationMessage(txt.ToString(), SubModule.StdTextColor)); } } private void DailyTickClan(Clan clan) { if (!Settings.Instance!.EnableAlliances) { BreakAllAlliances(clan); return; } if (clan.Leader == clan.Kingdom?.Leader && clan.Leader != Hero.MainHero && clan.MapFaction.IsKingdomFaction) { var kingdom = clan.Kingdom; ConsiderBreakingAlliances(kingdom); ConsiderFormingAlliances(kingdom); } } private static void ConsiderFormingAlliances(Kingdom kingdom) { var potentialAllies = KingdomExtensions.AllActiveKingdoms .Where(k => k != kingdom && FormAllianceConditions.Instance.CanApply(kingdom, k)) .ToList(); foreach (var potentialAlly in potentialAllies) if (MBRandom.RandomFloat < 0.05f && AllianceScoringModel.Instance.ShouldFormBidirectional(kingdom, potentialAlly)) DeclareAllianceAction.Apply(kingdom, potentialAlly); } private static void ConsiderBreakingAlliances(Kingdom kingdom) { var alliedKingdoms = KingdomExtensions.AllActiveKingdoms .Where(k => k != kingdom && FactionManager.IsAlliedWithFaction(kingdom, k)) .ToList(); foreach (var alliedKingdom in alliedKingdoms) { if (MBRandom.RandomFloat < 0.05f && BreakAllianceConditions.Instance.CanApply(kingdom, alliedKingdom) && !AllianceScoringModel.Instance.ShouldForm(kingdom, alliedKingdom)) { BreakAllianceAction.Apply(kingdom, alliedKingdom); } } } private static void BreakAllAlliances(Clan clan) { var kingdom = clan.Kingdom; if (kingdom is null) return; var alliedKingdoms = KingdomExtensions.AllActiveKingdoms .Where(k => k != kingdom && FactionManager.IsAlliedWithFaction(kingdom, k)) .ToList(); foreach (var alliedKingdom in alliedKingdoms) BreakAllianceAction.Apply(kingdom, alliedKingdom); } } }
412
0.789473
1
0.789473
game-dev
MEDIA
0.827752
game-dev
0.749357
1
0.749357
gucheng0712/CombatDesigner
3,626
CombatDesigner/Library/PackageCache/com.unity.textmeshpro@3.0.1/Scripts/Editor/TMPro_TexturePostProcessor.cs
using System; using UnityEngine; using UnityEditor; using System.Collections; namespace TMPro.EditorUtilities { public class TMPro_TexturePostProcessor : AssetPostprocessor { void OnPostprocessTexture(Texture2D texture) { Texture2D tex = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D; // Send Event Sub Objects if (tex != null) TMPro_EventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, tex); } } /// <summary> /// Asset post processor used to handle font assets getting updated outside of the Unity editor. /// </summary> class FontAssetPostProcessor : AssetPostprocessor { private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (var asset in importedAssets) { if (AssetDatabase.GetMainAssetTypeAtPath(asset) == typeof(TMP_FontAsset)) { TMP_FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(asset, typeof(TMP_FontAsset)) as TMP_FontAsset; if (fontAsset != null) TMP_EditorResourceManager.RegisterFontAssetForDefinitionRefresh(fontAsset); } } } } //public class TMPro_PackageImportPostProcessor : AssetPostprocessor //{ // static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) // { // for (int i = 0; i < importedAssets.Length; i++) // { // if (importedAssets[i].Contains("TextMesh Pro/Resources/TMP Settings.asset")) // { // Debug.Log("New TMP Settings file was just imported."); // // TMP Settings file was just re-imported. // // Check if project already contains // } // if (importedAssets[i].Contains("com.unity.TextMeshPro/Examples")) // { // //Debug.Log("New TMP Examples folder was just imported."); // } // //Debug.Log("[" + importedAssets[i] + "] was just imported."); // } // //for (int i = 0; i < deletedAssets.Length; i++) // //{ // // if (deletedAssets[i] == "Assets/TextMesh Pro") // // { // // //Debug.Log("Asset [" + deletedAssets[i] + "] has been deleted."); // // string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); // // //Check for and inject TMP_PRESENT // // if (currentBuildSettings.Contains("TMP_PRESENT;")) // // { // // currentBuildSettings = currentBuildSettings.Replace("TMP_PRESENT;", ""); // // PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings); // // } // // else if (currentBuildSettings.Contains("TMP_PRESENT")) // // { // // currentBuildSettings = currentBuildSettings.Replace("TMP_PRESENT", ""); // // PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings); // // } // // } // //} // } //} }
412
0.939575
1
0.939575
game-dev
MEDIA
0.90291
game-dev
0.954358
1
0.954358
folgerwang/UnrealEngine
1,065
Engine/Source/Editor/UnrealEd/Classes/Commandlets/GatherTextFromMetadataCommandlet.h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "Commandlets/GatherTextCommandletBase.h" #include "GatherTextFromMetadataCommandlet.generated.h" /** * UGatherTextFromMetaDataCommandlet: Localization commandlet that collects all text to be localized from generated metadata. */ UCLASS() class UGatherTextFromMetaDataCommandlet : public UGatherTextCommandletBase { GENERATED_UCLASS_BODY() public: //~ Begin UCommandlet Interface virtual int32 Main(const FString& Params) override; //~ End UCommandlet Interface private: struct FGatherParameters { TArray<FString> InputKeys; TArray<FString> OutputNamespaces; TArray<FText> OutputKeys; }; private: void GatherTextFromUObjects(const TArray<FString>& IncludePaths, const TArray<FString>& ExcludePaths, const FGatherParameters& Arguments); void GatherTextFromUObject(UField* const Field, const FGatherParameters& Arguments, const FName InPlatformName); private: bool ShouldGatherFromEditorOnlyData; };
412
0.571784
1
0.571784
game-dev
MEDIA
0.751284
game-dev
0.533839
1
0.533839
china20/MPFUI
4,655
trunk/suicore/src/System/Windows/InheritStateProperty.cpp
// ====================================================================== // // Copyright (c) 2008-2022 (ӵUI), Inc. All rights reserved. // // MPFѭָԴЭ飬˾Э鹺Ȩ // κθˡ˾ܾڴ˿κҵʵĿ롣 // // ====================================================================== ///////////////////////////////////////////////////////////////////////// // InheritStateProperty.cpp #include <System/Input/Mouse.h> #include <System/Input/Keyboard.h> #include <System/Windows/CoreTool.h> #include <System/Windows/FrameworkElement.h> #include <System/Windows/InheritStateProperty.h> #include <System/Tools/VisualTreeOp.h> #include <System/Interop/InternalWindowOper.h> namespace suic { InheritStateProperty::InheritStateProperty(DpProperty* dp, int cacheFlag, int changedFlag) : _dp(dp) , _cacheFlag(cacheFlag) , _changedFlag(changedFlag) { } void InheritStateProperty::DoRelative(Element* oldElem, Element* newElem) { } void InheritStateProperty::OnOriginalValueChanged(Element* oldElem, Element* newElem) { // һ뿪Ԫ״̬(IsMouseOverChange) Element* pElem = oldElem; while (pElem != NULL) { // // ״̬ı // pElem->WriteFlag(_changedFlag, true); // // ȡͣ־ // pElem->WriteFlag(_cacheFlag, false); if (pElem->BlockVisualState()) { break; } pElem = pElem->GetUIParent(); } // ڶӵԪ״̬(IsMouseOverChange) pElem = newElem; while (pElem != NULL) { // // ״̬ı // pElem->WriteFlag(_changedFlag, !pElem->ReadFlag(_changedFlag)); // // ȡͣ־ // pElem->WriteFlag(_cacheFlag, true); if (pElem->BlockVisualState()) { break; } pElem = pElem->GetUIParent(); } //DoRelative(oldElem, newElem); Element* pRoot = oldElem ? VisualTreeOp::GetVisualRoot(oldElem) : VisualTreeOp::GetVisualRoot(newElem); // ״̬IsMouseOverChangeıԪ // ӦMouseEnterMouseLeave¼ pElem = oldElem; while (pElem != NULL) { if (pElem->ReadFlag(_changedFlag)) { pElem->WriteFlag(_changedFlag, false); pElem->WriteFlag(_cacheFlag, false); // ״̬ı pElem->SetValue(_dp, Boolean::False); FireState(pElem, true); } if (pElem->BlockVisualState()) { break; } pElem = pElem->GetUIParent(); } // pElem = newElem; while (pElem != NULL) { if (pElem->ReadFlag(_changedFlag)) { pElem->WriteFlag(_changedFlag, false); pElem->WriteFlag(_cacheFlag, true); if (pElem->IsEnabled()) { // ״̬ı pElem->SetValue(_dp, Boolean::True); FireState(pElem, false); } } if (pElem->BlockVisualState()) { break; } pElem = pElem->GetUIParent(); } } //=========================================================== // MouseOverProperty MouseOverProperty::MouseOverProperty() : InheritStateProperty(Element::IsMouseOverProperty , CoreFlags::IsMouseOverWithinCache , CoreFlags::IsMouseOverWithinChanged) { } void MouseOverProperty::FireState(Element* sender, bool oldValue) { Point pt = __GetCusorPoint(sender); MouseButtonEventArg e(sender, pt); if (oldValue) { e.SetRoutedEvent(sender->MouseLeaveEvent); } else { e.OnOverrideOriginalSource(MouseDevice::GetMouseOver()); e.SetRoutedEvent(sender->MouseEnterEvent); } sender->RaiseEvent(&e); } void MouseOverProperty::HandleRelativeMouse(Element* elem) { } void MouseOverProperty::DoRelative(Element* oldElem, Element* newElem) { } //=========================================================== // MouseCaptureProperty MouseCaptureProperty::MouseCaptureProperty() : InheritStateProperty(Element::IsMouseCaptureWithinProperty , CoreFlags::IsMouseCapturedWithinCache , CoreFlags::IsMouseCapturedWithinChanged) { } void MouseCaptureProperty::FireState(Element* sender, bool oldValue) { sender->OnMouseCaptureWithinChanged(!oldValue); } //=========================================================== // FocusWithinProperty FocusWithinProperty::FocusWithinProperty() : InheritStateProperty(Element::IsKeyboardFocusWithinProperty , CoreFlags::IsKeyboardFocusWithinCache , CoreFlags::IsKeyboardFocusWithinChanged) { } void FocusWithinProperty::FireState(Element* sender, bool oldValue) { if (sender->IsFocusable()) { sender->OnKeyboardFocusWithinChanged(!oldValue); } } }
412
0.955037
1
0.955037
game-dev
MEDIA
0.875671
game-dev
0.988636
1
0.988636
wheybags/freeablo
15,262
extern/SDL2/include/SDL_keycode.h
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * \file SDL_keycode.h * * Defines constants which identify keyboard keys and modifiers. */ #ifndef SDL_keycode_h_ #define SDL_keycode_h_ #include "SDL_stdinc.h" #include "SDL_scancode.h" /** * \brief The SDL virtual key representation. * * Values of this type are used to represent keyboard keys using the current * layout of the keyboard. These values include Unicode values representing * the unmodified character that would be generated by pressing the key, or * an SDLK_* constant for those keys that do not generate characters. * * A special exception is the number keys at the top of the keyboard which * always map to SDLK_0...SDLK_9, regardless of layout. */ typedef Sint32 SDL_Keycode; #define SDLK_SCANCODE_MASK (1<<30) #define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK) enum { SDLK_UNKNOWN = 0, SDLK_RETURN = '\r', SDLK_ESCAPE = '\033', SDLK_BACKSPACE = '\b', SDLK_TAB = '\t', SDLK_SPACE = ' ', SDLK_EXCLAIM = '!', SDLK_QUOTEDBL = '"', SDLK_HASH = '#', SDLK_PERCENT = '%', SDLK_DOLLAR = '$', SDLK_AMPERSAND = '&', SDLK_QUOTE = '\'', SDLK_LEFTPAREN = '(', SDLK_RIGHTPAREN = ')', SDLK_ASTERISK = '*', SDLK_PLUS = '+', SDLK_COMMA = ',', SDLK_MINUS = '-', SDLK_PERIOD = '.', SDLK_SLASH = '/', SDLK_0 = '0', SDLK_1 = '1', SDLK_2 = '2', SDLK_3 = '3', SDLK_4 = '4', SDLK_5 = '5', SDLK_6 = '6', SDLK_7 = '7', SDLK_8 = '8', SDLK_9 = '9', SDLK_COLON = ':', SDLK_SEMICOLON = ';', SDLK_LESS = '<', SDLK_EQUALS = '=', SDLK_GREATER = '>', SDLK_QUESTION = '?', SDLK_AT = '@', /* Skip uppercase letters */ SDLK_LEFTBRACKET = '[', SDLK_BACKSLASH = '\\', SDLK_RIGHTBRACKET = ']', SDLK_CARET = '^', SDLK_UNDERSCORE = '_', SDLK_BACKQUOTE = '`', SDLK_a = 'a', SDLK_b = 'b', SDLK_c = 'c', SDLK_d = 'd', SDLK_e = 'e', SDLK_f = 'f', SDLK_g = 'g', SDLK_h = 'h', SDLK_i = 'i', SDLK_j = 'j', SDLK_k = 'k', SDLK_l = 'l', SDLK_m = 'm', SDLK_n = 'n', SDLK_o = 'o', SDLK_p = 'p', SDLK_q = 'q', SDLK_r = 'r', SDLK_s = 's', SDLK_t = 't', SDLK_u = 'u', SDLK_v = 'v', SDLK_w = 'w', SDLK_x = 'x', SDLK_y = 'y', SDLK_z = 'z', SDLK_CAPSLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK), SDLK_F1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1), SDLK_F2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2), SDLK_F3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3), SDLK_F4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4), SDLK_F5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5), SDLK_F6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6), SDLK_F7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7), SDLK_F8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8), SDLK_F9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9), SDLK_F10 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10), SDLK_F11 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11), SDLK_F12 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12), SDLK_PRINTSCREEN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN), SDLK_SCROLLLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK), SDLK_PAUSE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE), SDLK_INSERT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT), SDLK_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME), SDLK_PAGEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP), SDLK_DELETE = '\177', SDLK_END = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END), SDLK_PAGEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN), SDLK_RIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT), SDLK_LEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT), SDLK_DOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN), SDLK_UP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP), SDLK_NUMLOCKCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR), SDLK_KP_DIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE), SDLK_KP_MULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY), SDLK_KP_MINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS), SDLK_KP_PLUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS), SDLK_KP_ENTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER), SDLK_KP_1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1), SDLK_KP_2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2), SDLK_KP_3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3), SDLK_KP_4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4), SDLK_KP_5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5), SDLK_KP_6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6), SDLK_KP_7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7), SDLK_KP_8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8), SDLK_KP_9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9), SDLK_KP_0 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0), SDLK_KP_PERIOD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD), SDLK_APPLICATION = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION), SDLK_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER), SDLK_KP_EQUALS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS), SDLK_F13 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13), SDLK_F14 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14), SDLK_F15 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15), SDLK_F16 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16), SDLK_F17 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17), SDLK_F18 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18), SDLK_F19 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19), SDLK_F20 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20), SDLK_F21 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21), SDLK_F22 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22), SDLK_F23 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23), SDLK_F24 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24), SDLK_EXECUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE), SDLK_HELP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP), SDLK_MENU = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU), SDLK_SELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT), SDLK_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP), SDLK_AGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN), SDLK_UNDO = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO), SDLK_CUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT), SDLK_COPY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY), SDLK_PASTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE), SDLK_FIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND), SDLK_MUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE), SDLK_VOLUMEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP), SDLK_VOLUMEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN), SDLK_KP_COMMA = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA), SDLK_KP_EQUALSAS400 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400), SDLK_ALTERASE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE), SDLK_SYSREQ = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ), SDLK_CANCEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL), SDLK_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR), SDLK_PRIOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR), SDLK_RETURN2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2), SDLK_SEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR), SDLK_OUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT), SDLK_OPER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER), SDLK_CLEARAGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN), SDLK_CRSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL), SDLK_EXSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL), SDLK_KP_00 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00), SDLK_KP_000 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000), SDLK_THOUSANDSSEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR), SDLK_DECIMALSEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR), SDLK_CURRENCYUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT), SDLK_CURRENCYSUBUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT), SDLK_KP_LEFTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN), SDLK_KP_RIGHTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN), SDLK_KP_LEFTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE), SDLK_KP_RIGHTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE), SDLK_KP_TAB = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB), SDLK_KP_BACKSPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE), SDLK_KP_A = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A), SDLK_KP_B = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B), SDLK_KP_C = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C), SDLK_KP_D = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D), SDLK_KP_E = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E), SDLK_KP_F = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F), SDLK_KP_XOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR), SDLK_KP_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER), SDLK_KP_PERCENT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT), SDLK_KP_LESS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS), SDLK_KP_GREATER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER), SDLK_KP_AMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND), SDLK_KP_DBLAMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND), SDLK_KP_VERTICALBAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR), SDLK_KP_DBLVERTICALBAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR), SDLK_KP_COLON = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON), SDLK_KP_HASH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH), SDLK_KP_SPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE), SDLK_KP_AT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT), SDLK_KP_EXCLAM = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM), SDLK_KP_MEMSTORE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE), SDLK_KP_MEMRECALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL), SDLK_KP_MEMCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR), SDLK_KP_MEMADD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD), SDLK_KP_MEMSUBTRACT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT), SDLK_KP_MEMMULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY), SDLK_KP_MEMDIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE), SDLK_KP_PLUSMINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS), SDLK_KP_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR), SDLK_KP_CLEARENTRY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY), SDLK_KP_BINARY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY), SDLK_KP_OCTAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL), SDLK_KP_DECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL), SDLK_KP_HEXADECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL), SDLK_LCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL), SDLK_LSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT), SDLK_LALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT), SDLK_LGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI), SDLK_RCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL), SDLK_RSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT), SDLK_RALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT), SDLK_RGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI), SDLK_MODE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE), SDLK_AUDIONEXT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIONEXT), SDLK_AUDIOPREV = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPREV), SDLK_AUDIOSTOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOSTOP), SDLK_AUDIOPLAY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPLAY), SDLK_AUDIOMUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOMUTE), SDLK_MEDIASELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIASELECT), SDLK_WWW = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WWW), SDLK_MAIL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MAIL), SDLK_CALCULATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALCULATOR), SDLK_COMPUTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COMPUTER), SDLK_AC_SEARCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH), SDLK_AC_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME), SDLK_AC_BACK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK), SDLK_AC_FORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD), SDLK_AC_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP), SDLK_AC_REFRESH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH), SDLK_AC_BOOKMARKS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS), SDLK_BRIGHTNESSDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSDOWN), SDLK_BRIGHTNESSUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSUP), SDLK_DISPLAYSWITCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DISPLAYSWITCH), SDLK_KBDILLUMTOGGLE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMTOGGLE), SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN), SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP), SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT), SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP), SDLK_APP1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP1), SDLK_APP2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP2), SDLK_AUDIOREWIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOREWIND), SDLK_AUDIOFASTFORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOFASTFORWARD) }; /** * \brief Enumeration of valid key mods (possibly OR'd together). */ typedef enum { KMOD_NONE = 0x0000, KMOD_LSHIFT = 0x0001, KMOD_RSHIFT = 0x0002, KMOD_LCTRL = 0x0040, KMOD_RCTRL = 0x0080, KMOD_LALT = 0x0100, KMOD_RALT = 0x0200, KMOD_LGUI = 0x0400, KMOD_RGUI = 0x0800, KMOD_NUM = 0x1000, KMOD_CAPS = 0x2000, KMOD_MODE = 0x4000, KMOD_RESERVED = 0x8000 } SDL_Keymod; #define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) #define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) #define KMOD_ALT (KMOD_LALT|KMOD_RALT) #define KMOD_GUI (KMOD_LGUI|KMOD_RGUI) #endif /* SDL_keycode_h_ */ /* vi: set ts=4 sw=4 expandtab: */
412
0.84295
1
0.84295
game-dev
MEDIA
0.748009
game-dev
0.704047
1
0.704047
devtron-labs/devtron
1,316
cel/bean.go
package cel type ParamValuesType string const ( ParamTypeString ParamValuesType = "string" ParamTypeObject ParamValuesType = "object" ParamTypeInteger ParamValuesType = "integer" ParamTypeList ParamValuesType = "list" ParamTypeBool ParamValuesType = "bool" ParamTypeMapStringToAny ParamValuesType = "mapStringToAny" ) type ParamName string const AppName ParamName = "appName" const ProjectName ParamName = "projectName" const EnvName ParamName = "envName" const CdPipelineName ParamName = "cdPipelineName" const IsProdEnv ParamName = "isProdEnv" const ClusterName ParamName = "clusterName" const ChartRefId ParamName = "chartRefId" const CdPipelineTriggerType ParamName = "cdPipelineTriggerType" const ContainerRepo ParamName = "containerRepository" const ContainerImage ParamName = "containerImage" const ContainerImageTag ParamName = "containerImageTag" const ImageLabels ParamName = "imageLabels" type Request struct { Expression string `json:"expression"` ExpressionMetadata ExpressionMetadata `json:"params"` } type ExpressionMetadata struct { Params []ExpressionParam } type ExpressionParam struct { ParamName ParamName `json:"paramName"` Value interface{} `json:"value"` Type ParamValuesType `json:"type"` }
412
0.640259
1
0.640259
game-dev
MEDIA
0.3944
game-dev
0.616341
1
0.616341
GateteVerde/Gatete-Mario-Engine-9
1,240
Gatete Mario Engine 9/objects/obj_npc/Step_0.gml
/// @description NPC logic //Inherit the parent event event_inherited(); #region INTERACT //Check for Mario var mario = collision_rectangle(bbox_left-16, bbox_top-16, bbox_right+16, bbox_bottom, obj_mario, 0, 0); if (ready == 1) && (mario) && (mario.state < playerstate.jump) && (!instance_exists(obj_mario_transform)) && ((input_check_pressed(input.up)) || (gamepad_axis_value(0, gp_axislv) < -0.5)) { //Play 'Message' sound audio_play_sound(snd_message, 0, false); //Create the message with (instance_create_layer(0, 0, "GUI", obj_message_dialog)) { varmsg = other.varmsg; mugshot = other.mugshot; char_name = other.char_name; mute_sound = other.mute_sound; } //Make it unreadable to prevent spam ready = 0; //Delay readability of the signpost after a while alarm[0] = 24; //If a timeline has been specified, trigger it. if (tline != noone) { //Set the time timeline_index = tline; //If the timeline is not running if (timeline_running == 0) { timeline_position = 0; timeline_running = 1; } } } #endregion //Set the facing direction if (!instance_exists(obj_mario)) || (obj_mario.x < x) xscale = -1; else xscale = 1;
412
0.951927
1
0.951927
game-dev
MEDIA
0.897466
game-dev
0.847714
1
0.847714
WayofTime/BloodMagic
2,954
src/main/java/wayoftime/bloodmagic/core/registry/AlchemyArrayRegistry.java
package wayoftime.bloodmagic.core.registry; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import wayoftime.bloodmagic.BloodMagic; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffect; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectBinding; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectBounce; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectCrafting; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectDay; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectMovement; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectNight; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectSpike; import wayoftime.bloodmagic.common.alchemyarray.AlchemyArrayEffectUpdraft; import wayoftime.bloodmagic.impl.BloodMagicAPI; import wayoftime.bloodmagic.recipe.RecipeAlchemyArray; public class AlchemyArrayRegistry { public static Map<ResourceLocation, AlchemyArrayEffect> effectMap = new HashMap<ResourceLocation, AlchemyArrayEffect>(); public static final ResourceLocation BINDING_ARRAY = BloodMagic.rl("textures/models/alchemyarrays/bindingarray.png"); public static boolean registerEffect(ResourceLocation rl, AlchemyArrayEffect effect) { boolean hadKey = effectMap.containsKey(rl); effectMap.put(rl, effect); return hadKey; } public static void registerBaseArrays() { registerEffect(BloodMagic.rl("array/movement"), new AlchemyArrayEffectMovement()); registerEffect(BloodMagic.rl("array/updraft"), new AlchemyArrayEffectUpdraft()); registerEffect(BloodMagic.rl("array/spike"), new AlchemyArrayEffectSpike()); registerEffect(BloodMagic.rl("array/day"), new AlchemyArrayEffectDay()); registerEffect(BloodMagic.rl("array/night"), new AlchemyArrayEffectNight()); registerEffect(BloodMagic.rl("array/bounce"), new AlchemyArrayEffectBounce()); } public static AlchemyArrayEffect getEffect(Level world, ResourceLocation rl, RecipeAlchemyArray recipe) { if (effectMap.containsKey(rl)) { return effectMap.get(rl).getNewCopy(); } if (!recipe.getOutput().isEmpty()) { if (recipe.getTexture().equals(BINDING_ARRAY)) { return new AlchemyArrayEffectBinding(recipe.getOutput()); } // Return a new instance of AlchemyEffectCrafting return new AlchemyArrayEffectCrafting(recipe.getOutput()); } return null; } public static AlchemyArrayEffect getEffect(Level world, ItemStack input, ItemStack catalyst) { Pair<Boolean, RecipeAlchemyArray> array = BloodMagicAPI.INSTANCE.getRecipeRegistrar().getAlchemyArray(world, input, catalyst); if (array == null || array.getRight() == null || !array.getLeft()) return null; return getEffect(world, array.getRight().getId(), array.getRight()); } }
412
0.82157
1
0.82157
game-dev
MEDIA
0.935291
game-dev
0.887731
1
0.887731
ax-grymyr/l2dn-server
3,333
L2Dn/L2Dn.GameServer.Scripts/Handlers/EffectHandlers/ManaHealByLevel.cs
using L2Dn.GameServer.Model; using L2Dn.GameServer.Model.Actor; using L2Dn.GameServer.Model.Effects; using L2Dn.GameServer.Model.Items.Instances; using L2Dn.GameServer.Model.Skills; using L2Dn.GameServer.Network.Enums; using L2Dn.GameServer.Network.OutgoingPackets; using L2Dn.Model.Enums; using L2Dn.Utilities; namespace L2Dn.GameServer.Scripts.Handlers.EffectHandlers; /// <summary> /// Mana Heal By Level effect implementation. /// </summary> public sealed class ManaHealByLevel: AbstractEffect { private readonly double _power; public ManaHealByLevel(StatSet @params) { _power = @params.getDouble("power", 0); } public override EffectType getEffectType() => EffectType.MANAHEAL_BY_LEVEL; public override bool isInstant() => true; public override void instant(Creature effector, Creature effected, Skill skill, Item? item) { if (effected.isDead() || effected.isDoor() || effected.isMpBlocked()) return; if (effected != effector && effected.isAffected(EffectFlag.FACEOFF)) return; double amount = _power; // recharged mp influenced by difference between target level and skill level // if target is within 5 levels or lower then skill level there's no penalty. amount = effected.getStat().getValue(Stat.MANA_CHARGE, amount); if (effected.getLevel() > skill.getMagicLevel()) { int levelDiff = effected.getLevel() - skill.getMagicLevel(); // if target is too high compared to skill level, the amount of recharged mp gradually decreases. if (levelDiff == 6) amount *= 0.9; // only 90% effective else if (levelDiff == 7) amount *= 0.8; // 80% else if (levelDiff == 8) amount *= 0.7; // 70% else if (levelDiff == 9) amount *= 0.6; // 60% else if (levelDiff == 10) amount *= 0.5; // 50% else if (levelDiff == 11) amount *= 0.4; // 40% else if (levelDiff == 12) amount *= 0.3; // 30% else if (levelDiff == 13) amount *= 0.2; // 20% else if (levelDiff == 14) amount *= 0.1; // 10% else if (levelDiff >= 15) amount = 0; // 0mp recharged } // Prevents overheal and negative amount amount = Math.Max(Math.Min(amount, effected.getMaxRecoverableMp() - effected.getCurrentMp()), 0); if (amount != 0) { double newMp = amount + effected.getCurrentMp(); effected.setCurrentMp(newMp, false); effected.broadcastStatusUpdate(effector); } SystemMessagePacket sm = new SystemMessagePacket(effector.ObjectId != effected.ObjectId ? SystemMessageId.YOU_HAVE_RECOVERED_S2_MP_WITH_C1_S_HELP : SystemMessageId.S1_MP_HAS_BEEN_RESTORED); if (effector.ObjectId != effected.ObjectId) { sm.Params.addString(effector.getName()); } sm.Params.addInt((int)amount); effected.sendPacket(sm); } public override int GetHashCode() => HashCode.Combine(_power); public override bool Equals(object? obj) => this.EqualsTo(obj, static x => x._power); }
412
0.862295
1
0.862295
game-dev
MEDIA
0.985252
game-dev
0.98056
1
0.98056
FastLED/FastLED
1,065
src/fx/1d/noisewave.h
#pragma once #include "FastLED.h" #include "fl/namespace.h" #include "fx/fx1d.h" #include "noisegen.h" namespace fl { FASTLED_SMART_PTR(NoiseWave); class NoiseWave : public Fx1d { public: NoiseWave(uint16_t num_leds) : Fx1d(num_leds), noiseGeneratorRed(500, 14), noiseGeneratorBlue(500, 10) {} void draw(DrawContext context) override { if (context.leds == nullptr || mNumLeds == 0) { return; } if (start_time == 0) { start_time = context.now; } unsigned long time_now = millis() - start_time; for (int32_t i = 0; i < mNumLeds; ++i) { int r = noiseGeneratorRed.LedValue(i, time_now); int b = noiseGeneratorBlue.LedValue(i, time_now + 100000) >> 1; int g = 0; context.leds[i] = CRGB(r, g, b); } } fl::string fxName() const override { return "NoiseWave"; } private: NoiseGenerator noiseGeneratorRed; NoiseGenerator noiseGeneratorBlue; fl::u32 start_time = 0; }; } // namespace fl
412
0.661884
1
0.661884
game-dev
MEDIA
0.390818
game-dev
0.70375
1
0.70375
eromatiya/the-glorious-dotfiles
1,225
config/awesome/gnawesome/widget/xdg-folders/pictures.lua
local wibox = require('wibox') local awful = require('awful') local naughty = require('naughty') local gears = require('gears') local clickable_container = require('widget.clickable-container') local dpi = require('beautiful').xresources.apply_dpi local config_dir = gears.filesystem.get_configuration_dir() local widget_icon_dir = config_dir .. 'widget/xdg-folders/icons/' local create_widget = function() local pic_widget = wibox.widget { { image = widget_icon_dir .. 'folder-pictures.svg', resize = true, widget = wibox.widget.imagebox }, layout = wibox.layout.align.horizontal } local pic_button = wibox.widget { { pic_widget, margins = dpi(10), widget = wibox.container.margin }, widget = clickable_container } pic_button:buttons( gears.table.join( awful.button( {}, 1, nil, function() awful.spawn.with_shell('xdg-open $(xdg-user-dir PICTURES)') end ) ) ) awful.tooltip( { objects = {pic_button}, mode = 'outside', align = 'right', text = 'Pictures', margin_leftright = dpi(8), margin_topbottom = dpi(8), preferred_positions = {'top', 'bottom', 'right', 'left'} } ) return pic_button end return create_widget
412
0.73644
1
0.73644
game-dev
MEDIA
0.577161
game-dev,desktop-app
0.554437
1
0.554437
LearnCocos2D/cocos2d-iphone-arc-templates
8,905
cocos2d-2.x-Box2D-ARC-iOS/cocos2d-2.x-Box2D-ARC-iOS/libs/Box2D/Dynamics/Contacts/b2Contact.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_CONTACT_H #define B2_CONTACT_H #include <Box2D/Common/b2Math.h> #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Dynamics/b2Fixture.h> class b2Body; class b2Contact; class b2Fixture; class b2World; class b2BlockAllocator; class b2StackAllocator; class b2ContactListener; /// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. /// For example, anything slides on ice. inline float32 b2MixFriction(float32 friction1, float32 friction2) { return std::sqrt(friction1 * friction2); } /// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. /// For example, a superball bounces on anything. inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); struct b2ContactRegister { b2ContactCreateFcn* createFcn; b2ContactDestroyFcn* destroyFcn; bool primary; }; /// A contact edge is used to connect bodies and contacts together /// in a contact graph where each body is a node and each contact /// is an edge. A contact edge belongs to a doubly linked list /// maintained in each attached body. Each contact has two contact /// nodes, one for each attached body. struct b2ContactEdge { b2Body* other; ///< provides quick access to the other body attached. b2Contact* contact; ///< the contact b2ContactEdge* prev; ///< the previous contact edge in the body's contact list b2ContactEdge* next; ///< the next contact edge in the body's contact list }; /// The class manages contact between two shapes. A contact exists for each overlapping /// AABB in the broad-phase (except if filtered). Therefore a contact object may exist /// that has no contact points. class b2Contact { public: /// Get the contact manifold. Do not modify the manifold unless you understand the /// internals of Box2D. b2Manifold* GetManifold(); const b2Manifold* GetManifold() const; /// Get the world manifold. void GetWorldManifold(b2WorldManifold* worldManifold) const; /// Is this contact touching? bool IsTouching() const; /// Enable/disable this contact. This can be used inside the pre-solve /// contact listener. The contact is only disabled for the current /// time step (or sub-step in continuous collisions). void SetEnabled(bool flag); /// Has this contact been disabled? bool IsEnabled() const; /// Get the next contact in the world's contact list. b2Contact* GetNext(); const b2Contact* GetNext() const; /// Get fixture A in this contact. b2Fixture* GetFixtureA(); const b2Fixture* GetFixtureA() const; /// Get the child primitive index for fixture A. int32 GetChildIndexA() const; /// Get fixture B in this contact. b2Fixture* GetFixtureB(); const b2Fixture* GetFixtureB() const; /// Get the child primitive index for fixture B. int32 GetChildIndexB() const; /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. /// This value persists until set or reset. void SetFriction(float32 friction); /// Get the friction. float32 GetFriction() const; /// Reset the friction mixture to the default value. void ResetFriction(); /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. /// The value persists until you set or reset. void SetRestitution(float32 restitution); /// Get the restitution. float32 GetRestitution() const; /// Reset the restitution to the default value. void ResetRestitution(); /// Evaluate this contact with your own manifold and transforms. virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; protected: friend class b2ContactManager; friend class b2World; friend class b2ContactSolver; friend class b2Body; friend class b2Fixture; // Flags stored in m_flags enum { // Used when crawling contact graph when forming islands. e_islandFlag = 0x0001, // Set when the shapes are touching. e_touchingFlag = 0x0002, // This contact can be disabled (by user) e_enabledFlag = 0x0004, // This contact needs filtering because a fixture filter was changed. e_filterFlag = 0x0008, // This bullet contact had a TOI event e_bulletHitFlag = 0x0010, // This contact has a valid TOI in m_toi e_toiFlag = 0x0020 }; /// Flag this contact for filtering. Filtering will occur the next time step. void FlagForFiltering(); static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, b2Shape::Type typeA, b2Shape::Type typeB); static void InitializeRegisters(); static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); virtual ~b2Contact() {} void Update(b2ContactListener* listener); static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; static bool s_initialized; uint32 m_flags; // World pool and list pointers. b2Contact* m_prev; b2Contact* m_next; // Nodes for connecting bodies. b2ContactEdge m_nodeA; b2ContactEdge m_nodeB; b2Fixture* m_fixtureA; b2Fixture* m_fixtureB; int32 m_indexA; int32 m_indexB; b2Manifold m_manifold; int32 m_toiCount; float32 m_toi; float32 m_friction; float32 m_restitution; }; inline b2Manifold* b2Contact::GetManifold() { return &m_manifold; } inline const b2Manifold* b2Contact::GetManifold() const { return &m_manifold; } inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const { const b2Body* bodyA = m_fixtureA->GetBody(); const b2Body* bodyB = m_fixtureB->GetBody(); const b2Shape* shapeA = m_fixtureA->GetShape(); const b2Shape* shapeB = m_fixtureB->GetShape(); worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); } inline void b2Contact::SetEnabled(bool flag) { if (flag) { m_flags |= e_enabledFlag; } else { m_flags &= ~e_enabledFlag; } } inline bool b2Contact::IsEnabled() const { return (m_flags & e_enabledFlag) == e_enabledFlag; } inline bool b2Contact::IsTouching() const { return (m_flags & e_touchingFlag) == e_touchingFlag; } inline b2Contact* b2Contact::GetNext() { return m_next; } inline const b2Contact* b2Contact::GetNext() const { return m_next; } inline b2Fixture* b2Contact::GetFixtureA() { return m_fixtureA; } inline const b2Fixture* b2Contact::GetFixtureA() const { return m_fixtureA; } inline b2Fixture* b2Contact::GetFixtureB() { return m_fixtureB; } inline int32 b2Contact::GetChildIndexA() const { return m_indexA; } inline const b2Fixture* b2Contact::GetFixtureB() const { return m_fixtureB; } inline int32 b2Contact::GetChildIndexB() const { return m_indexB; } inline void b2Contact::FlagForFiltering() { m_flags |= e_filterFlag; } inline void b2Contact::SetFriction(float32 friction) { m_friction = friction; } inline float32 b2Contact::GetFriction() const { return m_friction; } inline void b2Contact::ResetFriction() { m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); } inline void b2Contact::SetRestitution(float32 restitution) { m_restitution = restitution; } inline float32 b2Contact::GetRestitution() const { return m_restitution; } inline void b2Contact::ResetRestitution() { m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); } #endif
412
0.95616
1
0.95616
game-dev
MEDIA
0.674079
game-dev
0.953684
1
0.953684
sarl/sarl
4,876
sarl-lang/core/src/main/java/io/sarl/lang/core/AgentTrait.java
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2026 SARL.io, the original authors and main authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.lang.core; import java.lang.ref.WeakReference; import java.util.UUID; import org.eclipse.xtext.xbase.lib.Inline; import org.eclipse.xtext.xbase.lib.Pure; import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; /** This class represents a part of trait of an agent. * * @author $Author: srodriguez$ * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ public abstract class AgentTrait extends AgentProtectedAPIObject { private WeakReference<Agent> agentRef; /** Construct a trait to the given agent. * * @param agent the owner of this trait. */ protected AgentTrait(Agent agent) { this.agentRef = new WeakReference<>(agent); } /** Construct a trait. */ protected AgentTrait() { this.agentRef = new WeakReference<>(null); } @Override protected void toString(ToStringBuilder builder) { builder.add("type", getClass().getSimpleName()); //$NON-NLS-1$ builder.add("owner", getOwner()); //$NON-NLS-1$ } /** Set the agent that has this trait. * * @param agent the owner of this trait. */ void setOwner(Agent agent) { this.agentRef = new WeakReference<>(agent); } /** Replies the agent that has this trait. * * @return the owner. */ @Pure public Agent getOwner() { return this.agentRef.get(); } /** Replies the identifier of the agent that has this trait. * * @return the UUID of the owner. * @since 0.6 */ @Pure @Inline("getOwner().getID()") public UUID getID() { return getOwner().getID(); } @Override @Pure protected final <S extends Capacity> S getSkill(Class<S> capacity) { assert capacity != null; final var skill = $getSkill(capacity); assert skill != null; return $castSkill(capacity, skill); } /** Cast the skill reference to the given capacity type. * * @param <S> the expected capacity type. * @param capacity the expected capacity type. * @param skillReference the skill reference. * @return the skill casted to the given capacity. */ @Pure protected <S extends Capacity> S $castSkill(Class<S> capacity, AtomicSkillReference skillReference) { if (skillReference != null) { final var skill = capacity.cast(skillReference.get()); if (skill != null) { return skill; } } throw new UnimplementedCapacityException(capacity, getOwner().getID()); } @Override protected AtomicSkillReference $getSkill(Class<? extends Capacity> capacity) { final var owner = getOwner(); if (owner == null) { throw new OwnerNotFoundException(this); } return owner.$getSkill(capacity); } @Override @Inline("setSkill($2, $1)") protected <S extends Skill> void operator_mappedTo(Class<? extends Capacity> capacity, S skill) { setSkill(skill, capacity); } @Override @SafeVarargs protected final <S extends Skill> S setSkill(S skill, Class<? extends Capacity>... capacities) { final var owner = getOwner(); if (owner == null) { return skill; } return owner.setSkill(skill, capacities); } @Override @SafeVarargs protected final void setSkillIfAbsent(Skill skill, Class<? extends Capacity>... capacities) { final var owner = getOwner(); if (owner != null) { owner.setSkillIfAbsent(skill, capacities); } } @Override protected <S extends Capacity> S clearSkill(Class<S> capacity) { final var owner = getOwner(); if (owner == null) { return null; } return owner.clearSkill(capacity); } @Override @Pure protected boolean hasSkill(Class<? extends Capacity> capacity) { final var owner = getOwner(); if (owner == null) { return false; } return owner.hasSkill(capacity); } @Override @Pure public boolean isMe(Address address) { final var owner = getOwner(); if (owner == null) { return false; } return owner.isMe(address); } @Override @Pure public boolean isMe(UUID uID) { final var owner = getOwner(); if (owner == null) { return false; } return owner.isMe(uID); } @Override @Pure public boolean isFromMe(Event event) { final var owner = getOwner(); if (owner == null) { return false; } return owner.isFromMe(event); } }
412
0.870674
1
0.870674
game-dev
MEDIA
0.258899
game-dev
0.966854
1
0.966854
TaiyitistMC/Taiyitist
5,710
modules/taiyitist-server/src/main/java/com/taiyitistmc/mixin/world/level/chunk/MixinChunkGenerator.java
package com.taiyitistmc.mixin.world.level.chunk; import com.taiyitistmc.injection.world.level.chunk.InjectionChunkGenerator; import java.util.Objects; import java.util.function.Predicate; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.RegistryAccess; import net.minecraft.core.SectionPos; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.LegacyRandomSource; import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.WorldgenRandom; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.generator.CraftLimitedRegion; import org.bukkit.craftbukkit.generator.structure.CraftStructure; import org.bukkit.craftbukkit.util.RandomSourceWrapper; import org.bukkit.generator.BlockPopulator; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ChunkGenerator.class) public abstract class MixinChunkGenerator implements InjectionChunkGenerator { @Shadow @Mutable public BiomeSource biomeSource; // Banner start - fix mixin conflict BoundingBox box; // @formatter:on org.bukkit.event.world.AsyncStructureSpawnEvent event; @Shadow private static int fetchReferences(StructureManager structureManager, ChunkAccess chunk, SectionPos sectionPos, Structure structure) { return 0; } // @formatter:off @Shadow public abstract void applyBiomeDecoration(WorldGenLevel p_187712_, ChunkAccess p_187713_, StructureManager p_187714_); @Inject(method = "applyBiomeDecoration", at = @At("RETURN")) private void taiyitist$addBukkitDecoration(WorldGenLevel level, ChunkAccess chunkAccess, StructureManager manager, CallbackInfo ci) { this.addDecorations(level, chunkAccess, manager); } // Banner end /** * @author wdog5 * @reason bukkit */ @Overwrite private boolean tryGenerateStructure(StructureSet.StructureSelectionEntry structureSelectionEntry, StructureManager structureManager, RegistryAccess registryAccess, RandomState random, StructureTemplateManager structureTemplateManager, long seed, ChunkAccess chunk, ChunkPos chunkPos, SectionPos sectionPos) { Structure structure = structureSelectionEntry.structure().value(); int i = fetchReferences(structureManager, chunk, sectionPos, structure); HolderSet<Biome> holderSet = structure.biomes(); Objects.requireNonNull(holderSet); Predicate<Holder<Biome>> predicate = holderSet::contains; StructureStart structureStart = structure.generate(registryAccess, ((ChunkGenerator) (Object) this), this.biomeSource, random, structureTemplateManager, seed, chunkPos, i, chunk, predicate); if (structureStart.isValid()) { structureManager.setStartForStructure(sectionPos, structure, structureStart, chunk); box = structureStart.getBoundingBox(); event = new org.bukkit.event.world.AsyncStructureSpawnEvent((structureManager.level.getMinecraftWorld()).getWorld(), CraftStructure.minecraftToBukkit(structure), new org.bukkit.util.BoundingBox(box.minX(), box.minY(), box.minZ(), box.maxX(), box.maxY(), box.maxZ()), chunkPos.x, chunkPos.z); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { return true; } return true; } else { return false; } } @Override public void applyBiomeDecoration(WorldGenLevel level, ChunkAccess chunkAccess, StructureManager structureFeatureManager, boolean vanilla) { if (vanilla) { this.applyBiomeDecoration(level, chunkAccess, structureFeatureManager); } else { this.addDecorations(level, chunkAccess, structureFeatureManager); } } @Override public void addDecorations(WorldGenLevel region, ChunkAccess chunk, StructureManager structureManager) { org.bukkit.World world = region.getMinecraftWorld().getWorld(); // only call when a populator is present (prevents unnecessary entity conversion) if (!world.getPopulators().isEmpty()) { CraftLimitedRegion limitedRegion = new CraftLimitedRegion(region, chunk.getPos()); int x = chunk.getPos().x; int z = chunk.getPos().z; for (BlockPopulator populator : world.getPopulators()) { WorldgenRandom random = new WorldgenRandom(new LegacyRandomSource(region.getSeed())); random.setDecorationSeed(region.getSeed(), x, z); populator.populate(world, new RandomSourceWrapper.RandomWrapper(random), x, z, limitedRegion); } limitedRegion.saveEntities(); limitedRegion.breakLink(); } } }
412
0.855298
1
0.855298
game-dev
MEDIA
0.99799
game-dev
0.840415
1
0.840415
onnoj/DeusExEchelonRenderer
31,101
INCLUDE/deusex/Core/Src/UnLinker.h
/*============================================================================= UnLinker.h: Unreal object linker. Copyright 1997-1999 Epic Games, Inc. All Rights Reserved. Revision history: * Created by Tim Sweeney =============================================================================*/ /*----------------------------------------------------------------------------- Hash function. -----------------------------------------------------------------------------*/ inline INT HashNames( FName A, FName B, FName C ) { if( C==NAME_UnrealShare )//oldver C=NAME_UnrealI; return A.GetIndex() + 7 * B.GetIndex() + 31*C.GetIndex(); } /*----------------------------------------------------------------------------- FObjectExport. -----------------------------------------------------------------------------*/ // // Information about an exported object. // struct CORE_API FObjectExport { // Variables. INT ClassIndex; // Persistent. INT SuperIndex; // Persistent (for UStruct-derived objects only). INT PackageIndex; // Persistent. FName ObjectName; // Persistent. DWORD ObjectFlags; // Persistent. INT SerialSize; // Persistent. INT SerialOffset; // Persistent (for checking only). UObject* _Object; // Internal. INT _iHashNext; // Internal. // Functions. FObjectExport() : _Object ( NULL ) , _iHashNext ( INDEX_NONE ) {} FObjectExport( UObject* InObject ) : ClassIndex ( 0 ) , SuperIndex ( 0 ) , PackageIndex ( 0 ) , ObjectName ( InObject ? (InObject->GetFName() ) : NAME_None ) , ObjectFlags ( InObject ? (InObject->GetFlags() & RF_Load) : 0 ) , SerialSize ( 0 ) , SerialOffset ( 0 ) , _Object ( InObject ) {} friend FArchive& operator<<( FArchive& Ar, FObjectExport& E ) { guard(FObjectExport<<); Ar << AR_INDEX(E.ClassIndex); Ar << AR_INDEX(E.SuperIndex); Ar << E.PackageIndex; Ar << E.ObjectName; Ar << E.ObjectFlags; Ar << AR_INDEX(E.SerialSize); if( E.SerialSize ) Ar << AR_INDEX(E.SerialOffset); return Ar; unguard; } }; /*----------------------------------------------------------------------------- FObjectImport. -----------------------------------------------------------------------------*/ // // Information about an imported object. // struct CORE_API FObjectImport { // Variables. FName ClassPackage; // Persistent. FName ClassName; // Persistent. INT PackageIndex; // Persistent. FName ObjectName; // Persistent. UObject* XObject; // Internal (only really needed for saving, can easily be gotten rid of for loading). ULinkerLoad* SourceLinker; // Internal. INT SourceIndex; // Internal. // Functions. FObjectImport() {} FObjectImport( UObject* InObject ) : ClassPackage ( InObject->GetClass()->GetOuter()->GetFName()) , ClassName ( InObject->GetClass()->GetFName() ) , PackageIndex ( 0 ) , ObjectName ( InObject->GetFName() ) , XObject ( InObject ) , SourceLinker ( NULL ) , SourceIndex ( INDEX_NONE ) { if( XObject ) UObject::GImportCount++; } friend FArchive& operator<<( FArchive& Ar, FObjectImport& I ) { guard(FObjectImport<<); Ar << I.ClassPackage << I.ClassName; Ar << I.PackageIndex; Ar << I.ObjectName; if( Ar.IsLoading() ) { I.SourceIndex = INDEX_NONE; I.XObject = NULL; } return Ar; unguard; } }; /*---------------------------------------------------------------------------- Items stored in Unrealfiles. ----------------------------------------------------------------------------*/ // // Unrealfile summary, stored at top of file. // struct FGenerationInfo { INT ExportCount, NameCount; FGenerationInfo( INT InExportCount, INT InNameCount ) : ExportCount(InExportCount), NameCount(InNameCount) {} friend FArchive& operator<<( FArchive& Ar, FGenerationInfo& Info ) { guard(FGenerationInfo<<); return Ar << Info.ExportCount << Info.NameCount; unguard; } }; struct FPackageFileSummary { // Variables. INT Tag; INT FileVersion; DWORD PackageFlags; INT NameCount, NameOffset; INT ExportCount, ExportOffset; INT ImportCount, ImportOffset; FGuid Guid; TArray<FGenerationInfo> Generations; // Constructor. FPackageFileSummary() { appMemzero( this, sizeof(*this) ); } // Serializer. friend FArchive& operator<<( FArchive& Ar, FPackageFileSummary& Sum ) { guard(FUnrealfileSummary<<); Ar << Sum.Tag; Ar << Sum.FileVersion; Ar << Sum.PackageFlags; Ar << Sum.NameCount << Sum.NameOffset; Ar << Sum.ExportCount << Sum.ExportOffset; Ar << Sum.ImportCount << Sum.ImportOffset; if( Sum.FileVersion>=68 ) { INT GenerationCount = Sum.Generations.Num(); Ar << Sum.Guid << GenerationCount; //!!67 had: return if( Ar.IsLoading() ) Sum.Generations = TArray<FGenerationInfo>( GenerationCount ); for( INT i=0; i<GenerationCount; i++ ) Ar << Sum.Generations(i); } else //oldver { INT HeritageCount, HeritageOffset; Ar << HeritageCount << HeritageOffset; INT Saved = Ar.Tell(); if( HeritageCount ) { Ar.Seek( HeritageOffset ); for( INT i=0; i<HeritageCount; i++ ) Ar << Sum.Guid; } Ar.Seek( Saved ); if( Ar.IsLoading() ) { Sum.Generations.Empty( 1 ); new(Sum.Generations)FGenerationInfo(Sum.ExportCount,Sum.NameCount); } } return Ar; unguard; } }; /*---------------------------------------------------------------------------- ULinker. ----------------------------------------------------------------------------*/ // // A file linker. // class CORE_API ULinker : public UObject { DECLARE_CLASS(ULinker,UObject,CLASS_Transient) NO_DEFAULT_CONSTRUCTOR(ULinker) // Variables. UObject* LinkerRoot; // The linker's root object. FPackageFileSummary Summary; // File summary. TArray<FName> NameMap; // Maps file name indices to name table indices. TArray<FObjectImport> ImportMap; // Maps file object indices >=0 to external object names. TArray<FObjectExport> ExportMap; // Maps file object indices >=0 to external object names. INT Success; // Whether the object was constructed successfully. FString Filename; // Filename. DWORD _ContextFlags; // Load flag mask. // Constructors. ULinker( UObject* InRoot, const TCHAR* InFilename ) : LinkerRoot( InRoot ) , Summary() , Success( 123456 ) , Filename( InFilename ) , _ContextFlags( 0 ) { check(LinkerRoot); check(InFilename); // Set context flags. if( GIsEditor ) _ContextFlags |= RF_LoadForEdit; if( GIsClient ) _ContextFlags |= RF_LoadForClient; if( GIsServer ) _ContextFlags |= RF_LoadForServer; } // UObject interface. void Serialize( FArchive& Ar ) { guard(ULinker::Serialize); Super::Serialize( Ar ); // Sizes. ImportMap .CountBytes( Ar ); ExportMap .CountBytes( Ar ); // Prevent garbage collecting of linker's names and package. Ar << NameMap << LinkerRoot; {for( INT i=0; i<ExportMap.Num(); i++ ) { FObjectExport& E = ExportMap(i); Ar << E.ObjectName; }} {for( INT i=0; i<ImportMap.Num(); i++ ) { FObjectImport& I = ImportMap(i); Ar << *(UObject**)&I.SourceLinker; Ar << I.ClassPackage << I.ClassName; }} unguard; } // ULinker interface. FString GetImportFullName( INT i ) { guard(ULinkerLoad::GetImportFullName); FString S; for( INT j=-i-1; j!=0; j=ImportMap(-j-1).PackageIndex ) { if( j != -i-1 ) S = US + TEXT(".") + S; S = FString(*ImportMap(-j-1).ObjectName) + S; } return FString(*ImportMap(i).ClassName) + TEXT(" ") + S ; unguard; } FString GetExportFullName( INT i, const TCHAR* FakeRoot=NULL ) { guard(ULinkerLoad::GetExportFullName); FString S; for( INT j=i+1; j!=0; j=ExportMap(j-1).PackageIndex ) { if( j != i+1 ) S = US + TEXT(".") + S; S = FString(*ExportMap(j-1).ObjectName) + S; } INT ClassIndex = ExportMap(i).ClassIndex; FName ClassName = ClassIndex>0 ? ExportMap(ClassIndex-1).ObjectName : ClassIndex<0 ? ImportMap(-ClassIndex-1).ObjectName : NAME_Class; return FString(*ClassName) + TEXT(" ") + (FakeRoot ? FakeRoot : LinkerRoot->GetPathName()) + TEXT(".") + S; unguard; } }; /*---------------------------------------------------------------------------- ULinkerLoad. ----------------------------------------------------------------------------*/ // // A file loader. // class ULinkerLoad : public ULinker, public FArchive { DECLARE_CLASS(ULinkerLoad,ULinker,CLASS_Transient) NO_DEFAULT_CONSTRUCTOR(ULinkerLoad) // Friends. friend class UObject; friend class UPackageMap; // Variables. DWORD LoadFlags; UBOOL Verified; INT ExportHash[256]; TArray<FLazyLoader*> LazyLoaders; FArchive* Loader; // Constructor; all errors here throw exceptions which are fully recoverable. ULinkerLoad( UObject* InParent, const TCHAR* InFilename, DWORD InLoadFlags ) : ULinker( InParent, InFilename ) , LoadFlags( InLoadFlags ) { guard(ULinkerLoad::ULinkerLoad); if(!(LoadFlags & LOAD_Quiet)) debugf( TEXT("Loading: %s"), InParent->GetFullName() ); Loader = GFileManager->CreateFileReader( InFilename, 0, GError ); if( !Loader ) appThrowf( LocalizeError("OpenFailed") ); // Error if linker already loaded. {for( INT i=0; i<GObjLoaders.Num(); i++ ) if( GetLoader(i)->LinkerRoot == LinkerRoot ) appThrowf( LocalizeError("LinkerExists"), LinkerRoot->GetName() );} // Begin. GWarn->StatusUpdatef( 0, 0, LocalizeProgress("Loading"), *Filename ); // Set status info. guard(InitAr); ArVer = PACKAGE_FILE_VERSION; ArIsLoading = ArIsPersistent = 1; ArForEdit = GIsEditor; ArForClient = 1; ArForServer = 1; unguard; // Read summary from file. guard(LoadSummary); *this << Summary; ArVer = Summary.FileVersion; if( Cast<UPackage>(LinkerRoot) ) Cast<UPackage>(LinkerRoot)->PackageFlags = Summary.PackageFlags; unguard; // Check tag. guard(CheckTag); if( Summary.Tag != PACKAGE_FILE_TAG ) { GWarn->Logf( LocalizeError("BinaryFormat"), *Filename ); throw( LocalizeError("Aborted") ); } unguard; // Validate the summary. guard(CheckVersion); if( Summary.FileVersion < PACKAGE_MIN_VERSION ) if( !GWarn->YesNof( LocalizeQuery("OldVersion"), *Filename ) ) throw( LocalizeError("Aborted") ); unguard; // Slack everything according to summary. ImportMap .Empty( Summary.ImportCount ); ExportMap .Empty( Summary.ExportCount ); NameMap .Empty( Summary.NameCount ); // Load and map names. guard(LoadNames); if( Summary.NameCount > 0 ) { Seek( Summary.NameOffset ); for( INT i=0; i<Summary.NameCount; i++ ) { // Read the name entry from the file. FNameEntry NameEntry; *this << NameEntry; // Add it to the name table if it's needed in this context. NameMap.AddItem( (NameEntry.Flags & _ContextFlags) ? FName( NameEntry.Name, FNAME_Add ) : NAME_None ); } } unguard; // Load import map. guard(LoadImportMap); if( Summary.ImportCount > 0 ) { Seek( Summary.ImportOffset ); for( INT i=0; i<Summary.ImportCount; i++ ) *this << *new(ImportMap)FObjectImport; } unguard; // Load export map. guard(LoadExportMap); if( Summary.ExportCount > 0 ) { Seek( Summary.ExportOffset ); for( INT i=0; i<Summary.ExportCount; i++ ) *this << *new(ExportMap)FObjectExport; } unguard; // Create export hash. //warning: Relies on import & export tables, so must be done here. {for( INT i=0; i<ARRAY_COUNT(ExportHash); i++ ) { ExportHash[i] = INDEX_NONE; }} {for( INT i=0; i<ExportMap.Num(); i++ ) { INT iHash = HashNames( ExportMap(i).ObjectName, GetExportClassName(i), GetExportClassPackage(i) ) & (ARRAY_COUNT(ExportHash)-1); ExportMap(i)._iHashNext = ExportHash[iHash]; ExportHash[iHash] = i; }} // Add this linker to the object manager's linker array. GObjLoaders.AddItem( this ); if( !(LoadFlags & LOAD_NoVerify) ) Verify(); // Success. Success = 1; unguard; } void Verify() { guard(ULinkerLoad::Verify); if( !Verified ) { if( Cast<UPackage>(LinkerRoot) ) Cast<UPackage>(LinkerRoot)->PackageFlags &= ~PKG_BrokenLinks; try { // Validate all imports and map them to their remote linkers. guard(ValidateImports); for( INT i=0; i<Summary.ImportCount; i++ ) VerifyImport( i ); unguard; } catch( TCHAR* Error ) { GObjLoaders.RemoveItem( this ); throw( Error ); } } Verified=1; unguard; } FName GetExportClassPackage( INT i ) { guardSlow(ULinkerLoad::GetExportClassPackage); FObjectExport& Export = ExportMap( i ); if( Export.ClassIndex < 0 ) { FObjectImport& Import = ImportMap( -Export.ClassIndex-1 ); checkSlow(Import.PackageIndex<0); return ImportMap( -Import.PackageIndex-1 ).ObjectName; } else if( Export.ClassIndex > 0 ) { return LinkerRoot->GetFName(); } else { return NAME_Core; } unguardSlow; } FName GetExportClassName( INT i ) { guardSlow(GetExportClassName); FObjectExport& Export = ExportMap(i); if( Export.ClassIndex < 0 ) { return ImportMap( -Export.ClassIndex-1 ).ObjectName; } else if( Export.ClassIndex > 0 ) { return ExportMap( Export.ClassIndex-1 ).ObjectName; } else { return NAME_Class; } unguardSlow; } // Safely verify an import. void VerifyImport( INT i ) { guard(ULinkerLoad::VerifyImport); SharewareHack://oldver FObjectImport& Import = ImportMap(i); if ( Import.SourceIndex != INDEX_NONE || Import.ClassPackage == NAME_None || Import.ClassName == NAME_None || Import.ObjectName == NAME_None ) { // Already verified, or not relevent in this context. return; } // Find or load this import's linker. INT Depth=0; UObject* Pkg=NULL; if( Import.PackageIndex == 0 ) { check(Import.ClassName==NAME_Package); check(Import.ClassPackage==NAME_Core); UPackage* TmpPkg = CreatePackage( NULL, *Import.ObjectName ); SharewareKludge://oldver try { Import.SourceLinker = GetPackageLinker( TmpPkg, NULL, LOAD_Throw | (LoadFlags & LOAD_Propagate), NULL, NULL ); } catch( const TCHAR* Error )//oldver { if( TmpPkg->GetFName()==NAME_UnrealI ) { TmpPkg = CreatePackage( NULL, TEXT("UnrealShare") ); goto SharewareKludge; } appThrowf( Error ); } } else { check(Import.PackageIndex<0); VerifyImport( -Import.PackageIndex-1 ); Import.SourceLinker = ImportMap(-Import.PackageIndex-1).SourceLinker; check(Import.SourceLinker); FObjectImport* Top; for ( Top = &Import ; Top->PackageIndex<0 ; Top = &ImportMap(-Top->PackageIndex-1),Depth++ ); Pkg = CreatePackage( NULL, *Top->ObjectName ); } // Find this import within its existing linker. UBOOL SafeReplace = 0; Rehack://oldver //new: INT iHash = HashNames( Import.ObjectName, Import.ClassName, Import.ClassPackage) & (ARRAY_COUNT(ExportHash)-1); for( INT j=Import.SourceLinker->ExportHash[iHash]; j!=INDEX_NONE; j=Import.SourceLinker->ExportMap(j)._iHashNext ) //old: //for( INT j=0; j<Import.SourceLinker->ExportMap.Num(); j++ ) { FObjectExport& Source = Import.SourceLinker->ExportMap( j ); UBOOL ClassHack = Import.ClassPackage==NAME_UnrealI && Import.SourceLinker->GetExportClassPackage(j)==NAME_UnrealShare;//oldver if ( (Source.ObjectName ==Import.ObjectName ) && (Import.SourceLinker->GetExportClassName (j)==Import.ClassName ) && (Import.SourceLinker->GetExportClassPackage(j)==Import.ClassPackage || ClassHack) ) { if( Import.PackageIndex<0 ) { FObjectImport& ParentImport = ImportMap(-Import.PackageIndex-1); if( ParentImport.SourceLinker ) { if( ParentImport.SourceIndex==INDEX_NONE ) { if( Source.PackageIndex!=0 ) { continue; } } else if( ParentImport.SourceIndex+1 != Source.PackageIndex ) { if( Source.PackageIndex!=0 ) { continue; } } } } if( !(Source.ObjectFlags & RF_Public) ) { if( LoadFlags & LOAD_Forgiving ) { if( Cast<UPackage>(LinkerRoot) ) Cast<UPackage>(LinkerRoot)->PackageFlags |= PKG_BrokenLinks; debugf( TEXT("Broken import: %s %s (file %s)"), *Import.ClassName, *GetImportFullName(i), *Import.SourceLinker->Filename ); return; } appThrowf( LocalizeError("FailedImportPrivate"), *Import.ClassName, *GetImportFullName(i) ); } Import.SourceIndex = j; break; } } if( appStricmp(*Import.ClassName,TEXT("Mesh"))==0 )//oldver { Import.ClassName=FName(TEXT("LodMesh")); goto Rehack; } // If not found in file, see if it's a public native transient class. if( Import.SourceIndex==INDEX_NONE && Pkg!=NULL ) { UObject* ClassPackage = FindObject<UPackage>( NULL, *Import.ClassPackage ); if( ClassPackage ) { UClass* FindClass = FindObject<UClass>( ClassPackage, *Import.ClassName ); if( FindClass ) { UObject* FindObject = StaticFindObject( FindClass, Pkg, *Import.ObjectName ); if ( (FindObject) && (FindObject->GetFlags() & RF_Public) && (FindObject->GetFlags() & RF_Native) && (FindObject->GetFlags() & RF_Transient) ) { Import.XObject = FindObject; GImportCount++; } else if( FindClass->ClassFlags & CLASS_SafeReplace ) { if( GCheckConflicts ) debugf( TEXT("Missing %s %s"), FindClass->GetName(), *GetImportFullName(i) ); SafeReplace = 1; } } } if( !Import.XObject && Pkg!=NULL && Pkg->GetFName()==NAME_UnrealI && Depth==1 )//oldver { Import.PackageIndex = -ImportMap.Num()-1; FObjectImport& New = *new(ImportMap)FObjectImport; New.ClassPackage = NAME_Core; New.ClassName = NAME_Package; New.PackageIndex = 0; New.ObjectName = NAME_UnrealShare; New.XObject = NULL; New.SourceLinker = NULL; New.SourceIndex = INDEX_NONE; VerifyImport(ImportMap.Num()-1); goto SharewareHack; } if( !Import.XObject && !SafeReplace ) { if( LoadFlags & LOAD_Forgiving ) { if( Cast<UPackage>(LinkerRoot) ) Cast<UPackage>(LinkerRoot)->PackageFlags |= PKG_BrokenLinks; debugf( TEXT("Broken import: %s %s (file %s)"), *Import.ClassName, *GetImportFullName(i), *Import.SourceLinker->Filename ); return; } appThrowf( LocalizeError("FailedImport"), *Import.ClassName, *GetImportFullName(i) ); } } unguard; } // Load all objects; all errors here are fatal. void LoadAllObjects() { guard(ULinkerLoad::LoadAllObjects); for( INT i=0; i<Summary.ExportCount; i++ ) CreateExport( i ); unguardobj; } // Find the index of a specified object. //!!without regard to specific package INT FindExportIndex( FName ClassName, FName ClassPackage, FName ObjectName, INT PackageIndex ) { guard(ULinkerLoad::FindExportIndex); Rehack://oldver INT iHash = HashNames( ObjectName, ClassName, ClassPackage ) & (ARRAY_COUNT(ExportHash)-1); for( INT i=ExportHash[iHash]; i!=INDEX_NONE; i=ExportMap(i)._iHashNext ) { if ( (ExportMap(i).ObjectName ==ObjectName ) && (ExportMap(i).PackageIndex==PackageIndex || PackageIndex==INDEX_NONE) && (GetExportClassPackage(i) ==ClassPackage ) && (GetExportClassName (i) ==ClassName ) ) { return i; } } if( appStricmp(*ClassName,TEXT("Mesh"))==0 )//oldver. { ClassName = FName(TEXT("LodMesh")); goto Rehack; } return INDEX_NONE; unguard; } // Create a single object. UObject* Create( UClass* ObjectClass, FName ObjectName, DWORD LoadFlags, UBOOL Checked ) { guard(ULinkerLoad::Create); //old: //for( INT i=0; i<ExportMap.Num(); i++ ) //new: INT Index = FindExportIndex( ObjectClass->GetFName(), ObjectClass->GetOuter()->GetFName(), ObjectName, INDEX_NONE ); if( Index!=INDEX_NONE ) return (LoadFlags & LOAD_Verify) ? (UObject*)-1 : CreateExport(Index); if( Checked ) appThrowf( LocalizeError("FailedCreate"), ObjectClass->GetName(), *ObjectName ); return NULL; unguard; } void Preload( UObject* Object ) { guard(ULinkerLoad::Preload); check(IsValid()); check(Object); if( Object->GetFlags() & RF_Preloading ) { // Warning for internal development. //debugf( "Object preload reentrancy: %s", Object->GetFullName() ); } if( Object->GetLinker()==this ) { // Preload the object if necessary. if( Object->GetFlags() & RF_NeedLoad ) { // If this is a struct, preload its super. if( Object->IsA(UStruct::StaticClass()) ) if( ((UStruct*)Object)->SuperField ) Preload( ((UStruct*)Object)->SuperField ); // Load the local object now. guard(LoadObject); FObjectExport& Export = ExportMap( Object->_LinkerIndex ); check(Export._Object==Object); INT SavedPos = Loader->Tell(); Loader->Seek( Export.SerialOffset ); Loader->Precache( Export.SerialSize ); // Load the object. Object->ClearFlags ( RF_NeedLoad ); Object->SetFlags ( RF_Preloading ); Object->Serialize ( *this ); Object->ClearFlags ( RF_Preloading ); //debugf(NAME_Log," %s: %i", Object->GetFullName(), Export.SerialSize ); // Make sure we serialized the right amount of stuff. if( Tell()-Export.SerialOffset != Export.SerialSize ) appErrorf( LocalizeError("SerialSize"), Object->GetFullName(), Tell()-Export.SerialOffset, Export.SerialSize ); Loader->Seek( SavedPos ); unguardf(( TEXT("(%s %i==%i/%i %i %i)"), Object->GetFullName(), Loader->Tell(), Loader->Tell(), Loader->TotalSize(), ExportMap( Object->_LinkerIndex ).SerialOffset, ExportMap( Object->_LinkerIndex ).SerialSize )); } } else if( Object->GetLinker() ) { // Send to the object's linker. Object->GetLinker()->Preload( Object ); } unguard; } private: // Return the loaded object corresponding to an export index; any errors are fatal. UObject* CreateExport( INT Index ) { guard(ULinkerLoad::CreateExport); // Map the object into our table. FObjectExport& Export = ExportMap( Index ); if( !Export._Object && (Export.ObjectFlags & _ContextFlags) ) { check(Export.ObjectName!=NAME_None || !(Export.ObjectFlags&RF_Public)); // Get the object's class. UClass* LoadClass = (UClass*)IndexToObject( Export.ClassIndex ); if( !LoadClass ) LoadClass = UClass::StaticClass(); check(LoadClass); check(LoadClass->GetClass()==UClass::StaticClass()); if( LoadClass->GetFName()==NAME_Camera )//oldver return NULL; Preload( LoadClass ); // Get the outer object. If that caused the object to load, return it. UObject* ThisParent = Export.PackageIndex ? IndexToObject(Export.PackageIndex) : LinkerRoot; if( Export._Object ) return Export._Object; //oldver: Move actors from root to level. /*if( Ver() <= 61 ) { static UClass* ActorClass = FindObject<UClass>(ANY_PACKAGE,"Actor"); static UClass* LevelClass = FindObject<UClass>(ANY_PACKAGE,"Level"); if( ActorClass && LoadClass->IsChildOf(ActorClass) && ThisParent==LinkerRoot ) ThisParent = StaticFindObjectChecked( LevelClass, LinkerRoot, "MyLevel" ); }*/ // Create the export object. Export._Object = StaticConstructObject ( LoadClass, ThisParent, Export.ObjectName, (Export.ObjectFlags & RF_Load) | RF_NeedLoad | RF_NeedPostLoad ); Export._Object->SetLinker( this, Index ); GObjLoaded.AddItem( Export._Object ); debugfSlow( NAME_DevLoad, TEXT("Created %s"), Export._Object->GetFullName() ); // If it's a struct or class, set its parent. if( Export._Object->IsA(UStruct::StaticClass()) && Export.SuperIndex!=0 ) ((UStruct*)Export._Object)->SuperField = (UStruct*)IndexToObject( Export.SuperIndex ); // If it's a class, bind it to C++. if( Export._Object->IsA( UClass::StaticClass() ) ) ((UClass*)Export._Object)->Bind(); } return Export._Object; unguardf(( TEXT("(%s %i)"), *ExportMap(Index).ObjectName, Tell() )); } // Return the loaded object corresponding to an import index; any errors are fatal. UObject* CreateImport( INT Index ) { guard(ULinkerLoad::CreateImport); FObjectImport& Import = ImportMap( Index ); if( !Import.XObject && Import.SourceIndex>=0 ) { //debugf( "Imported new %s %s.%s", *Import.ClassName, *Import.ObjectPackage, *Import.ObjectName ); check(Import.SourceLinker); Import.XObject = Import.SourceLinker->CreateExport( Import.SourceIndex ); GImportCount++; } return Import.XObject; unguard; } // Map an import/export index to an object; all errors here are fatal. UObject* IndexToObject( INT Index ) { guard(IndexToObject); if( Index > 0 ) { if( !ExportMap.IsValidIndex( Index-1 ) ) appErrorf( LocalizeError("ExportIndex"), Index-1, ExportMap.Num() ); return CreateExport( Index-1 ); } else if( Index < 0 ) { if( !ImportMap.IsValidIndex( -Index-1 ) ) appErrorf( LocalizeError("ImportIndex"), -Index-1, ImportMap.Num() ); return CreateImport( -Index-1 ); } else return NULL; unguard; } // Detach an export from this linker. void DetachExport( INT i ) { guard(ULinkerLoad::DetachExport); FObjectExport& E = ExportMap( i ); check(E._Object); if( !E._Object->IsValid() ) appErrorf( TEXT("Linker object %s %s.%s is invalid"), *GetExportClassName(i), LinkerRoot->GetName(), *E.ObjectName ); if( E._Object->GetLinker()!=this ) appErrorf( TEXT("Linker object %s %s.%s mislinked"), *GetExportClassName(i), LinkerRoot->GetName(), *E.ObjectName ); if( E._Object->_LinkerIndex!=i ) appErrorf( TEXT("Linker object %s %s.%s misindexed"), *GetExportClassName(i), LinkerRoot->GetName(), *E.ObjectName ); ExportMap(i)._Object->SetLinker( NULL, INDEX_NONE ); unguard; } // UObject interface. void Serialize( FArchive& Ar ) { guard(ULinkerLoad::Serialize); Super::Serialize( Ar ); LazyLoaders.CountBytes( Ar ); unguard; } void Destroy() { guard(ULinkerLoad::Destroy); if(!(LoadFlags & LOAD_Quiet)) debugf( TEXT("Unloading: %s"), LinkerRoot->GetFullName() ); // Detach all lazy loaders. DetachAllLazyLoaders( 0 ); // Detach all objects linked with this linker. for( INT i=0; i<ExportMap.Num(); i++ ) if( ExportMap(i)._Object ) DetachExport( i ); // Remove from object manager, if it has been added. GObjLoaders.RemoveItem( this ); if( Loader ) delete Loader; Loader = NULL; Super::Destroy(); unguardobj; } // FArchive interface. void AttachLazyLoader( FLazyLoader* LazyLoader ) { guard(ULinkerLoad::AttachLazyLoader); checkSlow(LazyLoader->SavedAr==NULL); checkSlow(LazyLoaders.FindItemIndex(LazyLoader)==INDEX_NONE); LazyLoaders.AddItem( LazyLoader ); LazyLoader->SavedAr = this; LazyLoader->SavedPos = Tell(); unguard; } void DetachLazyLoader( FLazyLoader* LazyLoader ) { guard(ULinkerLoad::DetachLazyLoader); checkSlow(LazyLoader->SavedAr==this); INT RemovedCount = LazyLoaders.RemoveItem(LazyLoader); if( RemovedCount!=1 ) appErrorf( TEXT("Detachment inconsistency: %i (%s)"), RemovedCount, *Filename ); LazyLoader->SavedAr = NULL; LazyLoader->SavedPos = 0; unguard; } void DetachAllLazyLoaders( UBOOL Load ) { guard(ULinkerLoad::DetachAllLazyLoaders); for( INT i=0; i<LazyLoaders.Num(); i++ ) { FLazyLoader* LazyLoader = LazyLoaders( i ); if( Load ) LazyLoader->Load(); LazyLoader->SavedAr = NULL; LazyLoader->SavedPos = 0; } LazyLoaders.Empty(); unguard; } // FArchive interface. void Seek( INT InPos ) { guard(ULinkerLoad::Seek); Loader->Seek( InPos ); unguard; } INT Tell() { guard(ULinkerLoad::Tell); return Loader->Tell(); unguard; } INT TotalSize() { guard(ULinkerLoad::TotalSize); return Loader->TotalSize(); unguard; } void Serialize( void* V, INT Length ) { guard(ULinkerLoad::Serialize); Loader->Serialize( V, Length ); unguard; } FArchive& operator<<( UObject*& Object ) { guard(ULinkerLoad<<UObject); INT Index; *Loader << AR_INDEX(Index); Object = IndexToObject( Index ); return *this; unguardf(( TEXT("(%s %i))"), GetFullName(), Tell() )); } FArchive& operator<<( FName& Name ) { guard(ULinkerLoad<<FName); NAME_INDEX NameIndex; *Loader << AR_INDEX(NameIndex); if( !NameMap.IsValidIndex(NameIndex) ) appErrorf( TEXT("Bad name index %i/%i"), NameIndex, NameMap.Num() ); Name = NameMap( NameIndex ); return *this; unguardf(( TEXT("(%s %i))"), GetFullName(), Tell() )); } }; /*---------------------------------------------------------------------------- ULinkerSave. ----------------------------------------------------------------------------*/ // // A file saver. // class ULinkerSave : public ULinker, public FArchive { DECLARE_CLASS(ULinkerSave,ULinker,CLASS_Transient); NO_DEFAULT_CONSTRUCTOR(ULinkerSave); // Variables. FArchive* Saver; TArray<INT> ObjectIndices; TArray<INT> NameIndices; // Constructor. ULinkerSave( UObject* InParent, const TCHAR* InFilename ) : ULinker( InParent, InFilename ) , Saver( NULL ) { // Create file saver. Saver = GFileManager->CreateFileWriter( InFilename, 0, GThrow ); if( !Saver ) appThrowf( LocalizeError("OpenFailed") ); // Set main summary info. Summary.Tag = PACKAGE_FILE_TAG; Summary.FileVersion = PACKAGE_FILE_VERSION; Summary.PackageFlags = Cast<UPackage>(LinkerRoot) ? Cast<UPackage>(LinkerRoot)->PackageFlags : 0; // Set status info. ArIsSaving = 1; ArIsPersistent = 1; ArForEdit = GIsEditor; ArForClient = 1; ArForServer = 1; // Allocate indices. ObjectIndices.AddZeroed( UObject::GObjObjects.Num() ); NameIndices .AddZeroed( FName::GetMaxNames() ); // Success. Success=1; } void Destroy() { guard(ULinkerSave::Destroy); if( Saver ) delete Saver; Saver = NULL; Super::Destroy(); unguard; } // FArchive interface. INT MapName( FName* Name ) { guardSlow(ULinkerSave::MapName); return NameIndices(Name->GetIndex()); unguardobjSlow; } INT MapObject( UObject* Object ) { guardSlow(ULinkerSave::MapObject); return Object ? ObjectIndices(Object->GetIndex()) : 0; unguardobjSlow; } // FArchive interface. FArchive& operator<<( FName& Name ) { guardSlow(ULinkerSave<<FName); INT Save = NameIndices(Name.GetIndex()); return *this << AR_INDEX(Save); unguardobjSlow; } FArchive& operator<<( UObject*& Obj ) { guardSlow(ULinkerSave<<UObject); INT Save = Obj ? ObjectIndices(Obj->GetIndex()) : 0; return *this << AR_INDEX(Save); unguardobjSlow; } void Seek( INT InPos ) { Saver->Seek( InPos ); } INT Tell() { return Saver->Tell(); } void Serialize( void* V, INT Length ) { Saver->Serialize( V, Length ); } }; /*---------------------------------------------------------------------------- The End. ----------------------------------------------------------------------------*/
412
0.948131
1
0.948131
game-dev
MEDIA
0.559303
game-dev,compilers-parsers
0.963088
1
0.963088
Golle/Titan
4,333
src/Titan/Systems/Scheduler/Executors/OrderedExecutor.cs
using System.Runtime.CompilerServices; using Titan.Jobs; namespace Titan.Systems.Scheduler.Executors; file enum SystemState { Waiting, Running, Completed } internal readonly struct OrderedExecutor : ISystemsExecutor { [SkipLocalsInit] [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static unsafe void Execute(IJobApi jobApi, SystemNode* nodes, int count) { if (count == 0) { return; } var states = stackalloc SystemState[count]; var handles = stackalloc JobHandle[count]; var systemsLeft = count; // The initial setup and execute some systems for (var index = 0; index < count; ++index) { ref var node = ref nodes[index]; var shouldRun = node.Criteria switch { RunCriteria.Always or RunCriteria.AlwaysInline => true, RunCriteria.Check or RunCriteria.CheckInline => node.ShouldRun(), RunCriteria.Once or _ => throw new NotImplementedException($"The {node.Criteria} has not been implemented yet."), }; if (shouldRun) { // the system have no dependencies, just start it. if (node.DependenciesCount == 0) { // Inline systems, just run them if (node.Criteria is RunCriteria.CheckInline or RunCriteria.AlwaysInline) { node.Update(); states[index] = SystemState.Completed; handles[index] = JobHandle.Invalid; systemsLeft--; } else { handles[index] = jobApi.Enqueue(JobItem.Create(node.Context, node.UpdateFunc, true, false)); states[index] = SystemState.Running; } } else { // the system has dependencies, put it in waiting stage (we should check the dependencies here, but might be unnecessary) states[index] = SystemState.Waiting; handles[index] = JobHandle.Invalid; } } else { // the system is marked as should not run, set it to completed and decrement the counter systemsLeft--; states[index] = SystemState.Completed; handles[index] = JobHandle.Invalid; } } while (systemsLeft > 0) { for (var index = 0; index < count; ++index) { // update the job handle ref var jobHandle = ref handles[index]; if (jobHandle.IsValid() && jobApi.IsCompleted(jobHandle)) { jobApi.Reset(ref jobHandle); states[index] = SystemState.Completed; systemsLeft--; } // if the system is not in a Waiting state, move to next. if (states[index] != SystemState.Waiting) { continue; } ref var node = ref nodes[index]; if (!IsReady(node, states)) { continue; } if (node.Criteria is RunCriteria.CheckInline or RunCriteria.AlwaysInline) { node.Update(); states[index] = SystemState.Completed; systemsLeft--; } else { handles[index] = jobApi.Enqueue(JobItem.Create(node.Context, node.UpdateFunc, true, false)); states[index] = SystemState.Running; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool IsReady(in SystemNode node, SystemState* states) { for (var i = 0; i < node.DependenciesCount; ++i) { if (states[node.Dependencies[i]] != SystemState.Completed) { return false; } } return true; } } }
412
0.911871
1
0.911871
game-dev
MEDIA
0.26663
game-dev
0.777836
1
0.777836
filoghost/ChestCommands
1,297
plugin/src/main/java/me/filoghost/chestcommands/parsing/menu/MenuOpenItem.java
/* * Copyright (C) filoghost and contributors * * SPDX-License-Identifier: GPL-3.0-or-later */ package me.filoghost.chestcommands.parsing.menu; import me.filoghost.fcommons.Preconditions; import org.bukkit.Material; import org.bukkit.event.block.Action; import org.bukkit.inventory.ItemStack; public class MenuOpenItem { private final Material material; private final ClickType clickType; private short durability; private boolean isRestrictiveDurability; public MenuOpenItem(Material material, ClickType clickType) { Preconditions.checkArgumentNotAir(material, "material"); Preconditions.notNull(clickType, "clickType"); this.material = material; this.clickType = clickType; } public void setRestrictiveDurability(short durability) { this.durability = durability; this.isRestrictiveDurability = true; } public boolean matches(ItemStack item, Action action) { if (item == null) { return false; } if (this.material != item.getType()) { return false; } if (isRestrictiveDurability && this.durability != item.getDurability()) { return false; } return clickType.isValidInteract(action); } }
412
0.605039
1
0.605039
game-dev
MEDIA
0.955355
game-dev
0.524194
1
0.524194
magefree/mage
3,308
Mage.Sets/src/mage/cards/n/NotionThief.java
package mage.cards.n; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.keyword.FlashAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.PhaseStep; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; import mage.players.Player; import mage.watchers.common.CardsDrawnDuringDrawStepWatcher; /** * * @author LevelX2 */ public final class NotionThief extends CardImpl { public NotionThief(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{U}{B}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.ROGUE); this.power = new MageInt(3); this.toughness = new MageInt(1); // Flash this.addAbility(FlashAbility.getInstance()); // If an opponent would draw a card except the first one they draw in each of their draw steps, instead that player skips that draw and you draw a card. this.addAbility(new SimpleStaticAbility(new NotionThiefReplacementEffect()), new CardsDrawnDuringDrawStepWatcher()); } private NotionThief(final NotionThief card) { super(card); } @Override public NotionThief copy() { return new NotionThief(this); } } class NotionThiefReplacementEffect extends ReplacementEffectImpl { NotionThiefReplacementEffect() { super(Duration.WhileOnBattlefield, Outcome.Benefit); staticText = "If an opponent would draw a card except the first one they draw in each of their draw steps, instead that player skips that draw and you draw a card"; } private NotionThiefReplacementEffect(final NotionThiefReplacementEffect effect) { super(effect); } @Override public NotionThiefReplacementEffect copy() { return new NotionThiefReplacementEffect(this); } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { Player player = game.getPlayer(source.getControllerId()); if (player != null) { player.drawCards(1, source, game, event); } return true; } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DRAW_CARD; } @Override public boolean applies(GameEvent event, Ability source, Game game) { if (game.getOpponents(source.getControllerId()).contains(event.getPlayerId())) { if (game.isActivePlayer(event.getPlayerId()) && game.getTurnStepType() == PhaseStep.DRAW) { CardsDrawnDuringDrawStepWatcher watcher = game.getState().getWatcher(CardsDrawnDuringDrawStepWatcher.class); if (watcher != null && watcher.getAmountCardsDrawn(event.getPlayerId()) > 0) { return true; } } else { // not an opponents players draw step, always replace the draw return true; } } return false; } }
412
0.982262
1
0.982262
game-dev
MEDIA
0.973418
game-dev
0.996621
1
0.996621
Waterdish/Shipwright-Android
15,811
soh/soh/Enhancements/randomizer/randomizer_check_objects.cpp
#include "randomizer_check_objects.h" #include "static_data.h" #include "context.h" #include <map> #include <string> #include <libultraship/bridge.h> #include "z64.h" #include "soh/OTRGlobals.h" #include "soh/cvar_prefixes.h" #include "fishsanity.h" std::map<RandomizerCheckArea, std::string> rcAreaNames = { { RCAREA_KOKIRI_FOREST, "Kokiri Forest" }, { RCAREA_LOST_WOODS, "Lost Woods" }, { RCAREA_SACRED_FOREST_MEADOW, "Sacred Forest Meadow" }, { RCAREA_HYRULE_FIELD, "Hyrule Field" }, { RCAREA_LAKE_HYLIA, "Lake Hylia" }, { RCAREA_GERUDO_VALLEY, "Gerudo Valley" }, { RCAREA_GERUDO_FORTRESS, "Gerudo Fortress" }, { RCAREA_WASTELAND, "Haunted Wasteland" }, { RCAREA_DESERT_COLOSSUS, "Desert Colossus" }, { RCAREA_MARKET, "Hyrule Market" }, { RCAREA_HYRULE_CASTLE, "Hyrule Castle" }, { RCAREA_KAKARIKO_VILLAGE, "Kakariko Village" }, { RCAREA_GRAVEYARD, "Graveyard" }, { RCAREA_DEATH_MOUNTAIN_TRAIL, "Death Mountain Trail" }, { RCAREA_GORON_CITY, "Goron City" }, { RCAREA_DEATH_MOUNTAIN_CRATER, "Death Mountain Crater" }, { RCAREA_ZORAS_RIVER, "Zora's River" }, { RCAREA_ZORAS_DOMAIN, "Zora's Domain" }, { RCAREA_ZORAS_FOUNTAIN, "Zora's Fountain" }, { RCAREA_LON_LON_RANCH, "Lon Lon Ranch" }, { RCAREA_DEKU_TREE, "Deku Tree" }, { RCAREA_DODONGOS_CAVERN, "Dodongo's Cavern" }, { RCAREA_JABU_JABUS_BELLY, "Jabu Jabu's Belly" }, { RCAREA_FOREST_TEMPLE, "Forest Temple" }, { RCAREA_FIRE_TEMPLE, "Fire Temple" }, { RCAREA_WATER_TEMPLE, "Water Temple" }, { RCAREA_SPIRIT_TEMPLE, "Spirit Temple" }, { RCAREA_SHADOW_TEMPLE, "Shadow Temple" }, { RCAREA_BOTTOM_OF_THE_WELL, "Bottom of the Well" }, { RCAREA_ICE_CAVERN, "Ice Cavern" }, { RCAREA_GERUDO_TRAINING_GROUND, "Gerudo Training Ground" }, { RCAREA_GANONS_CASTLE, "Ganon's Castle" }, { RCAREA_INVALID, "Invalid" }, }; std::map<RandomizerCheckArea, std::vector<RandomizerCheck>> rcObjectsByArea = {}; std::map<RandomizerCheckArea, std::vector<RandomizerCheck>> RandomizerCheckObjects::GetAllRCObjectsByArea() { if (rcObjectsByArea.size() == 0) { for (auto& location : Rando::StaticData::GetLocationTable()) { // There are some RCs that don't have checks implemented yet, prevent adding these to the map. if (location.GetRandomizerCheck() != RC_UNKNOWN_CHECK) { rcObjectsByArea[location.GetArea()].push_back(location.GetRandomizerCheck()); } } } return rcObjectsByArea; } bool RandomizerCheckObjects::AreaIsDungeon(RandomizerCheckArea area) { return area == RCAREA_GANONS_CASTLE || area == RCAREA_GERUDO_TRAINING_GROUND || area == RCAREA_ICE_CAVERN || area == RCAREA_BOTTOM_OF_THE_WELL || area == RCAREA_SHADOW_TEMPLE || area == RCAREA_SPIRIT_TEMPLE || area == RCAREA_WATER_TEMPLE || area == RCAREA_FIRE_TEMPLE || area == RCAREA_FOREST_TEMPLE || area == RCAREA_JABU_JABUS_BELLY || area == RCAREA_DODONGOS_CAVERN || area == RCAREA_DEKU_TREE; } bool RandomizerCheckObjects::AreaIsOverworld(RandomizerCheckArea area) { return !AreaIsDungeon(area); } std::string RandomizerCheckObjects::GetRCAreaName(RandomizerCheckArea area) { return rcAreaNames[area]; } std::map<SceneID, RandomizerCheckArea> rcAreaBySceneID = {}; std::map<SceneID, RandomizerCheckArea> RandomizerCheckObjects::GetAllRCAreaBySceneID() { // memoize on first request if (rcAreaBySceneID.size() == 0) { for (auto& location : Rando::StaticData::GetLocationTable()) { // There are some RCs that don't have checks implemented yet, prevent adding these to the map. if (location.GetRandomizerCheck() != RC_UNKNOWN_CHECK) { rcAreaBySceneID[location.GetScene()] = location.GetArea(); } } // Add checkless Hyrule Market areas to the area return for (int id = (int)SCENE_MARKET_ENTRANCE_DAY; id <= (int)SCENE_MARKET_RUINS; id++) { rcAreaBySceneID[(SceneID)id] = RCAREA_MARKET; } rcAreaBySceneID[SCENE_TEMPLE_OF_TIME] = RCAREA_MARKET; rcAreaBySceneID[SCENE_CASTLE_COURTYARD_GUARDS_DAY] = RCAREA_HYRULE_CASTLE; rcAreaBySceneID[SCENE_CASTLE_COURTYARD_GUARDS_NIGHT] = RCAREA_HYRULE_CASTLE; } return rcAreaBySceneID; } RandomizerCheckArea RandomizerCheckObjects::GetRCAreaBySceneID(SceneID sceneId) { std::map<SceneID, RandomizerCheckArea> areas = GetAllRCAreaBySceneID(); auto areaIt = areas.find(sceneId); if (areaIt == areas.end()) return RCAREA_INVALID; else return areaIt->second; } void RandomizerCheckObjects::UpdateImGuiVisibility() { auto ctx = Rando::Context::GetInstance(); for (auto& location : Rando::StaticData::GetLocationTable()) { auto itemLoc = ctx->GetItemLocation(location.GetRandomizerCheck()); itemLoc->SetVisible( (location.GetRandomizerCheck() != RC_UNKNOWN_CHECK) && (location.GetQuest() == RCQUEST_BOTH || location.GetQuest() == RCQUEST_MQ && ((CVarGetInteger(CVAR_RANDOMIZER_SETTING("MQDungeons"), RO_MQ_DUNGEONS_NONE) == RO_MQ_DUNGEONS_SET_NUMBER && (CVarGetInteger(CVAR_RANDOMIZER_SETTING("MQDungeonCount"), 12) > 0) || // at least one MQ dungeon CVarGetInteger(CVAR_RANDOMIZER_SETTING("MQDungeons"), RO_MQ_DUNGEONS_NONE) == RO_MQ_DUNGEONS_RANDOM_NUMBER)) || location.GetQuest() == RCQUEST_VANILLA && (CVarGetInteger(CVAR_RANDOMIZER_SETTING("MQDungeons"), RO_MQ_DUNGEONS_NONE) != RO_MQ_DUNGEONS_SET_NUMBER || CVarGetInteger(CVAR_RANDOMIZER_SETTING("MQDungeonCount"), 12) < 12) // at least one vanilla dungeon ) && (location.GetRCType() != RCTYPE_SHOP || !(ctx->GetOption(RSK_SHOPSANITY).Is(RO_SHOPSANITY_OFF) || (ctx->GetOption(RSK_SHOPSANITY).Is(RO_SHOPSANITY_SPECIFIC_COUNT) && ctx->GetOption(RSK_SHOPSANITY_COUNT).Is(RO_SHOPSANITY_COUNT_ZERO_ITEMS)))) && (location.GetRCType() != RCTYPE_SCRUB || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleScrubs"), RO_SCRUBS_OFF) != RO_SCRUBS_OFF || location.GetRandomizerCheck() == RC_HF_DEKU_SCRUB_GROTTO || location.GetRandomizerCheck() == RC_LW_DEKU_SCRUB_GROTTO_FRONT || location.GetRandomizerCheck() == RC_LW_DEKU_SCRUB_NEAR_BRIDGE) && // The 3 scrubs that are always randomized (location.GetRCType() != RCTYPE_MERCHANT || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleMerchants"), RO_SHUFFLE_MERCHANTS_OFF) != RO_SHUFFLE_MERCHANTS_OFF) && (location.GetRCType() != RCTYPE_SONG_LOCATION || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleSongs"), RO_SONG_SHUFFLE_SONG_LOCATIONS) != RO_SONG_SHUFFLE_SONG_LOCATIONS) && // song locations ((location.GetRCType() != RCTYPE_BOSS_HEART_OR_OTHER_REWARD && location.GetRandomizerCheck() != RC_SONG_FROM_IMPA && location.GetRandomizerCheck() != RC_SHEIK_IN_ICE_CAVERN) || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleSongs"), RO_SONG_SHUFFLE_SONG_LOCATIONS) != RO_SONG_SHUFFLE_DUNGEON_REWARDS) && // song dungeon rewards (location.GetRCType() != RCTYPE_DUNGEON_REWARD || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleDungeonReward"), RO_DUNGEON_REWARDS_END_OF_DUNGEON) != RO_DUNGEON_REWARDS_END_OF_DUNGEON) && // dungeon rewards end of dungeons (location.GetRCType() != RCTYPE_OCARINA || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleOcarinas"), RO_GENERIC_NO)) && // ocarina locations (location.GetRandomizerCheck() != RC_HC_ZELDAS_LETTER) && // don't show until we support shuffling letter (location.GetRCType() != RCTYPE_GOSSIP_STONE) && // don't show gossip stones (maybe gossipsanity will be a thing eventually?) (location.GetRCType() != RCTYPE_STATIC_HINT) && // don't show static hints (location.GetRCType() != RCTYPE_LINKS_POCKET) && // links pocket can be set to nothing if needed (location.GetRCType() != RCTYPE_CHEST_GAME) && // don't show non final reward chest game checks until we support shuffling them (location.GetRCType() != RCTYPE_SKULL_TOKEN || (CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleTokens"), RO_TOKENSANITY_OFF) == RO_TOKENSANITY_ALL) || ((CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleTokens"), RO_TOKENSANITY_OFF) == RO_TOKENSANITY_OVERWORLD) && RandomizerCheckObjects::AreaIsOverworld(location.GetArea())) || ((CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleTokens"), RO_TOKENSANITY_OFF) == RO_TOKENSANITY_DUNGEONS) && RandomizerCheckObjects::AreaIsDungeon(location.GetArea()))) && (location.GetRCType() != RCTYPE_FREESTANDING || (CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleFreestanding"), RO_SHUFFLE_FREESTANDING_OFF) == RO_SHUFFLE_FREESTANDING_ALL) || ((CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleFreestanding"), RO_SHUFFLE_FREESTANDING_OFF) == RO_SHUFFLE_FREESTANDING_OVERWORLD) && RandomizerCheckObjects::AreaIsOverworld(location.GetArea())) || ((CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleFreestanding"), RO_SHUFFLE_FREESTANDING_OFF) == RO_SHUFFLE_FREESTANDING_DUNGEONS) && RandomizerCheckObjects::AreaIsDungeon(location.GetArea()))) && (location.GetRCType() != RCTYPE_BEEHIVE || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleBeehives"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_COW || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleCows"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_POT || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShufflePots"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_GRASS || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGrass"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_CRATE || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleCrates"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_NLCRATE || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleCrates"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_SMALL_CRATE || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleCrates"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_FISH || ctx->GetFishsanity()->GetFishLocationIncluded(&location, FSO_SOURCE_CVARS)) && (location.GetRCType() != RCTYPE_ADULT_TRADE || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleAdultTrade"), RO_GENERIC_NO)) && (location.GetRandomizerCheck() != RC_KF_KOKIRI_SWORD_CHEST || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleKokiriSword"), RO_GENERIC_NO)) && (location.GetRandomizerCheck() != RC_LH_HYRULE_LOACH || CVarGetInteger(CVAR_RANDOMIZER_SETTING("Fishsanity"), RO_GENERIC_NO) == RO_FISHSANITY_HYRULE_LOACH) && (location.GetRandomizerCheck() != RC_ZR_MAGIC_BEAN_SALESMAN || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleMerchants"), RO_SHUFFLE_MERCHANTS_OFF) % 2) && (location.GetRandomizerCheck() != RC_HC_MALON_EGG || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleWeirdEgg"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_FROG_SONG || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleFrogSongRupees"), RO_GENERIC_NO)) && (location.GetRCType() != RCTYPE_FAIRY || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleFairies"), RO_GENERIC_NO)) && ((location.GetRCType() != RCTYPE_MAP && location.GetRCType() != RCTYPE_COMPASS) || CVarGetInteger(CVAR_RANDOMIZER_SETTING("StartingMapsCompasses"), RO_DUNGEON_ITEM_LOC_OWN_DUNGEON) != RO_DUNGEON_ITEM_LOC_VANILLA) && (location.GetRCType() != RCTYPE_SMALL_KEY || CVarGetInteger(CVAR_RANDOMIZER_SETTING("Keysanity"), RO_DUNGEON_ITEM_LOC_OWN_DUNGEON) != RO_DUNGEON_ITEM_LOC_VANILLA) && (location.GetRCType() != RCTYPE_BOSS_KEY || CVarGetInteger(CVAR_RANDOMIZER_SETTING("BossKeysanity"), RO_DUNGEON_ITEM_LOC_OWN_DUNGEON) != RO_DUNGEON_ITEM_LOC_VANILLA) && (location.GetRCType() != RCTYPE_GANON_BOSS_KEY || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_VANILLA) && // vanilla ganon boss key (location.GetRandomizerCheck() != RC_TOT_LIGHT_ARROWS_CUTSCENE || (CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_LACS_DUNGEONS && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_LACS_MEDALLIONS && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_LACS_REWARDS && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_LACS_STONES && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_LACS_TOKENS && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_LACS_VANILLA)) && // LACS ganon boss key (location.GetRandomizerCheck() != RC_KAK_100_GOLD_SKULLTULA_REWARD || CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGanonBossKey"), RO_GANON_BOSS_KEY_VANILLA) != RO_GANON_BOSS_KEY_KAK_TOKENS) && // 100 skull reward ganon boss key (location.GetRCType() != RCTYPE_GF_KEY && location.GetRandomizerCheck() != RC_GF_GERUDO_MEMBERSHIP_CARD || (CVarGetInteger(CVAR_RANDOMIZER_SETTING("FortressCarpenters"), RO_GF_CARPENTERS_NORMAL) == RO_GF_CARPENTERS_FREE && location.GetRCType() != RCTYPE_GF_KEY && location.GetRandomizerCheck() != RC_GF_GERUDO_MEMBERSHIP_CARD) || (CVarGetInteger(CVAR_RANDOMIZER_SETTING("FortressCarpenters"), RO_GF_CARPENTERS_NORMAL) == RO_GF_CARPENTERS_FAST && ((location.GetRandomizerCheck() == RC_GF_GERUDO_MEMBERSHIP_CARD && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGerudoToken"), RO_GENERIC_NO) == RO_GENERIC_YES) || (location.GetRandomizerCheck() == RC_GF_NORTH_F1_CARPENTER && CVarGetInteger(CVAR_RANDOMIZER_SETTING("GerudoKeys"), RO_GERUDO_KEYS_VANILLA) != RO_GERUDO_KEYS_VANILLA))) || (CVarGetInteger(CVAR_RANDOMIZER_SETTING("FortressCarpenters"), RO_GF_CARPENTERS_NORMAL) == RO_GF_CARPENTERS_NORMAL && ((location.GetRandomizerCheck() == RC_GF_GERUDO_MEMBERSHIP_CARD && CVarGetInteger(CVAR_RANDOMIZER_SETTING("ShuffleGerudoToken"), RO_GENERIC_NO) == RO_GENERIC_YES) || (location.GetRCType() == RCTYPE_GF_KEY && CVarGetInteger(CVAR_RANDOMIZER_SETTING("GerudoKeys"), RO_GERUDO_KEYS_VANILLA) != RO_GERUDO_KEYS_VANILLA))))); } }
412
0.916992
1
0.916992
game-dev
MEDIA
0.882197
game-dev,testing-qa
0.992332
1
0.992332
Soapwood/VXMusic
9,038
VXMusicOverlay/Library/PackageCache/com.unity.timeline@1.4.8/Editor/TimelineEditor.cs
using System; using System.Collections.Generic; using System.Linq; using UnityEditor.Timeline.Actions; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; namespace UnityEditor.Timeline { /// <summary> /// Information currently being edited in the Timeline Editor Window. /// </summary> public static class TimelineEditor { /// <summary> /// The PlayableDirector associated with the timeline currently being shown in the Timeline window. /// </summary> public static PlayableDirector inspectedDirector => state?.editSequence.director; /// <summary> /// The PlayableDirector responsible for the playback of the timeline currently being shown in the Timeline window. /// </summary> public static PlayableDirector masterDirector => state?.masterSequence.director; /// <summary> /// The TimelineAsset currently being shown in the Timeline window. /// </summary> public static TimelineAsset inspectedAsset => state?.editSequence.asset; /// <summary> /// The TimelineAsset at the root of the hierarchy currently being shown in the Timeline window. /// </summary> public static TimelineAsset masterAsset => state?.masterSequence.asset; /// <summary> /// The PlayableDirector currently being shown in the Timeline Editor Window. /// </summary> [Obsolete("playableDirector is ambiguous. Please select either inspectedDirector or masterDirector instead.", false)] public static PlayableDirector playableDirector { get { return inspectedDirector; } } /// <summary> /// The TimelineAsset currently being shown in the Timeline Editor Window. /// </summary> [Obsolete("timelineAsset is ambiguous. Please select either inspectedAsset or masterAsset instead.", false)] public static TimelineAsset timelineAsset { get { return inspectedAsset; } } /// <summary> /// <para> /// Refreshes the different components affected by the currently inspected /// <see cref="UnityEngine.Timeline.TimelineAsset"/>, based on the <see cref="RefreshReason"/> provided. /// </para> /// <para> /// For better performance, it is recommended that you invoke this method once, after you modify the /// <see cref="UnityEngine.Timeline.TimelineAsset"/>. You should also combine reasons using the <c>|</c> operator. /// </para> /// </summary> /// <remarks> /// Note: This operation is not synchronous. It is performed during the next GUI loop. /// </remarks> /// <param name="reason">The reason why a refresh should be performed.</param> public static void Refresh(RefreshReason reason) { if (state == null) return; if ((reason & RefreshReason.ContentsAddedOrRemoved) != 0) { state.Refresh(); } else if ((reason & RefreshReason.ContentsModified) != 0) { state.rebuildGraph = true; } else if ((reason & RefreshReason.SceneNeedsUpdate) != 0) { state.Evaluate(); } window.Repaint(); } internal static TimelineWindow window => TimelineWindow.instance; internal static WindowState state => window == null ? null : window.state; internal static readonly Clipboard clipboard = new Clipboard(); /// <summary> /// The list of clips selected in the TimelineEditor. /// </summary> public static TimelineClip[] selectedClips { get { return Selection.GetFiltered<EditorClip>(SelectionMode.Unfiltered).Select(e => e.clip).Where(x => x != null).ToArray(); } set { if (value == null || value.Length == 0) { Selection.objects = null; } else { var objects = new List<UnityEngine.Object>(); foreach (var clip in value) { if (clip == null) continue; var editorClip = EditorClipFactory.GetEditorClip(clip); if (editorClip != null) objects.Add(editorClip); } Selection.objects = objects.ToArray(); } } } /// <summary> /// The clip selected in the TimelineEditor. /// </summary> /// <remarks> /// If there are multiple clips selected, this property returns the first clip. /// </remarks> public static TimelineClip selectedClip { get { var editorClip = Selection.activeObject as EditorClip; if (editorClip != null) return editorClip.clip; return null; } set { var editorClip = (value != null) ? EditorClipFactory.GetEditorClip(value) : null; Selection.activeObject = editorClip; } } /// <summary> /// Local time (in seconds) of the inspected sequence. /// </summary> /// <exception cref="InvalidOperationException">Thrown if timeline window is not available.</exception> internal static double inspectedSequenceTime { get => state?.editSequence.time ?? 0; set { if (state == null) throw new InvalidOperationException("Cannot set time. Timeline Window may not be available."); state.editSequence.time = value; } } /// <summary> /// Global time (in seconds) of the master timeline. /// Same as local time if not inspected a subtimeline. /// </summary> /// <exception cref="InvalidOperationException">Thrown if timeline window is not available.</exception> internal static double masterSequenceTime { get => state?.editSequence.ToGlobalTime(state.editSequence.time) ?? 0; set { if (state == null) throw new InvalidOperationException("Cannot set time. Timeline Window may not be available."); state.masterSequence.time = value; } } /// <summary> /// Visible time range (in seconds) in Editor. /// x : min time /// y : max time /// </summary> /// <exception cref="InvalidOperationException">Thrown if timeline window is not available.</exception> internal static Vector2 visibleTimeRange { get => state?.timeAreaShownRange ?? TimelineAssetViewModel.TimeAreaDefaultRange; set { if (state == null) throw new InvalidOperationException("Cannot set visible time range. Timeline Window may not be available."); state.timeAreaShownRange = value; } } internal static ActionContext CurrentContext(Vector2? mousePos = null) { return new ActionContext { invocationTime = mousePos != null ? TimelineHelpers.GetCandidateTime(mousePos) : (double?)null, clips = SelectionManager.SelectedClips(), tracks = SelectionManager.SelectedTracks(), markers = SelectionManager.SelectedMarkers(), timeline = inspectedAsset, director = inspectedDirector }; } } /// <summary> /// <see cref="TimelineEditor.Refresh"/> uses these flags to determine what needs to be refreshed or updated. /// </summary> /// <remarks> /// Use the <c>|</c> operator to combine flags. /// <example> /// <code source="../DocCodeExamples/TimelineEditorExamples.cs" region="declare-refreshReason" title="refreshReason"/> /// </example> /// </remarks> [Flags] public enum RefreshReason { /// <summary> /// Use this flag when a change to the Timeline requires that the Timeline window be redrawn. /// </summary> WindowNeedsRedraw = 1 << 0, /// <summary> /// Use this flag when a change to the Timeline requires that the Scene be updated. /// </summary> SceneNeedsUpdate = 1 << 1, /// <summary> /// Use this flag when a Timeline element was modified. /// </summary> ContentsModified = 1 << 2, /// <summary> /// Use this flag when an element was added to or removed from the Timeline. /// </summary> ContentsAddedOrRemoved = 1 << 3 } }
412
0.827345
1
0.827345
game-dev
MEDIA
0.777809
game-dev,desktop-app
0.980489
1
0.980489
manny405/sapai
25,750
sapai/agents.py
# %% import os, json, itertools, torch import numpy as np from sapai import Player from sapai.battle import Battle from sapai.compress import compress, decompress ### Pets with a random component ### Random component in the future should just be handled in an exact way ### whereby all possible outcomes are evaluated just once. This would ### significantly speed up training. random_buy_pets = {"pet-otter"} random_sell_pets = {"pet-beaver"} random_pill_pets = {"pet-ant"} random_battle_pets = {"pet-mosquito"} class CombinatorialSearch: """ CombinatorialSearch is a method to enumerate the entire possible search space for the current shopping phase. The search starts from an initial player state provided in the arguments. Then all possible next actions are taken from that player state until the Player's gold is exhausted. Returned is a list of all final possible final player states after the shopping phase. This algorithm can be parallelized in the sense that after round 1, there will be a large number of player states. Each of these player states can then be fed back into the CombinatorialSearch individually to search for their round 2 possibilities. Therefore, parallelization can occur across the possible player states for each given round. This parallelization should take place outside of this Class. Parallelization within this Class itself would be a bit more difficult and would only be advantageous to improve the search speed when condering a single team. This would be better for run-time evaluation of models, but it unnecessary for larger searchers, which are the present focus. Therefore, this will be left until later. A CombinatorialAgent can be built on top of this to resemble the way that a human player will make decisions. However, the CombinatorialAgent will consider all possible combinations of decisions in order arrive at the best possible next decisions given the available gold. Arguments --------- verbose: bool If True, messages are printed during the search max_actions: int Maximum depth, equal to the number of shop actions, that can be performed during search space enumeration. Using max_actions of 1 would correspond to a greedy search algorithm in conjunction with any Agents. """ def __init__(self, verbose=True, max_actions=-1): self.verbose = verbose self.max_actions = max_actions ### This stores the player lists for performing all possible actions self.player_list = [] ### Player dict stores compressed str of all players such that if the ### same player state will never be used twice self.player_state_dict = {} self.current_print_number = 0 def avail_actions(self, player): """ Return all possible available actions """ action_list = [()] ### Include only the actions that cost gold action_list += self.avail_buy_pets(player) action_list += self.avail_buy_food(player) action_list += self.avail_buy_combine(player) action_list += self.avail_team_combine(player) action_list += self.avail_sell(player) action_list += self.avail_sell_buy(player) action_list += self.avail_roll(player) return action_list def avail_buy_pets(self, player): """ Returns all possible pets that can be bought from the player's shop """ action_list = [] gold = player.gold if len(player.team) == 5: ### Cannot buy for full team return action_list for shop_idx in player.shop.filled: shop_slot = player.shop[shop_idx] if shop_slot.slot_type == "pet": if shop_slot.cost <= gold: action_list.append((player.buy_pet, shop_idx)) return action_list def avail_buy_food(self, player): """ Returns all possible food that can be bought from the player's shop """ action_list = [] gold = player.gold if len(player.team) == 0: return action_list for shop_idx in player.shop.filled: shop_slot = player.shop[shop_idx] if shop_slot.slot_type == "food": if shop_slot.cost <= gold: for team_idx, team_slot in enumerate(player.team): if team_slot.empty: continue action_list.append((player.buy_food, shop_idx, team_idx)) return action_list def avail_buy_combine(self, player): action_list = [] gold = player.gold team_names = {} for team_idx, slot in enumerate(player.team): if slot.empty: continue if slot.pet.name not in team_names: team_names[slot.pet.name] = [] team_names[slot.pet.name].append(team_idx) if len(player.team) == 0: return action_list for shop_idx in player.shop.filled: shop_slot = player.shop[shop_idx] if shop_slot.slot_type == "pet": ### Can't combine if pet not already on team if shop_slot.obj.name not in team_names: continue if shop_slot.cost <= gold: for team_idx in team_names[shop_slot.obj.name]: action_list.append((player.buy_combine, shop_idx, team_idx)) return action_list def avail_team_combine(self, player): action_list = [] if len(player.team) == 0: return action_list team_names = {} for slot_idx, slot in enumerate(player.team): if slot.empty: continue if slot.pet.name not in team_names: team_names[slot.pet.name] = [] team_names[slot.pet.name].append(slot_idx) for key, value in team_names.items(): if len(value) == 1: continue for idx0, idx1 in itertools.combinations(value, r=2): action_list.append((player.combine, idx0, idx1)) return action_list def avail_sell(self, player): action_list = [] if len(player.team) <= 1: ### Not able to sell the final friend on team return action_list for team_idx, slot in enumerate(player.team): if slot.empty: continue action_list.append((player.sell, team_idx)) return action_list def avail_sell_buy(self, player): """ Sell buy should only be used if the team is full. This is done so that the search space is not increased unnecessarily. However, a full agent implementation can certainly consider this action at any point in the game as long as there are pets to sell and buy """ action_list = [] gold = player.gold if len(player.team) != 5: return action_list team_idx_list = player.team.get_fidx() shop_idx_list = [] for shop_idx in player.shop.filled: shop_slot = player.shop[shop_idx] if shop_slot.slot_type == "pet": if shop_slot.cost <= gold: shop_idx_list.append(shop_idx) prod = itertools.product(team_idx_list, shop_idx_list) for temp_team_idx, temp_shop_idx in prod: action_list.append((player.sell_buy, temp_team_idx, temp_shop_idx)) return action_list def avail_team_order(self, player): """Returns all possible orderings for the team""" action_list = [] team_range = np.arange(0, len(player.team)) if len(team_range) == 0: return [] for order in itertools.permutations(team_range, r=len(team_range)): action_list.append((player.reorder, order)) return action_list def avail_roll(self, player): action_list = [] ##### ASSUMPTION: If gold is not 1, do not roll for now because with ##### ShopLearn, rolling has no meaning if player.gold != 1: return action_list if player.gold > 0: action_list.append((player.roll,)) return action_list def search(self, player, player_state_dict=None): ### Initialize internal storage self.player = player self.player_list = [] self.player_state = self.player.state self.current_print_number = 0 self.print_message("start", self.player) ### build_player_list searches shop actions and returns player list ### In addition, it builds a player_state_dict which can be used for ### faster lookup of redundant player states if player_state_dict is None: self.player_state_dict = {} else: self.player_state_dict = player_state_dict self.player_list = self.build_player_list(self.player) self.print_message("player_list_done", self.player_list) ### Now consider all possible reorderings of team self.player_list, self.player_state_dict = self.search_reordering( self.player_list, self.player_state_dict ) ### End turn for all in player list for temp_player in self.player_list: temp_player.end_turn() ### NOTE: After end_turn the player_state_dict has not been updated, ### therefore, the player_state_dict is no longer reliable and should ### NOT be used outside of this Class. If the player_state_dict is ### required, it should be rebuilt from the player_list itself ### Also, return only the unique team list for convenience self.team_dict = self.get_team_dict(self.player_list) self.print_message("done", (self.player_list, self.team_dict)) return self.player_list, self.team_dict def build_player_list(self, player, player_list=None): """ Recursive function for building player list for a given turn using all actions during the shopping phase """ if player.gold <= 0: ### If gold is 0, then this is exit condition for the ### recursive function return [] if player_list is None: player_list = [] player_state = player.state self.print_message("size", self.player_state_dict) if self.max_actions > 0: actions_taken = len(player.action_history) if actions_taken >= self.max_actions: return [] avail_actions = self.avail_actions(player) for temp_action in avail_actions: if temp_action == (): ### Null action continue #### Re-initialize Player temp_player = Player.from_state(player_state) #### Perform action action_name = str(temp_action[0].__name__).split(".")[-1] action = getattr(temp_player, action_name) action(*temp_action[1:]) ### Check if this is unique player state temp_player.team.move_forward() ### Move team forward so that ### team is index invariant ### Don't need history in order to check for redundancy of the ### shop state. This means that it does not matter how a Shop ### gets to a state, just that the state is identical to others. cstate = compress(temp_player, minimal=True) # cstate = hash(json.dumps(temp_player.state)) if cstate not in self.player_state_dict: self.player_state_dict[cstate] = temp_player else: ### If player state has been seen before, then do not append ### to the player list. continue player_list.append(temp_player) full_player_list = player_list for player in player_list: ### Now, call this function recurisvely to add the next action temp_player_list = [] self.build_player_list(player, temp_player_list) full_player_list += temp_player_list return full_player_list def search_reordering(self, player_list, player_state_dict): """ Searches over all possible unique reorderings of the teams """ additional_player_list = [] for player in player_list: player_state = player.state reorder_actions = self.avail_team_order(player) for temp_action in reorder_actions: if temp_action == (): ### Null action continue #### Re-initialize identical Player temp_player = Player.from_state(player_state) #### Perform action action_name = str(temp_action[0].__name__).split(".")[-1] action = getattr(temp_player, action_name) action(*temp_action[1:]) ### Check if this is unique player state temp_player.team.move_forward() ### Move team forward so that ### team is index invariant ### Don't need history in order to check for redundancy of the ### shop state. This means that it does not matter how a Shop ### gets to a state, just that the state is identical to others. cstate = compress(temp_player, minimal=True) # cstate = hash(json.dumps(temp_player.state)) if cstate not in player_state_dict: player_state_dict[cstate] = temp_player else: ### If player state has been seen before, then do not append ### to the player list. continue additional_player_list.append(temp_player) ##### METHOD SHOULD BE USED THAT DOESN'T REQUIRE Player.from_state ##### This would save a lot of time # ### Move team back into place # order_idx = temp_action[1] # reorder_idx = np.argsort(order_idx).tolist() # action(reorder_idx) # ### Delete last two actions to reset player # del(temp_player.action_history[-1]) # del(temp_player.action_history[-1]) player_list += additional_player_list return player_list, player_state_dict def get_team_dict(self, player_list): """ Returns dictionary of only the unique teams """ team_dict = {} for player in player_list: team = player.team ### Move forward to make team index invariant team.move_forward() cteam = compress(team, minimal=True) ### Can just always do like this, don't need to check if it's ### already in dictionary because it can just be overwritten team_dict[cteam] = team return team_dict def print_message(self, message_type, info): if not self.verbose: return if message_type not in ["start", "size", "player_list_done", "done"]: raise Exception(f"Unrecognized message type {message_type}") if message_type == "start": print("---------------------------------------------------------") print("STARTING SEARCH WITH INITIAL PLAYER: ") print(info) print("---------------------------------------------------------") print("STARTING TO BUILD PLAYER LIST") elif message_type == "size": temp_size = len(info) if temp_size < (self.current_print_number + 100): return print(f"RUNNING MESSAGE: Current Number of Unique Players is {len(info)}") self.current_print_number = temp_size elif message_type == "player_list_done": print("---------------------------------------------------------") print("DONE BUILDING PLAYER LIST") print(f"NUMBER OF PLAYERS IN PLAYER LIST: {len(info)}") print("BEGINNING TO SEARCH FOR ALL POSSIBLE TEAM ORDERS") elif message_type == "done": print("---------------------------------------------------------") print("DONE WITH CombinatorialSearch") print(f"NUMBER OF PLAYERS IN PLAYER LIST: {len(info[0])}") print(f"NUMBER OF UNIQUE TEAMS: {len(info[1])}") class DatabaseLookupRanker: """ Will provide a rank to a given team based on its performance on a database of teams. """ def __init__( self, path="", ): self.path = path if os.path.exists(path): with open(path) as f: self.database = json.loads(f) else: self.database = {} self.team_database = {} for key, value in self.database: self.team_database[key] = { "team": decompress(key), "wins": int(len(self.database) * value), "total": len(self.database) - 1, } def __call__(self, team): c = compress(team) if c in self.database: return self.database[c] else: return self.run_against_database(team) def run_against_database(self, team): #### Add team to database team_key = compress(team, minimal=True) if team_key not in self.team_database: self.team_database[team_key] = {"team": team, "wins": 0, "total": 0} for key, value in self.team_database.items(): # print(team, value["team"]) self.t0 = team self.t1 = value["team"] f = Battle(team, value["team"]) winner = f.battle() winner_key = [[team_key], [key], []][winner] for temp_key in winner_key: self.team_database[temp_key]["wins"] += 1 for temp_key in [team_key, key]: self.team_database[temp_key]["total"] += 1 for key, value in self.team_database.items(): wins = self.team_database[key]["wins"] total = self.team_database[key]["total"] self.database[key] = wins / total wins = self.team_database[team_key]["wins"] total = self.team_database[team_key]["total"] return wins / total def test_against_database(self, team): wins = 0 total = 0 for key, value in self.team_database.items(): # print(team, value["team"]) f = Battle(team, value["team"]) winner = f.battle() if winner == 0: wins += 1 total += 1 return wins, total class PairwiseBattles: """ Parallel function using MPI for calculation Pairwise battles. Disadvantage of current method is that not check-pointing is done in the calculation. This means that the results will be written as all or nothing. If the calculation is interrupted before finishing, than all results will be lost. This is a common issue of simple parallelization... """ def __init__(self, output="results.pt"): try: from mpi4py import MPI parallel_check = True except: parallel_check = False if not parallel_check: raise Exception("MPI parallelization not available") self.comm = MPI.COMM_WORLD self.size = self.comm.Get_size() self.rank = self.comm.Get_rank() self.output = output def battle(self, obj): ### Prepare job-list on rank 0 if self.rank == 0: team_list = [] if type(obj) == dict: team_list += list(obj.values()) else: team_list += list(obj) if type(team_list[0]).__name__ != "Team": raise Exception("Input object is not Team Dict or Team List") print("------------------------------------", flush=True) print("RUNNING PAIRWISE BATTLES", flush=True) print(f"{'NUM':16s}: NUMBER", flush=True) print(f"{'NUM RANKS':16s}: {self.size}", flush=True) print(f"{'INPUT TEAMS':16s}: {len(obj)}", flush=True) ### Easier for indexing team_array = np.zeros((len(team_list),), dtype=object) team_array[:] = team_list[:] pair_idx = self._get_pair_idx(team_list) print(f"{'NUMBER BATTLES':16s}: {len(pair_idx)}", flush=True) ### Should I send just index and read in files on all ranks... ### or should Teams be sent to ranks... ### Well, I don't think this function will every have >2 GB sized ### team dataset anyways... for temp_rank in np.arange(1, self.size): temp_idx = pair_idx[temp_rank :: self.size] temp_teams = np.take(team_array, temp_idx) self.comm.send((temp_idx, temp_teams), temp_rank) my_idx = pair_idx[0 :: self.size] my_teams = np.take(team_array, my_idx) print(f"{'BATTLES PER RANK':16s}: {len(my_teams)}", flush=True) else: ### Wait for info from rank 0 my_idx, my_teams = self.comm.recv(source=0) if self.rank != 0: winner_list = [] iter_idx = 0 for t0, t1 in my_teams: b = Battle(t0, t1) temp_winner = b.battle() winner_list.append(temp_winner) iter_idx += 1 else: #### This is split to remove branching code in the for loop above winner_list = [] iter_idx = 0 for t0, t1 in my_teams: b = Battle(t0, t1) temp_winner = b.battle() winner_list.append(temp_winner) iter_idx += 1 if iter_idx % 1000 == 0: print( f"{'FINISHED':16s}: {iter_idx * self.size} of {len(pair_idx)}", flush=True, ) winner_list = np.array(winner_list).astype(int) ### Send results back to rank 0 self.comm.barrier() if self.rank == 0: print("------------------------------------", flush=True) print("DONE CALCULATING BATTLES", flush=True) ### Using +1 so that the last entry in the array can be used as ### as throw-away when draws occur wins = np.zeros((len(team_array) + 1,)).astype(int) total = np.zeros((len(team_array) + 1,)).astype(int) ### Add info from rank 0 add_totals_idx, add_totals = np.unique(my_idx[:, 0], return_counts=True) total[add_totals_idx] += add_totals add_totals_idx, add_totals = np.unique(my_idx[:, 1], return_counts=True) total[add_totals_idx] += add_totals ### Use for fast indexing for counting up wins temp_draw_idx = np.zeros((len(my_idx),)) - 1 winner_idx_mask = np.hstack([my_idx, temp_draw_idx[:, None]]) winner_idx_mask = winner_idx_mask.astype(int) winner_idx = winner_idx_mask[np.arange(0, len(winner_list)), winner_list] winner_idx, win_count = np.unique(winner_idx, return_counts=True) wins[winner_idx] += win_count for temp_rank in np.arange(1, self.size): temp_idx, temp_winner_list = self.comm.recv(source=temp_rank) add_totals_idx, add_totals = np.unique( temp_idx[:, 0], return_counts=True ) total[add_totals_idx] += add_totals add_totals_idx, add_totals = np.unique( temp_idx[:, 1], return_counts=True ) total[add_totals_idx] += add_totals ### Use for fast indexing for counting up wins temp_draw_idx = np.zeros((len(temp_idx),)) - 1 winner_idx_mask = np.hstack([temp_idx, temp_draw_idx[:, None]]) winner_idx_mask = winner_idx_mask.astype(int) winner_idx = winner_idx_mask[ np.arange(0, len(temp_winner_list)), temp_winner_list ] winner_idx, win_count = np.unique(winner_idx, return_counts=True) wins[winner_idx] += win_count ### Throw away last entry for ties wins = wins[0:-1] total = total[0:-1] frac = wins / total results = {} for iter_idx, temp_team in enumerate(team_list): temp_frac = frac[iter_idx] results[compress(temp_team, minimal=True)] = temp_frac print(f"WRITING OUTPUTS AT: {self.output}", flush=True) torch.save(results, self.output) print("------------------------------------", flush=True) print("COMPLETED", flush=True) else: self.comm.send((my_idx, winner_list), 0) ### Barrier before exiting self.comm.barrier() return def _get_pair_idx(self, team_list): """ Get the dictionary of pair_dict that have to be made for pair mode esxecution. """ idx = np.triu_indices(n=len(team_list), k=1, m=len(team_list)) return np.array([x for x in zip(idx[0], idx[1])]) # %%
412
0.649864
1
0.649864
game-dev
MEDIA
0.596778
game-dev
0.869694
1
0.869694
hankmorgan/UnderworldExporter
22,596
UnityScripts/scripts/UI/InventorySlot.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; public class InventorySlot : GuiBase { /*The slots containing items on the Inventory display*/ public short slotIndex;//What index of inventory slot is this public short SlotCategory; //What type of item is in the slot. Eg armour, rings, boots and general etc. //Possible values for the below. Should tally with UWexporter defines public const int GeneralItems = -1; public const int ARMOUR = 2; public const int HELM = 73; public const int RING = 74; public const int BOOT = 75; public const int GLOVES = 76; public const int LEGGINGS = 77; public static bool LookingAt; public static string TempLookAt; private ObjectInteraction QuantityObj = null;//Reference to quantity object being picked up public static bool Hovering; public void BeginDrag() { if ((UWCharacter.Instance.isRoaming == true) || (Quest.instance.InDreamWorld) || (UWCharacter.InteractionMode == UWCharacter.InteractionModeOptions)) {//No inventory use return; } if (CurrentObjectInHand == null) { if (!ConversationVM.InConversation) { UWCharacter.InteractionMode = UWCharacter.InteractionModePickup; InteractionModeControl.UpdateNow = true; } ClickEvent(-2); } } /// <summary> /// Handle using objects in inventory /// </summary> void UseFromSlot() { ObjectInteraction currObj = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); if (currObj != null) { currObj.Use(); } else { if (CurrentObjectInHand != null) { CurrentObjectInHand = null; } } } /// <summary> /// Handle looking at objects in inventory /// </summary> void LookFromSlot() { ObjectInteraction objLookedAt = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); if (objLookedAt != null) { if (objLookedAt.GetComponent<Readable>() != null) { objLookedAt.GetComponent<Readable>().Read(); } else { objLookedAt.LookDescription(); } } } public void OnClick(BaseEventData evnt) { PointerEventData pntr = (PointerEventData)evnt; ClickEvent(pntr.pointerId); UWCharacter.Instance.playerInventory.Refresh(); } /// <summary> /// Overall handling of clicking slots in the inventory /// </summary> /// <param name="pointerID"></param> void ClickEvent(int pointerID) { if ((UWCharacter.Instance.isRoaming == true) || (Quest.instance.InDreamWorld) || (UWCharacter.InteractionMode == UWCharacter.InteractionModeOptions)) {//No inventory use while using wizard eye. return; } bool leftClick = true; if (pointerID == -2) { leftClick = false; } if (UWCharacter.Instance.PlayerMagic.ReadiedSpell == "") { switch (UWCharacter.InteractionMode) { case UWCharacter.InteractionModeTalk://talk if (leftClick) {//Left Click UseFromSlot(); } else {//right click LookFromSlot(); } break; case UWCharacter.InteractionModePickup://pickup if (leftClick) { LeftClickPickup(); } else { RightClickPickup(); } break; case UWCharacter.InteractionModeLook://look if (leftClick) {//Left Click UseFromSlot(); } else {//right click LookFromSlot(); } break; case UWCharacter.InteractionModeAttack://attack if (leftClick) {//Left Click UseFromSlot(); } else {//right click LookFromSlot(); } break; case UWCharacter.InteractionModeUse://use if ((WindowDetect.ContextUIEnabled) && (WindowDetect.ContextUIUse)) { if ((leftClick) || (CurrentObjectInHand != null)) { UseFromSlot(); } else { RightClickPickup(); UWCharacter.InteractionMode = UWCharacter.InteractionModePickup; InteractionModeControl.UpdateNow = true; } } else { UseFromSlot(); } break; case UWCharacter.InteractionModeInConversation: ConversationClick(leftClick); break; } } else { UWCharacter.Instance.PlayerMagic.ObjectInSlot = null; if (UWCharacter.Instance.PlayerMagic.InventorySpell == true) { UWCharacter.Instance.PlayerMagic.ObjectInSlot = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); UWCharacter.Instance.PlayerMagic.castSpell(this.gameObject, UWCharacter.Instance.PlayerMagic.ReadiedSpell, false); UWCharacter.Instance.PlayerMagic.SpellCost = 0; UWHUD.instance.window.UWWindowWait(1.0f); } } } /// <summary> /// Handle clicking on inventory slots when in a conversation /// </summary> /// <param name="isLeftClick"></param> void ConversationClick(bool isLeftClick) { if (isLeftClick == false) {//Looking at object ObjectInteraction currObj = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); if (currObj != null) { if (currObj.GetComponent<Container>() != null) { currObj.GetComponent<Container>().OpenContainer(); return; } } return; } else { RightClickPickup(); } return; } /// <summary> /// Code for when left clicking in pickup mode /// </summary> void LeftClickPickup() { ObjectInteraction ObjectUsedOn = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); bool DoNotPickup = false; if (CurrentObjectInHand != null) { //Special case Eating food dropped on helm slot if (SlotCategory == HELM) { if(CurrentObjectInHand.Eat()) {//True is returned if some eating action has taken place. DoNotPickup = true; return; } } if ((SlotCategory != CurrentObjectInHand.GetItemType()) && (SlotCategory != -1)) {//Slot is not a general use one and this item type does not go in this slot. Eg putting a sword on a ring slot DoNotPickup = true; } if (CurrentObjectInHand.IsStackable()) {//Check if object is stackable and if so try and merge them together if the object being added is of the same type. if (ObjectUsedOn != null) { if (ObjectInteraction.CanMerge(ObjectUsedOn, CurrentObjectInHand)) { ObjectInteraction.Merge(ObjectUsedOn, CurrentObjectInHand); CurrentObjectInHand = null; UWCharacter.Instance.playerInventory.Refresh(); return; } } } } if (ObjectUsedOn == null)//No object in slot -> add to the slot { if (DoNotPickup == false) { if (Container.TestContainerRules(UWCharacter.Instance.playerInventory.currentContainer, slotIndex, false)) { UWCharacter.Instance.playerInventory.SetObjectAtSlot(slotIndex, CurrentObjectInHand); CurrentObjectInHand = null; } } } else { //Get the object at the slot and test if it is activated or effected by the object in the players hand if (ObjectUsedOn.Use() == false) {//if nothing happened when I clicked on the object at the slot. if (CurrentObjectInHand != null) { //TODO: Make sure this works with Equipment slots //No effect occurred. Swap the two objects. if (DoNotPickup == false) { if (Container.TestContainerRules(UWCharacter.Instance.playerInventory.currentContainer, slotIndex, true)) { UWCharacter.Instance.playerInventory.SwapObjects(ObjectUsedOn, slotIndex, CurrentObjectInHand); } } } else {//Pick up the item at that slot. //TODO: Make this work with Equipment slots CurrentObjectInHand = ObjectUsedOn; if (this.slotIndex >= 11) { UWCharacter.Instance.playerInventory.currentContainer.RemoveItemFromContainer(UWCharacter.Instance.playerInventory.ContainerOffset + this.slotIndex - 11); } UWCharacter.Instance.playerInventory.ClearSlot(this.slotIndex); } } } } void RightClickPickup() { ObjectInteraction ObjectUsedOn = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex);//The object at the clicked slot bool DoNotPickup = false; if (CurrentObjectInHand != null) { if ((SlotCategory != CurrentObjectInHand.GetItemType()) && (SlotCategory != -1)) {//Slot is not a general use on and This item type does not go in this slot. DoNotPickup = true; } //Eating food dropped in helm slot if (SlotCategory == HELM) { if (CurrentObjectInHand.GetItemType() == ObjectInteraction.FOOD) { CurrentObjectInHand.Use(); DoNotPickup = true; return; } } if (CurrentObjectInHand.IsStackable()) { if (ObjectUsedOn != null) { if (ObjectInteraction.CanMerge(ObjectUsedOn, CurrentObjectInHand)) { //merge the items ObjectInteraction.Merge(ObjectUsedOn, CurrentObjectInHand); CurrentObjectInHand = null; UWCharacter.Instance.playerInventory.Refresh(); return; } } } } //Code for when I right click in pickup mode. if (UWCharacter.Instance.playerInventory.GetObjectAtSlot(slotIndex) != null) {//Special case for opening containers in pickup mode. if ((CurrentObjectInHand == null)) { if (ObjectUsedOn.GetComponent<Container>() != null) { if (ObjectUsedOn.GetComponent<Container>().isOpenOnPanel == true) { return; } CurrentObjectInHand = ObjectUsedOn.GetComponent<ObjectInteraction>(); if (this.slotIndex >= 11) { UWCharacter.Instance.playerInventory.currentContainer.RemoveItemFromContainer(UWCharacter.Instance.playerInventory.ContainerOffset + this.slotIndex - 11); } UWCharacter.Instance.playerInventory.ClearSlot(this.slotIndex); return; } } } if (UWCharacter.Instance.playerInventory.GetObjectAtSlot(slotIndex) == null)//No object in slot { if (DoNotPickup == false) { if (Container.TestContainerRules(UWCharacter.Instance.playerInventory.currentContainer, slotIndex, false)) { UWCharacter.Instance.playerInventory.SetObjectAtSlot(slotIndex, CurrentObjectInHand); CurrentObjectInHand = null; } } } else { bool ObjectActivated = false; //Get the object at the slot and test it's activation. //When right clicking only try to activate when an object in in the hand if (CurrentObjectInHand != null) { ObjectActivated = ObjectUsedOn.GetComponent<ObjectInteraction>().Use(); } if (ObjectActivated == false) {//if nothing happened when I clicked on the object at the slot with something in hand. if (CurrentObjectInHand != null) { if (DoNotPickup == false) { //TODO: Make sure this works with Equipment slots //No effect occurred. Swap the two objects. if (Container.TestContainerRules(UWCharacter.Instance.playerInventory.currentContainer, slotIndex, true)) { UWCharacter.Instance.playerInventory.SwapObjects(ObjectUsedOn, slotIndex, CurrentObjectInHand); UWCharacter.Instance.playerInventory.Refresh(); } } } else {//Pick up the item at that slot. //TODO: Make this work with Equipment slots if (DoNotPickup == false) { ObjectInteraction objIntUsedOn = ObjectUsedOn.GetComponent<ObjectInteraction>(); if ((!objIntUsedOn.IsStackable()) || ((objIntUsedOn.IsStackable()) && (objIntUsedOn.GetQty() <= 1))) {//Is either not a quant or is a quantity of 1 CurrentObjectInHand = ObjectUsedOn; if (this.slotIndex >= 11) { UWCharacter.Instance.playerInventory.currentContainer.RemoveItemFromContainer(UWCharacter.Instance.playerInventory.ContainerOffset + this.slotIndex - 11); } UWCharacter.Instance.playerInventory.ClearSlot(this.slotIndex); } else { if (ConversationVM.InConversation == true) { //InventorySlot.TempLookAt = UWHUD.instance.MessageScroll.NewUIOUt.text; //UWHUD.instance.MessageScroll.NewUIOUt.text = ""; UWHUD.instance.ConversationButtonParent.SetActive(false); UWHUD.instance.MessageScroll.Set("Move how many?"); ConversationVM.EnteringQty = true; } else { UWHUD.instance.MessageScroll.Set("Move how many?"); } InputField inputctrl = UWHUD.instance.InputControl; inputctrl.gameObject.SetActive(true); inputctrl.text = objIntUsedOn.GetQty().ToString();//"1"; inputctrl.gameObject.GetComponent<InputHandler>().target = this.gameObject; inputctrl.gameObject.GetComponent<InputHandler>().currentInputMode = InputHandler.InputInventoryQty; inputctrl.contentType = InputField.ContentType.IntegerNumber; inputctrl.Select(); WindowDetect.WaitingForInput = true; Time.timeScale = 0.0f; QuantityObj = ObjectUsedOn; } } } } } } /// <summary> /// Handle player choosing how many items to pick up in a stack /// </summary> /// <param name="quant"></param> public void OnSubmitPickup(int quant) { InputField inputctrl = UWHUD.instance.InputControl; inputctrl.text = ""; inputctrl.gameObject.SetActive(false); WindowDetect.WaitingForInput = false; ConversationVM.EnteringQty = false; if (ConversationVM.InConversation == false) { UWHUD.instance.MessageScroll.Clear(); Time.timeScale = 1.0f; } else { UWHUD.instance.ConversationButtonParent.SetActive(true); UWHUD.instance.MessageScroll.Set(""); // UWHUD.instance.MessageScroll.NewUIOUt.text = InventorySlot.TempLookAt;//Restore original text } if (quant == 0) {//cancel QuantityObj = null; } if (QuantityObj != null) {//Just do a normal pickup. if (quant >= QuantityObj.GetComponent<ObjectInteraction>().link) { CurrentObjectInHand = QuantityObj; if (this.slotIndex >= 11) { UWCharacter.Instance.playerInventory.currentContainer.RemoveItemFromContainer(UWCharacter.Instance.playerInventory.ContainerOffset + this.slotIndex - 11); } UWCharacter.Instance.playerInventory.ClearSlot(this.slotIndex); } else { //split the obj. ObjectInteraction objI = QuantityObj.GetComponent<ObjectInteraction>(); objI.link = objI.link - quant; ObjectLoaderInfo newObj = ObjectLoader.newWorldObject(objI.item_id, objI.quality, objI.owner, quant, -1); newObj.is_quant = 1; ObjectInteraction NewObjI = ObjectInteraction.CreateNewObject(CurrentTileMap(), newObj, CurrentObjectList().objInfo, GameWorldController.instance.InventoryMarker, GameWorldController.instance.InventoryMarker.transform.position); GameWorldController.MoveToInventory(NewObjI); CurrentObjectInHand = NewObjI; ObjectInteraction.Split(objI, NewObjI); UWCharacter.Instance.playerInventory.Refresh(); QuantityObj = null; } } } public ObjectInteraction GetGameObjectInteration() { return UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); } void TemporaryLookAt() {/*For looking at items temporarily in conversations where I need to restore the original log text*/ if (InventorySlot.LookingAt == true) { return; }//Only look at one thing at a time. ObjectInteraction objInt = GetGameObjectInteration(); if (objInt != null) { InventorySlot.LookingAt = true; InventorySlot.TempLookAt = UWHUD.instance.MessageScroll.NewUIOUt.text; StartCoroutine(ClearTempLookAt()); UWHUD.instance.MessageScroll.DirectSet(StringController.instance.GetFormattedObjectNameUW(objInt)); } } IEnumerator ClearTempLookAt() { Time.timeScale = 0.1f; yield return new WaitForSeconds(0.1f); InventorySlot.LookingAt = false; if (ConversationVM.InConversation == true) { Time.timeScale = 0.00f; } else { Time.timeScale = 1.0f;//just in case a conversation is ended while looking. } UWHUD.instance.MessageScroll.DirectSet(InventorySlot.TempLookAt); } /// <summary> /// Handles hovering over the slot /// </summary> public void OnHoverEnter() { Hovering = true; UWHUD.instance.ContextMenu.text = ""; ObjectInteraction objInt = UWCharacter.Instance.playerInventory.GetObjectIntAtSlot(slotIndex); if (objInt != null) { string ObjectName = ""; string UseString = ""; ObjectName = objInt.GetComponent<object_base>().ContextMenuDesc(objInt.item_id); if (CurrentObjectInHand == null) { switch (UWCharacter.InteractionMode) { case UWCharacter.InteractionModeUse: UseString = "L-Click to " + objInt.UseVerb() + " R-Click to " + objInt.PickupVerb(); break; case UWCharacter.InteractionModeLook: UseString = "L-Click to " + objInt.UseVerb() + " R-Click to " + objInt.ExamineVerb(); break; case UWCharacter.InteractionModePickup: UseString = "L-Click to " + objInt.UseVerb() + " R-Click to " + objInt.PickupVerb(); break; } } else { UseString = "L-Click to " + objInt.UseObjectOnVerb_Inv(); } UWHUD.instance.ContextMenu.text = ObjectName + "\n" + UseString; } } /// <summary> /// Handles cancelling hovering over the slot /// </summary> public void OnHoverExit() { UWHUD.instance.ContextMenu.text = ""; Hovering = false; } }
412
0.942897
1
0.942897
game-dev
MEDIA
0.970021
game-dev
0.938589
1
0.938589
haekb/nolf1-modernizer
6,475
NOLF/ClientShellDLL/CMoveMgr.h
// ----------------------------------------------------------------------- // // // MODULE : CMoveMgr.cpp // // PURPOSE : Client side player movement mgr - Definition // // CREATED : 10/2/98 // // (c) 1998-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __CMOVEMGR_H__ #define __CMOVEMGR_H__ #include "iltclient.h" #include "ContainerCodes.h" #include "SharedMovement.h" #include "SurfaceMgr.h" #include "VarTrack.h" #include "CameraOffsetMgr.h" class ILTClientPhysics; class CGameClientShell; class CCharacterFX; class CVehicleMgr; class CContainerInfo { public: float m_fGravity; float m_fViscosity; LTVector m_Current; ContainerCode m_ContainerCode; LTBOOL m_bHidden; }; class CMoveMgr { public: CMoveMgr(); ~CMoveMgr(); LTBOOL Init(); void Update(); void UpdateModels(); LTVector GetVelocity() const; void SetVelocity(LTVector vVel); LTFLOAT GetMaxVelMag() const; void SetGravity(LTFLOAT fGravity) { m_fGravity = fGravity; } LTFLOAT GetMovementPercent() const; LTFLOAT GetVelMagnitude(); LTBOOL IsPlayerModel(); CCharacterFX* GetCharacterFX() const { return m_pCharFX; } void SetCharacterFX(CCharacterFX* pFX) { m_pCharFX = pFX; } void OnPhysicsUpdate(HMESSAGEREAD hRead); void UpdateMouseStrafeFlags(float *pAxisOffsets); void OnEnterWorld(); void OnExitWorld(); void Save(HMESSAGEWRITE hWrite); void Load(HMESSAGEREAD hRead); LTRESULT OnObjectMove(HOBJECT hObj, LTBOOL bTeleport, LTVector *pPos); LTRESULT OnObjectRotate(HOBJECT hObj, LTBOOL bTeleport, LTRotation *pNewRot); void OnTouchNotify(CollisionInfo *pInfo, float forceMag); uint32 GetControlFlags() const { return m_dwControlFlags; } LTBOOL Jumped() const { return m_bJumped; } // CMoveMgr keeps a list of spheres that repel the player object. // These are created from explosions. LTRESULT AddPusher(LTVector &pos, float radius, float startDelay, float duration, float strength); HOBJECT GetObject() {return m_hObject;} void SetSpectatorMode(LTBOOL bSet); void OnServerForcePos(HMESSAGEREAD hRead); void WritePositionInfo(HMESSAGEWRITE hWrite); SurfaceType GetStandingOnSurface() const { return m_eStandingOnSurface; } LTBOOL CanDoFootstep(); LTBOOL IsHeadInLiquid() const { return IsLiquid(m_eCurContainerCode); } LTBOOL IsFreeMovement() const { return ::IsFreeMovement(m_eCurContainerCode); } LTBOOL IsBodyInLiquid() const { return m_bBodyInLiquid; } LTBOOL IsOnGround() const { return m_bOnGround; } LTBOOL IsBodyOnLadder() const { return m_bBodyOnLadder; } LTBOOL IsOnLift() const { return m_bOnLift; } LTBOOL IsFalling() const { return m_bFalling; } LTBOOL IsZipCordOn() const { return m_bZipCordOn; } LTBOOL IsMovingQuietly() const; void SetMouseStrafeFlags(int nFlags) { m_nMouseStrafeFlags = nFlags; } void UpdateOnGround(); LTFLOAT GetMoveMultiplier() const { return m_fMoveMultiplier; } LTFLOAT GetMoveAccelMultiplier() const { return m_fMoveAccelMultiplier; } LTVector GetTotalCurrent() const { return m_vTotalCurrent; } LTFLOAT GetTotalViscosity() const { return m_fTotalViscosity; } void AllowMovement(LTBOOL b=LTTRUE) { m_bAllowMovement = b; } void TurnOnZipCord(HOBJECT hHookObj); void TurnOffZipCord(); void UpdateStartMotion(LTBOOL bForce=LTFALSE); CVehicleMgr* GetVehicleMgr() const { return m_pVehicleMgr; } protected: void InitWorldData(); void ShowPos(char *pBlah); void UpdatePushers(); void UpdatePlayerAnimation(); LTBOOL AreDimsCorrect(); void ResetDims(LTVector *pOffset=NULL); void UpdateControlFlags(); void UpdateMotion(); void UpdateFriction(); void UpdateSound(); void UpdateNormalControlFlags(); void UpdateNormalMotion(); void UpdateNormalFriction(); void UpdateContainerMotion(); void UpdateContainerViscosity(CContainerInfo *pInfo); void UpdateOnLadder(CContainerInfo *pInfo); void UpdateInLiquid(CContainerInfo *pInfo); void HandleFallLand(LTFLOAT fDistFell); void MoveLocalSolidObject(); void UpdateVelMagnitude(); void SetClientObjNonsolid(); void MoveToClientObj(); void TermLevel(); protected : uint8 m_ClientMoveCode; // The object representing our movement. HOBJECT m_hObject; LTLink m_Pushers; LTVector m_vWantedDims; // Zip cord info. LTVector m_vZipCordPos; LTVector m_vZipHookDims; float m_fZipCordVel; LTBOOL m_bZipCordOn; // Movement state. uint32 m_dwControlFlags; uint32 m_dwLastControlFlags; uint32 m_nMouseStrafeFlags; LTBOOL m_bBodyInLiquid; LTBOOL m_bSwimmingOnSurface; LTBOOL m_bCanSwimJump; ContainerCode m_eBodyContainerCode; // Body container code LTBOOL m_bBodyOnLadder; LTBOOL m_bLoading; LTVector m_vSavedVel; HPOLY m_hStandingOnPoly; SurfaceType m_eStandingOnSurface; LTBOOL m_bOnGround; LTBOOL m_bOnLift; LTBOOL m_bFalling; LTBOOL m_bUsingPlayerModel; float m_fBaseMoveAccel; float m_fMoveAccelMultiplier; float m_fLastOnGroundY; LTBOOL m_bJumped; LTVector m_vTotalCurrent; float m_fTotalViscosity; // Movement speeds. float m_fJumpVel; float m_fJumpMultiplier; float m_fSwimVel; float m_fWalkVel; float m_fRunVel; float m_fLadderVel; float m_fMoveMultiplier; float m_fGravity; LTBOOL m_bSwimmingJump; LTBOOL m_bFirstAniUpdate; LTBOOL m_bAllowMovement; HLTSOUND m_hZipcordSnd; ContainerCode m_eLastContainerCode; ContainerCode m_eCurContainerCode; CContainerInfo m_Containers[MAX_TRACKED_CONTAINERS]; uint32 m_nContainers; // Spectator speed multiplier. VarTrack m_CV_SpectatorSpeedMul; CCharacterFX* m_pCharFX; CVehicleMgr* m_pVehicleMgr; CollisionInfo m_LastStandingOnInfo; int m_nLastStandingOnFrameCounter; }; inline LTBOOL CMoveMgr::IsMovingQuietly() const { LTBOOL bRet = LTFALSE; if ((m_dwControlFlags & BC_CFLG_DUCK) || !(m_dwControlFlags & BC_CFLG_RUN)) { if (!IsFreeMovement() && !IsBodyOnLadder() && IsOnGround()) { bRet = LTTRUE; } } return bRet; } #endif // __CMOVEMGR_H__
412
0.8569
1
0.8569
game-dev
MEDIA
0.898475
game-dev
0.559083
1
0.559083
AppliedEnergistics/GuideME
19,845
src/main/java/guideme/internal/command/StructureCommands.java
package guideme.internal.command; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import guideme.internal.GuideRegistry; import guideme.internal.GuidebookText; import guideme.internal.MutableGuide; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.PauseScreen; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.coordinates.BlockPosArgument; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.SingleThreadedRandomSource; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import org.apache.commons.lang3.mutable.MutableObject; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryStack; import org.lwjgl.util.tinyfd.TinyFileDialogs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements commands that help with the workflow to create and edit structures for use in the guidebook. The commands * will not be used directly by users, but rather by command blocks built by * {@link appeng.server.testplots.GuidebookPlot}. */ public final class StructureCommands { private static final Logger LOG = LoggerFactory.getLogger(StructureCommands.class); private StructureCommands() { } @Nullable private static String lastOpenedOrSavedPath; private static final String[] FILE_PATTERNS = { "*.snbt", "*.nbt" }; private static final String FILE_PATTERN_DESC = "Structure NBT Files (*.snbt, *.nbt)"; public static void register(CommandDispatcher<CommandSourceStack> dispatcher) { var rootCommand = Commands.literal("guideme"); registerPlaceAllStructures(rootCommand); registerImportCommand(rootCommand); registerExportCommand(rootCommand); dispatcher.register(rootCommand); } @Nullable private static ServerLevel getIntegratedServerLevel(CommandContext<CommandSourceStack> context) { var minecraft = Minecraft.getInstance(); if (!minecraft.hasSingleplayerServer()) { context.getSource().sendFailure(GuidebookText.CommandOnlyWorksInSinglePlayer.text()); return null; } return minecraft.getSingleplayerServer().getLevel( Minecraft.getInstance().player.level().dimension()); } private static void registerPlaceAllStructures(LiteralArgumentBuilder<CommandSourceStack> rootCommand) { LiteralArgumentBuilder<CommandSourceStack> subcommand = literal("placeallstructures"); // Only usable on singleplayer worlds and only by the local player (in case it is opened to LAN) subcommand = subcommand.requires(c -> c.hasPermission(2)); subcommand.then(Commands.argument("origin", BlockPosArgument.blockPos()) .executes(context -> { var level = getIntegratedServerLevel(context); if (level == null) { return 1; } var origin = BlockPosArgument.getBlockPos(context, "origin"); placeAllStructures(context.getSource(), level, origin); return 0; })); subcommand .then(Commands.argument("origin", BlockPosArgument.blockPos()) .then(Commands.argument("guide", GuideIdArgument.argument()) .executes(context -> { var level = getIntegratedServerLevel(context); if (level == null) { return 1; } var guideId = GuideIdArgument.getGuide(context, "guide"); var guide = GuideRegistry.getById(guideId); if (guide == null) { return 1; } var origin = BlockPosArgument.getBlockPos(context, "origin"); placeAllStructures(context.getSource(), level, new MutableObject<>(origin), guide); return 0; }))); rootCommand.then(subcommand); } private static void registerImportCommand(LiteralArgumentBuilder<CommandSourceStack> rootCommand) { LiteralArgumentBuilder<CommandSourceStack> importSubcommand = literal("importstructure"); // Only usable on singleplayer worlds and only by the local player (in case it is opened to LAN) importSubcommand .requires(c -> c.hasPermission(2)) .then(Commands.argument("origin", BlockPosArgument.blockPos()) .executes(context -> { var level = getIntegratedServerLevel(context); if (level == null) { return 1; } var origin = BlockPosArgument.getBlockPos(context, "origin"); importStructure(context.getSource(), getIntegratedServerLevel(context), origin); return 0; })); rootCommand.then(importSubcommand); } private static void placeAllStructures(CommandSourceStack source, ServerLevel level, BlockPos origin) { var currentPos = new MutableObject<>(origin); for (var guide : GuideRegistry.getAll()) { placeAllStructures(source, level, currentPos, guide); } } private static void placeAllStructures(CommandSourceStack source, ServerLevel level, MutableObject<BlockPos> origin, MutableGuide guide) { var minecraft = Minecraft.getInstance(); var server = minecraft.getSingleplayerServer(); if (server == null) { return; } var sourceFolder = guide.getDevelopmentSourceFolder(); List<Pair<String, Supplier<String>>> structures = new ArrayList<>(); if (sourceFolder == null) { var resourceManager = Minecraft.getInstance().getResourceManager(); var resources = resourceManager.listResources( guide.getContentRootFolder(), location -> location.getPath().endsWith(".snbt")); for (var entry : resources.entrySet()) { structures.add(Pair.of(entry.getKey().toString(), () -> { try (var in = entry.getValue().open()) { return new String(in.readAllBytes()); } catch (IOException e) { LOG.error("Failed to read structure {}", entry.getKey(), e); return null; } })); } } else { try (var s = Files.walk(sourceFolder) .filter(p -> Files.isRegularFile(p) && p.getFileName().toString().endsWith(".snbt"))) { s.forEach(path -> { structures.add(Pair.of( path.toString(), () -> { try { return Files.readString(path); } catch (IOException e) { LOG.error("Failed to read structure {}", path, e); return null; } })); }); } catch (IOException e) { LOG.error("Failed to find all structures.", e); source.sendFailure(Component.literal(e.toString())); return; } } for (var pair : structures) { var snbtFile = pair.getLeft(); var contentSupplier = pair.getRight(); LOG.info("Placing {}", snbtFile); try { var manager = level.getServer().getStructureManager(); CompoundTag compound; var textInFile = contentSupplier.get(); if (textInFile == null) { continue; } compound = NbtUtils.snbtToStructure(textInFile); var structure = manager.readStructure(compound); var pos = origin.getValue(); if (!structure.placeInWorld( level, pos, pos, new StructurePlaceSettings(), new SingleThreadedRandomSource(0L), Block.UPDATE_CLIENTS)) { source.sendFailure(Component.literal("Failed to place " + snbtFile)); } origin.setValue(origin.getValue().offset(structure.getSize().getX() + 2, 0, 0)); } catch (Exception e) { LOG.error("Failed to place {}.", snbtFile, e); source.sendFailure(Component.literal("Failed to place " + snbtFile + ": " + e)); } } source.sendSuccess(() -> Component.literal("Placed " + structures.size() + " structures"), true); } private static void importStructure(CommandSourceStack source, ServerLevel level, BlockPos origin) { var minecraft = Minecraft.getInstance(); var server = minecraft.getSingleplayerServer(); if (server == null) { return; } CompletableFuture .supplyAsync(StructureCommands::pickFileForOpen, minecraft) .thenApplyAsync(selectedPath -> { if (selectedPath == null) { return null; } lastOpenedOrSavedPath = selectedPath; // remember for save dialog try { if (placeStructure(level, origin, selectedPath)) { source.sendSuccess(() -> Component.literal("Placed structure"), true); } else { source.sendFailure(Component.literal("Failed to place structure")); } } catch (Exception e) { LOG.error("Failed to place structure.", e); source.sendFailure(Component.literal(e.toString())); } return null; }, server) .thenRunAsync(() -> { if (minecraft.screen instanceof PauseScreen) { minecraft.setScreen(null); } }, minecraft); } private static boolean placeStructure(ServerLevel level, BlockPos origin, String structurePath) throws CommandSyntaxException, IOException { var manager = level.getServer().getStructureManager(); CompoundTag compound; if (structurePath.toLowerCase(Locale.ROOT).endsWith(".snbt")) { var textInFile = Files.readString(Paths.get(structurePath), StandardCharsets.UTF_8); compound = NbtUtils.snbtToStructure(textInFile); } else { try (var is = new BufferedInputStream(new FileInputStream(structurePath))) { compound = NbtIo.readCompressed(is, NbtAccounter.unlimitedHeap()); } } var structure = manager.readStructure(compound); return structure.placeInWorld( level, origin, origin, new StructurePlaceSettings(), new SingleThreadedRandomSource(0L), Block.UPDATE_CLIENTS); } private static void registerExportCommand(LiteralArgumentBuilder<CommandSourceStack> rootCommand) { LiteralArgumentBuilder<CommandSourceStack> exportSubcommand = literal("exportstructure"); // Only usable on singleplayer worlds and only by the local player (in case it is opened to LAN) exportSubcommand .requires(c -> c.hasPermission(2)) .then(Commands.argument("origin", BlockPosArgument.blockPos()) .then(Commands.argument("sizeX", IntegerArgumentType.integer(1)) .then(Commands.argument("sizeY", IntegerArgumentType.integer(1)) .then(Commands.argument("sizeZ", IntegerArgumentType.integer(1)) .executes(context -> { var level = getIntegratedServerLevel(context); if (level == null) { return 1; } var origin = BlockPosArgument.getBlockPos(context, "origin"); var sizeX = IntegerArgumentType.getInteger(context, "sizeX"); var sizeY = IntegerArgumentType.getInteger(context, "sizeY"); var sizeZ = IntegerArgumentType.getInteger(context, "sizeZ"); var size = new Vec3i(sizeX, sizeY, sizeZ); exportStructure(context.getSource(), level, origin, size); return 0; }))))); rootCommand.then(exportSubcommand); } private static void exportStructure(CommandSourceStack source, ServerLevel level, BlockPos origin, Vec3i size) { var minecraft = Minecraft.getInstance(); var server = minecraft.getSingleplayerServer(); var player = minecraft.player; if (server == null || player == null) { return; } CompletableFuture .supplyAsync(StructureCommands::pickFileForSave, minecraft) .thenApplyAsync(selectedPath -> { if (selectedPath == null) { return null; } try { // Find the smallest box containing the placed blocks var to = BlockPos .betweenClosedStream(origin, origin.offset(size.getX() - 1, size.getY() - 1, size.getZ() - 1)) .filter(pos -> !level.getBlockState(pos).isAir()) .reduce( origin, (blockPos, blockPos2) -> new BlockPos( Math.max(blockPos.getX(), blockPos2.getX()), Math.max(blockPos.getY(), blockPos2.getY()), Math.max(blockPos.getZ(), blockPos2.getZ()))); var actualSize = new BlockPos( 1 + to.getX() - origin.getX(), 1 + to.getY() - origin.getY(), 1 + to.getZ() - origin.getZ()); var structureTemplate = new StructureTemplate(); structureTemplate.fillFromWorld( level, origin, actualSize, false, List.of()); var compound = structureTemplate.save(new CompoundTag()); if (selectedPath.toLowerCase(Locale.ROOT).endsWith(".snbt")) { Files.writeString( Paths.get(selectedPath), NbtUtils.structureToSnbt(compound), StandardCharsets.UTF_8); } else { NbtIo.writeCompressed(compound, Paths.get(selectedPath)); } source.sendSuccess(() -> Component.literal("Saved structure"), true); } catch (IOException e) { LOG.error("Failed to save structure.", e); source.sendFailure(Component.literal(e.toString())); } return null; }, server) .thenRunAsync(() -> { if (minecraft.screen instanceof PauseScreen) { minecraft.setScreen(null); } }, minecraft); } private static String pickFileForOpen() { setDefaultFolder(); try (var stack = MemoryStack.stackPush()) { return TinyFileDialogs.tinyfd_openFileDialog( "Load Structure", lastOpenedOrSavedPath, createFilterPatterns(stack), FILE_PATTERN_DESC, false); } } private static String pickFileForSave() { setDefaultFolder(); try (var stack = MemoryStack.stackPush()) { return TinyFileDialogs.tinyfd_saveFileDialog( "Save Structure", lastOpenedOrSavedPath, createFilterPatterns(stack), FILE_PATTERN_DESC); } } private static PointerBuffer createFilterPatterns(MemoryStack stack) { PointerBuffer filterPatternsBuffer = stack.mallocPointer(FILE_PATTERNS.length); for (var pattern : FILE_PATTERNS) { filterPatternsBuffer.put(stack.UTF8(pattern)); } filterPatternsBuffer.flip(); return filterPatternsBuffer; } private static void setDefaultFolder() { // If any guide has development sources, default to that folder if (lastOpenedOrSavedPath == null) { for (var guide : GuideRegistry.getAll()) { if (guide.getDevelopmentSourceFolder() != null) { lastOpenedOrSavedPath = guide.getDevelopmentSourceFolder().toString(); if (!lastOpenedOrSavedPath.endsWith("/") && !lastOpenedOrSavedPath.endsWith("\\")) { lastOpenedOrSavedPath += File.separator; } break; } } } } }
412
0.945741
1
0.945741
game-dev
MEDIA
0.991569
game-dev
0.970094
1
0.970094
apache/cayenne
3,853
cayenne/src/main/java/org/apache/cayenne/configuration/xml/DbKeyGeneratorHandler.java
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.configuration.xml; import org.apache.cayenne.map.DbEntity; import org.apache.cayenne.map.DbKeyGenerator; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * @since 4.1 */ public class DbKeyGeneratorHandler extends NamespaceAwareNestedTagHandler { private static final String DB_KEY_GENERATOR_TAG = "db-key-generator"; private static final String DB_GENERATOR_TYPE_TAG = "db-generator-type"; private static final String DB_GENERATOR_NAME_TAG = "db-generator-name"; private static final String DB_KEY_CACHE_SIZE_TAG = "db-key-cache-size"; DbEntity entity; public DbKeyGeneratorHandler(NamespaceAwareNestedTagHandler parentHandler, DbEntity entity) { super(parentHandler); this.entity = entity; } @Override protected boolean processElement(String namespaceURI, String localName, Attributes attributes) throws SAXException { switch (localName) { case DB_KEY_GENERATOR_TAG: createDbKeyGenerator(); return true; case DB_GENERATOR_NAME_TAG: case DB_GENERATOR_TYPE_TAG: case DB_KEY_CACHE_SIZE_TAG: return true; } return false; } @Override protected boolean processCharData(String localName, String data) { switch (localName) { case DB_GENERATOR_TYPE_TAG: setDbGeneratorType(data); break; case DB_GENERATOR_NAME_TAG: setDbGeneratorName(data); break; case DB_KEY_CACHE_SIZE_TAG: setDbKeyCacheSize(data); break; } return true; } private void createDbKeyGenerator() { entity.setPrimaryKeyGenerator(new DbKeyGenerator()); } private void setDbGeneratorType(String type) { if (entity == null) { return; } DbKeyGenerator pkGenerator = entity.getPrimaryKeyGenerator(); pkGenerator.setGeneratorType(type); if (pkGenerator.getGeneratorType() == null) { entity.setPrimaryKeyGenerator(null); } } private void setDbGeneratorName(String name) { if (entity == null) { return; } DbKeyGenerator pkGenerator = entity.getPrimaryKeyGenerator(); if (pkGenerator == null) { return; } pkGenerator.setGeneratorName(name); } private void setDbKeyCacheSize(String size) { if (entity == null) { return; } DbKeyGenerator pkGenerator = entity.getPrimaryKeyGenerator(); if (pkGenerator == null) { return; } try { pkGenerator.setKeyCacheSize(Integer.valueOf(size.trim())); } catch (Exception ex) { pkGenerator.setKeyCacheSize(null); } } }
412
0.835124
1
0.835124
game-dev
MEDIA
0.489595
game-dev,databases
0.931224
1
0.931224
cosmonium/cosmonium
29,779
ralph.py
#!/usr/bin/env python # # This file is part of Cosmonium. # # Copyright (C) 2018-2024 Laurent Deru. # # Cosmonium 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. # # Cosmonium 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 Cosmonium. If not, see <https://www.gnu.org/licenses/>. # # This demo is heavily based on the Ralph example of Panda3D # Author: Ryan Myers # Models: Jeff Styers, Reagan Heller # import sys import os # Disable stdout block buffering sys.stdout.flush() sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1) # Add lib/ directory to import path to be able to load the c++ libraries sys.path.insert(1, 'lib') # Add third-party/ directory to import path to be able to load the external libraries sys.path.insert(0, 'third-party') # CEFPanda and glTF modules aree not at top level sys.path.insert(0, 'third-party/cefpanda') sys.path.insert(0, 'third-party/gltf') import argparse import builtins from direct.showbase.PythonUtil import clamp from direct.showbase.ShowBaseGlobal import globalClock from direct.task.TaskManagerGlobal import taskMgr from math import pow, pi from panda3d.core import LPoint3d, LQuaterniond, LQuaternion, BitMask32, NodePath from panda3d.bullet import BulletHeightfieldShape, BulletRigidBodyNode, ZUp from cosmonium.astro import units from cosmonium.camera import CameraHolder, EventsControllerBase from cosmonium.controllers.controllers import FlatSurfaceBodyMover, CartesianBodyMover from cosmonium.cosmonium import CosmoniumBase from cosmonium.engine.c_settings import c_settings from cosmonium.foundation import BaseObject from cosmonium.nav import ControlNav, KineticNav from cosmonium.parsers.actorobjectparser import ActorObjectYamlParser from cosmonium.parsers.bulletparser import BulletPhysicsShapeYamlParser from cosmonium.parsers.cameraparser import CameraControllerYamlParser from cosmonium.parsers.collisionparser import CollisionShapeYamlParser from cosmonium.parsers.flatuniverseparser import FlatUniverseYamlParser from cosmonium.parsers.yamlparser import YamlModuleParser from cosmonium.patchedshapes.patchedshapes import PatchLayer from cosmonium.patchedshapes.tiles import TerrainLayerFactoryInterface from cosmonium.physics.bullet import BulletPhysics, BulletMover from cosmonium.physics.collision import CollisionPhysics from cosmonium.procedural.water import WaterNode from cosmonium.scene.flatuniverse import FlatUniverse from cosmonium.scene.scenemanager import C_CameraHolder, StaticSceneManager, remove_main_region from cosmonium.scene.sceneworld import CartesianWorld, SceneWorld from cosmonium.shadows import CustomShadowMapShadowCaster, PSSMShadowMapShadowCaster from cosmonium.ui.splash import NoSplash from cosmonium import settings, mesh # TODO: Change of base unit should be done properly units.m = 1.0 units.Km = 1000.0 class WaterLayer(PatchLayer): def __init__(self, config): self.config = config self.water = None def check_settings(self): if self.water is not None: if self.config.visible: self.water.create_instance() else: self.water.remove_instance() def create_instance(self, patch, tasks_tree): scale = patch.scale * patch.size / self.config.scale self.water = WaterNode(patch.x0, patch.y0, patch.size, scale, patch) if self.config.visible: self.water.create_instance() def patch_done(self, patch, early): pass def update_instance(self, patch): pass def remove_instance(self): if self.water is not None: self.water.remove_instance() self.water = None class WaterLayerFactory(TerrainLayerFactoryInterface): def __init__(self, water): self.water = water def create_layer(self, patch): return WaterLayer(self.water) class PhysicsLayer(PatchLayer): def __init__(self, physics): self.physics = physics self.instance = None def patch_done(self, patch, early): if early: return terrain = patch.owner.owner.surface heightmap = terrain.heightmap heightmap_patch = heightmap.get_patch_data(patch, strict=True) terrain_scale = terrain.get_scale() patch_scale = patch.get_scale() assert heightmap_patch.width == heightmap_patch.height assert patch_scale[0] == patch_scale[1] shape = BulletHeightfieldShape(heightmap_patch.texture, heightmap.max_height * terrain_scale[2], ZUp) shape.setUseDiamondSubdivision(True) self.instance = NodePath(BulletRigidBodyNode('Heightfield ' + patch.str_id())) self.instance.node().add_shape(shape) x = terrain_scale[0] * (patch.x0 + patch.x1) / 2.0 y = terrain_scale[1] * (patch.y0 + patch.y1) / 2.0 self.instance.set_pos(x, y, heightmap.max_height / 2 * terrain_scale[2]) self.instance.set_scale( terrain_scale[0] * patch_scale[0] / (heightmap_patch.width - 1), terrain_scale[1] * patch_scale[1] / (heightmap_patch.height - 1), 1, ) self.instance.setCollideMask(BitMask32.allOn()) self.physics.add_object(self, self.instance) def remove_instance(self): if self.instance is None: return self.physics.remove_object(self, self.instance) self.instance.remove_node() self.instance = None class PhysicsLayerFactory(TerrainLayerFactoryInterface): def __init__(self, physics): self.physics = physics def create_layer(self, patch): return PhysicsLayer(self.physics) class PhysicsBox: def __init__(self, model, physics, mass, limit): self.model = model self.physics = physics self.mass = mass self.limit = limit self.instance = None self.physics_instance = None def create_instance(self, observer): self.mesh = builtins.base.loader.loadModel(self.model) self.mesh.clearModelNodes() self.instance = NodePath("BoxHolder") self.mesh.reparent_to(self.instance) self.instance.reparent_to(builtins.base.render) self.physics_instance = self.physics.build_from_geom(self.mesh)[0] self.physics.set_mass(self.physics_instance, self.mass) self.physics_instance.setCollideMask(BitMask32.allOn()) # TODO: Replace with calc_absolute_... position = observer.get_local_position() + observer.get_absolute_orientation().xform(LPoint3d(0, 10, 5)) self.physics_instance.set_pos(*position) self.physics.add_object(self, self.physics_instance) def remove_instance(self): if self.instance is not None: self.instance.remove_node() self.instance = None self.physics.remove_object(self, self.physics_instance) self.physics_instance = None def update(self, observer): if self.instance is None: return False local_position = LPoint3d(*self.physics_instance.get_pos()) local_rotation = LQuaterniond(*self.physics_instance.get_quat()) if settings.camera_at_origin: scene_rel_position = local_position - observer.get_local_position() else: scene_rel_position = local_position self.instance.set_pos(*scene_rel_position) self.instance.set_quat(LQuaternion(*local_rotation)) if (local_position - observer.get_local_position()).length() > self.limit: print("Object is too far, removing it") self.remove_instance() return False else: return True class WaterConfig: def __init__(self, level, visible, scale): self.level = level self.visible = visible self.scale = scale class PhysicsConfig: def __init__(self, gravity, model, mass, limit, debug): self.gravity = gravity self.model = model self.mass = mass self.limit = limit self.debug = debug class RalphConfigParser(YamlModuleParser): def __init__(self, worlds): YamlModuleParser.__init__(self) self.worlds = worlds def decode(self, data): water = data.get('water', None) physics = data.get('physics', {}) parser = FlatUniverseYamlParser(self.worlds) parser.decode(data) terrain = data.get('terrain', {}) self.tile_size = terrain.get("tile-size", 1024) self.shadow_size = terrain.get('shadow-size', 16) self.shadow_box_length = terrain.get('shadow-depth', self.tile_size) if water is not None: level = water.get('level', 0) visible = water.get('visible', False) scale = water.get('scale', 8.0) self.water = WaterConfig(level, visible, scale) else: self.water = WaterConfig(0, False, 1.0) has_physics = physics.get('enable', False) debug = physics.get('debug', False) if has_physics: engine_name = physics.get('engine', 'bullet') gravity = physics.get('gravity', 9.81) if engine_name == 'bullet': engine = BulletPhysics(debug) else: engine = CollisionPhysics() model = physics.get('model', None) mass = physics.get('mass', 0.01) limit = physics.get('limit', 100) else: engine = None self.physics = engine if has_physics: self.physics_config = PhysicsConfig(gravity, model, mass, limit, debug) ralph = data.get('ralph', {}) if 'actor' in ralph: self.ralph_shape_object = ActorObjectYamlParser.decode(ralph['actor']) else: self.ralph_shape_object = None if has_physics: if 'physics-shape' in ralph: if engine_name == 'bullet': self.ralph_physics_shape = BulletPhysicsShapeYamlParser.decode(ralph['physics-shape']) else: self.ralph_physics_shape = CollisionShapeYamlParser.decode(ralph['physics-shape']) else: self.ralph_physics_shape = None else: self.ralph_physics_shape = None self.start_position = ralph.get('position') self.camera_controller = CameraControllerYamlParser.decode(data.get('camera')) return True class RalphWord(CartesianWorld): def __init__(self, name, ship_object, physics_shape, radius, physics): CartesianWorld.__init__(self, name) self.add_component(ship_object) self.ship_object = ship_object self.physics_shape = physics_shape self.current_state = None self.physics_node = None self.physics_instance = None self.physics = physics self.anchor.set_bounding_radius(radius) def set_state(self, new_state): if self.ship_object is None: return if self.current_state == new_state: return if new_state == 'moving': self.ship_object.shape.loop("run") if new_state == 'idle': self.ship_object.shape.stop() self.ship_object.shape.pose("walk", 5) self.current_state = new_state def check_and_update_instance(self, scene_manager, camera_pos, camera_rot): CartesianWorld.check_and_update_instance(self, scene_manager, camera_pos, camera_rot) if self.physics is not None and self.physics_instance is None: if self.physics_shape is None and self.ship_object is not None and self.ship_object.instance is not None: physics_shape = self.physics.create_capsule_shape_for(self.ship_object.instance) else: physics_shape = self.physics_shape if physics_shape is not None: self.physics_node = self.physics.create_controller_for(physics_shape) if self.ship_object is not None: instance = self.ship_object.instance else: instance = self.scene_anchor.instance self.physics_instance = builtins.base.physics.add_controller(self, instance, self.physics_node) def update(self, time, dt): CartesianWorld.update(self, time, dt) if self.physics_instance is not None: offset = LPoint3d(0, 0, 0) self.physics_instance.set_pos(*(self.anchor.get_local_position() + offset)) self.physics_instance.set_quat(LQuaternion(*self.anchor.get_absolute_orientation())) class RalphControl(EventsControllerBase): def __init__(self, sun, engine): EventsControllerBase.__init__(self) self.sun = sun self.engine = engine def register_events(self): self.accept("escape", sys.exit) self.accept("control-q", sys.exit) self.accept("w", self.engine.toggle_water) self.accept("h", self.engine.print_debug) self.accept("f2", self.engine.connect_pstats) self.accept("f3", self.engine.toggle_filled_wireframe) self.accept("shift-f3", self.engine.toggle_wireframe) self.accept("f5", self.engine.bufferViewer.toggleEnable) self.accept('f8', self.toggle_lod_freeze) if self.engine.terrain_shape is not None: self.accept("shift-f8", self.engine.terrain_shape.dump_tree) self.accept("shift-control-f8", self.engine.terrain_shape.dump_patches) self.accept('control-f8', self.toggle_split_merge_debug) self.accept('f9', self.toggle_shader_debug_coord) self.accept('shift-f9', self.toggle_bb) self.accept('control-f9', self.toggle_frustum) self.accept("f10", self.engine.save_screenshot) self.accept("shift-f11", self.debug_ls) self.accept("shift-f12", self.debug_print_tasks) self.accept('alt-enter', self.engine.toggle_fullscreen) self.accept('{', self.engine.incr_ambient, [-0.05]) self.accept('}', self.engine.incr_ambient, [+0.05]) self.accept('space', self.engine.spawn_box) self.accept("o", self.set_key, ["sun-left", True]) # , direct=True) self.accept("o-up", self.set_key, ["sun-left", False]) self.accept("p", self.set_key, ["sun-right", True]) # , direct=True) self.accept("p-up", self.set_key, ["sun-right", False]) def toggle_lod_freeze(self): settings.debug_lod_freeze = not settings.debug_lod_freeze def toggle_split_merge_debug(self): settings.debug_lod_split_merge = not settings.debug_lod_split_merge def toggle_shader_debug_coord(self): settings.shader_debug_coord = not settings.shader_debug_coord self.engine.trigger_check_settings = True def toggle_bb(self): settings.debug_lod_show_bb = not settings.debug_lod_show_bb self.engine.trigger_check_settings = True def toggle_frustum(self): settings.debug_lod_frustum = not settings.debug_lod_frustum self.engine.trigger_check_settings = True def debug_ls(self): self.engine.scene_manager.ls() if self.engine.physics is not None: self.engine.physics.ls() def debug_print_tasks(self): print(taskMgr) def update(self, time, dt): if self.keymap.get("sun-left"): self.sun.set_light_angle(self.sun.light_angle + 30 * dt) if self.keymap.get("sun-right"): self.sun.set_light_angle(self.sun.light_angle - 30 * dt) def get_point_radiance(self, distance): return 1 / pi class SimpleShadowCaster(CustomShadowMapShadowCaster): def update(self): pass class RalphAppConfig: def __init__(self): self.test_start = False class RoamingRalphDemo(CosmoniumBase): def create_tile(self, x, y): self.terrain_shape.add_root_patch(x, y) def create_terrain(self): self.terrain_world = self.worlds.terrain if self.terrain_world is not None: self.terrain_surface = self.terrain_world.surface self.terrain_shape = self.terrain_surface.shape if self.has_water: self.terrain_shape.factory.add_layer_factory(WaterLayerFactory(self.water)) if self.physics is not None and self.physics.support_heightmap: self.terrain_shape.factory.add_layer_factory(PhysicsLayerFactory(self.physics)) else: self.terrain_shape = None async def create_instance(self): # TODO: Should do init correctly WaterNode.z = self.water.level WaterNode.observer = self.observer if self.has_water: WaterNode.create_cam() def spawn_box(self): if not self.physics: return if self.ralph_config.physics_config.model is None: return box = PhysicsBox( self.ralph_config.physics_config.model, self.physics, self.ralph_config.physics_config.mass, self.ralph_config.physics_config.limit, ) box.create_instance(self.ralph_world.anchor) self.physic_objects.append(box) def toggle_water(self): if not self.has_water: return self.water.visible = not self.water.visible if self.water.visible: WaterNode.create_cam() else: WaterNode.remove_cam() self.terrain_shape.check_settings() def get_height(self, position): height = self.terrain_surface.get_height_under(position) if self.has_water and self.water.visible and height < self.water.level: height = self.water.level return height # Used by populator def get_height_patch(self, patch, u, v): height = self.terrain_surface.get_height_patch(patch, u, v) if self.has_water and self.water.visible and height < self.water.level: height = self.water.level return height def set_ambient(self, ambient): settings.global_ambient = clamp(ambient, 0.0, 1.0) if settings.use_srgb: corrected_ambient = pow(settings.global_ambient, 2.2) else: corrected_ambient = settings.global_ambient settings.corrected_global_ambient = corrected_ambient builtins.base.render.set_shader_input("global_ambient", settings.corrected_global_ambient) print("Ambient light level: %.2f" % settings.global_ambient) def incr_ambient(self, ambient_incr): self.set_ambient(settings.global_ambient + ambient_incr) # TODO: Needed by patchedshapes.py update_lod() def get_min_radius(self): return 0 def __init__(self, args): self.app_config = RalphAppConfig() CosmoniumBase.__init__(self) SceneWorld.context = self self.update_id = 0 settings.color_picking = False settings.scale = 1.0 settings.use_depth_scaling = False settings.infinite_far_plane = False self.gui = None self.worlds = FlatUniverse() if args.config is not None: self.config_file = args.config else: self.config_file = 'ralph-data/ralph.yaml' self.splash = NoSplash() self.ralph_config = RalphConfigParser(self.worlds) if self.ralph_config.load_and_parse(self.config_file) is None: sys.exit(1) self.has_water = True self.water = self.ralph_config.water self.physics = self.ralph_config.physics if self.physics: self.physics.enable() self.physics.set_gravity(self.ralph_config.physics_config.gravity) if self.ralph_config.physics_config.debug: print("Disabling camera at origin") settings.camera_at_origin = False mesh.set_physics_engine('bullet') self.physic_objects = [] self.fullscreen = False self.shadow_caster = None self.set_ambient(settings.global_ambient) self.shadows = True self.pssm_shadows = True self.init_c_settings() self.cam.node().set_camera_mask(BaseObject.DefaultCameraFlag | BaseObject.NearCameraFlag) self.observer = CameraHolder() self.observer.init() if C_CameraHolder is not None: self.c_camera_holder = C_CameraHolder(self.observer.anchor, self.observer.camera_np, self.observer.lens) else: self.c_camera_holder = self.observer self.update_c_settings() self.scene_manager = StaticSceneManager(builtins.base.render) self.scene_manager.init_camera(self.c_camera_holder, self.cam) remove_main_region(self.cam) self.scene_manager.scale = 1.0 self.pipeline.create() self.pipeline.set_scene_manager(self.scene_manager) self.context = self self.oid_color = 0 self.oid_texture = None builtins.base.setFrameRateMeter(True) taskMgr.add(self.init()) def init_c_settings(self): if c_settings is not None: c_settings.offset_body_center = settings.offset_body_center c_settings.camera_at_origin = settings.camera_at_origin c_settings.use_depth_scaling = settings.use_depth_scaling c_settings.use_inv_scaling = settings.use_inv_scaling c_settings.use_log_scaling = settings.use_log_scaling c_settings.inverse_z = settings.use_inverse_z c_settings.default_near_plane = settings.near_plane c_settings.infinite_far_plane = settings.infinite_far_plane c_settings.default_far_plane = settings.far_plane c_settings.infinite_plane = settings.infinite_plane c_settings.auto_infinite_plane = settings.auto_infinite_plane c_settings.lens_far_limit = settings.lens_far_limit def update_c_settings(self): if self.c_camera_holder is not None: self.c_camera_holder.cos_fov2 = self.observer.cos_fov2 async def init(self): self.create_terrain() await self.create_instance() if self.terrain_world is not None: self.create_tile(0, 0) # Create the main character, Ralph self.ralph_shape_object = self.ralph_config.ralph_shape_object self.ralph_world = RalphWord( 'ralph', self.ralph_shape_object, self.ralph_config.ralph_physics_shape, 1.5, self.physics ) self.worlds.add_world(self.ralph_world) self.worlds.add_special(self.ralph_world) self.ralph_world.anchor.do_update() if self.shadows: if self.pssm_shadows: self.worlds.set_global_shadows( PSSMShadowMapShadowCaster(self.worlds.lights.lights[0], self.ralph_world) ) else: self.shadow_caster = SimpleShadowCaster(self.light, self.terrain_world) self.shadow_caster.create() self.shadow_caster.shadow_map.set_lens( self.ralph_config.shadow_size, -self.ralph_config.shadow_box_length / 2.0, self.ralph_config.shadow_box_length / 2.0, self.skybox.light_dir, ) self.shadow_caster.shadow_map.snap_cam = True else: self.shadow_caster = None self.camera_controller = self.ralph_config.camera_controller self.camera_controller.set_terrain(self.terrain_world) self.camera_controller.activate(self.observer, self.ralph_world.anchor) self.controller = RalphControl(self.worlds.lights.lights[0], self) self.controller.register_events() if self.physics is None or not self.physics.support_heightmap: if self.terrain_world: self.mover = FlatSurfaceBodyMover(self.ralph_world.anchor, self.terrain_world) else: self.mover = CartesianBodyMover(self.ralph_world.anchor) else: self.mover = BulletMover(self.ralph_world) self.mover.activate() if self.ralph_config.start_position is not None: self.mover.set_local_position(LPoint3d(*self.ralph_config.start_position)) if self.mover.kinetic_mover: self.nav = KineticNav() else: self.nav = ControlNav() self.nav.set_controller(self.mover) self.nav.register_events(self) self.nav.speed = 2 self.nav.rot_step_per_sec = 2 self.ralph_world.mover = self.mover self.worlds.init() self.taskMgr.add(self.main_update_task, "main-update-task", sort=settings.main_update_task_sort) self.taskMgr.add(self.update_lod_task, "update_lod-task", sort=settings.update_lod_task_sort) self.taskMgr.add(self.update_instances_task, "update-instances-task", sort=settings.update_instances_task_sort) def main_update_task(self, task): dt = globalClock.get_dt() self.update_id += 1 self.pipeline.process_last_frame(dt) if self.trigger_check_settings: self.worlds.check_settings() self.trigger_check_settings = False self.mover.feedback() self.worlds.start_update() self.worlds.update_specials(0, self.update_id) self.nav.update(0, dt) self.controller.update(0, dt) self.mover.update() if self.physics: to_remove = [] self.physics.update(0, dt) for physic_object in self.physic_objects: keep = physic_object.update(self.observer) if not keep: to_remove.append(physic_object) for physic_object in to_remove: self.physic_objects.remove(physic_object) self.worlds.update_specials_after_physics(0, self.update_id) self.camera_controller.update(0, dt) self.worlds.update_specials_observer(self.observer, self.update_id) self.worlds.update(0, dt, self.update_id, self.observer) self.worlds.update_height_under(self.observer) if self.shadow_caster is not None: if self.pssm_shadows: pass # self.shadow_caster.update(self.scene_manager) else: vec = self.ralph_world.anchor.get_local_position() - self.observer.anchor.get_local_position() vec.set_z(0) dist = vec.length() vec.normalize() # TODO: Should use the directional light to set the pos self.shadow_caster.shadow_map.set_direction(self.skybox.light_dir) self.shadow_caster.shadow_map.set_pos( self.ralph_world.anchor.get_local_position() - vec * dist + vec * self.ralph_config.shadow_size / 2 ) self.scene_manager.update_scene_and_camera(0, self.c_camera_holder) self.worlds.update_states() self.worlds.update_scene_anchors(self.scene_manager) # self.worlds.check_scattering() self.worlds.find_shadows() self.worlds.update_instances_state(self.scene_manager) self.worlds.create_instances(self.scene_manager, self.observer) return task.cont def update_lod_task(self, task): self.worlds.update_lod(self.observer) return task.cont def update_instances_task(self, task): self.worlds.update_instances(self.scene_manager, self.observer) self.scene_manager.build_scene( self.common_state, self.c_camera_holder, self.worlds.visible_scene_anchors, self.worlds.resolved_scene_anchors, ) return task.cont def print_debug(self): if self.terrain_world is not None: print( "Height:", self.get_height(self.ralph_world.anchor.get_local_position()), self.terrain_surface.get_height_under(self.ralph_world.anchor.get_local_position()), ) print( "Ralph:", self.ralph_world.anchor.get_local_position(), self.ralph_world.anchor.get_frame_position(), self.ralph_world.anchor.get_frame_orientation().get_hpr(), self.ralph_world.anchor.get_absolute_orientation().get_hpr(), ) print("Camera:", self.observer.get_local_position(), self.observer.get_absolute_orientation().get_hpr()) position = self.ralph_world.anchor.get_local_position() coord = self.terrain_surface.shape.parametric_to_shape_coord(position[0], position[1]) patch = self.terrain_surface.shape.find_patch_at(coord) if patch is not None: print("Ralph patch:", patch.str_id()) position = self.observer.anchor.get_local_position() coord = self.terrain_surface.shape.parametric_to_shape_coord(position[0], position[1]) patch = self.terrain_surface.shape.find_patch_at(coord) if patch is not None: print("Camera patch:", patch.str_id()) parser = argparse.ArgumentParser() parser.add_argument("--config", help="Path to the file with the configuration", default=None) if sys.platform == "darwin": # Ignore -psn_<app_id> from MacOS parser.add_argument('-p', help=argparse.SUPPRESS) args = parser.parse_args() demo = RoamingRalphDemo(args) demo.run()
412
0.798648
1
0.798648
game-dev
MEDIA
0.565166
game-dev
0.834102
1
0.834102
morty6688/cs61b-sp18
4,136
lab15/huglife/SampleCreature.java
package huglife; import java.awt.Color; import java.util.Map; import java.util.List; /** Example of a creature you might create for your world. * * The SampleCreature is an immortal pacifist that wanders the * world eternally, never replicating or attacking. * * SCs doesn't like crowds, and if surrounded on three sides, will * move into any available space. * * Even if not surrounded, the SC will take a step with 20% * probability towards any empty space nearby. * * If a SampleCreature stands still, its color will change slightly, * but only in the red portion of its color. * * @author Josh Hug */ public class SampleCreature extends Creature { /** red color. */ private int r = 155; /** green color. */ private int g = 61; /** blue color. */ private int b = 76; /** probability of taking a move when ample space available. */ private double moveProbability = 0.2; /** degree of color shift to allow. */ private int colorShift = 5; /** fraction of energy to retain when replicating. */ private double repEnergyRetained = 0.3; /** fraction of energy to bestow upon offspring. */ private double repEnergyGiven = 0.65; /** Creates a sample creature with energy E. This * value isn't relevant to the life of a SampleCreature, since * its energy should never decrease. */ public SampleCreature(double e) { super("samplecreature"); energy = e; } /** Default constructor: Creatures creature with energy 1. */ public SampleCreature() { this(1); } /** Uses method from Occupant to return a color based on personal. * r, g, b values */ public Color color() { return color(r, g, b); } /** Do nothing, SampleCreatures are pacifists and won't pick this * action anyway. C is safe, for now. */ public void attack(Creature c) { } /** Nothing special happens when a SampleCreature moves. */ public void move() { } /** If a SampleCreature stands still, its red color shifts slightly, with * special code to keep it from going negative or above 255. * * You will probably find the HugLifeUtils library useful for generating * random information. */ public void stay() { r += HugLifeUtils.randomInt(-colorShift, colorShift); r = Math.min(r, 255); r = Math.max(r, 0); } /** Sample Creatures take actions according to the following rules about * NEIGHBORS: * 1. If surrounded on three sides, move into the empty space. * 2. Otherwise, if there are any empty spaces, move into one of them with * probabiltiy given by moveProbability. * 3. Otherwise, stay. * * Returns the action selected. */ public Action chooseAction(Map<Direction, Occupant> neighbors) { List<Direction> empties = getNeighborsOfType(neighbors, "empty"); if (empties.size() == 1) { Direction moveDir = empties.get(0); return new Action(Action.ActionType.MOVE, moveDir); } if (empties.size() > 1) { if (HugLifeUtils.random() < moveProbability) { Direction moveDir = HugLifeUtils.randomEntry(empties); return new Action(Action.ActionType.MOVE, moveDir); } } return new Action(Action.ActionType.STAY); } /** If a SampleCreature were to replicate, it would keep only 30% of its * energy, and a new baby creature would be returned that possesses 65%, * with 5% lost to the universe. * * However, as you'll see above, SampleCreatures never choose to * replicate, so this method should never be called. It is provided * because the Creature class insist we know how to replicate boo. * * If somehow this method were called, it would return a new * SampleCreature. */ public SampleCreature replicate() { energy = energy * repEnergyRetained; double babyEnergy = energy * repEnergyGiven; return new SampleCreature(babyEnergy); } }
412
0.907491
1
0.907491
game-dev
MEDIA
0.540479
game-dev
0.632335
1
0.632335
microsoft/vsminecraft
1,216
minecraftpkg/MekanismModSample/src/main/java/mekanism/common/item/ItemDust.java
package mekanism.common.item; import java.util.List; import mekanism.common.Resource; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; public class ItemDust extends ItemMekanism { public IIcon[] icons = new IIcon[256]; public ItemDust() { super(); setHasSubtypes(true); } @Override public void registerIcons(IIconRegister register) { for(int i = 0; i < Resource.values().length; i++) { icons[i] = register.registerIcon("mekanism:" + Resource.values()[i].getName() + "Dust"); } } @Override public IIcon getIconFromDamage(int meta) { return icons[meta]; } @Override public void getSubItems(Item item, CreativeTabs tabs, List itemList) { for(int counter = 0; counter < Resource.values().length; counter++) { itemList.add(new ItemStack(this, 1, counter)); } } @Override public String getUnlocalizedName(ItemStack item) { if(item.getItemDamage() <= Resource.values().length-1) { return "item." + Resource.values()[item.getItemDamage()].getName().toLowerCase() + "Dust"; } return "Invalid"; } }
412
0.552951
1
0.552951
game-dev
MEDIA
0.998438
game-dev
0.789744
1
0.789744
ONSdigital/aims-api
1,110
model/src/main/scala/uk/gov/ons/addressIndex/model/db/index/Relative.scala
package uk.gov.ons.addressIndex.model.db.index /** * Relative DTO * Relatives response contains a sequence of Relative objects, one per level */ case class Relative(level: Int, siblings: Seq[Long], parents: Seq[Long]) /** * Relative DTO companion object includes method to cast from elastic response * Relatives response contains a sequence of Relative objects, one per level * If there is only one sibling it is the same as the main uprn */ object Relative { object Fields { /** * Document Fields */ val level: String = "level" val siblings: String = "siblings" val parents: String = "parents" } def fromEsMap(rels: Map[String, Any]): Relative = { Relative( rels.getOrElse(Fields.level, 0).asInstanceOf[Int], // uprns sometimes come back as Integers instead of Longs from ES so need to deal with this rels.getOrElse(Fields.siblings, Seq.empty).asInstanceOf[Seq[Any]].map(_.toString.toLong), rels.getOrElse(Fields.parents, Seq.empty).asInstanceOf[Seq[Any]].map(_.toString.toLong) ) } }
412
0.919771
1
0.919771
game-dev
MEDIA
0.164192
game-dev
0.939387
1
0.939387
HPW-dev/HPW-Demo
1,111
src/game/util/replay.hpp
#pragma once #include <optional> #include "util/str.hpp" #include "util/macro.hpp" #include "util/mem-types.hpp" #include "util/math/num-types.hpp" #include "util/vector-types.hpp" #include "game/util/keybits.hpp" #include "game/core/difficulty.hpp" using Key_packet = Vector<hpw::keycode>; // Game replay (keylogger) class Replay final { public: struct Info; explicit Replay(cr<Str> path, bool write_mode); ~Replay(); void close(); void push(cr<Key_packet> key_packet); std::optional<Key_packet> pop(); // будет возвращать нажатые клавиши, пока не кончатся static Info get_info(cr<Str> path); utf32 warnings() const; // посмотреть проблемы с реплеем, если они есть private: nocopy(Replay); struct Impl; Unique<Impl> impl {}; }; struct Date { uint year {}; uint month {}; uint day {}; uint hour {}; uint minute {}; uint second {}; }; struct Replay::Info { Date date {}; utf32 player_name {}; Str path {}; Str date_str {}; Str hud_name {}; std::int64_t score {}; Difficulty difficulty {}; bool first_level_is_tutorial {}; }; Str get_random_replay_name();
412
0.722821
1
0.722821
game-dev
MEDIA
0.489597
game-dev,desktop-app
0.520537
1
0.520537
space-wizards/RobustToolbox
11,969
Robust.Server/GameStates/PvsSystem.Chunks.cs
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Prometheus; using Robust.Shared.Enums; using Robust.Shared.GameObjects; using Robust.Shared.Map.Components; using Robust.Shared.Map.Enumerators; using Robust.Shared.Maths; using Robust.Shared.Player; using Robust.Shared.Utility; namespace Robust.Server.GameStates; // Partial class for handling PVS chunks. internal sealed partial class PvsSystem { public const float ChunkSize = 8; private readonly Dictionary<PvsChunkLocation, PvsChunk> _chunks = new(); private readonly List<PvsChunk> _dirtyChunks = new(64); private readonly List<PvsChunk> _cleanChunks = new(64); // Store chunks grouped by the root node, for when maps/grids get deleted. private readonly Dictionary<EntityUid, HashSet<PvsChunkLocation>> _chunkSets = new(); private List<Entity<MapGridComponent>> _grids = new(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2i GetChunkIndices(Vector2 coordinates) => (coordinates / ChunkSize).Floored(); /// <summary> /// Iterate over all visible chunks and, if necessary, re-construct their list of entities. /// </summary> private void UpdateDirtyChunks(int index) { var chunk = _dirtyChunks[index]; DebugTools.Assert(chunk.Dirty); DebugTools.Assert(chunk.UpdateQueued); if (!chunk.PopulateContents(_metaQuery, _xformQuery)) return; // Failed to populate a dirty chunk. UpdateChunkPosition(chunk); } private void UpdateCleanChunks() { foreach (var chunk in CollectionsMarshal.AsSpan(_cleanChunks)) { UpdateChunkPosition(chunk); } } /// <summary> /// Update a chunk's world position. This is used to prioritize sending chunks that a closer to players. /// </summary> private void UpdateChunkPosition(PvsChunk chunk) { if (chunk.Root.Comp == null || chunk.Map.Comp == null || chunk.Root.Comp.EntityLifeStage >= EntityLifeStage.Terminating || chunk.Map.Comp.EntityLifeStage >= EntityLifeStage.Terminating) { Log.Error($"Encountered deleted root while updating pvs chunk positions. Root: {ToPrettyString(chunk.Root, chunk.Root)}. Map: {ToPrettyString(chunk.Map, chunk.Map)}" ); return; } var xform = Transform(chunk.Root); DebugTools.AssertEqual(chunk.Map.Owner, xform.MapUid); chunk.InvWorldMatrix = xform.InvLocalMatrix; var worldPos = Vector2.Transform(chunk.Centre, xform.LocalMatrix); chunk.Position = new(worldPos, xform.MapID); chunk.UpdateQueued = false; } /// <summary> /// Update the list of all currently visible chunks. /// </summary> internal void GetVisibleChunks() { using var _= Histogram.WithLabels("Get Chunks").NewTimer(); DebugTools.Assert(!_chunks.Values.Any(x=> x.UpdateQueued)); _dirtyChunks.Clear(); _cleanChunks.Clear(); foreach (var session in _sessions) { session.Chunks.Clear(); session.ChunkSet.Clear(); GetSessionViewers(session); foreach (var eye in session.Viewers) { GetVisibleChunks(eye, session.ChunkSet); } } DebugTools.Assert(_dirtyChunks.ToHashSet().Count == _dirtyChunks.Count); DebugTools.Assert(_cleanChunks.ToHashSet().Count == _cleanChunks.Count); } /// <summary> /// Get the chunks visible to a single entity and add them to a player's set of visible chunks. /// </summary> private void GetVisibleChunks(Entity<TransformComponent, EyeComponent?> eye, HashSet<PvsChunk> chunks) { var (viewPos, range, mapUid) = CalcViewBounds(eye); if (mapUid is not {} map) return; var mapChunkEnumerator = new ChunkIndicesEnumerator(viewPos, range, ChunkSize); while (mapChunkEnumerator.MoveNext(out var chunkIndices)) { var loc = new PvsChunkLocation(map, chunkIndices.Value); if (!_chunks.TryGetValue(loc, out var chunk)) continue; chunks.Add(chunk); if (chunk.UpdateQueued) continue; chunk.UpdateQueued = true; if (chunk.Dirty) _dirtyChunks.Add(chunk); else _cleanChunks.Add(chunk); } _grids.Clear(); var rangeVec = new Vector2(range, range); var box = new Box2(viewPos - rangeVec, viewPos + rangeVec); _mapManager.FindGridsIntersecting(map, box, ref _grids, approx: true, includeMap: false); foreach (var (grid, _) in _grids) { var localPos = Vector2.Transform(viewPos, _transform.GetInvWorldMatrix(grid)); var gridChunkEnumerator = new ChunkIndicesEnumerator(localPos, range, ChunkSize); while (gridChunkEnumerator.MoveNext(out var gridChunkIndices)) { var loc = new PvsChunkLocation(grid, gridChunkIndices.Value); if (!_chunks.TryGetValue(loc, out var chunk)) continue; chunks.Add(chunk); if (chunk.UpdateQueued) continue; chunk.UpdateQueued = true; if (chunk.Dirty) _dirtyChunks.Add(chunk); else _cleanChunks.Add(chunk); } } } /// <summary> /// Get all viewers for a given session. This is required to get a list of visible chunks. /// </summary> private void GetSessionViewers(PvsSession pvsSession) { var session = pvsSession.Session; if (session.Status != SessionStatus.InGame) { pvsSession.Viewers = Array.Empty<Entity<TransformComponent, EyeComponent?>>(); return; } // The majority of players will have no view subscriptions if (session.ViewSubscriptions.Count == 0) { if (session.AttachedEntity is not {} attached) { pvsSession.Viewers = Array.Empty<Entity<TransformComponent, EyeComponent?>>(); return; } Array.Resize(ref pvsSession.Viewers, 1); pvsSession.Viewers[0] = (attached, Transform(attached), _eyeQuery.CompOrNull(attached)); return; } var count = session.ViewSubscriptions.Count; var i = 0; if (session.AttachedEntity is { } local) { if (!session.ViewSubscriptions.Contains(local)) count += 1; Array.Resize(ref pvsSession.Viewers, count); // Attached entity is always the first viewer, to prioritize it and help reduce pop-in for the "main" eye. pvsSession.Viewers[i++] = (local, Transform(local), _eyeQuery.CompOrNull(local)); } else { Array.Resize(ref pvsSession.Viewers, count); } foreach (var ent in session.ViewSubscriptions) { if (ent != session.AttachedEntity) pvsSession.Viewers[i++] = (ent, Transform(ent), _eyeQuery.CompOrNull(ent)); } DebugTools.AssertEqual(i, pvsSession.Viewers.Length); } private void ProcessVisibleChunks() { using var _= Histogram.WithLabels("Update Chunks & Overrides").NewTimer(); var task = _parallelMgr.Process(_chunkJob, _chunkJob.Count); UpdateCleanChunks(); CacheGlobalOverrides(); task.WaitOne(); } /// <summary> /// Variant of <see cref="ProcessVisibleChunks"/> that isn't multithreaded. /// </summary> internal void ProcessVisibleChunksSequential() { for (var i = 0; i < _dirtyChunks.Count; i++) { UpdateDirtyChunks(i); } UpdateCleanChunks(); CacheGlobalOverrides(); } /// <summary> /// Add an entity to the set of entities that are directly attached to a chunk and mark the chunk as dirty. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AddEntityToChunk(EntityUid uid, MetaDataComponent meta, PvsChunkLocation location) { DebugTools.Assert(meta.EntityLifeStage < EntityLifeStage.Terminating); ref var chunk = ref CollectionsMarshal.GetValueRefOrAddDefault(_chunks, location, out var existing); if (!existing) { chunk = _chunkPool.Get(); try { chunk.Initialize(location, _metaQuery, _xformQuery); } catch (Exception) { _chunks.Remove(location); throw; } _chunkSets.GetOrNew(location.Uid).Add(location); } chunk!.MarkDirty(); chunk.Children.Add(uid); meta.LastPvsLocation = location; } /// <summary> /// Remove an entity from a chunk and mark it as dirty. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RemoveEntityFromChunk(EntityUid uid, MetaDataComponent meta) { if (meta.LastPvsLocation is not {} old) return; meta.LastPvsLocation = null; if (!_chunks.TryGetValue(old, out var chunk)) return; chunk.MarkDirty(); chunk.Children.Remove(uid); if (chunk.Children.Count > 0) return; _chunks.Remove(old); _chunkPool.Return(chunk); _chunkSets[old.Uid].Remove(old); } /// <summary> /// Mark a chunk as dirty. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private void DirtyChunk(PvsChunkLocation location) { if (_chunks.TryGetValue(location, out var chunk)) chunk.MarkDirty(); } /// <summary> /// Mark all chunks as dirty. /// </summary> private void DirtyAllChunks() { foreach (var chunk in _chunks.Values) { chunk.MarkDirty(); } } private void OnGridRemoved(GridRemovalEvent ev) { RemoveRoot(ev.EntityUid); } private void OnMapChanged(MapRemovedEvent ev) { RemoveRoot(ev.Uid); } private void RemoveRoot(EntityUid root) { if (!_chunkSets.Remove(root, out var locations)) { DebugTools.Assert(_chunks.Values.All(x => x.Map.Owner != root && x.Root.Owner != root)); return; } DebugTools.Assert(_chunks.Values.All(x => locations.Contains(x.Location) || x.Root.Owner != root)); foreach (var loc in locations) { if (_chunks.Remove(loc, out var chunk)) _chunkPool.Return(chunk); } DebugTools.Assert(_chunks.Values.All(x => x.Map.Owner != root && x.Root.Owner != root)); } internal void GridParentChanged(Entity<TransformComponent, MetaDataComponent> grid) { if (!_chunkSets.TryGetValue(grid.Owner, out var locations)) { DebugTools.Assert(_chunks.Values.All(x => x.Root.Owner != grid.Owner)); return; } DebugTools.Assert(_chunks.Values.All(x => locations.Contains(x.Location) || x.Root.Owner != grid.Owner)); if (grid.Comp1.MapUid is not { } map || !TryComp(map, out MetaDataComponent? meta)) { if (grid.Comp2.EntityLifeStage < EntityLifeStage.Terminating) Log.Error($"Grid {ToPrettyString(grid)} has no map?"); RemoveRoot(grid.Owner); return; } var newMap = new Entity<MetaDataComponent>(map, meta); foreach (var loc in locations) { if (_chunks.TryGetValue(loc, out var chunk)) chunk.Map = newMap; } } }
412
0.892565
1
0.892565
game-dev
MEDIA
0.913679
game-dev
0.990873
1
0.990873
Darkrp-community/OpenKeep
1,540
code/controllers/subsystem/rogue/role_class_handler/drifter_queue/drifter_waves/drifter_wave.dm
/datum/drifter_wave/drifters // Name of the wave to be shown where relevant wave_type_name = "Adventurers" // Maximum playercount of wave maximum_playercount = 6 // Tooltip when moused over on wave wave_type_tooltip = "A band of immigrants searching for fame and fortune." // Title of the job related to the job subsystem thats being made/equipped towards for the wave job_rank = "Drifter" drifter_wave_categories = list(DTAG_FILLERS) advclass_cat_rolls = list(CTAG_PILGRIM = 26, CTAG_ADVENTURER = 22) class_cat_plusboost_attempts = list(CTAG_PILGRIM = 3) // Here you go buddy, have a 3 on pilgrims wave_delay_time = 2 MINUTES // BUILD THE LIST! drifter_dropzone_targets = list() /datum/drifter_wave/drifters/build_dropzone() // This will be full of turfs var/list/potential_target_dropzones = list() for(var/obj/effect/landmark/cur_landmark in GLOB.landmarks_list) if(istype(cur_landmark, /obj/effect/landmark/start/adventurerlate)) potential_target_dropzones += cur_landmark if(!potential_target_dropzones.len) if(SSjob.latejoin_trackers.len) potential_target_dropzones += pick(SSjob.latejoin_trackers) var/atom/TITS = pick(potential_target_dropzones) // Well we got our thing // we try our best to deploy each guy into his own turf ok this def needs to be less retarded but the map landmarks can be retarded var/rows_2_make = ceil(maximum_playercount/2) for(var/turf/T in block(TITS.x-1, TITS.y-2, TITS.z, TITS.x+rows_2_make, TITS.y+1, TITS.z)) if(isopenturf(T)) drifter_dropzone_targets += T
412
0.847373
1
0.847373
game-dev
MEDIA
0.92567
game-dev
0.978865
1
0.978865
Arkensor/EnfusionPersistenceFramework
1,908
src/Scripts/Game/Entities/Character/EPF_CharacterInventoryStorageComponentSaveData.c
[EPF_ComponentSaveDataType(SCR_CharacterInventoryStorageComponent), BaseContainerProps()] class EPF_CharacterInventoryStorageComponentSaveDataClass : EPF_BaseInventoryStorageComponentSaveDataClass { [Attribute(defvalue: "10", uiwidget: UIWidgets.Slider, desc: "Maximum time until the quickbar is synced after a change in SECONDS. Higher values reduce traffic.", params: "1 1000 1")] int m_iMaxQuickbarSaveTime; }; [EDF_DbName.Automatic()] class EPF_CharacterInventoryStorageComponentSaveData : EPF_BaseInventoryStorageComponentSaveData { ref array<ref EPF_PersistentQuickSlotItem> m_aQuickSlotEntities; //------------------------------------------------------------------------------------------------ override EPF_EReadResult ReadFrom(IEntity owner, GenericComponent component, EPF_ComponentSaveDataClass attributes) { EPF_EReadResult result = super.ReadFrom(owner, component, attributes); if (!result) return EPF_EReadResult.ERROR; m_aQuickSlotEntities = {}; SCR_CharacterInventoryStorageComponent inventoryStorage = SCR_CharacterInventoryStorageComponent.Cast(component); foreach (int idx, auto quickslot: inventoryStorage.GetQuickSlotItems()) { auto quickslotEntity = SCR_QuickslotEntityContainer.Cast(quickslot); if (!quickslotEntity) continue; string persistentId = EPF_PersistenceComponent.GetPersistentId(quickslotEntity.GetEntity()); if (!persistentId) continue; EPF_PersistentQuickSlotItem slot(); slot.m_iIndex = idx; slot.m_sEntityId = persistentId; m_aQuickSlotEntities.Insert(slot); } if (result == EPF_EReadResult.DEFAULT && m_aQuickSlotEntities.IsEmpty()) return EPF_EReadResult.DEFAULT; return EPF_EReadResult.OK; } //! >>> "ApplyTo" happens in modded SCR_RespawnComponent as it needs to be done on the client and data is sent via RPC. <<< }; class EPF_PersistentQuickSlotItem { int m_iIndex; string m_sEntityId; };
412
0.94154
1
0.94154
game-dev
MEDIA
0.615815
game-dev
0.959601
1
0.959601
apache/camel-karavan
12,363
karavan-app/src/main/java/org/apache/camel/karavan/model/PodContainerStatus.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.karavan.model; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; public class PodContainerStatus { public enum State { created, running, restarting, paused, exited, dead } public enum Command { run, pause, stop, delete, } String projectId; String containerName; String containerId; String image; List<ContainerPort> ports; String env; ContainerType type; String memoryInfo; String cpuInfo; String created; String finished; List<Command> commands; String state; String phase; Boolean codeLoaded; Boolean inTransit = false; String initDate; String podIP; String camelRuntime; String commit; Map<String, String> labels; public PodContainerStatus(String projectId, String containerName, String containerId, String image, List<ContainerPort> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, String phase, Boolean codeLoaded, Boolean inTransit, String initDate, String podIP, String camelRuntime, String commit, Map<String, String> labels) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.phase = phase; this.codeLoaded = codeLoaded; this.inTransit = inTransit; this.initDate = initDate; this.podIP = podIP; this.camelRuntime = camelRuntime; this.commit = commit; this.labels = labels; } public PodContainerStatus(String projectId, String containerName, String containerId, String image, List<ContainerPort> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, String phase, Boolean codeLoaded, Boolean inTransit, String initDate, String podIP, String camelRuntime) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.phase = phase; this.codeLoaded = codeLoaded; this.inTransit = inTransit; this.initDate = initDate; this.podIP = podIP; this.camelRuntime = camelRuntime; } public PodContainerStatus(String projectId, String containerName, String containerId, String image, List<ContainerPort> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, String phase, Boolean codeLoaded, Boolean inTransit, String initDate, Map<String, String> labels) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.phase = phase; this.codeLoaded = codeLoaded; this.inTransit = inTransit; this.initDate = initDate; this.labels = labels; } public PodContainerStatus(String projectId, String containerName, String containerId, String image, List<ContainerPort> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, Boolean codeLoaded, Boolean inTransit, String camelRuntime, Map<String, String> labels) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.codeLoaded = codeLoaded; this.camelRuntime = camelRuntime; this.inTransit = inTransit; this.initDate = Instant.now().toString(); this.labels = labels; } public PodContainerStatus(String containerName, List<Command> commands, String projectId, String env, ContainerType type, String memoryInfo, String cpuInfo, String created) { this.containerName = containerName; this.commands = commands; this.projectId = projectId; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.initDate = Instant.now().toString(); } public PodContainerStatus(String containerName, List<Command> commands, String projectId, String env, ContainerType type, String created) { this.containerName = containerName; this.commands = commands; this.projectId = projectId; this.env = env; this.created = created; this.type = type; this.initDate = Instant.now().toString(); } public static PodContainerStatus createDevMode(String projectId, String env) { return new PodContainerStatus(projectId, projectId, null, null, null, env, ContainerType.devmode, null, null, null, null, List.of(Command.run), null, false, false, "", new HashMap<>()); } public static PodContainerStatus createByType(String name, String env, ContainerType type) { return new PodContainerStatus(name, name, null, null, null, env, type, null, null, null, null, List.of(Command.run), null, false, false, "", new HashMap<>()); } public static PodContainerStatus createWithId(String projectId, String containerName, String env, String containerId, String image, List<ContainerPort> ports, ContainerType type, List<Command> commands, String status, String created, String camelRuntime, Map<String, String> labels) { return new PodContainerStatus(projectId, containerName, containerId, image, ports, env, type, null, null, created, null, commands, status, false, false, camelRuntime, labels); } public PodContainerStatus() { } public PodContainerStatus copy() { return new PodContainerStatus( projectId, containerName, containerId, image, ports, env, type, memoryInfo, cpuInfo, created, finished, commands, state, phase, codeLoaded, inTransit, initDate, podIP, camelRuntime, commit, labels ); } public String getPodIP() { return podIP; } public void setPodIP(String podIP) { this.podIP = podIP; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getContainerName() { return containerName; } public void setContainerName(String containerName) { this.containerName = containerName; } public String getContainerId() { return containerId; } public void setContainerId(String containerId) { this.containerId = containerId; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public List<ContainerPort> getPorts() { return ports; } public void setPorts(List<ContainerPort> ports) { this.ports = ports; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } public ContainerType getType() { return type; } public void setType(ContainerType type) { this.type = type; } public String getMemoryInfo() { return memoryInfo; } public void setMemoryInfo(String memoryInfo) { this.memoryInfo = memoryInfo; } public String getCpuInfo() { return cpuInfo; } public void setCpuInfo(String cpuInfo) { this.cpuInfo = cpuInfo; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public List<Command> getCommands() { return commands; } public void setCommands(List<Command> commands) { this.commands = commands; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Boolean getCodeLoaded() { return codeLoaded; } public void setCodeLoaded(Boolean codeLoaded) { this.codeLoaded = codeLoaded; } public Boolean getInTransit() { return inTransit; } public void setInTransit(Boolean inTransit) { this.inTransit = inTransit; } public String getFinished() { return finished; } public void setFinished(String finished) { this.finished = finished; } public String getInitDate() { return initDate; } public void setInitDate(String initDate) { this.initDate = initDate; } public String getPhase() { return phase; } public void setPhase(String phase) { this.phase = phase; } public String getCamelRuntime() { return camelRuntime; } public void setCamelRuntime(String camelRuntime) { this.camelRuntime = camelRuntime; } public String getCommit() { return commit; } public void setCommit(String commit) { this.commit = commit; } public Map<String, String> getLabels() { return labels; } public void setLabels(Map<String, String> labels) { this.labels = labels; } @Override public String toString() { return "ContainerStatus{" + "projectId='" + projectId + '\'' + ", containerName='" + containerName + '\'' + ", containerId='" + containerId + '\'' + ", image='" + image + '\'' + ", ports=" + ports + ", env='" + env + '\'' + ", type=" + type + ", memoryInfo='" + memoryInfo + '\'' + ", cpuInfo='" + cpuInfo + '\'' + ", created='" + created + '\'' + ", finished='" + finished + '\'' + ", commands=" + commands + ", state='" + state + '\'' + ", phase='" + phase + '\'' + ", codeLoaded=" + codeLoaded + ", inTransit=" + inTransit + ", initDate='" + initDate + '\'' + ", podIP='" + podIP + '\'' + ", commit='" + commit + '\'' + ", labels='" + labels + '\'' + '}'; } }
412
0.525045
1
0.525045
game-dev
MEDIA
0.387177
game-dev
0.640461
1
0.640461
kettingpowered/Ketting-1-20-x
1,364
src/main/java/org/bukkit/event/raid/RaidSpawnWaveEvent.java
package org.bukkit.event.raid; import java.util.Collections; import java.util.List; import org.bukkit.Raid; import org.bukkit.World; import org.bukkit.entity.Raider; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Called when a raid wave spawns. */ public class RaidSpawnWaveEvent extends RaidEvent { private static final HandlerList handlers = new HandlerList(); // private final List<Raider> raiders; private final Raider leader; public RaidSpawnWaveEvent(@NotNull Raid raid, @NotNull World world, @Nullable Raider leader, @NotNull List<Raider> raiders) { super(raid, world); this.raiders = raiders; this.leader = leader; } /** * Returns the patrol leader. * * @return {@link Raider} */ @Nullable public Raider getPatrolLeader() { return leader; } /** * Returns all {@link Raider} that spawned in this wave. * * @return an immutable list of raiders */ @NotNull public List<Raider> getRaiders() { return Collections.unmodifiableList(raiders); } @NotNull @Override public HandlerList getHandlers() { return handlers; } @NotNull public static HandlerList getHandlerList() { return handlers; } }
412
0.806164
1
0.806164
game-dev
MEDIA
0.92041
game-dev
0.78039
1
0.78039
ciscocsirt/malspider
1,034
malspider/pipelines/DuplicateFilterPipeline.py
# -*- coding: utf-8 -*- # # Copyright (c) 2016-present, Cisco Systems, Inc. All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # from malspider import settings from malspider.items import PageLink from malspider.items import WebPage from malspider.items import Alert from scrapy.exceptions import DropItem class DuplicateFilterPipeline(object): def __init__(self): self.extracted_links = set() def process_item(self, item, spider): if not type(item) == PageLink: return item if 'raw' in item: if 'uri' in item and (item['uri'].startswith("#") or item['uri'].startswith("/")): raise DropItem("Dropping same origin uri: ", item['uri']) elif item['raw'] in self.extracted_links: raise DropItem("Duplicate item found: ", item['raw']) else: self.extracted_links.add(item['raw']) return item
412
0.80212
1
0.80212
game-dev
MEDIA
0.273026
game-dev
0.858969
1
0.858969
magefree/mage
2,117
Mage.Sets/src/mage/cards/m/Marut.java
package mage.cards.m; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.TreasureSpentToCastCondition; import mage.abilities.dynamicvalue.DynamicValue; import mage.abilities.effects.Effect; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.keyword.TrampleAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.game.Game; import mage.game.permanent.token.TreasureToken; import mage.watchers.common.ManaPaidSourceWatcher; import java.util.UUID; /** * @author TheElk801 */ public final class Marut extends CardImpl { public Marut(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{8}"); this.subtype.add(SubType.CONSTRUCT); this.power = new MageInt(7); this.toughness = new MageInt(7); // Trample this.addAbility(TrampleAbility.getInstance()); // When Marut enters the battlefield, if mana from a Treasure was spent to cast it, create a Treasure token for each mana from a Treasure spent to cast it. this.addAbility(new EntersBattlefieldTriggeredAbility( new CreateTokenEffect(new TreasureToken(), MarutValue.instance) ).withInterveningIf(TreasureSpentToCastCondition.instance)); } private Marut(final Marut card) { super(card); } @Override public Marut copy() { return new Marut(this); } } enum MarutValue implements DynamicValue { instance; @Override public int calculate(Game game, Ability sourceAbility, Effect effect) { return ManaPaidSourceWatcher.getTreasurePaid(sourceAbility.getSourceId(), game); } @Override public MarutValue copy() { return this; } @Override public String getMessage() { return "mana from a Treasure spent to cast it"; } @Override public String toString() { return "1"; } }
412
0.948719
1
0.948719
game-dev
MEDIA
0.975882
game-dev
0.995824
1
0.995824
ngud-119/GetFitness
1,847
Pods/leveldb-library/table/iterator.cc
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/iterator.h" namespace leveldb { Iterator::Iterator() { cleanup_head_.function = nullptr; cleanup_head_.next = nullptr; } Iterator::~Iterator() { if (!cleanup_head_.IsEmpty()) { cleanup_head_.Run(); for (CleanupNode* node = cleanup_head_.next; node != nullptr;) { node->Run(); CleanupNode* next_node = node->next; delete node; node = next_node; } } } void Iterator::RegisterCleanup(CleanupFunction func, void* arg1, void* arg2) { assert(func != nullptr); CleanupNode* node; if (cleanup_head_.IsEmpty()) { node = &cleanup_head_; } else { node = new CleanupNode(); node->next = cleanup_head_.next; cleanup_head_.next = node; } node->function = func; node->arg1 = arg1; node->arg2 = arg2; } namespace { class EmptyIterator : public Iterator { public: EmptyIterator(const Status& s) : status_(s) {} ~EmptyIterator() override = default; bool Valid() const override { return false; } void Seek(const Slice& target) override {} void SeekToFirst() override {} void SeekToLast() override {} void Next() override { assert(false); } void Prev() override { assert(false); } Slice key() const override { assert(false); return Slice(); } Slice value() const override { assert(false); return Slice(); } Status status() const override { return status_; } private: Status status_; }; } // anonymous namespace Iterator* NewEmptyIterator() { return new EmptyIterator(Status::OK()); } Iterator* NewErrorIterator(const Status& status) { return new EmptyIterator(status); } } // namespace leveldb
412
0.952941
1
0.952941
game-dev
MEDIA
0.166024
game-dev
0.857891
1
0.857891
huawei-noah/SMARTS
6,976
smarts/sstudio/sstypes/bubble.py
# MIT License # # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved. # # 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 NON-INFRINGEMENT. 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. from dataclasses import dataclass, field from typing import Optional, Tuple, Union from smarts.core import gen_id from smarts.core.condition_state import ConditionState from smarts.core.utils.id import SocialAgentId from smarts.sstudio.sstypes.actor.social_agent_actor import ( BoidAgentActor, SocialAgentActor, ) from smarts.sstudio.sstypes.actor.traffic_engine_actor import TrafficEngineActor from smarts.sstudio.sstypes.bubble_limits import BubbleLimits from smarts.sstudio.sstypes.condition import ( Condition, ConditionRequires, LiteralCondition, ) from smarts.sstudio.sstypes.zone import MapZone, Zone @dataclass(frozen=True) class Bubble: """A descriptor that defines a capture bubble for social agents. Bubbles consist of an airlock and hijack zone. The airlock is always the same size or larger than the hijack zone. A vehicle must first pass into the airlock and pass the conditions of the airlock to be considered by the hijack zone. """ zone: Zone """The zone which to capture vehicles.""" actor: Union[SocialAgentActor, TrafficEngineActor] """The actor specification that this bubble works for.""" margin: float = 2 """The exterior buffer area that extends the air-locking zone area. Must be >= 0.""" limit: Optional[BubbleLimits] = None """The maximum number of actors that could be captured. If limit != None it will only allow that specified number of vehicles to be hijacked. N.B. when actor = BoidAgentActor the lesser of the actor capacity and bubble limit will be used. """ exclusion_prefixes: Tuple[str, ...] = field(default_factory=tuple) """Used to exclude social actors from capture.""" id: str = field(default_factory=lambda: f"bubble-{gen_id()}") follow_actor_id: Optional[str] = None """Actor ID of agent we want to pin to. Doing so makes this a "traveling bubble" which means it moves to follow the `follow_actor_id`'s vehicle. Offset is from the vehicle's center position to the bubble's center position. """ follow_offset: Optional[Tuple[float, float]] = None """Maintained offset to place the traveling bubble relative to the follow vehicle if it were facing north. """ keep_alive: bool = False """If enabled, the social agent actor will be spawned upon first vehicle airlock and be reused for every subsequent vehicle entering the bubble until the episode is over. """ follow_vehicle_id: Optional[str] = None """Vehicle ID of a vehicle we want to pin to. Doing so makes this a "traveling bubble" which means it moves to follow the `follow_vehicle_id`'s vehicle. Offset is from the vehicle's center position to the bubble's center position. """ active_condition: Condition = LiteralCondition(ConditionState.TRUE) """Conditions that determine if the bubble is enabled.""" airlock_condition: Condition = LiteralCondition(ConditionState.TRUE) """This condition is used to determine if an actor is allowed into the bubble airlock. """ def __post_init__(self): if self.margin < 0: raise ValueError("Airlocking margin must be greater than 0") if self.follow_actor_id is not None and self.follow_vehicle_id is not None: raise ValueError( "Only one option of follow actor id and follow vehicle id can be used at any time." ) if ( self.follow_actor_id is not None or self.follow_vehicle_id is not None ) and self.follow_offset is None: raise ValueError( "A follow offset must be set if this is a traveling bubble" ) if self.keep_alive and not self.is_boid: # TODO: We may want to remove this restriction in the future raise ValueError( "Only boids can have keep_alive enabled (for persistent boids)" ) if not isinstance(self.zone, MapZone): poly = self.zone.to_geometry(road_map=None) if not poly.is_valid: follow_id = ( self.follow_actor_id if self.follow_actor_id else self.follow_vehicle_id ) raise ValueError( f"The zone polygon of {type(self.zone).__name__} of moving {self.id} which following {follow_id} is not a valid closed loop" if follow_id else f"The zone polygon of {type(self.zone).__name__} of fixed position {self.id} is not a valid closed loop" ) invalid_condition_requires = ( ConditionRequires.any_current_actor_state & self.active_condition.requires ) if invalid_condition_requires != ConditionRequires.none: raise ValueError( "Actor state conditions not allowed in broadphase inclusion." f"Invalid conditions requirements: {invalid_condition_requires}" ) @staticmethod def to_actor_id(actor, mission_group): """Mashes the actor id and mission group to create what needs to be a unique id.""" return SocialAgentId.new(actor.name, group=mission_group) @property def is_boid(self): """Tests if the actor is to control multiple vehicles.""" return isinstance(self.actor, (BoidAgentActor, TrafficEngineActor)) @property def traffic_provider(self) -> Optional[str]: """The name of the traffic provider used if the actor is to be controlled by a traffic engine. Returns: (Optional[str]): The name of the traffic provider or `None`. """ return ( self.actor.traffic_provider if isinstance(self.actor, TrafficEngineActor) else None )
412
0.781439
1
0.781439
game-dev
MEDIA
0.522747
game-dev,ml-ai
0.86447
1
0.86447
ultralight-ux/WebCore
3,565
Source/WebCore/rendering/svg/SVGSubpathData.h
/* * Copyright (C) 2012 Google, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #pragma once #include "Path.h" #include <wtf/Forward.h> namespace WebCore { class SVGSubpathData { public: SVGSubpathData(Vector<FloatPoint>& zeroLengthSubpathLocations) : m_zeroLengthSubpathLocations(zeroLengthSubpathLocations) { } static void updateFromPathElement(SVGSubpathData& subpathFinder, const PathElement& element) { switch (element.type) { case PathElementMoveToPoint: if (subpathFinder.m_pathIsZeroLength && !subpathFinder.m_haveSeenMoveOnly) subpathFinder.m_zeroLengthSubpathLocations.append(subpathFinder.m_lastPoint); subpathFinder.m_lastPoint = subpathFinder.m_movePoint = element.points[0]; subpathFinder.m_haveSeenMoveOnly = true; subpathFinder.m_pathIsZeroLength = true; break; case PathElementAddLineToPoint: if (subpathFinder.m_lastPoint != element.points[0]) { subpathFinder.m_pathIsZeroLength = false; subpathFinder.m_lastPoint = element.points[0]; } subpathFinder.m_haveSeenMoveOnly = false; break; case PathElementAddQuadCurveToPoint: if (subpathFinder.m_lastPoint != element.points[0] || element.points[0] != element.points[1]) { subpathFinder.m_pathIsZeroLength = false; subpathFinder.m_lastPoint = element.points[1]; } subpathFinder.m_haveSeenMoveOnly = false; break; case PathElementAddCurveToPoint: if (subpathFinder.m_lastPoint != element.points[0] || element.points[0] != element.points[1] || element.points[1] != element.points[2]) { subpathFinder.m_pathIsZeroLength = false; subpathFinder.m_lastPoint = element.points[2]; } subpathFinder.m_haveSeenMoveOnly = false; break; case PathElementCloseSubpath: if (subpathFinder.m_pathIsZeroLength) subpathFinder.m_zeroLengthSubpathLocations.append(subpathFinder.m_lastPoint); subpathFinder.m_haveSeenMoveOnly = true; // This is an implicit move for the next element subpathFinder.m_pathIsZeroLength = true; // A new sub-path also starts here subpathFinder.m_lastPoint = subpathFinder.m_movePoint; break; } } void pathIsDone() { if (m_pathIsZeroLength && !m_haveSeenMoveOnly) m_zeroLengthSubpathLocations.append(m_lastPoint); } private: Vector<FloatPoint>& m_zeroLengthSubpathLocations; FloatPoint m_lastPoint; FloatPoint m_movePoint; bool m_haveSeenMoveOnly { false }; bool m_pathIsZeroLength { false }; }; } // namespace WebCore
412
0.895566
1
0.895566
game-dev
MEDIA
0.573719
game-dev
0.80458
1
0.80458
dviglo/dviglo
4,478
source/third-party/bullet/bullet/BulletSoftBody/btSoftBodySolvers.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SOFT_BODY_SOLVERS_H #define BT_SOFT_BODY_SOLVERS_H #include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h" class btSoftBodyTriangleData; class btSoftBodyLinkData; class btSoftBodyVertexData; class btVertexBufferDescriptor; class btCollisionObject; class btSoftBody; class btSoftBodySolver { public: enum SolverTypes { DEFAULT_SOLVER, CPU_SOLVER, CL_SOLVER, CL_SIMD_SOLVER, DX_SOLVER, DX_SIMD_SOLVER, DEFORMABLE_SOLVER }; protected: int m_numberOfPositionIterations; int m_numberOfVelocityIterations; // Simulation timescale float m_timeScale; public: btSoftBodySolver() : m_numberOfPositionIterations(10), m_timeScale(1) { m_numberOfVelocityIterations = 0; m_numberOfPositionIterations = 5; } virtual ~btSoftBodySolver() { } /** * Return the type of the solver. */ virtual SolverTypes getSolverType() const = 0; /** Ensure that this solver is initialized. */ virtual bool checkInitialized() = 0; /** Optimize soft bodies in this solver. */ virtual void optimize(btAlignedObjectArray<btSoftBody *> &softBodies, bool forceUpdate = false) = 0; /** Copy necessary data back to the original soft body source objects. */ virtual void copyBackToSoftBodies(bool bMove = true) = 0; /** Predict motion of soft bodies into next timestep */ virtual void predictMotion(btScalar solverdt) = 0; /** Solve constraints for a set of soft bodies */ virtual void solveConstraints(btScalar solverdt) = 0; /** Perform necessary per-step updates of soft bodies such as recomputing normals and bounding boxes */ virtual void updateSoftBodies() = 0; /** Process a collision between one of the world's soft bodies and another collision object */ virtual void processCollision(btSoftBody *, const struct btCollisionObjectWrapper *) = 0; /** Process a collision between two soft bodies */ virtual void processCollision(btSoftBody *, btSoftBody *) = 0; /** Set the number of velocity constraint solver iterations this solver uses. */ virtual void setNumberOfPositionIterations(int iterations) { m_numberOfPositionIterations = iterations; } /** Get the number of velocity constraint solver iterations this solver uses. */ virtual int getNumberOfPositionIterations() { return m_numberOfPositionIterations; } /** Set the number of velocity constraint solver iterations this solver uses. */ virtual void setNumberOfVelocityIterations(int iterations) { m_numberOfVelocityIterations = iterations; } /** Get the number of velocity constraint solver iterations this solver uses. */ virtual int getNumberOfVelocityIterations() { return m_numberOfVelocityIterations; } /** Return the timescale that the simulation is using */ float getTimeScale() { return m_timeScale; } #if 0 /** * Add a collision object to be used by the indicated softbody. */ virtual void addCollisionObjectForSoftBody( int clothIdentifier, btCollisionObject *collisionObject ) = 0; #endif }; /** * Class to manage movement of data from a solver to a given target. * This version is abstract. Subclasses will have custom pairings for different combinations. */ class btSoftBodySolverOutput { protected: public: btSoftBodySolverOutput() { } virtual ~btSoftBodySolverOutput() { } /** Output current computed vertex data to the vertex buffers for all cloths in the solver. */ virtual void copySoftBodyToVertexBuffer(const btSoftBody *const softBody, btVertexBufferDescriptor *vertexBuffer) = 0; }; #endif // #ifndef BT_SOFT_BODY_SOLVERS_H
412
0.871811
1
0.871811
game-dev
MEDIA
0.966697
game-dev
0.85828
1
0.85828
LandSandBoat/server
1,567
scripts/zones/Bhaflau_Remnants/npcs/_23b.lua
----------------------------------- -- NPC: Door -- Area: Bhaflau Remnants -- 2nd Floor 1st Door opens West Wing, locks East Wing -- !pos 280 -6 260 ----------------------------------- local ID = zones[xi.zone.BHAFLAU_REMNANTS] ----------------------------------- ---@type TNpcEntity local entity = {} entity.onTrigger = function(player, npc) if npc:getLocalVar('unSealed') == 1 then player:startEvent(300) else player:messageSpecial(ID.text.DOOR_IS_SEALED) end end entity.onEventFinish = function(player, csid, option, npc) if csid == 300 and option == 1 then local instance = npc:getInstance() if instance and xi.salvage.onDoorOpen(npc, nil, 2) then xi.salvage.sealDoors(instance, ID.npc.DOOR_2_EAST_ENTRANCE) xi.salvage.unsealDoors(instance, { ID.npc.DOOR_2_SW_ENTRANCE, ID.npc.DOOR_2_NW_ENTRANCE }) local mobs = { utils.slice(ID.mob.WANDERING_WAMOURA, 4, 12), utils.slice(ID.mob.TROLL_ENGRAVER, 1, 3), utils.slice(ID.mob.TROLL_IRONWORKER, 6, 8), } xi.salvage.spawnGroup(instance, mobs) if math.random(100) >= 50 then GetNPCByID(ID.npc.SOCKET, instance):setPos(222, 0, 260) GetMobByID(ID.mob.FLUX_FLAN, instance):setSpawn(225, -0.5, 260, 0) GetNPCByID(ID.npc.SOCKET, instance):setStatus(xi.status.NORMAL) end else player:messageSpecial(ID.text.DOOR_IS_SEALED) end end end return entity
412
0.9394
1
0.9394
game-dev
MEDIA
0.965109
game-dev
0.967504
1
0.967504
Fewnity/Xenity-Engine
19,052
Xenity_Engine/include/SDL3/SDL_properties.h
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * # CategoryProperties * * A property is a variable that can be created and retrieved by name at * runtime. * * All properties are part of a property group (SDL_PropertiesID). A property * group can be created with the SDL_CreateProperties function and destroyed * with the SDL_DestroyProperties function. * * Properties can be added to and retrieved from a property group through the * following functions: * * - SDL_SetPointerProperty and SDL_GetPointerProperty operate on `void*` * pointer types. * - SDL_SetStringProperty and SDL_GetStringProperty operate on string types. * - SDL_SetNumberProperty and SDL_GetNumberProperty operate on signed 64-bit * integer types. * - SDL_SetFloatProperty and SDL_GetFloatProperty operate on floating point * types. * - SDL_SetBooleanProperty and SDL_GetBooleanProperty operate on boolean * types. * * Properties can be removed from a group by using SDL_ClearProperty. */ #ifndef SDL_properties_h_ #define SDL_properties_h_ #include <SDL3/SDL_stdinc.h> #include <SDL3/SDL_error.h> #include <SDL3/SDL_begin_code.h> /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * SDL properties ID * * \since This datatype is available since SDL 3.2.0. */ typedef Uint32 SDL_PropertiesID; /** * SDL property type * * \since This enum is available since SDL 3.2.0. */ typedef enum SDL_PropertyType { SDL_PROPERTY_TYPE_INVALID, SDL_PROPERTY_TYPE_POINTER, SDL_PROPERTY_TYPE_STRING, SDL_PROPERTY_TYPE_NUMBER, SDL_PROPERTY_TYPE_FLOAT, SDL_PROPERTY_TYPE_BOOLEAN } SDL_PropertyType; /** * Get the global SDL properties. * * \returns a valid property ID on success or 0 on failure; call * SDL_GetError() for more information. * * \since This function is available since SDL 3.2.0. */ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetGlobalProperties(void); /** * Create a group of properties. * * All properties are automatically destroyed when SDL_Quit() is called. * * \returns an ID for a new group of properties, or 0 on failure; call * SDL_GetError() for more information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_DestroyProperties */ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_CreateProperties(void); /** * Copy a group of properties. * * Copy all the properties from one group of properties to another, with the * exception of properties requiring cleanup (set using * SDL_SetPointerPropertyWithCleanup()), which will not be copied. Any * property that already exists on `dst` will be overwritten. * * \param src the properties to copy. * \param dst the destination properties. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. */ extern SDL_DECLSPEC bool SDLCALL SDL_CopyProperties(SDL_PropertiesID src, SDL_PropertiesID dst); /** * Lock a group of properties. * * Obtain a multi-threaded lock for these properties. Other threads will wait * while trying to lock these properties until they are unlocked. Properties * must be unlocked before they are destroyed. * * The lock is automatically taken when setting individual properties, this * function is only needed when you want to set several properties atomically * or want to guarantee that properties being queried aren't freed in another * thread. * * \param props the properties to lock. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_UnlockProperties */ extern SDL_DECLSPEC bool SDLCALL SDL_LockProperties(SDL_PropertiesID props); /** * Unlock a group of properties. * * \param props the properties to unlock. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_LockProperties */ extern SDL_DECLSPEC void SDLCALL SDL_UnlockProperties(SDL_PropertiesID props); /** * A callback used to free resources when a property is deleted. * * This should release any resources associated with `value` that are no * longer needed. * * This callback is set per-property. Different properties in the same group * can have different cleanup callbacks. * * This callback will be called _during_ SDL_SetPointerPropertyWithCleanup if * the function fails for any reason. * * \param userdata an app-defined pointer passed to the callback. * \param value the pointer assigned to the property to clean up. * * \threadsafety This callback may fire without any locks held; if this is a * concern, the app should provide its own locking. * * \since This datatype is available since SDL 3.2.0. * * \sa SDL_SetPointerPropertyWithCleanup */ typedef void (SDLCALL *SDL_CleanupPropertyCallback)(void *userdata, void *value); /** * Set a pointer property in a group of properties with a cleanup function * that is called when the property is deleted. * * The cleanup function is also called if setting the property fails for any * reason. * * For simply setting basic data types, like numbers, bools, or strings, use * SDL_SetNumberProperty, SDL_SetBooleanProperty, or SDL_SetStringProperty * instead, as those functions will handle cleanup on your behalf. This * function is only for more complex, custom data. * * \param props the properties to modify. * \param name the name of the property to modify. * \param value the new value of the property, or NULL to delete the property. * \param cleanup the function to call when this property is deleted, or NULL * if no cleanup is necessary. * \param userdata a pointer that is passed to the cleanup function. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPointerProperty * \sa SDL_SetPointerProperty * \sa SDL_CleanupPropertyCallback */ extern SDL_DECLSPEC bool SDLCALL SDL_SetPointerPropertyWithCleanup(SDL_PropertiesID props, const char *name, void *value, SDL_CleanupPropertyCallback cleanup, void *userdata); /** * Set a pointer property in a group of properties. * * \param props the properties to modify. * \param name the name of the property to modify. * \param value the new value of the property, or NULL to delete the property. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPointerProperty * \sa SDL_HasProperty * \sa SDL_SetBooleanProperty * \sa SDL_SetFloatProperty * \sa SDL_SetNumberProperty * \sa SDL_SetPointerPropertyWithCleanup * \sa SDL_SetStringProperty */ extern SDL_DECLSPEC bool SDLCALL SDL_SetPointerProperty(SDL_PropertiesID props, const char *name, void *value); /** * Set a string property in a group of properties. * * This function makes a copy of the string; the caller does not have to * preserve the data after this call completes. * * \param props the properties to modify. * \param name the name of the property to modify. * \param value the new value of the property, or NULL to delete the property. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetStringProperty */ extern SDL_DECLSPEC bool SDLCALL SDL_SetStringProperty(SDL_PropertiesID props, const char *name, const char *value); /** * Set an integer property in a group of properties. * * \param props the properties to modify. * \param name the name of the property to modify. * \param value the new value of the property. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetNumberProperty */ extern SDL_DECLSPEC bool SDLCALL SDL_SetNumberProperty(SDL_PropertiesID props, const char *name, Sint64 value); /** * Set a floating point property in a group of properties. * * \param props the properties to modify. * \param name the name of the property to modify. * \param value the new value of the property. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetFloatProperty */ extern SDL_DECLSPEC bool SDLCALL SDL_SetFloatProperty(SDL_PropertiesID props, const char *name, float value); /** * Set a boolean property in a group of properties. * * \param props the properties to modify. * \param name the name of the property to modify. * \param value the new value of the property. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetBooleanProperty */ extern SDL_DECLSPEC bool SDLCALL SDL_SetBooleanProperty(SDL_PropertiesID props, const char *name, bool value); /** * Return whether a property exists in a group of properties. * * \param props the properties to query. * \param name the name of the property to query. * \returns true if the property exists, or false if it doesn't. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPropertyType */ extern SDL_DECLSPEC bool SDLCALL SDL_HasProperty(SDL_PropertiesID props, const char *name); /** * Get the type of a property in a group of properties. * * \param props the properties to query. * \param name the name of the property to query. * \returns the type of the property, or SDL_PROPERTY_TYPE_INVALID if it is * not set. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_HasProperty */ extern SDL_DECLSPEC SDL_PropertyType SDLCALL SDL_GetPropertyType(SDL_PropertiesID props, const char *name); /** * Get a pointer property from a group of properties. * * By convention, the names of properties that SDL exposes on objects will * start with "SDL.", and properties that SDL uses internally will start with * "SDL.internal.". These should be considered read-only and should not be * modified by applications. * * \param props the properties to query. * \param name the name of the property to query. * \param default_value the default value of the property. * \returns the value of the property, or `default_value` if it is not set or * not a pointer property. * * \threadsafety It is safe to call this function from any thread, although * the data returned is not protected and could potentially be * freed if you call SDL_SetPointerProperty() or * SDL_ClearProperty() on these properties from another thread. * If you need to avoid this, use SDL_LockProperties() and * SDL_UnlockProperties(). * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetBooleanProperty * \sa SDL_GetFloatProperty * \sa SDL_GetNumberProperty * \sa SDL_GetPropertyType * \sa SDL_GetStringProperty * \sa SDL_HasProperty * \sa SDL_SetPointerProperty */ extern SDL_DECLSPEC void * SDLCALL SDL_GetPointerProperty(SDL_PropertiesID props, const char *name, void *default_value); /** * Get a string property from a group of properties. * * \param props the properties to query. * \param name the name of the property to query. * \param default_value the default value of the property. * \returns the value of the property, or `default_value` if it is not set or * not a string property. * * \threadsafety It is safe to call this function from any thread, although * the data returned is not protected and could potentially be * freed if you call SDL_SetStringProperty() or * SDL_ClearProperty() on these properties from another thread. * If you need to avoid this, use SDL_LockProperties() and * SDL_UnlockProperties(). * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPropertyType * \sa SDL_HasProperty * \sa SDL_SetStringProperty */ extern SDL_DECLSPEC const char * SDLCALL SDL_GetStringProperty(SDL_PropertiesID props, const char *name, const char *default_value); /** * Get a number property from a group of properties. * * You can use SDL_GetPropertyType() to query whether the property exists and * is a number property. * * \param props the properties to query. * \param name the name of the property to query. * \param default_value the default value of the property. * \returns the value of the property, or `default_value` if it is not set or * not a number property. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPropertyType * \sa SDL_HasProperty * \sa SDL_SetNumberProperty */ extern SDL_DECLSPEC Sint64 SDLCALL SDL_GetNumberProperty(SDL_PropertiesID props, const char *name, Sint64 default_value); /** * Get a floating point property from a group of properties. * * You can use SDL_GetPropertyType() to query whether the property exists and * is a floating point property. * * \param props the properties to query. * \param name the name of the property to query. * \param default_value the default value of the property. * \returns the value of the property, or `default_value` if it is not set or * not a float property. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPropertyType * \sa SDL_HasProperty * \sa SDL_SetFloatProperty */ extern SDL_DECLSPEC float SDLCALL SDL_GetFloatProperty(SDL_PropertiesID props, const char *name, float default_value); /** * Get a boolean property from a group of properties. * * You can use SDL_GetPropertyType() to query whether the property exists and * is a boolean property. * * \param props the properties to query. * \param name the name of the property to query. * \param default_value the default value of the property. * \returns the value of the property, or `default_value` if it is not set or * not a boolean property. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. * * \sa SDL_GetPropertyType * \sa SDL_HasProperty * \sa SDL_SetBooleanProperty */ extern SDL_DECLSPEC bool SDLCALL SDL_GetBooleanProperty(SDL_PropertiesID props, const char *name, bool default_value); /** * Clear a property from a group of properties. * * \param props the properties to modify. * \param name the name of the property to clear. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. */ extern SDL_DECLSPEC bool SDLCALL SDL_ClearProperty(SDL_PropertiesID props, const char *name); /** * A callback used to enumerate all the properties in a group of properties. * * This callback is called from SDL_EnumerateProperties(), and is called once * per property in the set. * * \param userdata an app-defined pointer passed to the callback. * \param props the SDL_PropertiesID that is being enumerated. * \param name the next property name in the enumeration. * * \threadsafety SDL_EnumerateProperties holds a lock on `props` during this * callback. * * \since This datatype is available since SDL 3.2.0. * * \sa SDL_EnumerateProperties */ typedef void (SDLCALL *SDL_EnumeratePropertiesCallback)(void *userdata, SDL_PropertiesID props, const char *name); /** * Enumerate the properties contained in a group of properties. * * The callback function is called for each property in the group of * properties. The properties are locked during enumeration. * * \param props the properties to query. * \param callback the function to call for each property. * \param userdata a pointer that is passed to `callback`. * \returns true on success or false on failure; call SDL_GetError() for more * information. * * \threadsafety It is safe to call this function from any thread. * * \since This function is available since SDL 3.2.0. */ extern SDL_DECLSPEC bool SDLCALL SDL_EnumerateProperties(SDL_PropertiesID props, SDL_EnumeratePropertiesCallback callback, void *userdata); /** * Destroy a group of properties. * * All properties are deleted and their cleanup functions will be called, if * any. * * \param props the properties to destroy. * * \threadsafety This function should not be called while these properties are * locked or other threads might be setting or getting values * from these properties. * * \since This function is available since SDL 3.2.0. * * \sa SDL_CreateProperties */ extern SDL_DECLSPEC void SDLCALL SDL_DestroyProperties(SDL_PropertiesID props); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include <SDL3/SDL_close_code.h> #endif /* SDL_properties_h_ */
412
0.826138
1
0.826138
game-dev
MEDIA
0.667409
game-dev
0.613228
1
0.613228
Sicraftails/SMM-WE-OpenWE
4,188
objects/obj_spike_ball_b/Other_13.gml
if (((hspeed < 0 && collision_rectangle(((bbox_left - 1) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_solid, 1, 0)) || (hspeed > 0 && collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_solid, 1, 0)) || (hspeed < 0 && collision_rectangle(((bbox_left - 1) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_physicssolid, 1, 0)) || (hspeed > 0 && collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_physicssolid, 1, 0)) || (hspeed < 0 && collision_rectangle(((bbox_left - 1) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_solidphy, 1, 0)) || (hspeed > 0 && collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_solidphy, 1, 0)) || (hspeed < 0 && collision_rectangle(((bbox_left - 1) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_bullebill_base, 1, 0)) || (hspeed > 0 && collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_bullebill_base, 1, 0)) || (hspeed < 0 && collision_rectangle(((bbox_left - 1) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_onewaygate_right, 1, 0)) || (hspeed > 0 && collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_onewaygate_left, 1, 0))) && ready == 1) { var col_one_left = collision_rectangle(bbox_right, (bbox_top + 1), (bbox_right + 1), (bbox_bottom - 4), obj_onewaygate_left, 0, 0) var col_one_right = collision_rectangle((bbox_left - 1), (bbox_top + 1), bbox_left, (bbox_bottom - 4), obj_onewaygate_right, 0, 0) if (hspeed > 0 && col_one_left) { with (col_one_left) { rot = 1 event_user(0) } } if (hspeed < 0 && col_one_right) { with (col_one_right) { rot = 1 event_user(0) } } var pow_right = collision_rectangle(((bbox_left - 3) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_block_pow_hold, 1, 0) var pow_left = collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_block_pow_hold, 1, 0) if (hspeed < 0 && pow_right && pow_right.held == 0) { with (pow_right) { explode = 1 event_user(6) } } if (hspeed > 0 && pow_left && pow_left.held == 0) { with (pow_left) { explode = 1 event_user(6) } } var block_right = collision_rectangle(((bbox_left - 3) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_blockparent, 1, 0) var block_left = collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_blockparent, 1, 0) if (hspeed < 0 && block_right && block_right.ready == 0) { if (block_right.object_index == obj_onoffblock) { with (block_right) event_user(1) } else { with (block_right) event_user(2) } } else if (hspeed > 0 && block_left && block_left.ready == 0) { if (block_left.object_index == obj_onoffblock) { with (block_left) event_user(1) } else { with (block_right) event_user(2) } } var shield_left = collision_rectangle(bbox_right, (bbox_top + 4), ((bbox_right + 1) + hspeed), (bbox_bottom - 4), obj_shield_left, 1, 0) var shield_right = collision_rectangle(((bbox_left - 1) + hspeed), (bbox_top + 4), bbox_left, (bbox_bottom - 4), obj_shield_right, 1, 0) if (hspeed > 0 && shield_left) { with (shield_left) event_user(0) fisica = 1 vspeed = -1 hspeed = (-hspeed) with (obj_mario) hspeed = 1 } else if (hspeed < 0 && shield_right) { with (shield_right) event_user(0) fisica = 1 vspeed = -1 hspeed = (-hspeed) with (obj_mario) hspeed = -1 } else event_user(0) }
412
0.679581
1
0.679581
game-dev
MEDIA
0.815965
game-dev
0.989278
1
0.989278
FalAut/Mierno
1,403
kubejs/client_scripts/ponder/first_tree.js
Ponder.registry((event) => { event.create('oak_sapling').scene('first_tree', '第一颗树', 'mierno:first_tree', (scene, util) => { scene.setSceneOffsetY(-1); scene.scaleSceneView(0.8); scene.showStructure(0); scene.text(60, '首先,我们需要搭建一个结构'); scene.idle(10); for (let y = 1; y <= 3; y++) { scene.world.showSection([2, y, 2], 'down'); scene.idle(10); } for (let y = 4; y <= 7; y++) { for (let x = 0; x < 6; x++) { scene.world.showSection( [ [x, y, 0], [x, y, 5], ], 'down' ); scene.idle(3); } } scene.idle(10); scene.text(20, '搭建完毕后,右键底部的方块').attachKeyFrame(); scene.showControls(20, [2, 1.5, 2.5], 'left').rightClick(); scene.overlay.showOutline('red', 1, [2, 1, 2], 20); scene.idle(20); for (let x = 0; x <= 6; x++) { for (let y = 1; y <= 8; y++) { for (let z = 0; z <= 6; z++) { scene.world.destroyBlock([x, y, z]); } } } scene.world.createItemEntity([2.5, 1.5, 2.5], Vec3d.ZERO, 'oak_sapling'); scene.idle(40); scene.text(100, '可前往「胶囊」章节获取胶囊来快速放置这个结构'); }); });
412
0.53303
1
0.53303
game-dev
MEDIA
0.684748
game-dev,graphics-rendering
0.872468
1
0.872468
Wynntils/Wynntils-Legacy
3,961
src/main/java/com/wynntils/modules/music/events/ClientEvents.java
/* * * Copyright © Wynntils - 2022. */ package com.wynntils.modules.music.events; import com.wynntils.McIf; import com.wynntils.Reference; import com.wynntils.core.events.custom.*; import com.wynntils.core.framework.enums.ClassType; import com.wynntils.core.framework.interfaces.Listener; import com.wynntils.core.utils.helpers.Delay; import com.wynntils.core.utils.objects.Location; import com.wynntils.modules.core.enums.ToggleSetting; import com.wynntils.modules.core.overlays.inventories.ChestReplacer; import com.wynntils.modules.music.configs.MusicConfig; import com.wynntils.modules.music.managers.AreaTrackManager; import com.wynntils.modules.music.managers.BossTrackManager; import com.wynntils.modules.music.managers.SoundTrackManager; import com.wynntils.modules.utilities.overlays.hud.WarTimerOverlay; import com.wynntils.webapi.WebManager; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.SPacketTitle; import net.minecraft.network.play.server.SPacketWindowItems; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; public class ClientEvents implements Listener { // player ticking @SubscribeEvent public void tick(TickEvent.ClientTickEvent e) { if (!MusicConfig.INSTANCE.enabled || e.phase == TickEvent.Phase.START) return; SoundTrackManager.getPlayer().update(); } @SubscribeEvent public void serverLeft(WynncraftServerEvent.Leave e) { SoundTrackManager.getPlayer().stop(); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void worldLeft(WynnWorldEvent.Leave e) { SoundTrackManager.getPlayer().stop(); } // character selection @SubscribeEvent public void characterChange(WynnClassChangeEvent e) { if (e.getNewClass() == ClassType.NONE && Reference.onWorld) return; // character selection // Toggle wynncraft music off if wynntils music replacer is enabled if (MusicConfig.INSTANCE.replaceJukebox && MusicConfig.INSTANCE.enabled && Reference.onWorld) { new Delay(() -> ToggleSetting.MUSIC.set(false), 20); } SoundTrackManager.getPlayer().stop(); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void openCharacterSelection(GuiOverlapEvent.ChestOverlap.InitGui e) { if (!MusicConfig.INSTANCE.classSelectionMusic || !e.getGui().getLowerInv().getName().contains("Select a Character")) return; SoundTrackManager.findTrack(WebManager.getMusicLocations().getEntryTrack("characterSelector"), true, MusicConfig.INSTANCE.characterSelectorQuiet); } // special tracks @SubscribeEvent public void dungeonTracks(PacketEvent<SPacketTitle> e) { if (!MusicConfig.INSTANCE.replaceJukebox || e.getPacket().getType() != SPacketTitle.Type.TITLE) return; String title = TextFormatting.getTextWithoutFormattingCodes(McIf.getFormattedText(e.getPacket().getMessage())); String songName = WebManager.getMusicLocations().getDungeonTrack(title); if (songName == null) return; SoundTrackManager.findTrack(songName, true); } @SubscribeEvent public void warTrack(WarStageEvent e) { if (!MusicConfig.INSTANCE.replaceJukebox || e.getNewStage() != WarTimerOverlay.WarStage.WAITING_FOR_MOB_TIMER) return; SoundTrackManager.findTrack(WebManager.getMusicLocations().getEntryTrack("wars"), true); } // area tracks @SubscribeEvent public void areaTracks(SchedulerEvent.RegionUpdate e) { if (!MusicConfig.INSTANCE.replaceJukebox) return; McIf.mc().addScheduledTask(BossTrackManager::update); if (BossTrackManager.isAlive()) return; AreaTrackManager.update(new Location(McIf.player())); } }
412
0.95456
1
0.95456
game-dev
MEDIA
0.645605
game-dev,desktop-app
0.952526
1
0.952526
ianpatt/sfse
1,836
sfse_common/FileStream.cpp
#include "FileStream.h" #include <string> #include <direct.h> FileStream::FileStream() : m_file(nullptr) { // } FileStream::~FileStream() { close(); } bool FileStream::open(const char * path) { return internalOpen(path, "rb"); } bool FileStream::open(const wchar_t * path) { return internalOpen(path, L"rb"); } bool FileStream::create(const char * path) { return internalOpen(path, "wb"); } bool FileStream::create(const wchar_t * path) { return internalOpen(path, L"wb"); } void FileStream::close() { if (m_file) { fclose(m_file); m_file = nullptr; m_len = 0; m_offset = 0; } } void FileStream::flush() { fflush(m_file); } u64 FileStream::seek(u64 offset) { _fseeki64_nolock(m_file, offset, SEEK_SET); m_offset = offset; return offset; } u64 FileStream::read(void * dst, u64 len) { u64 bytesRead = _fread_nolock(dst, 1, len, m_file); m_offset += bytesRead; return bytesRead; } u64 FileStream::write(const void * src, u64 len) { u64 bytesWritten = _fwrite_nolock(src, 1, len, m_file); m_offset += bytesWritten; return bytesWritten; } bool FileStream::internalOpen(const char * path, const char * mode) { close(); fopen_s(&m_file, path, mode); if (!m_file) return false; internalSetup(); return true; } bool FileStream::internalOpen(const wchar_t * path, const wchar_t * mode) { close(); _wfopen_s(&m_file, path, mode); if (!m_file) return false; internalSetup(); return true; } void FileStream::internalSetup() { fseek(m_file, 0, SEEK_END); m_len = _ftelli64_nolock(m_file); fseek(m_file, 0, SEEK_SET); m_offset = 0; } void FileStream::makeDirs(const char * path) { std::string fullPath = path; for (uint i = 1; i < fullPath.size(); i++) { char data = fullPath[i]; if ((data == '\\') || (data == '/')) { _mkdir(fullPath.substr(0, i).c_str()); } } }
412
0.93698
1
0.93698
game-dev
MEDIA
0.256041
game-dev
0.920615
1
0.920615
momotech/MLN
26,048
MLN-iOS/MLN/Classes/Kit/Component/UI/StyleString/MLNStyleString.m
// // MLNStyleString.m // MMDebugTools-DebugManager // // Created by MoMo on 2018/7/4. // #import "MLNStyleString.h" #import "MLNKitHeader.h" #import <CoreText/CoreText.h> #import "MLNViewExporterMacro.h" #import "MLNFont.h" #import "MLNStyleElement.h" #import "NSAttributedString+MLNKit.h" #import "MLNKitInstanceHandlersManager.h" @interface MLNStyleString () @property (nonatomic, strong) NSString *fontName; @property (nonatomic, assign) CGFloat fontSize; @property (nonatomic, assign) MLNFontStyle fontStyle; @property (nonatomic, strong) UIColor *fontColor; @property (nonatomic, strong) UIColor *backgroundColor; @property (nonatomic, assign) BOOL statusChanged; @property (nonatomic, assign) MLNStyleImageAlignType imageAlign; @property (nonatomic, strong) NSMutableDictionary *styleElementsDictM; @end @implementation MLNStyleString - (instancetype)initWithAttributedString:(NSAttributedString *)attributes { if (self = [super init]){ _mutableStyledString = attributes.mutableCopy; [_mutableStyledString setLua_styleString:self]; } return self; } - (instancetype)initWithLuaCore:(MLNLuaCore *)luaCore string:(NSString *)attriteStr { if (self = [super initWithLuaCore:luaCore]){ attriteStr = attriteStr ?: @""; _mutableStyledString = [[NSMutableAttributedString alloc]initWithString:attriteStr]; [_mutableStyledString setLua_styleString:self]; // 设置默认行间距 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 2; [_mutableStyledString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attriteStr.length)]; } return self; } #pragma mark - getter - (NSMutableDictionary *)styleElementsDictM { if (!_styleElementsDictM) { _styleElementsDictM = [NSMutableDictionary dictionaryWithCapacity:_mutableStyledString.length]; } return _styleElementsDictM; } #pragma mark - Method - (NSArray *)shouldChangedElementWithNewRange:(NSRange *)newRange; { NSMutableArray *interRangesArray = [NSMutableArray array]; NSArray *sortedArray = [self.styleElementsDictM.allValues sortedArrayUsingComparator:^NSComparisonResult(MLNStyleElement *obj1, MLNStyleElement *obj2) { return obj1.range.location > obj2.range.location; }]; for (MLNStyleElement *element in sortedArray) { NSRange oldRange = element.range; NSRange interRange = NSIntersectionRange(oldRange, (*newRange)); if (interRange.length == 0) { continue; } //存在交集,四种情况,旧包含新,新包含旧,新大于旧,新小于旧 if ((*newRange).location > oldRange.location && (*newRange).location + (*newRange).length < oldRange.location + oldRange.length) { //旧包裹新且不沾边 1-5 2-3 NSRange range1 = NSMakeRange(oldRange.location, (*newRange).location - oldRange.location); MLNStyleElement *element1 = [element copy]; element1.range = range1; NSRange range2 = (*newRange); MLNStyleElement *element2 = [element copy]; element2.range = range2; NSRange range3 = NSMakeRange((*newRange).location + (*newRange).length, oldRange.location + oldRange.length - (*newRange).location - (*newRange).length); MLNStyleElement *element3 = [element copy]; element3.range = range3; [self.styleElementsDictM removeObjectForKey:NSStringFromRange(oldRange)]; [self.styleElementsDictM setObject:element1 forKey:NSStringFromRange(range1)]; [self.styleElementsDictM setObject:element2 forKey:NSStringFromRange(range2)]; [self.styleElementsDictM setObject:element3 forKey:NSStringFromRange(range3)]; [interRangesArray addObject:element2]; (*newRange).length = 0; break; } else if ((*newRange).location == oldRange.location && (*newRange).location + (*newRange).length < oldRange.location + oldRange.length) { //旧包裹新且左沾边 1-5 1-2 NSRange range1 = (*newRange); MLNStyleElement *element1 = [element copy]; element1.range = range1; NSRange range2 = NSMakeRange((*newRange).location + (*newRange).length, oldRange.location + oldRange.length - (*newRange).location - (*newRange).length); MLNStyleElement *element2 = [element copy]; element2.range = range2; [self.styleElementsDictM removeObjectForKey:NSStringFromRange(oldRange)]; [self.styleElementsDictM setObject:element1 forKey:NSStringFromRange(range1)]; [self.styleElementsDictM setObject:element2 forKey:NSStringFromRange(range2)]; [interRangesArray addObject:element1]; (*newRange).length = 0; break; } else if ((*newRange).location > oldRange.location && (*newRange).location + (*newRange).length == oldRange.location + oldRange.length) {//旧包裹新且右沾边 1-5 3-5 NSRange range1 = NSMakeRange(oldRange.location, (*newRange).location - oldRange.location); MLNStyleElement *element1 = [element copy]; element1.range = range1; NSRange range2 = (*newRange); MLNStyleElement *element2 = [element copy]; element2.range = range2; [self.styleElementsDictM removeObjectForKey:NSStringFromRange(oldRange)]; [self.styleElementsDictM setObject:element1 forKey:NSStringFromRange(range1)]; [self.styleElementsDictM setObject:element2 forKey:NSStringFromRange(range2)]; [interRangesArray addObject:element2]; (*newRange).length = 0; break; } else if ((*newRange).location < oldRange.location && (*newRange).location + (*newRange).length > oldRange.location + oldRange.length ) { //新包裹旧 1-5 0-6 NSRange range1 = NSMakeRange((*newRange).location,oldRange.location - (*newRange).location); MLNStyleElement *element1 = [self styleElementWithKey:NSStringFromRange(range1)]; element1.range = range1; NSRange range2 = oldRange; MLNStyleElement *element2 = element; element2.range = range2; (*newRange) = NSMakeRange(oldRange.location + oldRange.length , (*newRange).location + (*newRange).length - oldRange.location - oldRange.length); [interRangesArray addObject:element1]; [interRangesArray addObject:element2]; } else if ((*newRange).location > oldRange.location && (*newRange).location < oldRange.location + oldRange.length && (*newRange).location + (*newRange).length > oldRange.location + oldRange.length) { // 新右边跨旧 1-5 2-6 NSRange range1 = NSMakeRange(oldRange.location, (*newRange).location - oldRange.location); MLNStyleElement *element1 = element.copy; element1.range = range1; NSRange range2 = NSMakeRange((*newRange).location, oldRange.location + oldRange.length - (*newRange).location); MLNStyleElement *element2 = element.copy; element2.range = range2; (*newRange) = NSMakeRange(oldRange.location + oldRange.length , (*newRange).location + (*newRange).length - oldRange.location - oldRange.length); [self.styleElementsDictM removeObjectForKey:NSStringFromRange(oldRange)]; [self.styleElementsDictM setObject:element1 forKey:NSStringFromRange(range1)]; [self.styleElementsDictM setObject:element2 forKey:NSStringFromRange(range2)]; [interRangesArray addObject:element2]; } else if ((*newRange).location == oldRange.location && (*newRange).location + (*newRange).length > oldRange.location + oldRange.length) { //新左边贴旧 1-5 1-6 (*newRange) = NSMakeRange(oldRange.location + oldRange.length , (*newRange).location + (*newRange).length - oldRange.location - oldRange.length); [interRangesArray addObject:element]; } else if ((*newRange).location < oldRange.location && (*newRange).location + (*newRange).length >= oldRange.location) { //新左边跨旧 1-5 0-3 NSRange range1 = NSMakeRange((*newRange).location,oldRange.location - (*newRange).location); MLNStyleElement *element1 = [self styleElementWithKey:NSStringFromRange(range1)]; element1.range = range1; NSRange range2 = NSMakeRange(oldRange.location, (*newRange).location + (*newRange).length - oldRange.location); MLNStyleElement *element2 = [element copy]; element2.range = range2; NSRange range3 = NSMakeRange((*newRange).location + (*newRange).length , oldRange.location + oldRange.length - (*newRange).location - (*newRange).length); MLNStyleElement *element3 = [element copy]; element3.range = range3; [self.styleElementsDictM removeObjectForKey:NSStringFromRange(oldRange)]; [self.styleElementsDictM setObject:element2 forKey:NSStringFromRange(range2)]; [self.styleElementsDictM setObject:element3 forKey:NSStringFromRange(range3)]; [interRangesArray addObject:element1]; [interRangesArray addObject:element2]; (*newRange).length = 0; break; } } return interRangesArray; } - (BOOL)outOfRange:(NSInteger)location length:(NSInteger)length { MLNLuaAssert(self.mln_luaCore, ((location + length) <= self.mutableStyledString.length), @"out of range"); return (location + length) > self.mutableStyledString.length; } - (MLNStyleElement *)styleElementWithKey:(NSString *)key { if (!key || key.length == 0) { return nil; } MLNStyleElement* element = [self.styleElementsDictM objectForKey:key]; if (!element) { element = [[MLNStyleElement alloc] init]; element.instance = [self myKitInstance]; [self.styleElementsDictM setObject:element forKey:key]; } return element; } - (void)handleStyleStringIfNeed { if (!_statusChanged) { return; } for (MLNStyleElement *element in self.styleElementsDictM.allValues) { NSRange range = element.range; if ([self outOfRange:range.location length:range.length] || element.changed == NO || element.imagePath.length > 0) continue; [self.mutableStyledString addAttributes:element.attributes range:range]; element.changed = NO; } _statusChanged = NO; } - (void)mln_checkImageIfNeed { NSMutableArray *imageElementArray = [NSMutableArray array]; MLNImageLoadFinishedCallback tempCallback = self.loadFinishedCallback; NSMutableAttributedString *tempAttributeString = self.mutableStyledString; for (MLNStyleElement *element in self.styleElementsDictM.allValues) { if (element.imagePath.length > 0 && element.range.length > 0 ) { [imageElementArray addObject:element]; } } if (imageElementArray.count > 0) { __block NSUInteger count = 0; dispatch_group_t imagesGroup = dispatch_group_create(); id<MLNImageLoaderProtocol> imageLoader = [self imageLoader]; for (MLNStyleElement *element in imageElementArray) { dispatch_group_enter(imagesGroup); [imageLoader view:(UIView<MLNEntityExportProtocol> *)self loadImageWithPath:element.imagePath completed:^(UIImage *image, NSError *error, NSString *imagePath) { if (image) { element.image = image; element.changed = NO; } count += 1; dispatch_group_leave(imagesGroup); }]; } dispatch_group_notify(imagesGroup, dispatch_get_main_queue(), ^{ if (count == imageElementArray.count && tempCallback) { for (MLNStyleElement *element in imageElementArray) { NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; textAttachment.image = element.image; UIFont *font = [self lineHeightWithElement:element]; switch (self.imageAlign) { case MLNStyleImageAlignTypeCenter: { CGFloat attachmentTop = fabs(element.imageSize.height - font.capHeight)/2.0; textAttachment.bounds = CGRectMake(0, -attachmentTop, element.imageSize.width, element.imageSize.height); } break; case MLNStyleImageAlignTypeTop: case MLNStyleImageAlignTypeBottom: default: { textAttachment.bounds = CGRectMake(0, 0, element.imageSize.width, element.imageSize.height); } break; } NSAttributedString *imageAttribute = [NSAttributedString attributedStringWithAttachment:textAttachment].mutableCopy; [tempAttributeString replaceCharactersInRange:element.range withAttributedString:imageAttribute]; } tempCallback(tempAttributeString); } }); } } - (id<MLNImageLoaderProtocol>)imageLoader { return MLN_KIT_INSTANCE(self.mln_luaCore).instanceHandlersManager.imageLoader; } #pragma mark - Method For Lua - (void)lua_setFontName:(NSString *)name { [self lua_setFontName:name location:0 length:self.mutableStyledString.length]; } - (void)lua_setFontName:(NSString *)name location:(NSInteger)location length:(NSInteger)length { location = location <= 0 ? 0 : location - 1; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); if (self.styleElementsDictM.count > 0) { NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.fontName = name; } } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.fontName = name; } } - (void)lua_setFontSize:(CGFloat)size { [self lua_setFontSize:size location:0 length:self.mutableStyledString.length]; } - (void)lua_setFontSize:(CGFloat)size location:(NSInteger)location length:(NSInteger)length { location = location <= 0 ? 0 : location - 1; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); if (self.styleElementsDictM.count > 0) { NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.fontSize = size; } } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.fontSize = size; } } - (void)lua_setFontColor:(UIColor *)color { MLNCheckTypeAndNilValue(color, @"Color", [UIColor class]) [self lua_setFontColor:color location:0 length:self.mutableStyledString.length]; } - (void)lua_setFontColor:(UIColor *)color location:(NSInteger)location length:(NSInteger)length { MLNCheckTypeAndNilValue(color, @"Color", [UIColor class]) location = location <= 0 ? 0 : location - 1; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.fontColor = color; } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.fontColor = color; } } - (void)lua_setBackgroundColor:(UIColor *)color { MLNCheckTypeAndNilValue(color, @"Color", UIColor) [self lua_setBackgroundColor:color location:0 length:self.mutableStyledString.length]; } - (void)lua_setBackgroundColor:(UIColor *)color location:(NSInteger)location length:(NSInteger)length { MLNCheckTypeAndNilValue(color, @"Color", UIColor) location = location <= 0 ? 0 : location - 1; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.backgroundColor = color; } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.backgroundColor = color; } } - (void)lua_setFontStyle:(MLNFontStyle)style { [self lua_setFontStyle:style location:0 length:self.mutableStyledString.length]; } - (void)lua_setFontStyle:(MLNFontStyle)style location:(NSInteger)location length:(NSInteger)length { location = location <= 0 ? 0 : location - 1; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.fontStyle = style; } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.fontStyle = style; } } - (void)lua_setUnderLineStyle:(MLNUnderlineStyle)style { [self lua_setUnderLineStyle:style location:0 length:self.mutableStyledString.length]; } - (void)lua_setUnderLineStyle:(MLNUnderlineStyle)style location:(NSInteger)location length:(NSInteger)length { location = location <= 0 ? 0 : location - 1; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.underline = style; } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.underline = style; } } - (void)lua_setLinkCallback:(MLNBlock *) callback { NSInteger location = 0; NSInteger length = self.mutableStyledString.length; _statusChanged = YES; NSRange newRange = NSMakeRange(location, length); NSArray *interRangesArray = [self shouldChangedElementWithNewRange:&newRange]; if (interRangesArray.count > 0) { for (MLNStyleElement *element in interRangesArray) { element.linkCallBack = callback; } } if (newRange.length != 0) { MLNStyleElement *element = [self styleElementWithKey:NSStringFromRange(newRange)]; element.range = newRange; element.linkCallBack = callback; } } - (void)lua_setImageAlignType:(MLNStyleImageAlignType)alignType { self.imageAlign = alignType; } - (void)lua_append:(NSMutableAttributedString *)styleString { MLNCheckTypeAndNilValue(styleString, @"StyleString", [NSMutableAttributedString class]) if (![styleString isKindOfClass:[NSMutableAttributedString class]]) return; if (!styleString || !self.mutableStyledString) return; MLNStyleString *lua_styleString = styleString.lua_styleString; if (lua_styleString) { for (MLNStyleElement *element in lua_styleString.styleElementsDictM.allValues) { MLNStyleElement *newElement = element.copy; NSRange oldRange = element.range; oldRange.location += self.mutableStyledString.length; newElement.range = oldRange; [self.styleElementsDictM setObject:newElement forKey:NSStringFromRange(newElement.range)]; } } [styleString setLua_styleString:nil]; [self.mutableStyledString appendAttributedString:[styleString copy]]; } - (id)mln_rawNativeData { [self handleStyleStringIfNeed]; return self.mutableStyledString; } - (CGSize)calculateSize:(CGFloat)maxWidth { [self handleStyleStringIfNeed]; CGSize size = [self.mutableStyledString boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size; return size; } - (CGSize)lua_sizeThatFits:(CGFloat)maxWidth { [self handleStyleStringIfNeed]; if (!self.mutableStyledString) return CGSizeZero; NSMutableAttributedString *drawString = self.mutableStyledString; CFAttributedStringRef attributedStringRef = (__bridge_retained CFAttributedStringRef)drawString; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedStringRef); CFRelease(attributedStringRef); if (!framesetter) { // 字符串处理失败 return CGSizeZero; } CFRange range = CFRangeMake(0, 0); CFRange fitCFRange = CFRangeMake(0, 0); CGSize newSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, range, NULL, CGSizeMake(maxWidth, MAXFLOAT), &fitCFRange); if (framesetter) { CFRelease(framesetter); } if (newSize.height < 14 * 2) { return CGSizeMake(ceilf(newSize.width), ceilf(newSize.height)); } else { return CGSizeMake(maxWidth, ceilf(newSize.height)); } } - (BOOL)lua_showAsImageWithSize:(CGSize)size { NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; NSString *imagePathString = self.mutableStyledString.string; textAttachment.image = nil; textAttachment.bounds = CGRectMake(0, 0, size.width, size.height); _mutableStyledString = [NSAttributedString attributedStringWithAttachment:textAttachment].mutableCopy; [_mutableStyledString setLua_styleString:self]; MLNStyleElement *element = [[MLNStyleElement alloc] init]; element.range = NSMakeRange(0, 1); element.imageSize = size; element.imagePath = imagePathString; element.instance = [self myKitInstance]; [self.styleElementsDictM removeAllObjects]; [_styleElementsDictM setObject:element forKey:NSStringFromRange(element.range)]; _statusChanged = YES; return textAttachment.image != nil; } - (void)lua_setText:(NSString*)attriteStr { attriteStr = attriteStr ?: @""; [_mutableStyledString setLua_styleString:nil]; [_styleElementsDictM removeAllObjects]; _mutableStyledString = [[NSMutableAttributedString alloc]initWithString:attriteStr]; [_mutableStyledString setLua_styleString:self]; // 设置默认行间距 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 2; [_mutableStyledString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attriteStr.length)]; } #pragma mark - Private method - (UIFont *)lineHeightWithElement:(MLNStyleElement *)element { NSArray *sortKeys = [self.styleElementsDictM keysSortedByValueUsingComparator:^NSComparisonResult(MLNStyleElement * _Nonnull obj1, MLNStyleElement * _Nonnull obj2) { if (obj1.range.location < obj2.range.location) { return NSOrderedAscending; } else { return NSOrderedDescending; } }]; NSUInteger index = [sortKeys indexOfObjectIdenticalTo:NSStringFromRange(element.range)]; index = index > 0? index - 1 : index + 1; MLNStyleElement *styleElement = nil; if (index >= 0 && index < sortKeys.count) { styleElement = [self.styleElementsDictM objectForKey:[sortKeys objectAtIndex:index]]; } if (!styleElement) { styleElement = element; } return [MLNFont fontWithFontName:styleElement.fontName fontStyle:styleElement.fontStyle fontSize:styleElement.fontSize instance:[self myKitInstance]]; } - (MLNKitInstance *)myKitInstance { return MLN_KIT_INSTANCE(self.mln_luaCore); } #pragma mark - Export For Lua LUA_EXPORT_BEGIN(MLNStyleString) LUA_EXPORT_METHOD(fontName,"lua_setFontName:",MLNStyleString) LUA_EXPORT_METHOD(setFontNameForRange,"lua_setFontName:location:length:",MLNStyleString) LUA_EXPORT_METHOD(fontSize,"lua_setFontSize:",MLNStyleString) LUA_EXPORT_METHOD(setFontSizeForRange,"lua_setFontSize:location:length:",MLNStyleString) LUA_EXPORT_METHOD(fontStyle,"lua_setFontStyle:",MLNStyleString) LUA_EXPORT_METHOD(setFontStyleForRange,"lua_setFontStyle:location:length:",MLNStyleString) LUA_EXPORT_METHOD(fontColor,"lua_setFontColor:",MLNStyleString) LUA_EXPORT_METHOD(setFontColorForRange,"lua_setFontColor:location:length:",MLNStyleString) LUA_EXPORT_METHOD(backgroundColor,"lua_setBackgroundColor:",MLNStyleString) LUA_EXPORT_METHOD(setBackgroundColorForRange,"lua_setBackgroundColor:location:length:",MLNStyleString) LUA_EXPORT_METHOD(underline,"lua_setUnderLineStyle:",MLNStyleString) LUA_EXPORT_METHOD(setLinkCallback,"lua_setLinkCallback:",MLNStyleString) LUA_EXPORT_METHOD(setUnderlineForRange,"lua_setUnderLineStyle:location:length:",MLNStyleString) LUA_EXPORT_METHOD(showAsImage,"lua_showAsImageWithSize:",MLNStyleString) LUA_EXPORT_METHOD(append, "lua_append:", MLNStyleString) LUA_EXPORT_METHOD(calculateSize, "calculateSize:", MLNStyleString) LUA_EXPORT_METHOD(sizeThatFits, "lua_sizeThatFits:", MLNStyleString) LUA_EXPORT_METHOD(setText, "lua_setText:", MLNStyleString) LUA_EXPORT_METHOD(imageAlign, "lua_setImageAlignType:", MLNStyleString) LUA_EXPORT_END(MLNStyleString, StyleString, NO, NULL, "initWithLuaCore:string:") @end
412
0.753516
1
0.753516
game-dev
MEDIA
0.44168
game-dev
0.647294
1
0.647294
JHDev2006/Super-Mario-Bros.-Remastered-Public
1,211
Scripts/Parts/BulletBillCannon.gd
extends Node2D @export var item: PackedScene = preload("res://Scenes/Prefabs/Entities/Enemies/BulletBill.tscn") var timer := 15 const MAX_TIME := 15 const HARD_TIME := 7 func _physics_process(_delta: float) -> void: if randi_range(0, 8) == 8: timer -= 1 if timer <= 0: if Global.second_quest: timer = HARD_TIME else: timer = MAX_TIME fire() func fire() -> void: if BulletBill.amount >= 3 or $PlayerDetect.get_overlapping_areas().any(func(area: Area2D): return area.owner is Player) or is_inside_tree() == false: return var player: Player = get_tree().get_first_node_in_group("Players") var direction = sign(player.global_position.x - global_position.x) $BlockCheck.scale.x = direction $BlockCheck/RayCast2D.force_raycast_update() if $BlockCheck/RayCast2D.is_colliding(): return var node = item.instantiate() node.global_position = global_position + Vector2(0, 8) node.set("direction", direction) if node is CharacterBody2D: node.position.x += 8 * direction node.set("velocity", Vector2(100 * direction, 0)) if node is not BulletBill: AudioManager.play_sfx("cannon", global_position) else: node.cannon = true add_sibling(node) func flag_die() -> void: queue_free()
412
0.882208
1
0.882208
game-dev
MEDIA
0.929327
game-dev
0.854115
1
0.854115
Sigma-Skidder-Team/SigmaRemap
1,921
src/main/java/mapped/Class2879.java
package mapped; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import net.minecraft.entity.Entity; import java.util.Arrays; public class Class2879<T extends Entity> extends Class2803<T> { private static String[] field17851; private final ModelRenderer field17852; private final ModelRenderer[] field17853 = new ModelRenderer[8]; private final ImmutableList<ModelRenderer> field17854; public Class2879() { byte var3 = -16; this.field17852 = new ModelRenderer(this, 0, 0); this.field17852.method22673(-6.0F, -8.0F, -6.0F, 12.0F, 16.0F, 12.0F); this.field17852.rotationPointY += 8.0F; for (int var4 = 0; var4 < this.field17853.length; var4++) { this.field17853[var4] = new ModelRenderer(this, 48, 0); double var5 = (double)var4 * Math.PI * 2.0 / (double)this.field17853.length; float var7 = (float)Math.cos(var5) * 5.0F; float var8 = (float)Math.sin(var5) * 5.0F; this.field17853[var4].method22673(-1.0F, 0.0F, -1.0F, 2.0F, 18.0F, 2.0F); this.field17853[var4].rotationPointX = var7; this.field17853[var4].rotationPointZ = var8; this.field17853[var4].rotationPointY = 15.0F; var5 = (double)var4 * Math.PI * -2.0 / (double)this.field17853.length + (Math.PI / 2); this.field17853[var4].rotateAngleY = (float)var5; } Builder var9 = ImmutableList.builder(); var9.add(this.field17852); var9.addAll(Arrays.<ModelRenderer>asList(this.field17853)); this.field17854 = var9.build(); } @Override public void setRotationAngles(T var1, float var2, float var3, float var4, float var5, float var6) { for (ModelRenderer var12 : this.field17853) { var12.rotateAngleX = var4; } } @Override public Iterable<ModelRenderer> method11015() { return this.field17854; } }
412
0.787309
1
0.787309
game-dev
MEDIA
0.809606
game-dev,graphics-rendering
0.929921
1
0.929921
sstokic-tgm/JFTSE
8,404
chat-server/src/main/java/com/jftse/emulator/server/core/service/impl/LotteryServiceImpl.java
package com.jftse.emulator.server.core.service.impl; import com.jftse.emulator.common.utilities.ResourceUtil; import com.jftse.emulator.common.utilities.StringUtils; import com.jftse.emulator.server.core.packets.inventory.S2CInventoryItemCountPacket; import com.jftse.emulator.server.core.packets.inventory.S2CInventoryItemsPlacePacket; import com.jftse.emulator.server.net.FTClient; import com.jftse.entities.database.model.item.Product; import com.jftse.entities.database.model.lottery.LotteryItemDto; import com.jftse.entities.database.model.player.Player; import com.jftse.entities.database.model.pocket.PlayerPocket; import com.jftse.entities.database.model.pocket.Pocket; import com.jftse.server.core.item.EItemCategory; import com.jftse.server.core.item.EItemChar; import com.jftse.server.core.item.EItemUseType; import com.jftse.server.core.net.Client; import com.jftse.server.core.net.Connection; import com.jftse.server.core.service.LotteryService; import com.jftse.server.core.service.PlayerPocketService; import com.jftse.server.core.service.PocketService; import com.jftse.server.core.service.ProductService; import com.jftse.server.core.shared.packets.inventory.S2CInventoryItemRemoveAnswerPacket; import lombok.RequiredArgsConstructor; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @Service @RequiredArgsConstructor @Transactional(isolation = Isolation.SERIALIZABLE) public class LotteryServiceImpl implements LotteryService { private final ProductService productService; private final PlayerPocketService playerPocketService; private final PocketService pocketService; private Random random; @PostConstruct @Override public void init() { random = new Random(); } @Override public List<PlayerPocket> drawLottery(Connection<? extends Client<?>> connection, long playerPocketId, int productIndex) { FTClient ftClient = (FTClient) connection.getClient(); Player player = ftClient.getPlayer(); List<PlayerPocket> result = new ArrayList<>(); handlePlayerPocket(connection, playerPocketId); List<Product> productList = productService.findProductsByItemList(Stream.of(productIndex).collect(Collectors.toList())); List<LotteryItemDto> lotteryItemList = getLotteryItemsByGachaIndex(player.getPlayerType(), productList.get(0).getItem0()); LotteryItemDto lotteryItem = pickItemLotteryFromList(lotteryItemList); Product winningItem = productService.findProductsByItemList(Stream.of(lotteryItem.getShopIndex()).collect(Collectors.toList())).get(0); productList.clear(); Pocket pocket = pocketService.findById(player.getPocket().getId()); PlayerPocket playerPocket = saveWinningItem(winningItem, lotteryItem, pocket); result.add(playerPocket); player.setPocket(playerPocket.getPocket()); ftClient.savePlayer(player); return result; } private void handlePlayerPocket(Connection<?> connection, long playerPocketId) { PlayerPocket playerPocket = playerPocketService.findById(playerPocketId); if (playerPocket != null) { int itemCount = playerPocket.getItemCount() - 1; if (itemCount <= 0) { pocketService.decrementPocketBelongings(playerPocket.getPocket()); playerPocketService.remove(playerPocket.getId()); // if current count is 0 remove the item S2CInventoryItemRemoveAnswerPacket inventoryItemRemoveAnswerPacket = new S2CInventoryItemRemoveAnswerPacket((int) playerPocketId); connection.sendTCP(inventoryItemRemoveAnswerPacket); } else { playerPocket.setItemCount(itemCount); playerPocket = playerPocketService.save(playerPocket); S2CInventoryItemCountPacket inventoryItemCountPacket = new S2CInventoryItemCountPacket(playerPocket); connection.sendTCP(inventoryItemCountPacket); } } } private List<LotteryItemDto> getLotteryItemsByGachaIndex(byte playerType, int gachaIndex) { List<LotteryItemDto> result = new ArrayList<>(); String playerTypeName = StringUtils.firstCharToUpperCase(EItemChar.getNameByValue(playerType).toLowerCase()); try { InputStream lotteryItemFile = ResourceUtil.getResource("res/lottery/Ini3_Lot_" + (gachaIndex < 10 ? ("0" + gachaIndex) : gachaIndex ) + ".xml"); SAXReader reader = new SAXReader(); reader.setEncoding("UTF-8"); Document document = reader.read(lotteryItemFile); List<Node> lotteryItemList = document.selectNodes("/LotteryItemList/LotteryItem_" + playerTypeName); for (int i = 0; i < lotteryItemList.size(); i++) { Node lotteryItem = lotteryItemList.get(i); LotteryItemDto lotteryItemDto = new LotteryItemDto(); lotteryItemDto.setShopIndex(Integer.valueOf(lotteryItem.valueOf("@ShopIndex"))); lotteryItemDto.setQuantityMin(Integer.valueOf(lotteryItem.valueOf("@QuantityMin"))); lotteryItemDto.setQuantityMax(Integer.valueOf(lotteryItem.valueOf("@QuantityMax"))); lotteryItemDto.setChansPer(Double.valueOf(lotteryItem.valueOf("@ChansPer"))); result.add(lotteryItemDto); } lotteryItemFile.close(); } catch (DocumentException | IOException de) { return new ArrayList<>(); } return result; } private LotteryItemDto pickItemLotteryFromList(List<LotteryItemDto> lotteryItemList) { int size = lotteryItemList.size(); double[] cumProb = new double[size]; cumProb[0] = lotteryItemList.get(0).getChansPer() / 100.0; for (int i = 1; i < size; i++) { cumProb[i] = cumProb[i - 1] + lotteryItemList.get(i).getChansPer() / 100.0; } double randomNum = random.nextDouble() * cumProb[cumProb.length - 1]; int index = Arrays.binarySearch(cumProb, randomNum); if (index < 0) { index = -(index + 1); } return lotteryItemList.get(index); } private PlayerPocket saveWinningItem(Product winningItem, LotteryItemDto lotteryItem, Pocket pocket) { PlayerPocket playerPocket = playerPocketService.getItemAsPocketByItemIndexAndCategoryAndPocket(winningItem.getItem0(), winningItem.getCategory(), pocket); int existingItemCount = 0; boolean existingItem = false; boolean existingPartItem = false; if (playerPocket != null && !playerPocket.getCategory().equals(EItemCategory.PARTS.getName())) { existingItemCount = playerPocket.getItemCount(); existingItem = true; } else if (playerPocket != null && playerPocket.getCategory().equals(EItemCategory.PARTS.getName())) { existingPartItem = true; } else { playerPocket = new PlayerPocket(); } if (!existingPartItem) { playerPocket.setCategory(winningItem.getCategory()); playerPocket.setItemIndex(winningItem.getItem0()); playerPocket.setUseType(winningItem.getUseType()); playerPocket.setItemCount(lotteryItem.getQuantityMin() + existingItemCount); if (playerPocket.getUseType().equalsIgnoreCase(EItemUseType.TIME.getName())) { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.add(Calendar.DAY_OF_MONTH, playerPocket.getItemCount()); playerPocket.setCreated(cal.getTime()); playerPocket.setItemCount(1); } playerPocket.setPocket(pocket); playerPocket = playerPocketService.save(playerPocket); if (!existingItem) pocketService.incrementPocketBelongings(playerPocket.getPocket()); } return playerPocket; } }
412
0.829068
1
0.829068
game-dev
MEDIA
0.635229
game-dev
0.957855
1
0.957855
natbro/kaon
32,515
lsteamclient/lsteamclient/steamworks_sdk_146/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_ERemoteStoragePlatformReserved2 = (1 << 4), k_ERemoteStoragePlatformAndroid = (1 << 5), k_ERemoteStoragePlatformIOS = (1 << 6), k_ERemoteStoragePlatformAll = 0xffffffff }; enum ERemoteStoragePublishedFileVisibility { k_ERemoteStoragePublishedFileVisibilityPublic = 0, k_ERemoteStoragePublishedFileVisibilityFriendsOnly = 1, k_ERemoteStoragePublishedFileVisibilityPrivate = 2, }; 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, }; //----------------------------------------------------------------------------- // 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; // The following functions are only necessary on the Playstation 3. On PC & Mac, the Steam client will handle these operations for you // On Playstation 3, the game controls which files are stored in the cloud, via FilePersist, FileFetch, and FileForget. #if defined(_PS3) || defined(_SERVER) // Connect to Steam and get a list of files in the Cloud - results in a RemoteStorageAppSyncStatusCheck_t callback virtual void GetFileListFromServer() = 0; // Indicate this file should be downloaded in the next sync virtual bool FileFetch( const char *pchFile ) = 0; // Indicate this file should be persisted in the next sync virtual bool FilePersist( const char *pchFile ) = 0; // Pull any requested files down from the Cloud - results in a RemoteStorageAppSyncedClient_t callback virtual bool SynchronizeToClient() = 0; // Upload any requested files to the Cloud - results in a RemoteStorageAppSyncedServer_t callback virtual bool SynchronizeToServer() = 0; // Reset any fetch/persist/etc requests virtual bool ResetFileRequestState() = 0; #endif // 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; }; #define STEAMREMOTESTORAGE_INTERFACE_VERSION "STEAMREMOTESTORAGE_INTERFACE_VERSION014" // 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 //----------------------------------------------------------------------------- // Purpose: sent when the local file cache is fully synced with the server for an app // That means that an application can be started and has all latest files //----------------------------------------------------------------------------- struct RemoteStorageAppSyncedClient_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 1 }; AppId_t m_nAppID; EResult m_eResult; int m_unNumDownloads; }; //----------------------------------------------------------------------------- // Purpose: sent when the server is fully synced with the local file cache for an app // That means that we can shutdown Steam and our data is stored on the server //----------------------------------------------------------------------------- struct RemoteStorageAppSyncedServer_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 2 }; AppId_t m_nAppID; EResult m_eResult; int m_unNumUploads; }; //----------------------------------------------------------------------------- // Purpose: Status of up and downloads during a sync session // //----------------------------------------------------------------------------- struct RemoteStorageAppSyncProgress_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 3 }; char m_rgchCurrentFile[k_cchFilenameMax]; // Current file being transferred AppId_t m_nAppID; // App this info relates to uint32 m_uBytesTransferredThisChunk; // Bytes transferred this chunk double m_dAppPercentComplete; // Percent complete that this app's transfers are bool m_bUploading; // if false, downloading }; // // IMPORTANT! k_iClientRemoteStorageCallbacks + 4 is used, see iclientremotestorage.h // //----------------------------------------------------------------------------- // Purpose: Sent after we've determined the list of files that are out of sync // with the server. //----------------------------------------------------------------------------- struct RemoteStorageAppSyncStatusCheck_t { enum { k_iCallback = k_iClientRemoteStorageCallbacks + 5 }; AppId_t m_nAppID; EResult m_eResult; }; //----------------------------------------------------------------------------- // 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; }; //----------------------------------------------------------------------------- // 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 }; #pragma pack( pop ) #endif // ISTEAMREMOTESTORAGE_H
412
0.98332
1
0.98332
game-dev
MEDIA
0.812457
game-dev
0.777923
1
0.777923
refinedmods/refinedstorage2
4,663
refinedstorage-common/src/main/java/com/refinedmods/refinedstorage/common/constructordestructor/BlockBreakDestructorStrategy.java
package com.refinedmods.refinedstorage.common.constructordestructor; import com.refinedmods.refinedstorage.api.core.Action; import com.refinedmods.refinedstorage.api.network.Network; import com.refinedmods.refinedstorage.api.network.storage.StorageNetworkComponent; import com.refinedmods.refinedstorage.api.resource.filter.Filter; import com.refinedmods.refinedstorage.api.storage.Actor; import com.refinedmods.refinedstorage.api.storage.root.RootStorage; import com.refinedmods.refinedstorage.common.Platform; import com.refinedmods.refinedstorage.common.api.constructordestructor.DestructorStrategy; import com.refinedmods.refinedstorage.common.support.resource.ItemResource; import java.util.List; import java.util.function.Supplier; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Containers; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.state.BlockState; class BlockBreakDestructorStrategy implements DestructorStrategy { private final ServerLevel level; private final BlockPos pos; private final Direction direction; private final ItemStack tool; BlockBreakDestructorStrategy( final ServerLevel level, final BlockPos pos, final Direction direction, final ItemStack tool ) { this.level = level; this.pos = pos; this.direction = direction; this.tool = tool; } @Override public boolean apply(final Filter filter, final Actor actor, final Supplier<Network> networkProvider, final Player player) { if (!level.isLoaded(pos)) { return false; } final BlockState blockState = level.getBlockState(pos); final Block block = blockState.getBlock(); if (isFastExit(blockState) || blockState.getDestroySpeed(level, pos) == -1.0 || !isAllowed(player, filter, blockState, block) || !Platform.INSTANCE.canBreakBlock(level, pos, blockState, player)) { return false; } final List<ItemStack> drops = Block.getDrops( blockState, level, pos, level.getBlockEntity(pos), player, tool ); if (!insertDrops(actor, drops, getRootStorage(networkProvider), Action.SIMULATE)) { return false; } block.playerWillDestroy(level, pos, blockState, player); level.removeBlock(pos, false); insertDrops(actor, drops, getRootStorage(networkProvider), Action.EXECUTE); return true; } private static RootStorage getRootStorage(final Supplier<Network> network) { return network.get().getComponent(StorageNetworkComponent.class); } private static boolean isFastExit(final BlockState blockState) { return blockState.isAir() || blockState.getBlock() instanceof LiquidBlock; } private boolean isAllowed( final Player actingPlayer, final Filter filter, final BlockState state, final Block block ) { final ItemStack blockAsStack = Platform.INSTANCE.getBlockAsItemStack( block, state, direction, level, pos, actingPlayer ); if (blockAsStack.isEmpty()) { return false; } final ItemResource blockAsResource = ItemResource.ofItemStack(blockAsStack); return filter.isAllowed(blockAsResource); } private boolean insertDrops( final Actor actor, final List<ItemStack> drops, final RootStorage storage, final Action action ) { for (final ItemStack drop : drops) { final ItemResource resource = ItemResource.ofItemStack(drop); final boolean didNotInsertCompletely = storage.insert(resource, drop.getCount(), action, actor) != drop.getCount(); if (didNotInsertCompletely) { final boolean didWeDisconnectStorageInTheProcessOfRemovingABlock = action == Action.EXECUTE; if (didWeDisconnectStorageInTheProcessOfRemovingABlock) { Containers.dropItemStack(level, pos.getX(), pos.getY(), pos.getZ(), drop); } else { return false; } } } return true; } }
412
0.876493
1
0.876493
game-dev
MEDIA
0.996944
game-dev
0.975677
1
0.975677