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
plankes-projects/BaseWar
7,529
client/proj.ios/libs/cocos2dx/actions/CCActionGrid.h
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2009 On-Core http://www.cocos2d-x.org 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 __ACTION_CCGRID_ACTION_H__ #define __ACTION_CCGRID_ACTION_H__ #include "CCActionInterval.h" #include "CCActionInstant.h" NS_CC_BEGIN class CCGridBase; /** * @addtogroup actions * @{ */ /** @brief Base class for Grid actions */ class CC_DLL CCGridAction : public CCActionInterval { public: virtual CCObject* copyWithZone(CCZone* pZone); virtual void startWithTarget(CCNode *pTarget); virtual CCActionInterval* reverse(void); /** initializes the action with size and duration */ virtual bool initWithDuration(float duration, const CCSize& gridSize); /** returns the grid */ virtual CCGridBase* getGrid(void); public: /** creates the action with size and duration */ // We can't make this create function compatible with previous version, bindings-generator will be confused since they // have the same function name and the same number of arguments. So sorry about that. //CC_DEPRECATED_ATTRIBUTE static CCGridAction* create(const CCSize& gridSize, float duration); /** creates the action with size and duration */ static CCGridAction* create(float duration, const CCSize& gridSize); protected: CCSize m_sGridSize; }; /** @brief Base class for CCGrid3D actions. Grid3D actions can modify a non-tiled grid. */ class CC_DLL CCGrid3DAction : public CCGridAction { public: /** returns the grid */ virtual CCGridBase* getGrid(void); /** returns the vertex than belongs to certain position in the grid */ ccVertex3F vertex(const CCPoint& position); /** returns the non-transformed vertex than belongs to certain position in the grid */ ccVertex3F originalVertex(const CCPoint& position); /** sets a new vertex to a certain position of the grid */ void setVertex(const CCPoint& position, const ccVertex3F& vertex); public: /** creates the action with size and duration */ static CCGrid3DAction* create(float duration, const CCSize& gridSize); }; /** @brief Base class for CCTiledGrid3D actions */ class CC_DLL CCTiledGrid3DAction : public CCGridAction { public: /** returns the tile that belongs to a certain position of the grid */ ccQuad3 tile(const CCPoint& position); /** returns the non-transformed tile that belongs to a certain position of the grid */ ccQuad3 originalTile(const CCPoint& position); /** sets a new tile to a certain position of the grid */ void setTile(const CCPoint& position, const ccQuad3& coords); /** returns the grid */ virtual CCGridBase* getGrid(void); public: /** creates the action with size and duration */ static CCTiledGrid3DAction* create(float duration, const CCSize& gridSize); }; /** @brief CCAccelDeccelAmplitude action */ class CC_DLL CCAccelDeccelAmplitude : public CCActionInterval { public: virtual ~CCAccelDeccelAmplitude(void); /** initializes the action with an inner action that has the amplitude property, and a duration time */ bool initWithAction(CCAction *pAction, float duration); virtual void startWithTarget(CCNode *pTarget); virtual void update(float time); virtual CCActionInterval* reverse(void); /** get amplitude rate */ inline float getRate(void) { return m_fRate; } /** set amplitude rate */ inline void setRate(float fRate) { m_fRate = fRate; } public: /** creates the action with an inner action that has the amplitude property, and a duration time */ static CCAccelDeccelAmplitude* create(CCAction *pAction, float duration); protected: float m_fRate; CCActionInterval *m_pOther; }; /** @brief CCAccelAmplitude action */ class CC_DLL CCAccelAmplitude : public CCActionInterval { public: ~CCAccelAmplitude(void); /** initializes the action with an inner action that has the amplitude property, and a duration time */ bool initWithAction(CCAction *pAction, float duration); /** get amplitude rate */ inline float getRate(void) { return m_fRate; } /** set amplitude rate */ inline void setRate(float fRate) { m_fRate = fRate; } virtual void startWithTarget(CCNode *pTarget); virtual void update(float time); virtual CCActionInterval* reverse(void); public: /** creates the action with an inner action that has the amplitude property, and a duration time */ static CCAccelAmplitude* create(CCAction *pAction, float duration); protected: float m_fRate; CCActionInterval *m_pOther; }; /** @brief CCDeccelAmplitude action */ class CC_DLL CCDeccelAmplitude : public CCActionInterval { public: ~CCDeccelAmplitude(void); /** initializes the action with an inner action that has the amplitude property, and a duration time */ bool initWithAction(CCAction *pAction, float duration); /** get amplitude rate */ inline float getRate(void) { return m_fRate; } /** set amplitude rate */ inline void setRate(float fRate) { m_fRate = fRate; } virtual void startWithTarget(CCNode *pTarget); virtual void update(float time); virtual CCActionInterval* reverse(void); public: /** creates the action with an inner action that has the amplitude property, and a duration time */ static CCDeccelAmplitude* create(CCAction *pAction, float duration); protected: float m_fRate; CCActionInterval *m_pOther; }; /** @brief CCStopGrid action. @warning Don't call this action if another grid action is active. Call if you want to remove the the grid effect. Example: CCSequence::actions(Lens::action(...), CCStopGrid::action(...), NULL); */ class CC_DLL CCStopGrid : public CCActionInstant { public: virtual void startWithTarget(CCNode *pTarget); public: /** Allocates and initializes the action */ static CCStopGrid* create(void); }; /** @brief CCReuseGrid action */ class CC_DLL CCReuseGrid : public CCActionInstant { public: /** initializes an action with the number of times that the current grid will be reused */ bool initWithTimes(int times); virtual void startWithTarget(CCNode *pTarget); public: /** creates an action with the number of times that the current grid will be reused */ static CCReuseGrid* create(int times); protected: int m_nTimes; }; // end of actions group /// @} NS_CC_END #endif // __ACTION_CCGRID_ACTION_H__
412
0.955535
1
0.955535
game-dev
MEDIA
0.950149
game-dev
0.542163
1
0.542163
Le-Petit-C/LPCTools
1,274
src/client/java/lpctools/mixin/client/ClientPlayNetworkHandlerMixin.java
package lpctools.mixin.client; import com.llamalad7.mixinextras.sugar.Local; import lpctools.lpcfymasaapi.Registries; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.world.ClientWorld; import net.minecraft.network.packet.s2c.play.ChunkDataS2CPacket; import net.minecraft.world.chunk.WorldChunk; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @Mixin(ClientPlayNetworkHandler.class) public class ClientPlayNetworkHandlerMixin { @Shadow private ClientWorld world; @ModifyArg(method = "onChunkData", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/world/ClientWorld;enqueueChunkUpdate(Ljava/lang/Runnable;)V")) Runnable inject(Runnable updater, @Local(argsOnly = true) ChunkDataS2CPacket packet){ int i = packet.getChunkX(); int j = packet.getChunkZ(); return ()->{ updater.run(); WorldChunk worldChunk = world.getChunkManager().getWorldChunk(i, j, false); if (worldChunk != null) Registries.CLIENT_CHUNK_LIGHT_LOAD.run().onClientWorldChunkLightUpdated(world, worldChunk); }; } }
412
0.709779
1
0.709779
game-dev
MEDIA
0.931098
game-dev
0.665469
1
0.665469
castle-engine/castle-engine
3,540
tools/build-tool/data/android/services/sound/app/src/main/cpp/sound/openal-soft/core/mastering.h
#ifndef CORE_MASTERING_H #define CORE_MASTERING_H #include <memory> #include "almalloc.h" #include "bufferline.h" struct SlidingHold; using uint = unsigned int; /* General topology and basic automation was based on the following paper: * * D. Giannoulis, M. Massberg and J. D. Reiss, * "Parameter Automation in a Dynamic Range Compressor," * Journal of the Audio Engineering Society, v61 (10), Oct. 2013 * * Available (along with supplemental reading) at: * * http://c4dm.eecs.qmul.ac.uk/audioengineering/compressors/ */ struct Compressor { size_t mNumChans{0u}; struct { bool Knee : 1; bool Attack : 1; bool Release : 1; bool PostGain : 1; bool Declip : 1; } mAuto{}; uint mLookAhead{0}; float mPreGain{0.0f}; float mPostGain{0.0f}; float mThreshold{0.0f}; float mSlope{0.0f}; float mKnee{0.0f}; float mAttack{0.0f}; float mRelease{0.0f}; alignas(16) float mSideChain[2*BufferLineSize]{}; alignas(16) float mCrestFactor[BufferLineSize]{}; SlidingHold *mHold{nullptr}; FloatBufferLine *mDelay{nullptr}; float mCrestCoeff{0.0f}; float mGainEstimate{0.0f}; float mAdaptCoeff{0.0f}; float mLastPeakSq{0.0f}; float mLastRmsSq{0.0f}; float mLastRelease{0.0f}; float mLastAttack{0.0f}; float mLastGainDev{0.0f}; ~Compressor(); void process(const uint SamplesToDo, FloatBufferLine *OutBuffer); int getLookAhead() const noexcept { return static_cast<int>(mLookAhead); } DEF_PLACE_NEWDEL() /** * The compressor is initialized with the following settings: * * \param NumChans Number of channels to process. * \param SampleRate Sample rate to process. * \param AutoKnee Whether to automate the knee width parameter. * \param AutoAttack Whether to automate the attack time parameter. * \param AutoRelease Whether to automate the release time parameter. * \param AutoPostGain Whether to automate the make-up (post) gain * parameter. * \param AutoDeclip Whether to automate clipping reduction. Ignored * when not automating make-up gain. * \param LookAheadTime Look-ahead time (in seconds). * \param HoldTime Peak hold-time (in seconds). * \param PreGainDb Gain applied before detection (in dB). * \param PostGainDb Make-up gain applied after compression (in dB). * \param ThresholdDb Triggering threshold (in dB). * \param Ratio Compression ratio (x:1). Set to INFINIFTY for true * limiting. Ignored when automating knee width. * \param KneeDb Knee width (in dB). Ignored when automating knee * width. * \param AttackTime Attack time (in seconds). Acts as a maximum when * automating attack time. * \param ReleaseTime Release time (in seconds). Acts as a maximum when * automating release time. */ static std::unique_ptr<Compressor> Create(const size_t NumChans, const float SampleRate, const bool AutoKnee, const bool AutoAttack, const bool AutoRelease, const bool AutoPostGain, const bool AutoDeclip, const float LookAheadTime, const float HoldTime, const float PreGainDb, const float PostGainDb, const float ThresholdDb, const float Ratio, const float KneeDb, const float AttackTime, const float ReleaseTime); }; using CompressorPtr = std::unique_ptr<Compressor>; #endif /* CORE_MASTERING_H */
412
0.946471
1
0.946471
game-dev
MEDIA
0.65863
game-dev
0.886186
1
0.886186
shasankp000/AI-Player
4,678
src/main/java/net/shasankp000/DangerZoneDetector/LavaDetector.java
package net.shasankp000.DangerZoneDetector; import net.minecraft.block.Blocks; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Box; import net.minecraft.util.math.Vec3d; import net.minecraft.world.RaycastContext; import net.minecraft.world.World; public class LavaDetector { /** * Detects the nearest lava block by casting rays in multiple directions. * * @param source The bot entity (or player). * @param reach The maximum distance to check. * @return Distance to the nearest lava block, or Double.MAX_VALUE if none found. */ public static double detectNearestLavaWithRaycast(ServerPlayerEntity source, double reach) { double nearestDistance = Double.MAX_VALUE; // Cast rays in 6 cardinal directions (positive and negative X, Y, Z) Vec3d[] directions = new Vec3d[]{ new Vec3d(1, 0, 0), // +X new Vec3d(-1, 0, 0), // -X new Vec3d(0, 1, 0), // +Y new Vec3d(0, -1, 0), // -Y new Vec3d(0, 0, 1), // +Z new Vec3d(0, 0, -1) // -Z }; for (Vec3d direction : directions) { double distance = rayTraceForLava(source, direction, reach); if (distance < nearestDistance) { nearestDistance = distance; } } return nearestDistance; } /** * Casts a single ray in a given direction to detect lava blocks. * * @param source The bot entity (or player). * @param direction The direction to cast the ray. * @param reach The maximum distance to cast. * @return Distance to the nearest lava block, or Double.MAX_VALUE if none found. */ private static double rayTraceForLava(ServerPlayerEntity source, Vec3d direction, double reach) { Vec3d start = source.getCameraPosVec(1.0F); // Starting point of the ray Vec3d end = start.add(direction.multiply(reach)); // End point of the ray BlockHitResult blockHit = source.getWorld().raycast(new RaycastContext( start, end, RaycastContext.ShapeType.OUTLINE, RaycastContext.FluidHandling.ANY, source )); // Check if the block hit is lava if (blockHit != null && source.getWorld().getBlockState(blockHit.getBlockPos()).isOf(Blocks.LAVA)) { return start.distanceTo(blockHit.getPos()); } return Double.MAX_VALUE; // No lava found in this direction } /** * Detects the nearest lava block within a bounding box around the bot. * * @param source The bot entity. * @param range The search range (distance in blocks from the bot). * @return Distance to the nearest lava block, or Double.MAX_VALUE if none found. */ public static double detectNearestLavaWithBoundingBox(ServerPlayerEntity source, int range) { World world = source.getWorld(); // Define a bounding box around the bot Box boundingBox = source.getBoundingBox().expand(range, range, range); double nearestDistance = Double.MAX_VALUE; // Iterate through all block positions within the bounding box BlockPos.Mutable mutable = new BlockPos.Mutable(); for (int x = (int) boundingBox.minX; x <= (int) boundingBox.maxX; x++) { for (int y = (int) boundingBox.minY; y <= (int) boundingBox.maxY; y++) { for (int z = (int) boundingBox.minZ; z <= (int) boundingBox.maxZ; z++) { mutable.set(x, y, z); // Check if the block is a lava source or flowing lava if (world.getBlockState(mutable).isOf(Blocks.LAVA)) { double distance = source.getPos().distanceTo(Vec3d.ofCenter(mutable)); if (distance < nearestDistance) { nearestDistance = distance; } } } } } return nearestDistance; } public static double detectNearestLava(ServerPlayerEntity source, double reach, int range) { // Step 1: Try raycasting for visible lava double nearestLavaFromRaycast = detectNearestLavaWithRaycast(source, reach); // Step 2: If no visible lava, fall back to bounding box if (nearestLavaFromRaycast == Double.MAX_VALUE) { return detectNearestLavaWithBoundingBox(source, range); } return nearestLavaFromRaycast; } }
412
0.821293
1
0.821293
game-dev
MEDIA
0.880682
game-dev
0.917133
1
0.917133
lucrybpin/unity-lab
4,071
Assets/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 #if true // MODULE_MARKER using System; using UnityEngine; using DG.Tweening.Core; using DG.Tweening.Plugins.Options; #pragma warning disable 1591 namespace DG.Tweening { public static class DOTweenModuleSprite { #region Shortcuts #region SpriteRenderer /// <summary>Tweens a SpriteRenderer's color to the given value. /// Also stores the spriteRenderer as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this SpriteRenderer target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Material's alpha color to the given value. /// Also stores the spriteRenderer as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this SpriteRenderer target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a SpriteRenderer's color using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this SpriteRenderer target, Gradient gradient, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.color = c.color; continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } #endregion #region Blendables #region SpriteRenderer /// <summary>Tweens a SpriteRenderer's color to the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the SpriteRenderer as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this SpriteRenderer target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #endregion #endregion } } #endif
412
0.791138
1
0.791138
game-dev
MEDIA
0.748815
game-dev
0.940109
1
0.940109
kek-m8/kek-eft-dma
10,985
arena-dma-radar/Arena/ArenaPlayer/ArenaObservedPlayer.cs
using arena_dma_radar.Arena.ArenaPlayer.Plugins; using arena_dma_radar.Arena.GameWorld; using eft_dma_shared.Common.DMA.ScatterAPI; using eft_dma_shared.Common.Misc; using eft_dma_shared.Common.Misc.Commercial; using eft_dma_shared.Common.Players; using eft_dma_shared.Common.Unity; using eft_dma_shared.Common.Unity.Collections; using static SDK.ClassNames; namespace arena_dma_radar.Arena.ArenaPlayer { public sealed class ArenaObservedPlayer : Player { private ulong _arenaOverlayDataContainer; /// <summary> /// ObservedPlayerController for non-clientplayer players. /// </summary> private ulong ObservedPlayerController { get; } /// <summary> /// ObservedHealthController for non-clientplayer players. /// </summary> private ulong ObservedHealthController { get; } /// <summary> /// Player name. /// </summary> public override string Name { get; } /// <summary> /// Account UUID for Human Controlled Players. /// </summary> public override string AccountID { get; } /// <summary> /// Group that the player belongs to. /// </summary> public override int TeamID { get; } = -1; /// <summary> /// Player's Faction. /// </summary> public override Enums.EPlayerSide PlayerSide { get; } /// <summary> /// Player is Human-Controlled. /// </summary> public override bool IsHuman { get; } /// <summary> /// MovementContext / StateContext /// </summary> public override ulong MovementContext { get; } /// <summary> /// EFT.PlayerBody /// </summary> public override ulong Body { get; } /// <summary> /// Inventory Controller field address. /// </summary> public override ulong InventoryControllerAddr { get; } /// <summary> /// Hands Controller field address. /// </summary> public override ulong HandsControllerAddr { get; } /// <summary> /// Corpse field address.. /// </summary> public override ulong CorpseAddr { get; } public override ulong BodyStateAddr { get; } /// <summary> /// Player Rotation Field Address (view angles). /// </summary> public override ulong RotationAddress { get; } /// <summary> /// Player's Skeleton Bones. /// </summary> public override Skeleton Skeleton_ { get; } /// <summary> /// Player's Current Health Status /// </summary> public Enums.ETagStatus HealthStatus { get; private set; } = Enums.ETagStatus.Healthy; /// <summary> /// Player's Gear/Loadout Information and contained items. /// </summary> public GearManager Gear { get; private set; } /// <summary> /// Contains information about the item/weapons in Player's hands. /// </summary> public HandsManager Hands { get; private set; } internal ArenaObservedPlayer(ulong playerBase) : base(playerBase) { var side = (Enums.EPlayerSide)Memory.ReadValue<int>(this + Offsets.ObservedPlayerView.Side, false); var cameraType = Memory.ReadValue<int>(this + Offsets.ObservedPlayerView.VisibleToCameraType); ArgumentOutOfRangeException.ThrowIfNotEqual(cameraType, (int)Enums.ECameraType.Default, nameof(cameraType)); ObservedPlayerController = Memory.ReadPtr(this + Offsets.ObservedPlayerView.ObservedPlayerController); ArgumentOutOfRangeException.ThrowIfNotEqual(this, Memory.ReadValue<ulong>(ObservedPlayerController + Offsets.ObservedPlayerController.Player), nameof(ObservedPlayerController)); ObservedHealthController = Memory.ReadPtr(ObservedPlayerController + Offsets.ObservedPlayerController.HealthController); ArgumentOutOfRangeException.ThrowIfNotEqual(this, Memory.ReadValue<ulong>(ObservedHealthController + Offsets.ObservedHealthController.Player), nameof(ObservedHealthController)); Body = Memory.ReadPtr(this + Offsets.ObservedPlayerView.PlayerBody); InventoryControllerAddr = ObservedPlayerController + Offsets.ObservedPlayerController.InventoryController; HandsControllerAddr = ObservedPlayerController + Offsets.ObservedPlayerController.HandsController; CorpseAddr = ObservedHealthController + Offsets.ObservedHealthController.PlayerCorpse; AccountID = GetAccountID(); IsFocused = CheckIfFocused(); TeamID = GetTeamID(); MovementContext = GetMovementContext(); //SetPlayerState(); RotationAddress = ValidateRotationAddr(MovementContext + Offsets.ObservedMovementController.Rotation); /// Setup Transforms this.Skeleton_ = new Skeleton(this, GetTransformInternalChain); bool isAI = Memory.ReadValue<bool>(this + Offsets.ObservedPlayerView.IsAI); IsHuman = !isAI; if (isAI) { Name = "AI"; Type = PlayerType.AI; } else // Human Player { if (LocalGameWorld.MatchHasTeams) ArgumentOutOfRangeException.ThrowIfEqual(TeamID, -1, nameof(TeamID)); Name = GetName(); Type = TeamID != -1 && TeamID == Memory.LocalPlayer.TeamID ? PlayerType.Teammate : PlayerType.Player; } } /// <summary> /// Get Player's Account ID. /// </summary> /// <returns>Account ID Numeric String.</returns> private string GetAccountID() { var idPTR = Memory.ReadPtr(this + Offsets.ObservedPlayerView.AccountId); return Memory.ReadUnityString(idPTR); } /*private float GetHealthForBone(Enums.EBodyPart bone) { var dictPtr = Memory.ReadValue<ulong>(BodyStateAddr, false); var dict = MemDictionary<ulong, ulong>.Get(dictPtr, false); foreach (var entry in dict) { //entry.Key = EBodyPart //entry.Value = BodyPartState if(entry.Key == (ulong)bone) { var bodyPartStatePtr = Memory.ReadPtr(entry.Value, false); var healthPtr = Memory.ReadPtr(bodyPartStatePtr + 0x10, false); var isDestroyed = Memory.ReadValue<bool>(healthPtr + 0x18, false); if (isDestroyed) return 0f; var valuePtr = Memory.ReadPtr(healthPtr + 0x10, false); return Memory.ReadValue<float>(valuePtr); } } return -1f; // not found }*/ /// <summary> /// Gets player's Team ID. /// </summary> private int GetTeamID() { try { var inventoryController = Memory.ReadPtr(ObservedPlayerController + Offsets.ObservedPlayerController.InventoryController); return GetTeamID(inventoryController); } catch { return -1; } } /// <summary> /// Get Player Name. /// </summary> /// <returns>Player Name String.</returns> private string GetName() { var namePtr = Memory.ReadPtr(this + Offsets.ObservedPlayerView.NickName); var name = Memory.ReadUnityString(namePtr)?.Trim(); if (string.IsNullOrEmpty(name)) name = "default"; return name; } /*private void SetPlayerState() { PlayerState = (Enums.EPlayerState)Memory.ReadValue<byte>(MovementContext + Offsets.ObservedMovementController.CurrentStateName); }*/ /// <summary> /// Get Movement Context Instance. /// </summary> private ulong GetMovementContext() { return Memory.ReadPtrChain(ObservedPlayerController, Offsets.ObservedPlayerController.MovementController); } /// <summary> /// Refresh Player Information. /// </summary> public override void OnRegRefresh(ScatterReadIndex index, IReadOnlySet<ulong> registered, bool? isActiveParam = null) { if (isActiveParam is not bool isActive) isActive = registered.Contains(this); if (isActive) { UpdateHealthStatus(); //SetPlayerState(); } base.OnRegRefresh(index, registered, isActive); } /// <summary> /// Get Player's Updated Health Condition /// Only works in Online Mode. /// </summary> public void UpdateHealthStatus() { try { var tag = (Enums.ETagStatus)Memory.ReadValue<int>(ObservedHealthController + Offsets.ObservedHealthController.HealthStatus); if ((tag & Enums.ETagStatus.Dying) == Enums.ETagStatus.Dying) HealthStatus = Enums.ETagStatus.Dying; else if ((tag & Enums.ETagStatus.BadlyInjured) == Enums.ETagStatus.BadlyInjured) HealthStatus = Enums.ETagStatus.BadlyInjured; else if ((tag & Enums.ETagStatus.Injured) == Enums.ETagStatus.Injured) HealthStatus = Enums.ETagStatus.Injured; else HealthStatus = Enums.ETagStatus.Healthy; } catch (Exception ex) { LoneLogging.WriteLine($"ERROR updating Health Status for '{Name}': {ex}"); } } /// <summary> /// Get the Transform Internal Chain for this Player. /// </summary> /// <param name="bone">Bone to lookup.</param> /// <returns>Array of offsets for transform internal chain.</returns> public override uint[] GetTransformInternalChain(Bones bone) => Offsets.ObservedPlayerView.GetTransformChain(bone); /// <summary> /// Get Player's Gear/Equipment. /// </summary> public void GetGear() { try { Gear ??= new(this); } catch (Exception ex) { LoneLogging.WriteLine($"[GearManager] ERROR for Player {Name}: {ex}"); } } /// <summary> /// Refresh item in player's hands. /// </summary> public void RefreshHands() { try { if (IsActive && IsAlive) { Hands ??= new HandsManager(this); Hands?.Refresh(); } } catch { } } } }
412
0.957079
1
0.957079
game-dev
MEDIA
0.774361
game-dev
0.911606
1
0.911606
modernuo/ModernUO
3,746
Projects/UOContent/Engines/Bulk Orders/BaseBOD.cs
using System.Collections.Generic; using ModernUO.Serialization; namespace Server.Engines.BulkOrders { [SerializationGenerator(1)] public abstract partial class BaseBOD : Item { public BaseBOD(int hue, int amountMax, bool requireExeptional, BulkMaterialType material) : this() { Hue = hue; _amountMax = amountMax; _requireExceptional = requireExeptional; _material = material; } public BaseBOD() : base(Core.AOS ? 0x2258 : 0x14EF) => LootType = LootType.Blessed; public override double DefaultWeight => 1.0; public abstract bool Complete { get; } [SerializableField(0)] [InvalidateProperties] [SerializedCommandProperty(AccessLevel.GameMaster)] private int _amountMax; [SerializableField(1)] [InvalidateProperties] [SerializedCommandProperty(AccessLevel.GameMaster)] private bool _requireExceptional; [SerializableField(2)] [InvalidateProperties] [SerializedCommandProperty(AccessLevel.GameMaster)] private BulkMaterialType _material; public static BulkMaterialType GetRandomMaterial(BulkMaterialType start, double[] chances) { var random = Utility.RandomDouble(); for (var i = 0; i < chances.Length; ++i) { if (random < chances[i]) { return i == 0 ? BulkMaterialType.None : start + (i - 1); } random -= chances[i]; } return BulkMaterialType.None; } public abstract RewardGroup GetRewardGroup(); public abstract int ComputeGold(); public abstract int ComputeFame(); public abstract void EndCombine(Mobile from, Item item); public virtual void GetRewards(out Item reward, out int gold, out int fame) { gold = ComputeGold(); fame = ComputeFame(); var rewards = ComputeRewards(false); reward = rewards.RandomElement()?.Construct(); } public virtual List<RewardItem> ComputeRewards(bool full) { var rewardGroup = GetRewardGroup(); var list = new List<RewardItem>(); if (full) { for (var i = 0; i < rewardGroup?.Items.Length; ++i) { var reward = rewardGroup.Items[i]; if (reward != null) { list.Add(reward); } } } else { var reward = rewardGroup.AcquireItem(); if (reward != null) { list.Add(reward); } } return list; } public virtual void BeginCombine(Mobile from) { if (Complete) { // The maximum amount of requested items have already been combined to this deed. from.SendLocalizedMessage(1045166); } else { from.Target = new BODTarget(this); } } [AfterDeserialization(false)] private void AfterDeserialization() { if (Parent == null && Map == Map.Internal && Location == Point3D.Zero) { Delete(); } } private void Deserialize(IGenericReader reader, int version) { AmountMax = reader.ReadInt(); RequireExceptional = reader.ReadBool(); Material = (BulkMaterialType)reader.ReadInt(); } } }
412
0.92452
1
0.92452
game-dev
MEDIA
0.945259
game-dev
0.950064
1
0.950064
GeneralTradingSarl/mql4_experts
7,914
Indics Shaker EA - expert for MetaTrader 4/6xIndics_M.mq4
//+------------------------------------------------------------------+ //| Indics_Shaker.mq4 | //| Gift or donations accepted [:-) | //+------------------------------------------------------------------+ #property copyright "mich99@o2.pl" #property link "" extern bool SELL = true; extern bool BUY = true; extern bool Closeby = false; extern double k = 1; extern double u = 2; extern double t = 3; extern double e = 4; extern double r = 3; extern double o = 4; extern double sh1 = 10; extern double sh2 = 10; extern double sh3 = 10; extern double zz = 1; extern int tp = 300;//for 4 digits = 30 extern int sl = 300; extern bool Trailing = false; extern int tsl = 300; extern bool ProfitTrailing = false; extern int LockPips = 300; extern double lots = 0.1; extern bool Martingale = false; extern int MagicNumber = 911; static int prevtime = 0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---- return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- return(0); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { if(Time[0] == prevtime) return(0); prevtime = Time[0]; //---- if(IsTradeAllowed()) { RefreshRates(); } else { prevtime = Time[1]; return(0); } int ticket = -1; int total = OrdersTotal(); //---- for(int i = 0; i < total; i++) { OrderSelect(i, SELECT_BY_POS, MODE_TRADES); if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { int prevticket = OrderTicket(); if(OrderType() == OP_BUY) { if(Bid > OrderOpenPrice() ) { if(OPEN_POS()<0 && Closeby ) { ticket = OrderClose(OrderTicket(), OrderLots(), Bid, 30, MediumSeaGreen); Sleep(10000); if(ticket < 0) prevtime = Time[1]; } if( Trailing && OrderStopLoss()<Bid-tsl * Point && (!ProfitTrailing || Bid > OrderOpenPrice()+(tsl+LockPips)*Point)) { // trailing stop if(!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - tsl * Point, OrderTakeProfit(), 0, Blue)) { Sleep(30000); prevtime = Time[1]; } } } } else { if(Ask < OrderOpenPrice() ) { if(OPEN_POS()>0 && Closeby ) { ticket = OrderClose(OrderTicket(), OrderLots(), Ask, 30, MediumSeaGreen); Sleep(10000); //---- if(ticket < 0) prevtime = Time[1]; } if(Trailing && OrderStopLoss()>Ask +tsl*Point && (!ProfitTrailing || Ask < OrderOpenPrice()-((tsl+LockPips)*Point))) { if(!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + tsl * Point, OrderTakeProfit(), 0, Blue)) { Sleep(30000); prevtime = Time[1]; } } } } return(0); } } if(BUY &&OPEN_POS()>0 ) { ticket = OrderSend(Symbol(), OP_BUY, LotSize() , Ask, 30, Ask - sl * Point,Ask + tp * Point, WindowExpertName(), MagicNumber, 0, Blue); if(ticket < 0) { Sleep(30000); prevtime = Time[1]; } } if(SELL &&OPEN_POS()<0 ) { ticket = OrderSend(Symbol(), OP_SELL, LotSize() , Bid, 30, Bid + sl * Point, Bid - tp * Point, WindowExpertName(), MagicNumber, 0, Red); if(ticket < 0) { Sleep(30000); prevtime = Time[1]; } } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ double OPEN_POS() { double klon1 = iAC(Symbol(),0,1); double klon2 = iAC(Symbol(),0,10); double klon3 = iAC(Symbol(),0,20); double klon4 = iAO(Symbol(),0,0)-iAO(Symbol(),0,sh1); double klon5 = iAC(Symbol(),0,0)-iAC(Symbol(),0,sh2); double klon6 = iAC(Symbol(),0,0)-iAC(Symbol(),0,sh3); double a = 0; double b = 0; double c = 0; double d = 0; double f = 0; double g = 0; if(k==0)a=klon1; if(k==1)a=klon2; if(k==2)a=klon3; if(k==3)a=klon4; if(k==4)a=klon5; if(k==5)a=klon6; if(u==0)b=klon1; if(u==1)b=klon2; if(u==2)b=klon3; if(u==3)b=klon4; if(u==4)b=klon5; if(u==5)b=klon6; if(t==0)c=klon1; if(t==1)c=klon2; if(t==2)c=klon3; if(t==3)c=klon4; if(t==4)c=klon5; if(t==5)c=klon6; if(e==0)d=klon1; if(e==1)d=klon2; if(e==2)d=klon3; if(e==3)d=klon4; if(e==4)d=klon5; if(e==5)d=klon6; if(r==0)f=klon1; if(r==1)f=klon2; if(r==2)f=klon3; if(r==3)f=klon4; if(r==4)f=klon5; if(r==5)f=klon6; if(o==0)g=klon1; if(o==1)g=klon2; if(o==2)g=klon3; if(o==3)g=klon4; if(o==4)g=klon5; if(o==5)g=klon6; double stoch70 =iStochastic(NULL, 0, 5, 5, 5, 0, 0, MODE_MAIN, 1); if( a > 0 && b > 0.0001*zz && c > 0.0002*zz && d < 0 && f < 0.0001*zz && g < 0.0002*zz && stoch70<15 ) { return(1);} // a > xb/100 && c > yb/100 if( a < 0 && b < 0.0001*zz && c < 0.0002*zz && d > 0 && f > 0.0001*zz && g > 0.0002*zz && stoch70>85 ) { return(-1);} //b > xs/100 && d > ys/100 return(0); } double LotSize() { if (IsOptimization()|| !Martingale ) { return(lots); } double losses = 0; double minlot = MarketInfo(Symbol(), MODE_MINLOT); int round = MathAbs(MathLog(minlot) / MathLog(10.0)) + 0.5; double result = lots; int total = OrdersHistoryTotal(); double spread = MarketInfo(Symbol(), MODE_SPREAD); double k = (tp + sl) / (tp ); for (int i = 0; i < total; i++) { OrderSelect(i, SELECT_BY_POS, MODE_HISTORY); if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { if (OrderProfit() > 0) { result = lots; losses = 0; } else { result = result * k; losses++; } } } result = NormalizeDouble(result, round); double maxlot = MarketInfo(Symbol(), MODE_MAXLOT); if (result > maxlot) { result = maxlot; } if (result < minlot) { MagicNumber = MagicNumber + 1; } RefreshRates(); return(result); }
412
0.629431
1
0.629431
game-dev
MEDIA
0.75056
game-dev
0.904454
1
0.904454
Kermalis/PokemonBattleEngine
2,140
PokemonBattleEngineTests/Moves/BellyDrumTests.cs
using Kermalis.PokemonBattleEngine.Battle; using Kermalis.PokemonBattleEngine.Data; using Xunit; using Xunit.Abstractions; namespace Kermalis.PokemonBattleEngineTests.Moves; [Collection("Utils")] public class BellyDrumTests { public BellyDrumTests(TestUtils _, ITestOutputHelper output) { TestUtils.SetOutputHelper(output); } [Theory] [InlineData(true)] [InlineData(false)] public void BellyDrum_Contrary__Bug(bool bugFix) { #region Setup PBEDataProvider.GlobalRandom.Seed = 0; var settings = new PBESettings { BugFix = bugFix }; settings.MakeReadOnly(); var p0 = new TestPokemonCollection(1); p0[0] = new TestPokemon(settings, PBESpecies.Hariyama, 0, 100, PBEMove.BellyDrum) { Ability = PBEAbility.Contrary }; var p1 = new TestPokemonCollection(1); p1[0] = new TestPokemon(settings, PBESpecies.Magikarp, 0, 100, PBEMove.Splash); var battle = PBEBattle.CreateTrainerBattle(PBEBattleFormat.Single, settings, new PBETrainerInfo(p0, "Trainer 0", false), new PBETrainerInfo(p1, "Trainer 1", false)); battle.OnNewEvent += PBEBattle.ConsoleBattleEventHandler; PBETrainer t0 = battle.Trainers[0]; PBETrainer t1 = battle.Trainers[1]; PBEBattlePokemon hariyama = t0.Party[0]; PBEBattlePokemon magikarp = t1.Party[0]; hariyama.AttackChange = settings.MaxStatChange; battle.Begin(); #endregion #region Use and check Assert.True(t0.SelectActionsIfValid(out _, new PBETurnAction(hariyama, PBEMove.BellyDrum, PBETurnTarget.AllyCenter))); Assert.True(t1.SelectActionsIfValid(out _, new PBETurnAction(magikarp, PBEMove.Splash, PBETurnTarget.AllyCenter))); battle.RunTurn(); if (settings.BugFix) { Assert.True(!battle.VerifyMoveResultHappened(hariyama, hariyama, PBEResult.InvalidConditions) && hariyama.AttackChange == -settings.MaxStatChange); // Stat minimized because of Contrary } else { Assert.True(battle.VerifyMoveResultHappened(hariyama, hariyama, PBEResult.InvalidConditions) && hariyama.AttackChange == settings.MaxStatChange); // Buggy } #endregion #region Cleanup battle.OnNewEvent -= PBEBattle.ConsoleBattleEventHandler; #endregion } }
412
0.761012
1
0.761012
game-dev
MEDIA
0.881098
game-dev,testing-qa
0.562483
1
0.562483
CafeFPS/r5_flowstate
9,392
vscripts/mp/_score.nut
untyped global function Score_Init global function AddPlayerScore global function AddCallback_OnPlayerScored global function AddCallback_Score_OnPlayerKilled global function ScoreEvent_PlayerKilled global function ScoreEvent_TitanDoomed global function ScoreEvent_TitanKilled global function ScoreEvent_NPCKilled global function ScoreEvent_SetEarnMeterValues global function ScoreEvent_SetupEarnMeterValuesForMixedModes global function IsPlaylistAllowedForDefaultKillNotifications global function PreScoreEventUpdateStats global function PostScoreEventUpdateStats //========================================================= // _score.nut // Handles scoring for MP. // // Interface: // - ScoreEvent_*(); called from various places in different scripts to award score to players //========================================================= struct { bool firstStrikeDone = false bool victoryKillEnabled = false bool firstStrikeGiven = false array<void functionref( entity, ScoreEvent )> onPlayerScoredCallbacks table< string, void functionref( entity, entity, var ) > onPlayerKilledCallbacks } file void function Score_Init() { } void function AddCallback_OnPlayerScored( void functionref( entity, ScoreEvent ) callbackFunc ) { file.onPlayerScoredCallbacks.append( callbackFunc ) } void function AddPlayerScore( entity targetPlayer, string scoreEventName, entity associatedEnt = null, string noideawhatthisis = "", int ownValueOverride = -1 ) { if ( !IsValid_ThisFrame( targetPlayer ) || !targetPlayer.IsPlayer() ) return if ( !targetPlayer.hasConnected || targetPlayer.GetTeam() == TEAM_SPECTATOR ) return ScoreEvent event = GetScoreEvent( scoreEventName ) if ( !event.enabled ) return var associatedHandle = 0 if ( associatedEnt != null ) associatedHandle = associatedEnt.GetEncodedEHandle() float scale = targetPlayer.IsTitan() ? event.coreMeterScalar : 1.0 float earnValue = event.earnMeterEarnValue * scale float ownValue = event.earnMeterOwnValue * scale if( scoreEventName == "Sur_DownedPilot" ) ownValue = GetTotalDamageTakenByPlayer( associatedEnt, targetPlayer ) if ( Playlist() == ePlaylists.fs_scenarios && ownValueOverride != -1 || Playlist() == ePlaylists.fs_scenarios && ownValueOverride == -1 && scoreEventName == "FS_Scenarios_PenaltyRing" || Gamemode() == eGamemodes.fs_snd && ownValueOverride != -1 ) //point value is unused in r5, gonna use own value for scenarios. Cafe ownValue = float( ownValueOverride ) //PlayerEarnMeter_AddEarnedAndOwned( targetPlayer, earnValue * scale, ownValue * scale ) Remote_CallFunction_NonReplay( targetPlayer, "ServerCallback_ScoreEvent", event.eventId, event.pointValue, event.displayType, associatedHandle, ownValue, earnValue ) if ( event.displayType & eEventDisplayType.CALLINGCARD ) // callingcardevents are shown to all players { foreach ( entity player in GetPlayerArray() ) { if ( player == targetPlayer ) // targetplayer already gets this in the scorevent callback continue //Remote_CallFunction_NonReplay( player, "ServerCallback_CallingCardEvent", event.eventId, associatedHandle ) } } if ( ScoreEvent_HasConversation( event ) ) { printt( FUNC_NAME(), "conversation:", event.conversation, "player:", targetPlayer.GetPlayerName(), "delay:", event.conversationDelay ) // todo: reimplement conversations //thread Delayed_PlayConversationToPlayer( event.conversation, targetPlayer, event.conversationDelay ) } } bool function IsPlaylistAllowedForDefaultKillNotifications() { switch( Playlist() ) { case ePlaylists.fs_scenarios: return false } switch( Gamemode() ) { case eGamemodes.fs_snd: return false } return true } void function AddCallback_Score_OnPlayerKilled( string gamemode, void functionref( entity, entity, var ) callbackFunc ) { file.onPlayerKilledCallbacks[gamemode] <- callbackFunc } void function PreScoreEventUpdateStats( entity attacker, entity victim ) //This is run before the friendly fire team check in PlayerOrNPCKilled { if ( !GamePlayingOrSuddenDeath() ) return entity killer = attacker if ( Bleedout_IsBleedingOut( victim ) ) { killer = Bleedout_GetBleedoutAttacker( victim ) if ( !IsValid( killer ) || !killer.IsPlayer() ) killer = attacker } if ( victim.IsPlayer() ) { victim.p.numberOfDeaths++ victim.p.numberOfDeathsSinceLastKill++ victim.p.playerOrTitanKillsSinceLastDeath = 0 victim.p.lastKiller = killer victim.p.seekingRevenge = true if ( killer.IsPlayer() ) { if ( !( victim in killer.p.playerKillStreaks ) ) killer.p.playerKillStreaks[ victim ] <- 0 killer.p.playerKillStreaks[ victim ]++ for ( int i = killer.p.recentPlayerKilledTimes.len() - 1; i >= 0; i-- ) { if ( killer.p.recentPlayerKilledTimes[ i ] < ( Time() - CASCADINGKILL_REQUIREMENT_TIME ) ) killer.p.recentPlayerKilledTimes.remove( i ) } killer.p.recentPlayerKilledTimes.append( Time() ) } } if ( killer.IsPlayer() ) { killer.p.numberOfDeathsSinceLastKill = 0 if ( IsAlive( killer ) ) { if ( ShouldIncrementPlayerOrTitanKillsSinceLastDeath( killer, victim ) ) { if ( victim.IsPlayer() && victim.IsTitan() ) killer.p.playerOrTitanKillsSinceLastDeath+= 2 //Count as 2 kills for kill spree when klling a player titan else killer.p.playerOrTitanKillsSinceLastDeath++ } } for ( int i = killer.p.recentAllKilledTimes.len() - 1; i >= 0; i-- ) { if ( killer.p.recentAllKilledTimes[ i ] < Time() - CASCADINGKILL_REQUIREMENT_TIME ) killer.p.recentAllKilledTimes.remove( i ) } killer.p.recentAllKilledTimes.append( Time() ) } } bool function ShouldIncrementPlayerOrTitanKillsSinceLastDeath( entity attackerPlayer, entity victim ) { if ( victim.IsPlayer() ) return true if ( victim.IsTitan() && victim.GetTeam() != attackerPlayer.GetTeam() ) //NPC titans count for kill spree. The team check is necessary since ejecting from your own undamaged Titan will make it count as you killing the Titan! return true return false } void function PostScoreEventUpdateStats( entity attacker, entity victim ) //This is run before the friendly fire team check in PlayerOrNPCKilled { if ( !GamePlayingOrSuddenDeath() ) return if ( victim.IsPlayer() ) { if ( attacker in victim.p.playerKillStreaks ) delete victim.p.playerKillStreaks[ attacker ] } if ( attacker.IsPlayer() ) { if ( victim.IsPlayer() ) //Updating attacker killed times for CASCADINGKILL_REQUIREMENT_TIME checks to be valid. { for ( int i = 0; i < attacker.p.recentPlayerKilledTimes.len(); i++ ) { attacker.p.recentPlayerKilledTimes[ i ] = Time() } } attacker.p.seekingRevenge = false } } void function ScoreEvent_PlayerKilled( entity victim, entity attacker, var damageInfo, bool downed = false) { if( is1v1EnabledAndAllowed() ) { int sourceId = DamageInfo_GetDamageSourceIdentifier( damageInfo ) if ( sourceId == eDamageSourceId.damagedef_suicide ) return } if( isScenariosMode() || Gamemode() == eGamemodes.fs_snd ) return if ( downed && GetGameState() >= eGameState.Playing) AddPlayerScore( attacker, "Sur_DownedPilot", victim ) else if( !downed && GetGameState() >= eGameState.Playing ) AddPlayerScore( attacker, "EliminatePilot", victim ) else if( !downed && GetGameState() <= eGameState.Playing ) AddPlayerScore( attacker, "KillPilot", victim ) } void function ScoreEvent_TitanDoomed( entity titan, entity attacker, var damageInfo ) { // will this handle npc titans with no owners well? i have literally no idea if ( titan.IsNPC() ) AddPlayerScore( attacker, "DoomAutoTitan", titan ) else AddPlayerScore( attacker, "DoomTitan", titan ) } void function ScoreEvent_TitanKilled( entity victim, entity attacker, var damageInfo ) { // will this handle npc titans with no owners well? i have literally no idea if ( attacker.IsTitan() ) AddPlayerScore( attacker, "TitanKillTitan", victim.GetTitanSoul().GetOwner() ) else AddPlayerScore( attacker, "KillTitan", victim.GetTitanSoul().GetOwner() ) } void function ScoreEvent_NPCKilled( entity victim, entity attacker, var damageInfo ) { #if HAS_NPC_SCORE_EVENTS AddPlayerScore( attacker, ScoreEventForNPCKilled( victim, damageInfo ), victim ) #endif } void function ScoreEvent_SetEarnMeterValues( string eventName, float earned, float owned, float coreScale = 1.0 ) { ScoreEvent event = GetScoreEvent( eventName ) event.earnMeterEarnValue = earned event.earnMeterOwnValue = owned event.coreMeterScalar = coreScale } void function ScoreEvent_SetupEarnMeterValuesForMixedModes() // mixed modes in this case means modes with both pilots and titans { // todo needs earn/overdrive values // player-controlled stuff ScoreEvent_SetEarnMeterValues( "KillPilot", 0.0, 0.05 ) ScoreEvent_SetEarnMeterValues( "KillTitan", 0.0, 0.15 ) ScoreEvent_SetEarnMeterValues( "TitanKillTitan", 0.0, 0.0 ) // unsure ScoreEvent_SetEarnMeterValues( "PilotBatteryStolen", 0.0, 0.35 ) // ai ScoreEvent_SetEarnMeterValues( "KillGrunt", 0.0, 0.02, 0.5 ) ScoreEvent_SetEarnMeterValues( "KillSpectre", 0.0, 0.02, 0.5 ) ScoreEvent_SetEarnMeterValues( "LeechSpectre", 0.0, 0.02 ) ScoreEvent_SetEarnMeterValues( "KillStalker", 0.0, 0.02, 0.5 ) ScoreEvent_SetEarnMeterValues( "KillSuperSpectre", 0.0, 0.1, 0.5 ) } void function ScoreEvent_SetupEarnMeterValuesForTitanModes() { // todo needs earn/overdrive values }
412
0.939498
1
0.939498
game-dev
MEDIA
0.957726
game-dev
0.8773
1
0.8773
AionGermany/aion-germany
2,406
AL-Game-5.8/data/scripts/system/handlers/ai/BombAi2.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package ai; import com.aionemu.gameserver.ai2.AI2Actions; import com.aionemu.gameserver.ai2.AIName; import com.aionemu.gameserver.ai2.poll.AIAnswer; import com.aionemu.gameserver.ai2.poll.AIAnswers; import com.aionemu.gameserver.ai2.poll.AIQuestion; import com.aionemu.gameserver.dataholders.DataManager; import com.aionemu.gameserver.model.ai.BombTemplate; import com.aionemu.gameserver.utils.ThreadPoolManager; /** * @author xTz */ @AIName("bomb") public class BombAi2 extends AggressiveNpcAI2 { private BombTemplate template; @Override protected void handleSpawned() { template = DataManager.AI_DATA.getAiTemplate().get(getNpcId()).getBombs().getBombTemplate(); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { doUseSkill(); } }, 2000); } private void doUseSkill() { ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { useSkill(template.getSkillId()); } }, template.getCd()); } @Override protected AIAnswer pollInstance(AIQuestion question) { switch (question) { case SHOULD_DECAY: return AIAnswers.NEGATIVE; case SHOULD_RESPAWN: return AIAnswers.NEGATIVE; case SHOULD_REWARD: return AIAnswers.NEGATIVE; default: return null; } } private void useSkill(int skill) { AI2Actions.targetSelf(this); AI2Actions.useSkill(this, skill); int duration = DataManager.SKILL_DATA.getSkillTemplate(skill).getDuration(); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { AI2Actions.deleteOwner(BombAi2.this); } }, duration != 0 ? duration + 4000 : 0); } }
412
0.765546
1
0.765546
game-dev
MEDIA
0.946125
game-dev
0.535612
1
0.535612
dofera/dofedex
1,275
loader/dofus/graphics/gapi/ui/waypoints/WaypointsItem.as
class dofus.graphics.gapi.ui.waypoints.WaypointsItem extends ank.gapi.core.UIBasicComponent { function WaypointsItem() { super(); } function __set__list(var2) { this._mcList = var2; return this.__get__list(); } function setValue(var2, var3, var4) { if(var2) { this._oItem = var4; this._lblCost.text = var4.cost != 0?var4.cost + "k":"-"; this._lblCoords.text = var4.coordinates; this._lblName.text = var4.name; this._mcRespawn._visible = var4.isRespawn; this._mcCurrent._visible = var4.isCurrent; this._btnLocate._visible = true; } else if(this._lblCost.text != undefined) { this._lblCost.text = ""; this._lblCoords.text = ""; this._lblName.text = ""; this._mcRespawn._visible = false; this._mcCurrent._visible = false; this._btnLocate._visible = false; } } function init() { super.init(false); this._mcRespawn._visible = false; this._mcCurrent._visible = false; this._btnLocate._visible = false; } function createChildren() { this.addToQueue({object:this,method:this.addListeners}); } function addListeners() { this._btnLocate.addEventListener("click",this); } function click(var2) { this._mcList.gapi.loadUIAutoHideComponent("MapExplorer","MapExplorer",{mapID:this._oItem.id}); } }
412
0.704536
1
0.704536
game-dev
MEDIA
0.884441
game-dev
0.895476
1
0.895476
Planshit/ProjectEvent
6,838
src/ProjectEvent.UI/Controls/Action/Builders/ActionBuilder.cs
using ProjectEvent.Core.Action.Models; using ProjectEvent.UI.Models.DataModels; using ProjectEvent.UI.Types; using System; using System.Collections.Generic; using System.Text; namespace ProjectEvent.UI.Controls.Action.Builders { public class ActionBuilder { public static IActionBuilder BuilderByActionItem(ActionItemModel action) { IActionBuilder builder = null; switch (action.ActionType) { case ActionType.WriteFile: builder = new WriteFileActionBuilder(); break; case ActionType.IF: builder = new IFActionActionBuilder(); break; case ActionType.HttpRequest: builder = new HttpRequestActionBuilder(); break; case ActionType.StartProcess: builder = new StartProcessActionBuilder(); break; case ActionType.Shutdown: builder = new ShutdownActionBuilder(); break; case ActionType.OpenURL: builder = new OpenURLActionBuilder(); break; case ActionType.Snipping: builder = new SnippingActionBuilder(); break; case ActionType.DeleteFile: builder = new DeleteFileActionBuilder(); break; case ActionType.SoundPlay: builder = new SoundPlayActionBuilder(); break; case ActionType.GetIPAddress: builder = new GetIPAddressActionBuilder(); break; case ActionType.Keyboard: builder = new KeyboardActionBuilder(); break; case ActionType.SystemNotification: builder = new SystemNotificationActionBuilder(); break; case ActionType.DownloadFile: builder = new DownloadFileActionBuilder(); break; case ActionType.Dialog: builder = new DialogActionBuilder(); break; case ActionType.Delay: builder = new DelayActionBuilder(); break; case ActionType.Loops: builder = new LoopsActionBuilder(); break; case ActionType.KillProcess: builder = new KillProcessActionBuilder(); break; case ActionType.SetDeviceVolume: builder = new SetDeviceVolumeActionBuilder(); break; case ActionType.Regex: builder = new RegexActionBuilder(); break; case ActionType.ReadFile: builder = new ReadFileActionBuilder(); break; case ActionType.JsonDeserialize: builder = new JsonDeserializeActionBuilder(); break; } if (builder != null) { builder.ImportActionItem(action); } return builder; } public static IActionBuilder BuilderByAction(ActionModel action) { IActionBuilder builder = null; switch (action.Action) { case Core.Action.Types.ActionType.WriteFile: builder = new WriteFileActionBuilder(); break; case Core.Action.Types.ActionType.IF: builder = new IFActionActionBuilder(); break; case Core.Action.Types.ActionType.HttpRequest: builder = new HttpRequestActionBuilder(); break; case Core.Action.Types.ActionType.StartProcess: builder = new StartProcessActionBuilder(); break; case Core.Action.Types.ActionType.Shutdown: builder = new ShutdownActionBuilder(); break; case Core.Action.Types.ActionType.OpenURL: builder = new OpenURLActionBuilder(); break; case Core.Action.Types.ActionType.Snipping: builder = new SnippingActionBuilder(); break; case Core.Action.Types.ActionType.DeleteFile: builder = new DeleteFileActionBuilder(); break; case Core.Action.Types.ActionType.SoundPlay: builder = new SoundPlayActionBuilder(); break; case Core.Action.Types.ActionType.GetIPAddress: builder = new GetIPAddressActionBuilder(); break; case Core.Action.Types.ActionType.Keyboard: builder = new KeyboardActionBuilder(); break; case Core.Action.Types.ActionType.SystemNotification: builder = new SystemNotificationActionBuilder(); break; case Core.Action.Types.ActionType.DownloadFile: builder = new DownloadFileActionBuilder(); break; case Core.Action.Types.ActionType.Dialog: builder = new DialogActionBuilder(); break; case Core.Action.Types.ActionType.Delay: builder = new DelayActionBuilder(); break; case Core.Action.Types.ActionType.Loops: builder = new LoopsActionBuilder(); break; case Core.Action.Types.ActionType.KillProcess: builder = new KillProcessActionBuilder(); break; case Core.Action.Types.ActionType.SetDeviceVolume: builder = new SetDeviceVolumeActionBuilder(); break; case Core.Action.Types.ActionType.Regex: builder = new RegexActionBuilder(); break; case Core.Action.Types.ActionType.ReadFile: builder = new ReadFileActionBuilder(); break; case Core.Action.Types.ActionType.JsonDeserialize: builder = new JsonDeserializeActionBuilder(); break; } if (builder != null) { builder.ImportAction(action); } return builder; } } }
412
0.734761
1
0.734761
game-dev
MEDIA
0.42983
game-dev
0.726777
1
0.726777
Fluorohydride/ygopro-scripts
1,384
c81791932.lua
--スネーク・ホイッスル function c81791932.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_DESTROYED) e1:SetCondition(c81791932.condition) e1:SetTarget(c81791932.target) e1:SetOperation(c81791932.activate) c:RegisterEffect(e1) end function c81791932.cfilter(c,tp) return c:IsRace(RACE_REPTILE) and c:IsPreviousPosition(POS_FACEUP) and c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_MZONE) end function c81791932.condition(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c81791932.cfilter,1,nil,tp) end function c81791932.filter(c,e,tp) return c:IsLevelBelow(4) and c:IsRace(RACE_REPTILE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c81791932.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c81791932.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c81791932.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c81791932.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) local tc=g:GetFirst() if tc then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
412
0.942037
1
0.942037
game-dev
MEDIA
0.965797
game-dev
0.966431
1
0.966431
soedinglab/MMseqs2
4,886
src/test/TestDBReaderZstd.cpp
#include <iostream> #include <list> #include <algorithm> #include <math.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include "Clustering.h" #include "DBReader.h" #include "DBWriter.h" #include "Parameters.h" const char* binary_name = "test_dbreader_zlib"; //static off_t fsize_orDie(const char *filename) //{ // struct stat st; // if (stat(filename, &st) == 0) return st.st_size; // /* error */ // perror(filename); // exit(1); //} // //static FILE* fopen_orDie(const char *filename, const char *instruction) //{ // FILE* const inFile = fopen(filename, instruction); // if (inFile) return inFile; // /* error */ // perror(filename); // exit(2); //} // //static void* malloc_orDie(size_t size) //{ // void* const buff = malloc(size); // if (buff) return buff; // /* error */ // perror(NULL); // exit(3); //} //static void* loadFile_orDie(const char* fileName, size_t* size) //{ // off_t const fileSize = fsize_orDie(fileName); // size_t const buffSize = (size_t)fileSize; // if ((off_t)buffSize < fileSize) { /* narrowcast overflow */ // fprintf(stderr, "%s : filesize too large \n", fileName); // exit(4); // } // FILE* const inFile = fopen_orDie(fileName, "rb"); // void* const buffer = malloc_orDie(buffSize); // size_t const readSize = fread(buffer, 1, buffSize, inFile); // if (readSize != (size_t)buffSize) { // fprintf(stderr, "fread: %s : %s \n", fileName, strerror(errno)); // exit(5); // } // fclose(inFile); /* can't fail, read only */ // *size = buffSize; // return buffer; //} // // //static void saveFile_orDie(const char* fileName, const void* buff, size_t buffSize) //{ // FILE* const oFile = fopen_orDie(fileName, "wb"); // size_t const wSize = fwrite(buff, 1, buffSize, oFile); // if (wSize != (size_t)buffSize) { // fprintf(stderr, "fwrite: %s : %s \n", fileName, strerror(errno)); // exit(6); // } // if (fclose(oFile)) { // perror(fileName); // exit(7); // } //} //static void compress_orDie(const char* fname, const char* oname) { // size_t fSize; // void* const fBuff = loadFile_orDie(fname, &fSize); // size_t const cBuffSize = ZSTD_compressBound(fSize); // void* const cBuff = malloc_orDie(cBuffSize); // // size_t const cSize = ZSTD_compress(cBuff, cBuffSize, fBuff, fSize, 1); // if (ZSTD_isError(cSize)) { // fprintf(stderr, "error compressing %s : %s \n", fname, ZSTD_getErrorName(cSize)); // exit(8); // } // // saveFile_orDie(oname, cBuff, cSize); // // /* success */ // printf("%25s : %6u -> %7u - %s \n", fname, (unsigned)fSize, (unsigned)cSize, oname); // // free(fBuff); // free(cBuff); //} // // //static char* createOutFilename_orDie(const char* filename) { // size_t const inL = strlen(filename); // size_t const outL = inL + 5; // void* const outSpace = malloc_orDie(outL); // memset(outSpace, 0, outL); // strcat((char*)outSpace, filename); // strcat((char*)outSpace, ".zst"); // return (char*)outSpace; //} int main (int, const char**) { DBWriter writer("dataLinear", "dataLinear.index", 1, Parameters::WRITER_COMPRESSED_MODE, Parameters::DBTYPE_NUCLEOTIDES); writer.open(); const char * data = "CTGGCGAAACCCAGACCGGTAAGCTTTTCCGTATGCGCGGTAAAGGCGTCAAGTCTGTCC" "GCGGTGGCGCACAGGGTGATTTGCTGTGCCGCGTTGTCGTCGAAACACCGGTAGGCCTGA" "ACGAGAAGCAGAAACAGCTGCTGCAAGAGCTGCAAGAAAGCTTCGGTGGCCCAACCGGTG" "AGCACAACAGCCCGCGCTCAAAGAGCTTCTTTGATGGTGTGAAGAAGTTTTTTGACGACC" "TGACCCGCTAACCTCCCCAAAAGCCTGCCCGTGGGCAGGCCTGGGTAAAAATAGGGTGCG" "TTGAAGATATGCGAGCACCTGTAAAGTGGCGGGGATCACTCCCCGCCGTTGCTCTTACTC" "GGATTCGTAAGCCGTGAAAACAGCAACCTCCGTCTGGCCAGTTCGGGTGTGAACCTCACA" "GAGGTCTTTTCTCGTTACCAGCGCCGCCACTACGGCGGTGATACAGATGACGATCAGGGC" "GACAATCATCGCCTTATGCTGCTTCATTGCTCTCTTCTCCTTGACCTTACGGTCAGTAAG" "AGGCACTCTACATGTGTTCAGCATATAGGGGGCCTCGGGTTGATGGTAAAATATCACTCG" "GGGCTTTTCTCTATCTGCCGTTCAGCTAATGCCTGAGACAGACAGCCTCAAGCACCCGCC" "GCTATTATATCGCTCTCTTTAACCCATTCTGTTTTATCGATTCTAATCCTGAAGACGCCT" "CGCATTTTTATGGCGTAATTTTTTAATGATTTAATTATTTAACTTTAATTTATCTCTTCA"; writer.writeData((char*)data,strlen(data), 1,0); writer.close(); DBReader<unsigned int> reader("dataLinear", "dataLinear.index", 1, 0); reader.open(0); reader.readMmapedDataInMemory(); reader.printMagicNumber(); std::cout << reader.getSize() << std::endl; for(size_t i = 0; i < reader.getSize(); i++){ std::cout << reader.getSeqLen(i) << std::endl; std::cout << reader.getData(i, 0) << std::endl; } reader.close(); }
412
0.531684
1
0.531684
game-dev
MEDIA
0.4369
game-dev
0.643852
1
0.643852
shiversoftdev/t8-src
1,869
script_1edaf4333ed0bece.gsc
// Decompiled by Serious. Credits to Scoba for his original tool, Cerberus, which I heavily upgraded to support remaining features, other games, and other platforms. #using scripts\core_common\util_shared.csc; #using scripts\core_common\clientfield_shared.csc; #namespace namespace_6036de69; /* Name: init Namespace: namespace_6036de69 Checksum: 0xB04C3281 Offset: 0x130 Size: 0x144 Parameters: 0 Flags: Linked */ function init() { clientfield::register("scriptmover", "gear_box_spark", 24000, 1, "int", &gear_box_spark_fx, 0, 0); clientfield::register("scriptmover", "flinger_impact_wood", 24000, 1, "int", &flinger_impact_wood_fx, 0, 0); clientfield::register("clientuimodel", "ZMInventoryPersonal.heat_pack", 1, 1, "int", undefined, 0, 0); level._effect[#"hash_5bea6497d336bbf"] = #"hash_299249c1ff22e1c2"; level._effect[#"flinger_impact_wood"] = #"hash_7677e82b27eada6f"; forcestreamxmodel("p8_zm_ora_crate_wood_01_tall_open_lid_dmg"); } /* Name: gear_box_spark_fx Namespace: namespace_6036de69 Checksum: 0x40270E23 Offset: 0x280 Size: 0xBE Parameters: 7 Flags: Linked */ function gear_box_spark_fx(localclientnum, oldval, newval, bnewent, binitialsnap, fieldname, bwastimejump) { if(newval) { self.var_91180673 = util::playfxontag(localclientnum, level._effect[#"hash_5bea6497d336bbf"], self, "tag_generator"); } else if(isdefined(self.var_91180673)) { stopfx(localclientnum, self.var_91180673); self.var_91180673 = undefined; } } /* Name: flinger_impact_wood_fx Namespace: namespace_6036de69 Checksum: 0xCCFE278C Offset: 0x348 Size: 0x82 Parameters: 7 Flags: Linked */ function flinger_impact_wood_fx(localclientnum, oldval, newval, bnewent, binitialsnap, fieldname, bwastimejump) { if(newval) { self.var_91180673 = util::playfxontag(localclientnum, level._effect[#"flinger_impact_wood"], self, "tag_origin"); } }
412
0.794105
1
0.794105
game-dev
MEDIA
0.809533
game-dev
0.730107
1
0.730107
m969/AOGame
2,459
AOClient/Unity/Assets/ThirdParty/FairyGUI/Scripts/Tween/TweenPropType.cs
namespace FairyGUI { /// <summary> /// /// </summary> public enum TweenPropType { None, X, Y, Z, XY, Position, Width, Height, Size, ScaleX, ScaleY, Scale, Rotation, RotationX, RotationY, Alpha, Progress } internal class TweenPropTypeUtils { internal static void SetProps(object target, TweenPropType propType, TweenValue value) { GObject g = target as GObject; if (g == null) return; switch (propType) { case TweenPropType.X: g.x = value.x; break; case TweenPropType.Y: g.y = value.x; break; case TweenPropType.Z: g.z = value.x; break; case TweenPropType.XY: g.xy = value.vec2; break; case TweenPropType.Position: g.position = value.vec3; break; case TweenPropType.Width: g.width = value.x; break; case TweenPropType.Height: g.height = value.x; break; case TweenPropType.Size: g.size = value.vec2; break; case TweenPropType.ScaleX: g.scaleX = value.x; break; case TweenPropType.ScaleY: g.scaleY = value.x; break; case TweenPropType.Scale: g.scale = value.vec2; break; case TweenPropType.Rotation: g.rotation = value.x; break; case TweenPropType.RotationX: g.rotationX = value.x; break; case TweenPropType.RotationY: g.rotationY = value.x; break; case TweenPropType.Alpha: g.alpha = value.x; break; case TweenPropType.Progress: g.asProgress.Update(value.d); break; } } } }
412
0.708998
1
0.708998
game-dev
MEDIA
0.446677
game-dev
0.978549
1
0.978549
EcsRx/EcsR3.Unity
1,426
src/Assets/Plugins/Zenject/Source/Editor/Editors/ProjectContextEditor.cs
#if !ODIN_INSPECTOR using UnityEditor; namespace Zenject { [CustomEditor(typeof(ProjectContext))] [NoReflectionBaking] public class ProjectContextEditor : ContextEditor { SerializedProperty _settingsProperty; SerializedProperty _editorReflectionBakingCoverageModeProperty; SerializedProperty _buildsReflectionBakingCoverageModeProperty; SerializedProperty _parentNewObjectsUnderContextProperty; public override void OnEnable() { base.OnEnable(); _settingsProperty = serializedObject.FindProperty("_settings"); _editorReflectionBakingCoverageModeProperty = serializedObject.FindProperty("_editorReflectionBakingCoverageMode"); _buildsReflectionBakingCoverageModeProperty = serializedObject.FindProperty("_buildsReflectionBakingCoverageMode"); _parentNewObjectsUnderContextProperty = serializedObject.FindProperty("_parentNewObjectsUnderContext"); } protected override void OnGui() { base.OnGui(); EditorGUILayout.PropertyField(_settingsProperty, true); EditorGUILayout.PropertyField(_editorReflectionBakingCoverageModeProperty, true); EditorGUILayout.PropertyField(_buildsReflectionBakingCoverageModeProperty, true); EditorGUILayout.PropertyField(_parentNewObjectsUnderContextProperty); } } } #endif
412
0.774158
1
0.774158
game-dev
MEDIA
0.862138
game-dev
0.50353
1
0.50353
Nekogram/Nekogram
1,298
TMessagesProj/jni/voip/webrtc/base/containers/intrusive_heap.cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/containers/intrusive_heap.h" #include "base/logging.h" #include "base/memory/ptr_util.h" namespace base { //////////////////////////////////////////////////////////////////////////////// // HeapHandle // static HeapHandle HeapHandle::Invalid() { return HeapHandle(); } //////////////////////////////////////////////////////////////////////////////// // InternalHeapHandleStorage InternalHeapHandleStorage::InternalHeapHandleStorage() : handle_(new HeapHandle()) {} InternalHeapHandleStorage::InternalHeapHandleStorage( InternalHeapHandleStorage&& other) noexcept : handle_(std::move(other.handle_)) { DCHECK(intrusive_heap::IsInvalid(other.handle_)); } InternalHeapHandleStorage::~InternalHeapHandleStorage() = default; InternalHeapHandleStorage& InternalHeapHandleStorage::operator=( InternalHeapHandleStorage&& other) noexcept { handle_ = std::move(other.handle_); DCHECK(intrusive_heap::IsInvalid(other.handle_)); return *this; } void InternalHeapHandleStorage::swap( InternalHeapHandleStorage& other) noexcept { std::swap(handle_, other.handle_); } } // namespace base
412
0.713531
1
0.713531
game-dev
MEDIA
0.376746
game-dev
0.508498
1
0.508498
udacity/ud406
2,066
2.8.05-Exercise-MobileTouchTargets/core/src/com/udacity/gamedev/gigagal/entities/Enemy.java
package com.udacity.gamedev.gigagal.entities; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.TimeUtils; import com.udacity.gamedev.gigagal.util.Assets; import com.udacity.gamedev.gigagal.util.Constants; import com.udacity.gamedev.gigagal.util.Enums.Direction; import com.udacity.gamedev.gigagal.util.Utils; public class Enemy { final long startTime; final float bobOffset; private final Platform platform; public Vector2 position; public int health; private Direction direction; public Enemy(Platform platform) { this.platform = platform; direction = Direction.RIGHT; position = new Vector2(platform.left, platform.top + Constants.ENEMY_CENTER.y); startTime = TimeUtils.nanoTime(); health = Constants.ENEMY_HEALTH; bobOffset = MathUtils.random(); } public void update(float delta) { switch (direction) { case LEFT: position.x -= Constants.ENEMY_MOVEMENT_SPEED * delta; break; case RIGHT: position.x += Constants.ENEMY_MOVEMENT_SPEED * delta; } if (position.x < platform.left) { position.x = platform.left; direction = Direction.RIGHT; } else if (position.x > platform.right) { position.x = platform.right; direction = Direction.LEFT; } final float elapsedTime = Utils.secondsSince(startTime); final float bobMultiplier = 1 + MathUtils.sin(MathUtils.PI2 * (bobOffset + elapsedTime / Constants.ENEMY_BOB_PERIOD)); position.y = platform.top + Constants.ENEMY_CENTER.y + Constants.ENEMY_BOB_AMPLITUDE * bobMultiplier; } public void render(SpriteBatch batch) { final TextureRegion region = Assets.instance.enemyAssets.enemy; Utils.drawTextureRegion(batch, region, position, Constants.ENEMY_CENTER); } }
412
0.677039
1
0.677039
game-dev
MEDIA
0.977139
game-dev
0.967553
1
0.967553
defold/defold
3,548
external/bullet3d/package/bullet-2.77/src/BulletCollision/CollisionShapes/btConeShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btConeShape.h" btConeShape::btConeShape (btScalar radius,btScalar height): btConvexInternalShape (), m_radius (radius), m_height(height) { m_shapeType = CONE_SHAPE_PROXYTYPE; setConeUpIndex(1); btVector3 halfExtents; m_sinAngle = (m_radius / btSqrt(m_radius * m_radius + m_height * m_height)); } btConeShapeZ::btConeShapeZ (btScalar radius,btScalar height): btConeShape(radius,height) { setConeUpIndex(2); } btConeShapeX::btConeShapeX (btScalar radius,btScalar height): btConeShape(radius,height) { setConeUpIndex(0); } ///choose upAxis index void btConeShape::setConeUpIndex(int upIndex) { switch (upIndex) { case 0: m_coneIndices[0] = 1; m_coneIndices[1] = 0; m_coneIndices[2] = 2; break; case 1: m_coneIndices[0] = 0; m_coneIndices[1] = 1; m_coneIndices[2] = 2; break; case 2: m_coneIndices[0] = 0; m_coneIndices[1] = 2; m_coneIndices[2] = 1; break; default: btAssert(0); }; } btVector3 btConeShape::coneLocalSupport(const btVector3& v) const { btScalar halfHeight = m_height * btScalar(0.5); if (v[m_coneIndices[1]] > v.length() * m_sinAngle) { btVector3 tmp; tmp[m_coneIndices[0]] = btScalar(0.); tmp[m_coneIndices[1]] = halfHeight; tmp[m_coneIndices[2]] = btScalar(0.); return tmp; } else { btScalar s = btSqrt(v[m_coneIndices[0]] * v[m_coneIndices[0]] + v[m_coneIndices[2]] * v[m_coneIndices[2]]); if (s > SIMD_EPSILON) { btScalar d = m_radius / s; btVector3 tmp; tmp[m_coneIndices[0]] = v[m_coneIndices[0]] * d; tmp[m_coneIndices[1]] = -halfHeight; tmp[m_coneIndices[2]] = v[m_coneIndices[2]] * d; return tmp; } else { btVector3 tmp; tmp[m_coneIndices[0]] = btScalar(0.); tmp[m_coneIndices[1]] = -halfHeight; tmp[m_coneIndices[2]] = btScalar(0.); return tmp; } } } btVector3 btConeShape::localGetSupportingVertexWithoutMargin(const btVector3& vec) const { return coneLocalSupport(vec); } void btConeShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { for (int i=0;i<numVectors;i++) { const btVector3& vec = vectors[i]; supportVerticesOut[i] = coneLocalSupport(vec); } } btVector3 btConeShape::localGetSupportingVertex(const btVector3& vec) const { btVector3 supVertex = coneLocalSupport(vec); if ( getMargin()!=btScalar(0.) ) { btVector3 vecnorm = vec; if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) { vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.)); } vecnorm.normalize(); supVertex+= getMargin() * vecnorm; } return supVertex; }
412
0.941269
1
0.941269
game-dev
MEDIA
0.973142
game-dev
0.994415
1
0.994415
Tencent/puerts
13,259
unreal/Puerts/Source/JsEnv/Private/ContainerWrapper.h
/* * Tencent is pleased to support the open source community by making Puerts available. * Copyright (C) 2020 Tencent. All rights reserved. * Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may * be subject to their corresponding license terms. This file is subject to the terms and conditions defined in file 'LICENSE', * which is part of this source code package. */ #pragma once #include <memory> #include <vector> #include "CoreMinimal.h" #include "CoreUObject.h" #include "V8Utils.h" #include "ObjectMapper.h" #include "JSLogger.h" #include "NamespaceDef.h" PRAGMA_DISABLE_UNDEFINED_IDENTIFIER_WARNINGS #pragma warning(push, 0) #include "libplatform/libplatform.h" #include "v8.h" #pragma warning(pop) PRAGMA_ENABLE_UNDEFINED_IDENTIFIER_WARNINGS namespace PUERTS_NAMESPACE { class FPropertyTranslator; FORCEINLINE int32 GetSizeWithAlignment(PropertyMacro* InProperty) { return Align(InProperty->GetSize(), InProperty->GetMinAlignment()); } struct FScriptArrayEx { FScriptArray Data; #if ENGINE_MINOR_VERSION < 25 && ENGINE_MAJOR_VERSION < 5 TWeakObjectPtr<PropertyMacro> PropertyPtr; #else TWeakFieldPtr<PropertyMacro> PropertyPtr; #endif FORCEINLINE FScriptArrayEx(PropertyMacro* InProperty) { // UE_LOG(LogTemp, Warning, TEXT("FScriptArrayEx:%p"), this); PropertyPtr = InProperty; } FORCEINLINE ~FScriptArrayEx() { // UE_LOG(LogTemp, Warning, TEXT("~FScriptArrayEx:%p"), this); if (PropertyPtr.IsValid()) { Empty(&Data, PropertyPtr.Get()); } else { UE_LOG(Puerts, Error, TEXT("~FScriptArrayEx: Property is invalid")); } } FORCEINLINE static uint8* GetData(FScriptArray* ScriptArray, int32 ElementSize, int32 Index) { return static_cast<uint8*>(ScriptArray->GetData()) + Index * ElementSize; } FORCEINLINE static void Destruct(FScriptArray* ScriptArray, PropertyMacro* Property, int32 Index, int32 Count = 1) { const int32 ElementSize = GetSizeWithAlignment(Property); uint8* Dest = GetData(ScriptArray, ElementSize, Index); for (int32 i = 0; i < Count; ++i) { Property->DestroyValue(Dest); Dest += ElementSize; } } FORCEINLINE static void Empty(FScriptArray* ScriptArray, PropertyMacro* Property) { Destruct(ScriptArray, Property, 0, ScriptArray->Num()); #if ENGINE_MAJOR_VERSION > 4 ScriptArray->Empty(0, GetSizeWithAlignment(Property), __STDCPP_DEFAULT_NEW_ALIGNMENT__); #else ScriptArray->Empty(0, GetSizeWithAlignment(Property)); #endif } }; struct FScriptSetEx { FScriptSet Data; #if ENGINE_MINOR_VERSION < 25 && ENGINE_MAJOR_VERSION < 5 TWeakObjectPtr<PropertyMacro> PropertyPtr; #else TWeakFieldPtr<PropertyMacro> PropertyPtr; #endif FORCEINLINE FScriptSetEx(PropertyMacro* InProperty) { // UE_LOG(LogTemp, Warning, TEXT("FScriptSetEx:%p"), this); PropertyPtr = InProperty; } FORCEINLINE ~FScriptSetEx() { // UE_LOG(LogTemp, Warning, TEXT("~FScriptSetEx:%p"), this); if (PropertyPtr.IsValid()) { Empty(&Data, PropertyPtr.Get()); } else { UE_LOG(Puerts, Error, TEXT("~FScriptSetEx: Property is invalid")); } } FORCEINLINE static void Destruct(FScriptSet* ScriptSet, PropertyMacro* Property, int32 Index, int32 Count = 1) { auto SetLayout = ScriptSet->GetScriptLayout(Property->GetSize(), Property->GetMinAlignment()); for (int32 i = Index; i < Index + Count; ++i) { if (ScriptSet->IsValidIndex(i)) { void* Data = ScriptSet->GetData(i, SetLayout); Property->DestroyValue(Data); } } } FORCEINLINE static void Empty(FScriptSet* ScriptSet, PropertyMacro* Property) { auto SetLayout = FScriptSet::GetScriptLayout(Property->GetSize(), Property->GetMinAlignment()); Destruct(ScriptSet, Property, 0, ScriptSet->Num()); ScriptSet->Empty(0, SetLayout); } }; FORCEINLINE static int32 GetKeyOffset(const FScriptMapLayout& ScriptMapLayout) { #if ENGINE_MINOR_VERSION < 22 && ENGINE_MAJOR_VERSION < 5 return ScriptMapLayout.KeyOffset; #else return 0; #endif } struct FScriptMapEx { FScriptMap Data; #if ENGINE_MINOR_VERSION < 25 && ENGINE_MAJOR_VERSION < 5 TWeakObjectPtr<PropertyMacro> KeyPropertyPtr; TWeakObjectPtr<PropertyMacro> ValuePropertyPtr; #else TWeakFieldPtr<PropertyMacro> KeyPropertyPtr; TWeakFieldPtr<PropertyMacro> ValuePropertyPtr; #endif FORCEINLINE FScriptMapEx(PropertyMacro* InKeyProperty, PropertyMacro* InValueProperty) { // UE_LOG(LogTemp, Warning, TEXT("FScriptMapEx:%p"), this); KeyPropertyPtr = InKeyProperty; ValuePropertyPtr = InValueProperty; } FORCEINLINE ~FScriptMapEx() { // UE_LOG(LogTemp, Warning, TEXT("~FScriptMapEx:%p"), this); if (KeyPropertyPtr.IsValid() && ValuePropertyPtr.IsValid()) { Empty(&Data, KeyPropertyPtr.Get(), ValuePropertyPtr.Get()); } else { UE_LOG(Puerts, Error, TEXT("~FScriptMapEx: Property is invalid")); } } FORCEINLINE static FScriptMapLayout GetScriptLayout(const PropertyMacro* KeyProperty, const PropertyMacro* ValueProperty) { return FScriptMap::GetScriptLayout( KeyProperty->GetSize(), KeyProperty->GetMinAlignment(), ValueProperty->GetSize(), ValueProperty->GetMinAlignment()); } FORCEINLINE static void Destruct( FScriptMap* ScriptMap, PropertyMacro* KeyProperty, PropertyMacro* ValueProperty, int32 Index, int32 Count = 1) { int32 MaxIndex = ScriptMap->GetMaxIndex(); auto MapLayout = GetScriptLayout(KeyProperty, ValueProperty); for (int32 i = Index; i < Index + Count; ++i) { if (ScriptMap->IsValidIndex(i)) { uint8* Data = reinterpret_cast<uint8*>(ScriptMap->GetData(i, MapLayout)); void* Key = Data + GetKeyOffset(MapLayout); void* Value = Data + MapLayout.ValueOffset; KeyProperty->DestroyValue(Key); ValueProperty->DestroyValue(Value); } } } FORCEINLINE static void Empty(FScriptMap* ScriptMap, PropertyMacro* KeyProperty, PropertyMacro* ValueProperty) { auto MapLayout = GetScriptLayout(KeyProperty, ValueProperty); Destruct(ScriptMap, KeyProperty, ValueProperty, 0, ScriptMap->Num()); ScriptMap->Empty(0, MapLayout); } }; template <typename T> struct ContainerExTypeMapper; template <> struct ContainerExTypeMapper<FScriptArray> { using Type = FScriptArrayEx; }; template <> struct ContainerExTypeMapper<FScriptSet> { using Type = FScriptSetEx; }; template <> struct ContainerExTypeMapper<FScriptMap> { using Type = FScriptMapEx; }; template <typename T> class FContainerWrapper { public: static void OnGarbageCollectedWithFree(const v8::WeakCallbackInfo<void>& Data) { typedef typename ContainerExTypeMapper<T>::Type ET; ET* Container = static_cast<ET*>(DataTransfer::MakeAddressWithHighPartOfTwo(Data.GetInternalField(0), Data.GetInternalField(1))); FV8Utils::IsolateData<IObjectMapper>(Data.GetIsolate())->UnBindContainer(Container); delete Container; } static void OnGarbageCollected(const v8::WeakCallbackInfo<void>& Data) { T* Container = static_cast<T*>(DataTransfer::MakeAddressWithHighPartOfTwo(Data.GetInternalField(0), Data.GetInternalField(1))); FV8Utils::IsolateData<IObjectMapper>(Data.GetIsolate())->UnBindContainer(Container); } static void New(const v8::FunctionCallbackInfo<v8::Value>& Info) { v8::Isolate* Isolate = Info.GetIsolate(); FV8Utils::ThrowException(Isolate, "Container Constructor no support yet"); } // TODO - 用doxygen注释 // 参数:无 // 返回:容器内元素总数 static void Num(const v8::FunctionCallbackInfo<v8::Value>& Info) { v8::Isolate* Isolate = Info.GetIsolate(); v8::HandleScope HandleScope(Isolate); v8::Local<v8::Context> Context = Isolate->GetCurrentContext(); auto Self = FV8Utils::GetPointerFast<T>(Info.Holder()); Info.GetReturnValue().Set(Self->Num()); } }; class FScriptArrayWrapper : public FContainerWrapper<FScriptArray> { public: static v8::Local<v8::FunctionTemplate> ToFunctionTemplate(v8::Isolate* Isolate); private: // 参数:一到多个容器元素 // 返回:无 // 作用:追加新元素到容器 static void Add(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:索引 // 返回:元素(值类型,有内存拷贝) // 作用:获取索引对应的元素,如果索引越界则抛出异常 static void Get(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:索引 // 返回:元素(引用类型) // 作用:获取索引对应的元素,如果索引越界则抛出异常 static void GetRef(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数1:索引;参数2:元素 // 返回:无 // 作用:设置容器中索引对应的元素值,如果索引越界则抛出异常 static void Set(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:元素 // 返回:bool // 作用:查询容器是否包含该元素,若是则返回true,否则返回false static void Contains(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:元素 // 返回:索引 // 作用:返回容器中第一次出现该元素的索引,若元素不存在则返回INDEX_NONE(-1) static void FindIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:索引 // 返回:无 // 作用:移除索引对应的元素,被移除的位置之后的元素会自动前移,如果索引越界则抛出异常 static void RemoveAt(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:索引 // 返回:bool // 作用:如果参数是有效索引,返回true,否则返回false static void IsValidIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); // 参数:无 // 返回:无 // 作用:清空容器 static void Empty(const v8::FunctionCallbackInfo<v8::Value>& Info); FORCEINLINE static int32 AddUninitialized(FScriptArray* ScriptArray, int32 ElementSize, int32 Count = 1); FORCEINLINE static uint8* GetData(FScriptArray* ScriptArray, int32 ElementSize, int32 Index); FORCEINLINE static void Construct(FScriptArray* ScriptArray, FPropertyTranslator* Inner, int32 Index, int32 Count = 1); static int32 FindIndexInner(const v8::FunctionCallbackInfo<v8::Value>& Info); FORCEINLINE static void InternalGet(const v8::FunctionCallbackInfo<v8::Value>& Info, bool PassByPointer); }; class FScriptSetWrapper : public FContainerWrapper<FScriptSet> { public: static v8::Local<v8::FunctionTemplate> ToFunctionTemplate(v8::Isolate* Isolate); private: static void Add(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Get(const v8::FunctionCallbackInfo<v8::Value>& Info); static void GetRef(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Contains(const v8::FunctionCallbackInfo<v8::Value>& Info); static void FindIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); static void RemoveAt(const v8::FunctionCallbackInfo<v8::Value>& Info); static void GetMaxIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); static void IsValidIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Empty(const v8::FunctionCallbackInfo<v8::Value>& Info); FORCEINLINE static int32 FindIndexInner(const v8::FunctionCallbackInfo<v8::Value>& Info); FORCEINLINE static void InternalGet(const v8::FunctionCallbackInfo<v8::Value>& Info, bool PassByPointer); }; class FScriptMapWrapper : public FContainerWrapper<FScriptMap> { public: static v8::Local<v8::FunctionTemplate> ToFunctionTemplate(v8::Isolate* Isolate); private: static void Add(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Get(const v8::FunctionCallbackInfo<v8::Value>& Info); static void GetRef(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Set(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Remove(const v8::FunctionCallbackInfo<v8::Value>& Info); static void GetMaxIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); static void IsValidIndex(const v8::FunctionCallbackInfo<v8::Value>& Info); static void GetKey(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Empty(const v8::FunctionCallbackInfo<v8::Value>& Info); FORCEINLINE static FScriptMapLayout GetScriptLayout(const PropertyMacro* KeyProperty, const PropertyMacro* ValueProperty); FORCEINLINE static void InternalGet(const v8::FunctionCallbackInfo<v8::Value>& Info, bool PassByPointer); }; class FFixSizeArrayWrapper { public: static v8::Local<v8::FunctionTemplate> ToFunctionTemplate(v8::Isolate* Isolate); private: static void New(const v8::FunctionCallbackInfo<v8::Value>& Info) { } static void Num(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Get(const v8::FunctionCallbackInfo<v8::Value>& Info); static void GetRef(const v8::FunctionCallbackInfo<v8::Value>& Info); static void Set(const v8::FunctionCallbackInfo<v8::Value>& Info); FORCEINLINE static void InternalGet(const v8::FunctionCallbackInfo<v8::Value>& Info, bool PassByPointer); }; } // namespace PUERTS_NAMESPACE
412
0.933414
1
0.933414
game-dev
MEDIA
0.470874
game-dev
0.900681
1
0.900681
MCSLTeam/MCServerLauncher-Future
8,289
MCServerLauncher.WPF/View/Components/CreateInstance/QuiltLoaderSet.xaml.cs
using MCServerLauncher.WPF.Modules; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using static MCServerLauncher.WPF.Modules.Constants; namespace MCServerLauncher.WPF.View.Components.CreateInstance { /// <summary> /// QuiltLoaderSet.xaml 的交互逻辑 /// </summary> public partial class QuiltLoaderSet : ICreateInstanceStep { public QuiltLoaderSet() { InitializeComponent(); void initialHandler1(object sender, SelectionChangedEventArgs args) { if (!IsDisposed1) { SetValue(IsFinished1Property, !(MinecraftVersionComboBox.SelectedIndex == -1)); } } void initialHandler2(object sender, SelectionChangedEventArgs args) { if (!IsDisposed2) { SetValue(IsFinished2Property, !(QuiltVersionComboBox.SelectedIndex == -1)); } } MinecraftVersionComboBox.SelectionChanged += initialHandler1; QuiltVersionComboBox.SelectionChanged += initialHandler2; // As you can see, we have to trigger it manually VisualTreeHelper.InitStepState(MinecraftVersionComboBox); VisualTreeHelper.InitStepState(QuiltVersionComboBox); ToggleStableMinecraftVersionCheckBox.Checked += ToggleStableMinecraftVersion; ToggleStableMinecraftVersionCheckBox.Unchecked += ToggleStableMinecraftVersion; FetchMinecraftVersionsButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); FetchQuiltVersionButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); } #nullable enable private List<QuiltMinecraftVersion>? SupportedAllMinecraftVersions { get; set; } private List<string>? QuiltLoaderVersions { get; set; } private bool IsDisposed1 { get; set; } = false; private bool IsDisposed2 { get; set; } = false; ~QuiltLoaderSet() { IsDisposed1 = true; IsDisposed2 = true; } public static readonly DependencyProperty IsFinished1Property = DependencyProperty.Register( nameof(IsFinished1), typeof(bool), typeof(QuiltLoaderSet), new PropertyMetadata(false, OnStatus1Changed)); private static void OnStatus1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not QuiltLoaderSet control) return; if (e.NewValue is not bool status) return; control.StatusShow1.Visibility = status switch { true => Visibility.Visible, false => Visibility.Hidden, }; } public static readonly DependencyProperty IsFinished2Property = DependencyProperty.Register( nameof(IsFinished2), typeof(bool), typeof(QuiltLoaderSet), new PropertyMetadata(false, OnStatus2Changed)); private static void OnStatus2Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not QuiltLoaderSet control) return; if (e.NewValue is not bool status) return; control.StatusShow2.Visibility = status switch { true => Visibility.Visible, false => Visibility.Hidden, }; } public bool IsFinished1 { get => (bool)GetValue(IsFinished1Property); private set => SetValue(IsFinished1Property, value); } public bool IsFinished2 { get => (bool)GetValue(IsFinished2Property); private set => SetValue(IsFinished2Property, value); } public bool IsFinished { get => (bool)GetValue(IsFinished1Property) && (bool)GetValue(IsFinished2Property); //private set => SetValue(IsFinished1Property, value); } public CreateInstanceData ActualData => new() { Type = CreateInstanceDataType.Struct, Data = new MinecraftLoaderVersion { MCVersion = MinecraftVersionComboBox.SelectedItem!.ToString(), LoaderVersion = QuiltVersionComboBox.SelectedItem!.ToString(), } }; /// <summary> /// Determine the endpoint to fetch data. /// </summary> /// <returns>The correct endpoint.</returns> private string GetEndPoint() { return SettingsManager.Get?.InstanceCreation != null && SettingsManager.Get.InstanceCreation.UseMirrorForMinecraftQuiltInstall ? "https://bmclapi2.bangbang93.com/quilt-meta" : "https://meta.quiltmc.org"; } /// <summary> /// Fetch supported Minecraft versions. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void FetchMinecraftVersions(object sender, RoutedEventArgs e) { FetchMinecraftVersionsButton.IsEnabled = false; MinecraftVersionComboBox.IsEnabled = false; var response = await Network.SendGetRequest($"{GetEndPoint()}/v3/versions/game", true); var allSupportedVersionsList = JsonConvert.DeserializeObject<JToken>(await response.Content.ReadAsStringAsync()); SupportedAllMinecraftVersions = allSupportedVersionsList!.Select(mcVersion => new QuiltMinecraftVersion { MinecraftVersion = mcVersion.SelectToken("version")!.ToString(), IsStable = mcVersion.SelectToken("stable")!.ToObject<bool>() }).ToList(); ToggleStableMinecraftVersionCheckBox.RaiseEvent(new RoutedEventArgs(ToggleButton.CheckedEvent)); MinecraftVersionComboBox.IsEnabled = true; FetchMinecraftVersionsButton.IsEnabled = true; } /// <summary> /// Toggle stable/snapshot Minecraft versions. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ToggleStableMinecraftVersion(object sender, RoutedEventArgs e) { ToggleStableMinecraftVersionCheckBox.IsEnabled = false; MinecraftVersionComboBox.IsEnabled = false; if (SupportedAllMinecraftVersions != null) MinecraftVersionComboBox.ItemsSource = DownloadManager.SequenceMinecraftVersion( (ToggleStableMinecraftVersionCheckBox.IsChecked.GetValueOrDefault(true) ? SupportedAllMinecraftVersions.Where(mcVersion => mcVersion.IsStable).ToList() .Select(mcVersion => mcVersion.MinecraftVersion).ToList() : SupportedAllMinecraftVersions.Select(mcVersion => mcVersion.MinecraftVersion).ToList())! ); MinecraftVersionComboBox.IsEnabled = true; ToggleStableMinecraftVersionCheckBox.IsEnabled = true; } /// <summary> /// Fetch supported Quilt versions. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void FetchQuiltVersions(object sender, RoutedEventArgs e) { FetchQuiltVersionButton.IsEnabled = false; QuiltVersionComboBox.IsEnabled = false; var response = await Network.SendGetRequest($"{GetEndPoint()}/v3/versions/loader"); var apiData = JsonConvert.DeserializeObject<JToken>(await response.Content.ReadAsStringAsync()); QuiltLoaderVersions = apiData!.Select(version => version.SelectToken("version")!.ToString()).ToList(); QuiltVersionComboBox.ItemsSource = QuiltLoaderVersions; QuiltVersionComboBox.IsEnabled = true; FetchQuiltVersionButton.IsEnabled = true; } private class QuiltMinecraftVersion { public string? MinecraftVersion { get; set; } public bool IsStable { get; set; } } #nullable disable } }
412
0.787735
1
0.787735
game-dev
MEDIA
0.753158
game-dev
0.718031
1
0.718031
NeotokyoRebuild/neo
2,546
src/game/client/c_te_beamring.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "c_te_basebeam.h" #include "iviewrender_beams.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: BeamRing TE //----------------------------------------------------------------------------- class C_TEBeamRing : public C_TEBaseBeam { public: DECLARE_CLASS( C_TEBeamRing, C_TEBaseBeam ); DECLARE_CLIENTCLASS(); C_TEBeamRing( void ); virtual ~C_TEBeamRing( void ); virtual void PostDataUpdate( DataUpdateType_t updateType ); public: int m_nStartEntity; int m_nEndEntity; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBeamRing::C_TEBeamRing( void ) { m_nStartEntity = 0; m_nEndEntity = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_TEBeamRing::~C_TEBeamRing( void ) { } void TE_BeamRing( IRecipientFilter& filter, float delay, int start, int end, int modelindex, int haloindex, int startframe, int framerate, float life, float width, int spread, float amplitude, int r, int g, int b, int a, int speed, int flags ) { beams->CreateBeamRing( start, end, modelindex, haloindex, 0.0f, life, width, 0.1 * spread, 0.0f, amplitude, a, 0.1 * speed, startframe, 0.1 * framerate, r, g, b, flags ); } //----------------------------------------------------------------------------- // Purpose: // Input : bool - //----------------------------------------------------------------------------- void C_TEBeamRing::PostDataUpdate( DataUpdateType_t updateType ) { beams->CreateBeamRing( m_nStartEntity, m_nEndEntity, m_nModelIndex, m_nHaloIndex, 0.0f, m_fLife, m_fWidth, m_fEndWidth, m_nFadeLength, m_fAmplitude, a, 0.1 * m_nSpeed, m_nStartFrame, 0.1 * m_nFrameRate, r, g, b, m_nFlags ); } IMPLEMENT_CLIENTCLASS_EVENT_DT(C_TEBeamRing, DT_TEBeamRing, CTEBeamRing) RecvPropInt( RECVINFO(m_nStartEntity)), RecvPropInt( RECVINFO(m_nEndEntity)), END_RECV_TABLE()
412
0.671502
1
0.671502
game-dev
MEDIA
0.625126
game-dev
0.621467
1
0.621467
chauncygu/Safe-Reinforcement-Learning-Baselines
16,056
Safe-RL/Shield-Hybrid-Systems/tab-CCSynthesis/Blueprints/CC__PreShielded.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE nta PUBLIC '-//Uppaal Team//DTD Flat System 1.5//EN' 'http://www.it.uu.se/research/group/darts/uppaal/flat-1_5.dtd'> <nta> <declaration>/** Changes have been made to this model. - minVelocityFront changed from -10 to -8 - Code and guards have been added to shield the system. - The discrete simulation has been removed. Following is the original header: */ /** This case study has been published at "Correct System Design" Symposium in Honor of Ernst-Rüdiger Olderog on the Occasion of His 60th Birthday Oldenburg, Germany, September 8–9, 2015. The paper "Safe and Optimal Adaptive Cruise Control" by Kim Guldstrand Larsen, Marius Mikucionis, Jakob Haahr Taankvist. @incollection{cruise, year={2015}, isbn={978-3-319-23505-9}, booktitle={Correct System Design}, volume={9360}, series={Lecture Notes in Computer Science}, editor={Meyer, Roland and Platzer, André and Wehrheim, Heike}, doi={10.1007/978-3-319-23506-6_17}, title={Safe and Optimal Adaptive Cruise Control}, url={http://dx.doi.org/10.1007/978-3-319-23506-6_17}, publisher={Springer International Publishing}, author={Larsen, Kim Guldstrand and Miku\v{c}ionis, Marius and Taankvist, Jakob Haahr}, pages={260-277}, language={English} } */ // Place global declarations here. clock time; const int maxVelocityEgo = 20; const int maxVelocityFront = 20; const int minVelocityEgo = -10; /** This value has been changed from -10 to -8 */ const int minVelocityFront = -8; const int maxSensorDistance = 200; clock waitTimer; int[-2,2] accelerationEgo; broadcast chan chooseEgo; int[-2,2] accelerationFront; broadcast chan chooseFront; broadcast chan update; // Hybrid stuff hybrid clock rVelocityEgo; hybrid clock rVelocityFront; hybrid clock rDistance = 10.0; hybrid clock D; /** Added code for Shielding */ import "%ccshieldfile%" { int get_value(double v_ego, double v_front, double distance); }; typedef struct { bool backwards; bool neutral; bool forwards; } allowedActions; allowedActions intToActions(int bitarray) { allowedActions result = { (0 != (bitarray &amp; (1 &lt;&lt; 0))), (0 != (bitarray &amp; (1 &lt;&lt; 1))), (0 != (bitarray &amp; (1 &lt;&lt; 2))) }; return result; } double clamp(double x, double lower, double upper) { if (x &lt; lower) { return lower; } if (x &gt; upper) { return upper; } return x; } allowedActions getAllowedActions(double v_ego, double v_front, double distance) { // UPPAAL has a habit of estimating the hybrid clocks to be slightly outside the allowed range. // For example, it is possible to reach rVelocityFront = -8.0000034 // which is outside the bounds of the shield and therefore allows any action. double v_ego2 = clamp(v_ego, minVelocityEgo, maxVelocityEgo); double v_front2 = clamp(v_front, minVelocityFront - 1, maxVelocityFront + 1); // Bug: guards do not account for odd velocity returning from sensor range // Furthermore, the distance can exceed the sensor range by quite a bit // in the moment where Front disappears. // Only in the next time-step is it reduced to maxSensorDistance + 1. double distance2 = fmin(distance, maxSensorDistance + 1); int bitarray = get_value(v_ego2, v_front2, distance2); if (bitarray == 0) { // Since the barbaric method is an under-approximation of behaviour // Red areas may sometimes be entered. // Yes, this is extremely interesting and worth examining further. return intToActions(1 + 2 + 4); } return intToActions(bitarray); } int outOfBounds = 0; int noSafeActions = 0; int safetyViolations = 0; // Variant of getAllowedActions that mutate the state of some global variables. // Such functions are not allowed for initialization. allowedActions shieldingDebug(double v_ego, double v_front, double distance) { // UPPAAL has a habit of estimating the hybrid clocks to be slightly outside the allowed range. // For example, it is possible to reach rVelocityFront = -8.0000034 // which is outside the bounds of the shield and therefore allows any action. double v_ego2 = clamp(v_ego, minVelocityEgo, maxVelocityEgo); double v_front2 = clamp(v_front, minVelocityFront - 1, maxVelocityFront + 1); // Bug: guards do not account for odd velocity returning from sensor range // Furthermore, the distance can exceed the sensor range by quite a bit // in the moment where Front disappears. // Only in the next time-step is it reduced to maxSensorDistance + 1. double distance2 = fmin(distance, maxSensorDistance + 1); int bitarray = get_value(v_ego2, v_front2, distance2); if (bitarray == -1) { ++outOfBounds; } if (distance &lt;= 0) { ++safetyViolations; } if (bitarray == 0) { // Since the barbaric method is an under-approximation of behaviour // Red areas may sometimes be entered. // Yes, this is extremely interesting and worth examining further. ++noSafeActions; return intToActions(1 + 2 +4); } return intToActions(bitarray); } allowedActions allowed = getAllowedActions(0, 0, 10); /** Tested on CC 192 samples with G of 0.5.shield * / allowedActions debug1 = getAllowedActions(3, 10, 20); //111 allowedActions debug2 = getAllowedActions(-3, 0, 8); //110 allowedActions debug3 = getAllowedActions(-3, 5, 8); //111 allowedActions debug4 = getAllowedActions(-4, -8, 17.7);//110 allowedActions debug5 = getAllowedActions(5, -8, 10); //111 (no safe actions) allowedActions debug6 = getAllowedActions(-8, -9, 6);//110 /* */ </declaration> <template> <name x="5" y="5">Ego</name> <location id="id0" x="86" y="51"> <name x="119" y="42">Negative_acc</name> </location> <location id="id1" x="-204" y="-68"> <name x="-272" y="-76">No_acc</name> </location> <location id="id2" x="-34" y="-68"> <name x="-17" y="-76">Choose</name> <committed/> </location> <location id="id3" x="85" y="-187"> <name x="75" y="-221">Positive_acc</name> </location> <init ref="id1"/> <transition id="id4"> <source ref="id0"/> <target ref="id2"/> <label kind="synchronisation" x="-59" y="34">chooseEgo?</label> <nail x="-8" y="25"/> </transition> <transition id="id5"> <source ref="id3"/> <target ref="id2"/> <label kind="synchronisation" x="-59" y="-187">chooseEgo?</label> <nail x="-8" y="-161"/> </transition> <transition id="id6"> <source ref="id1"/> <target ref="id2"/> <label kind="synchronisation" x="-170" y="-119">chooseEgo?</label> <nail x="-119" y="-102"/> </transition> <transition id="id7"> <source ref="id2"/> <target ref="id0"/> <label kind="guard" x="76" y="-51">allowed.backwards &amp;&amp; rVelocityEgo &gt; minVelocityEgo</label> <label kind="assignment" x="76" y="-17">accelerationEgo = -2</label> <nail x="59" y="-42"/> </transition> <transition id="id8"> <source ref="id2"/> <target ref="id3"/> <label kind="guard" x="85" y="-161">allowed.forwards &amp;&amp; rVelocityEgo &lt; maxVelocityEgo</label> <label kind="assignment" x="85" y="-127">accelerationEgo = 2</label> <nail x="59" y="-102"/> </transition> <transition id="id9"> <source ref="id2"/> <target ref="id1"/> <label kind="guard" x="-340" y="-42">allowed.neutral</label> <label kind="assignment" x="-340" y="-25">accelerationEgo = 0</label> <nail x="-119" y="-25"/> </transition> </template> <template> <name>Front</name> <location id="id10" x="-340" y="-306"> <name x="-331" y="-331">Faraway</name> </location> <location id="id11" x="102" y="-136"> <name x="92" y="-170">Positive_acc</name> </location> <location id="id12" x="102" y="68"> <name x="59" y="85">Negative_acc</name> </location> <location id="id13" x="-102" y="68"> <name x="-153" y="85">No_acceleration</name> </location> <location id="id14" x="0" y="-34"> <name x="17" y="-42">Choose</name> <committed/> </location> <location id="id15" x="-340" y="-238"> <committed/> </location> <location id="id16" x="-340" y="-153"> <committed/> </location> <branchpoint id="id17" x="-340" y="-195"/> <init ref="id13"/> <transition id="id18" controllable="false"> <source ref="id16"/> <target ref="id10"/> <label kind="guard" x="-680" y="-238">rVelocityEgo &lt; minVelocityFront</label> <nail x="-416" y="-153"/> <nail x="-416" y="-306"/> </transition> <transition id="id19"> <source ref="id17"/> <target ref="id10"/> <nail x="-374" y="-195"/> <nail x="-374" y="-306"/> </transition> <transition id="id20"> <source ref="id17"/> <target ref="id16"/> </transition> <transition id="id21" controllable="false"> <source ref="id15"/> <target ref="id17"/> </transition> <transition id="id22" controllable="false"> <source ref="id12"/> <target ref="id10"/> <label kind="guard" x="-178" y="-323">rDistance &gt; maxSensorDistance</label> <label kind="synchronisation" x="-178" y="-306">update?</label> <label kind="assignment" x="-178" y="-289">rDistance = maxSensorDistance+1, accelerationFront = 0</label> <nail x="263" y="68"/> <nail x="263" y="-306"/> </transition> <transition id="id23" controllable="false"> <source ref="id11"/> <target ref="id10"/> <label kind="guard" x="-204" y="-246">rDistance &gt; maxSensorDistance</label> <label kind="synchronisation" x="-204" y="-229">update?</label> <label kind="assignment" x="-204" y="-212">rDistance = maxSensorDistance+1, accelerationFront = 0</label> <nail x="102" y="-229"/> <nail x="-204" y="-229"/> <nail x="-246" y="-280"/> </transition> <transition id="id24" controllable="false"> <source ref="id13"/> <target ref="id10"/> <label kind="guard" x="-382" y="17">rDistance &gt; maxSensorDistance</label> <label kind="synchronisation" x="-382" y="34">update?</label> <label kind="assignment" x="-382" y="51">rDistance = maxSensorDistance+1, accelerationFront = 0</label> <nail x="-391" y="68"/> <nail x="-391" y="-306"/> </transition> <transition id="id25" controllable="false"> <source ref="id12"/> <target ref="id14"/> <label kind="synchronisation" x="-25" y="68">chooseFront?</label> <nail x="0" y="68"/> </transition> <transition id="id26" controllable="false"> <source ref="id11"/> <target ref="id14"/> <label kind="synchronisation" x="-17" y="-153">chooseFront?</label> <nail x="0" y="-136"/> </transition> <transition id="id27" controllable="false"> <source ref="id13"/> <target ref="id14"/> <label kind="synchronisation" x="-93" y="17">chooseFront?</label> </transition> <transition id="id28" controllable="false"> <source ref="id14"/> <target ref="id12"/> <label kind="guard" x="25" y="8">rVelocityFront &gt; minVelocityFront</label> <label kind="assignment" x="25" y="25">accelerationFront = -2</label> </transition> <transition id="id29" controllable="false"> <source ref="id14"/> <target ref="id11"/> <label kind="guard" x="25" y="-102">rVelocityFront &lt; maxVelocityFront</label> <label kind="assignment" x="25" y="-85">accelerationFront = 2</label> </transition> <transition id="id30" controllable="false"> <source ref="id14"/> <target ref="id13"/> <label kind="assignment" x="-204" y="-8">accelerationFront = 0</label> <nail x="-102" y="-8"/> </transition> <transition id="id31" controllable="false"> <source ref="id10"/> <target ref="id15"/> <label kind="synchronisation" x="-365" y="-280">chooseFront?</label> </transition> <transition id="id32" controllable="false"> <source ref="id16"/> <target ref="id14"/> <label kind="select" x="-331" y="-136">i:int[minVelocityFront, maxVelocityFront]</label> <label kind="guard" x="-331" y="-119">i &lt;= rVelocityEgo</label> <label kind="assignment" x="-331" y="-102">rVelocityFront = i * 1.0, rDistance = 1.0*maxSensorDistance</label> <nail x="-340" y="-34"/> </transition> </template> <template> <name>Monitor</name> <declaration> double distanceRate(double velFront, double velEgo, double dist){ if (dist &gt; maxSensorDistance) return 0.0; else return velFront - velEgo; } </declaration> <location id="id33" x="-153" y="-144"> <label kind="invariant" x="-315" y="-127">rVelocityEgo' == accelerationEgo &amp;&amp; rVelocityFront' == accelerationFront &amp;&amp; rDistance' == distanceRate(rVelocityFront,rVelocityEgo, rDistance) &amp;&amp; D' == rDistance</label> </location> <init ref="id33"/> </template> <template> <name>System</name> <location id="id34" x="-68" y="-238"> <name x="-85" y="-272">Done</name> <urgent/> </location> <location id="id35" x="-238" y="-238"> <name x="-272" y="-272">FrontNext</name> <urgent/> </location> <location id="id36" x="-238" y="-187"> <name x="-255" y="-170">Wait</name> <label kind="invariant" x="-280" y="-153">waitTimer &lt;= 1</label> </location> <location id="id37" x="-408" y="-238"> <name x="-433" y="-272">EgoNext</name> <urgent/> </location> <init ref="id37"/> <transition id="id38" controllable="false"> <source ref="id36"/> <target ref="id37"/> <label kind="guard" x="-536" y="-144">waitTimer &gt;= 1</label> <label kind="assignment" x="-535" y="-127">allowed = shieldingDebug(rVelocityEgo, rVelocityFront, rDistance)</label> <nail x="-357" y="-144"/> <nail x="-536" y="-144"/> <nail x="-535" y="-238"/> </transition> <transition id="id39" controllable="false"> <source ref="id34"/> <target ref="id36"/> <label kind="synchronisation" x="-144" y="-195">update!</label> <label kind="assignment" x="-144" y="-212">waitTimer = 0</label> </transition> <transition id="id40" controllable="false"> <source ref="id35"/> <target ref="id34"/> <label kind="synchronisation" x="-204" y="-255">chooseFront!</label> </transition> <transition id="id41" controllable="false"> <source ref="id37"/> <target ref="id35"/> <label kind="synchronisation" x="-365" y="-255">chooseEgo!</label> </transition> </template> <system> system Ego, Front, System, Monitor; </system> <queries> <query> <formula>simulate [&lt;=120;100] { accelerationEgo, accelerationFront, rVelocityEgo, rVelocityFront, rDistance, 0, 200 }</formula> <comment/> </query> <query> <formula>simulate [&lt;=120;10] { rDistance, 0, 200 }</formula> <comment/> </query> <query> <formula>E[&lt;=120;1000] (max: D/10000)</formula> <comment/> </query> <query> <formula>E[&lt;=120;1000] (max: D/10000 + (rDistance &lt;= 0 ? 1000 : 0))</formula> <comment/> </query> <query> <formula>E[&lt;=120;1000] (max: (rDistance &lt;= 0))</formula> <comment/> </query> <query> <formula>strategy DeathCosts1000 = minE (D/1000 + (rDistance &lt;= 0 ? 1000 : 0)) [&lt;=120] {} -&gt; {rVelocityEgo, rVelocityFront, rDistance}: &lt;&gt; time &gt;= 120</formula> <comment/> </query> <query> <formula>simulate [&lt;=120;10] { rDistance, 0, 200 } under DeathCosts1000</formula> <comment/> </query> <query> <formula>E[&lt;=120;1000] (max: D/1000) under DeathCosts1000</formula> <comment/> </query> <query> <formula>E[&lt;=120;1000] (max: rDistance &lt; 0) under DeathCosts1000</formula> <comment/> </query> <query> <formula>saveStrategy("/home/asger/Experiments/E1/DeathCosts1000.strategy.json", DeathCosts1000)</formula> <comment/> </query> <query> <formula>strategy DeathCosts1000 = loadStrategy {} -&gt; {rVelocityEgo, rVelocityFront, rDistance}("/home/asger/Experiments/E1/DeathCosts1000.strategy.json")</formula> <comment/> </query> <query> <formula/> <comment/> </query> <query> <formula/> <comment/> </query> </queries> </nta>
412
0.70864
1
0.70864
game-dev
MEDIA
0.295369
game-dev
0.899916
1
0.899916
RockinChaos/ItemJoin
8,804
src/main/java/me/RockinChaos/itemjoin/listeners/Placement.java
/* * ItemJoin * Copyright (C) CraftationGaming <https://www.craftationgaming.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.RockinChaos.itemjoin.listeners; import me.RockinChaos.core.handlers.PlayerHandler; import me.RockinChaos.core.utils.SchedulerUtils; import me.RockinChaos.core.utils.ServerUtils; import me.RockinChaos.core.utils.StringUtils; import me.RockinChaos.itemjoin.item.ItemMap; import me.RockinChaos.itemjoin.item.ItemUtilities; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import java.util.Objects; public class Placement implements Listener { /** * Prevents the player from placing the custom item. * * @param event - BlockPlaceEvent */ @EventHandler(ignoreCancelled = true) private void onBlockPlace(BlockPlaceEvent event) { ItemStack item = event.getItemInHand(); Player player = event.getPlayer(); if (!ItemUtilities.getUtilities().isAllowed(player, item, "placement")) { event.setCancelled(true); PlayerHandler.updateInventory(player, 1L); } } /** * Refills the custom item to its original stack size when placing the item. * * @param event - PlayerInteractEvent */ @EventHandler() private void onCountLock(PlayerInteractEvent event) { final ItemStack item = (event.getItem() != null ? event.getItem().clone() : event.getItem()); final Player player = event.getPlayer(); final int slot = player.getInventory().getHeldItemSlot(); if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK && !PlayerHandler.isCreativeMode(player)) { if (!ItemUtilities.getUtilities().isAllowed(player, item, "count-lock")) { ItemMap itemMap = ItemUtilities.getUtilities().getItemMap(item); item.setAmount(itemMap.getCount(player)); SchedulerUtils.run(() -> { final boolean isCraftingInv = PlayerHandler.isCraftingInv(player); if (StringUtils.containsIgnoreCase(item.getType().name(), "WATER") || StringUtils.containsIgnoreCase(item.getType().name(), "LAVA") || item.getType().name().equalsIgnoreCase("BUCKET") || StringUtils.containsIgnoreCase(item.getType().name(), "POTION")) { if (player.getInventory().getHeldItemSlot() == slot) { PlayerHandler.setMainHandItem(player, item); } else if (isCraftingInv) { player.getInventory().setItem(slot, item); } } else { final ItemStack heldItem = PlayerHandler.getHandItem(player); if (heldItem.getAmount() <= 1) { if (ServerUtils.hasSpecificUpdate("1_9")) { if (Objects.equals(event.getHand(), EquipmentSlot.HAND)) { if (player.getInventory().getHeldItemSlot() == slot) { PlayerHandler.setMainHandItem(player, item); } else if (isCraftingInv) { player.getInventory().setItem(slot, item); } } else if (Objects.equals(event.getHand(), EquipmentSlot.OFF_HAND)) { PlayerHandler.setOffHandItem(player, item); } } else { if (player.getInventory().getHeldItemSlot() == slot) { PlayerHandler.setMainHandItem(player, item); } else if (isCraftingInv) { player.getInventory().setItem(slot, item); } } } else if (itemMap.isSimilar(player, heldItem)) { heldItem.setAmount(itemMap.getCount(player)); } } }); } } } /** * Prevents the player from placing a custom item inside an itemframe. * * @param event - PlayerInteractEntityEvent */ @EventHandler(ignoreCancelled = true) private void onFramePlace(PlayerInteractEntityEvent event) { try { if (event.getRightClicked() instanceof ItemFrame) { try { ItemStack item; if (ServerUtils.hasSpecificUpdate("1_9")) { item = PlayerHandler.getPerfectHandItem(event.getPlayer(), event.getHand().toString()); } else { item = PlayerHandler.getPerfectHandItem(event.getPlayer(), ""); } Player player = event.getPlayer(); if (!ItemUtilities.getUtilities().isAllowed(player, item, "placement")) { event.setCancelled(true); PlayerHandler.updateInventory(player, 1L); } } catch (Exception e) { ServerUtils.sendDebugTrace(e); } } } catch (Exception ignored) {} // pale_oak_boat (paper bug) fix (and fixes future entities). } /** * Refills the custom item to its original stack size when placing the item into an itemframe. * * @param event - PlayerInteractEntityEvent */ @EventHandler() private void onFrameLock(PlayerInteractEntityEvent event) { try { if (event.getRightClicked() instanceof ItemFrame) { try { ItemStack item; if (ServerUtils.hasSpecificUpdate("1_9")) { item = PlayerHandler.getPerfectHandItem(event.getPlayer(), event.getHand().toString()); } else { item = PlayerHandler.getPerfectHandItem(event.getPlayer(), ""); } Player player = event.getPlayer(); if (PlayerHandler.isCreativeMode(player)) { if (!ItemUtilities.getUtilities().isAllowed(player, item, "count-lock")) { ItemMap itemMap = ItemUtilities.getUtilities().getItemMap(item); if (itemMap != null) { final ItemStack heldItem = PlayerHandler.getHandItem(player); if (heldItem.getAmount() <= 1) { if (ServerUtils.hasSpecificUpdate("1_9")) { if (event.getHand().equals(EquipmentSlot.HAND)) { PlayerHandler.setMainHandItem(player, item); } else if (event.getHand().equals(EquipmentSlot.OFF_HAND)) { PlayerHandler.setOffHandItem(player, item); } } else { PlayerHandler.setMainHandItem(player, item); } } else if (itemMap.isSimilar(player, heldItem)) { heldItem.setAmount(itemMap.getCount(player)); } } } } } catch (Exception e) { ServerUtils.sendDebugTrace(e); } } } catch (Exception ignored) {} // pale_oak_boat (paper bug) fix (and fixes future entities). } }
412
0.963541
1
0.963541
game-dev
MEDIA
0.968187
game-dev
0.977274
1
0.977274
LofizKittyCat/GradleMCPBase
1,897
src/main/java/net/minecraft/network/play/server/S11PacketSpawnExperienceOrb.java
package net.minecraft.network.play.server; import java.io.IOException; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; public class S11PacketSpawnExperienceOrb implements Packet<INetHandlerPlayClient> { private int entityID; private int posX; private int posY; private int posZ; private int xpValue; public S11PacketSpawnExperienceOrb() { } public S11PacketSpawnExperienceOrb(EntityXPOrb xpOrb) { this.entityID = xpOrb.getEntityId(); this.posX = MathHelper.floor_double(xpOrb.posX * 32.0D); this.posY = MathHelper.floor_double(xpOrb.posY * 32.0D); this.posZ = MathHelper.floor_double(xpOrb.posZ * 32.0D); this.xpValue = xpOrb.getXpValue(); } public void readPacketData(PacketBuffer buf) throws IOException { this.entityID = buf.readVarIntFromBuffer(); this.posX = buf.readInt(); this.posY = buf.readInt(); this.posZ = buf.readInt(); this.xpValue = buf.readShort(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeVarIntToBuffer(this.entityID); buf.writeInt(this.posX); buf.writeInt(this.posY); buf.writeInt(this.posZ); buf.writeShort(this.xpValue); } public void processPacket(INetHandlerPlayClient handler) { handler.handleSpawnExperienceOrb(this); } public int getEntityID() { return this.entityID; } public int getX() { return this.posX; } public int getY() { return this.posY; } public int getZ() { return this.posZ; } public int getXPValue() { return this.xpValue; } }
412
0.868934
1
0.868934
game-dev
MEDIA
0.838935
game-dev,networking
0.686136
1
0.686136
codenamecpp/carnage3d
3,474
src/GameObjectsManager.h
#pragma once #include "Pedestrian.h" #include "Vehicle.h" #include "Projectile.h" #include "Decoration.h" #include "Obstacle.h" #include "Explosion.h" // define game objects manager class class GameObjectsManager final: public cxx::noncopyable { public: // readonly std::vector<GameObject*> mAllObjects; std::vector<Pedestrian*> mPedestriansList; std::vector<Vehicle*> mVehiclesList; public: ~GameObjectsManager(); void EnterWorld(); void ClearWorld(); void UpdateFrame(); void DebugDraw(DebugRenderer& debugRender); // Add new pedestrian instance to map at specific location // @param position: Real world position // @param heading: Initial rotation // @param pedestrianType: Pedestrian type // @param remap: Remap Pedestrian* CreatePedestrian(const glm::vec3& position, cxx::angle_t heading, ePedestrianType pedestrianType, int remap = NO_REMAP); // Add new car instance to map at specific location // @param position: Initial world position // @param heading: Initial rotation // @param desc: Car style // @param carModel: Car model identifier Vehicle* CreateVehicle(const glm::vec3& position, cxx::angle_t heading, VehicleInfo* desc); Vehicle* CreateVehicle(const glm::vec3& position, cxx::angle_t heading, eVehicleModel carModel); // Add new projectile instance to map at specific location Projectile* CreateProjectile(const glm::vec3& position, cxx::angle_t heading, Pedestrian* shooter); Projectile* CreateProjectile(const glm::vec3& position, cxx::angle_t heading, WeaponInfo* weaponInfo, Pedestrian* shooter); // Add new decoration instance to map at specific location Decoration* CreateDecoration(const glm::vec3& position, cxx::angle_t heading, GameObjectInfo* desc); Decoration* CreateFirstBlood(const glm::vec3& position); Decoration* CreateWaterSplash(const glm::vec3& position); Decoration* CreateBigSmoke(const glm::vec3& position); // Add explosion instance to map at specific location Explosion* CreateExplosion(GameObject* explodingObject, Pedestrian* causer, eExplosionType explosionType, const glm::vec3& position); // Add new obstacle instance to map at specific location Obstacle* CreateObstacle(const glm::vec3& position, cxx::angle_t heading, GameObjectInfo* desc); // Find gameobject by its unique identifier // @param objectID: Unique identifier Vehicle* GetVehicleByID(GameObjectID objectID) const; Obstacle* GetObstacleByID(GameObjectID objectID) const; Decoration* GetDecorationByID(GameObjectID objectID) const; Pedestrian* GetPedestrianByID(GameObjectID objectID) const; GameObject* GetGameObjectByID(GameObjectID objectID) const; // Will immediately destroy gameobject, don't call this mehod during UpdateFrame // @param object: Object to destroy void DestroyGameObject(GameObject* object); private: bool CreateStartupObjects(); void DestroyAllObjects(); void DestroyMarkedForDeletionObjects(); GameObjectID GenerateUniqueID(); private: GameObjectID mIDsCounter = 0; // objects pools cxx::object_pool<Pedestrian> mPedestriansPool; cxx::object_pool<Vehicle> mCarsPool; cxx::object_pool<Projectile> mProjectilesPool; cxx::object_pool<Decoration> mDecorationsPool; cxx::object_pool<Obstacle> mObstaclesPool; cxx::object_pool<Explosion> mExplosionsPool; }; extern GameObjectsManager gGameObjectsManager;
412
0.887697
1
0.887697
game-dev
MEDIA
0.994414
game-dev
0.636873
1
0.636873
mapmint/mapmint
3,094
mapmint-ui/js/OpenLayers-2.10/lib/OpenLayers/Strategy.js
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * Class: OpenLayers.Strategy * Abstract vector layer strategy class. Not to be instantiated directly. Use * one of the strategy subclasses instead. */ OpenLayers.Strategy = OpenLayers.Class({ /** * Property: layer * {<OpenLayers.Layer.Vector>} The layer this strategy belongs to. */ layer: null, /** * Property: options * {Object} Any options sent to the constructor. */ options: null, /** * Property: active * {Boolean} The control is active. */ active: null, /** * Property: autoActivate * {Boolean} The creator of the strategy can set autoActivate to false * to fully control when the protocol is activated and deactivated. * Defaults to true. */ autoActivate: true, /** * Property: autoDestroy * {Boolean} The creator of the strategy can set autoDestroy to false * to fully control when the strategy is destroyed. Defaults to * true. */ autoDestroy: true, /** * Constructor: OpenLayers.Strategy * Abstract class for vector strategies. Create instances of a subclass. * * Parameters: * options - {Object} Optional object whose properties will be set on the * instance. */ initialize: function(options) { OpenLayers.Util.extend(this, options); this.options = options; // set the active property here, so that user cannot override it this.active = false; }, /** * APIMethod: destroy * Clean up the strategy. */ destroy: function() { this.deactivate(); this.layer = null; this.options = null; }, /** * Method: setLayer * Called to set the <layer> property. * * Parameters: * {<OpenLayers.Layer.Vector>} */ setLayer: function(layer) { this.layer = layer; }, /** * Method: activate * Activate the strategy. Register any listeners, do appropriate setup. * * Returns: * {Boolean} True if the strategy was successfully activated or false if * the strategy was already active. */ activate: function() { if (!this.active) { this.active = true; return true; } return false; }, /** * Method: deactivate * Deactivate the strategy. Unregister any listeners, do appropriate * tear-down. * * Returns: * {Boolean} True if the strategy was successfully deactivated or false if * the strategy was already inactive. */ deactivate: function() { if (this.active) { this.active = false; return true; } return false; }, CLASS_NAME: "OpenLayers.Strategy" });
412
0.692159
1
0.692159
game-dev
MEDIA
0.772271
game-dev
0.792527
1
0.792527
fredakilla/GPlayEngine
27,511
thirdparty/bullet/src/BulletCollision/Gimpact/btGImpactShape.h
/*! \file btGImpactShape.h \author Francisco Len Njera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com 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 GIMPACT_SHAPE_H #define GIMPACT_SHAPE_H #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionShapes/btTriangleShape.h" #include "BulletCollision/CollisionShapes/btStridingMeshInterface.h" #include "BulletCollision/CollisionShapes/btCollisionMargin.h" #include "BulletCollision/CollisionDispatch/btCollisionWorld.h" #include "BulletCollision/CollisionShapes/btConcaveShape.h" #include "BulletCollision/CollisionShapes/btTetrahedronShape.h" #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" #include "LinearMath/btMatrix3x3.h" #include "LinearMath/btAlignedObjectArray.h" #include "btGImpactQuantizedBvh.h" // box tree class //! declare Quantized trees, (you can change to float based trees) typedef btGImpactQuantizedBvh btGImpactBoxSet; enum eGIMPACT_SHAPE_TYPE { CONST_GIMPACT_COMPOUND_SHAPE = 0, CONST_GIMPACT_TRIMESH_SHAPE_PART, CONST_GIMPACT_TRIMESH_SHAPE }; //! Helper class for tetrahedrons class btTetrahedronShapeEx:public btBU_Simplex1to4 { public: btTetrahedronShapeEx() { m_numVertices = 4; } SIMD_FORCE_INLINE void setVertices( const btVector3 & v0,const btVector3 & v1, const btVector3 & v2,const btVector3 & v3) { m_vertices[0] = v0; m_vertices[1] = v1; m_vertices[2] = v2; m_vertices[3] = v3; recalcLocalAabb(); } }; //! Base class for gimpact shapes class btGImpactShapeInterface : public btConcaveShape { protected: btAABB m_localAABB; bool m_needs_update; btVector3 localScaling; btGImpactBoxSet m_box_set;// optionally boxset //! use this function for perfofm refit in bounding boxes //! use this function for perfofm refit in bounding boxes virtual void calcLocalAABB() { lockChildShapes(); if(m_box_set.getNodeCount() == 0) { m_box_set.buildSet(); } else { m_box_set.update(); } unlockChildShapes(); m_localAABB = m_box_set.getGlobalBox(); } public: btGImpactShapeInterface() { m_shapeType=GIMPACT_SHAPE_PROXYTYPE; m_localAABB.invalidate(); m_needs_update = true; localScaling.setValue(1.f,1.f,1.f); } //! performs refit operation /*! Updates the entire Box set of this shape. \pre postUpdate() must be called for attemps to calculating the box set, else this function will does nothing. \post if m_needs_update == true, then it calls calcLocalAABB(); */ SIMD_FORCE_INLINE void updateBound() { if(!m_needs_update) return; calcLocalAABB(); m_needs_update = false; } //! If the Bounding box is not updated, then this class attemps to calculate it. /*! \post Calls updateBound() for update the box set. */ void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { btAABB transformedbox = m_localAABB; transformedbox.appy_transform(t); aabbMin = transformedbox.m_min; aabbMax = transformedbox.m_max; } //! Tells to this object that is needed to refit the box set virtual void postUpdate() { m_needs_update = true; } //! Obtains the local box, which is the global calculated box of the total of subshapes SIMD_FORCE_INLINE const btAABB & getLocalBox() { return m_localAABB; } virtual int getShapeType() const { return GIMPACT_SHAPE_PROXYTYPE; } /*! \post You must call updateBound() for update the box set. */ virtual void setLocalScaling(const btVector3& scaling) { localScaling = scaling; postUpdate(); } virtual const btVector3& getLocalScaling() const { return localScaling; } virtual void setMargin(btScalar margin) { m_collisionMargin = margin; int i = getNumChildShapes(); while(i--) { btCollisionShape* child = getChildShape(i); child->setMargin(margin); } m_needs_update = true; } //! Subshape member functions //!@{ //! Base method for determinig which kind of GIMPACT shape we get virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const = 0 ; //! gets boxset SIMD_FORCE_INLINE const btGImpactBoxSet * getBoxSet() const { return &m_box_set; } //! Determines if this class has a hierarchy structure for sorting its primitives SIMD_FORCE_INLINE bool hasBoxSet() const { if(m_box_set.getNodeCount() == 0) return false; return true; } //! Obtains the primitive manager virtual const btPrimitiveManagerBase * getPrimitiveManager() const = 0; //! Gets the number of children virtual int getNumChildShapes() const = 0; //! if true, then its children must get transforms. virtual bool childrenHasTransform() const = 0; //! Determines if this shape has triangles virtual bool needsRetrieveTriangles() const = 0; //! Determines if this shape has tetrahedrons virtual bool needsRetrieveTetrahedrons() const = 0; virtual void getBulletTriangle(int prim_index,btTriangleShapeEx & triangle) const = 0; virtual void getBulletTetrahedron(int prim_index,btTetrahedronShapeEx & tetrahedron) const = 0; //! call when reading child shapes virtual void lockChildShapes() const { } virtual void unlockChildShapes() const { } //! if this trimesh SIMD_FORCE_INLINE void getPrimitiveTriangle(int index,btPrimitiveTriangle & triangle) const { getPrimitiveManager()->get_primitive_triangle(index,triangle); } //! Retrieves the bound from a child /*! */ virtual void getChildAabb(int child_index,const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { btAABB child_aabb; getPrimitiveManager()->get_primitive_box(child_index,child_aabb); child_aabb.appy_transform(t); aabbMin = child_aabb.m_min; aabbMax = child_aabb.m_max; } //! Gets the children virtual btCollisionShape* getChildShape(int index) = 0; //! Gets the child virtual const btCollisionShape* getChildShape(int index) const = 0; //! Gets the children transform virtual btTransform getChildTransform(int index) const = 0; //! Sets the children transform /*! \post You must call updateBound() for update the box set. */ virtual void setChildTransform(int index, const btTransform & transform) = 0; //!@} //! virtual method for ray collision virtual void rayTest(const btVector3& rayFrom, const btVector3& rayTo, btCollisionWorld::RayResultCallback& resultCallback) const { (void) rayFrom; (void) rayTo; (void) resultCallback; } //! Function for retrieve triangles. /*! It gives the triangles in local space */ virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const { (void) callback; (void) aabbMin; (void) aabbMax; } //! Function for retrieve triangles. /*! It gives the triangles in local space */ virtual void processAllTrianglesRay(btTriangleCallback* /*callback*/,const btVector3& /*rayFrom*/, const btVector3& /*rayTo*/) const { } //!@} }; //! btGImpactCompoundShape allows to handle multiple btCollisionShape objects at once /*! This class only can manage Convex subshapes */ class btGImpactCompoundShape : public btGImpactShapeInterface { public: //! compound primitive manager class CompoundPrimitiveManager:public btPrimitiveManagerBase { public: virtual ~CompoundPrimitiveManager() {} btGImpactCompoundShape * m_compoundShape; CompoundPrimitiveManager(const CompoundPrimitiveManager& compound) : btPrimitiveManagerBase() { m_compoundShape = compound.m_compoundShape; } CompoundPrimitiveManager(btGImpactCompoundShape * compoundShape) { m_compoundShape = compoundShape; } CompoundPrimitiveManager() { m_compoundShape = NULL; } virtual bool is_trimesh() const { return false; } virtual int get_primitive_count() const { return (int )m_compoundShape->getNumChildShapes(); } virtual void get_primitive_box(int prim_index ,btAABB & primbox) const { btTransform prim_trans; if(m_compoundShape->childrenHasTransform()) { prim_trans = m_compoundShape->getChildTransform(prim_index); } else { prim_trans.setIdentity(); } const btCollisionShape* shape = m_compoundShape->getChildShape(prim_index); shape->getAabb(prim_trans,primbox.m_min,primbox.m_max); } virtual void get_primitive_triangle(int prim_index,btPrimitiveTriangle & triangle) const { btAssert(0); (void) prim_index; (void) triangle; } }; protected: CompoundPrimitiveManager m_primitive_manager; btAlignedObjectArray<btTransform> m_childTransforms; btAlignedObjectArray<btCollisionShape*> m_childShapes; public: btGImpactCompoundShape(bool children_has_transform = true) { (void) children_has_transform; m_primitive_manager.m_compoundShape = this; m_box_set.setPrimitiveManager(&m_primitive_manager); } virtual ~btGImpactCompoundShape() { } //! if true, then its children must get transforms. virtual bool childrenHasTransform() const { if(m_childTransforms.size()==0) return false; return true; } //! Obtains the primitive manager virtual const btPrimitiveManagerBase * getPrimitiveManager() const { return &m_primitive_manager; } //! Obtains the compopund primitive manager SIMD_FORCE_INLINE CompoundPrimitiveManager * getCompoundPrimitiveManager() { return &m_primitive_manager; } //! Gets the number of children virtual int getNumChildShapes() const { return m_childShapes.size(); } //! Use this method for adding children. Only Convex shapes are allowed. void addChildShape(const btTransform& localTransform,btCollisionShape* shape) { btAssert(shape->isConvex()); m_childTransforms.push_back(localTransform); m_childShapes.push_back(shape); } //! Use this method for adding children. Only Convex shapes are allowed. void addChildShape(btCollisionShape* shape) { btAssert(shape->isConvex()); m_childShapes.push_back(shape); } //! Gets the children virtual btCollisionShape* getChildShape(int index) { return m_childShapes[index]; } //! Gets the children virtual const btCollisionShape* getChildShape(int index) const { return m_childShapes[index]; } //! Retrieves the bound from a child /*! */ virtual void getChildAabb(int child_index,const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { if(childrenHasTransform()) { m_childShapes[child_index]->getAabb(t*m_childTransforms[child_index],aabbMin,aabbMax); } else { m_childShapes[child_index]->getAabb(t,aabbMin,aabbMax); } } //! Gets the children transform virtual btTransform getChildTransform(int index) const { btAssert(m_childTransforms.size() == m_childShapes.size()); return m_childTransforms[index]; } //! Sets the children transform /*! \post You must call updateBound() for update the box set. */ virtual void setChildTransform(int index, const btTransform & transform) { btAssert(m_childTransforms.size() == m_childShapes.size()); m_childTransforms[index] = transform; postUpdate(); } //! Determines if this shape has triangles virtual bool needsRetrieveTriangles() const { return false; } //! Determines if this shape has tetrahedrons virtual bool needsRetrieveTetrahedrons() const { return false; } virtual void getBulletTriangle(int prim_index,btTriangleShapeEx & triangle) const { (void) prim_index; (void) triangle; btAssert(0); } virtual void getBulletTetrahedron(int prim_index,btTetrahedronShapeEx & tetrahedron) const { (void) prim_index; (void) tetrahedron; btAssert(0); } //! Calculates the exact inertia tensor for this shape virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual const char* getName()const { return "GImpactCompound"; } virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const { return CONST_GIMPACT_COMPOUND_SHAPE; } }; //! This class manages a sub part of a mesh supplied by the btStridingMeshInterface interface. /*! - Simply create this shape by passing the btStridingMeshInterface to the constructor btGImpactMeshShapePart, then you must call updateBound() after creating the mesh - When making operations with this shape, you must call <b>lock</b> before accessing to the trimesh primitives, and then call <b>unlock</b> - You can handle deformable meshes with this shape, by calling postUpdate() every time when changing the mesh vertices. */ class btGImpactMeshShapePart : public btGImpactShapeInterface { public: //! Trimesh primitive manager /*! Manages the info from btStridingMeshInterface object and controls the Lock/Unlock mechanism */ class TrimeshPrimitiveManager:public btPrimitiveManagerBase { public: btScalar m_margin; btStridingMeshInterface * m_meshInterface; btVector3 m_scale; int m_part; int m_lock_count; const unsigned char *vertexbase; int numverts; PHY_ScalarType type; int stride; const unsigned char *indexbase; int indexstride; int numfaces; PHY_ScalarType indicestype; TrimeshPrimitiveManager() { m_meshInterface = NULL; m_part = 0; m_margin = 0.01f; m_scale = btVector3(1.f,1.f,1.f); m_lock_count = 0; vertexbase = 0; numverts = 0; stride = 0; indexbase = 0; indexstride = 0; numfaces = 0; } TrimeshPrimitiveManager(const TrimeshPrimitiveManager & manager) : btPrimitiveManagerBase() { m_meshInterface = manager.m_meshInterface; m_part = manager.m_part; m_margin = manager.m_margin; m_scale = manager.m_scale; m_lock_count = 0; vertexbase = 0; numverts = 0; stride = 0; indexbase = 0; indexstride = 0; numfaces = 0; } TrimeshPrimitiveManager( btStridingMeshInterface * meshInterface, int part) { m_meshInterface = meshInterface; m_part = part; m_scale = m_meshInterface->getScaling(); m_margin = 0.1f; m_lock_count = 0; vertexbase = 0; numverts = 0; stride = 0; indexbase = 0; indexstride = 0; numfaces = 0; } virtual ~TrimeshPrimitiveManager() {} void lock() { if(m_lock_count>0) { m_lock_count++; return; } m_meshInterface->getLockedReadOnlyVertexIndexBase( &vertexbase,numverts, type, stride,&indexbase, indexstride, numfaces,indicestype,m_part); m_lock_count = 1; } void unlock() { if(m_lock_count == 0) return; if(m_lock_count>1) { --m_lock_count; return; } m_meshInterface->unLockReadOnlyVertexBase(m_part); vertexbase = NULL; m_lock_count = 0; } virtual bool is_trimesh() const { return true; } virtual int get_primitive_count() const { return (int )numfaces; } SIMD_FORCE_INLINE int get_vertex_count() const { return (int )numverts; } SIMD_FORCE_INLINE void get_indices(int face_index,unsigned int &i0,unsigned int &i1,unsigned int &i2) const { if(indicestype == PHY_SHORT) { unsigned short* s_indices = (unsigned short *)(indexbase + face_index * indexstride); i0 = s_indices[0]; i1 = s_indices[1]; i2 = s_indices[2]; } else { unsigned int * i_indices = (unsigned int *)(indexbase + face_index*indexstride); i0 = i_indices[0]; i1 = i_indices[1]; i2 = i_indices[2]; } } SIMD_FORCE_INLINE void get_vertex(unsigned int vertex_index, btVector3 & vertex) const { if(type == PHY_DOUBLE) { double * dvertices = (double *)(vertexbase + vertex_index*stride); vertex[0] = btScalar(dvertices[0]*m_scale[0]); vertex[1] = btScalar(dvertices[1]*m_scale[1]); vertex[2] = btScalar(dvertices[2]*m_scale[2]); } else { float * svertices = (float *)(vertexbase + vertex_index*stride); vertex[0] = svertices[0]*m_scale[0]; vertex[1] = svertices[1]*m_scale[1]; vertex[2] = svertices[2]*m_scale[2]; } } virtual void get_primitive_box(int prim_index ,btAABB & primbox) const { btPrimitiveTriangle triangle; get_primitive_triangle(prim_index,triangle); primbox.calc_from_triangle_margin( triangle.m_vertices[0], triangle.m_vertices[1],triangle.m_vertices[2],triangle.m_margin); } virtual void get_primitive_triangle(int prim_index,btPrimitiveTriangle & triangle) const { unsigned int indices[3]; get_indices(prim_index,indices[0],indices[1],indices[2]); get_vertex(indices[0],triangle.m_vertices[0]); get_vertex(indices[1],triangle.m_vertices[1]); get_vertex(indices[2],triangle.m_vertices[2]); triangle.m_margin = m_margin; } SIMD_FORCE_INLINE void get_bullet_triangle(int prim_index,btTriangleShapeEx & triangle) const { unsigned int indices[3]; get_indices(prim_index,indices[0],indices[1],indices[2]); get_vertex(indices[0],triangle.m_vertices1[0]); get_vertex(indices[1],triangle.m_vertices1[1]); get_vertex(indices[2],triangle.m_vertices1[2]); triangle.setMargin(m_margin); } }; protected: TrimeshPrimitiveManager m_primitive_manager; public: btGImpactMeshShapePart() { m_box_set.setPrimitiveManager(&m_primitive_manager); } btGImpactMeshShapePart( btStridingMeshInterface * meshInterface, int part ); virtual ~btGImpactMeshShapePart(); //! if true, then its children must get transforms. virtual bool childrenHasTransform() const { return false; } //! call when reading child shapes virtual void lockChildShapes() const; virtual void unlockChildShapes() const; //! Gets the number of children virtual int getNumChildShapes() const { return m_primitive_manager.get_primitive_count(); } //! Gets the children virtual btCollisionShape* getChildShape(int index) { (void) index; btAssert(0); return NULL; } //! Gets the child virtual const btCollisionShape* getChildShape(int index) const { (void) index; btAssert(0); return NULL; } //! Gets the children transform virtual btTransform getChildTransform(int index) const { (void) index; btAssert(0); return btTransform(); } //! Sets the children transform /*! \post You must call updateBound() for update the box set. */ virtual void setChildTransform(int index, const btTransform & transform) { (void) index; (void) transform; btAssert(0); } //! Obtains the primitive manager virtual const btPrimitiveManagerBase * getPrimitiveManager() const { return &m_primitive_manager; } SIMD_FORCE_INLINE TrimeshPrimitiveManager * getTrimeshPrimitiveManager() { return &m_primitive_manager; } virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual const char* getName()const { return "GImpactMeshShapePart"; } virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const { return CONST_GIMPACT_TRIMESH_SHAPE_PART; } //! Determines if this shape has triangles virtual bool needsRetrieveTriangles() const { return true; } //! Determines if this shape has tetrahedrons virtual bool needsRetrieveTetrahedrons() const { return false; } virtual void getBulletTriangle(int prim_index,btTriangleShapeEx & triangle) const { m_primitive_manager.get_bullet_triangle(prim_index,triangle); } virtual void getBulletTetrahedron(int prim_index,btTetrahedronShapeEx & tetrahedron) const { (void) prim_index; (void) tetrahedron; btAssert(0); } SIMD_FORCE_INLINE int getVertexCount() const { return m_primitive_manager.get_vertex_count(); } SIMD_FORCE_INLINE void getVertex(int vertex_index, btVector3 & vertex) const { m_primitive_manager.get_vertex(vertex_index,vertex); } SIMD_FORCE_INLINE void setMargin(btScalar margin) { m_primitive_manager.m_margin = margin; postUpdate(); } SIMD_FORCE_INLINE btScalar getMargin() const { return m_primitive_manager.m_margin; } virtual void setLocalScaling(const btVector3& scaling) { m_primitive_manager.m_scale = scaling; postUpdate(); } virtual const btVector3& getLocalScaling() const { return m_primitive_manager.m_scale; } SIMD_FORCE_INLINE int getPart() const { return (int)m_primitive_manager.m_part; } virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; virtual void processAllTrianglesRay(btTriangleCallback* callback,const btVector3& rayFrom,const btVector3& rayTo) const; }; //! This class manages a mesh supplied by the btStridingMeshInterface interface. /*! Set of btGImpactMeshShapePart parts - Simply create this shape by passing the btStridingMeshInterface to the constructor btGImpactMeshShape, then you must call updateBound() after creating the mesh - You can handle deformable meshes with this shape, by calling postUpdate() every time when changing the mesh vertices. */ class btGImpactMeshShape : public btGImpactShapeInterface { btStridingMeshInterface* m_meshInterface; protected: btAlignedObjectArray<btGImpactMeshShapePart*> m_mesh_parts; void buildMeshParts(btStridingMeshInterface * meshInterface) { for (int i=0;i<meshInterface->getNumSubParts() ;++i ) { btGImpactMeshShapePart * newpart = new btGImpactMeshShapePart(meshInterface,i); m_mesh_parts.push_back(newpart); } } //! use this function for perfofm refit in bounding boxes virtual void calcLocalAABB() { m_localAABB.invalidate(); int i = m_mesh_parts.size(); while(i--) { m_mesh_parts[i]->updateBound(); m_localAABB.merge(m_mesh_parts[i]->getLocalBox()); } } public: btGImpactMeshShape(btStridingMeshInterface * meshInterface) { m_meshInterface = meshInterface; buildMeshParts(meshInterface); } virtual ~btGImpactMeshShape() { int i = m_mesh_parts.size(); while(i--) { btGImpactMeshShapePart * part = m_mesh_parts[i]; delete part; } m_mesh_parts.clear(); } btStridingMeshInterface* getMeshInterface() { return m_meshInterface; } const btStridingMeshInterface* getMeshInterface() const { return m_meshInterface; } int getMeshPartCount() const { return m_mesh_parts.size(); } btGImpactMeshShapePart * getMeshPart(int index) { return m_mesh_parts[index]; } const btGImpactMeshShapePart * getMeshPart(int index) const { return m_mesh_parts[index]; } virtual void setLocalScaling(const btVector3& scaling) { localScaling = scaling; int i = m_mesh_parts.size(); while(i--) { btGImpactMeshShapePart * part = m_mesh_parts[i]; part->setLocalScaling(scaling); } m_needs_update = true; } virtual void setMargin(btScalar margin) { m_collisionMargin = margin; int i = m_mesh_parts.size(); while(i--) { btGImpactMeshShapePart * part = m_mesh_parts[i]; part->setMargin(margin); } m_needs_update = true; } //! Tells to this object that is needed to refit all the meshes virtual void postUpdate() { int i = m_mesh_parts.size(); while(i--) { btGImpactMeshShapePart * part = m_mesh_parts[i]; part->postUpdate(); } m_needs_update = true; } virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; //! Obtains the primitive manager virtual const btPrimitiveManagerBase * getPrimitiveManager() const { btAssert(0); return NULL; } //! Gets the number of children virtual int getNumChildShapes() const { btAssert(0); return 0; } //! if true, then its children must get transforms. virtual bool childrenHasTransform() const { btAssert(0); return false; } //! Determines if this shape has triangles virtual bool needsRetrieveTriangles() const { btAssert(0); return false; } //! Determines if this shape has tetrahedrons virtual bool needsRetrieveTetrahedrons() const { btAssert(0); return false; } virtual void getBulletTriangle(int prim_index,btTriangleShapeEx & triangle) const { (void) prim_index; (void) triangle; btAssert(0); } virtual void getBulletTetrahedron(int prim_index,btTetrahedronShapeEx & tetrahedron) const { (void) prim_index; (void) tetrahedron; btAssert(0); } //! call when reading child shapes virtual void lockChildShapes() const { btAssert(0); } virtual void unlockChildShapes() const { btAssert(0); } //! Retrieves the bound from a child /*! */ virtual void getChildAabb(int child_index,const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { (void) child_index; (void) t; (void) aabbMin; (void) aabbMax; btAssert(0); } //! Gets the children virtual btCollisionShape* getChildShape(int index) { (void) index; btAssert(0); return NULL; } //! Gets the child virtual const btCollisionShape* getChildShape(int index) const { (void) index; btAssert(0); return NULL; } //! Gets the children transform virtual btTransform getChildTransform(int index) const { (void) index; btAssert(0); return btTransform(); } //! Sets the children transform /*! \post You must call updateBound() for update the box set. */ virtual void setChildTransform(int index, const btTransform & transform) { (void) index; (void) transform; btAssert(0); } virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const { return CONST_GIMPACT_TRIMESH_SHAPE; } virtual const char* getName()const { return "GImpactMesh"; } virtual void rayTest(const btVector3& rayFrom, const btVector3& rayTo, btCollisionWorld::RayResultCallback& resultCallback) const; //! Function for retrieve triangles. /*! It gives the triangles in local space */ virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; virtual void processAllTrianglesRay (btTriangleCallback* callback,const btVector3& rayFrom,const btVector3& rayTo) const; virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btGImpactMeshShapeData { btCollisionShapeData m_collisionShapeData; btStridingMeshInterfaceData m_meshInterface; btVector3FloatData m_localScaling; float m_collisionMargin; int m_gimpactSubType; }; SIMD_FORCE_INLINE int btGImpactMeshShape::calculateSerializeBufferSize() const { return sizeof(btGImpactMeshShapeData); } #endif //GIMPACT_MESH_SHAPE_H
412
0.974684
1
0.974684
game-dev
MEDIA
0.642979
game-dev
0.964009
1
0.964009
rds1983/DigitalRune
3,557
Samples/Samples/Samples/Animation/CharacterAnimation/06-StressTestSample.cs
using System; using System.Collections.Generic; using System.Linq; using DigitalRune.Animation; using DigitalRune.Animation.Character; using DigitalRune.Geometry; using DigitalRune.Graphics.SceneGraph; using DigitalRune.Mathematics.Algebra; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Samples.Animation { [Sample(SampleCategory.Animation, "This sample renders many models with independent animations to test performance.", "", 56)] [Controls(@"Sample Press <Space> to start next animation.")] public class StressTestSample : CharacterAnimationSample { #if WINDOWS_PHONE || ANDROID || IOS private const int NumberOfModels = 20; #else private const int NumberOfModels = 100; #endif private readonly MeshNode[] _meshNodes; private readonly ITimeline[] _animations; private int _currentAnimationIndex; public StressTestSample(Microsoft.Xna.Framework.Game game) : base(game) { // Load model. var modelNode = ContentManager.Load<ModelNode>("Marine/PlayerMarine"); var meshNode = modelNode.GetSubtree().OfType<MeshNode>().First(); SampleHelper.EnablePerPixelLighting(meshNode); // Create looping animations for all imported animations. Dictionary<string, SkeletonKeyFrameAnimation> animations = meshNode.Mesh.Animations; _animations = new ITimeline[animations.Count]; int index = 0; foreach (var animation in animations.Values) { _animations[index] = new AnimationClip<SkeletonPose>(animation) { LoopBehavior = LoopBehavior.Cycle, Duration = TimeSpan.MaxValue, }; index++; } // Create a lot of clones of the mesh node and start a new animation on each instance. _meshNodes = new MeshNode[NumberOfModels]; for (int i = 0; i < NumberOfModels; i++) { var rowLength = (int)Math.Sqrt(NumberOfModels); var x = (i % rowLength) - rowLength / 2; var z = -i / rowLength; var position = new Vector3F(x, 0, z) * 1.5f; _meshNodes[i] = meshNode.Clone(); _meshNodes[i].PoseWorld = new Pose(position); GraphicsScreen.Scene.Children.Add(_meshNodes[i]); AnimationService.StartAnimation(_animations[0], (IAnimatableProperty)_meshNodes[i].SkeletonPose) .AutoRecycle(); } } public override void Update(GameTime gameTime) { base.Update(gameTime); // <Space> --> Cross-fade to next animation. if (InputService.IsPressed(Keys.Space, true)) { _currentAnimationIndex++; if (_currentAnimationIndex >= _animations.Length) _currentAnimationIndex = 0; for (int i = 0; i < NumberOfModels; i++) { // Start a next animation using a Replace transition with a fade-in time. AnimationService.StartAnimation( _animations[_currentAnimationIndex], (IAnimatableProperty<SkeletonPose>)_meshNodes[i].SkeletonPose, AnimationTransitions.Replace(TimeSpan.FromSeconds(0.2))) .AutoRecycle(); } } // Side note: // SkeletonPose.Update() is a method that can be called to update all internal skeleton pose // data immediately. If SkeletonPose.Update() is not called, the internal data will // be updated when needed - for example, when SkeletonPose.SkinningMatricesXna are accessed. //for (int i = 0; i < NumberOfModels; i++) // _meshNodes[i].SkeletonPose.Update(); } } }
412
0.551952
1
0.551952
game-dev
MEDIA
0.685913
game-dev,graphics-rendering
0.949783
1
0.949783
kennedyvnak/unity-metroidvania
4,905
Assets/Scripts/Modules/Entities/EntitiesManager.cs
using Metroidvania.Events; using System.Collections.Generic; using Unity.Mathematics; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; namespace Metroidvania.Entities { // Why don't I make the main character the only target? To not create dependencies and allow the creation of // a multiplayer system or others systems that include multiples targets in the future /// <summary>Class for make entity management. see also <see cref="Addressables"/></summary> public class EntitiesManager : ScriptableSingleton<EntitiesManager> { public delegate void OnEntityDelegate(EntityBehaviour entity); /// <summary>All available targets in scene</summary> public List<EntityTarget> targets { get; private set; } = new List<EntityTarget>(); /// <summary>All instantiated entities in scene</summary> public List<EntityBehaviour> entities { get; private set; } = new List<EntityBehaviour>(); /// <summary>Called when a target is added to the manager</summary> public ObjectEventChannel targetValidated; /// <summary>Called when a target is removed from the manager</summary> public ObjectEventChannel targetReleased; /// <summary>Called when a entity is instantiated by the manager. see also <see cref="InstantiateEntity"/></summary> public ObjectEventChannel entityInstantiated; /// <summary>Called when a entity is destroyed by the manager. see also <see cref="DestroyEntity"/></summary> public ObjectEventChannel entityDestroyed; /// <summary>Instantiate a new entity to the given position</summary> /// <param name="entityObject">Entity to be instantiated</param> /// <param name="position">Position where the entity will be instantiated in world position units</param> /// <param name="entityInstantiated">Event called when the entity is instantiated</param> /// <returns>The instantiation operation</returns> public AsyncOperationHandle<GameObject> InstantiateEntity(EntityObject entityObject, Vector2 position) { AsyncOperationHandle<GameObject> op = entityObject.prefab.InstantiateAsync(position, quaternion.identity); op.Completed += opHandle => { EntityBehaviour instantiatedEntity = opHandle.Result.GetComponent<EntityBehaviour>(); entities.Add(instantiatedEntity); entityInstantiated?.Raise(instantiatedEntity); }; return op; } /// <summary>Destroy the given entity</summary> /// <param name="entity">The entity that will be destroyed</param> public void DestroyEntity(EntityBehaviour entity) { if (!entities.Contains(entity)) return; entities.Remove(entity); entityDestroyed?.Raise(entity); Addressables.ReleaseInstance(entity.gameObject); } /// <summary>Add a target to the manager</summary> /// <param name="target">The target to be added</param> public void AddTarget(EntityTarget target) { if (targets.Contains(target)) return; targets.Add(target); targetValidated?.Raise(target); } /// <summary>Remove a target from the manager</summary> /// <param name="target">The target to be removed</param> public void RemoveTarget(EntityTarget target) { if (!targets.Contains(target)) return; targets.Remove(target); targetReleased?.Raise(target); } /// <summary>Get the closest available target in the scene</summary> /// <param name="position">The position to compare distances</param> /// <returns>The closest target in scene</returns> public EntityTarget GetClosestTarget(Vector2 position) { return targets.Count switch { // If has only one target, return it 1 => targets[0], // If there are no targets, returns null <= 0 => null, // If have more than one target, return the closest one > 1 => GetClosest() }; EntityTarget GetClosest() { EntityTarget closest = null; float curDistance = Mathf.Infinity; foreach (EntityTarget target in targets) { float distance = (position - (Vector2)target.t.position).sqrMagnitude; if (distance >= curDistance) continue; curDistance = distance; closest = target; } return closest; } } } }
412
0.89336
1
0.89336
game-dev
MEDIA
0.97621
game-dev
0.84634
1
0.84634
espeed/bulbs
5,355
bulbs/gremlin.groovy
// // Copyright 2012 James Thornton (http://jamesthornton.com) // BSD License (see LICENSE for details) // // Gremlin scripts in Gremlin-Groovy v1.3 // // See the Gremlin and Blueprints docs for the full Gremlin/Blueprints API. // // Gremlin Wiki: https://github.com/tinkerpop/gremlin/wiki // Gremlin Steps: https://github.com/tinkerpop/gremlin/wiki/Gremlin-Steps // Gremlin Methods: https://github.com/tinkerpop/gremlin/wiki/Gremlin-Methods // Blueprints Wiki: https://github.com/tinkerpop/blueprints/wiki // // Client-specific methods are defined at the client level. // e.g. neo4j/gremlin.groovy and rexster/gremlin.groovy // // Graph def get_vertices() { g.getVertices() } def get_edges() { g.getEdges() } // Vertices // These edge-label conditionals are a messy hack until Gremin allows null labels. // See https://github.com/tinkerpop/gremlin/issues/267 // the || label == "null" is a hack until Rexster fixes its null label bug. // See https://github.com/tinkerpop/rexster/issues/197 def outE(_id, label, start, limit) { if (label == null) pipe = g.v(_id).outE() else pipe = g.v(_id).outE(label) if (start != null && limit != null) pipe = pipe.range(start, start+limit-1) return pipe } def inE(_id, label, start, limit) { if (label == null) pipe = g.v(_id).inE() else pipe = g.v(_id).inE(label) if (start != null && limit != null) pipe = pipe.range(start, start+limit-1) return pipe } def bothE(_id, label, start, limit) { if (label == null) pipe = g.v(_id).bothE() else pipe = g.v(_id).bothE(label) if (start != null && limit != null) pipe = pipe.range(start, start+limit-1) return pipe } def outV(_id, label, start, limit) { if (label == null) pipe = g.v(_id).out() else pipe = g.v(_id).out(label) if (start != null && limit != null) pipe = pipe.range(start, start+limit-1) return pipe } def inV(_id, label, start, limit) { if (label == null) pipe = g.v(_id).in() else pipe = g.v(_id).in(label) if (start != null && limit != null) pipe = pipe.range(start, start+limit-1) return pipe } def bothV(_id, label, start, limit) { if (label == null) pipe = g.v(_id).both() else pipe = g.v(_id).both(label) if (start != null && limit != null) pipe = pipe.range(start, start+limit-1) return pipe } // Neo4j requires you delete all adjacent edges first. // Blueprints' removeVertex() method does that; the Neo4jServer DELETE URI does not. def delete_vertex(_id) { vertex = g.v(_id) g.removeVertex(vertex) } // Indices def index_count(index_name, key, value) { index = g.idx(index_name); return index.count(key,value); } def get_or_create_vertex_index(index_name, index_params) { def getOrCreateVertexIndex = { index = g.idx(index_name) if (index == null) { if (index_params == null) { index = g.createIndex(index_name, Vertex.class) } else { index = g.createIndex(index_name, Vertex.class, index_params) } } return index } def transaction = { final Closure closure -> try { results = closure(); g.commit(); return results; } catch (e) { g.rollback(); throw e; } } return transaction(getOrCreateVertexIndex); } def get_or_create_edge_index(index_name, index_params) { def getOrCreateEdgeIndex = { index = g.idx(index_name) if (index == null) { if (index_params == null) { index = g.createIndex(index_name, Edge.class) } else { index = g.createIndex(index_name, Edge.class, index_params) } } return index } def transaction = { final Closure closure -> try { results = closure(); g.commit(); return results; } catch (e) { g.rollback(); throw e; } } return transaction(getOrCreateEdgeIndex); } // Utils def warm_cache() { for (vertex in g.getVertices()) { vertex.getOutEdges() } } def load_graphml(uri) { g.loadGraphML(uri) } def save_graphml() { g.saveGraphML('bulbs.graphml') new File('bulbs.graphml').getText() } def clear() { g.clear() } // // Gremln user-defined steps // // You must execute the step definition script at least once before you // use the steps. For production use, this should really be defined server side. // // Tree Steps: inTree() and outTree() // See https://groups.google.com/d/topic/gremlin-users/iCPUifiU_wk/discussion // Obsoleted with the addition of the the TreePipe in Gremlin 1.6 // See https://groups.google.com/d/topic/gremlin-users/9s2YWsqK_Ro/discussion def define_tree_steps() { tree = { vertices -> def results = [] vertices.each() { results << it children = it."$direction"().toList() if (children) { child_tree = tree(children) results << child_tree } } results } inClosure = {final Object... params -> try { label = params[0] } catch(e){ label = null } results = [] direction = "in" _().transform{ tree(it) } } outClosure = {final Object... params -> try { label = params[0] } catch(e){ label = null } results = [] direction = "out" _().transform{ tree(it) } } Gremlin.defineStep("inTree", [Vertex,Pipe], inClosure) Gremlin.defineStep("outTree", [Vertex,Pipe], outClosure) }
412
0.877923
1
0.877923
game-dev
MEDIA
0.166448
game-dev
0.914093
1
0.914093
Grimrukh/SoulsAI
14,598
ai_scripts/m12_00_00_00/006802_battle.lua
REGISTER_GOAL(GOAL_ForestHunterSword6802_Battle, "ForestHunterSword6802Battle") local NormalR_min = 0 local NormalR_max = 2.1 local LargeR_min = 0 local LargeR_max = 3.2 local Whand_jyaku_min = 0 local Whand_jyaku_max = 2.4 local Whand_kyou_min = 0 local Whand_kyou_max = 1.9 local Backstep_Atk_min = 0 local Backstep_Atk_max = 1.1 local Backstep_AtkW_min = 0 local Backstep_AtkW_max = 1 local Rolling_Atk_min = 3.5 local Rolling_Atk_max = 4.5 local Rolling_AtkW_min = 4 local Rolling_AtkW_max = 5 local PushR_min = 0 local PushR_max = 1 REGISTER_GOAL_NO_UPDATE(GOAL_ForestHunterSword6802_Battle, 1) function ForestHunterSword6802Battle_Activate(ai, goal) local actPerArr = {} local actFuncArr = {} local defFuncParamTbl = {} Common_Clear_Param(actPerArr, actFuncArr, defFuncParamTbl) local fate = ai:GetRandam_Int(1, 100) local fate2 = ai:GetRandam_Int(1, 100) local BothHandOff = ai:GetRandam_Int(1, 100) local targetDist = ai:GetDist(TARGET_ENE_0) local RYOUTE_odds = 1 local KATATE_odds = 1 if ai:IsTargetGuard(TARGET_ENE_0) == true then RYOUTE_odds = 10 end if 8 <= targetDist then actPerArr[1] = 20 * KATATE_odds actPerArr[2] = 30 * KATATE_odds actPerArr[7] = 10 * KATATE_odds actPerArr[9] = 20 * RYOUTE_odds actPerArr[10] = 30 * RYOUTE_odds actPerArr[15] = 10 * RYOUTE_odds elseif 4 <= targetDist then actPerArr[1] = 25 * KATATE_odds actPerArr[2] = 25 * KATATE_odds actPerArr[7] = 10 * KATATE_odds actPerArr[9] = 25 * RYOUTE_odds actPerArr[10] = 25 * RYOUTE_odds actPerArr[15] = 10 * RYOUTE_odds elseif 2.1 <= targetDist then actPerArr[1] = 25 * KATATE_odds actPerArr[2] = 25 * KATATE_odds actPerArr[9] = 25 * RYOUTE_odds actPerArr[10] = 25 * RYOUTE_odds elseif 1 <= targetDist then actPerArr[1] = 18 * KATATE_odds actPerArr[2] = 17 * KATATE_odds actPerArr[5] = 15 * KATATE_odds actPerArr[9] = 10 * RYOUTE_odds actPerArr[10] = 10 * RYOUTE_odds actPerArr[13] = 13 * KATATE_odds actPerArr[17] = 30 * RYOUTE_odds else actPerArr[1] = 20 * KATATE_odds actPerArr[2] = 20 * KATATE_odds actPerArr[5] = 10 * KATATE_odds actPerArr[17] = 20 * RYOUTE_odds end actFuncArr[1] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act01) actFuncArr[2] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act02) actFuncArr[5] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act05) actFuncArr[7] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act07) actFuncArr[9] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act09) actFuncArr[10] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act10) actFuncArr[13] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act13) actFuncArr[15] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act15) actFuncArr[17] = REGIST_FUNC(ai, goal, ForestHunterSword6802_Act17) local atkAfterFunc = REGIST_FUNC(ai, goal, ForestHunterSword6802_ActAfter_AdjustSpace, atkAfterOddsTbl) Common_Battle_Activate(ai, goal, actPerArr, actFuncArr, atkAfterFunc, defFuncParamTbl) return end NormalR_min = NormalR_max function ForestHunterSword6802_Act01(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) NPC_KATATE_Switch(ai, goal) CommonNPC_UseSecondaryLeftHand(ai, goal) local approachDist = NormalR_max local dashDist = NormalR_max + 5 local Odds_Guard = 50 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) if fate <= 40 then goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 1.5, 90) else goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 1.5, 90) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 0, -1) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = LargeR_max function ForestHunterSword6802_Act02(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) NPC_KATATE_Switch(ai, goal) CommonNPC_UseSecondaryLeftHand(ai, goal) local approachDist = LargeR_max local dashDist = LargeR_max + 5 local Odds_Guard = 50 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_LargeR, TARGET_ENE_0, DIST_Middle, 1.5, 90) GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = Backstep_Atk_max function ForestHunterSword6802_Act05(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) NPC_KATATE_Switch(ai, goal) CommonNPC_UseSecondaryLeftHand(ai, goal) local approachDist = Backstep_Atk_max local dashDist = Backstep_Atk_max + 5 local Odds_Guard = 50 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_BackstepB, TARGET_ENE_0, 6, 1.5, 90) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 0, -1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = Rolling_Atk_max function ForestHunterSword6802_Act07(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) NPC_KATATE_Switch(ai, goal) CommonNPC_UseSecondaryLeftHand(ai, goal) local approachDist = Rolling_Atk_max local dashDist = Rolling_Atk_max + 5 local Odds_Guard = 50 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_StepF, TARGET_ENE_0, 3, 1.5, 90) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 0, -1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = Whand_jyaku_max function ForestHunterSword6802_Act09(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) CommonNPC_UseSecondaryLeftHand(ai, goal) NPC_RYOUTE_Switch(ai, goal) local approachDist = Whand_jyaku_max local dashDist = Whand_jyaku_max + 5 local Odds_Guard = 50 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) if fate <= 40 then goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 1.5, 90) else goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 1.5, 90) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 0, -1) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = Whand_kyou_max function ForestHunterSword6802_Act10(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) CommonNPC_UseSecondaryLeftHand(ai, goal) NPC_RYOUTE_Switch(ai, goal) local approachDist = Whand_kyou_max local dashDist = Whand_kyou_max + 5 local Odds_Guard = 50 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_LargeR, TARGET_ENE_0, DIST_Middle, 1.5, 90) GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = Backstep_AtkW_max function ForestHunterSword6802_Act13(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) CommonNPC_UseSecondaryLeftHand(ai, goal) NPC_RYOUTE_Switch(ai, goal) local approachDist = Backstep_AtkW_max local dashDist = Backstep_AtkW_max + 5 local Odds_Guard = 100 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_BackstepB, TARGET_ENE_0, 6, 1.5, 90) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 0, -1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = Rolling_AtkW_max function ForestHunterSword6802_Act15(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) CommonNPC_UseSecondaryLeftHand(ai, goal) NPC_RYOUTE_Switch(ai, goal) local approachDist = Rolling_AtkW_max local dashDist = Rolling_AtkW_max + 5 local Odds_Guard = 100 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_StepF, TARGET_ENE_0, 3, 1.5, 90) goal:AddSubGoal(GOAL_COMMON_ComboFinal, 10, NPC_ATK_NormalR, TARGET_ENE_0, DIST_Middle, 0, -1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end NormalR_min = PushR_max function ForestHunterSword6802_Act17(ai, goal, paramTbl) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) local approachDist = PushR_max local dashDist = PushR_max + 5 local Odds_Guard = 100 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_PushR, TARGET_ENE_0, DIST_Middle, 1.5, 90) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function ForestHunterSword6802_ActAfter_AdjustSpace(ai, goal, paramTbl) local fate = ai:GetRandam_Int(1, 100) local fate2 = ai:GetRandam_Int(1, 100) local MoveDist = 3 if fate <= 5 then if fate2 <= 50 then goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, NPC_ATK_StepB, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 2) elseif fate2 <= 75 then goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, NPC_ATK_StepL, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 2) else goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, NPC_ATK_StepR, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 2) end elseif fate2 <= 70 then goal:AddSubGoal(GOAL_COMMON_LeaveTarget, 3, TARGET_ENE_0, ai:GetRandam_Float(2.5, 3.5), TARGET_ENE_0, true, 4) else goal:AddSubGoal(GOAL_COMMON_LeaveTarget, 6, TARGET_ENE_0, ai:GetRandam_Float(1.5, 3), TARGET_ENE_0, true, 4) goal:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, ai:GetRandam_Int(0, 1), ai:GetRandam_Int(30, 45), true, true, 4) end return end function ForestHunterSword6802Battle_Update(ai, goal) return GOAL_RESULT_Continue end function ForestHunterSword6802Battle_Terminate(ai, goal) return end NormalR_min = LargeR_max function ForestHunterSword6802Battle_Interupt(ai, goal) local targetDist = ai:GetDist(TARGET_ENE_0) local fate = ai:GetRandam_Int(1, 100) local fate2 = ai:GetRandam_Int(1, 100) local fate3 = ai:GetRandam_Int(1, 100) if ai:IsInterupt(INTERUPT_FindAttack) then local FindATKDist = 3 local FindATKPer = 10 local MoveDist = 3 if targetDist <= FindATKDist and fate <= FindATKPer then goal:ClearSubGoal() if fate <= 50 then goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, NPC_ATK_StepB, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 0) else goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, ai:GetRandam_Int(11, 12), TARGET_SELF, 0, AI_DIR_TYPE_F, 4) end return true end end if ai:IsInterupt(INTERUPT_SuccessGuard) then local Suc_GuardDist = 3 local Suc_GuardPer = 80 if targetDist <= Suc_GuardDist and fate <= Suc_GuardPer then goal:ClearSubGoal() goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_LargeR, TARGET_ENE_0, DIST_None, 0, -1) return true end end if ai:IsInterupt(INTERUPT_Damaged) then local combRunDist = 3 local combRunPer = 10 if targetDist < combRunDist and fate <= combRunPer then goal:ClearSubGoal() if fate <= 50 then goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, NPC_ATK_StepB, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 0) else goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, ai:GetRandam_Int(11, 12), TARGET_SELF, 0, AI_DIR_TYPE_F, 4) end end end if ai:IsInterupt(INTERUPT_GuardBreak) then local distGuardBreak_Act = 2 local oddsGuardBreak_Act = 100 if targetDist <= distGuardBreak_Act and fate <= oddsGuardBreak_Act then goal:ClearSubGoal() goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_LargeR, TARGET_ENE_0, DIST_Middle, 1.5, 90) return true end end if ai:IsInterupt(INTERUPT_ReboundByOpponentGuard) then local ResDist = 3 local ResPer = 10 if targetDist < ResDist then if fate <= ResPer then goal:ClearSubGoal() if fate2 <= ResPer then if fate3 <= 50 then goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, NPC_ATK_StepB, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 0) else goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, ai:GetRandam_Int(11, 12), TARGET_SELF, 0, AI_DIR_TYPE_F, 4) end else ai:Replaning() goal:AddSubGoal(GOAL_COMMON_Wait, 0.1, TARGET_ENE_0) return true end else goal:ClearSubGoal() goal:AddSubGoal(GOAL_COMMON_Wait, 0.1, TARGET_ENE_0) ai:Replaning() return true end else goal:ClearSubGoal() goal:AddSubGoal(GOAL_COMMON_Wait, 0.1, TARGET_ENE_0) ai:Replaning() return true end end if ai:IsInterupt(INTERUPT_Shoot) then local shootIntPer = 50 if fate <= shootIntPer then goal:ClearSubGoal() if fate <= 50 then goal:AddSubGoal(GOAL_COMMON_SpinStep, 10, ai:GetRandam_Int(11, 12), TARGET_SELF, 0, AI_DIR_TYPE_F, 4) else local approachDist = LargeR_max local dashDist = LargeR_max + 5 local Odds_Guard = 100 NPC_Approach_Act(ai, goal, approachDist, dashDist, Odds_Guard) goal:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, NPC_ATK_LargeR, TARGET_ENE_0, DIST_Middle, 1.5, 90) end return true end end return false end return
412
0.857055
1
0.857055
game-dev
MEDIA
0.973194
game-dev
0.875725
1
0.875725
magefree/mage
1,156
Mage.Sets/src/mage/cards/c/CobaltGolem.java
package mage.cards.c; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Zone; /** * * @author Loki */ public final class CobaltGolem extends CardImpl { public CobaltGolem(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT,CardType.CREATURE},"{4}"); this.subtype.add(SubType.GOLEM); this.power = new MageInt(2); this.toughness = new MageInt(3); this.addAbility(new SimpleActivatedAbility(new GainAbilitySourceEffect(FlyingAbility.getInstance(), Duration.EndOfTurn), new ManaCostsImpl<>("{1}{U}"))); } private CobaltGolem(final CobaltGolem card) { super(card); } @Override public CobaltGolem copy() { return new CobaltGolem(this); } }
412
0.899387
1
0.899387
game-dev
MEDIA
0.944646
game-dev
0.947065
1
0.947065
swgemu/Core3
1,064
MMOCoreORB/src/server/zone/objects/creature/commands/Saber1hComboHit2Command.h
/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #ifndef SABER1HCOMBOHIT2COMMAND_H_ #define SABER1HCOMBOHIT2COMMAND_H_ #include "JediCombatQueueCommand.h" class Saber1hComboHit2Command : public JediCombatQueueCommand { public: Saber1hComboHit2Command(const String& name, ZoneProcessServer* server) : JediCombatQueueCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const { if (!checkStateMask(creature)) return INVALIDSTATE; if (!checkInvalidLocomotions(creature)) return INVALIDLOCOMOTION; if (isWearingArmor(creature)) { return NOJEDIARMOR; } float mods[3] = {0.f, 0.f, 0.f}; for (int i = 0; i < 2; i++) mods[System::random(2)] += 0.5f; UnicodeString args = "healthDamageMultiplier=" + String::valueOf(mods[0]) + ";actionDamageMultiplier=" + String::valueOf(mods[1]) + ";mindDamageMultiplier=" + String::valueOf(mods[2]) + ";"; return doCombatAction(creature, target, args); } }; #endif //SABER1HCOMBOHIT2COMMAND_H_
412
0.852551
1
0.852551
game-dev
MEDIA
0.932733
game-dev
0.921234
1
0.921234
QuestionableM/SM-ProximityVoiceChat
11,259
Dependencies/bullet3/BulletCollision/CollisionShapes/btHeightfieldTerrainShape.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btHeightfieldTerrainShape.h" #include "LinearMath/btTransformUtil.h" btHeightfieldTerrainShape::btHeightfieldTerrainShape( int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis, PHY_ScalarType hdt, bool flipQuadEdges) { initialize(heightStickWidth, heightStickLength, heightfieldData, heightScale, minHeight, maxHeight, upAxis, hdt, flipQuadEdges); } btHeightfieldTerrainShape::btHeightfieldTerrainShape(int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar maxHeight, int upAxis, bool useFloatData, bool flipQuadEdges) { // legacy constructor: support only float or unsigned char, // and min height is zero PHY_ScalarType hdt = (useFloatData) ? PHY_FLOAT : PHY_UCHAR; btScalar minHeight = 0.0f; // previously, height = uchar * maxHeight / 65535. // So to preserve legacy behavior, heightScale = maxHeight / 65535 btScalar heightScale = maxHeight / 65535; initialize(heightStickWidth, heightStickLength, heightfieldData, heightScale, minHeight, maxHeight, upAxis, hdt, flipQuadEdges); } void btHeightfieldTerrainShape::initialize( int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis, PHY_ScalarType hdt, bool flipQuadEdges) { // validation btAssert(heightStickWidth > 1); // && "bad width"); btAssert(heightStickLength > 1); // && "bad length"); btAssert(heightfieldData); // && "null heightfield data"); // btAssert(heightScale) -- do we care? Trust caller here btAssert(minHeight <= maxHeight); // && "bad min/max height"); btAssert(upAxis >= 0 && upAxis < 3); // && "bad upAxis--should be in range [0,2]"); btAssert(hdt != PHY_UCHAR || hdt != PHY_FLOAT || hdt != PHY_SHORT); // && "Bad height data type enum"); // initialize member variables m_shapeType = TERRAIN_SHAPE_PROXYTYPE; m_heightStickWidth = heightStickWidth; m_heightStickLength = heightStickLength; m_minHeight = minHeight; m_maxHeight = maxHeight; m_width = (btScalar)(heightStickWidth - 1); m_length = (btScalar)(heightStickLength - 1); m_heightScale = heightScale; m_heightfieldDataUnknown = heightfieldData; m_heightDataType = hdt; m_flipQuadEdges = flipQuadEdges; m_useDiamondSubdivision = false; m_useZigzagSubdivision = false; m_upAxis = upAxis; m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.)); // determine min/max axis-aligned bounding box (aabb) values switch (m_upAxis) { case 0: { m_localAabbMin.setValue(m_minHeight, 0, 0); m_localAabbMax.setValue(m_maxHeight, m_width, m_length); break; } case 1: { m_localAabbMin.setValue(0, m_minHeight, 0); m_localAabbMax.setValue(m_width, m_maxHeight, m_length); break; }; case 2: { m_localAabbMin.setValue(0, 0, m_minHeight); m_localAabbMax.setValue(m_width, m_length, m_maxHeight); break; } default: { //need to get valid m_upAxis btAssert(0); // && "Bad m_upAxis"); } } // remember origin (defined as exact middle of aabb) m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax); } btHeightfieldTerrainShape::~btHeightfieldTerrainShape() { } void btHeightfieldTerrainShape::getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const { btVector3 halfExtents = (m_localAabbMax - m_localAabbMin) * m_localScaling * btScalar(0.5); btVector3 localOrigin(0, 0, 0); localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5); localOrigin *= m_localScaling; btMatrix3x3 abs_b = t.getBasis().absolute(); btVector3 center = t.getOrigin(); btVector3 extent = halfExtents.dot3(abs_b[0], abs_b[1], abs_b[2]); extent += btVector3(getMargin(), getMargin(), getMargin()); aabbMin = center - extent; aabbMax = center + extent; } /// This returns the "raw" (user's initial) height, not the actual height. /// The actual height needs to be adjusted to be relative to the center /// of the heightfield's AABB. btScalar btHeightfieldTerrainShape::getRawHeightFieldValue(int x, int y) const { btScalar val = 0.f; switch (m_heightDataType) { case PHY_FLOAT: { val = m_heightfieldDataFloat[(y * m_heightStickWidth) + x]; break; } case PHY_UCHAR: { unsigned char heightFieldValue = m_heightfieldDataUnsignedChar[(y * m_heightStickWidth) + x]; val = heightFieldValue * m_heightScale; break; } case PHY_SHORT: { short hfValue = m_heightfieldDataShort[(y * m_heightStickWidth) + x]; val = hfValue * m_heightScale; break; } default: { btAssert(!"Bad m_heightDataType"); } } return val; } /// this returns the vertex in bullet-local coordinates void btHeightfieldTerrainShape::getVertex(int x, int y, btVector3& vertex) const { btAssert(x >= 0); btAssert(y >= 0); btAssert(x < m_heightStickWidth); btAssert(y < m_heightStickLength); btScalar height = getRawHeightFieldValue(x, y); switch (m_upAxis) { case 0: { vertex.setValue( height - m_localOrigin.getX(), (-m_width / btScalar(2.0)) + x, (-m_length / btScalar(2.0)) + y); break; } case 1: { vertex.setValue( (-m_width / btScalar(2.0)) + x, height - m_localOrigin.getY(), (-m_length / btScalar(2.0)) + y); break; }; case 2: { vertex.setValue( (-m_width / btScalar(2.0)) + x, (-m_length / btScalar(2.0)) + y, height - m_localOrigin.getZ()); break; } default: { //need to get valid m_upAxis btAssert(0); } } vertex *= m_localScaling; } static inline int getQuantized( btScalar x) { if (x < 0.0) { return (int)(x - 0.5); } return (int)(x + 0.5); } /// given input vector, return quantized version /** This routine is basically determining the gridpoint indices for a given input vector, answering the question: "which gridpoint is closest to the provided point?". "with clamp" means that we restrict the point to be in the heightfield's axis-aligned bounding box. */ void btHeightfieldTerrainShape::quantizeWithClamp(int* out, const btVector3& point, int /*isMax*/) const { btVector3 clampedPoint(point); clampedPoint.setMax(m_localAabbMin); clampedPoint.setMin(m_localAabbMax); out[0] = getQuantized(clampedPoint.getX()); out[1] = getQuantized(clampedPoint.getY()); out[2] = getQuantized(clampedPoint.getZ()); } /// process all triangles within the provided axis-aligned bounding box /** basic algorithm: - convert input aabb to local coordinates (scale down and shift for local origin) - convert input aabb to a range of heightfield grid points (quantize) - iterate over all triangles in that subset of the grid */ void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const { // scale down the input aabb's so they are in local (non-scaled) coordinates btVector3 localAabbMin = aabbMin * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]); btVector3 localAabbMax = aabbMax * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]); // account for local origin localAabbMin += m_localOrigin; localAabbMax += m_localOrigin; //quantize the aabbMin and aabbMax, and adjust the start/end ranges int quantizedAabbMin[3]; int quantizedAabbMax[3]; quantizeWithClamp(quantizedAabbMin, localAabbMin, 0); quantizeWithClamp(quantizedAabbMax, localAabbMax, 1); // expand the min/max quantized values // this is to catch the case where the input aabb falls between grid points! for (int i = 0; i < 3; ++i) { quantizedAabbMin[i]--; quantizedAabbMax[i]++; } int startX = 0; int endX = m_heightStickWidth - 1; int startJ = 0; int endJ = m_heightStickLength - 1; switch (m_upAxis) { case 0: { if (quantizedAabbMin[1] > startX) startX = quantizedAabbMin[1]; if (quantizedAabbMax[1] < endX) endX = quantizedAabbMax[1]; if (quantizedAabbMin[2] > startJ) startJ = quantizedAabbMin[2]; if (quantizedAabbMax[2] < endJ) endJ = quantizedAabbMax[2]; break; } case 1: { if (quantizedAabbMin[0] > startX) startX = quantizedAabbMin[0]; if (quantizedAabbMax[0] < endX) endX = quantizedAabbMax[0]; if (quantizedAabbMin[2] > startJ) startJ = quantizedAabbMin[2]; if (quantizedAabbMax[2] < endJ) endJ = quantizedAabbMax[2]; break; }; case 2: { if (quantizedAabbMin[0] > startX) startX = quantizedAabbMin[0]; if (quantizedAabbMax[0] < endX) endX = quantizedAabbMax[0]; if (quantizedAabbMin[1] > startJ) startJ = quantizedAabbMin[1]; if (quantizedAabbMax[1] < endJ) endJ = quantizedAabbMax[1]; break; } default: { //need to get valid m_upAxis btAssert(0); } } for (int j = startJ; j < endJ; j++) { for (int x = startX; x < endX; x++) { btVector3 vertices[3]; if (m_flipQuadEdges || (m_useDiamondSubdivision && !((j + x) & 1)) || (m_useZigzagSubdivision && !(j & 1))) { //first triangle getVertex(x, j, vertices[0]); getVertex(x, j + 1, vertices[1]); getVertex(x + 1, j + 1, vertices[2]); callback->processTriangle(vertices, x, j); //second triangle // getVertex(x,j,vertices[0]);//already got this vertex before, thanks to Danny Chapman getVertex(x + 1, j + 1, vertices[1]); getVertex(x + 1, j, vertices[2]); callback->processTriangle(vertices, x, j); } else { //first triangle getVertex(x, j, vertices[0]); getVertex(x, j + 1, vertices[1]); getVertex(x + 1, j, vertices[2]); callback->processTriangle(vertices, x, j); //second triangle getVertex(x + 1, j, vertices[0]); //getVertex(x,j+1,vertices[1]); getVertex(x + 1, j + 1, vertices[2]); callback->processTriangle(vertices, x, j); } } } } void btHeightfieldTerrainShape::calculateLocalInertia(btScalar, btVector3& inertia) const { //moving concave objects not supported inertia.setValue(btScalar(0.), btScalar(0.), btScalar(0.)); } void btHeightfieldTerrainShape::setLocalScaling(const btVector3& scaling) { m_localScaling = scaling; } const btVector3& btHeightfieldTerrainShape::getLocalScaling() const { return m_localScaling; }
412
0.978971
1
0.978971
game-dev
MEDIA
0.984536
game-dev
0.997151
1
0.997151
wanghongfei/gae
3,105
src/main/java/org/fh/gae/query/index/idea/UnitIdeaRelIndex.java
package org.fh.gae.query.index.idea; import org.fh.gae.query.index.GaeIndex; import org.fh.gae.query.index.unit.AdUnitInfo; import org.fh.gae.query.session.ThreadCtx; import org.fh.gae.query.utils.GaeCollectionUtils; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; @Component public class UnitIdeaRelIndex implements GaeIndex<UnitIdeaRelInfo> { public static final int LEVEL = 5; private Map<Integer, Set<String>> unitIdeaMap; @PostConstruct private void init() { unitIdeaMap = new ConcurrentHashMap<>(); } @Override public int getLevel() { return LEVEL; } @Override public int getLength() { return 2; } public Set<String> fetchIdeaIds(Set<AdUnitInfo> unitInfoSet) { Set<String> resultSet = new HashSet<>(unitInfoSet.size() + unitInfoSet.size() / 3); Map<Integer, Integer> wMap = ThreadCtx.getWeightMap(); Map<String, AdUnitInfo> ideaInfoMap = new HashMap<>(); ThreadCtx.putContext(ThreadCtx.KEY_IDEA, ideaInfoMap); for (AdUnitInfo unitInfo : unitInfoSet ) { // 得到单元下所有创意 Set<String> idSet = unitIdeaMap.get(unitInfo.getUnitId()); if (!CollectionUtils.isEmpty(idSet)) { resultSet.addAll(idSet); // 如果一个创意被多个单元绑定 // 则出权重最高的单元下的创意 for (String ideaId : idSet) { AdUnitInfo info = ideaInfoMap.get(ideaId); if (null == info) { ideaInfoMap.put(ideaId, unitInfo); } else { Integer oldWeight = wMap.get(info.getUnitId()); Integer newWeight = wMap.get(unitInfo.getUnitId()); if (null != oldWeight && null != newWeight) { ideaInfoMap.put(ideaId, newWeight > oldWeight ? unitInfo :info); } } } } } return resultSet; } @Override public UnitIdeaRelInfo packageInfo(String[] tokens) { Integer unitId = Integer.valueOf(tokens[2]); String ideaId = tokens[3]; return new UnitIdeaRelInfo(unitId, ideaId); } @Override public void add(UnitIdeaRelInfo info) { Set<String> ideaSet = GaeCollectionUtils.getAndCreateIfNeed( info.getUnitId(), unitIdeaMap, () -> new ConcurrentSkipListSet<>() ); ideaSet.add(info.getIdeaId()); } @Override public void update(UnitIdeaRelInfo info) { throw new IllegalStateException("unit idea relation index cannot be updated"); } @Override public void delete(UnitIdeaRelInfo info) { unitIdeaMap.get(info.getUnitId()).remove(info.getIdeaId()); } }
412
0.898295
1
0.898295
game-dev
MEDIA
0.463084
game-dev
0.939103
1
0.939103
2881099/FreeSql.Cloud
3,009
examples/net40_tcc_saga/BuyTccUnit.cs
using FreeSql; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace net60_tcc_saga { class TccUnit1State { public int UserId { get; set; } public int Point { get; set; } public Guid BuyLogId { get; set; } public int GoodsId { get; set; } public Guid OrderId { get; set; } } [Description("第1步:数据库db1 扣除用户积分")] class Tcc1 : TccUnit<TccUnit1State> { public override void Try() { var affrows = Orm.Update<User>() .Set(a => a.Point - State.Point) .Where(a => a.Id == State.UserId && a.Point >= State.Point) .ExecuteAffrows(); if (affrows <= 0) throw new Exception("扣除积分失败"); //记录积分变动日志? } public override void Confirm() { } public override void Cancel() { Orm.Update<User>() .Set(a => a.Point + State.Point) .Where(a => a.Id == State.UserId) .ExecuteAffrows(); //退还积分 //记录积分变动日志? } } class TccUnit2State { public int UserId { get; set; } public int Point { get; set; } public Guid BuyLogId { get; set; } public int GoodsId { get; set; } public Guid OrderId { get; set; } } [Description("第2步:数据库db2 扣除库存")] class Tcc2 : TccUnit<TccUnit2State> { public override void Try() { var affrows = Orm.Update<Goods>() .Set(a => a.Stock - 1) .Where(a => a.Id == State.GoodsId && a.Stock >= 1) .ExecuteAffrows(); if (affrows <= 0) throw new Exception("扣除库存失败"); } public override void Confirm() { } public override void Cancel() { Orm.Update<Goods>() .Set(a => a.Stock + 1) .Where(a => a.Id == State.GoodsId) .ExecuteAffrows(); //退还库存 } } class TccUnit3State { public int UserId { get; set; } public int Point { get; set; } public Guid BuyLogId { get; set; } public int GoodsId { get; set; } public Guid OrderId { get; set; } } [Description("第3步:数据库db3 创建订单")] class Tcc3 : TccUnit<TccUnit3State> { public override void Try() { Orm.Insert(new Order { Id = State.OrderId, Status = Order.OrderStatus.Pending, CreateTime = DateTime.Now }) .ExecuteAffrows(); } public override void Confirm() { //幂等交付 Orm.Update<Order>() .Set(a => a.Status == Order.OrderStatus.Success) .Where(a => a.Id == State.OrderId && a.Status == Order.OrderStatus.Pending) .ExecuteAffrows(); } public override void Cancel() { } } }
412
0.677718
1
0.677718
game-dev
MEDIA
0.353392
game-dev
0.808815
1
0.808815
GarageGames/Qt
2,142
qt-5/qtwebengine/src/3rdparty/chromium/ui/views/controls/webview/unhandled_keyboard_event_handler.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "content/public/browser/native_web_keyboard_event.h" #include "ui/views/focus/focus_manager.h" namespace views { UnhandledKeyboardEventHandler::UnhandledKeyboardEventHandler() : ignore_next_char_event_(false) { } UnhandledKeyboardEventHandler::~UnhandledKeyboardEventHandler() { } void UnhandledKeyboardEventHandler::HandleKeyboardEvent( const content::NativeWebKeyboardEvent& event, FocusManager* focus_manager) { if (!focus_manager) { NOTREACHED(); return; } // Previous calls to TranslateMessage can generate Char events as well as // RawKeyDown events, even if the latter triggered an accelerator. In these // cases, we discard the Char events. if (event.type == blink::WebInputEvent::Char && ignore_next_char_event_) { ignore_next_char_event_ = false; return; } // It's necessary to reset this flag, because a RawKeyDown event may not // always generate a Char event. ignore_next_char_event_ = false; if (event.type == blink::WebInputEvent::RawKeyDown) { ui::Accelerator accelerator( static_cast<ui::KeyboardCode>(event.windowsKeyCode), content::GetModifiersFromNativeWebKeyboardEvent(event)); // This is tricky: we want to set ignore_next_char_event_ if // ProcessAccelerator returns true. But ProcessAccelerator might delete // |this| if the accelerator is a "close tab" one. So we speculatively // set the flag and fix it if no event was handled. ignore_next_char_event_ = true; if (focus_manager->ProcessAccelerator(accelerator)) { return; } // ProcessAccelerator didn't handle the accelerator, so we know both // that |this| is still valid, and that we didn't want to set the flag. ignore_next_char_event_ = false; } if (event.os_event && !event.skip_in_browser) HandleNativeKeyboardEvent(event.os_event, focus_manager); } } // namespace views
412
0.737697
1
0.737697
game-dev
MEDIA
0.440789
game-dev
0.797917
1
0.797917
CalamityTeam/CalamityModPublic
1,569
Tiles/Furniture/EffigyOfDecayPlaceable.cs
using CalamityMod.Buffs.Placeables; using CalamityMod.Items.Placeables.Furniture; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.Enums; using Terraria.Localization; using Terraria.ModLoader; using Terraria.ObjectData; namespace CalamityMod.Tiles.Furniture { public class EffigyOfDecayPlaceable : ModTile { public override void SetStaticDefaults() { Main.tileLighted[Type] = true; Main.tileFrameImportant[Type] = true; Main.tileLavaDeath[Type] = true; TileObjectData.newTile.Width = 2; TileObjectData.newTile.Height = 4; TileObjectData.newTile.CoordinateHeights = new int[] { 16, 16, 16, 16 }; TileObjectData.newTile.CoordinateWidth = 16; TileObjectData.newTile.CoordinatePadding = 2; TileObjectData.newTile.Origin = new Point16(0, 3); TileObjectData.newTile.UsesCustomCanPlace = true; TileObjectData.newTile.AnchorBottom = new AnchorData(AnchorType.SolidTile | AnchorType.SolidWithTop, 2, 0); TileObjectData.addTile(Type); AddMapEntry(new Color(113, 90, 71), CalamityUtils.GetItemName<EffigyOfDecay>()); } public override void NearbyEffects(int i, int j, bool closer) { Player player = Main.LocalPlayer; if (player is null) return; if (!player.dead && player.active) player.AddBuff(ModContent.BuffType<EffigyOfDecayBuff>(), 20); } } }
412
0.695963
1
0.695963
game-dev
MEDIA
0.975351
game-dev
0.622018
1
0.622018
id-Software/Enemy-Territory
35,010
src/cgame/cg_predict.c
/* =========================================================================== Wolfenstein: Enemy Territory GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Wolfenstein: Enemy Territory GPL Source Code (“Wolf ET Source Code”). Wolf ET 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. Wolf ET 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 Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Wolf: ET 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 Wolf ET 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. =========================================================================== */ // cg_predict.c -- this file generates cg.predictedPlayerState by either // interpolating between snapshots from the server or locally predicting // ahead the client's movement. // It also handles local physics interaction, like fragments bouncing off walls #include "cg_local.h" /*static*/ pmove_t cg_pmove; static int cg_numSolidEntities; static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; static int cg_numSolidFTEntities; static centity_t *cg_solidFTEntities[MAX_ENTITIES_IN_SNAPSHOT]; static int cg_numTriggerEntities; static centity_t *cg_triggerEntities[MAX_ENTITIES_IN_SNAPSHOT]; /* ==================== CG_BuildSolidList When a new cg.snap has been set, this function builds a sublist of the entities that are actually solid, to make for more efficient collision detection ==================== */ void CG_BuildSolidList( void ) { int i; centity_t *cent; snapshot_t *snap; entityState_t *ent; cg_numSolidEntities = 0; cg_numSolidFTEntities = 0; cg_numTriggerEntities = 0; if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) { snap = cg.nextSnap; } else { snap = cg.snap; } for ( i = 0 ; i < snap->numEntities ; i++ ) { cent = &cg_entities[ snap->entities[ i ].number ]; ent = &cent->currentState; // rain - don't clip against temporarily non-solid SOLID_BMODELS // (e.g. constructibles); use current state so prediction isn't fubar if ( cent->currentState.solid == SOLID_BMODEL && ( cent->currentState.eFlags & EF_NONSOLID_BMODEL ) ) { continue; } if ( ent->eType == ET_ITEM || ent->eType == ET_PUSH_TRIGGER || ent->eType == ET_TELEPORT_TRIGGER || ent->eType == ET_CONCUSSIVE_TRIGGER || ent->eType == ET_OID_TRIGGER #ifdef VISIBLE_TRIGGERS || ent->eType == ET_TRIGGER_MULTIPLE || ent->eType == ET_TRIGGER_FLAGONLY || ent->eType == ET_TRIGGER_FLAGONLY_MULTIPLE #endif // VISIBLE_TRIGGERS ) { cg_triggerEntities[cg_numTriggerEntities] = cent; cg_numTriggerEntities++; continue; } if ( ent->eType == ET_CONSTRUCTIBLE ) { cg_triggerEntities[cg_numTriggerEntities] = cent; cg_numTriggerEntities++; } if ( cent->nextState.solid ) { /* if(cg_fastSolids.integer) { // Gordon: "optimization" (disabling until i fix it) vec3_t vec; float len; cg_solidFTEntities[cg_numSolidFTEntities] = cent; cg_numSolidFTEntities++; // FIXME: use range to bbox, not to origin if ( cent->nextState.solid == SOLID_BMODEL ) { VectorAdd( cgs.inlineModelMidpoints[ cent->currentState.modelindex ], cent->lerpOrigin, vec ); VectorSubtract( vec, cg.predictedPlayerEntity.lerpOrigin, vec ); } else { VectorSubtract( cent->lerpOrigin, cg.predictedPlayerEntity.lerpOrigin, vec ); } if((len = DotProduct( vec, vec )) < (512 * 512)) { cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; continue; } } else*/{ cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; cg_solidFTEntities[cg_numSolidFTEntities] = cent; cg_numSolidFTEntities++; continue; } } } } /* ==================== CG_ClipMoveToEntities ==================== */ static void CG_ClipMoveToEntities( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask, int capsule, trace_t *tr ) { int i, x, zd, zu; trace_t trace; entityState_t *ent; clipHandle_t cmodel; vec3_t bmins, bmaxs; vec3_t origin, angles; centity_t *cent; for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { cent = cg_solidEntities[ i ]; ent = &cent->currentState; if ( ent->number == skipNumber ) { continue; } if ( ent->solid == SOLID_BMODEL ) { // special value for bmodel cmodel = trap_CM_InlineModel( ent->modelindex ); // VectorCopy( cent->lerpAngles, angles ); // VectorCopy( cent->lerpOrigin, origin ); BG_EvaluateTrajectory( &cent->currentState.apos, cg.physicsTime, angles, qtrue, cent->currentState.effect2Time ); BG_EvaluateTrajectory( &cent->currentState.pos, cg.physicsTime, origin, qfalse, cent->currentState.effect2Time ); } else { // encoded bbox x = ( ent->solid & 255 ); zd = ( ( ent->solid >> 8 ) & 255 ); zu = ( ( ent->solid >> 16 ) & 255 ) - 32; bmins[0] = bmins[1] = -x; bmaxs[0] = bmaxs[1] = x; bmins[2] = -zd; bmaxs[2] = zu; //cmodel = trap_CM_TempCapsuleModel( bmins, bmaxs ); cmodel = trap_CM_TempBoxModel( bmins, bmaxs ); VectorCopy( vec3_origin, angles ); VectorCopy( cent->lerpOrigin, origin ); } // MrE: use bbox of capsule if ( capsule ) { trap_CM_TransformedCapsuleTrace( &trace, start, end, mins, maxs, cmodel, mask, origin, angles ); } else { trap_CM_TransformedBoxTrace( &trace, start, end, mins, maxs, cmodel, mask, origin, angles ); } if ( trace.allsolid || trace.fraction < tr->fraction ) { trace.entityNum = ent->number; *tr = trace; } else if ( trace.startsolid ) { tr->startsolid = qtrue; } if ( tr->allsolid ) { return; } } } static void CG_ClipMoveToEntities_FT( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask, int capsule, trace_t *tr ) { int i, x, zd, zu; trace_t trace; entityState_t *ent; clipHandle_t cmodel; vec3_t bmins, bmaxs; vec3_t origin, angles; centity_t *cent; for ( i = 0 ; i < cg_numSolidFTEntities ; i++ ) { cent = cg_solidFTEntities[ i ]; ent = &cent->currentState; if ( ent->number == skipNumber ) { continue; } if ( ent->solid == SOLID_BMODEL ) { // special value for bmodel cmodel = trap_CM_InlineModel( ent->modelindex ); // VectorCopy( cent->lerpAngles, angles ); // VectorCopy( cent->lerpOrigin, origin ); BG_EvaluateTrajectory( &cent->currentState.apos, cg.physicsTime, angles, qtrue, cent->currentState.effect2Time ); BG_EvaluateTrajectory( &cent->currentState.pos, cg.physicsTime, origin, qfalse, cent->currentState.effect2Time ); } else { // encoded bbox x = ( ent->solid & 255 ); zd = ( ( ent->solid >> 8 ) & 255 ); zu = ( ( ent->solid >> 16 ) & 255 ) - 32; bmins[0] = bmins[1] = -x; bmaxs[0] = bmaxs[1] = x; bmins[2] = -zd; bmaxs[2] = zu; cmodel = trap_CM_TempCapsuleModel( bmins, bmaxs ); VectorCopy( vec3_origin, angles ); VectorCopy( cent->lerpOrigin, origin ); } // MrE: use bbox of capsule if ( capsule ) { trap_CM_TransformedCapsuleTrace( &trace, start, end, mins, maxs, cmodel, mask, origin, angles ); } else { trap_CM_TransformedBoxTrace( &trace, start, end, mins, maxs, cmodel, mask, origin, angles ); } if ( trace.allsolid || trace.fraction < tr->fraction ) { trace.entityNum = ent->number; *tr = trace; } else if ( trace.startsolid ) { tr->startsolid = qtrue; } if ( tr->allsolid ) { return; } } } /* ================ CG_Trace ================ */ void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask ) { trace_t t; trap_CM_BoxTrace( &t, start, end, mins, maxs, 0, mask ); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models CG_ClipMoveToEntities( start, mins, maxs, end, skipNumber, mask, qfalse, &t ); *result = t; } void CG_Trace_World( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask ) { trace_t t; trap_CM_BoxTrace( &t, start, end, mins, maxs, 0, mask ); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; *result = t; } void CG_FTTrace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask ) { trace_t t; trap_CM_BoxTrace( &t, start, end, mins, maxs, 0, mask ); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models CG_ClipMoveToEntities_FT( start, mins, maxs, end, skipNumber, mask, qfalse, &t ); *result = t; } /* ================ CG_TraceCapsule ================ */ void CG_TraceCapsule( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask ) { trace_t t; trap_CM_CapsuleTrace( &t, start, end, mins, maxs, 0, mask ); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models CG_ClipMoveToEntities( start, mins, maxs, end, skipNumber, mask, qtrue, &t ); *result = t; } void CG_TraceCapsule_World( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask ) { trace_t t; trap_CM_CapsuleTrace( &t, start, end, mins, maxs, 0, mask ); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; *result = t; } /* ================ CG_PointContents ================ */ int CG_PointContents( const vec3_t point, int passEntityNum ) { int i; entityState_t *ent; centity_t *cent; clipHandle_t cmodel; int contents; contents = trap_CM_PointContents( point, 0 ); for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { cent = cg_solidEntities[ i ]; ent = &cent->currentState; if ( ent->number == passEntityNum ) { continue; } if ( ent->solid != SOLID_BMODEL ) { // special value for bmodel continue; } cmodel = trap_CM_InlineModel( ent->modelindex ); if ( !cmodel ) { continue; } contents |= trap_CM_TransformedPointContents( point, cmodel, cent->lerpOrigin, cent->lerpAngles ); // Gordon: again, need to use the projected water position to allow for moving entity based water. // contents |= trap_CM_TransformedPointContents( point, cmodel, ent->origin, ent->angles ); } return contents; } /* ======================== CG_InterpolatePlayerState Generates cg.predictedPlayerState by interpolating between cg.snap->player_state and cg.nextFrame->player_state ======================== */ static void CG_InterpolatePlayerState( qboolean grabAngles ) { float f; int i; playerState_t *out; snapshot_t *prev, *next; out = &cg.predictedPlayerState; prev = cg.snap; next = cg.nextSnap; *out = cg.snap->ps; if ( cg.showGameView ) { return; } // if we are still allowing local input, short circuit the view angles if ( grabAngles ) { usercmd_t cmd; int cmdNum; cmdNum = trap_GetCurrentCmdNumber(); trap_GetUserCmd( cmdNum, &cmd ); // rain - added tracemask PM_UpdateViewAngles( out, &cg.pmext, &cmd, CG_Trace, MASK_PLAYERSOLID ); } // if the next frame is a teleport, we can't lerp to it if ( cg.nextFrameTeleport ) { return; } if ( !next || next->serverTime <= prev->serverTime ) { return; } f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime ); i = next->ps.bobCycle; if ( i < prev->ps.bobCycle ) { i += 256; // handle wraparound } out->bobCycle = prev->ps.bobCycle + f * ( i - prev->ps.bobCycle ); for ( i = 0 ; i < 3 ; i++ ) { out->origin[i] = prev->ps.origin[i] + f * ( next->ps.origin[i] - prev->ps.origin[i] ); if ( !grabAngles ) { out->viewangles[i] = LerpAngle( prev->ps.viewangles[i], next->ps.viewangles[i], f ); } out->velocity[i] = prev->ps.velocity[i] + f * ( next->ps.velocity[i] - prev->ps.velocity[i] ); } } /* =================== CG_TouchItem =================== */ static void CG_TouchItem( centity_t *cent ) { gitem_t *item; return; if ( !cg_predictItems.integer ) { return; } if ( !cg_autoactivate.integer ) { return; } if ( !BG_PlayerTouchesItem( &cg.predictedPlayerState, &cent->currentState, cg.time ) ) { return; } // never pick an item up twice in a prediction if ( cent->miscTime == cg.time ) { return; } if ( !BG_CanItemBeGrabbed( &cent->currentState, &cg.predictedPlayerState, cgs.clientinfo[cg.snap->ps.clientNum].skill, cgs.clientinfo[cg.snap->ps.clientNum].team ) ) { return; // can't hold it } item = &bg_itemlist[ cent->currentState.modelindex ]; // force activate only for weapons you don't have if ( item->giType == IT_WEAPON ) { if ( item->giTag != WP_AMMO ) { if ( !COM_BitCheck( cg.predictedPlayerState.weapons, item->giTag ) ) { return; // force activate only } } } // OSP - Do it here rather than forcing gamestate into BG_CanItemBeGrabbed if ( cgs.gamestate != GS_PLAYING && item->giType != IT_WEAPON && item->giType != IT_AMMO && item->giType != IT_HEALTH ) { return; } // OSP - special case for panzers, as server may not allow us to pick them up // let the server tell us for sure that we got it if ( item->giType == IT_WEAPON && item->giTag == WP_PANZERFAUST ) { return; } // (SA) no prediction of books/clipboards if ( item->giType == IT_HOLDABLE ) { if ( item->giTag >= HI_BOOK1 && item->giTag <= HI_BOOK3 ) { return; } } // (SA) treasure needs to be activeated, no touch if ( item->giType == IT_TREASURE ) { return; } // Special case for flags. // We don't predict touching our own flag if ( cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_AXIS && item->giTag == PW_REDFLAG ) { return; } if ( cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_ALLIES && item->giTag == PW_BLUEFLAG ) { return; } // grab it BG_AddPredictableEventToPlayerstate( EV_ITEM_PICKUP, cent->currentState.modelindex, &cg.predictedPlayerState ); // remove it from the frame so it won't be drawn cent->currentState.eFlags |= EF_NODRAW; // don't touch it again this prediction cent->miscTime = cg.time; // if its a weapon, give them some predicted ammo so the autoswitch will work if ( item->giType == IT_WEAPON ) { COM_BitSet( cg.predictedPlayerState.weapons, item->giTag ); if ( !cg.predictedPlayerState.ammo[ BG_FindAmmoForWeapon( item->giTag )] ) { cg.predictedPlayerState.ammo[ BG_FindAmmoForWeapon( item->giTag )] = 1; } } } void CG_AddDirtBulletParticles( vec3_t origin, vec3_t dir, int speed, int duration, int count, float randScale, float width, float height, float alpha, qhandle_t shader ); /* ========================= CG_TouchTriggerPrediction Predict push triggers and items ========================= */ static void CG_TouchTriggerPrediction( void ) { int i; // trace_t trace; entityState_t *ent; clipHandle_t cmodel; centity_t *cent; qboolean spectator; // vec3_t mins, maxs; // TTimo: unused const char *cs; // dead clients don't activate triggers if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) { return; } spectator = ( ( cg.predictedPlayerState.pm_type == PM_SPECTATOR ) || ( cg.predictedPlayerState.pm_flags & PMF_LIMBO ) ); // JPW NERVE if ( cg.predictedPlayerState.pm_type != PM_NORMAL && !spectator ) { return; } for ( i = 0 ; i < cg_numTriggerEntities ; i++ ) { cent = cg_triggerEntities[ i ]; ent = &cent->currentState; if ( ent->eType == ET_ITEM && !spectator && ( cg.predictedPlayerState.groundEntityNum == ENTITYNUM_WORLD ) ) { CG_TouchItem( cent ); continue; } if ( ent->solid != SOLID_BMODEL ) { continue; } // Gordon: er, this lookup was wrong... cmodel = cgs.inlineDrawModel[ ent->modelindex ]; // cmodel = trap_CM_InlineModel( ent->modelindex ); if ( !cmodel ) { continue; } if ( ent->eType == ET_CONSTRUCTIBLE || ent->eType == ET_OID_TRIGGER #ifdef VISIBLE_TRIGGERS || ent->eType == ET_TRIGGER_MULTIPLE || ent->eType == ET_TRIGGER_FLAGONLY || ent->eType == ET_TRIGGER_FLAGONLY_MULTIPLE #endif // VISIBLE_TRIGGERS ) { vec3_t mins, maxs, pmins, pmaxs; if ( ent->eType == ET_CONSTRUCTIBLE && ent->aiState ) { continue; } trap_R_ModelBounds( cmodel, mins, maxs ); VectorAdd( cent->lerpOrigin, mins, mins ); VectorAdd( cent->lerpOrigin, maxs, maxs ); #ifdef VISIBLE_TRIGGERS if ( ent->eType == ET_TRIGGER_MULTIPLE || ent->eType == ET_TRIGGER_FLAGONLY || ent->eType == ET_TRIGGER_FLAGONLY_MULTIPLE ) { } else #endif // VISIBLE_TRIGGERS { // expand the bbox a bit VectorSet( mins, mins[0] - 48, mins[1] - 48, mins[2] - 48 ); VectorSet( maxs, maxs[0] + 48, maxs[1] + 48, maxs[2] + 48 ); } VectorAdd( cg.predictedPlayerState.origin, cg_pmove.mins, pmins ); VectorAdd( cg.predictedPlayerState.origin, cg_pmove.maxs, pmaxs ); #ifdef VISIBLE_TRIGGERS CG_RailTrail( NULL, mins, maxs, 1 ); #endif // VISIBLE_TRIGGERS if ( !BG_BBoxCollision( pmins, pmaxs, mins, maxs ) ) { continue; } cs = NULL; if ( ent->eType == ET_OID_TRIGGER ) { cs = CG_ConfigString( CS_OID_TRIGGERS + ent->teamNum ); } else if ( ent->eType == ET_CONSTRUCTIBLE ) { cs = CG_ConfigString( CS_OID_TRIGGERS + ent->otherEntityNum2 ); } if ( cs ) { CG_ObjectivePrint( va( "You are near %s\n", cs ), SMALLCHAR_WIDTH ); } continue; } } } #define MAX_PREDICT_ORIGIN_DELTA 0.1f #define MAX_PREDICT_VELOCITY_DELTA 0.1f #define MAX_PREDICT_VIEWANGLES_DELTA 1.0f qboolean CG_PredictionOk( playerState_t *ps1, playerState_t *ps2 ) { vec3_t vec; int i; if ( ps2->pm_type != ps1->pm_type || ps2->pm_flags != ps1->pm_flags || ps2->pm_time != ps1->pm_time ) { return qfalse; } VectorSubtract( ps2->origin, ps1->origin, vec ); if ( DotProduct( vec, vec ) > Square( MAX_PREDICT_ORIGIN_DELTA ) ) { return qfalse; } VectorSubtract( ps2->velocity, ps1->velocity, vec ); if ( DotProduct( vec, vec ) > Square( MAX_PREDICT_VELOCITY_DELTA ) ) { return qfalse; } if ( ps2->eFlags != ps1->eFlags ) { return qfalse; } if ( ps2->weaponTime != ps1->weaponTime ) { return qfalse; } if ( ps2->groundEntityNum != ps1->groundEntityNum ) { return qfalse; } if ( ps1->groundEntityNum != ENTITYNUM_WORLD || ps1->groundEntityNum != ENTITYNUM_NONE || ps2->groundEntityNum != ENTITYNUM_WORLD || ps2->groundEntityNum != ENTITYNUM_NONE ) { return qfalse; } if ( ps2->speed != ps1->speed || ps2->delta_angles[0] != ps1->delta_angles[0] || ps2->delta_angles[1] != ps1->delta_angles[1] || ps2->delta_angles[2] != ps1->delta_angles[2] ) { return qfalse; } if ( ps2->legsTimer != ps1->legsTimer || ps2->legsAnim != ps1->legsAnim || ps2->torsoTimer != ps1->torsoTimer || ps2->torsoAnim != ps1->torsoAnim ) { return qfalse; } /* if( ps2->movementDir != ps1->movementDir ) { return qfalse; }*/ if ( ps2->eventSequence != ps1->eventSequence ) { return qfalse; } for ( i = 0; i < MAX_EVENTS; i++ ) { if ( ps2->events[i] != ps1->events[i] || ps2->eventParms[i] != ps1->eventParms[i] ) { return qfalse; } } if ( ps2->externalEvent != ps1->externalEvent || ps2->externalEventParm != ps1->externalEventParm || ps2->externalEventTime != ps1->externalEventTime ) { return qfalse; } if ( ps2->clientNum != ps1->clientNum ) { return qfalse; } if ( ps2->weapon != ps1->weapon || ps2->weaponstate != ps1->weaponstate ) { return qfalse; } for ( i = 0; i < 3; i++ ) { if ( abs( ps2->viewangles[i] - ps1->viewangles[i] ) > MAX_PREDICT_VIEWANGLES_DELTA ) { return qfalse; } } if ( ps2->viewheight != ps1->viewheight ) { return qfalse; } if ( ps2->damageEvent != ps1->damageEvent || ps2->damageYaw != ps1->damageYaw || ps2->damagePitch != ps1->damagePitch || ps2->damageCount != ps1->damageCount ) { return qfalse; } for ( i = 0; i < MAX_STATS; i++ ) { if ( ps2->stats[i] != ps1->stats[i] ) { return qfalse; } } for ( i = 0; i < MAX_PERSISTANT; i++ ) { if ( ps2->persistant[i] != ps1->persistant[i] ) { return qfalse; } } for ( i = 0; i < MAX_POWERUPS; i++ ) { if ( ps2->powerups[i] != ps1->powerups[i] ) { return qfalse; } } for ( i = 0; i < MAX_WEAPONS; i++ ) { if ( ps2->ammo[i] != ps1->ammo[i] || ps2->ammoclip[i] != ps1->ammoclip[i] ) { return qfalse; } } if ( ps1->viewlocked != ps2->viewlocked || ps1->viewlocked_entNum != ps2->viewlocked_entNum ) { return qfalse; } if ( ps1->onFireStart != ps2->onFireStart ) { return qfalse; } return qtrue; } #define RESET_PREDICTION \ cg.lastPredictedCommand = 0; \ cg.backupStateTail = cg.backupStateTop; \ useCommand = current - CMD_BACKUP + 1; /* ================= CG_PredictPlayerState Generates cg.predictedPlayerState for the current cg.time cg.predictedPlayerState is guaranteed to be valid after exiting. For demo playback, this will be an interpolation between two valid playerState_t. For normal gameplay, it will be the result of predicted usercmd_t on top of the most recent playerState_t received from the server. Each new snapshot will usually have one or more new usercmd over the last, but we simulate all unacknowledged commands each time, not just the new ones. This means that on an internet connection, quite a few pmoves may be issued each frame. OPTIMIZE: don't re-simulate unless the newly arrived snapshot playerState_t differs from the predicted one. Would require saving all intermediate playerState_t during prediction. (this is "dead reckoning" and would definately be nice to have in there (SA)) We detect prediction errors and allow them to be decayed off over several frames to ease the jerk. ================= */ // rain - we need to keep pmext around for old frames, because Pmove() // fills in some values when it does prediction. This in itself is fine, // but the prediction loop starts in the past and predicts from the // snapshot time up to the current time, and having things like jumpTime // appear to be set for prediction runs where they previously weren't // is a Bad Thing. This is my bugfix for #166. pmoveExt_t oldpmext[CMD_BACKUP]; void CG_PredictPlayerState( void ) { int cmdNum, current; playerState_t oldPlayerState; qboolean moved; usercmd_t oldestCmd; usercmd_t latestCmd; vec3_t deltaAngles; pmoveExt_t pmext; // int useCommand = 0; cg.hyperspace = qfalse; // will be set if touching a trigger_teleport // if this is the first frame we must guarantee // predictedPlayerState is valid even if there is some // other error condition if ( !cg.validPPS ) { cg.validPPS = qtrue; cg.predictedPlayerState = cg.snap->ps; } // demo playback just copies the moves if ( cg.demoPlayback || ( cg.snap->ps.pm_flags & PMF_FOLLOW ) ) { CG_InterpolatePlayerState( qfalse ); return; } // non-predicting local movement will grab the latest angles if ( cg_nopredict.integer #ifdef ALLOW_GSYNC || cg_synchronousClients.integer #endif // ALLOW_GSYNC ) { cg_pmove.ps = &cg.predictedPlayerState; cg_pmove.pmext = &cg.pmext; cg.pmext.airleft = ( cg.waterundertime - cg.time ); // Arnout: are we using an mg42? if ( cg_pmove.ps->eFlags & EF_MG42_ACTIVE || cg_pmove.ps->eFlags & EF_AAGUN_ACTIVE ) { cg.pmext.harc = cg_entities[cg_pmove.ps->viewlocked_entNum].currentState.origin2[0]; cg.pmext.varc = cg_entities[cg_pmove.ps->viewlocked_entNum].currentState.origin2[1]; VectorCopy( cg_entities[cg_pmove.ps->viewlocked_entNum].currentState.angles2, cg.pmext.centerangles ); cg.pmext.centerangles[PITCH] = AngleNormalize180( cg.pmext.centerangles[PITCH] ); cg.pmext.centerangles[YAW] = AngleNormalize180( cg.pmext.centerangles[YAW] ); cg.pmext.centerangles[ROLL] = AngleNormalize180( cg.pmext.centerangles[ROLL] ); } CG_InterpolatePlayerState( qtrue ); return; } if ( cg_pmove.ps && cg_pmove.ps->eFlags & EF_MOUNTEDTANK ) { centity_t* tank = &cg_entities[cg_entities[cg.snap->ps.clientNum].tagParent]; cg.pmext.centerangles[YAW] = tank->lerpAngles[ YAW ]; cg.pmext.centerangles[PITCH] = tank->lerpAngles[ PITCH ]; } // prepare for pmove cg_pmove.ps = &cg.predictedPlayerState; cg_pmove.pmext = &pmext; //&cg.pmext; cg_pmove.character = CG_CharacterForClientinfo( &cgs.clientinfo[cg.snap->ps.clientNum], &cg_entities[cg.snap->ps.clientNum] ); cg.pmext.airleft = ( cg.waterundertime - cg.time ); // Arnout: are we using an mg42? if ( cg_pmove.ps->eFlags & EF_MG42_ACTIVE || cg_pmove.ps->eFlags & EF_AAGUN_ACTIVE ) { cg.pmext.harc = cg_entities[cg_pmove.ps->viewlocked_entNum].currentState.origin2[0]; cg.pmext.varc = cg_entities[cg_pmove.ps->viewlocked_entNum].currentState.origin2[1]; VectorCopy( cg_entities[cg_pmove.ps->viewlocked_entNum].currentState.angles2, cg.pmext.centerangles ); cg.pmext.centerangles[PITCH] = AngleNormalize180( cg.pmext.centerangles[PITCH] ); cg.pmext.centerangles[YAW] = AngleNormalize180( cg.pmext.centerangles[YAW] ); cg.pmext.centerangles[ROLL] = AngleNormalize180( cg.pmext.centerangles[ROLL] ); } else if ( cg_pmove.ps->eFlags & EF_MOUNTEDTANK ) { centity_t* tank = &cg_entities[cg_entities[cg.snap->ps.clientNum].tagParent]; cg.pmext.centerangles[PITCH] = tank->lerpAngles[PITCH]; } cg_pmove.skill = cgs.clientinfo[cg.snap->ps.clientNum].skill; cg_pmove.trace = CG_TraceCapsule; //cg_pmove.trace = CG_Trace; cg_pmove.pointcontents = CG_PointContents; if ( cg_pmove.ps->pm_type == PM_DEAD ) { cg_pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; cg_pmove.ps->eFlags |= EF_DEAD; // DHM-Nerve added:: EF_DEAD is checked for in Pmove functions, but wasn't being set until after Pmove } else if ( cg_pmove.ps->pm_type == PM_SPECTATOR ) { // rain - fix the spectator can-move-partway-through-world weirdness // bug by actually setting tracemask when spectating :x cg_pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; cg_pmove.trace = CG_TraceCapsule_World; } else { cg_pmove.tracemask = MASK_PLAYERSOLID; } if ( ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) || ( cg.snap->ps.pm_flags & PMF_LIMBO ) ) { // JPW NERVE limbo cg_pmove.tracemask &= ~CONTENTS_BODY; // spectators can fly through bodies } cg_pmove.noFootsteps = qfalse; cg_pmove.noWeapClips = qfalse; // save the state before the pmove so we can detect transitions oldPlayerState = cg.predictedPlayerState; current = trap_GetCurrentCmdNumber(); // rain - fill in the current cmd with the latest prediction from // cg.pmext (#166) memcpy( &oldpmext[current & CMD_MASK], &cg.pmext, sizeof( pmoveExt_t ) ); // if we don't have the commands right after the snapshot, we // can't accurately predict a current position, so just freeze at // the last good position we had cmdNum = current - CMD_BACKUP + 1; trap_GetUserCmd( cmdNum, &oldestCmd ); if ( oldestCmd.serverTime > cg.snap->ps.commandTime && oldestCmd.serverTime < cg.time ) { // special check for map_restart if ( cg_showmiss.integer ) { CG_Printf( "exceeded PACKET_BACKUP on commands\n" ); } } // get the latest command so we can know which commands are from previous map_restarts trap_GetUserCmd( current, &latestCmd ); // get the most recent information we have, even if // the server time is beyond our current cg.time, // because predicted player positions are going to // be ahead of everything else anyway // rain - NEIN - this'll cause us to execute events from the next frame // early, resulting in doubled events and the like. it seems to be // worse as far as prediction, too, so BLAH at id. (#405) #if 0 if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) { cg.predictedPlayerState = cg.nextSnap->ps; cg.physicsTime = cg.nextSnap->serverTime; } else { #endif cg.predictedPlayerState = cg.snap->ps; cg.physicsTime = cg.snap->serverTime; // } if ( pmove_msec.integer < 8 ) { trap_Cvar_Set( "pmove_msec", "8" ); } else if ( pmove_msec.integer > 33 ) { trap_Cvar_Set( "pmove_msec", "33" ); } cg_pmove.pmove_fixed = pmove_fixed.integer; // | cg_pmove_fixed.integer; cg_pmove.pmove_msec = pmove_msec.integer; // run cmds moved = qfalse; for ( cmdNum = current - CMD_BACKUP + 1 ; cmdNum <= current ; cmdNum++ ) { // get the command trap_GetUserCmd( cmdNum, &cg_pmove.cmd ); // get the previous command trap_GetUserCmd( cmdNum - 1, &cg_pmove.oldcmd ); if ( cg_pmove.pmove_fixed ) { // rain - added tracemask PM_UpdateViewAngles( cg_pmove.ps, cg_pmove.pmext, &cg_pmove.cmd, CG_Trace, cg_pmove.tracemask ); } // don't do anything if the time is before the snapshot player time if ( cg_pmove.cmd.serverTime <= cg.predictedPlayerState.commandTime ) { continue; } // don't do anything if the command was from a previous map_restart if ( cg_pmove.cmd.serverTime > latestCmd.serverTime ) { continue; } // check for a prediction error from last frame // on a lan, this will often be the exact value // from the snapshot, but on a wan we will have // to predict several commands to get to the point // we want to compare if ( cg.predictedPlayerState.commandTime == oldPlayerState.commandTime ) { vec3_t delta; float len; if ( BG_PlayerMounted( cg_pmove.ps->eFlags ) ) { // no prediction errors here, we're locked in place VectorClear( cg.predictedError ); } else if ( cg.thisFrameTeleport ) { // a teleport will not cause an error decay VectorClear( cg.predictedError ); if ( cg_showmiss.integer ) { CG_Printf( "PredictionTeleport\n" ); } cg.thisFrameTeleport = qfalse; } else if ( !cg.showGameView ) { vec3_t adjusted; CG_AdjustPositionForMover( cg.predictedPlayerState.origin, cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted, deltaAngles ); // RF, add the deltaAngles (fixes jittery view while riding trains) // ydnar: only do this if player is prone or using set mortar if ( ( cg.predictedPlayerState.eFlags & EF_PRONE ) || cg.weaponSelect == WP_MORTAR_SET ) { cg.predictedPlayerState.delta_angles[YAW] += ANGLE2SHORT( deltaAngles[YAW] ); } if ( cg_showmiss.integer ) { if ( !VectorCompare( oldPlayerState.origin, adjusted ) ) { CG_Printf( "prediction error\n" ); } } VectorSubtract( oldPlayerState.origin, adjusted, delta ); len = VectorLength( delta ); if ( len > 0.1 ) { if ( cg_showmiss.integer ) { CG_Printf( "Prediction miss: %f\n", len ); } if ( cg_errorDecay.integer ) { int t; float f; t = cg.time - cg.predictedErrorTime; f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; if ( f < 0 ) { f = 0; } if ( f > 0 && cg_showmiss.integer ) { CG_Printf( "Double prediction decay: %f\n", f ); } VectorScale( cg.predictedError, f, cg.predictedError ); } else { VectorClear( cg.predictedError ); } VectorAdd( delta, cg.predictedError, cg.predictedError ); cg.predictedErrorTime = cg.oldTime; } } } // don't predict gauntlet firing, which is only supposed to happen // when it actually inflicts damage cg_pmove.gauntletHit = qfalse; if ( cg_pmove.pmove_fixed ) { cg_pmove.cmd.serverTime = ( ( cg_pmove.cmd.serverTime + pmove_msec.integer - 1 ) / pmove_msec.integer ) * pmove_msec.integer; } // ydnar: if server respawning, freeze the player if ( cg.serverRespawning ) { cg_pmove.ps->pm_type = PM_FREEZE; } cg_pmove.gametype = cgs.gametype; // rain - only fill in the charge times if we're on a playing team if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_AXIS || cg.snap->ps.persistant[PERS_TEAM] == TEAM_ALLIES ) { cg_pmove.ltChargeTime = cg.ltChargeTime[cg.snap->ps.persistant[PERS_TEAM] - 1]; cg_pmove.soldierChargeTime = cg.soldierChargeTime[cg.snap->ps.persistant[PERS_TEAM] - 1]; cg_pmove.engineerChargeTime = cg.engineerChargeTime[cg.snap->ps.persistant[PERS_TEAM] - 1]; cg_pmove.medicChargeTime = cg.medicChargeTime[cg.snap->ps.persistant[PERS_TEAM] - 1]; cg_pmove.covertopsChargeTime = cg.covertopsChargeTime[cg.snap->ps.persistant[PERS_TEAM] - 1]; } #ifdef SAVEGAME_SUPPORT if ( CG_IsSinglePlayer() && cg_reloading.integer ) { cg_pmove.reloading = qtrue; } #endif // SAVEGAME_SUPPORT // memcpy( &pmext, &cg.pmext, sizeof(pmoveExt_t) ); // grab data, we only want the final result // rain - copy the pmext as it was just before we // previously ran this cmd (or, this will be the // current predicted data if this is the current cmd) (#166) memcpy( &pmext, &oldpmext[cmdNum & CMD_MASK], sizeof( pmoveExt_t ) ); fflush( stdout ); Pmove( &cg_pmove ); moved = qtrue; // add push trigger movement effects CG_TouchTriggerPrediction(); } if ( cg_showmiss.integer > 1 ) { CG_Printf( "[%i : %i] ", cg_pmove.cmd.serverTime, cg.time ); } if ( !moved ) { if ( cg_showmiss.integer ) { CG_Printf( "not moved\n" ); } return; } // restore pmext memcpy( &cg.pmext, &pmext, sizeof( pmoveExt_t ) ); if ( !cg.showGameView ) { // adjust for the movement of the groundentity CG_AdjustPositionForMover( cg.predictedPlayerState.origin, cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.time, cg.predictedPlayerState.origin, deltaAngles ); } // fire events and other transition triggered things CG_TransitionPlayerState( &cg.predictedPlayerState, &oldPlayerState ); // ydnar: shake player view here, rather than fiddle with view angles if ( cg.time > cg.cameraShakeTime ) { cg.cameraShakeScale = 0; } else { float x; // starts at 1, approaches 0 over time x = ( cg.cameraShakeTime - cg.time ) / cg.cameraShakeLength; // move cg.predictedPlayerState.origin[ 2 ] += sin( M_PI * 8 * 13 + cg.cameraShakePhase ) * x * 6.0f * cg.cameraShakeScale; cg.predictedPlayerState.origin[ 1 ] += sin( M_PI * 17 * x + cg.cameraShakePhase ) * x * 6.0f * cg.cameraShakeScale; cg.predictedPlayerState.origin[ 0 ] += cos( M_PI * 7 * x + cg.cameraShakePhase ) * x * 6.0f * cg.cameraShakeScale; } }
412
0.96294
1
0.96294
game-dev
MEDIA
0.839351
game-dev
0.893244
1
0.893244
DustinHLand/vkDOOM3
18,693
neo/ui/Winvar.h
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition 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 BFG Edition 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 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition 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 BFG Edition 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. =========================================================================== */ #ifndef __WINVAR_H__ #define __WINVAR_H__ #include "Rectangle.h" static const char *VAR_GUIPREFIX = "gui::"; static const int VAR_GUIPREFIX_LEN = strlen(VAR_GUIPREFIX); class idWindow; class idWinVar { public: idWinVar(); virtual ~idWinVar(); void SetGuiInfo(idDict *gd, const char *_name); const char *GetName() const { if (name) { if (guiDict && *name == '*') { return guiDict->GetString(&name[1]); } return name; } return ""; } void SetName(const char *_name) { delete []name; name = NULL; if (_name) { name = new (TAG_OLD_UI) char[strlen(_name)+1]; strcpy(name, _name); } } idWinVar &operator=( const idWinVar &other ) { guiDict = other.guiDict; SetName(other.name); return *this; } idDict *GetDict() const { return guiDict; } bool NeedsUpdate() { return (guiDict != NULL); } virtual void Init(const char *_name, idWindow* win) = 0; virtual void Set(const char *val) = 0; virtual void Update() = 0; virtual const char *c_str() const = 0; virtual size_t Size() { size_t sz = (name) ? strlen(name) : 0; return sz + sizeof(*this); } virtual void WriteToSaveGame( idFile *savefile ) = 0; virtual void ReadFromSaveGame( idFile *savefile ) = 0; virtual float x() const = 0; void SetEval(bool b) { eval = b; } bool GetEval() { return eval; } protected: idDict *guiDict; char *name; bool eval; }; class idWinBool : public idWinVar { public: idWinBool() : idWinVar() {}; ~idWinBool() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { data = guiDict->GetBool(GetName()); } } int operator==( const bool &other ) { return (other == data); } bool &operator=( const bool &other ) { data = other; if (guiDict) { guiDict->SetBool(GetName(), data); } return data; } idWinBool &operator=( const idWinBool &other ) { idWinVar::operator=(other); data = other.data; return *this; } operator bool() const { return data; } virtual void Set(const char *val) { data = ( atoi( val ) != 0 ); if (guiDict) { guiDict->SetBool(GetName(), data); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetBool( s ); } } virtual const char *c_str() const {return va("%i", data); } // SaveGames virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } virtual float x() const { return data ? 1.0f : 0.0f; }; protected: bool data; }; class idWinStr : public idWinVar { public: idWinStr() : idWinVar() {}; ~idWinStr() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { const char * name = GetName(); if ( name[0] == 0 ) { data = ""; } else { data = guiDict->GetString( name ); } } } int operator==( const idStr &other ) const { return (other == data); } int operator==( const char *other ) const { return (data == other); } idStr &operator=( const idStr &other ) { data = other; if (guiDict) { guiDict->Set(GetName(), data); } return data; } idWinStr &operator=( const idWinStr &other ) { idWinVar::operator=(other); data = other.data; return *this; } operator const char *() const { return data.c_str(); } operator const idStr &() const { return data; } int LengthWithoutColors() { if (guiDict && name && *name) { data = guiDict->GetString(GetName()); } return data.LengthWithoutColors(); } int Length() { if (guiDict && name && *name) { data = guiDict->GetString(GetName()); } return data.Length(); } void RemoveColors() { if (guiDict && name && *name) { data = guiDict->GetString(GetName()); } data.RemoveColors(); } virtual const char *c_str() const { return data.c_str(); } virtual void Set(const char *val) { data = val; if ( guiDict ) { guiDict->Set(GetName(), data); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetString( s ); } } virtual size_t Size() { size_t sz = idWinVar::Size(); return sz +data.Allocated(); } // SaveGames virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); int len = data.Length(); savefile->Write( &len, sizeof( len ) ); if ( len > 0 ) { savefile->Write( data.c_str(), len ); } } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); int len; savefile->Read( &len, sizeof( len ) ); if ( len > 0 ) { data.Fill( ' ', len ); savefile->Read( &data[0], len ); } } // return wether string is emtpy virtual float x() const { return data[0] ? 1.0f : 0.0f; }; protected: idStr data; }; class idWinInt : public idWinVar { public: idWinInt() : idWinVar() {}; ~idWinInt() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { data = guiDict->GetInt(GetName()); } } int &operator=( const int &other ) { data = other; if (guiDict) { guiDict->SetInt(GetName(), data); } return data; } idWinInt &operator=( const idWinInt &other ) { idWinVar::operator=(other); data = other.data; return *this; } operator int () const { return data; } virtual void Set(const char *val) { data = atoi(val);; if (guiDict) { guiDict->SetInt(GetName(), data); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetInt( s ); } } virtual const char *c_str() const { return va("%i", data); } // SaveGames virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } // no suitable conversion virtual float x() const { assert( false ); return 0.0f; }; protected: int data; }; class idWinFloat : public idWinVar { public: idWinFloat() : idWinVar() {}; ~idWinFloat() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { data = guiDict->GetFloat(GetName()); } } idWinFloat &operator=( const idWinFloat &other ) { idWinVar::operator=(other); data = other.data; return *this; } float &operator=( const float &other ) { data = other; if (guiDict) { guiDict->SetFloat(GetName(), data); } return data; } operator float() const { return data; } virtual void Set(const char *val) { data = atof(val); if (guiDict) { guiDict->SetFloat(GetName(), data); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetFloat( s ); } } virtual const char *c_str() const { return va("%f", data); } virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } virtual float x() const { return data; }; protected: float data; }; class idWinRectangle : public idWinVar { public: idWinRectangle() : idWinVar() {}; ~idWinRectangle() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { idVec4 v = guiDict->GetVec4(GetName()); data.x = v.x; data.y = v.y; data.w = v.z; data.h = v.w; } } int operator==( const idRectangle &other ) const { return (other == data); } idWinRectangle &operator=( const idWinRectangle &other ) { idWinVar::operator=(other); data = other.data; return *this; } idRectangle &operator=( const idVec4 &other ) { data = other; if (guiDict) { guiDict->SetVec4(GetName(), other); } return data; } idRectangle &operator=( const idRectangle &other ) { data = other; if (guiDict) { idVec4 v = data.ToVec4(); guiDict->SetVec4(GetName(), v); } return data; } operator const idRectangle&() const { return data; } float x() const { return data.x; } float y() const { return data.y; } float w() const { return data.w; } float h() const { return data.h; } float Right() const { return data.Right(); } float Bottom() const { return data.Bottom(); } idVec4 &ToVec4() { static idVec4 ret; ret = data.ToVec4(); return ret; } virtual void Set(const char *val) { if ( strchr ( val, ',' ) ) { sscanf( val, "%f,%f,%f,%f", &data.x, &data.y, &data.w, &data.h ); } else { sscanf( val, "%f %f %f %f", &data.x, &data.y, &data.w, &data.h ); } if (guiDict) { idVec4 v = data.ToVec4(); guiDict->SetVec4(GetName(), v); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { idVec4 v = guiDict->GetVec4( s ); data.x = v.x; data.y = v.y; data.w = v.z; data.h = v.w; } } virtual const char *c_str() const { return data.ToVec4().ToString(); } virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } protected: idRectangle data; }; class idWinVec2 : public idWinVar { public: idWinVec2() : idWinVar() {}; ~idWinVec2() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { data = guiDict->GetVec2(GetName()); } } int operator==( const idVec2 &other ) const { return (other == data); } idWinVec2 &operator=( const idWinVec2 &other ) { idWinVar::operator=(other); data = other.data; return *this; } idVec2 &operator=( const idVec2 &other ) { data = other; if (guiDict) { guiDict->SetVec2(GetName(), data); } return data; } float x() const { return data.x; } float y() const { return data.y; } virtual void Set(const char *val) { if ( strchr ( val, ',' ) ) { sscanf( val, "%f,%f", &data.x, &data.y ); } else { sscanf( val, "%f %f", &data.x, &data.y); } if (guiDict) { guiDict->SetVec2(GetName(), data); } } operator const idVec2&() const { return data; } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetVec2( s ); } } virtual const char *c_str() const { return data.ToString(); } void Zero() { data.Zero(); } virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } protected: idVec2 data; }; class idWinVec4 : public idWinVar { public: idWinVec4() : idWinVar() {}; ~idWinVec4() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { data = guiDict->GetVec4(GetName()); } } int operator==( const idVec4 &other ) const { return (other == data); } idWinVec4 &operator=( const idWinVec4 &other ) { idWinVar::operator=(other); data = other.data; return *this; } idVec4 &operator=( const idVec4 &other ) { data = other; if (guiDict) { guiDict->SetVec4(GetName(), data); } return data; } operator const idVec4&() const { return data; } float x() const { return data.x; } float y() const { return data.y; } float z() const { return data.z; } float w() const { return data.w; } virtual void Set(const char *val) { if ( strchr ( val, ',' ) ) { sscanf( val, "%f,%f,%f,%f", &data.x, &data.y, &data.z, &data.w ); } else { sscanf( val, "%f %f %f %f", &data.x, &data.y, &data.z, &data.w); } if ( guiDict ) { guiDict->SetVec4( GetName(), data ); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetVec4( s ); } } virtual const char *c_str() const { return data.ToString(); } void Zero() { data.Zero(); if ( guiDict ) { guiDict->SetVec4(GetName(), data); } } const idVec3 &ToVec3() const { return data.ToVec3(); } virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } protected: idVec4 data; }; class idWinVec3 : public idWinVar { public: idWinVec3() : idWinVar() {}; ~idWinVec3() {}; virtual void Init(const char *_name, idWindow *win) { idWinVar::Init(_name, win); if (guiDict) { data = guiDict->GetVector(GetName()); } } int operator==( const idVec3 &other ) const { return (other == data); } idWinVec3 &operator=( const idWinVec3 &other ) { idWinVar::operator=(other); data = other.data; return *this; } idVec3 &operator=( const idVec3 &other ) { data = other; if (guiDict) { guiDict->SetVector(GetName(), data); } return data; } operator const idVec3&() const { return data; } float x() const { return data.x; } float y() const { return data.y; } float z() const { return data.z; } virtual void Set(const char *val) { sscanf( val, "%f %f %f", &data.x, &data.y, &data.z); if (guiDict) { guiDict->SetVector(GetName(), data); } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetVector( s ); } } virtual const char *c_str() const { return data.ToString(); } void Zero() { data.Zero(); if (guiDict) { guiDict->SetVector(GetName(), data); } } virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); savefile->Write( &data, sizeof( data ) ); } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); savefile->Read( &data, sizeof( data ) ); } protected: idVec3 data; }; class idWinBackground : public idWinStr { public: idWinBackground() : idWinStr() { mat = NULL; }; ~idWinBackground() {}; virtual void Init(const char *_name, idWindow *win) { idWinStr::Init(_name, win); if (guiDict) { data = guiDict->GetString(GetName()); } } int operator==( const idStr &other ) const { return (other == data); } int operator==( const char *other ) const { return (data == other); } idStr &operator=( const idStr &other ) { data = other; if (guiDict) { guiDict->Set(GetName(), data); } if (mat) { if ( data == "" ) { (*mat) = NULL; } else { (*mat) = declManager->FindMaterial(data); } } return data; } idWinBackground &operator=( const idWinBackground &other ) { idWinVar::operator=(other); data = other.data; mat = other.mat; if (mat) { if ( data == "" ) { (*mat) = NULL; } else { (*mat) = declManager->FindMaterial(data); } } return *this; } operator const char *() const { return data.c_str(); } operator const idStr &() const { return data; } int Length() { if (guiDict) { data = guiDict->GetString(GetName()); } return data.Length(); } virtual const char *c_str() const { return data.c_str(); } virtual void Set(const char *val) { data = val; if (guiDict) { guiDict->Set(GetName(), data); } if (mat) { if ( data == "" ) { (*mat) = NULL; } else { (*mat) = declManager->FindMaterial(data); } } } virtual void Update() { const char *s = GetName(); if ( guiDict && s[0] != '\0' ) { data = guiDict->GetString( s ); if (mat) { if ( data == "" ) { (*mat) = NULL; } else { (*mat) = declManager->FindMaterial(data); } } } } virtual size_t Size() { size_t sz = idWinVar::Size(); return sz +data.Allocated(); } void SetMaterialPtr( const idMaterial **m ) { mat = m; } virtual void WriteToSaveGame( idFile *savefile ) { savefile->Write( &eval, sizeof( eval ) ); int len = data.Length(); savefile->Write( &len, sizeof( len ) ); if ( len > 0 ) { savefile->Write( data.c_str(), len ); } } virtual void ReadFromSaveGame( idFile *savefile ) { savefile->Read( &eval, sizeof( eval ) ); int len; savefile->Read( &len, sizeof( len ) ); if ( len > 0 ) { data.Fill( ' ', len ); savefile->Read( &data[0], len ); } if ( mat ) { if ( len > 0 ) { (*mat) = declManager->FindMaterial( data ); } else { (*mat) = NULL; } } } protected: idStr data; const idMaterial **mat; }; /* ================ idMultiWinVar multiplexes access to a list if idWinVar* ================ */ class idMultiWinVar : public idList< idWinVar * > { public: void Set( const char *val ); void Update(); void SetGuiInfo( idDict *dict ); }; #endif /* !__WINVAR_H__ */
412
0.728046
1
0.728046
game-dev
MEDIA
0.630837
game-dev,networking
0.973486
1
0.973486
KagiamamaHIna/Wand-Editor
28,990
files/misc/bygoki/lib/helper.lua
local MISC = dofile_once("mods/wand_editor/files/misc/bygoki/lib/options.lua"); dofile_once("mods/wand_editor/files/misc/bygoki/lib/variables.lua"); --[[ #define ENUM_DAMAGE_TYPES(_) _(DAMAGE_MELEE, 1 << 0 ) _(DAMAGE_PROJECTILE, 1 << 1 ) _(DAMAGE_EXPLOSION, 1 << 2 ) _(DAMAGE_BITE, 1 << 3 ) _(DAMAGE_FIRE, 1 << 4 ) _(DAMAGE_MATERIAL, 1 << 5 ) _(DAMAGE_FALL, 1 << 6 ) _(DAMAGE_ELECTRICITY, 1 << 7 ) _(DAMAGE_DROWNING, 1 << 8 ) _(DAMAGE_PHYSICS_BODY_DAMAGED, 1 << 9 ) _(DAMAGE_DRILL, 1 << 10 ) _(DAMAGE_SLICE, 1 << 11 ) _(DAMAGE_ICE, 1 << 12 ) _(DAMAGE_HEALING, 1 << 13 ) _(DAMAGE_PHYSICS_HIT, 1 << 14 ) _(DAMAGE_RADIOACTIVE, 1 << 15 ) _(DAMAGE_POISON, 1 << 16 ) _(DAMAGE_MATERIAL_WITH_FLASH, 1 << 17 ) _(DAMAGE_OVEREATING, 1 << 18 ) #define ENUM_RAGDOLL_FX(_) _(NONE, 0) _(NORMAL, 1) _(BLOOD_EXPLOSION, 2) _(BLOOD_SPRAY, 3) _(FROZEN, 4) _(CONVERT_TO_MATERIAL, 5) _(CUSTOM_RAGDOLL_ENTITY, 6) _(DISINTEGRATED, 7) _(NO_RAGDOLL_FILE, 8) _(PLAYER_RAGDOLL_CAMERA, 9) ]] function load_dynamic_badge ( key, append_bool_table ) local badge_image = "ui_icon_image_"..key; local badge_name = "ui_icon_name_"..key; local badge_description = "ui_icon_description_"..key; if append_bool_table ~= nil then for _,pair in ipairs(append_bool_table) do for append,bool in pairs(pair) do if bool then badge_image = badge_image .. append; badge_name = badge_name .. append; badge_description = badge_description .. append; end end end end local badge = EntityLoad( "mods/gkbrkn_noita/files/gkbrkn/badges/badge.xml" ); if badge ~= nil then local ui_icon = EntityGetFirstComponent( badge, "UIIconComponent" ); if ui_icon ~= nil then ComponentSetValue2( ui_icon, "icon_sprite_file", GameTextGetTranslatedOrNot("$"..badge_image) ); ComponentSetValue2( ui_icon, "name", GameTextGetTranslatedOrNot("$"..badge_name) ); ComponentSetValue2( ui_icon, "description", GameTextGetTranslatedOrNot("$"..badge_description) ); ComponentSetValue2( ui_icon, "is_perk", true ); end end return badge; end function get_update_time( ) return tonumber( GlobalsGetValue( "gkbrkn_update_time" ) ) or 0; end function reset_update_time( ) GlobalsSetValue( "gkbrkn_update_time", 0 ); end function get_frame_time( ) return tonumber( GlobalsGetValue( "gkbrkn_frame_time" ) ) or 0; end function reset_frame_time( ) GlobalsSetValue( "gkbrkn_frame_time", 0 ); end function add_update_time( amount ) GlobalsSetValue( "gkbrkn_update_time", get_update_time() + amount ); end function add_frame_time( amount ) GlobalsSetValue( "gkbrkn_frame_time", get_frame_time() + amount ); end function generate_perk_entry( perk_id, key, usable_by_enemies, pickup_function, deprecated, author, stackable ) if stackable == nil then stackable = true; end return { id = perk_id, ui_name = "$perk_name_gkbrkn_"..key, ui_description = "$perk_desc_gkbrkn_"..key, ui_icon = "mods/gkbrkn_noita/files/gkbrkn/perks/"..key.."/icon_ui.png", perk_icon = "mods/gkbrkn_noita/files/gkbrkn/perks/"..key.."/icon_ig.png", usable_by_enemies = usable_by_enemies, func = pickup_function, deprecated = deprecated, author = author or "goki_dev", local_content = true, stackable = stackable }; end function generate_action_entry( action_id, key, action_type, spawn_level, spawn_probability, price, mana, max_uses, custom_xml, action_function, deprecated, icon_path, author, related_projectiles, enabled_by_default ) return { id = action_id, name = "$action_name_gkbrkn_"..key, description = "$action_desc_gkbrkn_"..key, sprite = icon_path or "mods/gkbrkn_noita/files/gkbrkn/actions/"..key.."/icon.png", sprite_unidentified = icon_path or "mods/gkbrkn_noita/files/gkbrkn/actions/"..key.."/icon.png", type = action_type, spawn_level = spawn_level, spawn_probability = spawn_probability, price = price, mana = mana, max_uses = max_uses, custom_xml_file = custom_xml, action = action_function, deprecated = deprecated, author = author or "goki_dev", related_projectiles = related_projectiles, local_content = true, enabled_by_default = enabled_by_default }; end function spawn_gold_nuggets( gold_value, x, y, blood_money ) local sizes = { 10000, 1000, 200, 50, 10 }; local world_entity_id = GameGetWorldStateEntity(); local world_state = EntityGetFirstComponent( world_entity_id, "WorldStateComponent" ); local is_gold_forever = false; if world_state ~= nil then is_gold_forever = ComponentGetValue2( world_state, "perk_gold_is_forever" ); end for _,size in pairs(sizes) do while gold_value >= size do gold_value = gold_value - size; local gold_nugget = EntityLoad( "data/entities/items/pickup/goldnugget_"..size..".xml", x, y ); if is_gold_forever then EntityRemoveComponent( gold_nugget, EntityGetFirstComponent( gold_nugget, "LifetimeComponent" ) ); end end end end function does_entity_drop_gold( entity ) local drops_gold = false; for _,component in pairs( EntityGetComponent( entity, "LuaComponent" ) or {} ) do if ComponentGetValue2( component, "script_death" ) == "data/scripts/items/drop_money.lua" then drops_gold = true; break; end end if drops_gold == true then if EntityGetFirstComponent( entity, "VariableStorageComponent", "no_drop_gold" ) ~= nil then drops_gold = false; end end return drops_gold; end function script_wait_frames_fixed( entity_id, frames ) local now = GameGetFrameNum(); local last_execution = ComponentGetValueInt( GetUpdatedComponentID(), "mLastExecutionFrame" ); if now - last_execution < frames then return true; end return false; end function set_lost_treasure( gold_nugget_entity ) EntityAddComponent( gold_nugget_entity, "LuaComponent", { execute_every_n_frame = "-1", script_item_picked_up = "mods/gkbrkn_noita/files/gkbrkn/perks/lost_treasure/gold_pickup.lua", }); local removal_lua = EntityAddComponent( gold_nugget_entity, "LuaComponent", { _tags="gkbrkn_lost_treasure", execute_on_removed="1", execute_every_n_frame="-1", script_source_file = "mods/gkbrkn_noita/files/gkbrkn/perks/lost_treasure/gold_removed.lua", }); end function clear_lost_treasure( gold_nugget_entity ) local lost_treasure_script = EntityGetFirstComponent( gold_nugget_entity, "LuaComponent", "gkbrkn_lost_treasure" ); if lost_treasure_script ~= nil then EntityRemoveComponent( gold_nugget_entity, lost_treasure_script ); end end function is_lost_treasure( gold_nugget_entity ) return EntityGetFirstComponent( gold_nugget_entity, "LuaComponent", "gkbrkn_lost_treasure" ) ~= nil; end function is_gold_decay( gold_nugget_entity ) return EntityGetFirstComponent( gold_nugget_entity, "LuaComponent", "gkbrkn_gold_decay" ) ~= nil; end function set_gold_decay( gold_nugget_entity ) EntityAddComponent( gold_nugget_entity, "LuaComponent", { execute_every_n_frame = "-1", remove_after_executed = "1", script_item_picked_up = "mods/gkbrkn_noita/files/gkbrkn/misc/gold_decay/gold_pickup.lua", }); EntityAddComponent( gold_nugget_entity, "LuaComponent", { _tags="gkbrkn_gold_decay", execute_on_removed="1", execute_every_n_frame="-1", script_source_file = "mods/gkbrkn_noita/files/gkbrkn/misc/gold_decay/gold_removed.lua", }); end function clear_gold_decay( gold_nugget_entity ) local script = EntityGetFirstComponent( gold_nugget_entity, "LuaComponent", "gkbrkn_gold_decay" ); if script ~= nil then EntityRemoveComponent( gold_nugget_entity, script ); end end function limit_to_every_n_frames( entity, variable_name, n, callback ) local now = GameGetFrameNum(); if now - EntityGetVariableNumber( entity, variable_name, 0 ) >= n then EntitySetVariableNumber( entity, variable_name, now ); callback(); end end function trend_towards_range( value, divisor, min, max ) return min + (max - min) * ( value / ( value + divisor ) ); end function get_projectile_root_shooter( entity ) local root_shooter = entity; local projectile = EntityGetFirstComponent( entity, "ProjectileComponent" ); if projectile ~= nil then local shooter = ComponentGetValue2( projectile, "mWhoShot" ); while shooter ~= nil and shooter ~= 0 do root_shooter = shooter; local shooter_projectile = EntityGetFirstComponent( shooter, "ProjectileComponent" ); if shooter_projectile == nil then break; end shooter = ComponentGetValue2( shooter_projectile, "mWhoShot" ); end end return root_shooter; end function make_projectile_not_damage_shooter( entity, force_shooter ) local projectile = EntityGetFirstComponent( entity, "ProjectileComponent" ); if projectile ~= nil then ComponentSetValue2( projectile, "explosion_dont_damage_shooter", true ); ComponentSetValue2( projectile, "friendly_fire", false ); local shooter = force_shooter or get_projectile_root_shooter( entity ); if shooter ~= nil and shooter ~= 0 then ComponentObjectSetValue( projectile, "config_explosion", "dont_damage_this", tostring( shooter ) ); EntityIterateComponentsByType( entity, "AreaDamageComponent", function(component) if EntityHasTag( shooter, "player_unit" ) then ComponentSetValue2( component, "entities_with_tag", "enemy" ); else ComponentSetValue2( component, "entities_with_tag", "player_unit" ); end end ); local lightning = EntityGetFirstComponent( entity, "LightningComponent" ); if lightning ~= nil then ComponentObjectSetValue( lightning, "config_explosion", "dont_damage_this", tostring( shooter ) ); end end end end -- TODO this doesn't handle all damage components and doesn't handle multiple components of the same type function adjust_entity_damage( entity, projectile_damage_callback, typed_damage_callback, explosive_damage_callback, lightning_damage_callback, area_damage_callback ) local projectile = EntityGetFirstComponent( entity, "ProjectileComponent" ); local lightning = EntityGetFirstComponent( entity, "LightningComponent" ); if projectile ~= nil then if projectile_damage_callback ~= nil then local current_damage = ComponentGetValue2( projectile, "damage" ); local new_damage = projectile_damage_callback( current_damage ); if current_damage ~= new_damage then ComponentSetValue2( projectile, "damage", new_damage ); end if typed_damage_callback ~= nil then local damage_by_types = ComponentObjectGetMembers( projectile, "damage_by_type" ) or {}; local damage_by_types_fixed = {}; for type,_ in pairs( damage_by_types ) do damage_by_types_fixed[type] = ComponentObjectGetValue2( projectile, "damage_by_type", type ); end local damage_by_types_adjusted = typed_damage_callback( damage_by_types_fixed ); for type,amount in pairs( damage_by_types_adjusted ) do if amount ~= nil then ComponentObjectSetValue2( projectile, "damage_by_type", type, amount or damage_by_types_fixed[type] or 0 ); end end end if explosive_damage_callback ~= nil then local current_damage = ComponentObjectGetValue2( projectile, "config_explosion", "damage" ); local new_damage = explosive_damage_callback( current_damage ); if current_damage ~= new_damage then ComponentObjectSetValue2( projectile, "config_explosion", "damage", new_damage ); end end end if lightning_damage_callback ~= nil then local lightning = EntityGetFirstComponent( entity, "LightningComponent" ); if lightning ~= nil then local current_damage = tonumber( ComponentObjectGetValue2( lightning, "config_explosion", "damage" ) ); local new_damage = lightning_damage_callback( current_damage ); if current_damage ~= new_damage then ComponentObjectSetValue2( lightning, "config_explosion", "damage", new_damage ); end end end if area_damage_callback ~= nil then local area_damage = EntityGetFirstComponent( entity, "AreaDamageComponent" ); if area_damage ~= nil then local current_damage = ComponentGetValue2( area_damage, "damage_per_frame" ); local new_damage = area_damage_callback( current_damage ); if current_damage ~= new_damage then ComponentSetValue2( area_damage, "damage_per_frame", new_damage ); end end end end end function adjust_all_entity_damage( entity, callback ) adjust_entity_damage( entity, function( current_damage ) return callback( current_damage ); end, function( current_damages ) for type,current_damage in pairs( current_damages ) do if current_damage ~= 0 then current_damages[type] = callback( current_damage ); end end return current_damages; end, function( current_damage ) return callback( current_damage ); end, function( current_damage ) return callback( current_damage ); end, function( current_damage ) return callback( current_damage ); end ); end function add_entity_mini_health_bar( entity ) EntityAddComponent( entity, "HealthBarComponent" ); EntityAddComponent( entity, "SpriteComponent", { _tags="health_bar,ui,no_hitbox", alpha="1", has_special_scale="1", image_file="mods/gkbrkn_noita/files/gkbrkn/misc/health_bar.png", never_ragdollify_on_death="1", is_text_sprite="0", next_rect_animation="", offset_x="11", offset_y="-8", rect_animation="", special_scale_x="0.2", special_scale_y="0.6", ui_is_parent="0", update_transform="1", update_transform_rotation="0", visible="1", z_index="-9000", } ); end function entity_adjust_health( entity, callback ) local damage_models = EntityGetComponent( entity, "DamageModelComponent" ); if damage_models ~= nil then for _,damage_model in pairs( damage_models ) do local hp = ComponentGetValue2( damage_model, "hp" ); local max_hp = ComponentGetValue2( damage_model, "max_hp" ); local new_max_hp, new_hp = callback( max_hp, hp ); ComponentSetValue2( damage_model, "hp", new_hp or hp ); ComponentSetValue2( damage_model, "max_hp", new_max_hp or max_hp ); end end end function entity_get_health_ratio( entity ) local current_hp = 0; local current_max_hp = 0; local damage_models = EntityGetComponent( entity, "DamageModelComponent" ) or {}; for _,damage_model in pairs( damage_models ) do local hp = ComponentGetValue2( damage_model, "hp" ); if hp > current_hp then current_hp = hp; end local max_hp = ComponentGetValue2( damage_model, "max_hp" ); if max_hp > current_max_hp then current_max_hp = max_hp; end end local ratio = current_hp / current_max_hp; if ratio ~= ratio then return 0; end return ratio; end function entity_draw_health_bar( entity, frames ) local health_ratio = entity_get_health_ratio( entity ); if health_ratio < 1 then local x, y = EntityGetTransform( entity ); local health_bar_image = 11 - math.ceil( health_ratio * 10 ); local sprite = "mods/gkbrkn_noita/files/gkbrkn/misc/health_bars/health_bar"..health_bar_image..".png"; local w,h = EntityGetFirstHitboxSize( entity ); if w == nil or h == nil then GameCreateSpriteForXFrames( sprite, x, y + 8, true, 0, 0, frames ); else GameCreateSpriteForXFrames( sprite, x, y + h / 2 + 2, true, 0, 0, frames ); end end end function string_trim( s ) local from = s:match"^%s*()" return from > #s and "" or s:match(".*%S", from) end function string_split( s, splitter ) local words = {}; for word in string.gmatch( s, '([^'..splitter..']+)') do table.insert( words, word ); end return words; end function reduce_particles( entity, disable ) local particle_emitters = EntityGetComponent( entity, "ParticleEmitterComponent" ) or {}; local sprite_particle_emitters = EntityGetComponent( entity, "SpriteParticleEmitterComponent" ) or {}; local projectile = EntityGetFirstComponent( entity, "ProjectileComponent" ); if not disable then for _,emitter in pairs( particle_emitters ) do if ComponentGetValue2( emitter, "emit_cosmetic_particles" ) == true and ComponentGetValue2( emitter, "create_real_particles" ) == false and ComponentGetValue2( emitter, "emit_real_particles" ) == false then ComponentSetValue2( emitter, "count_min", 1 ); ComponentSetValue2( emitter, "count_max", 1 ); ComponentSetValue2( emitter, "collide_with_grid", false ); ComponentSetValue2( emitter, "is_trail", false ); local lifetime_min = tonumber( ComponentGetValue2( emitter, "lifetime_min" ) ); ComponentSetValue2( emitter, "lifetime_min", math.min( lifetime_min * 0.5, 0.1 ) ); local lifetime_max = tonumber( ComponentGetValue2( emitter, "lifetime_max" ) ); ComponentSetValue2( emitter, "lifetime_max", math.min( lifetime_max * 0.5, 0.5 ) ); end end for _,emitter in pairs( sprite_particle_emitters ) do if ComponentGetValue2( emitter, "entity_file" ) == "" then ComponentSetValue2( emitter, "count_max", 1 ); ComponentSetValue2( emitter, "emission_interval_min_frames", math.ceil( ComponentGetValue2( emitter, "emission_interval_min_frames" ) * 2 ) ); ComponentSetValue2( emitter, "emission_interval_max_frames", math.ceil( ComponentGetValue2( emitter, "emission_interval_max_frames" ) * 2 ) ); end end if projectile ~= nil then ComponentObjectAdjustValues( projectile, "config_explosion", { sparks_count_min=function( value ) return math.min( value, 1 ); end, sparks_count_max=function( value ) return math.min( value, 2 ); end, }); end else for _,emitter in pairs( particle_emitters ) do if ComponentGetValue2( emitter, "emit_cosmetic_particles" ) == true and ComponentGetValue2( emitter, "create_real_particles" ) == false and ComponentGetValue2( emitter, "emit_real_particles" ) == false then EntitySetComponentIsEnabled( entity, emitter, false ); end end for _,emitter in pairs( sprite_particle_emitters ) do EntitySetComponentIsEnabled( entity, emitter, false ); end if projectile ~= nil then ComponentObjectSetValues( projectile, "config_explosion", { sparks_enabled=false, particle_effect=false }); end end end function remove_explosion_stains( entity ) local projectile = EntityGetFirstComponent( entity, "ProjectileComponent" ); if projectile ~= nil then ComponentObjectAdjustValues( projectile, "config_explosion", { stains_enabled=function( value ) return false; end, }); end end function find_polymorphed_players() local nearby_polymorph = EntityGetWithTag( "polymorphed" ) or {}; local polymorphed_players = {}; for _,entity in pairs( nearby_polymorph ) do local game_stats = EntityGetFirstComponent( entity, "GameStatsComponent" ); if game_stats ~= nil then if ComponentGetValue2( game_stats, "is_player" ) == true then table.insert( polymorphed_players, entity ); end end end return polymorphed_players; end function normalize( value, start_value, end_value ) width = end_value - start_value; offsetValue = value - start_value ; return ( offsetValue - ( math.floor( offsetValue / width ) * width ) ) + start_value; end -- TODO fix function wrap_angle(angle) local PI = math.pi; local TWO_PI = math.pi * 2; if angle > 0 then angle = angle % TWO_PI else angle = -(math.abs(angle)%TWO_PI) end if angle > PI then angle = angle - TWO_PI elseif angle < -PI then angle = angle + TWO_PI end return angle end function ease_angle( angle, target_angle, easing ) local dir = (angle - target_angle) / (math.pi*2); dir = dir - math.floor(dir + 0.5); dir = dir * (math.pi*2); return angle - dir * easing; end function angle_difference( target_angle, starting_angle ) return math.atan2( math.sin( target_angle - starting_angle ), math.cos( target_angle - starting_angle ) ); end function projectile_change_particle_colors( projectile_entity, color ) local r = bit.band( 0xFF, color ); local g = bit.rshift( bit.band( 0xFF00, color ), 8 ); local b = bit.rshift( bit.band( 0xFF0000, color ), 16 ); local particle_emitters = EntityGetComponent( projectile_entity, "ParticleEmitterComponent" ) or {}; for _,particle_emitter in pairs( particle_emitters ) do --for k,v in pairs( ComponentGetMembers( particle_emitter ) or {} ) do -- print( k.."/"..tostring(v)); --end if ComponentGetValue2( particle_emitter, "emit_real_particles" ) == false then ComponentSetValue2( particle_emitter, "color", color ); end end local sprite_particle_emitters = EntityGetComponent( projectile_entity, "SpriteParticleEmitterComponent" ) or {}; for _,sprite_particle_emitter in pairs( sprite_particle_emitters ) do local color = {ComponentGetValue2( sprite_particle_emitter, "color" )}; local color_change = {ComponentGetValue2( sprite_particle_emitter, "color_change" )}; local ratio_r = r / 255; local ratio_g = g / 255; local ratio_b = b / 255; ComponentSetValue2( sprite_particle_emitter, "color", ratio_r, ratio_g, ratio_b, color[4] ); end end function distance_to_entity( x, y, entity ) local tx, ty = EntityGetFirstHitboxCenter( entity ); if tx == nil or ty == nil then tx, ty = EntityGetTransform( entity ); end return math.sqrt( math.pow( tx - x, 2 ) + math.pow( ty - y, 2 ) ); end function get_protagonist_bonus( entity ) local multiplier = 1.0; local health_ratio = 1; local damage_models = EntityGetComponent( entity, "DamageModelComponent" ); if damage_models ~= nil then for i,damage_model in ipairs( damage_models ) do local current_hp = ComponentGetValue2( damage_model, "hp" ); local max_hp = ComponentGetValue2( damage_model, "max_hp" ); local ratio = current_hp / max_hp; if ratio < health_ratio then health_ratio = ratio; end end end if entity ~= nil then local current_protagonist_bonus = EntityGetVariableNumber( entity, "gkbrkn_low_health_damage_bonus", 0.0 ); local adjuted_ratio = ( 1 - health_ratio ) ^ 1.5; multiplier = 1.0 + current_protagonist_bonus * adjuted_ratio; end return multiplier; end function append_translations( filepath, translation_file ) if translation_file == nil then translation_file = "data/translations/common.csv"; end local translations = ModTextFileGetContent( translation_file ); if translations ~= nil then while translations:find("\r\n\r\n") do translations = translations:gsub("\r\n\r\n","\r\n"); end local new_translations = ModTextFileGetContent( filepath ); translations = translations .. new_translations; ModTextFileSetContent( translation_file, translations ); end end function thousands_separator(amount) local formatted = amount; while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if (k==0) then break end end return formatted; end function decimal_format( amount, decimals ) if decimals == nil then decimals = 0; end return thousands_separator( string.format( "%."..decimals.."f", amount ) ); end function copy_component( left, right ) for k,v in pairs( ComponentGetMembers( left ) ) do ComponentSetValue2( right, k, ComponentGetValue2( left, k ) ) end end function sort_keyed_table( keyed_table, sort_function ) local h = {}; for k,v in pairs( keyed_table ) do table.insert( h, { key=k, value=v }) end table.sort( h, sort_function ); return h; end function get_magic_focus_multiplier( last_calibration_shot_frame, last_calibration_percent ) local multiplier = 1.0; local current_frame = GameGetFrameNum(); local difference = current_frame - last_calibration_shot_frame; if difference < MISC.PerkOptions.MagicFocus.DecayFrames then return ( 1 - (difference / MISC.PerkOptions.MagicFocus.DecayFrames) ) * last_calibration_percent; else return math.min( 1, (difference - MISC.PerkOptions.MagicFocus.DecayFrames) / MISC.PerkOptions.MagicFocus.ChargeFrames); end end function get_entity_held_or_random_wand( entity, or_random ) if or_random == nil then or_random = true; end local base_wand = nil; local wands = {}; local children = EntityGetAllChildren( entity ) or {}; for key,child in pairs( children ) do if EntityGetName( child ) == "inventory_quick" then wands = EntityGetChildrenWithTag( child, "wand" ); break; end end if #wands > 0 then local inventory2 = EntityGetFirstComponent( entity, "Inventory2Component" ); local active_item = ComponentGetValue2( inventory2, "mActiveItem" ); for _,wand in pairs( wands ) do if wand == active_item then base_wand = wand; break; end end if base_wand == nil and or_random then SetRandomSeed( EntityGetTransform( entity ) ); base_wand = Random( 1, #wands ); end end return base_wand; end function entity_get_inventory_wands( entity ) local wands = {}; local inventory2 = EntityGetFirstComponent( entity, "Inventory2Component" ); if inventory2 ~= nil then for key, child in pairs( EntityGetAllChildren( entity ) or {} ) do if EntityGetName( child ) == "inventory_quick" then wands = EntityGetChildrenWithTag( child, "wand" ) or {}; break; end end end return wands; end function log_table( t ) for k,v in pairs(t) do print(k..": "..tostring(v)) end; end function change_materials_that_damage( entity, data ) for material,damage in pairs( data ) do EntitySetDamageFromMaterial( entity, material, damage ); end end function parse_custom_world_seed( seed ) seed = seed:gsub( "%a", function( value ) return tostring( value:byte( 1 ) ); end ); return tonumber( seed ) % (2 ^ 32); end function nexp( value, exponent ) return ( ( math.abs( value ^ 2 ) ) ^ exponent ) / value; end
412
0.946745
1
0.946745
game-dev
MEDIA
0.964513
game-dev
0.89311
1
0.89311
PopMedNet-Team/FDA-My-Studies-Mobile-Application-System
6,948
iOS/HPHC/Pods/Realm/include/core/realm/util/system_process.hpp
/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_UTIL_SYSTEM_PROCESS_HPP #define REALM_UTIL_SYSTEM_PROCESS_HPP #include <string> #include <vector> #include <map> #include <thread> #include <realm/util/logger.hpp> namespace realm { namespace util { namespace sys_proc { using Environment = std::map<std::string, std::string>; /// This function is safe to call only when the caller can be sure that there /// are no threads that modify the environment concurrently. /// /// When possible, call this function from the main thread before any other /// threads are created, such as early in `main()`. Environment copy_local_environment(); struct ExitInfo { /// If nonzero, the process was killed by a signal. The value is the /// signal number. int killed_by_signal = 0; /// Zero if the process was killed by a signal, otherwise this is the value /// returned by the `main()` function, or passed to `exit()`. /// /// On a POSIX system, if an error occurs during ::execve(), that is, after /// ::fork(), an exit status of 127 will be used (aligned with /// ::posix_spawn()). int status = 0; /// In some cases, ChildHandle::join() will set `signal_name` when it sets /// `killed_by_signal` to a non-zero value. In those cases, `signal_name` is /// set to point to a null-terminated string specifying the name of the /// signal that killed the child process. const char* signal_name = nullptr; /// Returns true if, and only if both `killed_by_signal` and `status` are /// zero. explicit operator bool() const noexcept; }; struct SpawnConfig { /// When set to true, the child process will be able to use a /// ParentDeathGuard to detect the destruction of the SystemProcess object /// in the parent process, even when this happens implicitly due to abrupt /// termination of the parent process. bool parent_death_guard = false; /// If a logger is specified here, the child process will be able to /// instantiate a ParentLogger object, and messages logged through that /// ParentLogger object will be transported to the parent process and /// submitted to the logger pointed to by `logger`. The specified logger is /// guaranteed to only be accessed while ChildHandle::join() is executing, /// and only by the thread that executes ChildHandle::join(). See /// ParentLogger for further details. Logger* logger = nullptr; }; class ChildHandle { public: /// Wait for the child process to exit. /// /// If a logger was passed to spawn() (SpawnConfig::logger), then this /// function will also transport log messages from the child to the parent /// process while waiting for the child process to exit. See ParentLogger /// for details. ExitInfo join(); ChildHandle(ChildHandle&&) noexcept; ~ChildHandle() noexcept; private: class Impl; std::unique_ptr<Impl> m_impl; ChildHandle(Impl*) noexcept; friend ChildHandle spawn(const std::string&, const std::vector<std::string>&, const Environment&, const SpawnConfig&); }; /// Returns true if, and only if the spawn() functions work on this platform. If /// this function returns false, the spawn() functions will throw. bool is_spawn_supported() noexcept; //@{ /// Spawn a child process. ChildHandle spawn(const std::string& path, const std::vector<std::string>& args = {}, const Environment& = {}); ChildHandle spawn(const std::string& path, const std::vector<std::string>& args, const Environment&, const SpawnConfig&); //@} /// Force a child process to terminate immediately if the parent process is /// terminated, or if the parent process destroys the ChildHandle object /// representing the child process. /// /// If a child process instantiates an object of this type, and keeps it alive, /// and the child process was spawned with support for detection of parent /// termination (SpawnConfig::parent_death_guard), then the child process will /// be killed shortly after the parent destroys its ChildHandle object, even /// when this happens implicitly due to abrupt termination of the parent /// process. /// /// If a child process instantiates an object of this type, that object must be /// instantiated by the main thread, and before any other thread is spawned in /// the child process. /// /// In order for the guard to have the intended effect, it must be instantiated /// immediately in the child process, and be kept alive for as long as the child /// process is running. class ParentDeathGuard { public: ParentDeathGuard(); ~ParentDeathGuard() noexcept; private: std::thread m_thread; int m_stop_pipe_write = -1; }; /// A logger that can transport log messages from the child to the parent /// process. /// /// If the parent process specifies a logger when spawning a child process /// (SpawnConfig::logger), then that child process can instantiate a /// ParentLogger object, and messages logged through it will be transported to /// the parent process. While the parent process is executing /// ChildHandle::join(), those messages will be written to the logger specified /// by the parent process. /// /// If a child process instantiates an object of this type, that object must be /// instantiated by the main thread, and before any other thread is spawned in /// the child process. /// /// At most one ParentLogger object may be instantiated per child process. /// /// This logger is **not** thread-safe. class ParentLogger : public RootLogger { public: ParentLogger(); ~ParentLogger() noexcept; protected: void do_log(Level, std::string) override final; private: int m_pipe_write = -1; }; // Implementation inline ExitInfo::operator bool() const noexcept { return (killed_by_signal == 0 && status == 0); } inline ChildHandle spawn(const std::string& path, const std::vector<std::string>& args, const Environment& env) { return spawn(path, args, env, SpawnConfig{}); // Throws } } // namespace sys_proc } // namespace util } // namespace realm #endif // REALM_UTIL_SYSTEM_PROCESS_HPP
412
0.970782
1
0.970782
game-dev
MEDIA
0.326684
game-dev
0.863767
1
0.863767
Dreamtowards/Ethertia
8,453
lib/physx-5.3.0/source/physxextensions/src/serialization/Binary/SnConvX.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SN_CONVX_H #define SN_CONVX_H #include "foundation/PxErrors.h" #include "common/PxTypeInfo.h" #include "extensions/PxBinaryConverter.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxArray.h" #include "foundation/PxHashMap.h" #include "SnConvX_Common.h" #include "SnConvX_Union.h" #include "SnConvX_MetaData.h" #include "SnConvX_Align.h" #define CONVX_ZERO_BUFFER_SIZE 256 namespace physx { class PxSerializationRegistry; namespace Sn { struct HeightFieldData; class PointerRemap { public: PointerRemap(); ~PointerRemap(); void setObjectRef(PxU64 object64, PxU32 ref); bool getObjectRef(PxU64 object64, PxU32& ref) const; typedef PxHashMap<PxU64, PxU32> PointerMap; PointerMap mData; }; class Handle16Remap { public: Handle16Remap(); ~Handle16Remap(); void setObjectRef(PxU16 object, PxU16 ref); bool getObjectRef(PxU16 object, PxU16& ref) const; typedef PxHashMap<PxU16, PxU16> Handle16Map; Handle16Map mData; }; class ConvX : public physx::PxBinaryConverter, public PxUserAllocated { public: ConvX(); virtual ~ConvX(); virtual void release(); virtual void setReportMode(PxConverterReportMode::Enum mode) { mReportMode = mode; } PX_FORCE_INLINE bool silentMode() const { return mReportMode==PxConverterReportMode::eNONE; } PX_FORCE_INLINE bool verboseMode() const { return mReportMode==PxConverterReportMode::eVERBOSE; } virtual bool setMetaData(PxInputStream& srcMetaData, PxInputStream& dstMetaData); virtual bool compareMetaData() const; virtual bool convert(PxInputStream& srcStream, PxU32 srcSize, PxOutputStream& targetStream); private: ConvX& operator=(const ConvX&); bool setMetaData(PxInputStream& inputStream, MetaDataType type); // Meta-data void releaseMetaData(); const MetaData* loadMetaData(PxInputStream& inputStream, MetaDataType type); const MetaData* getBinaryMetaData(MetaDataType type); int getNbMetaClasses(MetaDataType type); MetaClass* getMetaClass(unsigned int i, MetaDataType type) const; MetaClass* getMetaClass(const char* name, MetaDataType type) const; MetaClass* getMetaClass(PxConcreteType::Enum concreteType, MetaDataType type); MetaData* mMetaData_Src; MetaData* mMetaData_Dst; // Convert bool convert(const void* buffer, int fileSize); void resetConvexFlags(); void _enumerateFields(const MetaClass* mc, ExtraDataEntry2* entries, int& nb, int baseOffset, MetaDataType type) const; void _enumerateExtraData(const char* address, const MetaClass* mc, ExtraDataEntry* entries, int& nb, int offset, MetaDataType type) const; PxU64 read64(const void*& buffer); int read32(const void*& buffer); short read16(const void*& buffer); bool convertClass(const char* buffer, const MetaClass* mc, int offset); const char* convertExtraData_Array(const char* Address, const char* lastAddress, const char* objectAddress, const ExtraDataEntry& ed); const char* convertExtraData_Ptr(const char* Address, const char* lastAddress, const PxMetaDataEntry& entry, int count, int ptrSize_Src, int ptrSize_Dst); const char* convertExtraData_Handle(const char* Address, const char* lastAddress, const PxMetaDataEntry& entry, int count); int getConcreteType(const char* buffer); bool convertCollection(const void* buffer, int fileSize, int nbObjects); const void* convertManifestTable(const void* buffer, int& fileSize); const void* convertImportReferences(const void* buffer, int& fileSize); const void* convertExportReferences(const void* buffer, int& fileSize); const void* convertInternalReferences(const void* buffer, int& fileSize); const void* convertReferenceTables(const void* buffer, int& fileSize, int& nbObjectsInCollection); bool checkPaddingBytes(const char* buffer, int byteCount); // ---- big convex surgery ---- PsArray<bool> mConvexFlags; // Align const char* alignStream(const char* buffer, int alignment=ALIGN_DEFAULT); void alignTarget(int alignment); char mZeros[CONVX_ZERO_BUFFER_SIZE]; // Unions bool registerUnion(const char* name); bool registerUnionType(const char* unionName, const char* typeName, int typeValue); const char* getTypeName(const char* unionName, int typeValue); void resetUnions(); PsArray<Union> mUnions; // Output void setNullPtr(bool); void setNoOutput(bool); bool initOutput(PxOutputStream& targetStream); void closeOutput(); int getCurrentOutputSize(); void output(short value); void output(int value); void output(PxU64 value); void output(const char* buffer, int nbBytes); void convert8 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convertPad8 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convert16 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convert32 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convert64 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convertFloat(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convertPtr (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); void convertHandle16(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry); PxOutputStream* mOutStream; bool mMustFlip; int mOutputSize; int mSrcPtrSize; int mDstPtrSize; bool mNullPtr; bool mNoOutput; bool mMarkedPadding; // Errors void resetNbErrors(); int getNbErrors() const; void displayMessage(physx::PxErrorCode::Enum code, const char* format, ...); int mNbErrors; int mNbWarnings; // Settings PxConverterReportMode::Enum mReportMode; bool mPerformConversion; // Remap pointers void exportIntAsPtr(int value); void exportInt(int value); void exportInt64(PxU64 value); PointerRemap mPointerRemap; PointerRemap* mPointerActiveRemap; PxU32 mPointerRemapCounter; Handle16Remap mHandle16Remap; Handle16Remap* mHandle16ActiveRemap; PxU16 mHandle16RemapCounter; friend class MetaData; friend struct MetaClass; }; } } #endif
412
0.87611
1
0.87611
game-dev
MEDIA
0.218806
game-dev
0.550461
1
0.550461
copasi/COPASI
5,258
copasi/optimization/COptMethod.cpp
// Copyright (C) 2019 - 2025 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2002 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * COptMethod class * This class describes the interface to all optimization methods. * The various method like RandomSearch or GA have to be derived from * this class. * * Created for COPASI by Stefan Hoops 2002 */ #include <limits.h> #include "copasi/copasi.h" #include "copasi/optimization/COptTask.h" #include "copasi/optimization/COptMethod.h" #include "copasi/optimization/COptProblem.h" #include "copasi/core/CRootContainer.h" #include "copasi/commandline/CConfigurationFile.h" COptMethod::COptMethod(const CDataContainer * pParent, const CTaskEnum::Method & methodType, const CTaskEnum::Task & taskType, const bool & parallel) : CCopasiMethod(pParent, methodType, taskType) , mpParentTask(NULL) , mParallel(parallel) , mMathContext(parallel) , mProblemContext(parallel, this) , mLogVerbosity(0) , mMethodLog() { assertParameter("Log Verbosity", CCopasiParameter::Type::UINT, (unsigned C_INT32) 0, eUserInterfaceFlag::editable); } COptMethod::COptMethod(const COptMethod & src, const CDataContainer * pParent) : CCopasiMethod(src, pParent) , mpParentTask(src.mpParentTask) , mParallel(src.mParallel) , mMathContext(src.mParallel) , mProblemContext(src.mParallel, this) , mLogVerbosity(src.mLogVerbosity) , mMethodLog(src.mMethodLog) { mMathContext.setMaster(src.mMathContext.master()); mProblemContext.setMaster(src.mProblemContext.master()); mProblemContext.setMathContext(mMathContext); } //YOHE: seems "virtual" cannot be outside of class declaration COptMethod::~COptMethod() {} // static std::pair< C_FLOAT64, bool > COptMethod::objectiveValue(COptProblem * pProblem, const CVectorCore< C_FLOAT64 > & parameters) { std::pair< C_FLOAT64, bool > Result; pProblem->setParameters(parameters); Result.second = pProblem->calculate(); Result.first = pProblem->getCalculateValue(); return Result; } // static void COptMethod::reflect(COptProblem * pProblem, const C_FLOAT64 & bestValue, C_FLOAT64 & objectiveValue) { if (objectiveValue < bestValue && (!pProblem->checkParametricConstraints() || !pProblem->checkFunctionalConstraints())) objectiveValue = bestValue + bestValue - objectiveValue; } void COptMethod::setProblem(COptProblem * pProblem) { mProblemContext.setMaster(pProblem); mProblemContext.setMathContext(mMathContext); } //virtual C_INT32 COptMethod::Optimise(C_FLOAT64 (*func) (void)) bool COptMethod::optimise(void) { return false; } bool COptMethod::initialize() { if (mMathContext.master() == NULL || mProblemContext.master() == NULL) return false; mMathContext.sync(); mProblemContext.setMathContext(mMathContext); if (mProblemContext.size() > 1) #pragma omp parallel for for (size_t i = 0; i < mProblemContext.size(); ++i) { mProblemContext.threadData()[i]->initializeSubtaskBeforeOutput(); mProblemContext.threadData()[i]->initialize(); } mpParentTask = dynamic_cast<COptTask *>(getObjectParent()); if (!mpParentTask) return false; //new log mLogVerbosity = getValue< unsigned C_INT32 >("Log Verbosity"); mMethodLog = COptLog(); return true; } // virtual void COptMethod::signalMathContainerChanged() { mMathContext.setMaster(mpContainer); mProblemContext.setMathContext(mMathContext); } bool COptMethod::cleanup() {return true;} //virtual bool COptMethod::isValidProblem(const CCopasiProblem * pProblem) { if (!CCopasiMethod::isValidProblem(pProblem)) return false; const COptProblem * pTP = dynamic_cast<const COptProblem *>(pProblem); if (!pTP) { CCopasiMessage(CCopasiMessage::EXCEPTION, "Problem is not an optimization problem."); return false; } return true; } unsigned C_INT32 COptMethod::getMaxLogVerbosity() const { return 0; } const COptLog &COptMethod::getMethodLog() const { return mMethodLog; } C_FLOAT64 COptMethod::getBestValue() const { return std::numeric_limits< C_FLOAT64 >::infinity(); } C_FLOAT64 COptMethod::getCurrentValue() const { return std::numeric_limits< C_FLOAT64 >::infinity(); } const CVector< C_FLOAT64 > * COptMethod::getBestParameters() const { return NULL; } const CVector< C_FLOAT64 > * COptMethod::getCurrentParameters() const { return NULL; }
412
0.85816
1
0.85816
game-dev
MEDIA
0.284132
game-dev
0.868577
1
0.868577
ufocoder/fps
3,239
src/lib/ecs/systems/MapItemSystem.ts
import ECS from "src/lib/ecs"; import System from "src/lib/ecs/System"; import { Entity } from "src/lib/ecs/Entity"; import SoundManager from "src/managers/SoundManager"; import AnimationManager from "src/managers/AnimationManager"; import ItemComponent from "src/lib/ecs/components/ItemComponent"; import PlayerComponent from "src/lib/ecs/components/PlayerComponent"; import PositionComponent from "src/lib/ecs/components/PositionComponent"; import HealthComponent from "src/lib/ecs/components/HealthComponent"; import WeaponRangeComponent from "src/lib/ecs/components/WeaponRangeComponent"; import { WEAPON_PISTOL_INDEX } from "./WeaponSystem"; import { generatePistolWeapon } from "src/levels/generators/components"; export default class MapItemSystem extends System { public readonly componentsRequired = new Set([ PositionComponent, ItemComponent, ]); protected readonly animationManager: AnimationManager; protected readonly soundManager: SoundManager; constructor( ecs: ECS, animationManager: AnimationManager, soundManager: SoundManager ) { super(ecs); this.animationManager = animationManager; this.soundManager = soundManager; } start(): void {} update(_: number, entities: Set<Entity>) { const [player] = this.ecs.query([PlayerComponent, PositionComponent]); const playerContainer = this.ecs.getComponents(player); if (!playerContainer) { return; } const playerPlayer = playerContainer.get(PlayerComponent); const playerPosition = playerContainer.get(PositionComponent); const playerHealth = playerContainer.get(HealthComponent); const playerWeapon = playerContainer.get(WeaponRangeComponent); entities.forEach((entity) => { const entityItem = this.ecs.getComponents(entity).get(ItemComponent); const entityPosition = this.ecs .getComponents(entity) .get(PositionComponent); if ( Math.floor(playerPosition.x) === Math.floor(entityPosition.x) && Math.floor(playerPosition.y) === Math.floor(entityPosition.y) ) { if (!playerWeapon && entityItem.type === "pistol_weapon") { const pistolWeapon = generatePistolWeapon(this.animationManager); this.soundManager.playSound("pick"); playerPlayer.currentWeapon = pistolWeapon; if (!playerPlayer.weapons[WEAPON_PISTOL_INDEX]) { playerPlayer.weapons[WEAPON_PISTOL_INDEX] = pistolWeapon; } else { ( playerPlayer.weapons[WEAPON_PISTOL_INDEX] as WeaponRangeComponent ).bulletTotal += 30; } this.ecs.removeEntity(entity); } if ( playerPlayer.weapons[WEAPON_PISTOL_INDEX] && entityItem.type === "pistol_ammo" ) { this.soundManager.playSound("pick"); ( playerPlayer.weapons[WEAPON_PISTOL_INDEX] as WeaponRangeComponent ).bulletTotal += entityItem.value; this.ecs.removeEntity(entity); } if (playerHealth && entityItem.type === "health_pack") { playerHealth.current += entityItem.value; this.ecs.removeEntity(entity); } } }); } destroy(): void {} }
412
0.739787
1
0.739787
game-dev
MEDIA
0.938673
game-dev
0.823672
1
0.823672
scfmod/FS25_TerraFarm
4,447
scripts/gui/screens/SurveyorCursor.lua
---@class RaycastResult ---@field x number ---@field y number ---@field z number ---@field dx number ---@field dy number ---@field dz number ---@class SurveyorCursor : GuiTopDownCursor ---@field isActive boolean ---@field cursorOverlay Overlay ---@field ray RaycastResult ---@field errorMessage string|nil ---@field errorTime number ---@field raycastMode CursorRaycastMode ---@field raycastCollisionMask number ---@field raycastMaxDistance number ---@field currentHitX number ---@field currentHitY number ---@field currentHitZ number --- ---@field superClass fun(): GuiTopDownCursor SurveyorCursor = {} ---@enum CursorRaycastMode SurveyorCursor.RAYCAST_MODE = { NONE = 0, VEHICLE = 1, VEHICLE_TERRAIN = 2, } local SurveyorCursor_mt = Class(SurveyorCursor, GuiTopDownCursor) ---@return SurveyorCursor ---@nodiscard function SurveyorCursor.new() local self = GuiTopDownCursor.new(SurveyorCursor_mt) ---@cast self SurveyorCursor self:loadOverlay() self.raycastMode = SurveyorCursor.RAYCAST_MODE.NONE self.raycastCollisionMask = 0 self.raycastMaxDistance = 150 self.currentHitId = nil self.currentHitX = 0 self.currentHitY = 0 self.currentHitZ = 0 return self end function SurveyorCursor:loadOverlay() local uiScale = g_gameSettings:getValue("uiScale") local width, height = getNormalizedScreenValues(20 * uiScale, 20 * uiScale) self.cursorOverlay = Overlay.new(g_baseHUDFilename, 0.5, 0.5, width, height) self.cursorOverlay:setAlignment(Overlay.ALIGN_VERTICAL_MIDDLE, Overlay.ALIGN_HORIZONTAL_CENTER) self.cursorOverlay:setUVs(GuiUtils.getUVs({ 0, 48, 48, 48 })) self.cursorOverlay:setColor(1, 1, 1, 0.3) end ---@param mode CursorRaycastMode function SurveyorCursor:setRaycastMode(mode) if self.raycastMode ~= mode then if mode == SurveyorCursor.RAYCAST_MODE.VEHICLE_TERRAIN then -- self.raycastCollisionMask = CollisionFlag.TERRAIN + CollisionFlag.TERRAIN_DELTA + CollisionFlag.VEHICLE self.raycastCollisionMask = CollisionFlag.TERRAIN + CollisionFlag.VEHICLE elseif mode == SurveyorCursor.RAYCAST_MODE.VEHICLE then self.raycastCollisionMask = CollisionFlag.VEHICLE else self.raycastCollisionMask = 0 end self.currentHitId = nil self.currentHitX = 0 self.currentHitY = 0 self.currentHitZ = 0 end end function SurveyorCursor:activate() self.isActive = true self:onInputModeChanged({ g_inputBinding:getLastInputMode() }) self:registerActionEvents() g_messageCenter:subscribe(MessageType.INPUT_MODE_CHANGED, self.onInputModeChanged, self) end function SurveyorCursor:deactivate() self.isActive = false g_messageCenter:unsubscribeAll(self) self:removeActionEvents() end ---@param r number ---@param g number ---@param b number ---@param a number|nil function SurveyorCursor:setOverlayColor(r, g, b, a) self.cursorOverlay:setColor(r, g, b, a or 1) end ---@param message string|nil ---@param duration number|nil function SurveyorCursor:setErrorMessage(message, duration) if message ~= nil then duration = duration or 2000 self.errorMessage = message self.errorTime = g_time + duration else self.errorMessage = nil self.errorTime = 0 end end function SurveyorCursor:draw() if not self.isMouseMode then self.cursorOverlay:render() end end function SurveyorCursor:updateRaycast() local ray = self.ray local cursorShouldBeVisible = false if ray.x == nil then self.currentHitId = nil else local id, x, y, z = RaycastUtil.raycastClosest(ray.x, ray.y, ray.z, ray.dx, ray.dy, ray.dz, self.raycastMaxDistance, self.raycastCollisionMask) self.currentHitId, self.currentHitX, self.currentHitY, self.currentHitZ = id, x, y, z if id ~= nil then cursorShouldBeVisible = not self.hitTerrainOnly or g_terrainNode == id end end self:setVisible(cursorShouldBeVisible) end ---@return Surveyor | nil function SurveyorCursor:getHitVehicle() if self.currentHitId ~= nil and self.currentHitId ~= g_terrainNode then ---@type Surveyor | nil local object = g_currentMission:getNodeObject(self.currentHitId) if object ~= nil and object:isa(Vehicle) then return object end end end
412
0.897051
1
0.897051
game-dev
MEDIA
0.552859
game-dev,desktop-app
0.988228
1
0.988228
corecathx/LineTapper
11,848
src/lt/objects/play/Tile.hx
package lt.objects.play; import lt.backend.MapData.TileData; import lt.objects.play.Player.Direction; import openfl.geom.Rectangle; import openfl.display.BitmapData; import openfl.utils.ByteArray; import flixel.math.FlxRect; class Tile extends Sprite { /** Step offset for tile entrance animation. Starts early relative to the tile's time. **/ public static var _TILE_ENTER_OFFSET:Float = 6.4; /** Step offset for tile exit animation. Starts late after the tile's time (used when missed). **/ public static var _TILE_EXIT_OFFSET:Float = 1; /** Whether this tile can currently be hit. **/ public var hitable(get, never):Bool; /** Whether this tile should currently update. **/ public var canUpdate(get, never):Bool; /** Whether this tile has been missed. **/ public var invalid(get, never):Bool; /** Whether this tile can currently be released. **/ public var canRelease(get, never):Bool; /** Whether this tile has already been hit. **/ public var beenHit:Bool = false; /** Whether this tile was missed by the player. **/ public var missed:Bool = false; /** Whether this tile has already been released. **/ public var released:Bool = false; /** Whether the hold duration has ended. **/ public var holdFinish:Bool = false; /** The timing value (in steps) for this tile. **/ public var time(default, set):Float = 0; /** Hold length (in steps) for this tile. **/ public var length(default, set):Float = 0; /** Direction assigned to this tile. **/ public var direction(default, set):Direction = LEFT; /** (DEBUG) Multiplier for hold duration. **/ public var multiplier:Float = 1; /** Visual outline shown on hit. **/ public var hitOutline:TileEffect; /** Hold body sprite (used for hold tiles). **/ public var holdSprite:Sprite; /** Release tile sprite (used for hold tiles). **/ public var releaseSprite:Sprite; /** Reference to the main conductor. **/ private var conduct:Conductor = null; /** Whether this tile is placed in the editor. **/ public var editing:Bool = false; public function new(nX:Float, nY:Float, direction:Direction, time:Float, length:Float = 0.0) { super(nX, nY); setGraphic("play/tile"); this.time = time; this.direction = direction; conduct = Conductor.instance; // That one hit effect thing // var _graphicSize:Float = Player.BOX_SIZE + (200); hitOutline = new TileEffect(nX,nY).makeGraphic(300,300,0xFFFFFFFF); hitOutline.outline = 0.9; hitOutline.alpha = 0; hitOutline.setGraphicSize(_graphicSize,_graphicSize); hitOutline.updateHitbox(); // hold sprite // holdSprite = new Sprite().loadGraphic(Assets.image("play/hold")); holdSprite.active = false; // release sprite // releaseSprite = new Sprite().loadGraphic(Assets.image("play/stop_tile")); releaseSprite.active = false; releaseSprite.setGraphicSize(Player.BOX_SIZE, Player.BOX_SIZE); releaseSprite.updateHitbox(); this.length = length; } public function resetProp() { beenHit = false; missed = false; angle = 0; alpha = 1; time = time; setGraphicSize(Player.BOX_SIZE, Player.BOX_SIZE); updateHitbox(); } var _lastGraphic:String = ""; public function setGraphic(path:String) { if (_lastGraphic == path) return; _lastGraphic = path; loadGraphic(Assets.image(path)); setGraphicSize(Player.BOX_SIZE, Player.BOX_SIZE); updateHitbox(); } override function draw() { super.draw(); if (length > 0) { updateProps(); propDraw(holdSprite); propDraw(releaseSprite); } if (!editing) { hitOutline.x = x - (hitOutline.width - width) / 2; hitOutline.y = y - (hitOutline.height - height) / 2; hitOutline.draw(); } } function updateProps() { if (holdSprite == null || releaseSprite == null) return; switch (direction) { case LEFT: holdSprite.angle = 0; holdSprite.x = x - holdSprite.width; holdSprite.y = y + (height - holdSprite.height) * 0.5; releaseSprite.x = holdSprite.x - releaseSprite.width; releaseSprite.y = y + (height - releaseSprite.height) * 0.5; case DOWN: holdSprite.angle = 90; releaseSprite.x = x + (width - releaseSprite.width) * 0.5; releaseSprite.y = y + height + holdSprite.width; holdSprite.x = x + (width - holdSprite.width) * 0.5; holdSprite.y = y + height + (holdSprite.width-holdSprite.height)*0.5; case UP: holdSprite.angle = 90; releaseSprite.x = x + (width - releaseSprite.width) * 0.5; releaseSprite.y = y - (holdSprite.width+releaseSprite.height); holdSprite.x = x + (width - holdSprite.width) * 0.5; holdSprite.y = y - (holdSprite.width+holdSprite.height)*0.5; case RIGHT: holdSprite.angle = 0; holdSprite.x = x + width; holdSprite.y = y + (height - holdSprite.height) * 0.5; releaseSprite.x = holdSprite.x + holdSprite.width; releaseSprite.y = y + (height - releaseSprite.height) * 0.5; default: // do none } } function propDraw(spr:Sprite) { spr.alpha = alpha; spr.color = color; spr.draw(); } var _rotationAdd:Float = 0; var _scaleAdd:Float = 0; override function update(elapsed:Float) { super.update(elapsed); _updateAnimation(elapsed); } function _updateAnimation(elapsed:Float) { if (editing) return; var enterOffset:Float = conduct.step_ms * _TILE_ENTER_OFFSET; var exitOffset:Float = conduct.step_ms * _TILE_EXIT_OFFSET; var hitOffset:Float = conduct.step_ms * (_TILE_ENTER_OFFSET * 0.7); if (!beenHit) { if (conduct.time + hitOffset > time && conduct.time < time) { var timeDiff:Float = Math.abs(((conduct.time - time) % enterOffset) / enterOffset); var _animTime:Float = FlxEase.backOut(Math.abs(timeDiff)); var _graphicSize:Float = Player.BOX_SIZE + (100 * _animTime); hitOutline.scale.set(_graphicSize / hitOutline.frameWidth, _graphicSize / hitOutline.frameHeight); hitOutline.alpha += 6 * elapsed; } else { hitOutline.alpha -= 6 * elapsed; } if (conduct.time + enterOffset > time && !(conduct.time > time + exitOffset + length)) { alpha += 4 * elapsed; } else { alpha -= 4 * elapsed; } if (invalid && conduct.time > time + exitOffset) { color = 0xFFFF0000; } } else { if (conduct.time > time + length) { if (_rotationAdd == 0){ _rotationAdd = FlxG.random.float(-90, 90); alpha = 1; var toThis:Float = Player.BOX_SIZE/hitOutline.frameWidth; hitOutline.scale.set(toThis, toThis); hitOutline.alpha = 1; hitOutline.outline = 0.98; } scale.x += 0.05 * (elapsed*12); scale.y = scale.x; angle += _rotationAdd * elapsed; alpha -= 2 * elapsed; var _graphicSize:Float = Player.BOX_SIZE + (100); var lerpThing:Float = FlxMath.lerp(hitOutline.scale.x, _graphicSize/hitOutline.frameWidth, 12 * elapsed); hitOutline.scale.set(lerpThing, lerpThing); hitOutline.alpha -= 3 * elapsed; } } } override function destroy() { hitOutline?.destroy(); holdSprite?.destroy(); releaseSprite?.destroy(); super.destroy(); } inline function get_hitable():Bool { return time > Conductor.instance.time - (Conductor.instance.safe_zone_offset * 1.5) && time < Conductor.instance.time + (Conductor.instance.safe_zone_offset * 0.5); } inline function get_canUpdate():Bool { return Conductor.instance.time + (conduct.step_ms * _TILE_ENTER_OFFSET) > time && Conductor.instance.time < time + (conduct.beat_ms * (_TILE_EXIT_OFFSET+4)); } function get_invalid() { return !beenHit && time < (Conductor.instance.time - 166); } inline function get_canRelease():Bool { return time + length > Conductor.instance.time - (Conductor.instance.safe_zone_offset * 1.5) && time + length < Conductor.instance.time + (Conductor.instance.safe_zone_offset * 0.5); } function set_time(val:Float):Float { time = val; color = Utils.getTileColor(time, editing); return time = val; } function set_length(val:Float):Float { if (holdSprite!=null){ holdSprite.scale.x = (val/conduct.step_ms) * Player.BOX_SIZE * multiplier; holdSprite.scale.y = ((Player.BOX_SIZE*multiplier)*0.65) / holdSprite.frameHeight; holdSprite.updateHitbox(); } updateProps(); return length = val; } function set_direction(val:Direction):Direction { direction = val; var updateGraphic:Bool = true; switch (val) { case LEFT: angle = 90; case RIGHT: angle = -90; case UP: angle = 180; case DOWN: angle = 0; default: updateGraphic = false; setGraphic("play/stop_tile"); angle = 0; } if (updateGraphic) setGraphic("play/tile"); updateProps(); return val; } public function getData():TileData { return { direction: cast direction, length: this.length, time: this.time, event: [], type: '' }; } } /** * The hit approach outline of a Tile object. */ class TileEffect extends Sprite { public var outline(default, set):Float = 0; var _ogPixels:BitmapData; override public function loadGraphic(Graphic:Dynamic, Animated:Bool = false, Width:Int = 0, Height:Int = 0, Unique:Bool = false, Key:String = ""):TileEffect { super.loadGraphic(Graphic, Animated, Width, Height, Unique, Key); _ogPixels = this.pixels.clone(); return this; } override public function makeGraphic(Width:Int, Height:Int, Color:FlxColor = 0xFFFFFFFF, Unique:Bool = false, Key:String = ""):TileEffect { super.makeGraphic(Width, Height, Color, Unique, Key); _ogPixels = this.pixels.clone(); return this; } function set_outline(val:Float):Float { val = FlxMath.bound(val, 0, 1); pixels.copyPixels( _ogPixels, new Rectangle(0, 0, _ogPixels.width, _ogPixels.height), new openfl.geom.Point() ); var actualVal:Float = val; var innerW = frameWidth * val; var innerH = frameHeight * val; var innerX = (frameWidth - innerW) * 0.5; var innerY = (frameHeight - innerH) * 0.5; pixels.fillRect( new Rectangle(innerX, innerY, innerW, innerH), 0x00000000 ); return outline = val; } }
412
0.911424
1
0.911424
game-dev
MEDIA
0.767062
game-dev
0.995041
1
0.995041
pangcrd/LVGL_Bassic-tutorial
3,854
weather_station_simple_UI/lib/ArduinoJson/src/ArduinoJson/Collection/CollectionImpl.hpp
// ArduinoJson - https://arduinojson.org // Copyright © 2014-2025, Benoit BLANCHON // MIT License #pragma once #include <ArduinoJson/Collection/CollectionData.hpp> #include <ArduinoJson/Memory/Alignment.hpp> #include <ArduinoJson/Strings/StringAdapters.hpp> #include <ArduinoJson/Variant/VariantCompare.hpp> #include <ArduinoJson/Variant/VariantData.hpp> ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE inline CollectionIterator::CollectionIterator(VariantData* slot, SlotId slotId) : slot_(slot), currentId_(slotId) { nextId_ = slot_ ? slot_->next() : NULL_SLOT; } inline void CollectionIterator::next(const ResourceManager* resources) { ARDUINOJSON_ASSERT(currentId_ != NULL_SLOT); slot_ = resources->getVariant(nextId_); currentId_ = nextId_; if (slot_) nextId_ = slot_->next(); } inline CollectionData::iterator CollectionData::createIterator( const ResourceManager* resources) const { return iterator(resources->getVariant(head_), head_); } inline void CollectionData::appendOne(Slot<VariantData> slot, const ResourceManager* resources) { if (tail_ != NULL_SLOT) { auto tail = resources->getVariant(tail_); tail->setNext(slot.id()); tail_ = slot.id(); } else { head_ = slot.id(); tail_ = slot.id(); } } inline void CollectionData::appendPair(Slot<VariantData> key, Slot<VariantData> value, const ResourceManager* resources) { key->setNext(value.id()); if (tail_ != NULL_SLOT) { auto tail = resources->getVariant(tail_); tail->setNext(key.id()); tail_ = value.id(); } else { head_ = key.id(); tail_ = value.id(); } } inline void CollectionData::clear(ResourceManager* resources) { auto next = head_; while (next != NULL_SLOT) { auto currId = next; auto slot = resources->getVariant(next); next = slot->next(); resources->freeVariant({slot, currId}); } head_ = NULL_SLOT; tail_ = NULL_SLOT; } inline Slot<VariantData> CollectionData::getPreviousSlot( VariantData* target, const ResourceManager* resources) const { auto prev = Slot<VariantData>(); auto currentId = head_; while (currentId != NULL_SLOT) { auto currentSlot = resources->getVariant(currentId); if (currentSlot == target) break; prev = Slot<VariantData>(currentSlot, currentId); currentId = currentSlot->next(); } return prev; } inline void CollectionData::removeOne(iterator it, ResourceManager* resources) { if (it.done()) return; auto curr = it.slot_; auto prev = getPreviousSlot(curr, resources); auto next = curr->next(); if (prev) prev->setNext(next); else head_ = next; if (next == NULL_SLOT) tail_ = prev.id(); resources->freeVariant({it.slot_, it.currentId_}); } inline void CollectionData::removePair(ObjectData::iterator it, ResourceManager* resources) { if (it.done()) return; auto keySlot = it.slot_; auto valueId = it.nextId_; auto valueSlot = resources->getVariant(valueId); // remove value slot keySlot->setNext(valueSlot->next()); resources->freeVariant({valueSlot, valueId}); // remove key slot removeOne(it, resources); } inline size_t CollectionData::nesting(const ResourceManager* resources) const { size_t maxChildNesting = 0; for (auto it = createIterator(resources); !it.done(); it.next(resources)) { size_t childNesting = it->nesting(resources); if (childNesting > maxChildNesting) maxChildNesting = childNesting; } return maxChildNesting + 1; } inline size_t CollectionData::size(const ResourceManager* resources) const { size_t count = 0; for (auto it = createIterator(resources); !it.done(); it.next(resources)) count++; return count; } ARDUINOJSON_END_PRIVATE_NAMESPACE
412
0.951582
1
0.951582
game-dev
MEDIA
0.795974
game-dev
0.97945
1
0.97945
mikegashler/waffles
7,716
demos/bullet-2.77/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btSolve2LinearConstraint.h" #include "BulletDynamics/Dynamics/btRigidBody.h" #include "LinearMath/btVector3.h" #include "btJacobianEntry.h" void btSolve2LinearConstraint::resolveUnilateralPairConstraint( btRigidBody* body1, btRigidBody* body2, const btMatrix3x3& world2A, const btMatrix3x3& world2B, const btVector3& invInertiaADiag, const btScalar invMassA, const btVector3& linvelA,const btVector3& angvelA, const btVector3& rel_posA1, const btVector3& invInertiaBDiag, const btScalar invMassB, const btVector3& linvelB,const btVector3& angvelB, const btVector3& rel_posA2, btScalar depthA, const btVector3& normalA, const btVector3& rel_posB1,const btVector3& rel_posB2, btScalar depthB, const btVector3& normalB, btScalar& imp0,btScalar& imp1) { (void)linvelA; (void)linvelB; (void)angvelB; (void)angvelA; imp0 = btScalar(0.); imp1 = btScalar(0.); btScalar len = btFabs(normalA.length()) - btScalar(1.); if (btFabs(len) >= SIMD_EPSILON) return; btAssert(len < SIMD_EPSILON); //this jacobian entry could be re-used for all iterations btJacobianEntry jacA(world2A,world2B,rel_posA1,rel_posA2,normalA,invInertiaADiag,invMassA, invInertiaBDiag,invMassB); btJacobianEntry jacB(world2A,world2B,rel_posB1,rel_posB2,normalB,invInertiaADiag,invMassA, invInertiaBDiag,invMassB); //const btScalar vel0 = jacA.getRelativeVelocity(linvelA,angvelA,linvelB,angvelB); //const btScalar vel1 = jacB.getRelativeVelocity(linvelA,angvelA,linvelB,angvelB); const btScalar vel0 = normalA.dot(body1->getVelocityInLocalPoint(rel_posA1)-body2->getVelocityInLocalPoint(rel_posA1)); const btScalar vel1 = normalB.dot(body1->getVelocityInLocalPoint(rel_posB1)-body2->getVelocityInLocalPoint(rel_posB1)); // btScalar penetrationImpulse = (depth*contactTau*timeCorrection) * massTerm;//jacDiagABInv btScalar massTerm = btScalar(1.) / (invMassA + invMassB); // calculate rhs (or error) terms const btScalar dv0 = depthA * m_tau * massTerm - vel0 * m_damping; const btScalar dv1 = depthB * m_tau * massTerm - vel1 * m_damping; // dC/dv * dv = -C // jacobian * impulse = -error // //impulse = jacobianInverse * -error // inverting 2x2 symmetric system (offdiagonal are equal!) // btScalar nonDiag = jacA.getNonDiagonal(jacB,invMassA,invMassB); btScalar invDet = btScalar(1.0) / (jacA.getDiagonal() * jacB.getDiagonal() - nonDiag * nonDiag ); //imp0 = dv0 * jacA.getDiagonal() * invDet + dv1 * -nonDiag * invDet; //imp1 = dv1 * jacB.getDiagonal() * invDet + dv0 * - nonDiag * invDet; imp0 = dv0 * jacA.getDiagonal() * invDet + dv1 * -nonDiag * invDet; imp1 = dv1 * jacB.getDiagonal() * invDet + dv0 * - nonDiag * invDet; //[a b] [d -c] //[c d] inverse = (1 / determinant) * [-b a] where determinant is (ad - bc) //[jA nD] * [imp0] = [dv0] //[nD jB] [imp1] [dv1] } void btSolve2LinearConstraint::resolveBilateralPairConstraint( btRigidBody* body1, btRigidBody* body2, const btMatrix3x3& world2A, const btMatrix3x3& world2B, const btVector3& invInertiaADiag, const btScalar invMassA, const btVector3& linvelA,const btVector3& angvelA, const btVector3& rel_posA1, const btVector3& invInertiaBDiag, const btScalar invMassB, const btVector3& linvelB,const btVector3& angvelB, const btVector3& rel_posA2, btScalar depthA, const btVector3& normalA, const btVector3& rel_posB1,const btVector3& rel_posB2, btScalar depthB, const btVector3& normalB, btScalar& imp0,btScalar& imp1) { (void)linvelA; (void)linvelB; (void)angvelA; (void)angvelB; imp0 = btScalar(0.); imp1 = btScalar(0.); btScalar len = btFabs(normalA.length()) - btScalar(1.); if (btFabs(len) >= SIMD_EPSILON) return; btAssert(len < SIMD_EPSILON); //this jacobian entry could be re-used for all iterations btJacobianEntry jacA(world2A,world2B,rel_posA1,rel_posA2,normalA,invInertiaADiag,invMassA, invInertiaBDiag,invMassB); btJacobianEntry jacB(world2A,world2B,rel_posB1,rel_posB2,normalB,invInertiaADiag,invMassA, invInertiaBDiag,invMassB); //const btScalar vel0 = jacA.getRelativeVelocity(linvelA,angvelA,linvelB,angvelB); //const btScalar vel1 = jacB.getRelativeVelocity(linvelA,angvelA,linvelB,angvelB); const btScalar vel0 = normalA.dot(body1->getVelocityInLocalPoint(rel_posA1)-body2->getVelocityInLocalPoint(rel_posA1)); const btScalar vel1 = normalB.dot(body1->getVelocityInLocalPoint(rel_posB1)-body2->getVelocityInLocalPoint(rel_posB1)); // calculate rhs (or error) terms const btScalar dv0 = depthA * m_tau - vel0 * m_damping; const btScalar dv1 = depthB * m_tau - vel1 * m_damping; // dC/dv * dv = -C // jacobian * impulse = -error // //impulse = jacobianInverse * -error // inverting 2x2 symmetric system (offdiagonal are equal!) // btScalar nonDiag = jacA.getNonDiagonal(jacB,invMassA,invMassB); btScalar invDet = btScalar(1.0) / (jacA.getDiagonal() * jacB.getDiagonal() - nonDiag * nonDiag ); //imp0 = dv0 * jacA.getDiagonal() * invDet + dv1 * -nonDiag * invDet; //imp1 = dv1 * jacB.getDiagonal() * invDet + dv0 * - nonDiag * invDet; imp0 = dv0 * jacA.getDiagonal() * invDet + dv1 * -nonDiag * invDet; imp1 = dv1 * jacB.getDiagonal() * invDet + dv0 * - nonDiag * invDet; //[a b] [d -c] //[c d] inverse = (1 / determinant) * [-b a] where determinant is (ad - bc) //[jA nD] * [imp0] = [dv0] //[nD jB] [imp1] [dv1] if ( imp0 > btScalar(0.0)) { if ( imp1 > btScalar(0.0) ) { //both positive } else { imp1 = btScalar(0.); // now imp0>0 imp1<0 imp0 = dv0 / jacA.getDiagonal(); if ( imp0 > btScalar(0.0) ) { } else { imp0 = btScalar(0.); } } } else { imp0 = btScalar(0.); imp1 = dv1 / jacB.getDiagonal(); if ( imp1 <= btScalar(0.0) ) { imp1 = btScalar(0.); // now imp0>0 imp1<0 imp0 = dv0 / jacA.getDiagonal(); if ( imp0 > btScalar(0.0) ) { } else { imp0 = btScalar(0.); } } else { } } } /* void btSolve2LinearConstraint::resolveAngularConstraint( const btMatrix3x3& invInertiaAWS, const btScalar invMassA, const btVector3& linvelA,const btVector3& angvelA, const btVector3& rel_posA1, const btMatrix3x3& invInertiaBWS, const btScalar invMassB, const btVector3& linvelB,const btVector3& angvelB, const btVector3& rel_posA2, btScalar depthA, const btVector3& normalA, const btVector3& rel_posB1,const btVector3& rel_posB2, btScalar depthB, const btVector3& normalB, btScalar& imp0,btScalar& imp1) { } */
412
0.903834
1
0.903834
game-dev
MEDIA
0.894363
game-dev
0.993057
1
0.993057
OpenTTD/OpenTTD
6,824
src/saveload/game_sl.cpp
/* * This file is part of OpenTTD. * OpenTTD 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, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file game_sl.cpp Handles the saveload part of the GameScripts */ #include "../stdafx.h" #include "../debug.h" #include "saveload.h" #include "compat/game_sl_compat.h" #include "../string_func.h" #include "../game/game.hpp" #include "../game/game_config.hpp" #include "../network/network.h" #include "../game/game_instance.hpp" #include "../game/game_text.hpp" #include "../safeguards.h" static std::string _game_saveload_name; static int _game_saveload_version; static std::string _game_saveload_settings; static const SaveLoad _game_script_desc[] = { SLEG_SSTR("name", _game_saveload_name, SLE_STR), SLEG_SSTR("settings", _game_saveload_settings, SLE_STR), SLEG_VAR("version", _game_saveload_version, SLE_UINT32), }; static void SaveReal_GSDT(int) { GameConfig *config = GameConfig::GetConfig(); if (config->HasScript()) { _game_saveload_name = config->GetName(); _game_saveload_version = config->GetVersion(); } else { /* No GameScript is configured for this so store an empty string as name. */ _game_saveload_name.clear(); _game_saveload_version = -1; } _game_saveload_settings = config->SettingsToString(); SlObject(nullptr, _game_script_desc); Game::Save(); } struct GSDTChunkHandler : ChunkHandler { GSDTChunkHandler() : ChunkHandler('GSDT', CH_TABLE) {} void Load() const override { const std::vector<SaveLoad> slt = SlCompatTableHeader(_game_script_desc, _game_script_sl_compat); /* Free all current data */ GameConfig::GetConfig(GameConfig::SSS_FORCE_GAME)->Change(std::nullopt); if (SlIterateArray() == -1) return; _game_saveload_version = -1; SlObject(nullptr, slt); if (_game_mode == GM_MENU || (_networking && !_network_server)) { GameInstance::LoadEmpty(); if (SlIterateArray() != -1) SlErrorCorrupt("Too many GameScript configs"); return; } GameConfig *config = GameConfig::GetConfig(GameConfig::SSS_FORCE_GAME); if (!_game_saveload_name.empty()) { config->Change(_game_saveload_name, _game_saveload_version, false); if (!config->HasScript()) { /* No version of the GameScript available that can load the data. Try to load the * latest version of the GameScript instead. */ config->Change(_game_saveload_name, -1, false); if (!config->HasScript()) { if (_game_saveload_name.compare("%_dummy") != 0) { Debug(script, 0, "The savegame has an GameScript by the name '{}', version {} which is no longer available.", _game_saveload_name, _game_saveload_version); Debug(script, 0, "This game will continue to run without GameScript."); } else { Debug(script, 0, "The savegame had no GameScript available at the time of saving."); Debug(script, 0, "This game will continue to run without GameScript."); } } else { Debug(script, 0, "The savegame has an GameScript by the name '{}', version {} which is no longer available.", _game_saveload_name, _game_saveload_version); Debug(script, 0, "The latest version of that GameScript has been loaded instead, but it'll not get the savegame data as it's incompatible."); } /* Make sure the GameScript doesn't get the saveload data, as it was not the * writer of the saveload data in the first place */ _game_saveload_version = -1; } } config->StringToSettings(_game_saveload_settings); /* Load the GameScript saved data */ config->SetToLoadData(GameInstance::Load(_game_saveload_version)); if (SlIterateArray() != -1) SlErrorCorrupt("Too many GameScript configs"); } void Save() const override { SlTableHeader(_game_script_desc); SlSetArrayIndex(0); SlAutolength(SaveReal_GSDT, 0); } }; extern std::shared_ptr<GameStrings> _current_gamestrings_data; static std::string _game_saveload_string; static uint32_t _game_saveload_strings; class SlGameLanguageString : public DefaultSaveLoadHandler<SlGameLanguageString, LanguageStrings> { public: static inline const SaveLoad description[] = { SLEG_SSTR("string", _game_saveload_string, SLE_STR | SLF_ALLOW_CONTROL | SLF_REPLACE_TABCRLF), }; static inline const SaveLoadCompatTable compat_description = _game_language_string_sl_compat; void Save(LanguageStrings *ls) const override { SlSetStructListLength(ls->lines.size()); for (const auto &string : ls->lines) { _game_saveload_string = string; SlObject(nullptr, this->GetDescription()); } } void Load(LanguageStrings *ls) const override { uint32_t length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? _game_saveload_strings : (uint32_t)SlGetStructListLength(UINT32_MAX); for (uint32_t i = 0; i < length; i++) { SlObject(nullptr, this->GetLoadDescription()); ls->lines.emplace_back(_game_saveload_string); } } }; static const SaveLoad _game_language_desc[] = { SLE_SSTR(LanguageStrings, language, SLE_STR), SLEG_CONDVAR("count", _game_saveload_strings, SLE_UINT32, SL_MIN_VERSION, SLV_SAVELOAD_LIST_LENGTH), SLEG_STRUCTLIST("strings", SlGameLanguageString), }; struct GSTRChunkHandler : ChunkHandler { GSTRChunkHandler() : ChunkHandler('GSTR', CH_TABLE) {} void Load() const override { const std::vector<SaveLoad> slt = SlCompatTableHeader(_game_language_desc, _game_language_sl_compat); _current_gamestrings_data = std::make_shared<GameStrings>(); while (SlIterateArray() != -1) { LanguageStrings ls; SlObject(&ls, slt); _current_gamestrings_data->raw_strings.push_back(std::move(ls)); } /* If there were no strings in the savegame, set GameStrings to nullptr */ if (_current_gamestrings_data->raw_strings.empty()) { _current_gamestrings_data.reset(); return; } _current_gamestrings_data->Compile(); ReconsiderGameScriptLanguage(); } void Save() const override { SlTableHeader(_game_language_desc); if (_current_gamestrings_data == nullptr) return; for (uint i = 0; i < _current_gamestrings_data->raw_strings.size(); i++) { SlSetArrayIndex(i); SlObject(&_current_gamestrings_data->raw_strings[i], _game_language_desc); } } }; static const GSTRChunkHandler GSTR; static const GSDTChunkHandler GSDT; static const ChunkHandlerRef game_chunk_handlers[] = { GSTR, GSDT, }; extern const ChunkHandlerTable _game_chunk_handlers(game_chunk_handlers);
412
0.875179
1
0.875179
game-dev
MEDIA
0.901453
game-dev
0.786808
1
0.786808
manfromarce/DocSharp
1,628
src/DocSharp.Binary/DocSharp.Binary.Common/OlePropertySet/PropertySet.cs
using System; using System.Collections.Generic; using System.IO; using DocSharp.Binary.StructuredStorage.Reader; namespace DocSharp.Binary.OlePropertySet { public class PropertySet : List<object> { private uint size; private uint numProperties; private uint[] identifiers; private uint[] offsets; public PropertySet(VirtualStreamReader stream) { long pos = stream.BaseStream.Position; //read size and number of properties this.size = stream.ReadUInt32(); this.numProperties = stream.ReadUInt32(); //read the identifier and offsets this.identifiers = new uint[this.numProperties]; this.offsets = new uint[this.numProperties]; for (int i = 0; i < this.numProperties; i++) { this.identifiers[i] = stream.ReadUInt32(); this.offsets[i] = stream.ReadUInt32(); } //read the properties for (int i = 0; i < this.numProperties; i++) { if (this.identifiers[i] == 0) { // dictionary property throw new NotImplementedException("Dictionary Properties are not yet implemented!"); } else { // value property this.Add(new ValueProperty(stream)); } } // seek to the end of the property set to avoid crashes stream.BaseStream.Seek(pos + this.size, SeekOrigin.Begin); } } }
412
0.6932
1
0.6932
game-dev
MEDIA
0.285227
game-dev
0.892337
1
0.892337
Admer456/halflife-adm
2,850
src/common/cl_entity.h
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // cl_entity.h #pragma once struct cl_entity_t; struct mleaf_t; struct mnode_t; struct model_t; struct efrag_t { mleaf_t* leaf; efrag_t* leafnext; cl_entity_t* entity; efrag_t* entnext; }; struct mouth_t { byte mouthopen; // 0 = mouth closed, 255 = mouth agape byte sndcount; // counter for running average int sndavg; // running average }; struct latchedvars_t { float prevanimtime; float sequencetime; byte prevseqblending[2]; Vector prevorigin; Vector prevangles; int prevsequence; float prevframe; byte prevcontroller[4]; byte prevblending[2]; }; struct position_history_t { // Time stamp for this movement float animtime; Vector origin; Vector angles; }; #define HISTORY_MAX 64 // Must be power of 2 #define HISTORY_MASK (HISTORY_MAX - 1) #include "entity_state.h" #include "progs.h" struct cl_entity_t { int index; // Index into cl_entities ( should match actual slot, but not necessarily ) qboolean player; // True if this entity is a "player" entity_state_t baseline; // The original state from which to delta during an uncompressed message entity_state_t prevstate; // The state information from the penultimate message received from the server entity_state_t curstate; // The state information from the last message received from server int current_position; // Last received history update index position_history_t ph[HISTORY_MAX]; // History of position and angle updates for this player mouth_t mouth; // For synchronizing mouth movements. latchedvars_t latched; // Variables used by studio model rendering routines // Information based on interplocation, extrapolation, prediction, or just copied from last msg received. // float lastmove; // Actual render position and angles Vector origin; Vector angles; // Attachment points Vector attachment[4]; // Other entity local information int trivial_accept; model_t* model; // cl.model_precache[ curstate.modelindes ]; all visible entities have a model efrag_t* efrag; // linked list of efrags mnode_t* topnode; // for bmodels, first world node that splits bmodel, or nullptr if not split float syncbase; // for client-side animations -- used by obsolete alias animation system, remove? int visframe; // last frame this entity was found in an active leaf colorVec cvFloorColor; };
412
0.925871
1
0.925871
game-dev
MEDIA
0.759738
game-dev
0.510836
1
0.510836
wvwwvwwv/scalable-delayed-dealloc
4,968
src/guard.rs
use std::panic::{RefUnwindSafe, UnwindSafe}; use std::ptr::NonNull; use crate::Epoch; use crate::collectible::DeferredClosure; use crate::collector::Collector; /// [`Guard`] allows the user to read [`AtomicShared`](super::AtomicShared) and keeps the /// underlying instance pinned to the thread. /// /// [`Guard`] internally prevents the global epoch value from passing through the value /// announced by the current thread, thus keeping reachable instances in the thread from being /// garbage collected. #[derive(Debug)] pub struct Guard { collector_ptr: NonNull<Collector>, } impl Guard { /// Creates a new [`Guard`]. /// /// # Panics /// /// The maximum number of [`Guard`] instances in a thread is limited to `u32::MAX`; a /// thread panics when the number of [`Guard`] instances in the thread exceeds the limit. /// /// # Examples /// /// ``` /// use sdd::Guard; /// /// let guard = Guard::new(); /// ``` #[inline] #[must_use] pub fn new() -> Self { let collector_ptr = Collector::current(); Collector::new_guard(collector_ptr.as_ptr(), true); Self { collector_ptr } } /// Returns the epoch in which the current thread lives. /// /// This method can be used to check whether a retired memory region is potentially reachable or /// not. A chunk of memory retired in a witnessed [`Epoch`] can be deallocated after the thread /// has observed three new epochs. For instance, if the witnessed epoch value is `1` in the /// current thread where the global epoch value is `2`, and an instance is retired in the same /// thread, the instance can be dropped when the thread witnesses `0` which is three epochs away /// from `1`. /// /// In other words, there can be potential readers of the memory chunk until the current thread /// witnesses the previous epoch. In the above example, the global epoch can be in `2` /// while the current thread has only witnessed `1`, and therefore there can a reader of the /// memory chunk in another thread in epoch `2`. The reader can survive until the global epoch /// reaches `0`, because the thread being in `2` prevents the global epoch from reaching `0`. /// /// # Examples /// /// ``` /// use sdd::{Guard, Owned}; /// use std::sync::atomic::AtomicBool; /// use std::sync::atomic::Ordering::Relaxed; /// /// static DROPPED: AtomicBool = AtomicBool::new(false); /// /// struct D(&'static AtomicBool); /// /// impl Drop for D { /// fn drop(&mut self) { /// self.0.store(true, Relaxed); /// } /// } /// /// let owned = Owned::new(D(&DROPPED)); /// /// let epoch_before = Guard::new().epoch(); /// /// drop(owned); /// assert!(!DROPPED.load(Relaxed)); /// /// while Guard::new().epoch() == epoch_before { /// assert!(!DROPPED.load(Relaxed)); /// } /// /// while Guard::new().epoch() == epoch_before.next() { /// assert!(!DROPPED.load(Relaxed)); /// } /// /// while Guard::new().epoch() == epoch_before.next().next() { /// assert!(!DROPPED.load(Relaxed)); /// } /// /// assert!(DROPPED.load(Relaxed)); /// assert_eq!(Guard::new().epoch(), epoch_before.next().next().next()); /// ``` #[inline] #[must_use] pub fn epoch(&self) -> Epoch { Collector::current_epoch() } /// Forces the [`Guard`] to try to start a new epoch when it is dropped. /// /// # Examples /// /// ``` /// use sdd::Guard; /// /// let guard = Guard::new(); /// /// let epoch = guard.epoch(); /// guard.accelerate(); /// /// drop(guard); /// /// assert_ne!(epoch, Guard::new().epoch()); /// ``` #[inline] pub fn accelerate(&self) { unsafe { (*self.collector_ptr.as_ptr()).accelerate(); } } /// Executes the supplied closure at a later point of time. /// /// It is guaranteed that the closure will be executed after every [`Guard`] at the moment when /// the method was invoked is dropped, however it is totally non-deterministic when exactly the /// closure will be executed. /// /// # Examples /// /// ``` /// use sdd::Guard; /// /// let guard = Guard::new(); /// guard.defer_execute(|| println!("deferred")); /// ``` #[inline] pub fn defer_execute<F: 'static + FnOnce()>(&self, f: F) { Collector::collect( self.collector_ptr.as_ptr(), Box::into_raw(Box::new(DeferredClosure::new(f))), ); } } impl Default for Guard { #[inline] fn default() -> Self { Self::new() } } impl Drop for Guard { #[inline] fn drop(&mut self) { Collector::end_guard(self.collector_ptr.as_ptr()); } } impl RefUnwindSafe for Guard {} impl UnwindSafe for Guard {}
412
0.937328
1
0.937328
game-dev
MEDIA
0.445458
game-dev
0.894859
1
0.894859
mit-gfx/VLMaterial
3,327
infinigen/worldgen/tools/dev/generate_terrain_assets.py
# Copyright (c) Princeton University. # This source code is licensed under the BSD 3-Clause license found in the LICENSE file in the root directory of this source tree. # Authors: Zeyu Ma ''' fileheader placeholder ''' import os import sys import argparse from pathlib import Path sys.path.append(os.getcwd()) import bpy from terrain.assets.caves import caves_asset from terrain.assets.landtiles import landtile_asset from terrain.assets.upsidedown_mountains import upsidedown_mountains_asset from util import blender as butil from util.math import int_hash, FixedSeed from util.organization import Assets, LandTile, AssetFile def asset_generation( output_folder, assets, instance_ids, seed, device, check_only=False, ): for i in instance_ids: for asset in assets: if asset in [LandTile.Mesa, LandTile.Canyon, LandTile.Canyons, LandTile.Cliff, LandTile.Mountain, LandTile.River, LandTile.Volcano, LandTile.MultiMountains, LandTile.Coast]: if not (output_folder/asset/f"{i}"/AssetFile.Finish).exists(): print(asset, i) if not check_only: with FixedSeed(int_hash([asset, seed, i])): landtile_asset(output_folder/asset/f"{i}", asset, device=device) if asset == Assets.UpsidedownMountains: if not (output_folder/asset/f"{i}"/AssetFile.Finish).exists(): print(asset, i) if not check_only: with FixedSeed(int_hash([asset, seed, i])): upsidedown_mountains_asset(output_folder/Assets.UpsidedownMountains/f"{i}", device=device) if asset == Assets.Caves: if not (output_folder/asset/f"{i}"/AssetFile.Finish).exists(): print(asset, i) if not check_only: with FixedSeed(int_hash([asset, seed, i])): caves_asset(output_folder/Assets.Caves/f"{i}") if __name__ == "__main__": # by default infinigen does on-the-fly terrain asset generation, but if you want to pre-generate a pool of assets, run this code parser = argparse.ArgumentParser() parser.add_argument('-a', '--assets', nargs='+', default=[ LandTile.MultiMountains, LandTile.Coast, LandTile.Mesa, LandTile.Canyon, LandTile.Canyons, LandTile.Cliff, LandTile.Mountain, LandTile.River, LandTile.Volcano, Assets.UpsidedownMountains, Assets.Caves, ]) parser.add_argument('-s', '--start', type=int, default=0) parser.add_argument('-e', '--end', type=int, default=1) parser.add_argument('-f', '--folder') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--check_only', type=int, default=0) parser.add_argument('--device', type=str, default="cpu") args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:]) bpy.ops.preferences.addon_enable(module='add_mesh_extra_objects') bpy.ops.preferences.addon_enable(module='ant_landscape') butil.clear_scene(targets=[bpy.data.objects]) asset_generation(Path(args.folder), args.assets, list(range(args.start, args.end)), args.seed, args.device, check_only=args.check_only)
412
0.853456
1
0.853456
game-dev
MEDIA
0.84798
game-dev
0.894395
1
0.894395
Karl-HeinzSchneider/WoW-DragonflightUI
40,475
Embed/AuraDurations/Libs/LibClassicDurations/core.lua
--[================[ LibClassicDurations Author: d87 Description: Tracks all aura applications in combat log and provides duration, expiration time. And additionally enemy buffs info. Usage example 1: ----------------- -- Using UnitAura wrapper local UnitAura = _G.UnitAura local LibClassicDurations = LibStub("LibClassicDurations", true) if LibClassicDurations then LibClassicDurations:Register("YourAddon") UnitAura = LibClassicDurations.UnitAuraWrapper end --]================] if WOW_PROJECT_ID ~= WOW_PROJECT_CLASSIC then return end local MAJOR, MINOR = "LibClassicDurations", 71 local lib = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end lib.callbacks = lib.callbacks or LibStub("CallbackHandler-1.0"):New(lib) lib.frame = lib.frame or CreateFrame("Frame") lib.guids = lib.guids or {} lib.spells = lib.spells or {} lib.npc_spells = lib.npc_spells or {} lib.spellNameToID = lib.spellNameToID or {} local spellNameToID = lib.spellNameToID local NPCspellNameToID = {} if lib.NPCSpellTableTimer then lib.NPCSpellTableTimer:Cancel() end lib.DRInfo = lib.DRInfo or {} local DRInfo = lib.DRInfo lib.buffCache = lib.buffCache or {} local buffCache = lib.buffCache local buffCacheValid = {} lib.nameplateUnitMap = lib.nameplateUnitMap or {} local nameplateUnitMap = lib.nameplateUnitMap lib.castLog = lib.castLog or {} local castLog = lib.castLog lib.guidAccessTimes = lib.guidAccessTimes or {} local guidAccessTimes = lib.guidAccessTimes local f = lib.frame local callbacks = lib.callbacks local guids = lib.guids local spells = lib.spells local npc_spells = lib.npc_spells local indirectRefreshSpells = lib.indirectRefreshSpells local INFINITY = math.huge local PURGE_INTERVAL = 900 local PURGE_THRESHOLD = 1800 local UNKNOWN_AURA_DURATION = 3600 -- 60m local BUFF_CACHE_EXPIRATION_TIME = 40 local CombatLogGetCurrentEventInfo = CombatLogGetCurrentEventInfo local UnitGUID = UnitGUID local UnitAura = UnitAura local GetSpellInfo = GetSpellInfo local GetTime = GetTime local tinsert = table.insert local unpack = unpack local GetGUIDAuraTime local time = time if lib.enableEnemyBuffTracking == nil then lib.enableEnemyBuffTracking = false end local enableEnemyBuffTracking = lib.enableEnemyBuffTracking local COMBATLOG_OBJECT_CONTROL_PLAYER = COMBATLOG_OBJECT_CONTROL_PLAYER f:SetScript("OnEvent", function(self, event, ...) return self[event](self, event, ...) end) lib.dataVersions = lib.dataVersions or {} local SpellDataVersions = lib.dataVersions function lib:SetDataVersion(dataType, version) SpellDataVersions[dataType] = version npc_spells = lib.npc_spells indirectRefreshSpells = lib.indirectRefreshSpells end function lib:GetDataVersion(dataType) return SpellDataVersions[dataType] or 0 end lib.AddAura = function(id, opts) if not opts then return end local lastRankID if type(id) == "table" then local clones = id lastRankID = clones[#clones] else lastRankID = id end local spellName = GetSpellInfo(lastRankID) if not spellName then -- print(MINOR, lastRankID, spellName) return end spellNameToID[spellName] = lastRankID if type(id) == "table" then for _, spellID in ipairs(id) do spells[spellID] = opts end else spells[id] = opts end end lib.Talent = function (...) for i=1, 5 do local spellID = select(i, ...) if not spellID then break end if IsPlayerSpell(spellID) then return i end end return 0 end local prevID local counter = 0 local function processNPCSpellTable() local dataTable = lib.npc_spells counter = 0 local id = next(dataTable, prevID) while (id and counter < 300) do local spellName = GetSpellInfo(id) if spellName then NPCspellNameToID[GetSpellInfo(id)] = id end counter = counter + 1 prevID = id id = next(dataTable, prevID) end if (id) then C_Timer.After(1, processNPCSpellTable) end end lib.NPCSpellTableTimer = C_Timer.NewTimer(10, processNPCSpellTable) local function isHunterGUID(guid) return select(2, GetPlayerInfoByGUID(guid)) == "HUNTER" end local function isFriendlyFeigning(guid) if IsInRaid() then for i = 1, MAX_RAID_MEMBERS do local unitID = "raid"..i if (UnitGUID(unitID) == guid) and UnitIsFeignDeath(unitID) then return true end end elseif IsInGroup() then for i = 1, MAX_PARTY_MEMBERS do local unitID = "party"..i if (UnitGUID(unitID) == guid) and UnitIsFeignDeath(unitID) then return true end end end end -------------------------- -- OLD GUIDs PURGE -------------------------- local function purgeOldGUIDsArgs(dataTable, accessTimes) local now = time() local deleted = {} for guid, lastAccessTime in pairs(accessTimes) do if lastAccessTime + PURGE_THRESHOLD < now then dataTable[guid] = nil nameplateUnitMap[guid] = nil buffCacheValid[guid] = nil buffCache[guid] = nil DRInfo[guid] = nil castLog[guid] = nil tinsert(deleted, guid) end end for _, guid in ipairs(deleted) do accessTimes[guid] = nil end end local function purgeOldGUIDs() purgeOldGUIDsArgs(guids, guidAccessTimes) end if lib.purgeTicker then lib.purgeTicker:Cancel() end lib.purgeTicker = C_Timer.NewTicker( PURGE_INTERVAL, purgeOldGUIDs) ------------------------------------ -- Restore data if using standalone f:RegisterEvent("PLAYER_LOGIN") function f:PLAYER_LOGIN() if LCD_Data and LCD_GUIDAccess then purgeOldGUIDsArgs(LCD_Data, LCD_GUIDAccess) local function MergeTableNoOverwrite(t1, t2) if not t2 then return false end for k,v in pairs(t2) do if type(v) == "table" then if t1[k] == nil then t1[k] = CopyTable(v) else MergeTableNoOverwrite(t1[k], v) end elseif t1[k] == nil then t1[k] = v end end return t1 end local curSessionData = lib.guids local restoredSessionData = LCD_Data MergeTableNoOverwrite(curSessionData, restoredSessionData) local curSessionAccessTimes = lib.guidAccessTimes local restoredSessionAccessTimes = LCD_GUIDAccess MergeTableNoOverwrite(curSessionAccessTimes, restoredSessionAccessTimes) end f:RegisterEvent("PLAYER_LOGOUT") function f:PLAYER_LOGOUT() LCD_Data = guids LCD_GUIDAccess = guidAccessTimes end end -------------------------- -- DIMINISHING RETURNS -------------------------- local bit_band = bit.band local DRResetTime = 18.4 local COMBATLOG_OBJECT_TYPE_PLAYER = COMBATLOG_OBJECT_TYPE_PLAYER local COMBATLOG_OBJECT_REACTION_FRIENDLY = COMBATLOG_OBJECT_REACTION_FRIENDLY local DRMultipliers = { 0.5, 0.25, 0} local function addDRLevel(dstGUID, category) local guidTable = DRInfo[dstGUID] if not guidTable then DRInfo[dstGUID] = {} guidTable = DRInfo[dstGUID] end local catTable = guidTable[category] if not catTable then guidTable[category] = { level = 0, expires = 0} catTable = guidTable[category] end local now = GetTime() local isExpired = (catTable.expires or 0) <= now local oldDRLevel = catTable.level if isExpired or oldDRLevel >= 3 then catTable.level = 0 end catTable.level = catTable.level + 1 catTable.expires = now + DRResetTime end local function clearDRs(dstGUID) DRInfo[dstGUID] = nil end local function getDRMul(dstGUID, spellID) local category = lib.DR_CategoryBySpellID[spellID] if not category then return 1 end local guidTable = DRInfo[dstGUID] if guidTable then local catTable = guidTable[category] if catTable then local now = GetTime() local isExpired = (catTable.expires or 0) <= now if isExpired then return 1 else local mul = DRMultipliers[catTable.level] return mul or 1 end end end return 1 end local function CountDiminishingReturns(eventType, srcGUID, srcFlags, dstGUID, dstFlags, spellID, auraType) if auraType == "DEBUFF" then if eventType == "SPELL_AURA_REMOVED" or eventType == "SPELL_AURA_REFRESH" then local category = lib.DR_CategoryBySpellID[spellID] if not category then return end local isDstPlayer = bit_band(dstFlags, COMBATLOG_OBJECT_TYPE_PLAYER) > 0 -- local isFriendly = bit_band(dstFlags, COMBATLOG_OBJECT_REACTION_FRIENDLY) > 0 if not isDstPlayer then if not lib.DR_TypesPVE[category] then return end end addDRLevel(dstGUID, category) end if eventType == "UNIT_DIED" then if not isHunterGUID(dstGUID) then clearDRs(dstGUID) end end end end ------------------------ -- COMBO POINTS ------------------------ local GetComboPoints = GetComboPoints local _, playerClass = UnitClass("player") local cpWas = 0 local cpNow = 0 local function GetCP() if not cpNow then return GetComboPoints("player", "target") end return cpWas > cpNow and cpWas or cpNow end function f:PLAYER_TARGET_CHANGED(event) return self:UNIT_POWER_UPDATE(event, "player", "COMBO_POINTS") end function f:UNIT_POWER_UPDATE(event,unit, ptype) if ptype == "COMBO_POINTS" then cpWas = cpNow cpNow = GetComboPoints(unit, "target") end end --------------------------- -- COMBAT LOG --------------------------- local function cleanDuration(duration, spellID, srcGUID, comboPoints) if type(duration) == "function" then local isSrcPlayer = srcGUID == UnitGUID("player") -- Passing startTime for the sole reason of identifying different Rupture/KS applications for Rogues -- Then their duration func will cache one actual duration calculated at the moment of application return duration(spellID, isSrcPlayer, comboPoints) end return duration end local function GetSpellTable(srcGUID, dstGUID, spellID) local guidTable = guids[dstGUID] if not guidTable then return end local spellTable = guidTable[spellID] if not spellTable then return end local applicationTable if spellTable.applications then applicationTable = spellTable.applications[srcGUID] else applicationTable = spellTable end if not applicationTable then return end return applicationTable end local function RefreshTimer(srcGUID, dstGUID, spellID, overrideTime) local applicationTable = GetSpellTable(srcGUID, dstGUID, spellID) if not applicationTable then return end local oldStartTime = applicationTable[2] applicationTable[2] = overrideTime or GetTime() -- set start time to now return true, oldStartTime end local function SetTimer(srcGUID, dstGUID, dstName, dstFlags, spellID, spellName, opts, auraType, doRemove) if not opts then return end local guidTable = guids[dstGUID] if not guidTable then guids[dstGUID] = {} guidTable = guids[dstGUID] end local isStacking = opts.stacking -- local auraUID = MakeAuraUID(spellID, isStacking and srcGUID) if doRemove then if guidTable[spellID] then if isStacking then if guidTable[spellID].applications then guidTable[spellID].applications[srcGUID] = nil end else guidTable[spellID] = nil end end return end local spellTable = guidTable[spellID] if not spellTable then guidTable[spellID] = {} spellTable = guidTable[spellID] if isStacking then spellTable.applications = {} end end local applicationTable if isStacking then applicationTable = spellTable.applications[srcGUID] if not applicationTable then spellTable.applications[srcGUID] = {} applicationTable = spellTable.applications[srcGUID] end else applicationTable = spellTable end local duration = opts.duration local isDstPlayer = bit_band(dstFlags, COMBATLOG_OBJECT_CONTROL_PLAYER) > 0 if isDstPlayer and opts.pvpduration then duration = opts.pvpduration end if not duration then return SetTimer(srcGUID, dstGUID, dstName, dstFlags, spellID, spellName, opts, auraType, true) end -- local mul = getDRMul(dstGUID, spellID) -- duration = duration * mul local now = GetTime() -- local expirationTime -- if duration == 0 then -- expirationTime = now + UNKNOWN_AURA_DURATION -- 60m -- else -- -- local temporaryDuration = cleanDuration(opts.duration, spellID, srcGUID) -- expirationTime = now + duration -- end applicationTable[1] = duration applicationTable[2] = now -- applicationTable[2] = expirationTime applicationTable[3] = auraType local isSrcPlayer = srcGUID == UnitGUID("player") local comboPoints if isSrcPlayer and playerClass == "ROGUE" then comboPoints = GetCP() end applicationTable[4] = comboPoints guidAccessTimes[dstGUID] = time() end local function FireToUnits(event, dstGUID) if dstGUID == UnitGUID("target") then callbacks:Fire(event, "target") end local nameplateUnit = nameplateUnitMap[dstGUID] if nameplateUnit then callbacks:Fire(event, nameplateUnit) end end local function GetLastRankSpellID(spellName) local spellID = spellNameToID[spellName] if not spellID then spellID = NPCspellNameToID[spellName] end return spellID end local eventSnapshot castLog.SetLastCast = function(self, srcGUID, spellID, timestamp) self[srcGUID] = { spellID, timestamp } guidAccessTimes[srcGUID] = time() end castLog.IsCurrent = function(self, srcGUID, spellID, timestamp, timeWindow) local entry = self[srcGUID] if entry then local lastSpellID, lastTimestamp = entry[1], entry[2] return lastSpellID == spellID and (timestamp - lastTimestamp < timeWindow) end end local lastResistSpellID local lastResistTime = 0 --------------------------- -- COMBAT LOG HANDLER --------------------------- function f:COMBAT_LOG_EVENT_UNFILTERED(event) return self:CombatLogHandler(CombatLogGetCurrentEventInfo()) end local rollbackTable = setmetatable({}, { __mode="v" }) local function ProcIndirectRefresh(eventType, spellName, srcGUID, srcFlags, dstGUID, dstFlags, dstName, isCrit) if indirectRefreshSpells[spellName] then local targetSpells = indirectRefreshSpells[spellName] for targetSpellID, refreshTable in pairs(targetSpells) do if refreshTable.events[eventType] then local condition = refreshTable.condition if condition then local isMine = bit_band(srcFlags, COMBATLOG_OBJECT_AFFILIATION_MINE) == COMBATLOG_OBJECT_AFFILIATION_MINE if not condition(isMine, isCrit) then return end end if refreshTable.targetResistCheck then local now = GetTime() if lastResistSpellID == targetSpellID and now - lastResistTime < 0.4 then return end end if refreshTable.applyAura then local opts = spells[targetSpellID] if opts then local targetAuraType = "DEBUFF" local targetSpellName = GetSpellInfo(targetSpellID) SetTimer(srcGUID, dstGUID, dstName, dstFlags, targetSpellID, targetSpellName, opts, targetAuraType) end elseif refreshTable.customAction then refreshTable.customAction(srcGUID, dstGUID, targetSpellID) else local _, oldStartTime = RefreshTimer(srcGUID, dstGUID, targetSpellID) if refreshTable.rollbackMisses and oldStartTime then rollbackTable[srcGUID] = rollbackTable[srcGUID] or {} rollbackTable[srcGUID][dstGUID] = rollbackTable[srcGUID][dstGUID] or {} local now = GetTime() rollbackTable[srcGUID][dstGUID][targetSpellID] = {now, oldStartTime} end end end end end end local igniteName = GetSpellInfo(12654) do local igniteOpts = { duration = 4 } function f:IgniteHandler(...) local timestamp, eventType, hideCaster, srcGUID, srcName, srcFlags, srcFlags2, dstGUID, dstName, dstFlags, dstFlags2, spellID, spellName, spellSchool, auraType, _, _, _, _, _, isCrit = ... spellID = 12654 local opts = igniteOpts if eventType == "SPELL_AURA_APPLIED" then SetTimer(srcGUID, dstGUID, dstName, dstFlags, spellID, spellName, opts, auraType) local spellTable = GetSpellTable(srcGUID, dstGUID, spellID) spellTable.tickExtended = true -- skipping first tick by treating it as already extended if lib.DEBUG_IGNITE then print(GetTime(), "[Ignite] Applied", dstGUID, "StartTime:", spellTable[2]) end elseif eventType == "SPELL_PERIODIC_DAMAGE" then local spellTable = GetSpellTable(srcGUID, dstGUID, spellID) if spellTable then if lib.DEBUG_IGNITE then print(GetTime(), "[Ignite] Tick", dstGUID) end spellTable.tickExtended = false -- unmark tick end elseif eventType == "SPELL_AURA_REMOVED" then SetTimer(srcGUID, dstGUID, dstName, dstFlags, spellID, spellName, opts, auraType, true) if lib.DEBUG_IGNITE then print(GetTime(), "[Ignite] Removed", dstGUID) end end end -- if playerClass ~= "MAGE" then -- f.IgniteHandler = function() end -- end function lib:GetSpellTable(...) return GetSpellTable(...) end end function f:CombatLogHandler(...) local timestamp, eventType, hideCaster, srcGUID, srcName, srcFlags, srcFlags2, dstGUID, dstName, dstFlags, dstFlags2, spellID, spellName, spellSchool, auraType, _, _, _, _, _, isCrit = ... ProcIndirectRefresh(eventType, spellName, srcGUID, srcFlags, dstGUID, dstFlags, dstName, isCrit) if spellName == igniteName then self:IgniteHandler(...) end if eventType == "SPELL_MISSED" and bit_band(srcFlags, COMBATLOG_OBJECT_AFFILIATION_MINE) == COMBATLOG_OBJECT_AFFILIATION_MINE then local missType = auraType -- ABSORB BLOCK DEFLECT DODGE EVADE IMMUNE MISS PARRY REFLECT RESIST if not (missType == "ABSORB" or missType == "BLOCK") then -- not sure about those two local refreshTable = indirectRefreshSpells[spellName] -- This is just for Sunder Armor misses if refreshTable and refreshTable.rollbackMisses then local rollbacksFromSource = rollbackTable[srcGUID] if rollbacksFromSource then local rollbacks = rollbacksFromSource[dstGUID] if rollbacks then local targetSpellID = refreshTable.targetSpellID local snapshot = rollbacks[targetSpellID] if snapshot then local timestamp, oldStartTime = unpack(snapshot) local now = GetTime() if now - timestamp < 0.5 then RefreshTimer(srcGUID, dstGUID, targetSpellID, oldStartTime) end end end end end spellID = GetLastRankSpellID(spellName) if not spellID then return end lastResistSpellID = spellID lastResistTime = GetTime() end end if auraType == "BUFF" or auraType == "DEBUFF" or eventType == "SPELL_CAST_SUCCESS" then if spellID == 0 then -- so not to rewrite the whole thing to spellnames after the combat log change -- just treat everything as max rank id of that spell name spellID = GetLastRankSpellID(spellName) if not spellID then return end end CountDiminishingReturns(eventType, srcGUID, srcFlags, dstGUID, dstFlags, spellID, auraType) local isDstFriendly = bit_band(dstFlags, COMBATLOG_OBJECT_REACTION_FRIENDLY) > 0 local opts = spells[spellID] if not opts then local npcDurationForSpellName = npc_spells[spellID] if npcDurationForSpellName then opts = { duration = npcDurationForSpellName } -- elseif enableEnemyBuffTracking and not isDstFriendly and auraType == "BUFF" then -- opts = { duration = 0 } -- it'll be accepted but as an indefinite aura end end if opts then local castEventPass if opts.castFilter then -- Buff and Raidwide Buff events arrive in the following order: -- 1571716930.161 ID: 21562 SPELL_AURA_APPLIED/REFRESH to Caster himself (if selfcast or raidwide) -- 1571716930.161 ID: 21562 SPELL_CAST_SUCCESS on Cast Target -- 1571716930.161 ID: 21562 SPELL_AURA_APPLIED/REFRESH to everyone else -- For spells that have cast filter enabled: -- First APPLIED event gets snapshotted and otherwise ignored -- CAST event effectively sets castEventPass to true -- Snapshotted event now gets handled with cast pass -- All the following APPLIED events are accepted while cast pass is valid -- (Unconfirmed whether timestamp is the same even for a 40m raid) local now = GetTime() castEventPass = castLog:IsCurrent(srcGUID, spellID, now, 0.8) if not castEventPass and (eventType == "SPELL_AURA_REFRESH" or eventType == "SPELL_AURA_APPLIED") then eventSnapshot = { timestamp, eventType, hideCaster, srcGUID, srcName, srcFlags, srcFlags2, dstGUID, dstName, dstFlags, dstFlags2, spellID, spellName, spellSchool, auraType } return end if eventType == "SPELL_CAST_SUCCESS" then -- Aura spell ID can be different from cast spell id -- But all buffs are usually simple spells and it's the same for them castLog:SetLastCast(srcGUID, spellID, now) if eventSnapshot then self:CombatLogHandler(unpack(eventSnapshot)) eventSnapshot = nil end end end local isEnemyBuff = not isDstFriendly and auraType == "BUFF" -- print(eventType, srcGUID, "=>", dstName, spellID, spellName, auraType ) if eventType == "SPELL_AURA_REFRESH" or eventType == "SPELL_AURA_APPLIED" or eventType == "SPELL_AURA_APPLIED_DOSE" then if not opts.castFilter or castEventPass or isEnemyBuff then SetTimer(srcGUID, dstGUID, dstName, dstFlags, spellID, spellName, opts, auraType) end elseif eventType == "SPELL_AURA_REMOVED" then SetTimer(srcGUID, dstGUID, dstName, dstFlags, spellID, spellName, opts, auraType, true) -- elseif eventType == "SPELL_AURA_REMOVED_DOSE" then -- self:RemoveDose(srcGUID, dstGUID, spellID, spellName, auraType, amount) end if enableEnemyBuffTracking and isEnemyBuff then -- invalidate buff cache buffCacheValid[dstGUID] = nil FireToUnits("UNIT_BUFF", dstGUID) if eventType == "SPELL_AURA_REFRESH" or eventType == "SPELL_AURA_APPLIED" or eventType == "SPELL_AURA_APPLIED_DOSE" then FireToUnits("UNIT_BUFF_GAINED", dstGUID, spellID) end end end end if eventType == "UNIT_DIED" then if isHunterGUID(dstGUID) then local isDstFriendly = bit_band(dstFlags, COMBATLOG_OBJECT_REACTION_FRIENDLY) > 0 if not isDstFriendly or isFriendlyFeigning(dstGUID) then return end end guids[dstGUID] = nil buffCache[dstGUID] = nil buffCacheValid[dstGUID] = nil guidAccessTimes[dstGUID] = nil local isDstFriendly = bit_band(dstFlags, COMBATLOG_OBJECT_REACTION_FRIENDLY) > 0 if enableEnemyBuffTracking and not isDstFriendly then FireToUnits("UNIT_BUFF", dstGUID) end nameplateUnitMap[dstGUID] = nil end end --------------------------- -- ENEMY BUFFS --------------------------- local makeBuffInfo = function(spellID, applicationTable, dstGUID, srcGUID) local spellName = GetSpellInfo(spellID) local icon = GetSpellTexture(spellID) local opts = spells[spellID] local buffInfo = { spellName, icon, 0, (opts and opts.buffType), 0, 0, nil, nil, nil, spellID, false, false, false, false, 1 } local isStacking = opts and opts.stacking local duration, expirationTime = GetGUIDAuraTime(dstGUID, spellName, spellID, srcGUID, isStacking) if duration then buffInfo[5] = duration buffInfo[6] = expirationTime end return buffInfo end local shouldDisplayAura = function(auraTable) if auraTable[3] == "BUFF" then local now = GetTime() local expirationTime = auraTable[2] return expirationTime > now end return false end lib.scanTip = lib.scanTip or CreateFrame("GameTooltip", "LibClassicDurationsScanTip", nil, "GameTooltipTemplate") local scanTip = lib.scanTip scanTip:SetOwner(WorldFrame, "ANCHOR_NONE") local function RegenerateBuffList(unit, dstGUID) local buffs = {} local guidTable = guids[dstGUID] if not guidTable then return end for spellID, t in pairs(guidTable) do if t.applications then for srcGUID, auraTable in pairs(t.applications) do if auraTable[3] == "BUFF" then local buffInfo = makeBuffInfo(spellID, auraTable, dstGUID, nil) if buffInfo then tinsert(buffs, buffInfo) end end end else if t[3] == "BUFF" then local buffInfo = makeBuffInfo(spellID, t, dstGUID, nil) if buffInfo then tinsert(buffs, buffInfo) end end end end --[[ local spellName for i=1, 32 do scanTip:ClearLines() scanTip:SetUnitAura(unit, i, "HELPFUL") spellName = LibClassicDurationsScanTipTextLeft1:GetText() if spellName then local spellID = GetLastRankSpellID(spellName) if spellID then local icon = GetSpellTexture(spellID) local opts = spells[spellID] local buffInfo = { spellName, icon, 0, (opts and opts.buffType), 0, 0, nil, nil, nil, spellID, false, false, false, false, 1 } local isStacking = opts and opts.stacking local srcGUID = nil local duration, expirationTime = GetGUIDAuraTime(dstGUID, spellName, spellID, srcGUID, isStacking) if duration then buffInfo[5] = duration buffInfo[6] = expirationTime end tinsert(buffs, buffInfo) end else break end end ]] buffCache[dstGUID] = buffs buffCacheValid[dstGUID] = GetTime() + BUFF_CACHE_EXPIRATION_TIME -- Expiration timestamp end local FillInDuration = function(unit, buffName, icon, count, debuffType, duration, expirationTime, caster, canStealOrPurge, nps, spellId, ...) if buffName then local durationNew, expirationTimeNew = lib.GetAuraDurationByUnitDirect(unit, spellId, caster, buffName) if duration == 0 and durationNew then duration = durationNew expirationTime = expirationTimeNew end return buffName, icon, count, debuffType, duration, expirationTime, caster, canStealOrPurge, nps, spellId, ... end end lib.FillInDuration = FillInDuration function lib.UnitAuraDirect(unit, index, filter) if enableEnemyBuffTracking and filter == "HELPFUL" and not UnitIsFriend("player", unit) and not UnitAura(unit, 1, filter) then local unitGUID = UnitGUID(unit) if not unitGUID then return end local isValid = buffCacheValid[unitGUID] if not isValid or isValid < GetTime() then RegenerateBuffList(unit, unitGUID) end local buffCacheHit = buffCache[unitGUID] if buffCacheHit then local buffReturns = buffCache[unitGUID][index] if buffReturns then return unpack(buffReturns) end end else return FillInDuration(unit, UnitAura(unit, index, filter)) end end function lib.UnitAuraWithBuffs(...) return lib.UnitAuraDirect(...) end function lib.UnitAuraWrapper(unit, ...) return lib.FillInDuration(unit, UnitAura(unit, ...)) end function lib:UnitAura(...) return self.UnitAuraDirect(...) end function f:NAME_PLATE_UNIT_ADDED(event, unit) local unitGUID = UnitGUID(unit) nameplateUnitMap[unitGUID] = unit end function f:NAME_PLATE_UNIT_REMOVED(event, unit) local unitGUID = UnitGUID(unit) if unitGUID then -- it returns correctly on death, but just in case nameplateUnitMap[unitGUID] = nil end end function callbacks.OnUsed() lib.enableEnemyBuffTracking = true enableEnemyBuffTracking = lib.enableEnemyBuffTracking f:RegisterEvent("NAME_PLATE_UNIT_ADDED") f:RegisterEvent("NAME_PLATE_UNIT_REMOVED") end function callbacks.OnUnused() lib.enableEnemyBuffTracking = false enableEnemyBuffTracking = lib.enableEnemyBuffTracking f:UnregisterEvent("NAME_PLATE_UNIT_ADDED") f:UnregisterEvent("NAME_PLATE_UNIT_REMOVED") end if next(callbacks.events) then callbacks.OnUsed() end --------------------------- -- PUBLIC FUNCTIONS --------------------------- GetGUIDAuraTime = function(dstGUID, spellName, spellID, srcGUID, isStacking, forcedNPCDuration) local guidTable = guids[dstGUID] if guidTable then local lastRankID = GetLastRankSpellID(spellName) local spellTable = guidTable[lastRankID] if spellTable then local applicationTable -- Return when player spell and npc spell have the same name and the player spell is stacking -- NPC spells are always assumed to not stack, so it won't find startTime if forcedNPCDuration and spellTable.applications then return nil end if isStacking then if srcGUID and spellTable.applications then applicationTable = spellTable.applications[srcGUID] elseif spellTable.applications then -- return some duration applicationTable = select(2,next(spellTable.applications)) end else applicationTable = spellTable end if not applicationTable then return end local durationFunc, startTime, auraType, comboPoints = unpack(applicationTable) local duration = forcedNPCDuration or cleanDuration(durationFunc, spellID, srcGUID, comboPoints) if duration == INFINITY then return nil end if not duration then return nil end if not startTime then return nil end local mul = getDRMul(dstGUID, spellID) -- local mul = getDRMul(dstGUID, lastRankID) duration = duration * mul local expirationTime = startTime + duration if GetTime() <= expirationTime then return duration, expirationTime end end end end if playerClass == "MAGE" then local NormalGetGUIDAuraTime = GetGUIDAuraTime local Chilled = GetSpellInfo(12486) GetGUIDAuraTime = function(dstGUID, spellName, spellID, ...) -- Overriding spellName for Improved blizzard's spellIDs if spellName == Chilled and spellID == 12486 or spellID == 12484 or spellID == 12485 then spellName = "ImpBlizzard" end return NormalGetGUIDAuraTime(dstGUID, spellName, spellID, ...) end end function lib.GetAuraDurationByUnitDirect(unit, spellID, casterUnit, spellName) assert(spellID, "spellID is nil") local opts = spells[spellID] local isStacking local npcDurationById if opts then isStacking = opts.stacking else npcDurationById = npc_spells[spellID] if not npcDurationById then return end end local dstGUID = UnitGUID(unit) local srcGUID = casterUnit and UnitGUID(casterUnit) if not spellName then spellName = GetSpellInfo(spellID) end return GetGUIDAuraTime(dstGUID, spellName, spellID, srcGUID, isStacking, npcDurationById) end function lib:GetAuraDurationByUnit(...) return self.GetAuraDurationByUnitDirect(...) end function lib:GetAuraDurationByGUID(dstGUID, spellID, srcGUID, spellName) local opts = spells[spellID] if not opts then return end if not spellName then spellName = GetSpellInfo(spellID) end return GetGUIDAuraTime(dstGUID, spellName, spellID, srcGUID, opts.stacking) end function lib:GetLastRankSpellIDByName(spellName) return GetLastRankSpellID(spellName) end -- Will not work for cp-based durations, KS and Rupture function lib:GetDurationForRank(spellName, spellID, srcGUID) local lastRankID = spellNameToID[spellName] local opts = spells[lastRankID] if opts then return cleanDuration(opts.duration, spellID, srcGUID) end end lib.activeFrames = lib.activeFrames or {} local activeFrames = lib.activeFrames function lib:RegisterFrame(frame) activeFrames[frame] = true if next(activeFrames) then f:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") if playerClass == "ROGUE" then f:RegisterEvent("PLAYER_TARGET_CHANGED") f:RegisterUnitEvent("UNIT_POWER_UPDATE", "player") end end end lib.Register = lib.RegisterFrame function lib:UnregisterFrame(frame) activeFrames[frame] = nil if not next(activeFrames) then f:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") if playerClass == "ROGUE" then f:UnregisterEvent("PLAYER_TARGET_CHANGED") f:UnregisterEvent("UNIT_POWER_UPDATE") end end end lib.Unregister = lib.UnregisterFrame function lib:ToggleDebug() if not lib.debug then lib.debug = CreateFrame("Frame") lib.debug:SetScript("OnEvent",function( self, event ) local timestamp, eventType, hideCaster, srcGUID, srcName, srcFlags, srcFlags2, dstGUID, dstName, dstFlags, dstFlags2, spellID, spellName, spellSchool, auraType, amount = CombatLogGetCurrentEventInfo() local isSrcPlayer = (bit_band(srcFlags, COMBATLOG_OBJECT_AFFILIATION_MINE) == COMBATLOG_OBJECT_AFFILIATION_MINE) if isSrcPlayer then print (GetTime(), "ID:", spellID, spellName, eventType, srcFlags, srcGUID,"|cff00ff00==>|r", dstGUID, dstFlags, auraType, amount) end end) end if not lib.debug.enabled then lib.debug:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") lib.debug.enabled = true print("[LCD] Enabled combat log event display") else lib.debug:UnregisterAllEvents() lib.debug.enabled = false print("[LCD] Disabled combat log event display") end end function lib:MonitorUnit(unit) if not lib.debug then lib.debug = CreateFrame("Frame") local debugGUID = UnitGUID(unit) lib.debug:SetScript("OnEvent",function( self, event ) local timestamp, eventType, hideCaster, srcGUID, srcName, srcFlags, srcFlags2, dstGUID, dstName, dstFlags, dstFlags2, spellID, spellName, spellSchool, auraType, amount = CombatLogGetCurrentEventInfo() if srcGUID == debugGUID or dstGUID == debugGUID then print (GetTime(), "ID:", spellID, spellName, eventType, srcFlags, srcGUID,"|cff00ff00==>|r", dstGUID, dstFlags, auraType, amount) end end) end if not lib.debug.enabled then lib.debug:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") lib.debug.enabled = true print("[LCD] Enabled combat log event display") else lib.debug:UnregisterAllEvents() lib.debug.enabled = false print("[LCD] Disabled combat log event display") end end ------------------ -- Set Tracking ------------------ local itemSets = {} function lib:TrackItemSet(setname, itemArray) itemSets[setname] = itemSets[setname] or {} if not itemSets[setname].items then itemSets[setname].items = {} itemSets[setname].callbacks = {} local bitems = itemSets[setname].items for _, itemID in ipairs(itemArray) do bitems[itemID] = true end end end function lib:RegisterSetBonusCallback(setname, pieces, handle_on, handle_off) local set = itemSets[setname] if not set then error(string.format("Itemset '%s' is not registered", setname)) end set.callbacks[pieces] = {} set.callbacks[pieces].equipped = false set.callbacks[pieces].on = handle_on set.callbacks[pieces].off = handle_off end function lib:IsSetBonusActive(setname, bonusLevel) local set = itemSets[setname] if not set then return false end local setCallbacks = set.callbacks if setCallbacks[bonusLevel] and setCallbacks[bonusLevel].equipped then return true end return false end function lib:IsSetBonusActiveFullCheck(setname, bonusLevel) local set = itemSets[setname] if not set then return false end local set_items = set.items local pieces_equipped = 0 for slot=1,17 do local itemID = GetInventoryItemID("player", slot) if set_items[itemID] then pieces_equipped = pieces_equipped + 1 end end return (pieces_equipped >= bonusLevel) end lib.setwatcher = lib.setwatcher or CreateFrame("Frame", nil, UIParent) local setwatcher = lib.setwatcher setwatcher:SetScript("OnEvent", function(self, event, ...) return self[event](self, event, ...) end) setwatcher:RegisterEvent("PLAYER_LOGIN") function setwatcher:PLAYER_LOGIN() if next(itemSets) then self:RegisterUnitEvent("UNIT_INVENTORY_CHANGED", "player") self:UNIT_INVENTORY_CHANGED(nil, "player") end end function setwatcher:UNIT_INVENTORY_CHANGED(event, unit) for setname, set in pairs(itemSets) do local set_items = set.items local pieces_equipped = 0 for slot=1,17 do -- That excludes ranged slot in classic local itemID = GetInventoryItemID("player", slot) if set_items[itemID] then pieces_equipped = pieces_equipped + 1 end end for bp, bonus in pairs(set.callbacks) do if pieces_equipped >= bp then if not bonus.equipped then if bonus.on then bonus.on() end bonus.equipped = true end else if bonus.equipped then if bonus.off then bonus.off() end bonus.equipped = false end end end end end
412
0.902001
1
0.902001
game-dev
MEDIA
0.828291
game-dev
0.983316
1
0.983316
Mindgamesnl/OpenAudioMc
2,663
OpenAudioMc/Plugin/src/main/java/com/craftmend/openaudiomc/spigot/modules/commands/subcommands/voice/VoiceInspectSubCommand.java
package com.craftmend.openaudiomc.spigot.modules.commands.subcommands.voice; import com.craftmend.openaudiomc.generic.client.ClientDataService; import com.craftmend.openaudiomc.generic.client.store.ClientDataStore; import com.craftmend.openaudiomc.generic.commands.interfaces.SubCommand; import com.craftmend.openaudiomc.generic.mojang.MojangLookupService; import com.craftmend.openaudiomc.generic.mojang.store.MojangProfile; import com.craftmend.openaudiomc.generic.rest.Task; import com.craftmend.openaudiomc.generic.platform.OaColor; import com.craftmend.openaudiomc.generic.platform.interfaces.TaskService; import com.craftmend.openaudiomc.api.user.User; import org.bukkit.entity.Player; import java.util.UUID; public class VoiceInspectSubCommand extends SubCommand { public VoiceInspectSubCommand() { super("inspect"); this.trimArguments = true; } @Override public void onExecute(User sender, String[] args) { if (!(sender.getOriginal() instanceof Player)) { message(sender, "Only players can open moderation menu's."); return; } if (args.length == 0) { message(sender, "Please specify the name of the player you want to inspect"); return; } message(sender, "Fetching cached profile..."); Task<MojangProfile> mojangFetch = getService(MojangLookupService.class).getByName(args[0]); mojangFetch.setWhenFailed((error) -> { message(sender, OaColor.RED + "There's no record of that player ever joining this server (" + error + ")"); }); mojangFetch.setWhenFinished(mojangProfile -> { message(sender, OaColor.GRAY + "Loading client data from " + mojangProfile.getUuid().toString() + "..."); Task<ClientDataStore> clientDataRequest = getService(ClientDataService.class) .getClientData(mojangProfile.getUuid(), true, false); clientDataRequest.setWhenFailed((error) -> { message(sender, OaColor.RED + "Failed to load profile data..."); }); clientDataRequest.setWhenFinished(clientDataStore -> { handleInspect(sender, args, clientDataStore, mojangProfile.getUuid(), mojangProfile.getName()); }); }); } public void handleInspect(User sender, String[] args, ClientDataStore target, UUID targetId, String targetName) { message(sender, OaColor.GREEN + "Opening profile"); resolveDependency(TaskService.class).runSync(() -> { new VoiceInspectGui((Player) sender.getOriginal(), target, targetId, targetName); }); } }
412
0.819934
1
0.819934
game-dev
MEDIA
0.594752
game-dev,web-backend
0.943659
1
0.943659
amethyst/amethyst
2,904
examples/pong_tutorial_02/pong.rs
use amethyst::{ assets::{DefaultLoader, Handle, Loader, ProcessingQueue}, core::transform::Transform, prelude::*, renderer::{Camera, SpriteRender, SpriteSheet, Texture}, }; const ARENA_HEIGHT: f32 = 100.0; const ARENA_WIDTH: f32 = 100.0; const PADDLE_HEIGHT: f32 = 16.0; const PADDLE_WIDTH: f32 = 4.0; pub struct Pong; impl SimpleState for Pong { fn on_start(&mut self, data: StateData<'_, GameData>) { let world = data.world; // Load the spritesheet necessary to render the graphics. // `spritesheet` is the layout of the sprites on the image; // `texture` is the pixel data. let sprite_sheet_handle = load_sprite_sheet(data.resources); initialize_paddles(world, sprite_sheet_handle); initialize_camera(world); } } #[derive(PartialEq, Eq)] enum Side { Left, Right, } struct Paddle { pub side: Side, pub width: f32, pub height: f32, } impl Paddle { fn new(side: Side) -> Paddle { Paddle { side, width: PADDLE_WIDTH, height: PADDLE_HEIGHT, } } } fn load_sprite_sheet(resources: &mut Resources) -> Handle<SpriteSheet> { let texture: Handle<Texture> = { let loader = resources.get::<DefaultLoader>().unwrap(); loader.load("texture/pong_spritesheet.png") }; let loader = resources.get::<DefaultLoader>().unwrap(); let sprites = loader.load("texture/pong_spritesheet.ron"); loader.load_from_data( SpriteSheet { texture, sprites }, (), &resources.get::<ProcessingQueue<SpriteSheet>>().unwrap(), ) } /// initialize the camera. fn initialize_camera(world: &mut World) { // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left. let mut transform = Transform::default(); transform.set_translation_xyz(ARENA_WIDTH * 0.5, ARENA_HEIGHT * 0.5, 1.0); world.push((Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT), transform)); } /// initializes one paddle on the left, and one paddle on the right. fn initialize_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>) { let mut left_transform = Transform::default(); let mut right_transform = Transform::default(); // Correctly position the paddles. let y = ARENA_HEIGHT / 2.0; left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0); right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0); // Assign the sprites for the paddles let sprite_render = SpriteRender::new(sprite_sheet_handle, 0); // paddle is the first sprite in the sprite_sheet // Create a left plank entity. world.push(( sprite_render.clone(), Paddle::new(Side::Left), left_transform, )); // Create right plank entity. world.push((sprite_render, Paddle::new(Side::Right), right_transform)); }
412
0.827329
1
0.827329
game-dev
MEDIA
0.873199
game-dev,graphics-rendering
0.785993
1
0.785993
Advanced-Rocketry/AdvancedRocketry
1,632
src/main/java/zmaster587/advancedRocketry/world/biome/BiomeGenMarsh.java
package zmaster587.advancedRocketry.world.biome; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.feature.WorldGenAbstractTree; import net.minecraft.world.gen.feature.WorldGenShrub; import javax.annotation.Nonnull; import java.util.Random; public class BiomeGenMarsh extends Biome { public BiomeGenMarsh(BiomeProperties properties) { super(properties); this.decorator.clayPerChunk = 10; this.decorator.flowersPerChunk = 0; this.decorator.mushroomsPerChunk = 0; this.decorator.treesPerChunk = 0; this.decorator.grassPerChunk = 0; this.decorator.waterlilyPerChunk = 10; this.decorator.sandPatchesPerChunk = 0; this.spawnableCreatureList.clear(); } @Override public void genTerrainBlocks(World worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) { super.genTerrainBlocks(worldIn, rand, chunkPrimerIn, x, z, noiseVal); double d1 = GRASS_COLOR_NOISE.getValue((double)x * 0.25D, (double)z * 0.25D); x = Math.abs(x % 16); z = Math.abs(z % 16); if (d1 > 0.2D) { chunkPrimerIn.setBlockState(x, 62, z, Blocks.GRASS.getDefaultState()); for(int y = 61; y > 1; y--) { if(!chunkPrimerIn.getBlockState(x, y, z).isOpaqueCube()) chunkPrimerIn.setBlockState(x, y, z, Blocks.GRASS.getDefaultState()); else break; } } } @Override @Nonnull public WorldGenAbstractTree getRandomTreeFeature(Random rand) { return new WorldGenShrub(Blocks.LOG.getDefaultState(), Blocks.LEAVES.getDefaultState()); } }
412
0.745867
1
0.745867
game-dev
MEDIA
0.987883
game-dev
0.830338
1
0.830338
TeamWisp/WispRenderer
5,197
tests/demo/physics_engine.cpp
/*! * Copyright 2019 Breda University of Applied Sciences and Team Wisp (Viktor Zoutman, Emilio Laiso, Jens Hagen, Meine Zeinstra, Tahar Meijs, Koen Buitenhuis, Niels Brunekreef, Darius Bouma, Florian Schut) * * 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. */ #include "physics_engine.hpp" #include "physics_node.hpp" #include "debug_camera.hpp" #include "model_pool.hpp" namespace phys { void PhysicsEngine::CreatePhysicsWorld() { ///collision configuration contains default setup for memory, collision setup collision_config = new btDefaultCollisionConfiguration(); //m_collisionConfiguration->setConvexConvexMultipointIterations(); ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) coll_dispatcher = new btCollisionDispatcher(collision_config); broadphase = new btDbvtBroadphase(); ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) constraint_solver = new btSequentialImpulseConstraintSolver(); phys_world = new btDiscreteDynamicsWorld(coll_dispatcher, broadphase, constraint_solver, collision_config); phys_world->setGravity(btVector3(0, -9.8, 0)); } btSphereShape* PhysicsEngine::CreateSphereShape(const float radius) { auto shape = new btSphereShape(radius); collision_shapes.push_back(shape); return shape; } btCapsuleShape* PhysicsEngine::CreateCapsuleShape(const float width, const float height) { auto shape = new btCapsuleShape(width, height); collision_shapes.push_back(shape); return shape; } std::vector<btConvexHullShape*> PhysicsEngine::CreateConvexShape(wr::ModelData* model) { std::vector<btConvexHullShape*> hulls; for (auto& mesh_data : model->m_meshes) { btConvexHullShape* shape = new btConvexHullShape(); for (auto& idx : mesh_data->m_indices) { auto pos = mesh_data->m_positions[idx]; shape->addPoint(btVector3(pos.x, pos.y, pos.z), false); } shape->recalcLocalAabb(); collision_shapes.push_back(shape); hulls.push_back(shape); } return hulls; } std::vector<btBvhTriangleMeshShape*> PhysicsEngine::CreateTriangleMeshShape(wr::ModelData* model) { std::vector<btBvhTriangleMeshShape*> hulls; for (auto& mesh_data : model->m_meshes) { btTriangleIndexVertexArray* va = new btTriangleIndexVertexArray(mesh_data->m_indices.size() / 3, reinterpret_cast<int*>(mesh_data->m_indices.data()), 3 * sizeof(std::uint32_t), mesh_data->m_positions.size(), reinterpret_cast<btScalar*>(mesh_data->m_positions.data()), sizeof(DirectX::XMFLOAT3)); btBvhTriangleMeshShape* shape = new btBvhTriangleMeshShape(va, true); collision_shapes.push_back(shape); hulls.push_back(shape); } return hulls; } btBoxShape* PhysicsEngine::CreateBoxShape(const btVector3& halfExtents) { auto shape = new btBoxShape(halfExtents); collision_shapes.push_back(shape); return shape; } btRigidBody* PhysicsEngine::CreateRigidBody(float mass, const btTransform& startTransform, btCollisionShape* shape) { btAssert((!shape || shape->getShapeType() != INVALID_SHAPE_PROXYTYPE)); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool is_dynamic = (mass != 0.f); btVector3 local_inertia(0, 0, 0); if (is_dynamic) shape->calculateLocalInertia(mass, local_inertia); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects #ifdef USE_MOTIONSTATE btDefaultMotionState* motion_state = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo cInfo(mass, motion_state, shape, local_inertia); btRigidBody* body = new btRigidBody(cInfo); //body->setContactProcessingThreshold(m_defaultContactProcessingThreshold); #else btRigidBody* body = new btRigidBody(mass, 0, shape, localInertia); body->setWorldTransform(startTransform); #endif body->setUserIndex(-1); phys_world->addRigidBody(body); return body; } void PhysicsEngine::UpdateSim(float delta, wr::SceneGraph& sg) { phys_world->stepSimulation(delta); for (auto& n : sg.GetMeshNodes()) { if (auto & node = std::dynamic_pointer_cast<PhysicsMeshNode>(n)) { if (!node->m_rigid_bodies.has_value() && node->m_rigid_body) { auto world_position = node->m_rigid_body->getWorldTransform().getOrigin(); node->m_position = util::BV3toDXV3(world_position); node->SignalTransformChange(); } } } } PhysicsEngine::~PhysicsEngine() { delete phys_world; delete broadphase; delete coll_dispatcher; delete constraint_solver; delete collision_config; } } /* phys*/
412
0.936891
1
0.936891
game-dev
MEDIA
0.961256
game-dev
0.899379
1
0.899379
Planimeter/hl2sb-src
1,258
src/game/client/c_te_effect_dispatch.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef C_TE_EFFECT_DISPATCH_H #define C_TE_EFFECT_DISPATCH_H #ifdef _WIN32 #pragma once #endif #include "effect_dispatch_data.h" typedef void (*ClientEffectCallback)( const CEffectData &data ); class CClientEffectRegistration { public: CClientEffectRegistration( const char *pEffectName, ClientEffectCallback fn ); public: const char *m_pEffectName; ClientEffectCallback m_pFunction; CClientEffectRegistration *m_pNext; static CClientEffectRegistration *s_pHead; }; // // Use this macro to register a client effect callback. // If you do DECLARE_CLIENT_EFFECT( "MyEffectName", MyCallback ), then MyCallback will be // called when the server does DispatchEffect( "MyEffect", data ) // #define DECLARE_CLIENT_EFFECT( effectName, callbackFunction ) \ static CClientEffectRegistration ClientEffectReg_##callbackFunction( effectName, callbackFunction ); void DispatchEffectToCallback( const char *pEffectName, const CEffectData &m_EffectData ); void DispatchEffect( const char *pName, const CEffectData &data ); #endif // C_TE_EFFECT_DISPATCH_H
412
0.875363
1
0.875363
game-dev
MEDIA
0.178536
game-dev
0.632268
1
0.632268
magefree/mage
2,184
Mage/src/main/java/mage/watchers/common/CrewedVehicleWatcher.java
package mage.watchers.common; import mage.MageObjectReference; import mage.constants.WatcherScope; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.watchers.Watcher; import java.util.*; import java.util.stream.Collectors; /** * @author TheElk801 */ public class CrewedVehicleWatcher extends Watcher { private final Map<MageObjectReference, Set<MageObjectReference>> crewMap = new HashMap<>(); public CrewedVehicleWatcher() { super(WatcherScope.GAME); } @Override public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.CREWED_VEHICLE) { crewMap.computeIfAbsent(new MageObjectReference(event.getSourceId(), game), x -> new HashSet<>()) .add(new MageObjectReference(event.getTargetId(), game)); } } @Override public void reset() { super.reset(); crewMap.clear(); } public static boolean checkIfCrewedThisTurn(Permanent crewer, Permanent crewed, Game game) { return game .getState() .getWatcher(CrewedVehicleWatcher.class) .crewMap .getOrDefault(new MageObjectReference(crewed, game), Collections.emptySet()) .stream() .anyMatch(mor -> mor.refersTo(crewer, game)); } public static int getCrewCount(Permanent vehicle, Game game) { return game .getState() .getWatcher(CrewedVehicleWatcher.class) .crewMap .getOrDefault(new MageObjectReference(vehicle, game), Collections.emptySet()) .size(); } public static Set<Permanent> getCrewers(Permanent vehicle, Game game) { return game .getState() .getWatcher(CrewedVehicleWatcher.class) .crewMap .getOrDefault(new MageObjectReference(vehicle, game), Collections.emptySet()) .stream() .map(mor -> mor.getPermanent(game)) .filter(Objects::nonNull) .collect(Collectors.toSet()); } }
412
0.920731
1
0.920731
game-dev
MEDIA
0.913884
game-dev
0.99339
1
0.99339
CafeFPS/r5_flowstate
1,535
vscripts/weapons/mp_weapon_melee_primary.nut
global function OnWeaponActivate_weapon_melee_primary global function OnWeaponDeactivate_weapon_melee_primary global function OnWeaponActivate_vctblue void function OnWeaponActivate_weapon_melee_primary( entity weapon ) { } void function OnWeaponDeactivate_weapon_melee_primary( entity weapon ) { } void function OnWeaponActivate_vctblue( entity weapon ) { entity player = weapon.GetWeaponOwner() weapon.kv.rendercolor = player.p.snd_knifecolor thread function () : ( weapon ) { Signal( weapon, "VCTBlueFX" ) EndSignal( weapon, "VCTBlueFX" ) EndSignal( weapon, "OnDestroy" ) float endTime float frac string current float startTime vector startColor vector endColor float colorResultX float colorResultY float colorResultZ for( ;; ) { if( Time() > endTime ) { startTime = Time() endTime = startTime + 3 current = expect string ( weapon.kv.rendercolor ) startColor = < split( current, " " )[0].tointeger(), split( current, " " )[1].tointeger(), split( current, " " )[2].tointeger() > endColor = Vector( RandomInt( 255 ), RandomInt( 255 ), RandomInt( 255 ) ) } colorResultX = GraphCapped( Time(), startTime, endTime, startColor.x, endColor.x ) colorResultY = GraphCapped( Time(), startTime, endTime, startColor.y, endColor.y ) colorResultZ = GraphCapped( Time(), startTime, endTime, startColor.z, endColor.z ) string colorString = colorResultX + " " + colorResultY + " " + colorResultZ weapon.kv.rendercolor = colorString WaitFrame() } }() }
412
0.827126
1
0.827126
game-dev
MEDIA
0.849787
game-dev
0.78666
1
0.78666
SkyFireArchives/SkyFireEMU_420
3,755
src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/> * Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Kormok SD%Complete: 100 SDComment: SDCategory: Scholomance EndScriptData */ #include "ScriptPCH.h" #define SPELL_SHADOWBOLTVOLLEY 20741 #define SPELL_BONESHIELD 27688 class boss_kormok : public CreatureScript { public: boss_kormok() : CreatureScript("boss_kormok") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_kormokAI (pCreature); } struct boss_kormokAI : public ScriptedAI { boss_kormokAI(Creature *c) : ScriptedAI(c) {} uint32 ShadowVolley_Timer; uint32 BoneShield_Timer; uint32 Minion_Timer; uint32 Mage_Timer; bool Mages; void Reset() { ShadowVolley_Timer = 10000; BoneShield_Timer = 2000; Minion_Timer = 15000; Mage_Timer = 0; Mages = false; } void EnterCombat(Unit * /*who*/) { } void SummonMinions(Unit* victim) { if (Creature *SummonedMinion = DoSpawnCreature(16119, float(irand(-7, 7)), float(irand(-7, 7)), 0, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 120000)) SummonedMinion->AI()->AttackStart(victim); } void SummonMages(Unit* victim) { if (Creature *SummonedMage = DoSpawnCreature(16120, float(irand(-9, 9)), float(irand(-9, 9)), 0, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 120000)) SummonedMage->AI()->AttackStart(victim); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //ShadowVolley_Timer if (ShadowVolley_Timer <= diff) { DoCast(me->getVictim(), SPELL_SHADOWBOLTVOLLEY); ShadowVolley_Timer = 15000; } else ShadowVolley_Timer -= diff; //BoneShield_Timer if (BoneShield_Timer <= diff) { DoCast(me->getVictim(), SPELL_BONESHIELD); BoneShield_Timer = 45000; } else BoneShield_Timer -= diff; //Minion_Timer if (Minion_Timer <= diff) { //Cast SummonMinions(me->getVictim()); SummonMinions(me->getVictim()); SummonMinions(me->getVictim()); SummonMinions(me->getVictim()); Minion_Timer = 12000; } else Minion_Timer -= diff; //Summon 2 Bone Mages if (!Mages && HealthBelowPct(26)) { //Cast SummonMages(me->getVictim()); SummonMages(me->getVictim()); Mages = true; } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_kormok() { new boss_kormok(); }
412
0.893658
1
0.893658
game-dev
MEDIA
0.989402
game-dev
0.91541
1
0.91541
lender544/new1.20.1
15,702
src/main/java/com/github/L_Ender/cataclysm/client/model/entity/Wadjet_Model.java
package com.github.L_Ender.cataclysm.client.model.entity;// Made with Blockbench 4.9.4 // Exported for Minecraft version 1.15 - 1.16 with MCP mappings // Paste this class into your mod and generate all required imports import com.github.L_Ender.cataclysm.client.animation.Wadjet_Animation; import com.github.L_Ender.cataclysm.entity.InternalAnimationMonster.Wadjet_Entity; import com.github.L_Ender.lionfishapi.client.model.tools.AdvancedEntityModel; import com.github.L_Ender.lionfishapi.client.model.tools.AdvancedModelBox; import com.github.L_Ender.lionfishapi.client.model.tools.BasicModelPart; import com.github.L_Ender.lionfishapi.client.model.tools.DynamicChain; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.client.Minecraft; public class Wadjet_Model extends AdvancedEntityModel<Wadjet_Entity> { private final AdvancedModelBox everything; private final AdvancedModelBox mid_root; private final AdvancedModelBox upper_body1; private final AdvancedModelBox pelvis; private final AdvancedModelBox upper_body2; private final AdvancedModelBox body; private final AdvancedModelBox neck1; private final AdvancedModelBox neck2; private final AdvancedModelBox face; private final AdvancedModelBox head; private final AdvancedModelBox cube_r1; private final AdvancedModelBox cube_r2; private final AdvancedModelBox cube_r3; private final AdvancedModelBox cube_r4; private final AdvancedModelBox jaw; private final AdvancedModelBox right_arm; private final AdvancedModelBox right_fore_arm; private final AdvancedModelBox right_finger3; private final AdvancedModelBox right_finger2; private final AdvancedModelBox right_finger1; private final AdvancedModelBox right_finger4; private final AdvancedModelBox wand; private final AdvancedModelBox cube_r5; private final AdvancedModelBox left_arm; private final AdvancedModelBox left_fore_arm; private final AdvancedModelBox left_finger3; private final AdvancedModelBox left_finger2; private final AdvancedModelBox left_finger1; private final AdvancedModelBox left_finger4; private final AdvancedModelBox tail1; private final AdvancedModelBox tail2; private final AdvancedModelBox tail3; private final AdvancedModelBox tail4; private final AdvancedModelBox tail5; private final AdvancedModelBox tailend; private DynamicChain tail; public AdvancedModelBox[] tailOriginal; public AdvancedModelBox[] tailDynamic; public Wadjet_Model() { texWidth = 256; texHeight = 256; everything = new AdvancedModelBox(this,"everything"); everything.setRotationPoint(0.0F, 18.1769F, -2.6276F); mid_root = new AdvancedModelBox(this,"mid_root"); mid_root.setRotationPoint(0.0F, 5.8231F, 2.6276F); everything.addChild(mid_root); upper_body1 = new AdvancedModelBox(this,"upper_body1"); upper_body1.setRotationPoint(0.0F, -4.8231F, -0.6276F); mid_root.addChild(upper_body1); setRotationAngle(upper_body1, -0.2618F, 0.0F, 0.0F); upper_body1.setTextureOffset(0, 63).addBox(-5.5F, -17.8375F, -3.68F, 11.0F, 20.0F, 6.0F, 0.0F, false); pelvis = new AdvancedModelBox(this,"pelvis"); pelvis.setRotationPoint(-0.0798F, -17.8375F, 2.02F); upper_body1.addChild(pelvis); setRotationAngle(pelvis, 0.5716F, 0.0F, 0.0F); pelvis.setTextureOffset(0, 47).addBox(-4.5076F, -3.0225F, -5.0839F, 9.0F, 4.0F, 6.0F, 0.0F, false); upper_body2 = new AdvancedModelBox(this,"upper_body2"); upper_body2.setRotationPoint(-0.0076F, -2.9878F, 0.5324F); pelvis.addChild(upper_body2); setRotationAngle(upper_body2, -0.1814F, 0.0F, 0.0F); upper_body2.setTextureOffset(79, 63).addBox(-8.5403F, -15.7808F, -5.6395F, 17.0F, 7.2F, 8.0F, 0.0F, false); upper_body2.setTextureOffset(37, 0).addBox(-3.5403F, -13.7808F, -3.6395F, 7.0F, 14.2F, 4.0F, 0.0F, false); body = new AdvancedModelBox(this,"body"); body.setRotationPoint(0.0492F, -6.6808F, 0.7605F); upper_body2.addChild(body); setRotationAngle(body, 0.0429F, 0.0F, 0.0F); neck1 = new AdvancedModelBox(this,"neck1"); neck1.setRotationPoint(0.0F, -8.5F, 0.0F); body.addChild(neck1); setRotationAngle(neck1, -0.2593F, 0.0F, 0.0F); neck1.setTextureOffset(112, 79).addBox(-4.3316F, -7.2976F, 0.0584F, 9.0F, 8.0F, 0.0F, 0.0F, false); neck1.setTextureOffset(0, 0).addBox(-2.3316F, -7.3252F, -3.9267F, 5.0F, 8.0F, 4.0F, 0.0F, false); neck2 = new AdvancedModelBox(this,"neck2"); neck2.setRotationPoint(0.3579F, -7.4995F, 1.0809F); neck1.addChild(neck2); setRotationAngle(neck2, 0.7854F, 0.0F, 0.0F); neck2.setTextureOffset(38, 63).addBox(-2.1895F, -8.4892F, -4.7357F, 4.0F, 8.0F, 4.0F, -0.1F, false); neck2.setTextureOffset(31, 26).addBox(-7.1895F, -7.5444F, -0.8563F, 14.0F, 9.0F, 0.0F, 0.0F, false); face = new AdvancedModelBox(this,"face"); face.setRotationPoint(-0.0895F, -6.8719F, -1.2524F); neck2.addChild(face); head = new AdvancedModelBox(this,"head"); head.setRotationPoint(0.0F, 0.0F, 0.0F); face.addChild(head); setRotationAngle(head, -0.4363F, 0.0F, 0.0F); cube_r1 = new AdvancedModelBox(this); cube_r1.setRotationPoint(-1.6F, 8.0116F, -1.3235F); head.addChild(cube_r1); setRotationAngle(cube_r1, 0.1745F, 0.0F, 0.0F); cube_r1.setTextureOffset(103, 0).addBox(-1.0F, -9.9F, -3.0F, 5.0F, 3.0F, 6.0F, 0.0F, false); cube_r2 = new AdvancedModelBox(this); cube_r2.setRotationPoint(1.4F, 1.0116F, -6.3235F); head.addChild(cube_r2); setRotationAngle(cube_r2, 0.7195F, 0.4166F, 0.2315F); cube_r2.setTextureOffset(31, 47).addBox(-2.2863F, -1.9404F, -0.9425F, 3.0F, 3.0F, 8.0F, 0.0F, false); cube_r3 = new AdvancedModelBox(this); cube_r3.setRotationPoint(-1.6F, 1.0116F, -6.3235F); head.addChild(cube_r3); setRotationAngle(cube_r3, 0.7195F, -0.4166F, -0.2315F); cube_r3.setTextureOffset(99, 99).addBox(-0.7137F, -1.9404F, -0.9425F, 3.0F, 3.0F, 8.0F, 0.0F, false); cube_r4 = new AdvancedModelBox(this); cube_r4.setRotationPoint(-1.1F, 8.0116F, -1.3235F); head.addChild(cube_r4); setRotationAngle(cube_r4, 0.3491F, 0.0F, 0.0F); cube_r4.setTextureOffset(103, 20).addBox(-1.0F, -10.0F, -4.8F, 4.0F, 3.0F, 5.0F, 0.0F, false); jaw = new AdvancedModelBox(this,"jaw"); jaw.setRotationPoint(0.5895F, 0.9632F, -2.4564F); head.addChild(jaw); setRotationAngle(jaw, 0.3927F, 0.0F, 0.0F); jaw.setTextureOffset(103, 10).addBox(-2.1895F, -1.0797F, -6.0886F, 3.0F, 2.0F, 7.0F, 0.0F, false); right_arm = new AdvancedModelBox(this,"right_arm"); right_arm.setRotationPoint(-5.3F, -5.8F, -2.4F); body.addChild(right_arm); setRotationAngle(right_arm, 0.0F, 0.5672F, -1.2654F); right_arm.setTextureOffset(65, 25).addBox(-9.9464F, -0.9857F, -1.7571F, 11.0F, 4.0F, 4.0F, 0.0F, false); right_fore_arm = new AdvancedModelBox(this,"right_fore_arm"); right_fore_arm.setRotationPoint(-9.9464F, -0.5213F, 0.1616F); right_arm.addChild(right_fore_arm); setRotationAngle(right_fore_arm, 0.0F, -0.6545F, 0.0F); right_fore_arm.setTextureOffset(0, 90).addBox(-11.0F, -0.4395F, -1.9186F, 11.0F, 3.0F, 4.0F, 0.0F, false); right_fore_arm.setTextureOffset(65, 0).addBox(-12.0F, -0.9395F, -2.4186F, 11.0F, 2.0F, 5.0F, 0.0F, false); right_finger3 = new AdvancedModelBox(this,"right_finger3"); right_finger3.setRotationPoint(-11.0F, 1.1F, -2.3F); right_fore_arm.addChild(right_finger3); right_finger3.setTextureOffset(0, 35).addBox(-6.0211F, -0.936F, 0.3767F, 6.0F, 2.0F, 0.0F, 0.0F, false); right_finger2 = new AdvancedModelBox(this,"right_finger2"); right_finger2.setRotationPoint(-11.0F, 1.1F, -0.3F); right_fore_arm.addChild(right_finger2); right_finger2.setTextureOffset(31, 36).addBox(-6.0211F, -0.936F, 0.3767F, 6.0F, 2.0F, 0.0F, 0.0F, false); right_finger1 = new AdvancedModelBox(this,"right_finger1"); right_finger1.setRotationPoint(-11.0F, 1.1F, 1.7F); right_fore_arm.addChild(right_finger1); right_finger1.setTextureOffset(0, 38).addBox(-6.0211F, -0.936F, 0.3767F, 6.0F, 2.0F, 0.0F, 0.0F, false); right_finger4 = new AdvancedModelBox(this,"right_finger4"); right_finger4.setRotationPoint(-10.0F, 2.5F, -2.7F); right_fore_arm.addChild(right_finger4); right_finger4.setTextureOffset(0, 16).addBox(-5.0211F, 0.164F, -0.7233F, 6.0F, 0.0F, 2.0F, 0.0F, false); wand = new AdvancedModelBox(this,"wand"); wand.setRotationPoint(-13.0F, 1.0F, 0.0F); right_fore_arm.addChild(wand); wand.setTextureOffset(0, 0).addBox(-1.0F, 0.0F, -25.0F, 2.0F, 2.0F, 60.0F, 0.0F, false); wand.setTextureOffset(65, 0).addBox(0.0F, -7.0F, -45.0F, 0.0F, 16.0F, 37.0F, 0.0F, false); cube_r5 = new AdvancedModelBox(this); cube_r5.setRotationPoint(13.0F, -1.0F, 0.0F); wand.addChild(cube_r5); setRotationAngle(cube_r5, 0.0F, 0.0F, -1.5708F); cube_r5.setTextureOffset(0, 63).addBox(-2.0F, -20.0F, -45.0F, 0.0F, 16.0F, 37.0F, 0.0F, false); left_arm = new AdvancedModelBox(this,"left_arm"); left_arm.setRotationPoint(5.121F, -5.8F, -2.4F); body.addChild(left_arm); setRotationAngle(left_arm, 0.0F, -0.2618F, 1.2654F); left_arm.setTextureOffset(65, 16).addBox(-1.0905F, -0.9857F, -1.8408F, 11.0F, 4.0F, 4.0F, 0.0F, false); left_fore_arm = new AdvancedModelBox(this,"left_fore_arm"); left_fore_arm.setRotationPoint(9.9095F, -0.5213F, 0.0778F); left_arm.addChild(left_fore_arm); setRotationAngle(left_fore_arm, 0.0F, 0.6545F, 0.0F); left_fore_arm.setTextureOffset(38, 90).addBox(0.0F, -0.4395F, -1.9186F, 11.0F, 3.0F, 4.0F, 0.0F, false); left_fore_arm.setTextureOffset(65, 8).addBox(1.0F, -0.9395F, -2.4186F, 11.0F, 2.0F, 5.0F, 0.0F, false); left_finger3 = new AdvancedModelBox(this,"left_finger3"); left_finger3.setRotationPoint(11.0F, 1.1F, -2.3F); left_fore_arm.addChild(left_finger3); left_finger3.setTextureOffset(0, 32).addBox(0.0211F, -0.936F, 0.3767F, 6.0F, 2.0F, 0.0F, 0.0F, false); left_finger2 = new AdvancedModelBox(this,"left_finger2"); left_finger2.setRotationPoint(11.0F, 1.1F, -0.3F); left_fore_arm.addChild(left_finger2); left_finger2.setTextureOffset(0, 29).addBox(0.0211F, -0.936F, 0.3767F, 6.0F, 2.0F, 0.0F, 0.0F, false); left_finger1 = new AdvancedModelBox(this,"left_finger1"); left_finger1.setRotationPoint(11.0F, 1.1F, 1.7F); left_fore_arm.addChild(left_finger1); left_finger1.setTextureOffset(0, 26).addBox(0.0211F, -0.936F, 0.3767F, 6.0F, 2.0F, 0.0F, 0.0F, false); left_finger4 = new AdvancedModelBox(this,"left_finger4"); left_finger4.setRotationPoint(10.0F, 2.5F, -2.7F); left_fore_arm.addChild(left_finger4); left_finger4.setTextureOffset(0, 13).addBox(-0.9789F, 0.164F, -0.7233F, 6.0F, 0.0F, 2.0F, 0.0F, false); tail1 = new AdvancedModelBox(this,"tail1"); tail1.setRotationPoint(0.0F, -3.0F, -2.0F); mid_root.addChild(tail1); tail1.setTextureOffset(38, 63).addBox(-5.0F, -3.0F, 0.0F, 10.0F, 6.0F, 20.0F, 0.0F, false); tail2 = new AdvancedModelBox(this,"tail2"); tail2.setRotationPoint(0.0F, 0.5F, 18.0F); tail1.addChild(tail2); tail2.setTextureOffset(0, 0).addBox(-4.0F, -2.5F, 0.0F, 8.0F, 5.0F, 20.0F, 0.0F, false); tail3 = new AdvancedModelBox(this,"tail3"); tail3.setRotationPoint(0.0F, 0.5F, 18.0F); tail2.addChild(tail3); tail3.setTextureOffset(0, 26).addBox(-3.5F, -2.0F, 0.0F, 7.0F, 4.0F, 16.0F, 0.0F, false); tail4 = new AdvancedModelBox(this,"tail4"); tail4.setRotationPoint(-0.5F, 1.0F, 15.0F); tail3.addChild(tail4); tail4.setTextureOffset(83, 79).addBox(-2.5F, -2.0F, 0.0F, 6.0F, 3.0F, 16.0F, 0.0F, false); tail5 = new AdvancedModelBox(this,"tail5"); tail5.setRotationPoint(0.5F, 0.0F, 15.0F); tail4.addChild(tail5); tail5.setTextureOffset(75, 99).addBox(-2.0F, -1.0F, 0.0F, 4.0F, 2.0F, 15.0F, 0.0F, false); tailend = new AdvancedModelBox(this,"tailend"); tailend.setRotationPoint(0.0F, 0.0F, 15.0F); tail5.addChild(tailend); updateDefaultPose(); tailOriginal = new AdvancedModelBox[]{tail1, tail2, tail3, tail4, tail5, tailend}; tailDynamic = new AdvancedModelBox[tailOriginal.length]; } @Override public void renderToBuffer(PoseStack matrixStackIn, VertexConsumer bufferIn, int packedLightIn, int packedOverlayIn, float red, float green, float blue, float alpha) { this.everything.render(matrixStackIn, bufferIn, packedLightIn, packedOverlayIn, red, green, blue, alpha); if (tail != null) tail.render(matrixStackIn, bufferIn, packedLightIn, packedOverlayIn, red, green, blue, alpha, tailDynamic); for (AdvancedModelBox AdvancedModelBox : tailOriginal) { AdvancedModelBox.showModel = false; } } public void animate(Wadjet_Entity entity, float f, float f1, float f2, float f3, float f4) { tail = entity.dc; this.resetToDefaultPose(); } @Override public void setupAnim(Wadjet_Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { animate(entity,limbSwing,limbSwingAmount,ageInTicks,netHeadYaw,headPitch); float swimSpeed = 0.1F; float swimDegree = 0.5F; float partialTick = Minecraft.getInstance().getFrameTime(); float attackProgress = entity.getAttackProgress(partialTick); float attackAmount = attackProgress * limbSwingAmount * 1.5F; this.animateHeadLookTarget(netHeadYaw, headPitch); this.animateWalk(Wadjet_Animation.WALK, limbSwing, limbSwingAmount, 1.0F, 1.0F); progressRotationPrev(upper_body1,attackAmount,(float)Math.toRadians(23.1591F), 0, 0, 10F); this.animate(entity.getAnimationState("idle"), Wadjet_Animation.IDLE, ageInTicks, 1.0F); this.animate(entity.getAnimationState("sleep"), Wadjet_Animation.SLEEP, ageInTicks, 1.0F); this.animate(entity.getAnimationState("awake"), Wadjet_Animation.AWAKE, ageInTicks, 1.0F); this.animate(entity.getAnimationState("charge"), Wadjet_Animation.SPEAR_CHARGE, ageInTicks, 1.0F); this.animate(entity.getAnimationState("magic"), Wadjet_Animation.MAGIC, ageInTicks, 1.0F); this.animate(entity.getAnimationState("death"), Wadjet_Animation.DEATH, ageInTicks, 1.0F); this.animate(entity.getAnimationState("doubleswing"), Wadjet_Animation.DOUBLE_SWING, ageInTicks, 1.0F); this.animate(entity.getAnimationState("stabnswing"), Wadjet_Animation.STAB_N_SWING, ageInTicks, 1.0F); this.animate(entity.getAnimationState("block"), Wadjet_Animation.BLOCK, ageInTicks, 1.0F); this.chainSwing(tailOriginal, swimSpeed * 4F, swimDegree * 1F, -3, limbSwing,limbSwingAmount); this.chainSwing(tailOriginal, swimSpeed * 0.6F, swimDegree * 0.15F, -3, ageInTicks,1.0F); entity.dc.updateChain(Minecraft.getInstance().getFrameTime(), tailOriginal, tailDynamic, 0.4f, 1.5f, 1.8f, 0.87f, 20, true); } private void animateHeadLookTarget(float yRot, float xRot) { float yawAmount = yRot / 57.295776F; float pitchAmount = xRot / 57.295776F; this.neck2.rotateAngleX += pitchAmount * 0.5F; this.neck2.rotateAngleY += yawAmount * 0.5F; this.face.rotateAngleX += pitchAmount * 0.5F; this.face.rotateAngleY += yawAmount * 0.5F; } public void setRotationAngle(AdvancedModelBox AdvancedModelBox, float x, float y, float z) { AdvancedModelBox.rotateAngleX = x; AdvancedModelBox.rotateAngleY = y; AdvancedModelBox.rotateAngleZ = z; } @Override public Iterable<BasicModelPart> parts() { return ImmutableList.of(everything); } @Override public Iterable<AdvancedModelBox> getAllParts() { return ImmutableList.of( everything, upper_body1, mid_root, pelvis, upper_body2, body, neck1, neck2, face, head, cube_r1, cube_r2, cube_r3, cube_r4, jaw, right_arm, right_fore_arm, right_finger3, right_finger2, right_finger1, right_finger4, wand, cube_r5, left_arm, left_fore_arm, left_finger3, left_finger2, left_finger1, left_finger4, tail1, tail2, tail3, tail4, tail5, tailend); } }
412
0.896548
1
0.896548
game-dev
MEDIA
0.485727
game-dev
0.894254
1
0.894254
huangkaoya/redalert2
5,187
src/game/superweapon/LightningStormEffect.ts
import { Coords } from "@/game/Coords"; import { LightningStormCloudEvent } from "@/game/event/LightningStormCloudEvent"; import { LightningStormManifestEvent } from "@/game/event/LightningStormManifestEvent"; import { CollisionType } from "@/game/gameobject/unit/CollisionType"; import { RangeHelper } from "@/game/gameobject/unit/RangeHelper"; import { GameSpeed } from "@/game/GameSpeed"; import { RandomTileFinder } from "@/game/map/tileFinder/RandomTileFinder"; import { Warhead } from "@/game/Warhead"; import { SuperWeaponEffect } from "@/game/superweapon/SuperWeaponEffect"; import { Game } from "@/game/Game"; import { Vector3 } from "@/game/math/Vector3"; enum LightningStormState { Approaching, Manifesting } interface Cloud { tile: TileCoord; durationTicks: number; ticksLeft: number; } export class LightningStormEffect extends SuperWeaponEffect { private state: LightningStormState = LightningStormState.Approaching; private clouds: Cloud[] = []; private manifestStartTimer: number = 0; private manifestEndTimer: number = 0; private nextDirectHitTimer: number = 0; private nextRandomHitTimer: number = 0; onStart(game: Game): void { const lightningStorm = game.rules.general.lightningStorm; this.manifestStartTimer = lightningStorm.deferment; this.manifestEndTimer = lightningStorm.duration; this.nextDirectHitTimer = 0; this.nextRandomHitTimer = 0; } onTick(game: Game): boolean { if (this.state === LightningStormState.Approaching) { if (this.manifestStartTimer > 0) { this.manifestStartTimer--; } else { this.state = LightningStormState.Manifesting; game.events.dispatch(new LightningStormManifestEvent(this.tile)); } } if (this.state === LightningStormState.Manifesting) { const lightningStorm = game.rules.general.lightningStorm; if (this.manifestEndTimer > 0) { this.manifestEndTimer--; if (this.nextDirectHitTimer > 0) { this.nextDirectHitTimer--; } if (this.nextDirectHitTimer <= 0) { this.nextDirectHitTimer = lightningStorm.hitDelay; this.spawnCloudAt(this.tile, game); } if (this.nextRandomHitTimer > 0) { this.nextRandomHitTimer--; } if (this.nextRandomHitTimer <= 0) { this.nextRandomHitTimer = lightningStorm.scatterDelay; const radius = Math.floor(lightningStorm.cellSpread / 2); const separation = lightningStorm.separation; const rangeHelper = new RangeHelper(game.map.tileOccupation); const tileFinder = new RandomTileFinder( game.map.tiles, game.map.mapBounds, this.tile, radius, game, (tile) => !this.clouds.some(cloud => rangeHelper.tileDistance(tile, cloud.tile) < separation), false ); const randomTile = tileFinder.getNextTile(); if (randomTile) { this.spawnCloudAt(randomTile, game); } } } for (const cloud of this.clouds.slice()) { if (cloud.ticksLeft > 0) { cloud.ticksLeft--; if (cloud.ticksLeft === Math.floor(cloud.durationTicks / 2)) { const warheadName = lightningStorm.warhead; const warhead = new Warhead(game.rules.getWarhead(warheadName)); const tile = cloud.tile; const bridge = game.map.tileOccupation.getBridgeOnTile(tile); const elevation = bridge?.tileElevation ?? 0; const zone = game.map.getTileZone(tile); warhead.detonate( game, lightningStorm.damage, tile, elevation, Coords.tile3dToWorld(tile.rx + 0.5, tile.ry + 0.5, tile.z + elevation), zone, bridge ? CollisionType.OnBridge : CollisionType.None, game.createTarget(bridge, tile), { player: this.owner, weapon: undefined }, false, true, undefined ); } } else { this.clouds.splice(this.clouds.indexOf(cloud), 1); } } if (!this.clouds.length && this.manifestEndTimer <= 0) { return true; } } return false; } private spawnCloudAt(tile: TileCoord, game: Game): void { const clouds = game.rules.audioVisual.weatherConClouds; const cloudIndex = game.generateRandomInt(0, clouds.length - 1); const animation = game.art.getAnimation(clouds[cloudIndex]); const rate = animation.art.getNumber("Rate", 60 * GameSpeed.BASE_TICKS_PER_SECOND) / 60; const durationTicks = Math.floor((GameSpeed.BASE_TICKS_PER_SECOND / rate) * 60); this.clouds.push({ tile, durationTicks, ticksLeft: durationTicks }); const elevation = (game.map.tileOccupation.getBridgeOnTile(tile)?.tileElevation ?? 0) + Coords.worldToTileHeight(game.rules.general.flightLevel); const position = Coords.tile3dToWorld(tile.rx + 0.5, tile.ry + 0.5, tile.z + elevation); game.events.dispatch(new LightningStormCloudEvent(position)); } }
412
0.968688
1
0.968688
game-dev
MEDIA
0.792357
game-dev
0.99529
1
0.99529
IronLanguages/ironpython2
3,263
Src/IronPythonTest/GenMeth.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. namespace IronPythonTest { // The sole purpose of this class is to provide many different methods of the same name that // differ only in their signature and/or their type parameters. Each returns a string that // uniquely identifies it so that we can validate the correct binding from the python side. // The instance and static methods have different names simply because C# doesn't allow two // methods to differ only by their "static-ness". public class GenMeth { public string InstMeth() { return "InstMeth()"; } public string InstMeth<T>() { return "InstMeth<" + typeof(T).Name + ">()"; } public string InstMeth<T, U>() { return "InstMeth<" + typeof(T).Name + ", " + typeof(U).Name + ">()"; } public string InstMeth(int arg1) { return "InstMeth(Int32)"; } public string InstMeth(string arg1) { return "InstMeth(String)"; } public string InstMeth<T>(int arg1) { return "InstMeth<" + typeof(T).Name + ">(Int32)"; } public string InstMeth<T>(string arg1) { return "InstMeth<" + typeof(T).Name + ">(String)"; } public string InstMeth<T, U>(int arg1) { return "InstMeth<" + typeof(T).Name + ", " + typeof(U).Name + ">(Int32)"; } public string InstMeth<T>(T arg1) { return "InstMeth<" + typeof(T).Name + ">(" + typeof(T).Name + ")"; } public string InstMeth<T, U>(T arg1, U arg2) { return "InstMeth<" + typeof(T).Name + ", " + typeof(U).Name + ">(" + typeof(T).Name + ", " + typeof(U).Name + ")"; } public static string StaticMeth() { return "StaticMeth()"; } public static string StaticMeth<T>() { return "StaticMeth<" + typeof(T).Name + ">()"; } public static string StaticMeth<T, U>() { return "StaticMeth<" + typeof(T).Name + ", " + typeof(U).Name + ">()"; } public static string StaticMeth(int arg1) { return "StaticMeth(Int32)"; } public static string StaticMeth(string arg1) { return "StaticMeth(String)"; } public static string StaticMeth<T>(int arg1) { return "StaticMeth<" + typeof(T).Name + ">(Int32)"; } public static string StaticMeth<T>(string arg1) { return "StaticMeth<" + typeof(T).Name + ">(String)"; } public static string StaticMeth<T, U>(int arg1) { return "StaticMeth<" + typeof(T).Name + ", " + typeof(U).Name + ">(Int32)"; } public static string StaticMeth<T>(T arg1) { return "StaticMeth<" + typeof(T).Name + ">(" + typeof(T).Name + ")"; } public static string StaticMeth<T, U>(T arg1, U arg2) { return "StaticMeth<" + typeof(T).Name + ", " + typeof(U).Name + ">(" + typeof(T).Name + ", " + typeof(U).Name + ")"; } } }
412
0.792777
1
0.792777
game-dev
MEDIA
0.242728
game-dev
0.775626
1
0.775626
EFanZh/LeetCode
1,041
src/problem_0789_escape_the_ghosts/mathematical.rs
pub struct Solution; // ------------------------------------------------------ snip ------------------------------------------------------ // impl Solution { pub fn escape_ghosts(ghosts: Vec<Vec<i32>>, target: Vec<i32>) -> bool { let [target_x, target_y] = target.as_slice().try_into().unwrap(); let my_distance = target_x.abs() + target_y.abs(); ghosts.iter().all(|ghost| { let [ghost_x, ghost_y] = ghost.as_slice().try_into().unwrap(); let ghost_distance = (target_x - ghost_x).abs() + (target_y - ghost_y).abs(); ghost_distance > my_distance }) } } // ------------------------------------------------------ snip ------------------------------------------------------ // impl super::Solution for Solution { fn escape_ghosts(ghosts: Vec<Vec<i32>>, target: Vec<i32>) -> bool { Self::escape_ghosts(ghosts, target) } } #[cfg(test)] mod tests { #[test] fn test_solution() { super::super::tests::run::<super::Solution>(); } }
412
0.728759
1
0.728759
game-dev
MEDIA
0.939579
game-dev
0.81786
1
0.81786
CyberdyneCC/Thermos
4,216
patches/org/bukkit/event/entity/EntityDamageEvent.java.patch
--- ../src-base/minecraft/org/bukkit/event/entity/EntityDamageEvent.java +++ ../src-work/minecraft/org/bukkit/event/entity/EntityDamageEvent.java @@ -10,6 +10,8 @@ import org.bukkit.event.HandlerList; import org.bukkit.util.NumberConversions; +import com.google.common.base.Function; +import com.google.common.base.Functions; import com.google.common.collect.ImmutableMap; /** @@ -18,7 +20,9 @@ public class EntityDamageEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private static final DamageModifier[] MODIFIERS = DamageModifier.values(); + private static final Function<? super Double, Double> ZERO = Functions.constant(-0.0); private final Map<DamageModifier, Double> modifiers; + private final Map<DamageModifier, ? extends Function<? super Double, Double>> modifierFunctions; private final Map<DamageModifier, Double> originals; private boolean cancelled; private final DamageCause cause; @@ -30,16 +34,20 @@ @Deprecated public EntityDamageEvent(final Entity damagee, final DamageCause cause, final double damage) { - this(damagee, cause, new EnumMap<DamageModifier, Double>(ImmutableMap.of(DamageModifier.BASE, damage))); + this(damagee, cause, new EnumMap<DamageModifier, Double>(ImmutableMap.of(DamageModifier.BASE, damage)), new EnumMap<DamageModifier, Function<? super Double, Double>>(ImmutableMap.of(DamageModifier.BASE, ZERO))); } - public EntityDamageEvent(final Entity damagee, final DamageCause cause, final Map<DamageModifier, Double> modifiers) { + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final Map<DamageModifier, Double> modifiers, final Map<DamageModifier, ? extends Function<? super Double, Double>> modifierFunctions) { super(damagee); Validate.isTrue(modifiers.containsKey(DamageModifier.BASE), "BASE DamageModifier missing"); Validate.isTrue(!modifiers.containsKey(null), "Cannot have null DamageModifier"); + Validate.noNullElements(modifiers.values(), "Cannot have null modifier values"); + Validate.isTrue(modifiers.keySet().equals(modifierFunctions.keySet()), "Must have a modifier function for each DamageModifier"); + Validate.noNullElements(modifierFunctions.values(), "Cannot have null modifier function"); this.originals = new EnumMap<DamageModifier, Double>(modifiers); this.cause = cause; this.modifiers = modifiers; + this.modifierFunctions = modifierFunctions; } public boolean isCancelled() { @@ -149,11 +157,39 @@ } /** - * Sets the raw amount of damage caused by the event + * Sets the raw amount of damage caused by the event. + * <p> + * For compatibility this also recalculates the modifiers and scales + * them by the difference between the modifier for the previous damage + * value and the new one. * * @param damage The raw amount of damage caused by the event */ public void setDamage(double damage) { + // These have to happen in the same order as the server calculates them, keep the enum sorted + double remaining = damage; + double oldRemaining = getDamage(DamageModifier.BASE); + for (DamageModifier modifier : MODIFIERS) { + if (!isApplicable(modifier)) { + continue; + } + + Function<? super Double, Double> modifierFunction = modifierFunctions.get(modifier); + double newVanilla = modifierFunction.apply(remaining); + double oldVanilla = modifierFunction.apply(oldRemaining); + double difference = oldVanilla - newVanilla; + + // Don't allow value to cross zero, assume zero values should be negative + double old = getDamage(modifier); + if (old > 0) { + setDamage(modifier, Math.max(0, old - difference)); + } else { + setDamage(modifier, Math.min(0, old - difference)); + } + remaining += newVanilla; + oldRemaining += oldVanilla; + } + setDamage(DamageModifier.BASE, damage); }
412
0.924094
1
0.924094
game-dev
MEDIA
0.92833
game-dev
0.720623
1
0.720623
pd-l2ork/pd-l2ork
4,607
externals/miXed/cyclone/sickle/poke.c
/* Copyright (c) 2003 krzYszcz and others. * For information on usage and redistribution, and for a DISCLAIMER OF ALL * WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ /* LATER: 'click' method */ #include "m_pd.h" #include "shared.h" #include "unstable/fragile.h" #include "sickle/sic.h" #include "sickle/arsic.h" #define POKE_MAXCHANNELS 4 /* LATER implement arsic resizing feature */ typedef struct _poke { t_arsic x_arsic; int x_maxchannels; int x_effchannel; /* effective channel (clipped reqchannel) */ int x_reqchannel; /* requested channel */ t_sample *x_indexptr; t_clock *x_clock; double x_clocklasttick; int x_clockset; } t_poke; static t_class *poke_class; static void poke_tick(t_poke *x) { arsic_redraw((t_arsic *)x); /* LATER redraw only dirty channel(s!) */ x->x_clockset = 0; x->x_clocklasttick = clock_getlogicaltime(); } static void poke_set(t_poke *x, t_symbol *s) { arsic_setarray((t_arsic *)x, s, 1); } static void poke_bang(t_poke *x) { arsic_redraw((t_arsic *)x); } /* CHECKED: index 0-based, negative values block input, overflowed are clipped. LATER revisit: incompatibly, the code below is nop for any out-of-range index (see also peek.c) */ /* CHECKED: value never clipped, 'clip' not understood */ /* CHECKED: no float-to-signal conversion. 'Float' message is ignored when dsp is on -- whether a signal is connected to the left inlet, or not (if not, current index is set to zero). Incompatible (revisit LATER) */ static void poke_float(t_poke *x, t_float f) { t_arsic *sic = (t_arsic *)x; t_word *vp; arsic_validate(sic, 0); /* LATER rethink (efficiency, and complaining) */ if (vp = sic->s_vectors[x->x_effchannel]) { int ndx = (int)*x->x_indexptr; if (ndx >= 0 && ndx < sic->s_vecsize) { double timesince; vp[ndx].w_float = f; timesince = clock_gettimesince(x->x_clocklasttick); if (timesince > 1000) poke_tick(x); else if (!x->x_clockset) { clock_delay(x->x_clock, 1000 - timesince); x->x_clockset = 1; } } } } static void poke_ft2(t_poke *x, t_floatarg f) { if ((x->x_reqchannel = (f > 1 ? (int)f - 1 : 0)) > x->x_maxchannels) x->x_effchannel = x->x_maxchannels - 1; else x->x_effchannel = x->x_reqchannel; } static t_int *poke_perform(t_int *w) { t_arsic *sic = (t_arsic *)(w[1]); int nblock = (int)(w[2]); t_float *in1 = (t_float *)(w[3]); t_float *in2 = (t_float *)(w[4]); t_poke *x = (t_poke *)sic; t_word *vp = sic->s_vectors[x->x_effchannel]; if (vp && sic->s_playable) { int vecsize = sic->s_vecsize; while (nblock--) { t_float f = *in1++; int ndx = (int)*in2++; if (ndx >= 0 && ndx < vecsize) vp[ndx].w_float = f; } } return (w + sic->s_nperfargs + 1); } static void poke_dsp(t_poke *x, t_signal **sp) { arsic_dsp((t_arsic *)x, sp, poke_perform, 0); } static void poke_free(t_poke *x) { if (x->x_clock) clock_free(x->x_clock); arsic_free((t_arsic *)x); } static void *poke_new(t_symbol *s, t_floatarg f) { int ch = (f > 0 ? (int)f : 0); t_poke *x = (t_poke *)arsic_new(poke_class, s, (ch ? POKE_MAXCHANNELS : 0), 2, 0); if (x) { t_inlet *in2; if (ch > POKE_MAXCHANNELS) ch = POKE_MAXCHANNELS; x->x_maxchannels = (ch ? POKE_MAXCHANNELS : 1); x->x_effchannel = x->x_reqchannel = (ch ? ch - 1 : 0); /* CHECKED: no float-to-signal conversion. Floats in 2nd inlet are ignored when dsp is on, but only if a signal is connected to this inlet. Incompatible (revisit LATER). */ in2 = inlet_new((t_object *)x, (t_pd *)x, &s_signal, &s_signal); x->x_indexptr = fragile_inlet_signalscalar(in2); inlet_new((t_object *)x, (t_pd *)x, &s_float, gensym("ft2")); x->x_clock = clock_new(x, (t_method)poke_tick); x->x_clocklasttick = clock_getlogicaltime(); x->x_clockset = 0; } return (x); } void poke_tilde_setup(void) { poke_class = class_new(gensym("poke~"), (t_newmethod)poke_new, (t_method)poke_free, sizeof(t_poke), 0, A_DEFSYM, A_DEFFLOAT, 0); arsic_setup(poke_class, poke_dsp, poke_float); class_addbang(poke_class, poke_bang); /* LATER rethink */ class_addfloat(poke_class, poke_float); class_addmethod(poke_class, (t_method)poke_set, gensym("set"), A_SYMBOL, 0); class_addmethod(poke_class, (t_method)poke_ft2, gensym("ft2"), A_FLOAT, 0); // logpost(NULL, 4, "this is cyclone/poke~ %s, %dth %s build", // CYCLONE_VERSION, CYCLONE_BUILD, CYCLONE_RELEASE); }
412
0.920457
1
0.920457
game-dev
MEDIA
0.630982
game-dev
0.71164
1
0.71164
Gaby-Station/Gaby-Station
3,246
Content.Server/Destructible/Thresholds/Behaviors/DumpRestockInventory.cs
// SPDX-FileCopyrightText: 2023 Chief-Engineer <119664036+Chief-Engineer@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 DrSmugleaf <DrSmugleaf@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 Nemanja <98561806+EmoGarbage404@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 Vordenburg <114301317+Vordenburg@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 TemporalOroboros <TemporalOroboros@gmail.com> // SPDX-FileCopyrightText: 2024 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: MIT using Robust.Shared.Random; using Content.Shared.Stacks; using Content.Shared.Prototypes; using Content.Shared.VendingMachines; namespace Content.Server.Destructible.Thresholds.Behaviors { /// <summary> /// Spawns a portion of the total items from one of the canRestock /// inventory entries on a VendingMachineRestock component. /// </summary> [Serializable] [DataDefinition] public sealed partial class DumpRestockInventory: IThresholdBehavior { /// <summary> /// The percent of each inventory entry that will be salvaged /// upon destruction of the package. /// </summary> [DataField("percent", required: true)] public float Percent = 0.5f; [DataField("offset")] public float Offset { get; set; } = 0.5f; public void Execute(EntityUid owner, DestructibleSystem system, EntityUid? cause = null) { if (!system.EntityManager.TryGetComponent<VendingMachineRestockComponent>(owner, out var packagecomp) || !system.EntityManager.TryGetComponent<TransformComponent>(owner, out var xform)) return; var randomInventory = system.Random.Pick(packagecomp.CanRestock); if (!system.PrototypeManager.TryIndex(randomInventory, out VendingMachineInventoryPrototype? packPrototype)) return; foreach (var (entityId, count) in packPrototype.StartingInventory) { var toSpawn = (int) Math.Round(count * Percent); if (toSpawn == 0) continue; if (EntityPrototypeHelpers.HasComponent<StackComponent>(entityId, system.PrototypeManager, system.EntityManager.ComponentFactory)) { var spawned = system.EntityManager.SpawnEntity(entityId, xform.Coordinates.Offset(system.Random.NextVector2(-Offset, Offset))); system.StackSystem.SetCount(spawned, toSpawn); system.EntityManager.GetComponent<TransformComponent>(spawned).LocalRotation = system.Random.NextAngle(); } else { for (var i = 0; i < toSpawn; i++) { var spawned = system.EntityManager.SpawnEntity(entityId, xform.Coordinates.Offset(system.Random.NextVector2(-Offset, Offset))); system.EntityManager.GetComponent<TransformComponent>(spawned).LocalRotation = system.Random.NextAngle(); } } } } } }
412
0.939737
1
0.939737
game-dev
MEDIA
0.982475
game-dev
0.951833
1
0.951833
followingthefasciaplane/source-engine-diff-check
5,514
misc/game/client/portal2/gameui/optionssubmultiplayer.h
//========= Copyright (c) 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef OPTIONSSUBMULTIPLAYER_H #define OPTIONSSUBMULTIPLAYER_H #ifdef _WIN32 #pragma once #endif #include <vgui_controls/PropertyPage.h> class CLabeledCommandComboBox; class CBitmapImagePanel; class CCvarToggleCheckButton; class CCvarTextEntry; class CCvarSlider; class CrosshairImagePanel; class CMultiplayerAdvancedDialog; class AdvancedCrosshairImagePanel; enum ConversionErrorType { CE_SUCCESS, CE_MEMORY_ERROR, CE_CANT_OPEN_SOURCE_FILE, CE_ERROR_PARSING_SOURCE, CE_SOURCE_FILE_FORMAT_NOT_SUPPORTED, CE_ERROR_WRITING_OUTPUT_FILE, CE_ERROR_LOADING_DLL }; struct TGAHeader { byte identsize; // size of ID field that follows 18 byte header (0 usually) byte colourmaptype; // type of colour map 0=none, 1=has palette byte imagetype; // type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed short colourmapstart; // first colour map entry in palette short colourmaplength; // number of colours in palette byte colourmapbits; // number of bits per palette entry 15,16,24,32 short xstart; // image x origin short ystart; // image y origin short width; // image width in pixels short height; // image height in pixels byte bits; // image bits per pixel 8,16,24,32 byte descriptor; // image descriptor bits (vh flip bits) }; //----------------------------------------------------------------------------- // Purpose: multiplayer options property page //----------------------------------------------------------------------------- class COptionsSubMultiplayer : public vgui::PropertyPage { DECLARE_CLASS_SIMPLE( COptionsSubMultiplayer, vgui::PropertyPage ); public: COptionsSubMultiplayer(vgui::Panel *parent); ~COptionsSubMultiplayer(); virtual vgui::Panel *CreateControlByName(const char *controlName); protected: // Called when page is loaded. Data should be reloaded from document into controls. virtual void OnResetData(); // Called when the OK / Apply button is pressed. Changed data should be written into document. virtual void OnApplyChanges(); virtual void OnCommand( const char *command ); private: void InitModelList(CLabeledCommandComboBox *cb); void InitLogoList(CLabeledCommandComboBox *cb); void RemapModel(); void RemapLogo(); MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel ); MESSAGE_FUNC_PARAMS( OnSliderMoved, "SliderMoved", data ); MESSAGE_FUNC( OnApplyButtonEnable, "ControlModified" ); MESSAGE_FUNC_CHARPTR( OnFileSelected, "FileSelected", fullpath ); void RemapPalette(char *filename, int topcolor, int bottomcolor); void ColorForName(char const *pszColorName, int &r, int &g, int &b); CBitmapImagePanel *m_pModelImage; CLabeledCommandComboBox *m_pModelList; char m_ModelName[128]; vgui::ImagePanel *m_pLogoImage; CLabeledCommandComboBox *m_pLogoList; char m_LogoName[128]; CCvarSlider *m_pPrimaryColorSlider; CCvarSlider *m_pSecondaryColorSlider; CCvarToggleCheckButton *m_pHighQualityModelCheckBox; // Mod specific general checkboxes vgui::Dar< CCvarToggleCheckButton * > m_cvarToggleCheckButtons; // --- crosshair controls ---------------------------------- CLabeledCommandComboBox *m_pCrosshairSize; void InitCrosshairSizeList(CLabeledCommandComboBox *cb); CCvarToggleCheckButton *m_pCrosshairTranslucencyCheckbox; vgui::ComboBox *m_pCrosshairColorComboBox; void InitCrosshairColorEntries(); void ApplyCrosshairColorChanges(); CrosshairImagePanel *m_pCrosshairImage; // called when the appearance of the crosshair has changed. void RedrawCrosshairImage(); // --------------------------------------------------------- // --- advanced crosshair controls AdvancedCrosshairImagePanel *m_pAdvCrosshairImage; CCvarSlider *m_pAdvCrosshairRedSlider; CCvarSlider *m_pAdvCrosshairBlueSlider; CCvarSlider *m_pAdvCrosshairGreenSlider; CCvarSlider *m_pAdvCrosshairScaleSlider; CLabeledCommandComboBox *m_pAdvCrosshairStyle; void InitAdvCrosshairStyleList(CLabeledCommandComboBox *cb); void RedrawAdvCrosshairImage(); // ----- // --- client download filter vgui::ComboBox *m_pDownloadFilterCombo; // Begin Spray Import Functions ConversionErrorType ConvertJPEGToTGA(const char *jpgPath, const char *tgaPath); ConversionErrorType ConvertBMPToTGA(const char *bmpPath, const char *tgaPath); ConversionErrorType ConvertTGA(const char *tgaPath); unsigned char *ReadTGAAsRGBA(const char *tgaPath, int &width, int &height, ConversionErrorType &errcode, TGAHeader &tgaHeader); ConversionErrorType StretchRGBAImage(const unsigned char *srcBuf, const int srcWidth, const int srcHeight, unsigned char *destBuf, const int destWidth, const int destHeight); ConversionErrorType PadRGBAImage(const unsigned char *srcBuf, const int srcWidth, const int srcHeight, unsigned char *destBuf, const int destWidth, const int destHeight); ConversionErrorType ConvertTGAToVTF(const char *tgaPath); ConversionErrorType WriteSprayVMT(const char *vtfPath); void SelectLogo(const char *logoName); // End Spray Import Functions int m_nTopColor; int m_nBottomColor; int m_nLogoR; int m_nLogoG; int m_nLogoB; vgui::DHANDLE<CMultiplayerAdvancedDialog> m_hMultiplayerAdvancedDialog; vgui::FileOpenDialog *m_hImportSprayDialog; }; #endif // OPTIONSSUBMULTIPLAYER_H
412
0.890031
1
0.890031
game-dev
MEDIA
0.539654
game-dev,desktop-app
0.687433
1
0.687433
Azerothwav/Az_trailer
11,844
lib/menu/Menu.lua
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by Dylan Malandain. --- DateTime: 21/04/2019 21:20 --- ---CreateMenu ---@param Title string ---@param Subtitle string ---@param X number ---@param Y number ---@param TextureDictionary string ---@param TextureName string ---@param R number ---@param G number ---@param B number ---@param A number ---@return RageUIMenus ---@public function RageUI.CreateMenu(Title, Subtitle, X, Y, TextureDictionary, TextureName, R, G, B, A) ---@type table local Menu = {} Menu.Display = {}; Menu.InstructionalButtons = {} Menu.Display.Header = true; Menu.Display.Glare = true; Menu.Display.Subtitle = true; Menu.Display.Background = true; Menu.Display.Navigation = true; Menu.Display.InstructionalButton = false; Menu.Display.PageCounter = true; Menu.Title = Title or "" Menu.TitleFont = 1 Menu.TitleScale = 1.2 Menu.Subtitle = string.upper(Subtitle) or nil Menu.SubtitleHeight = -37 Menu.Description = nil Menu.DescriptionHeight = RageUI.Settings.Items.Description.Background.Height Menu.X = X or 0 Menu.Y = Y or 0 Menu.Parent = nil Menu.WidthOffset = RageUI.UI.Style[RageUI.UI.Current].Width Menu.Open = false Menu.Controls = RageUI.Settings.Controls Menu.Index = 1 Menu.Sprite = { Dictionary = TextureDictionary or "commonmenu", Texture = TextureName or "interaction_bgd", Color = { R = R, G = G, B = B, A = A } } Menu.Rectangle = nil Menu.Pagination = { Minimum = 1, Maximum = 10, Total = 10 } Menu.Safezone = true Menu.SafeZoneSize = nil Menu.EnableMouse = false Menu.Options = 0 Menu.Closable = true Menu.InstructionalScaleform = RequestScaleformMovie("INSTRUCTIONAL_BUTTONS") Menu.CursorStyle = 1 if string.starts(Menu.Subtitle, "~") then Menu.PageCounterColour = string.lower(string.sub(Menu.Subtitle, 1, 3)) else Menu.PageCounterColour = "" end if Menu.Subtitle ~= "" then local SubtitleLineCount = GetLineCount(Menu.Subtitle, Menu.X + RageUI.Settings.Items.Subtitle.Text.X, Menu.Y + RageUI.Settings.Items.Subtitle.Text.Y, 0, RageUI.Settings.Items.Subtitle.Text.Scale, 245, 245, 245, 255, nil, false, false, RageUI.Settings.Items.Subtitle.Background.Width + Menu.WidthOffset) if SubtitleLineCount > 1 then Menu.SubtitleHeight = 18 * SubtitleLineCount else Menu.SubtitleHeight = 0 end end Citizen.CreateThread(function() if not HasScaleformMovieLoaded(Menu.InstructionalScaleform) then Menu.InstructionalScaleform = RequestScaleformMovie("INSTRUCTIONAL_BUTTONS") while not HasScaleformMovieLoaded(Menu.InstructionalScaleform) do Citizen.Wait(0) end end end) Citizen.CreateThread(function() local ScaleformMovie = RequestScaleformMovie("MP_MENU_GLARE") while not HasScaleformMovieLoaded(ScaleformMovie) do Citizen.Wait(0) end end) return setmetatable(Menu, RageUI.Menus) end ---CreateSubMenu ---@param ParentMenu function ---@param Title string ---@param Subtitle string ---@param X number ---@param Y number ---@param TextureDictionary string ---@param TextureName string ---@param R number ---@param G number ---@param B number ---@param A number ---@return RageUIMenus ---@public function RageUI.CreateSubMenu(ParentMenu, Title, Subtitle, X, Y, TextureDictionary, TextureName, R, G, B, A) if ParentMenu ~= nil then if ParentMenu() then local Menu = RageUI.CreateMenu(Title or ParentMenu.Title, Subtitle ~= nil and (Subtitle ~= "" and (Subtitle) or (ParentMenu.Subtitle)) or "", X or ParentMenu.X, Y or ParentMenu.Y) Menu.Parent = ParentMenu Menu.WidthOffset = ParentMenu.WidthOffset Menu.Safezone = ParentMenu.Safezone if ParentMenu.Sprite then Menu.Sprite = { Dictionary = TextureDictionary or ParentMenu.Sprite.Dictionary, Texture = TextureName or ParentMenu.Sprite.Texture, Color = { R = R or ParentMenu.Sprite.Color.R, G = G or ParentMenu.Sprite.Color.G, B = B or ParentMenu.Sprite.Color.B, A = A or ParentMenu.Sprite.Color.A } } else Menu.Rectangle = ParentMenu.Rectangle end return setmetatable(Menu, RageUI.Menus) else return nil end else return nil end end function RageUI.Menus:DisplayHeader(boolean) self.Display.Header = boolean; return self.Display.Header; end function RageUI.Menus:DisplayGlare(boolean) self.Display.Glare = boolean; return self.Display.Glare; end function RageUI.Menus:DisplaySubtitle(boolean) self.Display.Subtitle = boolean; return self.Display.Subtitle; end function RageUI.Menus:DisplayNavigation(boolean) self.Display.Navigation = boolean; return self.Display.Navigation; end function RageUI.Menus:DisplayInstructionalButton(boolean) self.Display.InstructionalButton = boolean; return self.Display.InstructionalButton; end function RageUI.Menus:DisplayPageCounter(boolean) self.Display.PageCounter= boolean; return self.Display.PageCounter; end ---SetTitle ---@param Title string ---@return nil ---@public function RageUI.Menus:SetTitle(Title) self.Title = Title end function RageUI.Menus:SetStyleSize(Value) local witdh if Value >= 0 and Value <= 100 then witdh = Value else witdh = 100 end self.WidthOffset = witdh end ---GetStyleSize ---@return any ---@public function RageUI.Menus:GetStyleSize() if (self.WidthOffset == 100) then return "RageUI" elseif (self.WidthOffset == 0) then return "NativeUI"; else return self.WidthOffset; end end ---SetStyleSize ---@param Int string ---@return void ---@public function RageUI.Menus:SetCursorStyle(Int) self.CursorStyle = Int or 1 or 0 SetMouseCursorSprite(Int) end ---ResetCursorStyle ---@return void ---@public function RageUI.Menus:ResetCursorStyle() self.CursorStyle = 1 SetMouseCursorSprite(1) end ---UpdateCursorStyle ---@return void ---@public function RageUI.Menus:UpdateCursorStyle() SetMouseCursorSprite(self.CursorStyle) end ---RefreshIndex ---@return void ---@public function RageUI.Menus:RefreshIndex() self.Index = 1 end ---SetSubtitle ---@param Subtitle string ---@return nil ---@public function RageUI.Menus:SetSubtitle(Subtitle) self.Subtitle = string.upper(Subtitle) or string.upper(self.Subtitle) if string.starts(self.Subtitle, "~") then self.PageCounterColour = string.lower(string.sub(self.Subtitle, 1, 3)) else self.PageCounterColour = "" end if self.Subtitle ~= "" then local SubtitleLineCount = GetLineCount(self.Subtitle, self.X + RageUI.Settings.Items.Subtitle.Text.X, self.Y + RageUI.Settings.Items.Subtitle.Text.Y, 0, RageUI.Settings.Items.Subtitle.Text.Scale, 245, 245, 245, 255, nil, false, false, RageUI.Settings.Items.Subtitle.Background.Width + self.WidthOffset) if SubtitleLineCount > 1 then self.SubtitleHeight = 18 * SubtitleLineCount else self.SubtitleHeight = 0 end else self.SubtitleHeight = -37 end end ---PageCounter ---@param Subtitle string ---@return nil ---@public function RageUI.Menus:SetPageCounter(Subtitle) self.PageCounter = Subtitle end ---EditSpriteColor ---@param Colors table ---@return nil ---@public function RageUI.Menus:EditSpriteColor(R, G, B, A) if self.Sprite.Dictionary == "commonmenu" then self.Sprite.Color = { R = tonumber(R) or 255, G = tonumber(G) or 255, B = tonumber(B) or 255, A = tonumber(A) or 255 } end end ---SetPosition ---@param X number ---@param Y number ---@return nil ---@public function RageUI.Menus:SetPosition(X, Y) self.X = tonumber(X) or self.X self.Y = tonumber(Y) or self.Y end ---SetTotalItemsPerPage ---@param Value number ---@return nil ---@public function RageUI.Menus:SetTotalItemsPerPage(Value) self.Pagination.Total = tonumber(Value) or self.Pagination.Total end ---SetRectangleBanner ---@param R number ---@param G number ---@param B number ---@param A number ---@return nil ---@public function RageUI.Menus:SetRectangleBanner(R, G, B, A) self.Rectangle = { R = tonumber(R) or 255, G = tonumber(G) or 255, B = tonumber(B) or 255, A = tonumber(A) or 255 } self.Sprite = nil end ---SetSpriteBanner ---@param TextureDictionary string ---@param Texture string ---@return nil ---@public function RageUI.Menus:SetSpriteBanner(TextureDictionary, Texture) self.Sprite = { Dictionary = TextureDictionary or "commonmenu", Texture = Texture or "interaction_bgd" } self.Rectangle = nil end function RageUI.Menus:Closable(boolean) if type(boolean) == "boolean" then self.Closable = boolean else error("Type is not boolean") end end function RageUI.Menus:AddInstructionButton(button) if type(button) == "table" and #button == 2 then table.insert(self.InstructionalButtons, button) self.UpdateInstructionalButtons(true); end end function RageUI.Menus:RemoveInstructionButton(button) if type(button) == "table" then for i = 1, #self.InstructionalButtons do if button == self.InstructionalButtons[i] then table.remove(self.InstructionalButtons, i) self.UpdateInstructionalButtons(true); break end end else if tonumber(button) then if self.InstructionalButtons[tonumber(button)] then table.remove(self.InstructionalButtons, tonumber(button)) self.UpdateInstructionalButtons(true); end end end end function RageUI.Menus:UpdateInstructionalButtons(Visible) if not Visible then return end BeginScaleformMovieMethod(self.InstructionalScaleform, "CLEAR_ALL") EndScaleformMovieMethod() BeginScaleformMovieMethod(self.InstructionalScaleform, "TOGGLE_MOUSE_BUTTONS") ScaleformMovieMethodAddParamInt(0) EndScaleformMovieMethod() BeginScaleformMovieMethod(self.InstructionalScaleform, "CREATE_CONTAINER") EndScaleformMovieMethod() BeginScaleformMovieMethod(self.InstructionalScaleform, "SET_DATA_SLOT") ScaleformMovieMethodAddParamInt(0) PushScaleformMovieMethodParameterButtonName(GetControlInstructionalButton(2, 176, 0)) PushScaleformMovieMethodParameterString(GetLabelText("HUD_INPUT2")) EndScaleformMovieMethod() if self.Closable then BeginScaleformMovieMethod(self.InstructionalScaleform, "SET_DATA_SLOT") ScaleformMovieMethodAddParamInt(1) PushScaleformMovieMethodParameterButtonName(GetControlInstructionalButton(2, 177, 0)) PushScaleformMovieMethodParameterString(GetLabelText("HUD_INPUT3")) EndScaleformMovieMethod() end local count = 2 if (self.InstructionalButtons ~= nil) then for i = 1, #self.InstructionalButtons do if self.InstructionalButtons[i] then if #self.InstructionalButtons[i] == 2 then BeginScaleformMovieMethod(self.InstructionalScaleform, "SET_DATA_SLOT") ScaleformMovieMethodAddParamInt(count) PushScaleformMovieMethodParameterButtonName(self.InstructionalButtons[i][1]) PushScaleformMovieMethodParameterString(self.InstructionalButtons[i][2]) EndScaleformMovieMethod() count = count + 1 end end end end BeginScaleformMovieMethod(self.InstructionalScaleform, "DRAW_INSTRUCTIONAL_BUTTONS") ScaleformMovieMethodAddParamInt(-1) EndScaleformMovieMethod() end
412
0.912005
1
0.912005
game-dev
MEDIA
0.690561
game-dev
0.807912
1
0.807912
Rz-C/Mohist
2,805
src/main/java/net/minecraftforge/event/AttachCapabilitiesEvent.java
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.minecraftforge.event; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.Collections; import java.util.List; import java.util.Map; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.eventbus.api.GenericEvent; /** * Fired whenever an object with Capabilities support {currently TileEntity/Item/Entity) * is created. Allowing for the attachment of arbitrary capability providers. * * Please note that as this is fired for ALL object creations efficient code is recommended. * And if possible use one of the sub-classes to filter your intended objects. */ public class AttachCapabilitiesEvent<T> extends GenericEvent<T> { private final T obj; private final Map<ResourceLocation, ICapabilityProvider> caps = Maps.newLinkedHashMap(); private final Map<ResourceLocation, ICapabilityProvider> view = Collections.unmodifiableMap(caps); private final List<Runnable> listeners = Lists.newArrayList(); private final List<Runnable> listenersView = Collections.unmodifiableList(listeners); public AttachCapabilitiesEvent(Class<T> type, T obj) { super(type); this.obj = obj; } /** * Retrieves the object that is being created, Not much state is set. */ public T getObject() { return this.obj; } /** * Adds a capability to be attached to this object. * Keys MUST be unique, it is suggested that you set the domain to your mod ID. * If the capability is an instance of INBTSerializable, this key will be used when serializing this capability. * * @param key The name of owner of this capability provider. * @param cap The capability provider */ public void addCapability(ResourceLocation key, ICapabilityProvider cap) { if (caps.containsKey(key)) throw new IllegalStateException("Duplicate Capability Key: " + key + " " + cap); this.caps.put(key, cap); } /** * A unmodifiable view of the capabilities that will be attached to this object. */ public Map<ResourceLocation, ICapabilityProvider> getCapabilities() { return view; } /** * Adds a callback that is fired when the attached object is invalidated. * Such as a Entity/TileEntity being removed from world. * All attached providers should invalidate all of their held capability instances. */ public void addListener(Runnable listener) { this.listeners.add(listener); } public List<Runnable> getListeners() { return this.listenersView; } }
412
0.808857
1
0.808857
game-dev
MEDIA
0.872583
game-dev
0.61662
1
0.61662
himself65/OpenArkCompiler
4,073
src/mplfe/common/src/fe_input.cpp
/* * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include "fe_input.h" #include "mempool_allocator.h" namespace maple { // ---------- FEInputContent ---------- template <typename T> FEInputContent<T>::FEInputContent(MapleAllocator &alloc) : allocator(alloc), items(allocator.Adapter()), nameItemMap(allocator.Adapter()), sameNames(allocator.Adapter()), policySameName(FEInputSameNamePolicy::kFatalOnce) {} template <typename T> void FEInputContent<T>::RegisterItem(T *item) { FEInputUnit *itemUnit = dynamic_cast<FEInputUnit*>(item); ASSERT(itemUnit != nullptr, "Invalid item type"); ASSERT(itemUnit->GetNameIdxMpl().GetIdx() != 0, "Invalid name idx (not set)"); GStrIdx nameIdxMpl = itemUnit->GetNameIdxMpl(); if (nameItemMap.find(nameIdxMpl) != nameItemMap.end()) { // name is defined std::string catagoryName = itemUnit->GetCatagoryName(); std::string name = GlobalTables::GetStrTable().GetStringFromStrIdx(nameIdxMpl); switch (policySameName) { case FEInputSameNamePolicy::kFatalOnce: FATAL(kLncFatal, "%s with the same name %s existed. exit.", catagoryName.c_str(), name.c_str()); break; case FEInputSameNamePolicy::kFatalAll: WARN(kLncWarn, "%s with the same name %s existed.", catagoryName.c_str(), name.c_str()); sameNames.push_back(nameIdxMpl); break; case FEInputSameNamePolicy::kUseFirst: WARN(kLncWarn, "%s with the same name %s existed. Use first.", catagoryName.c_str(), name.c_str()); break; case FEInputSameNamePolicy::kUseNewest: WARN(kLncWarn, "%s with the same name %s existed. Use newest.", catagoryName.c_str(), name.c_str()); EraseItem(nameIdxMpl); items.push_back(item); nameItemMap[nameIdxMpl] = item; break; } } else { // name is undefined items.push_back(item); nameItemMap[nameIdxMpl] = item; } } template <typename T> void FEInputContent<T>::CheckSameName() { if (policySameName != FEInputSameNamePolicy::kFatalAll) { return; } if (sameNames.size() > 0) { T *item = items.front(); FEInputUnit *itemUnit = dynamic_cast<FEInputUnit*>(item); ASSERT(itemUnit != nullptr, "Invalid item type"); FATAL(kLncFatal, "%s with the same name existed. Exit", itemUnit->GetCatagoryName().c_str()); } } template <typename T> void FEInputContent<T>::EraseItem(GStrIdx nameIdxMpl) { typename MapleList<T*>::iterator it; for (it = items.begin(); it != items.end();) { FEInputUnit *itemUnit = dynamic_cast<FEInputUnit*>(*it); ASSERT(itemUnit != nullptr, "Invalid item type"); if (itemUnit->GetNameIdxMpl() == nameIdxMpl) { it = items.erase(it); } else { ++it; } } } // ---------- FEInputUnitMethod ---------- FEInputUnitMethod::FEInputUnitMethod(MapleAllocator &alloc) : allocator(alloc) {} std::string FEInputUnitMethod::GetCatagoryNameImpl() { return "Method"; } // ---------- FEInputUnitVariable ---------- FEInputUnitVariable::FEInputUnitVariable(MapleAllocator &alloc) : allocator(alloc) {} std::string FEInputUnitVariable::GetCatagoryNameImpl() { return "Variable/Field"; } // ---------- FEInputUnitStruct ---------- FEInputUnitStruct::FEInputUnitStruct(MapleAllocator &alloc) : allocator(alloc), methods(allocator), methodsStatic(allocator), fields(allocator), fieldsStatic(allocator), typeKind(kTypeInvalid) {} std::string FEInputUnitStruct::GetCatagoryNameImpl() { return "Variable/Field"; } } // namespace maple
412
0.937762
1
0.937762
game-dev
MEDIA
0.528527
game-dev
0.954002
1
0.954002
googlearchive/caja
3,794
src/com/google/caja/parser/js/UncajoledModule.java
// Copyright (C) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.caja.parser.js; import com.google.caja.lexer.FilePosition; import com.google.caja.lexer.TokenConsumer; import com.google.caja.parser.AbstractParseTreeNode; import com.google.caja.parser.ParseTreeNode; import com.google.caja.render.Concatenator; import com.google.caja.render.JsPrettyPrinter; import com.google.caja.reporting.RenderContext; import com.google.caja.util.Callback; import java.io.IOException; import java.util.Collections; import java.util.List; /** * Translates to a cajoled module which renders as: <tt>___.loadModule...</tt>. * This is not a core JavaScript parse tree node &mdash; it is never produced by * {@link Parser}. * * Legacy: still used by TracingRewriter even though there's no longer such * things as cajoling or modules. * * @author erights@gmail.com * @author ihab.awad@gmail.com */ public final class UncajoledModule extends AbstractParseTreeNode { private static final long serialVersionUID = 4647984501924442035L; /** @param value unused. This ctor is provided for reflection. */ @ReflectiveCtor public UncajoledModule(FilePosition pos, Void value, List<? extends Block> children) { this(pos, children.get(0)); assert children.size() == 1; } public UncajoledModule(FilePosition pos, Block body) { super(pos, Block.class); createMutation().appendChild(body).execute(); } public UncajoledModule(Block body) { this(FilePosition.UNKNOWN, body); } public static UncajoledModule of(ParseTreeNode node) { if (node instanceof Block) { return new UncajoledModule((Block) node); } else if (node instanceof Statement) { return new UncajoledModule(new Block( node.getFilePosition(), Collections.singletonList((Statement) node))); } else if (node instanceof Expression) { return new UncajoledModule(new Block( node.getFilePosition(), Collections.singletonList(new ExpressionStmt((Expression) node)))); } else { throw new ClassCastException("Unexpected node type " + node); } } @Override protected void childrenChanged() { super.childrenChanged(); if (children().size() != 1) { throw new IllegalStateException( "An UncajoledModule may only have one child"); } ParseTreeNode module = children().get(0); if (!(module instanceof Block)) { throw new ClassCastException("Expected block, not " + module); } } @Override public Object getValue() { return null; } @Override public List<? extends Block> children() { return childrenAs(Block.class); } public Block getModuleBody() { return children().get(0); } public final TokenConsumer makeRenderer( Appendable out, Callback<IOException> exHandler) { return new JsPrettyPrinter(new Concatenator(out, exHandler)); } public void render(RenderContext rc) { TokenConsumer out = rc.getOut(); out.consume("/* Start Uncajoled Module */"); out.consume("throw"); out.consume("'Uncajoled Module must never be executed'"); out.consume(";"); getModuleBody().render(rc); out.consume("/* End Uncajoled Module */"); } }
412
0.869201
1
0.869201
game-dev
MEDIA
0.340767
game-dev
0.837701
1
0.837701
collabnix/kubelabs
4,545
.bundles_cache/ruby/2.6.0/gems/eventmachine-1.2.7/ext/fastfilereader/mapper.cpp
/***************************************************************************** $Id: mapper.cpp 4527 2007-07-04 10:21:34Z francis $ File: mapper.cpp Date: 02Jul07 Copyright (C) 2007 by Francis Cianfrocca. All Rights Reserved. Gmail: garbagecat10 This program is free software; you can redistribute it and/or modify it under the terms of either: 1) the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version; or 2) Ruby's License. See the file COPYING for complete licensing information. *****************************************************************************/ ////////////////////////////////////////////////////////////////////// // UNIX implementation ////////////////////////////////////////////////////////////////////// #ifdef OS_UNIX #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <iostream> #include <string> #include <cstring> #include <stdexcept> #include "mapper.h" /****************** Mapper_t::Mapper_t ******************/ Mapper_t::Mapper_t (const std::string &filename) { /* We ASSUME we can open the file. * (More precisely, we assume someone else checked before we got here.) */ Fd = open (filename.c_str(), O_RDONLY); if (Fd < 0) throw std::runtime_error (strerror (errno)); struct stat st; if (fstat (Fd, &st)) throw std::runtime_error (strerror (errno)); FileSize = st.st_size; #ifdef OS_WIN32 MapPoint = (char*) mmap (0, FileSize, PROT_READ, MAP_SHARED, Fd, 0); #else MapPoint = (const char*) mmap (0, FileSize, PROT_READ, MAP_SHARED, Fd, 0); #endif if (MapPoint == MAP_FAILED) throw std::runtime_error (strerror (errno)); } /******************* Mapper_t::~Mapper_t *******************/ Mapper_t::~Mapper_t() { Close(); } /*************** Mapper_t::Close ***************/ void Mapper_t::Close() { // Can be called multiple times. // Calls to GetChunk are invalid after a call to Close. if (MapPoint) { #ifdef CC_SUNWspro // TODO: The void * cast works fine on Solaris 11, but // I don't know at what point that changed from older Solaris. munmap ((char*)MapPoint, FileSize); #else munmap ((void*)MapPoint, FileSize); #endif MapPoint = NULL; } if (Fd >= 0) { close (Fd); Fd = -1; } } /****************** Mapper_t::GetChunk ******************/ const char *Mapper_t::GetChunk (unsigned start) { return MapPoint + start; } #endif // OS_UNIX ////////////////////////////////////////////////////////////////////// // WINDOWS implementation ////////////////////////////////////////////////////////////////////// #ifdef OS_WIN32 #include <windows.h> #include <iostream> #include <string> #include <stdexcept> #include "mapper.h" /****************** Mapper_t::Mapper_t ******************/ Mapper_t::Mapper_t (const std::string &filename) { /* We ASSUME we can open the file. * (More precisely, we assume someone else checked before we got here.) */ hFile = INVALID_HANDLE_VALUE; hMapping = NULL; MapPoint = NULL; FileSize = 0; hFile = CreateFile (filename.c_str(), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) throw std::runtime_error ("File not found"); BY_HANDLE_FILE_INFORMATION i; if (GetFileInformationByHandle (hFile, &i)) FileSize = i.nFileSizeLow; hMapping = CreateFileMapping (hFile, NULL, PAGE_READWRITE, 0, 0, NULL); if (!hMapping) throw std::runtime_error ("File not mapped"); #ifdef OS_WIN32 MapPoint = (char*) MapViewOfFile (hMapping, FILE_MAP_WRITE, 0, 0, 0); #else MapPoint = (const char*) MapViewOfFile (hMapping, FILE_MAP_WRITE, 0, 0, 0); #endif if (!MapPoint) throw std::runtime_error ("Mappoint not read"); } /******************* Mapper_t::~Mapper_t *******************/ Mapper_t::~Mapper_t() { Close(); } /*************** Mapper_t::Close ***************/ void Mapper_t::Close() { // Can be called multiple times. // Calls to GetChunk are invalid after a call to Close. if (MapPoint) { UnmapViewOfFile (MapPoint); MapPoint = NULL; } if (hMapping != NULL) { CloseHandle (hMapping); hMapping = NULL; } if (hFile != INVALID_HANDLE_VALUE) { CloseHandle (hFile); hFile = INVALID_HANDLE_VALUE; } } /****************** Mapper_t::GetChunk ******************/ const char *Mapper_t::GetChunk (unsigned start) { return MapPoint + start; } #endif // OS_WINDOWS
412
0.881348
1
0.881348
game-dev
MEDIA
0.214126
game-dev
0.919846
1
0.919846
doukutsu-rs/doukutsu-rs
12,154
src/game/npc/boss/heavy_press.rs
use crate::common::{Direction, Rect}; use crate::framework::error::GameResult; use crate::game::npc::boss::BossNPC; use crate::game::npc::{NPCContext, NPC}; use crate::game::physics::HitExtents; use crate::game::shared_game_state::SharedGameState; use crate::util::rng::RNG; use super::BossNPCContext; impl NPC { pub(crate) fn tick_n325_heavy_press_lightning( &mut self, state: &mut SharedGameState, NPCContext { npc_list, .. }: NPCContext, ) -> GameResult { match self.action_num { 0 | 1 => { if self.action_num == 0 { self.action_num = 1; state.sound_manager.play_sfx(29); } self.animate(0, 0, 2); self.action_counter += 1; if self.action_counter > 50 { self.action_num = 10; self.anim_counter = 0; self.anim_num = 3; self.damage = 10; self.display_bounds.left = 0x1000; self.display_bounds.top = 0x1800; state.sound_manager.play_sfx(101); npc_list.create_death_smoke(self.x, self.y + 0xA800, 0, 3, state, &self.rng); } } 10 => { self.animate(2, 3, 7); if self.anim_num > 6 { self.cond.set_alive(false); return Ok(()); }; } _ => (), } self.anim_rect = state.constants.npc.n325_heavy_press_lightning[self.anim_num as usize]; Ok(()) } } impl BossNPC { pub(crate) fn tick_b08_heavy_press( &mut self, state: &mut SharedGameState, BossNPCContext { npc_list, npc_token, stage, .. }: BossNPCContext, ) { match self.parts[0].action_num { 0 => { self.parts[0].action_num = 10; self.parts[0].cond.set_alive(true); self.parts[0].exp = 1; self.parts[0].direction = Direction::Right; self.parts[0].x = 0; self.parts[0].y = 0; self.parts[0].display_bounds = Rect { left: 0x5000, top: 0x7800, right: 0x5000, bottom: 0x7800 }; self.parts[0].hit_bounds = HitExtents { left: 0x6200, top: 0x7800, right: 0x5000, bottom: 0x6000 }; self.hurt_sound[0] = 54; self.parts[0].npc_flags.set_ignore_solidity(true); self.parts[0].npc_flags.set_solid_hard(true); self.parts[0].npc_flags.set_event_when_killed(true); self.parts[0].npc_flags.set_show_damage(true); self.parts[0].size = 3; self.parts[0].damage = 10; self.parts[0].event_num = 1000; self.parts[0].life = 700; } 5 => { self.parts[0].action_num = 6; self.parts[0].x = 0; self.parts[0].y = 0; self.parts[1].cond.set_alive(false); self.parts[2].cond.set_alive(false); } 10 => { self.parts[0].action_num = 11; self.parts[0].x = 0x14000; self.parts[0].y = 0x9400; } 20 | 21 => { if self.parts[0].action_num == 20 { self.parts[0].action_num = 21; self.parts[0].damage = 0; self.parts[0].x = 0x14000 + (state.constants.game.tile_offset_x * 0x2000); self.parts[0].y = 0x33A00; self.parts[0].npc_flags.set_solid_hard(false); self.parts[1].cond.set_alive(false); self.parts[2].cond.set_alive(false); } self.parts[0].action_counter += 1; if self.parts[0].action_counter % 16 == 0 { npc_list.create_death_smoke( self.parts[0].x + self.parts[0].rng.range(-40..40) * 0x200, self.parts[0].y + self.parts[0].rng.range(-60..60) * 0x200, 1, 1, state, &self.parts[0].rng, ); } } 30 | 31 => { if self.parts[0].action_num == 30 { self.parts[0].action_num = 31; self.parts[0].anim_num = 2; self.parts[0].x = 0x14000 + (state.constants.game.tile_offset_x * 0x2000); self.parts[0].y = 0x8000; } self.parts[0].y += 0x800; if self.parts[0].y >= 0x33A00 { self.parts[0].y = 0x33A00; self.parts[0].anim_num = 0; self.parts[0].action_num = 20; state.sound_manager.play_sfx(44); for _ in 0..5 { let mut npc = NPC::create(4, &state.npc_table); npc.x = self.parts[0].x + self.parts[0].rng.range(-40..40) * 0x200; npc.y = self.parts[0].y + 0x7800; let _ = npc_list.spawn(0x100, npc.clone()); } } } 100 | 101 => { if self.parts[0].action_num == 100 { self.parts[0].action_num = 101; self.parts[0].action_counter3 = 9; self.parts[0].action_counter = 0; // This should be -100 self.parts[1].cond.set_alive(true); self.parts[1].npc_flags.set_invulnerable(true); self.parts[1].npc_flags.set_ignore_solidity(true); self.parts[1].hit_bounds = HitExtents { left: 0x1C00, top: 0x1000, right: 0x1C00, bottom: 0x1000 }; self.parts[2] = self.parts[1].clone(); self.parts[3].cond.set_alive(true); self.parts[3].cond.set_damage_boss(true); self.parts[3].npc_flags.set_shootable(true); self.parts[3].hit_bounds = HitExtents { left: 0xC00, top: 0x1000, right: 0xC00, bottom: 0x1000 }; let mut npc = NPC::create(325, &state.npc_table); npc.cond.set_alive(true); npc.x = self.parts[0].x; npc.y = self.parts[0].y + 0x7800; let _ = npc_list.spawn(0x100, npc); } if self.parts[0].action_counter3 > 1 && self.parts[0].life < self.parts[0].action_counter3 * 70 { self.parts[0].action_counter3 -= 1; // This relies heavily on the map not being changed // Need to calculate offset from the default starting location for i in 0..5 { let extra_smoke = if stage.change_tile(i + 8, self.parts[0].action_counter3 as usize, 0) { 3 } else { 0 }; npc_list.create_death_smoke( (i as i32 + 8) * 0x2000, self.parts[0].action_counter3 as i32 * 0x2000, 0, 4 + extra_smoke, state, &self.parts[0].rng, ); state.sound_manager.play_sfx(12); } } self.parts[0].action_counter += 1; // All of these checks are +100 to account for no negative values if self.parts[0].action_counter == 181 || self.parts[0].action_counter == 341 { let mut npc = NPC::create(323, &state.npc_table); npc.cond.set_alive(true); npc.x = 0x6000; npc.y = 0x1E000; npc.direction = Direction::Up; let _ = npc_list.spawn(0x100, npc); } else if self.parts[0].action_counter == 101 || self.parts[0].action_counter == 261 { let mut npc = NPC::create(323, &state.npc_table); npc.cond.set_alive(true); npc.x = 0x22000; npc.y = 0x1E000; npc.direction = Direction::Up; let _ = npc_list.spawn(0x100, npc); } else if self.parts[0].action_counter >= 400 { self.parts[0].action_counter = 100; // Should be 0 let mut npc = NPC::create(325, &state.npc_table); npc.cond.set_alive(true); npc.x = self.parts[0].x; npc.y = self.parts[0].y + 0x7800; let _ = npc_list.spawn(0x100, npc); } } 500 | 501 => { if self.parts[0].action_num == 500 { self.parts[3].npc_flags.set_shootable(false); self.parts[0].action_num = 501; self.parts[0].action_counter = 0; self.parts[0].action_counter2 = 0; npc_list.kill_npcs_by_type(325, true, state, npc_token); npc_list.kill_npcs_by_type(330, true, state, npc_token); } self.parts[0].action_counter += 1; if self.parts[0].action_counter % 16 == 0 { state.sound_manager.play_sfx(12); npc_list.create_death_smoke( self.parts[0].x + self.parts[0].rng.range(-40..40) * 0x200, self.parts[0].y + self.parts[0].rng.range(-60..60) * 0x200, 1, 1, state, &self.parts[0].rng, ); } if self.parts[0].action_counter == 95 { self.parts[0].anim_num = 1; } else if self.parts[0].action_counter == 98 { self.parts[0].anim_num = 2; } else if self.parts[0].action_counter > 100 { self.parts[0].action_num = 510; } } 510 => { self.parts[0].vel_y += 64; self.parts[0].damage = 127; self.parts[0].y += self.parts[0].vel_y; if self.parts[0].action_counter2 == 0 && self.parts[0].y > 0x14000 { self.parts[0].action_counter2 = 1; self.parts[0].vel_y = -0x200; self.parts[0].damage = 0; // This relies heavily on the map not being changed // Need to calculate offset from the default starting location for i in 0..7 { stage.change_tile(i + 7, 14, 0); // This should be called with an amount of 0, but change_tile also needs to make smoke npc_list.create_death_smoke((i as i32 + 7) * 0x2000, 0x1C000, 0, 3, state, &self.parts[0].rng); state.sound_manager.play_sfx(12); } } if self.parts[0].y > 0x3C000 { self.parts[0].action_num = 520; } } _ => (), } self.parts[1].x = self.parts[0].x - 0x3000; self.parts[1].y = self.parts[0].y + 0x6800; self.parts[2].x = self.parts[0].x + 0x3000; self.parts[2].y = self.parts[0].y + 0x6800; self.parts[3].x = self.parts[0].x; self.parts[3].y = self.parts[0].y + 0x5000; let mut anim_offset = 0; if self.parts[0].shock != 0 { self.parts[4].action_counter += 1; if self.parts[4].action_counter & 0x02 == 0 { anim_offset = 3; } } self.parts[0].anim_rect = state.constants.npc.b08_heavy_press[self.parts[0].anim_num as usize + anim_offset]; } }
412
0.787405
1
0.787405
game-dev
MEDIA
0.909435
game-dev
0.908596
1
0.908596
Lotus-AU/LotusContinued
5,157
src/Managers/Templates/TemplateTriggers.cs
using System; using System.Collections.Generic; using System.Linq; using Lotus.API.Reactive; using Lotus.API.Reactive.HookEvents; using Lotus.Extensions; using Lotus.Logging; using Lotus.Managers.Templates.Models; using Lotus.Roles.Interfaces; using Lotus.Roles; using VentLib.Utilities; using VentLib.Utilities.Extensions; using VentLib.Utilities.Optionals; namespace Lotus.Managers.Templates; public class TemplateTriggers { private static readonly StandardLogger log = LoggerFactory.GetLogger<StandardLogger>(typeof(TemplateTriggers)); public static Dictionary<string, TriggerBinder> TriggerHooks = new() { { "LobbyStart", (key, action) => Hooks.NetworkHooks.GameJoinHook.Bind(key, ev => Async.WaitUntil(() => { }, () => ev.Loaded, () => { if (AmongUsClient.Instance.AmHost) action(ev); }, maxRetries: 30), true) }, { "PlayerDeath", (key, action) => Hooks.PlayerHooks.PlayerDeathHook.Bind(key, action, true) }, { "PlayerDisconnect", (key, action) => Hooks.PlayerHooks.PlayerDisconnectHook.Bind(key, action, true) }, { "PlayerChat", (key, action) => Hooks.PlayerHooks.PlayerMessageHook.Bind(key, action, true) }, { "CustomCommand", (key, action) => Hooks.ModHooks.CustomCommandHook.Bind(key, action, true) }, { "StatusReceived", (key, action) => Hooks.ModHooks.StatusReceivedHook.Bind(key, action, true) }, { "TaskComplete", (key, action) => Hooks.PlayerHooks.PlayerTaskCompleteHook.Bind(key, ev => Async.Schedule(() => action(ev), 0.001f), true) }, { "ForceEndGame", (key, action) => Hooks.ResultHooks.ForceEndGameHook.Bind(key, action, true) }, }; public static Dictionary<Type, Func<IHookEvent, ResolvedTrigger>> TriggerResolvers = new() { { typeof(PlayerMessageHookEvent), he => ResultFromPlayerMessageHook((PlayerMessageHookEvent)he) }, { typeof(CustomCommandHookEvent), he => ResultFromCustomCommandHook((CustomCommandHookEvent)he) }, { typeof(GameJoinHookEvent), he => ResultFromGameJoinHook((GameJoinHookEvent)he) }, { typeof(PlayerStatusReceivedHook), he => ResultFromPlayerStatusHook((PlayerStatusReceivedHook)he) }, { typeof(PlayerTaskHookEvent), he => ResultFromPlayerTaskHook((PlayerTaskHookEvent)he) }, { typeof(PlayerMurderHookEvent), he => ResultFromPlayerDeathHook((PlayerDeathHookEvent)he) }, { typeof(PlayerDeathHookEvent), he => ResultFromPlayerHook((PlayerDeathHookEvent)he) }, { typeof(PlayerHookEvent), he => ResultFromPlayerHook((PlayerHookEvent)he) }, { typeof(EmptyHookEvent), he => ResultFromEmptyHook((EmptyHookEvent)he) }, }; public static ResolvedTrigger ResultFromGameJoinHook(GameJoinHookEvent gje) { return new ResolvedTrigger { Player = PlayerControl.LocalPlayer, Data = gje.IsNewLobby.ToString() }; } public static ResolvedTrigger ResultFromEmptyHook(EmptyHookEvent _) { return new ResolvedTrigger { Player = PlayerControl.LocalPlayer, Data = PlayerControl.LocalPlayer.name }; } public static ResolvedTrigger ResultFromPlayerStatusHook(PlayerStatusReceivedHook playerHookEvent) { return new ResolvedTrigger { Player = playerHookEvent.Player, Data = playerHookEvent.Status.Name }; } public static ResolvedTrigger ResultFromPlayerTaskHook(PlayerTaskHookEvent playerHookEvent) { return new ResolvedTrigger { Player = playerHookEvent.Player, Data = playerHookEvent.Player.Data.Tasks.ToArray().Count(t => t.Complete).ToString() }; } public static ResolvedTrigger ResultFromCustomCommandHook(CustomCommandHookEvent commandHookEvent) { return new ResolvedTrigger { Player = commandHookEvent.Player, Data = commandHookEvent.Args.Fuse(" ") }; } public static ResolvedTrigger ResultFromPlayerMessageHook(PlayerMessageHookEvent playerHookEvent) { return new ResolvedTrigger { Player = playerHookEvent.Player, Data = playerHookEvent.Message.Trim() }; } public static ResolvedTrigger ResultFromPlayerDeathHook(PlayerDeathHookEvent playerHookEvent) { return new ResolvedTrigger { Player = playerHookEvent.Player, Data = playerHookEvent.CauseOfDeath.Instigator().FlatMap(fp => new UnityOptional<PlayerControl>(fp.MyPlayer)).Map(p => p.name).OrElse("Unknown") }; } public static ResolvedTrigger ResultFromPlayerHook(PlayerHookEvent playerHookEvent) { return new ResolvedTrigger { Player = playerHookEvent.Player, Data = playerHookEvent.Player.name }; } public static Hook? BindTrigger(string key, string trigger, Action<ResolvedTrigger?> handler) { return TriggerHooks.GetOptional(trigger).Transform(tb => tb(key, h => { DevLogger.Log($"Event: {h}"); DevLogger.Log($"Event Type: {h.GetType()}"); handler(TriggerResolvers.GetValueOrDefault(h.GetType())?.Invoke(h)); }), () => { log.Warn($"Could not bind Trigger \"{key}.\" No such trigger exists!"); return null!; }); } public delegate Hook TriggerBinder(string key, Action<IHookEvent> handler); }
412
0.885123
1
0.885123
game-dev
MEDIA
0.857193
game-dev
0.903216
1
0.903216
guttir14/SoT-Hook
1,073
include/UE4/Rotator.h
#pragma once struct FRotator { float Pitch, Yaw, Roll; FRotator() : Pitch(0), Yaw(0), Roll(0) { } FRotator(float pitch, float yaw, float roll) : Pitch(pitch), Yaw(yaw), Roll(roll) {} FRotator operator+ (const FRotator& other) const { return FRotator(Pitch + other.Pitch, Yaw + other.Yaw, Roll + other.Roll); } FRotator operator- (const FRotator& other) const { return FRotator(Pitch - other.Pitch, Yaw - other.Yaw, Roll - other.Roll); } FRotator operator* (float scalar) const { return FRotator(Pitch * scalar, Yaw * scalar, Roll * scalar); } FRotator& operator= (const FRotator& other) { Pitch = other.Pitch; Yaw = other.Yaw; Roll = other.Roll; return *this; } FRotator& operator+= (const FRotator& other) { Pitch += other.Pitch; Yaw += other.Yaw; Roll += other.Roll; return *this; } FRotator& operator-= (const FRotator& other) { Pitch -= other.Pitch; Yaw -= other.Yaw; Roll -= other.Roll; return *this; } FRotator& operator*= (const float other) { Yaw *= other; Pitch *= other; Roll *= other; return *this; } struct FQuat Quaternion() const; };
412
0.614438
1
0.614438
game-dev
MEDIA
0.8172
game-dev
0.847859
1
0.847859
DruidMech/UE4-CPP-Shooter-Series
1,593
Source Code Per Lesson/Section 5 - The Weapon/56 The Item Class/ShooterAnimInstance.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Animation/AnimInstance.h" #include "ShooterAnimInstance.generated.h" /** * */ UCLASS() class SHOOTER_API UShooterAnimInstance : public UAnimInstance { GENERATED_BODY() public: UFUNCTION(BlueprintCallable) void UpdateAnimationProperties(float DeltaTime); virtual void NativeInitializeAnimation() override; private: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) class AShooterCharacter* ShooterCharacter; /** The speed of the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) float Speed; /** Whether or not the character is in the air */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) bool bIsInAir; /** Whether or not the character is moving */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) bool bIsAccelerating; /** Offset yaw used for strafing */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true")) float MovementOffsetYaw; /** Offset yaw the frame before we stopped moving */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement, meta = (AllowPrivateAccess = "true")) float LastMovementOffsetYaw; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) bool bAiming; };
412
0.767343
1
0.767343
game-dev
MEDIA
0.938165
game-dev
0.612545
1
0.612545
JoeyDeVries/Lucid
7,392
Includes/Box2D/Dynamics/Contacts/b2Contact.cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2CircleContact.h> #include <Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2PolygonContact.h> #include <Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h> #include <Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h> #include <Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h> #include <Box2D/Dynamics/Contacts/b2ContactSolver.h> #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2TimeOfImpact.h> #include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Common/b2BlockAllocator.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2World.h> b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; bool b2Contact::s_initialized = false; void b2Contact::InitializeRegisters() { AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); } void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, b2Shape::Type type1, b2Shape::Type type2) { b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); s_registers[type1][type2].createFcn = createFcn; s_registers[type1][type2].destroyFcn = destoryFcn; s_registers[type1][type2].primary = true; if (type1 != type2) { s_registers[type2][type1].createFcn = createFcn; s_registers[type2][type1].destroyFcn = destoryFcn; s_registers[type2][type1].primary = false; } } b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) { if (s_initialized == false) { InitializeRegisters(); s_initialized = true; } b2Shape::Type type1 = fixtureA->GetType(); b2Shape::Type type2 = fixtureB->GetType(); b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; if (createFcn) { if (s_registers[type1][type2].primary) { return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); } else { return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); } } else { return NULL; } } void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) { b2Assert(s_initialized == true); b2Fixture* fixtureA = contact->m_fixtureA; b2Fixture* fixtureB = contact->m_fixtureB; if (contact->m_manifold.pointCount > 0 && fixtureA->IsSensor() == false && fixtureB->IsSensor() == false) { fixtureA->GetBody()->SetAwake(true); fixtureB->GetBody()->SetAwake(true); } b2Shape::Type typeA = fixtureA->GetType(); b2Shape::Type typeB = fixtureB->GetType(); b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; destroyFcn(contact, allocator); } b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) { m_flags = e_enabledFlag; m_fixtureA = fA; m_fixtureB = fB; m_indexA = indexA; m_indexB = indexB; m_manifold.pointCount = 0; m_prev = NULL; m_next = NULL; m_nodeA.contact = NULL; m_nodeA.prev = NULL; m_nodeA.next = NULL; m_nodeA.other = NULL; m_nodeB.contact = NULL; m_nodeB.prev = NULL; m_nodeB.next = NULL; m_nodeB.other = NULL; m_toiCount = 0; m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); m_tangentSpeed = 0.0f; } // Update the contact manifold and touching status. // Note: do not assume the fixture AABBs are overlapping or are valid. void b2Contact::Update(b2ContactListener* listener) { b2Manifold oldManifold = m_manifold; // Re-enable this contact. m_flags |= e_enabledFlag; bool touching = false; bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; bool sensorA = m_fixtureA->IsSensor(); bool sensorB = m_fixtureB->IsSensor(); bool sensor = sensorA || sensorB; b2Body* bodyA = m_fixtureA->GetBody(); b2Body* bodyB = m_fixtureB->GetBody(); const b2Transform& xfA = bodyA->GetTransform(); const b2Transform& xfB = bodyB->GetTransform(); // Is this contact a sensor? if (sensor) { const b2Shape* shapeA = m_fixtureA->GetShape(); const b2Shape* shapeB = m_fixtureB->GetShape(); touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); // Sensors don't generate manifolds. m_manifold.pointCount = 0; } else { Evaluate(&m_manifold, xfA, xfB); touching = m_manifold.pointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. for (int32 i = 0; i < m_manifold.pointCount; ++i) { b2ManifoldPoint* mp2 = m_manifold.points + i; mp2->normalImpulse = 0.0f; mp2->tangentImpulse = 0.0f; b2ContactID id2 = mp2->id; for (int32 j = 0; j < oldManifold.pointCount; ++j) { b2ManifoldPoint* mp1 = oldManifold.points + j; if (mp1->id.key == id2.key) { mp2->normalImpulse = mp1->normalImpulse; mp2->tangentImpulse = mp1->tangentImpulse; break; } } } if (touching != wasTouching) { bodyA->SetAwake(true); bodyB->SetAwake(true); } } if (touching) { m_flags |= e_touchingFlag; } else { m_flags &= ~e_touchingFlag; } if (wasTouching == false && touching == true && listener) { listener->BeginContact(this); } if (wasTouching == true && touching == false && listener) { listener->EndContact(this); } if (sensor == false && touching && listener) { listener->PreSolve(this, &oldManifold); } }
412
0.972749
1
0.972749
game-dev
MEDIA
0.787207
game-dev
0.972427
1
0.972427
iniside/Velesarc
1,586
ArcX/ArcAI/Source/ArcAI/Tasks/ArcMassUseGameplayAbilityTask.h
#pragma once #include "GameplayAbilitySpecHandle.h" #include "MassActorSubsystem.h" #include "MassStateTreeTypes.h" #include "ArcMassUseGameplayAbilityTask.generated.h" class UGameplayAbility; USTRUCT() struct FArcMassUseGameplayAbilityTaskInstanceData { GENERATED_BODY() public: UPROPERTY(EditAnywhere, Category = "Parameter") TSubclassOf<UGameplayAbility> AbilityClassToActivate; UPROPERTY(EditAnywhere, Category = "Parameter") FGameplayTagContainer ActivateAbilityWithTags; FDelegateHandle OnAbilityEndedHandle; FGameplayAbilitySpecHandle AbilityHandle; }; USTRUCT(meta = (DisplayName = "Arc Mass Actor Use Gameplay Ability", Category = "AI|Action")) struct FArcMassUseGameplayAbilityTask : public FMassStateTreeTaskBase { GENERATED_BODY() public: using FInstanceDataType = FArcMassUseGameplayAbilityTaskInstanceData; virtual const UStruct* GetInstanceDataType() const override { return FInstanceDataType::StaticStruct(); } FArcMassUseGameplayAbilityTask(); virtual bool Link(FStateTreeLinker& Linker) override; virtual void GetDependencies(UE::MassBehavior::FStateTreeDependencyBuilder& Builder) const override; virtual EStateTreeRunStatus EnterState(FStateTreeExecutionContext& Context, const FStateTreeTransitionResult& Transition) const override; //virtual EStateTreeRunStatus Tick(FStateTreeExecutionContext& Context, const float DeltaTime) const override; //virtual void ExitState(FStateTreeExecutionContext& Context, const FStateTreeTransitionResult& Transition) const override; TStateTreeExternalDataHandle<FMassActorFragment> MassActorHandle; };
412
0.844231
1
0.844231
game-dev
MEDIA
0.980871
game-dev
0.59825
1
0.59825
Keyslam/Inky
5,164
inky/core/element/init.lua
local PATH = string.sub(..., 1, string.len(...) - string.len("core.element")) ---@module "inky.lib.class" local Class = require(PATH .. "lib.class") ---@module "inky.core.element.internal" local Internal = require(PATH .. "core.element.internal") ---@alias Inky.Element.Initializer fun(self: Inky.Element, scene: Inky.Scene): Inky.Element.Draw ---@alias Inky.Element.Draw fun(self: Inky.Element, x: number, y: number, w: number, h: number, depth?: number) ---@alias Inky.Element.OnCallback fun(element: Inky.Element, ...: any): nil ---@alias Inky.Element.OnPointerCallback fun(element: Inky.Element, pointer: Inky.Pointer, ...: any): nil ---@alias Inky.Element.OnPointerInHierarchyCallback fun(element: Inky.Element, pointer: Inky.Pointer, ...: any): nil ---@alias Inky.Element.OnPointerEnterCallback fun(element: Inky.Element, pointer: Inky.Pointer): nil ---@alias Inky.Element.OnPointerExitCallback fun(element: Inky.Element, pointer: Inky.Pointer): nil ---@alias Inky.Element.OnEnableCallback fun(element: Inky.Element): nil ---@alias Inky.Element.OnDisableCallback fun(element: Inky.Element): nil ---@alias Inky.Element.Effect fun(element: Inky.Element): nil ---@alias Inky.Element.OverlapPredicate fun(pointerX: number, pointerY: number, x: number, y: number, w: number, h: number): boolean ---@class Inky.Element --- ---@field private _internal Inky.Element.Internal --- ---@field props Inky.Props --- ---@operator call:Inky.Element local Element = Class() ---@param initializer Inky.Element.Initializer ---@private function Element:constructor(scene, initializer) self._internal = Internal(self, scene, initializer) self.props = self._internal:getProps() end ---Return the x, y, w, h that the Element was last rendered at --- ---@return number x ---@return number y ---@return number w ---@return number h ---@nodiscard function Element:getView() return self._internal:getView() end ---Execute callback when Scene event is raised from the parent Scene ---\ ---@see Inky.Scene.raise --- ---@param eventName string ---@param callback Inky.Element.OnCallback ---@return self function Element:on(eventName, callback) self._internal:on(eventName, callback) return self end ---Execute callback when a Pointer event is raised from an overlapping/capturing Pointer ---\ ---@see Inky.Pointer.raise ---@see Inky.Pointer.captureElement --- ---@param eventName string ---@param callback Inky.Element.OnPointerCallback ---@return self function Element:onPointer(eventName, callback) self._internal:onPointer(eventName, callback) return self end ---Execute callback when a Pointer event was accepted by a child Element ---\ ---@see Inky.Pointer.raise ---@see Inky.Element.onPointer --- ---@param eventName string ---@param callback Inky.Element.OnPointerInHierarchyCallback ---@return self function Element:onPointerInHierarchy(eventName, callback) self._internal:onPointerInHierarchy(eventName, callback) return self end ---Execute callback when a Pointer enters the bounding box of the Element --- ---@param callback Inky.Element.OnPointerEnterCallback ---@return self function Element:onPointerEnter(callback) self._internal:onPointerEnter(callback) return self end ---Execute callback when a Pointer exits the bounding box of the Element ---@param callback Inky.Element.OnPointerExitCallback ---@return self function Element:onPointerExit(callback) self._internal:onPointerExit(callback) return self end ---Execute callback when an Element is rendered, when it wasn't rendered last frame --- ---@param callback? Inky.Element.OnEnableCallback ---@return self function Element:onEnable(callback) self._internal:onEnable(callback) return self end ---Execute callback when an Element isn't rendered, when it was rendered last frame --- ---@param callback? Inky.Element.OnDisableCallback ---@return self function Element:onDisable(callback) self._internal:onDisable(callback) return self end ---Use an additional check to determine if a Pointer is overlapping an Element --- ---Note: Check is performed after a bounding box check --- ---@param predicate Inky.Element.OverlapPredicate ---@return self function Element:useOverlapCheck(predicate) self._internal:useOverlapCheck(predicate) return self end ---Execute a side effect when any specified Element's prop changes --- ---Note: The effect is ran right before a render --- ---@param effect Inky.Element.Effect ---@param ... any ---@return self function Element:useEffect(effect, ...) self._internal:useEffect(effect, ...) return self end ---Render the Element, setting up all the hooks and drawing the Element --- ---Note: The parent Scene's frame must have been begun to be able to render\ --- ---@see Inky.Scene.beginFrame --- ---@param x number ---@param y number ---@param w number ---@param h number ---@param depth? number function Element:render(x, y, w, h, depth) self._internal:render(x, y, w, h, depth) return self end ---Get the internal representation of the Element --- ---For internal use\ ---Don't touch unless you know what you're doing ---@return Inky.Element.Internal ---@nodiscard function Element:__getInternal() return self._internal end return Element
412
0.879748
1
0.879748
game-dev
MEDIA
0.335545
game-dev
0.945462
1
0.945462
godlikepanos/anki-3d-engine
4,227
ThirdParty/Jolt/Samples/Tests/Constraints/ConstraintVsCOMChangeTest.cpp
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) // SPDX-FileCopyrightText: 2023 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <TestFramework.h> #include <Tests/Constraints/ConstraintVsCOMChangeTest.h> #include <Jolt/Physics/Collision/Shape/MutableCompoundShape.h> #include <Jolt/Physics/Collision/Shape/BoxShape.h> #include <Jolt/Physics/Collision/GroupFilterTable.h> #include <Jolt/Physics/Constraints/HingeConstraint.h> #include <Jolt/Physics/Body/BodyCreationSettings.h> #include <Layers.h> JPH_IMPLEMENT_RTTI_VIRTUAL(ConstraintVsCOMChangeTest) { JPH_ADD_BASE_CLASS(ConstraintVsCOMChangeTest, Test) } void ConstraintVsCOMChangeTest::Initialize() { constexpr int cChainLength = 15; constexpr float cMinAngle = DegreesToRadians(-10.0f); constexpr float cMaxAngle = DegreesToRadians(20.0f); // Floor CreateFloor(); // Create box shape mBox = new BoxShape(Vec3::sReplicate(0.5f * cBoxSize)); // Build a collision group filter that disables collision between adjacent bodies Ref<GroupFilterTable> group_filter = new GroupFilterTable(cChainLength); for (CollisionGroup::SubGroupID i = 0; i < cChainLength - 1; ++i) group_filter->DisableCollision(i, i + 1); // Create chain of bodies RVec3 position(0, 25, 0); for (int i = 0; i < cChainLength; ++i) { position += Vec3(cBoxSize, 0, 0); Quat rotation = Quat::sIdentity(); // Create compound shape specific for this body MutableCompoundShapeSettings compound_shape; compound_shape.SetEmbedded(); compound_shape.AddShape(Vec3::sZero(), Quat::sIdentity(), mBox); // Create body Body& segment = *mBodyInterface->CreateBody(BodyCreationSettings(&compound_shape, position, rotation, i == 0 ? EMotionType::Static : EMotionType::Dynamic, i == 0 ? Layers::NON_MOVING : Layers::MOVING)); segment.SetCollisionGroup(CollisionGroup(group_filter, 0, CollisionGroup::SubGroupID(i))); mBodyInterface->AddBody(segment.GetID(), EActivation::Activate); if (i > 0) { // Create hinge HingeConstraintSettings settings; settings.mPoint1 = settings.mPoint2 = position + Vec3(-0.5f * cBoxSize, -0.5f * cBoxSize, 0); settings.mHingeAxis1 = settings.mHingeAxis2 = Vec3::sAxisZ(); settings.mNormalAxis1 = settings.mNormalAxis2 = Vec3::sAxisX(); settings.mLimitsMin = cMinAngle; settings.mLimitsMax = cMaxAngle; Constraint* constraint = settings.Create(*mBodies.back(), segment); mPhysicsSystem->AddConstraint(constraint); mConstraints.push_back(constraint); } mBodies.push_back(&segment); } } void ConstraintVsCOMChangeTest::PrePhysicsUpdate(const PreUpdateParams& inParams) { // Increment time mTime += inParams.mDeltaTime; UpdateShapes(); } void ConstraintVsCOMChangeTest::SaveState(StateRecorder &inStream) const { inStream.Write(mTime); } void ConstraintVsCOMChangeTest::RestoreState(StateRecorder &inStream) { inStream.Read(mTime); UpdateShapes(); } void ConstraintVsCOMChangeTest::UpdateShapes() { // Check if we need to change the configuration int num_shapes = int(mTime) & 1? 2 : 1; if (mNumShapes != num_shapes) { mNumShapes = num_shapes; // Change the COM of the bodies for (int i = 1; i < (int)mBodies.size(); i += 2) { Body *b = mBodies[i]; MutableCompoundShape *s = static_cast<MutableCompoundShape *>(const_cast<Shape *>(b->GetShape())); // Remember the center of mass before the change Vec3 prev_com = s->GetCenterOfMass(); // First remove all existing shapes for (int j = s->GetNumSubShapes() - 1; j >= 0; --j) s->RemoveShape(j); // Then create the desired number of shapes for (int j = 0; j < num_shapes; ++j) s->AddShape(Vec3(0, 0, (1.0f + cBoxSize) * j), Quat::sIdentity(), mBox); // Update the center of mass to account for the new box configuration s->AdjustCenterOfMass(); // Notify the physics system that the shape has changed mBodyInterface->NotifyShapeChanged(b->GetID(), prev_com, true, EActivation::Activate); // Notify the constraints that the shape has changed (this could be done more efficient as we know which constraints are affected) Vec3 delta_com = s->GetCenterOfMass() - prev_com; for (Constraint *c : mConstraints) c->NotifyShapeChanged(b->GetID(), delta_com); } } }
412
0.976416
1
0.976416
game-dev
MEDIA
0.815599
game-dev
0.891294
1
0.891294
Dreaming381/lsss-wip
2,450
Packages/com.latios.latiosframework/PsyshockPhysics/Physics/Internal/Queries/InternalQueryTypes.cs
using System.Diagnostics; using Unity.Mathematics; namespace Latios.Psyshock { internal struct PointDistanceResultInternal { public float3 hitpoint; public float distance; // Negative if inside the collider public float3 normal; public ushort featureCode; } public struct ColliderDistanceResultInternal { public float3 hitpointA; public float3 hitpointB; public float3 normalA; public float3 normalB; public float distance; internal ushort featureCodeA; internal ushort featureCodeB; } internal struct SupportPoint { public float3 pos; public uint id; public int idA => (int)(id >> 16); public int idB => (int)(id & 0xffff); } internal static class InternalQueryTypeUtilities { public static ColliderDistanceResult BinAResultToWorld(in ColliderDistanceResultInternal bInAResult, in RigidTransform aTransform) { return new ColliderDistanceResult { hitpointA = math.transform(aTransform, bInAResult.hitpointA), hitpointB = math.transform(aTransform, bInAResult.hitpointB), normalA = math.rotate(aTransform, bInAResult.normalA), normalB = math.rotate(aTransform, bInAResult.normalB), distance = bInAResult.distance, subColliderIndexA = 0, subColliderIndexB = 0, featureCodeA = bInAResult.featureCodeA, featureCodeB = bInAResult.featureCodeB }; } public static int GetSubcolliders(in Collider collider) { switch(collider.type) { case ColliderType.TriMesh: return collider.m_triMesh().triMeshColliderBlob.Value.triangles.Length; case ColliderType.Compound: return collider.m_compound().compoundColliderBlob.Value.blobColliders.Length; default: return 1; } } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal static void CheckMprResolved(bool somethingWentWrong) { if (somethingWentWrong) UnityEngine.Debug.LogWarning("MPR failed to resolve within the allotted number of iterations. If you see this, please report a bug."); } } }
412
0.791528
1
0.791528
game-dev
MEDIA
0.648381
game-dev
0.93195
1
0.93195
cmangos/mangos-classic
3,384
src/game/Entities/Corpse.h
/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MANGOSSERVER_CORPSE_H #define MANGOSSERVER_CORPSE_H #include "Common.h" #include "Entities/Object.h" #include "Database/DatabaseEnv.h" #include "Maps/GridDefines.h" enum CorpseType { CORPSE_BONES = 0, CORPSE_RESURRECTABLE_PVE = 1, CORPSE_RESURRECTABLE_PVP = 2 }; #define MAX_CORPSE_TYPE 3 // Value equal client resurrection dialog show radius. #define CORPSE_RECLAIM_RADIUS 39 enum CorpseFlags { CORPSE_FLAG_NONE = 0x00, CORPSE_FLAG_BONES = 0x01, CORPSE_FLAG_UNK1 = 0x02, CORPSE_FLAG_UNK2 = 0x04, CORPSE_FLAG_HIDE_HELM = 0x08, CORPSE_FLAG_HIDE_CLOAK = 0x10, CORPSE_FLAG_LOOTABLE = 0x20 }; class Corpse : public WorldObject { public: explicit Corpse(CorpseType type = CORPSE_BONES); ~Corpse(); void AddToWorld() override; void RemoveFromWorld() override; bool Create(uint32 guidlow); bool Create(uint32 guidlow, Player* owner); void SaveToDB(); bool LoadFromDB(uint32 lowguid, Field* fields); void DeleteBonesFromWorld(); void DeleteFromDB() const; ObjectGuid const& GetOwnerGuid() const override { return GetGuidValue(CORPSE_FIELD_OWNER); } void SetOwnerGuid(ObjectGuid guid) override { SetGuidValue(CORPSE_FIELD_OWNER, guid); } uint8 getRace() const { return GetByteValue(CORPSE_FIELD_BYTES_1, 1); } uint32 getRaceMask() const { return 1 << (getRace() - 1); } uint8 getGender() const { return GetByteValue(CORPSE_FIELD_BYTES_1, 2); } // faction template id uint32 GetFaction() const override; time_t const& GetGhostTime() const { return m_time; } void ResetGhostTime() { m_time = time(nullptr); } CorpseType GetType() const { return m_type; } GridPair const& GetGrid() const { return m_grid; } void SetGrid(GridPair const& grid) { m_grid = grid; } bool isVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const override; Player* lootRecipient; bool lootForBody; GridReference<Corpse>& GetGridRef() { return m_gridRef; } bool IsExpired(time_t t) const; Team GetTeam() const; uint8 GetRankSnapshot() const { return m_rankSnapshot; } private: GridReference<Corpse> m_gridRef; CorpseType m_type; time_t m_time; GridPair m_grid; // gride for corpse position for fast search uint8 m_rankSnapshot; }; #endif
412
0.920401
1
0.920401
game-dev
MEDIA
0.8952
game-dev
0.630952
1
0.630952
FoxMCTeam/TenacityRecode-master
10,767
src/java/dev/tenacity/utils/client/addons/mobends/client/model/entity/ModelBendsPlayerArmor.java
package dev.tenacity.utils.client.addons.mobends.client.model.entity; import dev.tenacity.utils.client.addons.mobends.client.model.ModelBoxBends; import dev.tenacity.utils.client.addons.mobends.client.model.ModelRendererBends; import dev.tenacity.utils.client.addons.mobends.client.model.ModelRendererBends_SeperatedChild; import dev.tenacity.utils.client.addons.mobends.client.renderer.SwordTrail; import dev.tenacity.utils.client.addons.mobends.data.Data_Player; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import org.lwjgl.opengl.GL11; import dev.tenacity.utils.client.addons.mobends.util.SmoothVector3f; public class ModelBendsPlayerArmor extends ModelBiped { public ModelRendererBends bipedRightForeArm; public ModelRendererBends bipedLeftForeArm; public ModelRendererBends bipedRightForeLeg; public ModelRendererBends bipedLeftForeLeg; public ModelRendererBends bipedCloak; public ModelRendererBends bipedEars; public SmoothVector3f renderOffset = new SmoothVector3f(); public SmoothVector3f renderRotation = new SmoothVector3f(); public SmoothVector3f renderItemRotation = new SmoothVector3f(); public SwordTrail swordTrail = new SwordTrail(); public float headRotationX, headRotationY; public float armSwing, armSwingAmount; public ModelBendsPlayerArmor(float p_i46304_1_) { super(p_i46304_1_); this.textureWidth = 64; this.textureHeight = 32; this.bipedEars = new ModelRendererBends(this, 24, 0); this.bipedEars.addBox(-3.0F, -6.0F, -1.0F, 6, 6, 1, p_i46304_1_); this.bipedCloak = new ModelRendererBends(this, 0, 0); this.bipedCloak.setTextureSize(64, 32); this.bipedCloak.addBox(-5.0F, 0.0F, -1.0F, 10, 16, 1, p_i46304_1_); this.bipedHead = new ModelRendererBends(this, 0, 0).setShowChildIfHidden(true); this.bipedHead.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, p_i46304_1_); this.bipedHead.setRotationPoint(0.0F, -12.0F, 0.0F); this.bipedHeadwear = new ModelRendererBends(this, 32, 0); this.bipedHeadwear.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, p_i46304_1_ + 0.5F); this.bipedHeadwear.setRotationPoint(0.0F, 0.0F, 0.0F); this.bipedBody = new ModelRendererBends(this, 16, 16); this.bipedBody.addBox(-4.0F, -12.0F, -2.0F, 8, 12, 4, p_i46304_1_); this.bipedBody.setRotationPoint(0.0F, 12.0F, 0.0F); this.bipedLeftArm = new ModelRendererBends_SeperatedChild(this, 40, 16).setMother((ModelRendererBends) this.bipedBody).setShowChildIfHidden(true); this.bipedLeftArm.addBox(-1.0F, -2.0F, -2.0F, 4, 6, 4, p_i46304_1_); this.bipedLeftArm.setRotationPoint(5.0F, 2.0F - 12.0f, 0.0F); this.bipedLeftArm.mirror = true; this.bipedRightArm = new ModelRendererBends_SeperatedChild(this, 40, 16).setMother((ModelRendererBends) this.bipedBody).setShowChildIfHidden(true); this.bipedRightArm.addBox(-3.0F, -2.0F, -2.0F, 4, 6, 4, p_i46304_1_); this.bipedRightArm.setRotationPoint(-5.0F, 2.0F - 12.0f, 0.0F); ((ModelRendererBends) this.bipedRightArm).offsetBox_Add(-0.01f, 0, -0.01f).resizeBox(4.02f, 6.0f, 4.02f).updateVertices(); ((ModelRendererBends) this.bipedLeftArm).offsetBox_Add(-0.01f, 0, -0.01f).resizeBox(4.02f, 6.0f, 4.02f).updateVertices(); this.bipedLeftForeArm = new ModelRendererBends(this, 40, 16 + 6); this.bipedLeftForeArm.addBox(-1.0F, 0.0F, -4.0F, 4, 6, 4, p_i46304_1_); this.bipedLeftForeArm.setRotationPoint(0.0F, 4.0F, 2.0F); this.bipedLeftForeArm.mirror = true; this.bipedLeftForeArm.getBox().offsetTextureQuad(this.bipedLeftForeArm, ModelBoxBends.BOTTOM, 0, -6.0f); this.bipedRightForeArm = new ModelRendererBends(this, 40, 16 + 6); this.bipedRightForeArm.addBox(-3.0F, 0.0F, -4.0F, 4, 6, 4, p_i46304_1_); this.bipedRightForeArm.setRotationPoint(0.0F, 4.0F, 2.0F); this.bipedRightForeArm.getBox().offsetTextureQuad(this.bipedRightForeArm, ModelBoxBends.BOTTOM, 0, -6.0f); this.bipedRightLeg = new ModelRendererBends(this, 0, 16); this.bipedRightLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, p_i46304_1_); this.bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F); this.bipedLeftLeg = new ModelRendererBends(this, 0, 16); this.bipedLeftLeg.mirror = true; this.bipedLeftLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, p_i46304_1_); this.bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F); this.bipedRightForeLeg = new ModelRendererBends(this, 0, 16 + 6); this.bipedRightForeLeg.addBox(-2.0F, 0.0F, 0.0F, 4, 6, 4, p_i46304_1_); this.bipedRightForeLeg.setRotationPoint(0, 6.0F, -2.0F); this.bipedRightForeLeg.getBox().offsetTextureQuad(this.bipedRightForeLeg, ModelBoxBends.BOTTOM, 0, -6.0f); this.bipedLeftForeLeg = new ModelRendererBends(this, 0, 16 + 6); this.bipedLeftForeLeg.mirror = true; this.bipedLeftForeLeg.addBox(-2.0F, 0.0F, 0.0F, 4, 6, 4, p_i46304_1_); this.bipedLeftForeLeg.setRotationPoint(0, 6.0F, -2.0F); this.bipedLeftForeLeg.getBox().offsetTextureQuad(this.bipedLeftForeLeg, ModelBoxBends.BOTTOM, 0, -6.0f); //this.bipedBody.addChild(this.bipedHead); this.bipedBody.addChild(this.bipedRightArm); this.bipedBody.addChild(this.bipedLeftArm); this.bipedHead.addChild(this.bipedHeadwear); this.bipedRightArm.addChild(this.bipedRightForeArm); this.bipedLeftArm.addChild(this.bipedLeftForeArm); this.bipedRightLeg.addChild(this.bipedRightForeLeg); this.bipedLeftLeg.addChild(this.bipedLeftForeLeg); ((ModelRendererBends_SeperatedChild) this.bipedRightArm).setSeperatedPart(this.bipedRightForeArm); ((ModelRendererBends_SeperatedChild) this.bipedLeftArm).setSeperatedPart(this.bipedLeftForeArm); ((ModelRendererBends) this.bipedRightLeg).offsetBox_Add(-0.01f, 0, -0.01f).resizeBox(4.02f, 6.0f, 4.02f).updateVertices(); ((ModelRendererBends) this.bipedLeftLeg).offsetBox_Add(-0.01f, 0, -0.01f).resizeBox(4.02f, 6.0f, 4.02f).updateVertices(); } public void render(Entity argEntity, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float p_78088_7_) { this.setRotationAngles(p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_, argEntity); GL11.glPushMatrix(); if (this.isChild) { float f6 = 2.0F; GL11.glPushMatrix(); GL11.glScalef(1.5F / f6, 1.5F / f6, 1.5F / f6); GL11.glTranslatef(0.0F, 16.0F * p_78088_7_, 0.0F); this.bipedHead.render(p_78088_7_); GL11.glPopMatrix(); GL11.glPushMatrix(); GL11.glScalef(1.0F / f6, 1.0F / f6, 1.0F / f6); GL11.glTranslatef(0.0F, 24.0F * p_78088_7_, 0.0F); this.bipedBody.render(p_78088_7_); this.bipedRightArm.render(p_78088_7_); this.bipedLeftArm.render(p_78088_7_); this.bipedRightLeg.render(p_78088_7_); this.bipedLeftLeg.render(p_78088_7_); this.bipedHeadwear.render(p_78088_7_); GL11.glPopMatrix(); } else { this.bipedBody.render(p_78088_7_); this.bipedRightLeg.render(p_78088_7_); this.bipedLeftLeg.render(p_78088_7_); GL11.glPushMatrix(); this.bipedBody.postRender(p_78088_7_); this.bipedHead.render(p_78088_7_); GL11.glPopMatrix(); } GL11.glPopMatrix(); } public void setRotationAngles(float argSwingTime, float argSwingAmount, float argArmSway, float argHeadY, float argHeadX, float argNr6, Entity argEntity) { if (Minecraft.getMinecraft().theWorld == null) { return; } if (Minecraft.getMinecraft().theWorld.isRemote) { if (Minecraft.getMinecraft().isGamePaused()) { return; } } Data_Player data = (Data_Player) Data_Player.get(argEntity.getEntityId()); this.armSwing = argSwingTime; this.armSwingAmount = argSwingAmount; this.headRotationX = argHeadX; this.headRotationY = argHeadY; if (Minecraft.getMinecraft().currentScreen != null) { this.headRotationY = 0; } ((ModelRendererBends) this.bipedHead).sync(data.head); ((ModelRendererBends) this.bipedHeadwear).sync(data.headwear); ((ModelRendererBends) this.bipedBody).sync(data.body); ((ModelRendererBends) this.bipedRightArm).sync(data.rightArm); ((ModelRendererBends) this.bipedLeftArm).sync(data.leftArm); ((ModelRendererBends) this.bipedRightLeg).sync(data.rightLeg); ((ModelRendererBends) this.bipedLeftLeg).sync(data.leftLeg); this.bipedRightForeArm.sync(data.rightForeArm); this.bipedLeftForeArm.sync(data.leftForeArm); this.bipedRightForeLeg.sync(data.rightForeLeg); this.bipedLeftForeLeg.sync(data.leftForeLeg); this.renderOffset.set(data.renderOffset); this.renderRotation.set(data.renderRotation); this.renderItemRotation.set(data.renderItemRotation); this.swordTrail = data.swordTrail; } public void postRender(float argScale) { GlStateManager.translate(this.renderOffset.vSmooth.x * argScale, -this.renderOffset.vSmooth.y * argScale, this.renderOffset.vSmooth.z * argScale); GlStateManager.rotate(this.renderRotation.getX(), 1.0f, 0.0f, 0.0f); GlStateManager.rotate(this.renderRotation.getY(), 0.0f, 1.0f, 0.0f); GlStateManager.rotate(this.renderRotation.getZ(), 0.0f, 0.0f, 1.0f); } public void postRenderTranslate(float argScale) { GlStateManager.translate(this.renderOffset.vSmooth.x * argScale, -this.renderOffset.vSmooth.y * argScale, this.renderOffset.vSmooth.z * argScale); } public void postRenderRotate(float argScale) { GlStateManager.rotate(this.renderRotation.getX(), 1.0f, 0.0f, 0.0f); GlStateManager.rotate(this.renderRotation.getY(), 0.0f, 1.0f, 0.0f); GlStateManager.rotate(this.renderRotation.getZ(), 0.0f, 0.0f, 1.0f); } public void updateWithEntityData(AbstractClientPlayer argPlayer) { Data_Player data = (Data_Player) Data_Player.get(argPlayer.getEntityId()); if (data != null) { this.renderOffset.set(data.renderOffset); this.renderRotation.set(data.renderRotation); this.renderItemRotation.set(data.renderItemRotation); } } }
412
0.692852
1
0.692852
game-dev
MEDIA
0.7103
game-dev,graphics-rendering
0.939531
1
0.939531
esmf-org/esmf
32,275
src/Superstructure/State/src/ESMF_StateContainer.F90
! $Id$ ! ! Earth System Modeling Framework ! Copyright (c) 2002-2025, University Corporation for Atmospheric Research, ! Massachusetts Institute of Technology, Geophysical Fluid Dynamics ! Laboratory, University of Michigan, National Centers for Environmental ! Prediction, Los Alamos National Laboratory, Argonne National Laboratory, ! NASA Goddard Space Flight Center. ! Licensed under the University of Illinois-NCSA License. ! !============================================================================== #define ESMF_FILENAME "ESMF_StateContainer.F90" !============================================================================== ! ! ESMF Container Module module ESMF_StateContainerMod ! !============================================================================== ! ! This file contains the StateItem specific overloads to the ESMF_Container API ! !------------------------------------------------------------------------------ ! INCLUDES #include "ESMF.h" !============================================================================== !BOPI ! !MODULE: ESMF_StateContainerMod ! ! Fortran API wrapper of C++ implemenation of Container ! !------------------------------------------------------------------------------ ! !USES: use ESMF_UtilTypesMod ! ESMF utility types use ESMF_InitMacrosMod ! ESMF initializer macros use ESMF_LogErrMod ! ESMF error handling use ESMF_ContainerMod ! ESMF Container use ESMF_StateItemMod ! ESMF State types implicit none !------------------------------------------------------------------------------ ! !PRIVATE TYPES: private !------------------------------------------------------------------------------ ! ! !PUBLIC MEMBER FUNCTIONS: ! - ESMF-internal methods: public ESMF_ContainerAdd public ESMF_ContainerAddReplace public ESMF_ContainerGet public ESMF_ContainerReplace public ESMF_ContainerGarbageGet !EOPI !------------------------------------------------------------------------------ !------------------------------------------------------------------------------ ! The following line turns the CVS identifier string into a printable variable. character(*), parameter, private :: version = & '$Id$' !============================================================================== ! ! INTERFACE BLOCKS ! !============================================================================== ! -------------------------- ESMF-internal method ----------------------------- !BOPI ! !IROUTINE: ESMF_ContainerAdd -- Generic interface ! !INTERFACE: interface ESMF_ContainerAdd ! !PRIVATE MEMBER FUNCTIONS: ! module procedure ESMF_ContainerAddSIL ! !DESCRIPTION: ! Add item to Container. !EOPI end interface ! -------------------------- ESMF-internal method ----------------------------- !BOPI ! !IROUTINE: ESMF_ContainerAddReplace -- Generic interface ! !INTERFACE: interface ESMF_ContainerAddReplace ! !PRIVATE MEMBER FUNCTIONS: ! module procedure ESMF_ContainerAddReplaceSIL ! !DESCRIPTION: ! AddReplace item to/in Container. !EOPI end interface ! -------------------------- ESMF-internal method ----------------------------- !BOPI ! !IROUTINE: ESMF_ContainerGet -- Generic interface ! !INTERFACE: interface ESMF_ContainerGet ! !PRIVATE MEMBER FUNCTIONS: ! module procedure ESMF_ContainerGetSI module procedure ESMF_ContainerGetSIL module procedure ESMF_ContainerGetSILAll ! !DESCRIPTION: ! Query Container. !EOPI end interface ! -------------------------- ESMF-internal method ----------------------------- !BOPI ! !IROUTINE: ESMF_ContainerReplace -- Generic interface ! !INTERFACE: interface ESMF_ContainerReplace ! !PRIVATE MEMBER FUNCTIONS: ! module procedure ESMF_ContainerReplaceSIL ! !DESCRIPTION: ! Replace item in Container. !EOPI end interface ! -------------------------- ESMF-internal method ----------------------------- !BOPI ! !IROUTINE: ESMF_ContainerGarbageGet -- Generic interface ! !INTERFACE: interface ESMF_ContainerGarbageGet ! !PRIVATE MEMBER FUNCTIONS: ! module procedure ESMF_ContainerGarbageGetSIL ! !DESCRIPTION: ! Query Container for garbage. !EOPI end interface !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contains !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerAddSIL()" !BOPI ! !IROUTINE: ESMF_ContainerAdd - Add StateItems to Container object ! !INTERFACE: ! Private name; call using ESMF_ContainerAdd() subroutine ESMF_ContainerAddSIL(container, itemList, keywordEnforcer, & multiflag, relaxedflag, rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(inout) :: container type(ESMF_StateItemWrap), intent(in) :: itemList(:) type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below logical, intent(in), optional :: multiflag logical, intent(in), optional :: relaxedflag integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Add elements to an {\tt ESMF\_Container} object. ! ! This method defines garbage as those elements in {\tt itemList} that ! cannot be added to the container because an element with the same name ! already exists in the container. Garbage can only be generated in relaxed ! mode. ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be added to. ! \item[itemList] ! Items to be added. ! \item [{[multiflag]}] ! A setting of {\tt .true.} allows multiple items with the same name ! to be added to {\tt container}. For {\tt .false.}, added items must ! have unique names. The default setting is {\tt .false.}. ! \item [{[relaxedflag]}] ! A setting of {\tt .true.} indicates a relaxed definition of "add" ! under {\tt multiflag=.false.} mode, where it is {\em not} an error if ! {\tt itemList} contains items with names that are also found in ! {\tt container}. The {\tt container} is left unchanged for these items. ! For {\tt .false.} this is treated as an error condition. ! The default setting is {\tt .false.}. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code type(ESMF_Logical) :: multiflagArg type(ESMF_Logical) :: relaxedflagArg integer :: i character(len=ESMF_MAXSTR) :: name type(ESMF_StateItemWrap) :: siw ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) if (present(multiflag)) then multiflagArg = multiflag else multiflagArg = ESMF_FALSE endif if (present(relaxedflag)) then relaxedflagArg = relaxedflag else relaxedflagArg = ESMF_FALSE endif do i=1, size(itemList) ! Get the name of the item call ESMF_StateItemGet(itemList(i)%si, name=name, rc=localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return ! Call into the C++ interface layer siw = itemList(i) ! makes object passing robust call c_ESMC_ContainerAdd(container, trim(name), siw, & multiflagArg, relaxedflagArg, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return enddo ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerAddSIL !------------------------------------------------------------------------------ ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerAddReplaceSIL()" !BOPI ! !IROUTINE: ESMF_ContainerAddReplace - Conditionally add or replace StateItems in Container object ! !INTERFACE: ! Private name; call using ESMF_ContainerAddReplace() subroutine ESMF_ContainerAddReplaceSIL(container, itemList, keywordEnforcer, & rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(inout) :: container type(ESMF_StateItemWrap), intent(in) :: itemList(:) type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Elements in {\tt itemList} that do not match any items by name in ! {\tt container} are added to the Container. Elements in {\tt itemList} ! that match by name items in {\tt container} replaced those items. ! ! This method defines garbage as those elements in {\tt container} that ! were replaced as a consequence of this operation. ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be added to. ! \item[itemList] ! Elements to be added or used to replace items with. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code integer :: i character(len=ESMF_MAXSTR) :: name type(ESMF_StateItemWrap) :: siw ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) do i=1, size(itemList) ! Get the name of the StateItems call ESMF_StateItemGet(itemList(i)%si, name=name, rc=localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return ! Call into the C++ interface layer siw = itemList(i) ! makes object passing robust call c_ESMC_ContainerAddReplace(container, trim(name), siw, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return enddo ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerAddReplaceSIL !------------------------------------------------------------------------------ ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerGetSI()" !BOPI ! !IROUTINE: ESMF_ContainerGet - Query scalar information about a specific itemName ! !INTERFACE: ! Private name; call using ESMF_ContainerGet() subroutine ESMF_ContainerGetSI(container, itemName, item, keywordEnforcer, & itemCount, isPresent, rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(in) :: container character(len=*), intent(in) :: itemName type(ESMF_StateItemWrap), intent(out) :: item type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below integer, intent(out), optional :: itemCount logical, intent(out), optional :: isPresent integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Get items from a {\tt ESMF\_Container} object. ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be queried. ! \item[itemName] ! The name of the specified item. ! \item[item] ! Returned item. ! \item [{[itemCount]}] ! Number of items with {\tt itemName} in {\tt container}. ! \item [{[isPresent]}] ! Upon return indicates whether item with {\tt itemName} is contained in ! {\tt container}. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code type(ESMF_Logical) :: dummyIsPresent ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) ! Call into the C++ interface call c_ESMC_ContainerGetSI(container, trim(itemName), item, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return if (present(itemCount)) then ! Call into the C++ interface call c_ESMC_ContainerGetCount(container, trim(itemName), itemCount, & localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return endif if (present(isPresent)) then ! Call into the C++ interface call c_ESMC_ContainerGetIsPresent(container, trim(itemName), & dummyIsPresent, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return isPresent = dummyIsPresent endif ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerGetSI !------------------------------------------------------------------------------ ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerGetSIL()" !BOPI ! !IROUTINE: ESMF_ContainerGet - Access a list of items matching itemName ! !INTERFACE: ! Private name; call using ESMF_ContainerGet() subroutine ESMF_ContainerGetSIL(container, itemName, itemList, & keywordEnforcer, itemorderflag, rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(in) :: container character(len=*), intent(in) :: itemName type(ESMF_StateItemWrap), pointer :: itemList(:) type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below type(ESMF_ItemOrder_Flag), intent(in), optional :: itemorderflag integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Get items from a {\tt ESMF\_Container} object. ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be queried. ! \item[itemName] ! The name of the specified item. ! \item[{[itemList]}] ! List of items in {\tt container} that match {\tt itemName}. ! This argument has the pointer attribute. ! If the argument comes into this call associated the memory ! allocation is not changed. Instead the size of the memory allocation is ! checked against the total number of elements in the container, and if ! sufficiently sized the container elements are returned in the provided ! memory allocation. If the argument comes into this call unassociated, ! memory will be allocated internally and filled with the container ! elements. In the latter case the size of the returned {\tt itemList} ! will be identical to the number of items in the container that matches ! {\tt itemName} - even if that number is zero. ! In both cases the returned {\tt itemList} will be associated. It is the ! responsibility of the caller to deallocate the memory. ! \item[{[itemorderflag]}] ! Specifies the order of the returned container items in the {\tt itemList}. ! The default is {\tt ESMF\_ITEMORDER\_ABC}. ! See \ref{const:itemorderflag} for a full list of options. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code integer :: stat integer :: i, itemC type(ESMF_Pointer) :: vector type(ESMF_StateItemWrap) :: siw type(ESMF_ItemOrder_Flag) :: itemorderflagArg ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) ! Deal with optional itemorderflag argument itemorderflagArg = ESMF_ITEMORDER_ABC ! default if (present(itemorderflag)) & itemorderflagArg = itemorderflag ! Call into the C++ interface call c_ESMC_ContainerGetCount(container, trim(itemName), itemC, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return if (associated(itemList)) then if (size(itemList) < itemC) then call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE, & msg="itemList is too small", & ESMF_CONTEXT, rcToReturn=rc) return ! bail out endif else allocate(itemList(itemC), stat=stat) if (ESMF_LogFoundAllocError(stat, msg= "allocating itemList", & ESMF_CONTEXT, rcToReturn=rc)) return ! bail out endif ! Call into the C++ interface to set up the vector on the C++ side call c_ESMC_ContainerGetVector(container, trim(itemName), vector, & itemorderflagArg, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return do i=0, itemC-1 ! C-style indexing, zero-based ! Call into the C++ interface to get item from vector call c_ESMC_ContainerGetVSI(container, vector, i, siw, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return itemList(i+1) = siw ! makes object passing robust enddo ! release vector here ! Call into the C++ interface to release the vector on the C++ side call c_ESMC_ContainerReleaseVector(container, vector, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerGetSIL !------------------------------------------------------------------------------ ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerGetSILAll()" !BOPI ! !IROUTINE: ESMF_ContainerGet - Query Container object ! !INTERFACE: ! Private name; call using ESMF_ContainerGet() subroutine ESMF_ContainerGetSILAll(container, itemList, keywordEnforcer, & itemorderflag, itemCount, rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(in) :: container type(ESMF_StateItemWrap), pointer :: itemList(:) type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below type(ESMF_ItemOrder_Flag), intent(in), optional :: itemorderflag integer, intent(out), optional :: itemCount integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Get items from a {\tt ESMF\_Container} object. ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be queried. ! \item[itemList] ! List of items in {\tt container}. This argument has the pointer ! attribute. If the argument comes into this call associated the memory ! allocation is not changed. Instead the size of the memory allocation is ! checked against the total number of elements in the container, and if ! sufficiently sized the container elements are returned in the provided ! memory allocation. If the argument comes into this call unassociated, ! memory will be allocated internally and filled with the container ! elements. In the latter case the size of the returned {\tt itemList} ! will be identical to the number of items in the container - even if that ! number is zero. ! In both cases the returned {\tt itemList} will be associated. It is the ! responsibility of the caller to deallocate the memory. ! \item[{[itemorderflag]}] ! Specifies the order of the returned container items in the {\tt itemList}. ! The default is {\tt ESMF\_ITEMORDER\_ABC}. ! See \ref{const:itemorderflag} for a full list of options. ! \item[{[itemCount]}] ! Number of items {\tt container}. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code integer :: stat integer :: i, itemC type(ESMF_Pointer) :: vector type(ESMF_StateItemWrap) :: siw type(ESMF_ItemOrder_Flag) :: itemorderflagArg ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) ! Deal with optional itemorderflag argument itemorderflagArg = ESMF_ITEMORDER_ABC ! default if (present(itemorderflag)) & itemorderflagArg = itemorderflag ! Call into the C++ interface call c_ESMC_ContainerGetCountAll(container, itemC, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return if (associated(itemList)) then if (size(itemList) < itemC) then call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE, & msg="itemList is too small", & ESMF_CONTEXT, rcToReturn=rc) return ! bail out endif else allocate(itemList(itemC), stat=stat) if (ESMF_LogFoundAllocError(stat, msg= "allocating itemList", & ESMF_CONTEXT, rcToReturn=rc)) return ! bail out endif ! Call into the C++ interface to set up the vector on the C++ side call c_ESMC_ContainerGetVectorAll(container, vector, itemorderflagArg, & localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return do i=0, itemC-1 ! C-style indexing, zero-based ! Call into the C++ interface to get item from vector call c_ESMC_ContainerGetVSI(container, vector, i, siw, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return itemList(i+1) = siw ! makes object passing robust enddo ! release vector here ! Call into the C++ interface to release the vector on the C++ side call c_ESMC_ContainerReleaseVector(container, vector, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return if (present(itemCount)) then itemCount = itemC endif ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerGetSILAll !------------------------------------------------------------------------------ ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerReplaceSIL()" !BOPI ! !IROUTINE: ESMF_ContainerReplace - Replace StateItems in Container object ! !INTERFACE: ! Private name; call using ESMF_ContainerReplace() subroutine ESMF_ContainerReplaceSIL(container, itemList, keywordEnforcer, & multiflag, relaxedflag, rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(inout) :: container type(ESMF_StateItemWrap), intent(in) :: itemList(:) type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below logical, intent(in), optional :: multiflag logical, intent(in), optional :: relaxedflag integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Replace items in an {\tt ESMF\_Container} object. ! ! This method defines garbage as those elements in {\tt container} that ! were replaced as a consequence of this operation {\em and} elements in ! {\tt itemList} that were not used for replacement (in relaxed mode). ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be added to. ! \item[itemList] ! Elements used to replace container items. ! \item [{[multiflag]}] ! A setting of {\tt .true.} allows multiple items with the same name ! to be replaced in {\tt container}. For {\tt .false.}, items to be replaced ! must have unique names. The default setting is {\tt .false.}. ! \item [{[relaxedflag]}] ! A setting of {\tt .true.} indicates a relaxed definition of "replace" ! where it is {\em not} an error if {\tt itemList} contains items with ! names that are not found in {\tt container}. These items in ! {\tt itemList} are ignored in the relaxed mode. For {\tt .false.} this ! is treated as an error condition. ! Further, in {\tt multiflag=.false.} mode, the relaxed definition of ! "replace" also covers the case where there are multiple items in ! {\tt container} that match a single entry by name in {\tt itemList}. ! For {\tt relaxedflag=.false.} this is treated as an error condition. ! The default setting is {\tt .false.}. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code type(ESMF_Logical) :: multiflagArg type(ESMF_Logical) :: relaxedflagArg integer :: i character(len=ESMF_MAXSTR) :: name type(ESMF_StateItemWrap) :: siw ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) if (present(multiflag)) then multiflagArg = multiflag else multiflagArg = ESMF_FALSE endif if (present(relaxedflag)) then relaxedflagArg = relaxedflag else relaxedflagArg = ESMF_FALSE endif do i=1, size(itemList) ! Get the name of the StateItem call ESMF_StateItemGet(itemList(i)%si, name=name, rc=localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return ! Call into the C++ interface layer siw = itemList(i) ! makes object passing robust call c_ESMC_ContainerReplace(container, trim(name), siw, & multiflagArg, relaxedflagArg, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return enddo ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerReplaceSIL !------------------------------------------------------------------------------ ! -------------------------- ESMF-internal method ----------------------------- #undef ESMF_METHOD #define ESMF_METHOD "ESMF_ContainerGarbageGetSIL()" !BOPI ! !IROUTINE: ESMF_ContainerGarbageGet - Query Container object about StateItem garbage ! !INTERFACE: ! Private name; call using ESMF_ContainerGarbageGet() subroutine ESMF_ContainerGarbageGetSIL(container, garbageList, & keywordEnforcer, garbageCount, rc) ! ! !ARGUMENTS: type(ESMF_Container), intent(in) :: container type(ESMF_StateItemWrap), pointer :: garbageList(:) type(ESMF_KeywordEnforcer), optional:: keywordEnforcer ! must use keywords below integer, intent(out), optional :: garbageCount integer, intent(out), optional :: rc ! ! !DESCRIPTION: ! Get items from a {\tt ESMF\_Container} object. ! ! The arguments are: ! \begin{description} ! \item[container] ! {\tt ESMF\_Container} object to be queried. ! \item[garbageList] ! List of objects in {\tt container} garbage. This argument has the pointer ! attribute. If the argument comes into this call associated the memory ! allocation is not changed. Instead the size of the memory allocation is ! checked against the total number of elements in the container gargbage, ! and if sufficiently sized the container garbage elements are returned in ! the provided memory allocation. If the argument comes into this call ! unassociated, memory will be allocated internally and filled with the ! container garbage elements. In the latter case the size of the returned ! {\tt garbageList} will be identical to the number of items in the ! container garbage - even if that number is zero. ! In both cases the returned {\tt garbageList} will be associated. It is the ! responsibility of the caller to deallocate the memory. ! \item[{[garbageCount]}] ! Number of objects in {\tt container} garbage. ! \item[{[rc]}] ! Return code; equals {\tt ESMF\_SUCCESS} if there are no errors. ! \end{description} ! !EOPI !------------------------------------------------------------------------------ integer :: localrc ! local return code integer :: stat integer :: i, garbageC type(ESMF_Pointer) :: vector type(ESMF_StateItemWrap) :: siw ! Initialize return code; assume failure until success is certain localrc = ESMF_RC_NOT_IMPL if (present(rc)) rc = ESMF_RC_NOT_IMPL ! Check init status of arguments ESMF_INIT_CHECK_DEEP_SHORT(ESMF_ContainerGetInit, container, rc) ! Call into the C++ interface call c_ESMC_ContainerGarbageCount(container, garbageC, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return if (associated(garbageList)) then if (size(garbageList) < garbageC) then call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE, & msg="garbageList is too small", & ESMF_CONTEXT, rcToReturn=rc) return ! bail out endif else allocate(garbageList(garbageC), stat=stat) if (ESMF_LogFoundAllocError(stat, msg= "allocating garbageList", & ESMF_CONTEXT, rcToReturn=rc)) return ! bail out endif ! Call into the C++ interface to set up the vector on the C++ side call c_ESMC_ContainerGarbageGet(container, vector, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return do i=0, garbageC-1 ! C-style indexing, zero-based ! Call into the C++ interface to get item from vector call c_ESMC_ContainerGetVSI(container, vector, i, siw, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return garbageList(i+1) = siw ! makes object passing robust enddo ! release vector here ! Call into the C++ interface to release the vector on the C++ side call c_ESMC_ContainerReleaseVector(container, vector, localrc) if (ESMF_LogFoundError(localrc, ESMF_ERR_PASSTHRU, & ESMF_CONTEXT, rcToReturn=rc)) return if (present(garbageCount)) then garbageCount = garbageC endif ! Return successfully if (present(rc)) rc = ESMF_SUCCESS end subroutine ESMF_ContainerGarbageGetSIL !------------------------------------------------------------------------------ end module ESMF_StateContainerMod
412
0.943935
1
0.943935
game-dev
MEDIA
0.494441
game-dev
0.821014
1
0.821014
EpicSentry/P2ASW
1,744
src/game/shared/physics_saverestore.h
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef PHYSICS_SAVERESTORE_H #define PHYSICS_SAVERESTORE_H #if defined( _WIN32 ) #pragma once #endif #include "vphysics_interface.h" class ISaveRestoreBlockHandler; class IPhysicsObject; class CPhysCollide; //----------------------------------------------------------------------------- ISaveRestoreBlockHandler *GetPhysSaveRestoreBlockHandler(); ISaveRestoreOps *GetPhysObjSaveRestoreOps( PhysInterfaceId_t ); //------------------------------------- #define DEFINE_PHYSPTR(name) \ { FIELD_CUSTOM, #name, offsetof(classNameTypedef,name), 1, FTYPEDESC_SAVE, NULL, GetPhysObjSaveRestoreOps( GetPhysIID( &(((classNameTypedef *)0)->name) ) ), NULL } #define DEFINE_PHYSPTR_ARRAY(name) \ { FIELD_CUSTOM, #name, offsetof(classNameTypedef,name), ARRAYSIZE(((classNameTypedef *)0)->name), FTYPEDESC_SAVE, NULL, GetPhysObjSaveRestoreOps( GetPhysIID( &(((classNameTypedef *)0)->name[0]) ) ), NULL } //----------------------------------------------------------------------------- abstract_class IPhysSaveRestoreManager { public: virtual void NoteBBox( const Vector &mins, const Vector &maxs, CPhysCollide * ) = 0; virtual void AssociateModel( IPhysicsObject *, int modelIndex ) = 0; virtual void AssociateModel( IPhysicsObject *, const CPhysCollide *pModel ) = 0; virtual void ForgetModel( IPhysicsObject * ) = 0; virtual void ForgetAllModels() = 0; }; extern IPhysSaveRestoreManager *g_pPhysSaveRestoreManager; //============================================================================= #endif // PHYSICS_SAVERESTORE_H
412
0.964017
1
0.964017
game-dev
MEDIA
0.870849
game-dev
0.674994
1
0.674994
opticks-org/opticks
31,424
Code/application/PlugIns/src/Aspam/AspamImporter.cpp
/* * The information in this file is * Copyright(c) 2020 Ball Aerospace & Technologies Corporation * and is subject to the terms and conditions of the * GNU Lesser General Public License Version 2.1 * The license text is available from * http://www.gnu.org/licenses/lgpl.html */ #include "Any.h" #include "AppVersion.h" #include "Aspam.h" #include "AspamImporter.h" #include "AspamManager.h" #include "AppVerify.h" #include "DataDescriptor.h" #include "FileDescriptor.h" #include "FileResource.h" #include "ImportDescriptor.h" #include "MessageLogResource.h" #include "ModelServices.h" #include "ObjectResource.h" #include "PlugInArg.h" #include "PlugInArgList.h" #include "PlugInManagerServices.h" #include "PlugInRegistration.h" #include "Progress.h" #include "UInt64.h" #include <sstream> using namespace std; REGISTER_PLUGIN_BASIC(OpticksAspam, AspamImporter); /****** * Parsing helper functions ******/ namespace { inline bool checkForToken(stringstream& sstr, string token, bool unget = false) { streampos sstrPosition(sstr.tellg()); bool result(true); stringstream tokenStream(token); while (!tokenStream.eof()) { string a; string b; sstr >> a; tokenStream >> b; if (a != b) { result = false; break; } } if (unget && !result) { sstr.seekg(sstrPosition, ios_base::beg); } return result; } inline bool checkForString(stringstream& sstr, string str, bool unget = false) { streampos sstrPosition(sstr.tellg()); bool result(true); for (unsigned int p = 0; p < str.size(); p++) { char c; sstr >> c; if (c != str[p]) { result = false; break; } } if (unget && !result) { sstr.seekg(sstrPosition, ios_base::beg); } return result; } template <class T> inline void readNumOrNoData(stringstream& sstr, T& val) { streampos sstrPosition(sstr.tellg()); string buf; sstr >> buf; if (buf.empty() || buf[0] != '*') { sstr.seekg(sstrPosition, ios_base::beg); sstr >> val; } else if (buf[0] == '*') { for (unsigned int i = 0; i < buf.size(); i++) { if (buf[i] != '*') { sstr.seekg(static_cast<streamoff>(sstrPosition) + i + 1, ios_base::beg); break; } } } } template <class T> inline void readFixedLength(stringstream& sstr, T& val, unsigned int length) { string buf(length + 1, ' '); sstr.get(const_cast<char*>(buf.c_str()), length + 1); stringstream bufs(buf); bufs >> val; } inline const char* findParagraphStart(const char* pStart, const char* pParagraphStart) { string buf(pStart); string::size_type pos = buf.find(pParagraphStart); if (pos == string::npos) { return NULL; } return pStart + pos; } }; AspamImporter::AspamImporter() : mpAspam(NULL) { setName("ASPAM Importer"); setCreator("Ball Aerospace & Technologies Corp."); setCopyright(APP_COPYRIGHT); setVersion(APP_VERSION_NUMBER); setExtensions("ASPAM Files (*.wxdata *.WXDATA)"); setDescription("Import Atmospheric Slant Path Analysis Model (ASPAM) data files."); setSubtype("ASPAM"); setDescriptorId("{F0CDDAEF-7300-4882-A6AB-B4ACC3EC88CA}"); allowMultipleInstances(true); setProductionStatus(APP_IS_PRODUCTION_RELEASE); } AspamImporter::~AspamImporter() {} bool AspamImporter::getInputSpecification(PlugInArgList*& pInArgList) { Service<PlugInManagerServices> pPlugInManager; pInArgList = pPlugInManager->getPlugInArgList(); VERIFY(pInArgList != NULL); pInArgList->addArg<Progress>(Executable::ProgressArg(), NULL, Executable::ProgressArgDescription()); Service<ModelServices> pModel; pModel->addElementType("Aspam"); PlugInArg* pArg = NULL; VERIFY((pArg = pPlugInManager->getPlugInArg()) != NULL); pArg->setName(Importer::ImportElementArg()); pArg->setType("Aspam"); pArg->setDefaultValue(NULL); pArg->setDescription("ASPAM file to import."); pInArgList->addArg(*pArg); return true; } bool AspamImporter::getOutputSpecification(PlugInArgList*& pOutArgList) { pOutArgList = NULL; return true; } vector<ImportDescriptor*> AspamImporter::getImportDescriptors(const string& filename) { vector<ImportDescriptor*> descriptors; if (!filename.empty()) { Service<ModelServices> pModel; ImportDescriptor* pImportDescriptor = pModel->createImportDescriptor(filename, "Aspam", NULL); if (pImportDescriptor != NULL) { DataDescriptor* pDescriptor = pImportDescriptor->getDataDescriptor(); if (pDescriptor != NULL) { FactoryResource<FileDescriptor> pFileDescriptor; if (pFileDescriptor.get() != NULL) { pFileDescriptor->setFilename(filename); pDescriptor->setFileDescriptor(pFileDescriptor.get()); } } descriptors.push_back(pImportDescriptor); } } return descriptors; } unsigned char AspamImporter::getFileAffinity(const std::string& filename) { FileResource pFile(filename.c_str(), "rt"); if (pFile.get() == NULL) { return Importer::CAN_NOT_LOAD; } string data(128, '\0'); // 128 should be plenty to locate start of Paragraph A fread(&data[0], sizeof(char), 127, pFile); stringstream sstr(data); if (checkForToken(sstr, "A.", true) && checkForToken(sstr, "SITE")) { return Importer::CAN_LOAD; } return Importer::CAN_NOT_LOAD; } bool AspamImporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList) { Any* pAspamContainer = NULL; Progress* pProgress = NULL; StepResource pStep("Import ASPAM", "app", "82AFD6B1-841C-4B15-9F8D-5431757057E5"); // get input arguments and log some useful info about them { // scope the MessageResource MessageResource pMsg("Input arguments", "app", "69A4FC3B-9FBB-4327-BEAF-03321046EF60"); pProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg()); pMsg->addBooleanProperty("Progress Present", (pProgress != NULL)); pAspamContainer = pInArgList->getPlugInArgValueUnsafe<Any>(Importer::ImportElementArg()); if (pAspamContainer == NULL) { if (pProgress != NULL) { pProgress->updateProgress("No data element", 100, ERRORS); } pStep->finalize(Message::Failure, "No data element"); return false; } pMsg->addProperty("Element name", pAspamContainer->getName()); if (pAspamContainer->getFilename().empty()) { if (pProgress != NULL) { pProgress->updateProgress("No file", 100, ERRORS); } pStep->finalize(Message::Failure, "No file"); return false; } } // initialize the Aspam data mpAspam = NULL; vector<PlugIn*> instances = Service<PlugInManagerServices>()->getPlugInInstances("ASPAM Manager"); AspamManager* pAspamManager = instances.empty() ? NULL : dynamic_cast<AspamManager*>(instances.front()); if (pAspamManager != NULL) { if (pAspamManager->initializeAspam(pAspamContainer)) { mpAspam = dynamic_cast<Aspam*>(pAspamContainer->getData()); } } if (mpAspam == NULL) { string message = "Unable to initialize the ASPAM."; if (pProgress != NULL) { pProgress->updateProgress(message, 0, ERRORS); } pStep->finalize(Message::Failure, message); return false; } if (pProgress != NULL) { pProgress->updateProgress("Open ASPAM file", 20, NORMAL); } FileResource pFile(pAspamContainer->getFilename().c_str(), "rt"); if (pFile.get() == NULL) { string msg = "Unable to open file."; if (pProgress != NULL) { pProgress->updateProgress(msg, 100, ERRORS); } pStep->finalize(Message::Failure, msg); return false; } if (pProgress != NULL) { pProgress->updateProgress("Parse ASPAM file", 40, NORMAL); } bool rval = deserialize(pFile.get()); // ensure at least one paragraph loads. rval = rval && (mpAspam->getParagraphA().mLoaded || mpAspam->getParagraphB().mLoaded || mpAspam->getParagraphC().mLoaded || mpAspam->getParagraphD().mLoaded || mpAspam->getParagraphE().mLoaded || mpAspam->getParagraphF().mLoaded || mpAspam->getParagraphG().mLoaded || mpAspam->getParagraphH().mLoaded || mpAspam->getParagraphI().mLoaded || mpAspam->getParagraphJ().mLoaded || mpAspam->getParagraphK().mLoaded); if (!rval) { string msg = "Unable to parse ASPAM file"; if (pProgress != NULL) { pProgress->updateProgress(msg, 100, ERRORS); } pStep->finalize(Message::Failure, msg); return false; } if (pProgress != NULL) { pProgress->updateProgress("Finished importing ASPAM", 100, NORMAL); } pStep->finalize(Message::Success); return true; } const char* AspamImporter::parseParagraphA(const char* pStart) { Aspam::ParagraphA paragraphA; MessageResource pMsg("Paragraph A", "app", "0090303F-B432-49E2-B7CC-18B6DD428B13"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, "A."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } // BEGIN PARSING stringstream sstr(pStart); if (checkForToken(sstr, "A.", true) && (checkForToken(sstr, "SITE -", true) || checkForToken(sstr, "SITE"))) { success = true; sstr >> paragraphA.mSiteId.mX; // some weather files have a 5 digit value after SITE but it is not a lat/long if ((paragraphA.mSiteId.mX > 180) || (paragraphA.mSiteId.mX < -180)) { paragraphA.mSiteId.mX = 0.0; sstr >> paragraphA.mSiteId.mX >> paragraphA.mSiteId.mY; } else { sstr >> paragraphA.mSiteId.mY; } } paragraphA.mLoaded = success; mpAspam->setParagraphA(paragraphA); const char* pStop = pStart + static_cast<int>(sstr.tellg()); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } const char* AspamImporter::parseParagraphB(const char* pStart) { Aspam::ParagraphB paragraphB; MessageResource pMsg("Paragraph B", "app", "2C87848E-C3BC-4D11-821A-DE7C3354A870"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, "B."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } // BEGIN PARSING stringstream sstr(pStart); if (checkForToken(sstr, "B.", true) && (checkForToken(sstr, "TIME -", true) || checkForToken(sstr, "TIME"))) { int ztime; char cbuf; sstr >> ztime >> cbuf; if (cbuf == 'Z') { unsigned short minute = static_cast<unsigned short>(ztime % 100); unsigned short hour = static_cast<unsigned short>(ztime / 100); unsigned short day = 0; unsigned short month = 0; unsigned short year = 0; string monthBuf; sstr >> day >> monthBuf >> year; if (monthBuf == "JAN") { month = 1; } else if (monthBuf == "FEB") { month = 2; } else if (monthBuf == "MAR") { month = 3; } else if (monthBuf == "APR") { month = 4; } else if (monthBuf == "MAY") { month = 5; } else if (monthBuf == "JUN") { month = 6; } else if (monthBuf == "JUL") { month = 7; } else if (monthBuf == "AUG") { month = 8; } else if (monthBuf == "SEP") { month = 9; } else if (monthBuf == "OCT") { month = 10; } else if (monthBuf == "NOV") { month = 11; } else if (monthBuf == "DEC") { month = 12; } else { month = 0; } if (year < 100) // this is a 2 digit year { year += 1900; } success = paragraphB.mpDateTime->set(year, month, day, hour, minute, 0); } } paragraphB.mLoaded = success; mpAspam->setParagraphB(paragraphB); const char* pStop = pStart + static_cast<int>(sstr.tellg()); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } const char* AspamImporter::parseParagraphD(const char* pStart) { Aspam::ParagraphD paragraphD; MessageResource pMsg("Paragraph D", "app", "D1A66370-096E-43A8-B4B5-B2C165405821"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, "D."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } // BEGIN PARSING stringstream sstr(pStart); if (checkForToken(sstr, "D.", true) && (checkForToken(sstr, "WEATHER AT SITE -", true)) || checkForToken(sstr, "WEATHER AT SITE")) { if (checkForToken(sstr, "VSBY")) { // some files only have visibility in D, thus set success to true here sstr >> paragraphD.mSurfaceVisibility >> paragraphD.mUnits; success = true; for (int layerNum = 0; layerNum < 4; layerNum++) { Aspam::CloudLayer layer; sstr >> layer.mCoverage; checkForToken(sstr, "/8"); sstr >> layer.mType; readNumOrNoData(sstr, layer.mBaseAltitude); checkForString(sstr, "/"); // code to replace the problem that readNumOrNoData had with commas string buf; sstr >> buf; if (buf == "") { layer.mTopAltitude = 0; } else { layer.mTopAltitude = atoi( buf.c_str() ); } paragraphD.mCloudLayers.push_back(layer); // The standard says there is a space between layers but some // files seem to have comma and space so we read in a character // to throw away any invalid character. sstr.get(); } } if ((checkForToken(sstr, "TOTAL CLOUD COVERAGE IS", true)) || (checkForToken(sstr, "TOTAL CLOUD COVERAGE"))) { sstr >> paragraphD.mTotalCoverage; checkForToken(sstr, "/8"); checkForToken(sstr, "WIND"); unsigned int windValue(0); readNumOrNoData(sstr, windValue); paragraphD.mWindSpeed = windValue % 1000; paragraphD.mWindDirection = windValue / 1000; checkForString(sstr, "G"); readNumOrNoData(sstr, paragraphD.mGustSpeed); getline(sstr, paragraphD.mRemark); } } paragraphD.mLoaded = success; mpAspam->setParagraphD(paragraphD); const char* pStop = pStart + static_cast<int>(sstr.tellg()); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } const char* AspamImporter::parseParagraphF(const char* pStart, bool isReallyI) { Aspam::ParagraphF paragraphF; MessageResource pMsg("Paragraph F", "app", "293B5D84-CE8D-4891-8E3E-DC7B67F11878"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, isReallyI ? "I." : "F."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } const char* pStop = pStart; // BEGIN PARSING stringstream sstr(pStart); if (checkForToken(sstr, isReallyI ? "I." : "F.", true) && (checkForToken(sstr, "WINDS, TEMPERATURE, ABS HUMIDITY, DENSITY, PRESSURE -", true) || checkForToken(sstr, "WINDS, TEMPERATURE, ABS HUMIDITY. DENSITY, PRESSURE -", true) || checkForToken(sstr, "WINDS, TEMPERATURE, ABS HUMIDITY, DENSITY, PRESSURE"))) { checkForToken(sstr, "-", true); if (checkForToken(sstr, "HEIGHT", true)) { // The spec does not say anything about the existance of this // line but all the "official" examples have this so we assume // it exists...if not, we probably have a Paragraph F declaration // with no data in it. string buf; getline(sstr, buf); if (checkForToken(sstr, "F", true) || checkForToken(sstr, "M", true)) { //need to check for MSL as well as AGL sstr >> paragraphF.mLevel; getline(sstr, buf); } for ( ; ; ) // this will break which done reading { Aspam::Analytic data; if (checkForToken(sstr, "SFC", true)) { data.mHeight = 0; } else if (checkForToken(sstr, "0M", true)) { data.mHeight = 0; data.mUnits = 'M'; } else if (checkForToken(sstr, "0H", true)) { data.mHeight = 0; data.mUnits = 'H'; } else { int sstrPosition = static_cast<int>(sstr.tellg()); sstr >> data.mHeight >> data.mUnits; // height will be zero if (data.mHeight == 0) { // we've reached the end of the data pStop += sstrPosition; break; } } readNumOrNoData(sstr, data.mWindDirection); readNumOrNoData(sstr, data.mWindSpeed); readNumOrNoData(sstr, data.mTemperature); readNumOrNoData(sstr, data.mHumidity); readNumOrNoData(sstr, data.mDensity); readNumOrNoData(sstr, data.mPressure); paragraphF.mAnalytic.push_back(data); } success = true; } } paragraphF.mLoaded = success; mpAspam->setParagraphF(paragraphF); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } const char* AspamImporter::parseParagraphG(const char* pStart) { Aspam::ParagraphG paragraphG; MessageResource pMsg("Paragraph G", "app", "6A05FA26-9F59-4693-B3CD-29B2EBD680EC"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, "G."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } // BEGIN PARSING stringstream sstr(pStart); if (checkForToken(sstr, "G.", true) && checkForToken(sstr, "REMARKS -")) { paragraphG.mRemarks.erase(); while (!sstr.eof()) { string buf; getline(sstr, buf); if (buf.size() == 0) { success = true; break; } paragraphG.mRemarks += buf + "\n"; } } paragraphG.mLoaded = success; mpAspam->setParagraphG(paragraphG); const char* pStop = pStart + static_cast<int>(sstr.tellg()); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } const char* AspamImporter::parseParagraphH(const char* pStart) { Aspam::ParagraphH paragraphH; MessageResource pMsg("Paragraph H", "app", "542EC588-12B5-4925-996A-9AC36549BFC6"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, "H."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } // BEGIN PARSING stringstream sstr(pStart); bool foundH = (checkForToken(sstr, "H.", true) && checkForToken(sstr, "AEROSOL PARAMETERS", true)); if (foundH) { streampos sstrPosition(sstr.tellg()); char dummy; const char pCheckString[] = "TARGETVERTICALPROFILEINFORMATION"; for (size_t i = 0; foundH && i < strlen(pCheckString); i++) { sstr >> dummy; foundH = (dummy == pCheckString[i]); } if (!foundH) { sstr.seekg(sstrPosition, ios_base::beg); } } if (foundH) { if (sstr.get() != ' ') // get the space { sstr.unget(); } readFixedLength(sstr, paragraphH.mLevels, 2); readFixedLength(sstr, paragraphH.mPrimaryBoundaryLayerAerosolParameter, 1); if (paragraphH.mPrimaryBoundaryLayerAerosolParameter == 3) { readFixedLength(sstr, paragraphH.mAirParcelType, 2); } else { if (sstr.get() != ' ') // get the space { sstr.unget(); } if (sstr.get() != ' ') // get the space { sstr.unget(); } } readFixedLength(sstr, paragraphH.mSeasonalDependence, 1); readFixedLength(sstr, paragraphH.mStratosphericAerosol, 1); readFixedLength(sstr, paragraphH.mSurfaceVisibility, 2); readFixedLength(sstr, paragraphH.mOzoneProfile, 1); readFixedLength(sstr, paragraphH.mBoundaryLayerParameterQualityIndex, 2); readFixedLength(sstr, paragraphH.mAlternateSurfaceVisibility, 2); readFixedLength(sstr, paragraphH.mAlternateBoundaryLayerAerosolParameter, 1); if (paragraphH.mAlternateBoundaryLayerAerosolParameter == 3) { readFixedLength(sstr, paragraphH.mAlternateAirParcelType, 2); } int stage; // 0 - searching for data, 1 - parsing data, 2 - finished parsing data for (stage = 0; sstr.good() && stage != 2; ) { string line; getline(sstr, line); if (stage == 0 && line.size() >= 30) { stage = 1; } if (stage == 1) { if (line.size() < 30) { stage = 2; } else { stringstream lineStr(line); Aspam::Aerosol aerosol; // eat a space if it exists if (lineStr.get() != ' ') { lineStr.unget(); } // read a fixed length field...this must be a fixed length // read as this may butt against the next column without // a space. I don't currently know the length of the other // fields (the standard is ambiguous) so they remain numeric // reads until we have more information readFixedLength(lineStr, aerosol.mHeight, 5); lineStr >> aerosol.mPressure >> aerosol.mTemperature >> aerosol.mWaterVaporDensity >> aerosol.mAlternateTemperature >> aerosol.mAlternateWaterVaporDensity; long location; lineStr >> location; aerosol.mLatitude = location / 100000; aerosol.mLongtitude = abs(location % 100000); lineStr >> aerosol.mOzoneRatio; paragraphH.mAerosol.push_back(aerosol); } } } success = (stage == 2); } paragraphH.mLoaded = success; mpAspam->setParagraphH(paragraphH); const char* pStop = pStart + static_cast<int>(sstr.tellg()); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } const char* AspamImporter::parseParagraphJ(const char* pStart) { Aspam::ParagraphJ paragraphJ; MessageResource pMsg("Paragraph J", "app", "F7569E21-BA50-48A2-86BD-B603F3CC43E0"); bool success = false; const char* pParagraphStart = findParagraphStart(pStart, "J."); if (pParagraphStart != NULL) { pStart = pParagraphStart; } // BEGIN PARSING stringstream sstr(pStart); if (checkForToken(sstr, "J.", true) && checkForToken(sstr, "SURFACE WEATHER HISTORY", true) && checkForToken(sstr, "24 HOUR SURFACE WEATHER HISTORY", true)) { int stage; // 0 - searching for wx data, 1 - parsing wx data, 2 - finished parsing data for (stage = 0; sstr.good() && stage != 2; ) { string line; getline(sstr, line); if (stage == 0 && line.size() >= 60) { stage = 1; } if (stage == 1) { if (line.size() < 60) { stage = 2; } else { stringstream lineStr(line); Aspam::SurfaceWeather wx; readFixedLength(lineStr, wx.mYear, 2); readFixedLength(lineStr, wx.mJulianDay, 3); readFixedLength(lineStr, wx.mHour, 2); readFixedLength(lineStr, wx.mMinutes, 2); readFixedLength(lineStr, wx.mCloudBase1, 3); readFixedLength(lineStr, wx.mCloudCoverage1, 2); readFixedLength(lineStr, wx.mCloudThickness1, 2); if (wx.mCloudBase1 == 999) { wx.mCloudBase1 = 0; wx.mCloudCoverage1 = 0; wx.mCloudThickness1 = 0; } readFixedLength(lineStr, wx.mCloudBase2, 3); readFixedLength(lineStr, wx.mCloudCoverage2, 2); readFixedLength(lineStr, wx.mCloudThickness2, 2); if (wx.mCloudBase2 == 999) { wx.mCloudBase2 = 0; wx.mCloudCoverage2 = 0; wx.mCloudThickness2 = 0; } readFixedLength(lineStr, wx.mCloudBase3, 3); readFixedLength(lineStr, wx.mCloudCoverage3, 2); readFixedLength(lineStr, wx.mCloudThickness3, 2); if (wx.mCloudBase3 == 999) { wx.mCloudBase3 = 0; wx.mCloudCoverage3 = 0; wx.mCloudThickness3 = 0; } readFixedLength(lineStr, wx.mCloudBase4, 3); readFixedLength(lineStr, wx.mCloudCoverage4, 2); readFixedLength(lineStr, wx.mCloudThickness4, 2); if (wx.mCloudBase4 == 999) { wx.mCloudBase4 = 0; wx.mCloudCoverage4 = 0; wx.mCloudThickness4 = 0; } readFixedLength(lineStr, wx.mTotalCoverage, 2); readFixedLength(lineStr, wx.mVisibility, 2); readFixedLength(lineStr, wx.mPrecipitationType, 2); if (wx.mPrecipitationType == "99") { wx.mPrecipitationType = ""; } readFixedLength(lineStr, wx.mObscuration, 1); if (wx.mObscuration == "9") { wx.mObscuration = ""; } lineStr.get(); // skip space readFixedLength(lineStr, wx.mPressure, 4); lineStr.get(); // skip space readFixedLength(lineStr, wx.mTemperature, 3); lineStr.get(); // skip space readFixedLength(lineStr, wx.mDewpoint, 3); readFixedLength(lineStr, wx.mWindDirection, 2); readFixedLength(lineStr, wx.mWindSpeed, 3); readFixedLength(lineStr, wx.mAlternateWindSpeed, 3); paragraphJ.mSurfaceWeather.push_back(wx); } } if (stage == 2) { stringstream lineStr(line); lineStr >> paragraphJ.mMaxTemperature >> paragraphJ.mMinTemperature >> paragraphJ.mSnowDepth; } } success = (stage == 2); } paragraphJ.mLoaded = success; mpAspam->setParagraphJ(paragraphJ); const char* pStop = pStart + static_cast<int>(sstr.tellg()); // END PARSING if (success) { pMsg->addProperty("Result", "Success"); } else if (pStop != pStart) { pMsg->addProperty("Result", "Failed to parse"); } else { pMsg->addProperty("Result", "Not present"); } string remaining(pStop, pStop + 10); pMsg->addProperty("Remaining data", remaining); pMsg->finalize(); return pStop; } bool AspamImporter::deserialize(FILE* pFp) { string data = ""; { // scope the resource MessageResource pLoadMsg("Load data from file", "app", "AC28F536-5970-4FD0-AD70-C949BCF63B43"); while (!feof(pFp)) { string buf(1024, ' '); unsigned int numberRead = fread(const_cast<char*>(buf.c_str()), sizeof(char), 1024, pFp); data += buf.substr(0, numberRead); } pLoadMsg->addProperty("Length", UInt64(data.size())); pLoadMsg->finalize(); } MessageResource pParseMsg("Parse ASPAM data", "app", "ED0C895C-9E01-4FD0-A82F-177CCB14430C"); const char* pParseLocation = data.c_str(); pParseLocation = parseParagraphA(pParseLocation); pParseLocation = parseParagraphB(pParseLocation); pParseLocation = parseParagraphD(pParseLocation); pParseLocation = parseParagraphF(pParseLocation); pParseLocation = parseParagraphG(pParseLocation); pParseLocation = parseParagraphH(pParseLocation); if (!mpAspam->getParagraphF().mLoaded) { // attempt to load paragraph I // I and F are identical and should be mutually exclusive // if for some reason both are present, F takes pecedent pParseLocation = parseParagraphF(pParseLocation, true); } pParseLocation = parseParagraphJ(pParseLocation); // Skip any remaining whitespace while (pParseLocation != NULL && *pParseLocation != NULL && (*pParseLocation == ' ' || *pParseLocation == '\t' || *pParseLocation == '\n' || *pParseLocation == '\r')) { pParseLocation++; } if (*pParseLocation != NULL) { string remaining(pParseLocation, pParseLocation + 10); pParseMsg->addProperty("Remaining Data", remaining); } return true; }
412
0.978535
1
0.978535
game-dev
MEDIA
0.240949
game-dev
0.985677
1
0.985677
Alex-Rachel/GameplayTags
4,581
Editor/GameplayTagContainerTreeView.cs
using System; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace GameplayTags.Editor { public class GameplayTagContainerTreeView : GameplayTagTreeViewBase { private static GUIContent s_TempContent = new(); private SerializedProperty m_ExplicitTagsProperty; public GameplayTagContainerTreeView(TreeViewState treeViewState, SerializedProperty explicitTagsProperty) : base(treeViewState) { m_ExplicitTagsProperty = explicitTagsProperty; m_ExplicitTagsProperty.serializedObject.Update(); ExpandIncludedTagItems(); UpdateIncludedTags(); } protected override void OnToolbarGUI() { if (ToolbarButton("Clear All")) { m_ExplicitTagsProperty.arraySize = 0; m_ExplicitTagsProperty.serializedObject.ApplyModifiedProperties(); UpdateIncludedTags(); } } protected override void RowGUI(RowGUIArgs args) { float indent = GetContentIndent(args.item); Rect rect = args.rowRect; rect.xMin += indent - (hasSearch ? 14 : 0); GameplayTagTreeViewItem item = args.item as GameplayTagTreeViewItem; using (new EditorGUI.DisabledGroupScope(item.IsIncluded && !item.IsExplicitIncluded)) { s_TempContent.text = hasSearch ? item.Tag.Name : args.label; s_TempContent.tooltip = item.Tag.Description; EditorGUI.BeginChangeCheck(); bool added = EditorGUI.ToggleLeft(rect, s_TempContent, item.IsIncluded); if (EditorGUI.EndChangeCheck()) { if (added) { m_ExplicitTagsProperty.InsertArrayElementAtIndex(0); SerializedProperty element = m_ExplicitTagsProperty.GetArrayElementAtIndex(0); element.stringValue = item.Tag.Name; } else { for (int i = 0; i < m_ExplicitTagsProperty.arraySize; i++) { SerializedProperty element = m_ExplicitTagsProperty.GetArrayElementAtIndex(i); if (string.Equals(element.stringValue, item.Tag.Name, StringComparison.OrdinalIgnoreCase)) { m_ExplicitTagsProperty.DeleteArrayElementAtIndex(i); break; } } } m_ExplicitTagsProperty.serializedObject.ApplyModifiedProperties(); m_ExplicitTagsProperty.serializedObject.Update(); UpdateIncludedTags(); } } } private unsafe void UpdateIncludedTags() { foreach (TreeViewItem row in GetRows()) { if (row is GameplayTagTreeViewItem item) { item.IsExplicitIncluded = false; item.IsIncluded = false; } } for (int i = 0; i < m_ExplicitTagsProperty.arraySize; i++) { SerializedProperty element = m_ExplicitTagsProperty.GetArrayElementAtIndex(i); GameplayTag tag = GameplayTagManager.RequestTag(element.stringValue); GameplayTagTreeViewItem item = FindItem(tag.RuntimeIndex); if (item == null) { Debug.Log(element.stringValue); continue; } item.IsExplicitIncluded = true; item.IsIncluded = true; foreach (GameplayTag parentTag in tag.ParentTags) { GameplayTagTreeViewItem parentItem = FindItem(parentTag.RuntimeIndex); if (parentItem == null) continue; parentItem.IsIncluded = true; } } } private unsafe void ExpandIncludedTagItems() { for (int i = 0; i < m_ExplicitTagsProperty.arraySize; i++) { SerializedProperty element = m_ExplicitTagsProperty.GetArrayElementAtIndex(i); GameplayTag tag = GameplayTagManager.RequestTag(element.stringValue); GameplayTagTreeViewItem item = FindItem(tag.RuntimeIndex); if (item == null) continue; foreach (GameplayTag parentTag in tag.ParentTags) { GameplayTagTreeViewItem parentItem = FindItem(parentTag.RuntimeIndex); if (parentItem == null) continue; SetExpanded(parentItem.id, true); } } } } }
412
0.912509
1
0.912509
game-dev
MEDIA
0.926472
game-dev
0.92103
1
0.92103
randomguy3725/MoonLight
4,522
src/main/java/net/minecraft/client/renderer/tileentity/TileEntityPistonRenderer.java
package net.minecraft.client.renderer.tileentity; import net.minecraft.block.Block; import net.minecraft.block.BlockPistonBase; import net.minecraft.block.BlockPistonExtension; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockRendererDispatcher; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntityPiston; import net.minecraft.util.BlockPos; import net.minecraft.world.World; public class TileEntityPistonRenderer extends TileEntitySpecialRenderer<TileEntityPiston> { private final BlockRendererDispatcher blockRenderer = Minecraft.getMinecraft().getBlockRendererDispatcher(); public void renderTileEntityAt(TileEntityPiston te, double x, double y, double z, float partialTicks, int destroyStage) { BlockPos blockpos = te.getPos(); IBlockState iblockstate = te.getPistonState(); Block block = iblockstate.getBlock(); if (block.getMaterial() != Material.air && te.getProgress(partialTicks) < 1.0F) { Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); this.bindTexture(TextureMap.locationBlocksTexture); RenderHelper.disableStandardItemLighting(); GlStateManager.blendFunc(770, 771); GlStateManager.enableBlend(); GlStateManager.disableCull(); if (Minecraft.isAmbientOcclusionEnabled()) { GlStateManager.shadeModel(7425); } else { GlStateManager.shadeModel(7424); } worldrenderer.begin(7, DefaultVertexFormats.BLOCK); worldrenderer.setTranslation((float)x - (float)blockpos.getX() + te.getOffsetX(partialTicks), (float)y - (float)blockpos.getY() + te.getOffsetY(partialTicks), (float)z - (float)blockpos.getZ() + te.getOffsetZ(partialTicks)); World world = this.getWorld(); if (block == Blocks.piston_head && te.getProgress(partialTicks) < 0.5F) { iblockstate = iblockstate.withProperty(BlockPistonExtension.SHORT, Boolean.TRUE); this.blockRenderer.getBlockModelRenderer().renderModel(world, this.blockRenderer.getModelFromBlockState(iblockstate, world, blockpos), iblockstate, blockpos, worldrenderer, true); } else if (te.shouldPistonHeadBeRendered() && !te.isExtending()) { BlockPistonExtension.EnumPistonType blockpistonextension$enumpistontype = block == Blocks.sticky_piston ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT; IBlockState iblockstate1 = Blocks.piston_head.getDefaultState().withProperty(BlockPistonExtension.TYPE, blockpistonextension$enumpistontype).withProperty(BlockPistonExtension.FACING, iblockstate.getValue(BlockPistonBase.FACING)); iblockstate1 = iblockstate1.withProperty(BlockPistonExtension.SHORT, te.getProgress(partialTicks) >= 0.5F); this.blockRenderer.getBlockModelRenderer().renderModel(world, this.blockRenderer.getModelFromBlockState(iblockstate1, world, blockpos), iblockstate1, blockpos, worldrenderer, true); worldrenderer.setTranslation((float)x - (float)blockpos.getX(), (float)y - (float)blockpos.getY(), (float)z - (float)blockpos.getZ()); iblockstate.withProperty(BlockPistonBase.EXTENDED, Boolean.TRUE); this.blockRenderer.getBlockModelRenderer().renderModel(world, this.blockRenderer.getModelFromBlockState(iblockstate, world, blockpos), iblockstate, blockpos, worldrenderer, true); } else { this.blockRenderer.getBlockModelRenderer().renderModel(world, this.blockRenderer.getModelFromBlockState(iblockstate, world, blockpos), iblockstate, blockpos, worldrenderer, false); } worldrenderer.setTranslation(0.0D, 0.0D, 0.0D); tessellator.draw(); RenderHelper.enableStandardItemLighting(); } } }
412
0.899874
1
0.899874
game-dev
MEDIA
0.971013
game-dev
0.959899
1
0.959899
dufernst/LegionCore-7.3.5
62,403
src/server/scripts/Legion/TrialOfValor/boss_tov_helya.cpp
#include "trial_of_valor.h" #include "AreaTriggerAI.h" #include "PrecompiledHeaders/ScriptPCH.h" enum Says { SAY_INTRO_1 = 11, SAY_INTRO_2, SAY_INTRO_3, SAY_AGGRO, SAY_BILEWATER_BREATH, SAY_PHASE_2 = 6, SAY_PHASE_3, SAY_ORB_OF_CORROSION, SAY_CORRUPTED_BREATH, SAY_DEATH }; enum Spells { SpellHelyaBluePower = 232229, SpellHelyaPurplePower = 232230, SpellBerserk = 64238, SpellBilewaterBreath = 227967, SpellBilewaterBreathDmg = 230229, SpellBilewaterBreathNpc = 230216, SpellBilewaterLiquefactionDmg = 227992, SpellBilewaterLiquefactionKill = 227993, SpellBilewaterRedox = 227982, SpellRemoveDebuffs = 34098, SpellHelyaImmunityDamage = 228847, SpellHelyaAltPower = 228372, SpellHelyaReuse = 200239, SpellCorruptedBreath = 228565, SpellCorruptedBreathDmg = 228566, SpellReanimation1 = 228104, SpellReanimation2 = 234199, SpellHelyaVisualTentacles = 228772, SpellHelyaVisualTentacles1 = 228778, SpellRideVehicleHardcoded = 46598, SpellFuryoftheMaw = 228032, SpellFuryOfTheMawAT = 230356, SpellFureOfTheMawLong = 228300, SpellRagingTempest = 201119, SpellHelyaAltPowerRegen = 228546, SpellTaintOfTheSea = 228054, SpellTaintOfTheSeaDmg = 228053, SpellOrbOfCorruption = 227903, SpellOrbOfCorruptionSpawnAura = 227906, SpellOrbOfCorruptionVisual = 227939, SpellOrbOfCorruptionDmg = 227930, SpellOrbOfCorruptionAuraProc = 227926, SpellOrbofCorruptionOnPlayer = 229119, SpellOrbOfCorrosion = 228056, SpellOrbOfCorrosionSpawnAura = 228057, SpellOrbOfCorrosionVisual = 228060, SpellOrbOfCorrosionAuraProc = 228061, SpellOrbofCorrosionOnPlayer = 230267, SpellOrbOfCorrosionShare = 228062, SpellOrbOfCorrosionDmg = 228063, SpellBilewaterLiquefaction = 227990, SpellBilewaterLiquefactionScale = 228984, SpellSlimey = 154241, SpellCorrosiveNova = 228872, SpellTorrent = 228514, SpellBuildingStorm = 228803, SpellAnchorSlam = 228519, SpellSludgeNova = 228390, SpellFetidRotHit = 228397, SpellFetidRot = 193367, SpellTaintedEssence = 228052, SpellGiveNoQuarter = 228632, SpellLanternOfDarkness = 228619, SpellDarkness = 228383, SpellGhostlyRage = 228611, SpellRallyOfTheKvaldir = 232346, SpellDecay = 228121, SpellVigor = 203816, SpellRabid = 202476, SpellTentacleSlam = 228731, SpellDarkHatred = 232488, SpellCorruptedAxion = 232418, SpellCorruptedAxionAOE = 232452, SpellCorruptedAxionAura = 232450, SpellCorrupted = 232350, SpellBleakEruption = 231862, SpellMistInfusion = 228854, SpellTentacleStrike = 228730 }; enum Events { EVENT_TAINT_OF_THE_SEA = 1, EVENT_TENTECLE_STRIKE = 2, EVENT_ORB_OF_CURRUPTION = 3, EVENT_TORRENT = 4, EVENT_TELEPORT_OUTSIDE = 5, EVENT_TELEPORT_HOME = 6, EVENT_ORB_OF_CORROSION = 7, EVENT_FURY_OF_THE_MAW = 8, EVENT_FURY_OF_THE_MAW_CLEAN_AT = 9, EVENT_REANIMATION = 10, EVENT_SUMMON_SKELETION = 11, EVENT_BOAT = 12 }; enum Phase { PHASE_1 = 1, PHASE_2, PHASE_3 }; Position const Pos_AncientBonethrall[3] = { { 542.715f, 614.908f, 6.76841f, 2.33339f }, { 539.062f, 640.273f, 3.53224f, 2.64075f }, { 537.57f, 629.615f, 6.64555f, 3.21549f } }; Position const Pos_DarkSeraph[4] = { { 454.929f, 595.392f, 4.5516f, 4.69926f }, { 433.75f, 673.292f, 11.1958f, 5.168f }, { 453.01f, 676.46f, 16.4407f, 4.31975f }, { 564.712f, 671.016f, 22.047f, 4.89319f } }; Position const Pos_KvaldirTideWitch[5] = { { 438.646f, 669.132f, 7.11206f, 4.94863f }, { 446.311f, 669.043f, 7.02397f, 4.97584f }, { 466.095f, 698.087f, 18.0504f, 4.31252f }, { 564.804f, 664.471f, 18.0398f, 3.0071f }, { 462.96f, 707.84f, 18.048f, 2.79169f } }; Position const Pos_KvaldirReefcaller[8] = { { 554.536f, 659.163f, 18.04f, 3.40563f }, { 497.158f, 649.146f, 1.93921f, 1.00977f }, { 502.023f, 640.695f, 1.92648f, 1.16326f }, { 490.314f, 647.658f, 1.95429f, 0.897942f }, { 500.812f, 646.582f, 1.92656f, 1.08693f }, { 484.189f, 647.012f, 2.10088f, 0.805534f }, { 575.047f, 653.731f, 18.0399f, 3.20372f }, { 503.719f, 634.96f, 1.9753f, 1.21486f } }; Position const Pos_DeepbrineMonstrosity[4] = { { 465.504f, 641.476f, 5.21661f, 0.582881f }, { 523.799f, 662.377f, 2.27014f, 3.65067f }, { 500.641f, 674.398f, 2.22507f, 4.62842f }, { 471.521f, 708.076f, 18.0694f, 0.768197f } }; Position const StrikingTentacle[3] = { //{ 466.0955f, 698.0868f, 18.05038f, 4.312522f }, //{ 564.8038f, 664.4705f, 18.03976f, 3.007097f }, { 525.5886f, 678.2604f, 2.877361f, 4.050999f }, { 505.826f, 693.526f, 2.877363f, 4.66783f }, { 475.3333f, 606.6406f, 2.891779f, 0.9923878f } }; Position const skeletionPos[10] = { { 529.276f, 702.028f, -2.0632f, 4.31416f }, { 539.448f, 699.825f, -2.43245f, 4.31416f }, { 522.04f, 709.505f, -2.51397f, 4.31416f }, { 503.182f, 583.628f, -0.529175f, 1.36772f }, { 491.255f, 586.115f, -0.529175f, 1.4199f }, { 515.188f, 580.21f, -0.529175f, 1.33011f }, { 482.042f, 590.741f, -0.529178f, 1.5545f }, { 528.059f, 583.365f, -0.529168f, 1.75563f }, { 517.481f, 719.132f, -3.38609f, 4.31416f }, { 549.359f, 698.911f, -3.12035f, 4.31416f } }; struct boss_helya_tov : BossAI { explicit boss_helya_tov(Creature* creature) : BossAI(creature, Data::BossIDs::HelyaID) { HelyaIntro = false; Intro(); } uint32 berserk; uint8 trashDiedCount; uint8 trashPhase2Count; uint8 eventPhase; uint32 power; uint32 count; uint32 AOEdmg; uint32 _checkEvadeTimer; bool phase2; bool phase3; bool HelyaIntro; bool checkrephase; bool FuryOfTheMaw; bool FuryOfTheMawTrash; ObjectGuid playerGuid; void Reset() override { _Reset(); me->SetPower(POWER_ENERGY, 0); me->SetMaxPower(POWER_ENERGY, 100); me->RemoveAllAuras(); me->AddUnitState(UNIT_STATE_ROOT); me->SetReactState(REACT_AGGRESSIVE); me->RemoveAllAreaObjects(); DoCast(SpellHelyaBluePower); RemoveAllDebaffsOnPlayer(); playerGuid.Clear(); DespawnAllSummons(); berserk = 0; eventPhase = 0; trashDiedCount = 0; trashPhase2Count = 0; count = 0; AOEdmg = 0; _checkEvadeTimer = 0; phase2 = false; phase3 = false; checkrephase = false; FuryOfTheMawTrash = false; FuryOfTheMaw = false; events.RescheduleEvent(EVENT_REANIMATION, 1000); } void RemoveAllDebaffsOnPlayer() { instance->DoRemoveAurasDueToSpellOnPlayers(SpellCorruptedAxionAura); instance->DoRemoveAurasDueToSpellOnPlayers(SpellCorrupted); instance->DoRemoveAurasDueToSpellOnPlayers(SpellBleakEruption); instance->DoRemoveAurasDueToSpellOnPlayers(SpellBleakEruption); instance->DoRemoveAurasDueToSpellOnPlayers(SpellTaintOfTheSea); instance->DoRemoveAurasDueToSpellOnPlayers(SpellOrbofCorrosionOnPlayer); } void DespawnAllSummons() { std::list<Creature*> list; list.clear(); me->GetCreatureListWithEntryInGrid(list, 114523, 200.0f); me->GetCreatureListWithEntryInGrid(list, 114566, 200.0f); if (!list.empty()) for (auto& sum : list) sum->DespawnOrUnsummon(); } void Intro() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NOT_ATTACKABLE_1); if (instance->GetBossState(Data::BossIDs::HelyaID) != DONE) { for (uint8 i = 0; i < 3; ++i) me->SummonCreature(Data::Creatures::AncientBonethrall, Pos_AncientBonethrall[i]); for (uint8 i = 0; i < 4; ++i) me->SummonCreature(Data::Creatures::DarkSeraph, Pos_DarkSeraph[i]); for (uint8 i = 0; i < 5; ++i) me->SummonCreature(Data::Creatures::KvaldirTideWitch, Pos_KvaldirTideWitch[i]); for (uint8 i = 0; i < 8; ++i) me->SummonCreature(Data::Creatures::KvaldirReefcaller, Pos_KvaldirReefcaller[i]); for (uint8 i = 0; i < 4; ++i) me->SummonCreature(Data::Creatures::DeepbrineMonstrosity, Pos_DeepbrineMonstrosity[i]); me->SummonCreature(Data::Creatures::RotsoulGiant, 567.617f, 656.039f, 18.2112f, 0.967337f); me->SummonCreature(Data::Creatures::KvaldirCoralMaiden, 561.031f, 665.738f, 18.0399f, 5.4091f); } } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); StartEvents(PHASE_1); _checkEvadeTimer = 1500; } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); instance->DoUpdateAchievementCriteria(CRITERIA_TYPE_COMPLETE_DUNGEON_ENCOUNTER, 2008); me->RemoveAllAreaObjects(); RemoveAllDebaffsOnPlayer(); DespawnAllSummons(); _JustDied(); } void EnterEvadeMode() override { Talk(SAY_INTRO_1); me->NearTeleportTo(524.031f, 699.055f, 5.17631f, 4.29875f); BossAI::EnterEvadeMode(); } void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) override { switch (summon->GetEntry()) { case Data::Creatures::DeepbrineMonstrosity: case Data::Creatures::KvaldirReefcaller: case Data::Creatures::KvaldirTideWitch: case Data::Creatures::DarkSeraph: case Data::Creatures::RotsoulGiant: case Data::Creatures::AncientBonethrall: case Data::Creatures::KvaldirCoralMaiden: trashDiedCount++; if (!HelyaIntro) { HelyaIntro = true; DoAction(ACTION_2); } break; case Data::Creatures::GrippingTentacle: trashPhase2Count++; break; } if (trashDiedCount == 26 && eventPhase == 0) { Talk(SAY_INTRO_3); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NOT_ATTACKABLE_1); } if (trashPhase2Count == 9 && eventPhase == PHASE_2) StartEvents(PHASE_3); } void SetPower(Powers power, int32 value) override { if (power == POWER_ENERGY) { if (value == 100 && eventPhase == PHASE_1) { if (!me->HasUnitState(UNIT_STATE_CASTING)) { DoCast(SpellBilewaterBreath); Talk(SAY_BILEWATER_BREATH); me->AddDelayedEvent(500, [=]() -> void { me->SetPower(POWER_ENERGY, 0); }); } } if (value == 100 && eventPhase == PHASE_3) { if (!me->HasUnitState(UNIT_STATE_CASTING)) { DoCast(SpellCorruptedBreath); Talk(SAY_CORRUPTED_BREATH); me->AddDelayedEvent(500, [=]() -> void { me->SetPower(POWER_ENERGY, 0); }); } } } if (power == POWER_ALTERNATE) { if (value == 100) { if (!me->HasUnitState(UNIT_STATE_CASTING)) { if (IsHeroicPlusRaid() && eventPhase == PHASE_2 && !FuryOfTheMaw) { FuryOfTheMaw = true; me->AddDelayedEvent(5000, [=]() -> void { FuryOfTheMawTrash = false; DoCast(SpellFureOfTheMawLong); FuryOfTheMaw = false; me->SetPower(POWER_ALTERNATE, 0); }); } else if (IsLfrRaid() || IsNormalRaid()) { if (eventPhase == PHASE_2) { DoCast(SpellFuryoftheMaw); events.RescheduleEvent(EVENT_FURY_OF_THE_MAW_CLEAN_AT, 4000); me->AddDelayedEvent(500, [=]() -> void { me->SetPower(POWER_ALTERNATE, 0); }); } } if (eventPhase == PHASE_3) { FuryOfTheMawTrash = false; DoCast(SpellFuryoftheMaw); events.RescheduleEvent(EVENT_FURY_OF_THE_MAW_CLEAN_AT, 4000); me->AddDelayedEvent(500, [=]() -> void { me->SetPower(POWER_ALTERNATE, 0); }); } } } } } void StartEvents(uint8 phase) { events.Reset(); eventPhase = phase; switch (phase) { case PHASE_1: Talk(SAY_AGGRO); AOEdmg = 1000; me->SetPower(POWER_ENERGY, 79); if (IsMythicRaid()) { events.RescheduleEvent(EVENT_TAINT_OF_THE_SEA, 15000); events.RescheduleEvent(EVENT_TENTECLE_STRIKE, 35000); events.RescheduleEvent(EVENT_ORB_OF_CURRUPTION, 14000); } else if (IsHeroicRaid()) { events.RescheduleEvent(EVENT_TAINT_OF_THE_SEA, 19000); events.RescheduleEvent(EVENT_TENTECLE_STRIKE, 36000); events.RescheduleEvent(EVENT_ORB_OF_CURRUPTION, 29000); } else if (IsNormalRaid() || IsLfrRaid()) { events.RescheduleEvent(EVENT_TAINT_OF_THE_SEA, 12000); events.RescheduleEvent(EVENT_TENTECLE_STRIKE, 53000); events.RescheduleEvent(EVENT_ORB_OF_CURRUPTION, 18000); } if (IsHeroicPlusRaid()) berserk = 660000; // 11 min break; case PHASE_2: events.RescheduleEvent(EVENT_TELEPORT_OUTSIDE, 1000); checkrephase = true; DoCast(SpellRemoveDebuffs); DoCast(SpellHelyaImmunityDamage); DoCast(SpellHelyaAltPower); DoCast(SpellHelyaReuse); me->CastStop(); me->AttackStop(); me->SetReactState(REACT_PASSIVE); me->SetPower(POWER_ENERGY, 0); me->RemoveAura(SpellHelyaBluePower); me->RemoveAura(SpellCorrosiveNova); me->SummonCreatureGroup(3); me->AddDelayedEvent(5000, [=]() -> void { DoCast(SpellHelyaReuse); Talk(SAY_PHASE_2); events.RescheduleEvent(EVENT_TORRENT, 9000); events.RescheduleEvent(EVENT_REANIMATION, 30000); if (IsLfrRaid() || IsNormalRaid()) { DoCast(SpellHelyaAltPowerRegen); events.RescheduleEvent(EVENT_FURY_OF_THE_MAW, 2000); } else if (IsHeroicPlusRaid()) me->SetPower(POWER_ALTERNATE, 100); }); break; case PHASE_3: events.RescheduleEvent(EVENT_TELEPORT_HOME, 2000); DoCast(SpellHelyaReuse); me->CastStop(); me->RemoveAura(SpellFureOfTheMawLong); me->RemoveAura(SpellHelyaImmunityDamage); me->RemoveAura(SpellHelyaAltPowerRegen); me->RemoveAura(SpellTorrent); me->AddDelayedCombat(5000, [=]() -> void { Talk(SAY_PHASE_3); me->SetPower(POWER_ENERGY, 61); me->SetPower(POWER_ALTERNATE, 42); me->SetReactState(REACT_AGGRESSIVE); me->RemoveAura(SpellBuildingStorm); me->RemoveAura(SpellCorrosiveNova); me->AddDelayedEvent(1500, [=]() -> void { DoCast(SpellHelyaAltPowerRegen); checkrephase = false; }); DoCast(SpellHelyaReuse); DoCast(SpellHelyaPurplePower); events.RescheduleEvent(EVENT_REANIMATION, 52000); if (IsMythicRaid()) events.RescheduleEvent(EVENT_ORB_OF_CORROSION, 6000); else if (IsHeroicRaid()) events.RescheduleEvent(EVENT_ORB_OF_CORROSION, 14000); else if (IsNormalRaid() || IsLfrRaid()) events.RescheduleEvent(EVENT_ORB_OF_CORROSION, 18000); }); break; } } void DamageTaken(Unit* /*attacker*/, uint32& damage, DamageEffectType /*dmgType*/) override { if (!phase2 && me->HealthBelowPct(65)) { phase2 = true; StartEvents(PHASE_2); } } void SpellHit(Unit* owner, SpellInfo const* spell) override { switch (spell->Id) { case SpellBilewaterLiquefactionKill: if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(227992)) { float damage = spellInfo->GetEffect(EFFECT_0, owner->GetSpawnMode())->CalcValue(); float healthPct = owner->GetHealthPct() > 5.0f ? owner->GetHealthPct() : 5.0f; damage = CalculatePct(damage, healthPct); me->CastCustomSpell(owner, SpellBilewaterLiquefactionDmg, &damage, &healthPct, nullptr, true); } break; case SpellOrbOfCorruption: { if (me->GetMap() && (me->GetMap()->GetSpawnMode() == DIFFICULTY_NORMAL_RAID) || (me->GetMap()->GetSpawnMode() == DIFFICULTY_LFR_RAID)) count = 2; else if (me->GetMap() && (me->GetMap()->GetSpawnMode() == DIFFICULTY_MYTHIC_RAID) || (me->GetMap()->GetSpawnMode() == DIFFICULTY_HEROIC_RAID)) count = 3; std::list<Player*> playerList; GetPlayerListInGrid(playerList, me, 300.0f); Trinity::Containers::RandomResizeList(playerList, count); if (playerList.empty()) return; for (auto& player : playerList) { DoCast(player, SpellOrbOfCorruptionVisual, true); playerGuid.Clear(); playerGuid = player->GetGUID(); Position pos; player->GetPosition(&pos); pos.m_positionX -= 6.0f; pos.m_positionY -= 6.0f; me->AddDelayedEvent(2000, [=]() -> void { me->SummonCreature(Data::Creatures::OrbOfCorruption, pos, playerGuid, TEMPSUMMON_TIMED_DESPAWN, 9000); }); } break; } case SpellOrbOfCorrosion: { if (me->GetMap() && (me->GetMap()->GetSpawnMode() == DIFFICULTY_NORMAL_RAID) || (me->GetMap()->GetSpawnMode() == DIFFICULTY_LFR_RAID)) count = 2; else if (me->GetMap() && (me->GetMap()->GetSpawnMode() == DIFFICULTY_MYTHIC_RAID) || (me->GetMap()->GetSpawnMode() == DIFFICULTY_HEROIC_RAID)) count = 3; std::list<Player*> playerList; GetPlayerListInGrid(playerList, me, 300.0f); Trinity::Containers::RandomResizeList(playerList, count); if (playerList.empty()) return; for (auto& player : playerList) { playerGuid.Clear(); playerGuid = player->GetGUID(); DoCast(player, SpellOrbOfCorrosionVisual, true); Position pos; player->GetPosition(&pos); pos.m_positionX -= 6.0f; pos.m_positionY -= 6.0f; me->AddDelayedEvent(2000, [=]() -> void { me->SummonCreature(Data::Creatures::OrbOfCorrosion, pos, playerGuid, TEMPSUMMON_TIMED_DESPAWN, 9000); }); } break; } case SpellBilewaterBreath: { uint8 count = me->GetMap()->GetPlayersCountExceptGMs(); if (count <= 10) count = 2; else if (count <= 15) count = 3; else if (count <= 20) count = 4; else if (count <= 25) count = 5; else count = 6; Position pos; float angle = 0.0f; float dist = 40.0f; for (uint8 i = 0; i < count; ++i) { dist += 11.0f; me->GetFirstCollisionPosition(pos, dist, angle); me->CastSpell(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), SpellBilewaterBreathNpc, true); } break; } case SpellCorruptedBreath: { if (!IsHeroicPlusRaid()) return; uint32 countTarget = 0; if (IsMythicRaid()) countTarget = 5; else countTarget = 3; Position pos; float angle = me->GetAngle(me); float dist = 30.0f; for (uint8 i = 0; i < countTarget; ++i) { dist += 13.0f; me->GetNearPosition(pos, dist, angle); me->CastSpell(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), SpellCorruptedAxion, true); } break; } case SpellOrbOfCorrosionShare: DoCast(owner, SpellOrbOfCorrosionDmg, true); break; } } void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { case SpellBilewaterBreathDmg: DoCast(target, SpellBilewaterRedox, true); break; case SpellCorruptedBreathDmg: DoCast(target, SpellDarkHatred, false); break; } } void SpellFinishCast(SpellInfo const* spell) override { switch (spell->Id) { case SpellFuryOfTheMawAT: if (IsHeroicPlusRaid()) { if (!FuryOfTheMawTrash) { events.RescheduleEvent(EVENT_BOAT, 500); events.RescheduleEvent(EVENT_SUMMON_SKELETION, 31000); events.RescheduleEvent(EVENT_SUMMON_SKELETION, 41000); FuryOfTheMawTrash = true; } events.RescheduleEvent(EVENT_FURY_OF_THE_MAW_CLEAN_AT, 3000); } else if (IsLfrRaid() || IsNormalRaid()) { if (eventPhase == PHASE_3 || eventPhase == PHASE_2) { events.RescheduleEvent(EVENT_BOAT, 500); events.RescheduleEvent(EVENT_SUMMON_SKELETION, 31000); events.RescheduleEvent(EVENT_SUMMON_SKELETION, 41000); } } break; } } void DoAction(int32 const action) override { switch (action) { case ACTION_1: DoCast(SpellHelyaAltPowerRegen); events.RescheduleEvent(EVENT_TORRENT, 2000); break; case ACTION_2: if (instance->GetBossState(Data::BossIDs::GarmID) == DONE) { Talk(SAY_INTRO_1); me->AddDelayedEvent(13000, [=]() -> void { Talk(SAY_INTRO_2); }); } break; default: break; } } void JustSummoned(Creature* sum) override { summons.Summon(sum); switch (sum->GetEntry()) { case Data::Creatures::OrbOfCorruption: if (auto target = ObjectAccessor::GetUnit(*sum, sum->GetTargetGUID())) sum->CastSpell(target, SpellOrbofCorruptionOnPlayer, true); break; case Data::Creatures::OrbOfCorrosion: if (auto target = ObjectAccessor::GetUnit(*sum, sum->GetTargetGUID())) sum->CastSpell(target, SpellOrbofCorrosionOnPlayer, true); break; case Data::Creatures::NightWatchMariner: if (eventPhase == PHASE_3) sum->AddAura(SpellRallyOfTheKvaldir, sum); break; default: break; } } uint32 GetData(uint32 type) const override { if (type == Data::BossIDs::HelyaID) return eventPhase; return 0; } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && me->isInCombat()) return; if (_checkEvadeTimer) { if (_checkEvadeTimer <= diff) { _checkEvadeTimer = 1500; if (auto victim = me->getVictim()) { if (me->GetDistance(victim) > 90.0f && eventPhase != PHASE_2) EnterEvadeMode(); else if (me->GetDistance(victim) > 140.0f && eventPhase == PHASE_2) EnterEvadeMode(); } } else _checkEvadeTimer -= diff; } events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_TAINT_OF_THE_SEA: { if (eventPhase == PHASE_1 || eventPhase == PHASE_3) { auto threatlist = me->getThreatManager().getThreatList(); for (uint8 i = 0; i < (IsMythicRaid() ? 5 : 3); ++i) { if (threatlist.empty()) break; if (auto itr = Trinity::Containers::SelectRandomContainerElement(threatlist)) { if (Unit* target = itr->getTarget()) me->AddAura(SpellTaintOfTheSea, target); threatlist.remove(itr); } } if (IsMythicRaid()) events.RescheduleEvent(EVENT_TAINT_OF_THE_SEA, 12000); else if (IsHeroicRaid()) events.RescheduleEvent(EVENT_TAINT_OF_THE_SEA, 14000); else if (IsNormalRaid() || IsLfrRaid()) events.RescheduleEvent(EVENT_TAINT_OF_THE_SEA, 12000); } break; } case EVENT_TENTECLE_STRIKE: if (eventPhase == PHASE_1) { me->SummonCreature(Data::Creatures::StrikingTentacle, StrikingTentacle[urand(0, 2)], TEMPSUMMON_TIMED_DESPAWN, 9000); if (IsMythicRaid()) events.RescheduleEvent(EVENT_TENTECLE_STRIKE, 35000); else events.RescheduleEvent(EVENT_TENTECLE_STRIKE, 30000); } break; case EVENT_ORB_OF_CURRUPTION: if (eventPhase == PHASE_1) { DoCast(SpellOrbOfCorruption); if (IsMythicRaid()) events.RescheduleEvent(EVENT_ORB_OF_CURRUPTION, 23000); else events.RescheduleEvent(EVENT_ORB_OF_CURRUPTION, 26000); } break; case EVENT_ORB_OF_CORROSION: if (eventPhase == PHASE_3) { Talk(SAY_ORB_OF_CORROSION); DoCast(SpellOrbOfCorrosion); if (IsMythicRaid()) events.RescheduleEvent(EVENT_ORB_OF_CORROSION, 13000); else events.RescheduleEvent(EVENT_ORB_OF_CORROSION, 17000); } break; case EVENT_TORRENT: if (!me->HasUnitState(UNIT_STATE_CASTING)) { if (eventPhase == PHASE_2) { if (!me->HasAura(SpellFureOfTheMawLong)) { power = me->GetPower(POWER_ALTERNATE); if (power <= 95) { DoCast(SpellTorrent); events.RescheduleEvent(EVENT_TORRENT, 10000); } } } } break; case EVENT_TELEPORT_OUTSIDE: me->NearTeleportTo(553.95f, 733.01f, 5.1663f, 4.03013f); break; case EVENT_TELEPORT_HOME: me->NearTeleportTo(524.031f, 699.055f, 5.17631f, 4.29875f); break; case EVENT_FURY_OF_THE_MAW: DoCast(SpellFuryOfTheMawAT); events.RescheduleEvent(EVENT_FURY_OF_THE_MAW_CLEAN_AT, 3000); break; case EVENT_FURY_OF_THE_MAW_CLEAN_AT: me->RemoveAreaObject(SpellBilewaterLiquefactionDmg); me->RemoveAreaObject(SpellDecay); break; case EVENT_REANIMATION: if (eventPhase == 0) { DoCast(SpellReanimation1); DoCast(SpellReanimation2); events.RescheduleEvent(EVENT_REANIMATION, 15000); } break; case EVENT_SUMMON_SKELETION: for (uint8 i = 0; i < 10; ++i) me->SummonCreature(Data::Creatures::DecayingMinion, skeletionPos[i], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); break; case EVENT_BOAT: if (eventPhase == PHASE_2) { me->SummonCreature(Data::Creatures::KvaldirLongboat, 569.39f, 857.6201f, 0.00213f, 4.433769f, TEMPSUMMON_TIMED_DESPAWN, 5000); me->SummonCreature(Data::Creatures::KvaldirLongboat, 638.672f, 817.6201f, 0.00213f, 3.943812f, TEMPSUMMON_TIMED_DESPAWN, 5000); me->AddDelayedCombat(4000, [=]() -> void { me->SummonCreature(Data::Creatures::Grimelord, 458.674f, 639.483f, 7.53757f, 4.433769f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); me->SummonCreature(Data::Creatures::NightWatchMariner, 516.007f, 614.179f, 5.5823f, 3.943812f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); }); if (IsMythicRaid()) { me->SummonCreature(Data::Creatures::HelarjarMistwatcher, 564.366f, 653.4237f, 17.9559f, 2.401197f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); me->SummonCreature(Data::Creatures::HelarjarMistwatcher, 469.7802f, 703.5213f, 17.96658f, 6.12398f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); } } else if (eventPhase == PHASE_3) { me->AddDelayedCombat(4000, [=]() -> void { me->SummonCreature(Data::Creatures::NightWatchMariner, 516.007f, 614.179f, 5.5823f, 3.943812f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000); }); me->SummonCreature(Data::Creatures::KvaldirLongboat, 638.672f, 817.6201f, 0.00213f, 3.943812f, TEMPSUMMON_TIMED_DESPAWN, 5000); } break; } } if (berserk) { if (berserk <= diff) { berserk = 0; DoCast(me, SpellBerserk, true); } else berserk -= diff; } if (AOEdmg) { if (AOEdmg <= diff) { if (eventPhase != PHASE_2) { if (checkrephase) return; if (auto victim = me->getVictim()) if (!me->IsWithinMeleeRange(victim)) DoCast(SpellCorrosiveNova); } } else AOEdmg -= diff; } DoMeleeAttackIfReady(); } }; //232229 class spell_helya_blue_power_regen : public AuraScript { PrepareAuraScript(spell_helya_blue_power_regen); uint8 power{}; std::vector<uint32> energy_initial = { 1, 2, 2, 1, 1, 2, 1, 2, 2, 2, 2, 1, 2 }; std::vector<uint32> energy = { 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 }; uint32 i = 0; bool initial_energy = false; void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (!GetCaster()) return; if (auto helya = GetCaster()->ToCreature()) if (helya->isInCombat() && !initial_energy) initial_energy = true; } void Tick(AuraEffect const* aurEff) { if (auto helya = GetCaster()->ToCreature()) { power = helya->GetPower(POWER_ENERGY); if (!helya->isInCombat()) return; if (power == 0 && helya->HasAura(SpellHelyaBluePower)) initial_energy = false; if (power != 100) { if (initial_energy) helya->SetPower(POWER_ENERGY, power + energy_initial[i]); else helya->SetPower(POWER_ENERGY, power + energy[i]); } } } void Register() override { AfterEffectApply += AuraEffectApplyFn(spell_helya_blue_power_regen::OnApply, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL); OnEffectPeriodic += AuraEffectPeriodicFn(spell_helya_blue_power_regen::Tick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; //232230 class spell_helya_purple_power_regen : public AuraScript { PrepareAuraScript(spell_helya_purple_power_regen); uint8 power{}; void Tick(AuraEffect const* aurEff) { if (auto helya = GetCaster()->ToCreature()) { if (!helya->isInCombat()) return; power = helya->GetPower(POWER_ENERGY); helya->SetPower(POWER_ENERGY, power + 2); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_helya_purple_power_regen::Tick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; //228383 class spell_tov_darkness : public AuraScript { PrepareAuraScript(spell_tov_darkness); uint8 power{}; std::vector<uint32> energyLfr = { 1, 2, 3, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2 }; std::vector<uint32> energy = { 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4}; uint32 i = 0; void Tick(AuraEffect const* aurEff) { if (auto npc = GetCaster()->ToCreature()) { if (!npc->isInCombat()) return; power = npc->GetPower(POWER_ENERGY); if (npc->GetMap() && (npc->GetMap()->GetSpawnMode() == DIFFICULTY_LFR_RAID)) npc->SetPower(POWER_ENERGY, power + energyLfr[i]); else npc->SetPower(POWER_ENERGY, power + energy[i]); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_tov_darkness::Tick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; //228546 class spell_helya_alt_power_regen : public AuraScript { PrepareAuraScript(spell_helya_alt_power_regen); uint8 power{}; uint32 i = 0; uint32 alt_energy[4] = {2, 3, 2, 1}; void Tick(AuraEffect const* aurEff) { if (auto helya = GetCaster()->ToCreature()) { if (!helya->isInCombat()) return; power = helya->GetPower(POWER_ALTERNATE); helya->SetPower(POWER_ALTERNATE, power + alt_energy[urand(0, 3)]); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_helya_alt_power_regen::Tick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; //228053 class spell_taint_of_the_sea : public AuraScript { PrepareAuraScript(spell_taint_of_the_sea); void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if (!target && !target->isInCombat()) return; if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_ENEMY_SPELL) GetCaster()->CastSpell(target, SpellTaintedEssence, true); else target->CastSpell(target, SpellTaintOfTheSeaDmg, true); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_taint_of_the_sea::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE, AURA_EFFECT_HANDLE_REAL); } }; //114523 struct npc_orb_of_corruption : ScriptedAI { explicit npc_orb_of_corruption(Creature* creature) : ScriptedAI(creature) { me->SetReactState(REACT_PASSIVE); instance = me->GetInstanceScript(); } EventMap events; InstanceScript* instance; void IsSummonedBy(Unit* /*owner*/) override { DoCast(SpellOrbOfCorruptionSpawnAura); DoCast(SpellOrbOfCorruptionAuraProc); events.RescheduleEvent(EVENT_1, 500); } void Reset() override {} void UpdateAI(uint32 diff) override { events.Update(diff); if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: if (auto target = ObjectAccessor::GetUnit(*me, me->GetTargetGUID())) me->GetMotionMaster()->MovePoint(1, target->GetPosition()); events.RescheduleEvent(EVENT_2, 1000); break; case EVENT_2: if (auto target = ObjectAccessor::GetUnit(*me, me->GetTargetGUID())) me->GetMotionMaster()->MovePoint(1, target->GetPosition()); else events.RescheduleEvent(EVENT_1, 1000); if (instance->GetBossState(Data::BossIDs::HelyaID) == DONE) me->DespawnOrUnsummon(); events.RescheduleEvent(EVENT_2, 1000); break; } } } }; //114566 struct npc_orb_of_corrosion : ScriptedAI { explicit npc_orb_of_corrosion(Creature* creature) : ScriptedAI(creature) { me->SetReactState(REACT_PASSIVE); instance = me->GetInstanceScript(); } EventMap events; InstanceScript* instance; void IsSummonedBy(Unit* /*owner*/) override { DoCast(SpellOrbOfCorrosionSpawnAura); DoCast(SpellOrbOfCorrosionAuraProc); events.RescheduleEvent(EVENT_1, 500); } void Reset() override {} void UpdateAI(uint32 diff) override { events.Update(diff); if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: if (auto target = ObjectAccessor::GetUnit(*me, me->GetTargetGUID())) me->GetMotionMaster()->MovePoint(1, target->GetPosition()); events.RescheduleEvent(EVENT_2, 1000); break; case EVENT_2: if (auto target = ObjectAccessor::GetUnit(*me, me->GetTargetGUID())) me->GetMotionMaster()->MovePoint(1, target->GetPosition()); else events.RescheduleEvent(EVENT_1, 1000); if (instance->GetBossState(Data::BossIDs::HelyaID) == DONE) me->DespawnOrUnsummon(); events.RescheduleEvent(EVENT_2, 1000); break; } } } }; //114553 struct npc_bilewater_slime : ScriptedAI { explicit npc_bilewater_slime(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); me->SetReactState(REACT_PASSIVE); DoCast(me, SpellSlimey, true); spellhit = false; } InstanceScript* instance; bool spellhit; void IsSummonedBy(Unit* /*summoner*/) override { DoCast(me, SpellBilewaterLiquefactionScale, true); DoCast(SpellBilewaterLiquefaction); } void SpellHit(Unit* /*owner*/, SpellInfo const* spell) override { if (spell->Id == SpellBilewaterLiquefaction) { if (!spellhit) { spellhit = true; DoCast(SpellBilewaterLiquefactionKill); } } } void JustDied(Unit* /*killer*/) override { if (!spellhit) DoCast(SpellBilewaterLiquefactionKill); } }; //114709 struct npc_grimelord : ScriptedAI { explicit npc_grimelord(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); } EventMap events; InstanceScript* instance; void Reset() override { events.Reset(); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void EnterCombat(Unit* /*who*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me); events.RescheduleEvent(EVENT_1, 14000); events.RescheduleEvent(EVENT_2, 16000); events.RescheduleEvent(EVENT_3, 9000); } void IsSummonedBy(Unit* /*summoner*/) override { if (auto player = me->FindNearestPlayer(100.0f, true)) AttackStart(player); } void JustDied(Unit* /*killer*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && me->isInCombat()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: DoCast(SpellAnchorSlam); events.RescheduleEvent(EVENT_1, 12000); break; case EVENT_2: DoCast(SpellSludgeNova); events.RescheduleEvent(EVENT_2, 25000); break; case EVENT_3: { auto threatlist = me->getThreatManager().getThreatList(); for (uint8 i = 0; i < 2; ++i) { if (threatlist.empty()) break; if (auto itr = Trinity::Containers::SelectRandomContainerElement(threatlist)) { if (Unit* target = itr->getTarget()) me->AddAura(SpellFetidRot, target); threatlist.remove(itr); } } events.RescheduleEvent(EVENT_3, 17000); break; } } } DoMeleeAttackIfReady(); } }; //114809 struct npc_night_watch_mariner : ScriptedAI { explicit npc_night_watch_mariner(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); } EventMap events; InstanceScript* instance; void Reset() override { events.Reset(); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); me->SetPower(POWER_ENERGY, 0); me->SetMaxPower(POWER_ENERGY, 100); } void EnterCombat(Unit* /*who*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me); DoCast(SpellDarkness); events.RescheduleEvent(EVENT_1, 8000); events.RescheduleEvent(EVENT_2, 10000); } void IsSummonedBy(Unit* /*summoner*/) override { if (auto player = me->FindNearestPlayer(100.0f, true)) AttackStart(player); } void JustDied(Unit* /*killer*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void SetPower(Powers power, int32 value) override { if (power == POWER_ENERGY) { if (value == 100) { DoCast(me, SpellLanternOfDarkness, false); me->AddDelayedEvent(1000, [=]() -> void { me->SetPower(POWER_ENERGY, 0); }); } } } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && me->isInCombat()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: { auto threatlist = me->getThreatManager().getThreatList(); for (uint8 i = 0; i < (IsMythicRaid() ? 2 : 1); ++i) { if (threatlist.empty()) break; if (auto itr = Trinity::Containers::SelectRandomContainerElement(threatlist)) { if (Unit* target = itr->getTarget()) DoCast(target, SpellGiveNoQuarter, false); threatlist.remove(itr); } } events.RescheduleEvent(EVENT_1, 9000); break; } case EVENT_2: DoCast(SpellGhostlyRage); events.RescheduleEvent(EVENT_2, 16000); break; } } DoMeleeAttackIfReady(); } }; //114568 struct npc_decaying_minion : ScriptedAI { explicit npc_decaying_minion(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); DoCast(SpellRabid); } EventMap events; InstanceScript* instance; void Reset() override { events.Reset(); } void EnterCombat(Unit* /*who*/) override { events.RescheduleEvent(EVENT_1, 8000); } void JustDied(Unit* /*killer*/) override { if (auto helya = instance->instance->GetCreature(instance->GetGuidData(Data::Creatures::Helya))) helya->CastSpell(me, SpellDecay, true); } void IsSummonedBy(Unit* /*summoner*/) override { events.RescheduleEvent(EVENT_3, urand(500, 2000)); } void UpdateAI(uint32 diff) override { if (!UpdateVictim() && me->isInCombat()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: DoCast(SpellVigor); events.RescheduleEvent(EVENT_1, 9000); break; case EVENT_2: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (auto player = me->FindNearestPlayer(200.0f, true)) AttackStart(player); break; case EVENT_3: if (me->GetPositionX() >= 548.3593f && me->GetPositionX() <= 550.3593f) me->GetMotionMaster()->MoveJump(532.17f, 665.08f, 2.1955f, 20, 20); if (me->GetPositionX() >= 538.4478f && me->GetPositionX() <= 544.3593f) me->GetMotionMaster()->MoveJump(525.428f, 666.552f, 2.19553f, 20, 20); if (me->GetPositionX() >= 529.1761f && me->GetPositionX() <= 535.3593f) me->GetMotionMaster()->MoveJump(519.117f, 665.5169f, 2.0715f, 20, 20); if (me->GetPositionX() >= 521.0399f && me->GetPositionX() <= 526.3593f) me->GetMotionMaster()->MoveJump(506.52f, 671.52f, 2.04149f, 20, 20); if (me->GetPositionX() >= 517.1808f && me->GetPositionX() <= 520.3593f) me->GetMotionMaster()->MoveJump(501.103f, 675.1241f, 2.17084f, 20, 20); if (me->GetPositionX() >= 481.0416f && me->GetPositionX() <= 489.3593f) me->GetMotionMaster()->MoveJump(488.698f, 612.844f, 2.19552f, 20, 20); if (me->GetPositionX() >= 490.2551f && me->GetPositionX() <= 495.3593f) me->GetMotionMaster()->MoveJump(494.009f, 611.8982f, 2.19546f, 20, 20); if (me->GetPositionX() >= 501.1823f && me->GetPositionX() <= 510.3593f) me->GetMotionMaster()->MoveJump(505.3662f, 607.2649f, 2.80966f, 20, 20); if (me->GetPositionX() >= 514.1875f && me->GetPositionX() <= 516.3593f) me->GetMotionMaster()->MoveJump(510.0153f, 606.5961f, 4.22821f, 20, 20); if (me->GetPositionX() >= 528.01902f && me->GetPositionX() <= 528.9593f) me->GetMotionMaster()->MoveJump(517.567f, 609.2846f, 4.71457f, 20, 20); events.RescheduleEvent(EVENT_2, 3000); break; } } DoMeleeAttackIfReady(); } }; //116335 struct npc_helarjar_mistwatcher : ScriptedAI { explicit npc_helarjar_mistwatcher(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); me->SetReactState(REACT_PASSIVE); DoCast(SpellBleakEruption); } EventMap events; InstanceScript* instance; void Reset() override { events.Reset(); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void IsSummonedBy(Unit* /*summoner*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me); events.RescheduleEvent(EVENT_1, 3000); } void JustDied(Unit* /*killer*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void UpdateAI(uint32 diff) override { events.Update(diff); if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: if (auto owner = me->GetAnyOwner()) DoCast(owner, SpellMistInfusion, false); events.RescheduleEvent(EVENT_1, 7000); break; } } } }; //114900 struct npc_gripping_tentacle : ScriptedAI { explicit npc_gripping_tentacle(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); me->SetReactState(REACT_PASSIVE); me->SetControlled(1, UNIT_STATE_ROOT); } InstanceScript* instance; void Reset() override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } void EnterCombat(Unit* /*who*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me); } void JustDied(Unit* /*killer*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); } }; //114881 struct npc_striking_tentacle : ScriptedAI { explicit npc_striking_tentacle(Creature* creature) : ScriptedAI(creature) { me->SetControlled(1, UNIT_STATE_ROOT); } void IsSummonedBy(Unit* /*summoner*/) override { DoZoneInCombat(); } void EnterCombat(Unit* /*who*/) override { me->AddDelayedEvent(1000, [=]() -> void { if (auto target = me->FindNearestPlayer(40.0f, true)) me->CastSpell(target, SpellTentacleStrike, false); }); if (auto helya = me->FindNearestCreature(Data::Creatures::Helya, 30.0f)) ZoneTalk(6); else ZoneTalk(5); } }; Position const WPLeftSide[6] = { { 606.645f, 773.61f, 2.18505f, 0.0f }, { 589.789f, 751.336f, 2.81854f, 0.0f }, { 565.098f, 727.396f, 4.04037f, 0.0f }, { 537.359f, 675.583f, 5.16302f, 0.0f }, { 511.927f, 625.218f, 5.81001f, 0.0f }, { 516.007f, 614.179f, 5.5823f, 0.0f } }; Position const WPRightSide[6] = { { 559.634f, 835.07f, 0.00213f, 0.0f }, { 536.195f, 775.74f, 1.63033f, 0.0f }, { 531.157f, 745.006f, 5.09614f, 0.0f }, { 507.911f, 696.116f, 7.63036f, 0.0f }, { 478.192f, 654.984f, 6.92052f, 0.0f }, { 458.674f, 639.483f, 7.53757f, 0.0f } }; //115941 struct npc_kvaldir_longboat : ScriptedAI { explicit npc_kvaldir_longboat(Creature* creature) : ScriptedAI(creature) { me->SetReactState(REACT_PASSIVE); } EventMap events; bool leftSide = false; bool rightSide = false; void Reset() override { if (me->GetPositionX() >= 636.672f) { leftSide = true; me->GetMotionMaster()->MovePoint(1, WPLeftSide[0]); } else if (me->GetPositionX() <= 570.39) { rightSide = true; me->GetMotionMaster()->MovePoint(1, WPRightSide[0]); } } void MovementInform(uint32 type, uint32 data) override { if (type == POINT_MOTION_TYPE) { switch (data) { case 1: events.RescheduleEvent(EVENT_1, 100); break; case 2: events.RescheduleEvent(EVENT_2, 100); break; case 3: events.RescheduleEvent(EVENT_3, 100); break; case 4: events.RescheduleEvent(EVENT_4, 100); break; case 5: events.RescheduleEvent(EVENT_5, 100); break; } } } void UpdateAI(uint32 diff) override { events.Update(diff); if (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_1: if (rightSide) me->GetMotionMaster()->MovePoint(2, WPRightSide[1]); else if (leftSide) me->GetMotionMaster()->MovePoint(2, WPLeftSide[1]); break; case EVENT_2: if (rightSide) me->GetMotionMaster()->MovePoint(3, WPRightSide[2]); else if (leftSide) me->GetMotionMaster()->MovePoint(3, WPLeftSide[2]); break; case EVENT_3: if (rightSide) me->GetMotionMaster()->MovePoint(4, WPRightSide[3]); else if (leftSide) me->GetMotionMaster()->MovePoint(4, WPLeftSide[3]); break; case EVENT_4: if (rightSide) me->GetMotionMaster()->MovePoint(5, WPRightSide[4]); else if (leftSide) me->GetMotionMaster()->MovePoint(5, WPLeftSide[4]); break; case EVENT_5: if (rightSide) me->GetMotionMaster()->MovePoint(6, WPRightSide[5]); else if (leftSide) me->GetMotionMaster()->MovePoint(6, WPLeftSide[5]); break; } } } }; //228397 class spell_fetid_rot : public SpellScript { PrepareSpellScript(spell_fetid_rot); void HandleDamage(SpellEffIndex /*effectIndex*/) { Unit* target = GetHitUnit(); if (!target) return; target->AddAura(SpellFetidRot, target); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_fetid_rot::HandleDamage, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); } }; //228730 class spell_tentacle_strike : public SpellScript { PrepareSpellScript(spell_tentacle_strike); uint8 targetsCount = 0; void FilterTargets(std::list<WorldObject*>& targets) { Unit* caster = GetCaster(); if (!caster) return; if (targets.empty()) caster->CastSpell(caster, SpellTentacleSlam, true); else targetsCount = targets.size(); } void HandleDamage(SpellEffIndex /*effectIndex*/) { if (targetsCount) SetHitDamage(GetHitDamage() / targetsCount); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_tentacle_strike::FilterTargets, EFFECT_0, TARGET_UNIT_BETWEEN_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_tentacle_strike::HandleDamage, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); } }; //232449 class spell_corrupted_axion : public SpellScript { PrepareSpellScript(spell_corrupted_axion); void FilterTargets(std::list<WorldObject*>& targets) { Unit* caster = GetCaster(); if (!caster) return; if (targets.empty()) caster->CastSpell(caster, SpellCorruptedAxionAOE, true); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_corrupted_axion::FilterTargets, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY); } }; //232450 class spell_corrupted_axion_aura : public AuraScript { PrepareAuraScript(spell_corrupted_axion_aura); void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if (!target) return; Unit* caster = GetCaster(); if (!caster || !caster->GetMap()) return; if (caster->GetMap()->GetSpawnMode() == DIFFICULTY_MYTHIC_RAID) if (GetTargetApplication()->GetRemoveMode() != AURA_REMOVE_BY_ENEMY_SPELL) caster->CastSpell(target, SpellCorrupted, false); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_corrupted_axion_aura::OnRemove, EFFECT_1, SPELL_AURA_SCHOOL_HEAL_ABSORB, AURA_EFFECT_HANDLE_REAL); } }; //232350 class spell_corrupted_mc : public AuraScript { PrepareAuraScript(spell_corrupted_mc); void OnProc(AuraEffect const* aurEff) { Unit* target = GetTarget(); Unit* caster = GetCaster(); if (!target || !caster) return; if (target && target->HealthBelowPct(11)) target->RemoveAura(SpellCorrupted); target->GetMotionMaster()->Clear(); if (!target->HasUnitState(UNIT_STATE_CASTING)) target->CastSpell(caster, SpellMistInfusion, false); } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_corrupted_mc::OnProc, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; //228300 class spell_fury_of_the_maw : public AuraScript { PrepareAuraScript(spell_fury_of_the_maw); void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* caster = GetCaster()->ToCreature(); if (!caster) return; caster->GetAI()->DoAction(ACTION_1); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_fury_of_the_maw::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; //228514 class spell_tov_torrent : public SpellScript { PrepareSpellScript(spell_tov_torrent); void FilterTargets(std::list<WorldObject*>& targets) { uint32 count = 5; if (targets.size() > count) targets.resize(count); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_tov_torrent::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); } }; struct at_fury_of_the_maw : AreaTriggerAI { explicit at_fury_of_the_maw(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) {} bool IsValidTarget(Unit* caster, Unit* target, AreaTriggerActionMoment /*actionM*/) { if (!target || !target->IsPlayer()) return false; if (target->GetPositionZ() > 17.80f) return false; return true; } }; void AddSC_boss_tov_helya() { RegisterCreatureAI(boss_helya_tov); RegisterCreatureAI(npc_orb_of_corruption); RegisterCreatureAI(npc_orb_of_corrosion); RegisterCreatureAI(npc_bilewater_slime); RegisterCreatureAI(npc_grimelord); RegisterCreatureAI(npc_night_watch_mariner); RegisterCreatureAI(npc_decaying_minion); RegisterCreatureAI(npc_gripping_tentacle); RegisterCreatureAI(npc_helarjar_mistwatcher); RegisterCreatureAI(npc_striking_tentacle); RegisterCreatureAI(npc_kvaldir_longboat); RegisterAuraScript(spell_helya_blue_power_regen); RegisterAuraScript(spell_helya_purple_power_regen); RegisterAuraScript(spell_helya_alt_power_regen); RegisterAuraScript(spell_tov_darkness); RegisterAuraScript(spell_taint_of_the_sea); RegisterAuraScript(spell_corrupted_axion_aura); RegisterAuraScript(spell_corrupted_mc); RegisterAuraScript(spell_fury_of_the_maw); RegisterSpellScript(spell_fetid_rot); RegisterSpellScript(spell_tentacle_strike); RegisterSpellScript(spell_corrupted_axion); RegisterSpellScript(spell_tov_torrent); RegisterAreaTriggerAI(at_fury_of_the_maw); }
412
0.989814
1
0.989814
game-dev
MEDIA
0.906126
game-dev
0.522434
1
0.522434
magefree/mage
3,126
Mage.Sets/src/mage/cards/b/BloodSpatterAnalysis.java
package mage.cards.b; import mage.abilities.Ability; import mage.abilities.common.DiesOneOrMoreTriggeredAbility; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.common.delayed.ReflexiveTriggeredAbility; import mage.abilities.condition.Condition; import mage.abilities.condition.common.SourceHasCounterCondition; import mage.abilities.costs.common.SacrificeSourceCost; import mage.abilities.decorator.ConditionalOneShotEffect; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.effects.common.DoWhenCostPaid; import mage.abilities.effects.common.MillCardsControllerEffect; import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.counters.CounterType; import mage.filter.StaticFilters; import mage.target.common.TargetCardInYourGraveyard; import mage.target.common.TargetOpponentsCreaturePermanent; import java.util.UUID; /** * @author Cguy7777 */ public final class BloodSpatterAnalysis extends CardImpl { private static final Condition condition = new SourceHasCounterCondition(CounterType.BLOODSTAIN, 5); public BloodSpatterAnalysis(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{B}{R}"); // When Blood Spatter Analysis enters the battlefield, it deals 3 damage to target creature an opponent controls. Ability ability = new EntersBattlefieldTriggeredAbility(new DamageTargetEffect(3)); ability.addTarget(new TargetOpponentsCreaturePermanent()); this.addAbility(ability); // Whenever one or more creatures die, mill a card and put a bloodstain counter on Blood Spatter Analysis. // Then sacrifice it if it has five or more bloodstain counters on it. // When you do, return target creature card from your graveyard to your hand. ability = new DiesOneOrMoreTriggeredAbility(new MillCardsControllerEffect(1), StaticFilters.FILTER_PERMANENT_CREATURES, false); ability.addEffect(new AddCountersSourceEffect(CounterType.BLOODSTAIN.createInstance()).concatBy("and")); ReflexiveTriggeredAbility returnAbility = new ReflexiveTriggeredAbility(new ReturnFromGraveyardToHandTargetEffect(), false); returnAbility.addTarget(new TargetCardInYourGraveyard(StaticFilters.FILTER_CARD_CREATURE_YOUR_GRAVEYARD)); ability.addEffect(new ConditionalOneShotEffect(new DoWhenCostPaid( returnAbility, new SacrificeSourceCost(), null, false ), condition).setText("Then sacrifice it if it has five or more bloodstain counters on it. " + "When you do, return target creature card from your graveyard to your hand")); this.addAbility(ability); } private BloodSpatterAnalysis(final BloodSpatterAnalysis card) { super(card); } @Override public BloodSpatterAnalysis copy() { return new BloodSpatterAnalysis(this); } }
412
0.953638
1
0.953638
game-dev
MEDIA
0.934412
game-dev
0.980617
1
0.980617
KoboldKit/KoboldKit
1,597
KoboldKit/KoboldKitFree/Framework/Behaviors/Movement/KKFollowTargetBehavior.h
/* * Copyright (c) 2013 Steffen Itterheim. * Released under the MIT License: * KoboldAid/licenses/KoboldKitFree.License.txt */ #import <SpriteKit/SpriteKit.h> #import "KKBehavior.h" /** Updates the owning node's position from another node's position, applying optional offset and/or multiplier. The multiplier can be used to achieve a parallaxing effect. */ @interface KKFollowTargetBehavior : KKBehavior /** The target the behavior's node is following. */ @property (atomic, weak) SKNode* target; /** The target's position is multiplied by this position multiplier before the resulting point is set as the node's position. */ @property (atomic) CGPoint positionMultiplier; /** The target's position has this offset added before the resulting point is set as the node's position. */ @property (atomic) CGPoint positionOffset; /** Follow another node. @param target The node to follow. @returns A new instance. */ +(id) followTarget:(SKNode*)target; /** Follow another node at an offset. @param target The node to follow. @param positionOffset The offset to add to the target's position. @returns A new instance. */ +(id) followTarget:(SKNode*)target offset:(CGPoint)positionOffset; /** Follow another node at an offset with multiplier (for parallaxing effect). @param target The node to follow. @param positionOffset The offset to add to the target's position. @param positionMultiplier Multiply the target position by these multipliers. @returns A new instance. */ +(id) followTarget:(SKNode*)target offset:(CGPoint)positionOffset multiplier:(CGPoint)positionMultiplier; @end
412
0.951479
1
0.951479
game-dev
MEDIA
0.178782
game-dev
0.848057
1
0.848057
Tencent/Hippy
6,936
framework/examples/voltron-demo/flutter_module/lib/base_voltron_page.dart
// // Tencent is pleased to support the open source community by making // Hippy available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:voltron/voltron.dart'; import 'my_api_provider.dart'; enum PageStatus { init, loading, success, error, } class Monitor extends EngineMonitor { @override bool enableBuildTime = true; @override bool enablePerformance = true; @override bool enableCreateElementTime = true; } /// 自定义错误处理 class CustomExceptionHandler extends VoltronExceptionHandlerAdapter { final bool isDebugMode; final GlobalKey<State> key; CustomExceptionHandler(this.isDebugMode, this.key); void handleJsException(JsError exception) { LogUtils.e('Voltron3Page', exception.toString()); var currentRootContext = key.currentContext; /// 只有开发模式下把js异常抛出来 if (currentRootContext == null || !isDebugMode) return; showDialog( context: currentRootContext, builder: (BuildContext context) { return AlertDialog( title: Text('JS Error'), content: Container( height: 300, child: SingleChildScrollView( child: Text( exception.toString(), ), ), ), actions: <Widget>[ TextButton( child: Text('确定'), onPressed: () { // 执行确认操作 Navigator.of(context).pop(); }, ), ], ); }, ); } void handleNativeException(Error error, bool haveCaught) { LogUtils.e('Voltron3Page', 'error: ${error.toString()}, haveCaught: $haveCaught'); } void handleBackgroundTracing(String details) { LogUtils.e('Voltron3Page', details); } } class BaseVoltronPage extends StatefulWidget { final bool isHome; final bool debugMode; final String coreBundle; final String indexBundle; final String remoteServerUrl; BaseVoltronPage({ this.isHome = false, this.debugMode = false, this.coreBundle = '', this.indexBundle = '', this.remoteServerUrl = '', }); @override State<StatefulWidget> createState() { return _BaseVoltronPageState(); } } class _BaseVoltronPageState extends State<BaseVoltronPage> { GlobalKey<State> dialogRootKey = GlobalKey(); PageStatus engineStatus = PageStatus.init; PageStatus loadModuleStatus = PageStatus.init; late VoltronJSLoaderManager _loaderManager; late VoltronJSLoader _jsLoader; int errorCode = -1; late bool _debugMode; late String _coreBundle; late String _indexBundle; late String _remoteServerUrl; @override void initState() { super.initState(); _debugMode = widget.debugMode; _coreBundle = widget.coreBundle; _indexBundle = widget.indexBundle; _remoteServerUrl = widget.remoteServerUrl; _initVoltronData(); } void _initVoltronData() async { IosDeviceInfo? deviceData; if (Platform.isIOS) { try { deviceData = await DeviceInfoPlugin().iosInfo; } catch (err) { setState(() { engineStatus = PageStatus.error; }); } } var initParams = EngineInitParams(); initParams.debugMode = _debugMode; initParams.enableLog = true; if (_debugMode) { // 调试模式下直接使用debug参数 initParams.remoteServerUrl = _remoteServerUrl; } else { // 如果是不分包加载,可以只填写coreJSAssetsPath,下面的jsAssetsPath直接忽略即可 initParams.coreJSAssetsPath = _coreBundle; initParams.codeCacheTag = "common"; } initParams.integratedMode = IntegratedMode.flutterModule; initParams.providers = [ MyAPIProvider(), ]; initParams.engineMonitor = Monitor(); initParams.exceptionHandler = CustomExceptionHandler(_debugMode, dialogRootKey); _loaderManager = VoltronJSLoaderManager.createLoaderManager( initParams, (statusCode, msg) { LogUtils.i( 'loadEngine', 'code($statusCode), msg($msg)', ); if (statusCode == EngineInitStatus.ok) { setState(() { engineStatus = PageStatus.success; }); } else { setState(() { engineStatus = PageStatus.error; errorCode = statusCode.value; }); } }, ); var loadParams = ModuleLoadParams(); loadParams.componentName = "Demo"; loadParams.codeCacheTag = "Demo"; if (isWebUrl(_indexBundle)) { loadParams.jsHttpPath = _indexBundle; } else { loadParams.jsAssetsPath = _indexBundle; } loadParams.jsParams = VoltronMap(); loadParams.jsParams?.push( "msgFromNative", "Hi js developer, I come from native code!", ); if (deviceData != null) { loadParams.jsParams?.push( "isSimulator", !deviceData.isPhysicalDevice, ); } _jsLoader = _loaderManager.createLoader( loadParams, moduleListener: (status, msg) { if (status == ModuleLoadStatus.ok) { loadModuleStatus = PageStatus.success; } else { loadModuleStatus = PageStatus.error; } LogUtils.i( "flutterRender", "loadModule status($status), msg ($msg)", ); }, ); } @override void dispose() { super.dispose(); _jsLoader.destroy(); _loaderManager.destroy(); } @override Widget build(BuildContext context) { Widget child; if (engineStatus == PageStatus.success) { child = Scaffold( body: VoltronWidget( loader: _jsLoader, loadingBuilder: _debugMode ? null : (context) => Container(), ), ); } else if (engineStatus == PageStatus.error) { child = Center( child: Text('init engine error, code: ${errorCode.toString()}'), ); } else { child = Container(); } child = SafeArea( key: dialogRootKey, bottom: false, child: child, ); return WillPopScope( onWillPop: () async { return !(_jsLoader.back(() { Navigator.of(context).pop(); if (widget.isHome) { SystemNavigator.pop(); } })); }, child: child, ); } }
412
0.911037
1
0.911037
game-dev
MEDIA
0.635797
game-dev
0.941621
1
0.941621
huangkaoya/redalert2
2,656
src/gui/screen/mainMenu/modSel/ModMeta.ts
import { ModManager } from "@/gui/screen/mainMenu/modSel/ModManager"; interface IniSection { getString(key: string): string | undefined; get(key: string): string | string[] | undefined; getNumber(key: string): number | undefined; getBool(key: string): boolean; } interface IniFile { getSection(name: string): IniSection | undefined; } export class ModMeta { public id?: string; public name?: string; public supported: boolean = false; public description?: string; public authors?: string[]; public website?: string; public version?: string; public download?: string; public downloadSize?: number; public manualDownload: boolean = false; fromIniFile(iniFile: IniFile): this { const generalSection = iniFile.getSection("General"); if (!generalSection) { throw new Error("Mod meta missing [General] section"); } return this.fromIniSection(generalSection); } fromIniSection(section: IniSection): this { const id = section.getString("ID"); const name = section.getString("Name"); if (!id) { throw new Error("Mod meta missing ID"); } if (!id.match(ModManager.modIdRegex)) { throw new Error( `Mod meta has invalid ID "${id}". ` + "ID must contain only alphanumeric characters, dash (-) or underscore (_)", ); } if (!name) { throw new Error("Mod meta missing Name"); } this.id = id; this.name = name; this.supported = true; this.description = section.getString("Description") || undefined; const authors = section.get("Author"); if (authors) { this.authors = Array.isArray(authors) ? authors : [authors]; } const website = section.getString("Website"); if (website) { if (website.match(/^https?:\/\//)) { this.website = website; } else { console.warn(`Invalid mod meta website "${website}"`); } } this.version = section.getString("Version") || undefined; this.download = section.getString("Download") || undefined; this.downloadSize = section.getNumber("DownloadSize") || undefined; this.manualDownload = section.getBool("ManualDownload"); return this; } clone(): ModMeta { const cloned = new ModMeta(); cloned.id = this.id; cloned.name = this.name; cloned.supported = this.supported; cloned.description = this.description; cloned.authors = this.authors?.slice(); cloned.website = this.website; cloned.version = this.version; cloned.download = this.download; cloned.downloadSize = this.downloadSize; cloned.manualDownload = this.manualDownload; return cloned; } }
412
0.828303
1
0.828303
game-dev
MEDIA
0.350137
game-dev
0.571355
1
0.571355