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
fallahn/crogine
18,326
android/BulletDroid/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_QUANTIZED_BVH_H #define BT_QUANTIZED_BVH_H class btSerializer; //#define DEBUG_CHECK_DEQUANTIZATION 1 #ifdef DEBUG_CHECK_DEQUANTIZATION #ifdef __SPU__ #define printf spu_printf #endif //__SPU__ #include <stdio.h> #include <stdlib.h> #endif //DEBUG_CHECK_DEQUANTIZATION #include "LinearMath/btVector3.h" #include "LinearMath/btAlignedAllocator.h" #ifdef BT_USE_DOUBLE_PRECISION #define btQuantizedBvhData btQuantizedBvhDoubleData #define btOptimizedBvhNodeData btOptimizedBvhNodeDoubleData #define btQuantizedBvhDataName "btQuantizedBvhDoubleData" #else #define btQuantizedBvhData btQuantizedBvhFloatData #define btOptimizedBvhNodeData btOptimizedBvhNodeFloatData #define btQuantizedBvhDataName "btQuantizedBvhFloatData" #endif //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/vclrf__m128.asp //Note: currently we have 16 bytes per quantized node #define MAX_SUBTREE_SIZE_IN_BYTES 2048 // 10 gives the potential for 1024 parts, with at most 2^21 (2097152) (minus one // actually) triangles each (since the sign bit is reserved #define MAX_NUM_PARTS_IN_BITS 10 ///btQuantizedBvhNode is a compressed aabb node, 16 bytes. ///Node can be used for leafnode or internal node. Leafnodes can point to 32-bit triangle index (non-negative range). ATTRIBUTE_ALIGNED16 (struct) btQuantizedBvhNode { BT_DECLARE_ALIGNED_ALLOCATOR(); //12 bytes unsigned short int m_quantizedAabbMin[3]; unsigned short int m_quantizedAabbMax[3]; //4 bytes int m_escapeIndexOrTriangleIndex; bool isLeafNode() const { //skipindex is negative (internal node), triangleindex >=0 (leafnode) return (m_escapeIndexOrTriangleIndex >= 0); } int getEscapeIndex() const { btAssert(!isLeafNode()); return -m_escapeIndexOrTriangleIndex; } int getTriangleIndex() const { btAssert(isLeafNode()); unsigned int x=0; unsigned int y = (~(x&0))<<(31-MAX_NUM_PARTS_IN_BITS); // Get only the lower bits where the triangle index is stored return (m_escapeIndexOrTriangleIndex&~(y)); } int getPartId() const { btAssert(isLeafNode()); // Get only the highest bits where the part index is stored return (m_escapeIndexOrTriangleIndex>>(31-MAX_NUM_PARTS_IN_BITS)); } } ; /// btOptimizedBvhNode contains both internal and leaf node information. /// Total node size is 44 bytes / node. You can use the compressed version of 16 bytes. ATTRIBUTE_ALIGNED16 (struct) btOptimizedBvhNode { BT_DECLARE_ALIGNED_ALLOCATOR(); //32 bytes btVector3 m_aabbMinOrg; btVector3 m_aabbMaxOrg; //4 int m_escapeIndex; //8 //for child nodes int m_subPart; int m_triangleIndex; //pad the size to 64 bytes char m_padding[20]; }; ///btBvhSubtreeInfo provides info to gather a subtree of limited size ATTRIBUTE_ALIGNED16(class) btBvhSubtreeInfo { public: BT_DECLARE_ALIGNED_ALLOCATOR(); //12 bytes unsigned short int m_quantizedAabbMin[3]; unsigned short int m_quantizedAabbMax[3]; //4 bytes, points to the root of the subtree int m_rootNodeIndex; //4 bytes int m_subtreeSize; int m_padding[3]; btBvhSubtreeInfo() { //memset(&m_padding[0], 0, sizeof(m_padding)); } void setAabbFromQuantizeNode(const btQuantizedBvhNode& quantizedNode) { m_quantizedAabbMin[0] = quantizedNode.m_quantizedAabbMin[0]; m_quantizedAabbMin[1] = quantizedNode.m_quantizedAabbMin[1]; m_quantizedAabbMin[2] = quantizedNode.m_quantizedAabbMin[2]; m_quantizedAabbMax[0] = quantizedNode.m_quantizedAabbMax[0]; m_quantizedAabbMax[1] = quantizedNode.m_quantizedAabbMax[1]; m_quantizedAabbMax[2] = quantizedNode.m_quantizedAabbMax[2]; } } ; class btNodeOverlapCallback { public: virtual ~btNodeOverlapCallback() {}; virtual void processNode(int subPart, int triangleIndex) = 0; }; #include "LinearMath/btAlignedAllocator.h" #include "LinearMath/btAlignedObjectArray.h" ///for code readability: typedef btAlignedObjectArray<btOptimizedBvhNode> NodeArray; typedef btAlignedObjectArray<btQuantizedBvhNode> QuantizedNodeArray; typedef btAlignedObjectArray<btBvhSubtreeInfo> BvhSubtreeInfoArray; ///The btQuantizedBvh class stores an AABB tree that can be quickly traversed on CPU and Cell SPU. ///It is used by the btBvhTriangleMeshShape as midphase. ///It is recommended to use quantization for better performance and lower memory requirements. ATTRIBUTE_ALIGNED16(class) btQuantizedBvh { public: enum btTraversalMode { TRAVERSAL_STACKLESS = 0, TRAVERSAL_STACKLESS_CACHE_FRIENDLY, TRAVERSAL_RECURSIVE }; protected: btVector3 m_bvhAabbMin; btVector3 m_bvhAabbMax; btVector3 m_bvhQuantization; int m_bulletVersion; //for serialization versioning. It could also be used to detect endianess. int m_curNodeIndex; //quantization data bool m_useQuantization; NodeArray m_leafNodes; NodeArray m_contiguousNodes; QuantizedNodeArray m_quantizedLeafNodes; QuantizedNodeArray m_quantizedContiguousNodes; btTraversalMode m_traversalMode; BvhSubtreeInfoArray m_SubtreeHeaders; //This is only used for serialization so we don't have to add serialization directly to btAlignedObjectArray mutable int m_subtreeHeaderCount; ///two versions, one for quantized and normal nodes. This allows code-reuse while maintaining readability (no template/macro!) ///this might be refactored into a virtual, it is usually not calculated at run-time void setInternalNodeAabbMin(int nodeIndex, const btVector3& aabbMin) { if (m_useQuantization) { quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] ,aabbMin,0); } else { m_contiguousNodes[nodeIndex].m_aabbMinOrg = aabbMin; } } void setInternalNodeAabbMax(int nodeIndex,const btVector3& aabbMax) { if (m_useQuantization) { quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0],aabbMax,1); } else { m_contiguousNodes[nodeIndex].m_aabbMaxOrg = aabbMax; } } btVector3 getAabbMin(int nodeIndex) const { if (m_useQuantization) { return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMin[0]); } //non-quantized return m_leafNodes[nodeIndex].m_aabbMinOrg; } btVector3 getAabbMax(int nodeIndex) const { if (m_useQuantization) { return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMax[0]); } //non-quantized return m_leafNodes[nodeIndex].m_aabbMaxOrg; } void setInternalNodeEscapeIndex(int nodeIndex, int escapeIndex) { if (m_useQuantization) { m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = -escapeIndex; } else { m_contiguousNodes[nodeIndex].m_escapeIndex = escapeIndex; } } void mergeInternalNodeAabb(int nodeIndex,const btVector3& newAabbMin,const btVector3& newAabbMax) { if (m_useQuantization) { unsigned short int quantizedAabbMin[3]; unsigned short int quantizedAabbMax[3]; quantize(quantizedAabbMin,newAabbMin,0); quantize(quantizedAabbMax,newAabbMax,1); for (int i=0;i<3;i++) { if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] > quantizedAabbMin[i]) m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] = quantizedAabbMin[i]; if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] < quantizedAabbMax[i]) m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] = quantizedAabbMax[i]; } } else { //non-quantized m_contiguousNodes[nodeIndex].m_aabbMinOrg.setMin(newAabbMin); m_contiguousNodes[nodeIndex].m_aabbMaxOrg.setMax(newAabbMax); } } void swapLeafNodes(int firstIndex,int secondIndex); void assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex); protected: void buildTree (int startIndex,int endIndex); int calcSplittingAxis(int startIndex,int endIndex); int sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis); void walkStacklessTree(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; void walkStacklessQuantizedTreeAgainstRay(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex,int endNodeIndex) const; void walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const; void walkStacklessTreeAgainstRay(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex,int endNodeIndex) const; ///tree traversal designed for small-memory processors like PS3 SPU void walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const; ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal void walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const; ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal void walkRecursiveQuantizedTreeAgainstQuantizedTree(const btQuantizedBvhNode* treeNodeA,const btQuantizedBvhNode* treeNodeB,btNodeOverlapCallback* nodeCallback) const; void updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex); public: BT_DECLARE_ALIGNED_ALLOCATOR(); btQuantizedBvh(); virtual ~btQuantizedBvh(); ///***************************************** expert/internal use only ************************* void setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin=btScalar(1.0)); QuantizedNodeArray& getLeafNodeArray() { return m_quantizedLeafNodes; } ///buildInternal is expert use only: assumes that setQuantizationValues and LeafNodeArray are initialized void buildInternal(); ///***************************************** expert/internal use only ************************* void reportAabbOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; void reportRayOverlappingNodex (btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget) const; void reportBoxCastOverlappingNodex(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin,const btVector3& aabbMax) const; SIMD_FORCE_INLINE void quantize(unsigned short* out, const btVector3& point,int isMax) const { btAssert(m_useQuantization); btAssert(point.getX() <= m_bvhAabbMax.getX()); btAssert(point.getY() <= m_bvhAabbMax.getY()); btAssert(point.getZ() <= m_bvhAabbMax.getZ()); btAssert(point.getX() >= m_bvhAabbMin.getX()); btAssert(point.getY() >= m_bvhAabbMin.getY()); btAssert(point.getZ() >= m_bvhAabbMin.getZ()); btVector3 v = (point - m_bvhAabbMin) * m_bvhQuantization; ///Make sure rounding is done in a way that unQuantize(quantizeWithClamp(...)) is conservative ///end-points always set the first bit, so that they are sorted properly (so that neighbouring AABBs overlap properly) ///@todo: double-check this if (isMax) { out[0] = (unsigned short) (((unsigned short)(v.getX()+btScalar(1.)) | 1)); out[1] = (unsigned short) (((unsigned short)(v.getY()+btScalar(1.)) | 1)); out[2] = (unsigned short) (((unsigned short)(v.getZ()+btScalar(1.)) | 1)); } else { out[0] = (unsigned short) (((unsigned short)(v.getX()) & 0xfffe)); out[1] = (unsigned short) (((unsigned short)(v.getY()) & 0xfffe)); out[2] = (unsigned short) (((unsigned short)(v.getZ()) & 0xfffe)); } #ifdef DEBUG_CHECK_DEQUANTIZATION btVector3 newPoint = unQuantize(out); if (isMax) { if (newPoint.getX() < point.getX()) { printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n",newPoint.getX()-point.getX(), newPoint.getX(),point.getX()); } if (newPoint.getY() < point.getY()) { printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n",newPoint.getY()-point.getY(), newPoint.getY(),point.getY()); } if (newPoint.getZ() < point.getZ()) { printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n",newPoint.getZ()-point.getZ(), newPoint.getZ(),point.getZ()); } } else { if (newPoint.getX() > point.getX()) { printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n",newPoint.getX()-point.getX(), newPoint.getX(),point.getX()); } if (newPoint.getY() > point.getY()) { printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n",newPoint.getY()-point.getY(), newPoint.getY(),point.getY()); } if (newPoint.getZ() > point.getZ()) { printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n",newPoint.getZ()-point.getZ(), newPoint.getZ(),point.getZ()); } } #endif //DEBUG_CHECK_DEQUANTIZATION } SIMD_FORCE_INLINE void quantizeWithClamp(unsigned short* out, const btVector3& point2,int isMax) const { btAssert(m_useQuantization); btVector3 clampedPoint(point2); clampedPoint.setMax(m_bvhAabbMin); clampedPoint.setMin(m_bvhAabbMax); quantize(out,clampedPoint,isMax); } SIMD_FORCE_INLINE btVector3 unQuantize(const unsigned short* vecIn) const { btVector3 vecOut; vecOut.setValue( (btScalar)(vecIn[0]) / (m_bvhQuantization.getX()), (btScalar)(vecIn[1]) / (m_bvhQuantization.getY()), (btScalar)(vecIn[2]) / (m_bvhQuantization.getZ())); vecOut += m_bvhAabbMin; return vecOut; } ///setTraversalMode let's you choose between stackless, recursive or stackless cache friendly tree traversal. Note this is only implemented for quantized trees. void setTraversalMode(btTraversalMode traversalMode) { m_traversalMode = traversalMode; } SIMD_FORCE_INLINE QuantizedNodeArray& getQuantizedNodeArray() { return m_quantizedContiguousNodes; } SIMD_FORCE_INLINE BvhSubtreeInfoArray& getSubtreeInfoArray() { return m_SubtreeHeaders; } //////////////////////////////////////////////////////////////////// /////Calculate space needed to store BVH for serialization unsigned calculateSerializeBufferSize() const; /// Data buffer MUST be 16 byte aligned virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian) const; ///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place' static btQuantizedBvh *deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian); static unsigned int getAlignmentSerializationPadding(); ////////////////////////////////////////////////////////////////////// virtual int calculateSerializeBufferSizeNew() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; virtual void deSerializeFloat(struct btQuantizedBvhFloatData& quantizedBvhFloatData); virtual void deSerializeDouble(struct btQuantizedBvhDoubleData& quantizedBvhDoubleData); //////////////////////////////////////////////////////////////////// SIMD_FORCE_INLINE bool isQuantized() { return m_useQuantization; } private: // Special "copy" constructor that allows for in-place deserialization // Prevents btVector3's default constructor from being called, but doesn't inialize much else // ownsMemory should most likely be false if deserializing, and if you are not, don't call this (it also changes the function signature, which we need) btQuantizedBvh(btQuantizedBvh &other, bool ownsMemory); } ; struct btBvhSubtreeInfoData { int m_rootNodeIndex; int m_subtreeSize; unsigned short m_quantizedAabbMin[3]; unsigned short m_quantizedAabbMax[3]; }; struct btOptimizedBvhNodeFloatData { btVector3FloatData m_aabbMinOrg; btVector3FloatData m_aabbMaxOrg; int m_escapeIndex; int m_subPart; int m_triangleIndex; char m_pad[4]; }; struct btOptimizedBvhNodeDoubleData { btVector3DoubleData m_aabbMinOrg; btVector3DoubleData m_aabbMaxOrg; int m_escapeIndex; int m_subPart; int m_triangleIndex; char m_pad[4]; }; struct btQuantizedBvhNodeData { unsigned short m_quantizedAabbMin[3]; unsigned short m_quantizedAabbMax[3]; int m_escapeIndexOrTriangleIndex; }; struct btQuantizedBvhFloatData { btVector3FloatData m_bvhAabbMin; btVector3FloatData m_bvhAabbMax; btVector3FloatData m_bvhQuantization; int m_curNodeIndex; int m_useQuantization; int m_numContiguousLeafNodes; int m_numQuantizedContiguousNodes; btOptimizedBvhNodeFloatData *m_contiguousNodesPtr; btQuantizedBvhNodeData *m_quantizedContiguousNodesPtr; btBvhSubtreeInfoData *m_subTreeInfoPtr; int m_traversalMode; int m_numSubtreeHeaders; }; struct btQuantizedBvhDoubleData { btVector3DoubleData m_bvhAabbMin; btVector3DoubleData m_bvhAabbMax; btVector3DoubleData m_bvhQuantization; int m_curNodeIndex; int m_useQuantization; int m_numContiguousLeafNodes; int m_numQuantizedContiguousNodes; btOptimizedBvhNodeDoubleData *m_contiguousNodesPtr; btQuantizedBvhNodeData *m_quantizedContiguousNodesPtr; int m_traversalMode; int m_numSubtreeHeaders; btBvhSubtreeInfoData *m_subTreeInfoPtr; }; SIMD_FORCE_INLINE int btQuantizedBvh::calculateSerializeBufferSizeNew() const { return sizeof(btQuantizedBvhData); } #endif //BT_QUANTIZED_BVH_H
412
0.974129
1
0.974129
game-dev
MEDIA
0.817671
game-dev
0.958896
1
0.958896
mono/CocosSharp
4,341
tests/tests/classes/tests/MotionStreakTest/MotionStreakTest.cs
using CocosSharp; namespace tests { public class MotionStreakTest : CCLayer { private static int sceneIdx = 0; private static int MAX_LAYER = 3; private string s_pPathB1 = "Images/b1"; private string s_pPathB2 = "Images/b2"; private string s_pPathF1 = "Images/f1"; private string s_pPathF2 = "Images/f2"; private string s_pPathR1 = "Images/r1"; private string s_pPathR2 = "Images/r2"; private const int kTagLabel = 2; protected CCMotionStreak streak; public static CCLayer createMotionLayer(int nIndex) { switch (nIndex) { case 0: return new MotionStreakTest1(); case 1: return new MotionStreakTest2(); case 2: return new Issue1358(); } return null; } public static CCLayer nextMotionAction() { sceneIdx++; sceneIdx = sceneIdx % MAX_LAYER; CCLayer pLayer = createMotionLayer(sceneIdx); return pLayer; } public static CCLayer backMotionAction() { sceneIdx--; int total = MAX_LAYER; if (sceneIdx < 0) sceneIdx += total; CCLayer pLayer = createMotionLayer(sceneIdx); return pLayer; } public static CCLayer restartMotionAction() { CCLayer pLayer = createMotionLayer(sceneIdx); return pLayer; } public virtual string title() { return "No title"; } public virtual string subtitle() { return ""; } public override void OnEnter() { base.OnEnter(); CCSize s = Layer.VisibleBoundsWorldspace.Size; var label = new CCLabel(title(), "arial", 32, CCLabelFormat.SpriteFont); AddChild(label, 0, kTagLabel); label.Position = new CCPoint(s.Width / 2, s.Height - 50); string subTitle = this.subtitle(); if (subTitle.Length > 0) { var l = new CCLabel(subTitle, "arial", 16, CCLabelFormat.SpriteFont); AddChild(l, 1); l.Position = new CCPoint(s.Width / 2, s.Height - 80); } var item1 = new CCMenuItemImage(s_pPathB1, s_pPathB2, backCallback); var item2 = new CCMenuItemImage(s_pPathR1, s_pPathR2, restartCallback); var item3 = new CCMenuItemImage(s_pPathF1, s_pPathF2, nextCallback); var menu = new CCMenu(item1, item2, item3); menu.Position = CCPoint.Zero; item1.Position = new CCPoint(s.Width / 2 - item2.ContentSize.Width * 2, item2.ContentSize.Height / 2); item2.Position = new CCPoint(s.Width / 2, item2.ContentSize.Height / 2); item3.Position = new CCPoint(s.Width / 2 + item2.ContentSize.Width * 2, item2.ContentSize.Height / 2); AddChild(menu, 1); var itemMode = new CCMenuItemToggle(modeCallback, new CCMenuItemFont("Use High Quality Mode"), new CCMenuItemFont("Use Fast Mode") ); var menuMode = new CCMenu(itemMode); AddChild(menuMode); menuMode.Position = new CCPoint(s.Width / 2, s.Height / 4); } private void modeCallback(object pSender) { bool fastMode = streak.FastMode; streak.FastMode = !fastMode; } public void restartCallback(object pSender) { CCScene s = new MotionStreakTestScene(); s.AddChild(restartMotionAction()); Scene.Director.ReplaceScene(s); } public void nextCallback(object pSender) { CCScene s = new MotionStreakTestScene(); s.AddChild(nextMotionAction()); Scene.Director.ReplaceScene(s); } public void backCallback(object pSender) { CCScene s = new MotionStreakTestScene(); s.AddChild(backMotionAction()); Scene.Director.ReplaceScene(s); } } }
412
0.914641
1
0.914641
game-dev
MEDIA
0.658745
game-dev,graphics-rendering
0.931334
1
0.931334
CalamityTeam/CalamityModPublic
3,071
CalPlayer/Dashes/PlaguebringerArmorDash.cs
using System; using CalamityMod.Enums; using CalamityMod.Items.Accessories; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.CalPlayer.Dashes { public class PlaguebringerArmorDash : PlayerDashEffect { public static new string ID => "Plaguebringer Armor"; public override DashCollisionType CollisionType => DashCollisionType.NoCollision; public override bool IsOmnidirectional => false; public override float CalculateDashSpeed(Player player) => 19f; public override void OnDashEffects(Player player) { // Spawn plague dust around the player's body. for (int d = 0; d < 60; d++) { Dust dust = Dust.NewDustDirect(player.position, player.width, player.height, DustID.GemEmerald, 0f, 0f, 100, default, 1.25f); dust.position.X += Main.rand.NextFloat(-5f, 5f); dust.position.Y += Main.rand.NextFloat(-5f, 5f); dust.velocity *= 0.2f; dust.scale *= Main.rand.NextFloat(1f, 1.2f); dust.shader = GameShaders.Armor.GetSecondaryShader(player.ArmorSetDye(), player); dust.noGravity = true; dust.fadeIn = 0.5f; } } public override void MidDashEffects(Player player, ref float dashSpeed, ref float dashSpeedDecelerationFactor, ref float runSpeedDecelerationFactor) { // Spawn plague dust around the player's body. for (int m = 0; m < 24; m++) { Dust plagueDashDust = Dust.NewDustDirect(new Vector2(player.position.X, player.position.Y + 4f), player.width, player.height - 8, DustID.GemEmerald, 0f, 0f, 100, default, 1f); plagueDashDust.velocity *= 0.1f; plagueDashDust.scale *= Main.rand.NextFloat(1f, 1.2f); plagueDashDust.shader = GameShaders.Armor.GetSecondaryShader(player.ArmorSetDye(), player); plagueDashDust.noGravity = true; if (Main.rand.NextBool()) plagueDashDust.fadeIn = 0.5f; } // Dash at a faster speed than the default value. dashSpeed = 12.5f; } public override void OnHitEffects(Player player, NPC npc, IEntitySource source, ref DashHitContext hitContext) { // Define hit context variables. int hitDirection = player.direction; if (player.velocity.X != 0f) hitDirection = Math.Sign(player.velocity.X); hitContext.HitDirection = hitDirection; hitContext.PlayerImmunityFrames = AsgardsValor.ShieldSlamIFrames; // Define damage parameters. int dashDamage = 50; hitContext.damageClass = DamageClass.Summon; hitContext.BaseDamage = player.ApplyArmorAccDamageBonusesTo(dashDamage); hitContext.BaseKnockback = 3f; } } }
412
0.759394
1
0.759394
game-dev
MEDIA
0.967856
game-dev
0.969575
1
0.969575
ralph-irving/squeezeplay
12,660
src/squeezeplay/share/jive/ui/Textarea.lua
--[[ =head1 NAME jive.ui.Textarea - A text area widget. =head1 DESCRIPTION A text area widget, extends L<jive.ui.Widget>. =head1 SYNOPSIS -- Create a new text area local textarea = jive.ui.Textarea("text", "This is some\ntext that spans\nseveral lines") -- Scroll the text down by 2 lines textarea:scroll(2) -- Set the text textarea:setValue("Different text") =head1 STYLE The Label includes the following style parameters in addition to the widgets basic parameters. =over B<bg> : the background color, defaults to no background color. B<fg> : the foreground color, defaults to black. B<bg_img> : the background image. B<font> : the text font, a L<jive.ui.Font> object. B<line_height> : the line height to use, defaults to the font ascend height. =back B<text_align> : the text alignment. =head1 METHODS =cut --]] -- stuff we use local _assert, string, tostring, type = _assert, string, tostring, type local oo = require("loop.simple") local string = require("string") local Widget = require("jive.ui.Widget") local Scrollbar = require("jive.ui.Scrollbar") local IRMenuAccel = require("jive.ui.IRMenuAccel") local Flick = require("jive.ui.Flick") local math = require("math") local log = require("jive.utils.log").logger("squeezeplay.ui") local EVENT_SCROLL = jive.ui.EVENT_SCROLL local EVENT_KEY_PRESS = jive.ui.EVENT_KEY_PRESS local EVENT_MOUSE_PRESS = jive.ui.EVENT_MOUSE_PRESS local EVENT_MOUSE_DOWN = jive.ui.EVENT_MOUSE_DOWN local EVENT_MOUSE_UP = jive.ui.EVENT_MOUSE_UP local EVENT_MOUSE_MOVE = jive.ui.EVENT_MOUSE_MOVE local EVENT_MOUSE_DRAG = jive.ui.EVENT_MOUSE_DRAG local EVENT_MOUSE_HOLD = jive.ui.EVENT_MOUSE_HOLD local EVENT_MOUSE_ALL = jive.ui.EVENT_MOUSE_ALL local EVENT_IR_DOWN = jive.ui.EVENT_IR_DOWN local EVENT_IR_REPEAT = jive.ui.EVENT_IR_REPEAT local EVENT_IR_HOLD = jive.ui.EVENT_IR_HOLD local EVENT_IR_PRESS = jive.ui.EVENT_IR_PRESS local EVENT_IR_UP = jive.ui.EVENT_IR_UP local EVENT_IR_ALL = jive.ui.EVENT_IR_ALL local EVENT_CONSUME = jive.ui.EVENT_CONSUME local EVENT_UNUSED = jive.ui.EVENT_UNUSED local ACTION = jive.ui.ACTION local KEY_FWD = jive.ui.KEY_FWD local KEY_REW = jive.ui.KEY_REW local KEY_GO = jive.ui.KEY_GO local KEY_BACK = jive.ui.KEY_BACK local KEY_UP = jive.ui.KEY_UP local KEY_DOWN = jive.ui.KEY_DOWN local KEY_LEFT = jive.ui.KEY_LEFT local KEY_RIGHT = jive.ui.KEY_RIGHT local KEY_PAGE_UP = jive.ui.KEY_PAGE_UP local KEY_PAGE_DOWN = jive.ui.KEY_PAGE_DOWN -- our class module(...) oo.class(_M, Widget) --[[ =head2 jive.ui.Textarea(style, text) Construct a new Textarea widget. I<style> is the widgets style. I<text> is the initial text displayed. =cut --]] function __init(self, style, text) _assert(type(style) == "string") _assert(type(text) ~= nil) local obj = oo.rawnew(self, Widget(style)) obj.scrollbar = Scrollbar("scrollbar", function(_, value) obj:_scrollTo(value) end) obj.scrollbar.parent = obj obj.dragOrigin = {} obj.dragYSinceShift = 0 obj.pixelOffsetY = 0 obj.pixelOffsetYHeaderWidget = 0 obj.currentShiftDirection = 0 obj.flick = Flick(obj) obj.topLine = 0 obj.visibleLines = 0 obj.text = text obj:addActionListener("page_up", obj, _pageUpAction) obj:addActionListener("page_down", obj, _pageDownAction) obj.irAccel = IRMenuAccel() obj.irAccel.onlyScrollByOne = true --up/down coming in as scroll events obj:addListener(EVENT_SCROLL | EVENT_MOUSE_ALL | EVENT_IR_DOWN | EVENT_IR_REPEAT, function (event) return obj:_eventHandler(event) end) return obj end function setPixelOffsetY(self, value) self.pixelOffsetY = value + self.pixelOffsetYHeaderWidget end --[[ =head2 jive.ui.Textarea:getText() Returns the text contained in this Textarea. =cut --]] function getText(self) return self.text end --[[ =head2 jive.ui.Textarea:setValue(text) Sets the text in the Textarea to I<text>. =cut --]] function setValue(self, text) local oldText = self.text if text ~= oldText then self.text = text self:invalidate() self:reLayout() end end function setHideScrollbar(self, setting) self.hideScrollbar = setting end function setIsMenuChild(self, setting) self.isMenuChild = setting end --[[ =head2 jive.ui.Textarea:isScrollable() Returns true if the textarea is scrollable, otherwise it returns false. =cut --]] function isScrollable(self) return true -- #self.items > self.visibleItems end function isTouchMouseEvent(self, mouseEvent) local x, y, fingerCount = mouseEvent:getMouse() return fingerCount ~= nil end function _pageUpAction(self) self:scrollBy( -(self.visibleLines - 1) ) end function _pageDownAction(self) self:scrollBy( self.visibleLines - 1 ) end --[[ =head2 jive.ui.Textarea:scrollBy(scroll) Scroll the Textarea by I<scroll> items. If I<scroll> is negative the text scrolls up, otherwise the text scrolls down. =cut --]] function scrollBy(self, scroll) _assert(type(scroll) == "number") self:_scrollTo(self.topLine + scroll) end function _scrollTo(self, topLine) if topLine < 0 then topLine = 0 end if topLine + self.visibleLines > self.numLines then topLine = self.numLines - self.visibleLines end self.topLine = topLine self.scrollbar:setScrollbar(0, self.numLines, self.topLine + 1, self.visibleLines) self:reDraw() end function _eventHandler(self, event) local type = event:getType() if type == EVENT_SCROLL then self:scrollBy(event:getScroll()) return EVENT_CONSUME end if type == EVENT_IR_DOWN or type == EVENT_IR_REPEAT then --todo add lock cancelling like in key press - let action hanlding take care of this if event:isIRCode("arrow_up") or event:isIRCode("arrow_down") then self:scrollBy(self.irAccel:event(event, self.topLine + 1, self.topLine + 1, 1, self.visibleLines)) return EVENT_CONSUME end end if type == EVENT_MOUSE_PRESS or type == EVENT_MOUSE_HOLD or type == EVENT_MOUSE_MOVE then --no special handling, consume return EVENT_CONSUME end if type == EVENT_MOUSE_DOWN then --sometimes up doesn't occur so we must again try to reset state -- note: sometimes down isn't called either (if drag starts outside of bounds), so bug still exists where scrollbar drag falsely continues self.sliderDragInProgress = false self.bodyDragInProgress = false --stop any running flick on contact if self.flick.flickTimer:isRunning() then self.flick:stopFlick(true) return EVENT_CONSUME end end if type == EVENT_MOUSE_DRAG or type == EVENT_MOUSE_DOWN then if self.scrollbar:mouseInside(event) or (self.sliderDragInProgress and evtype ~= EVENT_MOUSE_DOWN ) then self.sliderDragInProgress = true --zero out offset (scrollbar currently only moves discretely) self:setPixelOffsetY(0) return self.scrollbar:_event(event) else --mouse is inside textarea body if false and not self:isTouchMouseEvent(event) then --disabling regular desktop mouse behavior - favoring drag style for now -- return self.scrollbar:_event(event) else --touchpad if type == EVENT_MOUSE_DOWN then self.dragOrigin.x, self.dragOrigin.y = event:getMouse(); self.currentShiftDirection = 0 self.flick:resetFlickData() self.flick:updateFlickData(event) else -- type == EVENT_MOUSE_DRAG if ( self.dragOrigin.y == nil) then --might have started drag outside of this textarea's bounds, so reset origin self.dragOrigin.x, self.dragOrigin.y = event:getMouse(); end local mouseX, mouseY = event:getMouse() local dragAmountY = self.dragOrigin.y - mouseY --reset origin self.dragOrigin.x, self.dragOrigin.y = mouseX, mouseY self.flick:updateFlickData(event) self:handleDrag(dragAmountY) end end end return EVENT_CONSUME end if type == EVENT_MOUSE_UP then if self.sliderDragInProgress then return self.scrollbar:_event(event) end self.dragOrigin.x, self.dragOrigin.y = nil, nil --Hmm, possible bug, itemHeight is always nil!?! supposed to be lineHeight? local flickSpeed, flickDirection = self.flick:getFlickSpeed(self.itemHeight) if flickSpeed then self.flick:flick(flickSpeed, flickDirection) end self.flick:resetFlickData() self.sliderDragInProgress = false self.bodyDragInProgress = false return EVENT_CONSUME end return EVENT_UNUSED end function resetDragData(self) self:setPixelOffsetY(0) self.dragYSinceShift = 0 end function handleDrag(self, dragAmountY, byItemOnly) if dragAmountY ~= 0 then -- log:error("handleDrag dragAmountY: ", dragAmountY ) self.dragYSinceShift = self.dragYSinceShift + dragAmountY -- log:error("handleDrag dragYSinceShift: ", self.dragYSinceShift ) if (self.dragYSinceShift > 0 and math.floor(self.dragYSinceShift / self.lineHeight) > 0) or (self.dragYSinceShift < 0 and math.floor(self.dragYSinceShift / self.lineHeight) < 0) then local itemShift = math.floor(self.dragYSinceShift / self.lineHeight) self.dragYSinceShift = self.dragYSinceShift % self.lineHeight if not byItemOnly then self:setPixelOffsetY(-1 * self.dragYSinceShift) else --by item only so fix the position so that the top item is visible in the same spot each time self:setPixelOffsetY(0) end if itemShift > 0 and self.currentShiftDirection <= 0 then self.currentShiftDirection = 1 elseif itemShift < 0 and self.currentShiftDirection >= 0 then self.currentShiftDirection = -1 end log:debug("self:scrollBy( itemShift ) ", itemShift, " self.pixelOffsetY: ", self.pixelOffsetY ) self:scrollBy( itemShift) if self:isAtTop() or self:isAtBottom() then self:resetDragData() end else --smooth scroll if not byItemOnly then self:setPixelOffsetY(-1 * self.dragYSinceShift) end if self:isAtBottom() then self:resetDragData() end log:debug("Scroll offset by: ", self.pixelOffsetY, " item height: ", self.lineHeight) --todo: update scrollbar -- self:_updateScrollbar() self:reDraw() end end end function handleMenuHeaderWidgetScrollBy(self, scroll, menu) local selectedBefore = menu.selected or 1 local endItemIndex = menu.topItem + menu.numWidgets - 1 local endItem = menu:getItem(endItemIndex) if menu:getItem(selectedBefore).isHeaderItem then if scroll > 0 then if menu.currentShiftDirection <= 0 then --changing shift direction, move cursor so scroll wil occur menu.currentShiftDirection = 1 local selectedAfter = menu.topItem + menu.numWidgets - 1 if selectedAfter > menu.virtualItemCount then --shift to the first real menu item if it is onscreen selectedAfter = menu.virtualItemCount end menu.selected = selectedAfter menu:_scrollList() menu:reLayout() end --first item might be on screen jump to it --continuing down selectedAfter = menu.topItem + menu.numWidgets - 1 if selectedAfter == menu.virtualItemCount + 1 then --shift to the first real menu item when it becomes onscreen selectedAfter = menu.virtualItemCount menu.selected = selectedAfter + 1 menu:_scrollList() menu:reLayout() end elseif scroll < 0 then if menu.currentShiftDirection >= 0 then --changing shift direction, move cursor so scroll wil occur menu.currentShiftDirection = -1 menu.selected = menu.topItem menu:_scrollList() menu:reLayout() end if (menu.virtualItemCount < menu.numWidgets - 1 or menu:numItems() <= menu.numWidgets) and menu.topItem == 1 then --textarea not scrollable, so don't enter it menu.selected = menu.topItem + menu.virtualItemCount menu:_scrollList() menu:reLayout() elseif menu.topItem == 1 and menu:numItems() > menu.numWidgets and menu.virtualItemCount < menu.numWidgets - 1 then --textarea brought back on, and is not longer than a screen --so highlight first real item menu.selected = menu.topItem + menu.virtualItemCount menu:_scrollList() menu:reLayout() end end end local itemShift = menu.topItem -1 self.pixelOffsetYHeaderWidget = -1 * itemShift * menu.itemHeight --adjust temporarily to parent while shift is occurring self:setPixelOffsetY(menu.pixelOffsetY) self:reDraw() end --required functions for Drag module function isAtBottom(self) return (self.topLine + self.visibleLines >= self.numLines) end function isAtTop(self) return self.topLine == 0 end function __tostring(self) return "Textarea(" .. string.sub(tostring(self.text), 1, 20) .."...)" end --[[ =head1 LICENSE Copyright 2010 Logitech. All Rights Reserved. This file is licensed under BSD. Please see the LICENSE file for details. =cut --]]
412
0.924559
1
0.924559
game-dev
MEDIA
0.479157
game-dev
0.986364
1
0.986364
BlueMonk1107/UGUISolution
27,073
Assets/Plugins/XCharts/Scripts/UI/Internal/BaseChart.cs
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System; using UnityEngine.EventSystems; namespace XCharts { public enum Orient { Horizonal, Vertical } public class BaseChart : Graphic, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IScrollHandler { private static readonly string s_TitleObjectName = "title"; private static readonly string s_LegendObjectName = "legend"; [SerializeField] protected float m_ChartWidth; [SerializeField] protected float m_ChartHeight; [SerializeField] protected ThemeInfo m_ThemeInfo; [SerializeField] protected Title m_Title = Title.defaultTitle; [SerializeField] protected Legend m_Legend = Legend.defaultLegend; [SerializeField] protected Tooltip m_Tooltip = Tooltip.defaultTooltip; [SerializeField] protected Series m_Series = Series.defaultSeries; [SerializeField] protected float m_Large = 1; [SerializeField] protected int m_MinShowDataNumber; [SerializeField] protected int m_MaxShowDataNumber; [SerializeField] protected int m_MaxCacheDataNumber; [NonSerialized] private Theme m_CheckTheme = 0; [NonSerialized] private Title m_CheckTitle = Title.defaultTitle; [NonSerialized] private Legend m_CheckLegend = Legend.defaultLegend; [NonSerialized] private float m_CheckWidth = 0; [NonSerialized] private float m_CheckHeight = 0; [NonSerialized] private float m_CheckSerieCount = 0; [NonSerialized] private List<string> m_CheckSerieName = new List<string>(); [NonSerialized] private bool m_RefreshChart = false; protected Vector2 chartAnchorMax { get { return rectTransform.anchorMax; } } protected Vector2 chartAnchorMin { get { return rectTransform.anchorMin; } } protected Vector2 chartPivot { get { return rectTransform.pivot; } } public Title title { get { return m_Title; } } public Legend legend { get { return m_Legend; } } public Tooltip tooltip { get { return m_Tooltip; } } public Series series { get { return m_Series; } } public float chartWidth { get { return m_ChartWidth; } } public float chartHeight { get { return m_ChartHeight; } } /// <summary> /// The min number of data to show in chart. /// </summary> public int minShowDataNumber { get { return m_MinShowDataNumber; } set { m_MinShowDataNumber = value; if (m_MinShowDataNumber < 0) m_MinShowDataNumber = 0; } } /// <summary> /// The max number of data to show in chart. /// </summary> public int maxShowDataNumber { get { return m_MaxShowDataNumber; } set { m_MaxShowDataNumber = value; if (m_MaxShowDataNumber < 0) m_MaxShowDataNumber = 0; } } /// <summary> /// The max number of serie and axis data cache. /// The first data will be remove when the size of serie and axis data is larger then maxCacheDataNumber. /// default:0,unlimited. /// </summary> public int maxCacheDataNumber { get { return m_MaxCacheDataNumber; } set { m_MaxCacheDataNumber = value; if (m_MaxCacheDataNumber < 0) m_MaxCacheDataNumber = 0; } } /// <summary> /// Set the size of chart. /// </summary> /// <param name="width">width</param> /// <param name="height">height</param> public virtual void SetSize(float width, float height) { m_ChartWidth = width; m_ChartHeight = height; m_CheckWidth = width; m_CheckHeight = height; rectTransform.sizeDelta = new Vector2(m_ChartWidth, m_ChartHeight); OnSizeChanged(); } /// <summary> /// Remove all series and legend data. /// It just emptying all of serie's data without emptying the list of series. /// </summary> public virtual void ClearData() { m_Series.ClearData(); m_Legend.ClearData(); RefreshChart(); } /// <summary> /// Remove legend and serie by name. /// </summary> /// <param name="serieName">the name of serie</param> public virtual void RemoveData(string serieName) { m_Series.Remove(serieName); m_Legend.RemoveData(serieName); RefreshChart(); } /// <summary> /// Remove all data from series and legend. /// The series list is also cleared. /// </summary> public virtual void RemoveData() { m_Legend.ClearData(); m_Series.RemoveAll(); RefreshChart(); } /// <summary> /// Add a serie to serie list. /// </summary> /// <param name="serieName">the name of serie</param> /// <param name="type">the type of serie</param> /// <param name="show">whether to show this serie</param> /// <returns>the added serie</returns> public virtual Serie AddSerie(string serieName, SerieType type, bool show = true) { m_Legend.AddData(serieName); return m_Series.AddSerie(serieName, type); } /// <summary> /// Add a data to serie. /// When serie doesn't exist, the data is ignored. /// If serieName doesn't exist in legend,will be add to legend. /// </summary> /// <param name="serieName">the name of serie</param> /// <param name="value">the data to add</param> /// <returns>Returns True on success</returns> public virtual bool AddData(string serieName, float value) { m_Legend.AddData(serieName); var success = m_Series.AddData(serieName, value, m_MaxCacheDataNumber); if (success) RefreshChart(); return success; } /// <summary> /// Add a data to serie. /// When serie doesn't exist, the data is ignored. /// </summary> /// <param name="serieIndex">the index of serie</param> /// <param name="value">the data to add</param> /// <returns>Returns True on success</returns> public virtual bool AddData(int serieIndex, float value) { var success = m_Series.AddData(serieIndex, value, m_MaxCacheDataNumber); if (success) RefreshChart(); return success; } /// <summary> /// Add a (x,y) data to serie. /// When serie doesn't exist, the data is ignored. /// </summary> /// <param name="serieName">the name of serie</param> /// <param name="xValue">x data</param> /// <param name="yValue">y data</param> /// <returns>Returns True on success</returns> public virtual bool AddXYData(string serieName, float xValue, float yValue) { var success = m_Series.AddXYData(serieName, xValue, yValue, m_MaxCacheDataNumber); if (success) RefreshChart(); return true; } /// <summary> /// Add a (x,y) data to serie. /// When serie doesn't exist, the data is ignored. /// </summary> /// <param name="serieIndex">the index of serie</param> /// <param name="xValue">x data</param> /// <param name="yValue">y data</param> /// <returns>Returns True on success</returns> public virtual bool AddXYData(int serieIndex, float xValue, float yValue) { var success = m_Series.AddXYData(serieIndex, xValue, yValue, m_MaxCacheDataNumber); if (success) RefreshChart(); return success; } /// <summary> /// Update serie data by serie name. /// </summary> /// <param name="serieName">the name of serie</param> /// <param name="value">the data will be update</param> /// <param name="dataIndex">the index of data</param> public virtual void UpdateData(string serieName, float value, int dataIndex = 0) { m_Series.UpdateData(serieName, value, dataIndex); RefreshChart(); } /// <summary> /// Update serie data by serie index. /// </summary> /// <param name="serieIndex">the index of serie</param> /// <param name="value">the data will be update</param> /// <param name="dataIndex">the index of data</param> public virtual void UpdateData(int serieIndex, float value, int dataIndex = 0) { m_Series.UpdateData(serieIndex, value, dataIndex); RefreshChart(); } /// <summary> /// Whether to show serie and legend. /// </summary> /// <param name="serieName">the name of serie</param> /// <param name="active">Active or not</param> public virtual void SetActive(string serieName, bool active) { var serie = m_Series.GetSerie(serieName); if (serie != null) { SetActive(serie.index, active); } } /// <summary> /// Whether to show serie and legend. /// </summary> /// <param name="serieIndex">the index of serie</param> /// <param name="active">Active or not</param> public virtual void SetActive(int serieIndex, bool active) { m_Series.SetActive(serieIndex, active); var serie = m_Series.GetSerie(serieIndex); if (serie != null && !string.IsNullOrEmpty(serie.name)) { var bgColor1 = active ? m_ThemeInfo.GetColor(serie.index) : m_ThemeInfo.legendUnableColor; m_Legend.UpdateButtonColor(serie.name, bgColor1); } } /// <summary> /// Whether serie is activated. /// </summary> /// <param name="serieName">the name of serie</param> /// <returns>True when activated</returns> public virtual bool IsActive(string serieName) { return m_Series.IsActive(serieName); } /// <summary> /// Whether serie is activated. /// </summary> /// <param name="serieIndex">the index of serie</param> /// <returns>True when activated</returns> public virtual bool IsActive(int serieIndex) { return m_Series.IsActive(serieIndex); } /// <summary> /// Redraw chart next frame. /// </summary> public void RefreshChart() { m_RefreshChart = true; } /// <summary> /// Update chart theme /// </summary> /// <param name="theme">theme</param> public void UpdateTheme(Theme theme) { m_ThemeInfo.theme = theme; OnThemeChanged(); RefreshChart(); } protected override void Awake() { if (m_ThemeInfo == null) { m_ThemeInfo = ThemeInfo.Default; } raycastTarget = false; rectTransform.anchorMax = Vector2.zero; rectTransform.anchorMin = Vector2.zero; rectTransform.pivot = Vector2.zero; m_ChartWidth = rectTransform.sizeDelta.x; m_ChartHeight = rectTransform.sizeDelta.y; m_CheckWidth = m_ChartWidth; m_CheckHeight = m_ChartHeight; m_CheckTheme = m_ThemeInfo.theme; InitTitle(); InitLegend(); InitTooltip(); } protected virtual void Update() { CheckSize(); CheckTheme(); CheckTile(); CheckLegend(); CheckTooltip(); CheckRefreshChart(); } protected override void OnEnable() { base.OnEnable(); Awake(); } protected override void OnDisable() { base.OnDisable(); ChartHelper.DestoryAllChilds(transform); } #if UNITY_EDITOR protected override void Reset() { var sizeDelta = rectTransform.sizeDelta; if (sizeDelta.x < 580 && sizeDelta.y < 300) { rectTransform.sizeDelta = new Vector2(580, 300); } ChartHelper.DestoryAllChilds(transform); m_ThemeInfo = ThemeInfo.Default; m_Title = Title.defaultTitle; m_Legend = Legend.defaultLegend; m_Tooltip = Tooltip.defaultTooltip; m_Series = Series.defaultSeries; Awake(); } #endif protected override void OnDestroy() { for (int i = transform.childCount - 1; i >= 0; i--) { DestroyImmediate(transform.GetChild(i).gameObject); } } private void InitTitle() { m_Title.OnChanged(); TextAnchor anchor = m_Title.location.textAnchor; Vector2 anchorMin = m_Title.location.anchorMin; Vector2 anchorMax = m_Title.location.anchorMax; Vector2 pivot = m_Title.location.pivot; Vector3 titlePosition = m_Title.location.GetPosition(chartWidth, chartHeight); Vector3 subTitlePosition = -new Vector3(0, m_Title.textFontSize + m_Title.itemGap, 0); float titleWid = chartWidth; var titleObject = ChartHelper.AddObject(s_TitleObjectName, transform, anchorMin, anchorMax, pivot, new Vector2(chartWidth, chartHeight)); titleObject.transform.localPosition = titlePosition; ChartHelper.HideAllObject(titleObject, s_TitleObjectName); Text titleText = ChartHelper.AddTextObject(s_TitleObjectName, titleObject.transform, m_ThemeInfo.font, m_ThemeInfo.textColor, anchor, anchorMin, anchorMax, pivot, new Vector2(titleWid, m_Title.textFontSize), m_Title.textFontSize); titleText.alignment = anchor; titleText.gameObject.SetActive(m_Title.show); titleText.transform.localPosition = Vector2.zero; titleText.text = m_Title.text; Text subText = ChartHelper.AddTextObject(s_TitleObjectName + "_sub", titleObject.transform, m_ThemeInfo.font, m_ThemeInfo.textColor, anchor, anchorMin, anchorMax, pivot, new Vector2(titleWid, m_Title.subTextFontSize), m_Title.subTextFontSize); subText.alignment = anchor; subText.gameObject.SetActive(m_Title.show && !string.IsNullOrEmpty(m_Title.subText)); subText.transform.localPosition = subTitlePosition; subText.text = m_Title.subText; } private void InitLegend() { m_Legend.OnChanged(); ChartHelper.HideAllObject(transform, s_LegendObjectName); TextAnchor anchor = m_Legend.location.textAnchor; Vector2 anchorMin = m_Legend.location.anchorMin; Vector2 anchorMax = m_Legend.location.anchorMax; Vector2 pivot = m_Legend.location.pivot; var legendObject = ChartHelper.AddObject(s_LegendObjectName, transform, anchorMin, anchorMax, pivot, new Vector2(chartWidth, chartHeight)); legendObject.transform.localPosition = m_Legend.location.GetPosition(chartWidth, chartHeight); ChartHelper.HideAllObject(legendObject, s_LegendObjectName); var serieNameList = m_Series.GetSerieNameList(); List<string> datas; if (m_Legend.data.Count > 0) { datas = new List<string>(); for (int i = 0; i < m_Legend.data.Count; i++) { var category = m_Legend.data[i]; if (serieNameList.Contains(category)) datas.Add(category); } } else { datas = serieNameList; } m_Legend.RemoveButton(); for (int i = 0; i < datas.Count; i++) { string legendName = datas[i]; Button btn = ChartHelper.AddButtonObject(s_LegendObjectName + "_" + legendName, legendObject.transform, m_ThemeInfo.font, m_Legend.itemFontSize, m_ThemeInfo.legendTextColor, anchor, anchorMin, anchorMax, pivot, new Vector2(m_Legend.itemWidth, m_Legend.itemHeight)); var bgColor = IsActive(legendName) ? m_ThemeInfo.GetColor(i) : m_ThemeInfo.legendUnableColor; m_Legend.SetButton(legendName, btn, datas.Count); m_Legend.UpdateButtonColor(legendName, bgColor); btn.GetComponentInChildren<Text>().text = legendName; ChartHelper.AddEventListener(btn.gameObject, EventTriggerType.PointerDown, (data) => { if (data.selectedObject == null) return; string selectedName = data.selectedObject.name.Split('_')[1]; foreach (var serie in m_Series.GetSeries(selectedName)) { SetActive(serie.index, !serie.show); } OnYMaxValueChanged(); OnLegendButtonClicked(); RefreshChart(); }); } } private void InitTooltip() { var tooltipObject = ChartHelper.AddObject("tooltip", transform, chartAnchorMin, chartAnchorMax, chartPivot, new Vector2(chartWidth, chartHeight)); tooltipObject.transform.localPosition = Vector3.zero; DestroyImmediate(tooltipObject.GetComponent<Image>()); var parent = tooltipObject.transform; ChartHelper.HideAllObject(tooltipObject.transform); GameObject content = ChartHelper.AddTooltipContent("content", parent, m_ThemeInfo.font); m_Tooltip.SetObj(tooltipObject); m_Tooltip.SetContentObj(content); m_Tooltip.SetContentBackgroundColor(m_ThemeInfo.tooltipBackgroundColor); m_Tooltip.SetContentTextColor(m_ThemeInfo.tooltipTextColor); m_Tooltip.SetActive(false); } private Vector3 GetLegendPosition(int i) { return m_Legend.location.GetPosition(chartWidth, chartHeight); } protected float GetMaxValue(int index) { return m_Series.GetMaxValue(index); } private void CheckSize() { if (m_CheckWidth != chartWidth || m_CheckHeight != chartHeight) { SetSize(chartWidth, chartHeight); } var sizeDelta = rectTransform.sizeDelta; if (m_CheckWidth != sizeDelta.x || m_CheckHeight != sizeDelta.y) { SetSize(sizeDelta.x, sizeDelta.y); } } private void CheckTheme() { if (m_CheckTheme != m_ThemeInfo.theme) { m_CheckTheme = m_ThemeInfo.theme; OnThemeChanged(); } } private void CheckTile() { if (!m_CheckTitle.Equals(m_Title)) { m_CheckTitle.Copy(m_Title); OnTitleChanged(); } } private void CheckLegend() { if (m_CheckLegend != m_Legend) { m_CheckLegend.Copy(m_Legend); OnLegendChanged(); } else if (m_Legend.show) { if (m_CheckSerieCount != m_Series.Count) { m_CheckSerieCount = m_Series.Count; m_CheckSerieName.Clear(); var serieNames = m_Series.GetSerieNameList(); foreach (var name in serieNames) m_CheckSerieName.Add(name); OnLegendChanged(); } else if (!ChartHelper.IsValueEqualsList(m_CheckSerieName, m_Series.GetSerieNameList())) { var serieNames = m_Series.GetSerieNameList(); foreach (var name in serieNames) m_CheckSerieName.Add(name); OnLegendChanged(); } } } private void CheckTooltip() { if (!m_Tooltip.show || !m_Tooltip.isInited) { if (m_Tooltip.dataIndex[0] != 0 || m_Tooltip.dataIndex[1] != 0) { m_Tooltip.dataIndex[0] = m_Tooltip.dataIndex[1] = -1; m_Tooltip.SetActive(false); RefreshChart(); } return; } m_Tooltip.dataIndex[0] = m_Tooltip.dataIndex[1] = -1; Vector2 local; if (canvas == null) return; if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, canvas.worldCamera, out local)) { m_Tooltip.SetActive(false); RefreshChart(); return; } if (local.x < 0 || local.x > chartWidth || local.y < 0 || local.y > chartHeight) { m_Tooltip.SetActive(false); RefreshChart(); return; } m_Tooltip.pointerPos = local; CheckTootipArea(local); } protected virtual void CheckTootipArea(Vector2 localPostion) { } protected void CheckRefreshChart() { if (m_RefreshChart) { int tempWid = (int)chartWidth; rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, tempWid - 1); rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, tempWid); m_RefreshChart = false; } } protected virtual void OnSizeChanged() { InitTitle(); InitLegend(); InitTooltip(); } protected virtual void OnThemeChanged() { switch (m_ThemeInfo.theme) { case Theme.Dark: m_ThemeInfo.Copy(ThemeInfo.Dark); break; case Theme.Default: m_ThemeInfo.Copy(ThemeInfo.Default); break; case Theme.Light: m_ThemeInfo.Copy(ThemeInfo.Light); break; } InitTitle(); InitLegend(); InitTooltip(); } protected virtual void OnTitleChanged() { InitTitle(); } protected virtual void OnLegendChanged() { InitLegend(); } protected virtual void OnYMaxValueChanged() { } protected virtual void OnLegendButtonClicked() { } protected virtual void RefreshTooltip() { } protected override void OnPopulateMesh(VertexHelper vh) { vh.Clear(); DrawBackground(vh); DrawChart(vh); DrawTooltip(vh); } protected virtual void DrawChart(VertexHelper vh) { } protected virtual void DrawTooltip(VertexHelper vh) { } private void DrawBackground(VertexHelper vh) { // draw bg Vector3 p1 = new Vector3(0, chartHeight); Vector3 p2 = new Vector3(chartWidth, chartHeight); Vector3 p3 = new Vector3(chartWidth, 0); Vector3 p4 = new Vector3(0, 0); ChartHelper.DrawPolygon(vh, p1, p2, p3, p4, m_ThemeInfo.backgroundColor); } protected void DrawSymbol(VertexHelper vh, SerieSymbolType type, float symbolSize, float tickness, Vector3 pos, Color color) { switch (type) { case SerieSymbolType.None: break; case SerieSymbolType.Circle: ChartHelper.DrawCricle(vh, pos, symbolSize, color, GetSymbolCricleSegment(symbolSize)); break; case SerieSymbolType.EmptyCircle: int segment = GetSymbolCricleSegment(symbolSize); ChartHelper.DrawCricle(vh, pos, symbolSize, m_ThemeInfo.backgroundColor, segment); ChartHelper.DrawDoughnut(vh, pos, symbolSize - tickness, symbolSize, 0, 360, color, segment); break; case SerieSymbolType.Rect: ChartHelper.DrawPolygon(vh, pos, symbolSize, color); break; case SerieSymbolType.Triangle: var x = symbolSize * Mathf.Cos(30 * Mathf.PI / 180); var y = symbolSize * Mathf.Sin(30 * Mathf.PI / 180); var p1 = new Vector2(pos.x - x, pos.y - y); var p2 = new Vector2(pos.x, pos.y + symbolSize); var p3 = new Vector2(pos.x + x, pos.y - y); ChartHelper.DrawTriangle(vh, p1, p2, p3, color); break; case SerieSymbolType.Diamond: p1 = new Vector2(pos.x - symbolSize, pos.y); p2 = new Vector2(pos.x, pos.y + symbolSize); p3 = new Vector2(pos.x + symbolSize, pos.y); var p4 = new Vector2(pos.x, pos.y - symbolSize); ChartHelper.DrawPolygon(vh, p1, p2, p3, p4, color); break; } } private int GetSymbolCricleSegment(float radiu) { int max = 50; int segent = (int)(2 * Mathf.PI * radiu / ChartHelper.CRICLE_SMOOTHNESS); if (segent > max) segent = max; segent = (int)(segent / (1 + (m_Large - 1) / 10)); return segent; } public virtual void OnPointerDown(PointerEventData eventData) { } public virtual void OnPointerUp(PointerEventData eventData) { } public virtual void OnPointerEnter(PointerEventData eventData) { } public virtual void OnPointerExit(PointerEventData eventData) { } public virtual void OnBeginDrag(PointerEventData eventData) { } public virtual void OnEndDrag(PointerEventData eventData) { } public virtual void OnDrag(PointerEventData eventData) { } public virtual void OnScroll(PointerEventData eventData) { } } }
412
0.988412
1
0.988412
game-dev
MEDIA
0.589427
game-dev
0.905109
1
0.905109
Shinoow/AbyssalCraft
7,359
src/main/java/com/shinoow/abyssalcraft/client/render/entity/layers/LayerEvilSheepWool.java
/******************************************************************************* * AbyssalCraft * Copyright (c) 2012 - 2025 Shinoow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Contributors: * Shinoow - implementation ******************************************************************************/ package com.shinoow.abyssalcraft.client.render.entity.layers; import java.util.HashMap; import java.util.Map; import com.google.common.collect.Iterables; import com.mojang.authlib.GameProfile; import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.properties.Property; import com.shinoow.abyssalcraft.client.model.entity.ModelEvilSheep1; import com.shinoow.abyssalcraft.client.render.entity.RenderEvilSheep; import com.shinoow.abyssalcraft.common.entity.demon.EntityEvilSheep; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.layers.LayerRenderer; import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class LayerEvilSheepWool implements LayerRenderer<EntityEvilSheep> { private static final ResourceLocation TEXTURE = new ResourceLocation("textures/entity/sheep/sheep_fur.png"); private final RenderEvilSheep sheepRenderer; private final ModelEvilSheep1 sheepModel = new ModelEvilSheep1(); private final Map<GameProfile, GameProfile> checkedProfiles = new HashMap<>(); public LayerEvilSheepWool(RenderEvilSheep sheepRendererIn) { sheepRenderer = sheepRendererIn; } /* * Player skin fetching code borrowed from https://github.com/CyclopsMC/EvilCraft/blob/master-1.9/src/main/java/org/cyclops/evilcraft/client/render/entity/RenderVengeanceSpirit.java */ @Override public void doRenderLayer(EntityEvilSheep entitylivingbaseIn, float p_177141_2_, float p_177141_3_, float partialTicks, float p_177141_5_, float p_177141_6_, float p_177141_7_, float scale) { if (!entitylivingbaseIn.isInvisible()) { if(entitylivingbaseIn.getKilledPlayerUUID() != null && entitylivingbaseIn.getKilledPlayerName() != null && entitylivingbaseIn.getKilledPlayerName().length() > 0){ setupModelStuff(); GameProfile gameProfile = new GameProfile(entitylivingbaseIn.getKilledPlayerUUID(), entitylivingbaseIn.getKilledPlayerName()); ResourceLocation resourcelocation = DefaultPlayerSkin.getDefaultSkin(entitylivingbaseIn.getKilledPlayerUUID()); Minecraft minecraft = Minecraft.getMinecraft(); // Check if we have loaded the (texturized) profile before, otherwise we load it and cache it. if(!checkedProfiles.containsKey(gameProfile)) { Property property = (Property) Iterables.getFirst(gameProfile.getProperties().get("textures"), (Object) null); if (property == null) { // The game profile enchanced with texture information. GameProfile newGameProfile = Minecraft.getMinecraft().getSessionService().fillProfileProperties(gameProfile, true); checkedProfiles.put(gameProfile, newGameProfile); } } else { Map map = minecraft.getSkinManager().loadSkinFromCache(checkedProfiles.get(gameProfile)); if (map.containsKey(MinecraftProfileTexture.Type.SKIN)) resourcelocation = minecraft.getSkinManager().loadSkin((MinecraftProfileTexture) map.get(MinecraftProfileTexture.Type.SKIN), MinecraftProfileTexture.Type.SKIN); } sheepRenderer.bindTexture(resourcelocation); }else { resetModelStuff(); sheepRenderer.bindTexture(TEXTURE); } if (entitylivingbaseIn.hasCustomName() && "jeb_".equals(entitylivingbaseIn.getCustomNameTag())) { int i = entitylivingbaseIn.ticksExisted / 25 + entitylivingbaseIn.getEntityId(); int j = EnumDyeColor.values().length; int k = i % j; int l = (i + 1) % j; float f = (entitylivingbaseIn.ticksExisted % 25 + partialTicks) / 25.0F; float[] afloat1 = EntitySheep.getDyeRgb(EnumDyeColor.byMetadata(k)); float[] afloat2 = EntitySheep.getDyeRgb(EnumDyeColor.byMetadata(l)); GlStateManager.color(afloat1[0] * (1.0F - f) + afloat2[0] * f, afloat1[1] * (1.0F - f) + afloat2[1] * f, afloat1[2] * (1.0F - f) + afloat2[2] * f); } sheepModel.setModelAttributes(sheepRenderer.getMainModel()); sheepModel.setLivingAnimations(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks); sheepModel.render(entitylivingbaseIn, p_177141_2_, p_177141_3_, p_177141_5_, p_177141_6_, p_177141_7_, scale); } } @Override public boolean shouldCombineTextures() { return true; } private void setupModelStuff(){ if(sheepModel.textureHeight != 64){ sheepModel.textureHeight = 64; sheepModel.head = new ModelRenderer(sheepModel, 2, 2); sheepModel.head.addBox(-3.0F, -4.0F, -4.0F, 6, 6, 6, 0.6F); sheepModel.head.setRotationPoint(0.0F, 6.0F, -8.0F); sheepModel.body = new ModelRenderer(sheepModel, 8, 10); sheepModel.body.addBox(-4.0F, -10.0F, -7.0F, 8, 16, 6, 1.75F); sheepModel.body.setRotationPoint(0.0F, 5.0F, 2.0F); sheepModel.leg1 = new ModelRenderer(sheepModel, 40, 16); sheepModel.leg1.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.5F); sheepModel.leg1.setRotationPoint(-3.0F, 12.0F, 7.0F); sheepModel.leg2 = new ModelRenderer(sheepModel, 40, 16); sheepModel.leg2.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.5F); sheepModel.leg2.setRotationPoint(3.0F, 12.0F, 7.0F); sheepModel.leg3 = new ModelRenderer(sheepModel, 40, 16); sheepModel.leg3.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.5F); sheepModel.leg3.setRotationPoint(-3.0F, 12.0F, -5.0F); sheepModel.leg4 = new ModelRenderer(sheepModel, 40, 16); sheepModel.leg4.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.5F); sheepModel.leg4.setRotationPoint(3.0F, 12.0F, -5.0F); } } private void resetModelStuff(){ if(sheepModel.textureHeight != 32){ sheepModel.textureHeight = 32; sheepModel.head = new ModelRenderer(sheepModel, 0, 0); sheepModel.head.addBox(-3.0F, -4.0F, -4.0F, 6, 6, 6, 0.6F); sheepModel.head.setRotationPoint(0.0F, 6.0F, -8.0F); sheepModel.body = new ModelRenderer(sheepModel, 28, 8); sheepModel.body.addBox(-4.0F, -10.0F, -7.0F, 8, 16, 6, 1.75F); sheepModel.body.setRotationPoint(0.0F, 5.0F, 2.0F); float f = 0.5F; sheepModel.leg1 = new ModelRenderer(sheepModel, 0, 16); sheepModel.leg1.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); sheepModel.leg1.setRotationPoint(-3.0F, 12.0F, 7.0F); sheepModel.leg2 = new ModelRenderer(sheepModel, 0, 16); sheepModel.leg2.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); sheepModel.leg2.setRotationPoint(3.0F, 12.0F, 7.0F); sheepModel.leg3 = new ModelRenderer(sheepModel, 0, 16); sheepModel.leg3.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); sheepModel.leg3.setRotationPoint(-3.0F, 12.0F, -5.0F); sheepModel.leg4 = new ModelRenderer(sheepModel, 0, 16); sheepModel.leg4.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, f); sheepModel.leg4.setRotationPoint(3.0F, 12.0F, -5.0F); } } }
412
0.738192
1
0.738192
game-dev
MEDIA
0.96929
game-dev
0.955075
1
0.955075
PacktPublishing/Pragmatic-Microservices-with-CSharp-and-Azure
2,069
ch08/Codebreaker.GameAPIs.KiotaClient/codebreaker/Models/Game_fieldValues.cs
// <auto-generated/> using Microsoft.Kiota.Abstractions.Serialization; using System.Collections.Generic; using System.IO; using System.Linq; using System; namespace Codebreaker.Client.Models { public class Game_fieldValues : IAdditionalDataHolder, IParsable { /// <summary>Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.</summary> public IDictionary<string, object> AdditionalData { get; set; } /// <summary> /// Instantiates a new <see cref="Game_fieldValues"/> and sets the default values. /// </summary> public Game_fieldValues() { AdditionalData = new Dictionary<string, object>(); } /// <summary> /// Creates a new instance of the appropriate class based on discriminator value /// </summary> /// <returns>A <see cref="Game_fieldValues"/></returns> /// <param name="parseNode">The parse node to use to read the discriminator value and create the object</param> public static Game_fieldValues CreateFromDiscriminatorValue(IParseNode parseNode) { _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode)); return new Game_fieldValues(); } /// <summary> /// The deserialization information for the current model /// </summary> /// <returns>A IDictionary&lt;string, Action&lt;IParseNode&gt;&gt;</returns> public virtual IDictionary<string, Action<IParseNode>> GetFieldDeserializers() { return new Dictionary<string, Action<IParseNode>> { }; } /// <summary> /// Serializes information the current object /// </summary> /// <param name="writer">Serialization writer to use to serialize this model</param> public virtual void Serialize(ISerializationWriter writer) { _ = writer ?? throw new ArgumentNullException(nameof(writer)); writer.WriteAdditionalData(AdditionalData); } } }
412
0.742285
1
0.742285
game-dev
MEDIA
0.77715
game-dev
0.636966
1
0.636966
tgstation/tgstation
13,538
code/modules/shuttle/misc/special.dm
// Special objects for shuttle templates go here if nowhere else // Wabbajack statue, a sleeping frog statue that shoots bolts of change if // living carbons are put on its altar/tables /obj/machinery/power/emitter/energycannon name = "Energy Cannon" desc = "A heavy duty industrial laser." icon = 'icons/obj/machines/engine/singularity.dmi' icon_state = "emitter_+a" base_icon_state = "emitter_+a" anchored = TRUE density = TRUE resistance_flags = INDESTRUCTIBLE | FIRE_PROOF | ACID_PROOF use_power = NO_POWER_USE idle_power_usage = 0 active_power_usage = 0 active = TRUE locked = TRUE welded = TRUE /obj/machinery/power/emitter/energycannon/RefreshParts() SHOULD_CALL_PARENT(FALSE) return /obj/machinery/power/emitter/energycannon/magical name = "wabbajack statue" desc = "Who am I? What is my purpose in life? What do I mean by who am I?" projectile_type = /obj/projectile/magic/change icon = 'icons/obj/machines/magic_emitter.dmi' icon_state = "wabbajack_statue" icon_state_on = "wabbajack_statue_on" base_icon_state = "wabbajack_statue" active = FALSE allow_switch_interact = FALSE var/list/active_tables = list() var/tables_required = 2 /obj/machinery/power/emitter/energycannon/magical/Initialize(mapload) . = ..() if(prob(50)) desc = "Oh no, not again." update_appearance() /obj/machinery/power/emitter/energycannon/magical/update_icon_state() . = ..() icon_state = active ? icon_state_on : initial(icon_state) /obj/machinery/power/emitter/energycannon/magical/process_early(seconds_per_tick) . = ..() if(active_tables.len >= tables_required) if(!active) visible_message("<span class='revenboldnotice'>\ [src] opens its eyes.</span>") active = TRUE else if(active) visible_message("<span class='revenboldnotice'>\ [src] closes its eyes.</span>") active = FALSE update_appearance() /obj/machinery/power/emitter/energycannon/magical/attackby(obj/item/W, mob/user, list/modifiers, list/attack_modifiers) return /obj/machinery/power/emitter/energycannon/magical/ex_act(severity) return FALSE /obj/machinery/power/emitter/energycannon/magical/emag_act(mob/user, obj/item/card/emag/emag_card) return FALSE /obj/structure/table/abductor/wabbajack name = "wabbajack altar" desc = "Whether you're sleeping or waking, it's going to be quite chaotic." max_integrity = 1000 verb_say = "chants" var/obj/machinery/power/emitter/energycannon/magical/our_statue var/list/mob/living/sleepers = list() var/never_spoken = TRUE /obj/structure/table/abductor/wabbajack/Initialize(mapload, obj/structure/table_frame/frame_used, obj/item/stack/stack_used) . = ..() START_PROCESSING(SSobj, src) /obj/structure/table/abductor/wabbajack/Destroy() STOP_PROCESSING(SSobj, src) . = ..() /obj/structure/table/abductor/wabbajack/screwdriver_act(mob/living/user, obj/item/tool) return NONE /obj/structure/table/abductor/wabbajack/wrench_act(mob/living/user, obj/item/tool) return NONE /obj/structure/table/abductor/wabbajack/process() if(isnull(our_statue)) our_statue = locate() in orange(4, src) if(isnull(our_statue)) name = "inert [initial(name)]" return name = initial(name) var/turf/T = get_turf(src) var/list/found = list() for(var/mob/living/carbon/C in T) if(C.stat != DEAD) found += C // New sleepers for(var/i in found - sleepers) var/mob/living/L = i L.add_atom_colour(COLOR_PURPLE, TEMPORARY_COLOUR_PRIORITY) L.visible_message(span_revennotice("A strange purple glow wraps itself around [L] as [L.p_they()] suddenly fall[L.p_s()] unconscious."), span_revendanger("[desc]")) // Don't let them sit suround unconscious forever addtimer(CALLBACK(src, PROC_REF(sleeper_dreams), L), 10 SECONDS) // Existing sleepers for(var/i in found) var/mob/living/L = i L.SetSleeping(200) // Missing sleepers for(var/i in sleepers - found) var/mob/living/L = i L.remove_atom_colour(TEMPORARY_COLOUR_PRIORITY, COLOR_PURPLE) L.visible_message("<span class='revennotice'>The glow from [L] fades \ away.</span>") L.grab_ghost() sleepers = found if(sleepers.len) our_statue.active_tables |= src if(never_spoken || prob(5)) say(desc) never_spoken = FALSE else our_statue.active_tables -= src /obj/structure/table/abductor/wabbajack/proc/sleeper_dreams(mob/living/sleeper) if(sleeper in sleepers) to_chat(sleeper, span_revennotice("While you slumber, you have the strangest dream, like you can see yourself from the outside.")) sleeper.ghostize(TRUE) /obj/structure/table/abductor/wabbajack/left desc = "You sleep so it may wake." /obj/structure/table/abductor/wabbajack/right desc = "It wakes so you may sleep." /** * Bar staff, mobs with the TRAIT_GODMODE trait (as long as they stay in the shuttle) * that just want to make sure people have drinks and a good shuttle time. */ /mob/living/basic/drone/snowflake/bardrone name = "Bardrone" desc = "A barkeeping drone, a robot built to tend bars." hacked = TRUE shy = FALSE laws = "1. Serve drinks.\n\ 2. Talk to patrons.\n\ 3. Don't get messed up in their affairs." unique_name = FALSE // disables the (123) number suffix initial_language_holder = /datum/language_holder/universal default_storage = null /mob/living/basic/drone/snowflake/bardrone/Initialize(mapload) . = ..() AddComponentFrom(ROUNDSTART_TRAIT, /datum/component/area_based_godmode, area_type = /area/shuttle/escape, allow_area_subtypes = TRUE) // Bar table, a wooden table that kicks you in a direction if you're not // barstaff (defined as someone who was a roundstart bartender or someone // with CENTCOM_BARSTAFF) /obj/structure/table/wood/shuttle_bar resistance_flags = LAVA_PROOF | FIRE_PROOF | ACID_PROOF max_integrity = 1000 var/boot_dir = 1 /obj/structure/table/wood/shuttle_bar/Initialize(mapload, obj/structure/table_frame/frame_used, obj/item/stack/stack_used) . = ..() var/static/list/loc_connections = list( COMSIG_ATOM_ENTERED = PROC_REF(on_climbed), ) AddElement(/datum/element/connect_loc, loc_connections) /obj/structure/table/wood/shuttle_bar/screwdriver_act(mob/living/user, obj/item/tool) return NONE /obj/structure/table/wood/shuttle_bar/wrench_act(mob/living/user, obj/item/tool) return NONE /obj/structure/table/wood/shuttle_bar/proc/on_climbed(datum/source, atom/movable/AM) SIGNAL_HANDLER var/mob/living/M = AM if(istype(M) && !M.incorporeal_move && !is_barstaff(M)) // No climbing on the bar please var/throwtarget = get_edge_target_turf(src, boot_dir) M.Paralyze(40) M.throw_at(throwtarget, 5, 1) to_chat(M, span_notice("No climbing on the bar please.")) /obj/structure/table/wood/shuttle_bar/proc/is_barstaff(mob/living/user) . = FALSE if(ishuman(user)) var/mob/living/carbon/human/human_user = user if(is_bartender_job(human_user.mind?.assigned_role)) return TRUE if(istype(user, /mob/living/basic/drone/snowflake/bardrone)) return TRUE var/obj/item/card/id/ID = user.get_idcard(FALSE) if(ID && (ACCESS_CENT_BAR in ID.access)) return TRUE //Luxury Shuttle Blockers /obj/machinery/scanner_gate/luxury_shuttle name = "luxury shuttle ticket field" density = FALSE //allows shuttle airlocks to close, nothing but an approved passenger gets past CanPass locked = TRUE use_power = NO_POWER_USE resistance_flags = INDESTRUCTIBLE | LAVA_PROOF | FIRE_PROOF | UNACIDABLE | ACID_PROOF speech_span = SPAN_ROBOT var/threshold = 500 var/static/list/approved_passengers = list() var/static/list/check_times = list() var/list/payees = list() /obj/machinery/scanner_gate/luxury_shuttle/CanAllowThrough(atom/movable/mover, border_dir) . = ..() if(mover in approved_passengers) set_scanline("scanning", 10) if(isvehicle(mover)) var/obj/vehicle/vehicle = mover for(var/mob/living/rat in vehicle.occupants) if(!(rat in approved_passengers)) say("Stowaway detected. Please exit the vehicle first.") return FALSE return TRUE if(isitem(mover)) return TRUE if(isstructure(mover)) var/obj/structure/struct = mover for(var/mob/living/rat in struct.contents) say("Stowaway detected. Please exit the structure first.") return FALSE return TRUE return FALSE /obj/machinery/scanner_gate/luxury_shuttle/auto_scan(atom/movable/AM) return /obj/machinery/scanner_gate/luxury_shuttle/attackby(obj/item/W, mob/user, list/modifiers, list/attack_modifiers) return /obj/machinery/scanner_gate/luxury_shuttle/emag_act(mob/user, obj/item/card/emag/emag_card) return FALSE #define LUXURY_MESSAGE_COOLDOWN 100 /obj/machinery/scanner_gate/luxury_shuttle/Bumped(atom/movable/AM) ///If the atom entering the gate is a vehicle, we store it here to add to the approved list to enter/leave the scanner gate. var/obj/vehicle/vehicle ///We store the driver of vehicles separately so that we can add them to the approved list once payment is fully processed. var/mob/living/driver_holdout if(!isliving(AM) && !isvehicle(AM)) alarm_beep() return ..() var/datum/bank_account/account if(istype(AM.pulling, /obj/item/card/id)) var/obj/item/card/id/I = AM.pulling if(I.registered_account) account = I.registered_account else if(!check_times[AM] || check_times[AM] < world.time) //Let's not spam the message to_chat(AM, span_notice("This ID card doesn't have an owner associated with it!")) check_times[AM] = world.time + LUXURY_MESSAGE_COOLDOWN else if(isliving(AM)) var/mob/living/L = AM account = L.get_bank_account() else if(isvehicle(AM)) vehicle = AM for(var/passenger in vehicle.occupants) if(!isliving(passenger)) continue var/mob/living/rider = passenger if(vehicle.is_driver(rider)) driver_holdout = rider var/obj/item/card/id/id = rider.get_idcard(TRUE) account = id?.registered_account break if(account) if(account.account_balance < threshold - payees[AM]) account.adjust_money(-account.account_balance, "Scanner Gate: Entry Fee") payees[AM] += account.account_balance else var/money_owed = threshold - payees[AM] account.adjust_money(-money_owed, "Scanner Gate: Partial Entry Fee") payees[AM] += money_owed //Here is all the possible paygate payment methods. var/list/counted_money = list() for(var/obj/item/coin/C in AM.get_all_contents()) //Coins. if(payees[AM] >= threshold) break payees[AM] += C.value counted_money += C for(var/obj/item/stack/spacecash/S in AM.get_all_contents()) //Paper Cash if(payees[AM] >= threshold) break payees[AM] += S.value * S.amount counted_money += S for(var/obj/item/holochip/H in AM.get_all_contents()) //Holocredits if(payees[AM] >= threshold) break payees[AM] += H.credits counted_money += H if(payees[AM] < threshold && istype(AM.pulling, /obj/item/coin)) //Coins(Pulled). var/obj/item/coin/C = AM.pulling payees[AM] += C.value counted_money += C else if(payees[AM] < threshold && istype(AM.pulling, /obj/item/stack/spacecash)) //Cash(Pulled). var/obj/item/stack/spacecash/S = AM.pulling payees[AM] += S.value * S.amount counted_money += S else if(payees[AM] < threshold && istype(AM.pulling, /obj/item/holochip)) //Holocredits(pulled). var/obj/item/holochip/H = AM.pulling payees[AM] += H.credits counted_money += H if(payees[AM] < threshold) //Suggestions for those with no arms/simple animals. var/armless if(!ishuman(AM) && !isslime(AM)) armless = TRUE else var/mob/living/carbon/human/H = AM if(!H.get_bodypart(BODY_ZONE_L_ARM) && !H.get_bodypart(BODY_ZONE_R_ARM)) armless = TRUE if(armless) if(!AM.pulling || !iscash(AM.pulling) && !istype(AM.pulling, /obj/item/card/id)) if(!check_times[AM] || check_times[AM] < world.time) //Let's not spam the message to_chat(AM, span_notice("Try pulling a valid ID, space cash, holochip or coin into \the [src]!")) check_times[AM] = world.time + LUXURY_MESSAGE_COOLDOWN if(payees[AM] >= threshold) for(var/obj/I in counted_money) qdel(I) payees[AM] -= threshold var/change = FALSE if(payees[AM] > 0) change = TRUE var/obj/item/holochip/holocred = new /obj/item/holochip(AM.loc, payees[AM]) //Change is made in holocredits exclusively. if(ishuman(AM)) var/mob/living/carbon/human/H = AM if(!H.put_in_hands(holocred)) AM.pulling = holocred else AM.pulling = holocred payees[AM] -= payees[AM] say("Welcome to first class, [driver_holdout ? "[driver_holdout]" : "[AM]" ]![change ? " Here is your change." : ""]") approved_passengers |= AM if(vehicle) approved_passengers |= vehicle if(driver_holdout) approved_passengers |= driver_holdout check_times -= AM return else if (payees[AM] > 0) for(var/obj/I in counted_money) qdel(I) if(!check_times[AM] || check_times[AM] < world.time) //Let's not spam the message to_chat(AM, span_notice("[payees[AM]] cr received. You need [threshold-payees[AM]] cr more.")) check_times[AM] = world.time + LUXURY_MESSAGE_COOLDOWN alarm_beep() return ..() else alarm_beep() return ..() /mob/living/basic/bear/fightpit name = "fight pit bear" desc = "This bear's trained through ancient Russian secrets to fear the walls of its glass prison." environment_smash = ENVIRONMENT_SMASH_NONE /obj/effect/decal/hammerandsickle name = "hammer and sickle" desc = "Communism powerful force." icon = 'icons/effects/96x96.dmi' icon_state = "communist" pixel_x = -32 pixel_y = -32 /obj/effect/decal/hammerandsickle/shuttleRotate(rotation) setDir(angle2dir(rotation+dir2angle(dir))) // No parentcall, rest of the rotate code breaks the pixel offset. #undef LUXURY_MESSAGE_COOLDOWN
412
0.957801
1
0.957801
game-dev
MEDIA
0.969708
game-dev
0.9131
1
0.9131
maruohon/minihud
12,171
src/main/java/minihud/network/carpet/CarpetStructurePacketHandler.java
package minihud.network.carpet; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import io.netty.buffer.Unpooled; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.PacketBuffer; import net.minecraft.util.ResourceLocation; import malilib.network.PacketSplitter; import malilib.network.message.BasePacketHandler; import malilib.util.data.Constants; import malilib.util.game.wrap.GameWrap; import malilib.util.game.wrap.NbtWrap; import malilib.util.position.IntBoundingBox; import minihud.MiniHud; import minihud.data.DataStorage; import minihud.data.structure.StructureData; import minihud.data.structure.StructureStorage; import minihud.data.structure.StructureType; public class CarpetStructurePacketHandler extends BasePacketHandler { public static final ResourceLocation CHANNEL = new ResourceLocation("carpet:client"); public static final List<ResourceLocation> CHANNELS = ImmutableList.of(CHANNEL); public static final CarpetStructurePacketHandler INSTANCE = new CarpetStructurePacketHandler(); public static final int CARPET_ID_BOUNDINGBOX_MARKERS = 3; public static final int CARPET_ID_LARGE_BOUNDINGBOX_MARKERS_START = 7; public static final int CARPET_ID_LARGE_BOUNDINGBOX_MARKERS = 8; public static final int CARPET_STRUCTURE_ID_OUTER_BOUNDING_BOX = 0; public static final int CARPET_STRUCTURE_ID_END_CITY = 1; public static final int CARPET_STRUCTURE_ID_FORTRESS = 2; public static final int CARPET_STRUCTURE_ID_TEMPLE = 3; public static final int CARPET_STRUCTURE_ID_VILLAGE = 4; public static final int CARPET_STRUCTURE_ID_STRONGHOLD = 5; public static final int CARPET_STRUCTURE_ID_MINESHAFT = 6; public static final int CARPET_STRUCTURE_ID_MONUMENT = 7; public static final int CARPET_STRUCTURE_ID_MANSION = 8; private static final CarpetBoxReader CARPET_BOX_READER = new CarpetBoxReader(); private CarpetStructurePacketHandler() { this.registerToServer = true; this.usePacketSplitter = true; } @Override public List<ResourceLocation> getChannels() { return CHANNELS; } @Override public void onPacketReceived(PacketBuffer buf) { try { buf.readerIndex(0); if (buf.readerIndex() < buf.writerIndex() - 4) { int type = buf.readInt(); MiniHud.debugLog("StructureStorage#updateStructureDataFromCarpetServer(), packet type = {}", type); if (type == CARPET_ID_BOUNDINGBOX_MARKERS) { NBTTagCompound tag = buf.readCompoundTag(); StructureStorage.INSTANCE.addStructureDataFromServer(readStructureDataCarpetAllBoxes(tag)); } else if (type == CARPET_ID_LARGE_BOUNDINGBOX_MARKERS_START) { readSplitStructuresHeader(buf); } else if (type == CARPET_ID_LARGE_BOUNDINGBOX_MARKERS) { readSplitStructureBoxes(buf); } } buf.readerIndex(0); } catch (Exception e) { MiniHud.LOGGER.warn("Failed to read structure data from Carpet mod packet", e); } } public void sendBoundingBoxRequest() { PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); buf.writeInt(CARPET_ID_BOUNDINGBOX_MARKERS); PacketSplitter.send(CHANNEL, buf, GameWrap.getNetworkConnection()); } private static ArrayListMultimap<StructureType, StructureData> readStructureDataCarpetAllBoxes(NBTTagCompound tag) { ArrayListMultimap<StructureType, StructureData> map = ArrayListMultimap.create(); NBTTagList tagList = NbtWrap.getList(tag, "Boxes", Constants.NBT.TAG_LIST); MiniHud.debugLog("StructureStorage#readStructureDataCarpetAll() - tag count: {}", tagList.tagCount()); List<NBTTagCompound> tags = new ArrayList<>(); final int size = NbtWrap.getListSize(tagList); if (NbtWrap.containsLong(tag, "Seed")) { DataStorage.getInstance().setWorldSeed(NbtWrap.getLong(tag, "Seed")); } for (int listNum = 0; listNum < size; ++listNum) { NBTTagList innerList = (NBTTagList) tagList.get(listNum); final int innerSize = NbtWrap.getListSize(innerList); for (int i = 0; i < innerSize; ++i) { tags.add(NbtWrap.getCompoundAt(innerList, i)); } } //System.out.printf("SD - readStructureDataCarpetAllBoxes, list: %d\n", tags.size()); readStructureDataCarpetAllBoxes(map, tags); MiniHud.debugLog("Structure data from Carpet server (all), structure count = {}", map.size()); return map; } private static void readStructureDataCarpetAllBoxes(ArrayListMultimap<StructureType, StructureData> map, List<NBTTagCompound> tags) { ImmutableList.Builder<IntBoundingBox> builder = ImmutableList.builder(); IntBoundingBox bbMain = null; StructureType type = null; int componentBoxes = 0; for (int i = 0; i < tags.size(); ++i) { NBTTagCompound tag = tags.get(i); int id = NbtWrap.getInt(tag, "type"); // Carpet puts the main box as the first entry in the same list of compound tags // Only the subsequent component boxes will have the structure type ID if (id == CARPET_STRUCTURE_ID_OUTER_BOUNDING_BOX) { // The beginning of another structure if (type != null && bbMain != null) { map.put(type, new StructureData(bbMain, builder.build())); builder = ImmutableList.builder(); type = null; } if (tags.size() > i + 1) { bbMain = IntBoundingBox.fromArray(NbtWrap.getIntArray(tag, "bb")); id = NbtWrap.getInt(tags.get(i + 1), "type"); type = getTypeFromCarpetId(id); } MiniHud.debugLog("readStructureDataCarpetAllBoxes(): Enclosing box, id = {}", id); } // Don't add the component boxes of unknown/unsupported structure types to the builder else if (type != null) { builder.add(IntBoundingBox.fromArray(NbtWrap.getIntArray(tag, "bb"))); ++componentBoxes; MiniHud.debugLog("readStructureDataCarpetAllBoxes(): componentBoxes currently: {}", componentBoxes); } } if (componentBoxes > 0 && type != null && bbMain != null) { map.put(type, new StructureData(bbMain, builder.build())); } } private static void readSplitStructuresHeader(PacketBuffer buf) { CarpetBoxReader reader = CARPET_BOX_READER; reader.reset(); try { NBTTagCompound tag = buf.readCompoundTag(); int boxCount = buf.readVarInt(); reader.expectedStructures = boxCount; MiniHud.debugLog("Structure data header received from Carpet server, expecting {} boxes", boxCount); if (NbtWrap.containsLong(tag, "Seed")) { DataStorage.getInstance().setWorldSeed(NbtWrap.getLong(tag, "Seed")); } } catch (Exception e) { MiniHud.LOGGER.warn("Failed to read structure data from Carpet server (split boxes header)", e); } } private static void readSplitStructureBoxes(PacketBuffer buf) { try { List<NBTTagCompound> tags = new ArrayList<>(); int boxCount = buf.readByte(); for (int i = 0; i < boxCount; ++i) { tags.add(buf.readCompoundTag()); } readSplitStructureBoxes(tags); } catch (Exception e) { MiniHud.LOGGER.warn("Failed to read structure data from Carpet server", e); } } private static void readSplitStructureBoxes(List<NBTTagCompound> tags) { for (NBTTagCompound tag : tags) { readSplitStructureBox(tag); } MiniHud.debugLog("Structure data received from Carpet server (split boxes), received {} boxes", tags.size()); } private static void readSplitStructureBox(NBTTagCompound tag) { CarpetBoxReader reader = CARPET_BOX_READER; int id = NbtWrap.getInt(tag, "type"); reader.seenStructures++; if (id == CARPET_STRUCTURE_ID_OUTER_BOUNDING_BOX) { if (reader.type != null && reader.bbMain != null && reader.componentBoxes > 0) { reader.map.put(reader.type, new StructureData(reader.bbMain, reader.componentsBuilder.build())); } IntBoundingBox bb = IntBoundingBox.fromArray(NbtWrap.getIntArray(tag, "bb")); reader.bbMain = bb; reader.readTypeFromNextBox = true; reader.type = null; reader.componentsBuilder = ImmutableList.builder(); } else { reader.componentBoxes++; if (reader.readTypeFromNextBox) { reader.type = getTypeFromCarpetId(id); reader.readTypeFromNextBox = false; } if (reader.componentsBuilder != null) { IntBoundingBox bb = IntBoundingBox.fromArray(NbtWrap.getIntArray(tag, "bb")); reader.componentsBuilder.add(bb); } } if (reader.seenStructures >= reader.expectedStructures) { if (reader.type != null && reader.bbMain != null && reader.componentBoxes > 0) { reader.map.put(reader.type, new StructureData(reader.bbMain, reader.componentsBuilder.build())); } MiniHud.debugLog("Structure data from Carpet server (split data), structure count = {}", reader.map.size()); StructureStorage.INSTANCE.addStructureDataFromServer(reader.map); reader.reset(); } } @Nullable private static StructureType getTypeFromCarpetId(int id) { switch (id) { case CARPET_STRUCTURE_ID_END_CITY: return StructureType.END_CITY; case CARPET_STRUCTURE_ID_FORTRESS: return StructureType.NETHER_FORTRESS; case CARPET_STRUCTURE_ID_MANSION: return StructureType.MANSION; case CARPET_STRUCTURE_ID_MONUMENT: return StructureType.OCEAN_MONUMENT; case CARPET_STRUCTURE_ID_MINESHAFT: return StructureType.MINESHAFT; case CARPET_STRUCTURE_ID_STRONGHOLD: return StructureType.STRONGHOLD; case CARPET_STRUCTURE_ID_TEMPLE: return StructureType.WITCH_HUT; case CARPET_STRUCTURE_ID_VILLAGE: return StructureType.VILLAGE; } return null; } private static class CarpetBoxReader { protected StructureType type; protected IntBoundingBox bbMain; protected ImmutableList.Builder<IntBoundingBox> componentsBuilder; protected ArrayListMultimap<StructureType, StructureData> map = ArrayListMultimap.create(); protected boolean readTypeFromNextBox; protected int expectedStructures = -1; protected int seenStructures; protected int componentBoxes; protected void reset() { this.map = ArrayListMultimap.create(); this.type = null; this.bbMain = null; this.componentsBuilder = null; this.readTypeFromNextBox = false; this.componentBoxes = 0; this.expectedStructures = -1; this.seenStructures = 0; } } }
412
0.932036
1
0.932036
game-dev
MEDIA
0.883561
game-dev
0.922098
1
0.922098
MATTYOneInc/AionEncomBase_Java8
4,749
AL-Game/data/scripts/system/handlers/quest/high_daevanion/_25304Walk_The_Walk.java
/* * =====================================================================================* * This file is part of Aion-Unique (Aion-Unique Home Software Development) * * Aion-Unique Development is a closed Aion Project that use Old Aion Project Base * * Like Aion-Lightning, Aion-Engine, Aion-Core, Aion-Extreme, Aion-NextGen, ArchSoft, * * Aion-Ger, U3J, Encom And other Aion project, All Credit Content * * That they make is belong to them/Copyright is belong to them. And All new Content * * that Aion-Unique make the copyright is belong to Aion-Unique * * You may have agreement with Aion-Unique Development, before use this Engine/Source * * You have agree with all of Term of Services agreement with Aion-Unique Development * * =====================================================================================* */ package quest.high_daevanion; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestDialog; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /****/ /** Author Ghostfur & Unknown (Aion-Unique) /****/ public class _25304Walk_The_Walk extends QuestHandler { private final static int questId = 25304; private final static int[] Ab1NewMobs = {883285, 883286, 883287, 883288, 883290, 883291, 883297, 883298, 883299}; public _25304Walk_The_Walk() { super(questId); } public void register() { qe.registerQuestNpc(805339).addOnQuestStart(questId); qe.registerQuestNpc(805339).addOnTalkEvent(questId); qe.registerQuestNpc(805340).addOnTalkEvent(questId); for (int mob: Ab1NewMobs) { qe.registerQuestNpc(mob).addOnKillEvent(questId); } } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); int targetId = env.getTargetId(); if (qs == null) { return false; } if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 805339) { switch (env.getDialog()) { case START_DIALOG: { return sendQuestDialog(env, 4762); } case ACCEPT_QUEST: case ACCEPT_QUEST_SIMPLE: { return sendQuestStartDialog(env); } case REFUSE_QUEST_SIMPLE: { return closeDialogWindow(env); } } } } else if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (targetId == 805340) { switch (env.getDialog()) { case START_DIALOG: { if (var == 0) { return sendQuestDialog(env, 1011); } else if (var == 1) { return sendQuestDialog(env, 1352); } else if (var == 2) { return sendQuestDialog(env, 1693); } else if (var == 3) { return sendQuestDialog(env, 2036); } } case SELECT_ACTION_1012: { if (var == 0) { return sendQuestDialog(env, 1012); } } case STEP_TO_1: { changeQuestStep(env, 0, 1, false); return closeDialogWindow(env); } case SET_REWARD: { giveQuestItem(env, 182215874, 1); //Daevanion Pants Prototype. removeQuestItem(env, 182215850, 1); //Marchutan's Improved Pattern Of Ease. changeQuestStep(env, 3, 4, true); return closeDialogWindow(env); } case CHECK_COLLECTED_ITEMS: { return checkQuestItems(env, 1, 2, false, 10000, 10001); } } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 805339) { if (env.getDialog() == QuestDialog.START_DIALOG) { return sendQuestDialog(env, 10002); } else { return sendQuestEndDialog(env); } } } return false; } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var == 2) { int var1 = qs.getQuestVarById(1); if (var1 >= 0 && var1 < 59) { return defaultOnKillEvent(env, Ab1NewMobs, var1, var1 + 1, 1); } else if (var1 == 59) { qs.setQuestVar(3); updateQuestStatus(env); return true; } } } return false; } }
412
0.95113
1
0.95113
game-dev
MEDIA
0.967537
game-dev
0.966699
1
0.966699
EssexUniversityMCTS/gvgai
3,626
src/core/content/ParameterContent.java
package core.content; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; /** * Created with IntelliJ IDEA. * User: Diego * Date: 18/10/13 * Time: 07:01 * This is a Java port from Tom Schaul's VGDL - https://github.com/schaul/py-vgdl */ public class ParameterContent extends Content { /** * Number of points that can be sampled from minValue */ protected int nPoints; /** * Is final value set */ protected boolean isFinalValueSet; /** * Debug only: Shows the values given to parameters. */ protected boolean VERBOSE = false; /** * Default constructor. */ public ParameterContent(){} /** * Constructor that extracts the contents from a String line * @param line String with the contents in VGDL format, to be mapped to the * data structures of this class. */ public ParameterContent(String line) { this.nPoints = -1; this.line = line; //Init structures of node content. parameters = new HashMap<String, String>(); //Take the pieces and the first one is the name that defines the content String pieces[] = line.split(" "); if(pieces.length < 2) { //This is the ParameterSet line. Just finish here identifier = pieces[0].trim(); return; } identifier = pieces[0].trim(); //Take the other pieces and extract properties and parameters key-value. for(int i = 1; i < pieces.length; ++i) { String piece = pieces[i].trim(); if(piece.contains("=")) { String keyValue[] = piece.split("="); String key = keyValue[0]; String value = keyValue[1]; parameters.put(key, value); }else if(piece.equals(">")) { this.is_definition = true; } } } public static ParameterContent create(String line) { ParameterContent pc = new ParameterContent(line); if(pc.parameters.size() == 0) return pc; //This happens when parsing lines like "ParameterSet" String[] valuesToRead = (pc.parameters.get("values")).split(":"); if(valuesToRead.length == 3) { if(valuesToRead[0].contains(".") || valuesToRead[1].contains(".") || valuesToRead[2].contains(".")) { return new ParameterDoubleContent(pc, line); } return new ParameterIntContent(pc, line); }else{ //Assuming it's a definition True, False. if((valuesToRead[0].equalsIgnoreCase("true") || valuesToRead[0].equalsIgnoreCase("false")) && (valuesToRead[1].equalsIgnoreCase("true") || valuesToRead[1].equalsIgnoreCase("false"))){ return new ParameterBoolContent(pc, line); } } return null; } @Override public void decorate(HashMap<String, ParameterContent> pcs) { //Nothing to do here (too recursive to be true :-)) } public void init() { } public void setRunningValue(int value) { } public int getnPoints() {return nPoints;} public String getStValue() {return "";} public String toString() { if(parameters.containsKey("string")) return parameters.get("string"); return "Undefined"; } public String values() { if(parameters.containsKey("values")) return parameters.get("values"); return "Undefined-values"; } }
412
0.891332
1
0.891332
game-dev
MEDIA
0.302826
game-dev
0.907577
1
0.907577
keepwn/Altman
7,330
Source/Altman.Webshell/Core/CustomCommandCode.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using Altman.Util.Common.AltData; using Altman.Util.Setting; namespace Altman.Webshell.Core { internal class CustomCommandCode { private CustomShellType _customShellType; private string _pass; private string _coding; private Dictionary<string, string> _randomParam; public CustomCommandCode(CustomShellType customShellType, string pass) { _customShellType = customShellType; _pass = pass; _randomParam = new Dictionary<string, string>(); } /** * Dictionary<string1,string2> * string1值为:Body,Cookie,Referer(header头)等 * string2值为:pass=MMM&z=AAA&z1=BBB ,MMM,等 */ private void AddItemToDic(Dictionary<string, string> dic, string key, string value) { if (dic.ContainsKey(key)) { dic[key] += "&" + value; } else { dic.Add(key, value); } } private string EncryItem(EncryMode mode, string item) { if (mode == EncryMode.None) { return item; } else if (mode == EncryMode.Base64) { return DataConvert.StrToBase64(item, 1); } else if (mode == EncryMode.Hex) { return DataConvert.StrToHex(item); } else { return item; } } private string GetRandomStr(int length) { Random r = new Random(); string str = string.Empty; for (int i = 0; i < length; i++) { string s = ((char)r.Next(97, 123)).ToString(); str += s; } return str; } /// <summary> /// 填充参数,主要用于MainCodeSetting.item和FuncCodeSetting.func.item中的$par$=>par /// </summary> /// <param name="item"></param> /// <param name="pars"></param> /// <returns></returns> private string FillParams(string item, object pars) { List<string> parList = new List<string>(); //将传入参数转换为List<string> if (pars is CustomShellType.ParamStruct) { parList.Add(((CustomShellType.ParamStruct)pars).Name); } else if (pars is List<CustomShellType.ParamStruct>) { List<CustomShellType.ParamStruct> tmp = (List<CustomShellType.ParamStruct>)pars; foreach (var i in tmp) { parList.Add(i.Name); } } foreach (string par in parList) { if (GlobalSetting.IsParamRandom) { //string newguid = Guid.NewGuid().ToString().Substring(0, 2); string newguid = GetRandomStr(1); //新的uid不能等于pass且,不与已经产生的uid相同 while (newguid == _pass || _randomParam.ContainsValue(newguid)) { newguid = GetRandomStr(1); } _randomParam.Add(par, newguid); item = item.Replace("$" + par + "$", newguid); } else { item = item.Replace("$" + par + "$", par); } } return item; } private Dictionary<string, string> GetCode(CustomShellType customShellType, string pass, CustomShellType.FuncCode funcCode, string[] parmas) { DataCombine dataCombine = new DataCombine(); Dictionary<string, string> dic = new Dictionary<string, string>(); //MainCodeSetting string mainCodeString = FillParams(customShellType.MainCodeSetting.Item, customShellType.MainCodeSetting.FuncCodeParam); NameValueCollection mainCodeItem = new NameValueCollection { {pass, EncryItem(customShellType.BasicSetting.MainCodeParam.EncryMode, mainCodeString)} }; AddItemToDic(dic, customShellType.BasicSetting.MainCodeParam.Location, dataCombine.CombineToStr(mainCodeItem)); //FuncCode string funcCodeString = ""; if (funcCode.FuncParams.Count > 0) { funcCodeString = FillParams(funcCode.Item, funcCode.FuncParams); } else { funcCodeString = funcCode.Item; } //判断是否随机参数 string funcParamName = customShellType.MainCodeSetting.FuncCodeParam.Name; if (GlobalSetting.IsParamRandom) { string newguid = _randomParam[funcParamName]; funcParamName = newguid; } NameValueCollection funcCodeItem = new NameValueCollection { {funcParamName, EncryItem(customShellType.MainCodeSetting.FuncCodeParam.EncryMode, funcCodeString)} }; AddItemToDic(dic, customShellType.MainCodeSetting.FuncCodeParam.Location, dataCombine.CombineToStr(funcCodeItem)); //FunParma if (parmas != null && parmas.Length > 0) { if (parmas.Length != funcCode.FuncParams.Count) { throw new Exception("调用方法的参数个数与实现代码的参数个数不符合"); } for (int i = 0; i < parmas.Length; i++) { string parName = funcCode.FuncParams[i].Name; if (GlobalSetting.IsParamRandom) { string newguid = _randomParam[parName]; parName = newguid; } NameValueCollection item = new NameValueCollection { {parName, EncryItem(funcCode.FuncParams[i].EncryMode, parmas[i])} }; AddItemToDic(dic, funcCode.FuncParams[i].Location, dataCombine.CombineToStr(item)); //dataCombine.AddFuncParmaItem("z" + (i + 1), EncryItem(FuncCode.FuncParmaEncryMode, parmas[i])); } //AddItemToDic(dic, FuncCode.FuncParmaLocation, dataCombine.CombineToStr(dataCombine.FuncParmaItems)); } return dic; } public Dictionary<string, string> GetCode(string funcCodeNameXpath, string[] parmas) { //分解funcCodeNameXpath,将"cmder/exec"分解为cmder和exec List<string> list = new List<string>(funcCodeNameXpath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)); string funcCodeName = list[list.Count-1]; list.RemoveAt(list.Count-1); string path = string.Join("/", list); return GetCode(_customShellType, _pass, _customShellType.GetFuncCode(path, funcCodeName), parmas); } } }
412
0.821774
1
0.821774
game-dev
MEDIA
0.55909
game-dev
0.808738
1
0.808738
Vedenin/useful-java-links
2,652
helloworlds/3.8-json/jackson/src/main/java/jackson/advanced/JsonPointerHelloWorld.java
package jackson.advanced; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; /** * Json Path Hello World * */ public class JsonPointerHelloWorld { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); String author = root.at("/store/book/3/title").asText(); System.out.println(author); // print ["Hello, Middle-earth! "] System.out.println(); String jsonHiWorld = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\""; String message = mapper.readTree(jsonHiWorld).at("/message").asText(); String place = mapper.readTree(jsonHiWorld).at("/place/name").asText(); System.out.println(message + " " + place); // print "Hi World!" } private final static String json = "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Evelyn Waugh\",\n" + " \"title\": \"Sword of Honour\",\n" + " \"price\": 12.99\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"J. R. R. Tolkien\",\n" + " \"title\": \"Hello, Middle-earth! \",\n" + " \"isbn\": \"0-395-19395-8\",\n" + " \"price\": 22.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}"; }
412
0.54359
1
0.54359
game-dev
MEDIA
0.272869
game-dev
0.603937
1
0.603937
mehah/otclient
41,439
src/client/thingtype.cpp
/* * Copyright (c) 2010-2025 OTClient <https://github.com/edubart/otclient> * * 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. */ #include "thingtype.h" #include "game.h" #include "lightview.h" #include "localplayer.h" #include "map.h" #include "spriteappearances.h" #include "spritemanager.h" #include <framework/core/asyncdispatcher.h> #include <framework/core/eventdispatcher.h> #include <framework/core/filestream.h> #include <framework/core/graphicalapplication.h> #include <framework/graphics/drawpoolmanager.h> #include <framework/graphics/image.h> #include <framework/graphics/texture.h> #include <framework/otml/otml.h> const static TexturePtr m_textureNull; void ThingType::unserializeAppearance(const uint16_t clientId, const ThingCategory category, const appearances::Appearance& appearance) { m_null = false; m_id = clientId; m_category = category; m_name = appearance.name(); m_description = appearance.description(); applyAppearanceFlags(appearance.flags()); if (!g_game.getFeature(Otc::GameLoadSprInsteadProtobuf)) { m_animationPhases = 0; int totalSpritesCount = 0; for (const auto& framegroup : appearance.frame_group()) { const int frameGroupType = framegroup.fixed_frame_group(); const auto& spriteInfo = framegroup.sprite_info(); const auto& animation = spriteInfo.animation(); spriteInfo.sprite_id(); // sprites const auto& spritesPhases = animation.sprite_phase(); m_numPatternX = spriteInfo.pattern_width(); m_numPatternY = spriteInfo.pattern_height(); m_numPatternZ = spriteInfo.pattern_depth(); m_layers = spriteInfo.layers(); m_opaque = spriteInfo.is_opaque(); m_animationPhases += std::max<int>(1, spritesPhases.size()); if (const auto& sheet = g_spriteAppearances.getSheetBySpriteId(spriteInfo.sprite_id(0), false)) { m_size = sheet->getSpriteSize() / g_gameConfig.getSpriteSize(); } // animations if (spritesPhases.size() > 1) { auto* animator = new Animator; animator->unserializeAppearance(animation); if (frameGroupType == FrameGroupMoving) m_animator = animator; else if (frameGroupType == FrameGroupIdle || frameGroupType == FrameGroupInitial) m_idleAnimator = animator; } const int totalSprites = m_layers * m_numPatternX * m_numPatternY * m_numPatternZ * std::max<int>(1, spritesPhases.size()); if (totalSpritesCount + totalSprites > 4096) throw Exception("a thing type has more than 4096 sprites"); m_spritesIndex.resize(totalSpritesCount + totalSprites); for (int j = totalSpritesCount, spriteId = 0; j < (totalSpritesCount + totalSprites); ++j, ++spriteId) { m_spritesIndex[j] = spriteInfo.sprite_id(spriteId); } totalSpritesCount += totalSprites; } m_textureData.resize(m_animationPhases); } } void ThingType::applyAppearanceFlags(const appearances::AppearanceFlags& flags) { if (flags.has_bank()) { m_groundSpeed = flags.bank().waypoints(); m_flags |= ThingFlagAttrGround; } if (flags.has_clip() && flags.clip()) { m_flags |= ThingFlagAttrGroundBorder; } if (flags.has_bottom()) { m_flags |= ThingFlagAttrOnBottom; } if (flags.has_top()) { m_flags |= ThingFlagAttrOnTop; } if (flags.has_container() && flags.container()) { m_flags |= ThingFlagAttrContainer; } if (flags.has_cumulative() && flags.cumulative()) { m_flags |= ThingFlagAttrStackable; } if (flags.has_multiuse() && flags.multiuse()) { m_flags |= ThingFlagAttrMultiUse; } if (flags.has_forceuse() && flags.forceuse()) { m_flags |= ThingFlagAttrForceUse; } if (flags.has_write()) { m_flags |= ThingFlagAttrWritable; m_maxTextLength = flags.write().max_text_length(); } if (flags.has_write_once()) { m_flags |= ThingFlagAttrWritableOnce; m_maxTextLength = flags.write_once().max_text_length_once(); } if (flags.has_liquidpool() && flags.liquidpool()) { m_flags |= ThingFlagAttrSplash; } if (flags.has_unpass() && flags.unpass()) { m_flags |= ThingFlagAttrNotWalkable; } if (flags.has_unmove() && flags.unmove()) { m_flags |= ThingFlagAttrNotMoveable; } if (flags.has_unsight() && flags.unsight()) { m_flags |= ThingFlagAttrBlockProjectile; } if (flags.has_avoid() && flags.avoid()) { m_flags |= ThingFlagAttrNotPathable; } // no_movement_animation (?) if (flags.has_take() && flags.take()) { m_flags |= ThingFlagAttrPickupable; } if (flags.has_liquidcontainer() && flags.liquidcontainer()) { m_flags |= ThingFlagAttrFluidContainer; } if (flags.has_hang() && flags.hang()) { m_flags |= ThingFlagAttrHangable; } if (flags.has_hook()) { const auto& hookDirection = flags.hook(); if (hookDirection.east()) { m_flags |= ThingFlagAttrHookEast; } else if (hookDirection.south()) { m_flags |= ThingFlagAttrHookSouth; } } if (flags.has_light()) { m_flags |= ThingFlagAttrLight; m_light = { static_cast<uint8_t>(flags.light().brightness()), static_cast<uint8_t>(flags.light().color()) }; } if (flags.has_rotate() && flags.rotate()) { m_flags |= ThingFlagAttrRotateable; } if (flags.has_dont_hide() && flags.dont_hide()) { m_flags |= ThingFlagAttrDontHide; } if (flags.has_translucent() && flags.translucent()) { m_flags |= ThingFlagAttrTranslucent; } if (flags.has_shift()) { m_displacement = Point(flags.shift().x(), flags.shift().y()); m_flags |= ThingFlagAttrDisplacement; } if (flags.has_height()) { m_elevation = flags.height().elevation(); m_flags |= ThingFlagAttrElevation; } if (flags.has_lying_object() && flags.lying_object()) { m_flags |= ThingFlagAttrLyingCorpse; } if (flags.has_animate_always() && flags.animate_always()) { m_flags |= ThingFlagAttrAnimateAlways; } if (flags.has_automap()) { m_minimapColor = flags.automap().color(); m_flags |= ThingFlagAttrMinimapColor; } if (flags.has_lenshelp()) { m_lensHelp = flags.lenshelp().id(); m_flags |= ThingFlagAttrLensHelp; } if (flags.has_fullbank() && flags.fullbank()) { m_flags |= ThingFlagAttrFullGround; } if (flags.has_ignore_look() && flags.ignore_look()) { m_flags |= ThingFlagAttrLook; } if (flags.has_clothes()) { m_clothSlot = flags.clothes().slot(); m_flags |= ThingFlagAttrCloth; } // default action if (flags.has_market()) { m_market.category = static_cast<ITEM_CATEGORY>(flags.market().category()); m_market.tradeAs = flags.market().trade_as_object_id(); m_market.showAs = flags.market().show_as_object_id(); if (g_game.getFeature(Otc::GameLoadSprInsteadProtobuf)) { // keep from tibia.dat if (m_market.name.empty() && !flags.market().name().empty()) { m_market.name = flags.market().name(); } } else { m_market.name = m_name; } for (const int32_t voc : flags.market().restrict_to_profession()) { uint16_t vocBitMask = std::pow(2, voc - 1); m_market.restrictVocation |= vocBitMask; } m_market.requiredLevel = flags.market().minimum_level(); m_flags |= ThingFlagAttrMarket; } if (flags.has_wrap() && flags.wrap()) { m_flags |= ThingFlagAttrWrapable; } if (flags.has_unwrap() && flags.unwrap()) { m_flags |= ThingFlagAttrUnwrapable; } if (flags.has_topeffect() && flags.topeffect()) { m_flags |= ThingFlagAttrTopEffect; } if (flags.has_default_action()) { m_defaultAction = static_cast<PLAYER_ACTION>(flags.default_action().action()); } // npcsaledata if (flags.npcsaledata_size() > 0) { for (int i = 0; i < flags.npcsaledata_size(); ++i) { NPCData data; data.name = flags.npcsaledata(i).name(); data.location = flags.npcsaledata(i).location(); data.salePrice = flags.npcsaledata(i).sale_price(); data.buyPrice = flags.npcsaledata(i).buy_price(); data.currencyObjectTypeId = flags.npcsaledata(i).currency_object_type_id(); data.currencyQuestFlagDisplayName = flags.npcsaledata(i).currency_quest_flag_display_name(); m_npcData.push_back(data); } m_flags |= ThingFlagAttrNPC; } // charged to expire // corpse // player_corpse // cyclopediaitem // ammo if (flags.has_show_off_socket() && flags.show_off_socket()) { m_flags |= ThingFlagAttrPodium; } // reportable if (flags.has_upgradeclassification()) { m_upgradeClassification = flags.upgradeclassification().upgrade_classification(); } // reverse_addons_east // reverse_addons_west // reverse_addons_south // reverse_addons_north if (flags.has_wearout() && flags.wearout()) { m_flags |= ThingFlagAttrWearOut; } if (flags.has_clockexpire() && flags.clockexpire()) { m_flags |= ThingFlagAttrClockExpire; } if (flags.has_expire() && flags.expire()) { m_flags |= ThingFlagAttrExpire; } if (flags.has_expirestop() && flags.expirestop()) { m_flags |= ThingFlagAttrExpireStop; } if (flags.has_deco_kit() && flags.deco_kit()) { m_flags |= ThingFlagAttrExpireStop; } } void ThingType::unserialize(const uint16_t clientId, const ThingCategory category, const FileStreamPtr& fin) { m_null = false; m_id = clientId; m_category = category; int count = 0; int attr = -1; bool done = false; for (int i = 0; i < ThingLastAttr; ++i) { ++count; attr = fin->getU8(); if (attr == ThingLastAttr) { done = true; break; } if (g_game.getClientVersion() >= 1000) { /* In 10.10+ all attributes from 16 and up were * incremented by 1 to make space for 16 as * "No Movement Animation" flag. */ if (attr == 16) attr = ThingAttrNoMoveAnimation; else if (attr == 254) { // Usable attr = ThingAttrUsable; } else if (attr == 35) { // Default Action attr = ThingAttrDefaultAction; } else if (attr > 16) attr -= 1; } else if (g_game.getClientVersion() >= 860) { /* Default attribute values follow * the format of 8.6-9.86. * Therefore no changes here. */ } else if (g_game.getClientVersion() >= 780) { /* In 7.80-8.54 all attributes from 8 and higher were * incremented by 1 to make space for 8 as * "Item Charges" flag. */ if (attr == 8) { attr = ThingAttrChargeable; continue; } if (attr > 8) attr -= 1; } else if (g_game.getClientVersion() >= 755) { /* In 7.55-7.72 attributes 23 is "Floor Change". */ if (attr == 23) attr = ThingAttrFloorChange; } else if (g_game.getClientVersion() >= 740) { /* In 7.4-7.5 attribute "Ground Border" did not exist * attributes 1-15 have to be adjusted. * Several other changes in the format. */ if (attr > 0 && attr <= 15) attr += 1; else if (attr == 16) attr = ThingAttrLight; else if (attr == 17) attr = ThingAttrFloorChange; else if (attr == 18) attr = ThingAttrFullGround; else if (attr == 19) attr = ThingAttrElevation; else if (attr == 20) attr = ThingAttrDisplacement; else if (attr == 22) attr = ThingAttrMinimapColor; else if (attr == 23) attr = ThingAttrRotateable; else if (attr == 24) attr = ThingAttrLyingCorpse; else if (attr == 25) attr = ThingAttrHangable; else if (attr == 26) attr = ThingAttrHookSouth; else if (attr == 27) attr = ThingAttrHookEast; else if (attr == 28) attr = ThingAttrAnimateAlways; /* "Multi Use" and "Force Use" are swapped */ if (attr == ThingAttrMultiUse) attr = ThingAttrForceUse; else if (attr == ThingAttrForceUse) attr = ThingAttrMultiUse; } const auto thingAttr = static_cast<ThingAttr>(attr); m_flags |= thingAttrToThingFlagAttr(thingAttr); switch (attr) { case ThingAttrDisplacement: { if (g_game.getClientVersion() >= 755) { if (g_game.getFeature(Otc::GameNegativeOffset)) { m_displacement.x = fin->get16(); m_displacement.y = fin->get16(); } else { m_displacement.x = fin->getU16(); m_displacement.y = fin->getU16(); } } else { m_displacement.x = 8; m_displacement.y = 8; } break; } case ThingAttrLight: { m_light.intensity = fin->getU16(); m_light.color = fin->getU16(); break; } case ThingAttrMarket: { m_market.category = static_cast<ITEM_CATEGORY>(fin->getU16()); m_market.tradeAs = fin->getU16(); m_market.showAs = fin->getU16(); m_market.name = fin->getString(); m_market.restrictVocation = fin->getU16(); m_market.requiredLevel = fin->getU16(); break; } case ThingAttrElevation: m_elevation = fin->getU16(); break; case ThingAttrGround: m_groundSpeed = fin->getU16(); break; case ThingAttrWritable: m_maxTextLength = fin->getU16(); break; case ThingAttrWritableOnce:m_maxTextLength = fin->getU16(); break; case ThingAttrMinimapColor: m_minimapColor = fin->getU16(); break; case ThingAttrCloth: m_clothSlot = fin->getU16(); break; case ThingAttrLensHelp: m_lensHelp = fin->getU16(); break; case ThingAttrDefaultAction: m_defaultAction = static_cast<PLAYER_ACTION>(fin->getU16()); break; } } if (!done) throw Exception("corrupt data (id: {}, category: {}, count: {}, lastAttr: {})", m_id, m_category, count, attr); const bool hasFrameGroups = category == ThingCategoryCreature && g_game.getFeature(Otc::GameIdleAnimations); const uint8_t groupCount = hasFrameGroups ? fin->getU8() : 1; m_animationPhases = 0; int totalSpritesCount = 0; std::vector<Size> sizes; std::vector<int> total_sprites; for (int i = 0; i < groupCount; ++i) { uint8_t frameGroupType = FrameGroupDefault; if (hasFrameGroups) frameGroupType = fin->getU8(); const uint8_t width = fin->getU8(); const uint8_t height = fin->getU8(); m_size = { width, height }; sizes.emplace_back(m_size); if (width > 1 || height > 1) { m_realSize = std::max<int>(m_realSize, fin->getU8()); } m_layers = fin->getU8(); m_numPatternX = fin->getU8(); m_numPatternY = fin->getU8(); if (g_game.getClientVersion() >= 755) m_numPatternZ = fin->getU8(); else m_numPatternZ = 1; const int groupAnimationsPhases = fin->getU8(); m_animationPhases += groupAnimationsPhases; if (groupAnimationsPhases > 1 && g_game.getFeature(Otc::GameEnhancedAnimations)) { auto* animator = new Animator; animator->unserialize(groupAnimationsPhases, fin); if (frameGroupType == FrameGroupMoving) m_animator = animator; else if (frameGroupType == FrameGroupIdle) m_idleAnimator = animator; } const int totalSprites = m_size.area() * m_layers * m_numPatternX * m_numPatternY * m_numPatternZ * groupAnimationsPhases; total_sprites.push_back(totalSprites); if (totalSpritesCount + totalSprites > 4096) throw Exception("a thing type has more than 4096 sprites"); m_spritesIndex.resize(totalSpritesCount + totalSprites); for (int j = totalSpritesCount; j < (totalSpritesCount + totalSprites); ++j) m_spritesIndex[j] = g_game.getFeature(Otc::GameSpritesU32) ? fin->getU32() : fin->getU16(); totalSpritesCount += totalSprites; } if (sizes.size() > 1) { bool hasDifferentSizes = false; const Size& firstSize = sizes[0]; for (size_t i = 1; i < sizes.size(); ++i) { if (sizes[i] != firstSize) { hasDifferentSizes = true; break; } } if (hasDifferentSizes) { for (const auto& s : sizes) { m_size.setWidth(std::max<int>(m_size.width(), s.width())); m_size.setHeight(std::max<int>(m_size.height(), s.height())); } const size_t expectedSize = m_size.area() * m_layers * m_numPatternX * m_numPatternY * m_numPatternZ * m_animationPhases; if (expectedSize != m_spritesIndex.size()) { const std::vector sprites(std::move(m_spritesIndex)); m_spritesIndex.clear(); m_spritesIndex.reserve(expectedSize); for (size_t i = 0, idx = 0; i < sizes.size(); ++i) { const int totalSprites = total_sprites[i]; if (m_size == sizes[i]) { for (int j = 0; j < totalSprites; ++j) { m_spritesIndex.push_back(sprites[idx++]); } continue; } const size_t patterns = (totalSprites / sizes[i].area()); for (size_t p = 0; p < patterns; ++p) { for (int x = 0; x < m_size.width(); ++x) { for (int y = 0; y < m_size.height(); ++y) { if (x < sizes[i].width() && y < sizes[i].height()) { m_spritesIndex.push_back(sprites[idx++]); continue; } m_spritesIndex.push_back(0); } } } } } } } m_textureData.resize(m_animationPhases); } void ThingType::unserializeOtml(const OTMLNodePtr& node) { for (const auto& node2 : node->children()) { if (node2->tag() == "opacity") m_opacity = node2->value<float>(); else if (node2->tag() == "image") m_customImage = node2->value(); else if (node2->tag() == "full-ground") { if (node2->value<bool>()) m_flags &= ~ThingFlagAttrFullGround; else m_flags |= ThingFlagAttrFullGround; } } } void ThingType::drawWithFrameBuffer(const TexturePtr& texture, const Rect& screenRect, const Rect& textureRect, const Color& color) { const int size = static_cast<int>(g_gameConfig.getSpriteSize() * std::max<int>(m_size.area(), 2) * g_drawPool.getScaleFactor()); const auto& p = (Point(size) - screenRect.size().toPoint()) / 2; const auto& destDiff = Rect(screenRect.topLeft() - p, Size{ size }); g_drawPool.bindFrameBuffer(destDiff.size()); { // Debug // g_drawPool.addBoundingRect(Rect(Point(0), destDiff.size()), Color::red); g_drawPool.addTexturedRect(Rect(p, screenRect.size()), texture, textureRect, color); } g_drawPool.releaseFrameBuffer(destDiff); g_drawPool.resetShaderProgram(); } void ThingType::draw(const Point& dest, const int layer, const int xPattern, const int yPattern, const int zPattern, const int animationPhase, const Color& color, const bool drawThings, const LightViewPtr& lightView) { if (m_null) return; if (animationPhase >= m_animationPhases) return; TexturePtr texture; if (g_drawPool.getCurrentType() != DrawPoolType::LIGHT) { texture = getTexture(animationPhase); // texture might not exists, neither its rects. if (!texture) return; } const auto& textureData = m_textureData[animationPhase]; const uint32_t frameIndex = getTextureIndex(layer, xPattern, yPattern, zPattern); if (frameIndex >= textureData.pos.size()) return; const auto& textureOffset = textureData.pos[frameIndex].offsets; const auto& textureRect = textureData.pos[frameIndex].rects; const Rect screenRect(dest + (textureOffset - m_displacement - (m_size.toPoint() - Point(1)) * g_gameConfig.getSpriteSize()) * g_drawPool.getScaleFactor(), textureRect.size() * g_drawPool.getScaleFactor()); if (drawThings && texture) { const auto& newColor = m_opacity < 1.0f ? Color(color, m_opacity) : color; if (g_drawPool.shaderNeedFramebuffer()) drawWithFrameBuffer(texture, screenRect, textureRect, newColor); else g_drawPool.addTexturedRect(screenRect, texture, textureRect, newColor); } if (lightView && hasLight()) { lightView->addLightSource(screenRect.center(), m_light); } } const TexturePtr& ThingType::getTexture(const int animationPhase) { if (m_null) return m_textureNull; m_lastTimeUsage.restart(); auto& textureData = m_textureData[animationPhase]; auto& animationPhaseTexture = textureData.source; if (animationPhaseTexture) return animationPhaseTexture; bool async = g_app.isLoadingAsyncTexture(); if (g_game.isUsingProtobuf() && g_drawPool.getCurrentType() == DrawPoolType::FOREGROUND) async = false; if (!async) { loadTexture(animationPhase); return textureData.source; } if (!m_loading) { m_loading = true; auto action = [this] { for (int_fast8_t i = -1; ++i < m_animationPhases;) loadTexture(i); m_loading = false; }; g_asyncDispatcher.detach_task(std::move(action)); } return m_textureNull; } void ThingType::loadTexture(const int animationPhase) { auto& textureData = m_textureData[animationPhase]; if (textureData.source) return; // we don't need layers in common items, they will be pre-drawn int textureLayers = 1; int numLayers = m_layers; if (m_category == ThingCategoryCreature && numLayers >= 2) { // 5 layers: outfit base, red mask, green mask, blue mask, yellow mask textureLayers = 5; numLayers = 5; } const bool useCustomImage = animationPhase == 0 && !m_customImage.empty(); const int indexSize = textureLayers * m_numPatternX * m_numPatternY * m_numPatternZ; const auto& textureSize = getBestTextureDimension(m_size.width(), m_size.height(), indexSize); const auto& fullImage = useCustomImage ? Image::load(m_customImage) : std::make_shared<Image>(textureSize * g_gameConfig.getSpriteSize()); const bool protobufSupported = g_game.isUsingProtobuf(); static Color maskColors[] = { Color::red, Color::green, Color::blue, Color::yellow }; textureData.pos.resize(indexSize); for (int z = 0; z < m_numPatternZ; ++z) { for (int y = 0; y < m_numPatternY; ++y) { for (int x = 0; x < m_numPatternX; ++x) { for (int l = 0; l < numLayers; ++l) { const bool spriteMask = m_category == ThingCategoryCreature && l > 0; const int frameIndex = getTextureIndex(l % textureLayers, x, y, z); const auto& framePos = Point(frameIndex % (textureSize.width() / m_size.width()) * m_size.width(), frameIndex / (textureSize.width() / m_size.width()) * m_size.height()) * g_gameConfig.getSpriteSize(); if (!useCustomImage) { if (protobufSupported) { const uint32_t spriteIndex = getSpriteIndex(-1, -1, spriteMask ? 1 : l, x, y, z, animationPhase); auto spriteId = m_spritesIndex[spriteIndex]; bool isLoading = false; const auto& spriteImage = g_sprites.getSpriteImage(spriteId, isLoading); if (isLoading) return; // verifies that the first block in the lower right corner is transparent. if (!spriteImage || spriteImage->hasTransparentPixel()) { fullImage->setTransparentPixel(true); } if (spriteImage) { if (spriteMask) { spriteImage->overwriteMask(maskColors[(l - 1)]); } auto spriteSize = spriteImage->getSize() / g_gameConfig.getSpriteSize(); const Point& spritePos = Point(m_size.width() - spriteSize.width(), m_size.height() - spriteSize.height()) * g_gameConfig.getSpriteSize(); fullImage->blit(framePos + spritePos, spriteImage); } } else { for (int h = 0; h < m_size.height(); ++h) { for (int w = 0; w < m_size.width(); ++w) { const uint32_t spriteIndex = getSpriteIndex(w, h, spriteMask ? 1 : l, x, y, z, animationPhase); auto spriteId = m_spritesIndex[spriteIndex]; bool isLoading = false; const auto& spriteImage = g_sprites.getSpriteImage(spriteId, isLoading); if (isLoading) return; // verifies that the first block in the lower right corner is transparent. if (h == 0 && w == 0 && (!spriteImage || spriteImage->hasTransparentPixel())) { fullImage->setTransparentPixel(true); } if (spriteImage) { if (spriteMask) { spriteImage->overwriteMask(maskColors[(l - 1)]); } const Point& spritePos = Point(m_size.width() - w - 1, m_size.height() - h - 1) * g_gameConfig.getSpriteSize(); fullImage->blit(framePos + spritePos, spriteImage); } } } } } auto& posData = textureData.pos[frameIndex]; posData.rects = { framePos + Point(m_size.width(), m_size.height()) * g_gameConfig.getSpriteSize() - Point(1), framePos }; for (int fx = framePos.x; fx < framePos.x + m_size.width() * g_gameConfig.getSpriteSize(); ++fx) { for (int fy = framePos.y; fy < framePos.y + m_size.height() * g_gameConfig.getSpriteSize(); ++fy) { const uint8_t* p = fullImage->getPixel(fx, fy); if (p[3] == 0x00) continue; posData.rects.setTop(std::min<int>(fy, posData.rects.top())); posData.rects.setLeft(std::min<int>(fx, posData.rects.left())); posData.rects.setBottom(std::max<int>(fy, posData.rects.bottom())); posData.rects.setRight(std::max<int>(fx, posData.rects.right())); } } posData.originRects = Rect(framePos, Size(m_size.width(), m_size.height()) * g_gameConfig.getSpriteSize()); posData.offsets = posData.rects.topLeft() - framePos; } } } } if (m_opacity < 1.0f) fullImage->setTransparentPixel(true); if (m_opaque == -1) m_opaque = !fullImage->hasTransparentPixel(); textureData.source = std::make_shared<Texture>(fullImage, true, false); textureData.source->allowAtlasCache(); } Size ThingType::getBestTextureDimension(int w, int h, const int count) { int k = 1; while (k < w) k <<= 1; w = k; k = 1; while (k < h) k <<= 1; h = k; const int numSprites = w * h * count; assert(numSprites <= g_gameConfig.getSpriteSize() * g_gameConfig.getSpriteSize()); assert(w <= g_gameConfig.getSpriteSize()); assert(h <= g_gameConfig.getSpriteSize()); Size bestDimension = { g_gameConfig.getSpriteSize() }; for (int i = w; i <= g_gameConfig.getSpriteSize(); i <<= 1) { for (int j = h; j <= g_gameConfig.getSpriteSize(); j <<= 1) { Size candidateDimension = { i, j }; if (candidateDimension.area() < numSprites) continue; if ((candidateDimension.area() < bestDimension.area()) || (candidateDimension.area() == bestDimension.area() && candidateDimension.width() + candidateDimension.height() < bestDimension.width() + bestDimension.height())) bestDimension = candidateDimension; } } return bestDimension; } uint32_t ThingType::getSpriteIndex(const int w, const int h, const int l, const int x, const int y, const int z, const int a) const { uint32_t index = ((((((a % m_animationPhases) * m_numPatternZ + z) * m_numPatternY + y) * m_numPatternX + x) * m_layers + l) * m_size.height() + h) * m_size.width() + w; if (w == -1 && h == -1) { // protobuf does not use width and height, because sprite image is the exact sprite size, not split by 32x32, so -1 is passed instead index = ((((a % m_animationPhases) * m_numPatternZ + z) * m_numPatternY + y) * m_numPatternX + x) * m_layers + l; } assert(index < m_spritesIndex.size()); return index; } uint32_t ThingType::getTextureIndex(const int l, const int x, const int y, const int z) const { return ((l * m_numPatternZ + z) * m_numPatternY + y) * m_numPatternX + x; } int ThingType::getExactSize(const int layer, const int xPattern, const int yPattern, const int zPattern, const int animationPhase) { if (m_null) return 0; if (!getTexture(animationPhase)) // we must calculate it anyway. return 0; const int frameIndex = getTextureIndex(layer, xPattern, yPattern, zPattern); const auto& pos = m_textureData[animationPhase].pos; const auto& textureDataPos = pos[std::min<int>(frameIndex, pos.size() - 1)]; const auto& size = textureDataPos.originRects.size() - textureDataPos.offsets.toSize(); return std::max<int>(size.width(), size.height()); } void ThingType::setPathable(const bool var) { if (var == true) m_flags &= ~ThingFlagAttrNotPathable; else m_flags |= ThingFlagAttrNotPathable; } int ThingType::getExactHeight() { if (m_null) return 0; if (m_exactHeight != 0) return m_exactHeight; getTexture(0); const int frameIndex = getTextureIndex(0, 0, 0, 0); const auto& textureDataPos = m_textureData[0].pos[frameIndex]; const Size& size = textureDataPos.originRects.size() - textureDataPos.offsets.toSize(); return m_exactHeight = size.height(); } ThingFlagAttr ThingType::thingAttrToThingFlagAttr(const ThingAttr attr) { switch (attr) { case ThingAttrDisplacement: return ThingFlagAttrDisplacement; case ThingAttrLight: return ThingFlagAttrLight; case ThingAttrElevation: return ThingFlagAttrElevation; case ThingAttrGround: return ThingFlagAttrGround; case ThingAttrWritable: return ThingFlagAttrWritable; case ThingAttrWritableOnce: return ThingFlagAttrWritableOnce; case ThingAttrMinimapColor: return ThingFlagAttrMinimapColor; case ThingAttrCloth: return ThingFlagAttrCloth; case ThingAttrLensHelp: return ThingFlagAttrLensHelp; case ThingAttrDefaultAction: return ThingFlagAttrDefaultAction; case ThingAttrUsable: return ThingFlagAttrUsable; case ThingAttrGroundBorder: return ThingFlagAttrGroundBorder; case ThingAttrOnBottom: return ThingFlagAttrOnBottom; case ThingAttrOnTop: return ThingFlagAttrOnTop; case ThingAttrContainer: return ThingFlagAttrContainer; case ThingAttrStackable: return ThingFlagAttrStackable; case ThingAttrForceUse: return ThingFlagAttrForceUse; case ThingAttrMultiUse: return ThingFlagAttrMultiUse; case ThingAttrChargeable: return ThingFlagAttrChargeable; case ThingAttrFluidContainer: return ThingFlagAttrFluidContainer; case ThingAttrSplash: return ThingFlagAttrSplash; case ThingAttrNotWalkable: return ThingFlagAttrNotWalkable; case ThingAttrNotMoveable: return ThingFlagAttrNotMoveable; case ThingAttrBlockProjectile: return ThingFlagAttrBlockProjectile; case ThingAttrNotPathable: return ThingFlagAttrNotPathable; case ThingAttrPickupable: return ThingFlagAttrPickupable; case ThingAttrHangable: return ThingFlagAttrHangable; case ThingAttrHookSouth: return ThingFlagAttrHookSouth; case ThingAttrHookEast: return ThingFlagAttrHookEast; case ThingAttrRotateable: return ThingFlagAttrRotateable; case ThingAttrDontHide: return ThingFlagAttrDontHide; case ThingAttrTranslucent: return ThingFlagAttrTranslucent; case ThingAttrLyingCorpse: return ThingFlagAttrLyingCorpse; case ThingAttrAnimateAlways: return ThingFlagAttrAnimateAlways; case ThingAttrFullGround: return ThingFlagAttrFullGround; case ThingAttrLook: return ThingFlagAttrLook; case ThingAttrWrapable: return ThingFlagAttrWrapable; case ThingAttrUnwrapable: return ThingFlagAttrUnwrapable; case ThingAttrWearOut: return ThingFlagAttrWearOut; case ThingAttrClockExpire: return ThingFlagAttrClockExpire; case ThingAttrExpire: return ThingFlagAttrExpire; case ThingAttrExpireStop: return ThingFlagAttrExpireStop; case ThingAttrPodium: return ThingFlagAttrPodium; case ThingAttrTopEffect: return ThingFlagAttrTopEffect; case ThingAttrMarket: return ThingFlagAttrMarket; case ThingAttrDecoKit: return ThingFlagAttrDecoKit; default: break; } return ThingFlagAttrNone; } bool ThingType::isTall(const bool useRealSize) { return useRealSize ? getRealSize() > g_gameConfig.getSpriteSize() : getHeight() > 1; } #ifdef FRAMEWORK_EDITOR void ThingType::serialize(const FileStreamPtr& fin) { for (int i = 0; i < ThingLastAttr; ++i) { int attr = i; if (g_game.getClientVersion() >= 780) { if (attr == ThingAttrChargeable) attr = ThingAttrWritable; else if (attr >= ThingAttrWritable) attr += 1; } else if (g_game.getClientVersion() >= 1000) { if (attr == ThingAttrNoMoveAnimation) attr = 16; else if (attr >= ThingAttrPickupable) attr += 1; } if (!hasAttr(static_cast<ThingAttr>(attr))) continue; switch (attr) { case ThingAttrDisplacement: { fin->addU16(m_displacement.x); fin->addU16(m_displacement.y); break; } case ThingAttrLight: { fin->addU16(m_light.intensity); fin->addU16(m_light.color); break; } case ThingAttrMarket: { fin->addU16(m_market.category); fin->addU16(m_market.tradeAs); fin->addU16(m_market.showAs); fin->addString(m_market.name); fin->addU16(m_market.restrictVocation); fin->addU16(m_market.requiredLevel); break; } case ThingAttrElevation: fin->addU16(m_elevation); break; case ThingAttrMinimapColor: fin->add16(m_minimapColor); break; case ThingAttrCloth: fin->add16(m_clothSlot); break; case ThingAttrLensHelp: fin->add16(m_lensHelp); break; case ThingAttrUsable: fin->add16(isUsable()); break; case ThingAttrGround: fin->add16(isGround()); break; case ThingAttrWritable: fin->add16(isWritable()); break; case ThingAttrWritableOnce: fin->add16(isWritableOnce()); break; break; default: break; } } fin->addU8(ThingLastAttr); fin->addU8(m_size.width()); fin->addU8(m_size.height()); if (m_size.width() > 1 || m_size.height() > 1) fin->addU8(m_realSize); fin->addU8(m_layers); fin->addU8(m_numPatternX); fin->addU8(m_numPatternY); fin->addU8(m_numPatternZ); fin->addU8(m_animationPhases); if (g_game.getFeature(Otc::GameEnhancedAnimations)) { if (m_animationPhases > 1 && m_animator) { m_animator->serialize(fin); } } for (const int i : m_spritesIndex) { if (g_game.getFeature(Otc::GameSpritesU32)) fin->addU32(i); else fin->addU16(i); } } void ThingType::exportImage(const std::string& fileName) { if (m_null) throw Exception("cannot export null thingtype"); if (m_spritesIndex.empty()) throw Exception("cannot export thingtype without sprites"); const auto& image = std::make_shared<Image>(Size(g_gameConfig.getSpriteSize() * m_size.width() * m_layers * m_numPatternX, g_gameConfig.getSpriteSize() * m_size.height() * m_animationPhases * m_numPatternY * m_numPatternZ)); for (int z = 0; z < m_numPatternZ; ++z) { for (int y = 0; y < m_numPatternY; ++y) { for (int x = 0; x < m_numPatternX; ++x) { for (int l = 0; l < m_layers; ++l) { for (int a = 0; a < m_animationPhases; ++a) { for (int w = 0; w < m_size.width(); ++w) { for (int h = 0; h < m_size.height(); ++h) { image->blit(Point(g_gameConfig.getSpriteSize() * (m_size.width() - w - 1 + m_size.width() * x + m_size.width() * m_numPatternX * l), g_gameConfig.getSpriteSize() * (m_size.height() - h - 1 + m_size.height() * y + m_size.height() * m_numPatternY * a + m_size.height() * m_numPatternY * m_animationPhases * z)), g_sprites.getSpriteImage(m_spritesIndex[getSpriteIndex(w, h, l, x, y, z, a)])); } } } } } } } image->savePNG(fileName); } #endif
412
0.962652
1
0.962652
game-dev
MEDIA
0.81234
game-dev
0.921153
1
0.921153
Bobris/BTDB
1,825
BTDB/KVDBLayer/Implementation/IKeyValueDBInternal.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BTDB.Collections; using BTDB.StreamLayer; namespace BTDB.KVDBLayer; public delegate void ValuesIterateAction(uint valueFileId, uint valueOfs, int valueSize); interface IKeyValueDBInternal : IKeyValueDB { long GetGeneration(uint fileId); void MarkAsUnknown(IEnumerable<uint> fileIds); IFileCollectionWithFileInfos FileCollection { get; } bool ContainsValuesAndDoesNotTouchGeneration(uint fileKey, long dontTouchGeneration); bool AreAllTransactionsBeforeFinished(long transactionId); // This will reference that root, after use you need to call DereferenceRootNodeInternal IRootNodeInternal ReferenceAndGetOldestRoot(); // This will reference that root, after use you need to call DereferenceRootNodeInternal IRootNodeInternal ReferenceAndGetLastCommitted(); void DereferenceRootNodeInternal(IRootNodeInternal root); ValueTask<long> ReplaceBTreeValues(CancellationToken cancellation, RefDictionary<ulong, uint> newPositionMap, uint targetFileId); long[] CreateIndexFile(CancellationToken cancellation, long preserveKeyIndexGeneration); MemWriter StartPureValuesFile(out uint fileId); bool LoadUsedFilesFromKeyIndex(uint fileId, IKeyIndex info); long CalculatePreserveKeyIndexGeneration(uint preserveKeyIndexKey); ulong DistanceFromLastKeyIndex(IRootNodeInternal root); Span<KeyIndexInfo> BuildKeyIndexInfos(); uint CalculatePreserveKeyIndexKeyFromKeyIndexInfos(ReadOnlySpan<KeyIndexInfo> keyIndexes); uint GetTrLogFileId(IRootNodeInternal root); void IterateRoot(IRootNodeInternal root, ValuesIterateAction visit); void GatherUsedFiles(CancellationToken cancellation, IRootNodeInternal root, ISet<uint> usedFileIds); }
412
0.775668
1
0.775668
game-dev
MEDIA
0.27428
game-dev
0.86127
1
0.86127
moneymod/moneymod
3,906
src/main/java/wtf/moneymod/client/mixin/mixins/MixinEntityOtherPlayerMP.java
package wtf.moneymod.client.mixin.mixins; import com.mojang.authlib.GameProfile; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import wtf.moneymod.client.Main; import wtf.moneymod.client.impl.module.render.NoInterp; @Mixin( EntityOtherPlayerMP.class ) public class MixinEntityOtherPlayerMP extends AbstractClientPlayer { @Shadow private int otherPlayerMPPosRotationIncrements; @Shadow private double otherPlayerMPX; @Shadow private double otherPlayerMPY; @Shadow private double otherPlayerMPZ; @Shadow private double otherPlayerMPYaw; @Shadow private double otherPlayerMPPitch; public MixinEntityOtherPlayerMP( World worldIn, GameProfile gameProfileIn ) { super( worldIn, gameProfileIn ); } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ @Overwrite public void onLivingUpdate() { if (this.otherPlayerMPPosRotationIncrements > 0) { double d0, d1, d2; double d3; if( Main.getMain().getModuleManager().get(NoInterp.class).isToggled()) { d0 = serverPosX / 4096.0D; d1 = serverPosY / 4096.0D; d2 = serverPosZ / 4096.0D; } else { d0 = this.posX + (this.otherPlayerMPX - this.posX) / otherPlayerMPPosRotationIncrements; d1 = this.posY + (this.otherPlayerMPY - this.posY) / otherPlayerMPPosRotationIncrements; d2 = this.posZ + (this.otherPlayerMPZ - this.posZ) / otherPlayerMPPosRotationIncrements; } for (d3 = this.otherPlayerMPYaw - (double)this.rotationYaw; d3 < -180.0D; d3 += 360.0D) {} while (d3 >= 180.0D) {d3 -= 360.0D;} this.rotationYaw = (float)((double)this.rotationYaw + d3 / (double)this.otherPlayerMPPosRotationIncrements); this.rotationPitch = (float)((double)this.rotationPitch + (this.otherPlayerMPPitch - (double)this.rotationPitch) / (double)this.otherPlayerMPPosRotationIncrements); --this.otherPlayerMPPosRotationIncrements; this.setPosition(d0, d1, d2); this.setRotation(this.rotationYaw, this.rotationPitch); } this.prevCameraYaw = this.cameraYaw; this.updateArmSwingProgress(); float f1 = MathHelper.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ); float f = (float)Math.atan(-this.motionY * 0.20000000298023224D) * 15.0F; if (f1 > 0.1F) {f1 = 0.1F;} if (!this.onGround || this.getHealth() <= 0.0F) {f1 = 0.0F;} if (this.onGround || this.getHealth() <= 0.0F) {f = 0.0F;} this.cameraYaw += (f1 - this.cameraYaw) * 0.4F; this.cameraPitch += (f - this.cameraPitch) * 0.8F; this.world.profiler.startSection("push"); this.collideWithNearbyEntities(); this.world.profiler.endSection(); } @Inject(method = "onUpdate", at = @At ("HEAD"), cancellable = true) public void prikol(CallbackInfo ci) { if(((NoInterp)Main.getMain().getModuleManager().get(NoInterp.class)).animation) { renderOffsetY = 0; super.onUpdate(); limbSwing = 0; limbSwingAmount = 0; prevLimbSwingAmount = 0; ci.cancel(); } } }
412
0.642471
1
0.642471
game-dev
MEDIA
0.902552
game-dev
0.902898
1
0.902898
AppliedEnergistics/Applied-Energistics-2
9,138
src/main/java/appeng/client/gui/widgets/UpgradesPanel.java
/* * This file is part of Applied Energistics 2. * Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved. * * Applied Energistics 2 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. * * Applied Energistics 2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>. */ package appeng.client.gui.widgets; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import org.jetbrains.annotations.Nullable; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.renderer.Rect2i; import net.minecraft.network.chat.Component; import net.minecraft.world.inventory.Slot; import appeng.api.upgrades.IUpgradeableObject; import appeng.api.upgrades.Upgrades; import appeng.client.Point; import appeng.client.gui.AEBaseScreen; import appeng.client.gui.ICompositeWidget; import appeng.client.gui.Rects; import appeng.client.gui.Tooltip; import appeng.client.gui.style.Blitter; import appeng.menu.slot.AppEngSlot; /** * A panel that can draw a dynamic number of upgrade slots in a vertical layout. */ public final class UpgradesPanel implements ICompositeWidget { private static final int SLOT_SIZE = 18; private static final int PADDING = 5; private static final int MAX_ROWS = 8; private static final Blitter BACKGROUND = Blitter.texture("guis/extra_panels.png", 128, 128); private static final Blitter INNER_CORNER = BACKGROUND.copy().src(12, 33, SLOT_SIZE, SLOT_SIZE); private final List<Slot> slots; // The screen origin in window space (used to layout slots) private Point screenOrigin = Point.ZERO; // Relative to current screen origin (not window) private int x; private int y; private final Supplier<List<Component>> tooltipSupplier; public UpgradesPanel(List<Slot> slots) { this(slots, Collections::emptyList); } public UpgradesPanel(List<Slot> slots, IUpgradeableObject upgradeableObject) { this(slots, () -> Upgrades.getTooltipLinesForMachine(upgradeableObject.getUpgrades().getUpgradableItem())); } public UpgradesPanel(List<Slot> slots, Supplier<List<Component>> tooltipSupplier) { this.slots = slots; this.tooltipSupplier = tooltipSupplier; } @Override public void setPosition(Point position) { x = position.getX(); y = position.getY(); } /** * Changes where the panel is positioned. Coordinates are relative to the current screen's origin. */ @Override public void setSize(int width, int height) { // Size of upgrades panel cannot be set via JSON } /** * The overall bounding box in screen coordinates. */ @Override public Rect2i getBounds() { int slotCount = getUpgradeSlotCount(); int height = 2 * PADDING + Math.min(MAX_ROWS, slotCount) * SLOT_SIZE; int width = 2 * PADDING + (slotCount + MAX_ROWS - 1) / MAX_ROWS * SLOT_SIZE; return new Rect2i(x, y, width, height); } @Override public void populateScreen(Consumer<AbstractWidget> addWidget, Rect2i bounds, AEBaseScreen<?> screen) { this.screenOrigin = Point.fromTopLeft(bounds); } @Override public void updateBeforeRender() { int slotOriginX = this.x; int slotOriginY = this.y + PADDING; for (Slot slot : slots) { if (!slot.isActive()) { continue; } slot.x = slotOriginX + 1; slot.y = slotOriginY + 1; slotOriginY += SLOT_SIZE; } } @Override public void drawBackgroundLayer(GuiGraphics guiGraphics, Rect2i bounds, Point mouse) { int slotCount = getUpgradeSlotCount(); if (slotCount <= 0) { return; } // This is the absolute x,y coord of the first slot within the panel int slotOriginX = screenOrigin.getX() + this.x + PADDING; int slotOriginY = screenOrigin.getY() + this.y + PADDING; for (int i = 0; i < slotCount; i++) { // Unlike other UIs, this is drawn top-to-bottom,left-to-right int row = i % MAX_ROWS; int col = i / MAX_ROWS; int x = slotOriginX + col * SLOT_SIZE; int y = slotOriginY + row * SLOT_SIZE; boolean borderLeft = col == 0; boolean borderTop = row == 0; // The panel can have a "jagged" edge if the number of slots is not divisible by MAX_ROWS boolean lastSlot = i + 1 >= slotCount; boolean lastRow = row + 1 >= MAX_ROWS; boolean borderBottom = lastRow || lastSlot; boolean borderRight = i >= slotCount - MAX_ROWS; drawSlot(guiGraphics, x, y, borderLeft, borderTop, borderRight, borderBottom); // Cover up the inner corner when we just drew a rather ugly "inner corner" if (col > 0 && lastSlot && !lastRow) { INNER_CORNER.dest(x, y + SLOT_SIZE).blit(guiGraphics); } } // Added border to match the rest of the GUI style - RID guiGraphics.hLine(slotOriginX - 4, slotOriginX + 11, slotOriginY, 0XFFf2f2f2); guiGraphics.hLine(slotOriginX - 4, slotOriginX + 11, slotOriginY + (SLOT_SIZE * slotCount) - 1, 0XFFf2f2f2); guiGraphics.vLine(slotOriginX - 5, slotOriginY - 1, slotOriginY + (SLOT_SIZE * slotCount), 0XFFf2f2f2); guiGraphics.vLine(slotOriginX + 12, slotOriginY - 1, slotOriginY + (SLOT_SIZE * slotCount), 0XFFf2f2f2); } @Override public void addExclusionZones(List<Rect2i> exclusionZones, Rect2i screenBounds) { int offsetX = screenBounds.getX(); int offsetY = screenBounds.getY(); int slotCount = getUpgradeSlotCount(); // Use a bit of a margin around the zone to avoid things looking too cramped final int margin = 2; // Add a single bounding rectangle for as many columns as are fully populated int fullCols = slotCount / MAX_ROWS; int rightEdge = offsetX + x; if (fullCols > 0) { int fullColWidth = PADDING * 2 + fullCols * SLOT_SIZE; exclusionZones.add(Rects.expand(new Rect2i( rightEdge, offsetY + y, fullColWidth, PADDING * 2 + MAX_ROWS * SLOT_SIZE), margin)); rightEdge += fullColWidth; } // If there's a partially populated row at the end, add a smaller rectangle for it int remaining = slotCount - fullCols * MAX_ROWS; if (remaining > 0) { exclusionZones.add(Rects.expand(new Rect2i( rightEdge, offsetY + y, // We need to add padding in case there's no full column that already includes it SLOT_SIZE + (fullCols > 0 ? 0 : PADDING * 2), PADDING * 2 + remaining * SLOT_SIZE), margin)); } } @Nullable @Override public Tooltip getTooltip(int mouseX, int mouseY) { if (getUpgradeSlotCount() == 0) { return null; } List<Component> tooltip = this.tooltipSupplier.get(); if (tooltip.isEmpty()) { return null; } return new Tooltip(tooltip); } private static void drawSlot(GuiGraphics guiGraphics, int x, int y, boolean borderLeft, boolean borderTop, boolean borderRight, boolean borderBottom) { int srcX = PADDING; int srcY = PADDING; int srcWidth = SLOT_SIZE; int srcHeight = SLOT_SIZE; if (borderLeft) { x -= PADDING; srcX = 0; srcWidth += PADDING; } if (borderRight) { srcWidth += PADDING; } if (borderTop) { y -= PADDING; srcY = 0; srcHeight += PADDING; } if (borderBottom) { srcHeight += PADDING + 2; } BACKGROUND.src(srcX, srcY, srcWidth, srcHeight) .dest(x, y) .blit(guiGraphics); } /** * We need this function since the cell workbench can dynamically change how many upgrade slots are active based on * the cell in the workbench. */ private int getUpgradeSlotCount() { int count = 0; for (Slot slot : slots) { if (slot instanceof AppEngSlot && ((AppEngSlot) slot).isSlotEnabled()) { count++; } } return count; } }
412
0.938662
1
0.938662
game-dev
MEDIA
0.638115
game-dev
0.970578
1
0.970578
Team-Beef-Studios/Doom3Quest
2,958
app/src/main/jni/d3es-multithread-master/neo/tools/common/SpinButton.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "tools/edit_gui_common.h" #include "SpinButton.h" void SpinButton_SetIncrement ( HWND hWnd, float inc ) { SetWindowLong ( hWnd, GWL_USERDATA, (long)(inc * 100.0f) ); } void SpinButton_SetRange ( HWND hWnd, float minRange, float maxRange ) { SendMessage ( hWnd, UDM_SETRANGE32, (LONG)(minRange*100.0f), (LONG)(maxRange*100.0f) ); } void SpinButton_HandleNotify ( NMHDR* hdr ) { // Return if incorrect data in edit box NM_UPDOWN* udhdr= (NM_UPDOWN*)hdr; // Change with 0.1 on each click char strValue[64]; float value; GetWindowText ( (HWND)SendMessage ( hdr->hwndFrom, UDM_GETBUDDY, 0, 0 ), strValue, 63 ); float inc = (float)GetWindowLong ( hdr->hwndFrom, GWL_USERDATA ); if ( inc == 0 ) { inc = 100.0f; SetWindowLong ( hdr->hwndFrom, GWL_USERDATA, 100 ); } inc /= 100.0f; if ( GetAsyncKeyState ( VK_SHIFT ) & 0x8000 ) { inc *= 10.0f; } value = atof(strValue); value += (udhdr->iDelta)*(inc); // Avoid round-off errors value = floor(value*1e3+0.5)/1e3; LONG minRange; LONG maxRange; SendMessage ( hdr->hwndFrom, UDM_GETRANGE32, (LONG)&minRange, (LONG)&maxRange ); if ( minRange != 0 || maxRange != 0 ) { float minRangef = (float)(long)minRange / 100.0f; float maxRangef = (float)maxRange / 100.0f; if ( value > maxRangef ) { value = maxRangef; } if ( value < minRangef ) { value = minRangef; } } SetWindowText ( (HWND)SendMessage ( hdr->hwndFrom, UDM_GETBUDDY, 0, 0 ), va("%g",value) ); }
412
0.800196
1
0.800196
game-dev
MEDIA
0.938373
game-dev
0.783741
1
0.783741
Smufrik/Hekili
10,586
Libs/AceGUI-3.0/widgets/AceGUIWidget-DropDown-Items.lua
--[[ $Id: AceGUIWidget-DropDown-Items.lua 1272 2022-08-29 15:56:35Z nevcairiel $ ]]-- local AceGUI = LibStub("AceGUI-3.0") -- Lua APIs local select, assert = select, assert -- WoW APIs local PlaySound = PlaySound local CreateFrame = CreateFrame local function fixlevels(parent,...) local i = 1 local child = select(i, ...) while child do child:SetFrameLevel(parent:GetFrameLevel()+1) fixlevels(child, child:GetChildren()) i = i + 1 child = select(i, ...) end end local function fixstrata(strata, parent, ...) local i = 1 local child = select(i, ...) parent:SetFrameStrata(strata) while child do fixstrata(strata, child, child:GetChildren()) i = i + 1 child = select(i, ...) end end -- ItemBase is the base "class" for all dropdown items. -- Each item has to use ItemBase.Create(widgetType) to -- create an initial 'self' value. -- ItemBase will add common functions and ui event handlers. -- Be sure to keep basic usage when you override functions. local ItemBase = { -- NOTE: The ItemBase version is added to each item's version number -- to ensure proper updates on ItemBase changes. -- Use at least 1000er steps. version = 2000, counter = 0, } function ItemBase.Frame_OnEnter(this) local self = this.obj if self.useHighlight then self.highlight:Show() end self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end function ItemBase.Frame_OnLeave(this) local self = this.obj self.highlight:Hide() self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, AceGUI callback function ItemBase.OnAcquire(self) self.frame:SetToplevel(true) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") end -- exported, AceGUI callback function ItemBase.OnRelease(self) self:SetDisabled(false) self.pullout = nil self.frame:SetParent(nil) self.frame:ClearAllPoints() self.frame:Hide() end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetPullout(self, pullout) self.pullout = pullout self.frame:SetParent(nil) self.frame:SetParent(pullout.itemFrame) self.parent = pullout.itemFrame fixlevels(pullout.itemFrame, pullout.itemFrame:GetChildren()) end -- exported function ItemBase.SetText(self, text) self.text:SetText(text or "") end -- exported function ItemBase.GetText(self) return self.text:GetText() end -- exported function ItemBase.SetPoint(self, ...) self.frame:SetPoint(...) end -- exported function ItemBase.Show(self) self.frame:Show() end -- exported function ItemBase.Hide(self) self.frame:Hide() end -- exported function ItemBase.SetDisabled(self, disabled) self.disabled = disabled if disabled then self.useHighlight = false self.text:SetTextColor(.5, .5, .5) else self.useHighlight = true self.text:SetTextColor(1, 1, 1) end end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnLeave(self, func) self.specialOnLeave = func end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnEnter(self, func) self.specialOnEnter = func end function ItemBase.Create(type) -- NOTE: Most of the following code is copied from AceGUI-3.0/Dropdown widget local count = AceGUI:GetNextWidgetNum(type) local frame = CreateFrame("Button", "AceGUI30DropDownItem"..count) local self = {} self.frame = frame frame.obj = self self.type = type self.useHighlight = true frame:SetHeight(17) frame:SetFrameStrata("FULLSCREEN_DIALOG") local text = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall") text:SetTextColor(1,1,1) text:SetJustifyH("LEFT") text:SetPoint("TOPLEFT",frame,"TOPLEFT",18,0) text:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-8,0) self.text = text local highlight = frame:CreateTexture(nil, "OVERLAY") highlight:SetTexture(136810) -- Interface\\QuestFrame\\UI-QuestTitleHighlight highlight:SetBlendMode("ADD") highlight:SetHeight(14) highlight:ClearAllPoints() highlight:SetPoint("RIGHT",frame,"RIGHT",-3,0) highlight:SetPoint("LEFT",frame,"LEFT",5,0) highlight:Hide() self.highlight = highlight local check = frame:CreateTexture(nil, "OVERLAY") check:SetWidth(16) check:SetHeight(16) check:SetPoint("LEFT",frame,"LEFT",3,-1) check:SetTexture(130751) -- Interface\\Buttons\\UI-CheckBox-Check check:Hide() self.check = check local sub = frame:CreateTexture(nil, "OVERLAY") sub:SetWidth(16) sub:SetHeight(16) sub:SetPoint("RIGHT",frame,"RIGHT",-3,-1) sub:SetTexture(130940) -- Interface\\ChatFrame\\ChatFrameExpandArrow sub:Hide() self.sub = sub frame:SetScript("OnEnter", ItemBase.Frame_OnEnter) frame:SetScript("OnLeave", ItemBase.Frame_OnLeave) self.OnAcquire = ItemBase.OnAcquire self.OnRelease = ItemBase.OnRelease self.SetPullout = ItemBase.SetPullout self.GetText = ItemBase.GetText self.SetText = ItemBase.SetText self.SetDisabled = ItemBase.SetDisabled self.SetPoint = ItemBase.SetPoint self.Show = ItemBase.Show self.Hide = ItemBase.Hide self.SetOnLeave = ItemBase.SetOnLeave self.SetOnEnter = ItemBase.SetOnEnter return self end -- Register a dummy LibStub library to retrieve the ItemBase, so other addons can use it. local IBLib = LibStub:NewLibrary("AceGUI-3.0-DropDown-ItemBase", ItemBase.version) if IBLib then IBLib.GetItemBase = function() return ItemBase end end --[[ Template for items: -- Item: -- do local widgetType = "Dropdown-Item-" local widgetVersion = 1 local function Constructor() local self = ItemBase.Create(widgetType) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end --]] -- Item: Header -- A single text entry. -- Special: Different text color and no highlight do local widgetType = "Dropdown-Item-Header" local widgetVersion = 1 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end local function OnLeave(this) local self = this.obj self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) if not disabled then self.text:SetTextColor(1, 1, 0) end end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnLeave", OnLeave) self.text:SetTextColor(1, 1, 0) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Execute -- A simple button do local widgetType = "Dropdown-Item-Execute" local widgetVersion = 1 local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self:Fire("OnClick") if self.pullout then self.pullout:Close() end end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Toggle -- Some sort of checkbox for dropdown menus. -- Does not close the pullout on click. do local widgetType = "Dropdown-Item-Toggle" local widgetVersion = 4 local function UpdateToggle(self) if self.value then self.check:Show() else self.check:Hide() end end local function OnRelease(self) ItemBase.OnRelease(self) self:SetValue(nil) end local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self.value = not self.value if self.value then PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON else PlaySound(857) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF end UpdateToggle(self) self:Fire("OnValueChanged", self.value) end -- exported local function SetValue(self, value) self.value = value UpdateToggle(self) end -- exported local function GetValue(self) return self.value end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) self.SetValue = SetValue self.GetValue = GetValue self.OnRelease = OnRelease AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Menu -- Shows a submenu on mouse over -- Does not close the pullout on click do local widgetType = "Dropdown-Item-Menu" local widgetVersion = 2 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end self.highlight:Show() if not self.disabled and self.submenu then self.submenu:Open("TOPLEFT", self.frame, "TOPRIGHT", self.pullout:GetRightBorderWidth(), 0, self.frame:GetFrameLevel() + 100) end end local function OnHide(this) local self = this.obj if self.submenu then self.submenu:Close() end end -- exported local function SetMenu(self, menu) assert(menu.type == "Dropdown-Pullout") self.submenu = menu end -- exported local function CloseMenu(self) self.submenu:Close() end local function Constructor() local self = ItemBase.Create(widgetType) self.sub:Show() self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnHide", OnHide) self.SetMenu = SetMenu self.CloseMenu = CloseMenu AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Separator -- A single line to separate items do local widgetType = "Dropdown-Item-Separator" local widgetVersion = 2 -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) self.useHighlight = false end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled local line = self.frame:CreateTexture(nil, "OVERLAY") line:SetHeight(1) line:SetColorTexture(.5, .5, .5) line:SetPoint("LEFT", self.frame, "LEFT", 10, 0) line:SetPoint("RIGHT", self.frame, "RIGHT", -10, 0) self.text:Hide() self.useHighlight = false AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end
412
0.952302
1
0.952302
game-dev
MEDIA
0.817225
game-dev,desktop-app
0.940626
1
0.940626
chenmingbiao/stone-age
3,312
gmsv/include/npcutil.h
#ifndef _NPCUTIL_H_ #define _NPCUTIL_H_ BOOL NPC_Util_AddOneTitle( int charindex, int titleindex ); BOOL NPC_Util_HaveTitle( int charindex , int titleindex ); BOOL NPC_Util_Nearby( int x1 , int y1, int x2 , int y2 ); BOOL NPC_Util_CharNearby(int ind1,int ind2); int NPC_Util_YN(char *input ); int NPC_Util_getDirFromTwoPoint( POINT* pstart, POINT* pend ); int NPC_Util_countHaveItem( int meindex , int itemid ); BOOL NPC_Util_isBackContact( int frontindex , int backindex ); void NPC_Util_AnnounceFloor( int floorid , char *msg ); BOOL NPC_Util_moveItemToChar( int charindex, int itemindex,BOOL net ); BOOL NPC_Util_createItemToChar( int charindex, int itemid , BOOL net); int NPC_Util_CharDistance( int index1, int index2 ); int NPC_Util_SearchNear( int meindex, int maxlen, int type ); int NPC_Util_SearchNearPlayer( int meindex, int maxlen ); int NPC_Util_SearchNearEnemy( int meindex, int maxlen ); int NPC_Util_SuberiWalk( int index, int dir ); int NPC_Util_GetNumFromArg( int meindex, char* in); int NPC_Util_GetDirCharToChar( int fromindex, int toindex, int mode); int NPC_Util_WalkCharToChar( int fromindex, int toindex, int mode, int suberi); BOOL NPC_Util_isFaceToFace( int index1, int index2, int distance ); BOOL NPC_Util_isFaceToChara( int index1, int index2, int distance ); BOOL NPC_Util_charIsInFrontOfChar( int index1, int index2, int distance ); int NPC_Util_SearchItemInChar( int charindex , int itemindex); int NPC_Util_GiveAllItemToChar( int give , int take ); /* int NPC_Util_ControlOtherNPC( CHAR_TYPE chartype , char *npcname, char *command ); */ void NPC_Util_NPCDelete( int srcindex ); BOOL NPC_Util_moveItemToMap( int itemindex , int fl , int x , int y, BOOL net ); char *NPC_Util_GetArgStr( int index, char *argstr, int len); int NPC_Util_GetNumFromStrWithDelim( char *srcstr, char* in); char *NPC_Util_GetStrFromStrWithDelim( char *srcstr, char *srhstr, char *buf, int len); inline double NPC_Util_sellRate( int seller ); inline double NPC_Util_buyRate( int buyer ); BOOL NPC_Util_IsVisiblePlayer( int meindex); BOOL NPC_Util_WordInclude( char *text , char *word ); void NPC_Util_RandomToken(char *in, char *out, int outbufsize ); void cutDotsTail( char *s ); int NPC_Util_FrontItem( int meindex ); void NPC_Util_Boss2KingStart( int bossindex ); int NPC_Util_FrontChar( int meindex ); int *NPC_Util_getEnemy( int meindex, int charaindex); void NPC_NowEndEventSetFlgCls(int talker,int shiftbit); void NPC_EventSetFlg(int talker,int shiftbit); BOOL NPC_EventCheckFlg(int point,int shiftbit); void NPC_NowEventSetFlg(int talker,int shiftbit); void NPC_NowEventSetFlgCls(int talker,int shiftbit); BOOL NPC_NowEventCheckFlg(int point,int shiftbit); char *NPC_Util_CheckAssignArgFile( int index, char *filename); // CoolFish: Family Adv 2001/8/4 void AddFMAdv(int talker, int shiftbit); // Robin 0817 family income int addNpcFamilyTax( int meindex, int talkerindex, int income ); #define NPC_ENEMY_ENEMYNUMBER 10 /* س */ /* ¦Ѱ̻ ļ漰 ٯ */ #define NPC_UTIL_GETARGSTR_LINEMAX 4096 /* ¦Ѱ̻P */ #ifdef _NEWEVENT //#define NPC_UTIL_GETARGSTR_BUFSIZE 1024*1200 #define NPC_UTIL_GETARGSTR_BUFSIZE 1024*32 #else #define NPC_UTIL_GETARGSTR_BUFSIZE 1024*12 #endif #endif
412
0.852419
1
0.852419
game-dev
MEDIA
0.796758
game-dev
0.531283
1
0.531283
Frostshake/WMVx
2,200
src/core/modeling/Attachment.cpp
#include "../../stdafx.h" #include "Attachment.h" #include "Model.h" namespace core { Attachment::Attachment(CharacterSlot slot): ComponentMeta(ComponentMeta::Type::ATTACHMENT) { AttachOwnedModel owned; owned.model = nullptr; owned.bone = 0; owned.position = Vector3(); modelData.emplace<AttachOwnedModel>(std::move(owned)); characterSlot = slot; } Attachment::Attachment(MergedModel* merged_model, CharacterSlot slot) : ComponentMeta(ComponentMeta::Type::ATTACHMENT) { AttachMergedModel merged; merged.model = merged_model; modelData.emplace<AttachMergedModel>(std::move(merged)); characterSlot = slot; } void Attachment::update(const Animator& animator, const AnimationTickArgs& tick) { visit<AttachOwnedModel>([&](AttachOwnedModel* owned) { owned->model->calculateBones(animator.getAnimationIndex().value(), tick); owned->updateAnimation(); owned->model->updateParticles(animator.getAnimationIndex().value(), tick); owned->model->updateRibbons(animator.getAnimationIndex().value(), tick); }); for (auto& effect : effects) { effect->update(animator, tick); } } CharacterSlot Attachment::getSlot() const { return characterSlot; } void Attachment::setPosition(AttachmentPosition attach_pos, uint16_t set_bone, const Vector3& set_pos) { attachmentPosition = attach_pos; visit<AttachOwnedModel>([&](AttachOwnedModel* owned) { owned->bone = set_bone; owned->position = set_pos; }); } M2Model* Attachment::getModel() const { return std::visit([](const auto& data) -> M2Model* { if constexpr (std::is_same_v<const Attachment::AttachOwnedModel&, decltype(data)>) { return data.model.get(); } else if constexpr (std::is_same_v<const Attachment::AttachMergedModel&, decltype(data)>) { return data.model->model.get(); } return nullptr; }, modelData); } Attachment::AttachMergedModel::AttachMergedModel(AttachMergedModel&& source) { model = source.model; source.model = nullptr; } Attachment::AttachMergedModel::~AttachMergedModel() { if (model != nullptr && model->owner != nullptr) { model->owner->removeRelation(model->getType(), model->getId()); model = nullptr; } } }
412
0.880827
1
0.880827
game-dev
MEDIA
0.733012
game-dev
0.564275
1
0.564275
cvet/fonline
4,721
ThirdParty/SDL/src/test/SDL_test_font.c
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <SDL3/SDL_test.h> #define UTF8_IsTrailingByte(c) ((c) >= 0x80 && (c) <= 0xBF) int FONT_CHARACTER_SIZE = SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE; bool SDLTest_DrawCharacter(SDL_Renderer *renderer, float x, float y, Uint32 c) { char str[5]; char *ptr = SDL_UCS4ToUTF8(c, str); *ptr = '\0'; return SDL_RenderDebugText(renderer, x, y, str); } bool SDLTest_DrawString(SDL_Renderer *renderer, float x, float y, const char *s) { return SDL_RenderDebugText(renderer, x, y, s); } SDLTest_TextWindow *SDLTest_TextWindowCreate(float x, float y, float w, float h) { SDLTest_TextWindow *textwin = (SDLTest_TextWindow *)SDL_malloc(sizeof(*textwin)); if (!textwin) { return NULL; } textwin->rect.x = x; textwin->rect.y = y; textwin->rect.w = w; textwin->rect.h = h; textwin->current = 0; textwin->numlines = (int)SDL_ceilf(h / FONT_LINE_HEIGHT); textwin->lines = (char **)SDL_calloc(textwin->numlines, sizeof(*textwin->lines)); if (!textwin->lines) { SDL_free(textwin); return NULL; } return textwin; } void SDLTest_TextWindowDisplay(SDLTest_TextWindow *textwin, SDL_Renderer *renderer) { int i; float y; for (y = textwin->rect.y, i = 0; i < textwin->numlines; ++i, y += FONT_LINE_HEIGHT) { if (textwin->lines[i]) { SDLTest_DrawString(renderer, textwin->rect.x, y, textwin->lines[i]); } } } void SDLTest_TextWindowAddText(SDLTest_TextWindow *textwin, const char *fmt, ...) { char text[1024]; va_list ap; va_start(ap, fmt); (void)SDL_vsnprintf(text, sizeof(text), fmt, ap); va_end(ap); SDLTest_TextWindowAddTextWithLength(textwin, text, SDL_strlen(text)); } void SDLTest_TextWindowAddTextWithLength(SDLTest_TextWindow *textwin, const char *text, size_t len) { size_t existing; bool newline = false; char *line; if (len > 0 && text[len - 1] == '\n') { --len; newline = true; } if (textwin->lines[textwin->current]) { existing = SDL_strlen(textwin->lines[textwin->current]); } else { existing = 0; } if (*text == '\b') { if (existing) { while (existing > 1 && UTF8_IsTrailingByte((Uint8)textwin->lines[textwin->current][existing - 1])) { --existing; } --existing; textwin->lines[textwin->current][existing] = '\0'; } else if (textwin->current > 0) { SDL_free(textwin->lines[textwin->current]); textwin->lines[textwin->current] = NULL; --textwin->current; } return; } line = (char *)SDL_realloc(textwin->lines[textwin->current], existing + len + 1); if (line) { SDL_memcpy(&line[existing], text, len); line[existing + len] = '\0'; textwin->lines[textwin->current] = line; if (newline) { if (textwin->current == textwin->numlines - 1) { SDL_free(textwin->lines[0]); SDL_memmove(&textwin->lines[0], &textwin->lines[1], (textwin->numlines - 1) * sizeof(textwin->lines[1])); textwin->lines[textwin->current] = NULL; } else { ++textwin->current; } } } } void SDLTest_TextWindowClear(SDLTest_TextWindow *textwin) { int i; for (i = 0; i < textwin->numlines; ++i) { if (textwin->lines[i]) { SDL_free(textwin->lines[i]); textwin->lines[i] = NULL; } } textwin->current = 0; } void SDLTest_TextWindowDestroy(SDLTest_TextWindow *textwin) { if (textwin) { SDLTest_TextWindowClear(textwin); SDL_free(textwin->lines); SDL_free(textwin); } } void SDLTest_CleanupTextDrawing(void) { }
412
0.657364
1
0.657364
game-dev
MEDIA
0.407371
game-dev
0.742007
1
0.742007
EverestAPI/CelesteTAS-EverestInterop
20,551
CelesteTAS-EverestInterop/Source/Gameplay/DesyncFix/SkinModFix.cs
using Celeste; using Celeste.Mod; using Celeste.Mod.Core; using Microsoft.Xna.Framework; using Monocle; using MonoMod.Cil; using MonoMod.RuntimeDetour; using MonoMod.Utils; using StudioCommunication; using StudioCommunication.Util; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Xml; using TAS.ModInterop; using TAS.Module; using TAS.Utils; namespace TAS.Gameplay.DesyncFix; /// Fixes desyncs caused by SkinMods changing animation lengths / carry offsets, /// by splitting the PlayerSprite into a visual and gameplay component internal static class SkinModFix { private static bool Enabled => TasSettings.Enabled && TasSettings.PreventSkinModGameplayChanges switch { GameplayEnableCondition.Never => false, GameplayEnableCondition.Always => true, GameplayEnableCondition.DuringTAS => Manager.Running, _ => throw new ArgumentOutOfRangeException() }; /// The `object` must be a boxed PlayerSpriteMode private static readonly ConditionalWeakTable<PlayerSprite, object> actualSpriteMode = new(); private static readonly ConditionalWeakTable<PlayerSprite, PlayerSprite> gameplayToVisualSprites = new(); private static readonly Dictionary<string, EverestModuleMetadata> moddedMaps = new(); private static readonly Dictionary<EverestModuleMetadata, SpriteBank> moddedSpriteBanks = new(); private static readonly Dictionary<EverestModuleMetadata, Dictionary<string, PlayerAnimMetadata>> moddedFrameMetadata = new(); [Load] private static void Load() { On.Celeste.Player.Update += On_Player_Update; using (new DetourConfigContext(new DetourConfig("CelesteTAS", priority: int.MaxValue)).Use()) { On.Celeste.PlayerSprite.ctor += On_PlayerSprite_ctor; } On.Monocle.Sprite.Update += On_Sprite_Update; On.Celeste.PlayerSprite.Render += On_PlayerSprite_Render; IL.Celeste.PlayerSprite.CreateFramesMetadata += IL_PlayerSprite_CreateFramesMetadata; On.Monocle.Sprite.Play += On_Sprite_Play; On.Monocle.Sprite.PlayOffset += On_Sprite_PlayOffset; On.Monocle.Sprite.Reverse += On_Sprite_Reverse; typeof(PlayerSprite) .GetGetMethod(nameof(PlayerSprite.HasHair))! .OnHook(On_PlayerSprite_getHasHair); typeof(PlayerSprite) .GetGetMethod(nameof(PlayerSprite.HairOffset))! .OnHook(On_PlayerSprite_getHairOffset); typeof(PlayerSprite) .GetGetMethod(nameof(PlayerSprite.HairFrame))! .OnHook(On_PlayerSprite_getHairFrame); typeof(PlayerSprite) .GetGetMethod(nameof(PlayerSprite.CarryYOffset))! .OnHook(On_PlayerSprite_getCarryYOffset); } [Unload] private static void Unload() { On.Celeste.Player.Update -= On_Player_Update; On.Celeste.PlayerSprite.ctor -= On_PlayerSprite_ctor; On.Monocle.Sprite.Update -= On_Sprite_Update; On.Celeste.PlayerSprite.Render -= On_PlayerSprite_Render; IL.Celeste.PlayerSprite.CreateFramesMetadata -= IL_PlayerSprite_CreateFramesMetadata; On.Monocle.Sprite.Play -= On_Sprite_Play; On.Monocle.Sprite.PlayOffset -= On_Sprite_PlayOffset; On.Monocle.Sprite.Reverse -= On_Sprite_Reverse; } [Initialize] private static void Initialize() { // Add color grade, hair and death particle support for SMH+ ModUtils.GetType("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.PlayerSkinSystem") ?.GetAllMethodInfos() .ForEach(method => method.IlHook((cursor, _) => FixPlayerHairSprite(cursor))); ModUtils.GetType("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.HairConfig") ?.GetAllMethodInfos() .ForEach(method => method.IlHook((cursor, _) => FixPlayerHairSprite(cursor))); ModUtils.GetMethod("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.SkinsSystem", "SyncColorGrade") ?.IlHook((cursor, _) => { FixSpriteParameter(cursor, index: 0); FixSpriteParameter(cursor, index: 1); }); ModUtils.GetMethod("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.PlayerSkinSystem", "SpriteRenderHook_ColorGrade") ?.IlHook((cursor, _) => FixSpriteParameter(cursor, index: 1)); ModUtils.GetMethod("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.CharacterConfig", "For") ?.IlHook((cursor, _) => FixSpriteParameter(cursor, index: 0)); ModUtils.GetMethod("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.SomePatches", "DeathEffectDrawHook") ?.IlHook((cursor, il) => { int spriteIdx = il.Body.Variables.IndexOf(var => var.VariableType.ResolveReflection() == typeof(Sprite)); cursor.GotoNext(MoveType.AfterLabel, instr => instr.MatchStloc(spriteIdx)); cursor.EmitDelegate(CorrectVisualSprite); }); ModUtils.GetMethod("SkinModHelperPlus", "Celeste.Mod.SkinModHelper.SomePatches", "DeathEffectRenderHook") ?.IlHook((cursor, il) => { int spriteIdx = il.Body.Variables.IndexOf(var => var.VariableType.ResolveReflection() == typeof(Sprite)); cursor.GotoNext(MoveType.AfterLabel, instr => instr.MatchStloc(spriteIdx)); cursor.EmitDelegate(CorrectVisualSprite); }); // The Avali Skinmod (non-SMH) has custom code to swap the sprites dynamically, // which needs to reference the visual sprite, instead of gameplay one. ModUtils.GetMethod("Avali-Skinmod", "Celeste.Mod.AvaliSkin.AvaliSkinModule", "trySpriteSwap") ?.IlHook((cursor, _) => FixSpriteParameter(cursor, index: 1)); return; static Sprite CorrectVisualSprite(Sprite sprite) { if (sprite is PlayerSprite playerSprite && gameplayToVisualSprites.TryGetValue(playerSprite, out var visualSprite)) { return visualSprite; } return sprite; } static void FixSpriteParameter(ILCursor cursor, int index) { #if DEBUG Debug.Assert(typeof(PlayerSprite).IsAssignableTo(cursor.Method.Parameters[index].ParameterType.ResolveReflection())); #endif cursor.EmitLdarg(index); cursor.EmitDelegate(CorrectVisualSprite); cursor.EmitStarg(index); } static void FixPlayerHairSprite(ILCursor cursor) { while (cursor.TryGotoNext(MoveType.After, instr => instr.MatchLdfld<PlayerHair>(nameof(PlayerHair.Sprite)))) { cursor.EmitDelegate(CorrectVisualSprite); } } } private static bool CheckMapRequiresSkin() { // Check if map set SMH+ skin if (Engine.Scene is Level && Everest.Modules.FirstOrDefault(module => module.Metadata.Name == "SkinModHelperPlus") is { } smhpModule) { // Reference: https://github.com/AAA1459/SkinModHelper/blob/8dcf2ab52b3850bbf0872b51a477c932f61be67a/Code/SkinModHelperUI.cs#L70 var smhSession = smhpModule._Session; bool mapSetSkin = smhSession?.GetPropertyValue<string?>("SelectedPlayerSkin") != null || smhSession?.GetPropertyValue<string?>("SelectedOtherSelfSkin") != null || smhSession?.GetPropertyValue<string?>("SelectedSilhouetteSkin") != null; if (mapSetSkin) { return true; } } return false; } /// Adjusted from SpriteBank.LoadSpriteBank (Everest) private static SpriteBank CreateSpriteBankForMod(EverestModuleMetadata metadata) { // Collect all direct / transitive dependencies var allDependencies = new HashSet<EverestModuleMetadata>(capacity: 1 + metadata.Dependencies.Count); var queue = new Stack<EverestModuleMetadata>(capacity: 1 + metadata.Dependencies.Count); queue.Push(metadata); while (queue.TryPop(out var curr)) { queue.PushRange(curr.Dependencies); allDependencies.Add(curr); } const string spritesXmlFilePath = "Graphics/Sprites.xml"; const string spritesXmlAssetPath = "Graphics/Sprites"; var spriteBankXml = Calc.orig_LoadContentXML(spritesXmlFilePath); var originalSpriteBankXml = Calc.orig_LoadContentXML(spritesXmlFilePath); var sprites = spriteBankXml["Sprites"]!; // Find all mod files that match this one, EXCEPT for the "shadow structure" asset - the unique "Graphics/Sprites" asset. ModAsset[] modAssets; lock (Everest.Content.Map) { modAssets = Everest.Content.Map .Where(entry => entry.Value.Type == typeof(AssetTypeSpriteBank) && entry.Value.PathVirtual.Equals(spritesXmlAssetPath) && !entry.Value.PathVirtual.Equals(entry.Key)) // Filter out the unique asset .Select(kvp => kvp.Value) .ToArray(); } foreach (var modAsset in modAssets) { // If metadata is null, this is a vanilla map bool isDependency = metadata != null && allDependencies.Contains(modAsset.Source.Mod); string modPath = modAsset.Source.Mod.PathDirectory; if (string.IsNullOrEmpty(modPath)) { modPath = modAsset.Source.Mod.PathArchive; } using var stream = modAsset.Stream; var modXml = new XmlDocument(); modXml.Load(stream); modXml = SpriteBank.GetSpriteBankExcludingVanillaCopyPastes(originalSpriteBankXml, modXml, modPath); foreach (XmlNode node in modXml["Sprites"]!.ChildNodes) { if (node is not XmlElement) { continue; } var importedNode = spriteBankXml.ImportNode(node, true); var existingNode = sprites.SelectSingleNode(node.Name); if (existingNode != null) { if (!isDependency) { continue; // Non-dependencies are not allowed to overwrite sprites } sprites.ReplaceChild(importedNode, existingNode); } else { sprites.AppendChild(importedNode); } } } return new SpriteBank(GFX.Game, spriteBankXml) { XMLPath = spritesXmlFilePath }; } private static Dictionary<string, PlayerAnimMetadata>? targetFramesMetadata = null; /// Modify vanilla method to target our dictionary instead /// The method cannot just be copy-pasted, since there are hooks on it, which need to be triggered private static void IL_PlayerSprite_CreateFramesMetadata(ILContext il) { var cursor = new ILCursor(il); cursor.GotoNext(MoveType.After, instr => instr.MatchLdsfld<PlayerSprite>(nameof(PlayerSprite.FrameMetadata))); cursor.EmitStaticDelegate("AdjustTargetDictionary", Dictionary<string, PlayerAnimMetadata> (Dictionary<string, PlayerAnimMetadata> orig) => targetFramesMetadata ?? orig); } private static void On_Player_Update(On.Celeste.Player.orig_Update orig, Player self) { if (Enabled) { bool shouldBeActive = !CheckMapRequiresSkin(); bool isActive = gameplayToVisualSprites.TryGetValue(self.Sprite, out _); if (shouldBeActive && !isActive) { ApplyPlayer(self); } else if (!shouldBeActive && isActive) { RestorePlayer(self); } } orig(self); } private static EverestModuleMetadata GetActiveMod() { // Use Everest's module to represent vanilla, since null isn't allowed as a key var vanillaModule = CoreModule.Instance.Metadata; if (Engine.Scene.GetSession() is not { } session) { return vanillaModule; } // SID -> Mod if (!moddedMaps.TryGetValue(session.Area.SID, out var mod)) { var area = session.MapData.Area; if (Everest.Content.TryGet($"Maps/{AreaData.Get(area).Mode[(int)area.Mode].Path}", out var mapAsset)) { // The mod source is null for stay .bin maps moddedMaps[session.Area.SID] = mod = (mapAsset.Source.Mod ?? vanillaModule); } else { moddedMaps[session.Area.SID] = mod = vanillaModule; } } return mod; } private static bool skipPlayerSpriteHook = false; private static void On_PlayerSprite_ctor(On.Celeste.PlayerSprite.orig_ctor orig, PlayerSprite self, PlayerSpriteMode mode) { // Separate gameplay and visual sprite if (Enabled && !CheckMapRequiresSkin() && !skipPlayerSpriteHook) { var mod = GetActiveMod(); if (!moddedSpriteBanks.TryGetValue(mod, out var spriteBank)) { moddedSpriteBanks[mod] = spriteBank = CreateSpriteBankForMod(mod); } var origSpriteBank = GFX.SpriteBank; GFX.SpriteBank = spriteBank; if (!moddedFrameMetadata.ContainsKey(mod)) { moddedFrameMetadata[mod] = targetFramesMetadata = new Dictionary<string, PlayerAnimMetadata>(); PlayerSprite.CreateFramesMetadata("player"); PlayerSprite.CreateFramesMetadata("player_no_backpack"); PlayerSprite.CreateFramesMetadata("badeline"); PlayerSprite.CreateFramesMetadata("player_badeline"); PlayerSprite.CreateFramesMetadata("player_playback"); targetFramesMetadata = null; } orig(self, mode); // Force-overwrite vanilla sprites switch (mode) { case PlayerSpriteMode.Madeline: self.spriteName = "player"; spriteBank.CreateOn(self, self.spriteName); break; case PlayerSpriteMode.MadelineNoBackpack: self.spriteName = "player_no_backpack"; spriteBank.CreateOn(self, self.spriteName); break; case PlayerSpriteMode.Badeline: self.spriteName = "badeline"; spriteBank.CreateOn(self, self.spriteName); break; case PlayerSpriteMode.MadelineAsBadeline: self.spriteName = "player_badeline"; spriteBank.CreateOn(self, self.spriteName); break; case PlayerSpriteMode.Playback: self.spriteName = "player_playback"; spriteBank.CreateOn(self, self.spriteName); break; } GFX.SpriteBank = origSpriteBank; skipPlayerSpriteHook = true; var visualSprite = new PlayerSprite(mode); skipPlayerSpriteHook = false; gameplayToVisualSprites.Add(self, visualSprite); } else { // Since SkinModHelper+ messes up the PlayerSpriteMode, we have to store it actualSpriteMode.Add(self, mode); orig(self, mode); } } private static void On_Sprite_Update(On.Monocle.Sprite.orig_Update orig, Sprite self) { if (self is PlayerSprite playerSprite && gameplayToVisualSprites.TryGetValue(playerSprite, out var visual)) { // Forward parameters visual.Rate = self.Rate; orig(visual); } orig(self); } private static void On_PlayerSprite_Render(On.Celeste.PlayerSprite.orig_Render orig, PlayerSprite self) { if (gameplayToVisualSprites.TryGetValue(self, out var visual)) { // Forward parameters visual.Entity = self.Entity; visual.Position = self.Position; visual.Justify = self.Justify; visual.Origin = self.Origin; visual.Scale = self.Scale; visual.Color = self.Color; orig(visual); visual.Entity = null; // Clear to avoid it holding a reference } else { orig(self); } } // Forward calls to visual sprite private static void On_Sprite_Play(On.Monocle.Sprite.orig_Play orig, Sprite self, string id, bool restart, bool randomizeFrame) { if (self is PlayerSprite playerSprite && gameplayToVisualSprites.TryGetValue(playerSprite, out var visual)) { orig(visual, id, restart, randomizeFrame); } orig(self, id, restart, randomizeFrame); } private static void On_Sprite_PlayOffset(On.Monocle.Sprite.orig_PlayOffset orig, Sprite self, string id, float offset, bool randomizeFrame) { if (self is PlayerSprite playerSprite && gameplayToVisualSprites.TryGetValue(playerSprite, out var visual)) { orig(visual, id, offset, randomizeFrame); } orig(self, id, offset, randomizeFrame); } private static void On_Sprite_Reverse(On.Monocle.Sprite.orig_Reverse orig, Sprite self, string id, bool restart) { if (self is PlayerSprite playerSprite && gameplayToVisualSprites.TryGetValue(playerSprite, out var visual)) { orig(visual, id, restart); } orig(self, id, restart); } // Fetch values from visual sprite private static bool On_PlayerSprite_getHasHair(Func<PlayerSprite, bool> orig, PlayerSprite self) { if (gameplayToVisualSprites.TryGetValue(self, out var visual)) { return orig(visual); } return orig(self); } private static Vector2 On_PlayerSprite_getHairOffset(Func<PlayerSprite, Vector2> orig, PlayerSprite self) { if (gameplayToVisualSprites.TryGetValue(self, out var visual)) { return orig(visual); } return orig(self); } private static int On_PlayerSprite_getHairFrame(Func<PlayerSprite, int> orig, PlayerSprite self) { if (gameplayToVisualSprites.TryGetValue(self, out var visual)) { return orig(visual); } return orig(self); } private static float On_PlayerSprite_getCarryYOffset(Func<PlayerSprite, float> orig, PlayerSprite self) { if (gameplayToVisualSprites.TryGetValue(self, out _)) { if (self.Texture != null && moddedFrameMetadata.TryGetValue(GetActiveMod(), out var frameMetadata) && frameMetadata.TryGetValue(self.Texture.AtlasPath, out var metadata)) { return metadata.CarryYOffset * self.Scale.Y; } return 0.0f; } return orig(self); } [EnableRun] private static void Apply() { if (Engine.Scene.GetPlayer() is { } player && TasSettings.PreventSkinModGameplayChanges == GameplayEnableCondition.DuringTAS) { ApplyPlayer(player); } } [DisableRun] private static void Restore() { if (Engine.Scene.GetPlayer() is { } player && TasSettings.PreventSkinModGameplayChanges == GameplayEnableCondition.DuringTAS) { RestorePlayer(player); } } private static void ApplyPlayer(Player player) { var newSprite = new PlayerSprite(actualSpriteMode.TryGetValue(player.Sprite, out object? boxedMode) ? (PlayerSpriteMode) boxedMode : player.Sprite.Mode); newSprite.Animating = player.Sprite.Animating; newSprite.CurrentAnimationID = player.Sprite.CurrentAnimationID; newSprite.CurrentAnimationFrame = player.Sprite.CurrentAnimationFrame; newSprite.currentAnimation = newSprite.Animations.TryGetValue(newSprite.CurrentAnimationID, out var anim) ? anim : player.Sprite.currentAnimation; newSprite.animationTimer = player.Sprite.animationTimer; newSprite.Scale = player.Sprite.Scale; if (gameplayToVisualSprites.TryGetValue(newSprite, out var visualSprite)) { gameplayToVisualSprites.Remove(newSprite); gameplayToVisualSprites.AddOrUpdate(player.Sprite, visualSprite); player.Sprite.CloneInto(visualSprite); } newSprite.CloneInto(player.Sprite); "Applied vanilla sprite behaviour to player".Log(); } private static void RestorePlayer(Player player) { if (!gameplayToVisualSprites.TryGetValue(player.Sprite, out var visual)) { return; } gameplayToVisualSprites.Remove(player.Sprite); visual.CloneInto(player.Sprite); "Restored default sprite behaviour to player".Log(); } }
412
0.893743
1
0.893743
game-dev
MEDIA
0.909607
game-dev
0.913233
1
0.913233
qt-creator/qt-creator
2,232
src/libs/utils/guard.cpp
// Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 #include "guard.h" #include "qtcassert.h" /*! \class Utils::Guard \inmodule QtCreator \brief The Guard class implements a recursive guard with locking mechanism. It may be used as an alternative to QSignalBlocker. QSignalBlocker blocks all signals of the object which is usually not desirable. It may also block signals which are needed internally by the object itself. The Guard and GuardLocker classes don't block signals at all. When calling a object's method which may in turn emit a signal which you are connected to, and you want to ignore this notification, you should keep the Guard object as your class member and declare the GuardLocker object just before calling the mentioned method, like: \code class MyClass : public QObject { \dots private: Guard updateGuard; // member of your class }; \dots void MyClass::updateOtherObject() { GuardLocker updatelocker(updateGuard); otherObject->update(); // this may trigger a signal } \endcode Inside a slot which is connected to the other's object signal you may check if the guard is locked and ignore the further operations in this case: \code void MyClass::otherObjectUpdated() { if (updateGuard.isLocked()) return; // we didn't trigger the update // so do update now \dots } \endcode The GuardLocker unlocks the Guard in its destructor. The Guard object is recursive, you may declare many GuardLocker objects for the same Guard instance and the Guard will be locked as long as at least one GuardLocker object created for the Guard is in scope. */ namespace Utils { Guard::Guard() = default; Guard::~Guard() { QTC_CHECK(m_lockCount == 0); } bool Guard::isLocked() const { return m_lockCount; } void Guard::lock() { ++m_lockCount; } void Guard::unlock() { QTC_CHECK(m_lockCount > 0); --m_lockCount; } GuardLocker::GuardLocker(Guard &guard) : m_guard(guard) { ++m_guard.m_lockCount; } GuardLocker::~GuardLocker() { --m_guard.m_lockCount; } } // namespace Utils
412
0.884688
1
0.884688
game-dev
MEDIA
0.317476
game-dev
0.639567
1
0.639567
webbukkit/dynmap
4,291
fabric-1.20.6/src/main/java/org/dynmap/fabric_1_20_6/FabricMapChunkCache.java
package org.dynmap.fabric_1_20_6; import net.minecraft.nbt.*; import net.minecraft.server.world.ServerChunkManager; import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ThreadedAnvilChunkStorage; import net.minecraft.util.collection.PackedIntegerArray; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.WordPackedArray; import net.minecraft.world.ChunkSerializer; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeEffects; import net.minecraft.world.chunk.ChunkManager; import net.minecraft.world.chunk.ChunkStatus; import org.dynmap.DynmapChunk; import org.dynmap.DynmapCore; import org.dynmap.DynmapWorld; import org.dynmap.Log; import org.dynmap.common.BiomeMap; import org.dynmap.common.chunk.GenericChunk; import org.dynmap.common.chunk.GenericChunkSection; import org.dynmap.common.chunk.GenericMapChunkCache; import org.dynmap.hdmap.HDBlockModels; import org.dynmap.renderer.DynmapBlockState; import org.dynmap.renderer.RenderPatchFactory; import org.dynmap.utils.*; import java.lang.reflect.Field; import java.util.*; /** * Container for managing chunks - dependent upon using chunk snapshots, since rendering is off server thread */ public class FabricMapChunkCache extends GenericMapChunkCache { private World w; private ServerChunkManager cps; /** * Construct empty cache */ public FabricMapChunkCache(DynmapPlugin plugin) { super(plugin.sscache); } public void setChunks(FabricWorld dw, List<DynmapChunk> chunks) { this.w = dw.getWorld(); if (dw.isLoaded()) { /* Check if world's provider is ServerChunkManager */ ChunkManager cp = this.w.getChunkManager(); if (cp instanceof ServerChunkManager) { cps = (ServerChunkManager) cp; } else { Log.severe("Error: world " + dw.getName() + " has unsupported chunk provider"); } } super.setChunks(dw, chunks); } // Load generic chunk from existing and already loaded chunk protected GenericChunk getLoadedChunk(DynmapChunk chunk) { GenericChunk gc = null; if (cps.isChunkLoaded(chunk.x, chunk.z)) { NbtCompound nbt = null; try { nbt = ChunkSerializer.serialize((ServerWorld) w, cps.getWorldChunk(chunk.x, chunk.z, false)); } catch (NullPointerException e) { // TODO: find out why this is happening and why it only seems to happen since 1.16.2 Log.severe("ChunkSerializer.serialize threw a NullPointerException", e); } if (nbt != null) { gc = parseChunkFromNBT(new NBT.NBTCompound(nbt)); } } return gc; } private NbtCompound readChunk(int x, int z) { try { ThreadedAnvilChunkStorage acl = cps.threadedAnvilChunkStorage; ChunkPos coord = new ChunkPos(x, z); // Async chunk reading is synchronized here. Perhaps we can do async and improve performance? return acl.getNbt(coord).join().orElse(null); } catch (Exception exc) { Log.severe(String.format("Error reading chunk: %s,%d,%d", dw.getName(), x, z), exc); return null; } } // Load generic chunk from unloaded chunk protected GenericChunk loadChunk(DynmapChunk chunk) { GenericChunk gc = null; NbtCompound nbt = readChunk(chunk.x, chunk.z); // If read was good if (nbt != null) { gc = parseChunkFromNBT(new NBT.NBTCompound(nbt)); } return gc; } @Override public int getFoliageColor(BiomeMap bm, int[] colormap, int x, int z) { return bm.<Biome>getBiomeObject().map(Biome::getEffects).flatMap(BiomeEffects::getFoliageColor).orElse(colormap[bm.biomeLookup()]); } @Override public int getGrassColor(BiomeMap bm, int[] colormap, int x, int z) { BiomeEffects effects = bm.<Biome>getBiomeObject().map(Biome::getEffects).orElse(null); if (effects == null) return colormap[bm.biomeLookup()]; return effects.getGrassColorModifier().getModifiedGrassColor(x, z, effects.getGrassColor().orElse(colormap[bm.biomeLookup()])); } }
412
0.892972
1
0.892972
game-dev
MEDIA
0.980052
game-dev
0.929434
1
0.929434
fortressforever/fortressforever
10,868
cl_dll/ff/ff_fx_overpressure.cpp
// =============== Fortress Forever =============== // ======== A modification for Half-Life 2 ======== // // @file cl_dll\ff\ff_fx_overpressure.cpp // @author Patrick O'Leary (Mulchman) // @date 10/6/2006 // @brief Overpressure particle effects // // particle manager for the overpressure particles // // Revisions // --------- // 10/6/2006, Mulchman // Initial version #include "cbase.h" #include "clienteffectprecachesystem.h" #include "particles_simple.h" #include "c_te_effect_dispatch.h" #include "cliententitylist.h" #include "ff_fx_overpressure.h" #define OVERPRESSURE_EFFECT_MATERIAL "particle/particle_smokegrenade" #define OVERPRESSURE_EFFECT_MATERIAL2 "effects/yellowflare" #define RING_EFFECT_MATERIAL "sprites/lgtning.vmt" ConVar overpressure_particles ( "cl_overpressure_numparticles", "32", FCVAR_CHEAT, "The number of particles in each overpressure." ); ConVar overpressure_speed ( "cl_overpressure_particle_lifetime", "1.0", FCVAR_CHEAT, "Duration of the overpressure effect." ); ConVar overpressure_particlespeed( "cl_overpressure_particlespeed", "250", FCVAR_CHEAT, "Velocity of the overpressure particles." ); ConVar overpressure_particlespeed_variability( "cl_overpressure_particlespeed_variability", "30", FCVAR_CHEAT, "Variability in the velocity of the overpressure particles." ); ConVar overpressure_particle_size( "cl_overpressure_particle_size", "32", FCVAR_CHEAT, "Velocity of the overpressure particles." ); ConVar overpressure_particles2 ( "cl_overpressure_particle2_numparticles", "64", FCVAR_CHEAT, "The number of particles in each overpressure." ); ConVar overpressure_speed2 ( "cl_overpressure_particle2_lifetime", "0.5", FCVAR_CHEAT, "Duration of the overpressure effect." ); ConVar overpressure_particle2speed( "cl_overpressure_particle2_speed", "400", FCVAR_CHEAT, "Velocity of the overpressure particles." ); ConVar overpressure_particle2speed_variability( "cl_overpressure_particle2_speed_variability", "30", FCVAR_CHEAT, "Variability in the velocity of the overpressure particles." ); ConVar overpressure_particle2_size( "cl_overpressure_particle2_size", "2", FCVAR_CHEAT, "Velocity of the overpressure particles." ); //======================================================================== // Client effect precache table //======================================================================== CLIENTEFFECT_REGISTER_BEGIN( PrecacheOverpressureEmitter ) CLIENTEFFECT_MATERIAL( OVERPRESSURE_EFFECT_MATERIAL ) CLIENTEFFECT_MATERIAL( OVERPRESSURE_EFFECT_MATERIAL2 ) CLIENTEFFECT_MATERIAL( RING_EFFECT_MATERIAL ) CLIENTEFFECT_REGISTER_END() //======================================================================== // Static material handles //======================================================================== PMaterialHandle COverpressureEmitter::m_hMaterial = INVALID_MATERIAL_HANDLE; PMaterialHandle COverpressureEmitter::m_hMaterial2 = INVALID_MATERIAL_HANDLE; //======================================================================== // COverpressureEmitter constructor //======================================================================== COverpressureEmitter::COverpressureEmitter( const char *pDebugName ) : CSimpleEmitter( pDebugName ) { m_pDebugName = pDebugName; m_flNextParticle = 0.0f; } //======================================================================== // COverpressureEmitter destructor //======================================================================== COverpressureEmitter::~COverpressureEmitter( void ) { } //======================================================================== // COverpressureEmitter::Create // ---------------------- // Purpose: Creates a new instance of a COverpressureEmitter object //======================================================================== CSmartPtr< COverpressureEmitter > COverpressureEmitter::Create( const char *pDebugName ) { COverpressureEmitter *pRet = new COverpressureEmitter( pDebugName ); if( !pRet ) return NULL; pRet->SetDynamicallyAllocated(); if( m_hMaterial == INVALID_MATERIAL_HANDLE ) m_hMaterial = pRet->GetPMaterial( OVERPRESSURE_EFFECT_MATERIAL ); if( m_hMaterial2 == INVALID_MATERIAL_HANDLE ) m_hMaterial2 = pRet->GetPMaterial( OVERPRESSURE_EFFECT_MATERIAL2 ); return pRet; } //======================================================================== // COverpressureEmitter::RenderParticles // ---------- // Purpose: Renders all the particles in the system //======================================================================== void COverpressureEmitter::RenderParticles( CParticleRenderIterator *pIterator ) { const OverpressureParticle *pParticle = ( const OverpressureParticle * )pIterator->GetFirst(); while( pParticle ) { Vector tPos; TransformParticle( ParticleMgr()->GetModelView(), pParticle->m_Pos, tPos ); float sortKey = ( int )tPos.z; Vector vColor = Vector( pParticle->m_uchColor[ 0 ] / 255.0f, pParticle->m_uchColor[ 1 ] / 255.0f, pParticle->m_uchColor[ 2 ] / 255.0f ); RenderParticle_ColorSizeAngle( pIterator->GetParticleDraw(), tPos, vColor, pParticle->m_flAlpha, pParticle->m_flSize, pParticle->m_flRoll ); pParticle = ( const OverpressureParticle * )pIterator->GetNext( sortKey ); } } //======================================================================== // COverpressureEmitter::SimulateParticles // ---------- // Purpose: Simulates all the particles in the system //======================================================================== void COverpressureEmitter::SimulateParticles( CParticleSimulateIterator *pIterator ) { float timeDelta = pIterator->GetTimeDelta(); OverpressureParticle *pParticle = ( OverpressureParticle * )pIterator->GetFirst(); while( pParticle ) { pParticle->m_flLifetime += timeDelta; float flEnd = pParticle->m_flLifetime / pParticle->m_flDieTime; float flBeg = 1.0f - flEnd; Vector F( 0.0f, 0.0f, 0.0f ); ApplyDrag( &F, pParticle->m_vVelocity, 4.0f, 20.0f ); pParticle->m_Pos += pParticle->m_vVelocity * timeDelta * 0.75f; pParticle->m_vVelocity += F * timeDelta; pParticle->m_Pos += pParticle->m_vVelocity * timeDelta * 0.75f; pParticle->m_flRoll += pParticle->m_flRollDelta * timeDelta; pParticle->m_flAlpha = 0.8f * flBeg + 0.0f * flEnd; if( pParticle->m_flLifetime >= pParticle->m_flDieTime ) pIterator->RemoveParticle( pParticle ); pParticle = ( OverpressureParticle * )pIterator->GetNext(); } } //======================================================================== // CRingEmitter::AddOverpressureParticle // ---------- // Purpose: Add a new particle to the system //======================================================================== OverpressureParticle *COverpressureEmitter::AddOverpressureParticle( const Vector& vecOrigin ) { OverpressureParticle *pRet = ( OverpressureParticle * )AddParticle( sizeof( OverpressureParticle ), m_hMaterial, vecOrigin ); if( pRet ) { pRet->m_vOrigin = vecOrigin; pRet->m_vFinalPos.Init(); pRet->m_vVelocity.Init(); pRet->m_flDieTime = 1.0f; pRet->m_flLifetime = 0.0f; pRet->m_uchColor[ 0 ] = 255; pRet->m_uchColor[ 1 ] = 255; pRet->m_uchColor[ 2 ] = 255; pRet->m_flAlpha = 0.8f; pRet->m_flSize = 1.0f; pRet->m_flRoll = 0.0f; pRet->m_flRollDelta = 0.0f; } return pRet; } //======================================================================== // CRingEmitter::AddOverpressureParticle // ---------- // Purpose: Add a new particle to the system //======================================================================== OverpressureParticle *COverpressureEmitter::AddOverpressureParticle2( const Vector& vecOrigin ) { OverpressureParticle *pRet = ( OverpressureParticle * )AddParticle( sizeof( OverpressureParticle ), m_hMaterial2, vecOrigin ); if( pRet ) { pRet->m_vOrigin = vecOrigin; pRet->m_vFinalPos.Init(); pRet->m_vVelocity.Init(); pRet->m_flDieTime = 1.0f; pRet->m_flLifetime = 0.0f; pRet->m_uchColor[ 0 ] = 255; pRet->m_uchColor[ 1 ] = 255; pRet->m_uchColor[ 2 ] = 255; pRet->m_flAlpha = 0.8f; pRet->m_flSize = 1.0f; pRet->m_flRoll = 0.0f; pRet->m_flRollDelta = 0.0f; } return pRet; } void COverpressureEmitter::ApplyDrag( Vector *F, Vector vecVelocity, float flScale, float flTargetVel ) { if( vecVelocity.IsLengthLessThan( flTargetVel ) ) return; Vector vecDir = -vecVelocity; vecVelocity.NormalizeInPlace(); float flMag = vecVelocity.Length() * flScale; *F += ( vecDir * flMag ); } void FF_FX_OverpressureEffect_Callback( const CEffectData &data ) { CSmartPtr< COverpressureEmitter > overpressureEffect = COverpressureEmitter::Create( "OverpressureEffect" ); //float offset = 0.0f; // Add smoke for( int i = 0; i < overpressure_particles.GetInt(); i++ ) { OverpressureParticle *pParticle = overpressureEffect->AddOverpressureParticle( data.m_vOrigin ); if( pParticle ) { pParticle->m_vOrigin = data.m_vOrigin; // get a random point on a unit sphere float ptZ = 2.0 * random->RandomFloat() - 1.0; float ptT = 2.0 * M_PI * random->RandomFloat(); float ptW = sqrt( 1 - ptZ*ptZ ); float ptX = ptW * cos( ptT ); float ptY = ptW * sin( ptT ); pParticle->m_vVelocity = Vector(ptX, ptY, ptZ) * (overpressure_particlespeed.GetFloat() + random->RandomInt(-overpressure_particlespeed_variability.GetInt(), overpressure_particlespeed_variability.GetInt())); pParticle->m_Pos = pParticle->m_vOrigin + RandomVector( -4.0f, 4.0f ); pParticle->m_flRoll = random->RandomFloat( 0, 2 * M_PI ); pParticle->m_flDieTime = overpressure_speed.GetFloat(); pParticle->m_flSize = overpressure_particle_size.GetFloat(); pParticle->m_flRollDelta = random->RandomFloat( -DEG2RAD( 180 ), DEG2RAD( 180 ) ); } } // Add smoke for( int i = 0; i < overpressure_particles2.GetInt(); i++ ) { OverpressureParticle *pParticle = overpressureEffect->AddOverpressureParticle2( data.m_vOrigin ); if( pParticle ) { pParticle->m_vOrigin = data.m_vOrigin; // get a random point on a unit sphere float ptZ = 2.0 * random->RandomFloat() - 1.0; float ptT = 2.0 * M_PI * random->RandomFloat(); float ptW = sqrt( 1 - ptZ*ptZ ); float ptX = ptW * cos( ptT ); float ptY = ptW * sin( ptT ); pParticle->m_vVelocity = Vector(ptX, ptY, ptZ) * (overpressure_particle2speed.GetFloat() + random->RandomInt(-overpressure_particle2speed_variability.GetInt(), overpressure_particle2speed_variability.GetInt())); pParticle->m_Pos = pParticle->m_vOrigin + RandomVector( -4.0f, 4.0f ); pParticle->m_flRoll = random->RandomFloat( 0, 2 * M_PI ); pParticle->m_flDieTime = overpressure_speed2.GetFloat(); pParticle->m_flSize = overpressure_particle2_size.GetFloat(); pParticle->m_flRollDelta = random->RandomFloat( -DEG2RAD( 180 ), DEG2RAD( 180 ) ); } } } DECLARE_CLIENT_EFFECT( "FF_OverpressureEffect", FF_FX_OverpressureEffect_Callback );
412
0.915147
1
0.915147
game-dev
MEDIA
0.478643
game-dev,graphics-rendering
0.832902
1
0.832902
PenisBlistashiq/Rust-plugins-236-240-dev
4,275
plugins2/CustomCraftTimes.cs
using System; using System.Collections.Generic; using UnityEngine; namespace Oxide.Plugins { [Info("Custom Craft Times", "Camoec", "1.1.1")] [Description("Allows you to change the crafting times")] public class CustomCraftTimes : RustPlugin { private const string UsePerm = "CustomCraftTimes.use"; Dictionary<int, BPItem> _restore = new Dictionary<int, BPItem>(); private PluginConfig _config; private class BPItem { public string shortname; public float time; } private class PluginConfig { public Dictionary<int,BPItem> itemdefinitions = new Dictionary<int, BPItem>(); } private void Init() { permission.RegisterPermission(UsePerm, this); } protected override void SaveConfig() => Config.WriteObject(_config, true); private void _LoadDefaultConfig() { Puts("Creating new config file"); _config = new PluginConfig(); foreach(var bp in ItemManager.bpList) { _config.itemdefinitions.Add(bp.targetItem.itemid,new BPItem() { shortname = bp.targetItem.shortname, time = bp.time }); } SaveConfig(); } private void _LoadConfig() { base.LoadConfig(); try { _config = Config.ReadObject<PluginConfig>(); if (_config == null) throw new Exception(); SaveConfig(); // override posible obsolet / outdated config } catch (Exception) { PrintError("Loaded default config"); _LoadDefaultConfig(); } } [ConsoleCommand("cct")] void GlobalSetup(ConsoleSystem.Arg arg) { if (arg == null && !arg.IsRcon && (arg.Player() != null && !permission.UserHasPermission(arg.Player().UserIDString, UsePerm))) return; if (arg.Args == null || arg.Args.Length < 2) { arg.ReplyWith("Use cct [category] [multiplier]"); return; } ItemCategory category = 0; float mult = 0; if(!float.TryParse(arg.Args[1], out mult)) { arg.ReplyWith("Invalid multiplier!"); } if ((arg.Args[0].ToLower() != "all" && !Enum.TryParse<ItemCategory>(arg.Args[0], out category))) { string availables = ""; foreach(var e in Enum.GetValues(typeof(ItemCategory))) { availables += $"{e} "; } arg.ReplyWith($"Invalid Category, try with: {availables}"); return; } int affected = 0; foreach(var bp in _restore) { var itemDef = ItemManager.FindItemDefinition(bp.Key); if(itemDef.category == category || arg.Args[0].ToLower() == "all") { _config.itemdefinitions[bp.Key].time = bp.Value.time * mult; affected++; } } SaveConfig(); arg.ReplyWith($"{affected} affected items, use 'oxide.reload CustomCraftTimes' to reload times"); } void OnServerInitialized(bool initial) { _LoadConfig(); Puts("Loading new times"); foreach (var bp in ItemManager.bpList) { _restore.Add(bp.targetItem.itemid, new BPItem() { time = bp.time, shortname = bp.name }); if (_config.itemdefinitions.ContainsKey(bp.targetItem.itemid)) { bp.time = _config.itemdefinitions[bp.targetItem.itemid].time; } } } void Unload() { if (ItemManager.bpList == null) return; foreach (var bp in ItemManager.bpList) { bp.time = _restore[bp.targetItem.itemid].time; } } } }
412
0.897333
1
0.897333
game-dev
MEDIA
0.515952
game-dev,desktop-app
0.952267
1
0.952267
UCLA-VAST/AutoBridge
3,570
archive/benchmarks/Stencil/3PE/constraint_ref.tcl
puts "applying partitioning constraints generated by the Context Sensitive HLS Solver" write_checkpoint ./before_opt_design.dcp -force startgroup create_pblock pblock_X0_Y0 resize_pblock pblock_X0_Y0 -add CLOCKREGION_X0Y0:CLOCKREGION_X3Y3 endgroup startgroup create_pblock pblock_X1_Y0 resize_pblock pblock_X1_Y0 -add CLOCKREGION_X5Y0:CLOCKREGION_X6Y3 endgroup startgroup create_pblock pblock_X0_Y1 resize_pblock pblock_X0_Y1 -add CLOCKREGION_X0Y4:CLOCKREGION_X3Y7 endgroup startgroup create_pblock pblock_X1_Y1 resize_pblock pblock_X1_Y1 -add CLOCKREGION_X4Y4:CLOCKREGION_X6Y7 endgroup startgroup create_pblock pblock_X0_Y2 resize_pblock pblock_X0_Y2 -add CLOCKREGION_X0Y8:CLOCKREGION_X3Y11 endgroup startgroup create_pblock pblock_X1_Y2 resize_pblock pblock_X1_Y2 -add CLOCKREGION_X4Y8:CLOCKREGION_X6Y11 endgroup startgroup create_pblock pblock_X0_Y3 resize_pblock pblock_X0_Y3 -add CLOCKREGION_X0Y12:CLOCKREGION_X3Y15 endgroup startgroup create_pblock pblock_X1_Y3 resize_pblock pblock_X1_Y3 -add CLOCKREGION_X5Y12:CLOCKREGION_X6Y15 endgroup add_cells_to_pblock [get_pblocks pblock_X0_Y0] [get_cells -hierarchical -regexp { (.*/)?load_0 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y1] [get_cells -hierarchical -regexp { (.*/)?compute_0 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y2] [get_cells -hierarchical -regexp { (.*/)?compute_1 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y3] [get_cells -hierarchical -regexp { (.*/)?compute_2 (.*/)?store_0 }] -clear_locs add_cells_to_pblock [get_pblocks pblock_dynamic_SLR3] [get_cells -hierarchical -regexp { (.*/)?jacobi2d_kernel_control_s_axi_U }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y0] [get_cells -hierarchical -regexp { (.*/)?input_stream_0_0/inst.*0.*unit (.*/)?input_stream_0_1/inst.*0.*unit (.*/)?input_stream_0_2/inst.*0.*unit (.*/)?input_stream_0_3/inst.*0.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y1] [get_cells -hierarchical -regexp { (.*/)?input_stream_0_0/inst.*1.*unit (.*/)?input_stream_0_1/inst.*1.*unit (.*/)?input_stream_0_2/inst.*1.*unit (.*/)?input_stream_0_3/inst.*1.*unit (.*/)?output_stream_0_0/inst.*0.*unit (.*/)?output_stream_0_1/inst.*0.*unit (.*/)?output_stream_0_2/inst.*0.*unit (.*/)?output_stream_0_3/inst.*0.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y2] [get_cells -hierarchical -regexp { (.*/)?output_stream_0_0/inst.*1.*unit (.*/)?output_stream_0_1/inst.*1.*unit (.*/)?output_stream_0_2/inst.*1.*unit (.*/)?output_stream_0_3/inst.*1.*unit (.*/)?output_stream_1_0/inst.*0.*unit (.*/)?output_stream_1_1/inst.*0.*unit (.*/)?output_stream_1_2/inst.*0.*unit (.*/)?output_stream_1_3/inst.*0.*unit }] -clear_locs add_cells_to_pblock [get_pblocks pblock_X0_Y3] [get_cells -hierarchical -regexp { (.*/)?output_stream_2_0 (.*/)?output_stream_2_1 (.*/)?output_stream_2_2 (.*/)?output_stream_2_3 (.*/)?output_stream_1_0/inst.*1.*unit (.*/)?output_stream_1_1/inst.*1.*unit (.*/)?output_stream_1_2/inst.*1.*unit (.*/)?output_stream_1_3/inst.*1.*unit }] -clear_locs delete_pblocks [get_pblocks pblock_X1_Y0] delete_pblocks [get_pblocks pblock_X1_Y1] delete_pblocks [get_pblocks pblock_X1_Y2] delete_pblocks [get_pblocks pblock_X1_Y3]
412
0.959946
1
0.959946
game-dev
MEDIA
0.31503
game-dev
0.947232
1
0.947232
i13-msrg/vibes
1,254
server/src/main/scala/com/vibes/actions/NodeActions.scala
package com.vibes.actions import akka.actor.ActorRef import com.vibes.models.{VBlock, VNode, VTransaction} import com.vibes.utils.VExecution import org.joda.time.DateTime object NodeActions { sealed trait Action case class ReceiveBlock(origin: VNode, newBlock: VBlock, timestamp: DateTime, blockchainCode: Int) extends Action case class ReceiveNeighbours(neighbours: Set[ActorRef]) extends Action case class StartSimulation(now: DateTime) extends Action case class ProcessNextExecutable(vote: VExecution.WorkRequest) extends Action case class CastNextWorkRequestAndMine(timestamp: DateTime, sender: ActorRef) extends Action case class IssueTransaction(toActor: ActorRef, time: DateTime) extends Action case class ReceiveTransaction(origin: VNode, transaction: VTransaction, time: DateTime) extends Action case class IssueTransactionFloodAttack(toActor: ActorRef, time: DateTime) extends Action case object CastNextWorkRequestOnly extends Action case object End extends Action }
412
0.845304
1
0.845304
game-dev
MEDIA
0.529039
game-dev
0.840044
1
0.840044
code10088/HelloWorld
3,010
HelloWorld/Assets/YooAsset/Runtime/ResourceManager/Handle/SubAssetsHandle.cs
using System.Collections.Generic; namespace YooAsset { public sealed class SubAssetsHandle : HandleBase { private System.Action<SubAssetsHandle> _callback; internal SubAssetsHandle(ProviderOperation provider) : base(provider) { } internal override void InvokeCallback() { _callback?.Invoke(this); } /// <summary> /// 完成委托 /// </summary> public event System.Action<SubAssetsHandle> Completed { add { if (IsValidWithWarning == false) throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid"); if (Provider.IsDone) value.Invoke(this); else _callback += value; } remove { if (IsValidWithWarning == false) throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid"); _callback -= value; } } /// <summary> /// 等待异步执行完毕 /// </summary> public void WaitForAsyncComplete() { if (IsValidWithWarning == false) return; Provider.WaitForAsyncComplete(); } /// <summary> /// 子资源对象集合 /// </summary> public IReadOnlyList<UnityEngine.Object> SubAssetObjects { get { if (IsValidWithWarning == false) return null; return Provider.SubAssetObjects; } } /// <summary> /// 获取子资源对象 /// </summary> /// <typeparam name="TObject">子资源对象类型</typeparam> /// <param name="assetName">子资源对象名称</param> public TObject GetSubAssetObject<TObject>(string assetName) where TObject : UnityEngine.Object { if (IsValidWithWarning == false) return null; foreach (var assetObject in Provider.SubAssetObjects) { if (assetObject.name == assetName && assetObject is TObject) return assetObject as TObject; } YooLogger.Warning($"Not found sub asset object : {assetName}"); return null; } /// <summary> /// 获取所有的子资源对象集合 /// </summary> /// <typeparam name="TObject">子资源对象类型</typeparam> public TObject[] GetSubAssetObjects<TObject>() where TObject : UnityEngine.Object { if (IsValidWithWarning == false) return null; List<TObject> result = new List<TObject>(Provider.SubAssetObjects.Length); foreach (var assetObject in Provider.SubAssetObjects) { var retObject = assetObject as TObject; if (retObject != null) result.Add(retObject); } return result.ToArray(); } } }
412
0.916927
1
0.916927
game-dev
MEDIA
0.643838
game-dev
0.970788
1
0.970788
Gozala/protocol
1,665
examples/event-object.js
/*jshint asi:true */ // module: ./event-object var Event = require('./event-protocol'), on = Event.on // Weak registry of listener maps associated // to event targets. var map = WeakMap() // Returns listeners of the given event `target` // for the given `type` with a given `capture` face. function getListeners(target, type, capture) { // If there is no listeners map associated with // this target then create one. if (!map.has(target)) map.set(target, Object.create(null)) var listeners = map.get(target) // prefix event type with a capture face flag. var address = (capture ? '!' : '-') + type // If there is no listeners array for the given type & capture // face than create one and return. return listeners[address] || (listeners[address] = []) } Event(Object, { on: function(target, type, listener, capture) { var listeners = getListeners(target, type, capture) // Add listener if not registered yet. if (!~listeners.indexOf(listener)) listeners.push(listener) }, once: function(target, type, listener, capture) { on(target, type, listener, capture) on(target, type, function cleanup() { off(target, type, listener, capture) }, capture) }, off: function(target, type, listener, capture) { var listeners = getListeners(target, type, capture) var index = listeners.indexOf(listener) // Remove listener if registered. if (~index) listeners.splice(index, 1) }, emit: function(target, type, event, capture) { var listeners = getListeners(target, type, capture).slice() // TODO: Exception handling while (listeners.length) listeners.shift().call(target, event) } })
412
0.703802
1
0.703802
game-dev
MEDIA
0.54041
game-dev
0.674257
1
0.674257
haekb/nolf1-modernizer
1,480
NOLF/ObjectDLL/AIVolumeMgr.h
// (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved #ifndef __AI_VOLUME_MGR_H__ #define __AI_VOLUME_MGR_H__ #include "AIVolume.h" class CAIPath; // Externs extern class CAIVolumeMgr* g_pAIVolumeMgr; // Classes class CAIVolumeMgr { public : // Ctors/Dtors/etc CAIVolumeMgr(); ~CAIVolumeMgr(); void Init(); void Term(); void Load(HMESSAGEREAD hRead); void Save(HMESSAGEWRITE hWrite); // Methods CAIVolume* FindContainingVolume(const LTVector& vPos, LTFLOAT fVerticalThreshhold = 0.0f, CAIVolume* pVolumeStart = LTNULL, LTBOOL bBruteForce = LTTRUE); CAIVolumeNeighbor* FindNeighbor(CAIVolume* pVolume, CAIVolume* pVolumeNeighbor); LTBOOL FindDangerScatterPosition(CAIVolume* pVolume, const LTVector& vAIPos, const LTVector& vDangerPos, LTFLOAT fDangerDistanceSqr, LTVector* pvScatterPosition, LTBOOL bNeighbor = LTFALSE); // Link methods for volumes void HandleBrokenLink(HOBJECT hObject); void Link(HOBJECT hObject); void Unlink(HOBJECT hObject); // Simple accessors int32 GetNumVolumes() const { return m_cVolumes; } CAIVolume* GetVolumeByIndex(int32 iVolume); CAIVolume* GetVolumeByName(const char* szVolume); LTBOOL IsInitialized() const { return m_bInitialized; } protected : CAIVolume* FindContainingVolumeBruteForce(const LTVector& vPos, LTFLOAT fVerticalThreshhold); protected : LTBOOL m_bInitialized; int32 m_cVolumes; CAIVolume* m_aVolumes; }; #endif // __AI_VOLUME_MGR_H__
412
0.784031
1
0.784031
game-dev
MEDIA
0.572539
game-dev
0.698954
1
0.698954
higan-emu/higan
2,832
hiro/core/widget/tab-frame-item.cpp
#if defined(Hiro_TabFrame) auto mTabFrameItem::allocate() -> pObject* { return new pTabFrameItem(*this); } auto mTabFrameItem::destruct() -> void { if(auto& sizable = state.sizable) sizable->destruct(); mObject::destruct(); } // auto mTabFrameItem::append(sSizable sizable) -> type& { if(auto& sizable = state.sizable) remove(sizable); state.sizable = sizable; sizable->setParent(this, 0); signal(append, sizable); return *this; } auto mTabFrameItem::closable() const -> bool { return state.closable; } auto mTabFrameItem::icon() const -> image { return state.icon; } auto mTabFrameItem::movable() const -> bool { return state.movable; } auto mTabFrameItem::remove() -> type& { if(auto tabFrame = parentTabFrame()) tabFrame->remove(*this); return *this; } auto mTabFrameItem::remove(sSizable sizable) -> type& { signal(remove, sizable); state.sizable.reset(); sizable->setParent(); return *this; } auto mTabFrameItem::reset() -> type& { if(auto& sizable = state.sizable) remove(sizable); return *this; } auto mTabFrameItem::selected() const -> bool { return state.selected; } auto mTabFrameItem::setClosable(bool closable) -> type& { state.closable = closable; signal(setClosable, closable); return *this; } auto mTabFrameItem::setEnabled(bool enabled) -> type& { mObject::setEnabled(enabled); if(auto& sizable = state.sizable) sizable->setEnabled(sizable->enabled()); return *this; } auto mTabFrameItem::setFont(const Font& font) -> type& { mObject::setFont(font); if(auto& sizable = state.sizable) sizable->setFont(sizable->font()); return *this; } auto mTabFrameItem::setIcon(const image& icon) -> type& { state.icon = icon; signal(setIcon, icon); return *this; } auto mTabFrameItem::setMovable(bool movable) -> type& { state.movable = movable; signal(setMovable, movable); return *this; } auto mTabFrameItem::setParent(mObject* parent, int offset) -> type& { if(auto& sizable = state.sizable) sizable->destruct(); mObject::setParent(parent, offset); if(auto& sizable = state.sizable) sizable->setParent(this, sizable->offset()); return *this; } auto mTabFrameItem::setSelected() -> type& { if(auto parent = parentTabFrame()) { for(auto& item : parent->state.items) item->state.selected = false; } state.selected = true; signal(setSelected); return *this; } auto mTabFrameItem::setText(const string& text) -> type& { state.text = text; signal(setText, text); return *this; } auto mTabFrameItem::setVisible(bool visible) -> type& { mObject::setVisible(visible); if(auto& sizable = state.sizable) sizable->setVisible(sizable->visible()); return *this; } auto mTabFrameItem::sizable() const -> Sizable { return state.sizable; } auto mTabFrameItem::text() const -> string { return state.text; } #endif
412
0.944918
1
0.944918
game-dev
MEDIA
0.698103
game-dev
0.901238
1
0.901238
mokkkk/MhdpColiseumDatapacksComponents
1,213
mhdp_core/data/mhdp_items/function/weapons/short_sword/type_tec/7_bash_1/attack.mcfunction
#> mhdp_items:weapons/short_sword/type_tec/7_bash_1/attack # # 水平斬りコンボ3 攻撃判定 # # @within function mhdp_items:weapons/great_sword/type_tec/1_charge/change_to_chargeattack # 命中判定 execute anchored eyes positioned ^ ^ ^1 positioned ~-0.5 ~-0.5 ~-0.5 run tag @e[type=slime,tag=Mns.HitBox,dx=1,dy=1,dz=1] add Temp.Hit execute anchored eyes positioned ^ ^ ^2 positioned ~-0.5 ~-0.5 ~-0.5 run tag @e[type=slime,tag=Mns.HitBox,dx=1,dy=1,dz=1] add Temp.Hit execute anchored eyes positioned ^ ^ ^3 positioned ~-0.5 ~-0.5 ~-0.5 run tag @e[type=slime,tag=Mns.HitBox,dx=1,dy=1,dz=1] add Temp.Hit execute anchored eyes positioned ^ ^ ^4 positioned ~-0.5 ~-0.5 ~-0.5 run tag @e[type=slime,tag=Mns.HitBox,dx=1,dy=1,dz=1] add Temp.Hit # ターゲット決定 execute as @e[type=slime,tag=Mns.HitBox,tag=Temp.Hit,sort=nearest,limit=1] run tag @s add Temp.Victim # ヒットストップ execute if entity @n[tag=Temp.Victim] run scoreboard players set @s Wpn.HitStopTimer 1 # 攻撃 data modify storage api: Arg set from storage mhdp_core:game_data WeaponAttackData.ShortSword.Tec.Bash.1 execute if entity @n[tag=Temp.Victim] run function api:damage_player_to_entity # 終了 tag @e[type=slime,tag=Temp.Hit] remove Temp.Hit
412
0.767662
1
0.767662
game-dev
MEDIA
0.997577
game-dev
0.750618
1
0.750618
coltonk9043/Aoba-Client
6,168
src/main/java/net/aoba/managers/pathfinding/TeleportPathManager.java
/* * Aoba Hacked Client * Copyright (C) 2019-2024 coltonk9043 * * Licensed under the GNU General Public License, Version 3 or later. * See <http://www.gnu.org/licenses/>. */ package net.aoba.managers.pathfinding; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import net.minecraft.block.AbstractTorchBlock; import net.minecraft.block.BlockState; import net.minecraft.block.PlantBlock; import net.minecraft.block.SnowBlock; import net.minecraft.block.VineBlock; import net.minecraft.entity.ai.pathing.NavigationType; import net.minecraft.registry.tag.FluidTags; import net.minecraft.util.math.BlockPos; /** * The WalkingPathManager class is responsible for managing and calculating * walking paths in the game. It extends the AbstractPathManager and provides * implementations for path recalculation and heuristic calculation. */ public class TeleportPathManager extends AbstractPathManager { protected float radius = 5.0f; public float getRadius() { return radius; } public void setRadius(float newRadius) { radius = newRadius; } @Override public ArrayList<PathNode> recalculatePath(BlockPos pos) { if (target != null) { // Priority queue to store nodes to be explored, ordered by their cost PriorityQueue<PathFinderEntry> queue = new PriorityQueue<>(Comparator.comparing(e -> e.cost)); // Maps to store parent relationships, visited nodes, and distances HashMap<PathNode, PathNode> parentMap = new HashMap<PathNode, PathNode>(); HashSet<PathNode> visited = new HashSet<PathNode>(); HashMap<PathNode, Float> distances = new HashMap<PathNode, Float>(); // Initialize the start node and set its distance to zero PathNode startNode = new PathNode(pos); distances.put(startNode, 0f); queue.add(new PathFinderEntry(startNode, heuristic(startNode, target))); PathFinderEntry previousTeleportNode = null; // Process nodes in the queue until it is empty while (!queue.isEmpty()) { PathFinderEntry current = queue.poll(); // Store the last teleportable block. This is used to continue the parent map // from a teleport-able location. if (isTeleportable(current.node.pos)) { previousTeleportNode = current; } // Check if the current node is the target if (current.node.pos.equals(target)) { return reconstructPath(startNode, new PathNode(target), parentMap); } // Mark the current node as visited visited.add(current.node); // Explore neighboring nodes ArrayList<PathNode> list = getNeighbouringBlocks(current.node); for (PathNode node : list) { if (visited.contains(node)) continue; float predictedDistanceToTarget = heuristic(node, target); PathFinderEntry newEntry = new PathFinderEntry(node, predictedDistanceToTarget); queue.add(newEntry); if (isTeleportable(node.pos)) { // Update distances and parent relationships if a shorter path is found if (!distances.containsKey(node) || predictedDistanceToTarget < distances.get(node)) { distances.put(node, predictedDistanceToTarget); if (previousTeleportNode != null) parentMap.put(node, previousTeleportNode.node); } } } } } // Return null if no path is found return null; } /** * Determines if a position can be teleported to. * * @param pos Position to check. * @return Whether or not the position can be teleported to. */ private boolean isTeleportable(BlockPos pos) { BlockPos down = pos.down(); BlockState state = MC.world.getBlockState(pos); BlockState stateBelow = MC.world.getBlockState(down); boolean isPlant = state.getBlock() instanceof PlantBlock; boolean isSnow = state.getBlock() instanceof SnowBlock; boolean isTorch = state.getBlock() instanceof AbstractTorchBlock; boolean isVine = state.getBlock() instanceof VineBlock; return isPlayerPassable(pos) && state.canPathfindThrough(NavigationType.LAND) && !state.getFluidState().isIn(FluidTags.WATER) && !state.getFluidState().isIn(FluidTags.LAVA) && !stateBelow.canPathfindThrough(NavigationType.LAND) && !stateBelow.isAir() && stateBelow.getFluidState().isEmpty() && !isPlant && !isSnow && !isTorch && !isVine; } @Override protected ArrayList<PathNode> getNeighbouringBlocks(PathNode node) { ArrayList<PathNode> potentialBlocks = new ArrayList<PathNode>( List.of(new PathNode(node.pos.north()), new PathNode(node.pos.east()), new PathNode(node.pos.south()), new PathNode(node.pos.west()), new PathNode(node.pos.up()), new PathNode(node.pos.down()))); return potentialBlocks; } @Override protected ArrayList<PathNode> reconstructPath(PathNode start, PathNode target, HashMap<PathNode, PathNode> parentMap) { float radiusSqr = radius * radius; ArrayList<PathNode> path = new ArrayList<>(); PathNode prev = target; path.addFirst(prev); // If the start equals the target, return early since there is only one node. if (start.equals(target)) return path; // Otherwise traverse the parentMap until we reach the destination. // Skips any nodes that are in the same 'direction' as the previous to trim it. PathNode current = parentMap.get(prev); while (current != null && !current.equals(start)) { if (isTeleportable(current.pos) && radiusSqr <= prev.pos.toCenterPos().squaredDistanceTo(current.pos.toCenterPos())) { prev = current; path.addFirst(current); } current = parentMap.get(current); } path.addFirst(start); return path; } @Override protected float heuristic(PathNode position, BlockPos target) { if (position == null || target == null) { throw new IllegalArgumentException("Position and target must not be null"); } // Calculate the squared differences in x, y, and z coordinates float dx = (float) Math.abs(position.pos.getX() - target.getX()); float dy = (float) Math.abs(position.pos.getY() - target.getY()); float dz = (float) Math.abs(position.pos.getZ() - target.getZ()); // Return the combined result of the squared differences return dx + dy + dz; } }
412
0.947542
1
0.947542
game-dev
MEDIA
0.731623
game-dev
0.993474
1
0.993474
dimforge/bevy_rapier
1,234
bevy_rapier2d/examples/rope_joint2.rs
use bevy::prelude::*; use bevy_rapier2d::prelude::*; fn main() { App::new() .insert_resource(ClearColor(Color::srgb( 0xF9 as f32 / 255.0, 0xF9 as f32 / 255.0, 0xFF as f32 / 255.0, ))) .add_plugins(( DefaultPlugins, RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(100.0), RapierDebugRenderPlugin::default(), )) .add_systems(Startup, (setup_graphics, setup_physics)) .run(); } pub fn setup_graphics(mut commands: Commands) { commands.spawn((Camera2d, Transform::from_xyz(0.0, -200.0, 0.0))); } pub fn setup_physics(mut commands: Commands) { let rad = 10.0; let rope_length = rad * 10.0; let parent = commands .spawn(( Transform::from_xyz(0.0, 0.0, 0.0), RigidBody::Fixed, Collider::cuboid(rad, rad), )) .id(); let joint = RopeJointBuilder::new(rope_length).local_anchor2(Vec2::new(rope_length, 0.0)); commands .spawn(( Transform::from_xyz(-rad * 2.0, 0.0, 0.0), RigidBody::Dynamic, Collider::cuboid(rad, rad), )) .insert(ImpulseJoint::new(parent, joint)); }
412
0.58286
1
0.58286
game-dev
MEDIA
0.635269
game-dev
0.673933
1
0.673933
imengyu/ONICPU
6,470
ONICPU/digit/DigitSeg.cs
using System; using System.Linq; using UnityEngine; namespace ONICPU.digit { public class DigitSeg : KMonoBehaviour, ISaveLoadable { private LogicPorts ports; public static readonly HashedString READ_PORT_ID = new HashedString("LogicRead"); public static readonly KAnimHashedString SegNegId = new KAnimHashedString("seg_neg"); private static readonly KAnimHashedString[][] SegId = new KAnimHashedString[7][]; private const int MAX_SEG_VALUE = 16; public int displayBits = 0; private KBatchedAnimController kbac; private int value = 0; static DigitSeg() { for (int i = 0; i < SegId.Length; i++) { KAnimHashedString[] arr = new KAnimHashedString[10]; for (int j = 0; j < arr.Length; j++) arr[j] = new KAnimHashedString($"seg{j}_{i}"); SegId[i] = arr; } } private Color activeTintColor = new Color(1f, 0.4f, 0.4f); private Color inactiveTintColor = new Color(40 / 255.0f, 58 / 255.0f, 46 / 255.0f); private static readonly EventSystem.IntraObjectHandler<DigitSeg> OnLogicValueChangedDelegate = new EventSystem.IntraObjectHandler<DigitSeg>(delegate (DigitSeg component, object data) { component.OnLogicValueChanged(data); }); protected override void OnSpawn() { Subscribe(-801688580, OnLogicValueChangedDelegate); ports = GetComponent<LogicPorts>(); kbac = GetComponent<KBatchedAnimController>(); kbac.Play("on"); } protected override void OnCleanUp() { Unsubscribe(-801688580, OnLogicValueChangedDelegate); base.OnCleanUp(); } public void OnLogicValueChanged(object data) { var logicValueChanged = (LogicValueChanged)data; if (logicValueChanged.portID == READ_PORT_ID) { value = ports.GetInputValue(READ_PORT_ID); RefreshAnim(); } } private void DisplayOverflow(int maxCount) { Update7Seg(kbac, 1, 0); Update7Seg(kbac, 0, 15); for (short i = 2; i < maxCount; i++) Update7Seg(kbac, i, MAX_SEG_VALUE); } private void RefreshAnim() { switch(displayBits) { case 8: case 16: { var maxCount = (displayBits == 8 ? 3 : 5); if (displayBits == 8) { if (value > 999 || value < -999) { //of DisplayOverflow(maxCount); return; } } else { if (value > short.MaxValue || value < short.MinValue) { //of DisplayOverflow(maxCount); return; } } short number1 = (short)value; //8bit char; 16 bit short short number = (short)Math.Abs((int)number1); short index = 0; if (number1 == 0) { short number2 = 0; for (; index < maxCount; index++) { Update7Seg(kbac, index, number2); number2 = MAX_SEG_VALUE; } Update7Seg(kbac, -1, 1); } else { while (number > 0) { Update7Seg(kbac, index, (short)(number % 10)); number = (short)(number / 10); index++; } if (number1 < 0) { Update7Seg(kbac, index >= maxCount ? (short)-1 : index, -1); index++; } else { Update7Seg(kbac, -1, 1); } for (; index < maxCount; index++) Update7Seg(kbac, index, MAX_SEG_VALUE); } break; } case 32: { const int maxCount = 10; var number1 = (long)value; if (number1 > int.MaxValue || number1 < int.MinValue) { //of DisplayOverflow(maxCount); return; } var number = Math.Abs(number1); short index = 0; if (number1 == 0) { short number2 = 0; for (; index < maxCount; index++) { Update7Seg(kbac, index, number2); number2 = MAX_SEG_VALUE; } Update7Seg(kbac, -1, 1); } else { while (number > 0) { Update7Seg(kbac, index, (short)(number % 10)); number = number / 10; index++; } if (number1 < 0) { Update7Seg(kbac, index >= maxCount ? (short)-1 : index, -1); index++; } else { Update7Seg(kbac, -1, 1); } for (; index < maxCount; index++) Update7Seg(kbac, index, MAX_SEG_VALUE); } break; } } } private static readonly short[][] Seg7ActiveMap = new short[7][] { new short[] { 2,3,5,6,7,8,9,0,10,12,14,15}, //a new short[] { 1,2,3,4,7,8,9,0,10,13 }, //b new short[] { 1,3,4,5,6,7,8,9,0,10,11,13 }, //c new short[] { 2,3,5,6,8,9,0,11,12,13,14}, //d new short[] { 2,6,0,8,10,11,12,13,14,15}, //e new short[] { 4,5,6,8,9,0,10,11,12,14,15 }, //f new short[] { 2,3,4,5,6,8,9,10,11,12,13,14,15 },//g }; private void Update7Seg(KBatchedAnimController component, short index, short value) { if (index == -1) { Utils.TintSymbolConditionally(true, value < 0, component, SegNegId, activeTintColor, inactiveTintColor); } else { if (value >= 0) { for (int i = 0; i < Seg7ActiveMap.Length; i++) Utils.TintSymbolConditionally(true, Seg7ActiveMap[i].Contains(value), component, SegId[i][index], activeTintColor, inactiveTintColor); } else { for (int i = 0; i < Seg7ActiveMap.Length - 1; i++) Utils.TintSymbolConditionally(true, false, component, SegId[i][index], activeTintColor, inactiveTintColor); Utils.TintSymbolConditionally(true, true, component, SegId[6][index], activeTintColor, inactiveTintColor); } } } } }
412
0.918691
1
0.918691
game-dev
MEDIA
0.244966
game-dev
0.951274
1
0.951274
QuestionableM/SM-BetterPaintTool
2,749
Dependencies/bullet3/Bullet3OpenCL/NarrowphaseCollision/b3ContactCache.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef B3_CONTACT_CACHE_H #define B3_CONTACT_CACHE_H #include "Bullet3Common/b3Vector3.h" #include "Bullet3Common/b3Transform.h" #include "Bullet3Common/b3AlignedAllocator.h" ///maximum contact breaking and merging threshold extern b3Scalar gContactBreakingThreshold; #define MANIFOLD_CACHE_SIZE 4 ///b3ContactCache is a contact point cache, it stays persistent as long as objects are overlapping in the broadphase. ///Those contact points are created by the collision narrow phase. ///The cache can be empty, or hold 1,2,3 or 4 points. Some collision algorithms (GJK) might only add one point at a time. ///updates/refreshes old contact points, and throw them away if necessary (distance becomes too large) ///reduces the cache to 4 points, when more then 4 points are added, using following rules: ///the contact point with deepest penetration is always kept, and it tries to maximuze the area covered by the points ///note that some pairs of objects might have more then one contact manifold. B3_ATTRIBUTE_ALIGNED16(class) b3ContactCache { /// sort cached points so most isolated points come first int sortCachedPoints(const b3Vector3& pt); public: B3_DECLARE_ALIGNED_ALLOCATOR(); int addManifoldPoint(const b3Vector3& newPoint); /*void replaceContactPoint(const b3Vector3& newPoint,int insertIndex) { b3Assert(validContactDistance(newPoint)); m_pointCache[insertIndex] = newPoint; } */ static bool validContactDistance(const b3Vector3& pt); /// calculated new worldspace coordinates and depth, and reject points that exceed the collision margin static void refreshContactPoints(const b3Transform& trA, const b3Transform& trB, struct b3Contact4Data& newContactCache); static void removeContactPoint(struct b3Contact4Data & newContactCache, int i); }; #endif //B3_CONTACT_CACHE_H
412
0.963825
1
0.963825
game-dev
MEDIA
0.93669
game-dev
0.897442
1
0.897442
motorsep/StormEngine2
16,370
neo/libs/SDL2/src/video/android/SDL_androidkeyboard.c
/* Simple DirectMedia Layer Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_ANDROID #include <android/log.h> #include "../../events/SDL_events_c.h" #include "SDL_androidkeyboard.h" #include "../../core/android/SDL_android.h" static SDL_Scancode Android_Keycodes[] = { SDL_SCANCODE_UNKNOWN, /* AKEYCODE_UNKNOWN */ SDL_SCANCODE_SOFTLEFT, /* AKEYCODE_SOFT_LEFT */ SDL_SCANCODE_SOFTRIGHT, /* AKEYCODE_SOFT_RIGHT */ SDL_SCANCODE_AC_HOME, /* AKEYCODE_HOME */ SDL_SCANCODE_AC_BACK, /* AKEYCODE_BACK */ SDL_SCANCODE_CALL, /* AKEYCODE_CALL */ SDL_SCANCODE_ENDCALL, /* AKEYCODE_ENDCALL */ SDL_SCANCODE_0, /* AKEYCODE_0 */ SDL_SCANCODE_1, /* AKEYCODE_1 */ SDL_SCANCODE_2, /* AKEYCODE_2 */ SDL_SCANCODE_3, /* AKEYCODE_3 */ SDL_SCANCODE_4, /* AKEYCODE_4 */ SDL_SCANCODE_5, /* AKEYCODE_5 */ SDL_SCANCODE_6, /* AKEYCODE_6 */ SDL_SCANCODE_7, /* AKEYCODE_7 */ SDL_SCANCODE_8, /* AKEYCODE_8 */ SDL_SCANCODE_9, /* AKEYCODE_9 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STAR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_POUND */ SDL_SCANCODE_UP, /* AKEYCODE_DPAD_UP */ SDL_SCANCODE_DOWN, /* AKEYCODE_DPAD_DOWN */ SDL_SCANCODE_LEFT, /* AKEYCODE_DPAD_LEFT */ SDL_SCANCODE_RIGHT, /* AKEYCODE_DPAD_RIGHT */ SDL_SCANCODE_SELECT, /* AKEYCODE_DPAD_CENTER */ SDL_SCANCODE_VOLUMEUP, /* AKEYCODE_VOLUME_UP */ SDL_SCANCODE_VOLUMEDOWN, /* AKEYCODE_VOLUME_DOWN */ SDL_SCANCODE_POWER, /* AKEYCODE_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CAMERA */ SDL_SCANCODE_CLEAR, /* AKEYCODE_CLEAR */ SDL_SCANCODE_A, /* AKEYCODE_A */ SDL_SCANCODE_B, /* AKEYCODE_B */ SDL_SCANCODE_C, /* AKEYCODE_C */ SDL_SCANCODE_D, /* AKEYCODE_D */ SDL_SCANCODE_E, /* AKEYCODE_E */ SDL_SCANCODE_F, /* AKEYCODE_F */ SDL_SCANCODE_G, /* AKEYCODE_G */ SDL_SCANCODE_H, /* AKEYCODE_H */ SDL_SCANCODE_I, /* AKEYCODE_I */ SDL_SCANCODE_J, /* AKEYCODE_J */ SDL_SCANCODE_K, /* AKEYCODE_K */ SDL_SCANCODE_L, /* AKEYCODE_L */ SDL_SCANCODE_M, /* AKEYCODE_M */ SDL_SCANCODE_N, /* AKEYCODE_N */ SDL_SCANCODE_O, /* AKEYCODE_O */ SDL_SCANCODE_P, /* AKEYCODE_P */ SDL_SCANCODE_Q, /* AKEYCODE_Q */ SDL_SCANCODE_R, /* AKEYCODE_R */ SDL_SCANCODE_S, /* AKEYCODE_S */ SDL_SCANCODE_T, /* AKEYCODE_T */ SDL_SCANCODE_U, /* AKEYCODE_U */ SDL_SCANCODE_V, /* AKEYCODE_V */ SDL_SCANCODE_W, /* AKEYCODE_W */ SDL_SCANCODE_X, /* AKEYCODE_X */ SDL_SCANCODE_Y, /* AKEYCODE_Y */ SDL_SCANCODE_Z, /* AKEYCODE_Z */ SDL_SCANCODE_COMMA, /* AKEYCODE_COMMA */ SDL_SCANCODE_PERIOD, /* AKEYCODE_PERIOD */ SDL_SCANCODE_LALT, /* AKEYCODE_ALT_LEFT */ SDL_SCANCODE_RALT, /* AKEYCODE_ALT_RIGHT */ SDL_SCANCODE_LSHIFT, /* AKEYCODE_SHIFT_LEFT */ SDL_SCANCODE_RSHIFT, /* AKEYCODE_SHIFT_RIGHT */ SDL_SCANCODE_TAB, /* AKEYCODE_TAB */ SDL_SCANCODE_SPACE, /* AKEYCODE_SPACE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SYM */ SDL_SCANCODE_WWW, /* AKEYCODE_EXPLORER */ SDL_SCANCODE_MAIL, /* AKEYCODE_ENVELOPE */ SDL_SCANCODE_RETURN, /* AKEYCODE_ENTER */ SDL_SCANCODE_BACKSPACE, /* AKEYCODE_DEL */ SDL_SCANCODE_GRAVE, /* AKEYCODE_GRAVE */ SDL_SCANCODE_MINUS, /* AKEYCODE_MINUS */ SDL_SCANCODE_EQUALS, /* AKEYCODE_EQUALS */ SDL_SCANCODE_LEFTBRACKET, /* AKEYCODE_LEFT_BRACKET */ SDL_SCANCODE_RIGHTBRACKET, /* AKEYCODE_RIGHT_BRACKET */ SDL_SCANCODE_BACKSLASH, /* AKEYCODE_BACKSLASH */ SDL_SCANCODE_SEMICOLON, /* AKEYCODE_SEMICOLON */ SDL_SCANCODE_APOSTROPHE, /* AKEYCODE_APOSTROPHE */ SDL_SCANCODE_SLASH, /* AKEYCODE_SLASH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NUM */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_HEADSETHOOK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_FOCUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PLUS */ SDL_SCANCODE_MENU, /* AKEYCODE_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NOTIFICATION */ SDL_SCANCODE_AC_SEARCH, /* AKEYCODE_SEARCH */ SDL_SCANCODE_AUDIOPLAY, /* AKEYCODE_MEDIA_PLAY_PAUSE */ SDL_SCANCODE_AUDIOSTOP, /* AKEYCODE_MEDIA_STOP */ SDL_SCANCODE_AUDIONEXT, /* AKEYCODE_MEDIA_NEXT */ SDL_SCANCODE_AUDIOPREV, /* AKEYCODE_MEDIA_PREVIOUS */ SDL_SCANCODE_AUDIOREWIND, /* AKEYCODE_MEDIA_REWIND */ SDL_SCANCODE_AUDIOFASTFORWARD, /* AKEYCODE_MEDIA_FAST_FORWARD */ SDL_SCANCODE_MUTE, /* AKEYCODE_MUTE */ SDL_SCANCODE_PAGEUP, /* AKEYCODE_PAGE_UP */ SDL_SCANCODE_PAGEDOWN, /* AKEYCODE_PAGE_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PICTSYMBOLS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SWITCH_CHARSET */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_A */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_B */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_C */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_X */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_Y */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_Z */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_L1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_R1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_L2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_R2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_THUMBL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_THUMBR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_START */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_SELECT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_MODE */ SDL_SCANCODE_ESCAPE, /* AKEYCODE_ESCAPE */ SDL_SCANCODE_DELETE, /* AKEYCODE_FORWARD_DEL */ SDL_SCANCODE_LCTRL, /* AKEYCODE_CTRL_LEFT */ SDL_SCANCODE_RCTRL, /* AKEYCODE_CTRL_RIGHT */ SDL_SCANCODE_CAPSLOCK, /* AKEYCODE_CAPS_LOCK */ SDL_SCANCODE_SCROLLLOCK, /* AKEYCODE_SCROLL_LOCK */ SDL_SCANCODE_LGUI, /* AKEYCODE_META_LEFT */ SDL_SCANCODE_RGUI, /* AKEYCODE_META_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_FUNCTION */ SDL_SCANCODE_PRINTSCREEN, /* AKEYCODE_SYSRQ */ SDL_SCANCODE_PAUSE, /* AKEYCODE_BREAK */ SDL_SCANCODE_HOME, /* AKEYCODE_MOVE_HOME */ SDL_SCANCODE_END, /* AKEYCODE_MOVE_END */ SDL_SCANCODE_INSERT, /* AKEYCODE_INSERT */ SDL_SCANCODE_AC_FORWARD, /* AKEYCODE_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_PLAY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_PAUSE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_CLOSE */ SDL_SCANCODE_EJECT, /* AKEYCODE_MEDIA_EJECT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_RECORD */ SDL_SCANCODE_F1, /* AKEYCODE_F1 */ SDL_SCANCODE_F2, /* AKEYCODE_F2 */ SDL_SCANCODE_F3, /* AKEYCODE_F3 */ SDL_SCANCODE_F4, /* AKEYCODE_F4 */ SDL_SCANCODE_F5, /* AKEYCODE_F5 */ SDL_SCANCODE_F6, /* AKEYCODE_F6 */ SDL_SCANCODE_F7, /* AKEYCODE_F7 */ SDL_SCANCODE_F8, /* AKEYCODE_F8 */ SDL_SCANCODE_F9, /* AKEYCODE_F9 */ SDL_SCANCODE_F10, /* AKEYCODE_F10 */ SDL_SCANCODE_F11, /* AKEYCODE_F11 */ SDL_SCANCODE_F12, /* AKEYCODE_F12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NUM_LOCK */ SDL_SCANCODE_KP_0, /* AKEYCODE_NUMPAD_0 */ SDL_SCANCODE_KP_1, /* AKEYCODE_NUMPAD_1 */ SDL_SCANCODE_KP_2, /* AKEYCODE_NUMPAD_2 */ SDL_SCANCODE_KP_3, /* AKEYCODE_NUMPAD_3 */ SDL_SCANCODE_KP_4, /* AKEYCODE_NUMPAD_4 */ SDL_SCANCODE_KP_5, /* AKEYCODE_NUMPAD_5 */ SDL_SCANCODE_KP_6, /* AKEYCODE_NUMPAD_6 */ SDL_SCANCODE_KP_7, /* AKEYCODE_NUMPAD_7 */ SDL_SCANCODE_KP_8, /* AKEYCODE_NUMPAD_8 */ SDL_SCANCODE_KP_9, /* AKEYCODE_NUMPAD_9 */ SDL_SCANCODE_KP_DIVIDE, /* AKEYCODE_NUMPAD_DIVIDE */ SDL_SCANCODE_KP_MULTIPLY, /* AKEYCODE_NUMPAD_MULTIPLY */ SDL_SCANCODE_KP_MINUS, /* AKEYCODE_NUMPAD_SUBTRACT */ SDL_SCANCODE_KP_PLUS, /* AKEYCODE_NUMPAD_ADD */ SDL_SCANCODE_KP_PERIOD, /* AKEYCODE_NUMPAD_DOT */ SDL_SCANCODE_KP_COMMA, /* AKEYCODE_NUMPAD_COMMA */ SDL_SCANCODE_KP_ENTER, /* AKEYCODE_NUMPAD_ENTER */ SDL_SCANCODE_KP_EQUALS, /* AKEYCODE_NUMPAD_EQUALS */ SDL_SCANCODE_KP_LEFTPAREN, /* AKEYCODE_NUMPAD_LEFT_PAREN */ SDL_SCANCODE_KP_RIGHTPAREN, /* AKEYCODE_NUMPAD_RIGHT_PAREN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_VOLUME_MUTE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_INFO */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CHANNEL_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CHANNEL_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ZOOM_IN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ZOOM_OUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_WINDOW */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_GUIDE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DVR */ SDL_SCANCODE_AC_BOOKMARKS, /* AKEYCODE_BOOKMARK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CAPTIONS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SETTINGS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STB_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STB_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AVR_POWER */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_AVR_INPUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_RED */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_GREEN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_YELLOW */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PROG_BLUE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_APP_SWITCH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_4 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_5 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_6 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_7 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_8 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_9 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_10 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_11 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_13 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_14 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_15 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_BUTTON_16 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_LANGUAGE_SWITCH */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MANNER_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_3D_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CONTACTS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_CALENDAR */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MUSIC */ SDL_SCANCODE_CALCULATOR, /* AKEYCODE_CALCULATOR */ SDL_SCANCODE_LANG5, /* AKEYCODE_ZENKAKU_HANKAKU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_EISU */ SDL_SCANCODE_INTERNATIONAL5, /* AKEYCODE_MUHENKAN */ SDL_SCANCODE_INTERNATIONAL4, /* AKEYCODE_HENKAN */ SDL_SCANCODE_LANG3, /* AKEYCODE_KATAKANA_HIRAGANA */ SDL_SCANCODE_INTERNATIONAL3, /* AKEYCODE_YEN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_RO */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_KANA */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_ASSIST */ SDL_SCANCODE_BRIGHTNESSDOWN, /* AKEYCODE_BRIGHTNESS_DOWN */ SDL_SCANCODE_BRIGHTNESSUP, /* AKEYCODE_BRIGHTNESS_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_AUDIO_TRACK */ SDL_SCANCODE_SLEEP, /* AKEYCODE_SLEEP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_WAKEUP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_PAIRING */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_TOP_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_11 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_12 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_LAST_CHANNEL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_DATA_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_VOICE_ASSIST */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_RADIO_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TELETEXT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_NUMBER_ENTRY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TERRESTRIAL_ANALOG */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TERRESTRIAL_DIGITAL */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_BS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_CS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_SATELLITE_SERVICE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_NETWORK */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_ANTENNA_CABLE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_HDMI_4 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPOSITE_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPOSITE_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPONENT_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_COMPONENT_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_INPUT_VGA_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_ZOOM_MODE */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_CONTENTS_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_MEDIA_CONTEXT_MENU */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_TV_TIMER_PROGRAMMING */ SDL_SCANCODE_HELP, /* AKEYCODE_HELP */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_PREVIOUS */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_NEXT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_IN */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_NAVIGATE_OUT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_PRIMARY */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_1 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_2 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_STEM_3 */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_UP_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_DOWN_LEFT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_UP_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_DPAD_DOWN_RIGHT */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_SKIP_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_SKIP_BACKWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_STEP_FORWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_STEP_BACKWARD */ SDL_SCANCODE_UNKNOWN, /* AKEYCODE_SOFT_SLEEP */ SDL_SCANCODE_CUT, /* AKEYCODE_CUT */ SDL_SCANCODE_COPY, /* AKEYCODE_COPY */ SDL_SCANCODE_PASTE, /* AKEYCODE_PASTE */ }; static SDL_Scancode TranslateKeycode(int keycode) { SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; if (keycode < SDL_arraysize(Android_Keycodes)) { scancode = Android_Keycodes[keycode]; } if (scancode == SDL_SCANCODE_UNKNOWN) { __android_log_print(ANDROID_LOG_INFO, "SDL", "Unknown keycode %d", keycode); } return scancode; } int Android_OnKeyDown(int keycode) { return SDL_SendKeyboardKey(SDL_PRESSED, TranslateKeycode(keycode)); } int Android_OnKeyUp(int keycode) { return SDL_SendKeyboardKey(SDL_RELEASED, TranslateKeycode(keycode)); } SDL_bool Android_HasScreenKeyboardSupport(_THIS) { return SDL_TRUE; } SDL_bool Android_IsScreenKeyboardShown(_THIS, SDL_Window * window) { return Android_JNI_IsScreenKeyboardShown(); } void Android_StartTextInput(_THIS) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; Android_JNI_ShowTextInput(&videodata->textRect); } void Android_StopTextInput(_THIS) { Android_JNI_HideTextInput(); } void Android_SetTextInputRect(_THIS, const SDL_Rect *rect) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; if (!rect) { SDL_InvalidParamError("rect"); return; } videodata->textRect = *rect; } #endif /* SDL_VIDEO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
412
0.82935
1
0.82935
game-dev
MEDIA
0.675816
game-dev
0.606454
1
0.606454
lorddusk/HQM
3,970
common/src/main/java/hardcorequesting/common/blocks/DeliveryBlock.java
package hardcorequesting.common.blocks; import hardcorequesting.common.HardcoreQuestingCore; import hardcorequesting.common.items.QuestBookItem; import hardcorequesting.common.quests.Quest; import hardcorequesting.common.tileentity.AbstractBarrelBlockEntity; import hardcorequesting.common.util.Translator; import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.BlockHitResult; import org.jetbrains.annotations.Nullable; public class DeliveryBlock extends BaseEntityBlock { public static final BooleanProperty BOUND = BooleanProperty.create("bound"); public DeliveryBlock(Properties properties) { super(properties); this.registerDefaultState(this.getStateDefinition().any().setValue(BOUND, false)); } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return HardcoreQuestingCore.platform.createBarrelBlockEntity(pos, state); } @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { if (!world.isClientSide) { ItemStack hold = player.getItemInHand(hand); BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof AbstractBarrelBlockEntity) { if (!hold.isEmpty() && hold.getItem() instanceof QuestBookItem) { ((AbstractBarrelBlockEntity) tile).storeSettings(player); if (((AbstractBarrelBlockEntity) tile).getCurrentTask() != null) { player.sendSystemMessage(Translator.translatable("tile.hqm:item_barrel.bindTo", Quest.getQuest(((AbstractBarrelBlockEntity) tile).getQuestUUID()).getName())); } else { player.sendSystemMessage(Translator.translatable("hqm.message.noTaskSelected")); } } else { if (((AbstractBarrelBlockEntity) tile).getCurrentTask() != null) { player.sendSystemMessage(Translator.translatable("tile.hqm:item_barrel.boundTo", Quest.getQuest(((AbstractBarrelBlockEntity) tile).getQuestUUID()).getName())); } else { player.sendSystemMessage(Translator.translatable("tile.hqm:item_barrel.nonBound")); } } } } return InteractionResult.SUCCESS; } @Override public boolean hasAnalogOutputSignal(BlockState state) { return true; } @Override public int getAnalogOutputSignal(BlockState state, Level world, BlockPos pos) { if (state.getValue(BOUND)) { return 15; } else { return 0; } } @Override public RenderShape getRenderShape(BlockState state) { return RenderShape.MODEL; } @Override public BlockState getStateForPlacement(BlockPlaceContext ctx) { return super.getStateForPlacement(ctx).setValue(BOUND, false); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder); builder.add(BOUND); } }
412
0.819998
1
0.819998
game-dev
MEDIA
0.998588
game-dev
0.941006
1
0.941006
plan-player-analytics/Plan
2,955
Plan/common/src/main/java/com/djrapitops/plan/delivery/rendering/json/graphs/pie/WorldPie.java
/* * This file is part of Player Analytics (Plan). * * Plan is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3 as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Plan is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Plan. If not, see <https://www.gnu.org/licenses/>. */ package com.djrapitops.plan.delivery.rendering.json.graphs.pie; import com.djrapitops.plan.gathering.domain.GMTimes; import com.djrapitops.plan.utilities.comparators.PieSliceComparator; import java.util.*; public class WorldPie extends PieWithDrilldown { private final Map<String, GMTimes> gmTimesAliasMap; WorldPie( Map<String, Long> playtimePerAlias, Map<String, GMTimes> gmTimesAliasMap, String[] colors, boolean orderByPercentage ) { super(turnIntoSlices(playtimePerAlias, colors)); this.gmTimesAliasMap = gmTimesAliasMap; if (orderByPercentage) { slices.sort(new PieSliceComparator()); } } private static List<PieSlice> turnIntoSlices(Map<String, Long> playtimePerAlias, String[] colors) { int colLength = colors.length; List<String> worlds = new ArrayList<>(playtimePerAlias.keySet()); Collections.sort(worlds); List<PieSlice> slices = new ArrayList<>(); int i = 0; for (String alias : worlds) { Long value = playtimePerAlias.getOrDefault(alias, 0L); if (value != 0L) { slices.add(new PieSlice(alias, value, colors[i % colLength], true)); } i++; } return slices; } public List<Map<String, Object>> toHighChartsDrillDownMaps() { List<Map<String, Object>> drilldowns = new ArrayList<>(); for (Map.Entry<String, GMTimes> worldAlias : gmTimesAliasMap.entrySet()) { Map<String, Object> drilldown = new HashMap<>(); drilldown.put("name", worldAlias.getKey()); drilldown.put("id", worldAlias.getKey()); drilldown.put("data", createGMTimesForWorld(worldAlias.getValue())); drilldowns.add(drilldown); } return drilldowns; } private List<List<Object>> createGMTimesForWorld(GMTimes gmTimes) { List<List<Object>> data = new ArrayList<>(); for (Map.Entry<String, Long> gmEntry : gmTimes.getTimes().entrySet()) { List<Object> gmList = Arrays.asList(gmEntry.getKey(), gmEntry.getValue()); data.add(gmList); } return data; } }
412
0.841017
1
0.841017
game-dev
MEDIA
0.506512
game-dev
0.895142
1
0.895142
Sergey1560/Marlin_FB4S
6,979
Marlin/src/lcd/menu/game/brickout.cpp
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(MARLIN_BRICKOUT) #include "game.h" #define BRICK_H 5 #define BRICK_TOP MENU_FONT_ASCENT #define PADDLE_H 2 #define PADDLE_VEL 3 #define PADDLE_W ((LCD_PIXEL_WIDTH) / 8) #define PADDLE_Y (LCD_PIXEL_HEIGHT - 1 - PADDLE_H) #define BRICK_W ((LCD_PIXEL_WIDTH) / (BRICK_COLS)) #define BRICK_BOT (BRICK_TOP + BRICK_H * BRICK_ROWS - 1) #define BRICK_COL(X) ((X) / (BRICK_W)) #define BRICK_ROW(Y) ((Y - (BRICK_TOP)) / (BRICK_H)) brickout_data_t &bdat = marlin_game_data.brickout; inline void reset_bricks(const uint16_t v) { bdat.brick_count = (BRICK_COLS) * (BRICK_ROWS); LOOP_L_N(i, BRICK_ROWS) bdat.bricks[i] = v; } void reset_ball() { constexpr uint8_t ball_dist = 24; bdat.bally = BTOF(PADDLE_Y - ball_dist); bdat.ballv = FTOF(1.3f); bdat.ballh = -FTOF(1.25f); uint8_t bx = bdat.paddle_x + (PADDLE_W) / 2 + ball_dist; if (bx >= LCD_PIXEL_WIDTH - 10) { bx -= ball_dist * 2; bdat.ballh = -bdat.ballh; } bdat.ballx = BTOF(bx); bdat.hit_dir = -1; } void BrickoutGame::game_screen() { if (game_frame()) { // Run logic twice for finer resolution // Update Paddle Position bdat.paddle_x = constrain(int8_t(ui.encoderPosition), 0, (LCD_PIXEL_WIDTH - (PADDLE_W)) / (PADDLE_VEL)); ui.encoderPosition = bdat.paddle_x; bdat.paddle_x *= (PADDLE_VEL); // Run the ball logic if (game_state) do { // Provisionally update the ball position const fixed_t newx = bdat.ballx + bdat.ballh, newy = bdat.bally + bdat.ballv; // current next position if (!WITHIN(newx, 0, BTOF(LCD_PIXEL_WIDTH - 1))) { // out in x? bdat.ballh = -bdat.ballh; _BUZZ(5, 220); // bounce x } if (newy < 0) { // out in y? bdat.ballv = -bdat.ballv; _BUZZ(5, 280); // bounce v bdat.hit_dir = 1; } // Did the ball go below the bottom? else if (newy > BTOF(LCD_PIXEL_HEIGHT)) { _BUZZ(500, 75); if (--bdat.balls_left) reset_ball(); else game_state = 0; break; // done } // Is the ball colliding with a brick? if (WITHIN(newy, BTOF(BRICK_TOP), BTOF(BRICK_BOT))) { const int8_t bit = BRICK_COL(FTOB(newx)), row = BRICK_ROW(FTOB(newy)); const uint16_t mask = _BV(bit); if (bdat.bricks[row] & mask) { // Yes. Remove it! bdat.bricks[row] &= ~mask; // Score! score += BRICK_ROWS - row; // If bricks are gone, go to reset state if (!--bdat.brick_count) game_state = 2; // Bounce the ball cleverly if ((bdat.ballv < 0) == (bdat.hit_dir < 0)) { bdat.ballv = -bdat.ballv; bdat.ballh += fixed_t(random(-16, 16)); _BUZZ(5, 880); } else { bdat.ballh = -bdat.ballh; bdat.ballv += fixed_t(random(-16, 16)); _BUZZ(5, 640); } } } // Is the ball moving down and in paddle range? else if (bdat.ballv > 0 && WITHIN(newy, BTOF(PADDLE_Y), BTOF(PADDLE_Y + PADDLE_H))) { // Ball actually hitting paddle const int8_t diff = FTOB(newx) - bdat.paddle_x; if (WITHIN(diff, 0, PADDLE_W - 1)) { // Reverse Y direction bdat.ballv = -bdat.ballv; _BUZZ(3, 880); bdat.hit_dir = -1; // Near edges affects X velocity const bool is_left_edge = (diff <= 1); if (is_left_edge || diff >= PADDLE_W-1 - 1) { if ((bdat.ballh > 0) == is_left_edge) bdat.ballh = -bdat.ballh; } else if (diff <= 3) { bdat.ballh += fixed_t(random(-64, 0)); LIMIT(bdat.ballh, BTOF(-2), BTOF(2)); } else if (diff >= PADDLE_W-1 - 3) { bdat.ballh += fixed_t(random( 0, 64)); LIMIT(bdat.ballh, BTOF(-2), BTOF(2)); } // Paddle hit after clearing the board? Reset the board. if (game_state == 2) { reset_bricks(0xFFFF); game_state = 1; } } } bdat.ballx += bdat.ballh; bdat.bally += bdat.ballv; // update with new velocity } while (false); } u8g.setColorIndex(1); // Draw bricks if (PAGE_CONTAINS(BRICK_TOP, BRICK_BOT)) { LOOP_L_N(y, BRICK_ROWS) { const uint8_t yy = y * BRICK_H + BRICK_TOP; if (PAGE_CONTAINS(yy, yy + BRICK_H - 1)) { LOOP_L_N(x, BRICK_COLS) { if (TEST(bdat.bricks[y], x)) { const uint8_t xx = x * BRICK_W; LOOP_L_N(v, BRICK_H - 1) if (PAGE_CONTAINS(yy + v, yy + v)) u8g.drawHLine(xx, yy + v, BRICK_W - 1); } } } } } // Draw paddle if (PAGE_CONTAINS(PADDLE_Y-1, PADDLE_Y)) { u8g.drawHLine(bdat.paddle_x, PADDLE_Y, PADDLE_W); #if PADDLE_H > 1 u8g.drawHLine(bdat.paddle_x, PADDLE_Y-1, PADDLE_W); #if PADDLE_H > 2 u8g.drawHLine(bdat.paddle_x, PADDLE_Y-2, PADDLE_W); #endif #endif } // Draw ball while game is running if (game_state) { const uint8_t by = FTOB(bdat.bally); if (PAGE_CONTAINS(by, by+1)) u8g.drawFrame(FTOB(bdat.ballx), by, 2, 2); } // Or draw GAME OVER else draw_game_over(); if (PAGE_UNDER(MENU_FONT_ASCENT)) { // Score Digits //const uint8_t sx = (LCD_PIXEL_WIDTH - (score >= 10 ? score >= 100 ? score >= 1000 ? 4 : 3 : 2 : 1) * MENU_FONT_WIDTH) / 2; constexpr uint8_t sx = 0; lcd_put_int(sx, MENU_FONT_ASCENT - 1, score); // Balls Left lcd_moveto(LCD_PIXEL_WIDTH - MENU_FONT_WIDTH * 3, MENU_FONT_ASCENT - 1); PGM_P const ohs = PSTR("ooo\0\0"); lcd_put_u8str_P(ohs + 3 - bdat.balls_left); } // A click always exits this game if (ui.use_click()) exit_game(); } #define SCREEN_M ((LCD_PIXEL_WIDTH) / 2) void BrickoutGame::enter_game() { init_game(2, game_screen); // 2 = reset bricks on paddle hit constexpr uint8_t paddle_start = SCREEN_M - (PADDLE_W) / 2; bdat.paddle_x = paddle_start; bdat.balls_left = 3; reset_bricks(0x0000); reset_ball(); ui.encoderPosition = paddle_start / (PADDLE_VEL); } #endif // MARLIN_BRICKOUT
412
0.973903
1
0.973903
game-dev
MEDIA
0.638851
game-dev,embedded-firmware
0.985145
1
0.985145
magefree/mage
1,156
Mage.Sets/src/mage/cards/m/MeganticSliver.java
package mage.cards.m; import mage.MageInt; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.continuous.BoostControlledEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.filter.StaticFilters; import java.util.UUID; /** * @author LevelX2 */ public final class MeganticSliver extends CardImpl { public MeganticSliver(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{5}{G}"); this.subtype.add(SubType.SLIVER); this.power = new MageInt(3); this.toughness = new MageInt(3); // Sliver creatures you control get +3/+3. this.addAbility(new SimpleStaticAbility(new BoostControlledEffect( 3, 3, Duration.WhileOnBattlefield, StaticFilters.FILTER_PERMANENT_SLIVERS ))); } private MeganticSliver(final MeganticSliver card) { super(card); } @Override public MeganticSliver copy() { return new MeganticSliver(this); } }
412
0.933155
1
0.933155
game-dev
MEDIA
0.945296
game-dev
0.960741
1
0.960741
joschu/trajopt
2,096
ext/bullet/src/BulletCollision/Gimpact/btGImpactMassUtil.h
/*! \file btGImpactMassUtil.h \author Francisco Leon Najera */ /* 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_MASS_UTIL_H #define GIMPACT_MASS_UTIL_H #include "LinearMath/btTransform.h" SIMD_FORCE_INLINE btVector3 gim_inertia_add_transformed( const btVector3 & source_inertia, const btVector3 & added_inertia, const btTransform & transform) { btMatrix3x3 rotatedTensor = transform.getBasis().scaled(added_inertia) * transform.getBasis().transpose(); btScalar x2 = transform.getOrigin()[0]; x2*= x2; btScalar y2 = transform.getOrigin()[1]; y2*= y2; btScalar z2 = transform.getOrigin()[2]; z2*= z2; btScalar ix = rotatedTensor[0][0]*(y2+z2); btScalar iy = rotatedTensor[1][1]*(x2+z2); btScalar iz = rotatedTensor[2][2]*(x2+y2); return btVector3(source_inertia[0]+ix,source_inertia[1]+iy,source_inertia[2] + iz); } SIMD_FORCE_INLINE btVector3 gim_get_point_inertia(const btVector3 & point, btScalar mass) { btScalar x2 = point[0]*point[0]; btScalar y2 = point[1]*point[1]; btScalar z2 = point[2]*point[2]; return btVector3(mass*(y2+z2),mass*(x2+z2),mass*(x2+y2)); } #endif //GIMPACT_MESH_SHAPE_H
412
0.860343
1
0.860343
game-dev
MEDIA
0.963988
game-dev
0.947894
1
0.947894
MeteorClientPlus/MeteorPlus
1,328
src/main/java/nekiplay/meteorplus/features/modules/movement/noslow/modes/NCPStrict.java
package nekiplay.meteorplus.features.modules.movement.noslow.modes; import nekiplay.main.events.PlayerUseMultiplierEvent; import nekiplay.meteorplus.features.modules.movement.noslow.NoSlowMode; import nekiplay.meteorplus.features.modules.movement.noslow.NoSlowModes; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; import net.minecraft.util.math.Direction; public class NCPStrict extends NoSlowMode { public NCPStrict() { super(NoSlowModes.NCP_Strict); } @Override public void onUse(PlayerUseMultiplierEvent event) { if (mc.player.isSneaking()) { event.setForward(settings.sneakForward.get().floatValue()); event.setSideways(settings.sneakSideways.get().floatValue()); } else if (mc.player.isUsingItem()) { event.setForward(settings.usingForward.get().floatValue()); event.setSideways(settings.usingSideways.get().floatValue()); } else { event.setForward(settings.otherForward.get().floatValue()); event.setSideways(settings.otherSideways.get().floatValue()); } if (mc.player.isUsingItem()) { ClientPlayNetworkHandler network = mc.getNetworkHandler(); network.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, mc.player.getBlockPos(), Direction.DOWN)); } } }
412
0.873585
1
0.873585
game-dev
MEDIA
0.963207
game-dev
0.91379
1
0.91379
henkelmax/audio-player
14,657
src/main/java/de/maxhenkel/audioplayer/audioloader/AudioData.java
package de.maxhenkel.audioplayer.audioloader; import com.google.gson.*; import de.maxhenkel.audioplayer.AudioPlayerMod; import de.maxhenkel.audioplayer.audioplayback.PlayerType; import de.maxhenkel.audioplayer.api.AudioPlayerModule; import de.maxhenkel.audioplayer.api.data.AudioDataModule; import de.maxhenkel.audioplayer.api.data.ModuleKey; import de.maxhenkel.audioplayer.api.events.AudioEvents; import de.maxhenkel.audioplayer.api.events.ItemEvents; import de.maxhenkel.audioplayer.apiimpl.AudioPlayerApiImpl; import de.maxhenkel.audioplayer.apiimpl.events.ApplyEventImpl; import de.maxhenkel.audioplayer.apiimpl.events.ClearEventImpl; import de.maxhenkel.audioplayer.apiimpl.events.GetSoundIdEventImpl; import de.maxhenkel.audioplayer.utils.ComponentUtils; import de.maxhenkel.audioplayer.utils.upgrade.ItemUpgrader; import de.maxhenkel.configbuilder.entry.ConfigEntry; import net.minecraft.ChatFormatting; import net.minecraft.core.Holder; import net.minecraft.core.component.DataComponentType; import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.world.item.*; import net.minecraft.world.item.component.*; import net.minecraft.world.level.block.SkullBlock; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.storage.ValueInput; import net.minecraft.world.level.storage.ValueOutput; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class AudioData implements de.maxhenkel.audioplayer.api.data.AudioData { public static final String AUDIOPLAYER_CUSTOM_DATA = "audioplayer"; public static final String DEFAULT_HEAD_LORE = "Has custom audio"; public static final Gson GSON = new GsonBuilder().create(); protected Map<ModuleKey<? extends AudioDataModule>, AudioDataModule> modules; protected Map<ResourceLocation, JsonObject> unknownModules; protected AudioData() { this.modules = new ConcurrentHashMap<>(); this.unknownModules = new ConcurrentHashMap<>(); } @Nullable private static AudioData fromJson(JsonObject rawData) { AudioData data = new AudioData(); for (Map.Entry<String, JsonElement> entry : rawData.entrySet()) { ResourceLocation resourceLocation = ResourceLocation.tryParse(entry.getKey()); if (resourceLocation == null) { AudioPlayerMod.LOGGER.warn("Invalid module key: {}", entry.getKey()); continue; } JsonElement jsonElement = entry.getValue(); if (!jsonElement.isJsonObject()) { AudioPlayerMod.LOGGER.warn("Invalid content for module: {}", entry.getKey()); continue; } JsonObject jsonObject = jsonElement.getAsJsonObject(); ModuleKey<? extends AudioDataModule> moduleKey = AudioPlayerApiImpl.INSTANCE.getModuleType(resourceLocation); if (moduleKey == null) { data.unknownModules.put(resourceLocation, jsonObject); AudioPlayerMod.LOGGER.debug("Unknown module: {}", resourceLocation); } else { AudioDataModule module = moduleKey.create(); try { module.load(jsonObject); data.modules.put(moduleKey, module); } catch (Exception e) { data.unknownModules.put(resourceLocation, jsonObject); AudioPlayerMod.LOGGER.error("Failed to load module {}", resourceLocation, e); } } } if (!data.modules.containsKey(AudioPlayerModule.KEY)) { AudioPlayerMod.LOGGER.error("Missing audio player module"); return null; } return data; } @Nullable public static AudioData of(ItemStack item) { if (ItemUpgrader.upgradeItem(item)) { AudioPlayerMod.LOGGER.info("Upgraded audio player data of item {}", item.getHoverName().getString()); } CustomData customData = item.get(DataComponents.CUSTOM_DATA); if (customData == null) { return null; } return of(customData.copyTag().getStringOr(AUDIOPLAYER_CUSTOM_DATA, null)); } @Nullable public static AudioData of(ValueInput valueInput) { AudioData upgradeData = ItemUpgrader.upgradeBlockEntity(valueInput); if (upgradeData != null) { AudioPlayerMod.LOGGER.info("Upgraded audio player data {}", upgradeData.getActualSoundId()); return upgradeData; } return of(valueInput.getStringOr(AUDIOPLAYER_CUSTOM_DATA, null)); } @Nullable public static AudioData of(@Nullable String data) { if (data == null) { return null; } try { JsonElement jsonElement = JsonParser.parseString(data); if (!jsonElement.isJsonObject()) { AudioPlayerMod.LOGGER.error("Failed to parse item data - element is not a json object"); return null; } return AudioData.fromJson(jsonElement.getAsJsonObject()); } catch (JsonSyntaxException e) { AudioPlayerMod.LOGGER.error("Failed to parse item data", e); return null; } } public static AudioData withSoundAndRange(UUID soundId, @Nullable Float range) { AudioData audioData = new AudioData(); audioData.modules.put(AudioPlayerModule.KEY, new AudioPlayerModule(soundId, range)); return audioData; } @Override public <T extends AudioDataModule> Optional<T> getModule(ModuleKey<T> id) { AudioDataModule module = modules.get(id); return Optional.ofNullable((T) module); } @Override public <T extends AudioDataModule> void setModule(ModuleKey<T> moduleKey, T module) { if (module == null) { throw new IllegalArgumentException("Module cannot be null"); } modules.put(moduleKey, module); } @Nullable @Override public <T extends AudioDataModule> T removeModule(ModuleKey<T> moduleKey) { if (moduleKey == null) { return null; } if (moduleKey.equals(AudioPlayerModule.KEY)) { throw new IllegalArgumentException("Can't remove base audioplayer module"); } return (T) modules.remove(moduleKey); } @Nullable public UUID getSoundIdToPlay() { UUID soundId = getModule(AudioPlayerModule.KEY).map(AudioPlayerModule::getSoundId).orElse(null); GetSoundIdEventImpl event = new GetSoundIdEventImpl(this, soundId); AudioEvents.GET_SOUND_ID.invoker().accept(event); return event.getSoundId(); } @Nullable public UUID getActualSoundId() { return getModule(AudioPlayerModule.KEY).map(AudioPlayerModule::getSoundId).orElse(null); } @Override public UUID getSoundId() { return getModule(AudioPlayerModule.KEY).map(AudioPlayerModule::getSoundId).orElseThrow(); } @Nullable @Override public Float getRange() { return getModule(AudioPlayerModule.KEY).map(AudioPlayerModule::getRange).orElse(null); } public Optional<Float> getOptionalRange() { return getModule(AudioPlayerModule.KEY).flatMap(m -> Optional.ofNullable(m.getRange())); } public float getRange(PlayerType playerType) { return getRangeOrDefault(playerType.getDefaultRange(), playerType.getMaxRange()); } public float getRangeOrDefault(ConfigEntry<Float> defaultRange, ConfigEntry<Float> maxRange) { float range = getOptionalRange().orElseGet(defaultRange::get); if (range > maxRange.get()) { return maxRange.get(); } else { return range; } } private JsonObject toJson() { JsonObject rawData = new JsonObject(); for (Map.Entry<ResourceLocation, JsonObject> entry : unknownModules.entrySet()) { rawData.add(entry.toString(), entry.getValue()); } for (Map.Entry<ModuleKey<? extends AudioDataModule>, AudioDataModule> entry : modules.entrySet()) { AudioDataModule module = entry.getValue(); JsonObject jsonData = new JsonObject(); try { module.save(jsonData); rawData.add(entry.getKey().getId().toString(), jsonData); } catch (Exception e) { AudioPlayerMod.LOGGER.error("Failed to save module {}", entry.getKey().getId(), e); } } return rawData; } public void saveToNbt(CompoundTag tag) { tag.putString(AUDIOPLAYER_CUSTOM_DATA, GSON.toJson(toJson())); } public void saveToValueOutput(ValueOutput valueOutput) { valueOutput.putString(AUDIOPLAYER_CUSTOM_DATA, GSON.toJson(toJson())); } public void saveToItemIgnoreLore(ItemStack stack) { saveToItem(stack, null, false); } @Override public void saveToItem(ItemStack stack) { saveToItem(stack, (Component) null); } public void saveToItem(ItemStack stack, @Nullable String loreString) { saveToItem(stack, loreString == null ? null : Component.literal(loreString), true); } @Override public void saveToItem(ItemStack stack, @Nullable Component lore) { saveToItem(stack, lore, true); } public void saveToItem(ItemStack stack, @Nullable Component lore, boolean applyLore) { CustomData customData = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY); CompoundTag tag = customData.copyTag(); saveToNbt(tag); stack.set(DataComponents.CUSTOM_DATA, CustomData.of(tag)); if (stack.has(DataComponents.INSTRUMENT)) { stack.set(DataComponents.INSTRUMENT, ComponentUtils.EMPTY_INSTRUMENT); } if (stack.has(DataComponents.JUKEBOX_PLAYABLE)) { stack.set(DataComponents.JUKEBOX_PLAYABLE, ComponentUtils.CUSTOM_JUKEBOX_PLAYABLE); } ItemLore l = null; if (stack.getItem() instanceof BlockItem blockItem && blockItem.getBlock() instanceof SkullBlock) { TypedEntityData<? extends BlockEntityType<?>> blockEntityData = stack.getOrDefault(DataComponents.BLOCK_ENTITY_DATA, TypedEntityData.of(BlockEntityType.SKULL, new CompoundTag())); CompoundTag blockEntityTag = blockEntityData.copyTagWithoutId(); saveToNbt(blockEntityTag); stack.set(DataComponents.BLOCK_ENTITY_DATA, TypedEntityData.of(BlockEntityType.SKULL, blockEntityTag)); if (lore == null) { l = new ItemLore(Collections.singletonList(Component.literal(DEFAULT_HEAD_LORE).withStyle(style -> style.withItalic(false)).withStyle(ChatFormatting.GRAY))); } } if (lore != null) { l = new ItemLore(Collections.singletonList(lore.copy().withStyle(style -> style.withItalic(false)).withStyle(ChatFormatting.GRAY))); } if (applyLore) { if (l != null) { stack.set(DataComponents.LORE, l); } else { stack.remove(DataComponents.LORE); } } TooltipDisplay tooltipDisplay = stack.getOrDefault(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.DEFAULT); LinkedHashSet<DataComponentType<?>> hiddenComponents = new LinkedHashSet<>(tooltipDisplay.hiddenComponents()); hiddenComponents.add(DataComponents.JUKEBOX_PLAYABLE); hiddenComponents.add(DataComponents.INSTRUMENT); stack.set(DataComponents.TOOLTIP_DISPLAY, new TooltipDisplay(tooltipDisplay.hideTooltip(), hiddenComponents)); ItemEvents.APPLY.invoker().accept(new ApplyEventImpl(this, stack)); } public static boolean clearItem(MinecraftServer server, ItemStack stack) { AudioData audioData = AudioData.of(stack); if (audioData == null) { return false; } CustomData customData = stack.get(DataComponents.CUSTOM_DATA); if (customData == null) { return false; } CompoundTag tag = customData.copyTag(); if (!tag.contains(AUDIOPLAYER_CUSTOM_DATA)) { return false; } tag.remove(AUDIOPLAYER_CUSTOM_DATA); stack.set(DataComponents.CUSTOM_DATA, CustomData.of(tag)); if (stack.getItem() instanceof BlockItem) { TypedEntityData<BlockEntityType<?>> blockEntityData = stack.get(DataComponents.BLOCK_ENTITY_DATA); if (blockEntityData != null) { CompoundTag blockEntityTag = blockEntityData.copyTagWithoutId(); blockEntityTag.remove(AUDIOPLAYER_CUSTOM_DATA); stack.set(DataComponents.BLOCK_ENTITY_DATA, TypedEntityData.of(blockEntityData.type(), blockEntityTag)); } } revertMinecraftData(server, stack); ItemEvents.CLEAR.invoker().accept(new ClearEventImpl(audioData, stack)); return true; } private static void revertMinecraftData(MinecraftServer server, ItemStack stack) { if (stack.has(DataComponents.INSTRUMENT)) { Optional<Holder.Reference<Instrument>> holder = server.registryAccess().lookupOrThrow(Registries.INSTRUMENT).get(Instruments.PONDER_GOAT_HORN); holder.ifPresent(instrumentReference -> stack.set(DataComponents.INSTRUMENT, new InstrumentComponent(instrumentReference))); } if (stack.has(DataComponents.JUKEBOX_PLAYABLE)) { JukeboxPlayable jukeboxPlayable = stack.getItem().components().get(DataComponents.JUKEBOX_PLAYABLE); if (jukeboxPlayable != null) { stack.set(DataComponents.JUKEBOX_PLAYABLE, jukeboxPlayable); } else { stack.remove(DataComponents.JUKEBOX_PLAYABLE); } } TooltipDisplay tooltipDisplay = stack.get(DataComponents.TOOLTIP_DISPLAY); if (tooltipDisplay != null) { LinkedHashSet<DataComponentType<?>> hiddenComponents = new LinkedHashSet<>(tooltipDisplay.hiddenComponents()); hiddenComponents.remove(DataComponents.JUKEBOX_PLAYABLE); hiddenComponents.remove(DataComponents.INSTRUMENT); stack.set(DataComponents.TOOLTIP_DISPLAY, new TooltipDisplay(tooltipDisplay.hideTooltip(), hiddenComponents)); } if (stack.has(DataComponents.LORE)) { stack.remove(DataComponents.LORE); } } }
412
0.943517
1
0.943517
game-dev
MEDIA
0.455045
game-dev,audio-video-media
0.941166
1
0.941166
SlimeKnights/TinkersConstruct
4,453
src/main/java/slimeknights/tconstruct/library/recipe/modifiers/adding/IncrementalModifierRecipeBuilder.java
package slimeknights.tconstruct.library.recipe.modifiers.adding; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; import slimeknights.mantle.recipe.helper.ItemOutput; import slimeknights.tconstruct.library.modifiers.ModifierEntry; import slimeknights.tconstruct.library.modifiers.ModifierId; import slimeknights.tconstruct.library.modifiers.util.LazyModifier; import java.util.function.Consumer; /** Recipe that supports not just adding multiple of an item, but also adding a partial amount */ @SuppressWarnings({"unused", "UnusedReturnValue"}) public class IncrementalModifierRecipeBuilder extends AbstractModifierRecipeBuilder<IncrementalModifierRecipeBuilder> { private Ingredient input = Ingredient.EMPTY; private int amountPerItem; private int neededPerLevel; private ItemOutput leftover = ItemOutput.EMPTY; protected IncrementalModifierRecipeBuilder(ModifierId result) { super(result); } /** * Creates a new recipe for 1 level of a modifier * @param modifier Modifier * @return Recipe for 1 level of the modifier */ public static IncrementalModifierRecipeBuilder modifier(ModifierId modifier) { return new IncrementalModifierRecipeBuilder(modifier); } /** * Creates a new recipe for 1 level of a modifier * @param modifier Modifier * @return Recipe for 1 level of the modifier */ public static IncrementalModifierRecipeBuilder modifier(LazyModifier modifier) { return modifier(modifier.getId()); } /* Inputs */ /** * Adds an input to the recipe * @param input Input * @param amountPerItem Amount each item matches * @param neededPerLevel Total number needed for this modifier * @return Builder instance */ public IncrementalModifierRecipeBuilder setInput(Ingredient input, int amountPerItem, int neededPerLevel) { if (amountPerItem < 1) { throw new IllegalArgumentException("Amount per item must be at least 1"); } if (neededPerLevel <= amountPerItem) { throw new IllegalArgumentException("Needed per level must be greater than amount per item"); } this.input = input; this.amountPerItem = amountPerItem; this.neededPerLevel = neededPerLevel; return this; } /** * Adds an input to the recipe * @param item Item input * @param amountPerItem Amount each item matches * @param neededPerLevel Total number needed for this modifier * @return Builder instance */ public IncrementalModifierRecipeBuilder setInput(ItemLike item, int amountPerItem, int neededPerLevel) { return setInput(Ingredient.of(item), amountPerItem, neededPerLevel); } /** * Adds an input to the recipe * @param tag Tag input * @param amountPerItem Amount each item matches * @param neededPerLevel Total number needed for this modifier * @return Builder instance */ public IncrementalModifierRecipeBuilder setInput(TagKey<Item> tag, int amountPerItem, int neededPerLevel) { return setInput(Ingredient.of(tag), amountPerItem, neededPerLevel); } /* Leftover */ /** Sets the leftover to the given output */ public IncrementalModifierRecipeBuilder setLeftover(ItemOutput leftover) { this.leftover = leftover; return this; } /** Sets the leftover to the given stack */ public IncrementalModifierRecipeBuilder setLeftover(ItemStack stack) { return setLeftover(ItemOutput.fromStack(stack)); } /** Sets the leftover to the given item */ public IncrementalModifierRecipeBuilder setLeftover(ItemLike item) { return setLeftover(ItemOutput.fromItem(item)); } /* Building */ @Override public void save(Consumer<FinishedRecipe> consumer, ResourceLocation id) { if (input == Ingredient.EMPTY) { throw new IllegalStateException("Must set input"); } ResourceLocation advancementId = buildOptionalAdvancement(id, "modifiers"); consumer.accept(new LoadableFinishedRecipe<>(new IncrementalModifierRecipe(id, input, amountPerItem, neededPerLevel, tools, maxToolSize, result, ModifierEntry.VALID_LEVEL.range(minLevel, maxLevel), slots, leftover, allowCrystal, checkTraitLevel), IncrementalModifierRecipe.LOADER, advancementId)); } }
412
0.877655
1
0.877655
game-dev
MEDIA
0.969113
game-dev
0.941639
1
0.941639
Mauler125/r5sdk
2,730
src/public/vgui/ienginevgui.h
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $Workfile: $ // $Date: $ // $NoKeywords: $ //===========================================================================// #if !defined( IENGINEVGUI_H ) #define IENGINEVGUI_H #ifdef _WIN32 #pragma once #endif //#include "interface.h" #include "vgui/vgui.h" // Forward declarations. namespace vgui { class Panel; }; // Todo: r5 seems to have the same number of enumerants, however the order is // still unconfirmed! enum VGuiPanel_t { PANEL_ROOT = 0, PANEL_GAMEUIDLL, // the console, game menu PANEL_CLIENTDLL, PANEL_TOOLS, PANEL_INGAMESCREENS, PANEL_GAMEDLL, PANEL_CLIENTDLL_TOOLS, PANEL_GAMEUIBACKGROUND, // the console background, shows under all other stuff in 3d engine view PANEL_TRANSITIONEFFECT, PANEL_STEAMOVERLAY, }; // In-game panels are cropped to the current engine viewport size enum PaintMode_t { PAINT_UIPANELS = (1 << 0), PAINT_INGAMEPANELS = (1 << 1), }; // Might not be complete: enum LevelLoadingProgress_e { PROGRESS_INVALID = -2, PROGRESS_DEFAULT = -1, PROGRESS_NONE, PROGRESS_CHANGELEVEL, PROGRESS_SPAWNSERVER, PROGRESS_LOADWORLDMODEL, PROGRESS_CRCMAP, PROGRESS_CRCCLIENTDLL, PROGRESS_CREATENETWORKSTRINGTABLES, PROGRESS_PRECACHEWORLD, PROGRESS_CLEARWORLD, PROGRESS_LEVELINIT, PROGRESS_PRECACHE, PROGRESS_ACTIVATESERVER, PROGRESS_BEGINCONNECT, PROGRESS_SIGNONCHALLENGE, PROGRESS_SIGNONCONNECT, PROGRESS_SIGNONCONNECTED, PROGRESS_PROCESSSERVERINFO, PROGRESS_PROCESSSTRINGTABLE, PROGRESS_SIGNONNEW, PROGRESS_SENDCLIENTINFO, PROGRESS_SENDSIGNONDATA, PROGRESS_SIGNONSPAWN, PROGRESS_CREATEENTITIES, PROGRESS_FULLYCONNECTED, PROGRESS_PRECACHELIGHTING, PROGRESS_READYTOPLAY, PROGRESS_HIGHESTITEM, // must be last item in list }; abstract_class IEngineVGui { public: virtual ~IEngineVGui(void) { } virtual vgui::VPANEL GetPanel(const VGuiPanel_t type) = 0; virtual vgui::VPANEL GetRootPanel(const VGuiPanel_t type) = 0; virtual void Unknown0() = 0; virtual bool Unknown1() = 0; // ReturnFalse virtual bool IsGameUIVisible() = 0; virtual void ActivateGameUI() = 0; virtual void HideGameUI() = 0; virtual void Simulate() = 0; virtual bool IsNotAllowedToHideGameUI() = 0; virtual void SetRuiFuncs(void* const ruiFuncsStruct) = 0; virtual void UpdateProgressBar(const LevelLoadingProgress_e progress) = 0; virtual void Unknown3() = 0; virtual void Unknown4() = 0; }; #define VENGINE_VGUI_VERSION "VEngineVGui001" //#if defined(_STATIC_LINKED) && defined(CLIENT_DLL) //namespace Client //{ // extern IEngineVGui* enginevgui; //} //#else //extern IEngineVGui* enginevgui; //#endif #endif // IENGINEVGUI_H
412
0.807954
1
0.807954
game-dev
MEDIA
0.561244
game-dev
0.807129
1
0.807129
ServUO/ServUO
2,051
Scripts/Items/Tools/MetallicLeatherDyeTub.cs
using System; namespace Server.Items { public class MetallicLeatherDyeTub : DyeTub, Engines.VeteranRewards.IRewardItem { private bool m_IsRewardItem; [Constructable] public MetallicLeatherDyeTub() { LootType = LootType.Blessed; } public MetallicLeatherDyeTub(Serial serial) : base(serial) { } public override bool AllowDyables { get { return false; } } public override bool AllowLeather { get { return true; } } public override int TargetMessage { get { return 1042416; } } // Select the leather item to dye. public override int FailMessage { get { return 1042418; } } // You can only dye leather with this tub. public override int LabelNumber { get { return 1153495; } } // Metallic Leather Dye Tub public override CustomHuePicker CustomHuePicker { get { return CustomHuePicker.MetallicDyeTub; } } [CommandProperty(AccessLevel.GameMaster)] public bool IsRewardItem { get { return m_IsRewardItem; } set { m_IsRewardItem = value; } } public override void OnDoubleClick(Mobile from) { if (m_IsRewardItem && !Engines.VeteranRewards.RewardSystem.CheckIsUsableBy(from, this, null)) return; base.OnDoubleClick(from); } public override void GetProperties(ObjectPropertyList list) { base.GetProperties(list); if (Core.ML && m_IsRewardItem) list.Add(1076221); // 5th Year Veteran Reward } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version writer.Write((bool)m_IsRewardItem); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); m_IsRewardItem = reader.ReadBool(); } } }
412
0.887198
1
0.887198
game-dev
MEDIA
0.841781
game-dev
0.830438
1
0.830438
hanabi1224/Programming-Language-Benchmarks
5,405
bench/algorithm/nbody/9.cs
namespace nbody { /* The Computer Language Benchmarks Game https://salsa.debian.org/benchmarksgame-team/benchmarksgame/ contributed by Isaac Gouy modified by Robert F. Tobler modified by Eric P. Nusbaum modified by hanabi1224 to use simd-powered Vector */ using System; using System.Numerics; public class NBody { public static void Main(String[] args) { var n = args.Length > 0 ? int.Parse(args[0]) : 1000; NBodySystem sys = new NBodySystem(); sys.OffsetMomentum(); Console.WriteLine("{0:f9}", sys.Energy()); for (var i = 0; i < n; i++) { sys.Advance(0.01); } Console.WriteLine("{0:f9}", sys.Energy()); } } public class Body { public Vector<double> Pos { get; set; } public Vector<double> Velocity { get; set; } public double Mass { get; } public Body(double x, double y, double z, double vx, double vy, double vz, double mass) { Pos = new Vector<double>(new[] { x, y, z, 0 }); Velocity = new Vector<double>(new[] { vx, vy, vz, 0 }); Mass = mass; } } public class NBodySystem { private Body[] _bodies; const byte bodyCount = 5; const double Pi = 3.141592653589793; const double Solarmass = 4 * Pi * Pi; const double Solarmass_inv = 1 / Solarmass; const double DaysPeryear = 365.24; public NBodySystem() { _bodies = new[] { // Sun new Body( x : 0, y : 0, z : 0, vx : 0, vy :0, vz : 0, mass:Solarmass ), // Jupiter new Body( x : 4.84143144246472090e+00, y : -1.16032004402742839e+00, z : -1.03622044471123109e-01, vx : 1.66007664274403694e-03*DaysPeryear, vy : 7.69901118419740425e-03*DaysPeryear, vz : -6.90460016972063023e-05*DaysPeryear, mass : 9.54791938424326609e-04*Solarmass ), // Saturn new Body( x : 8.34336671824457987e+00, y : 4.12479856412430479e+00, z : -4.03523417114321381e-01, vx : -2.76742510726862411e-03*DaysPeryear, vy : 4.99852801234917238e-03*DaysPeryear, vz : 2.30417297573763929e-05*DaysPeryear, mass : 2.85885980666130812e-04*Solarmass ), // Uranus new Body( x : 1.28943695621391310e+01, y : -1.51111514016986312e+01, z : -2.23307578892655734e-01, vx : 2.96460137564761618e-03*DaysPeryear, vy : 2.37847173959480950e-03*DaysPeryear, vz : -2.96589568540237556e-05*DaysPeryear, mass : 4.36624404335156298e-05*Solarmass ), // Neptune new Body( x : 1.53796971148509165e+01, y : -2.59193146099879641e+01, z : 1.79258772950371181e-01, vx : 2.68067772490389322e-03*DaysPeryear, vy : 1.62824170038242295e-03*DaysPeryear, vz : -9.51592254519715870e-05*DaysPeryear, mass : 5.15138902046611451e-05*Solarmass ), }; } public void OffsetMomentum() { var p = new Vector<double>(new[] { 0.0, 0.0, 0.0, 0.0 }); foreach (var b in _bodies) { p -= b.Velocity * b.Mass; } _bodies[0].Velocity = p * Solarmass_inv; } public void Advance(double dt) { for (var i = 0; i < bodyCount; i++) { var bi = _bodies[i]; var v = bi.Velocity; var pos = bi.Pos; var mi = bi.Mass; for (var j = i + 1; j < bodyCount; j++) { var bj = _bodies[j]; var dpos = pos - bj.Pos; double d2 = Vector.Dot(dpos, dpos); double mag = dt / (d2 * Math.Sqrt(d2)); dpos *= mag; v -= dpos * bj.Mass; bj.Velocity += dpos * mi; } bi.Velocity = v; bi.Pos += v * dt; } } public double Energy() { double e = 0.0; for (int i = 0; i < bodyCount; i++) { var bi = _bodies[i]; e += 0.5 * bi.Mass * Vector.Dot(bi.Velocity, bi.Velocity); for (int j = i + 1; j < bodyCount; j++) { var bj = _bodies[j]; var dpos = bi.Pos - bj.Pos; e -= (bi.Mass * bj.Mass) / Math.Sqrt(Vector.Dot(dpos, dpos)); } } return e; } } }
412
0.674683
1
0.674683
game-dev
MEDIA
0.665004
game-dev
0.637322
1
0.637322
TelepathicGrunt/Bumblezone
10,184
common/src/main/java/com/telepathicgrunt/the_bumblezone/entities/nonliving/ThrownStingerSpearEntity.java
package com.telepathicgrunt.the_bumblezone.entities.nonliving; import com.mojang.datafixers.util.Pair; import com.telepathicgrunt.the_bumblezone.enchantments.NeurotoxinsEnchantmentApplication; import com.telepathicgrunt.the_bumblezone.enchantments.PotentPoisonEnchantmentApplication; import com.telepathicgrunt.the_bumblezone.enchantments.datacomponents.ParalyzeMarker; import com.telepathicgrunt.the_bumblezone.items.StingerSpearItem; import com.telepathicgrunt.the_bumblezone.modinit.BzCriterias; import com.telepathicgrunt.the_bumblezone.modinit.BzEntities; import com.telepathicgrunt.the_bumblezone.modinit.BzItems; import com.telepathicgrunt.the_bumblezone.modinit.BzSounds; import com.telepathicgrunt.the_bumblezone.modinit.BzTags; import com.telepathicgrunt.the_bumblezone.modules.PlayerDataHandler; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvent; import net.minecraft.tags.EntityTypeTags; import net.minecraft.util.Mth; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.AbstractArrow; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.Level; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.Vec3; public class ThrownStingerSpearEntity extends AbstractArrow { private static final EntityDataAccessor<Byte> ID_LOYALTY = SynchedEntityData.defineId(ThrownStingerSpearEntity.class, EntityDataSerializers.BYTE); private static final EntityDataAccessor<Boolean> ID_FOIL = SynchedEntityData.defineId(ThrownStingerSpearEntity.class, EntityDataSerializers.BOOLEAN); private static final ItemStack DEFAULT_SPEAR_STACK = new ItemStack(BzItems.STINGER_SPEAR.get()); private boolean dealtDamage; public int clientSideReturnSpearTickCount; public ThrownStingerSpearEntity(EntityType<? extends ThrownStingerSpearEntity> entityType, Level level) { super(entityType, level); } public ThrownStingerSpearEntity(Level level, LivingEntity livingEntity, ItemStack ammo, ItemStack weaponItem) { super(BzEntities.THROWN_STINGER_SPEAR_ENTITY.get(), livingEntity, level, ammo, weaponItem); this.entityData.set(ID_LOYALTY, this.getLoyaltyFromItem(weaponItem)); this.entityData.set(ID_FOIL, weaponItem.hasFoil()); } @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { super.defineSynchedData(builder); builder.define(ID_LOYALTY, (byte)0); builder.define(ID_FOIL, false); } private byte getLoyaltyFromItem(ItemStack itemStack) { Level var3 = this.level(); return var3 instanceof ServerLevel serverLevel ? (byte) Mth.clamp(EnchantmentHelper.getTridentReturnToOwnerAcceleration(serverLevel, itemStack, this), 0, 127) : 0; } @Override public void tick() { if (this.inGroundTime > 4) { this.dealtDamage = true; } Entity entity = this.getOwner(); int loyalty = this.entityData.get(ID_LOYALTY); if (loyalty > 0 && (this.dealtDamage || this.isNoPhysics()) && entity != null) { if (!this.isAcceptibleReturnOwner()) { if (!this.level().isClientSide && this.pickup == AbstractArrow.Pickup.ALLOWED) { this.spawnAtLocation(this.getPickupItem(), 0.1F); } this.discard(); } else { this.setNoPhysics(true); Vec3 vec3 = entity.getEyePosition().subtract(this.position()); this.setPosRaw(this.getX(), this.getY() + vec3.y * 0.015D * (double)loyalty, this.getZ()); if (this.level().isClientSide) { this.yOld = this.getY(); } double returnSpeed = 0.05D * (double)loyalty; this.setDeltaMovement(this.getDeltaMovement().scale(0.95D).add(vec3.normalize().scale(returnSpeed))); if (this.clientSideReturnSpearTickCount == 0) { this.playSound(BzSounds.STINGER_SPEAR_RETURN.get(), 10.0F, 1.0F); } ++this.clientSideReturnSpearTickCount; } } super.tick(); } @Override protected void onHitEntity(EntityHitResult entityHitResult) { Entity entity = entityHitResult.getEntity(); Entity owner = this.getOwner(); Level level = this.level(); float damageAmount = StingerSpearItem.BASE_THROWN_DAMAGE; DamageSource damageSource = this.damageSources().trident(this, owner == null ? this : owner); if (level instanceof ServerLevel serverLevel) { damageAmount += EnchantmentHelper.modifyDamage(serverLevel, this.getWeaponItem(), entity, damageSource, damageAmount); } DamageSource damagesource = damageSources().trident(this, owner == null ? this : owner); dealtDamage = true; if (entity.hurt(damagesource, damageAmount)) { if (entity.getType() == EntityType.ENDERMAN) { return; } if (entity instanceof LivingEntity hitEntity) { if (level instanceof ServerLevel serverLevel) { EnchantmentHelper.doPostAttackEffectsWithItemSource(serverLevel, entity, damageSource, this.getWeaponItem()); } if (hitEntity instanceof LivingEntity livingEntity) { this.doKnockback(livingEntity, damageSource); this.doPostHurtEffects(livingEntity); } this.doPostHurtEffects(hitEntity); } } if(entity instanceof LivingEntity livingEntity && livingEntity.isDeadOrDying() && this.getOwner() instanceof ServerPlayer serverPlayer) { if (!serverPlayer.blockPosition().closerThan(this.blockPosition(), 50)) { BzCriterias.STINGER_SPEAR_LONG_RANGE_KILL_TRIGGER.get().trigger(serverPlayer); } if (entity.getType() == EntityType.WITHER && PlayerDataHandler.rootAdvancementDone(serverPlayer)) { BzCriterias.STINGER_SPEAR_KILLED_WITH_WITHER_TRIGGER.get().trigger(serverPlayer); } } this.setDeltaMovement(this.getDeltaMovement().multiply(-0.01D, -0.1D, -0.01D)); this.playSound(BzSounds.STINGER_SPEAR_HIT.get(), 1.0F, 1.0F); } @Override protected void doPostHurtEffects(LivingEntity victim) { if (!victim.getType().is(EntityTypeTags.UNDEAD)) { PotentPoisonEnchantmentApplication.doPostAttackBoostedPoison(this.getPickupItemStackOrigin(), victim); if (this.getOwner() instanceof ServerPlayer serverPlayer) { BzCriterias.STINGER_SPEAR_POISONING_TRIGGER.get().trigger(serverPlayer); } if (this.getOwner() instanceof LivingEntity ownerEntity && !victim.getType().is(BzTags.PARALYZED_IMMUNE)) { Pair<ParalyzeMarker, Integer> neurotoxin = NeurotoxinsEnchantmentApplication.getNeurotoxinEnchantLevel(this.getPickupItemStackOrigin()); if (neurotoxin != null && neurotoxin.getSecond() > 0) { this.getPickupItemStackOrigin().hurtAndBreak(neurotoxin.getFirst().durabilityDrainOnValidTargetHit(), ownerEntity, EquipmentSlot.MAINHAND); } } } } @Override protected float getWaterInertia() { return 0.75F; } private boolean isAcceptibleReturnOwner() { Entity entity = this.getOwner(); if (entity != null && entity.isAlive()) { return !(entity instanceof ServerPlayer) || !entity.isSpectator(); } else { return false; } } public boolean isFoil() { return this.entityData.get(ID_FOIL); } protected EntityHitResult findHitEntity(Vec3 vec3, Vec3 vec31) { return this.dealtDamage ? null : super.findHitEntity(vec3, vec31); } @Override protected boolean tryPickup(Player player) { return super.tryPickup(player) || this.isNoPhysics() && this.ownedBy(player) && player.getInventory().add(this.getPickupItem()); } @Override protected ItemStack getDefaultPickupItem() { return BzItems.STINGER_SPEAR.get().getDefaultInstance(); } @Override protected SoundEvent getDefaultHitGroundSoundEvent() { return BzSounds.STINGER_SPEAR_HIT_GROUND.get(); } @Override public void playerTouch(Player player) { if (this.ownedBy(player) || this.getOwner() == null) { super.playerTouch(player); } } @Override public void tickDespawn() { int loyalty = this.entityData.get(ID_LOYALTY); if (!this.isInvulnerable() && (this.pickup != Pickup.ALLOWED || loyalty <= 0)) { super.tickDespawn(); } } @Override public void readAdditionalSaveData(CompoundTag compoundTag) { super.readAdditionalSaveData(compoundTag); dealtDamage = compoundTag.getBoolean("DealtDamage"); this.entityData.set(ID_LOYALTY, this.getLoyaltyFromItem(this.getWeaponItem())); this.entityData.set(ID_FOIL, compoundTag.getBoolean("IsFoil")); } @Override public void addAdditionalSaveData(CompoundTag compoundTag) { super.addAdditionalSaveData(compoundTag); compoundTag.putBoolean("DealtDamage", dealtDamage); compoundTag.putBoolean("IsFoil", isFoil()); } @Override public boolean shouldRender(double x, double y, double z) { return true; } }
412
0.895824
1
0.895824
game-dev
MEDIA
0.97647
game-dev
0.950506
1
0.950506
antunnitraj/OfflineMinecraftLauncher
7,102
Character.cs
using System.Text; using System.Text.RegularExpressions; namespace OfflineMinecraftLauncher { internal class Character { // From 1.19.3 / 22w4x private static readonly string[] CharacterResourceNames1193 = [ "Alex_slim", "Ari_slim", "Efe_slim", "Kai_slim", "Makena_slim", "Noor_slim", "Steve_slim", "Sunny_slim", "Zuri_slim", "Alex_classic", "Ari_classic", "Efe_classic", "Kai_classic", "Makena_classic", "Noor_classic", "Steve_classic", "Sunny_classic", "Zuri_classic" ]; // From 1.8pre1 / 14wxx private static readonly string[] CharacterResourceNames18pre1 = [ "Steve_classic", "Alex_slim" ]; // Older private static readonly string[] CharacterResourceNamesOlder = [ "Steve_classic" ]; /* * Returns the character set for the given Minecraft version. * If the version is 1.19.3 or newer, it returns the full set of characters. * If the version is 1.8pre1 or newer but older than 1.19.3, it returns Steve and Alex. * Otherwise, it returns Steve only. */ internal static string[] GetCharacterSetForVersion(string minecraftVersion) { // Splitting the version for pre-release versions and snapshots // We will consider a pre-release as a full release for character selection minecraftVersion = minecraftVersion.Split("-")[0].Split(" ")[0]; if (string.IsNullOrWhiteSpace(minecraftVersion)) return CharacterResourceNamesOlder; // Remove suffixes like -pre1, -rc1, Pre-Release 2, etc. var versionPart = minecraftVersion.Split('-')[0].Split(' ')[0]; if (string.IsNullOrWhiteSpace(versionPart)) return CharacterResourceNamesOlder; if (Version.TryParse(versionPart, out var version)) { if (version >= new Version(1, 19, 3)) return CharacterResourceNames1193; else if (version >= new Version(1, 8)) return CharacterResourceNames18pre1; } else { // Try to match snapshot format, e.g. 22w45a var match = Regex.Match(minecraftVersion, @"^(?<yy>\d{2})w(?<ww>\d{2})[a-z]$", RegexOptions.IgnoreCase); if (match.Success) { int year = int.Parse(match.Groups["yy"].Value) + 2000; int week = int.Parse(match.Groups["ww"].Value); if (year > 2022 || (year == 2022 && week >= 45)) return CharacterResourceNames1193; else if ((year == 2022 && week < 45) || (year < 2022 && year >= 2014)) return CharacterResourceNames18pre1; } } // If the version is not recognized, return the oldest character names return CharacterResourceNamesOlder; } /* * Returns the character resource name based on the username and Minecraft version. */ internal static string GetCharacterResourceNameFromUsernameAndGameVersion(string username, string minecraftVersion) { // Current username UUID var playerUuid = GenerateUuidFromUsername(username); return GetCharacterResourceNameFromUuidAndGameVersion(playerUuid, minecraftVersion); } /* * Returns the character resource name based on the username uuid and Minecraft version. */ internal static string GetCharacterResourceNameFromUuidAndGameVersion(string playerUuid, string minecraftVersion) { // List of allowed characters for the game version var characterSet = GetCharacterSetForVersion(minecraftVersion); // If the array only contains one entry, return that entry directly if (characterSet.Length == 1) return characterSet[0]; // If empty minecraftVersion if (string.IsNullOrEmpty(minecraftVersion)) return characterSet[0]; // If empty playerUuid if (string.IsNullOrEmpty(playerUuid)) return characterSet[0]; // UUID3 string to bytes var hex = playerUuid.Replace("-", ""); var bytes = new byte[16]; for (int i = 0; i < 16; i++) bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); // hi and lo to big-endian ulong hi = ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) | ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | bytes[7]; ulong lo = ((ulong)bytes[8] << 56) | ((ulong)bytes[9] << 48) | ((ulong)bytes[10] << 40) | ((ulong)bytes[11] << 32) | ((ulong)bytes[12] << 24) | ((ulong)bytes[13] << 16) | ((ulong)bytes[14] << 8) | bytes[15]; long xor = (long)(hi ^ lo); int idx = (int)(xor ^ ((xor >> 32) & 0xffffffff)) % characterSet.Length; if (idx < 0) idx += characterSet.Length; return characterSet[idx]; } /* * Generates a UUID for an offline player based on the username. * The UUID is generated using the fixed namespace "OfflinePlayer:" and the username. */ internal static string GenerateUuidFromUsername(string username) { // Fallback name if (string.IsNullOrEmpty(username)) username = "Player"; // Minecraft offline player UUIDs are generated from the player name and // the fixed namespace "OfflinePlayer:". // The player name will define the UUID and thus the player Skin. const string ns = "OfflinePlayer:"; return GenerateUuid3(ns, username); } /* * Generates a UUID3 based on the namespace and name. */ internal static string GenerateUuid3(string ns, string name) { // Use ASCII encoding for both namespace and player name, no padding var nsBytes = Encoding.ASCII.GetBytes(ns); var nameBytes = Encoding.ASCII.GetBytes(name); var data = nsBytes.Concat(nameBytes).ToArray(); using var md5 = System.Security.Cryptography.MD5.Create(); var hash = md5.ComputeHash(data); hash[6] = (byte)((hash[6] & 0x0F) | 0x30); // Version 3 hash[8] = (byte)((hash[8] & 0x3F) | 0x80); // Variant RFC 4122 // Format as UUID string in big-endian order return $"{hash[0]:x2}{hash[1]:x2}{hash[2]:x2}{hash[3]:x2}-" + $"{hash[4]:x2}{hash[5]:x2}-" + $"{hash[6]:x2}{hash[7]:x2}-" + $"{hash[8]:x2}{hash[9]:x2}-" + $"{hash[10]:x2}{hash[11]:x2}{hash[12]:x2}{hash[13]:x2}{hash[14]:x2}{hash[15]:x2}"; } } }
412
0.545604
1
0.545604
game-dev
MEDIA
0.62199
game-dev
0.841873
1
0.841873
ehsan/ogre
3,748
RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramFactory.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreGLSLESProgramFactory.h" #include "OgreGLSLESLinkProgramManager.h" #include "OgreGLSLESProgramPipelineManager.h" #include "OgreGLSLESProgram.h" #include "OgreRoot.h" namespace Ogre { GLSLESLinkProgramManager* GLSLESProgramFactory::mLinkProgramManager = NULL; GLSLESProgramPipelineManager* GLSLESProgramFactory::mProgramPipelineManager = NULL; //----------------------------------------------------------------------- String GLSLESProgramFactory::sLanguageName = "glsles"; //----------------------------------------------------------------------- GLSLESProgramFactory::GLSLESProgramFactory(void) { if (mLinkProgramManager == NULL) { mLinkProgramManager = OGRE_NEW GLSLESLinkProgramManager(); } if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { if (mProgramPipelineManager == NULL) { mProgramPipelineManager = OGRE_NEW GLSLESProgramPipelineManager(); } } } //----------------------------------------------------------------------- GLSLESProgramFactory::~GLSLESProgramFactory(void) { if (mLinkProgramManager) { OGRE_DELETE mLinkProgramManager; mLinkProgramManager = NULL; } if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { if (mProgramPipelineManager) { OGRE_DELETE mProgramPipelineManager; mProgramPipelineManager = NULL; } } } //----------------------------------------------------------------------- const String& GLSLESProgramFactory::getLanguage(void) const { return sLanguageName; } //----------------------------------------------------------------------- HighLevelGpuProgram* GLSLESProgramFactory::create(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) { return OGRE_NEW GLSLESProgram(creator, name, handle, group, isManual, loader); } //----------------------------------------------------------------------- void GLSLESProgramFactory::destroy(HighLevelGpuProgram* prog) { OGRE_DELETE prog; } }
412
0.850105
1
0.850105
game-dev
MEDIA
0.619324
game-dev,graphics-rendering
0.81526
1
0.81526
ProjectEQ/projecteqquests
6,446
gunthak/Ofala_Olan.pl
#Ofala_Olan.pl #Started by Angelox, finished by Kilelen #Leviathan Eyes/Scryer's Trespass # items: 17889, 54025, 59015, 16506, 54006, 54008, 54007 sub EVENT_SAY { if ($text=~/Hail/i){ if ($class eq "Enchanter"){ quest::say("Salutations! It is nice to see one such as you in these parts; I do get lonely for some intelligent conversation around here once in awhile. The majority of the time however, I am much too preoccupied [researching]. There are so many interesting things to discover in a new area!"); } else{ quest::emote("glances up from the book she is reading and looks you over. 'If you are looking for the. . . Ahem. . . Library, it is the building to my right. Now if you'll excuse me I have some reading to do.."); } } if ($text=~/researching/i){ quest::say("Many things actually. The very land of this island has interesting peculiarities due to the foreign plant life and substances the pirates have introduced into the ecology. I have been working most specifically on deciphering what portions of the strange materials may hold magical properties that could be useful to our work as Enchanters. Why, just the other day I believe I was on the verge of a great breakthrough with some odd substances I had mixed together, unfortunately I was careless and did not seal the vial tightly enough. When I awoke the next morning the [specimen] had completely evaporated."); } if ($text=~/specimen/i){ quest::say("Among some of the substances I was experimenting with, I began to notice some peculiar attributes. I noticed some of the dark priests taking cuttings from certain mushrooms, and began experimenting with that first. I discovered that they could be boiled into a salve that had the most wondrous properties for the eyes! (sighs) It will take me ages to get the [necessary components] back to pick up where I left off on that particular spell, not to mention the research that I am compiling for my [brother] to assist with his specialties. I have enough material here to keep me swamped for ages, those spells will just have to wait!"); } if ($text=~/necessary components/i){ quest::say("Well, I believe that with two specific substances I can concoct a potion that will give certain effects for a specific amount of time. If I have these components I believe I have the understanding to capture the essence of them within a spell, so that the effects may be recalled at will. For this I would need the stalk of one of the local mushrooms, they secrete a fluid that is useful. I also need a mermaid scale from a mermaid here in the Gulf. Are you still willing to [assist] with this?"); } if ($text=~/assist/i){ quest::say("Take this vial with you then to contain the items that I have requested. Once you have them trapped inside, blend them together by sealing the bottle and shaking gently. Then bring it to me and I will see what I can do about finishing the task. Should the mixture prove true and I unlock the secret of the potion, I will share it with you for your efforts. Be very careful however, as always in dealing with items that we are not yet fully familiar with, the materials may prove dangerous!"); quest::summonitem(17889);#A Dusty Glass Vial } if ($text=~/brother/i){ quest::say("My brother is also an accomplished enchanter by the name of Stofo Olan. He has been hard at work in Erudin researching for his teacher Jeb Lumsed. He has a keen sense for the properties of stone and other such solid objects. For some time now he has been attempting to harness the power of stone for use in some form of mind control, that could be activated through a piece of jewelry. Entirely by accident, it seems that such a substance has been in use on this island for some time. It is very dangerous however, and as such most of my work has been based in theories tossed back and forth between he and I. Are you [interested] in this [strange rock] as well?"); } if ($text=~/strange rock/i){ quest::say("What a small world! I have skill with gem setting as many of our kind do, although I am afraid my specialties lie more with other types of elements and power. There have been stories of miners down in the Torgiran Mines losing their wits or becoming near zombie like in their actions. I have a hunch that whatever is doing this is being harvested there. Take good care down there, I fear that the miners themselves may not be too friendly. Travel into the mines and bring me two chunks of whatever the ore is that they are gathering, be sure it is of the type that glows brightly. Most likely the miners will have a few samples, but their masters probably have a few as well. Bring these to me with an enchanted bar of gold and I can fashion a test ring from it. Be careful!"); } } sub EVENT_ITEM { if(plugin::check_handin(\%itemcount, 54025 => 1)) {#Swirling Vial quest::emote("takes the vial gently from your hands and begins murmuring quietly. Thick incense smoke moves lazily through the air as she works, curling about and hanging onto your clothing. The strange liquid inside the vial begins to glow a deep red and seemingly moves of its own volition. Ofala quickly smears a bit of the substance about her eyes and looks up at you. 'We have solved it! I believe I can recall this again, let me get this down for you now before the spell wears. Use it well.' Withdrawing a fine quill from a pouch at her waist, she dips the tip into the swirling potion and scrawls out the words of a spell onto parchment."); quest::summonitem(59015); # Item: Spell: Leviathan Eyes quest::exp(1107392);#1% of level 45 xp } elsif(plugin::check_handin(\%itemcount, 16506 => 1, 54006 => 2)) {#Enchanted Gold Bar, 2 Gleaming Zraxthril Ores quest::emote("eyes you with a new measure of respect. 'Very well done! I did not think you would be successful in this. Let me harness this energy quickly then you must have Stofo take a look at it!' Being careful not to touch the gems too much with her bare hands, Ofala Olan deftly crafts a slim golden band, crossing strands of gold across the dimly pulsing stones to bind them in place and protect the wearer from harm. 'He still holes himself up in that dim room in Erudin. I don't know HOW he studies like that, but take it to him please! I am sure he will be most interested."); quest::summonitem(54008);#A Dimly Glowing Ring quest::summonitem(54007);#Note to Stofo } plugin::return_items(\%itemcount); }#Done
412
0.876595
1
0.876595
game-dev
MEDIA
0.852469
game-dev
0.711172
1
0.711172
hebohang/HEngine
2,999
Engine/Source/ThirdParty/SPIRV-Cross/reference/shaders-msl/tesc/complex-patch-out-types.tesc
#pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wmissing-braces" #include <metal_stdlib> #include <simd/simd.h> using namespace metal; template<typename T, size_t Num> struct spvUnsafeArray { T elements[Num ? Num : 1]; thread T& operator [] (size_t pos) thread { return elements[pos]; } constexpr const thread T& operator [] (size_t pos) const thread { return elements[pos]; } device T& operator [] (size_t pos) device { return elements[pos]; } constexpr const device T& operator [] (size_t pos) const device { return elements[pos]; } constexpr const constant T& operator [] (size_t pos) const constant { return elements[pos]; } threadgroup T& operator [] (size_t pos) threadgroup { return elements[pos]; } constexpr const threadgroup T& operator [] (size_t pos) const threadgroup { return elements[pos]; } }; struct Meep { float a; float b; }; struct Block { spvUnsafeArray<float, 2> a; float b; float2x2 m; Meep meep; spvUnsafeArray<Meep, 2> meeps; }; struct main0_out { float4 gl_Position; }; struct main0_patchOut { spvUnsafeArray<float, 2> a; float b; float2x2 m; Meep meep; spvUnsafeArray<Meep, 2> meeps; spvUnsafeArray<float, 2> B_a; float B_b; float2x2 B_m; Meep B_meep; spvUnsafeArray<Meep, 2> B_meeps; }; static inline __attribute__((always_inline)) void write_in_func(device main0_out* thread & gl_out, thread uint& gl_InvocationID, device spvUnsafeArray<float, 2>& a, device float& b, device float2x2& m, device Meep& meep, device spvUnsafeArray<Meep, 2>& meeps, device main0_patchOut& patchOut) { gl_out[gl_InvocationID].gl_Position = float4(1.0); a[0] = 1.0; a[1] = 2.0; b = 3.0; m = float2x2(float2(2.0, 0.0), float2(0.0, 2.0)); meep.a = 4.0; meep.b = 5.0; meeps[0].a = 6.0; meeps[0].b = 7.0; meeps[1].a = 8.0; meeps[1].b = 9.0; patchOut.B_a[0] = 1.0; patchOut.B_a[1] = 2.0; patchOut.B_b = 3.0; patchOut.B_m = float2x2(float2(4.0, 0.0), float2(0.0, 4.0)); patchOut.B_meep.a = 4.0; patchOut.B_meep.b = 5.0; patchOut.B_meeps[0].a = 6.0; patchOut.B_meeps[0].b = 7.0; patchOut.B_meeps[1].a = 8.0; patchOut.B_meeps[1].b = 9.0; } kernel void main0(uint gl_InvocationID [[thread_index_in_threadgroup]], uint gl_PrimitiveID [[threadgroup_position_in_grid]], device main0_out* spvOut [[buffer(28)]], constant uint* spvIndirectParams [[buffer(29)]], device main0_patchOut* spvPatchOut [[buffer(27)]], device MTLQuadTessellationFactorsHalf* spvTessLevel [[buffer(26)]]) { device main0_out* gl_out = &spvOut[gl_PrimitiveID * 4]; device main0_patchOut& patchOut = spvPatchOut[gl_PrimitiveID]; write_in_func(gl_out, gl_InvocationID, patchOut.a, patchOut.b, patchOut.m, patchOut.meep, patchOut.meeps, patchOut); }
412
0.752099
1
0.752099
game-dev
MEDIA
0.355638
game-dev
0.916693
1
0.916693
legacyclonk/LegacyClonk
3,533
src/C4InteractiveThread.cpp
/* * LegacyClonk * * Copyright (c) RedWolf Design * Copyright (c) 2017-2021, The LegacyClonk Team and contributors * * Distributed under the terms of the ISC license; see accompanying file * "COPYING" for details. * * "Clonk" is a registered trademark of Matthes Bender, used with permission. * See accompanying file "TRADEMARK" for details. * * To redistribute this file separately, substitute the full license texts * for the above references. */ #include "C4Include.h" #include "C4InteractiveThread.h" #include "C4Application.h" #include "C4Log.h" #include <C4Game.h> #include <cassert> // *** C4InteractiveThread C4InteractiveThread::C4InteractiveThread() { // Add head-item pFirstEvent = pLastEvent = new Event(); pFirstEvent->Type = Ev_None; pFirstEvent->Next = nullptr; // reset event handlers std::fill(pCallbacks, std::end(pCallbacks), nullptr); } C4InteractiveThread::~C4InteractiveThread() { CStdLock PushLock(&EventPushCSec), PopLock(&EventPopCSec); // Remove all items. This may leak data, if pData was allocated on the heap. while (PopEvent(nullptr, nullptr)); // Delete head-item delete pFirstEvent; pFirstEvent = pLastEvent = nullptr; } bool C4InteractiveThread::AddProc(StdSchedulerProc *pProc) { bool fFirst = !Scheduler.getProcCnt(); // Add the proc Scheduler.Add(pProc); // Not started yet? if (fFirst) if (!Scheduler.Start()) return false; return true; } void C4InteractiveThread::RemoveProc(StdSchedulerProc *pProc) { Scheduler.Remove(pProc); // Last proc to be removed? if (Scheduler.getProcCnt() == 0) { Scheduler.Stop(); } } bool C4InteractiveThread::PushEvent(C4InteractiveEventType eEvent, std::any data) { CStdLock PushLock(&EventPushCSec); if (!pLastEvent) return false; // create event Event *pEvent = new Event; pEvent->Type = eEvent; pEvent->Data = std::move(data); #ifndef NDEBUG pEvent->Time = timeGetTime(); #endif pEvent->Next = nullptr; // add item (at end) pLastEvent->Next = pEvent; pLastEvent = pEvent; PushLock.Clear(); #ifdef _WIN32 // post message to main thread try { Application.NetworkEvent.Set(); } catch (const std::runtime_error &) { LogFatalNTr("Network: could not post message to main thread!"); } return true; #else return Application.SignalNetworkEvent(); #endif } #ifndef NDEBUG double AvgNetEvDelay = 0; #endif bool C4InteractiveThread::PopEvent(C4InteractiveEventType *pEventType, std::any *data) // (by main thread) { CStdLock PopLock(&EventPopCSec); if (!pFirstEvent) return false; // get event Event *pEvent = pFirstEvent->Next; if (!pEvent) return false; // return if (pEventType) *pEventType = pEvent->Type; if (data) *data = std::move(pEvent->Data); #ifndef NDEBUG if (Game.IsRunning) AvgNetEvDelay += ((timeGetTime() - pEvent->Time) - AvgNetEvDelay) / 100; #endif // remove delete pFirstEvent; pFirstEvent = pEvent; pFirstEvent->Type = Ev_None; return true; } void C4InteractiveThread::ProcessEvents() // by main thread { C4InteractiveEventType eEventType; std::any eventData; while (PopEvent(&eEventType, &eventData)) switch (eEventType) { // Execute in main thread case Ev_ExecuteInMainThread: std::any_cast<const std::function<void()> &>(eventData)(); break; // Other events: check for a registered handler default: if (eEventType >= Ev_None && eEventType <= Ev_Last) if (pCallbacks[eEventType]) pCallbacks[eEventType]->OnThreadEvent(eEventType, eventData); // Note that memory might leak if the event wasn't processed.... } }
412
0.911384
1
0.911384
game-dev
MEDIA
0.390685
game-dev
0.888173
1
0.888173
EricDDK/billiards_cocos2d
3,093
Billiards/frameworks/cocos2d-x/external/bullet/BulletMultiThreaded/SpuContactManifoldCollisionAlgorithm.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.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. */ #include "SpuContactManifoldCollisionAlgorithm.h" #include "bullet/BulletCollision//CollisionDispatch/btCollisionDispatcher.h" #include "bullet/BulletCollision//CollisionDispatch/btCollisionObject.h" #include "bullet/BulletCollision//CollisionShapes/btCollisionShape.h" #include "bullet/BulletCollision//CollisionShapes/btPolyhedralConvexShape.h" void SpuContactManifoldCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { btAssert(0); } btScalar SpuContactManifoldCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) { btAssert(0); return 1.f; } #ifndef __SPU__ SpuContactManifoldCollisionAlgorithm::SpuContactManifoldCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObject* body0,const btCollisionObject* body1) :btCollisionAlgorithm(ci) #ifdef USE_SEPDISTANCE_UTIL ,m_sepDistance(body0->getCollisionShape()->getAngularMotionDisc(),body1->getCollisionShape()->getAngularMotionDisc()) #endif //USE_SEPDISTANCE_UTIL { m_manifoldPtr = m_dispatcher->getNewManifold(body0,body1); m_shapeType0 = body0->getCollisionShape()->getShapeType(); m_shapeType1 = body1->getCollisionShape()->getShapeType(); m_collisionMargin0 = body0->getCollisionShape()->getMargin(); m_collisionMargin1 = body1->getCollisionShape()->getMargin(); m_collisionObject0 = body0; m_collisionObject1 = body1; if (body0->getCollisionShape()->isPolyhedral()) { btPolyhedralConvexShape* convex0 = (btPolyhedralConvexShape*)body0->getCollisionShape(); m_shapeDimensions0 = convex0->getImplicitShapeDimensions(); } if (body1->getCollisionShape()->isPolyhedral()) { btPolyhedralConvexShape* convex1 = (btPolyhedralConvexShape*)body1->getCollisionShape(); m_shapeDimensions1 = convex1->getImplicitShapeDimensions(); } } #endif //__SPU__ SpuContactManifoldCollisionAlgorithm::~SpuContactManifoldCollisionAlgorithm() { if (m_manifoldPtr) m_dispatcher->releaseManifold(m_manifoldPtr); }
412
0.918407
1
0.918407
game-dev
MEDIA
0.994129
game-dev
0.848593
1
0.848593
elBukkit/MagicPlugin
1,104
CompatibilityLib/v1_21_5/src/main/java/com/elmakers/mine/bukkit/utility/platform/v1_21_5/goal/TriggerGoal.java
package com.elmakers.mine.bukkit.utility.platform.v1_21_5.goal; import java.util.Collection; import org.bukkit.ChatColor; import com.elmakers.mine.bukkit.api.magic.Mage; import net.minecraft.world.entity.ai.goal.Goal; public class TriggerGoal extends MagicGoal { private final Mage mage; private final String trigger; private final int interval; private long lastTrigger; public TriggerGoal(Mage mage, Collection<Goal> goals, boolean interruptable, String trigger, int interval) { super(goals, interruptable); this.mage = mage; this.interval = interval * 50; this.lastTrigger = System.currentTimeMillis(); this.trigger = trigger; } @Override public void tick() { super.tick(); long now = System.currentTimeMillis(); if (now > lastTrigger + interval) { lastTrigger = now; mage.trigger(trigger); } } @Override protected String getDescription() { return "Trigger" + ChatColor.GRAY + "(" + ChatColor.DARK_AQUA + trigger + ChatColor.GRAY + ")"; } }
412
0.862792
1
0.862792
game-dev
MEDIA
0.954493
game-dev
0.919617
1
0.919617
openairlinetycoon/OpenATDeluxe
5,696
src/Localization/LocalizationManager.cs
using Godot; using System.Linq; using System; using System.IO; using System.Collections.Generic; using File = System.IO.File; using System.Text; public class LocalizationManager { public static LocalizationManager instance; public List<LocalizationStack> stacks; public static void LoadLocalizationData() { new LocalizationManager(); } public LocalizationManager() { instance = this; stacks = new List<LocalizationStack>(); string[] locFiles = System.IO.Directory.GetFiles(GFXLibrary.pathToAirlineTycoonD + "/misc/", "*.res"); List<LocalizationFile> files = new List<LocalizationFile>(); foreach (string file in locFiles) { if (System.IO.Path.GetFileName(file) == "register.res") continue; stacks.AddRange(new LocalizationFile(file).locData); //File.WriteAllText(file + "s", files.Last().GetData()); } AddStacksToTranslationServer(); } public void AddStacksToTranslationServer() { List<Translation> translations = new List<Translation>(); foreach (LocalizedString.LanguageCode lang in (LocalizedString.LanguageCode[])Enum.GetValues(typeof(LocalizedString.LanguageCode))) { translations.Add(new Translation() { Locale = lang.ToString() }); } List<Export> exports = new List<Export>(); foreach (LocalizationStack stack in stacks) { string translationName; foreach (var strPair in stack.strings) { translationName = $"{stack.name}>{strPair.Key}"; Export e = new Export(); exports.Add(e); for (int lang = 0; lang <= (int)LocalizedString.LanguageCode.de; lang++) { if (strPair.Value.strings.ContainsKey((LocalizedString.Language)lang)) { translations[lang].AddMessage(translationName, strPair.Value.strings[(LocalizedString.Language)lang]); e.SetData(translationName, strPair.Value.strings[(LocalizedString.Language)lang], lang); } else { GD.Print($"Translation {(LocalizedString.Language)lang} not found for {translationName}!"); } } } } // Use something like CsvHelper or write your own library. // using (var writer = new StreamWriter(ProjectSettings.GlobalizePath("res://localization.csv"))) // using (var csv = new CsvWriter(writer)) { // csv.WriteRecords(exports); // } foreach (Translation t in translations) { TranslationServer.AddTranslation(t); } } public class Export { private string _id; private string _de; //German private string _pt_BR; private string _en; private string _fr; private string _it; private string _nl; private string _pt; private string _es; public string id { get => _id; set => _id = value; } public string pt_BR { get => _pt_BR; set => _pt_BR = value; } public string en { get => _en; set => _en = value; } public string fr { get => _fr; set => _fr = value; } public string it { get => _it; set => _it = value; } public string nl { get => _nl; set => _nl = value; } public string pt { get => _pt; set => _pt = value; } public string es { get => _es; set => _es = value; } public string de { get => _de; set => _de = value; } public void SetData(string id, string data, int language) { this._id = id; switch (language) { case (0): _pt_BR = data; break; case (1): _en = data; break; case (2): _fr = data; break; case (3): _it = data; break; case (4): _nl = data; break; case (5): _pt = data; break; case (6): _es = data; break; case (7): _de = data; break; } } } class LocalizationFile : BaseFileDecoder { public LocalizationFile(string _filePath) : base(_filePath) { locData = new List<LocalizationStack>(); LocalizationStack currentStack = null; LocalizedString currentString = null; foreach (string lineMessy in fileData.Split('\n')) { //Order of "if"s is important! A ">" string can be in a ">>" string but not vice verca! string line = lineMessy.TrimEnd('\r'); if (line.BeginsWith("//")) //Skip comments continue; if (line.Length < 2) //Skip empty lines continue; if (line.BeginsWith(" x")) { //Missing translation currentStack.RemoveString(currentString.id); continue; } if (line.BeginsWith(">>")) { //New string! string idS = line.Substring(2); idS = idS.Split(' ', '/')[0]; int.TryParse(idS, out int id); bool overrideString = true; if (currentStack.strings.ContainsKey(id)) { if (!overrideString) { GD.Print($"Localized String already in collection. NOT overriding! id: {id} stack: {currentStack.name}"); continue; } else { GD.Print($"Localized String already in collection. Overriding now! id: {id} stack: {currentStack.name}"); currentStack.strings.Remove(id); } } currentString = new LocalizedString(id); currentStack.AddString(id, currentString); continue; } if (line.BeginsWith(">")) { //New stack! currentStack = new LocalizationStack(line.Substring(1)); locData.Add(currentStack); continue; } if (line.BeginsWith(" ")) { //New string entry! currentString.AddString(line); } } } public List<LocalizationStack> locData; } } public class LocalizationStack { public string name; public Dictionary<int, LocalizedString> strings; public LocalizationStack(string name) { this.name = name; strings = new Dictionary<int, LocalizedString>(); } public void AddString(int id, LocalizedString str) { strings.Add(id, str); } public void RemoveString(int id) { strings.Remove(id); } public LocalizationStack(string name, Dictionary<int, LocalizedString> strings) { this.name = name; this.strings = strings; } }
412
0.857925
1
0.857925
game-dev
MEDIA
0.365052
game-dev
0.914801
1
0.914801
baba-s/kogane-unity-lib
1,242
Scripts/Extensions/DictionaryExt.cs
using System.Collections; using System.Collections.Generic; using System.Linq; namespace KoganeUnityLib { /// <summary> /// Dictionary 型の拡張メソッドを管理するクラス /// </summary> public static class DictionaryExt { /// <summary> /// 指定したキーに関連付けられている値を取得します。キーが存在しない場合は既定値を返します /// </summary> public static TValue GetOrDefault<TKey, TValue>( this Dictionary<TKey, TValue> self, TKey key, TValue defaultValue = default( TValue ) ) { TValue value; return self.TryGetValue( key, out value ) ? value : defaultValue; } /// <summary> /// Hashtable に変換します /// </summary> public static Hashtable ToHashtable<TKey, TValue>( this Dictionary<TKey, TValue> self ) { var result = new Hashtable(); foreach ( var n in self ) { result[ n.Key ] = n.Value; } return result; } /// <summary> /// ランダムに値を返します /// </summary> public static TValue ElementAtRandom<TKey, TValue>( this Dictionary<TKey, TValue> self ) { return self.ElementAt( UnityEngine.Random.Range( 0, self.Count ) ).Value; } /// <summary> /// クリアします。null の場合は何も行いません /// </summary> public static void ClearIfNotNull<TKey, TValue>( this Dictionary<TKey, TValue> self ) { if ( self == null ) return; self.Clear(); } } }
412
0.884539
1
0.884539
game-dev
MEDIA
0.35899
game-dev
0.861104
1
0.861104
glob3mobile/g3m
1,163
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/QuadTree.java
package org.glob3.mobile.generated; public class QuadTree { private QuadTree_Node _root; private final int _maxElementsPerNode; private final int _maxDepth; public QuadTree(Sector sector) { _root = new QuadTree_Node(sector); _maxElementsPerNode = 1; _maxDepth = 12; } public QuadTree() { _root = new QuadTree_Node(Sector.FULL_SPHERE); _maxElementsPerNode = 1; _maxDepth = 12; } public void dispose() { if (_root != null) _root.dispose(); } public final boolean add(Sector sector, QuadTree_Content content) { return _root.add(sector, content, _maxElementsPerNode, _maxDepth); } public final boolean acceptVisitor(Sector sector, QuadTreeVisitor visitor) { final boolean aborted = _root.acceptVisitor(sector, visitor); visitor.endVisit(aborted); return aborted; } public final void clear() { Sector sector = _root._sector; if (_root != null) _root.dispose(); _root = new QuadTree_Node(sector); } public final boolean isEmpty() { return _root.isEmpty(); } public final Sector getSector() { return _root._sector; } }
412
0.778545
1
0.778545
game-dev
MEDIA
0.453891
game-dev
0.805583
1
0.805583
lambertjamesd/spellcraft
3,471
src/objects/collectable.c
#include "collectable.h" #include "../collision/collision_scene.h" #include "../collision/shapes/sphere.h" #include "../cutscene/cutscene_runner.h" #include "../cutscene/show_item.h" #include "../menu/dialog_box.h" #include "../player/inventory.h" #include "../render/render_scene.h" #include "../resource/material_cache.h" #include "../spell/spell.h" #include "../time/time.h" #include "../util/hash_map.h" #define COLLECTABLE_RADIUS 0.75f static struct dynamic_object_type collectable_collision = { .minkowsi_sum = sphere_minkowski_sum, .bounding_box = sphere_bounding_box, .data = { .sphere = { .radius = COLLECTABLE_RADIUS, } }, .bounce = 0.2f, .friction = 0.25f, }; static struct hash_map collectable_hash_map; struct collectable_information { char* mesh_filename; }; static struct collectable_information collectable_information[] = { [COLLECTABLE_TYPE_HEALTH] = { .mesh_filename = "rom:/meshes/objects/pickups/heart.tmesh", }, [COLLECTABLE_TYPE_SPELL_RUNE] = { .mesh_filename = "rom:/meshes/objects/pickups/scroll.tmesh", }, }; void collectable_assets_load() { hash_map_init(&collectable_hash_map, 8); } void collectable_init(struct collectable* collectable, struct collectable_definition* definition, entity_id id) { collectable->collectable_type = definition->collectable_type; collectable->collectable_sub_type = definition->collectable_sub_type; transformSaInit(&collectable->transform, &definition->position, &definition->rotation, 1.0f); dynamic_object_init( id, &collectable->dynamic_object, &collectable_collision, COLLISION_LAYER_TANGIBLE | COLLISION_LAYER_LIGHTING_TANGIBLE, &collectable->transform.position, 0 ); struct collectable_information* type = &collectable_information[definition->collectable_type]; collision_scene_add(&collectable->dynamic_object); renderable_single_axis_init(&collectable->renderable, &collectable->transform, type->mesh_filename); render_scene_add_renderable(&collectable->renderable, 0.2f); hash_map_set(&collectable_hash_map, collectable->dynamic_object.entity_id, collectable); } void collectable_collected(struct collectable* collectable) { collectable_destroy(collectable); if (collectable->collectable_type == COLLECTABLE_TYPE_HEALTH) { dialog_box_show( "You got a heart\n\n" "Now if I only had a brain", NULL, NULL, NULL ); } if (collectable->collectable_type == COLLECTABLE_TYPE_SPELL_RUNE) { struct cutscene_builder builder; cutscene_builder_init(&builder); inventory_unlock_item(collectable->collectable_sub_type); show_item_in_cutscene(&builder, collectable->collectable_sub_type); cutscene_runner_run( cutscene_builder_finish(&builder), cutscene_runner_free_on_finish(), NULL, collectable->dynamic_object.entity_id ); } } void collectable_destroy(struct collectable* collectable) { collision_scene_remove(&collectable->dynamic_object); render_scene_remove(&collectable->renderable); renderable_destroy(&collectable->renderable); hash_map_delete(&collectable_hash_map, collectable->dynamic_object.entity_id); } struct collectable* collectable_get(entity_id id) { return hash_map_get(&collectable_hash_map, id); }
412
0.846677
1
0.846677
game-dev
MEDIA
0.812977
game-dev
0.939094
1
0.939094
simulationcraft/simc
20,776
ActionPriorityLists/default/evoker_augmentation.simc
# This default action priority list is automatically created based on your character. # It is a attempt to provide you with a action list that is both simple and practicable, # while resulting in a meaningful and good simulation. It may not result in the absolutely highest possible dps. # Feel free to edit, adapt and improve it to your own needs. # SimulationCraft is always looking for updates and improvements to the default action lists. # Executed before combat begins. Accepts non-harmful actions only. actions.precombat=snapshot_stats actions.precombat+=/variable,name=spam_heal,default=0,op=reset actions.precombat+=/variable,name=minimum_opener_delay,op=reset,default=0 actions.precombat+=/variable,name=opener_delay,value=variable.minimum_opener_delay,if=!talent.interwoven_threads actions.precombat+=/variable,name=opener_delay,value=variable.minimum_opener_delay+variable.opener_delay,if=talent.interwoven_threads actions.precombat+=/variable,name=opener_cds_detected,op=reset,default=0 actions.precombat+=/variable,name=trinket_1_exclude,value=trinket.1.is.ruby_whelp_shell|trinket.1.is.whispering_incarnate_icon|trinket.1.is.ovinaxs_mercurial_egg|trinket.1.is.aberrant_spellforge actions.precombat+=/variable,name=trinket_2_exclude,value=trinket.2.is.ruby_whelp_shell|trinket.2.is.whispering_incarnate_icon|trinket.2.is.ovinaxs_mercurial_egg|trinket.2.is.aberrant_spellforge # Nymues is complicated, Manual Handle actions.precombat+=/variable,name=trinket_1_manual,value=trinket.1.is.nymues_unraveling_spindle|trinket.1.is.spymasters_web|trinket.1.is.treacherous_transmitter|trinket.1.is.house_of_cards actions.precombat+=/variable,name=trinket_2_manual,value=trinket.2.is.nymues_unraveling_spindle|trinket.2.is.spymasters_web|trinket.2.is.treacherous_transmitter|trinket.2.is.house_of_cards actions.precombat+=/variable,name=trinket_1_ogcd_cast,value=trinket.1.is.beacon_to_the_beyond actions.precombat+=/variable,name=trinket_2_ogcd_cast,value=trinket.2.is.beacon_to_the_beyond actions.precombat+=/variable,name=trinket_1_buffs,value=(trinket.1.has_use_buff|(trinket.1.has_buff.intellect|trinket.1.has_buff.mastery|trinket.1.has_buff.versatility|trinket.1.has_buff.haste|trinket.1.has_buff.crit)&!variable.trinket_1_exclude)&(!trinket.1.is.flarendos_pilot_light) actions.precombat+=/variable,name=trinket_2_buffs,value=(trinket.2.has_use_buff|(trinket.2.has_buff.intellect|trinket.2.has_buff.mastery|trinket.2.has_buff.versatility|trinket.2.has_buff.haste|trinket.2.has_buff.crit)&!variable.trinket_2_exclude)&(!trinket.2.is.flarendos_pilot_light) actions.precombat+=/variable,name=trinket_1_sync,op=setif,value=1,value_else=0.5,condition=variable.trinket_1_buffs&(trinket.1.cooldown.duration%%120=0) actions.precombat+=/variable,name=trinket_2_sync,op=setif,value=1,value_else=0.5,condition=variable.trinket_2_buffs&(trinket.2.cooldown.duration%%120=0) actions.precombat+=/variable,name=trinket_priority,op=setif,value=2,value_else=1,condition=!variable.trinket_1_buffs&variable.trinket_2_buffs&(trinket.2.has_cooldown&!variable.trinket_2_exclude|!trinket.1.has_cooldown)|variable.trinket_2_buffs&((trinket.2.cooldown.duration%trinket.2.proc.any_dps.duration)*(0.5+trinket.2.has_buff.intellect*3+trinket.2.has_buff.mastery)*(variable.trinket_2_sync))>((trinket.1.cooldown.duration%trinket.1.proc.any_dps.duration)*(0.5+trinket.1.has_buff.intellect*3+trinket.1.has_buff.mastery)*(variable.trinket_1_sync)*(1+((trinket.1.ilvl-trinket.2.ilvl)%100))) actions.precombat+=/variable,name=damage_trinket_priority,op=setif,value=2,value_else=1,condition=!variable.trinket_1_buffs&!variable.trinket_2_buffs&trinket.2.ilvl>=trinket.1.ilvl # Double on use - Priotize Intellect on use trinkets over Nymues, force overwriting the normal logic to guarantee it is correct. actions.precombat+=/variable,name=trinket_priority,op=setif,value=2,value_else=1,condition=trinket.1.is.nymues_unraveling_spindle&trinket.2.has_buff.intellect|trinket.2.is.nymues_unraveling_spindle&!trinket.1.has_buff.intellect,if=(trinket.1.is.nymues_unraveling_spindle|trinket.2.is.nymues_unraveling_spindle)&(variable.trinket_1_buffs&variable.trinket_2_buffs) actions.precombat+=/variable,name=hold_empower_for,op=reset,default=6 actions.precombat+=/variable,name=ebon_might_pandemic_threshold,op=reset,default=0.4 actions.precombat+=/variable,name=wingleader_force_timings,op=reset,default=0 actions.precombat+=/variable,name=enforce_timings,op=reset,default=0 actions.precombat+=/variable,name=spam_on_use_trinket,op=reset,default=0 actions.precombat+=/use_item,name=aberrant_spellforge actions.precombat+=/blistering_scales,target_if=target.role.tank actions.precombat+=/living_flame # Executed every time the actor is available. actions=variable,name=temp_wound,value=debuff.temporal_wound.remains,target_if=max:debuff.temporal_wound.remains actions+=/variable,name=eons_remains,op=setif,value=cooldown.allied_virtual_cd_time.remains,value_else=cooldown.breath_of_eons.remains,condition=!talent.wingleader&(!set_bonus.tww3_2pc|!talent.temporal_burst.enabled|variable.enforce_timings)|variable.wingleader_force_timings,if=talent.breath_of_eons actions+=/variable,name=eons_remains,op=set,value=cooldown.allied_virtual_cd_time.remains,if=!talent.breath_of_eons actions+=/variable,name=pool_for_id,default=0,op=set,value=(variable.eons_remains<8&talent.breath_of_eons&(target.time_to_die>13&raid_event.adds.in>15|fight_remains<30&!fight_style.dungeonroute)|cooldown.deep_breath.remains<8&!talent.breath_of_eons)&essence.deficit>=1&!buff.essence_burst.react,if=(!set_bonus.tww3_4pc|!hero_tree.chronowarden)&talent.imminent_destruction actions+=/hover,use_off_gcd=1,if=gcd.remains>=0.5&(!raid_event.movement.exists&(trinket.1.is.ovinaxs_mercurial_egg|trinket.2.is.ovinaxs_mercurial_egg)|raid_event.movement.in<=6) # actions+=/time_skip,target_if=max:debuff.bombardments.remains,if=cooldown.fire_breath.full_recharge_time>0&cooldown.prescience.full_recharge_time>0&cooldown.breath_of_eons.full_recharge_time>0&cooldown.upheaval.full_recharge_time>0 actions+=/prescience,target_if=min:(debuff.prescience.remains-200*(target.role.attack|target.role.spell|target.role.dps)+50*target.spec.augmentation),if=((full_recharge_time<=gcd.max*3|cooldown.ebon_might.remains<=gcd.max*3&(buff.ebon_might_self.remains-gcd.max*3)<=buff.ebon_might_self.duration*variable.ebon_might_pandemic_threshold|fight_remains<=30)|variable.eons_remains<=8|talent.anachronism&buff.imminent_destruction.up&essence<1&!cooldown.fire_breath.up&!cooldown.upheaval.up)&debuff.prescience.remains<gcd.max*2&(!talent.anachronism|buff.essence_burst.stack<buff.essence_burst.max_stack|time<=10)&full_recharge_time<=gcd.max actions+=/prescience,target_if=min:(debuff.prescience.remains-200*(target.role.attack|target.role.spell|target.role.dps)+50*target.spec.augmentation),if=((full_recharge_time<=gcd.max*3|cooldown.ebon_might.remains<=gcd.max*3&(buff.ebon_might_self.remains-gcd.max*3)<=buff.ebon_might_self.duration*variable.ebon_might_pandemic_threshold|fight_remains<=30&!fight_style.dungeonroute)|variable.eons_remains<=8|talent.anachronism&buff.imminent_destruction.up&essence<1&!cooldown.fire_breath.up&!cooldown.upheaval.up)&debuff.prescience.remains<gcd.max*2&(!talent.anachronism|buff.essence_burst.stack<buff.essence_burst.max_stack|time<=10) actions+=/prescience,target_if=min:(debuff.prescience.remains-200*(target.spec.augmentation|target.role.tank)),if=full_recharge_time<=gcd.max*3&debuff.prescience.remains<gcd.max*2&(target.spec.augmentation|target.role.tank)&(!talent.anachronism|buff.essence_burst.stack<buff.essence_burst.max_stack|time<=5) actions+=/potion,if=variable.eons_remains<=0|cooldown.breath_of_eons.remains>=90|fight_remains<=30&!fight_style.dungeonroute actions+=/ebon_might,if=(((buff.ebon_might_self.remains-cast_time)<=buff.ebon_might_self.duration*variable.ebon_might_pandemic_threshold)&(active_enemies>0|raid_event.adds.in<=3)&(variable.eons_remains>0|!talent.breath_of_eons&cooldown.deep_breath.remains>0|raid_event.adds.in<=3|time>30|talent.molten_embers&(set_bonus.tww2_2pc|!talent.breath_of_eons|talent.overlord))&(!buff.imminent_destruction.up|buff.ebon_might_self.remains<=gcd.max)|variable.eons_remains>0&buff.ebon_might_self.value<=0.3&!cooldown.fire_breath.up&!cooldown.upheaval.up&talent.doubletime)&(buff.ebon_might_self.value<=0.3|(buff.ebon_might_self.remains-cast_time)<=buff.ebon_might_self.duration*0.3) actions+=/call_action_list,name=items actions+=/run_action_list,name=opener_filler,if=variable.opener_delay>0&!fight_style.dungeonroute actions+=/fury_of_the_aspects,if=talent.time_convergence&!buff.time_convergence_intellect.up&(essence>=2|buff.essence_burst.react)&variable.eons_remains>=8 actions+=/tip_the_scales,if=talent.threads_of_fate&(prev_gcd.1.breath_of_eons|prev_gcd.1.deep_breath|fight_remains<=30&!fight_style.dungeonroute|cooldown.breath_of_eons.remains>=30) actions+=/call_action_list,name=fb,if=(raid_event.adds.remains>6|raid_event.adds.in>20|evoker.allied_cds_up>0|!raid_event.adds.exists)&(!talent.molten_embers|cooldown.upheaval.remains<=(8+4*talent.blast_furnace-6*talent.font_of_magic.enabled))&(!cooldown.breath_of_eons.up|!talent.temporal_burst) actions+=/deep_breath,cancel_if=gcd.remains<=0 actions+=/breath_of_eons,if=talent.wingleader&(fight_style.dungeonroute|fight_style.dungeonslice)&target.time_to_die>=13&evoker.allied_cds_up>0,cancel_if=gcd.remains<=0&ticks>=10 actions+=/breath_of_eons,if=talent.wingleader&(target.time_to_die>=13&(raid_event.adds.in>=25|!raid_event.adds.exists|raid_event.adds.remains>=13&raid_event.adds.count%1.5<active_enemies))&!variable.wingleader_force_timings&(time%%240<=230&time%%240>=3|fight_style.dungeonroute|fight_style.dungeonslice)|fight_remains<=30&!fight_style.dungeonroute,cancel_if=gcd.remains<=0&ticks>=10 actions+=/breath_of_eons,if=(target.time_to_die>13&raid_event.adds.in>15|fight_remains<30&!fight_style.dungeonroute)&variable.eons_remains<=0&(time%%30<=12)|fight_remains<=15&(talent.imminent_destruction|talent.melt_armor)&!fight_style.dungeonroute,cancel_if=gcd.remains<=0&ticks>=10 actions+=/breath_of_eons,if=fight_style.dungeonroute&(target.time_to_die>=13&(raid_event.adds.in>=25|!raid_event.adds.exists|raid_event.adds.remains>=13&raid_event.adds.count%1.5<active_enemies)),cancel_if=gcd.remains<=0&ticks>=10 actions+=/upheaval,target_if=target.time_to_die>duration+0.2,empower_to=1,if=buff.ebon_might_self.remains>duration&(raid_event.adds.remains>10|evoker.allied_cds_up>0|!raid_event.adds.exists|raid_event.adds.in>20)&(!talent.molten_embers|dot.fire_breath_damage.ticking|cooldown.fire_breath.remains>=10)&(buff.essence_burst.stack<buff.essence_burst.max_stack|!set_bonus.tww2_4pc&!talent.rockfall|!buff.essence_burst.react) actions+=/time_skip,if=(((cooldown.fire_breath.remains>?20)+(cooldown.upheaval.remains>?20)))>=30&(cooldown.breath_of_eons.remains>=20&talent.breath_of_eons|!talent.breath_of_eons&cooldown.deep_breath.remains>=20)&(!buff.imminent_destruction.up|talent.temporal_burst&buff.temporal_burst.remains>=15) actions+=/emerald_blossom,if=talent.dream_of_spring&buff.essence_burst.react&(variable.spam_heal=2|variable.spam_heal=1&!buff.ancient_flame.up&talent.ancient_flame)&(buff.ebon_might_self.up|essence.deficit=0|buff.essence_burst.stack=buff.essence_burst.max_stack&cooldown.ebon_might.remains>4) actions+=/living_flame,target_if=max:debuff.bombardments.remains,if=talent.mass_eruption&buff.mass_eruption_stacks.up&!buff.imminent_destruction.up&buff.essence_burst.stack<buff.essence_burst.max_stack&essence.deficit>1&(buff.ebon_might_self.remains>=6|cooldown.ebon_might.remains<=6)&debuff.bombardments.remains<action.eruption.execute_time&(talent.pupil_of_alexstrasza|active_enemies=1) actions+=/azure_strike,target_if=max:debuff.bombardments.remains,if=talent.mass_eruption&buff.mass_eruption_stacks.up&!buff.imminent_destruction.up&buff.essence_burst.stack<buff.essence_burst.max_stack&essence.deficit>1&(buff.ebon_might_self.remains>=6|cooldown.ebon_might.remains<=6)&debuff.bombardments.remains<action.eruption.execute_time&(talent.echoing_strike&active_enemies>1) # actions+=/time_spiral,if=talent.time_convergence&!buff.time_convergence_intellect.up&(essence>=2|buff.essence_burst.react) actions+=/oppressing_roar,if=talent.time_convergence&!buff.time_convergence_intellect.up&(essence>=2|buff.essence_burst.react) actions+=/emerald_blossom,if=talent.dream_of_spring&mana>=650000&talent.ancient_flame&!buff.ancient_flame.up&buff.essence_burst.up&(buff.temporal_burst.up&set_bonus.tww3_4pc&(!buff.imminent_destruction.up|mana>=2000000)|equipped.diamantine_voidcore&mana.pct>=50) actions+=/living_flame,if=desired_targets>=2&buff.temporal_burst.up&set_bonus.tww3_4pc&!buff.essence_burst.up actions+=/eruption,target_if=min:debuff.bombardments.remains,if=(buff.ebon_might_self.remains>execute_time|essence.deficit=0|buff.essence_burst.stack=buff.essence_burst.max_stack&cooldown.ebon_might.remains>4|buff.essence_burst.react&set_bonus.tww2_4pc)&!variable.pool_for_id&(buff.imminent_destruction.up|essence.deficit<=2|buff.essence_burst.up|variable.ebon_might_pandemic_threshold>0) actions+=/blistering_scales,target_if=target.role.tank,if=!evoker.scales_up&buff.ebon_might_self.down actions+=/run_action_list,name=filler actions.fb=tip_the_scales,if=cooldown.fire_breath.ready&buff.ebon_might_self.up actions.fb+=/fire_breath,empower_to=4,target_if=target.time_to_die>4,if=talent.font_of_magic&(buff.ebon_might_self.remains>duration&(!talent.molten_embers|cooldown.upheaval.remains<=(20+4*talent.blast_furnace-6*3))|buff.tip_the_scales.up) actions.fb+=/fire_breath,empower_to=3,target_if=target.time_to_die>8,if=(buff.ebon_might_self.remains>duration&(!talent.molten_embers|cooldown.upheaval.remains<=(20+4*talent.blast_furnace-6*2))|buff.tip_the_scales.up) actions.fb+=/fire_breath,empower_to=2,target_if=target.time_to_die>12,if=buff.ebon_might_self.remains>duration&(!talent.molten_embers|cooldown.upheaval.remains<=(20+4*talent.blast_furnace-6*1)) actions.fb+=/fire_breath,empower_to=1,target_if=target.time_to_die>16,if=buff.ebon_might_self.remains>duration&(!talent.molten_embers|cooldown.upheaval.remains<=(20+4*talent.blast_furnace-6*0)) actions.fb+=/fire_breath,empower_to=4,target_if=target.time_to_die>4,if=talent.font_of_magic&(buff.ebon_might_self.remains>duration) actions.fb+=/fire_breath,empower_to=3,target_if=target.time_to_die>8,if=talent.font_of_magic&set_bonus.tww2_2pc&talent.molten_embers actions.filler=living_flame,if=(buff.ancient_flame.up|mana>=200000|!talent.dream_of_spring|variable.spam_heal=0)&(active_enemies=1|talent.pupil_of_alexstrasza) actions.filler+=/azure_strike actions.items=use_item,name=nymues_unraveling_spindle,if=cooldown.breath_of_eons.remains<=3&(trinket.1.is.nymues_unraveling_spindle&variable.trinket_priority=1|trinket.2.is.nymues_unraveling_spindle&variable.trinket_priority=2)|(cooldown.fire_breath.remains<=4|cooldown.upheaval.remains<=4)&cooldown.breath_of_eons.remains>10&!(debuff.temporal_wound.up|prev_gcd.1.breath_of_eons)&(trinket.1.is.nymues_unraveling_spindle&variable.trinket_priority=2|trinket.2.is.nymues_unraveling_spindle&variable.trinket_priority=1) actions.items+=/use_item,name=aberrant_spellforge actions.items+=/use_item,name=flarendos_pilot_light,if=!variable.trinket_1_buffs&!variable.trinket_1_manual&trinket.2.is.flarendos_pilot_light|!variable.trinket_2_buffs&!variable.trinket_2_manual&trinket.1.is.flarendos_pilot_light actions.items+=/use_item,name=treacherous_transmitter,if=cooldown.allied_virtual_cd_time.remains<=10|cooldown.breath_of_eons.remains<=10&talent.wingleader|fight_remains<=15 actions.items+=/do_treacherous_transmitter_task,use_off_gcd=1,if=(debuff.temporal_wound.up|prev_gcd.1.breath_of_eons|fight_remains<=15) actions.items+=/use_item,name=spymasters_web,if=(debuff.temporal_wound.up|prev_gcd.1.breath_of_eons)&(fight_remains<=130-(30+12*talent.interwoven_threads)*talent.wingleader-20*talent.time_skip*(cooldown.time_skip.remains<=90)*!talent.interwoven_threads)|(fight_remains<=20|evoker.allied_cds_up>0&fight_remains<=60)&(trinket.1.is.spymasters_web&(trinket.2.cooldown.duration=0|trinket.2.cooldown.remains>=10|variable.trinket_2_exclude)|trinket.2.is.spymasters_web&(trinket.1.cooldown.duration=0|trinket.1.cooldown.remains>=10|variable.trinket_1_exclude))&!buff.spymasters_web.up actions.items+=/use_item,name=house_of_cards,if=evoker.shifting_buffs>=2|evoker.shifting_buffs>=1&(cooldown.fire_breath.remains<=7|cooldown.upheaval.remains<=7) actions.items+=/use_item,slot=trinket1,if=variable.trinket_1_buffs&!variable.trinket_1_manual&!variable.trinket_1_exclude&((debuff.temporal_wound.up|prev_gcd.1.breath_of_eons|!talent.breath_of_eons&buff.ebon_might_self.up&active_enemies>=1|variable.spam_on_use_trinket&(!cooldown.breath_of_eons.up|variable.eons_remains>=10))|variable.trinket_2_buffs&!trinket.2.cooldown.up&(prev_gcd.1.fire_breath|prev_gcd.1.upheaval)&buff.ebon_might_self.up)&(variable.trinket_2_exclude|!trinket.2.has_cooldown|trinket.2.cooldown.remains|variable.trinket_priority=1)|trinket.1.proc.any_dps.duration>=fight_remains actions.items+=/use_item,slot=trinket2,if=variable.trinket_2_buffs&!variable.trinket_2_manual&!variable.trinket_2_exclude&((debuff.temporal_wound.up|prev_gcd.1.breath_of_eons|!talent.breath_of_eons&buff.ebon_might_self.up&active_enemies>=1|variable.spam_on_use_trinket&(!cooldown.breath_of_eons.up|variable.eons_remains>=10))|variable.trinket_1_buffs&!trinket.1.cooldown.up&(prev_gcd.1.fire_breath|prev_gcd.1.upheaval)&buff.ebon_might_self.up)&(variable.trinket_1_exclude|!trinket.1.has_cooldown|trinket.1.cooldown.remains|variable.trinket_priority=2)|trinket.2.proc.any_dps.duration>=fight_remains # Azure Strike for OGCD trinkets. Ideally this would be Prescience casts in reality but this is simpler and seems to have no noticeable diferrence in DPS. actions.items+=/azure_strike,if=cooldown.item_cd_1141.up&(variable.trinket_1_ogcd_cast&trinket.1.cooldown.up&(variable.damage_trinket_priority=1|trinket.2.cooldown.remains)|variable.trinket_2_ogcd_cast&trinket.2.cooldown.up&(variable.damage_trinket_priority=2|trinket.1.cooldown.remains)) # If only one on use trinket provides a buff, use the other on cooldown. Or if neither trinket provides a buff, use both on cooldown. actions.items+=/use_item,use_off_gcd=1,slot=trinket1,if=!variable.trinket_1_buffs&!variable.trinket_1_manual&!variable.trinket_1_exclude&(variable.damage_trinket_priority=1|trinket.2.cooldown.remains|trinket.2.is.spymasters_web&buff.spymasters_report.stack<30|variable.eons_remains>=20|!talent.breath_of_eons|trinket.2.cooldown.duration=0|variable.trinket_2_exclude)&(gcd.remains>0.1&variable.trinket_1_ogcd_cast) actions.items+=/use_item,use_off_gcd=1,slot=trinket2,if=!variable.trinket_2_buffs&!variable.trinket_2_manual&!variable.trinket_2_exclude&(variable.damage_trinket_priority=2|trinket.1.cooldown.remains|trinket.1.is.spymasters_web&buff.spymasters_report.stack<30|variable.eons_remains>=20|!talent.breath_of_eons|trinket.1.cooldown.duration=0|variable.trinket_1_exclude)&(gcd.remains>0.1&variable.trinket_2_ogcd_cast) actions.items+=/use_item,slot=trinket1,if=!variable.trinket_1_buffs&!variable.trinket_1_manual&!variable.trinket_1_exclude&(variable.damage_trinket_priority=1|trinket.2.cooldown.remains|trinket.2.is.spymasters_web&buff.spymasters_report.stack<30|variable.eons_remains>=20|!talent.breath_of_eons|trinket.2.cooldown.duration=0|variable.trinket_2_exclude)&(!variable.trinket_1_ogcd_cast) actions.items+=/use_item,slot=trinket2,if=!variable.trinket_2_buffs&!variable.trinket_2_manual&!variable.trinket_2_exclude&(variable.damage_trinket_priority=2|trinket.1.cooldown.remains|trinket.1.is.spymasters_web&buff.spymasters_report.stack<30|variable.eons_remains>=20|!talent.breath_of_eons|trinket.1.cooldown.duration=0|variable.trinket_1_exclude)&(!variable.trinket_2_ogcd_cast) actions.items+=/use_item,name=bestinslots,use_off_gcd=1,if=buff.ebon_might_self.up&(!variable.trinket_1_buffs|trinket.1.cooldown.duration<=20|trinket.1.cooldown.remains>=10)&(!variable.trinket_2_buffs|trinket.2.cooldown.duration<=20|trinket.2.cooldown.remains>=10) # Use on use weapons actions.items+=/use_item,slot=main_hand,use_off_gcd=1,if=gcd.remains>=gcd.max*0.6&!equipped.bestinslots actions.opener_filler=variable,name=opener_delay,value=variable.opener_delay>?variable.minimum_opener_delay,if=!variable.opener_cds_detected&evoker.allied_cds_up>0 actions.opener_filler+=/variable,name=opener_delay,value=variable.opener_delay-1 actions.opener_filler+=/variable,name=opener_cds_detected,value=1,if=!variable.opener_cds_detected&evoker.allied_cds_up>0 actions.opener_filler+=/eruption,if=variable.opener_delay>=3 actions.opener_filler+=/living_flame,if=active_enemies=1|talent.pupil_of_alexstrasza actions.opener_filler+=/azure_strike
412
0.940735
1
0.940735
game-dev
MEDIA
0.97558
game-dev
0.907091
1
0.907091
Traben-0/Entity_Texture_Features
1,247
src/main/java/traben/entity_texture_features/features/property_reading/properties/etf_properties/external/MonthProperty.java
package traben.entity_texture_features.features.property_reading.properties.etf_properties.external; import org.jetbrains.annotations.NotNull; import traben.entity_texture_features.features.property_reading.properties.generic_properties.SimpleIntegerArrayProperty; import traben.entity_texture_features.features.state.ETFEntityRenderState; import traben.entity_texture_features.utils.ETFEntity; import java.util.Calendar; import java.util.Properties; public class MonthProperty extends SimpleIntegerArrayProperty { protected MonthProperty(Properties properties, int propertyNum) throws RandomPropertyException { super(getGenericIntegerSplitWithRanges(properties, propertyNum, "month")); } public static MonthProperty getPropertyOrNull(Properties properties, int propertyNum) { try { return new MonthProperty(properties, propertyNum); } catch (RandomPropertyException e) { return null; } } @Override public @NotNull String[] getPropertyIds() { return new String[]{"month"}; } @Override protected int getValueFromEntity(ETFEntityRenderState entity) { return Calendar.getInstance().get(Calendar.MONTH); //january 0 } }
412
0.669629
1
0.669629
game-dev
MEDIA
0.237126
game-dev
0.636808
1
0.636808
RaymondMaarloeve/RaymondMaarloeve
6,722
RaymondMaarloeve/Assets/Scripts/PlayerController.cs
using System.Linq; using Gitmanik.Console; using UnityEngine; public enum PlayerState { Moving, // Gracz moze sie poruszac Interacting // Gracz jest w interakcji z NPC } /// <summary> /// Manages player movement, interaction with NPCs, and state transitions. /// Handles gravity, animations, and camera behavior during interactions. /// </summary> public class PlayerController : MonoBehaviour { /// <summary> /// Singleton instance of the PlayerController class. /// </summary> public static PlayerController Instance; /// <summary> /// Speed at which the player moves. /// </summary> public float moveSpeed = 5f; /// <summary> /// Gravity applied to the player. /// </summary> public float gravity = 9.81f; /// <summary> /// Reference to the CharacterController component. /// </summary> private CharacterController characterController; /// <summary> /// Direction of player movement. /// </summary> private Vector3 moveDirection; /// <summary> /// Current state of the player (e.g., Moving or Interacting). /// </summary> private PlayerState currentState = PlayerState.Moving; /// <summary> /// Transform of the NPC the player is targeting for interaction. /// </summary> private Transform targetNPC = null; /// <summary> /// Reference to the player's SkinnedMeshRenderer. /// </summary> private SkinnedMeshRenderer characterMesh; /// <summary> /// Reference to the NPC the player is currently interacting with. /// </summary> public NPC currentlyInteractingNPC = null; /// <summary> /// Reference to the Animator component for player animations. /// </summary> private Animator animator; /// <summary> /// Initializes the singleton instance. /// </summary> void Awake() { Instance = this; } /// <summary> /// Initializes components and sets the camera target to the player. /// </summary> void Start() { characterController = GetComponent<CharacterController>(); CameraFollow.Instance.SetTarget(transform, false); characterMesh = GetComponentInChildren<SkinnedMeshRenderer>(); animator = GetComponentInChildren<Animator>(); } /// <summary> /// Updates player movement and interaction logic every frame. /// </summary> void Update() { if (GitmanikConsole.Visible) return; if (currentState == PlayerState.Moving) { HandleMovement(); } if (Input.GetKeyDown(KeyCode.E)) { if (currentState == PlayerState.Moving && targetNPC != null) { StartInteraction(targetNPC.GetComponent<NPC>()); } } if (Input.GetKeyDown(KeyCode.Escape) && currentState == PlayerState.Interacting) { EndInteraction(); } } /// <summary> /// Handles player movement, including gravity and animations. /// </summary> void HandleMovement() { float moveX = Input.GetAxisRaw("Horizontal"); float moveZ = Input.GetAxisRaw("Vertical"); moveDirection = new Vector3(moveX, 0, moveZ).normalized * moveSpeed; if (moveDirection.magnitude > 0) { transform.forward = new Vector3(moveX, 0, moveZ); } if (!characterController.isGrounded) { moveDirection.y -= gravity * Time.deltaTime; } characterController.Move(moveDirection * Time.deltaTime); if (animator != null) { Vector3 horizontalMove = moveDirection; horizontalMove.y = 0f; animator.SetFloat("Speed", horizontalMove.magnitude); } } /// <summary> /// Starts interaction with the specified NPC. /// Adjusts camera and player state for interaction. /// </summary> /// <param name="npc">The NPC to interact with.</param> public void StartInteraction(NPC npc) { currentState = PlayerState.Interacting; moveDirection = Vector3.zero; // Zatrzymanie gracza characterMesh.enabled = false; GameManager.Instance.MinimapGameObject.SetActive(false); npc.OnInteraction(); currentlyInteractingNPC = npc; if (CameraFollow.Instance != null) { CameraFollow.Instance.SetTarget(npc.transform, true); // Kamera przybliza sie do NPC } else { Debug.LogError("CameraFollow.Instance is NULL!"); } if (DialogBoxManager.Instance != null) { DialogBoxManager.Instance.ShowDialogBox(); // Pokazanie okna dialogowego } else { Debug.LogError("DialogBoxManager.Instance is NULL!"); } Debug.Log("Started interaction with: " + npc.name); } /// <summary> /// Ends interaction with the currently interacting NPC. /// Resets camera and player state. /// </summary> public void EndInteraction() { currentState = PlayerState.Moving; characterMesh.enabled = true; GameManager.Instance.MinimapGameObject.SetActive(true); currentlyInteractingNPC.LookAt(null); var conv = DialogBoxManager.Instance.currentConversation.ToList(); StartCoroutine( Instance.currentlyInteractingNPC?.DrawConclusions(conv)); Instance.currentlyInteractingNPC = null; if (CameraFollow.Instance != null) { CameraFollow.Instance.SetTarget(transform, false); // Kamera wraca do gracza } else { Debug.LogError("CameraFollow.Instance is NULL!"); } if (DialogBoxManager.Instance != null) { DialogBoxManager.Instance.HideDialogBox(); // Ukrycie okna dialogowego } else { Debug.LogError("DialogBoxManager.Instance is NULL!"); } Debug.Log("Ended interaction"); } /// <summary> /// Detects when the player enters the trigger zone of an NPC. /// </summary> /// <param name="other">The collider of the NPC.</param> void OnTriggerEnter(Collider other) { if (other.CompareTag("NPC")) { targetNPC = other.transform; } } /// <summary> /// Detects when the player exits the trigger zone of an NPC. /// </summary> /// <param name="other">The collider of the NPC.</param> void OnTriggerExit(Collider other) { if (other.CompareTag("NPC")) { targetNPC = null; } } }
412
0.911224
1
0.911224
game-dev
MEDIA
0.984987
game-dev
0.95024
1
0.95024
luotan-123/libevent-server
142,194
linuxserverplatform/src/GameManage/GameDesk.cpp
#include "GameDesk.h" CGameDesk::CGameDesk(BYTE byBeginMode) : m_byBeginMode(byBeginMode) { m_bPlayGame = false; m_byMaxPeople = 0; m_byGameStation = 0; m_pDataManage = NULL; m_deskIdx = INVALID_DESKIDX; m_iVipGameCount = 0; //购买桌子局数 m_iBuyGameCount = 0; m_iRunGameCount = 0; //游戏运行的局数 m_masterID = 0; m_isMasterNotPlay = false; m_needLoadConfig = false; memset(m_szDeskPassWord, 0, sizeof(m_szDeskPassWord)); memset(m_szGameRules, 0, sizeof(m_szGameRules)); memset(m_uScore, 0, sizeof(m_uScore)); memset(m_gameWinCount, 0, sizeof(m_gameWinCount)); m_isDismissStatus = false; m_reqDismissDeskStation = INVALID_DESKSTATION; m_reqDismissTime = 0; m_isBegin = false; m_enable = false; m_finishedGameCount = 0; m_iConfigCount = 0; m_beginTime = 0; m_finishedTime = 0; m_friendsGroupMsg.Init(); m_autoBeginMode = 0; m_bGameStopJoin = 0; } CGameDesk::~CGameDesk() { } bool CGameDesk::Init(int deskIdx, BYTE byMaxPeople, CGameMainManage * pDataManage) { if (!pDataManage) { return false; } m_byMaxPeople = byMaxPeople; m_pDataManage = pDataManage; m_deskIdx = deskIdx; InitDeskGameStation(); ReSetGameState(0); // 初始化桌子玩家数组大小 m_deskUserInfoVec.resize(byMaxPeople); m_iConfigCount = byMaxPeople; return true; } bool CGameDesk::SetTimer(UINT uTimerID, int uElapse, BYTE timerType/* = SERVERTIMER_TYPE_SINGLE*/) { if (uTimerID >= TIME_SPACE) { ERROR_LOG("SetTimer error uTimerID >= %d", TIME_SPACE); return false; } if (!m_pDataManage) { return false; } unsigned int realTimerID = m_deskIdx * TIME_SPACE + uTimerID + TIME_START_ID; return m_pDataManage->SetTimer(realTimerID, uElapse, timerType); } bool CGameDesk::KillTimer(UINT uTimerID) { if (uTimerID >= TIME_SPACE) { return false; } if (!m_pDataManage) { return false; } return m_pDataManage->KillTimer(m_deskIdx * TIME_SPACE + TIME_START_ID + uTimerID); } bool CGameDesk::UserNetCut(GameUserInfo *pUser) { m_deskUserInfoVec[pUser->deskStation].bNetCut = true; if (GetRoomSort() == ROOM_SORT_NORMAL || GetRoomSort() == ROOM_SORT_SCENE) { BroadcastUserOfflineData(pUser->deskStation); } else if (GetRoomSort() == ROOM_SORT_HUNDRED) { HundredGameUserNetCutLogic(pUser); } return true; } bool CGameDesk::SendGameData(BYTE deskStation, unsigned int mainID, unsigned int assistID, unsigned int handleCode) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } m_pDataManage->SendData(userID, NULL, 0, mainID, assistID, handleCode); return true; } bool CGameDesk::SendGameData(BYTE deskStation, void* pData, int size, unsigned int mainID, unsigned int assistID, unsigned int handleCode) { int userID = GetUserIDByDeskStation(deskStation); if (userID > 0) { m_pDataManage->SendData(userID, pData, size, mainID, assistID, handleCode); } return true; } bool CGameDesk::CanBeginGame() { if (GetRoomSort() == ROOM_SORT_SCENE) { //场景类的游戏开始,交给游戏自己控制 return false; } if (IsPlayGame(0)) { return false; } int agreeCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (pUser) { if (pUser->playStatus == USER_STATUS_AGREE) { agreeCount++; } } } if (m_byBeginMode == ALL_ARGEE) { if (agreeCount <= 1) { return false; } int roomType = GetRoomType(); if (roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) { if (m_autoBeginMode > 0 && agreeCount < m_autoBeginMode) { return false; } } int currDeskUserCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID > 0) { currDeskUserCount++; } } if (agreeCount >= currDeskUserCount) { return true; } } else if (m_byBeginMode == FULL_BEGIN) { if (m_pDataManage->IsMultiPeopleGame()) { if (agreeCount == m_iConfigCount) { return true; } } else { if (agreeCount == m_byMaxPeople) { return true; } } } return false; } bool CGameDesk::UserAgreeGame(BYTE deskStation) { if (GetRoomSort() == ROOM_SORT_HUNDRED || GetRoomSort() == ROOM_SORT_SCENE) { // 百人类游戏和场景类游戏没有准备 return false; } if (GetRoomType() == ROOM_TYPE_MATCH) { // 比赛场不需要准备 return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { ERROR_LOG("GetUserIDByDeskStation failed deskStation:%d", deskStation); return false; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser userID:%d", userID); return false; } // 游戏状态是否正确 if (m_bPlayGame) { return false; } int roomType = GetRoomType(); // 玩家状态是否正确 if (pUser->playStatus != USER_STATUS_SITING && (roomType == ROOM_TYPE_GOLD || m_iRunGameCount > 0)) { return false; } //(金币房和俱乐部VIP房)判断该玩家金币是否满足条件 if (m_pDataManage->m_uNameID != 37550102 && (roomType == ROOM_TYPE_FRIEND && pUser->money < m_RemoveMinPoint || roomType == ROOM_TYPE_FG_VIP && pUser->fireCoin < m_RemoveMinPoint)) { ERROR_LOG("user(%d) money(%lld)金币不够,无法准备", pUser->userID, pUser->money); return true; } pUser->playStatus = USER_STATUS_AGREE; // 通知这个玩家已准备 BroadcastUserAgreeData(deskStation); if ((roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FG_VIP) && m_pDataManage->IsCanWatch() && m_autoBeginMode == 0) { // 第一局 if (m_iRunGameCount == 0 && CanBeginGame()) { SetBeginUser(); m_pDataManage->SendData(m_beginUserID, NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_CANBEGIN, 0); } if (m_iRunGameCount >= 1 && CanBeginGame()) { // 第一局之后的游戏不受房主控制 GameBegin(0); } } else { if (CanBeginGame()) { GameBegin(0); } } return true; } bool CGameDesk::SendGameStation(BYTE deskStation, UINT socketID, bool bWatchUser, void * pData, UINT size) { int roomType = GetRoomType(); LoaderGameInfo gameInfo; gameInfo.bGameStation = m_byGameStation; memcpy(gameInfo.gameRules, m_szGameRules, sizeof(gameInfo.gameRules)); if (roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) { if (m_iRunGameCount == 0 && GetUserIDByDeskStation(deskStation) == m_beginUserID && CanBeginGame()) { m_pDataManage->SendData(m_beginUserID, NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_CANBEGIN, 0); } } else if (roomType == ROOM_TYPE_MATCH) //比赛场特殊处理 { int iSocketIndex = -1; int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { iSocketIndex = (int)socketID; } else { GameUserInfo *pUser = m_pDataManage->GetUser(userID); if (pUser) { iSocketIndex = pUser->socketIdx; userID = pUser->userID; } else { ERROR_LOG("内存没有玩家数据:userID=%d", userID); } } m_pDataManage->m_pGServerConnect->SendData(iSocketIndex, &gameInfo, sizeof(gameInfo), MSG_MAIN_LOADER_FRAME, MSG_ASS_LOADER_GAME_INFO, 0, userID); m_pDataManage->m_pGServerConnect->SendData(iSocketIndex, pData, size, MSG_MAIN_LOADER_FRAME, MSG_ASS_LOADER_GAME_STATION, 0, userID); // 发送当前桌子状态 SendMatchDeskStatus(userID); return true; } //发送游戏信息 SendGameData(deskStation, &gameInfo, sizeof(gameInfo), MSG_MAIN_LOADER_FRAME, MSG_ASS_LOADER_GAME_INFO, 0); SendGameData(deskStation, pData, size, MSG_MAIN_LOADER_FRAME, MSG_ASS_LOADER_GAME_STATION, 0); return true; } bool CGameDesk::GameBegin(BYTE bBeginFlag) { if (GetRoomSort() == ROOM_SORT_HUNDRED) { return HundredGameBegin(); } if (GetRoomType() == ROOM_TYPE_MATCH) { return MatchRoomGameBegin(); } // 记录玩家状态,游戏开始最后验证数据 int iDeskErrorCount = 0, iMemErrorCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { iMemErrorCount++; ERROR_LOG("### 游戏开始,内存中没有玩家数据 userID=%d ###", userID); m_deskUserInfoVec[i].clear(); continue; } if (pUser->deskStation != i) { //数据异常 ERROR_LOG("user deskStation is not match userID:%d deskStation=%d i=%d", pUser->userID, pUser->deskStation, i); return false; } pUser->playStatus = USER_STATUS_PLAYING; } else { iDeskErrorCount++; } } if (m_byBeginMode == FULL_BEGIN && (iDeskErrorCount + iMemErrorCount) > 0) { ERROR_LOG("### 游戏无法开始,iDeskErrorCount=%d,iMemErrorCount=%d ###", iDeskErrorCount, iMemErrorCount); return false; } //记录游戏开始需要的数据 m_bPlayGame = true; m_beginTime = time(NULL); int roomType = GetRoomType(); // 金币场开局扣除玩家金币 if (roomType == ROOM_TYPE_GOLD) { ProcessDeduceMoneyWhenGameBegin(); } else if (roomType == ROOM_TYPE_FRIEND) { ProcessDeduceMoneyWhenGameBegin(); KillTimer(IDT_FRIEND_ROOM_GAMEBEGIN); } else if (roomType == ROOM_TYPE_FG_VIP) { KillTimer(IDT_FRIEND_ROOM_GAMEBEGIN); } // 局数 m_iRunGameCount++; if (roomType != ROOM_TYPE_GOLD) { BroadcastDeskBaseInfo(); int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (pRedis) { pRedis->SetPrivateDeskGameCount(deskMixID, m_iRunGameCount); } } // 告诉桌子的玩家游戏开始了 BroadcastDeskData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GAMEBEGIN); // 房卡场第一局 if ((roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FG_VIP) && m_iRunGameCount == 1) { if (m_isBegin == false) { m_isBegin = true; // 通知大厅 if (m_friendsGroupMsg.friendsGroupDeskNumber > 0) { NotifyLogonDeskStatusChange(); } } } return true; } bool CGameDesk::GameFinish(BYTE bDeskStation, BYTE bCloseFlag) { if (GetRoomSort() == ROOM_SORT_HUNDRED) { return HundredGameFinish(); } int roomType = GetRoomType(); if (roomType == ROOM_TYPE_MATCH) { return MatchRoomGameFinish(); } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } if (!m_bPlayGame) { // 没有开始的游戏怎么会结束 ERROR_LOG("m_bPlayGame error m_bPlayGame:%d", m_bPlayGame); return false; } m_finishedGameCount++; m_bPlayGame = false; time_t currTime = time(NULL); LoaderNotifyGameFinish finishMsg; int rechargePlayerCount = 0; if ((roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) && m_iRunGameCount < m_iVipGameCount) { OtherConfig otherConfig; if (!pRedis->GetOtherConfig(otherConfig)) { otherConfig = ConfigManage()->GetOtherConfig(); } // 不是最后一局 bool bNeedKickOutUser = false; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (pUser && (roomType == ROOM_TYPE_FRIEND && pUser->money < m_RemoveMinPoint || roomType == ROOM_TYPE_FG_VIP && pUser->fireCoin < m_RemoveMinPoint)) { long long leftMoney = (long long)m_MinPoint - (roomType == ROOM_TYPE_FRIEND ? pUser->money : pUser->fireCoin); m_pDataManage->NotifyUserRechargeMoney(userID, leftMoney, FRIEND_ROOM_WAIT_BEGIN_TIME); finishMsg.rechargeUserID[rechargePlayerCount++] = userID; bNeedKickOutUser = true; } } if (bNeedKickOutUser) { SetTimer(IDT_FRIEND_ROOM_GAMEBEGIN, FRIEND_ROOM_WAIT_BEGIN_TIME * 1000); } } char userIDList[2048] = ""; // 账单使用 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser:%d failed", userID); continue; } sprintf(userIDList + strlen(userIDList), "%d,", userID); pUser->playStatus = USER_STATUS_SITING; m_deskUserInfoVec[i].lastWaitAgreeTime = currTime; } PrivateDeskInfo privateDeskInfo; if (roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) { int deskMixID = m_pDataManage->m_InitData.uRoomID * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; pRedis->GetPrivateDeskRecordInfo(deskMixID, privateDeskInfo); BroadcastDeskData(&finishMsg, sizeof(finishMsg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GAMEFINISH); if (m_iRunGameCount >= m_iVipGameCount) { OnDeskDissmissFinishSendData(); OnDeskSuccessfulDissmiss(false); } } else if (roomType == ROOM_TYPE_GOLD) { BroadcastDeskData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GAMEFINISH); for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser:%d failed", userID); continue; } bool bKickOut = false; bool bDelUser = false; int kickReason = REASON_KICKOUT_STAND; if (pUser->deskStation != i) { // 走到这里数据已经异常了 ERROR_LOG("user deskStation is not match userID:%d deskStation=%d i=%d", pUser->userID, pUser->deskStation, i); bKickOut = true; bDelUser = true; } else if (!pUser->IsOnline) { bKickOut = true; bDelUser = true; } else { kickReason = CheckUserMoney(userID); if (kickReason != REASON_KICKOUT_DEFAULT) { bKickOut = true; } } if (bKickOut) { // 玩家被踢 UserBeKicked((BYTE)i); // 通知所有玩家 BroadcastUserLeftData((BYTE)i, kickReason); // 清理桌子玩家数据 deskUserInfo.clear(); // 设置玩家为站起状态 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; if (bDelUser) { // 内存和缓存中移除玩家数据 m_pDataManage->DelUser(userID); } } } } if (roomType == ROOM_TYPE_GOLD || roomType == ROOM_TYPE_FRIEND) { char tableName[128] = ""; ConfigManage()->GetTableNameByDate(TBL_STATI_GAME_RECORD_INFO, tableName, sizeof(tableName)); // 生成游戏记录 BillManage()->WriteBill(&m_pDataManage->m_SQLDataManage, "INSERT INTO %s (passwd,deskIdx,roomID,createTime,beginTime,finishedTime,userIDList) VALUES('%s',%d,%d,%d,%d,%d,'%s')", tableName, privateDeskInfo.passwd, m_deskIdx, m_pDataManage->GetRoomID(), (int)privateDeskInfo.createTime, (int)m_beginTime, (int)m_finishedTime, userIDList); } // 加载配置 if (m_needLoadConfig) { m_needLoadConfig = false; LoadDynamicConfig(); } return true; } bool CGameDesk::OnTimer(UINT timerID) { int roomType = GetRoomType(); if (timerID == IDT_AGREE_DISMISS_DESK && (roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP)) { OnDeskDissmissFinishSendData(); OnDeskSuccessfulDissmiss(true); } if (timerID == IDT_FRIEND_ROOM_GAMEBEGIN && (roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP)) { OnTimerFriendRoomGameBegin(); } return false; } bool CGameDesk::HandleNotifyMessage(BYTE deskStation, unsigned int assistID, void * pData, int uSize, bool bWatchUser) { switch (assistID) { case MSG_ASS_LOADER_GAME_AGREE: //用户同意 { return UserAgreeGame(deskStation); } case MSG_ASS_LOADER_GAME_AUTO: { return OnHandleUserRequestAuto(deskStation); } case MSG_ASS_LOADER_GAME_CANCEL_AUTO: { return OnHandleUserRequestCancelAuto(deskStation); } case MSG_ASS_LOADER_GAME_MAGICEXPRESS: { return OnHandleUserRequestMagicExpress(deskStation, pData, uSize); } default: break; } return false; } bool CGameDesk::HandleDissmissMessage(BYTE deskStation, unsigned int assistID, void * pData, int size) { if (GetRoomType() == ROOM_TYPE_GOLD || GetRoomType() == ROOM_TYPE_MATCH) { return true; } switch (assistID) { case MSG_ASS_LOADER_REQ_DESKDISSMISS: { return OnHandleUserRequestDissmiss(deskStation); } case MSG_ASS_LOADER_ANSWER_DESKDISMISS: { return OnHandleUserAnswerDissmiss(deskStation, pData, size); } default: { break; } } return false; } void CGameDesk::OnDeskSuccessfulDissmiss(bool isDismissMidway /*= true*/) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return; } CRedisPHP* pRedisPHP = m_pDataManage->GetRedisPHP(); if (!pRedisPHP) { return; } int roomID = m_pDataManage->GetRoomID(); int deskMixID = roomID * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; PrivateDeskInfo privateDeskInfo; if (!pRedis->GetPrivateDeskRecordInfo(deskMixID, privateDeskInfo)) { ERROR_LOG("GetPrivateDeskRecordInfo failed deskMixID(%d)", deskMixID); return; } // 退还房卡 BuyGameDeskInfo buyDeskInfo = ProcessCostJewels(); // 清除所有定时器 KillTimer(IDT_AGREE_DISMISS_DESK); KillTimer(IDT_FRIEND_ROOM_GAMEBEGIN); char userInfoList[1024] = ""; char pumpInfoList[512] = ""; char winCountInfoList[512] = ""; long long llAllPumpScore = 0; long long llReturnMoney = 0; int roomType = GetRoomType(); double rate = GetDeskPercentage(); int currTime = (int)time(NULL); int deskRemainPeopleCount = 0; // 通知前端成功解散TODO LoaderNotifyDismissSuccess msg; msg.isDismissMidway = isDismissMidway; BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_DISMISS_OK); if (m_finishedGameCount > 0) { //先找到最大的大赢家 long long llMaxWinMoney = 0; if (m_roomTipType == ROOM_TIP_TYPE_MAX_WIN) { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { if (m_deskUserInfoVec[i].leftRoomUser <= 0) { continue; } else { userID = m_deskUserInfoVec[i].leftRoomUser; } } else { deskRemainPeopleCount++; } if (m_uScore[i] > llMaxWinMoney) { llMaxWinMoney = m_uScore[i]; } } } // 保存大结算战绩TODO PrivateDeskGradeSimpleInfo simpleGradeInfo; simpleGradeInfo.roomID = roomID; simpleGradeInfo.time = currTime; memcpy(simpleGradeInfo.gameRules, m_szGameRules, sizeof(simpleGradeInfo.gameRules)); simpleGradeInfo.masterID = m_masterID; simpleGradeInfo.passwd = atoi(m_szDeskPassWord); simpleGradeInfo.gameCount = m_finishedGameCount; simpleGradeInfo.maxGameCount = m_iBuyGameCount; std::vector<int> userIDVec; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { if (m_deskUserInfoVec[i].leftRoomUser <= 0) { continue; } else { userID = m_deskUserInfoVec[i].leftRoomUser; } } userIDVec.push_back(userID); // 计算抽水 long long taxValue = 0; long long AllScore[MAX_PLAYER_GRADE]; memcpy(AllScore, m_uScore, sizeof(m_uScore)); if (rate > 0 && m_uScore[i] > 0 && (m_roomTipType == ROOM_TIP_TYPE_ALL_WIN || m_roomTipType == ROOM_TIP_TYPE_MAX_WIN && m_uScore[i] == llMaxWinMoney)) { taxValue = (long long)floor(rate * m_uScore[i]); m_uScore[i] -= taxValue; if (roomType == ROOM_TYPE_FRIEND) { pRedis->SetUserMoneyEx(userID, -taxValue, true, RESOURCE_CHANGE_REASON_ROOM_PUMP_CONSUME, roomID, 0, 0, m_friendsGroupMsg.friendsGroupID); if (m_friendsGroupMsg.friendsGroupID > 0) { //将抽水返给管理员 UserData MuserData; int ChouShui = 0; int ManagerId = 0; if (!pRedisPHP->GetfriendsGroupToUser(m_friendsGroupMsg.friendsGroupID, userID, ChouShui, ManagerId)) { ERROR_LOG("获取俱乐部绑定的管理员ID失败:userId=%d,friendsGroupID=%d", userID, m_friendsGroupMsg.friendsGroupID); } if (ChouShui > 0 && ChouShui < 100 && ManagerId > 0 && taxValue > 0) { long long taxValueEx = 0; double drate = double(ChouShui) / 100.0; taxValueEx = (long long)floor(drate * taxValue); //将金币抽水返现给房主 if (taxValueEx > 0 && pRedis->GetUserData(ManagerId, MuserData)) { MuserData.money += taxValueEx; pRedis->SetUserMoneyEx(ManagerId, taxValueEx, true, RESOURCE_CHANGE_REASON_GOLD_ROOM_PUMP, roomID, 0, 0, m_friendsGroupMsg.friendsGroupID); // 通知金币变化 m_pDataManage->SendResourcesChangeToLogonServer(ManagerId, RESOURCE_TYPE_MONEY, MuserData.money, RESOURCE_CHANGE_REASON_GOLD_ROOM_PUMP, taxValueEx); } llReturnMoney += taxValueEx; } } } else if (roomType == ROOM_TYPE_FG_VIP) { pRedisPHP->SetUserFriendsGroupMoney(m_friendsGroupMsg.friendsGroupID, userID, -taxValue, true, RESOURCE_CHANGE_REASON_ROOM_PUMP_CONSUME, roomID); if (m_friendsGroupMsg.friendsGroupID > 0) { //将抽水返给管理员 int ChouShui = 0; int ManagerId = 0; long long FirMoney = 0; if (!pRedisPHP->GetfriendsGroupToUser(m_friendsGroupMsg.friendsGroupID, userID, ChouShui, ManagerId)) { ERROR_LOG("获取俱乐部绑定的管理员ID失败:userId=%d,friendsGroupID=%d", userID, m_friendsGroupMsg.friendsGroupID); } if (ChouShui > 0 && ChouShui < 100 && ManagerId > 0 && taxValue > 0) { long long taxValueEx = 0; double drate = double(ChouShui) / 100.0; taxValueEx = (long long)floor(drate * taxValue); //将金币抽水返现给房主 if (taxValueEx > 0 && pRedisPHP->GetUserFriendsGroupMoney(m_friendsGroupMsg.friendsGroupID, ManagerId, FirMoney)) { FirMoney += taxValueEx; pRedisPHP->SetUserFriendsGroupMoney(m_friendsGroupMsg.friendsGroupID, ManagerId, taxValueEx, true, RESOURCE_CHANGE_REASON_GOLD_ROOM_PUMP, roomID); // 通知火币变化 m_pDataManage->SendFireCoinChangeToLogonServer(m_friendsGroupMsg.friendsGroupID, ManagerId, FirMoney, RESOURCE_CHANGE_REASON_GOLD_ROOM_PUMP, taxValueEx); } llReturnMoney += taxValueEx; } } } } // 生成战绩 sprintf(userInfoList + strlen(userInfoList), "%d,%lld|", userID, m_uScore[i]); //生成抽水 sprintf(pumpInfoList + strlen(pumpInfoList), "%d,%lld|", userID, taxValue); //生成胜局数 sprintf(winCountInfoList + strlen(winCountInfoList), "%d,%d|", userID, m_gameWinCount[i]); //累计抽水 llAllPumpScore += taxValue; //设置俱乐部玩家输赢分数 if (m_friendsGroupMsg.friendsGroupID > 0) { if (roomType == ROOM_TYPE_PRIVATE) { pRedisPHP->SetUserFriendsGroupResNums(m_friendsGroupMsg.friendsGroupID, userID, "score", m_uScore[i], true); } else if (roomType == ROOM_TYPE_FRIEND) { pRedisPHP->SetUserFriendsGroupResNums(m_friendsGroupMsg.friendsGroupID, userID, "money", m_uScore[i], true); } else if (roomType == ROOM_TYPE_FG_VIP) { pRedisPHP->SetUserFriendsGroupResNums(m_friendsGroupMsg.friendsGroupID, userID, "fireCoin", m_uScore[i], true); } } //生成金币业绩 if (roomType == ROOM_TYPE_FRIEND && m_pDataManage->m_uNameID != 37550102) { char tableName[128] = ""; ConfigManage()->GetTableNameByDate(TBL_WEB_AGENT_PUMP_MONEY, tableName, sizeof(tableName)); BillManage()->WriteBill(&m_pDataManage->m_SQLDataManage, "INSERT INTO %s (userID,time,money,changeMoney,reason,roomID,friendsGroupID,rateMoney) VALUES(%d,%d,%lld,%lld,%d,%d,%d,%lld)", tableName, userID, currTime, pRedis->GetUserResNums(userID, "money"), m_uScore[i], RESOURCE_CHANGE_REASON_GAME_FINISHED, roomID, m_friendsGroupMsg.friendsGroupID, taxValue); } } // 人数过大会溢出 memcpy(simpleGradeInfo.userInfoList, userInfoList, sizeof(simpleGradeInfo.userInfoList)); // 战绩 if (m_gradeIDVec.size() > 0) { pRedis->SetPrivateDeskSimpleInfo(userIDVec, simpleGradeInfo, m_gradeIDVec); } // 不能超过512个字节 // 拼接 sprintf(userInfoList + strlen(userInfoList), "#%s#%s#", pumpInfoList, winCountInfoList); // 俱乐部相关 if (m_friendsGroupMsg.friendsGroupID > 0) { // 生成俱乐部战绩 BillManage()->WriteBill(&m_pDataManage->m_SQLDataManage, "INSERT INTO %s (friendsGroupID,userID,msgID,time,roomID,realPlayCount,playCount,playMode,passwd,userInfoList,roomType,srcType,roomTipType,roomTipTypeNums) \ VALUES(%d,%d,%d,%d,%d,%d,%d,%d,'%s','%s',%d,%d,%d,%d)", TBL_FG_RECORD_ACCOUNTS, m_friendsGroupMsg.friendsGroupID, m_masterID, 0, currTime, roomID, m_finishedGameCount, m_iBuyGameCount, m_playMode , m_szDeskPassWord, userInfoList, roomType, m_friendsGroupMsg.friendsGroupDeskNumber, m_roomTipType, m_roomTipTypeNums); // 生成俱乐部消耗 int costMoney = 0, costJewels = 0, moneyPump = 0, fireCoinPump = 0; if (buyDeskInfo.gameID > 0 && m_payType == PAY_TYPE_NORMAL) { if (buyDeskInfo.costResType == RESOURCE_TYPE_MONEY) { costMoney = buyDeskInfo.costNums; } else if (buyDeskInfo.costResType == RESOURCE_TYPE_JEWEL) { costJewels = buyDeskInfo.costNums; } } if (roomType == ROOM_TYPE_FG_VIP) { fireCoinPump = (int)llAllPumpScore; } else if (roomType == ROOM_TYPE_FRIEND) { moneyPump = (int)llAllPumpScore; } // 生成俱乐部消耗 BillManage()->WriteBill(&m_pDataManage->m_SQLDataManage, "INSERT INTO %s (friendsGroupID,time,userID,costMoney,costJewels,fireCoinRecharge,fireCoinExchange,moneyPump,fireCoinPump,passwd) \ VALUES(%d,%d,%d,%d,%d,%d,%d,%d,%d,'%s')", TBL_FG_COST_ACCOUNTS, m_friendsGroupMsg.friendsGroupID, currTime, m_masterID, costMoney, costJewels, 0, 0, moneyPump, fireCoinPump, m_szDeskPassWord); } //把剩余金币返回给群主 UserData userData; llAllPumpScore -= llReturnMoney; if (llAllPumpScore > 0 && roomType == ROOM_TYPE_FRIEND && m_friendsGroupMsg.friendsGroupID > 0 && pRedis->GetUserData(m_masterID, userData)) { userData.money += llAllPumpScore; pRedis->SetUserMoneyEx(m_masterID, llAllPumpScore, true, RESOURCE_CHANGE_REASON_GOLD_ROOM_PUMP, roomID, 0, 0, m_friendsGroupMsg.friendsGroupID); // 通知金币变化 m_pDataManage->SendResourcesChangeToLogonServer(m_masterID, RESOURCE_TYPE_MONEY, userData.money, RESOURCE_CHANGE_REASON_GOLD_ROOM_PUMP, llAllPumpScore); } char tableName[128] = ""; ConfigManage()->GetTableNameByDate(TBL_STATI_GAME_RECORD_INFO, tableName, sizeof(tableName)); // 生成游戏记录 BillManage()->WriteBill(&m_pDataManage->m_SQLDataManage, "INSERT INTO %s (passwd,deskIdx,roomID,createTime,beginTime,finishedTime,userIDList) VALUES('%s',%d,%d,%d,%d,%d,'%s')", tableName, m_szDeskPassWord, m_deskIdx, roomID, (int)privateDeskInfo.createTime, (int)m_beginTime, currTime, userInfoList); } // 清理房间数据 ClearAllData(privateDeskInfo); } bool CGameDesk::ChangeUserPointPrivate(int *arPoint, bool *bCut, char *pVideoCode, bool bGrade, char * gameData) { if (NULL == arPoint) { return false; } long long llArPont[MAX_PLAYER_GRADE] = { 0 }; for (int i = 0; i < m_iConfigCount; i++) { llArPont[i] = arPoint[i]; } return ChangeUserPointPrivate(llArPont, bCut, pVideoCode, bGrade, gameData); } bool CGameDesk::ChangeUserPointPrivate(long long *arPoint, bool *bCut, char *pVideoCode, bool bGrade, char * gameData) { if (!arPoint) { ERROR_LOG("invalid arPoint"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("redis initialized failed"); return false; } LoaderNotifyUserGrade userGrade; char userInfoList[512] = ""; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } pRedis->SetUserTotalGameCount(userID); if (arPoint[i] > 0) { pRedis->SetUserWinCount(userID); m_gameWinCount[i] ++; } m_uScore[i] += arPoint[i]; userGrade.grade[i] = (int)m_uScore[i]; sprintf(userInfoList + strlen(userInfoList), "%d,%lld|", userID, arPoint[i]); } m_finishedTime = time(NULL); BroadcastDeskData(&userGrade, sizeof(userGrade), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GRADE); if (bGrade && !AddDeskGrade(pVideoCode, gameData, userInfoList)) { return false; } return true; } bool CGameDesk::ChangeUserPoint(int *arPoint, bool *bCut, long long * rateMoney/* = NULL*/) { if (NULL == arPoint) { return false; } long long llArPont[MAX_PEOPLE] = { 0 }; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { llArPont[i] = arPoint[i]; } return ChangeUserPoint(llArPont, bCut, rateMoney); } bool CGameDesk::ChangeUserPoint(long long *arPoint, bool *bCut, long long * rateMoney/* = NULL*/) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } //专门计算输赢和抽水 long long currSystemTaxMoney = 0; long long currSystemTaxRobotMoney = 0; long long i64RealPeopleWinMoney = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } //更新内存金币 long long llRedisMoney = pRedis->GetUserResNums(userID, "money"); if (llRedisMoney != pUser->money) { ERROR_LOG("内存金币和redis金币不一致,userID=%d,redisMoney=%lld,memMoney=%lld", userID, llRedisMoney, pUser->money); pUser->money = llRedisMoney; } if (!pUser->isVirtual) { pRedis->SetUserTotalGameCount(userID); } long long userWinMoney = arPoint[i]; long long taxValue = 0; if (rateMoney && rateMoney[i] > 0) { taxValue = rateMoney[i]; currSystemTaxMoney += taxValue; } if (pUser->isVirtual) { currSystemTaxRobotMoney += taxValue; } else { i64RealPeopleWinMoney += userWinMoney; } if (arPoint[i] > 0 && !pUser->isVirtual) { pRedis->SetUserWinCount(userID); } pRedis->SetUserMoneyEx(userID, userWinMoney, true, RESOURCE_CHANGE_REASON_GAME_FINISHED, m_pDataManage->GetRoomID(), taxValue, pUser->isVirtual, m_friendsGroupMsg.friendsGroupID, GetRoomType()); pUser->money += userWinMoney; if (pUser->money < 0) { pUser->money = 0; } UserSimpleInfo msg; if (!MakeUserSimpleInfo((BYTE)i, msg)) { continue; } if (GetRoomSort() == ROOM_SORT_NORMAL || GetRoomSort() == ROOM_SORT_SCENE) { BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MONEY); } else { SendGameData((BYTE)i, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MONEY, 0); } } m_finishedTime = time(NULL); // 统计系统输赢 long long llGameWinMoney = i64RealPeopleWinMoney + (currSystemTaxMoney - currSystemTaxRobotMoney); if (llGameWinMoney != 0) { pRedis->SetRoomGameWinMoney(m_pDataManage->GetRoomID(), -llGameWinMoney, true); } // 系统抽水 if (currSystemTaxMoney - currSystemTaxRobotMoney > 0) { pRedis->SetRoomPercentageWinMoney(m_pDataManage->GetRoomID(), currSystemTaxMoney - currSystemTaxRobotMoney, true); } // 统计输赢场次,直接写到数据库中 if (llGameWinMoney != 0) { char tableName[128] = ""; ConfigManage()->GetTableNameByDate(TBL_STATI_ROOM_WIN_COUNT, tableName, sizeof(tableName)); BillManage()->WriteBill(&m_pDataManage->m_SQLDataManage, "INSERT INTO %s (time,roomID,gameID,runGameCount,winMoney,taxMoney,friendsGroupID,platformCtrlPercent,ctrlParamInfo) VALUES(%lld,%d,%d,%d,%lld,%lld,%d,%lld,'%s')", tableName, m_finishedTime, m_pDataManage->GetRoomID(), m_pDataManage->m_uNameID, m_iRunGameCount, -llGameWinMoney, currSystemTaxMoney - currSystemTaxRobotMoney, m_friendsGroupMsg.friendsGroupID, pRedis->GetRoomPoolData(m_pDataManage->GetRoomID(), "platformCtrlPercent"), m_ctrlParmRecordInfo.c_str()); } return true; } bool CGameDesk::ChangeUserBage(BYTE deskStation, char * gameData, int changeNum, bool add) { if (!gameData) { return false; } //机器人不用背包 if (IsVirtual(deskStation)) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } if (changeNum == 0) { return true; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { return false; } pRedis->SetUserBag(userID, gameData, changeNum, add); return true; } bool CGameDesk::ChangeUserPoint(BYTE deskStation, long long point, long long rateMoney, bool notify/* = true*/) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } if (point == 0) { return true; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { return false; } if (rateMoney < 0) { rateMoney = 0; } pUser->money += point; if (pUser->money < 0) { pUser->money = 0; } if (pUser->isVirtual) { pRedis->SetUserMoney(userID, pUser->money); } else { pRedis->SetUserMoneyEx(userID, point, true, RESOURCE_CHANGE_REASON_GAME_FINISHED, m_pDataManage->GetRoomID(), rateMoney, pUser->isVirtual, m_friendsGroupMsg.friendsGroupID, GetRoomType()); } if (notify) { UserSimpleInfo msg; if (!MakeUserSimpleInfo(deskStation, msg)) { return false; } if (GetRoomSort() == ROOM_SORT_NORMAL || GetRoomSort() == ROOM_SORT_SCENE) { BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MONEY); } else { SendGameData(deskStation, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MONEY, 0); } } //统计系统输赢 if (!pUser->isVirtual) { pRedis->SetRoomGameWinMoney(m_pDataManage->GetRoomID(), -point, true); } // 系统抽水 if (!pUser->isVirtual && rateMoney > 0) { pRedis->SetRoomPercentageWinMoney(m_pDataManage->GetRoomID(), rateMoney, true); } return true; } bool CGameDesk::ChangeUserFireCoin(int *arPoint, char *pVideoCode /*= NULL*/, bool bGrade/* = false*/, char * gameData/* = NULL*/) { if (NULL == arPoint) { return false; } long long llArPont[MAX_PLAYER_GRADE] = { 0 }; for (int i = 0; i < m_iConfigCount; i++) { llArPont[i] = arPoint[i]; } return ChangeUserFireCoin(llArPont, pVideoCode, bGrade, gameData); } bool CGameDesk::ChangeUserFireCoin(long long *arPoint, char *pVideoCode/* = NULL*/, bool bGrade/* = false*/, char * gameData/* = NULL*/) { if (m_friendsGroupMsg.friendsGroupID <= 0) { ERROR_LOG("非俱乐部房间禁止更改火币"); return false; } if (!arPoint) { ERROR_LOG("invalid arPoint"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("redis initialized failed"); return false; } CRedisPHP* pRedisPHP = m_pDataManage->GetRedisPHP(); if (!pRedisPHP) { ERROR_LOG("pRedisPHP initialized failed"); return false; } LoaderNotifyUserGrade userGrade; char userInfoList[512] = ""; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } pRedis->SetUserTotalGameCount(userID); long long userWinMoney = arPoint[i]; if (userWinMoney > 0) { pRedis->SetUserWinCount(userID); m_gameWinCount[i] ++; } // 修改redis和内存的值 m_uScore[i] += userWinMoney; pUser->fireCoin += (int)userWinMoney; pRedisPHP->SetUserFriendsGroupMoney(m_friendsGroupMsg.friendsGroupID, userID, userWinMoney, true, RESOURCE_CHANGE_REASON_GAME_FINISHED, m_pDataManage->GetRoomID()); userGrade.grade[i] = (int)pUser->fireCoin; sprintf(userInfoList + strlen(userInfoList), "%d,%lld|", userID, userWinMoney); } BroadcastDeskData(&userGrade, sizeof(userGrade), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GRADE); m_finishedTime = time(NULL); if (bGrade && !AddDeskGrade(pVideoCode, gameData, userInfoList)) { return false; } return true; } bool CGameDesk::ChangeUserPointGoldRoom(int *arPoint, char *pVideoCode/* = NULL*/, bool bGrade /*= false*/, char * gameData/* = NULL*/, long long * rateMoney/* = NULL*/) { if (NULL == arPoint) { return false; } long long llArPont[MAX_PLAYER_GRADE] = { 0 }; for (int i = 0; i < m_iConfigCount; i++) { llArPont[i] = arPoint[i]; } return ChangeUserPointGoldRoom(llArPont, pVideoCode, bGrade, gameData, rateMoney); } bool CGameDesk::ChangeUserPointGoldRoom(long long *arPoint, char *pVideoCode /*= NULL*/, bool bGrade/* = false*/, char * gameData/* = NULL*/, long long * rateMoney/* = NULL*/) { if (!arPoint) { ERROR_LOG("invalid arPoint"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } //专门计算输赢和抽水 long long currSystemTaxMoney = 0; long long currSystemTaxRobotMoney = 0; long long i64RealPeopleWinMoney = 0; char userInfoList[512] = ""; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } //更新内存金币 long long llRedisMoney = pRedis->GetUserResNums(userID, "money"); if (llRedisMoney != pUser->money) { ERROR_LOG("内存金币和redis金币不一致,userID=%d,redisMoney=%lld,memMoney=%lld", userID, llRedisMoney, pUser->money); pUser->money = llRedisMoney; } pRedis->SetUserTotalGameCount(userID); long long userWinMoney = arPoint[i]; if (userWinMoney > 0) { pRedis->SetUserWinCount(userID); m_gameWinCount[i] ++; } long long taxValue = 0; if (rateMoney && rateMoney[i] > 0) { taxValue = rateMoney[i]; currSystemTaxMoney += taxValue; } if (pUser->isVirtual) { currSystemTaxRobotMoney += taxValue; } else { i64RealPeopleWinMoney += userWinMoney; } pRedis->SetUserMoneyEx(userID, userWinMoney, true, RESOURCE_CHANGE_REASON_GAME_FINISHED, m_pDataManage->GetRoomID(), taxValue, pUser->isVirtual, m_friendsGroupMsg.friendsGroupID); pUser->money += userWinMoney; if (pUser->money < 0) { pUser->money = 0; } m_uScore[i] += userWinMoney; sprintf(userInfoList + strlen(userInfoList), "%d,%lld|", userID, userWinMoney); if (userWinMoney == 0) //没有输赢,不用发送数据 { continue; } UserSimpleInfo msg; if (!MakeUserSimpleInfo((BYTE)i, msg)) { continue; } BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MONEY); } m_finishedTime = time(NULL); if (bGrade && !AddDeskGrade(pVideoCode, gameData, userInfoList)) { return false; } //统计系统输赢 long long llGameWinMoney = i64RealPeopleWinMoney + (currSystemTaxMoney - currSystemTaxRobotMoney); if (llGameWinMoney != 0) { pRedis->SetRoomGameWinMoney(m_pDataManage->GetRoomID(), -llGameWinMoney, true); } // 系统抽水 if (currSystemTaxMoney - currSystemTaxRobotMoney > 0) { pRedis->SetRoomPercentageWinMoney(m_pDataManage->GetRoomID(), currSystemTaxMoney - currSystemTaxRobotMoney, true); } return true; } bool CGameDesk::ChangeUserPointJewelsRoom(long long *arPoint, char *pVideoCode /*= NULL*/, bool bGrade /*= false*/, char * gameData/* = NULL*/, long long * rateJewels/* = NULL*/) { if (!arPoint) { ERROR_LOG("invalid arPoint"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } char userInfoList[512] = ""; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } //更新内存钻石 int iRedisJewels = (int)pRedis->GetUserResNums(userID, "jewels"); if (iRedisJewels != pUser->jewels) { ERROR_LOG("内存钻石和redis钻石不一致,userID=%d,redis=%d,mem=%d", userID, iRedisJewels, pUser->jewels); pUser->jewels = iRedisJewels; } pRedis->SetUserTotalGameCount(userID); int userWinJewels = (int)arPoint[i]; if (userWinJewels > 0) { pRedis->SetUserWinCount(userID); } pRedis->SetUserJewelsEx(userID, userWinJewels, true, RESOURCE_CHANGE_REASON_GAME_FINISHED, m_pDataManage->GetRoomID(), rateJewels == NULL || rateJewels[i] < 0 ? 0 : (int)rateJewels[i], pUser->isVirtual, m_friendsGroupMsg.friendsGroupID); pUser->jewels += userWinJewels; if (pUser->jewels < 0) { pUser->jewels = 0; } if (bGrade && i < MAX_PLAYER_GRADE) { if (userWinJewels > 0) { m_gameWinCount[i] ++; } m_uScore[i] += userWinJewels; sprintf(userInfoList + strlen(userInfoList), "%d,%d|", userID, userWinJewels); } if (userWinJewels == 0) //没有输赢,不用发送数据 { continue; } UserSimpleInfo msg; if (!MakeUserSimpleInfo((BYTE)i, msg)) { continue; } BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_JEWELS); } m_finishedTime = time(NULL); if (bGrade && !AddDeskGrade(pVideoCode, gameData, userInfoList)) { return false; } return true; } bool CGameDesk::ChangeUserPointJewelsRoom(int *arPoint, char *pVideoCode /*= NULL*/, bool bGrade/* = false*/, char * gameData/* = NULL*/, long long * rateJewels/* = NULL*/) { if (NULL == arPoint) { return false; } long long llArPont[MAX_PEOPLE] = { 0 }; for (int i = 0; i < m_iConfigCount; i++) { llArPont[i] = arPoint[i]; } return ChangeUserPointJewelsRoom(llArPont, pVideoCode, bGrade, gameData, rateJewels); } bool CGameDesk::SendWatchData(void * pData, int size, int mainID, int assistID, int handleCode) { if (GetRoomType() == ROOM_TYPE_MATCH && m_matchWatchUserID.size() > 0) { for (auto iter = m_matchWatchUserID.begin(); iter != m_matchWatchUserID.end(); ++iter) { GameUserInfo *pUser = m_pDataManage->GetUser(*iter); if (pUser) { m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, pData, size, mainID, assistID, handleCode, *iter); } } } if (m_watchUserInfoSet.size() <= 0) { return true; } auto iter = m_watchUserInfoSet.begin(); for (; iter != m_watchUserInfoSet.end(); ++iter) { const WatchUserInfo& info = *iter; int userID = info.userID; m_pDataManage->SendData(userID, pData, size, mainID, assistID, handleCode); } return true; } bool CGameDesk::SendGameMessage(BYTE deskStation, const char * lpszMessage, int wType/* = SMT_EJECT*/) { if (!lpszMessage) { return false; } LoaderNotifyERRMsg msg; int sizeCount = strlen(lpszMessage); if (sizeCount == 0 || sizeCount >= sizeof(msg.notify)) { return true; } msg.msgType = wType; msg.sizeCount = sizeCount; memcpy(msg.notify, lpszMessage, sizeCount); int userID = GetUserIDByDeskStation(deskStation); if (userID > 0) { m_pDataManage->SendData(userID, &msg, 8 + msg.sizeCount, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_ERR_MSG, 0); } return true; } // 广播消息,设定不广播特定玩家 void CGameDesk::BroadcastGameMessageExcept(BYTE deskStation, const char * lpszMessage, int wType/* = SMT_EJECT*/) { if (!lpszMessage) { return; } LoaderNotifyERRMsg msg; int sizeCount = strlen(lpszMessage); if (sizeCount == 0 || sizeCount >= sizeof(msg.notify)) { return; } msg.msgType = wType; msg.sizeCount = sizeCount; memcpy(msg.notify, lpszMessage, sizeCount); for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].isVirtual || i == deskStation) { continue; } int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { m_pDataManage->SendData(userID, &msg, 8 + msg.sizeCount, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_ERR_MSG, 0); } } } bool CGameDesk::GetVideoCode(char *pCode, int iLen) { if (!pCode || iLen <= 0) { return false; } char buf[64] = ""; SYSTEMTIME sys; GetLocalTime(&sys); sprintf(buf, "%04d%02d%02d%02d%02d%02d%03d", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds); memcpy(pCode, buf, iLen); return true; } bool CGameDesk::UserSitDesk(GameUserInfo* pUser) { int roomType = GetRoomType(); if (roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) { return PrivateSitDeskLogic(pUser); } else if (roomType == ROOM_TYPE_MATCH) { return MatchRoomSitDeskLogic(pUser); } else { return MoneySitDeskLogic(pUser); } } bool CGameDesk::HandleFrameMessage(BYTE deskStation, unsigned int assistID, void * pData, int size, bool bWatchUser/* = false*/) { switch (assistID) { // 房间信息 case MSG_ASS_LOADER_DESK_INFO: { return OnHandleUserRequestDeskInfo(deskStation); } //游戏状态 case MSG_ASS_LOADER_GAME_INFO: { return OnHandleUserRequestGameInfo(deskStation); } case MSG_ASS_LOADER_DESK_USERINFO: { return OnHandleUserRequestALLUserInfo(deskStation); } case MSG_ASS_LOADER_DESK_ONE_USERINFO: { return OnHandleUserRequestOneUserInfo(deskStation, pData, size); } default: break; } return false; } bool CGameDesk::UserLeftDesk(GameUserInfo * pUser) { if (!pUser) { return false; } // 增加百人类相关逻辑 TODO int roomSort = GetRoomSort(); int roomType = GetRoomType(); if (roomSort == ROOM_SORT_NORMAL || roomSort == ROOM_SORT_SCENE) { if (roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FG_VIP) { return PrivateUserLeftDeskLogic(pUser); } else if (roomType == ROOM_TYPE_MATCH) { return MatchRoomUserLeftDeskLogic(pUser); } else { return MoneyUserLeftDeskLogic(pUser); } } else if (roomSort == ROOM_SORT_HUNDRED) { return HundredGameUserLeftLogic(pUser); } return true; } bool CGameDesk::OnHandleUserRequestDeskInfo(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } // 发送桌子基本信息 SendDeskBaseInfo(deskStation); // 发送解散信息 SendDismissData(); return true; } bool CGameDesk::OnHandleUserRequestGameInfo(BYTE deskStation) { bool isWatcher = false; if (deskStation >= MAX_PEOPLE) { isWatcher = true; } //发送用户游戏状态(游戏实现) return OnGetGameStation(deskStation, -1, isWatcher); } bool CGameDesk::OnHandleUserRequestALLUserInfo(BYTE deskStation) { SendAllDeskUserInfo(deskStation); return true; } bool CGameDesk::OnHandleUserRequestOneUserInfo(BYTE deskStation, void* pData, int size) { if (size != sizeof(LoaderRequestOneUserSimpleInfo)) { return false; } LoaderRequestOneUserSimpleInfo* pMessage = (LoaderRequestOneUserSimpleInfo*)pData; if (!pMessage) { return false; } UserSimpleInfo userInfo; if (!MakeUserSimpleInfo(pMessage->deskStation, userInfo)) { return false; } SendGameData(deskStation, &userInfo, sizeof(userInfo), MSG_MAIN_LOADER_FRAME, MSG_ASS_LOADER_DESK_ONE_USERINFO, 0); return true; } bool CGameDesk::OnHandleUserRequestDissmiss(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { ERROR_LOG("GetUserIDByDeskStation failed deskStation: %d", deskStation); return false; } // 桌子是否有效 if (!m_enable) { ERROR_LOG("invalid desk status m_enable=%d", m_enable); return false; } // 已经有人申请解散了 if (m_reqDismissDeskStation != INVALID_DESKSTATION) { ERROR_LOG("deskStation: %d already request dismiss", m_reqDismissDeskStation); return true; } if (!m_isBegin) { // 还未开始之前只能房主解散 if (userID != m_masterID) { ERROR_LOG("user request dismiss before playing game but is not master deskStation:%d userID:%d m_masterID:%d", deskStation, userID, m_masterID); return false; } } //判断当前人数 int currUserCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID > 0) { currUserCount++; } } // 如果桌子还未开始游戏,那么直接解散 if (!m_isBegin || currUserCount <= 1) { // 直接解散(不用进入解散状态) OnDeskDissmissFinishSendData(); OnDeskSuccessfulDissmiss(true); return true; } DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; deskUserInfo.dismissType = DISMISS_TYPE_AGREE; // 记录相关信息 m_isDismissStatus = true; m_reqDismissDeskStation = deskStation; m_reqDismissTime = time(NULL); // 广播这件事 BroadcastDismissData(); // 启动解散定时器 SetTimer(IDT_AGREE_DISMISS_DESK, CFG_DISMISS_DESK_WAIT_TIME * 1000); return true; } bool CGameDesk::OnHandleUserAnswerDissmiss(BYTE deskStation, void* pData, int size) { if (size != sizeof(LoaderRequestAnswerDismiss)) { return false; } LoaderRequestAnswerDismiss* pMessage = (LoaderRequestAnswerDismiss*)pData; if (!pMessage) { return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } if (!m_enable) { SendGameData(deskStation, NULL, 0, MSG_MAIN_LOADER_DESKDISSMISS, MSG_ASS_LOADER_ANSWER_DESKDISMISS, ERROR_INVALID_DESK); return false; } // 是否处于待解散状态 if (!m_isDismissStatus) { SendGameData(deskStation, NULL, 0, MSG_MAIN_LOADER_DESKDISSMISS, MSG_ASS_LOADER_ANSWER_DESKDISMISS, ERROR_DESK_NOT_INDISMISSS); return false; } if (m_reqDismissDeskStation == INVALID_DESKSTATION) { return false; } // 是否已经操作过了 DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; if (deskUserInfo.dismissType != DISMISS_TYPE_DEFAULT) { return false; } if (pMessage->isAgree == true) { return OnUserAgreeDismiss(deskStation); } else { return OnDeskDismissFailed(); } return false; } bool CGameDesk::OnWatchUserOffline(int userID) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } auto iter = m_watchUserInfoSet.begin(); for (; iter != m_watchUserInfoSet.end(); ++iter) { if (iter->userID == userID) { break; } } if (iter == m_watchUserInfoSet.end()) { ERROR_LOG("watcher list find user(%d) failed", userID); return false; } m_watchUserInfoSet.erase(iter); int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); pRedis->SetPrivateDeskCurrWatchUserCount(deskMixID, (int)m_watchUserInfoSet.size()); m_pDataManage->RemoveWatchUser(userID); return true; } BYTE CGameDesk::AllocWatcherDeskStation() { int tempList[INVALID_DESKSTATION] = { 0 }; for (auto iter = m_watchUserInfoSet.begin(); iter != m_watchUserInfoSet.end(); ++iter) { const WatchUserInfo& info = *iter; if (info.deskStation < INVALID_DESKSTATION) { tempList[info.deskStation] = 1; } } for (BYTE i = MAX_PEOPLE; i < INVALID_DESKSTATION; i++) { if (tempList[i] == 0) { return i; } } return INVALID_DESKSTATION; } bool CGameDesk::IsWatcher(int userID) { auto iter = m_watchUserInfoSet.begin(); for (; iter != m_watchUserInfoSet.end(); ++iter) { const WatchUserInfo& info = *iter; if (info.userID == userID) { return true; } } return false; } bool CGameDesk::OnHandleTalkMessage(BYTE deskStation, void * pData, int size) { if (size <= 4) { return false; } LoaderRequestTalk* pMessage = (LoaderRequestTalk*)pData; if (!pMessage) { return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } if (pMessage->sizeCount + 4 != size || pMessage->sizeCount >= 1024) { ERROR_LOG("聊天字节数量发送错误,userID=%d,pMessage->sizeCount=%d", userID, pMessage->sizeCount); return true; } char words[1024] = ""; memcpy(words, pMessage->words, pMessage->sizeCount); if (CUtil::IsContainDirtyWord(words) == true) { SendGameData(deskStation, 0, NULL, MSG_MAIN_LOADER_VOICEANDTALK, MSG_ASS_LOADER_TALK, ERROR_HAVE_DIRTYWORD); return true; } LoaderNotifyTalk msg; msg.userID = userID; memcpy(msg.words, words, sizeof(words)); // 计算发送字节数量 msg.sizeCount = min(strlen(msg.words) + 1, sizeof(msg.words)); int iSendSize = 8 + msg.sizeCount; BroadcastDeskData(&msg, iSendSize, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_TALK, false); return true; } bool CGameDesk::OnHandleVoiceMessage(BYTE deskStation, void * pData, int size) { if (size != sizeof(LoaderRequestVoice)) { return false; } LoaderRequestVoice* pMessage = (LoaderRequestVoice*)pData; if (!pMessage) { return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } LoaderNotifyVoice msg; msg.userID = userID; msg.voiceID = pMessage->voiceID; BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_VOICE, false); return true; } bool CGameDesk::OnHandleUserRequestMagicExpress(BYTE deskStation, void* pData, int size) { if (size != sizeof(LoaderRequestMagicExpress)) { return false; } LoaderRequestMagicExpress* pMessage = (LoaderRequestMagicExpress*)pData; if (!pMessage) { return false; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { ERROR_LOG("GetUserIDByDeskStation failed deskStation=%d", deskStation); return false; } int targetUserID = pMessage->userID; if (targetUserID == userID) { return true; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID=%d", userID); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } OtherConfig otherConfig; if (!pRedis->GetOtherConfig(otherConfig)) { otherConfig = ConfigManage()->GetOtherConfig(); } int roomType = GetRoomType(); if (roomType == ROOM_TYPE_MATCH) { otherConfig.useMagicExpressCostMoney = 0; } if (otherConfig.useMagicExpressCostMoney > 0) { if (roomType == ROOM_TYPE_GOLD) { RoomBaseInfo roomBasekInfo; RoomBaseInfo* pRoomBaseInfo = NULL; if (pRedis->GetRoomBaseInfo(m_pDataManage->GetRoomID(), roomBasekInfo)) { pRoomBaseInfo = &roomBasekInfo; } else { pRoomBaseInfo = ConfigManage()->GetRoomBaseInfo(m_pDataManage->GetRoomID()); } if (pRoomBaseInfo && pRoomBaseInfo->minPoint > 0 && pUser->money - otherConfig.useMagicExpressCostMoney < pRoomBaseInfo->minPoint) { SendGameMessage(deskStation, "资源不足,无法发魔法表情"); return true; } } if (pUser->money < otherConfig.useMagicExpressCostMoney) { SendGameMessage(deskStation, "资源不足,无法发魔法表情"); return true; } // 扣钱 long long newMoney = pUser->money - otherConfig.useMagicExpressCostMoney; pUser->money = newMoney; pRedis->SetUserMoneyEx(userID, -otherConfig.useMagicExpressCostMoney, true, RESOURCE_CHANGE_REASON_MAGIC_EXPRESS, m_pDataManage->GetRoomID(), 0, pUser->isVirtual, m_friendsGroupMsg.friendsGroupID); if (pUser->isVirtual) { //将金币回收到奖池 //pRedis->SetRoomPoolMoney(m_pDataManage->GetRoomID(), otherConfig.useMagicExpressCostMoney, true); } else { //将金币放入其它方式赢钱 pRedis->SetRoomPoolData(m_pDataManage->GetRoomID(), "otherWinMoney", otherConfig.useMagicExpressCostMoney, true); } // 通知钱变化 NotifyUserResourceChange(userID, RESOURCE_TYPE_MONEY, newMoney, -otherConfig.useMagicExpressCostMoney); } // 广播使用魔法表情的通知 LoaderNotifyMagicExpress msg; msg.magicType = pMessage->magicType; msg.srcUserID = userID; msg.targetUserID = targetUserID; BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MAGICEXPRESS, false); return true; } bool CGameDesk::OnHandleUserRequestAuto(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; if (deskUserInfo.isAuto == false) { deskUserInfo.isAuto = true; LoaderNotifyIsAuto msg; msg.isAuto = true; msg.userID = userID; BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_ISAUTO, false); } return true; } bool CGameDesk::OnHandleUserRequestCancelAuto(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; deskUserInfo.isAuto = false; LoaderNotifyIsAuto msg; msg.isAuto = false; msg.userID = userID; BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_ISAUTO, false); return true; } void CGameDesk::MakeAllUserInfo(char* buf, int size, int& realSize) { int roomType = GetRoomType(); // 遍历寻找所有玩家的信息 std::vector<int> temp; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { temp.push_back(userID); } } int pos = 0; int* p = (int *)buf; *p = 0; pos += sizeof(int); for (size_t i = 0; i < temp.size(); i++) { int userID = temp[i]; GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); continue; } if (pos + sizeof(UserSimpleInfo) > size - sizeof(NetMessageHead)) { break; } UserSimpleInfo* pUserInfo = (UserSimpleInfo*)(buf + pos); if (pUserInfo) { pUserInfo->userID = userID; memcpy(pUserInfo->name, pUser->name, sizeof(pUser->name)); memcpy(pUserInfo->headURL, pUser->headURL, sizeof(pUser->headURL)); pUserInfo->isOnline = pUser->IsOnline; pUserInfo->deskStation = pUser->deskStation; pUserInfo->playStatus = pUser->playStatus; pUserInfo->iDeskIndex = pUser->deskIdx; memcpy(pUserInfo->longitude, pUser->longitude, sizeof(pUserInfo->longitude)); memcpy(pUserInfo->latitude, pUser->latitude, sizeof(pUserInfo->latitude)); memcpy(pUserInfo->ip, pUser->ip, sizeof(pUserInfo->ip)); memcpy(pUserInfo->address, pUser->address, sizeof(pUserInfo->address)); memcpy(pUserInfo->motto, pUser->motto, sizeof(pUserInfo->motto)); pUserInfo->sex = pUser->sex; pUserInfo->isAuto = IsAuto(pUser->deskStation); pUserInfo->money = pUser->money; pUserInfo->jewels = pUser->jewels; if (roomType == ROOM_TYPE_PRIVATE) { pUserInfo->score = (long)m_uScore[pUser->deskStation]; } else if (roomType == ROOM_TYPE_FG_VIP) { pUserInfo->score = (long)pUser->fireCoin; } else if (roomType == ROOM_TYPE_MATCH) { pUserInfo->score = (long)pUser->matchSocre; } pos += sizeof(UserSimpleInfo); *p = *p + 1; } } realSize = pos; } void CGameDesk::HundredMakeAllUserInfo(char* buf, int size, int& realSize) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return; } // 遍历寻找所有玩家的信息 std::vector<long> temp; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { temp.push_back(userID); } } int pos = 0; int* p = (int *)buf; *p = 0; pos += sizeof(int); for (size_t i = 0; i < temp.size(); i++) { int userID = temp[i]; GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); continue; } if (pos + sizeof(HundredGameUserSimpleInfo) > size - sizeof(NetMessageHead)) { break; } HundredGameUserSimpleInfo* pUserInfo = (HundredGameUserSimpleInfo*)(buf + pos); if (pUserInfo) { pUserInfo->userID = userID; pUserInfo->isOnline = pUser->IsOnline; pUserInfo->deskStation = pUser->deskStation; pUserInfo->userStatus = pUser->playStatus; pUserInfo->isAuto = IsAuto(pUser->deskStation); pUserInfo->money = pUser->money; pos += sizeof(HundredGameUserSimpleInfo); *p = *p + 1; } } realSize = pos; } bool CGameDesk::OnUserRequsetGameBegin(int userID) { //// 只要是房主,就能开始(房主能否在外面(比如大厅)控制开始todo) //if (userID != m_masterID) //{ // ERROR_LOG("user request gamebegin but is not master userID(%d) m_masterID(%d)", userID, m_masterID); // return false; //} if (m_isBegin == true) { ERROR_LOG("game is already begin deskIdx(%d)", m_deskIdx); return false; } int errCode = 0; if (CanBeginGame() == true) { GameBegin(0); } else { errCode = ERROR_GAME_CANNOT_GAMEBEGIN; } m_pDataManage->SendData(userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_GAME_BEGIN, errCode); return true; } bool CGameDesk::OnWatcherLeftDesk(GameUserInfo* pUser, const PrivateDeskInfo & deskInfo) { if (!pUser) { ERROR_LOG("invalid pUser is null"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } auto iter = m_watchUserInfoSet.begin(); for (; iter != m_watchUserInfoSet.end(); ++iter) { const WatchUserInfo& info = *iter; if (pUser->userID == info.userID) { break; } } if (iter == m_watchUserInfoSet.end()) { ERROR_LOG("user(%d) playstatus is watch but not in desk(%d) watcher list", pUser->userID, m_deskIdx); return false; } // 旁观者列表中移除玩家 m_watchUserInfoSet.erase(iter); // 修改缓存人数 int deskMixID = m_pDataManage->GetRoomID() * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; pRedis->SetPrivateDeskCurrWatchUserCount(deskMixID, m_watchUserInfoSet.size()); m_pDataManage->RemoveWatchUser(pUser->userID); return true; } bool CGameDesk::OnDeskUserLeftDesk(GameUserInfo* pUser, const PrivateDeskInfo& deskInfo) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } if (pUser->deskStation >= (BYTE)m_deskUserInfoVec.size()) { ERROR_LOG("user deskStation is invalid deskStation=%d,userID = %d", pUser->deskStation, pUser->userID); return false; } if (pUser->playStatus == USER_STATUS_STAND) { ERROR_LOG("玩家已经是站起状态 pUser->playStatus=%d,deskStation=%d,userID=%d", pUser->playStatus, pUser->deskStation, pUser->userID); return false; } if (m_bPlayGame) { ERROR_LOG("游戏中不能离开。deskStation=%d,userID=%d", pUser->deskStation, pUser->userID); SendGameMessage(pUser->deskStation, "游戏中不能离开"); return false; } int roomType = GetRoomType(); bool bIsRecord = false; if (m_isBegin && (roomType == ROOM_TYPE_FRIEND && pUser->money < m_RemoveMinPoint || roomType == ROOM_TYPE_FG_VIP && pUser->fireCoin < m_RemoveMinPoint)) { bIsRecord = true; } else { // 如果是游戏中则无法离开 if (m_isBegin) { ERROR_LOG("game is begin but user want left desk userID=%d", pUser->userID); SendGameMessage(pUser->deskStation, "游戏中不能离开"); return false; } } // 通知所有玩家 BroadcastUserLeftData(pUser->deskStation, REASON_KICKOUT_STAND); // 清理玩家桌子数据 m_deskUserInfoVec[pUser->deskStation].clear(); if (bIsRecord) { // 记录被清理的玩家数据 m_deskUserInfoVec[pUser->deskStation].leftRoomUser = pUser->userID; } // 清理玩家游戏数据 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; // 清除缓存中玩家数量 int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); int currDeskUserCount = deskInfo.currDeskUserCount - 1; pRedis->SetPrivateDeskCurrUserCount(deskMixID, currDeskUserCount); // 通知桌子人数变化 NotifyLogonBuyDeskInfoChange(m_masterID, currDeskUserCount, pUser->userID, 1, deskMixID); if ((roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_FG_VIP) && m_pDataManage->IsCanWatch() && m_autoBeginMode == 0) { // 第一局 if (m_iRunGameCount == 0 && CanBeginGame()) { SetBeginUser(); m_pDataManage->SendData(m_beginUserID, NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_CANBEGIN, 0); } if (m_iRunGameCount >= 1 && CanBeginGame()) { // 第一局之后的游戏不受房主控制 GameBegin(0); } } else { if (CanBeginGame()) { GameBegin(0); } } return true; } void CGameDesk::BroadcastDeskData(void * pData, int size, unsigned int mainID, unsigned int assistID, bool sendVirtual/* = true*/, unsigned int handleCode/* = 0*/) { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (!sendVirtual && m_deskUserInfoVec[i].isVirtual) { continue; } int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { m_pDataManage->SendData(userID, pData, size, mainID, assistID, handleCode); } } SendWatchData(pData, size, mainID, assistID, 0); } void CGameDesk::SendAllDeskUserInfo(BYTE deskStation) { char buf[MAX_TEMP_SENDBUF_SIZE] = ""; // 加入对拼接数据包长度的检查 int realSize = 0; if (GetRoomSort() == ROOM_SORT_NORMAL || GetRoomSort() == ROOM_SORT_SCENE) { MakeAllUserInfo(buf, sizeof(buf), realSize); SendGameData(deskStation, buf, realSize, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_ALL_USERINFO, 0); } else { HundredMakeAllUserInfo(buf, sizeof(buf), realSize); SendGameData(deskStation, buf, realSize, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_HUNDRED_ALL_USER, 0); } } void CGameDesk::SendDeskBaseInfo(BYTE deskStation) { if (GetRoomType() == ROOM_TYPE_GOLD || GetRoomType() == ROOM_TYPE_MATCH) { return; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { ERROR_LOG("GetUserIDByDeskStation failed %d", deskStation); return; } UserData masterData; if (!pRedis->GetUserData(m_masterID, masterData)) { ERROR_LOG("GetUserData failed: %d", m_masterID); return; } LoaderNotifyDeskInfo msg; msg.deskIdx = m_deskIdx; memcpy(msg.deskPasswd, m_szDeskPassWord, sizeof(m_szDeskPassWord)); msg.deskPasswdLen = 6; msg.masterID = m_masterID; memcpy(msg.masterName, masterData.name, sizeof(masterData.name)); msg.runGameCount = m_iRunGameCount; msg.totalGameCount = m_iBuyGameCount; msg.isDismissStatus = m_isDismissStatus; SendGameData(deskStation, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_BASEINFO, 0); // 处于解散状态的话,额外推送解散面板信息 if (m_isDismissStatus) { if (IsWatcher(userID) == false) { BroadcastDismissData(); } } } void CGameDesk::BroadcastDeskBaseInfo() { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { SendDeskBaseInfo((BYTE)i); } } } int CGameDesk::GetUserIDByDeskStation(BYTE deskStation) { if (deskStation == INVALID_DESKSTATION) { return 0; } if (deskStation < MAX_PEOPLE) { // 玩家 if (deskStation < m_deskUserInfoVec.size()) { return m_deskUserInfoVec[deskStation].userID; } } else { // 旁观者 for (auto iter = m_watchUserInfoSet.begin(); iter != m_watchUserInfoSet.end(); ++iter) { const WatchUserInfo& info = *iter; if (deskStation == info.deskStation) { return info.userID; } } } return 0; } BYTE CGameDesk::GetDeskStationByUserID(int userID) { if (userID <= 0) { return INVALID_DESKSTATION; } for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID == userID) { return (BYTE)i; } } return INVALID_DESKSTATION; } bool CGameDesk::GetUserData(BYTE deskStation, UserData & userData) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } bool ret = pRedis->GetUserData(userID, userData); if (!ret) { return false; } return true; } bool CGameDesk::GetUserData(BYTE deskStation, GameUserInfo & userData) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } if (!m_pDataManage) { return false; } GameUserInfo * pUser = m_pDataManage->GetUser(userID); if (!pUser) { return false; } userData = *pUser; return true; } int CGameDesk::GetRoomType() { if (m_pDataManage) { return m_pDataManage->m_InitData.iRoomType; } return ROOM_TYPE_PRIVATE; // 默认房卡场 } int CGameDesk::GetRoomSort() { if (m_pDataManage) { return m_pDataManage->m_InitData.iRoomSort; } return ROOM_SORT_NORMAL; } int CGameDesk::GetRoomLevel() { if (m_pDataManage) { return m_pDataManage->m_InitData.iRoomLevel; } return 0; } void CGameDesk::BroadcastUserSitData(BYTE deskStation) { UserSimpleInfo msg; if (!MakeUserSimpleInfo(deskStation, msg)) { return; } BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_SIT); } void CGameDesk::BroadcastUserSitDataExceptMyself(BYTE deskStation) { UserSimpleInfo msg; if (!MakeUserSimpleInfo(deskStation, msg)) { return; } for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i == deskStation && !m_deskUserInfoVec[i].isVirtual) { continue; } int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { m_pDataManage->SendData(userID, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_SIT, 0); } } } void CGameDesk::BroadcastUserSimpleInfo(BYTE deskStation) { UserSimpleInfo msg; if (!MakeUserSimpleInfo(deskStation, msg)) { return; } BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_INFO); } bool CGameDesk::BroadcastUserLeftData(BYTE deskStation, int reason) { LoaderNotifyUserLeft msg; msg.reason = reason; if (!MakeUserSimpleInfo(deskStation, msg.userInfo)) { return false; } BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_LEFT); if (IsGoldRoom() && m_pDataManage->IsCanCombineDesk() && !IsPlayGame(deskStation)) { BroadcastGameMessageExcept(deskStation, "有玩家离开游戏,请重新换桌"); } return true; } void CGameDesk::SendUserLeftData(BYTE deskStation, int reason) { LoaderNotifyUserLeft msg; msg.reason = reason; if (!MakeUserSimpleInfo(deskStation, msg.userInfo)) { return; } SendGameData(deskStation, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_LEFT, 0); } void CGameDesk::BroadcastUserAgreeData(BYTE deskStation) { UserSimpleInfo userInfo; if (!MakeUserSimpleInfo(deskStation, userInfo)) { return; } BroadcastDeskData(&userInfo, sizeof(userInfo), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_AGREE); } void CGameDesk::BroadcastUserOfflineData(BYTE deskStation) { UserSimpleInfo userInfo; if (!MakeUserSimpleInfo(deskStation, userInfo)) { return; } BroadcastDeskData(&userInfo, sizeof(userInfo), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_OFFLINE); } void CGameDesk::BroadcastUserKickoutData(BYTE deskStation) { UserSimpleInfo userInfo; if (!MakeUserSimpleInfo(deskStation, userInfo)) { return; } BroadcastDeskData(&userInfo, sizeof(userInfo), MSG_MAIN_LOADER_NOTIFY_USER, MSG_NTF_LOADER_DESK_USER_BE_KICKOUT); } void CGameDesk::ClearAllData(const PrivateDeskInfo& privateDeskInfo) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("GetRedis failed"); return; } int masterID = privateDeskInfo.masterID; if (masterID <= 0) { ERROR_LOG("无效的房主 masterID=%d,清理桌子失败", masterID); return; } int roomID = m_pDataManage->GetRoomID(); int deskMixID = roomID * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; // 清理玩家数据 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID=%d", pUser); continue; } // 设置为站起状态 pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; pUser->playStatus = USER_STATUS_STAND; // 彻底清除断线玩家的相关信息(在线的玩家需要发送登出) if (pUser->IsOnline == false) { m_pDataManage->RemoveOfflineUser(userID); } else { pRedis->SetUserRoomID(pUser->userID, 0); pRedis->SetUserDeskIdx(pUser->userID, INVALID_DESKIDX); } } // 清理桌子玩家 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { m_deskUserInfoVec[i].clear(); } // 清理旁观者数据 for (auto iter = m_watchUserInfoSet.begin(); iter != m_watchUserInfoSet.end(); ++iter) { m_pDataManage->RemoveWatchUser(iter->userID); } m_watchUserInfoSet.clear(); //填充俱乐部信息 m_friendsGroupMsg.friendsGroupID = privateDeskInfo.friendsGroupID; if (m_friendsGroupMsg.friendsGroupID != 0) { m_friendsGroupMsg.friendsGroupDeskNumber = privateDeskInfo.friendsGroupDeskNumber; } // 清除cache中桌子数据 pRedis->DelPrivateDeskRecord(deskMixID); // 清除房主的开房记录 pRedis->DelUserBuyDeskInfoInSet(masterID, privateDeskInfo.passwd); // 扣除房主购买桌子次数 if (privateDeskInfo.friendsGroupID == 0) { pRedis->SetUserBuyingDeskCount(masterID, -1, true); } // 清理临时战绩数据 m_gradeIDVec.clear(); // 通知大厅 NotifyLogonDeskDissmiss(privateDeskInfo); // 清理购买桌子数据 InitBuyDeskData(); // 清理解散数据 InitDismissData(); m_finishedGameCount = 0; m_autoBeginMode = 0; m_bGameStopJoin = 0; // 置为无效,可以复用 m_enable = false; //清理俱乐部数据 m_friendsGroupMsg.Init(); } bool CGameDesk::OnDeskDismissFailed() { // 清除定时器 KillTimer(IDT_AGREE_DISMISS_DESK); // 清除状态 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { m_deskUserInfoVec[i].dismissType = DISMISS_TYPE_DEFAULT; } InitDismissData(); // 通知前端 BroadcastDeskData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_DISMISS_FAILED); return true; } bool CGameDesk::OnUserAgreeDismiss(BYTE deskStation) { if (GetUserIDByDeskStation(deskStation) <= 0) { return false; } int roomType = GetRoomType(); DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; deskUserInfo.dismissType = DISMISS_TYPE_AGREE; // 广播这件事 BroadcastDismissData(); // 在线玩家数量 int onLineCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (pUser && pUser->IsOnline == true) { onLineCount++; } } // 同意解散玩家数量(在线) int agreeDismissCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; int dismissType = m_deskUserInfoVec[i].dismissType; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } //特殊房间特殊处理。金币房和火币房如果玩家金币不足也算是同意解散 if (m_pDataManage->m_uNameID != 37550102 && (roomType == ROOM_TYPE_FRIEND && pUser->money < m_RemoveMinPoint || roomType == ROOM_TYPE_FG_VIP && pUser->fireCoin < m_RemoveMinPoint)) { agreeDismissCount++; INFO_LOG("默认同意解散:userID=%d", userID); continue; } if (dismissType == DISMISS_TYPE_AGREE && pUser->IsOnline) { agreeDismissCount++; } } if (onLineCount > 0 && agreeDismissCount >= onLineCount) { // 解散 OnDeskDissmissFinishSendData(); OnDeskSuccessfulDissmiss(true); } return true; } void CGameDesk::MakeDismissData(char* buf, int& size) { if (!buf) { return; } int userCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID > 0) { userCount++; } } int pos = 0; // 申请者 BYTE* pDeskStation = (BYTE*)buf; *pDeskStation = m_reqDismissDeskStation; pos += sizeof(BYTE); // 解散剩余的时间 int* pLeftDismissTime = (int*)(buf + pos); *pLeftDismissTime = (int)(m_reqDismissTime + CFG_DISMISS_DESK_WAIT_TIME - time(NULL)); pos += sizeof(int); int* pCfgWaitDismissTime = (int*)(buf + pos); *pCfgWaitDismissTime = CFG_DISMISS_DESK_WAIT_TIME; pos += sizeof(int); // 玩家数量 int*pdeskUserCount = (int*)(buf + pos); *pdeskUserCount = userCount; pos += sizeof(int); // 人数太多缓冲区不够的问题 TODO for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { const DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID <= 0) { continue; } DeskDismissType *pDismissType = (DeskDismissType *)(buf + pos); if (pDismissType) { pDismissType->deskStation = (BYTE)i; pDismissType->dismissType = deskUserInfo.dismissType; pos += sizeof(DeskDismissType); } } size = pos; } void CGameDesk::BroadcastDismissData() { char buf[MAX_TEMP_SENDBUF_SIZE] = ""; int size = 0; MakeDismissData(buf, size); BroadcastDeskData(buf, size, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_DISMISS_INFO); } void CGameDesk::SendDismissData() { if (!m_isDismissStatus) { return; } char buf[MAX_TEMP_SENDBUF_SIZE] = ""; int size = 0; MakeDismissData(buf, size); BroadcastDeskData(buf, size, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_DISMISS_INFO); } void CGameDesk::SendLeftWaitAgreeData(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return; } const DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; LoaderNotifyWaitAgree msg; int leftWaitAgreeSecs = 0; if (!m_bPlayGame) { leftWaitAgreeSecs = int(GOLD_DESK_TIMEOUT_UNAGREE_KICKOUT_SECS + deskUserInfo.lastWaitAgreeTime - time(NULL)); } msg.cfgWaitAgreeSecs = GOLD_DESK_TIMEOUT_UNAGREE_KICKOUT_SECS; msg.leftWaitAgreeSecs = leftWaitAgreeSecs; m_pDataManage->SendData(userID, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_LEFT_WAITAGREE_TIME, 0); } bool CGameDesk::MakeUserSimpleInfo(BYTE deskStation, UserSimpleInfo & userInfo) { if (deskStation >= m_deskUserInfoVec.size()) { return false; } const DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; int userID = deskUserInfo.userID; if (userID <= 0) { return false; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser Fail userID=%d", userID); return false; } int roomType = GetRoomType(); userInfo.deskStation = deskStation; userInfo.isOnline = pUser->IsOnline; userInfo.userID = userID; memcpy(userInfo.headURL, pUser->headURL, sizeof(userInfo.headURL)); memcpy(userInfo.name, pUser->name, sizeof(userInfo.name)); userInfo.playStatus = pUser->playStatus; memcpy(userInfo.longitude, pUser->longitude, sizeof(userInfo.longitude)); memcpy(userInfo.latitude, pUser->latitude, sizeof(userInfo.latitude)); memcpy(userInfo.address, pUser->address, sizeof(userInfo.address)); memcpy(userInfo.ip, pUser->ip, sizeof(userInfo.ip)); userInfo.sex = pUser->sex; userInfo.isAuto = deskUserInfo.isAuto; userInfo.money = pUser->money; userInfo.jewels = pUser->jewels; userInfo.iDeskIndex = pUser->deskIdx; memcpy(userInfo.motto, pUser->motto, sizeof(userInfo.motto)); if (roomType == ROOM_TYPE_PRIVATE) { userInfo.score = (int)m_uScore[deskStation]; } else if (roomType == ROOM_TYPE_FG_VIP) { userInfo.score = (int)pUser->fireCoin; } else if (roomType == ROOM_TYPE_MATCH) { userInfo.score = (int)pUser->matchSocre; } return true; } void CGameDesk::InitBuyDeskData() { m_beginUserID = 0; m_playMode = 0; m_payType = PAY_TYPE_NORMAL; m_roomTipType = 0; m_roomTipTypeNums = 0; m_RemoveMinPoint = 1; m_MinPoint = 0; m_basePoint = 1; m_isBegin = false; m_iVipGameCount = 0; m_iBuyGameCount = 0; memset(m_szGameRules, 0, sizeof(m_szGameRules)); memset(m_szDeskPassWord, 0, sizeof(m_szDeskPassWord)); memset(m_uScore, 0, sizeof(m_uScore)); memset(m_gameWinCount, 0, sizeof(m_gameWinCount)); m_iRunGameCount = 0; m_masterID = 0; m_bPlayGame = false; m_byGameStation = 0; m_isMasterNotPlay = false; InitDeskGameData(); } void CGameDesk::InitDismissData() { m_isDismissStatus = false; m_reqDismissTime = 0; m_reqDismissDeskStation = INVALID_DESKSTATION; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { m_deskUserInfoVec[i].dismissType = DISMISS_TYPE_DEFAULT; } } void CGameDesk::LoadPrivateDeskInfo(const PrivateDeskInfo& privateDeskInfo) { m_masterID = privateDeskInfo.masterID; m_iVipGameCount = privateDeskInfo.buyGameCount; m_iBuyGameCount = privateDeskInfo.buyGameCount; m_isMasterNotPlay = privateDeskInfo.masterNotPlay == 0 ? false : true; strcpy(m_szDeskPassWord, privateDeskInfo.passwd); // 规则 if (strcmp(privateDeskInfo.gameRules, REDIS_STR_DEFAULT)) { memcpy(m_szGameRules, privateDeskInfo.gameRules, sizeof(m_szGameRules)); } //俱乐部信息 m_friendsGroupMsg.Init(); m_friendsGroupMsg.friendsGroupID = privateDeskInfo.friendsGroupID; if (m_friendsGroupMsg.friendsGroupID != 0) { m_friendsGroupMsg.friendsGroupDeskNumber = privateDeskInfo.friendsGroupDeskNumber; } m_enable = true; } bool CGameDesk::PrivateSitDeskLogic(GameUserInfo* pUser) { if (!pUser) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } // 只有旁观状态才能坐下 if (pUser->playStatus != USER_STATUS_WATCH) { ERROR_LOG("user(%d) status is invalid(%d)", pUser->userID, pUser->playStatus); return false; } auto iter = m_watchUserInfoSet.begin(); for (; iter != m_watchUserInfoSet.end(); ++iter) { const WatchUserInfo& info = *iter; if (info.userID == pUser->userID) { break; } } if (iter == m_watchUserInfoSet.end()) { ERROR_LOG("can't find user(%d) in watchUserSet", pUser->userID); return false; } PrivateDeskInfo privateDeskInfo; int deskMixID = m_pDataManage->GetRoomID() * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; if (!pRedis->GetPrivateDeskRecordInfo(deskMixID, privateDeskInfo)) { ERROR_LOG("GetPrivateDeskRecordInfo failed deskMixID:%d", deskMixID); return false; } //判断中途是否禁止加入 if (m_bGameStopJoin == 1 && m_isBegin) { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_STOP_JOIN); return true; } //游戏中禁止坐下 if (m_bPlayGame) { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_GAME_PLAYING_ERR_SIT); return true; } // 桌子是不是满了 if (privateDeskInfo.currDeskUserCount >= privateDeskInfo.maxDeskUserCount) { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_DESK_FULL); return true; } // 是否可以坐桌 if (!WatchCanSit(pUser)) { return true; } int roomType = GetRoomType(); // 判断玩家俱乐部火币 if (roomType == ROOM_TYPE_FG_VIP) { if (pUser->fireCoin < m_MinPoint) { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_FRIENDSGROUP_FIRECOIN_LIMIT); return true; } } // 房间里面是不是有这个人了 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (pUser->userID == m_deskUserInfoVec[i].userID) { return true; } } BYTE deskStation = INVALID_DESKSTATION; int deskUserInfoVecSize = m_deskUserInfoVec.size(); if (pUser->choiceDeskStation == INVALID_DESKSTATION) //系统分配座位 { if (roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) { for (int i = 0; i < deskUserInfoVecSize; i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == pUser->userID) { deskUserInfo.userID = pUser->userID; deskStation = (BYTE)i; deskUserInfo.leftRoomUser = 0; break; } } if (deskStation == INVALID_DESKSTATION) { for (int i = 0; i < deskUserInfoVecSize; i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == 0) { deskUserInfo.userID = pUser->userID; deskStation = (BYTE)i; break; } } } if (deskStation == INVALID_DESKSTATION) { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_FRIEND_ROOM_DESK_FULL); ERROR_LOG("私人房 deskIdx=%d userID=%d m_deskUserInfoVec size=%d", m_deskIdx, pUser->userID, deskUserInfoVecSize); return true; } } else { for (int i = 0; i < deskUserInfoVecSize; i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0) { deskUserInfo.userID = pUser->userID; deskStation = (BYTE)i; break; } } if (deskStation == INVALID_DESKSTATION) { ERROR_LOG("calc user deskStation is invalid deskIdx=%d userID=%d m_deskUserInfoVec size=%d", m_deskIdx, pUser->userID, deskUserInfoVecSize); return false; } } } else // 玩家自己选择座位 { if (pUser->choiceDeskStation >= deskUserInfoVecSize) { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_DESKSTATION_NOTEXISTS); return true; } if (roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) // 金币房 { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[pUser->choiceDeskStation]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == pUser->userID) { deskUserInfo.userID = pUser->userID; deskStation = pUser->choiceDeskStation; deskUserInfo.leftRoomUser = 0; } else if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == 0) { deskUserInfo.userID = pUser->userID; deskStation = pUser->choiceDeskStation; } else { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_DESKSTATION_HAVEUSER); return true; } } else //积分房 { if (m_deskUserInfoVec[pUser->choiceDeskStation].userID == 0) { m_deskUserInfoVec[pUser->choiceDeskStation].userID = pUser->userID; deskStation = pUser->choiceDeskStation; } else { m_pDataManage->SendData(pUser->userID, NULL, 0, MSG_MAIN_LOADER_ACTION, MSG_ASS_LOADER_ACTION_SIT, ERROR_DESKSTATION_HAVEUSER); return true; } } } // 旁观列表中移除玩家 m_watchUserInfoSet.erase(iter); // 设置玩家的桌子号,座位号,状态等 pUser->deskIdx = m_deskIdx; pUser->deskStation = deskStation; pUser->playStatus = USER_STATUS_SITING; pUser->choiceDeskStation = INVALID_DESKSTATION; pUser->lastOperateTime = time(NULL); m_deskUserInfoVec[deskStation].bNetCut = false; m_deskUserInfoVec[deskStation].lastWaitAgreeTime = time(NULL); m_deskUserInfoVec[deskStation].isVirtual = pUser->isVirtual; // 坐下人数和旁观人数 int currDeskUserCount = privateDeskInfo.currDeskUserCount + 1; int currWatchUserCount = privateDeskInfo.currWatchUserCount - 1; pRedis->SetPrivateDeskCurrUserCount(deskMixID, currDeskUserCount); pRedis->SetPrivateDeskCurrWatchUserCount(deskMixID, currWatchUserCount); // 广播坐下的信息 BroadcastUserSitData(pUser->deskStation); // 通知特殊游戏首次坐桌 UserSitDeskActionNotify(pUser->deskStation); // 通知大厅开房信息发生变化 NotifyLogonBuyDeskInfoChange(m_masterID, currDeskUserCount, pUser->userID, 0, deskMixID); if (currDeskUserCount >= privateDeskInfo.maxDeskUserCount) { // 桌子人数满了,通知旁观者 SendWatchData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_SITFULL, 0); } return true; } bool CGameDesk::MoneySitDeskLogic(GameUserInfo* pUser) { if (!pUser) { ERROR_LOG("MoneySitDeskLogic::pUser==NULL"); return false; } int userID = pUser->userID; if (userID <= 0) { ERROR_LOG("invalid userID: userID=%d", userID); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } time_t currTime = time(NULL); if (pUser->deskStation == INVALID_DESKSTATION) { // 第一次坐下 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID == userID) { ERROR_LOG("user deskStation is invalid but user is in desk userID=%d", userID); pUser->deskStation = (BYTE)i; break; } } if (pUser->deskStation == INVALID_DESKSTATION) { // 分配一个座位 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0) { deskUserInfo.userID = userID; pUser->deskStation = (BYTE)i; break; } } } } // 这里玩家不可能没有座位了 if (pUser->deskStation >= m_deskUserInfoVec.size()) { ERROR_LOG("user deskStation is invalid userID = %d deskStation = %d", userID, pUser->deskStation); return false; } if (!IsEnable()) { m_enable = true; m_masterID = 0; m_iVipGameCount = 0; m_iBuyGameCount = 0; memset(m_szDeskPassWord, 0, sizeof(m_szDeskPassWord)); memset(m_szGameRules, 0, sizeof(m_szGameRules)); memset(m_uScore, 0, sizeof(m_uScore)); } pRedis->SetUserRoomID(pUser->userID, m_pDataManage->GetRoomID()); // 设置玩家的桌子号,座位号,状态等 pUser->lastOperateTime = currTime; pUser->deskIdx = m_deskIdx; if (USER_STATUS_PLAYING != pUser->playStatus) { pUser->playStatus = USER_STATUS_SITING; } m_deskUserInfoVec[pUser->deskStation].bNetCut = false; m_deskUserInfoVec[pUser->deskStation].lastWaitAgreeTime = currTime; m_deskUserInfoVec[pUser->deskStation].isVirtual = pUser->isVirtual; if (pUser->isVirtual == 1) { RobotPositionInfo positionInfo; int iRobotIndex = pRedis->GetRobotInfoIndex(); ConfigManage()->GetRobotPositionInfo(iRobotIndex, positionInfo); strcpy(pUser->name, positionInfo.name.c_str()); strcpy(pUser->headURL, positionInfo.headUrl.c_str()); pUser->sex = positionInfo.sex; strcpy(pUser->longitude, positionInfo.longitude.c_str()); strcpy(pUser->latitude, positionInfo.latitude.c_str()); strcpy(pUser->address, positionInfo.address.c_str()); strcpy(pUser->ip, positionInfo.ip.c_str()); //修改redis中机器人的数据 std::unordered_map<std::string, std::string> umap; umap["name"] = pUser->name; umap["headURL"] = pUser->headURL; umap["sex"] = std::to_string(pUser->sex); umap["logonIP"] = pUser->ip; umap["address"] = pUser->address; umap["Lng"] = pUser->longitude; umap["Lat"] = pUser->latitude; pRedis->hmset(TBL_USER, pUser->userID, umap); //既然换名字,金币数量也换 //回收机器人金币数量 long long _i64PoolMoney = 0; long long _i64MoneyChange = 0; RoomBaseInfo roomBasekInfo; RoomBaseInfo* pRoomBaseInfo = NULL; if (pRedis->GetRoomBaseInfo(m_pDataManage->GetRoomID(), roomBasekInfo)) { pRoomBaseInfo = &roomBasekInfo; } else { pRoomBaseInfo = ConfigManage()->GetRoomBaseInfo(m_pDataManage->GetRoomID()); } if (pRoomBaseInfo) { if (pRoomBaseInfo->minPoint <= pRoomBaseInfo->basePoint) { _i64MoneyChange = CUtil::GetRandRange(1000 * pRoomBaseInfo->basePoint, 40000 * pRoomBaseInfo->basePoint); } else if (pRoomBaseInfo->maxPoint <= 0 || pRoomBaseInfo->maxPoint <= pRoomBaseInfo->minPoint) { if (pRoomBaseInfo->minPoint < 1000) { _i64MoneyChange = CUtil::GetRandRange(20 * pRoomBaseInfo->minPoint, 100 * pRoomBaseInfo->minPoint); } else { _i64MoneyChange = CUtil::GetRandRange(2 * pRoomBaseInfo->minPoint, 10 * pRoomBaseInfo->minPoint); } } else { _i64MoneyChange = CUtil::GetRandRange(pRoomBaseInfo->minPoint, pRoomBaseInfo->maxPoint); } //如果后台设置了金币范围直接按照后台来 int iMinRobotHaveMoney_ = m_pDataManage->GetPoolConfigInfo("minM"); int iMaxRobotHaveMoney_ = m_pDataManage->GetPoolConfigInfo("maxM"); if (iMaxRobotHaveMoney_ > iMinRobotHaveMoney_) { _i64MoneyChange = CUtil::GetRandRange(iMinRobotHaveMoney_, iMaxRobotHaveMoney_); } _i64PoolMoney = pUser->money - _i64MoneyChange; //pRedis->SetRoomPoolMoney(m_pDataManage->GetRoomID(), _i64PoolMoney, true); pRedis->SetUserMoney(userID, _i64MoneyChange); pUser->money = _i64MoneyChange; } } // 通知等待剩余时间 SendLeftWaitAgreeData(pUser->deskStation); // 广播坐下的信息(不广播自己) BroadcastUserSitData(pUser->deskStation); // 通知特殊游戏首次坐桌 UserSitDeskActionNotify(pUser->deskStation); return true; } bool CGameDesk::PrivateUserLeftDeskLogic(GameUserInfo* pUser) { if (!pUser) { ERROR_LOG("invalid pUser = null"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("GetRedis failed"); return false; } int deskMixID = m_pDataManage->GetRoomID() * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; PrivateDeskInfo deskInfo; if (!pRedis->GetPrivateDeskRecordInfo(deskMixID, deskInfo)) { ERROR_LOG("GetPrivateDeskRecordInfo failed deskMixID=%d", deskMixID); return false; } if (pUser->playStatus == USER_STATUS_WATCH) { // 旁观者 return OnWatcherLeftDesk(pUser, deskInfo); } else { return OnDeskUserLeftDesk(pUser, deskInfo); } } bool CGameDesk::MoneyUserLeftDeskLogic(GameUserInfo * pUser) { if (!pUser) { ERROR_LOG("MoneyUserLeftDeskLogic::pUser is NULL"); return false; } if (pUser->deskStation >= (BYTE)m_deskUserInfoVec.size()) { ERROR_LOG("user(%d) deskStation is invalid deskStation=%d", pUser->userID, pUser->deskStation); return false; } // 先通知桌子中的所有玩家 BroadcastUserLeftData(pUser->deskStation, REASON_KICKOUT_STAND); // 清理桌子中玩家的数据 m_deskUserInfoVec[pUser->deskStation].clear(); // 清理玩家游戏数据 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; // 玩家离开可能会触发游戏开始 if (m_bPlayGame == false && CanBeginGame()) { GameBegin(0); } return true; } bool CGameDesk::HundredGameUserLeftLogic(GameUserInfo* pUser) { if (!pUser) { ERROR_LOG("pUser is NULL"); return false; } if (pUser->deskStation >= (BYTE)m_deskUserInfoVec.size()) { ERROR_LOG("user(%d) deskStation is invalid deskStation=%d", pUser->userID, pUser->deskStation); return false; } // 先通知桌子中的所有玩家 BroadcastUserLeftData(pUser->deskStation, REASON_KICKOUT_STAND); // 清理桌子中玩家的数据 m_deskUserInfoVec[pUser->deskStation].clear(); // 清理玩家游戏数据 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; return true; } bool CGameDesk::HundredGameUserNetCutLogic(GameUserInfo * pUser) { if (!pUser) { return false; } return true; } int CGameDesk::CheckUserMoney(int userID) { int reason = REASON_KICKOUT_DEFAULT; if (userID <= 0) { ERROR_LOG("invalid userID = 0"); return REASON_KICKOUT_DEFAULT; } if (!m_pDataManage) { return REASON_KICKOUT_DEFAULT; } CRedisLoader * pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return REASON_KICKOUT_DEFAULT; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID=%d", userID); return REASON_KICKOUT_DEFAULT; } RoomBaseInfo roomBasekInfo; RoomBaseInfo* pRoomBaseInfo = NULL; if (pRedis->GetRoomBaseInfo(m_pDataManage->GetRoomID(), roomBasekInfo)) { pRoomBaseInfo = &roomBasekInfo; } else { pRoomBaseInfo = ConfigManage()->GetRoomBaseInfo(m_pDataManage->GetRoomID()); } if (!pRoomBaseInfo) { return REASON_KICKOUT_DEFAULT; } if (pRoomBaseInfo->minPoint > 0 && pUser->money < pRoomBaseInfo->minPoint) { return REASON_KICKOUT_STAND_MINLIMIT; } if (pRoomBaseInfo->minPoint > 0 && pRoomBaseInfo->maxPoint > pRoomBaseInfo->minPoint && pUser->money > pRoomBaseInfo->maxPoint) { return REASON_KICKOUT_STAND_MAXLIMIT; } if (pUser->money < 0) { return REASON_KICKOUT_STAND_MINLIMIT; } return REASON_KICKOUT_DEFAULT; } void CGameDesk::ProcessDeduceMoneyWhenGameBegin() { if (GetRoomSort() == ROOM_SORT_HUNDRED || GetRoomSort() == ROOM_SORT_SCENE) { return; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("GetRedis failed"); return; } int roomID = m_pDataManage->GetRoomID(); int roomType = GetRoomType(); long long costMoney = 0; RoomBaseInfo roomBasekInfo; RoomBaseInfo* pRoomBaseInfo = NULL; if (pRedis->GetRoomBaseInfo(roomID, roomBasekInfo)) { pRoomBaseInfo = &roomBasekInfo; } else { pRoomBaseInfo = ConfigManage()->GetRoomBaseInfo(roomID); } if (!pRoomBaseInfo) { ERROR_LOG("GetRoomBaseInfo failed roomID(%d)", roomID); return; } // 金币场开局扣除玩家金币 if (roomType == ROOM_TYPE_GOLD) { costMoney = pRoomBaseInfo->gameBeginCostMoney; } else if (roomType == ROOM_TYPE_FRIEND && m_payType == PAY_TYPE_AA) { BuyGameDeskInfo buyGameDeskInfo; BuyGameDeskInfo* pBuyGameDeskInfo = NULL; BuyGameDeskInfoKey buyDekKey(pRoomBaseInfo->gameID, m_iBuyGameCount, pRoomBaseInfo->type); if (pRedis->GetBuyGameDeskInfo(buyDekKey, buyGameDeskInfo)) { pBuyGameDeskInfo = &buyGameDeskInfo; } else { pBuyGameDeskInfo = ConfigManage()->GetBuyGameDeskInfo(buyDekKey); } if (!pBuyGameDeskInfo) { return; } costMoney = pBuyGameDeskInfo->AAcostNums; } //不扣金币 if (costMoney <= 0) { return; } long long percentageWinMoney = 0, recovMoney = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } if (pUser->isVirtual) { recovMoney += costMoney; } percentageWinMoney += costMoney; long long newMoney = pUser->money - costMoney; pUser->money = newMoney; pRedis->SetUserMoneyEx(userID, -costMoney, true, RESOURCE_CHANGE_REASON_GAME_BEGIN, roomID, 0, pUser->isVirtual, m_friendsGroupMsg.friendsGroupID); // 通知变化 NotifyUserResourceChange(userID, RESOURCE_TYPE_MONEY, newMoney, -costMoney); } //回收金币到奖池 pRedis->SetRoomPercentageWinMoney(roomID, percentageWinMoney - recovMoney, true); //pRedis->SetRoomPoolMoney(roomID, recovMoney, true); } void CGameDesk::NotifyLogonBuyDeskInfoChange(int masterID, int userCount, int userID, BYTE updateType, int deskMixID) { PlatformDeskPeopleCountChange msg; msg.friendsGroupID = m_friendsGroupMsg.friendsGroupID; msg.friendsGroupDeskNumber = m_friendsGroupMsg.friendsGroupDeskNumber; msg.masterID = masterID; memcpy(msg.roomPasswd, m_szDeskPassWord, sizeof(msg.roomPasswd)); msg.currUserCount = userCount; msg.updateType = updateType; msg.userID = userID; m_pDataManage->SendMessageToCenterServer(CENTER_MESSAGE_LOADER_BUYDESKINFO_CHANGE, &msg, sizeof(msg)); CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("GetRedis failed"); return; } pRedis->SetPrivateDeskUserID(deskMixID, userID, updateType); } void CGameDesk::NotifyLogonDeskDissmiss(const PrivateDeskInfo& privateDeskInfo) { PlatformDeskDismiss msg; msg.masterID = privateDeskInfo.masterID; msg.friendsGroupID = privateDeskInfo.friendsGroupID; msg.friendsGroupDeskNumber = privateDeskInfo.friendsGroupDeskNumber; memcpy(msg.passwd, privateDeskInfo.passwd, sizeof(msg.passwd)); msg.bDeleteDesk = m_friendsGroupMsg.bDeleteDesk; msg.roomType = GetRoomType(); msg.gameID = m_pDataManage->m_uNameID; msg.maxCount = privateDeskInfo.buyGameCount; memcpy(msg.gameRules, privateDeskInfo.gameRules, sizeof(msg.gameRules)); m_pDataManage->SendMessageToCenterServer(CENTER_MESSAGE_LOADER_DESK_DISSMISS, &msg, sizeof(msg)); if (m_friendsGroupMsg.friendsGroupID <= 0) { return; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("GetRedis failed"); return; } // 判断是否需要删除redis牌桌数据 if (m_friendsGroupMsg.bDeleteDesk) { // 删除redis中的牌桌 pRedis->DelFGDeskRoom(privateDeskInfo.friendsGroupID, privateDeskInfo.friendsGroupDeskNumber); } } void CGameDesk::NotifyLogonDeskStatusChange() { PlatformDeskGameCountChange msg; msg.friendsGroupID = m_friendsGroupMsg.friendsGroupID; msg.friendsGroupDeskNumber = m_friendsGroupMsg.friendsGroupDeskNumber; msg.gameStatus = m_isBegin; m_pDataManage->SendMessageToCenterServer(CENTER_MESSAGE_LOADER_DESK_STATUS_CHANGE, &msg, sizeof(msg)); } BuyGameDeskInfo CGameDesk::ProcessCostJewels() { BuyGameDeskInfo buyGameDeskInfo; int roomType = GetRoomType(); if (roomType == ROOM_TYPE_GOLD || roomType == ROOM_TYPE_MATCH) { return buyGameDeskInfo; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("GetRedis failed"); return buyGameDeskInfo; } int roomID = m_pDataManage->GetRoomID(); RoomBaseInfo roomBasekInfo; RoomBaseInfo* pRoomBaseInfo = NULL; if (pRedis->GetRoomBaseInfo(roomID, roomBasekInfo)) { pRoomBaseInfo = &roomBasekInfo; } else { pRoomBaseInfo = ConfigManage()->GetRoomBaseInfo(roomID); } if (!pRoomBaseInfo) { ERROR_LOG("GetRoomBaseInfo failed roomID(%d)", roomID); return buyGameDeskInfo; } int deskMixID = roomID * MAX_ROOM_HAVE_DESK_COUNT + m_deskIdx; PrivateDeskInfo privateDeskInfo; if (!pRedis->GetPrivateDeskRecordInfo(deskMixID, privateDeskInfo)) { ERROR_LOG("GetPrivateDeskRecordInfo failed, deskMixID(%d)", deskMixID); return buyGameDeskInfo; } BuyGameDeskInfo* pBuyGameDeskInfo = NULL; BuyGameDeskInfoKey buyDekKey(pRoomBaseInfo->gameID, privateDeskInfo.buyGameCount, GetRoomType()); if (pRedis->GetBuyGameDeskInfo(buyDekKey, buyGameDeskInfo)) { pBuyGameDeskInfo = &buyGameDeskInfo; } else { pBuyGameDeskInfo = ConfigManage()->GetBuyGameDeskInfo(buyDekKey); } if (!pBuyGameDeskInfo) { ERROR_LOG("GetAABuyGameDeskInfo failed gameID(%d) gameCount(%d)", pRoomBaseInfo->gameID, privateDeskInfo.buyGameCount); return buyGameDeskInfo; } buyGameDeskInfo = *pBuyGameDeskInfo; //退还金币或者房卡 if (m_finishedGameCount <= 0) { if (privateDeskInfo.payType == PAY_TYPE_NORMAL && pBuyGameDeskInfo->costNums > 0) // 普通支付 { int masterID = privateDeskInfo.masterID; UserData masterData; if (!pRedis->GetUserData(masterID, masterData)) { ERROR_LOG("返还金币或者房卡失败:masterID=%d", masterID); return buyGameDeskInfo; } if (pBuyGameDeskInfo->costResType == RESOURCE_TYPE_JEWEL) { long long newJewels = masterData.jewels + pBuyGameDeskInfo->costNums; pRedis->SetUserJewelsEx(masterID, pBuyGameDeskInfo->costNums, true, RESOURCE_CHANGE_REASON_GAME_SELLETE_ROLLBACK, roomID, 0, masterData.isVirtual, m_friendsGroupMsg.friendsGroupID); // 通知房卡变化 m_pDataManage->SendResourcesChangeToLogonServer(masterID, RESOURCE_TYPE_JEWEL, newJewels, RESOURCE_CHANGE_REASON_GAME_SELLETE_ROLLBACK, pBuyGameDeskInfo->costNums); } else { long long newGolds = masterData.money + pBuyGameDeskInfo->costNums; pRedis->SetUserMoneyEx(masterID, pBuyGameDeskInfo->costNums, true, RESOURCE_CHANGE_REASON_GAME_SELLETE_ROLLBACK, roomID, 0, 0, m_friendsGroupMsg.friendsGroupID); //算房卡场系统赢钱 pRedis->SetRoomGameWinMoney(roomID, -pBuyGameDeskInfo->costNums, true); // 通知金币变化 m_pDataManage->SendResourcesChangeToLogonServer(masterID, RESOURCE_TYPE_MONEY, newGolds, RESOURCE_CHANGE_REASON_GAME_SELLETE_ROLLBACK, pBuyGameDeskInfo->costNums); } } return buyGameDeskInfo; } if (privateDeskInfo.payType != PAY_TYPE_NORMAL && pRoomBaseInfo->type != ROOM_TYPE_FRIEND) // AA支付,金币房暂时没有AA支付,是开局消耗 { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } if (pBuyGameDeskInfo->costResType == RESOURCE_TYPE_JEWEL) { pRedis->SetUserJewelsEx(userID, -pBuyGameDeskInfo->AAcostNums, true, RESOURCE_CHANGE_REASON_GAME_SELLETE_AA, roomID, 0, m_deskUserInfoVec[i].isVirtual, m_friendsGroupMsg.friendsGroupID); } else { pRedis->SetUserMoneyEx(userID, -pBuyGameDeskInfo->AAcostNums, true, RESOURCE_CHANGE_REASON_GAME_SELLETE_AA, roomID, 0, 0, m_friendsGroupMsg.friendsGroupID); } } } return buyGameDeskInfo; } bool CGameDesk::ProcessUserWatch(GameUserInfo* pUser, const PrivateDeskInfo& privateDeskInfo) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } int userID = pUser->userID; if ((int)m_watchUserInfoSet.size() >= privateDeskInfo.maxWatchUserCount) { ERROR_LOG("watch user is too much currUser(%d) maxWatchUser(%d)", m_watchUserInfoSet.size(), privateDeskInfo.maxDeskUserCount); return false; } auto iter = m_watchUserInfoSet.begin(); for (; iter != m_watchUserInfoSet.end(); iter++) { const WatchUserInfo& info = *iter; if (info.userID == userID) { ERROR_LOG("user is already watch user(%d)", userID); return false; } } BYTE deskStation = AllocWatcherDeskStation(); if (deskStation == INVALID_DESKSTATION) { ERROR_LOG("AllocWatcherDeskStation failed"); return false; } int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); pRedis->SetPrivateDeskCurrWatchUserCount(deskMixID, privateDeskInfo.currWatchUserCount + 1); pUser->playStatus = USER_STATUS_WATCH; pUser->deskIdx = m_deskIdx; pUser->deskStation = deskStation; WatchUserInfo watchUserInfo; watchUserInfo.userID = userID; watchUserInfo.deskStation = deskStation; m_watchUserInfoSet.insert(watchUserInfo); return true; } bool CGameDesk::ProcessPrivateUserSitDesk(GameUserInfo* pUser, const PrivateDeskInfo& privateDeskInfo) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } // 房间里面是不是有这个人了 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (pUser->userID == m_deskUserInfoVec[i].userID) { ERROR_LOG("用户已经存在 userID = %d", pUser->userID); return true; } } BYTE deskStation = AllocDeskStation(pUser->userID); if (deskStation == INVALID_DESKSTATION) { ERROR_LOG("AllocDeskStation 分配座位号失败,userID:%d", pUser->userID); return false; } m_deskUserInfoVec[deskStation].userID = pUser->userID; m_deskUserInfoVec[deskStation].deskStation = deskStation; m_deskUserInfoVec[deskStation].leftRoomUser = 0; m_deskUserInfoVec[deskStation].bNetCut = false; m_deskUserInfoVec[deskStation].lastWaitAgreeTime = time(NULL); m_deskUserInfoVec[deskStation].isVirtual = pUser->isVirtual; pUser->playStatus = USER_STATUS_SITING; pUser->deskIdx = m_deskIdx; pUser->deskStation = deskStation; pUser->lastOperateTime = time(NULL); // 坐下人数 int currDeskUserCount = privateDeskInfo.currDeskUserCount + 1; int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); pRedis->SetPrivateDeskCurrUserCount(deskMixID, currDeskUserCount); // 广播坐下的信息 BroadcastUserSitData(pUser->deskStation); // 通知特殊游戏首次坐桌 UserSitDeskActionNotify(pUser->deskStation); // 通知大厅开房信息发生变化 NotifyLogonBuyDeskInfoChange(m_masterID, currDeskUserCount, pUser->userID, 0, deskMixID); return true; } BYTE CGameDesk::AllocDeskStation(int userID) { int deskUserInfoVecSize = m_deskUserInfoVec.size(); if (GetRoomType() == ROOM_TYPE_FRIEND || GetRoomType() == ROOM_TYPE_FG_VIP) { for (int i = 0; i < deskUserInfoVecSize; i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == userID) { return (BYTE)i; } } for (int i = 0; i < deskUserInfoVecSize; ++i) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == 0) { return (BYTE)i; } } } else { for (int i = 0; i < deskUserInfoVecSize; ++i) { if (m_deskUserInfoVec[i].userID == 0) { return (BYTE)i; } } } return INVALID_DESKSTATION; } bool CGameDesk::OnPrivateUserLogin(int userID, const PrivateDeskInfo& info) { GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } int roomType = GetRoomType(); // 从缓存中加载桌子数据 if (!IsEnable()) { LoadPrivateDeskInfo(info); memset(m_uScore, 0, sizeof(m_uScore)); if (m_pDataManage->IsMultiPeopleGame()) { Json::Reader reader; Json::Value value; if (reader.parse(info.gameRules, value)) { m_iConfigCount = value["rs"].asInt(); m_deskUserInfoVec.resize(m_iConfigCount); } } // 自动开始模式 Json::Reader reader; Json::Value value; if (reader.parse(info.gameRules, value)) { m_autoBeginMode = value["Start"].asInt(); //开始方式:0:手动开始,非0满几人开始 m_bGameStopJoin = value["Stopjoin"].asBool(); //中途禁止加入 m_MinPoint = value["mPoint"].asInt(); //入场限制 m_RemoveMinPoint = value["lPoint"].asInt(); //踢人限制 m_basePoint = value["bPoint"].asInt(); //底注 m_roomTipType = value["cCSFS"].asInt(); //抽水方式 m_roomTipTypeNums = value["cCSL"].asInt(); //抽水数量 m_payType = value["pay"].asInt(); //支付方式:1:普通支付,2:AA支付,3:大赢家支付 m_playMode = value["gameIdx"].asInt(); //游戏玩法 } if (m_autoBeginMode <= 1) { m_autoBeginMode = 0; } if (roomType == ROOM_TYPE_FRIEND) //金币房 { if (m_RemoveMinPoint < 1) { m_RemoveMinPoint = 1; } } if (m_roomTipTypeNums < 0 || m_roomTipTypeNums > 99) { m_roomTipTypeNums = 3; } if (30000007 == m_pDataManage->m_uNameID) { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { m_uScore[i] = value["DRJF"].asInt(); } } } // 得到玩家俱乐部火币 if (roomType == ROOM_TYPE_FG_VIP) { CRedisPHP* pRedisPHP = m_pDataManage->GetRedisPHP(); if (!pRedisPHP) { ERROR_LOG("pRedisPHP initialized failed"); return false; } long long carryFireCoin = 0; if (!pRedisPHP->GetUserFriendsGroupMoney(m_friendsGroupMsg.friendsGroupID, pUser->userID, carryFireCoin)) { ERROR_LOG("获取玩家俱乐部火币失败:userId=%d,friendsGroupID=%d", pUser->userID, m_friendsGroupMsg.friendsGroupID); } pUser->fireCoin = (int)carryFireCoin; } #ifdef OFFLINE_CHANGE_AGREE_STATUS //断线取消准备状态 if (pUser->playStatus == USER_STATUS_AGREE) { pUser->playStatus = USER_STATUS_SITING; return true; } // 已经坐下或者游戏中的玩家 if (pUser->playStatus == USER_STATUS_SITING || pUser->playStatus == USER_STATUS_PLAYING) { // 断线重连广播坐下,不广播自己 BroadcastUserSitDataExceptMyself(pUser->deskStation); return true; } #else //断线不取消准备状态 // 已经坐下或者游戏中的玩家 if (pUser->playStatus == USER_STATUS_SITING || pUser->playStatus == USER_STATUS_PLAYING || pUser->playStatus == USER_STATUS_AGREE) { // 断线重连广播坐下,不广播自己 BroadcastUserSitDataExceptMyself(pUser->deskStation); return true; } #endif if (pUser->playStatus != USER_STATUS_DEFAULT) { return true; } bool canWatch = m_pDataManage->IsCanWatch(); if (canWatch == true) { // 可旁观并且玩家为默认状态 return ProcessUserWatch(pUser, info); } else { // 不可旁观立即坐下 return ProcessPrivateUserSitDesk(pUser, info); } } int CGameDesk::GetAgreeUserCount() { int count = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID < 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (pUser && pUser->playStatus == USER_STATUS_AGREE) { count++; } } return count; } int CGameDesk::GetUserCount() { int count = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID > 0) { count++; } } return count; } int CGameDesk::GetOfflineUserCount() { int count = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); continue; } if (pUser->IsOnline == false) { count++; } } return count; } bool CGameDesk::IsAllUserOffline() { int offCount = 0, allCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); continue; } allCount++; if (pUser->IsOnline == false) { offCount++; } else { return false; } } return allCount <= 0 ? false : offCount >= allCount; } bool CGameDesk::IsCanSitDesk() { bool bCanSit = false; if (GetRoomSort() == ROOM_SORT_NORMAL) { if (m_bPlayGame) { return bCanSit; } } for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID <= 0) { bCanSit = true; break; } } return bCanSit; } int CGameDesk::AgreePeople() { int iAgree = 0; if (m_bPlayGame) { return iAgree; } for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID > 0) { GameUserInfo *pUser = m_pDataManage->GetUser(userID); if (pUser && USER_STATUS_AGREE == pUser->playStatus) { iAgree++; } } } return iAgree; } void CGameDesk::CheckTimeoutNotAgreeUser(time_t currTime) { if (m_bPlayGame) { // 游戏开始了则不管 return; } bool bIsKickedUser = false; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { deskUserInfo.clear(); continue; } bool bKickOut = false; int kickReason = REASON_KICKOUT_STAND; if (pUser->deskStation != i) { // 走到这里数据已经异常了 ERROR_LOG("user deskStation is not match userID:%d deskStation=%d i=%d", pUser->userID, pUser->deskStation, i); bKickOut = true; } else if (pUser->playStatus == USER_STATUS_SITING) { // 玩家超时没准备 if (currTime - deskUserInfo.lastWaitAgreeTime > GOLD_DESK_TIMEOUT_UNAGREE_KICKOUT_SECS) { bKickOut = true; kickReason = REASON_KICKOUT_NOTAGREE; } } if (bKickOut) { //玩家被踢 UserBeKicked((BYTE)i); if (!BroadcastUserLeftData((BYTE)i, kickReason)) { ERROR_LOG("send user left fail.userID=%d", pUser->userID); } deskUserInfo.clear(); m_pDataManage->DelUser(userID); bIsKickedUser = true; } } // 玩家离开可能会触发游戏开始 if (bIsKickedUser && m_bPlayGame == false && CanBeginGame()) { GameBegin(0); } } void CGameDesk::CheckTimeoutNotOperateUser(time_t currTime) { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { deskUserInfo.clear(); continue; } if (pUser->lastOperateTime > 0 && !IsPlayGame((BYTE)i) && HundredGameIsInfoChange((BYTE)i) && currTime - pUser->lastOperateTime > HUUNDRED_GAME_TIMEOUT_OPERATE_KICKOUT_SECS) { //玩家被踢 UserBeKicked((BYTE)i); BroadcastUserLeftData((BYTE)i, REASON_KICKOUT_LONG_TIME_NOOPERATION); deskUserInfo.clear(); if (!pUser->isVirtual) { m_pDataManage->DelUser(userID); } } } } bool CGameDesk::IsAuto(BYTE deskStation) { if (deskStation >= m_deskUserInfoVec.size()) { return false; } return m_deskUserInfoVec[deskStation].isAuto; } bool CGameDesk::IsNetCut(BYTE deskStation) { if (deskStation >= m_deskUserInfoVec.size()) { return false; } return m_deskUserInfoVec[deskStation].bNetCut; } bool CGameDesk::IsVirtual(BYTE deskStation) { if (deskStation >= m_deskUserInfoVec.size()) { return false; } return m_deskUserInfoVec[deskStation].isVirtual == 0 ? false : true; } bool CGameDesk::IsSuperUser(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } if (!m_pDataManage) { return false; } GameUserInfo * pUser = m_pDataManage->GetUser(userID); if (!pUser) { return false; } if ((pUser->userStatus&USER_IDENTITY_TYPE_SUPER) == USER_IDENTITY_TYPE_SUPER) { return true; } return false; } bool CGameDesk::IsVisitorUser(BYTE deskStation) { int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return false; } return m_pDataManage->IsVisitorUser(userID); } ////////////////////////////////////////////////////////////////////////// bool CGameDesk::HundredGameBegin() { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID > 0) { m_pDataManage->SetUserPlayStatus(deskUserInfo.userID, USER_STATUS_PLAYING); } } //记录游戏开始需要的数据 m_beginTime = time(NULL); m_bPlayGame = true; // 局数 m_iRunGameCount++; // 告诉桌子的玩家游戏开始了 BroadcastDeskData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GAMEBEGIN); return true; } bool CGameDesk::HundredGameFinish() { m_bPlayGame = false; // 让所有掉线的玩家离开 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID=%d", userID); continue; } bool bKickOut = false; bool bDelUser = false; int kickReason = REASON_KICKOUT_STAND; if (pUser->deskStation != i) { // 走到这里数据已经异常了 ERROR_LOG("user deskStation is not match userID:%d deskStation=%d i=%d", pUser->userID, pUser->deskStation, i); bKickOut = true; bDelUser = true; } else if (!pUser->IsOnline) { bKickOut = true; bDelUser = true; } else if (pUser->isVirtual && IsKickOutVirtual((BYTE)i)) // 一部分机器人出去 { bKickOut = true; bDelUser = false; } else { pUser->playStatus = USER_STATUS_SITING; kickReason = CheckUserMoney(userID); if (kickReason != REASON_KICKOUT_DEFAULT) { bKickOut = true; } } if (bKickOut) { // 玩家被踢 UserBeKicked((BYTE)i); // 通知所有玩家 BroadcastUserLeftData((BYTE)i, kickReason); // 清理桌子玩家数据 deskUserInfo.clear(); // 设置玩家为站起状态 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; if (bDelUser) { // 内存和缓存中移除玩家数据 m_pDataManage->DelUser(userID); } } } // 加载配置 if (m_needLoadConfig) { m_needLoadConfig = false; LoadDynamicConfig(); } return true; } int CGameDesk::GetRealPeople() { int iReal = 0; for (int i = 0; i < (int)m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } if (!m_deskUserInfoVec[i].isVirtual) { iReal++; } } return iReal; } UINT CGameDesk::GetRobotPeople() { UINT iCount = 0; for (int i = 0; i < (int)m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } if (m_deskUserInfoVec[i].isVirtual) { iCount++; } } return iCount; } int CGameDesk::GetBasePoint() { if (!m_pDataManage) { return 1; } CRedisLoader *pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return 1; } int roomID = m_pDataManage->GetRoomID(); RoomBaseInfo roomBasekInfo; RoomBaseInfo* pRoomBaseInfo = NULL; if (pRedis->GetRoomBaseInfo(roomID, roomBasekInfo)) { pRoomBaseInfo = &roomBasekInfo; } else { pRoomBaseInfo = ConfigManage()->GetRoomBaseInfo(roomID); } if (!pRoomBaseInfo) { ERROR_LOG("GetRoomBaseInfo failed roomID=%d", roomID); return 1; } if (pRoomBaseInfo->type == ROOM_TYPE_PRIVATE || pRoomBaseInfo->type == ROOM_TYPE_MATCH) { return 1; } else if (pRoomBaseInfo->type == ROOM_TYPE_FRIEND || pRoomBaseInfo->type == ROOM_TYPE_FG_VIP) { return m_basePoint > 0 ? m_basePoint : 1; } return pRoomBaseInfo->basePoint; } void CGameDesk::NotifyUserResourceChange(int userID, int resourceType, long long value, long long changeValue) { LoaderNotifyResourceChange msg; msg.userID = userID; msg.resourceType = resourceType; msg.value = value; msg.changeValue = changeValue; if (GetRoomSort() == ROOM_SORT_NORMAL || GetRoomSort() == ROOM_SORT_SCENE) { BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_RESOURCE_CHANGE, 0, false); } else { m_pDataManage->SendData(userID, &msg, sizeof(msg), MSG_MAIN_LOADER_RESOURCE_CHANGE, 0, 0); } } ////////////////////////////////////////////////////////////////////////// bool CGameDesk::SetServerRoomPoolData(const char * fieldName, long long fieldValue, bool bAdd) { if (!fieldName) { return false; } int roomID = m_pDataManage->GetRoomID(); if (roomID <= 0) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } return pRedis->SetRoomPoolData(roomID, fieldName, fieldValue, bAdd); } bool CGameDesk::SetServerRoomPoolData(const char * fieldName, const char * fieldValue) { if (!fieldName) { return false; } int roomID = m_pDataManage->GetRoomID(); if (roomID <= 0) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } std::unordered_map<std::string, std::string> umap; umap[fieldName] = fieldValue; if (!pRedis->hmset(TBL_REWARDS_POOL, roomID, umap, REDIS_EXTEND_MODE_UPDATE)) { ERROR_LOG("设置奖池信息失败:roomID=%d", roomID); return false; } return true; } bool CGameDesk::GetRoomConfigInfo(char configInfo[2048], int size) { if (configInfo == NULL || size <= 1) { return false; } int roomID = m_pDataManage->GetRoomID(); if (roomID <= 0) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } RoomBaseInfo roomBaseInfo; if (!pRedis->GetRoomBaseInfo(roomID, roomBaseInfo)) { return false; } memcpy(configInfo, roomBaseInfo.configInfo, Min_(sizeof(roomBaseInfo.configInfo), size)); return true; } ////////////////////////////////////////////////////////////////////////// bool CGameDesk::OnTimerFriendRoomGameBegin() { int roomType = GetRoomType(); if (roomType == ROOM_TYPE_PRIVATE || roomType == ROOM_TYPE_GOLD || roomType == ROOM_TYPE_MATCH || m_bPlayGame) { return false; } if (!m_enable) { return false; } int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } //先计算当前人数 int currUserCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); continue; } currUserCount++; } // 踢掉金钱不足的玩家 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); continue; } if (roomType == ROOM_TYPE_FRIEND && pUser->money < m_RemoveMinPoint || roomType == ROOM_TYPE_FG_VIP && pUser->fireCoin < m_RemoveMinPoint) { // 通知桌子所有玩家 BroadcastUserLeftData((BYTE)i, roomType == ROOM_TYPE_FRIEND ? REASON_KICKOUT_STAND_MINLIMIT : REASON_KICKOUT_STAND_FIRECOIN_MINLIMIT); //清理玩家游戏数据 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; // 清理桌子玩家数据 deskUserInfo.clear(); //保存这个位置玩家被清理 deskUserInfo.leftRoomUser = userID; // 内存和缓存中移除玩家数据 m_pDataManage->DelUser(pUser->userID); // 通知桌子人数变化 --currUserCount; NotifyLogonBuyDeskInfoChange(m_masterID, currUserCount, userID, 1, deskMixID); } } // 清除缓存中玩家数量 pRedis->SetPrivateDeskCurrUserCount(deskMixID, currUserCount); ///////////////////////////////自动开始游戏功能,可以注释不要/////////////////////////////////////////// for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; int userID = deskUserInfo.userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("金币房踢人出错,GetUser failed userID(%d)", userID); continue; } pUser->playStatus = USER_STATUS_AGREE; } //////////////////////////踢人需要判断,是否可以开始游戏//////////////////////////////////////////////// if (CanBeginGame()) { GameBegin(0); } return true; } void CGameDesk::LogonDissmissDesk(int userID, bool bDelete) { int roomType = GetRoomType(); if (roomType == ROOM_TYPE_GOLD || roomType == ROOM_TYPE_MATCH) { ERROR_LOG("金币场不能解散桌子"); return; } m_friendsGroupMsg.bDeleteDesk = bDelete; if (m_isBegin) { ERROR_LOG("游戏已经开始解散俱乐部牌桌失败 ,userID = %d", userID); return; } //直接解散桌子 OnDeskDissmissFinishSendData(); OnDeskSuccessfulDissmiss(true); } void CGameDesk::LogonDissmissDesk() { int roomType = GetRoomType(); if (roomType == ROOM_TYPE_GOLD || roomType == ROOM_TYPE_MATCH) { ERROR_LOG("金币场不能解散桌子"); return; } m_friendsGroupMsg.bDeleteDesk = true; //直接解散桌子 OnDeskDissmissFinishSendData(); OnDeskSuccessfulDissmiss(true); } bool CGameDesk::IsHaveDeskStation(int userID, const PrivateDeskInfo &info) { if (m_pDataManage->IsCanWatch()) { return true; } int iConfigCount = 0; if (m_pDataManage->IsMultiPeopleGame()) { Json::Reader reader; Json::Value value; if (reader.parse(info.gameRules, value)) { iConfigCount = value["rs"].asInt(); } } int deskUserInfoVecSize = iConfigCount > 0 ? iConfigCount : m_deskUserInfoVec.size(); int roomType = GetRoomType(); if (roomType == ROOM_TYPE_PRIVATE) { for (int i = 0; i < deskUserInfoVecSize; i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 || deskUserInfo.userID == userID) { return true; } } return false; } else if (roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_FG_VIP) { for (int i = 0; i < deskUserInfoVecSize; i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == userID || deskUserInfo.userID == userID && deskUserInfo.leftRoomUser == 0) { return true; } } for (int i = 0; i < deskUserInfoVecSize; ++i) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0 && deskUserInfo.leftRoomUser == 0) { return true; } } return false; } return true; } bool CGameDesk::SetUserScore(BYTE deskStation, long long score) { if (deskStation >= MAX_PLAYER_GRADE) { return false; } m_uScore[deskStation] = score; return true; } long long CGameDesk::GetUserScore(BYTE deskStation) { if (deskStation >= MAX_PLAYER_GRADE) { return 0; } return m_uScore[deskStation]; } bool CGameDesk::KickOutUser(BYTE deskStation, int ReaSon) { // 游戏中不能踢人 if (IsPlayGame(deskStation)) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } if (deskStation >= m_deskUserInfoVec.size()) { return false; } // 踢掉玩家 DeskUserInfo& deskUserInfo = m_deskUserInfoVec[deskStation]; int userID = deskUserInfo.userID; if (userID <= 0) { return false; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { ERROR_LOG("GetUser failed userID(%d)", userID); return false; } //玩家被踢 UserBeKicked(deskStation); // 通知桌子所有玩家 BroadcastUserLeftData(deskStation, ReaSon); // 清理桌子玩家数据 deskUserInfo.clear(); // 设置玩家为站起状态 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; // 内存和缓存中移除玩家数据 if (!pUser->isVirtual) { m_pDataManage->DelUser(pUser->userID); } ///////////////////如果是非金币场和比赛场,需要修改redis数据////////////////////// int deskMixID = MAKE_DESKMIXID(m_pDataManage->GetRoomID(), m_deskIdx); if (pRedis->IsKeyExists(TBL_CACHE_DESK, deskMixID)) { int currUserCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID <= 0) { continue; } GameUserInfo* pUserTemp = m_pDataManage->GetUser(m_deskUserInfoVec[i].userID); if (!pUserTemp) { continue; } currUserCount++; } // 清除缓存中玩家数量 pRedis->SetPrivateDeskCurrUserCount(deskMixID, currUserCount); // 通知桌子人数变化 NotifyLogonBuyDeskInfoChange(m_masterID, currUserCount, userID, 1, deskMixID); } return true; } void CGameDesk::OnDeskDissmissFinishSendData() { if (m_iRunGameCount <= 0) { return; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return; } LoaderNotifyDismissSuccessData msg; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { if (m_deskUserInfoVec[i].leftRoomUser <= 0) { continue; } else { userID = m_deskUserInfoVec[i].leftRoomUser; } } UserData userData; if (!pRedis->GetUserData(userID, userData)) { ERROR_LOG("大结算发送玩家信息失败:userID=%d", userID); continue; } //填充玩家id msg.userID[i] = userID; memcpy(msg.name[i], userData.name, sizeof(userData.name)); memcpy(msg.headURL[i], userData.headURL, sizeof(userData.headURL)); } BroadcastDeskData(&msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_DISMISS_USERID); } bool CGameDesk::GetRoomResNums(BYTE deskStation, long long &resNums) { if (deskStation >= m_deskUserInfoVec.size()) { return false; } int userID = m_deskUserInfoVec[deskStation].userID; if (userID <= 0) { return false; } GameUserInfo * pUser = m_pDataManage->GetUser(userID); if (!pUser) { return false; } resNums = 0; int roomType = GetRoomType(); if (roomType == ROOM_TYPE_FG_VIP) { resNums = pUser->fireCoin; } else if (roomType == ROOM_TYPE_FRIEND || roomType == ROOM_TYPE_GOLD) { resNums = pUser->money; } else if (roomType == ROOM_TYPE_PRIVATE) { resNums = m_uScore[deskStation]; } else if (roomType == ROOM_TYPE_MATCH) { resNums = pUser->matchSocre; } return true; } bool CGameDesk::GetUserBagData(BYTE bDeskStation, UserBag & userBagData) { int userID = GetUserIDByDeskStation(bDeskStation); if (userID <= 0) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } pRedis->GetUserBag(userID, userBagData); return true; } int CGameDesk::GetUserBagDataByKey(BYTE bDeskStation, const char * resName) { if (!resName) { return false; } int userID = GetUserIDByDeskStation(bDeskStation); if (userID <= 0) { return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } int resNums = pRedis->GetUserBagCount(userID, resName); return resNums; } double CGameDesk::GetDeskPercentage() { if (m_roomTipTypeNums <= 0 || m_roomTipTypeNums >= 100) { return 0.03; } return double(m_roomTipTypeNums) / 100.0; } bool CGameDesk::SetDeskPercentageScore(int * arPoint, int * ratePoint/* = NULL*/, bool arPointIsChange/* = true*/) { if (m_roomTipType == ROOM_TIP_TYPE_NO) { return true; } if (GetRoomType() == ROOM_TYPE_GOLD || GetRoomType() == ROOM_TYPE_PRIVATE || GetRoomType() == ROOM_TYPE_MATCH) { return true; } if (NULL == arPoint) { return false; } long long llArPont[MAX_PLAYER_GRADE] = { 0 }; for (int i = 0; i < m_iConfigCount; i++) { llArPont[i] = arPoint[i]; } long long llRatePont[MAX_PLAYER_GRADE] = { 0 }; if (ratePoint) { for (int i = 0; i < m_iConfigCount; i++) { llRatePont[i] = ratePoint[i]; } SetDeskPercentageScore(llArPont, llRatePont, arPointIsChange); } else { SetDeskPercentageScore(llArPont, NULL, arPointIsChange); } for (int i = 0; i < m_iConfigCount; i++) { arPoint[i] = (int)llArPont[i]; } if (ratePoint) { for (int i = 0; i < m_iConfigCount; i++) { ratePoint[i] = (int)llRatePont[i]; } } return true; } bool CGameDesk::SetDeskPercentageScore(long long * arPoint, long long * ratePoint/* = NULL*/, bool arPointIsChange/* = true*/) { if (!arPoint) { return false; } if (m_roomTipType == ROOM_TIP_TYPE_NO) { return true; } if (GetRoomType() == ROOM_TYPE_GOLD || GetRoomType() == ROOM_TYPE_PRIVATE || GetRoomType() == ROOM_TYPE_MATCH) { return true; } double rate = GetDeskPercentage(); if (rate <= 0) { return true; } //先找到最大的大赢家 long long llMaxWinMoney = 0; if (m_roomTipType == ROOM_TIP_TYPE_MAX_WIN) { for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } if (m_uScore[i] > llMaxWinMoney) { llMaxWinMoney = m_uScore[i]; } } } for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } if (arPoint[i] > 0 && (m_roomTipType == ROOM_TIP_TYPE_ALL_WIN || m_roomTipType == ROOM_TIP_TYPE_MAX_WIN && arPoint[i] == llMaxWinMoney)) { long long llRate = (long long)floor(arPoint[i] * rate); if (arPointIsChange) { arPoint[i] -= llRate; } if (ratePoint) { ratePoint[i] = llRate; } } } return true; } bool CGameDesk::AddDeskGrade(const char *pVideoCode, const char * gameData, const char * userInfoList) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("redis initialized failed"); return false; } if (pVideoCode && strlen(pVideoCode) != 0) { AsyncEventMsgUploadVideo asyncEvent; strcpy(asyncEvent.videoCode, pVideoCode); m_pDataManage->m_SQLDataManage.PushLine(&asyncEvent.dataLineHead, sizeof(AsyncEventMsgUploadVideo), ASYNC_EVENT_UPLOAD_VIDEO, 0, 0); } GameGradeInfo gameGradeInfo; gameGradeInfo.currTime = time(NULL); gameGradeInfo.masterID = m_masterID; gameGradeInfo.roomID = m_pDataManage->GetRoomID(); gameGradeInfo.deskPasswd = atoi(m_szDeskPassWord); gameGradeInfo.inning = m_finishedGameCount; memcpy(gameGradeInfo.userInfoList, userInfoList, sizeof(gameGradeInfo.userInfoList)); if (pVideoCode == NULL) { strcpy(gameGradeInfo.videoCode, REDIS_STR_DEFAULT); } else { memcpy(gameGradeInfo.videoCode, pVideoCode, sizeof(gameGradeInfo.videoCode)); } if (gameData == NULL) { strcpy(gameGradeInfo.gameData, REDIS_STR_DEFAULT); } else { memcpy(gameGradeInfo.gameData, gameData, sizeof(gameGradeInfo.gameData)); } long long gradeID = 0; if (pRedis->SetPrivateDeskGrade(gameGradeInfo, gradeID) == false) { ERROR_LOG("SetPrivateDeskGrade failed"); return false; } m_gradeIDVec.push_back(gradeID); return true; } void CGameDesk::SetBeginUser() { int firstUserID = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID <= 0) { continue; } GameUserInfo* pUserDesk = m_pDataManage->GetUser(m_deskUserInfoVec[i].userID); if (!pUserDesk) { continue; } if (firstUserID == 0) { firstUserID = m_deskUserInfoVec[i].userID; } if (pUserDesk->IsOnline) { m_beginUserID = m_deskUserInfoVec[i].userID; break; } } if (m_beginUserID == 0) { m_beginUserID = firstUserID; } // 如果房主在,由房主开始游戏 /*GameUserInfo* pUserMaster = m_pDataManage->GetUser(m_masterID); if (pUserMaster && pUserMaster->IsOnline && pUserMaster->deskIdx == m_deskIdx) { m_beginUserID = m_masterID; }*/ } int CGameDesk::GetUserControlParam(BYTE deskStation) { CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("redis initialized failed"); return -1; } int userID = GetUserIDByDeskStation(deskStation); if (userID <= 0) { return -1; } int value = -1; pRedis->GetUserControlParam(userID, value); return value; } bool CGameDesk::IsKickOutVirtual(BYTE deskStation) { if (!HundredGameIsInfoChange(deskStation)) { return false; } // 坐桌数量 int iMinRobotCount = m_pDataManage->GetPoolConfigInfo("minC"); int iMaxRobotCount = m_pDataManage->GetPoolConfigInfo("maxC"); iMinRobotCount = iMinRobotCount <= 0 ? 3 : iMinRobotCount; iMaxRobotCount = iMaxRobotCount <= 0 ? 40 : iMaxRobotCount; int iRobotCount = GetRobotPeople(); if (iRobotCount < iMinRobotCount) { return false; } if (iRobotCount > iMaxRobotCount) { return true; } // 获取机器人最大和最小携带金币,将金币超过限制的机器人踢出去 int iMinRobotHaveMoney_ = m_pDataManage->GetPoolConfigInfo("minM"); int iMaxRobotHaveMoney_ = m_pDataManage->GetPoolConfigInfo("maxM"); long long llResNums = 0; if (iMaxRobotHaveMoney_ > 0 && GetRoomResNums(deskStation, llResNums) && (llResNums > iMaxRobotHaveMoney_ || llResNums < iMinRobotHaveMoney_)) { return true; } int iUpdateRate = m_pDataManage->GetPoolConfigInfo("updateRate"); iUpdateRate = iUpdateRate <= 0 ? 5 : iUpdateRate; if (CUtil::GetRandNum() % 100 < iUpdateRate) { return false; } return true; } bool CGameDesk::IsOneToOnePlatform() { return m_pDataManage->IsOneToOnePlatform(); } int CGameDesk::GetPlatformMultiple() { return IsOneToOnePlatform() ? 100 : 1; } ////////////////////////////////////////////////////////////////////////// // 比赛场 // 初始化比赛场数据 void CGameDesk::InitDeskMatchData() { m_llPartOfMatchID = 0; m_iCurMatchRound = 0; m_iMaxMatchRound = 0; m_llStartMatchTime = 0; m_bFinishMatch = false; // 清理桌子玩家 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { m_deskUserInfoVec[i].clear(); } ReSetGameState(0); InitBuyDeskData(); } // 比赛场游戏结束 bool CGameDesk::MatchRoomGameBegin() { //记录比赛场相关信息 m_llStartMatchTime = 0; m_bFinishMatch = false; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } m_pDataManage->SetUserPlayStatus(userID, USER_STATUS_PLAYING); } //记录游戏开始需要的数据 m_bPlayGame = true; m_beginTime = time(NULL); // 局数 m_iRunGameCount++; // 告诉桌子的玩家游戏开始了 BroadcastDeskData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GAMEBEGIN); return true; } // 比赛场游戏结束 bool CGameDesk::MatchRoomGameFinish() { m_bFinishMatch = true; m_llStartMatchTime = 0; m_bPlayGame = false; BroadcastDeskData(NULL, 0, MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_GAMEFINISH); // 将旁观玩家踢出去 if (m_matchWatchUserID.size() > 0) { for (auto iter = m_matchWatchUserID.begin(); iter != m_matchWatchUserID.end(); ++iter) { int userID = *iter; if (userID <= 0) { continue; } GameUserInfo *pUser = m_pDataManage->GetUser(userID); if (pUser) { MatchQuitMyDeskWatch(pUser, pUser->socketIdx, 2); } } m_matchWatchUserID.clear(); } if (m_pDataManage->IsAllDeskFinishMatch(m_llPartOfMatchID)) //本轮游戏结束 { if (m_iCurMatchRound >= m_iMaxMatchRound) //决赛轮,整个比赛结束 { m_pDataManage->MatchEnd(m_llPartOfMatchID, m_iCurMatchRound, m_iMaxMatchRound); } else //淘汰部玩家,进入下一轮 { m_pDataManage->MatchNextRound(m_llPartOfMatchID, m_iCurMatchRound, m_iMaxMatchRound); } } else { // 根据业务需求,这里也可以淘汰玩家 m_pDataManage->MatchDeskFinish(m_llPartOfMatchID, m_deskIdx); } return true; } // 发送当前桌子的比赛状态 void CGameDesk::SendMatchDeskStatus(int userID) { if (userID <= 0) { return; } LoaderNotifyDeskMatchStatus msg; msg.iCurMatchRound = m_iCurMatchRound; msg.iMaxMatchRound = m_iMaxMatchRound; msg.llPartOfMatchID = m_llPartOfMatchID; if (IsPlayGame(0)) { msg.status = 0; } else if (m_bFinishMatch) { msg.status = 1; } else { msg.status = 2; msg.remainTime = int(m_llStartMatchTime - time(NULL)); } m_pDataManage->SendData(userID, &msg, sizeof(msg), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MATCH_STATUS, 0); } // 比赛场坐桌逻辑 bool CGameDesk::MatchRoomSitDeskLogic(GameUserInfo* pUser) { if (!pUser) { ERROR_LOG("MatchRoomSitDeskLogic::pUser==NULL"); return false; } int userID = pUser->userID; if (userID <= 0) { ERROR_LOG("invalid userID: userID=%d", userID); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { return false; } time_t currTime = time(NULL); if (pUser->deskStation == INVALID_DESKSTATION) { // 第一次坐下 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID == userID) { ERROR_LOG("user deskStation is invalid but user is in desk userID=%d", userID); return false; } } // 分配一个座位 for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { DeskUserInfo& deskUserInfo = m_deskUserInfoVec[i]; if (deskUserInfo.userID == 0) { deskUserInfo.userID = userID; pUser->deskStation = (BYTE)i; break; } } } // 这里玩家不可能没有座位了 if (pUser->deskStation >= m_deskUserInfoVec.size()) { ERROR_LOG("user deskStation is invalid userID = %d deskStation = %d", userID, pUser->deskStation); return false; } // 设置房间id pRedis->SetUserRoomID(pUser->userID, m_pDataManage->GetRoomID()); // 设置比赛状态 pRedis->SetUserMatchStatus(pUser->userID, m_pDataManage->m_matchTypeMap[m_llPartOfMatchID], USER_MATCH_STATUS_PLAYING); // 设置玩家的桌子号,座位号,状态等 pUser->deskIdx = m_deskIdx; if (USER_STATUS_PLAYING != pUser->playStatus) { pUser->playStatus = USER_STATUS_SITING; } m_deskUserInfoVec[pUser->deskStation].bNetCut = false; m_deskUserInfoVec[pUser->deskStation].lastWaitAgreeTime = currTime; m_deskUserInfoVec[pUser->deskStation].isVirtual = pUser->isVirtual; // 广播坐下的信息 BroadcastUserSitData(pUser->deskStation); // 发送当前桌子状态 SendMatchDeskStatus(userID); return true; } // 比赛场玩家离开桌子 bool CGameDesk::MatchRoomUserLeftDeskLogic(GameUserInfo * pUser) { if (!pUser) { ERROR_LOG("比赛场开开错误::pUser is NULL"); return false; } if (pUser->deskStation >= (BYTE)m_deskUserInfoVec.size()) { ERROR_LOG("user(%d) deskStation is invalid deskStation=%d", pUser->userID, pUser->deskStation); return false; } // 清理桌子中玩家的数据 m_deskUserInfoVec[pUser->deskStation].clear(); // 清理玩家游戏数据 pUser->playStatus = USER_STATUS_STAND; pUser->deskIdx = INVALID_DESKIDX; pUser->deskStation = INVALID_DESKSTATION; return true; } // 比赛场获取一个桌子所有玩家id int CGameDesk::MatchGetDeskUserID(int arrUserID[MAX_PLAYER_GRADE]) { if (arrUserID == NULL) { return 0; } int peopleCount = 0; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (m_deskUserInfoVec[i].userID > 0) { arrUserID[peopleCount++] = m_deskUserInfoVec[i].userID; } } return peopleCount; } // 比赛场进入本桌旁观 bool CGameDesk::MatchEnterMyDeskWatch(GameUserInfo * pUser, long long partOfMatchID) { if (!pUser) { return false; } LoaderResponseMatchEnterWatch msg; int iSendSize = 5; if (m_llPartOfMatchID == 0 || partOfMatchID != m_llPartOfMatchID) { ERROR_LOG("异常错误 :deskIdx=%d,partOfMatchID=%lld", m_deskIdx, partOfMatchID); msg.result = 4; m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, &msg, iSendSize, MSG_MAIN_LOADER_MATCH, MSG_ASS_LOADER_MATCH_ENTER_WATCH_DESK, 0, pUser->userID); return false; } if (!IsPlayGame(0)) { ERROR_LOG("本桌游戏结束 :%d", m_deskIdx); msg.result = 1; m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, &msg, iSendSize, MSG_MAIN_LOADER_MATCH, MSG_ASS_LOADER_MATCH_ENTER_WATCH_DESK, 0, pUser->userID); return false; } // 不能同时旁观两个桌子 if (pUser->watchDeskIdx != INVALID_DESKIDX) { ERROR_LOG("已经有旁观桌子了 pUser->watchDeskIdx=%d", pUser->watchDeskIdx); msg.result = 2; m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, &msg, iSendSize, MSG_MAIN_LOADER_MATCH, MSG_ASS_LOADER_MATCH_ENTER_WATCH_DESK, 0, pUser->userID); return false; } // 游戏中不能去旁观其它玩家 CGameDesk* pDesk = m_pDataManage->GetDeskObject(pUser->deskIdx); if (pDesk && pDesk->IsPlayGame(0)) { ERROR_LOG("游戏中不能旁观,userID=%d", pUser->userID); msg.result = 3; m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, &msg, iSendSize, MSG_MAIN_LOADER_MATCH, MSG_ASS_LOADER_MATCH_ENTER_WATCH_DESK, 0, pUser->userID); return false; } // 发送玩家 char buf[MAX_TEMP_SENDBUF_SIZE] = ""; buf[0] = 0; int realSize = 0; MakeAllUserInfo(buf + 1, sizeof(buf) - 1, realSize); memcpy(&msg, buf, realSize); iSendSize = realSize + 1; m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, &msg, iSendSize, MSG_MAIN_LOADER_MATCH, MSG_ASS_LOADER_MATCH_ENTER_WATCH_DESK, 0, pUser->userID); //发送用户游戏状态(游戏实现) OnGetGameStation(INVALID_DESKSTATION, pUser->socketIdx, true); // 加入旁观 pUser->watchDeskIdx = m_deskIdx; m_matchWatchUserID.insert(pUser->userID); return true; } // 比赛场退出本桌旁观 bool CGameDesk::MatchQuitMyDeskWatch(GameUserInfo * pUser, int socketIdx, BYTE result) { if (!pUser) { return false; } pUser->watchDeskIdx = INVALID_DESKIDX; m_matchWatchUserID.erase(pUser->userID); if (pUser->socketIdx <= 0) { return true; } LoaderMatchQuitWatch msg; msg.result = result; m_pDataManage->m_pGServerConnect->SendData(pUser->socketIdx, &msg, sizeof(msg), MSG_MAIN_LOADER_MATCH, MSG_ASS_LOADER_MATCH_QUIT_WATCH_DESK, 0, pUser->userID); return true; } bool CGameDesk::ChangeUserPointMatchRoom(long long *arPoint) { if (!arPoint) { ERROR_LOG("invalid arPoint"); return false; } CRedisLoader* pRedis = m_pDataManage->GetRedis(); if (!pRedis) { ERROR_LOG("redis initialized failed"); return false; } LoaderNotifyUserMatchRoomGrade userGrade; for (size_t i = 0; i < m_deskUserInfoVec.size(); i++) { if (i >= MAX_PLAYER_GRADE) { break; } int userID = m_deskUserInfoVec[i].userID; if (userID <= 0) { continue; } GameUserInfo* pUser = m_pDataManage->GetUser(userID); if (!pUser) { continue; } pRedis->SetUserTotalGameCount(userID); if (arPoint[i] > 0) { pRedis->SetUserWinCount(userID); } pUser->matchSocre += (int)arPoint[i]; userGrade.changeGrade[i] = (int)arPoint[i]; userGrade.grade[i] = pUser->matchSocre; } m_finishedTime = time(NULL); BroadcastDeskData(&userGrade, sizeof(userGrade), MSG_MAIN_LOADER_NOTIFY, MSG_NTF_LOADER_DESK_MATCH_GRADE); return true; } bool CGameDesk::ChangeUserPointMatchRoom(int *arPoint) { if (NULL == arPoint) { return false; } long long llArPont[MAX_PLAYER_GRADE] = { 0 }; for (int i = 0; i < m_iConfigCount; i++) { llArPont[i] = arPoint[i]; } return ChangeUserPointMatchRoom(llArPont); }
412
0.753162
1
0.753162
game-dev
MEDIA
0.682833
game-dev
0.971377
1
0.971377
Mercury-Language/mercury
17,117
compiler/follow_code.m
%-----------------------------------------------------------------------------% % vim: ft=mercury ts=4 sw=4 et %-----------------------------------------------------------------------------% % Copyright (C) 1994-2012 The University of Melbourne. % Copyright (C) 2014-2015, 2018, 2020-2023, 2025 The Mercury team. % This file may only be copied under the terms of the GNU General % Public License - see the file COPYING in the Mercury distribution. %-----------------------------------------------------------------------------% % % File: follow_code.m. % Main author: conway. % Extensive modifications by zs. % % The problem attacked by this module is that sometimes the code generator % doesn't know where it should put the values of live variables at the end % of a branched control structure. All branches must put each live variable % into the same lval, so having each branch leave each live variable where it % just happens to be is not an option. We currently just put all live variables % into its own rN register or stack slot, but often is not where the variable % happens to be at the end of any branch, nor is it where the variable is next % needed. % % The idea used by this module to attack this problem is to try to ensure % that the branched control structure is followed immediately either by a call % or by the end of the procedure body, because both have clear rules about % where every live variable must be. If a branched control structure is % followed by builtin goals such as unifications, we push those goals into % each branch. % %-----------------------------------------------------------------------------% :- module ll_backend.follow_code. :- interface. :- import_module hlds. :- import_module hlds.hlds_module. :- import_module hlds.hlds_pred. %-----------------------------------------------------------------------------% :- pred move_follow_code_in_proc(pred_proc_id::in, proc_info::in, proc_info::out, module_info::in, module_info::out) is det. %-----------------------------------------------------------------------------% %-----------------------------------------------------------------------------% :- implementation. :- import_module check_hlds. :- import_module check_hlds.recompute_instmap_deltas. :- import_module hlds.code_model. :- import_module hlds.goal_util. :- import_module hlds.hlds_goal. :- import_module hlds.hlds_markers. :- import_module hlds.hlds_proc_util. :- import_module hlds.hlds_rtti. :- import_module hlds.instmap. :- import_module hlds.quantification. :- import_module parse_tree. :- import_module parse_tree.prog_data. :- import_module parse_tree.prog_detism. :- import_module parse_tree.set_of_var. :- import_module bool. :- import_module list. :- import_module require. %-----------------------------------------------------------------------------% move_follow_code_in_proc(_PredProcId, !ProcInfo, !ModuleInfo) :- proc_info_get_goal(!.ProcInfo, Goal0), proc_info_get_var_table(!.ProcInfo, VarTable0), proc_info_get_rtti_varmaps(!.ProcInfo, RttiVarMaps0), move_follow_code_in_goal(Goal0, Goal1, RttiVarMaps0, no, Changed), ( Changed = yes, % We need to fix up the goal_info by recalculating the nonlocal % vars and the non-atomic instmap deltas. proc_info_get_headvars(!.ProcInfo, HeadVars), implicitly_quantify_clause_body_general(ord_nl_no_lambda, HeadVars, _Warnings, Goal1, Goal2, VarTable0, VarTable, RttiVarMaps0, RttiVarMaps), proc_info_get_initial_instmap(!.ModuleInfo, !.ProcInfo, InstMap0), proc_info_get_inst_varset(!.ProcInfo, InstVarSet), recompute_instmap_delta(no_recomp_atomics, VarTable, InstVarSet, InstMap0, Goal2, Goal, !ModuleInfo), proc_info_set_goal(Goal, !ProcInfo), proc_info_set_var_table(VarTable, !ProcInfo), proc_info_set_rtti_varmaps(RttiVarMaps, !ProcInfo) ; Changed = no ). %-----------------------------------------------------------------------------% %-----------------------------------------------------------------------------% :- pred move_follow_code_in_goal(hlds_goal::in, hlds_goal::out, rtti_varmaps::in, bool::in, bool::out) is det. move_follow_code_in_goal(Goal0, Goal, RttiVarMaps, !Changed) :- Goal0 = hlds_goal(GoalExpr0, GoalInfo), ( GoalExpr0 = conj(ConjType, Goals0), ( ConjType = plain_conj, ConjPurity = goal_info_get_purity(GoalInfo), move_follow_code_in_conj(Goals0, ConjPurity, RttiVarMaps, Goals, !Changed) ; ConjType = parallel_conj, move_follow_code_in_independent_goals(Goals0, Goals, RttiVarMaps, !Changed) ), GoalExpr = conj(ConjType, Goals), Goal = hlds_goal(GoalExpr, GoalInfo) ; GoalExpr0 = disj(Goals0), move_follow_code_in_independent_goals(Goals0, Goals, RttiVarMaps, !Changed), GoalExpr = disj(Goals), Goal = hlds_goal(GoalExpr, GoalInfo) ; GoalExpr0 = negation(SubGoal0), move_follow_code_in_goal(SubGoal0, SubGoal, RttiVarMaps, !Changed), GoalExpr = negation(SubGoal), Goal = hlds_goal(GoalExpr, GoalInfo) ; GoalExpr0 = switch(Var, Det, Cases0), move_follow_code_in_cases(Cases0, Cases, RttiVarMaps, !Changed), GoalExpr = switch(Var, Det, Cases), Goal = hlds_goal(GoalExpr, GoalInfo) ; GoalExpr0 = if_then_else(Vars, Cond0, Then0, Else0), move_follow_code_in_goal(Cond0, Cond, RttiVarMaps, !Changed), move_follow_code_in_goal(Then0, Then, RttiVarMaps, !Changed), move_follow_code_in_goal(Else0, Else, RttiVarMaps, !Changed), GoalExpr = if_then_else(Vars, Cond, Then, Else), Goal = hlds_goal(GoalExpr, GoalInfo) ; GoalExpr0 = scope(Reason, SubGoal0), ( if Reason = from_ground_term(_, FGT), ( FGT = from_ground_term_construct ; FGT = from_ground_term_deconstruct ) then SubGoal = SubGoal0 else move_follow_code_in_goal(SubGoal0, SubGoal, RttiVarMaps, !Changed) ), GoalExpr = scope(Reason, SubGoal), Goal = hlds_goal(GoalExpr, GoalInfo) ; ( GoalExpr0 = generic_call(_, _, _, _, _) ; GoalExpr0 = plain_call(_, _, _, _, _, _) ; GoalExpr0 = unify(_, _, _, _, _) ; GoalExpr0 = call_foreign_proc(_, _, _, _, _, _, _) ), Goal = Goal0 ; GoalExpr0 = shorthand(_), % These should have been expanded out by now. unexpected($pred, "shorthand") ). %-----------------------------------------------------------------------------% % move_follow_code_in_independent_goals is used both for disjunction and % parallel conjunction. % :- pred move_follow_code_in_independent_goals(list(hlds_goal)::in, list(hlds_goal)::out, rtti_varmaps::in, bool::in, bool::out) is det. move_follow_code_in_independent_goals([], [], _, !Changed). move_follow_code_in_independent_goals([Goal0 | Goals0], [Goal | Goals], RttiVarMaps, !Changed) :- move_follow_code_in_goal(Goal0, Goal, RttiVarMaps, !Changed), move_follow_code_in_independent_goals(Goals0, Goals, RttiVarMaps, !Changed). %-----------------------------------------------------------------------------% :- pred move_follow_code_in_cases(list(case)::in, list(case)::out, rtti_varmaps::in, bool::in, bool::out) is det. move_follow_code_in_cases([], [], _, !Changed). move_follow_code_in_cases([Case0 | Cases0], [Case | Cases], RttiVarMaps, !Changed) :- Case0 = case(MainConsId, OtherConsIds, Goal0), move_follow_code_in_goal(Goal0, Goal, RttiVarMaps, !Changed), Case = case(MainConsId, OtherConsIds, Goal), move_follow_code_in_cases(Cases0, Cases, RttiVarMaps, !Changed). %-----------------------------------------------------------------------------% % Find the first branched structure, and split the conj into those goals % before and after it. % :- pred move_follow_code_in_conj(list(hlds_goal)::in, purity::in, rtti_varmaps::in, list(hlds_goal)::out, bool::in, bool::out) is det. move_follow_code_in_conj(Goals0, ConjPurity, RttiVarMaps, Goals, !Changed) :- move_follow_code_in_conj_2(Goals0, ConjPurity, RttiVarMaps, [], RevGoals, !Changed), list.reverse(RevGoals, Goals). :- pred move_follow_code_in_conj_2(list(hlds_goal)::in, purity::in, rtti_varmaps::in, list(hlds_goal)::in, list(hlds_goal)::out, bool::in, bool::out) is det. move_follow_code_in_conj_2([], _ConjPurity, _RttiVarMaps, !RevPrevGoals, !Changed). move_follow_code_in_conj_2([Goal0 | Goals0], ConjPurity, RttiVarMaps, !RevPrevGoals, !Changed) :- ( if Goal0 = hlds_goal(GoalExpr0, GoalInfo0), goal_util.goal_is_branched(GoalExpr0), % A goal that has the mode_check_clauses marker on it will not % have its set of output variables updated by recompute_instmap_delta. % If we move new code into it, this lack of recomputation will % be a bug if that code binds any variables, which it almost certainly % will. not goal_info_has_feature(GoalInfo0, feature_mode_check_clauses_goal), move_follow_code_select(Goals0, RttiVarMaps, FollowGoals, RestGoalsPrime, ConjPurity, WorstPurity), FollowGoals = [_ | _], % Moving any goals that bind variables into a model_semi (or model_det) % disjunction gives that disjunction some outputs, which means that it % will become nondet. ( ( GoalExpr0 = disj(_), goal_info_get_code_model(GoalInfo0) \= model_non ) => no_bind_vars(FollowGoals) ), move_follow_code_move_goals(Goal0, FollowGoals, WorstPurity, Goal1Prime) then !:Changed = yes, Goal1 = Goal1Prime, RestGoals = RestGoalsPrime else Goal1 = Goal0, RestGoals = Goals0 ), move_follow_code_in_goal(Goal1, Goal, RttiVarMaps, !Changed), !:RevPrevGoals = [Goal | !.RevPrevGoals], move_follow_code_in_conj_2(RestGoals, ConjPurity, RttiVarMaps, !RevPrevGoals, !Changed). :- pred no_bind_vars(list(hlds_goal)::in) is semidet. no_bind_vars([]). no_bind_vars([Goal | Goals]) :- Goal = hlds_goal(_, GoalInfo), InstMapDelta = goal_info_get_instmap_delta(GoalInfo), instmap_delta_changed_vars(InstMapDelta, ChangedVars), set_of_var.is_empty(ChangedVars), no_bind_vars(Goals). %-----------------------------------------------------------------------------% % Split a list of goals into the prefix of builtins and the rest. % :- pred move_follow_code_select(list(hlds_goal)::in, rtti_varmaps::in, list(hlds_goal)::out, list(hlds_goal)::out, purity::in, purity::out) is det. move_follow_code_select([], _, [], [], !Purity). move_follow_code_select([Goal | Goals], RttiVarMaps, FollowGoals, RestGoals, !Purity) :- Goal = hlds_goal(GoalExpr, GoalInfo), ( if move_follow_code_is_builtin(GoalExpr), % Don't attempt to move existentially typed deconstructions % into branched structures. Doing so would confuse the % rtti_varmaps structure, which expects type(class)_infos % for a given type variable (constraint) to be retrieved from % a single location. % % XXX A better solution might be to introduce exists_cast goals, % which would allow separate type variables for each branch and % avoid the above confusion. % not ( GoalExpr = unify(_, _, _, Unification, _), Unification = deconstruct(_, _, Args, _, _, _), list.member(Arg, Args), rtti_varmaps_var_info(RttiVarMaps, Arg, RttiVarInfo), RttiVarInfo \= non_rtti_var ) then GoalPurity = goal_info_get_purity(GoalInfo), !:Purity = worst_purity(!.Purity, GoalPurity), move_follow_code_select(Goals, RttiVarMaps, FollowGoals0, RestGoals, !Purity), FollowGoals = [Goal | FollowGoals0] else FollowGoals = [], RestGoals = [Goal | Goals] ). %-----------------------------------------------------------------------------% :- pred move_follow_code_move_goals(hlds_goal::in, list(hlds_goal)::in, purity::in, hlds_goal::out) is semidet. move_follow_code_move_goals(Goal0, FollowGoals, FollowPurity, Goal) :- Goal0 = hlds_goal(GoalExpr0, GoalInfo0), ( GoalExpr0 = switch(Var, Det, Cases0), move_follow_code_move_goals_cases(Cases0, FollowGoals, FollowPurity, Cases), GoalExpr = switch(Var, Det, Cases) ; GoalExpr0 = disj(Goals0), move_follow_code_move_goals_disj(Goals0, FollowGoals, FollowPurity, Goals), GoalExpr = disj(Goals) ; GoalExpr0 = if_then_else(Vars, Cond, Then0, Else0), follow_code_conjoin_goal_and_goal_list(Then0, FollowGoals, FollowPurity, Then), follow_code_conjoin_goal_and_goal_list(Else0, FollowGoals, FollowPurity, Else), GoalExpr = if_then_else(Vars, Cond, Then, Else) ), OldPurity = goal_info_get_purity(GoalInfo0), NewPurity = worst_purity(OldPurity, FollowPurity), goal_info_set_purity(NewPurity, GoalInfo0, GoalInfo), Goal = hlds_goal(GoalExpr, GoalInfo). %-----------------------------------------------------------------------------% :- pred move_follow_code_move_goals_cases(list(case)::in, list(hlds_goal)::in, purity::in, list(case)::out) is semidet. move_follow_code_move_goals_cases([], _FollowGoals, _FollowPurity, []). move_follow_code_move_goals_cases([Case0 | Cases0], FollowGoals, FollowPurity, [Case | Cases]) :- Case0 = case(MainConsId, OtherConsIds, Goal0), follow_code_conjoin_goal_and_goal_list(Goal0, FollowGoals, FollowPurity, Goal), Case = case(MainConsId, OtherConsIds, Goal), move_follow_code_move_goals_cases(Cases0, FollowGoals, FollowPurity, Cases). %-----------------------------------------------------------------------------% :- pred move_follow_code_move_goals_disj(list(hlds_goal)::in, list(hlds_goal)::in, purity::in, list(hlds_goal)::out) is semidet. move_follow_code_move_goals_disj([], _FollowGoals, _FollowPurity, []). move_follow_code_move_goals_disj([Goal0 | Goals0], FollowGoals, FollowPurity, [Goal | Goals]) :- follow_code_conjoin_goal_and_goal_list(Goal0, FollowGoals, FollowPurity, Goal), move_follow_code_move_goals_disj(Goals0, FollowGoals, FollowPurity, Goals). %-----------------------------------------------------------------------------% % Takes a goal and a list of goals, and conjoins them (with a potentially % blank goal_info), checking that the determinism of the goal is not % changed. % :- pred follow_code_conjoin_goal_and_goal_list(hlds_goal::in, list(hlds_goal)::in, purity::in, hlds_goal::out) is semidet. follow_code_conjoin_goal_and_goal_list(Goal0, FollowGoals, FollowPurity, Goal) :- Goal0 = hlds_goal(GoalExpr0, GoalInfo0), Detism0 = goal_info_get_determinism(GoalInfo0), determinism_components(Detism0, _CanFail0, MaxSolns0), ( MaxSolns0 = at_most_zero, Goal = Goal0 ; ( MaxSolns0 = at_most_one ; MaxSolns0 = at_most_many ; MaxSolns0 = at_most_many_cc ), check_follow_code_detism(FollowGoals, Detism0), ( if GoalExpr0 = conj(plain_conj, Conjuncts0) then GoalExpr = conj(plain_conj, Conjuncts0 ++ FollowGoals) else GoalExpr = conj(plain_conj, [Goal0 | FollowGoals]) ), OldPurity = goal_info_get_purity(GoalInfo0), NewPurity = worst_purity(OldPurity, FollowPurity), goal_info_set_purity(NewPurity, GoalInfo0, GoalInfo), Goal = hlds_goal(GoalExpr, GoalInfo) ). % This check is necessary to make sure that follow_code doesn't change % the determinism of the goal. % :- pred check_follow_code_detism(list(hlds_goal)::in, determinism::in) is semidet. check_follow_code_detism([], _). check_follow_code_detism([hlds_goal(_, GoalInfo) | Goals], Detism0) :- Detism1 = goal_info_get_determinism(GoalInfo), det_conjunction_detism(Detism0, Detism1, Detism0), check_follow_code_detism(Goals, Detism0). %-----------------------------------------------------------------------------% :- pred move_follow_code_is_builtin(hlds_goal_expr::in) is semidet. move_follow_code_is_builtin(GoalExpr) :- ( GoalExpr = unify(_, _, _, Unification, _), Unification \= complicated_unify(_, _, _) ; GoalExpr = plain_call(_, _, _, inline_builtin, _, _) ). %-----------------------------------------------------------------------------% :- end_module ll_backend.follow_code. %-----------------------------------------------------------------------------%
412
0.693786
1
0.693786
game-dev
MEDIA
0.297014
game-dev
0.970599
1
0.970599
allenai/ScienceWorld
4,491
simulator/src/main/scala/scienceworld/objects/electricalcomponent/Generator.scala
package scienceworld.objects.electricalcomponent import scienceworld.objects.electricalcomponent.ElectricalComponent.{ROLE_VOLTAGE_GENERATOR, VOLTAGE_GENERATOR, VOLTAGE_GROUND} import scienceworld.objects.location.Outside import scienceworld.properties.{IsActivableDeviceOff, IsActivableDeviceOn, IsNotActivableDeviceOff, IsNotActivableDeviceOn} import scienceworld.struct.EnvObject import scienceworld.struct.EnvObject._ import scala.util.control.Breaks.{break, breakable} /* * Generators */ class Generator(val displayOnOff:Boolean = true) extends PolarizedElectricalComponent { this.name = "generator" this.propDevice = Some(new IsActivableDeviceOn()) this.electricalRole = ROLE_VOLTAGE_GENERATOR // Component uses voltage, rather than generating it override def tick(): Boolean = { // If this generator is activated, then generate a voltage potential at the terminals. if (this.propDevice.get.isActivated) { this.anode.voltage = Some(VOLTAGE_GENERATOR) this.cathode.voltage = Some(VOLTAGE_GROUND) } else { this.anode.voltage = None this.cathode.voltage = None } super.tick() } override def getReferents(): Set[String] = { Set("generator", this.name, this.getDescriptName()) } override def getDescription(mode:Int):String = { val os = new StringBuilder os.append("a " + this.getDescriptName() + "") if (displayOnOff) { os.append(", which is ") if (this.propDevice.get.isActivated) { os.append("on") } else { os.append("off") } } if (mode == MODE_DETAILED) { os.append(". ") os.append("its anode is connected to: " + this.anode.propElectricalConnection.get.getConnectedToStr() + ". ") os.append("its cathode is connected to: " + this.cathode.propElectricalConnection.get.getConnectedToStr() + ". ") } os.toString } } class Battery extends Generator(displayOnOff = false) { this.name = "battery" this.propDevice = Some(new IsNotActivableDeviceOn()) // Always on } // Non-renewable class GasGenerator extends Generator { this.name = "gas generator" this.propDevice = Some(new IsActivableDeviceOff()) } class NuclearGenerator extends Generator { this.name = "nuclear generator" this.propDevice = Some(new IsActivableDeviceOff()) } // Renewable // Renewable generator automatically activates when it's outside (i.e. has access to wind/sunlight) class RenewableOutdoorGenerator extends Generator { this.name = "renewable generator" this.propDevice = Some(new IsNotActivableDeviceOff()) override def tick(): Boolean = { // If this generator is in an outdoor location, then it is activated. breakable { var container = this.getContainer() val maxCount:Int = 10 var count:Int = 0 while (count < maxCount) { if (container.isEmpty) { this.propDevice.get.isActivated = false // Generator not in a container -- deactivate break() } else { container.get match { case x: Outside => { // Is in an outside location -- activate this.propDevice.get.isActivated = true // Generator in an outdoor location -- activate break() } case x: EnvObject => { // Check to see if it's a container if ((container.get.propContainer.isDefined) && (container.get.propContainer.get.isOpen)) { container = container.get.getContainer() // Generator in an open container (e.g. table) -- recurse. } else { this.propDevice.get.isActivated = false // Generator not in an open container -- deactivate break() } } } } count += 1 } // If we reach here, the generator is so deeply nested in containers away from an outdoor location that we'll stop and say it's inaccessible to the things it needs (e.g. wind/solar) this.propDevice.get.isActivated = false } super.tick() } } // Solar panel -- only works in outdoor environment class SolarPanel extends RenewableOutdoorGenerator { this.name = "solar panel" this.propDevice = Some(new IsNotActivableDeviceOff()) } // Wind generator -- only works in outdoor environment class WindGenerator extends RenewableOutdoorGenerator { this.name = "wind generator" this.propDevice = Some(new IsNotActivableDeviceOff()) }
412
0.547073
1
0.547073
game-dev
MEDIA
0.355935
game-dev
0.523669
1
0.523669
Monkestation/Monkestation2.0
3,035
code/datums/ai/movement/_ai_movement.dm
///This datum is an abstract class that can be overriden for different types of movement /datum/ai_movement ///Assoc list ist of controllers that are currently moving as key, and what they are moving to as value var/list/moving_controllers = list() ///How many times a given controller can fail on their route before they just give up var/max_pathing_attempts //Override this to setup the moveloop you want to use /datum/ai_movement/proc/start_moving_towards(datum/ai_controller/controller, atom/current_movement_target, min_distance) SHOULD_CALL_PARENT(TRUE) controller.consecutive_pathing_attempts = 0 controller.set_blackboard_key(BB_CURRENT_MIN_MOVE_DISTANCE, min_distance) moving_controllers[controller] = current_movement_target /datum/ai_movement/proc/stop_moving_towards(datum/ai_controller/controller) controller.consecutive_pathing_attempts = 0 moving_controllers -= controller // We got deleted as we finished an action if(!QDELETED(controller.pawn)) SSmove_manager.stop_looping(controller.pawn, SSai_movement) /datum/ai_movement/proc/increment_pathing_failures(datum/ai_controller/controller) controller.consecutive_pathing_attempts++ if(controller.consecutive_pathing_attempts >= max_pathing_attempts) controller.CancelActions() /datum/ai_movement/proc/reset_pathing_failures(datum/ai_controller/controller) controller.consecutive_pathing_attempts = 0 ///Should the movement be allowed to happen? As of writing this, MOVELOOP_SKIP_STEP is defined as (1<<0) so be careful on using (return TRUE) or (can_move = TRUE; return can_move) /datum/ai_movement/proc/allowed_to_move(datum/move_loop/source) var/atom/movable/pawn = source.moving var/datum/ai_controller/controller = source.extra_info source.delay = controller.movement_delay var/can_move = TRUE if(controller.ai_traits & STOP_MOVING_WHEN_PULLED && pawn.pulledby) //Need to store more state. Annoying. can_move = FALSE if(!isturf(pawn.loc)) //No moving if not on a turf can_move = FALSE // Check if this controller can actually run, so we don't chase people with corpses if(!controller.able_to_run()) controller.CancelActions() qdel(source) //stop moving return MOVELOOP_SKIP_STEP //Why doesn't this return TRUE or can_move? //MOVELOOP_SKIP_STEP is defined as (1<<0) and TRUE are defined as the same "1", returning TRUE would be the equivalent of skipping the move if(can_move) return increment_pathing_failures(controller) return MOVELOOP_SKIP_STEP ///Anything to do before moving; any checks if the pawn should be able to move should be placed in allowed_to_move() and called by this proc /datum/ai_movement/proc/pre_move(datum/move_loop/source) SIGNAL_HANDLER return allowed_to_move(source) //Anything to do post movement /datum/ai_movement/proc/post_move(datum/move_loop/source, succeeded) SIGNAL_HANDLER var/datum/ai_controller/controller = source.extra_info switch(succeeded) if(MOVELOOP_SUCCESS) reset_pathing_failures(controller) if(MOVELOOP_FAILURE) increment_pathing_failures(controller)
412
0.896744
1
0.896744
game-dev
MEDIA
0.450781
game-dev
0.954373
1
0.954373
one-for-all/gorilla-physics
7,129
src/control/mod.rs
use crate::joint::{JointTorque, ToJointTorqueVec}; use crate::PI; use na::{dvector, DVector}; use crate::{mechanism::MechanismState, types::Float, GRAVITY}; pub mod SLIP_control; pub mod biped_control; pub mod energy_control; pub mod gripper_control; pub mod hopper_control; pub mod kinematic_loop; pub mod leg_control; pub mod lqr; pub mod navbot_control; pub mod pusher_control; pub mod quadruped_control; pub mod servo; pub mod so101_control; pub mod swingup; pub struct ControlInput { floats: Vec<Float>, } impl ControlInput { pub fn new(floats: Vec<Float>) -> Self { ControlInput { floats } } } pub trait Controller { fn control( &mut self, state: &mut MechanismState, input: Option<&ControlInput>, ) -> Vec<JointTorque>; } pub struct NullController {} impl Controller for NullController { fn control( &mut self, _state: &mut MechanismState, _input: Option<&ControlInput>, ) -> Vec<JointTorque> { vec![] } } /// Control algorithm that effectively inverts the gravity for a pendulum system. /// u = 2mglsin(q) - Bv /// where q is the angle from the bottom, and Bv is the damping term. /// /// Reference: https://underactuated.csail.mit.edu/pend.html#section2 pub fn pendulum_gravity_inversion(state: &MechanismState) -> Vec<JointTorque> { let mass = state.bodies[0].inertia.mass; let length_to_com = state.bodies[0].inertia.center_of_mass().norm(); let q = state.q[0].float(); let gravity_inversion = 2.0 * mass * GRAVITY * length_to_com * q.sin(); let damping = -10.0 * state.v[0].float(); let torque = gravity_inversion + damping; vec![torque].to_joint_torque_vec() } /// Control algorithm that pumps energy into the system to achieve the desired /// energy which places the pendulum at the top. /// u = -k * qdot * (E - E_desired), k > 0 /// It shapes the energy error dynamics into: /// E_error_dot = -k * qdot * qdot * E_error /// which implies an exponential convergence. /// /// Note: it might not work as amazingly here in sim, due to numerical error. /// /// Reference: https://underactuated.csail.mit.edu/pend.html#section3 pub fn pendulum_energy_shaping(state: &MechanismState) -> Vec<JointTorque> { let mass = state.bodies[0].inertia.mass; let length_to_com = state.bodies[0].inertia.center_of_mass().norm(); let moment = state.bodies[0].inertia.moment; let axis = state.treejoints[0].axis(); let q = state.q[0].float(); let v = state.v[0].float(); let omega = axis * v; let E_desired = mass * GRAVITY * length_to_com; let KE = (0.5 * omega.transpose() * moment * omega)[0]; let PE = mass * GRAVITY * length_to_com * (-q.cos()); let E_diff = KE + PE - E_desired; let torque = -0.1 * v * E_diff; vec![torque].to_joint_torque_vec() } pub fn pendulum_swing_up_and_balance(state: &MechanismState) -> Vec<JointTorque> { let q = state.q[0].float(); if (q - PI).abs() > 0.15 { pendulum_energy_shaping(state) // Swing up } else { pendulum_gravity_inversion(state) // Balance } } /// PID controller for double pendulum around upright position /// actually with only P & D terms at the moment pub fn pid(state: &MechanismState) -> DVector<Float> { let q1 = state.q[0].float(); let q2 = state.q[1].float(); let v1 = state.v[0].float(); let v2 = state.v[1].float(); let kp1 = 5000.0; let kd1 = 100.0; let kp2 = 5000.0; let kd2 = 100.0; let q1_desired = -PI; let q2_desired = 0.0; let q1_error = q1_desired - q1; let q2_error = q2_desired - q2; let v1_error = 0.0 - v1; let v2_error = 0.0 - v2; let torque1 = kp1 * q1_error + kd1 * v1_error; let torque2 = kp2 * q2_error + kd2 * v2_error; dvector![torque1, torque2] } #[cfg(test)] mod control_tests { use crate::integrators::Integrator; use crate::joint::ToJointPositionVec; use crate::joint::ToJointVelocityVec; use crate::{simulate::simulate, PI}; use na::Isometry3; use na::Vector3; use na::{vector, Matrix3}; use super::*; /// Pendulum created at bottom position, and then slightly displaced. #[test] fn test_pendulum_gravity_inversion() { // Arrange let m = 5.0; let l = 7.0; let moment_x = 1.0 / 3.0 * m * l * l; let moment_y = 1.0 / 3.0 * m * l * l; let moment_z = 0.0; let moment = Matrix3::from_diagonal(&vector![moment_x, moment_y, moment_z]); let cross_part = vector![0.0, 0.0, -m * l / 2.0]; let rod_to_world = Isometry3::identity(); // transformation from rod to world frame let axis = Vector3::y_axis(); // axis of joint rotation let mut state = crate::helpers::build_pendulum(m, &moment, &cross_part, &rod_to_world, axis); let q_init = vec![0.1].to_joint_pos_vec(); // give it some initial displacement let v_init = vec![0.0].to_joint_vel_vec(); state.update(&q_init, &v_init); // Act let final_time = 200.0; let dt = 0.01; let (qs, vs) = simulate( &mut state, final_time, dt, pendulum_gravity_inversion, &Integrator::RungeKutta4, ); // Assert let q_final = qs.as_slice().last().unwrap()[0].float(); let q_error = q_final - PI; assert!( q_error.abs() < 1e-3, "Pendulum should swing to the top. q error: {}", q_error ); let v_final = vs.as_slice().last().unwrap()[0].float(); assert!( v_final.abs() < 1e-4, "Pendulum should stop at the top, v: {}", v_final ); } #[test] fn test_pendulum_energy_shaping() { // Arrange let m = 5.0; let l = 7.0; let moment_x = 1.0 / 3.0 * m * l * l; let moment_y = 1.0 / 3.0 * m * l * l; let moment_z = 0.0; let moment = Matrix3::from_diagonal(&vector![moment_x, moment_y, moment_z]); let cross_part = vector![0.0, 0.0, -m * l / 2.0]; let rod_to_world = Isometry3::identity(); // transformation from rod to world frame let axis = Vector3::y_axis(); // axis of joint rotation let mut state = crate::helpers::build_pendulum(m, &moment, &cross_part, &rod_to_world, axis); let q_init = vec![0.0].to_joint_pos_vec(); let v_init = vec![0.1].to_joint_vel_vec(); // give it some initial velocity state.update(&q_init, &v_init); // Act let final_time = 50.0; let dt = 0.01; let (qs, _vs) = simulate( &mut state, final_time, dt, pendulum_energy_shaping, &Integrator::SemiImplicitEuler, ); // Assert let q_max = qs .iter() .map(|q| q[0].float().clone()) .fold(Float::NEG_INFINITY, Float::max); assert!( q_max > 3.0, "Pendulum should swing to near the top. q_max: {}", q_max ); } }
412
0.952122
1
0.952122
game-dev
MEDIA
0.491749
game-dev
0.952292
1
0.952292
GateteVerde/Gatete-Mario-Engine-9
3,816
Gatete Mario Engine 9/objects/obj_powerup_sprout/Alarm_0.gml
/// @description Item check //Heart if (sprite_index == spr_heart) { //If health mode is activated, replace this with a mushroom if (global.hp_mode == true) sprite_index = spr_mushroom; } //Leaf else if (sprite_index == spr_leaf) { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); //Turn into a real leaf if (yspeed > 0) { with (instance_create_depth(x, ystart + 16, 11, obj_leaf_sprout)) alarm[1] = 1; } else instance_create_depth(x, ystart, 11, obj_leaf_sprout); } //Feather else if (sprite_index == spr_feather) { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); //Turn into a real feather if (yspeed > 0) { with (instance_create_depth(x, ystart + 16, 11, obj_feather_sprout)) alarm[1] = 1; } else instance_create_depth(x, ystart, 11, obj_feather_sprout); } //Propeller Mushroom else if (sprite_index == spr_propellershroom) { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); //Turn into a real leaf if (yspeed > 0) { with (instance_create_depth(x, ystart + 16, 11, obj_propellershroom_sprout)) { xspeed = 1; alarm[1] = 1; } } else instance_create_depth(x, ystart, 11, obj_propellershroom_sprout); } //Superbell else if ((yspeed < 0) && (sprite_index == spr_superbell)) { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); //Turn into a superbell with (instance_create_depth(x, ystart, 11, obj_superbell)) { depth = 10; yspeed = -4; } } //Fiery Leaf else if (sprite_index == spr_fieryleaf) { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); //Turn into a real leaf if (yspeed > 0) { with (instance_create_depth(x, ystart + 16, 11, obj_fieryleaf_sprout)) alarm[1] = 1; } else instance_create_depth(x, ystart, 11, obj_fieryleaf_sprout); } //Chill Leaf else if (sprite_index == spr_chillleaf) { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); //Turn into a real leaf if (yspeed > 0) { with (instance_create_depth(x, ystart + 16, 11, obj_chillleaf_sprout)) alarm[1] = 1; } else instance_create_depth(x, ystart, 11, obj_chillleaf_sprout); } //Beanstalk else if (sprite_index == spr_beanstalk) { instance_create_layer(x, ystart, "Main", obj_beanstalk); } //Side Beanstalk else if (sprite_index == spr_beanstalk_side) { with (instance_create_layer(x, ystart, "Main", obj_beanstalk)) { sprite_index = spr_beanstalk_side; vinetype = 1; } } //Otherwise else { //Play 'Sprout' sound audio_play_sound(snd_sprout, 0, false); if (big == 1) { shake_camera(6, ceil(audio_sound_length(snd_sprout) * room_speed), true); } //If moving up... if (yspeed < 0) { //...and the sprite is one of the following, make it bounce. if (sprite_index == spr_pswitch) || (sprite_index == spr_gswitch) || (sprite_index == spr_trampoline) || (sprite_index == spr_key) || (sprite_index == spr_propellerblock) || (sprite_index == spr_powblock) || (sprite_index == spr_billygun) || (sprite_index == spr_egg) || (sprite_index == spr_egg_r) || (sprite_index == spr_egg_y) || (sprite_index == spr_egg_b) || (sprite_index == spr_egg_t) || (sprite_index == spr_egg_p) || (sprite_index == spr_shoe_kuribo) || (sprite_index == spr_shoe_baburu) || (sprite_index == spr_shoe_dossun) || (sprite_index == spr_shoe_jugemu) || (sprite_index == spr_shoe_pentaro) { //Set vertical speed yspeed = (place_meeting(x, y, obj_swim)) ? -1.25 : -2.5; //Deny solid check readytogo = 1; //Make it bounce outside the block bouncy = 1; } } //Exit exit; } //Destroy instance_destroy();
412
0.612557
1
0.612557
game-dev
MEDIA
0.855905
game-dev
0.899671
1
0.899671
pablushaa/AllahClientRecode
5,407
net/minecraft/advancements/critereon/MobEffectsPredicate.java
package net.minecraft.advancements.critereon; import com.google.common.collect.Maps; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.JsonUtils; import net.minecraft.util.ResourceLocation; public class MobEffectsPredicate { public static final MobEffectsPredicate field_193473_a = new MobEffectsPredicate(Collections.emptyMap()); private final Map<Potion, MobEffectsPredicate.InstancePredicate> field_193474_b; public MobEffectsPredicate(Map<Potion, MobEffectsPredicate.InstancePredicate> p_i47538_1_) { this.field_193474_b = p_i47538_1_; } public boolean func_193469_a(Entity p_193469_1_) { if (this == field_193473_a) { return true; } else { return p_193469_1_ instanceof EntityLivingBase ? this.func_193470_a(((EntityLivingBase)p_193469_1_).func_193076_bZ()) : false; } } public boolean func_193472_a(EntityLivingBase p_193472_1_) { return this == field_193473_a ? true : this.func_193470_a(p_193472_1_.func_193076_bZ()); } public boolean func_193470_a(Map<Potion, PotionEffect> p_193470_1_) { if (this == field_193473_a) { return true; } else { for (Entry<Potion, MobEffectsPredicate.InstancePredicate> entry : this.field_193474_b.entrySet()) { PotionEffect potioneffect = p_193470_1_.get(entry.getKey()); if (!((MobEffectsPredicate.InstancePredicate)entry.getValue()).func_193463_a(potioneffect)) { return false; } } return true; } } public static MobEffectsPredicate func_193471_a(@Nullable JsonElement p_193471_0_) { if (p_193471_0_ != null && !p_193471_0_.isJsonNull()) { JsonObject jsonobject = JsonUtils.getJsonObject(p_193471_0_, "effects"); Map<Potion, MobEffectsPredicate.InstancePredicate> map = Maps.<Potion, MobEffectsPredicate.InstancePredicate>newHashMap(); for (Entry<String, JsonElement> entry : jsonobject.entrySet()) { ResourceLocation resourcelocation = new ResourceLocation(entry.getKey()); Potion potion = Potion.REGISTRY.getObject(resourcelocation); if (potion == null) { throw new JsonSyntaxException("Unknown effect '" + resourcelocation + "'"); } MobEffectsPredicate.InstancePredicate mobeffectspredicate$instancepredicate = MobEffectsPredicate.InstancePredicate.func_193464_a(JsonUtils.getJsonObject(entry.getValue(), entry.getKey())); map.put(potion, mobeffectspredicate$instancepredicate); } return new MobEffectsPredicate(map); } else { return field_193473_a; } } public static class InstancePredicate { private final MinMaxBounds field_193465_a; private final MinMaxBounds field_193466_b; @Nullable private final Boolean field_193467_c; @Nullable private final Boolean field_193468_d; public InstancePredicate(MinMaxBounds p_i47497_1_, MinMaxBounds p_i47497_2_, @Nullable Boolean p_i47497_3_, @Nullable Boolean p_i47497_4_) { this.field_193465_a = p_i47497_1_; this.field_193466_b = p_i47497_2_; this.field_193467_c = p_i47497_3_; this.field_193468_d = p_i47497_4_; } public boolean func_193463_a(@Nullable PotionEffect p_193463_1_) { if (p_193463_1_ == null) { return false; } else if (!this.field_193465_a.func_192514_a((float)p_193463_1_.getAmplifier())) { return false; } else if (!this.field_193466_b.func_192514_a((float)p_193463_1_.getDuration())) { return false; } else if (this.field_193467_c != null && this.field_193467_c.booleanValue() != p_193463_1_.getIsAmbient()) { return false; } else { return this.field_193468_d == null || this.field_193468_d.booleanValue() == p_193463_1_.doesShowParticles(); } } public static MobEffectsPredicate.InstancePredicate func_193464_a(JsonObject p_193464_0_) { MinMaxBounds minmaxbounds = MinMaxBounds.func_192515_a(p_193464_0_.get("amplifier")); MinMaxBounds minmaxbounds1 = MinMaxBounds.func_192515_a(p_193464_0_.get("duration")); Boolean obool = p_193464_0_.has("ambient") ? JsonUtils.getBoolean(p_193464_0_, "ambient") : null; Boolean obool1 = p_193464_0_.has("visible") ? JsonUtils.getBoolean(p_193464_0_, "visible") : null; return new MobEffectsPredicate.InstancePredicate(minmaxbounds, minmaxbounds1, obool, obool1); } } }
412
0.6446
1
0.6446
game-dev
MEDIA
0.443584
game-dev
0.830951
1
0.830951
intel/systemc-compiler
42,179
sc_tool/lib/sc_tool/elab/ScObjectView.cpp
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ /** * Author: Roman Popov */ #include "ScObjectView.h" #include <sc_tool/elab/ScElabDatabase.h> #include <sc_tool/diag/ScToolDiagnostic.h> #include <sc_tool/utils/DebugOptions.h> #include <sc_tool/ScCommandLine.h> #include <sc_tool/elab/ScVerilogModule.h> #include <sc_tool/utils/ScTypeTraits.h> #include <sc_tool/utils/CppTypeTraits.h> #include <sc_tool/dyn_elab/GlobalContext.h> #include <clang/AST/DeclTemplate.h> #include <llvm/Support/Debug.h> #include <variant> using namespace sc; using namespace llvm; using std::cout; using std::endl; namespace sc_elab { // Number of module and process instances, to print statistic size_t modNum; size_t procNum; // ObjectView ----------------------------------------------------------------- ObjectView::ObjectView(const sc_elab::Object *obj, const sc_elab::ElabDatabase *db) : obj(obj), db(db) { SCT_TOOL_ASSERT (obj != nullptr, "Object is null"); SCT_TOOL_ASSERT (db != nullptr, "DB is null"); } bool operator == (const ObjectView& one, const ObjectView& other) { return (one.obj == other.obj) && (one.db == other.db); } bool operator != (const ObjectView& one, const ObjectView& other) { return !(one == other); } clang::QualType ObjectView::getType() const { return db->getType(obj->type_id()); } bool ObjectView::isPointerOrRef() const { return isPrimitive() && (primitive()->isPointer() || primitive()->isReference()); } bool ObjectView::isChannel() const { if (isSignal()) return true; if (isPrimitive() && primitive()->isPort()) return true; return false; } bool ObjectView::isTopMod() const { return obj->id() == 0; } ElabObjVec ObjectView::getPointers() const { ElabObjVec res; for (auto pointerID : obj->pointer_ids()) { ObjectView pointer = db->getObj(pointerID); if (!pointer.primitive()->isPort()) res.push_back(pointer); } return res; } ElabObjVec ObjectView::getPorts() const { ElabObjVec res; for (auto pointerID : obj->pointer_ids()) { ObjectView pointer = db->getObj(pointerID); if (pointer.primitive()->isPort()) res.push_back(pointer); } return res; } ObjectView ObjectView::getParent() const { SCT_TOOL_ASSERT (!isTopMod(), ""); return db->getObj(obj->parent_ids(0)); } ModuleMIFView ObjectView::getParentModule() const { if(isTopMod()) return *this; auto parent = getParent(); while (!parent.isModule()) parent = parent.getParent(); return parent; } ModuleMIFView ObjectView::getParentModuleOrMIF() const { if(isTopMod()) return *this; auto parent = getParent(); while (!(parent.isModule() || parent.isModularInterface())) parent = parent.getParent(); return parent; } ModuleMIFView ObjectView::nearestCommonParentModule(ObjectView other) const { auto thisParents = this->getParentModulesList(); auto otherParents = other.getParentModulesList(); const auto minSize = std::min(thisParents.size(), otherParents.size()); for (size_t i = 0; i < minSize; ++i) { if (thisParents[i] != otherParents[i]) return thisParents[i-1]; } return thisParents[minSize-1]; } std::deque<ModuleMIFView> ObjectView::getParentModulesList() const { return getParentModulesList(*db->getObj(0).moduleMIF()); } std::deque<ModuleMIFView> ObjectView::getParentModulesList(const ModuleMIFView &rootMod) const { std::deque<ModuleMIFView> res; auto parentMod = *this; do { parentMod = parentMod.getParentModule(); res.push_front(parentMod); } while (parentMod != rootMod ); return res; } std::optional<uint32_t> ObjectView::getElementIndex() const { if (isArrayElement()) return obj->array_idx(); else return std::nullopt; } namespace { struct PtrNode {}; struct ArrNode { uint32_t idx; }; struct FieldNode { const clang::FieldDecl *fieldDecl; }; struct BaseNode { clang::QualType type; }; struct RootNode { ObjectView root; }; using NodeT = std::variant<PtrNode,ArrNode,FieldNode,BaseNode, RootNode>; std::deque<NodeT> getHierarchyNodeVec(ObjectView obj) { std::deque<NodeT> resPath; /// Traverse the tree back to parent module while (!obj.isModule()) { if (obj.isDynamic()) { if (obj.getPointers().size() > 0) { obj = obj.getPointers()[0]; resPath.emplace_front(PtrNode()); } else if (obj.isArrayLike()) { // pointer to first element of array interpreted as array pointer auto firstEl = obj.array()->at(0); SCT_TOOL_ASSERT (firstEl.getPointers().size() == 1, ""); obj = firstEl.getPointers()[0]; resPath.emplace_front(PtrNode()); } else { llvm_unreachable("ObjectView: Can not find pointer to object"); } } else { if (obj.isArrayElement()) { resPath.emplace_front( ArrNode {*obj.getElementIndex()} ); obj = obj.getParent(); } else if (obj.isDataMember() || obj.isStatic()) { resPath.emplace_front( FieldNode{obj.getFieldDecl()} ); obj = obj.getParent(); } else if (obj.isBaseClass()) { resPath.emplace_front( BaseNode{ obj.getType() } ); obj = obj.getParent(); } else if (obj.hasNoParent()) { return {}; } else { llvm_unreachable("ObjectView::selectAllSimilarArrayElements bad query"); } } } resPath.emplace_front( RootNode{ obj } ); return resPath; } void retriveObjectsRec( std::deque<NodeT> hierPath, ObjectView curObj, const IndexVec &indices, ArrayElemVec &resVec, bool getAllArrayElements) { if (hierPath.empty()) { resVec.push_back({curObj, indices}); } else { auto node = hierPath.front(); hierPath.pop_front(); if (std::get_if<PtrNode>(&node)) { auto ptr = *curObj.primitive()->ptrOrRef(); if (auto pointee = ptr.pointeeOrArray() ) { retriveObjectsRec(hierPath, *pointee, indices, resVec, getAllArrayElements); } else { return; } } else if (std::get_if<ArrNode>(&node)) { auto arrayObj = *curObj.array(); auto newIndicies = indices; newIndicies.push_back(0); for (unsigned i = 0; i < arrayObj.size(); ++i) { auto el = arrayObj.at(i); newIndicies.back() = i; retriveObjectsRec(hierPath, el, newIndicies, resVec, getAllArrayElements); if (!getAllArrayElements) break; } } else if (auto fieldNode = std::get_if<FieldNode>(&node)) { auto fieldObj = *curObj.record()->getField(fieldNode->fieldDecl); retriveObjectsRec(hierPath, fieldObj, indices, resVec, getAllArrayElements); } else if (auto baseNode = std::get_if<BaseNode>(&node)) { auto baseObj = *curObj.record()->getBase(baseNode->type); retriveObjectsRec(hierPath, baseObj, indices, resVec, getAllArrayElements); } } } ArrayElemVec retriveObjects(std::deque<NodeT> hierarchyVec, bool getAllArrayElements) { ArrayElemVec resVec; if (!hierarchyVec.empty()) { if (auto rootNode = std::get_if<RootNode>(&hierarchyVec.front())) { ModuleMIFView parentModule = rootNode->root; IndexVec indices; hierarchyVec.pop_front(); retriveObjectsRec(hierarchyVec, parentModule,indices, resVec, getAllArrayElements); } } return resVec; } IndexVec retriveIndices(std::deque<NodeT> hierarchyVec) { IndexVec resVec; for (auto el : hierarchyVec) { if (auto arrNode = std::get_if<ArrNode>(&el)) { resVec.push_back(arrNode->idx); } } return resVec; } } // namespace ArrayElemVec ObjectView::getAllSimilarArrayElements() const { DEBUG_WITH_TYPE(DebugOptions::doElab, outs() << "SEARCH " << *this << "\n";); auto hierarchyVec = getHierarchyNodeVec(*this); DEBUG_WITH_TYPE(DebugOptions::doElab, outs() << "MOD"; for (const auto &el : hierarchyVec ) { if (std::get_if<PtrNode>(&el)) { outs() << "<-"; } else if (std::get_if<ArrNode>(&el)) { outs() << "[*]"; } else if (auto fieldNode = std::get_if<FieldNode>(&el)) { outs() << "." << fieldNode->fieldDecl->getName(); } else if (auto baseNode = std::get_if<BaseNode>(&el)) { outs() << "." << baseNode->type.getAsString(); } } outs() << "\n"; ); auto resVec = retriveObjects(hierarchyVec, true); DEBUG_WITH_TYPE(DebugOptions::doElab, for (auto &el : resVec) { outs() << "FOUND: "<< el.obj << "\n"; } ); return resVec; } ArrayElemObjWithIndices ObjectView::getAsArrayElementWithIndicies() const { auto hierarchyVec = getHierarchyNodeVec(*this); IndexVec indices = retriveIndices(hierarchyVec); ObjectView element = retriveObjects(hierarchyVec, false)[0].obj; return ArrayElemObjWithIndices{element, indices}; } ArrayElemObjWithIndices ObjectView::getAsArrayElementWithIndicies(PortView port) const { if (isSignal() && isDynamic() && getPointers().size() == 0) { for (auto p : getPorts()) { if (p != port) { return p.getAsArrayElementWithIndicies(); } } llvm_unreachable("No bound port found for dynamic signal"); } else { return getAsArrayElementWithIndicies(); } } PortView ObjectView::getPortBound(PortView port) const { if (isSignal() && isDynamic() && getPointers().size() == 0) { for (auto p : getPorts()) { if (p != port) { return p; } } llvm_unreachable("No bound port found for dynamic signal"); } else { return port; } } std::optional<ObjectView> ObjectView::derefRecursively() const { std::optional<ObjectView> res = *this; while (res && res->isPointerOrRef()) { res = res->primitive()->ptrOrRef()->getFirstNonPointerPointee(); } return res; } std::optional<ObjectView> ObjectView::getVerilogNameOwner() const { if (auto arr = array()) { if (arr->hasElements()) { if (arr->isConstant()) return *this; else return arr->getFirstNonArrayEl(); } else return *this; } return this->derefRecursively(); } clang::ValueDecl* ObjectView::getValueDecl() const { if (isDataMember() || isStatic()) { auto cxxRecord = getParent().getType().getTypePtr()->getAsCXXRecordDecl(); for (clang::Decl* decl : cxxRecord->decls()) { if (auto* valDecl = llvm::dyn_cast<clang::ValueDecl>(decl)) { if (valDecl->getNameAsString() == obj->field_name() ) return valDecl; } } //llvm::outs() << "Can't find field: " << obj->field_name() << "\n"; return nullptr; } return nullptr; } const std::string* ObjectView::getFieldName() const { if (isDataMember() || isStatic() || (isPrimitive() && primitive()->isProcess())) { return &obj->field_name(); } return nullptr; } const clang::FieldDecl* ObjectView::getFieldDecl() const { if (isDataMember()) { const auto &fieldName = *getFieldName(); auto *parentRecDecl = getParent().getType()->getAsCXXRecordDecl(); for (const auto field: parentRecDecl->fields()) { if (field->getName() == fieldName) { return field; } } } return nullptr; } llvm::SmallVector<VerilogVarRef, 1> ObjectView::getVerilogVars() const { auto mod = this->getParentModule(); auto verilogMod = db->getVerilogModule(mod); llvm::SmallVector<VerilogVarRef, 1> res; if (this->isChannel()) { auto arrayEl = this->getAsArrayElementWithIndicies(); auto vars = verilogMod->getVerVariables(arrayEl.obj); for (auto *var : vars) { res.emplace_back(var, arrayEl.indices); } } else { auto vars = verilogMod->getVerVariables(*this); for (auto *var : vars) { res.emplace_back(var, IndexVec{}); } } return res; } // Do not change offset to zero as it done in getVerilogVars() llvm::SmallVector<VerilogVarRef, 1> ObjectView::getVerilogVarsOffset() const { auto mod = this->getParentModule(); auto verilogMod = db->getVerilogModule(mod); llvm::SmallVector<VerilogVarRef, 1> res; auto vars = verilogMod->getVerVariables(*this); for (auto *var : vars) { res.emplace_back(var, IndexVec{}); } return res; } std::optional<PrimitiveView> ObjectView::primitive() const { if (isPrimitive()) return PrimitiveView(*this); return std::nullopt; } std::optional<RecordView> ObjectView::record() const { if (isRecord()) return RecordView(*this); return std::nullopt; } std::optional<ModuleMIFView> ObjectView::moduleMIF() const { if (isModule() || isModularInterface()) return ModuleMIFView(*this); return std::nullopt; } std::optional<ArrayView> ObjectView::array() const { if (isArrayLike()) return ArrayView(*this); return std::nullopt; } std::optional<SignalView> ObjectView::signal() const { if (isSignal()) return SignalView(*this); return std::nullopt; } std::optional<std::string> ObjectView::string(bool isInteger) const { if (isPrimitive()) { if (obj->primitive().kind() == Primitive::STRING || isInteger && obj->primitive().kind() == Primitive::VALUE) { return obj->primitive().str_val(); } } return std::nullopt; } std::string ObjectView::getDebugString() const { std::string res; std::string kind; if (isArrayLike()) kind = "[ARRAY ]: "; else if(isModularInterface()) kind = "[MOD_IF ]: "; else if(isModule()) kind = "[MODULE ]: "; else if(isSignal()) kind = "[SIGNAL ]: "; else if(isRecord()) kind = "[RECORD ]: "; else if (isPrimitive()) { PrimitiveView prim = *primitive(); if (prim.isPointer()) kind = "[POINTER]: "; else if(prim.isReference()) kind = "[REF ]: "; else if(prim.isValue()) kind = "[VALUE ]: "; else if(prim.isPort()) kind = "[PORT ]: "; else if(prim.isProcess()) kind = "[PROCESS]: "; else if(prim.isEvent()) kind = "[EVENT ]: "; else if(prim.isExport()) kind = "[EXPORT]: "; else if(prim.isString()) kind = "[STRING]: "; else if(prim.isUnsupported()) kind = "[UNSUP ]: "; else SCT_TOOL_ASSERT (false, "Incorrect kind"); } else SCT_TOOL_ASSERT (false, "Incorrect kind"); auto parent = *this; while (!parent.isTopMod()) { if (parent.isDynamic()) res = "[new " + parent.getType().getAsString() + "]" + res; else if (parent.isArrayElement()) res = "["+std::to_string(*parent.getElementIndex())+"]"+ res; else if (parent.isDataMember()) res = "."+*parent.getFieldName() + res; else if (parent.isStatic()) res = ".(static)"+*parent.getFieldName() + res; else if (parent.isBaseClass()) res = "::"+ parent.getType().getAsString() + res; else if (parent.hasNoParent()) { res = "[NO_PARENT]"; } else { llvm_unreachable("Unknown rel type"); } parent = parent.getParent(); } res = kind + " [TOP]" + res; return res; } static void dumpHierarchyRecursive(ObjectView obj, const std::string& prefix, bool traverseSubmods) { if (obj.getID() == 0) { llvm::outs() << "[" << "TOP" << "] "; } else if (obj.isArrayElement()) { llvm::outs() << "[" << *obj.getElementIndex() << "] "; } else if (obj.isDataMember()) { llvm::outs() << "[" << obj.getType().getAsString() << " " << *obj.getFieldName() << "] "; } else if (obj.isBaseClass()) { llvm::outs() << "[" << obj.getType().getAsString() << "] "; } else if (obj.isDynamic()) { llvm::outs() << "[" << "DYN_ALLOC" << "] "; } else if (obj.isStatic()) { llvm::outs() << "[" << "STATIC" << "] "; } else SCT_TOOL_ASSERT (false, ""); if (obj.isProcess()) procNum++; llvm::outs() << "ID:" << obj.getID() << " "; auto getNewPrefixes = [&](bool isLast) { if (isLast) return std::make_pair("`---", prefix + " "); else return std::make_pair("|---", prefix + "| "); }; if (obj.isRecord()) { if (obj.isModularInterface()) llvm::outs() << "(MIF)\n"; else if (obj.isModule()) { modNum++; llvm::outs() << "(MOD)\n"; if (!traverseSubmods && !prefix.empty()) return; } else if (obj.isSignal()) llvm::outs() << "(SIG)\n"; else llvm::outs() << "(REC)\n"; ElabObjVec members; if (auto modMif = obj.moduleMIF()) members = modMif->getAllMembers(); else members = obj.record()->getMembers(); for (size_t i = 0; i < members.size(); ++i) { auto newPrefixes = getNewPrefixes(i == members.size() - 1); llvm::outs() << prefix << newPrefixes.first; dumpHierarchyRecursive(members[i], newPrefixes.second, traverseSubmods); } } else if (obj.isArrayLike()) { llvm::outs() << "(ARR)\n"; for (size_t i = 0; i < obj.array()->size(); ++i) { auto newPrefixes = getNewPrefixes(i == obj.array()->size() - 1); auto element = obj.array()->at(i); llvm::outs() << prefix << newPrefixes.first; dumpHierarchyRecursive(element, newPrefixes.second, traverseSubmods); } } else { llvm::outs() << "(PRM) "; auto prim = *obj.primitive(); if (auto ptr = prim.ptrOrRef()) { llvm::outs() << "PTR "; if (auto pointeeID = ptr->getPointeeID()) { llvm::outs() << "Pointee ID:" << *pointeeID; if (ptr->isBaseOffsetPtr()) llvm::outs() << ":" << *ptr->getOffset(); } else { if (ptr->isNull()) llvm::outs() << "Null "; else llvm::outs() << "Dangling "; } } else if (prim.isProcess()) { if (auto proc = prim.process()) { llvm::outs() << proc->getDebugString(); } } else if (prim.isString()) { if (auto str = prim.string()) { llvm::outs() << "STR \"" << *str << "\""; } } else { // Print primitive value if (auto primValue = prim.value()) { if (auto intValue = primValue->int64Val()) { llvm::outs() << (*intValue); if (isCharType(obj.getType())) { llvm::outs() << " " << char(*intValue); } } } } llvm::outs() << "\n"; } } void ObjectView::dumpHierarchy(bool traverseSubmods) const { modNum = 0; procNum = 0; llvm::outs() << "HIERARCHY DUMP " << getDebugString() << "\n"; dumpHierarchyRecursive(*this, "", traverseSubmods); llvm::outs() << "--------------------------------------\n" << "Module instance number " << modNum << "\n"; llvm::outs() << "Process instance number " << procNum << "\n" << "--------------------------------------\n"; } std::optional<ObjectView> ObjectView::getTopmostParentArray() const { using std::cout; using std::endl; ObjectView parent; if (isDynamic()) { // Dynamically allocated signal with leaked pointer if (getPointers().size() == 0) { parent = getParent(); } else { SCT_TOOL_ASSERT (getPointers().size() == 1, "Multiples pointers"); parent = getPointers()[0]; } } else { parent = getParent(); } if (parent.isArrayLike()) { ObjectView parParent; if (parent.isDynamic()) { if(parent.getPointers().size() == 1) parParent = parent.getPointers()[0]; else if (parent.array()->at(0).getPointers().size() == 1) parParent = parent.array()->at(0).getPointers()[0]; else ScDiag::reportErrAndDie( "Can't find unique owner for dynamic array" + parent.getDebugString() ); if (parParent.isArrayElement()) { return parParent.getTopmostParentArray(); } else { return parent; } } else { if (parent.getParent().isArrayLike()) { return parent.getTopmostParentArray(); } else { return parent; } } } if (parent.isPrimitive() && parent.primitive()->ptrOrRef()) { return parent.primitive()->ptrOrRef()->getTopmostParentArray(); } return std::nullopt; } // Return topmost array or pointer variable std::optional<ObjectView> ObjectView::getTopmostParentArrayOrPointer() const { using std::cout; using std::endl; ObjectView parent; if (isDynamic()) { SCT_TOOL_ASSERT (getPointers().size() == 1, "Multiples pointers"); parent = getPointers()[0]; } else { parent = getParent(); } //cout << "parent#1 " << parent.getDebugString() << endl; if (parent.isArrayLike()) { ObjectView parParent; if (parent.isDynamic()) { if (parent.getPointers().size() == 1) parParent = parent.getPointers()[0]; else if (parent.array()->at(0).getPointers().size() == 1) parParent = parent.array()->at(0).getPointers()[0]; else ScDiag::reportErrAndDie( "Can't find unique owner for dynamic array" + parent.getDebugString() ); if (parParent.isArrayElement()) { return parParent.getTopmostParentArray(); } else { return parent; } } else { if (parent.getParent().isArrayLike()) { return parent.getTopmostParentArray(); } else { return parent; } } } if (parent.isPrimitive() && parent.primitive()->ptrOrRef()) { auto parentArray = parent.primitive()->ptrOrRef()->getTopmostParentArray(); //cout << "prim #1 " << (parentArray ? parentArray->getDebugString() : "NO prim") << endl; if (parentArray) { // Array of pointers return *parentArray; } else { // Single pointer return *parent.primitive(); } } return std::nullopt; } // ArrayView ------------------------------------------------------------------- ArrayView::ArrayView(const ObjectView &parent) : ObjectView(parent) { SCT_TOOL_ASSERT (isArrayLike(), ""); } uint32_t ArrayView::size() const { return getProtobufObj()->array().element_ids().size(); } bool ArrayView::hasElements() const { return !getProtobufObj()->array().element_ids().empty(); } std::vector<size_t> ArrayView::getOptimizedArrayDims() const { std::vector<size_t> res; SCT_TOOL_ASSERT (!hasElements(), ""); for (auto dim : getProtobufObj()->array().dims()) res.push_back(dim); return res; } std::size_t ArrayView::getOptimizedArrayBitwidth() const { SCT_TOOL_ASSERT (!hasElements(), ""); return getProtobufObj()->primitive().init_val().dyn_bitwidth(); } std::optional<ObjectView> ArrayView::getFirstNonArrayEl() const { ObjectView el = at(0); if (std::optional<PrimitiveView> prim = el.primitive()) { if (std::optional<PtrOrRefView> ptr = prim->ptrOrRef()) { if (auto pointee = ptr->getFirstNonPointerPointee()) { el = *pointee; } else return std::nullopt; } } if (auto arrayEl = el.array()) { if (arrayEl->hasElements()) return arrayEl->getFirstNonArrayEl(); else return *arrayEl; } else { return el; } } bool ArrayView::isChannelArray() const { if (!hasElements()) return false; ObjectView el = at(0); if (std::optional<PrimitiveView> prim = el.primitive()) { if (std::optional<PtrOrRefView> ptr = prim->ptrOrRef()) { if (auto pointee = ptr->getFirstNonPointerPointee()) { el = *pointee; } else return false; } } if (auto arrayEl = el.array()) { return arrayEl->isChannelArray(); } else { return el.isChannel(); } } bool ArrayView::isConstPrimitiveArray() const { if (!isConstant()) return false; if (!hasElements()) return false; auto elemObj = at(0); if (auto primitiveView = elemObj.primitive()) return primitiveView->isValue(); if (auto arrayView = elemObj.array()) return arrayView->isConstPrimitiveArray(); return false; } ObjectView ArrayView::at(std::size_t idx) const { SCT_TOOL_ASSERT (idx < (std::size_t)getProtobufObj()->array(). element_ids_size(), ""); uint32_t elemID = getProtobufObj()->array().element_ids(idx); return getDatabase()->getObj(elemID); } // RecordView ------------------------------------------------------------------ RecordView::RecordView(const ObjectView &parent) : ObjectView(parent) { SCT_TOOL_ASSERT (isRecord(), ""); } std::optional<ObjectView> RecordView::getField(const clang::FieldDecl *fieldDecl) const { for (auto fieldView : getFields()) { if (fieldDecl->getName().compare(*fieldView.getFieldName()) == 0) return fieldView; } return std::nullopt; } std::optional<ObjectView> RecordView::getField(const std::string fieldName) const { for (auto fieldView : getFields()) { if (*fieldView.getFieldName() == fieldName) return fieldView; } return std::nullopt; } std::optional<ObjectView> RecordView::getBase(clang::QualType baseType) const { for (auto baseView : getBases()) { if (baseView.getType() == baseType) return baseView; } return std::nullopt; } std::vector<RecordView> RecordView::getBases() const { std::vector<RecordView> basesVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); if (memberObj.isBaseClass()) basesVec.push_back(*memberObj.record()); } return basesVec; } ElabObjVec RecordView::getFields() const { ElabObjVec fieldsVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); if (memberObj.isDataMember() || memberObj.isStatic()) fieldsVec.push_back(memberObj); } return fieldsVec; } void RecordView::getFieldsNoZero(ElabObjVec& fieldsVec) const { for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); //cout << " " << memberObj.getDebugString() << endl; if (memberObj.isDataMember() || memberObj.isStatic()) { const clang::QualType& type = memberObj.getType(); if (!sc::isZeroWidthType(type) && !sc::isZeroWidthArrayType(type)) { fieldsVec.push_back(memberObj); } } else if (memberObj.isRecord()) { memberObj.record()->getFieldsNoZero(fieldsVec); } } } ElabObjVec RecordView::getStaticFields() const { ElabObjVec staticVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); if (memberObj.isStatic()) staticVec.push_back(memberObj); } return staticVec; } ElabObjVec RecordView::getMembers() const { ElabObjVec membersVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); if (memberObj.isDataMember() || memberObj.isBaseClass() || memberObj.isStatic()) membersVec.push_back(memberObj); } return membersVec; } // ModuleMIFView -------------------------------------------------------------- ModuleMIFView ::ModuleMIFView (const ObjectView &parent) : RecordView(parent) { SCT_TOOL_ASSERT (isModule() || isModularInterface(), ""); } std::vector<ProcessView> ModuleMIFView::getProcesses() const { std::vector<ProcessView> processVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); if (auto prim = memberObj.primitive()) { if (auto proc = prim->process()) processVec.push_back(*proc); } } return processVec; } ElabObjVec ModuleMIFView::getDynamics() const { ElabObjVec dynamicsVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); if (memberObj.isDynamic()) dynamicsVec.push_back(memberObj); } return dynamicsVec; } ElabObjVec ModuleMIFView::getAllMembers() const { ElabObjVec membersVec; for (auto memberID : getProtobufObj()->record().member_ids()) { auto memberObj = getDatabase()->getObj(memberID); membersVec.push_back(memberObj); } return membersVec; } const VerilogModule * ModuleMIFView::getVerilogModule() const { return getDatabase()->getVerilogModule(*this); } // SignalView ----------------------------------------------------------------- SignalView::SignalView(const ObjectView &parent) : ObjectView(parent) { SCT_TOOL_ASSERT (isSignal(), ""); } ObjectView SignalView::getSignalValue() { return getDatabase()->getObj(getProtobufObj()->record().member_ids(0)); } // PrimitiveView -------------------------------------------------------------- PrimitiveView::PrimitiveView(const ObjectView &parent) : ObjectView(parent) { SCT_TOOL_ASSERT (isPrimitive(), ""); } std::optional<ValueView> PrimitiveView::value() const { if (isValue()) return ValueView(*this); return std::nullopt; } std::optional<PtrOrRefView> PrimitiveView::ptrOrRef() const { if (isPointer() || isReference()) return PtrOrRefView(*this); return std::nullopt; } std::optional<PortView> PrimitiveView::port() const { if (isPort()) return PortView(*this); return std::nullopt; } std::optional<ProcessView> PrimitiveView::process() const { if (isProcess()) return ProcessView(*this); return std::nullopt; } // ValueView ----------------------------------------------------------------- ValueView::ValueView(const ObjectView &parent) : PrimitiveView(parent) { SCT_TOOL_ASSERT (isValue(), ""); } std::size_t ValueView::bitwidth() const { return getProtobufObj()->primitive().init_val().bitwidth(); } std::size_t ValueView::dyn_bitwidth() const { return getProtobufObj()->primitive().init_val().dyn_bitwidth(); } std::optional<int64_t> ValueView::int64Val() const { if (getProtobufObj()->primitive().init_val().has_int64_value()) return getProtobufObj()->primitive().init_val().int64_value(); return std::nullopt; } std::optional<uint64_t> ValueView::uint64Val() const { if (getProtobufObj()->primitive().init_val().has_uint64_value()) return getProtobufObj()->primitive().init_val().uint64_value(); return std::nullopt; } std::optional<double> ValueView::doubleVal() const { if (getProtobufObj()->primitive().init_val().has_double_val()) return getProtobufObj()->primitive().init_val().double_val(); return std::nullopt; } // PtrOrRefView -------------------------------------------------------------- PtrOrRefView::PtrOrRefView(const ObjectView &parent) : PrimitiveView(parent) { SCT_TOOL_ASSERT (isPointer() || isReference(), ""); SCT_TOOL_ASSERT (getProtobufObj()->primitive().ptr_val(). pointee_id_size() <= 2, ""); } bool PtrOrRefView::isNotNullDangling() const { if (isNull()) return false; return getProtobufObj()->primitive().ptr_val().pointee_id_size() == 0; } bool PtrOrRefView::isBaseOffsetPtr() const { return getProtobufObj()->primitive().ptr_val().pointee_id_size() == 2; } std::optional<ObjectView> PtrOrRefView::pointee() const { if (getProtobufObj()->primitive().ptr_val().pointee_id().size() == 1) return getDatabase()->getObj(getProtobufObj()->primitive().ptr_val().pointee_id(0)); return std::nullopt; } std::optional<ObjectView> PtrOrRefView::pointeeOrArray() const { auto &pointee_ids = getProtobufObj()->primitive().ptr_val().pointee_id(); if (isBaseOffsetPtr()) { // for (size_t i = 1; i < pointee_ids.size(); ++i) { // if (pointee_ids[i] != 0) // return std::nullopt; // } return getDatabase()->getObj(pointee_ids[0]); } else { auto resPointee = pointee(); if (resPointee && resPointee->isArrayElement()) { if (*resPointee->getElementIndex() == 0) { resPointee = resPointee->getParent(); } else { return resPointee; } } return resPointee; } } std::optional<uint32_t> PtrOrRefView::getPointeeID() const { if (getProtobufObj()->primitive().ptr_val().pointee_id_size() > 0) return getProtobufObj()->primitive().ptr_val().pointee_id(0); return std::nullopt; } std::optional<uint32_t> PtrOrRefView::getOffset() const { SCT_TOOL_ASSERT (isBaseOffsetPtr(), ""); if (getProtobufObj()->primitive().ptr_val().pointee_id().size() == 2) return getProtobufObj()->primitive().ptr_val().pointee_id(1); return std::nullopt; } std::optional<ObjectView> PtrOrRefView::getFirstNonPointerPointee() const { if (isBaseOffsetPtr()) return pointeeOrArray(); if(std::optional<ObjectView> pointeeObj = pointee()) { if (auto prim = pointeeObj->primitive()) { if (prim->isPointer()) return prim->ptrOrRef()->getFirstNonPointerPointee(); } return pointeeObj; } return std::nullopt; } // PortView -------------------------------------------------------------- PortView::PortView(const ObjectView &parent) : PrimitiveView(parent) { SCT_TOOL_ASSERT (isPort(), ""); } bool PortView::isSignalPort() const { return (getDirection() != PortDirection::NONE); } SignalView PortView::getBindedSignal() const { auto bind = getDirectBind(); while(!bind.isSignal()) { bind = bind.primitive()->port()->getDirectBind(); } return bind; } ObjectView PortView::getDirectBind() const { SCT_TOOL_ASSERT (getProtobufObj()->primitive().ptr_val().pointee_id_size() == 1, "No single pointee object found for port binding"); return getDatabase()->getObj(getProtobufObj()->primitive().ptr_val(). pointee_id(0)); } PortDirection PortView::getDirection() const { if (!dirInitialized) { auto typeName = getType().getAsString(); llvm::StringRef ty(typeName); if (ty.contains("sc_core::sc_out<") || ty.contains("sct::sct_out<")) dir = PortDirection::OUT; else if (ty.contains("sc_core::sc_in<") || ty.contains("sct::sct_in<")) dir = PortDirection::IN; else if (ty.contains("sc_core::sc_inout<")) { ScDiag::reportErrAndDie("inout ports are not supported"); dir = PortDirection::INOUT; } else dir = PortDirection::NONE; } return dir; } std::optional<ObjectView> PortView::pointee() const { if (getProtobufObj()->primitive().ptr_val().pointee_id().size() == 1) return getDatabase()->getObj(getProtobufObj()->primitive().ptr_val().pointee_id(0)); return std::nullopt; } // ProcessView -------------------------------------------------------------- ProcessView::ProcessView(const ObjectView &parent) : PrimitiveView(parent) { SCT_TOOL_ASSERT (isProcess(), ""); } bool sc_elab::ProcessView::isScMethod() const { return getProtobufObj()->primitive().proc_val().kind() == Process::SC_METHOD; } bool ProcessView::isScThread() const { return getProtobufObj()->primitive().proc_val().kind() == Process::SC_THREAD; } bool ProcessView::isScCThread() const { return getProtobufObj()->primitive().proc_val().kind() == Process::SC_CTHREAD; } // Does not work well for methods in MIF bool ProcessView::isCombinational() const { bool isCombinational = isScMethod(); for (auto sens : staticSensitivity()) { if (!sens.isDefault()) isCombinational = false; } return isCombinational; } std::vector<ProcessView::SensEvent> ProcessView::staticSensitivity() const { std::vector<ProcessView::SensEvent> res; for (auto &event: getProtobufObj()->primitive().proc_val().static_events()) { res.push_back({getDatabase()->getObj(event.event_source_id()), event.kind()}); } return res; } std::vector<ProcessView::Reset> ProcessView::resets() const { std::vector<ProcessView::Reset> res; for (auto &reset: getProtobufObj()->primitive().proc_val().resets()) { res.emplace_back(getDatabase()->getObj(reset.source_id()), reset.level(), reset.async()); } return res; } static std::optional<RecordView> findBaseClassByType(RecordView recView, clang::QualType baseType) { if (recView.getType() == baseType) return recView; for (auto baseClassView : recView.getBases()) if (auto res = findBaseClassByType(baseClassView, baseType)) return res; return std::nullopt; } // Get host class and function declarations for given process name and // class where process run by SC_METHOD/SC_CTHREAD std::pair<clang::CXXRecordDecl*, clang::CXXMethodDecl*> ProcessView::getProcDeclFromBase(clang::CXXRecordDecl* moduleDecl, const std::string& procName) const { for (clang::CXXMethodDecl* procDecl : moduleDecl->methods()) { if (procDecl->getDeclName().getAsString() == procName) { return {moduleDecl, procDecl}; } } for (auto baseSpecf : moduleDecl->bases()) { if (auto baseDecl = baseSpecf.getType()->getAsCXXRecordDecl()) { auto entry = getProcDeclFromBase(baseDecl, procName); if (entry.first) { return entry; } } } return {nullptr, nullptr}; } std::pair<RecordView, clang::CXXMethodDecl*> ProcessView::getLocation() const { using namespace clang; ModuleMIFView parentModule = getParent(); auto methodName = getProtobufObj()->field_name(); auto typeName = getProtobufObj()->primitive().proc_val().type_name(); QualType hostType = getMangledTypeDB()->getType(typeName); // std::cout << "\nthis process " << getDebugString() // << "\nparentModule " << parentModule.getDebugString() // << "\nhostType " << hostType.getAsString() // << "\nmethodName " << methodName << "\n"; if (auto hostClass = findBaseClassByType(parentModule, hostType)) { // Get process host class declaration and process declaration // Process can be declared of base class and run from inheritor CXXRecordDecl* hostRecDecl = hostClass->getType()->getAsCXXRecordDecl(); auto entry = getProcDeclFromBase(hostRecDecl, methodName); if (entry.first) { // Get RecordView for process host class, may be it is base class QualType procClassType = QualType(entry.first->getTypeForDecl(), 0); if (auto procClass = findBaseClassByType(parentModule, procClassType)) { clang::CXXMethodDecl* procDecl = entry.second; return {*procClass, procDecl}; } } SCT_TOOL_ASSERT (false, "Process declaration not found"); } else { ScDiag::reportScDiag(ScDiag::SC_NO_MODULE_NAME); SCT_TOOL_ASSERT (false, "No hostClass for process"); } llvm_unreachable("Error in ProcessView::getLocation()"); } } // end namespace sc_elab
412
0.967129
1
0.967129
game-dev
MEDIA
0.345359
game-dev
0.947072
1
0.947072
mono/CocosSharp
6,752
tests/tests/classes/tests/SpriteTest/Sprite1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; using System.IO; namespace tests { public class SpriteMaskTest : SpriteTestDemo { CCMaskedSprite grossini, ball; CCSprite hit; #region Properties public override string Title { get { return "Sprite Collision Test"; } } #endregion Properties #region Constructors public SpriteMaskTest() { grossini = new CCMaskedSprite("Images/grossini", GetCollisionMask("grossini")); ball = new CCMaskedSprite("Images/ball-hd", GetCollisionMask("ball-hd")); hit = new CCSprite("Images/Icon"); AddChild(grossini, 1); AddChild(ball, 1); AddChild(hit, 5); } #endregion Constructors #region Setup content public override void OnEnter() { base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size; grossini.Position = new CCPoint(windowSize.Width / 3f, windowSize.Height / 2f); ball.Position = new CCPoint(windowSize.Width * 2f / 3f, windowSize.Height / 2f); hit.Visible = false; grossini.RunAction(new CCRepeatForever(new CCParallel( new CCRotateBy(9f, 360f), new CCSequence(new CCMoveBy(3f, new CCPoint(-100f, 0)), new CCMoveBy(3f, new CCPoint(500f, 0f)), new CCMoveBy(3f, new CCPoint(-400f, 0))) ))); ball.RunAction(new CCRepeatForever(new CCSequence(new CCMoveBy(1.5f, new CCPoint(-400f, 0)), new CCMoveBy(2f, new CCPoint(600f, 0f)), new CCMoveBy(1f, new CCPoint(-200f, 0))))); Schedule(new Action<float>(UpdateTest), .25f); } #endregion Setup content void UpdateTest(float dt) { CCPoint where; if (grossini.CollidesWith(ball, out where)) { hit.Position = where; hit.Visible = true; } else { hit.Visible = false; } } #region Collision Mask Support Code Stream GetEmbeddedResource(string name) { #if !NETFX_CORE System.Reflection.Assembly assem = System.Reflection.Assembly.GetExecutingAssembly(); Stream stream = assem.GetManifestResourceStream(name); if (stream == null) { stream = assem.GetManifestResourceStream("tests." + name); } return (stream); #else return null; #endif } byte[] ReadCollisionMask(Stream stream) { MemoryStream ms = new MemoryStream(); using (stream) { StreamReader sr = new StreamReader(stream); while (true) { string s = sr.ReadLine(); if (s == null) { break; } if (s.Length == 0 || s[0] == '#') { continue; } // This is hokey and lame, but let's get this working! for (int i = 0; i < s.Length; i++) { if (s[i] == '1') { ms.WriteByte(1); } else { ms.WriteByte(0); } } } } return (ms.ToArray()); } byte[] GetCollisionMask(string refName) { byte[] mask = null; try { Stream stream = GetEmbeddedResource(refName + ".mask"); if (stream != null) { mask = ReadCollisionMask(stream); } else { CCLog.Log("Failed to load the mask for " + refName); } } catch (Exception) { CCLog.Log("Failed to load the mask for " + refName); } return (mask); } #endregion Collision Mask Support Code } public class Sprite1 : SpriteTestDemo { #region Properties public override string Title { get { return "Testing Sprite"; } } public override string Subtitle { get { return "Tap screen to add more sprites"; } } #endregion Properties #region Constructors public Sprite1() { // Register Touch Event var touchListener = new CCEventListenerTouchAllAtOnce(); touchListener.OnTouchesEnded = OnTouchesEnded; AddEventListener(touchListener); } #endregion Constructors public override void OnEnter() { base.OnEnter(); AddNewSpriteWithCoords(Layer.VisibleBoundsWorldspace.Center); } void AddNewSpriteWithCoords(CCPoint p) { int idx = (int)(CCMacros.CCRandomBetween0And1() * 1400.0f / 100.0f); int x = (idx % 5) * 85; int y = (idx / 5) * 121; CCSprite sprite = new CCSprite("Images/grossini_dance_atlas", new CCRect(x, y, 85, 121)); AddChild(sprite); sprite.Position = p; CCFiniteTimeAction action; float random = CCMacros.CCRandomBetween0And1(); if (random < 0.20) action = new CCScaleBy(3, 2); else if (random < 0.40) action = new CCRotateBy (3, 360); else if (random < 0.60) action = new CCBlink (1, 3); else if (random < 0.8) action = new CCTintBy (2, 0, -255, -255); else action = new CCFadeOut (2); object obj = action.Reverse(); CCFiniteTimeAction action_back = (CCFiniteTimeAction)action.Reverse(); CCFiniteTimeAction seq = (CCFiniteTimeAction)(new CCSequence(action, action_back)); sprite.RunAction(new CCRepeatForever (seq)); } void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent) { foreach (CCTouch touch in touches) { var location = Layer.ScreenToWorldspace(touch.LocationOnScreen); AddNewSpriteWithCoords(location); } } } }
412
0.902337
1
0.902337
game-dev
MEDIA
0.750145
game-dev
0.990794
1
0.990794
gc-mojoconsole/gc-mojoconsole-backend
4,861
gc-plugin/src/main/java/com/mojo/consoleplus/RequestHandler.java
package com.mojo.consoleplus; import com.mojo.consoleplus.command.PluginCommand; import com.mojo.consoleplus.forms.RequestAuth; import com.mojo.consoleplus.forms.RequestJson; import com.mojo.consoleplus.forms.ResponseAuth; import com.mojo.consoleplus.forms.ResponseJson; import emu.grasscutter.Grasscutter; import emu.grasscutter.command.CommandMap; import emu.grasscutter.game.player.Player; import emu.grasscutter.server.http.Router; import emu.grasscutter.utils.MessageHandler; import io.javalin.Javalin; import io.javalin.http.Context; import java.io.IOException; import java.text.DecimalFormat; import java.util.Map; import java.util.Random; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; public final class RequestHandler implements Router { // private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @Override public void applyRoutes(Javalin javalin) { javalin.post("/mojoplus/api", RequestHandler::processRequest); javalin.post("/mojoplus/auth", RequestHandler::requestKey); } public static void processRequest(Context context) { RequestJson request = context.bodyAsClass(RequestJson.class); Player player = null; if (request.k2 != null) { // version 2 token int uid; long expire; String hashDigest; uid = parseInt(request.k2.split(":")[0]); expire = parseLong(request.k2.split(":")[1]); hashDigest = request.k2.split(":")[2]; if (ConsolePlus.authHandler.auth(uid, expire, hashDigest)){ Map<Integer, Player> playersMap = Grasscutter.getGameServer().getPlayers(); for (int playerid: playersMap.keySet()) { if (playersMap.get(playerid).getUid() == uid) { player = playersMap.get(playerid); } } } } if (player != null) { MessageHandler resultCollector = new MessageHandler(); player.setMessageHandler(resultCollector); // hook the message switch (request.request){ case "invoke": try{ // TODO: Enable execut commands to third party CommandMap.getInstance().invoke(player, player, request.payload); } catch (Exception e) { context.json(new ResponseJson("error", 500, e.getStackTrace().toString())); break; } case "ping": // res.json(new ResponseJson("success", 200)); context.json(new ResponseJson("success", 200, resultCollector.getMessage())); break; default: context.json(new ResponseJson("400 Bad Request", 400)); break; } player.setMessageHandler(null); return; } context.json(new ResponseJson("403 Forbidden", 403)); } public static void requestKey(Context context) throws IOException { RequestAuth request = context.bodyAsClass(RequestAuth.class); if (request.otp != null && !request.otp.equals("")) { if (PluginCommand.getInstance().tickets.get(request.otp) == null) { context.json(new ResponseAuth(404, "Not found", null)); return; } String key = PluginCommand.getInstance().tickets.get(request.otp).key; if (key == null){ context.json(new ResponseAuth(403, "Not ready yet", null)); } else { PluginCommand.getInstance().tickets.remove(request.otp); context.json(new ResponseAuth(200, "", key)); } } else if (request.uid != 0) { String otp = new DecimalFormat("000000").format(new Random().nextInt(999999)); while (PluginCommand.getInstance().tickets.containsKey(otp)){ otp = new DecimalFormat("000000").format(new Random().nextInt(999999)); } Map<Integer, Player> playersMap = Grasscutter.getGameServer().getPlayers(); Player targetPlayer = null; for (int playerid: playersMap.keySet()) { if (playersMap.get(playerid).getUid() == request.uid) { targetPlayer = playersMap.get(playerid); } } if (targetPlayer == null){ context.json(new ResponseAuth(404, "Not found", null)); return; } PluginCommand.getInstance().tickets.put(otp, new PluginCommand.Ticket(targetPlayer, System.currentTimeMillis()/ 1000 + 300, true)); context.json(new ResponseAuth(201, "Code generated", otp)); } } }
412
0.950399
1
0.950399
game-dev
MEDIA
0.635015
game-dev,web-backend
0.981446
1
0.981446
Redot-Engine/redot-engine
73,694
core/object/class_db.cpp
/**************************************************************************/ /* class_db.cpp */ /**************************************************************************/ /* This file is part of: */ /* REDOT ENGINE */ /* https://redotengine.org */ /**************************************************************************/ /* Copyright (c) 2024-present Redot Engine contributors */ /* (see REDOT_AUTHORS.md) */ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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. */ /**************************************************************************/ #include "class_db.h" #include "core/config/engine.h" #include "core/io/resource_loader.h" #include "core/object/script_language.h" #include "core/version.h" #ifdef DEBUG_ENABLED MethodDefinition D_METHODP(const char *p_name, const char *const **p_args, uint32_t p_argcount) { MethodDefinition md; md.name = StringName(p_name); md.args.resize(p_argcount); for (uint32_t i = 0; i < p_argcount; i++) { md.args.write[i] = StringName(*p_args[i]); } return md; } #endif // DEBUG_ENABLED ClassDB::APIType ClassDB::current_api = API_CORE; HashMap<ClassDB::APIType, uint32_t> ClassDB::api_hashes_cache; void ClassDB::set_current_api(APIType p_api) { DEV_ASSERT(!api_hashes_cache.has(p_api)); // This API type may not be suitable for caching of hash if it can change later. current_api = p_api; } ClassDB::APIType ClassDB::get_current_api() { return current_api; } HashMap<StringName, ClassDB::ClassInfo> ClassDB::classes; HashMap<StringName, StringName> ClassDB::resource_base_extensions; HashMap<StringName, StringName> ClassDB::compat_classes; #ifdef TOOLS_ENABLED HashMap<StringName, ObjectGDExtension> ClassDB::placeholder_extensions; class PlaceholderExtensionInstance { StringName class_name; HashMap<StringName, Variant> properties; // Checks if a property is from a runtime class, and not a non-runtime base class. bool is_runtime_property(const StringName &p_property_name) { StringName current_class_name = class_name; while (ClassDB::is_class_runtime(current_class_name)) { if (ClassDB::has_property(current_class_name, p_property_name, true)) { return true; } current_class_name = ClassDB::get_parent_class(current_class_name); } return false; } public: PlaceholderExtensionInstance(const StringName &p_class_name) { class_name = p_class_name; } ~PlaceholderExtensionInstance() {} void set(const StringName &p_name, const Variant &p_value, bool &r_valid) { r_valid = is_runtime_property(p_name); if (r_valid) { properties[p_name] = p_value; } } Variant get(const StringName &p_name, bool &r_valid) { const Variant *value = properties.getptr(p_name); Variant ret; if (value) { ret = *value; r_valid = true; } else { r_valid = is_runtime_property(p_name); if (r_valid) { ret = ClassDB::class_get_default_property_value(class_name, p_name); } } return ret; } static GDExtensionBool placeholder_instance_set(GDExtensionClassInstancePtr p_instance, GDExtensionConstStringNamePtr p_name, GDExtensionConstVariantPtr p_value) { PlaceholderExtensionInstance *self = (PlaceholderExtensionInstance *)p_instance; const StringName &name = *(StringName *)p_name; const Variant &value = *(const Variant *)p_value; bool valid = false; self->set(name, value, valid); return valid; } static GDExtensionBool placeholder_instance_get(GDExtensionClassInstancePtr p_instance, GDExtensionConstStringNamePtr p_name, GDExtensionVariantPtr r_ret) { PlaceholderExtensionInstance *self = (PlaceholderExtensionInstance *)p_instance; const StringName &name = *(StringName *)p_name; Variant *value = (Variant *)r_ret; bool valid = false; *value = self->get(name, valid); return valid; } static const GDExtensionPropertyInfo *placeholder_instance_get_property_list(GDExtensionClassInstancePtr p_instance, uint32_t *r_count) { *r_count = 0; return nullptr; } static void placeholder_instance_free_property_list(GDExtensionClassInstancePtr p_instance, const GDExtensionPropertyInfo *p_list, uint32_t p_count) { } static GDExtensionBool placeholder_instance_property_can_revert(GDExtensionClassInstancePtr p_instance, GDExtensionConstStringNamePtr p_name) { return false; } static GDExtensionBool placeholder_instance_property_get_revert(GDExtensionClassInstancePtr p_instance, GDExtensionConstStringNamePtr p_name, GDExtensionVariantPtr r_ret) { return false; } static GDExtensionBool placeholder_instance_validate_property(GDExtensionClassInstancePtr p_instance, GDExtensionPropertyInfo *p_property) { return false; } static void placeholder_instance_notification(GDExtensionClassInstancePtr p_instance, int32_t p_what, GDExtensionBool p_reversed) { } static void placeholder_instance_to_string(GDExtensionClassInstancePtr p_instance, GDExtensionBool *r_is_valid, GDExtensionStringPtr p_out) { *r_is_valid = true; } static void placeholder_instance_reference(GDExtensionClassInstancePtr p_instance) { } static void placeholder_instance_unreference(GDExtensionClassInstancePtr p_instance) { } static uint64_t placeholder_instance_get_rid(GDExtensionClassInstancePtr p_instance) { return 0; } static GDExtensionObjectPtr placeholder_class_create_instance(void *p_class_userdata, GDExtensionBool p_notify_postinitialize) { ClassDB::ClassInfo *ti = (ClassDB::ClassInfo *)p_class_userdata; // Find the closest native parent, that isn't a runtime class. ClassDB::ClassInfo *native_parent = ti->inherits_ptr; while (native_parent->gdextension || native_parent->is_runtime) { native_parent = native_parent->inherits_ptr; } ERR_FAIL_NULL_V(native_parent->creation_func, nullptr); // Construct a placeholder. Object *obj = native_parent->creation_func(static_cast<bool>(p_notify_postinitialize)); // ClassDB::set_object_extension_instance() won't be called for placeholders. // We need need to make sure that all the things it would have done (even if // done in a different way to support placeholders) will also be done here. obj->_extension = ClassDB::get_placeholder_extension(ti->name); obj->_extension_instance = memnew(PlaceholderExtensionInstance(ti->name)); #ifdef TOOLS_ENABLED if (obj->_extension->track_instance) { obj->_extension->track_instance(obj->_extension->tracking_userdata, obj); } #endif return obj; } static GDExtensionObjectPtr placeholder_class_recreate_instance(void *p_class_userdata, GDExtensionObjectPtr p_object) { ClassDB::ClassInfo *ti = (ClassDB::ClassInfo *)p_class_userdata; return memnew(PlaceholderExtensionInstance(ti->name)); } static void placeholder_class_free_instance(void *p_class_userdata, GDExtensionClassInstancePtr p_instance) { PlaceholderExtensionInstance *instance = (PlaceholderExtensionInstance *)p_instance; memdelete(instance); } static GDExtensionClassCallVirtual placeholder_class_get_virtual(void *p_class_userdata, GDExtensionConstStringNamePtr p_name, uint32_t p_hash) { return nullptr; } }; #endif bool ClassDB::_is_parent_class(const StringName &p_class, const StringName &p_inherits) { ClassInfo *c = classes.getptr(p_class); while (c) { if (c->name == p_inherits) { return true; } c = c->inherits_ptr; } return false; } bool ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) { Locker::Lock lock(Locker::STATE_READ); return _is_parent_class(p_class, p_inherits); } void ClassDB::get_class_list(List<StringName> *p_classes) { Locker::Lock lock(Locker::STATE_READ); for (const KeyValue<StringName, ClassInfo> &E : classes) { p_classes->push_back(E.key); } p_classes->sort_custom<StringName::AlphCompare>(); } #ifdef TOOLS_ENABLED void ClassDB::get_extensions_class_list(List<StringName> *p_classes) { Locker::Lock lock(Locker::STATE_READ); for (const KeyValue<StringName, ClassInfo> &E : classes) { if (E.value.api != API_EXTENSION && E.value.api != API_EDITOR_EXTENSION) { continue; } p_classes->push_back(E.key); } p_classes->sort_custom<StringName::AlphCompare>(); } void ClassDB::get_extension_class_list(const Ref<GDExtension> &p_extension, List<StringName> *p_classes) { Locker::Lock lock(Locker::STATE_READ); for (const KeyValue<StringName, ClassInfo> &E : classes) { if (E.value.api != API_EXTENSION && E.value.api != API_EDITOR_EXTENSION) { continue; } if (!E.value.gdextension || E.value.gdextension->library != p_extension.ptr()) { continue; } p_classes->push_back(E.key); } p_classes->sort_custom<StringName::AlphCompare>(); } #endif void ClassDB::get_inheriters_from_class(const StringName &p_class, LocalVector<StringName> &p_classes) { Locker::Lock lock(Locker::STATE_READ); for (const KeyValue<StringName, ClassInfo> &E : classes) { if (E.key != p_class && _is_parent_class(E.key, p_class)) { p_classes.push_back(E.key); } } } void ClassDB::get_direct_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes) { Locker::Lock lock(Locker::STATE_READ); for (const KeyValue<StringName, ClassInfo> &E : classes) { if (E.value.inherits == p_class) { p_classes->push_back(E.key); } } } StringName ClassDB::get_parent_class_nocheck(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); if (!ti) { return StringName(); } return ti->inherits; } bool ClassDB::get_inheritance_chain_nocheck(const StringName &p_class, Vector<StringName> &r_result) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *start = classes.getptr(p_class); if (!start) { return false; } int classes_to_add = 0; for (ClassInfo *ti = start; ti; ti = ti->inherits_ptr) { classes_to_add++; } int64_t old_size = r_result.size(); r_result.resize(old_size + classes_to_add); StringName *w = r_result.ptrw() + old_size; for (ClassInfo *ti = start; ti; ti = ti->inherits_ptr) { *w++ = ti->name; } return true; } StringName ClassDB::get_compatibility_remapped_class(const StringName &p_class) { if (classes.has(p_class)) { return p_class; } if (compat_classes.has(p_class)) { return compat_classes[p_class]; } return p_class; } StringName ClassDB::_get_parent_class(const StringName &p_class) { ClassInfo *ti = classes.getptr(p_class); ERR_FAIL_NULL_V_MSG(ti, StringName(), vformat("Cannot get class '%s'.", String(p_class))); return ti->inherits; } StringName ClassDB::get_parent_class(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); return _get_parent_class(p_class); } ClassDB::APIType ClassDB::get_api_type(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); ERR_FAIL_NULL_V_MSG(ti, API_NONE, vformat("Cannot get class '%s'.", String(p_class))); return ti->api; } uint32_t ClassDB::get_api_hash(APIType p_api) { #ifdef DEBUG_ENABLED Locker::Lock lock(Locker::STATE_WRITE); if (api_hashes_cache.has(p_api)) { return api_hashes_cache[p_api]; } uint64_t hash = hash_murmur3_one_64(HashMapHasherDefault::hash(REDOT_VERSION_FULL_CONFIG)); List<StringName> class_list; for (const KeyValue<StringName, ClassInfo> &E : classes) { class_list.push_back(E.key); } // Must be alphabetically sorted for hash to compute. class_list.sort_custom<StringName::AlphCompare>(); for (const StringName &E : class_list) { ClassInfo *t = classes.getptr(E); ERR_FAIL_NULL_V_MSG(t, 0, vformat("Cannot get class '%s'.", String(E))); if (t->api != p_api || !t->exposed) { continue; } hash = hash_murmur3_one_64(t->name.hash(), hash); hash = hash_murmur3_one_64(t->inherits.hash(), hash); { //methods List<StringName> snames; for (const KeyValue<StringName, MethodBind *> &F : t->method_map) { String name = F.key.operator String(); ERR_CONTINUE(name.is_empty()); if (name[0] == '_') { continue; // Ignore non-virtual methods that start with an underscore } snames.push_back(F.key); } snames.sort_custom<StringName::AlphCompare>(); for (const StringName &F : snames) { MethodBind *mb = t->method_map[F]; hash = hash_murmur3_one_64(mb->get_name().hash(), hash); hash = hash_murmur3_one_64(mb->get_argument_count(), hash); hash = hash_murmur3_one_64(mb->get_argument_type(-1), hash); //return for (int i = 0; i < mb->get_argument_count(); i++) { const PropertyInfo info = mb->get_argument_info(i); hash = hash_murmur3_one_64(info.type, hash); hash = hash_murmur3_one_64(info.name.hash(), hash); hash = hash_murmur3_one_64(info.hint, hash); hash = hash_murmur3_one_64(info.hint_string.hash(), hash); } hash = hash_murmur3_one_64(mb->get_default_argument_count(), hash); for (int i = 0; i < mb->get_argument_count(); i++) { if (mb->has_default_argument(i)) { Variant da = mb->get_default_argument(i); hash = hash_murmur3_one_64(da.hash(), hash); } } hash = hash_murmur3_one_64(mb->get_hint_flags(), hash); } } { //constants List<StringName> snames; for (const KeyValue<StringName, int64_t> &F : t->constant_map) { snames.push_back(F.key); } snames.sort_custom<StringName::AlphCompare>(); for (const StringName &F : snames) { hash = hash_murmur3_one_64(F.hash(), hash); hash = hash_murmur3_one_64(uint64_t(t->constant_map[F]), hash); } } { //signals List<StringName> snames; for (const KeyValue<StringName, MethodInfo> &F : t->signal_map) { snames.push_back(F.key); } snames.sort_custom<StringName::AlphCompare>(); for (const StringName &F : snames) { MethodInfo &mi = t->signal_map[F]; hash = hash_murmur3_one_64(F.hash(), hash); for (const PropertyInfo &pi : mi.arguments) { hash = hash_murmur3_one_64(pi.type, hash); } } } { //properties List<StringName> snames; for (const KeyValue<StringName, PropertySetGet> &F : t->property_setget) { snames.push_back(F.key); } snames.sort_custom<StringName::AlphCompare>(); for (const StringName &F : snames) { PropertySetGet *psg = t->property_setget.getptr(F); ERR_FAIL_NULL_V(psg, 0); hash = hash_murmur3_one_64(F.hash(), hash); hash = hash_murmur3_one_64(psg->setter.hash(), hash); hash = hash_murmur3_one_64(psg->getter.hash(), hash); } } //property list for (const PropertyInfo &F : t->property_list) { hash = hash_murmur3_one_64(F.name.hash(), hash); hash = hash_murmur3_one_64(F.type, hash); hash = hash_murmur3_one_64(F.hint, hash); hash = hash_murmur3_one_64(F.hint_string.hash(), hash); hash = hash_murmur3_one_64(F.usage, hash); } } hash = hash_fmix32(hash); // Extension API changes at runtime; let's just not cache them by now. if (p_api != API_EXTENSION && p_api != API_EDITOR_EXTENSION) { api_hashes_cache[p_api] = hash; } return hash; #else return 0; #endif // DEBUG_ENABLED } bool ClassDB::class_exists(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); return classes.has(p_class); } void ClassDB::add_compatibility_class(const StringName &p_class, const StringName &p_fallback) { Locker::Lock lock(Locker::STATE_WRITE); compat_classes[p_class] = p_fallback; } StringName ClassDB::get_compatibility_class(const StringName &p_class) { if (compat_classes.has(p_class)) { return compat_classes[p_class]; } return StringName(); } Object *ClassDB::_instantiate_internal(const StringName &p_class, bool p_require_real_class, bool p_notify_postinitialize, bool p_exposed_only) { ClassInfo *ti; { Locker::Lock lock(Locker::STATE_READ); ti = classes.getptr(p_class); if (!_can_instantiate(ti, p_exposed_only)) { if (compat_classes.has(p_class)) { ti = classes.getptr(compat_classes[p_class]); } } ERR_FAIL_NULL_V_MSG(ti, nullptr, vformat("Cannot get class '%s'.", String(p_class))); ERR_FAIL_COND_V_MSG(ti->disabled, nullptr, vformat("Class '%s' is disabled.", String(p_class))); if (p_exposed_only) { ERR_FAIL_COND_V_MSG(!ti->exposed, nullptr, vformat("Class '%s' isn't exposed.", String(p_class))); } ERR_FAIL_NULL_V_MSG(ti->creation_func, nullptr, vformat("Class '%s' or its base class cannot be instantiated.", String(p_class))); } #ifdef TOOLS_ENABLED if ((ti->api == API_EDITOR || ti->api == API_EDITOR_EXTENSION) && !Engine::get_singleton()->is_editor_hint()) { ERR_PRINT(vformat("Class '%s' can only be instantiated by editor.", String(p_class))); return nullptr; } #endif #ifdef TOOLS_ENABLED // Try to create placeholder. if (!p_require_real_class && ti->is_runtime && Engine::get_singleton()->is_editor_hint()) { bool can_create_placeholder = false; if (ti->gdextension) { if (ti->gdextension->create_instance2) { can_create_placeholder = true; } #ifndef DISABLE_DEPRECATED else if (ti->gdextension->create_instance) { can_create_placeholder = true; } #endif // DISABLE_DEPRECATED } else if (!ti->inherits_ptr || !ti->inherits_ptr->creation_func) { ERR_PRINT(vformat("Cannot make a placeholder instance of runtime class %s because its parent cannot be constructed.", ti->name)); } else { can_create_placeholder = true; } if (can_create_placeholder) { ObjectGDExtension *extension = get_placeholder_extension(ti->name); return (Object *)extension->create_instance2(extension->class_userdata, p_notify_postinitialize); } } #endif // TOOLS_ENABLED if (ti->gdextension && ti->gdextension->create_instance2) { ObjectGDExtension *extension = ti->gdextension; return (Object *)extension->create_instance2(extension->class_userdata, p_notify_postinitialize); } #ifndef DISABLE_DEPRECATED else if (ti->gdextension && ti->gdextension->create_instance) { ObjectGDExtension *extension = ti->gdextension; return (Object *)extension->create_instance(extension->class_userdata); } #endif // DISABLE_DEPRECATED else { return ti->creation_func(p_notify_postinitialize); } } bool ClassDB::_can_instantiate(ClassInfo *p_class_info, bool p_exposed_only) { if (!p_class_info) { return false; } if (p_exposed_only && !p_class_info->exposed) { return false; } if (p_class_info->disabled || !p_class_info->creation_func) { return false; } if (!p_class_info->gdextension) { return true; } if (p_class_info->gdextension->create_instance2) { return true; } #ifndef DISABLE_DEPRECATED if (p_class_info->gdextension->create_instance) { return true; } #endif // DISABLE_DEPRECATED return false; } Object *ClassDB::instantiate(const StringName &p_class) { return _instantiate_internal(p_class); } Object *ClassDB::instantiate_no_placeholders(const StringName &p_class) { return _instantiate_internal(p_class, true); } Object *ClassDB::instantiate_without_postinitialization(const StringName &p_class) { return _instantiate_internal(p_class, true, false); } #ifdef TOOLS_ENABLED ObjectGDExtension *ClassDB::get_placeholder_extension(const StringName &p_class) { ObjectGDExtension *placeholder_extension = placeholder_extensions.getptr(p_class); if (placeholder_extension) { return placeholder_extension; } ClassInfo *ti; { Locker::Lock lock(Locker::STATE_READ); ti = classes.getptr(p_class); if (!_can_instantiate(ti)) { if (compat_classes.has(p_class)) { ti = classes.getptr(compat_classes[p_class]); } } ERR_FAIL_NULL_V_MSG(ti, nullptr, vformat("Cannot get class '%s'.", String(p_class))); ERR_FAIL_COND_V_MSG(ti->disabled, nullptr, vformat("Class '%s' is disabled.", String(p_class))); } // Make a "fake" extension to act as a placeholder. placeholder_extensions[p_class] = ObjectGDExtension(); placeholder_extension = placeholder_extensions.getptr(p_class); placeholder_extension->is_runtime = true; placeholder_extension->is_placeholder = true; if (ti->gdextension) { placeholder_extension->library = ti->gdextension->library; placeholder_extension->parent = ti->gdextension->parent; placeholder_extension->children = ti->gdextension->children; placeholder_extension->parent_class_name = ti->gdextension->parent_class_name; placeholder_extension->class_name = ti->gdextension->class_name; placeholder_extension->editor_class = ti->gdextension->editor_class; placeholder_extension->reloadable = ti->gdextension->reloadable; placeholder_extension->is_virtual = ti->gdextension->is_virtual; placeholder_extension->is_abstract = ti->gdextension->is_abstract; placeholder_extension->is_exposed = ti->gdextension->is_exposed; placeholder_extension->tracking_userdata = ti->gdextension->tracking_userdata; placeholder_extension->track_instance = ti->gdextension->track_instance; placeholder_extension->untrack_instance = ti->gdextension->untrack_instance; } else { placeholder_extension->library = nullptr; placeholder_extension->parent = nullptr; placeholder_extension->parent_class_name = ti->inherits; placeholder_extension->class_name = ti->name; placeholder_extension->editor_class = ti->api == API_EDITOR; placeholder_extension->reloadable = false; placeholder_extension->is_virtual = ti->is_virtual; placeholder_extension->is_abstract = false; placeholder_extension->is_exposed = ti->exposed; } placeholder_extension->set = &PlaceholderExtensionInstance::placeholder_instance_set; placeholder_extension->get = &PlaceholderExtensionInstance::placeholder_instance_get; placeholder_extension->get_property_list = &PlaceholderExtensionInstance::placeholder_instance_get_property_list; placeholder_extension->free_property_list2 = &PlaceholderExtensionInstance::placeholder_instance_free_property_list; placeholder_extension->property_can_revert = &PlaceholderExtensionInstance::placeholder_instance_property_can_revert; placeholder_extension->property_get_revert = &PlaceholderExtensionInstance::placeholder_instance_property_get_revert; placeholder_extension->validate_property = &PlaceholderExtensionInstance::placeholder_instance_validate_property; #ifndef DISABLE_DEPRECATED placeholder_extension->notification = nullptr; placeholder_extension->free_property_list = nullptr; #endif // DISABLE_DEPRECATED placeholder_extension->notification2 = &PlaceholderExtensionInstance::placeholder_instance_notification; placeholder_extension->to_string = &PlaceholderExtensionInstance::placeholder_instance_to_string; placeholder_extension->reference = &PlaceholderExtensionInstance::placeholder_instance_reference; placeholder_extension->unreference = &PlaceholderExtensionInstance::placeholder_instance_unreference; placeholder_extension->get_rid = &PlaceholderExtensionInstance::placeholder_instance_get_rid; placeholder_extension->class_userdata = ti; #ifndef DISABLE_DEPRECATED placeholder_extension->create_instance = nullptr; #endif // DISABLE_DEPRECATED placeholder_extension->create_instance2 = &PlaceholderExtensionInstance::placeholder_class_create_instance; placeholder_extension->free_instance = &PlaceholderExtensionInstance::placeholder_class_free_instance; #ifndef DISABLE_DEPRECATED placeholder_extension->get_virtual = nullptr; placeholder_extension->get_virtual_call_data = nullptr; #endif // DISABLE_DEPRECATED placeholder_extension->get_virtual2 = &PlaceholderExtensionInstance::placeholder_class_get_virtual; placeholder_extension->get_virtual_call_data2 = nullptr; placeholder_extension->call_virtual_with_data = nullptr; placeholder_extension->recreate_instance = &PlaceholderExtensionInstance::placeholder_class_recreate_instance; return placeholder_extension; } #endif void ClassDB::set_object_extension_instance(Object *p_object, const StringName &p_class, GDExtensionClassInstancePtr p_instance) { ERR_FAIL_NULL(p_object); ClassInfo *ti; { Locker::Lock lock(Locker::STATE_READ); ti = classes.getptr(p_class); if (!_can_instantiate(ti)) { if (compat_classes.has(p_class)) { ti = classes.getptr(compat_classes[p_class]); } } ERR_FAIL_NULL_MSG(ti, vformat("Cannot get class '%s'.", String(p_class))); ERR_FAIL_COND_MSG(ti->disabled, vformat("Class '%s' is disabled.", String(p_class))); ERR_FAIL_NULL_MSG(ti->gdextension, vformat("Class '%s' has no native extension.", String(p_class))); } p_object->_extension = ti->gdextension; p_object->_extension_instance = p_instance; #ifdef TOOLS_ENABLED if (p_object->_extension->track_instance) { p_object->_extension->track_instance(p_object->_extension->tracking_userdata, p_object); } #endif } bool ClassDB::can_instantiate(const StringName &p_class) { String script_path; { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); if (!ti) { if (!ScriptServer::is_global_class(p_class)) { ERR_FAIL_V_MSG(false, vformat("Cannot get class '%s'.", String(p_class))); } script_path = ScriptServer::get_global_class_path(p_class); goto use_script; // Open the lock for resource loading. } #ifdef TOOLS_ENABLED if ((ti->api == API_EDITOR || ti->api == API_EDITOR_EXTENSION) && !Engine::get_singleton()->is_editor_hint()) { return false; } #endif return _can_instantiate(ti); } use_script: Ref<Script> scr = ResourceLoader::load(script_path); return scr.is_valid() && scr->is_valid() && !scr->is_abstract(); } bool ClassDB::is_abstract(const StringName &p_class) { String script_path; { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); if (!ti) { if (!ScriptServer::is_global_class(p_class)) { ERR_FAIL_V_MSG(false, vformat("Cannot get class '%s'.", String(p_class))); } script_path = ScriptServer::get_global_class_path(p_class); goto use_script; // Open the lock for resource loading. } if (ti->creation_func != nullptr) { return false; } if (!ti->gdextension) { return true; } #ifndef DISABLE_DEPRECATED return ti->gdextension->create_instance2 == nullptr && ti->gdextension->create_instance == nullptr; #else return ti->gdextension->create_instance2 == nullptr; #endif // DISABLE_DEPRECATED } use_script: Ref<Script> scr = ResourceLoader::load(script_path); return scr.is_valid() && scr->is_valid() && scr->is_abstract(); } bool ClassDB::is_virtual(const StringName &p_class) { String script_path; { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); if (!ti) { if (!ScriptServer::is_global_class(p_class)) { ERR_FAIL_V_MSG(false, vformat("Cannot get class '%s'.", String(p_class))); } script_path = ScriptServer::get_global_class_path(p_class); goto use_script; // Open the lock for resource loading. } #ifdef TOOLS_ENABLED if ((ti->api == API_EDITOR || ti->api == API_EDITOR_EXTENSION) && !Engine::get_singleton()->is_editor_hint()) { return false; } #endif return (_can_instantiate(ti) && ti->is_virtual); } use_script: Ref<Script> scr = ResourceLoader::load(script_path); return scr.is_valid() && scr->is_valid() && scr->is_abstract(); } void ClassDB::_add_class(const StringName &p_class, const StringName &p_inherits) { Locker::Lock lock(Locker::STATE_WRITE); const StringName &name = p_class; ERR_FAIL_COND_MSG(classes.has(name), vformat("Class '%s' already exists.", String(p_class))); classes[name] = ClassInfo(); ClassInfo &ti = classes[name]; ti.name = name; ti.inherits = p_inherits; ti.api = current_api; if (ti.inherits) { ERR_FAIL_COND(!classes.has(ti.inherits)); //it MUST be registered. ti.inherits_ptr = &classes[ti.inherits]; } else { ti.inherits_ptr = nullptr; } } static MethodInfo info_from_bind(MethodBind *p_method) { MethodInfo minfo; minfo.name = p_method->get_name(); minfo.id = p_method->get_method_id(); for (int i = 0; i < p_method->get_argument_count(); i++) { minfo.arguments.push_back(p_method->get_argument_info(i)); } minfo.return_val = p_method->get_return_info(); minfo.flags = p_method->get_hint_flags(); for (int i = 0; i < p_method->get_argument_count(); i++) { if (p_method->has_default_argument(i)) { minfo.default_arguments.push_back(p_method->get_default_argument(i)); } } return minfo; } void ClassDB::get_method_list(const StringName &p_class, List<MethodInfo> *p_methods, bool p_no_inheritance, bool p_exclude_from_properties) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->disabled) { if (p_no_inheritance) { break; } type = type->inherits_ptr; continue; } #ifdef DEBUG_ENABLED for (const MethodInfo &E : type->virtual_methods) { p_methods->push_back(E); } for (const StringName &E : type->method_order) { if (p_exclude_from_properties && type->methods_in_properties.has(E)) { continue; } MethodBind *method = type->method_map.get(E); MethodInfo minfo = info_from_bind(method); p_methods->push_back(minfo); } #else for (KeyValue<StringName, MethodBind *> &E : type->method_map) { MethodBind *m = E.value; MethodInfo minfo = info_from_bind(m); p_methods->push_back(minfo); } #endif // DEBUG_ENABLED if (p_no_inheritance) { break; } type = type->inherits_ptr; } } void ClassDB::get_method_list_with_compatibility(const StringName &p_class, List<Pair<MethodInfo, uint32_t>> *p_methods, bool p_no_inheritance, bool p_exclude_from_properties) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->disabled) { if (p_no_inheritance) { break; } type = type->inherits_ptr; continue; } #ifdef DEBUG_ENABLED for (const MethodInfo &E : type->virtual_methods) { Pair<MethodInfo, uint32_t> pair(E, E.get_compatibility_hash()); p_methods->push_back(pair); } for (const StringName &E : type->method_order) { if (p_exclude_from_properties && type->methods_in_properties.has(E)) { continue; } MethodBind *method = type->method_map.get(E); MethodInfo minfo = info_from_bind(method); Pair<MethodInfo, uint32_t> pair(minfo, method->get_hash()); p_methods->push_back(pair); } #else for (KeyValue<StringName, MethodBind *> &E : type->method_map) { MethodBind *method = E.value; MethodInfo minfo = info_from_bind(method); Pair<MethodInfo, uint32_t> pair(minfo, method->get_hash()); p_methods->push_back(pair); } #endif // DEBUG_ENABLED for (const KeyValue<StringName, LocalVector<MethodBind *, unsigned int, false, false>> &E : type->method_map_compatibility) { LocalVector<MethodBind *> compat = E.value; for (MethodBind *method : compat) { MethodInfo minfo = info_from_bind(method); Pair<MethodInfo, uint32_t> pair(minfo, method->get_hash()); p_methods->push_back(pair); } } if (p_no_inheritance) { break; } type = type->inherits_ptr; } } bool ClassDB::get_method_info(const StringName &p_class, const StringName &p_method, MethodInfo *r_info, bool p_no_inheritance, bool p_exclude_from_properties) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->disabled) { if (p_no_inheritance) { break; } type = type->inherits_ptr; continue; } #ifdef DEBUG_ENABLED MethodBind **method = type->method_map.getptr(p_method); if (method && *method) { if (r_info != nullptr) { MethodInfo minfo = info_from_bind(*method); *r_info = minfo; } return true; } else if (type->virtual_methods_map.has(p_method)) { if (r_info) { *r_info = type->virtual_methods_map[p_method]; } return true; } #else if (type->method_map.has(p_method)) { if (r_info) { MethodBind *m = type->method_map[p_method]; MethodInfo minfo = info_from_bind(m); *r_info = minfo; } return true; } #endif // DEBUG_ENABLED if (p_no_inheritance) { break; } type = type->inherits_ptr; } return false; } MethodBind *ClassDB::get_method(const StringName &p_class, const StringName &p_name) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { MethodBind **method = type->method_map.getptr(p_name); if (method && *method) { return *method; } type = type->inherits_ptr; } return nullptr; } Vector<uint32_t> ClassDB::get_method_compatibility_hashes(const StringName &p_class, const StringName &p_name) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->method_map_compatibility.has(p_name)) { LocalVector<MethodBind *> *c = type->method_map_compatibility.getptr(p_name); Vector<uint32_t> ret; for (uint32_t i = 0; i < c->size(); i++) { ret.push_back((*c)[i]->get_hash()); } return ret; } type = type->inherits_ptr; } return Vector<uint32_t>(); } MethodBind *ClassDB::get_method_with_compatibility(const StringName &p_class, const StringName &p_name, uint64_t p_hash, bool *r_method_exists, bool *r_is_deprecated) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { MethodBind **method = type->method_map.getptr(p_name); if (method && *method) { if (r_method_exists) { *r_method_exists = true; } if ((*method)->get_hash() == p_hash) { return *method; } } LocalVector<MethodBind *> *compat = type->method_map_compatibility.getptr(p_name); if (compat) { if (r_method_exists) { *r_method_exists = true; } for (uint32_t i = 0; i < compat->size(); i++) { if ((*compat)[i]->get_hash() == p_hash) { if (r_is_deprecated) { *r_is_deprecated = true; } return (*compat)[i]; } } } type = type->inherits_ptr; } return nullptr; } void ClassDB::bind_integer_constant(const StringName &p_class, const StringName &p_enum, const StringName &p_name, int64_t p_constant, bool p_is_bitfield) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); if (type->constant_map.has(p_name)) { ERR_FAIL(); } type->constant_map[p_name] = p_constant; String enum_name = p_enum; if (!enum_name.is_empty()) { if (enum_name.contains_char('.')) { enum_name = enum_name.get_slicec('.', 1); } ClassInfo::EnumInfo *constants_list = type->enum_map.getptr(enum_name); if (constants_list) { constants_list->constants.push_back(p_name); constants_list->is_bitfield = p_is_bitfield; } else { ClassInfo::EnumInfo new_list; new_list.is_bitfield = p_is_bitfield; new_list.constants.push_back(p_name); type->enum_map[enum_name] = new_list; } } #ifdef DEBUG_ENABLED type->constant_order.push_back(p_name); #endif // DEBUG_ENABLED } void ClassDB::get_integer_constant_list(const StringName &p_class, List<String> *p_constants, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { #ifdef DEBUG_ENABLED for (const StringName &E : type->constant_order) { p_constants->push_back(E); } #else for (const KeyValue<StringName, int64_t> &E : type->constant_map) { p_constants->push_back(E.key); } #endif // DEBUG_ENABLED if (p_no_inheritance) { break; } type = type->inherits_ptr; } } int64_t ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name, bool *p_success) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { int64_t *constant = type->constant_map.getptr(p_name); if (constant) { if (p_success) { *p_success = true; } return *constant; } type = type->inherits_ptr; } if (p_success) { *p_success = false; } return 0; } bool ClassDB::has_integer_constant(const StringName &p_class, const StringName &p_name, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->constant_map.has(p_name)) { return true; } if (p_no_inheritance) { return false; } type = type->inherits_ptr; } return false; } StringName ClassDB::get_integer_constant_enum(const StringName &p_class, const StringName &p_name, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { for (KeyValue<StringName, ClassInfo::EnumInfo> &E : type->enum_map) { List<StringName> &constants_list = E.value.constants; const List<StringName>::Element *found = constants_list.find(p_name); if (found) { return E.key; } } if (p_no_inheritance) { break; } type = type->inherits_ptr; } return StringName(); } void ClassDB::get_enum_list(const StringName &p_class, List<StringName> *p_enums, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { for (KeyValue<StringName, ClassInfo::EnumInfo> &E : type->enum_map) { p_enums->push_back(E.key); } if (p_no_inheritance) { break; } type = type->inherits_ptr; } } void ClassDB::get_enum_constants(const StringName &p_class, const StringName &p_enum, List<StringName> *p_constants, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { const ClassInfo::EnumInfo *constants = type->enum_map.getptr(p_enum); if (constants) { for (const List<StringName>::Element *E = constants->constants.front(); E; E = E->next()) { p_constants->push_back(E->get()); } } if (p_no_inheritance) { break; } type = type->inherits_ptr; } } void ClassDB::set_method_error_return_values(const StringName &p_class, const StringName &p_method, const Vector<Error> &p_values) { #ifdef DEBUG_ENABLED Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); type->method_error_values[p_method] = p_values; #endif // DEBUG_ENABLED } Vector<Error> ClassDB::get_method_error_return_values(const StringName &p_class, const StringName &p_method) { #ifdef DEBUG_ENABLED Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL_V(type, Vector<Error>()); if (!type->method_error_values.has(p_method)) { return Vector<Error>(); } return type->method_error_values[p_method]; #else return Vector<Error>(); #endif // DEBUG_ENABLED } bool ClassDB::has_enum(const StringName &p_class, const StringName &p_name, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->enum_map.has(p_name)) { return true; } if (p_no_inheritance) { return false; } type = type->inherits_ptr; } return false; } bool ClassDB::is_enum_bitfield(const StringName &p_class, const StringName &p_name, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->enum_map.has(p_name) && type->enum_map[p_name].is_bitfield) { return true; } if (p_no_inheritance) { return false; } type = type->inherits_ptr; } return false; } void ClassDB::add_signal(const StringName &p_class, const MethodInfo &p_signal) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); StringName sname = p_signal.name; #ifdef DEBUG_ENABLED ClassInfo *check = type; while (check) { ERR_FAIL_COND_MSG(check->signal_map.has(sname), vformat("Class '%s' already has signal '%s'.", String(p_class), String(sname))); check = check->inherits_ptr; } #endif // DEBUG_ENABLED type->signal_map[sname] = p_signal; } void ClassDB::get_signal_list(const StringName &p_class, List<MethodInfo> *p_signals, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); ClassInfo *check = type; while (check) { for (KeyValue<StringName, MethodInfo> &E : check->signal_map) { p_signals->push_back(E.value); } if (p_no_inheritance) { return; } check = check->inherits_ptr; } } bool ClassDB::has_signal(const StringName &p_class, const StringName &p_signal, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { if (check->signal_map.has(p_signal)) { return true; } if (p_no_inheritance) { return false; } check = check->inherits_ptr; } return false; } bool ClassDB::get_signal(const StringName &p_class, const StringName &p_signal, MethodInfo *r_signal) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { if (check->signal_map.has(p_signal)) { if (r_signal) { *r_signal = check->signal_map[p_signal]; } return true; } check = check->inherits_ptr; } return false; } void ClassDB::add_property_group(const StringName &p_class, const String &p_name, const String &p_prefix, int p_indent_depth) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); String prefix = p_prefix; if (p_indent_depth > 0) { prefix = vformat("%s,%d", p_prefix, p_indent_depth); } type->property_list.push_back(PropertyInfo(Variant::NIL, p_name, PROPERTY_HINT_NONE, prefix, PROPERTY_USAGE_GROUP)); } void ClassDB::add_property_subgroup(const StringName &p_class, const String &p_name, const String &p_prefix, int p_indent_depth) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); String prefix = p_prefix; if (p_indent_depth > 0) { prefix = vformat("%s,%d", p_prefix, p_indent_depth); } type->property_list.push_back(PropertyInfo(Variant::NIL, p_name, PROPERTY_HINT_NONE, prefix, PROPERTY_USAGE_SUBGROUP)); } void ClassDB::add_property_array_count(const StringName &p_class, const String &p_label, const StringName &p_count_property, const StringName &p_count_setter, const StringName &p_count_getter, const String &p_array_element_prefix, uint32_t p_count_usage) { add_property(p_class, PropertyInfo(Variant::INT, p_count_property, PROPERTY_HINT_NONE, "", p_count_usage | PROPERTY_USAGE_ARRAY, vformat("%s,%s", p_label, p_array_element_prefix)), p_count_setter, p_count_getter); } void ClassDB::add_property_array(const StringName &p_class, const StringName &p_path, const String &p_array_element_prefix) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); type->property_list.push_back(PropertyInfo(Variant::NIL, p_path, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, p_array_element_prefix)); } // NOTE: For implementation simplicity reasons, this method doesn't allow setters to have optional arguments at the end. void ClassDB::add_property(const StringName &p_class, const PropertyInfo &p_pinfo, const StringName &p_setter, const StringName &p_getter, int p_index) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); MethodBind *mb_set = nullptr; if (p_setter) { mb_set = get_method(p_class, p_setter); #ifdef DEBUG_ENABLED ERR_FAIL_NULL_MSG(mb_set, vformat("Invalid setter '%s::%s' for property '%s'.", p_class, p_setter, p_pinfo.name)); int exp_args = 1 + (p_index >= 0 ? 1 : 0); ERR_FAIL_COND_MSG(mb_set->get_argument_count() != exp_args, vformat("Invalid function for setter '%s::%s' for property '%s'.", p_class, p_setter, p_pinfo.name)); #endif // DEBUG_ENABLED } MethodBind *mb_get = nullptr; if (p_getter) { mb_get = get_method(p_class, p_getter); #ifdef DEBUG_ENABLED ERR_FAIL_NULL_MSG(mb_get, vformat("Invalid getter '%s::%s' for property '%s'.", p_class, p_getter, p_pinfo.name)); int exp_args = 0 + (p_index >= 0 ? 1 : 0); ERR_FAIL_COND_MSG(mb_get->get_argument_count() != exp_args, vformat("Invalid function for getter '%s::%s' for property '%s'.", p_class, p_getter, p_pinfo.name)); #endif // DEBUG_ENABLED } #ifdef DEBUG_ENABLED ERR_FAIL_COND_MSG(type->property_setget.has(p_pinfo.name), vformat("Object '%s' already has property '%s'.", p_class, p_pinfo.name)); #endif // DEBUG_ENABLED type->property_list.push_back(p_pinfo); type->property_map[p_pinfo.name] = p_pinfo; #ifdef DEBUG_ENABLED if (mb_get) { type->methods_in_properties.insert(p_getter); } if (mb_set) { type->methods_in_properties.insert(p_setter); } #endif // DEBUG_ENABLED PropertySetGet psg; psg.setter = p_setter; psg.getter = p_getter; psg._setptr = mb_set; psg._getptr = mb_get; psg.index = p_index; psg.type = p_pinfo.type; type->property_setget[p_pinfo.name] = psg; } void ClassDB::set_property_default_value(const StringName &p_class, const StringName &p_name, const Variant &p_default) { if (!default_values.has(p_class)) { default_values[p_class] = HashMap<StringName, Variant>(); } default_values[p_class][p_name] = p_default; } void ClassDB::add_linked_property(const StringName &p_class, const String &p_property, const String &p_linked_property) { #ifdef TOOLS_ENABLED Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ERR_FAIL_NULL(type); ERR_FAIL_COND(!type->property_map.has(p_property)); ERR_FAIL_COND(!type->property_map.has(p_linked_property)); if (!type->linked_properties.has(p_property)) { type->linked_properties.insert(p_property, List<StringName>()); } type->linked_properties[p_property].push_back(p_linked_property); #endif } void ClassDB::get_property_list(const StringName &p_class, List<PropertyInfo> *p_list, bool p_no_inheritance, const Object *p_validator) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { for (const PropertyInfo &pi : check->property_list) { if (p_validator) { // Making a copy as we may modify it. PropertyInfo pi_mut = pi; p_validator->validate_property(pi_mut); p_list->push_back(pi_mut); } else { p_list->push_back(pi); } } if (p_no_inheritance) { return; } check = check->inherits_ptr; } } void ClassDB::get_linked_properties_info(const StringName &p_class, const StringName &p_property, List<StringName> *r_properties, bool p_no_inheritance) { #ifdef TOOLS_ENABLED ClassInfo *check = classes.getptr(p_class); while (check) { if (!check->linked_properties.has(p_property)) { return; } for (const StringName &E : check->linked_properties[p_property]) { r_properties->push_back(E); } if (p_no_inheritance) { break; } check = check->inherits_ptr; } #endif } bool ClassDB::get_property_info(const StringName &p_class, const StringName &p_property, PropertyInfo *r_info, bool p_no_inheritance, const Object *p_validator) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *check = classes.getptr(p_class); while (check) { if (check->property_map.has(p_property)) { PropertyInfo pinfo = check->property_map[p_property]; if (p_validator) { p_validator->validate_property(pinfo); } if (r_info) { *r_info = pinfo; } return true; } if (p_no_inheritance) { break; } check = check->inherits_ptr; } return false; } bool ClassDB::set_property(Object *p_object, const StringName &p_property, const Variant &p_value, bool *r_valid) { ERR_FAIL_NULL_V(p_object, false); ClassInfo *type = classes.getptr(p_object->get_class_name()); ClassInfo *check = type; while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (!psg->setter) { if (r_valid) { *r_valid = false; } return true; //return true but do nothing } Callable::CallError ce; if (psg->index >= 0) { Variant index = psg->index; const Variant *arg[2] = { &index, &p_value }; //p_object->call(psg->setter,arg,2,ce); if (psg->_setptr) { psg->_setptr->call(p_object, arg, 2, ce); } else { p_object->callp(psg->setter, arg, 2, ce); } } else { const Variant *arg[1] = { &p_value }; if (psg->_setptr) { psg->_setptr->call(p_object, arg, 1, ce); } else { p_object->callp(psg->setter, arg, 1, ce); } } if (r_valid) { *r_valid = ce.error == Callable::CallError::CALL_OK; } return true; } check = check->inherits_ptr; } return false; } bool ClassDB::get_property(Object *p_object, const StringName &p_property, Variant &r_value) { ERR_FAIL_NULL_V(p_object, false); ClassInfo *type = classes.getptr(p_object->get_class_name()); ClassInfo *check = type; while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (!psg->getter) { return true; //return true but do nothing } if (psg->index >= 0) { Variant index = psg->index; const Variant *arg[1] = { &index }; Callable::CallError ce; const Variant value = p_object->callp(psg->getter, arg, 1, ce); r_value = (ce.error == Callable::CallError::CALL_OK) ? value : Variant(); } else { Callable::CallError ce; if (psg->_getptr) { r_value = psg->_getptr->call(p_object, nullptr, 0, ce); } else { const Variant value = p_object->callp(psg->getter, nullptr, 0, ce); r_value = (ce.error == Callable::CallError::CALL_OK) ? value : Variant(); } } return true; } const int64_t *c = check->constant_map.getptr(p_property); //constants count if (c) { r_value = *c; return true; } if (check->method_map.has(p_property)) { //methods count r_value = Callable(p_object, p_property); return true; } if (check->signal_map.has(p_property)) { //signals count r_value = Signal(p_object, p_property); return true; } check = check->inherits_ptr; } // The "free()" method is special, so we assume it exists and return a Callable. if (p_property == CoreStringName(free_)) { r_value = Callable(p_object, p_property); return true; } return false; } int ClassDB::get_property_index(const StringName &p_class, const StringName &p_property, bool *r_is_valid) { ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (r_is_valid) { *r_is_valid = true; } return psg->index; } check = check->inherits_ptr; } if (r_is_valid) { *r_is_valid = false; } return -1; } Variant::Type ClassDB::get_property_type(const StringName &p_class, const StringName &p_property, bool *r_is_valid) { ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { if (r_is_valid) { *r_is_valid = true; } return psg->type; } check = check->inherits_ptr; } if (r_is_valid) { *r_is_valid = false; } return Variant::NIL; } StringName ClassDB::get_property_setter(const StringName &p_class, const StringName &p_property) { ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { return psg->setter; } check = check->inherits_ptr; } return StringName(); } StringName ClassDB::get_property_getter(const StringName &p_class, const StringName &p_property) { ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { const PropertySetGet *psg = check->property_setget.getptr(p_property); if (psg) { return psg->getter; } check = check->inherits_ptr; } return StringName(); } bool ClassDB::has_property(const StringName &p_class, const StringName &p_property, bool p_no_inheritance) { ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { if (check->property_setget.has(p_property)) { return true; } if (p_no_inheritance) { break; } check = check->inherits_ptr; } return false; } void ClassDB::set_method_flags(const StringName &p_class, const StringName &p_method, int p_flags) { Locker::Lock lock(Locker::STATE_WRITE); ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; ERR_FAIL_NULL(check); ERR_FAIL_COND(!check->method_map.has(p_method)); check->method_map[p_method]->set_hint_flags(p_flags); } bool ClassDB::has_method(const StringName &p_class, const StringName &p_method, bool p_no_inheritance) { ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { if (check->method_map.has(p_method)) { return true; } if (p_no_inheritance) { return false; } check = check->inherits_ptr; } return false; } int ClassDB::get_method_argument_count(const StringName &p_class, const StringName &p_method, bool *r_is_valid, bool p_no_inheritance) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { MethodBind **method = type->method_map.getptr(p_method); if (method && *method) { if (r_is_valid) { *r_is_valid = true; } return (*method)->get_argument_count(); } if (p_no_inheritance) { break; } type = type->inherits_ptr; } if (r_is_valid) { *r_is_valid = false; } return 0; } void ClassDB::bind_method_custom(const StringName &p_class, MethodBind *p_method) { _bind_method_custom(p_class, p_method, false); } void ClassDB::bind_compatibility_method_custom(const StringName &p_class, MethodBind *p_method) { _bind_method_custom(p_class, p_method, true); } void ClassDB::_bind_compatibility(ClassInfo *type, MethodBind *p_method) { if (!type->method_map_compatibility.has(p_method->get_name())) { type->method_map_compatibility.insert(p_method->get_name(), LocalVector<MethodBind *>()); } type->method_map_compatibility[p_method->get_name()].push_back(p_method); } void ClassDB::_bind_method_custom(const StringName &p_class, MethodBind *p_method, bool p_compatibility) { Locker::Lock lock(Locker::STATE_WRITE); StringName method_name = p_method->get_name(); ClassInfo *type = classes.getptr(p_class); if (!type) { memdelete(p_method); ERR_FAIL_MSG(vformat("Couldn't bind custom method '%s' for instance '%s'.", method_name, p_class)); } if (p_compatibility) { _bind_compatibility(type, p_method); return; } if (type->method_map.has(method_name)) { // overloading not supported memdelete(p_method); ERR_FAIL_MSG(vformat("Method already bound '%s::%s'.", p_class, method_name)); } #ifdef DEBUG_ENABLED type->method_order.push_back(method_name); #endif // DEBUG_ENABLED type->method_map[method_name] = p_method; } MethodBind *ClassDB::_bind_vararg_method(MethodBind *p_bind, const StringName &p_name, const Vector<Variant> &p_default_args, bool p_compatibility) { MethodBind *bind = p_bind; bind->set_name(p_name); bind->set_default_arguments(p_default_args); String instance_type = bind->get_instance_class(); ClassInfo *type = classes.getptr(instance_type); if (!type) { memdelete(bind); ERR_FAIL_NULL_V(type, nullptr); } if (p_compatibility) { _bind_compatibility(type, bind); return bind; } if (type->method_map.has(p_name)) { memdelete(bind); // Overloading not supported ERR_FAIL_V_MSG(nullptr, vformat("Method already bound: '%s::%s'.", instance_type, p_name)); } type->method_map[p_name] = bind; #ifdef DEBUG_ENABLED // FIXME: <reduz> set_return_type is no longer in MethodBind, so I guess it should be moved to vararg method bind //bind->set_return_type("Variant"); type->method_order.push_back(p_name); #endif // DEBUG_ENABLED return bind; } #ifdef DEBUG_ENABLED MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, bool p_compatibility, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) { StringName mdname = method_name.name; #else MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, bool p_compatibility, const char *method_name, const Variant **p_defs, int p_defcount) { StringName mdname = StringName(method_name); #endif // DEBUG_ENABLED Locker::Lock lock(Locker::STATE_WRITE); ERR_FAIL_NULL_V(p_bind, nullptr); p_bind->set_name(mdname); String instance_type = p_bind->get_instance_class(); #ifdef DEBUG_ENABLED ERR_FAIL_COND_V_MSG(!p_compatibility && has_method(instance_type, mdname), nullptr, vformat("Class '%s' already has a method '%s'.", String(instance_type), String(mdname))); #endif // DEBUG_ENABLED ClassInfo *type = classes.getptr(instance_type); if (!type) { memdelete(p_bind); ERR_FAIL_V_MSG(nullptr, vformat("Couldn't bind method '%s' for instance '%s'.", mdname, instance_type)); } if (!p_compatibility && type->method_map.has(mdname)) { memdelete(p_bind); // overloading not supported ERR_FAIL_V_MSG(nullptr, vformat("Method already bound '%s::%s'.", instance_type, mdname)); } #ifdef DEBUG_ENABLED if (method_name.args.size() > p_bind->get_argument_count()) { memdelete(p_bind); ERR_FAIL_V_MSG(nullptr, vformat("Method definition provides more arguments than the method actually has '%s::%s'.", instance_type, mdname)); } if (p_defcount > p_bind->get_argument_count()) { memdelete(p_bind); ERR_FAIL_V_MSG(nullptr, vformat("Method definition for '%s::%s' provides more default arguments than the method has arguments.", instance_type, mdname)); } p_bind->set_argument_names(method_name.args); if (!p_compatibility) { type->method_order.push_back(mdname); } #endif // DEBUG_ENABLED if (p_compatibility) { _bind_compatibility(type, p_bind); } else { type->method_map[mdname] = p_bind; } Vector<Variant> defvals; defvals.resize(p_defcount); for (int i = 0; i < p_defcount; i++) { defvals.write[i] = *p_defs[i]; } p_bind->set_default_arguments(defvals); p_bind->set_hint_flags(p_flags); return p_bind; } void ClassDB::add_virtual_method(const StringName &p_class, const MethodInfo &p_method, bool p_virtual, const Vector<String> &p_arg_names, bool p_object_core) { ERR_FAIL_COND_MSG(!classes.has(p_class), vformat("Request for nonexistent class '%s'.", p_class)); Locker::Lock lock(Locker::STATE_WRITE); #ifdef DEBUG_ENABLED MethodInfo mi = p_method; if (p_virtual) { mi.flags |= METHOD_FLAG_VIRTUAL; } if (p_object_core) { mi.flags |= METHOD_FLAG_OBJECT_CORE; } if (!p_object_core) { if (p_arg_names.size() != mi.arguments.size()) { WARN_PRINT(vformat("Mismatch argument name count for virtual method: '%s::%s'.", String(p_class), p_method.name)); } else { for (int64_t i = 0; i < p_arg_names.size(); ++i) { mi.arguments.write[i].name = p_arg_names[i]; } } } if (classes[p_class].virtual_methods_map.has(p_method.name)) { // overloading not supported ERR_FAIL_MSG(vformat("Virtual method already bound '%s::%s'.", String(p_class), p_method.name)); } classes[p_class].virtual_methods.push_back(mi); classes[p_class].virtual_methods_map[p_method.name] = mi; #endif // DEBUG_ENABLED } void ClassDB::add_virtual_compatibility_method(const StringName &p_class, const MethodInfo &p_method, bool p_virtual, const Vector<String> &p_arg_names, bool p_object_core) { ERR_FAIL_COND_MSG(!classes.has(p_class), vformat("Request for nonexistent class '%s'.", p_class)); Locker::Lock lock(Locker::STATE_WRITE); HashMap<StringName, Vector<uint32_t>> &virtual_methods_compat = classes[p_class].virtual_methods_compat; Vector<uint32_t> *compat_hashes = virtual_methods_compat.getptr(p_method.name); if (!compat_hashes) { virtual_methods_compat[p_method.name] = Vector<uint32_t>(); compat_hashes = &virtual_methods_compat[p_method.name]; } compat_hashes->push_back(p_method.get_compatibility_hash()); } void ClassDB::get_virtual_methods(const StringName &p_class, List<MethodInfo> *p_methods, bool p_no_inheritance) { ERR_FAIL_COND_MSG(!classes.has(p_class), vformat("Request for nonexistent class '%s'.", p_class)); #ifdef DEBUG_ENABLED ClassInfo *type = classes.getptr(p_class); ClassInfo *check = type; while (check) { for (const MethodInfo &E : check->virtual_methods) { p_methods->push_back(E); } if (p_no_inheritance) { return; } check = check->inherits_ptr; } #endif // DEBUG_ENABLED } Vector<uint32_t> ClassDB::get_virtual_method_compatibility_hashes(const StringName &p_class, const StringName &p_name) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *type = classes.getptr(p_class); while (type) { if (type->virtual_methods_compat.has(p_name)) { Vector<uint32_t> *compat_hashes = type->virtual_methods_compat.getptr(p_name); if (compat_hashes) { return *compat_hashes; } break; } type = type->inherits_ptr; } return Vector<uint32_t>(); } void ClassDB::add_extension_class_virtual_method(const StringName &p_class, const GDExtensionClassVirtualMethodInfo *p_method_info) { ERR_FAIL_COND_MSG(!classes.has(p_class), vformat("Request for nonexistent class '%s'.", p_class)); #ifdef DEBUG_ENABLED PackedStringArray arg_names; MethodInfo mi; mi.name = *reinterpret_cast<StringName *>(p_method_info->name); mi.return_val = PropertyInfo(p_method_info->return_value); mi.return_val_metadata = p_method_info->return_value_metadata; mi.flags = p_method_info->method_flags; for (int i = 0; i < (int)p_method_info->argument_count; i++) { PropertyInfo arg(p_method_info->arguments[i]); mi.arguments.push_back(arg); mi.arguments_metadata.push_back(p_method_info->arguments_metadata[i]); arg_names.push_back(arg.name); } add_virtual_method(p_class, mi, true, arg_names); #endif // DEBUG_ENABLED } void ClassDB::set_class_enabled(const StringName &p_class, bool p_enable) { Locker::Lock lock(Locker::STATE_WRITE); ERR_FAIL_COND_MSG(!classes.has(p_class), vformat("Request for nonexistent class '%s'.", p_class)); classes[p_class].disabled = !p_enable; } bool ClassDB::is_class_enabled(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); if (!ti || !ti->creation_func) { if (compat_classes.has(p_class)) { ti = classes.getptr(compat_classes[p_class]); } } ERR_FAIL_NULL_V_MSG(ti, false, vformat("Cannot get class '%s'.", String(p_class))); return !ti->disabled; } bool ClassDB::is_class_exposed(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); ERR_FAIL_NULL_V_MSG(ti, false, vformat("Cannot get class '%s'.", String(p_class))); return ti->exposed; } bool ClassDB::is_class_reloadable(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); ERR_FAIL_NULL_V_MSG(ti, false, vformat("Cannot get class '%s'.", String(p_class))); return ti->reloadable; } bool ClassDB::is_class_runtime(const StringName &p_class) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); ERR_FAIL_NULL_V_MSG(ti, false, vformat("Cannot get class '%s'.", String(p_class))); return ti->is_runtime; } #ifdef TOOLS_ENABLED void ClassDB::add_class_dependency(const StringName &p_class, const StringName &p_dependency) { Locker::Lock lock(Locker::STATE_WRITE); ERR_FAIL_COND_MSG(!classes.has(p_class), vformat("Request for nonexistent class '%s'.", p_class)); if (classes[p_class].dependency_list.find(p_dependency)) { ERR_FAIL(); } classes[p_class].dependency_list.push_back(p_dependency); } void ClassDB::get_class_dependencies(const StringName &p_class, List<StringName> *r_rependencies) { Locker::Lock lock(Locker::STATE_READ); ClassInfo *ti = classes.getptr(p_class); ERR_FAIL_NULL_MSG(ti, vformat("Cannot get class '%s'.", String(p_class))); for (const StringName &dep : ti->dependency_list) { r_rependencies->push_back(dep); } } #endif // TOOLS_ENABLED void ClassDB::add_resource_base_extension(const StringName &p_extension, const StringName &p_class) { if (resource_base_extensions.has(p_extension)) { return; } resource_base_extensions[p_extension] = p_class; } void ClassDB::get_resource_base_extensions(List<String> *p_extensions) { for (const KeyValue<StringName, StringName> &E : resource_base_extensions) { p_extensions->push_back(E.key); } } bool ClassDB::is_resource_extension(const StringName &p_extension) { return resource_base_extensions.has(p_extension); } void ClassDB::get_extensions_for_type(const StringName &p_class, List<String> *p_extensions) { for (const KeyValue<StringName, StringName> &E : resource_base_extensions) { if (is_parent_class(p_class, E.value) || is_parent_class(E.value, p_class)) { p_extensions->push_back(E.key); } } } HashMap<StringName, HashMap<StringName, Variant>> ClassDB::default_values; HashSet<StringName> ClassDB::default_values_cached; Variant ClassDB::class_get_default_property_value(const StringName &p_class, const StringName &p_property, bool *r_valid) { if (!default_values_cached.has(p_class)) { if (!default_values.has(p_class)) { default_values[p_class] = HashMap<StringName, Variant>(); } Object *c = nullptr; bool cleanup_c = false; if (Engine::get_singleton()->has_singleton(p_class)) { c = Engine::get_singleton()->get_singleton_object(p_class); cleanup_c = false; } else if (ClassDB::can_instantiate(p_class) && !ClassDB::is_virtual(p_class)) { // Keep this condition in sync with doc_tools.cpp get_documentation_default_value. c = ClassDB::instantiate_no_placeholders(p_class); cleanup_c = true; } if (c) { List<PropertyInfo> plist; c->get_property_list(&plist); for (const PropertyInfo &E : plist) { if (E.usage & (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR)) { if (!default_values[p_class].has(E.name)) { Variant v = c->get(E.name); default_values[p_class][E.name] = v; } } } if (cleanup_c) { memdelete(c); } } default_values_cached.insert(p_class); } if (!default_values.has(p_class)) { if (r_valid != nullptr) { *r_valid = false; } return Variant(); } if (!default_values[p_class].has(p_property)) { if (r_valid != nullptr) { *r_valid = false; } return Variant(); } if (r_valid != nullptr) { *r_valid = true; } Variant var = default_values[p_class][p_property]; #ifdef DEBUG_ENABLED // Some properties may have an instantiated Object as default value, // (like Path2D's `curve` used to have), but that's not a good practice. // Instead, those properties should use PROPERTY_USAGE_EDITOR_INSTANTIATE_OBJECT // to be auto-instantiated when created in the editor with the following method: // EditorNode::get_editor_data().instantiate_object_properties(obj); if (var.get_type() == Variant::OBJECT) { Object *obj = var.get_validated_object(); if (obj) { WARN_PRINT(vformat("Instantiated %s used as default value for %s's \"%s\" property.", obj->get_class(), p_class, p_property)); } } #endif // DEBUG_ENABLED return var; } void ClassDB::register_extension_class(ObjectGDExtension *p_extension) { GLOBAL_LOCK_FUNCTION; ERR_FAIL_COND_MSG(classes.has(p_extension->class_name), vformat("Class already registered: '%s'.", String(p_extension->class_name))); ERR_FAIL_COND_MSG(!classes.has(p_extension->parent_class_name), vformat("Parent class name for extension class not found: '%s'.", String(p_extension->parent_class_name))); ClassInfo *parent = classes.getptr(p_extension->parent_class_name); #ifdef TOOLS_ENABLED // @todo This is a limitation of the current implementation, but it should be possible to remove. ERR_FAIL_COND_MSG(p_extension->is_runtime && parent->gdextension && !parent->is_runtime, vformat("Extension runtime class '%s' cannot descend from '%s' which isn't also a runtime class.", String(p_extension->class_name), parent->name)); #endif ClassInfo c; c.api = p_extension->editor_class ? API_EDITOR_EXTENSION : API_EXTENSION; c.gdextension = p_extension; c.name = p_extension->class_name; c.is_virtual = p_extension->is_virtual; if (!p_extension->is_abstract) { // Find the closest ancestor which is either non-abstract or native (or both). ClassInfo *concrete_ancestor = parent; while (concrete_ancestor->creation_func == nullptr && concrete_ancestor->inherits_ptr != nullptr && concrete_ancestor->gdextension != nullptr) { concrete_ancestor = concrete_ancestor->inherits_ptr; } ERR_FAIL_NULL_MSG(concrete_ancestor->creation_func, vformat("Extension class '%s' cannot extend native abstract class '%s'.", String(p_extension->class_name), String(concrete_ancestor->name))); c.creation_func = concrete_ancestor->creation_func; } c.inherits = parent->name; c.class_ptr = parent->class_ptr; c.inherits_ptr = parent; c.exposed = p_extension->is_exposed; if (c.exposed) { // The parent classes should be exposed if it has an exposed child class. while (parent && !parent->exposed) { parent->exposed = true; parent = classes.getptr(parent->name); } } c.reloadable = p_extension->reloadable; #ifdef TOOLS_ENABLED c.is_runtime = p_extension->is_runtime; #endif classes[p_extension->class_name] = c; } void ClassDB::unregister_extension_class(const StringName &p_class, bool p_free_method_binds) { ClassInfo *c = classes.getptr(p_class); ERR_FAIL_NULL_MSG(c, vformat("Class '%s' does not exist.", String(p_class))); if (p_free_method_binds) { for (KeyValue<StringName, MethodBind *> &F : c->method_map) { memdelete(F.value); } } classes.erase(p_class); default_values_cached.erase(p_class); default_values.erase(p_class); #ifdef TOOLS_ENABLED placeholder_extensions.erase(p_class); #endif } HashMap<StringName, ClassDB::NativeStruct> ClassDB::native_structs; void ClassDB::register_native_struct(const StringName &p_name, const String &p_code, uint64_t p_current_size) { NativeStruct ns; ns.ccode = p_code; ns.struct_size = p_current_size; native_structs[p_name] = ns; } void ClassDB::get_native_struct_list(List<StringName> *r_names) { for (const KeyValue<StringName, NativeStruct> &E : native_structs) { r_names->push_back(E.key); } } String ClassDB::get_native_struct_code(const StringName &p_name) { ERR_FAIL_COND_V(!native_structs.has(p_name), String()); return native_structs[p_name].ccode; } uint64_t ClassDB::get_native_struct_size(const StringName &p_name) { ERR_FAIL_COND_V(!native_structs.has(p_name), 0); return native_structs[p_name].struct_size; } Object *ClassDB::_instantiate_allow_unexposed(const StringName &p_class) { return _instantiate_internal(p_class, false, true, false); } void ClassDB::cleanup_defaults() { default_values.clear(); default_values_cached.clear(); } void ClassDB::cleanup() { //OBJTYPE_LOCK; hah not here for (KeyValue<StringName, ClassInfo> &E : classes) { ClassInfo &ti = E.value; for (KeyValue<StringName, MethodBind *> &F : ti.method_map) { memdelete(F.value); } for (KeyValue<StringName, LocalVector<MethodBind *>> &F : ti.method_map_compatibility) { for (uint32_t i = 0; i < F.value.size(); i++) { memdelete(F.value[i]); } } } classes.clear(); resource_base_extensions.clear(); compat_classes.clear(); native_structs.clear(); } // Array to use in optional parameters on methods and the DEFVAL_ARRAY macro. Array ClassDB::default_array_arg = Array::create_read_only(); bool ClassDB::is_default_array_arg(const Array &p_array) { return p_array.is_same_instance(default_array_arg); } // ClassDB::Locker::Lock::Lock(Locker::State p_state) { DEV_ASSERT(p_state != STATE_UNLOCKED); if (p_state == STATE_READ) { if (Locker::thread_state == STATE_UNLOCKED) { state = STATE_READ; Locker::thread_state = STATE_READ; Locker::lock.read_lock(); } } else if (p_state == STATE_WRITE) { if (Locker::thread_state == STATE_UNLOCKED) { state = STATE_WRITE; Locker::thread_state = STATE_WRITE; Locker::lock.write_lock(); } else if (Locker::thread_state == STATE_READ) { CRASH_NOW_MSG("Lock can't be upgraded from read to write."); } } } ClassDB::Locker::Lock::~Lock() { if (state == STATE_READ) { Locker::lock.read_unlock(); Locker::thread_state = STATE_UNLOCKED; } else if (state == STATE_WRITE) { Locker::lock.write_unlock(); Locker::thread_state = STATE_UNLOCKED; } }
412
0.993812
1
0.993812
game-dev
MEDIA
0.553839
game-dev
0.690059
1
0.690059
MATTYOneInc/AionEncomBase_Java8
3,553
AL-Game/data/scripts/system/handlers/quest/reshanta/_13864Siel_Miren_Guardian.java
/* * =====================================================================================* * This file is part of Aion-Unique (Aion-Unique Home Software Development) * * Aion-Unique Development is a closed Aion Project that use Old Aion Project Base * * Like Aion-Lightning, Aion-Engine, Aion-Core, Aion-Extreme, Aion-NextGen, ArchSoft, * * Aion-Ger, U3J, Encom And other Aion project, All Credit Content * * That they make is belong to them/Copyright is belong to them. And All new Content * * that Aion-Unique make the copyright is belong to Aion-Unique * * You may have agreement with Aion-Unique Development, before use this Engine/Source * * You have agree with all of Term of Services agreement with Aion-Unique Development * * =====================================================================================* */ package quest.reshanta; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestDialog; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; /****/ /** Author Ghostfur & Unknown (Aion-Unique) /****/ public class _13864Siel_Miren_Guardian extends QuestHandler { private final static int questId = 13864; private final static int[] Ab1241BossE = {279541, 269911}; public _13864Siel_Miren_Guardian() { super(questId); } public void register() { qe.registerQuestNpc(805380).addOnQuestStart(questId); //Lagranjia. qe.registerQuestNpc(805380).addOnTalkEvent(questId); //Lagranjia. for (int mob: Ab1241BossE) { qe.registerQuestNpc(mob).addOnKillEvent(questId); } } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); int targetId = env.getTargetId(); final QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) { if (targetId == 805380) { //Lagranjia. if (env.getDialog() == QuestDialog.START_DIALOG) { return sendQuestDialog(env, 4762); } else { return sendQuestStartDialog(env); } } } else if (qs == null || qs.getStatus() == QuestStatus.REWARD) { if (targetId == 805380) { //Lagranjia. if (env.getDialog() == QuestDialog.START_DIALOG) { return sendQuestDialog(env, 10002); } else if (env.getDialog() == QuestDialog.SELECT_REWARD) { return sendQuestDialog(env, 5); } else { return sendQuestEndDialog(env); } } } return false; } public boolean onKillEvent(QuestEnv env) { final Player player = env.getPlayer(); final QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { switch (env.getTargetId()) { case 279541: case 269911: if (qs.getQuestVarById(1) < 1) { qs.setQuestVarById(1, qs.getQuestVarById(1) + 1); updateQuestStatus(env); } if (qs.getQuestVarById(1) >= 1) { qs.setQuestVarById(0, 1); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); } } } return false; } }
412
0.900833
1
0.900833
game-dev
MEDIA
0.955468
game-dev
0.9426
1
0.9426
mmalka/TheNoobBot
12,504
meshReader/RecastLayer/Recast/Recast.cpp
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.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 <float.h> #define _USE_MATH_DEFINES #include <math.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <new> #include "Recast.h" #include "RecastAlloc.h" #include "RecastAssert.h" float rcSqrt(float x) { return sqrtf(x); } /// @class rcContext /// @par /// /// This class does not provide logging or timer functionality on its /// own. Both must be provided by a concrete implementation /// by overriding the protected member functions. Also, this class does not /// provide an interface for extracting log messages. (Only adding them.) /// So concrete implementations must provide one. /// /// If no logging or timers are required, just pass an instance of this /// class through the Recast build process. /// /// @par /// /// Example: /// @code /// // Where ctx is an instance of rcContext and filepath is a char array. /// ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not load '%s'", filepath); /// @endcode #pragma unmanaged void rcContext::log(const rcLogCategory category, const char* format, ...) { if (!m_logEnabled) return; static const int MSG_SIZE = 512; char msg[MSG_SIZE]; va_list ap; va_start(ap, format); int len = vsnprintf_s(msg, MSG_SIZE, format, ap); if (len >= MSG_SIZE) { len = MSG_SIZE-1; msg[MSG_SIZE-1] = '\0'; } va_end(ap); doLog(category, msg, len); } #pragma managed rcHeightfield* rcAllocHeightfield() { return new (rcAlloc(sizeof(rcHeightfield), RC_ALLOC_PERM)) rcHeightfield; } rcHeightfield::rcHeightfield() : width() , height() , bmin() , bmax() , cs() , ch() , spans() , pools() , freelist() { } rcHeightfield::~rcHeightfield() { // Delete span array. rcFree(spans); // Delete span pools. while (pools) { rcSpanPool* next = pools->next; rcFree(pools); pools = next; } } void rcFreeHeightField(rcHeightfield* hf) { if (!hf) return; hf->~rcHeightfield(); rcFree(hf); } rcCompactHeightfield* rcAllocCompactHeightfield() { rcCompactHeightfield* chf = (rcCompactHeightfield*)rcAlloc(sizeof(rcCompactHeightfield), RC_ALLOC_PERM); memset(chf, 0, sizeof(rcCompactHeightfield)); return chf; } void rcFreeCompactHeightfield(rcCompactHeightfield* chf) { if (!chf) return; rcFree(chf->cells); rcFree(chf->spans); rcFree(chf->dist); rcFree(chf->areas); rcFree(chf); } rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet() { rcHeightfieldLayerSet* lset = (rcHeightfieldLayerSet*)rcAlloc(sizeof(rcHeightfieldLayerSet), RC_ALLOC_PERM); memset(lset, 0, sizeof(rcHeightfieldLayerSet)); return lset; } void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* lset) { if (!lset) return; for (int i = 0; i < lset->nlayers; ++i) { rcFree(lset->layers[i].heights); rcFree(lset->layers[i].areas); rcFree(lset->layers[i].cons); } rcFree(lset->layers); rcFree(lset); } rcContourSet* rcAllocContourSet() { rcContourSet* cset = (rcContourSet*)rcAlloc(sizeof(rcContourSet), RC_ALLOC_PERM); memset(cset, 0, sizeof(rcContourSet)); return cset; } void rcFreeContourSet(rcContourSet* cset) { if (!cset) return; for (int i = 0; i < cset->nconts; ++i) { rcFree(cset->conts[i].verts); rcFree(cset->conts[i].rverts); } rcFree(cset->conts); rcFree(cset); } rcPolyMesh* rcAllocPolyMesh() { rcPolyMesh* pmesh = (rcPolyMesh*)rcAlloc(sizeof(rcPolyMesh), RC_ALLOC_PERM); memset(pmesh, 0, sizeof(rcPolyMesh)); return pmesh; } void rcFreePolyMesh(rcPolyMesh* pmesh) { if (!pmesh) return; rcFree(pmesh->verts); rcFree(pmesh->polys); rcFree(pmesh->regs); rcFree(pmesh->flags); rcFree(pmesh->areas); rcFree(pmesh); } rcPolyMeshDetail* rcAllocPolyMeshDetail() { rcPolyMeshDetail* dmesh = (rcPolyMeshDetail*)rcAlloc(sizeof(rcPolyMeshDetail), RC_ALLOC_PERM); memset(dmesh, 0, sizeof(rcPolyMeshDetail)); return dmesh; } void rcFreePolyMeshDetail(rcPolyMeshDetail* dmesh) { if (!dmesh) return; rcFree(dmesh->meshes); rcFree(dmesh->verts); rcFree(dmesh->tris); rcFree(dmesh); } void rcCalcBounds(const float* verts, int nv, float* bmin, float* bmax) { // Calculate bounding box. rcVcopy(bmin, verts); rcVcopy(bmax, verts); for (int i = 1; i < nv; ++i) { const float* v = &verts[i*3]; rcVmin(bmin, v); rcVmax(bmax, v); } } void rcCalcGridSize(const float* bmin, const float* bmax, float cs, int* w, int* h) { *w = (int)((bmax[0] - bmin[0])/cs+0.5f); *h = (int)((bmax[2] - bmin[2])/cs+0.5f); } /// @par /// /// See the #rcConfig documentation for more information on the configuration parameters. /// /// @see rcAllocHeightfield, rcHeightfield bool rcCreateHeightfield(rcContext* ctx, rcHeightfield& hf, int width, int height, const float* bmin, const float* bmax, float cs, float ch) { rcIgnoreUnused(ctx); hf.width = width; hf.height = height; rcVcopy(hf.bmin, bmin); rcVcopy(hf.bmax, bmax); hf.cs = cs; hf.ch = ch; hf.spans = (rcSpan**)rcAlloc(sizeof(rcSpan*)*hf.width*hf.height, RC_ALLOC_PERM); if (!hf.spans) return false; memset(hf.spans, 0, sizeof(rcSpan*)*hf.width*hf.height); return true; } static void calcTriNormal(const float* v0, const float* v1, const float* v2, float* norm) { float e0[3], e1[3]; rcVsub(e0, v1, v0); rcVsub(e1, v2, v0); rcVcross(norm, e0, e1); rcVnormalize(norm); } /// @par /// /// Only sets the area id's for the walkable triangles. Does not alter the /// area id's for unwalkable triangles. /// /// See the #rcConfig documentation for more information on the configuration parameters. /// /// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles void rcMarkWalkableTriangles(rcContext* ctx, const float walkableSlopeAngle, const float* verts, int nv, const int* tris, int nt, unsigned char* areas) { rcIgnoreUnused(ctx); rcIgnoreUnused(nv); const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI); float norm[3]; for (int i = 0; i < nt; ++i) { const int* tri = &tris[i*3]; calcTriNormal(&verts[tri[0]*3], &verts[tri[1]*3], &verts[tri[2]*3], norm); // Check if the face is walkable. if (norm[1] > walkableThr) areas[i] = RC_WALKABLE_AREA; } } /// @par /// /// Only sets the area id's for the unwalkable triangles. Does not alter the /// area id's for walkable triangles. /// /// See the #rcConfig documentation for more information on the configuration parameters. /// /// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles void rcClearUnwalkableTriangles(rcContext* ctx, const float walkableSlopeAngle, const float* verts, int /*nv*/, const int* tris, int nt, unsigned char* areas) { rcIgnoreUnused(ctx); const float walkableThr = cosf(walkableSlopeAngle/180.0f*RC_PI); float norm[3]; for (int i = 0; i < nt; ++i) { const int* tri = &tris[i*3]; calcTriNormal(&verts[tri[0]*3], &verts[tri[1]*3], &verts[tri[2]*3], norm); // Check if the face is walkable. if (norm[1] <= walkableThr) areas[i] = RC_NULL_AREA; } } int rcGetHeightFieldSpanCount(rcContext* ctx, rcHeightfield& hf) { rcIgnoreUnused(ctx); const int w = hf.width; const int h = hf.height; int spanCount = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { for (rcSpan* s = hf.spans[x + y*w]; s; s = s->next) { if (s->area != RC_NULL_AREA) spanCount++; } } } return spanCount; } /// @par /// /// This is just the beginning of the process of fully building a compact heightfield. /// Various filters may be applied, then the distance field and regions built. /// E.g: #rcBuildDistanceField and #rcBuildRegions /// /// See the #rcConfig documentation for more information on the configuration parameters. /// /// @see rcAllocCompactHeightfield, rcHeightfield, rcCompactHeightfield, rcConfig bool rcBuildCompactHeightfield(rcContext* ctx, const int walkableHeight, const int walkableClimb, rcHeightfield& hf, rcCompactHeightfield& chf) { rcAssert(ctx); rcScopedTimer timer(ctx, RC_TIMER_BUILD_COMPACTHEIGHTFIELD); const int w = hf.width; const int h = hf.height; const int spanCount = rcGetHeightFieldSpanCount(ctx, hf); // Fill in header. chf.width = w; chf.height = h; chf.spanCount = spanCount; chf.walkableHeight = walkableHeight; chf.walkableClimb = walkableClimb; chf.maxRegions = 0; rcVcopy(chf.bmin, hf.bmin); rcVcopy(chf.bmax, hf.bmax); chf.bmax[1] += walkableHeight*hf.ch; chf.cs = hf.cs; chf.ch = hf.ch; chf.cells = (rcCompactCell*)rcAlloc(sizeof(rcCompactCell)*w*h, RC_ALLOC_PERM); if (!chf.cells) { ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.cells' (%d)", w*h); return false; } memset(chf.cells, 0, sizeof(rcCompactCell)*w*h); chf.spans = (rcCompactSpan*)rcAlloc(sizeof(rcCompactSpan)*spanCount, RC_ALLOC_PERM); if (!chf.spans) { ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.spans' (%d)", spanCount); return false; } memset(chf.spans, 0, sizeof(rcCompactSpan)*spanCount); chf.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*spanCount, RC_ALLOC_PERM); if (!chf.areas) { ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.areas' (%d)", spanCount); return false; } memset(chf.areas, RC_NULL_AREA, sizeof(unsigned char)*spanCount); const int MAX_HEIGHT = 0xffff; // Fill in cells and spans. int idx = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { const rcSpan* s = hf.spans[x + y*w]; // If there are no spans at this cell, just leave the data to index=0, count=0. if (!s) continue; rcCompactCell& c = chf.cells[x+y*w]; c.index = idx; c.count = 0; while (s) { if (s->area != RC_NULL_AREA) { const int bot = (int)s->smax; const int top = s->next ? (int)s->next->smin : MAX_HEIGHT; chf.spans[idx].y = (unsigned short)rcClamp(bot, 0, 0xffff); chf.spans[idx].h = (unsigned char)rcClamp(top - bot, 0, 0xff); chf.areas[idx] = s->area; idx++; c.count++; } s = s->next; } } } // Find neighbour connections. const int MAX_LAYERS = RC_NOT_CONNECTED-1; int tooHighNeighbour = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { const rcCompactCell& c = chf.cells[x+y*w]; for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) { rcCompactSpan& s = chf.spans[i]; for (int dir = 0; dir < 4; ++dir) { rcSetCon(s, dir, RC_NOT_CONNECTED); const int nx = x + rcGetDirOffsetX(dir); const int ny = y + rcGetDirOffsetY(dir); // First check that the neighbour cell is in bounds. if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue; // Iterate over all neighbour spans and check if any of the is // accessible from current cell. const rcCompactCell& nc = chf.cells[nx+ny*w]; for (int k = (int)nc.index, nk = (int)(nc.index+nc.count); k < nk; ++k) { const rcCompactSpan& ns = chf.spans[k]; const int bot = rcMax(s.y, ns.y); const int top = rcMin(s.y+s.h, ns.y+ns.h); // Check that the gap between the spans is walkable, // and that the climb height between the gaps is not too high. if ((top - bot) >= walkableHeight && rcAbs((int)ns.y - (int)s.y) <= walkableClimb) { // Mark direction as walkable. const int lidx = k - (int)nc.index; if (lidx < 0 || lidx > MAX_LAYERS) { tooHighNeighbour = rcMax(tooHighNeighbour, lidx); continue; } rcSetCon(s, dir, lidx); break; } } } } } } if (tooHighNeighbour > MAX_LAYERS) { ctx->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)", tooHighNeighbour, MAX_LAYERS); } return true; } /* static int getHeightfieldMemoryUsage(const rcHeightfield& hf) { int size = 0; size += sizeof(hf); size += hf.width * hf.height * sizeof(rcSpan*); rcSpanPool* pool = hf.pools; while (pool) { size += (sizeof(rcSpanPool) - sizeof(rcSpan)) + sizeof(rcSpan)*RC_SPANS_PER_POOL; pool = pool->next; } return size; } static int getCompactHeightFieldMemoryusage(const rcCompactHeightfield& chf) { int size = 0; size += sizeof(rcCompactHeightfield); size += sizeof(rcCompactSpan) * chf.spanCount; size += sizeof(rcCompactCell) * chf.width * chf.height; return size; } */
412
0.970668
1
0.970668
game-dev
MEDIA
0.580683
game-dev
0.980753
1
0.980753
Patcher0/ThePitUltimate
2,209
core/src/main/java/net/mizukilab/pit/item/type/ArmageddonBoots.kt
package net.mizukilab.pit.item.type import net.mizukilab.pit.item.IMythicItem import net.mizukilab.pit.util.Utils import net.mizukilab.pit.util.item.ItemBuilder import net.mizukilab.pit.util.item.ItemUtil import org.bukkit.Color import org.bukkit.Material import org.bukkit.inventory.ItemStack import java.util.* class ArmageddonBoots : IMythicItem() { init { maxLive = 66 live = 66 uuid = UUID.randomUUID() } override fun getInternalName(): String { return "armageddon_boots" } override fun getItemDisplayName(): String { return "&c终末之靴" } override fun getItemDisplayMaterial(): Material { return Material.LEATHER_BOOTS } override fun isEnchanted(): Boolean { return true } override fun loadFromItemStack(item: ItemStack?) { item ?: return val nmsItem = Utils.toNMStackQuick(item) val tag = nmsItem?.tag ?: return val extra = tag.getCompound("extra") ?: return this.uuid = ItemUtil.getUUIDObj(item); this.maxLive = extra.getInt("maxLive") this.live = extra.getInt("live") if (extra.hasKey("forceCanTrade")) { if (extra.getBoolean("forceCanTrade")) { this.forceCanTrade = 1 } else { this.forceCanTrade = 0 } } if (extra.hasKey("customName")) { this.customName = extra.getString("customName") } } override fun toItemStack(): ItemStack? { return ItemBuilder(super.toItemStack()) .lore( "&7生命: " + (if (live / (maxLive * 1.0) <= 0.6) if (live / (maxLive * 1.0) <= 0.3) "&c" else "&e" else "&a") + live + "&7/" + maxLive, "", "&7攻击其他玩家时免疫 &9无尽黑暗 &7附魔效果.", "" ) .internalName(internalName) .maxLive(maxLive) .live(live) .uuid(uuid) .setLetherColor(Color.RED) .deathDrop(false) .canSaveToEnderChest(true) .removeOnJoin(false) .canDrop(false) .canTrade(true) .shiny() .build() } }
412
0.95196
1
0.95196
game-dev
MEDIA
0.960896
game-dev
0.964981
1
0.964981
magmafoundation/Magma-Neo
4,440
patches/net/minecraft/world/level/chunk/storage/ChunkStorage.java.patch
--- a/net/minecraft/world/level/chunk/storage/ChunkStorage.java +++ b/net/minecraft/world/level/chunk/storage/ChunkStorage.java @@ -38,17 +_,63 @@ return this.worker.isOldChunkAround(p_223452_, p_223453_); } + // CraftBukkit start + private boolean check(net.minecraft.server.level.ServerChunkCache cps, int x, int z) { + ChunkPos pos = new ChunkPos(x, z); + if (cps != null) { + com.google.common.base.Preconditions.checkState(org.bukkit.Bukkit.isPrimaryThread(), "primary thread"); + if (cps.hasChunk(x, z)) { + return true; + } + } + + CompoundTag nbt; + try { + nbt = read(pos).get().orElse(null); + } catch (InterruptedException | java.util.concurrent.ExecutionException ex) { + throw new RuntimeException(ex); + } + if (nbt != null) { + CompoundTag level = nbt.getCompound("Level"); + if (level.getBoolean("TerrainPopulated")) { + return true; + } + + net.minecraft.world.level.chunk.status.ChunkStatus status = net.minecraft.world.level.chunk.status.ChunkStatus.byName(level.getString("Status")); + if (status != null && status.isOrAfter(net.minecraft.world.level.chunk.status.ChunkStatus.FEATURES)) { + return true; + } + } + + return false; + } + // CraftBukkit end + public CompoundTag upgradeChunkTag( ResourceKey<Level> p_188289_, Supplier<DimensionDataStorage> p_188290_, CompoundTag p_188291_, - Optional<ResourceKey<MapCodec<? extends ChunkGenerator>>> p_188292_ + Optional<ResourceKey<MapCodec<? extends ChunkGenerator>>> p_188292_, + ChunkPos pos, // CraftBukkit + @Nullable net.minecraft.server.level.ServerLevel generatoraccess // CraftBukkit ) { int i = getVersion(p_188291_); if (i == SharedConstants.getCurrentVersion().getDataVersion().getVersion()) { return p_188291_; } else { try { + // CraftBukkit start + if (i < 1466) { + CompoundTag level = p_188291_.getCompound("Level"); + if (level.getBoolean("TerrainPopulated") && !level.getBoolean("LightPopulated")) { + net.minecraft.server.level.ServerChunkCache cps = (generatoraccess == null) ? null : generatoraccess.getChunkSource(); + if (check(cps, pos.x - 1, pos.z) && check(cps, pos.x - 1, pos.z - 1) && check(cps, pos.x, pos.z - 1)) { + level.putBoolean("LightPopulated", true); + } + } + } + // CraftBukkit end + if (i < 1493) { p_188291_ = DataFixTypes.CHUNK.update(this.fixerUpper, p_188291_, i, 1493); if (p_188291_.getCompound("Level").getBoolean("hasLegacyStructureData")) { @@ -57,8 +_,21 @@ } } + // Spigot start - SPIGOT-6806: Quick and dirty way to prevent below zero generation in old chunks, by setting the status to heightmap instead of empty + boolean stopBelowZero = false; + boolean belowZeroGenerationInExistingChunks = (generatoraccess != null) ? ((net.minecraft.server.level.ServerLevel) generatoraccess).spigotConfig.belowZeroGenerationInExistingChunks : org.spigotmc.SpigotConfig.belowZeroGenerationInExistingChunks; + if (i <= 2730 && !belowZeroGenerationInExistingChunks) { + stopBelowZero = "full".equals(p_188291_.getCompound("Level").getString("Status")); + } + // Spigot end + injectDatafixingContext(p_188291_, p_188289_, p_188292_); p_188291_ = DataFixTypes.CHUNK.updateToCurrentVersion(this.fixerUpper, p_188291_, Math.max(1493, i)); + // Spigot start + if (stopBelowZero) { + p_188291_.putString("Status", net.minecraft.core.registries.BuiltInRegistries.CHUNK_STATUS.getKey(net.minecraft.world.level.chunk.status.ChunkStatus.SPAWN).toString()); + } + // Spigot end removeDatafixingContext(p_188291_); NbtUtils.addCurrentDataVersion(p_188291_); return p_188291_;
412
0.846491
1
0.846491
game-dev
MEDIA
0.994359
game-dev
0.883792
1
0.883792
space-wizards/space-station-14
3,144
Content.Shared/Fluids/SharedPuddleSystem.Spillable.cs
using Content.Shared.Chemistry.Components; using Content.Shared.Database; using Content.Shared.DoAfter; using Content.Shared.Examine; using Content.Shared.FixedPoint; using Content.Shared.Fluids.Components; using Content.Shared.Nutrition.EntitySystems; using Content.Shared.Spillable; using Content.Shared.Verbs; using Content.Shared.Weapons.Melee; namespace Content.Shared.Fluids; public abstract partial class SharedPuddleSystem { [Dependency] protected readonly OpenableSystem Openable = default!; protected virtual void InitializeSpillable() { SubscribeLocalEvent<SpillableComponent, ExaminedEvent>(OnExamined); SubscribeLocalEvent<SpillableComponent, GetVerbsEvent<Verb>>(AddSpillVerb); } private void OnExamined(Entity<SpillableComponent> entity, ref ExaminedEvent args) { using (args.PushGroup(nameof(SpillableComponent))) { args.PushMarkup(Loc.GetString("spill-examine-is-spillable")); if (HasComp<MeleeWeaponComponent>(entity)) args.PushMarkup(Loc.GetString("spill-examine-spillable-weapon")); } } private void AddSpillVerb(Entity<SpillableComponent> entity, ref GetVerbsEvent<Verb> args) { if (!args.CanAccess || !args.CanInteract || args.Hands == null) return; if (!_solutionContainerSystem.TryGetSolution(args.Target, entity.Comp.SolutionName, out var soln, out var solution)) return; if (Openable.IsClosed(args.Target)) return; if (solution.Volume == FixedPoint2.Zero) return; Verb verb = new() { Text = Loc.GetString("spill-target-verb-get-data-text") }; // TODO VERB ICONS spill icon? pouring out a glass/beaker? if (entity.Comp.SpillDelay == null) { var target = args.Target; verb.Act = () => { var puddleSolution = _solutionContainerSystem.SplitSolution(soln.Value, solution.Volume); TrySpillAt(Transform(target).Coordinates, puddleSolution, out _); // TODO: Make this an event subscription once spilling puddles is predicted. // Injectors should not be hardcoded here. if (TryComp<InjectorComponent>(entity, out var injectorComp)) { injectorComp.ToggleState = InjectorToggleMode.Draw; Dirty(entity, injectorComp); } }; } else { var user = args.User; verb.Act = () => { _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, user, entity.Comp.SpillDelay ?? 0, new SpillDoAfterEvent(), entity.Owner, target: entity.Owner) { BreakOnDamage = true, BreakOnMove = true, NeedHand = true, }); }; } verb.Impact = LogImpact.Medium; // dangerous reagent reaction are logged separately. verb.DoContactInteraction = true; args.Verbs.Add(verb); } }
412
0.919084
1
0.919084
game-dev
MEDIA
0.9456
game-dev
0.920819
1
0.920819
MikeyTheA/PokeRogueModLoader
13,280
src/ui/fight-ui-handler.ts
import BattleScene, { InfoToggle } from "../battle-scene"; import { addTextObject, TextStyle } from "./text"; import { getTypeDamageMultiplierColor, Type } from "../data/type"; import { Command } from "./command-ui-handler"; import { Mode } from "./ui"; import UiHandler from "./ui-handler"; import * as Utils from "../utils"; import { MoveCategory } from "#app/data/move"; import i18next from "i18next"; import { Button } from "#enums/buttons"; import Pokemon, { PokemonMove } from "#app/field/pokemon"; import { CommandPhase } from "#app/phases/command-phase"; import MoveInfoOverlay from "./move-info-overlay"; import { BattleType } from "#app/battle"; export default class FightUiHandler extends UiHandler implements InfoToggle { public static readonly MOVES_CONTAINER_NAME = "moves"; private movesContainer: Phaser.GameObjects.Container; private moveInfoContainer: Phaser.GameObjects.Container; private typeIcon: Phaser.GameObjects.Sprite; private ppLabel: Phaser.GameObjects.Text; private ppText: Phaser.GameObjects.Text; private powerLabel: Phaser.GameObjects.Text; private powerText: Phaser.GameObjects.Text; private accuracyLabel: Phaser.GameObjects.Text; private accuracyText: Phaser.GameObjects.Text; private cursorObj: Phaser.GameObjects.Image | null; private moveCategoryIcon: Phaser.GameObjects.Sprite; private moveInfoOverlay : MoveInfoOverlay; protected fieldIndex: integer = 0; protected cursor2: integer = 0; constructor(scene: BattleScene) { super(scene, Mode.FIGHT); } setup() { const ui = this.getUi(); this.movesContainer = this.scene.add.container(18, -38.7); this.movesContainer.setName(FightUiHandler.MOVES_CONTAINER_NAME); ui.add(this.movesContainer); this.moveInfoContainer = this.scene.add.container(1, 0); this.moveInfoContainer.setName("move-info"); ui.add(this.moveInfoContainer); this.typeIcon = this.scene.add.sprite(this.scene.scaledCanvas.width - 57, -36, Utils.getLocalizedSpriteKey("types"), "unknown"); this.typeIcon.setVisible(false); this.moveInfoContainer.add(this.typeIcon); this.moveCategoryIcon = this.scene.add.sprite(this.scene.scaledCanvas.width - 25, -36, "categories", "physical"); this.moveCategoryIcon.setVisible(false); this.moveInfoContainer.add(this.moveCategoryIcon); this.ppLabel = addTextObject(this.scene, this.scene.scaledCanvas.width - 70, -26, "PP", TextStyle.MOVE_INFO_CONTENT); this.ppLabel.setOrigin(0.0, 0.5); this.ppLabel.setVisible(false); this.ppLabel.setText(i18next.t("fightUiHandler:pp")); this.moveInfoContainer.add(this.ppLabel); this.ppText = addTextObject(this.scene, this.scene.scaledCanvas.width - 12, -26, "--/--", TextStyle.MOVE_INFO_CONTENT); this.ppText.setOrigin(1, 0.5); this.ppText.setVisible(false); this.moveInfoContainer.add(this.ppText); this.powerLabel = addTextObject(this.scene, this.scene.scaledCanvas.width - 70, -18, "POWER", TextStyle.MOVE_INFO_CONTENT); this.powerLabel.setOrigin(0.0, 0.5); this.powerLabel.setVisible(false); this.powerLabel.setText(i18next.t("fightUiHandler:power")); this.moveInfoContainer.add(this.powerLabel); this.powerText = addTextObject(this.scene, this.scene.scaledCanvas.width - 12, -18, "---", TextStyle.MOVE_INFO_CONTENT); this.powerText.setOrigin(1, 0.5); this.powerText.setVisible(false); this.moveInfoContainer.add(this.powerText); this.accuracyLabel = addTextObject(this.scene, this.scene.scaledCanvas.width - 70, -10, "ACC", TextStyle.MOVE_INFO_CONTENT); this.accuracyLabel.setOrigin(0.0, 0.5); this.accuracyLabel.setVisible(false); this.accuracyLabel.setText(i18next.t("fightUiHandler:accuracy")); this.moveInfoContainer.add(this.accuracyLabel); this.accuracyText = addTextObject(this.scene, this.scene.scaledCanvas.width - 12, -10, "---", TextStyle.MOVE_INFO_CONTENT); this.accuracyText.setOrigin(1, 0.5); this.accuracyText.setVisible(false); this.moveInfoContainer.add(this.accuracyText); // prepare move overlay const overlayScale = 1; this.moveInfoOverlay = new MoveInfoOverlay(this.scene, { delayVisibility: true, scale: overlayScale, onSide: true, right: true, x: 0, y: -MoveInfoOverlay.getHeight(overlayScale, true), width: (this.scene.game.canvas.width / 6) + 4, hideEffectBox: true, hideBg: true }); ui.add(this.moveInfoOverlay); // register the overlay to receive toggle events this.scene.addInfoToggle(this.moveInfoOverlay); this.scene.addInfoToggle(this); } show(args: any[]): boolean { super.show(args); this.fieldIndex = args.length ? args[0] as integer : 0; const messageHandler = this.getUi().getMessageHandler(); messageHandler.bg.setVisible(false); messageHandler.commandWindow.setVisible(false); messageHandler.movesWindowContainer.setVisible(true); const pokemon = (this.scene.getCurrentPhase() as CommandPhase).getPokemon(); if (pokemon.battleSummonData.turnCount <= 1) { this.setCursor(0); } else { this.setCursor(this.getCursor()); } this.displayMoves(); this.toggleInfo(false); // in case cancel was pressed while info toggle is active this.active = true; return true; } processInput(button: Button): boolean { const ui = this.getUi(); let success = false; const cursor = this.getCursor(); if (button === Button.CANCEL || button === Button.ACTION) { if (button === Button.ACTION) { if ((this.scene.getCurrentPhase() as CommandPhase).handleCommand(Command.FIGHT, cursor, false)) { success = true; } else { ui.playError(); } } else { // Cannot back out of fight menu if skipToFightInput is enabled const { battleType, mysteryEncounter } = this.scene.currentBattle; if (battleType !== BattleType.MYSTERY_ENCOUNTER || !mysteryEncounter?.skipToFightInput) { ui.setMode(Mode.COMMAND, this.fieldIndex); success = true; } } } else { switch (button) { case Button.UP: if (cursor >= 2) { success = this.setCursor(cursor - 2); } break; case Button.DOWN: if (cursor < 2) { success = this.setCursor(cursor + 2); } break; case Button.LEFT: if (cursor % 2 === 1) { success = this.setCursor(cursor - 1); } break; case Button.RIGHT: if (cursor % 2 === 0) { success = this.setCursor(cursor + 1); } break; } } if (success) { ui.playSelect(); } return success; } toggleInfo(visible: boolean): void { if (visible) { this.movesContainer.setVisible(false); this.cursorObj?.setVisible(false); } this.scene.tweens.add({ targets: [ this.movesContainer, this.cursorObj ], duration: Utils.fixedInt(125), ease: "Sine.easeInOut", alpha: visible ? 0 : 1 }); if (!visible) { this.movesContainer.setVisible(true); this.cursorObj?.setVisible(true); } } isActive(): boolean { return this.active; } getCursor(): integer { return !this.fieldIndex ? this.cursor : this.cursor2; } setCursor(cursor: integer): boolean { const ui = this.getUi(); this.moveInfoOverlay.clear(); const changed = this.getCursor() !== cursor; if (changed) { if (!this.fieldIndex) { this.cursor = cursor; } else { this.cursor2 = cursor; } } if (!this.cursorObj) { this.cursorObj = this.scene.add.image(0, 0, "cursor"); ui.add(this.cursorObj); } const pokemon = (this.scene.getCurrentPhase() as CommandPhase).getPokemon(); const moveset = pokemon.getMoveset(); const hasMove = cursor < moveset.length; if (hasMove) { const pokemonMove = moveset[cursor]!; // TODO: is the bang correct? const moveType = pokemon.getMoveType(pokemonMove.getMove()); const textureKey = Utils.getLocalizedSpriteKey("types"); this.typeIcon.setTexture(textureKey, Type[moveType].toLowerCase()).setScale(0.8); const moveCategory = pokemonMove.getMove().category; this.moveCategoryIcon.setTexture("categories", MoveCategory[moveCategory].toLowerCase()).setScale(1.0); const power = pokemonMove.getMove().power; const accuracy = pokemonMove.getMove().accuracy; const maxPP = pokemonMove.getMovePp(); const pp = maxPP - pokemonMove.ppUsed; const ppLeftStr = Utils.padInt(pp, 2, " "); const ppMaxStr = Utils.padInt(maxPP, 2, " "); this.ppText.setText(`${ppLeftStr}/${ppMaxStr}`); this.powerText.setText(`${power >= 0 ? power : "---"}`); this.accuracyText.setText(`${accuracy >= 0 ? accuracy : "---"}`); const ppPercentLeft = pp / maxPP; //** Determines TextStyle according to percentage of PP remaining */ let ppColorStyle = TextStyle.MOVE_PP_FULL; if (ppPercentLeft > 0.25 && ppPercentLeft <= 0.5) { ppColorStyle = TextStyle.MOVE_PP_HALF_FULL; } else if (ppPercentLeft > 0 && ppPercentLeft <= 0.25) { ppColorStyle = TextStyle.MOVE_PP_NEAR_EMPTY; } else if (ppPercentLeft === 0) { ppColorStyle = TextStyle.MOVE_PP_EMPTY; } //** Changes the text color and shadow according to the determined TextStyle */ this.ppText.setColor(this.getTextColor(ppColorStyle, false)); this.ppText.setShadowColor(this.getTextColor(ppColorStyle, true)); this.moveInfoOverlay.show(pokemonMove.getMove()); pokemon.getOpponents().forEach((opponent) => { opponent.updateEffectiveness(this.getEffectivenessText(pokemon, opponent, pokemonMove)); }); } this.typeIcon.setVisible(hasMove); this.ppLabel.setVisible(hasMove); this.ppText.setVisible(hasMove); this.powerLabel.setVisible(hasMove); this.powerText.setVisible(hasMove); this.accuracyLabel.setVisible(hasMove); this.accuracyText.setVisible(hasMove); this.moveCategoryIcon.setVisible(hasMove); this.cursorObj.setPosition(13 + (cursor % 2 === 1 ? 100 : 0), -31 + (cursor >= 2 ? 15 : 0)); return changed; } /** * Gets multiplier text for a pokemon's move against a specific opponent * Returns undefined if it's a status move */ private getEffectivenessText(pokemon: Pokemon, opponent: Pokemon, pokemonMove: PokemonMove): string | undefined { const effectiveness = opponent.getMoveEffectiveness(pokemon, pokemonMove.getMove(), !opponent.battleData?.abilityRevealed); if (effectiveness === undefined) { return undefined; } return `${effectiveness}x`; } displayMoves() { const pokemon = (this.scene.getCurrentPhase() as CommandPhase).getPokemon(); const moveset = pokemon.getMoveset(); for (let moveIndex = 0; moveIndex < 4; moveIndex++) { const moveText = addTextObject(this.scene, moveIndex % 2 === 0 ? 0 : 100, moveIndex < 2 ? 0 : 16, "-", TextStyle.WINDOW); moveText.setName("text-empty-move"); if (moveIndex < moveset.length) { const pokemonMove = moveset[moveIndex]!; // TODO is the bang correct? moveText.setText(pokemonMove.getName()); moveText.setName(pokemonMove.getName()); moveText.setColor(this.getMoveColor(pokemon, pokemonMove) ?? moveText.style.color); } this.movesContainer.add(moveText); } } /** * Returns a specific move's color based on its type effectiveness against opponents * If there are multiple opponents, the highest effectiveness' color is returned * @returns A color or undefined if the default color should be used */ private getMoveColor(pokemon: Pokemon, pokemonMove: PokemonMove): string | undefined { if (!this.scene.typeHints) { return undefined; } const opponents = pokemon.getOpponents(); if (opponents.length <= 0) { return undefined; } const moveColors = opponents .map((opponent) => opponent.getMoveEffectiveness(pokemon, pokemonMove.getMove(), !opponent.battleData.abilityRevealed)) .sort((a, b) => b - a) .map((effectiveness) => getTypeDamageMultiplierColor(effectiveness ?? 0, "offense")); return moveColors[0]; } clear() { super.clear(); const messageHandler = this.getUi().getMessageHandler(); this.clearMoves(); this.typeIcon.setVisible(false); this.ppLabel.setVisible(false); this.ppText.setVisible(false); this.powerLabel.setVisible(false); this.powerText.setVisible(false); this.accuracyLabel.setVisible(false); this.accuracyText.setVisible(false); this.moveCategoryIcon.setVisible(false); this.moveInfoOverlay.clear(); messageHandler.bg.setVisible(true); this.eraseCursor(); this.active = false; } clearMoves() { this.movesContainer.removeAll(true); const opponents = (this.scene.getCurrentPhase() as CommandPhase).getPokemon().getOpponents(); opponents.forEach((opponent) => { opponent.updateEffectiveness(undefined); }); } eraseCursor() { if (this.cursorObj) { this.cursorObj.destroy(); } this.cursorObj = null; } }
412
0.931182
1
0.931182
game-dev
MEDIA
0.856149
game-dev
0.994252
1
0.994252
HbmMods/Hbm-s-Nuclear-Tech-GIT
10,977
src/main/java/com/hbm/inventory/recipes/PedestalRecipes.java
package com.hbm.inventory.recipes; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.hbm.inventory.OreDictManager.*; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonWriter; import com.hbm.blocks.ModBlocks; import com.hbm.inventory.RecipesCommon.AStack; import com.hbm.inventory.RecipesCommon.ComparableStack; import com.hbm.inventory.RecipesCommon.OreDictStack; import com.hbm.inventory.recipes.loader.SerializableRecipe; import com.hbm.items.ItemEnums.EnumChunkType; import com.hbm.items.ItemEnums.EnumSecretType; import com.hbm.items.food.ItemConserve.EnumFoodType; import com.hbm.items.ModItems; import com.hbm.items.weapon.sedna.factory.GunFactory.EnumAmmo; import com.hbm.items.weapon.sedna.factory.GunFactory.EnumAmmoSecret; import com.hbm.items.weapon.sedna.factory.GunFactory.EnumModSpecial; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; public class PedestalRecipes extends SerializableRecipe { public static List<PedestalRecipe> recipes = new ArrayList(); public static ArrayList<PedestalRecipe>[] recipeSets = new ArrayList[2]; static { for(int i = 0; i < recipeSets.length; i++) recipeSets[i] = new ArrayList(); } @Override public void registerDefaults() { register(new PedestalRecipe(new ItemStack(ModItems.gun_light_revolver_dani), null, new OreDictStack(PB.plate()), null, new OreDictStack(GOLD.plate()), new ComparableStack(ModItems.gun_light_revolver), new OreDictStack(GOLD.plate()), null, new OreDictStack(PB.plate()), null)); register(new PedestalRecipe(new ItemStack(ModItems.gun_maresleg_broken), new ComparableStack(ModBlocks.barbed_wire), new OreDictStack(WEAPONSTEEL.plate()), new ComparableStack(ModBlocks.barbed_wire), new OreDictStack(WEAPONSTEEL.plate()), new ComparableStack(ModItems.gun_maresleg), new OreDictStack(WEAPONSTEEL.plate()), new ComparableStack(ModBlocks.barbed_wire), new OreDictStack(WEAPONSTEEL.plate()), new ComparableStack(ModBlocks.barbed_wire))); register(new PedestalRecipe(new ItemStack(ModItems.gun_heavy_revolver_lilmac), null, new ComparableStack(ModItems.weapon_mod_special, 1, EnumModSpecial.SCOPE), null, new ComparableStack(ModItems.powder_magic), new ComparableStack(ModItems.gun_heavy_revolver), new OreDictStack(WEAPONSTEEL.plate()), null, new OreDictStack(BONE.grip()), new ComparableStack(Items.apple, 3))); register(new PedestalRecipe(new ItemStack(ModItems.gun_heavy_revolver_protege), new ComparableStack(ModBlocks.chain, 16), new OreDictStack(CINNABAR.gem()), new ComparableStack(ModBlocks.chain, 16), new ComparableStack(ModItems.scrap_nuclear), new ComparableStack(ModItems.gun_heavy_revolver), new ComparableStack(ModItems.scrap_nuclear), new ComparableStack(ModBlocks.chain, 16), new OreDictStack(CINNABAR.gem()), new ComparableStack(ModBlocks.chain, 16))); register(new PedestalRecipe(new ItemStack(ModItems.gun_flamer_daybreaker), new OreDictStack(GOLD.plateCast()), new ComparableStack(ModItems.canned_conserve, 1, EnumFoodType.JIZZ), new OreDictStack(GOLD.plateCast()), new OreDictStack(P_WHITE.ingot()), new ComparableStack(ModItems.gun_flamer), new OreDictStack(P_WHITE.ingot()), new OreDictStack(GOLD.plateCast()), new ComparableStack(ModItems.stick_dynamite), new OreDictStack(GOLD.plateCast())) .extra(PedestalExtraCondition.SUN)); register(new PedestalRecipe(new ItemStack(ModItems.gun_autoshotgun_sexy), new ComparableStack(ModItems.bolt_spike, 16), new ComparableStack(ModItems.wild_p), new ComparableStack(ModItems.bolt_spike, 16), new ComparableStack(ModItems.card_qos), new ComparableStack(ModItems.gun_autoshotgun), new ComparableStack(ModItems.card_aos), new ComparableStack(ModItems.bolt_spike, 16), new OreDictStack(STAR.ingot(), 16), new ComparableStack(ModItems.bolt_spike, 16))); register(new PedestalRecipe(new ItemStack(ModItems.gun_minigun_lacunae), null, new ComparableStack(ModItems.powder_magic, 4), null, new ComparableStack(ModItems.item_secret, 4, EnumSecretType.SELENIUM_STEEL), new ComparableStack(ModItems.gun_minigun), new ComparableStack(ModItems.item_secret, 4, EnumSecretType.SELENIUM_STEEL), null, new ComparableStack(ModItems.powder_magic, 4), null) .extra(PedestalExtraCondition.FULL_MOON)); register(new PedestalRecipe(new ItemStack(ModItems.gun_laser_pistol_morning_glory), null, new ComparableStack(ModItems.morning_glory, 1), null, new ComparableStack(ModItems.item_secret, 2, EnumSecretType.SELENIUM_STEEL), new ComparableStack(ModItems.gun_laser_pistol), new ComparableStack(ModItems.item_secret, 2, EnumSecretType.SELENIUM_STEEL), null, new OreDictStack(EMERALD.gem(), 16), null)); register(new PedestalRecipe(new ItemStack(ModItems.gun_folly), new ComparableStack(ModItems.item_secret, 4, EnumSecretType.FOLLY), new ComparableStack(ModItems.item_secret, 2, EnumSecretType.CONTROLLER), new ComparableStack(ModItems.item_secret, 4, EnumSecretType.FOLLY), new OreDictStack(BSCCO.ingot(), 16), new OreDictStack(STAR.block(), 64), new OreDictStack(BSCCO.ingot(), 16), new ComparableStack(ModItems.item_secret, 4, EnumSecretType.FOLLY), new ComparableStack(ModItems.item_secret, 2, EnumSecretType.CONTROLLER), new ComparableStack(ModItems.item_secret, 4, EnumSecretType.FOLLY)) .extra(PedestalExtraCondition.FULL_MOON).set(1)); register(new PedestalRecipe(new ItemStack(ModItems.gun_aberrator), null, new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), null, new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new OreDictStack(BIGMT.mechanism(), 4), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), null, new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), null).set(1)); register(new PedestalRecipe(new ItemStack(ModItems.gun_aberrator_eott), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new OreDictStack(BIGMT.mechanism(), 16), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR)) .extra(PedestalExtraCondition.GOOD_KARMA).set(1)); register(new PedestalRecipe(new ItemStack(ModItems.ammo_secret, 1, EnumAmmoSecret.FOLLY_SM.ordinal()), new OreDictStack(STAR.ingot(), 1), new ComparableStack(ModItems.powder_magic), new OreDictStack(STAR.ingot(), 1), new ComparableStack(ModItems.powder_magic), new ComparableStack(ModItems.chunk_ore, 1, EnumChunkType.MOONSTONE), new ComparableStack(ModItems.powder_magic), new OreDictStack(STAR.ingot(), 1), new ComparableStack(ModItems.powder_magic), new OreDictStack(STAR.ingot(), 1)) .extra(PedestalExtraCondition.FULL_MOON).set(1)); register(new PedestalRecipe(new ItemStack(ModItems.ammo_secret, 1, EnumAmmoSecret.FOLLY_NUKE.ordinal()), new OreDictStack(STAR.ingot(), 1), new ComparableStack(ModItems.powder_magic), new OreDictStack(STAR.ingot(), 1), new ComparableStack(ModItems.powder_magic), new ComparableStack(ModItems.ammo_standard, 4, EnumAmmo.NUKE_HIGH), new ComparableStack(ModItems.powder_magic), new OreDictStack(STAR.ingot(), 1), new ComparableStack(ModItems.powder_magic), new OreDictStack(STAR.ingot(), 1)) .extra(PedestalExtraCondition.FULL_MOON).set(1)); register(new PedestalRecipe(new ItemStack(ModItems.ammo_secret, 5, EnumAmmoSecret.P35_800.ordinal()), null, null, null, null, new ComparableStack(ModItems.item_secret, 1, EnumSecretType.ABERRATOR), null, null, null, null).set(1)); register(new PedestalRecipe(new ItemStack(ModItems.ammo_secret, 10, EnumAmmoSecret.P35_800_BL.ordinal()), null, null, null, null, new ComparableStack(ModItems.item_secret, 3, EnumSecretType.ABERRATOR), null, null, null, null).set(1)); } public static void register(PedestalRecipe recipe) { recipes.add(recipe); int set = Math.abs(recipe.recipeSet) % recipeSets.length; recipeSets[set].add(recipe); } @Override public String getFileName() { return "hbmPedestal.json"; } @Override public Object getRecipeObject() { return recipes; } @Override public void deleteRecipes() { recipes.clear(); for(int i = 0; i < recipeSets.length; i++) recipeSets[i].clear(); } @Override public void readRecipe(JsonElement recipe) { JsonObject obj = (JsonObject) recipe; ItemStack output = this.readItemStack(obj.get("output").getAsJsonArray()); JsonArray inputArray = obj.get("input").getAsJsonArray(); AStack[] input = new AStack[9]; for(int i = 0; i < 9; i++) { JsonElement element = inputArray.get(i); if(element.isJsonNull()) { input[i] = null; } else { input[i] = this.readAStack(element.getAsJsonArray()); } } PedestalRecipe rec = new PedestalRecipe(output, input); if(obj.has("extra")) { rec.extra = PedestalExtraCondition.valueOf(obj.get("extra").getAsString()); } if(obj.has("set")) { rec.recipeSet = obj.get("set").getAsInt(); } this.recipes.add(rec); } @Override public void writeRecipe(Object recipe, JsonWriter writer) throws IOException { PedestalRecipe rec = (PedestalRecipe) recipe; writer.name("output"); this.writeItemStack(rec.output, writer); writer.name("input").beginArray(); for(int i = 0; i < rec.input.length; i++) { if(rec.input[i] == null) { writer.nullValue(); } else { this.writeAStack(rec.input[i], writer); } } writer.endArray(); writer.name("extra").value(rec.extra.name()); if(rec.recipeSet != 0) writer.name("set").value(rec.recipeSet); } public static enum PedestalExtraCondition { NONE, FULL_MOON, NEW_MOON, SUN, GOOD_KARMA, BAD_KARMA } public static class PedestalRecipe { public ItemStack output; public AStack[] input; public int recipeSet = 0; public PedestalExtraCondition extra = PedestalExtraCondition.NONE; public PedestalRecipe(ItemStack output, AStack... input) { this.output = output; this.input = input; } public PedestalRecipe extra(PedestalExtraCondition extra) { this.extra = extra; return this; } public PedestalRecipe set(int set) { this.recipeSet = set; return this; } } }
412
0.751938
1
0.751938
game-dev
MEDIA
0.972673
game-dev
0.745849
1
0.745849
kevin-montrose/LinqAF
1,770
LinqAF/Repeat.cs
namespace LinqAF { [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Auto)] public struct RepeatEnumerator<TItem>: IStructEnumerator<TItem> { byte Sigil; TItem Item; int Count; int Index; public TItem Current { get; private set; } internal RepeatEnumerator(byte sigil, TItem item, int count) { Sigil = sigil; Item = item; Count = count; Index = 0; Current = default(TItem); } public bool IsDefaultValue() { return Sigil == default(byte); } public bool MoveNext() { if(Index < Count) { Current = Item; Index++; return true; } return false; } public void Reset() { Index = 0; Current = default(TItem); } public void Dispose() { Item = default(TItem); } } [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Auto)] public partial struct RepeatEnumerable<TItem>: IStructEnumerable<TItem, RepeatEnumerator<TItem>> { byte Sigil; internal TItem Item; internal int InnerCount; internal RepeatEnumerable(byte sigil, TItem item, int count) { Sigil = sigil; Item = item; InnerCount = count; } public bool IsDefaultValue() { return Sigil == default(byte); } public RepeatEnumerator<TItem> GetEnumerator() => new RepeatEnumerator<TItem>(Sigil, Item, InnerCount); } }
412
0.54837
1
0.54837
game-dev
MEDIA
0.545386
game-dev
0.861301
1
0.861301
SkyblockAPI/SkyblockAPI
9,204
src/common/main/kotlin/tech/thatgravyboat/skyblockapi/impl/debug/DebugCommands.kt
package tech.thatgravyboat.skyblockapi.impl.debug import com.google.gson.JsonArray import com.mojang.brigadier.arguments.StringArgumentType import me.owdding.ktmodules.Module import net.minecraft.core.registries.Registries import net.minecraft.network.chat.ClickEvent import net.minecraft.network.chat.Component import net.minecraft.network.chat.ComponentSerialization import net.minecraft.network.chat.HoverEvent import net.minecraft.world.item.ItemStack import net.minecraft.world.level.biome.Biome import tech.thatgravyboat.skyblockapi.api.events.base.Subscription import tech.thatgravyboat.skyblockapi.api.events.chat.ActionBarReceivedEvent import tech.thatgravyboat.skyblockapi.api.events.info.TabListHeaderFooterChangeEvent import tech.thatgravyboat.skyblockapi.api.events.misc.RegisterCommandsEvent import tech.thatgravyboat.skyblockapi.api.remote.hypixel.itemdata.ItemData import tech.thatgravyboat.skyblockapi.api.remote.hypixel.pricing.Pricing import tech.thatgravyboat.skyblockapi.helpers.McClient import tech.thatgravyboat.skyblockapi.helpers.McPlayer import tech.thatgravyboat.skyblockapi.utils.extentions.toFormattedString import tech.thatgravyboat.skyblockapi.utils.json.Json.toJson import tech.thatgravyboat.skyblockapi.utils.json.Json.toPrettyString import tech.thatgravyboat.skyblockapi.utils.mc.displayName import tech.thatgravyboat.skyblockapi.utils.text.Text import tech.thatgravyboat.skyblockapi.utils.text.Text.send import tech.thatgravyboat.skyblockapi.utils.text.TextColor import tech.thatgravyboat.skyblockapi.utils.text.TextProperties.stripped import tech.thatgravyboat.skyblockapi.utils.text.TextStyle.color import tech.thatgravyboat.skyblockapi.utils.text.TextStyle.style import kotlin.io.path.createDirectories @Module object DebugCommands { private var actionbar: String = "" private var tabListFooter: Component = Component.empty() private var tabListHeader: Component = Component.empty() private fun copyMessage(title: String) { Text.of("[SkyBlockAPI] Copied $title to clipboard.") { this.color = TextColor.YELLOW }.send() } @Subscription(receiveCancelled = true) fun onActionBar(event: ActionBarReceivedEvent.Pre) { actionbar = event.coloredText } @Subscription(priority = Int.MIN_VALUE) fun onHeaderFooter(event: TabListHeaderFooterChangeEvent) { tabListFooter = event.newFooter tabListHeader = event.newHeader } @Subscription fun onCommandsRegistration(event: RegisterCommandsEvent) { event.register("sbapi") { then("price id", StringArgumentType.greedyString()) { callback { val id = this.getArgument("id", String::class.java) val price = Pricing.getPrice(id) Text.of("[SkyBlockAPI] Price of $id is ${price.toFormattedString()}.") { this.color = TextColor.YELLOW }.send() } } then("itemdata id", StringArgumentType.greedyString()) { callback { val id = this.getArgument("id", String::class.java) val itemData = ItemData.getItemData(id) ?: run { Text.debug("ItemData for $id not found.") { this.color = TextColor.RED }.send() return@callback } McClient.clipboard = itemData.toString() Text.debug("ItemData of $id copied to clipboard.").send() } } then("copy") { then("scoreboard") { then("raw") { callback { copyMessage("raw scoreboard") McClient.clipboard = McClient.scoreboard.joinToString("\n") { it.toJson(ComponentSerialization.CODEC).toPrettyString() } } } callback { copyMessage("scoreboard") McClient.clipboard = McClient.scoreboard.joinToString("\n") { it.stripped } } } then("tablist") { then("footer") { then("raw") { callback { copyMessage("raw tablist footer") McClient.clipboard = tabListFooter.toJson(ComponentSerialization.CODEC).toPrettyString() } } callback { copyMessage("tablist footer") McClient.clipboard = tabListFooter.stripped } } then("header") { then("raw") { callback { copyMessage("raw tablist header") McClient.clipboard = tabListHeader.toJson(ComponentSerialization.CODEC).toPrettyString() } } callback { copyMessage("tablist header") McClient.clipboard = tabListHeader.stripped } } then("raw") { callback { copyMessage("raw tablist") McClient.clipboard = McClient.tablist.joinToString("\n") { it.displayName.toJson(ComponentSerialization.CODEC).toPrettyString() } } } callback { copyMessage("tablist") McClient.clipboard = McClient.tablist.joinToString("\n") { it.displayName.stripped } } } then("item") { callback { copyMessage("item") McClient.clipboard = McPlayer.heldItem.toJson(ItemStack.CODEC).toPrettyString() } } then("actionbar") { callback { copyMessage("actionbar") McClient.clipboard = actionbar } } } then("folder") { val gameDir = McClient.self.gameDirectory.toPath() listOf("config", "mods", "logs").forEach { thenCallback(it) { McClient.openUri(gameDir.resolve(it).toUri()) } } thenCallback("chest_dumps") { McClient.openUri(gameDir.resolve("config/skyblockapi/chest_dumps").toUri()) } } then("save") { thenCallback("registries") { val outputs = McClient.config.resolve(".skyblock-debug").resolve("registries") outputs.createDirectories() val connection = McClient.connection ?: return@thenCallback val registries = connection.registryAccess().registries() registries.forEach { registry -> val location = registry.key().location() val path = outputs.resolve("${location.namespace}-${location.path.replace("/", "-")}.json") val data = JsonArray() registry.value().keySet().forEach { data.add(it.toString()) } path.toFile().writeText(data.toPrettyString()) } } thenCallback("biomes") { val outputs = McClient.config.resolve(".skyblock-debug").resolve("biomes") outputs.createDirectories() val connection = McClient.connection ?: return@thenCallback val biomes = connection.registryAccess().lookupOrThrow(Registries.BIOME).entrySet() biomes.forEach { (key, biome) -> val location = key.location() val path = outputs.resolve(location.namespace) .resolve("worldgen") .resolve("biome") .resolve("${location.path}.json") path.parent.createDirectories() path.toFile().writeText(biome.toJson(Biome.DIRECT_CODEC).toPrettyString()) } Text.debug("Saved ${biomes.size} biomes. Click to open folder.") { this.style { this.withClickEvent(ClickEvent.OpenFile(outputs)) this.withHoverEvent(HoverEvent.ShowText(Text.of("Click to open the folder."))) } }.send() } } } } }
412
0.827738
1
0.827738
game-dev
MEDIA
0.327763
game-dev
0.868241
1
0.868241
HawkAnticheat/Hawk
2,656
src/me/islandscout/hawk/check/interaction/terrain/WrongBlockFace.java
/* * This file is part of Hawk Anticheat. * Copyright (C) 2018 Hawk Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package me.islandscout.hawk.check.interaction.terrain; import me.islandscout.hawk.HawkPlayer; import me.islandscout.hawk.check.BlockInteractionCheck; import me.islandscout.hawk.event.InteractWorldEvent; import me.islandscout.hawk.util.AABB; import me.islandscout.hawk.util.MathPlus; import me.islandscout.hawk.util.ServerUtils; import me.islandscout.hawk.wrap.block.WrappedBlock; import org.bukkit.block.Block; import org.bukkit.util.Vector; import org.bukkit.entity.Player; /** This check prevents players from interacting on * unavailable locations on blocks. Players must be * looking at the face of the block they want to interact * with. */ public class WrongBlockFace extends BlockInteractionCheck { public WrongBlockFace() { super("wrongblockface", true, 0, 10, 0.99, 5000, "%player% failed wrongblockface; interacted on invalid block face, VL: %vl%", null); } @Override protected void check(InteractWorldEvent e) { HawkPlayer pp = e.getHawkPlayer(); Block b = ServerUtils.getBlockAsync(e.getTargetedBlockLocation()); AABB hitbox; if(b != null) { hitbox = WrappedBlock.getWrappedBlock(b, pp.getClientVersion()).getHitBox(); } else { hitbox = new AABB(new Vector(), new Vector()); } Vector headPos; if(pp.isInVehicle()) { Player p = e.getPlayer(); headPos = hawk.getLagCompensator().getHistoryLocation(ServerUtils.getPing(p), p).toVector(); headPos.setY(headPos.getY() + p.getEyeHeight()); } else { headPos = pp.getHeadPosition(); } if(e.getTargetedBlockFaceNormal().dot(MathPlus.getDirection(pp.getYaw(), pp.getPitch())) >= 0 && !hitbox.containsPoint(headPos)) { punishAndTryCancelAndBlockRespawn(pp, e); } else { reward(pp); } } }
412
0.719112
1
0.719112
game-dev
MEDIA
0.930741
game-dev
0.618112
1
0.618112
opentibiabr/canary
3,140
data-otservbr-global/scripts/quests/wrath_of_the_emperor/actions_mission01_lights.lua
local positions = { { x = 33370, y = 31067, z = 9 }, { x = 33359, y = 31070, z = 9 }, { x = 33349, y = 31075, z = 8 }, { x = 33351, y = 31069, z = 9 }, } local function transformLamp(position, itemId, transformId) local lampItem = Tile(position):getItemById(itemId) if lampItem then lampItem:transform(transformId) end end local wrathEmperorMiss1Light = Action() function wrathEmperorMiss1Light.onUse(player, item, fromPosition, target, toPosition, isHotkey) if fromPosition == Position(positions[1]) then if Game.getStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light01) ~= 1 then Game.setStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light01, 1) addEvent(Game.setStorageValue, 20 * 1000, Storage.Quest.U8_6.WrathOfTheEmperor.Light01, 0) local pos = { Position(33369, 31075, 8), Position(33372, 31075, 8), Position(33375, 31075, 8), } for i = 1, #pos do transformLamp(pos[i], 10491, 10479) addEvent(transformLamp, 20 * 1000, pos[i], 10479, 10491) end end elseif fromPosition == Position(positions[2]) then if Game.getStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light02) ~= 1 then Game.setStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light02, 1) addEvent(Game.setStorageValue, 20 * 1000, Storage.Quest.U8_6.WrathOfTheEmperor.Light02, 0) local pos = { Position(33357, 31077, 8), Position(33360, 31079, 8), } for i = 1, #pos do transformLamp(pos[i], 10493, 10478) addEvent(transformLamp, 20 * 1000, pos[i], 10478, 10493) end end elseif fromPosition == Position(positions[3]) then if Game.getStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light04) ~= 1 then Game.setStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light04, 1) addEvent(Game.setStorageValue, 20 * 1000, Storage.Quest.U8_6.WrathOfTheEmperor.Light04, 0) local wallItem, pos for i = 1, 4 do pos = Position(33355, 31067 + i, 9) if i == 1 or 4 then wallItem = Tile(pos):getItemById(8348) if wallItem then wallItem:transform(8290) addEvent(Game.createItem, 20 * 1000, 8348, 1, pos) end end if i == 2 then wallItem = Tile(pos):getItemById(8291) if wallItem then wallItem:transform(8290) addEvent(Game.createItem, 20 * 1000, 8291, 1, pos) end end if i == 3 then wallItem = Tile(pos):getItemById(8293) if wallItem then wallItem:transform(8290) addEvent(Game.createItem, 20 * 1000, 8293, 1, pos) end end end end elseif fromPosition == Position(positions[4]) then if Game.getStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light03) ~= 1 then Game.setStorageValue(Storage.Quest.U8_6.WrathOfTheEmperor.Light03, 1) addEvent(Game.setStorageValue, 20 * 1000, Storage.Quest.U8_6.WrathOfTheEmperor.Light03, 0) local pos = Position(33346, 31074, 8) transformLamp(pos, 10493, 10478) addEvent(transformLamp, 20 * 1000, pos, 10478, 10493) end end return item:transform(item.itemid == 9125 and 9126 or 9125) end for index, value in pairs(positions) do wrathEmperorMiss1Light:position(value) end wrathEmperorMiss1Light:register()
412
0.88731
1
0.88731
game-dev
MEDIA
0.983825
game-dev
0.957263
1
0.957263
Dimbreath/ArknightsData
24,581
en-US/gamedata/[uc]lua/feature/activity/gridgacha/gridgachamaindlg.lua
local luaUtils = CS.Torappu.Lua.Util; GridGachaMainDlg = Class("GridGachaMainDlg", DlgBase); local GridGachaPackageView = require("Feature/Activity/GridGacha/GridGachaPackageView"); local GridGachaViewModel = require("Feature/Activity/GridGacha/GridGachaViewModel"); local GridGachaRuleView = require("Feature/Activity/GridGacha/GridGachaRuleView"); local GridGachaLineView = require("Feature/Activity/GridGacha/GridGachaLineView"); local DFT_POOL_COUNT = 100; local DFT_POOL_VERTICAL_COUNT = 10; local DFT_POOL_HORIZON_COUNT = 10; local LINE_POS = {0, 53, 106, 159, 212, 264, 317, 370, 423, 476}; local LINE_RANDOM_FLASH_TIME = 0.16; local LINE_FLASH_TIME = 0.4; local RED_LINE_LENGTH = 554; local BLACK_LINE_LENGTH = 528; local SOUND_SIGNAL_SCAN = "ON_GRIDGACHA_SCAN"; local SOUND_SIGNAL_BLINK = "ON_GRIDGACHA_BLINK"; local SOUND_SIGNAL_LASER = "ON_GRIDGACHA_LASER"; local SOUND_SIGNAL_LOCATE = "ON_GRIDGACHA_LOCATE"; local SOUND_SIGNAL_POPUP = "ON_MSGBOX_POPUP"; local SOUND_SIGNAL_REWARD = "ON_BATTLE_END_ITEM_POPUP"; local SOUND_SIGNAL_TICK = "ON_NUMBER_TICK"; local function _SetActive(gameObj, isActive); luaUtils.SetActiveIfNecessary(gameObj, isActive); end local function _CreateSwitch(canvasGroup) local ret = CS.Torappu.UI.FadeSwitchTween(canvasGroup, 0.5) ret:Reset(false) return ret end local function CalculatePosition(row, column) return 10 * row + column + 1; end function GridGachaMainDlg:OnInit() self.m_gridGachaText = {} local actId = self.m_parent:GetData("actId"); self:_InitFromGameData(actId); self.m_viewCache = {} self.m_viewModel = GridGachaViewModel.new(); self.m_viewMap = {} self.m_horizonLineView = {} self.m_verticalLineView = {} self.m_confirmSwitch = _CreateSwitch(self._alphaConfirm); self.m_finishedSwitch = _CreateSwitch(self._alphaFinished); self.m_processSwitch = _CreateSwitch(self._alphaProcess); CS.Torappu.Lua.LuaUIUtil.BindBackPressToButton(self._btnClose); self:AddButtonClickListener(self._btnClose, self.EventOnCloseClick); self:AddButtonClickListener(self._btnConfirm, self.EventOnConfirmClick); self.m_viewModel:InitData(actId, DFT_POOL_COUNT); self:_RefreshContent(); end function GridGachaMainDlg:_RefreshContent() local viewModel = self.m_viewModel if viewModel == nil then return end self:_RefreshBasicPacks() self:_RefreshTextsAndButtons() end function GridGachaMainDlg:CalPosition(index) local x = math.ceil(index / 10); local y = index % 10; if y == 0 then y = 10; end return {x, y}; end function GridGachaMainDlg:_RefreshBasicPacks() local viewMap = self.m_viewMap; local models = self.m_viewModel.packageModels; for i = 1, DFT_POOL_COUNT do local model = models[i]; if model ~= nil and (model.isGrandAward or model.isReward) then self:_CreateOrGetViewFromTable(viewMap, i, self._package, self._layout); end end for i = 1, DFT_POOL_HORIZON_COUNT do local view = self.m_horizonLineView[i]; if view == nil then view = self:CreateWidgetByPrefab(GridGachaLineView, self._gachaLine, self._horizonLineLayout); view:OnInit(); view._selfRect.localPosition = {x = LINE_POS[i], y = 0, z = 0 }; table.insert(self.m_horizonLineView, i, view); end view:Render(false); end for i = 1, DFT_POOL_VERTICAL_COUNT do local view = self.m_verticalLineView[i]; if view == nil then view = self:CreateWidgetByPrefab(GridGachaLineView, self._gachaLine, self._verticalLineLayout); view:OnInit(); view._selfRect.localEulerAngles = {x = 0, y = 0, z = -90}; view._selfRect.anchoredPosition = {x = 19, y = -LINE_POS[i], z = 0 }; table.insert(self.m_verticalLineView, i, view); end view:Render(false); end if self.m_viewModel:HasGacha() then local position = self:CalPosition(self.m_viewModel.rewardModel); self.m_horizonLineView[position[2]]:Render(true); self.m_verticalLineView[position[1]]:Render(true); end for index, view in pairs(viewMap) do self:_RenderPackView(view, index); end self._panelSkip:SetActive(not self.m_viewModel.m_isFirstDay); self._skipCheckBox.isOn = (CS.Torappu.UI.UILocalCache.instance.GridGachaSkipAnimation == 1); end function GridGachaMainDlg:_InitSound(signal) CS.Torappu.TorappuAudio.PlayUI(signal); end function GridGachaMainDlg:_CreateOrGetViewFromTable(viewMap, index, prefab, container) local view = viewMap[index] if view == nil then view = self:CreateWidgetByPrefab(GridGachaPackageView, prefab, container); view:InitView(self, index); viewMap[index] = view; end return view; end function GridGachaMainDlg:_RenderPackView(packView, index) local packModel = self.m_viewModel.packageModels[index]; packView:Render(packModel); end function GridGachaMainDlg:_RefreshTextsAndButtons() local viewModel = self.m_viewModel; local isFinish = viewModel.m_hasGacha; self.m_processSwitch:Reset(false); self.m_confirmSwitch:Reset(not isFinish); self.m_finishedSwitch:Reset(isFinish); self._textEndTime.text = viewModel.endTimeDesc; if self.m_viewModel:HasGacha() then self._imgFinish1.sizeDelta = {x = 192, y = 10}; self._textGroup1.sizeDelta = {x = 200, y = 52}; self._textGroup2.sizeDelta = {x = 200, y = 52}; self._textGroup3.sizeDelta = {x = 200, y = 52}; self._textGroup4.sizeDelta = {x = 200, y = 34}; self._imgTri1.color = {r = 1, g = 1, b = 1, a = 1}; self._rectTri1.anchoredPosition = { x = -72, y = 95, z = 0}; self._imgTri2.color = {r = 1, g = 1, b = 1, a = 1}; self._rectTri2.anchoredPosition = { x = -72, y = -151, z = 0}; self._maskBanner.sizeDelta = {x = 0, y = 650}; self._defaultText.color = {r = 0.26, g = 0.26, b = 0.26, a = 0}; self._gachaText.color = {r = 0.75, g = 0.29, b = 0.25, a = 1}; self._gachaText.text = self.m_gridGachaText[self.m_viewModel.openedType + 1]; self._panelDiamond.sizeDelta = {x = 146, y = 45}; self._redDiamondText.text = 0; self._redDiamondText.color = {r = 0.75, g = 0.29, b = 0.25, a = 0}; self._blackDiamondText.color = {r = 0.06, g = 0.06, b = 0.06, a = 0.51}; self._blackDiamondText.text = self.m_viewModel.rewards; self._imgScanLine.anchoredPosition = {x = 0, y = 0}; else self._imgFinish1.sizeDelta = {x = 0, y = 10}; self._textGroup1.sizeDelta = {x = 0, y = 52}; self._textGroup2.sizeDelta = {x = 0, y = 52}; self._textGroup3.sizeDelta = {x = 0, y = 52}; self._textGroup4.sizeDelta = {x = 0, y = 34}; self._imgTri1.color = {r = 1, g = 1, b = 1, a = 0}; self._rectTri1.anchoredPosition = { x = -72, y = 110, z = 0}; self._imgTri2.color = {r = 1, g = 1, b = 1, a = 0}; self._rectTri2.anchoredPosition = { x = -72, y = -136, z = 0}; self._maskBanner.sizeDelta = {x = 0, y = 650}; self._defaultText.color = {r = 0.26, g = 0.26, b = 0.26, a = 1}; self._gachaText.color = {r = 0.75, g = 0.29, b = 0.25, a = 0}; self._defaultText.text = CS.Torappu.StringRes.GRID_GACHA_NO_REWARD; self._panelDiamond.sizeDelta = {x = 146, y = 45}; self._redDiamondText.text = ""; self._redDiamondText.color = {r = 0.75, g = 0.29, b = 0.25, a = 0}; self._blackDiamondText.color = {r = 0.06, g = 0.06, b = 0.06, a = 0.51}; self._blackDiamondText.text = "0"; self._imgScanLine.anchoredPosition = {x = 0, y = 0}; end end function GridGachaMainDlg:_InitFromGameData(actId) self.m_actId = actId; self.m_poolCount = DFT_POOL_COUNT; local dynActs = CS.Torappu.ActivityDB.data.dynActs; if actId == nil or dynActs == nil then return; end local suc, jObject = dynActs:TryGetValue(actId); if not suc then luaUtils.LogError("Activity not found in dynActs : "..actId); return; end local data = luaUtils.ConvertJObjectToLuaTable(jObject); for i = 1, #data.rule do self:_CreateRuleText(self._ruleText, self._ruleScrollView, data.rule[i]); end table.insert(self.m_gridGachaText, data.name3); table.insert(self.m_gridGachaText, data.name2); table.insert(self.m_gridGachaText, data.name1); end function GridGachaMainDlg:_CreateRuleText(prefab, container, text) if text == nil then return end local view = self:CreateWidgetByPrefab(GridGachaRuleView, prefab, container); view:Render(text); end function GridGachaMainDlg:EventOnCloseClick() local viewModel = self.m_viewModel; if viewModel ~= nil and viewModel:IsGacha() then return; end if self._skipCheckBox.isOn then CS.Torappu.UI.UILocalCache.instance.GridGachaSkipAnimation = 1; else CS.Torappu.UI.UILocalCache.instance.GridGachaSkipAnimation = 0; end self:Close(); end function GridGachaMainDlg:EventOnConfirmClick() local viewModel = self.m_viewModel if viewModel == nil or viewModel:HasGacha() then return; end if CS.Torappu.UI.UISyncDataUtil.instance:CheckCrossDaysAndResync() then return; end if self._skipCheckBox.isOn then CS.Torappu.UI.UILocalCache.instance.GridGachaSkipAnimation = 1; else CS.Torappu.UI.UILocalCache.instance.GridGachaSkipAnimation = 0; end if (not self.m_viewModel.m_isFirstDay) and self._skipCheckBox.isOn then UISender.me:SendRequest(GridGachaServerCode.GACHA, { activityId = self.m_actId; }, { onProceed = Event.Create(self, self._OnGetRewardResponseNoAnime), hideMask = true } ); else UISender.me:SendRequest(GridGachaServerCode.GACHA, { activityId = self.m_actId; }, { onProceed = Event.Create(self, self._OnGetRewardResponse), hideMask = true } ); end end function GridGachaMainDlg:_OnGetRewardResponse(response) if self.m_viewModel == nil then return end local openedPosition = response.openedPosition; local addGrandPosition = response.addGrandPosition; local horizonLine = self.m_horizonLineView[openedPosition[2] + 1]; local verticalLine = self.m_verticalLineView[openedPosition[1] + 1]; local openedType = response.openedType; local reward = response.rewards[1]["count"]; local pack = nil; local scanShineImage = nil; self.m_viewModel:InitData(self.m_actId, self.m_poolCount); self.m_viewModel:MarkGachaStart(); self.m_confirmSwitch.isShow = false; self.m_processSwitch.isShow = true; self:Interval(0.05, 1, function() self._imgScanLine:DOAnchorPos({x = 584, y = 0}, 0.8); self:_InitSound(SOUND_SIGNAL_SCAN); end); if openedType ~= 2 then self:_CreateOrGetViewFromTable(self.m_viewMap, CalculatePosition(openedPosition[1], openedPosition[2]), self._package, self._layout); end pack = self.m_viewMap[CalculatePosition(openedPosition[1], openedPosition[2])]; if openedType ~= 2 then scanShineImage = pack._panelScanShine; else scanShineImage = pack._panelGrandScanShine; end local timeDelta = 0.8 * (openedPosition[2] + 1)/ DFT_POOL_VERTICAL_COUNT; if timeDelta > 0.85 then timeDelta = 0.85; end self:Interval(0.05 + timeDelta, 1, function() scanShineImage:DOFade(1, 0.4); end); self:Interval(1.17, 1, function() self:_SwitchFlash(horizonLine.gachaRandomSwitch, 2, true, SOUND_SIGNAL_BLINK); end); self:Interval(1.81, 1, function() self:_SwitchFlash(verticalLine.gachaRandomSwitch, 2, true, SOUND_SIGNAL_BLINK); end); self:Interval(2.13, 1, function() self:_ShowTriangle(horizonLine); end); self:Interval(2.77, 1, function() self:_ShowTriangle(verticalLine); end); self:Interval(2.29, 1, function() self:_InitSound(SOUND_SIGNAL_LASER); horizonLine._rectRedLine:DOSizeDelta({x = 1, y = RED_LINE_LENGTH}, 0.8); scanShineImage:DOFade(0, 0.2); end); self:Interval(2.93, 1, function() self:_InitSound(SOUND_SIGNAL_LASER); verticalLine._rectRedLine:DOSizeDelta({x = 1, y = RED_LINE_LENGTH}, 0.8); end); self:Interval(2.8, 1, function() self:_SwitchFlash(horizonLine.lineEndSwitch, 2, true, SOUND_SIGNAL_BLINK); end); self:Interval(3.44, 1, function() self:_SwitchFlash(verticalLine.lineEndSwitch, 2, true, SOUND_SIGNAL_BLINK); end); self:Interval(3.6, 1, function() horizonLine._rectRedLine.anchorMin = {x = 0, y = 0}; horizonLine._rectRedLine.anchorMax = {x = 0, y = 0}; horizonLine._rectRedLine.pivot = {x = 0, y = 0}; horizonLine._rectRedLine:DOSizeDelta({x = 1, y = 0}, 0.8); end); self:Interval(4.24, 1, function() verticalLine._rectRedLine.pivot = {x = 0, y = 0}; verticalLine._rectRedLine.anchorMin = {x = 0, y = 0}; verticalLine._rectRedLine.anchorMax = {x = 0, y = 0}; verticalLine._rectRedLine:DOSizeDelta({x = 1, y = 0}, 0.8); end); self:Interval(3.6, 1, function() horizonLine._rectBlackLine.sizeDelta = {x = 1, y = BLACK_LINE_LENGTH}; end); self:Interval(4.24, 1, function() verticalLine._rectBlackLine.sizeDelta = {x = 1, y = BLACK_LINE_LENGTH}; end); self:Interval(4.41, 1, function() self:_SwitchFlash(horizonLine.lineEndSwitch, 2, false, SOUND_SIGNAL_BLINK); end); self:Interval(5.04, 1, function() self:_SwitchFlash(verticalLine.lineEndSwitch, 2, false, SOUND_SIGNAL_BLINK); end); self:Interval(4.65, 1, function() horizonLine.triangleSwitch.isShow = false; end); self:Interval(5.28, 1, function() verticalLine.triangleSwitch.isShow = false; end); if(openedType ~= 2) then pack._imgCritical.color = {r = 1, g = 1, b = 1, a = 0}; pack._panelReward.alpha = 0; pack._shineRect.anchoredPosition = {x = 0, y = 15.6, z = 0}; pack._rewardRect.anchoredPosition = {x = 0, y = 12, z = 0}; self:Interval(3.6 + 0.8 * (openedPosition[1] - 1) / DFT_POOL_VERTICAL_COUNT, 1, function() self:_InitSound(SOUND_SIGNAL_LOCATE); pack._panelReward:DOFade(1, 0.3); pack._shineRect:DOAnchorPos({x = 0, y = 0, z = 0}, 0.3); pack._rewardRect:DOAnchorPos({x = 0, y = 0, z = 0}, 0.3); end); if(openedType == 1) then self:Interval(5.32, 1, function() pack._panelCritical.anchoredPosition = {x = 0, y = 12, z = 0}; pack._imgCritical:DOFade(1, 0.3); pack._panelCritical:DOAnchorPos({x = 0, y = 0, z = 0}, 0.3); end); end elseif openedType == 2 then self:Interval(5.32, 1, function() self:_InitSound(SOUND_SIGNAL_LOCATE); pack._panelCritical.anchoredPosition = {x = 0, y = 12, z = 0}; pack._imgCritical:DOFade(1, 0.3); pack._panelCritical:DOAnchorPos({x = 0, y = 0, z = 0}, 0.3); end); self:Interval(5.65, 1, function() pack._panelGrandShine:DOSizeDelta({x = 171, y = 171}, 0.3); end); end self._bannerText.text = self.m_gridGachaText[openedType + 1]; if openedType == 0 then self._panelBannerNormal:SetActive(true); elseif openedType == 1 then self._panelBannerCritical:SetActive(true); else self._panelBannerGrand:SetActive(true); end self:Interval(6, 1, function() self:_InitSound(SOUND_SIGNAL_POPUP); self._maskBanner:DOSizeDelta({x = 1206, y = 650}, 0.3); end); self:Interval(6.8, 1, function() self._defaultText.color = {r = 0, g = 0, b = 0, a = 0}; self._gachaText.text = self.m_gridGachaText[openedType + 1]; self._bannerGroup.anchorMin = {x = 0, y = 0.5}; self._bannerGroup.anchorMax = {x = 0, y = 0.5}; self._bannerGroup.anchoredPosition = {x = 0, y = -136, z = 0}; self._maskBanner.pivot = {x = 0, y = 1}; self._maskBanner.anchoredPosition = {x = 0, y = 0, z = 0}; self._maskBanner:DOSizeDelta({x = 0, y = 650}, 0.3); end); self:Interval(7.05, 1, function() self._gachaText:DOFade(1, 0.3); end); self:Interval(7.2, 1, function() self:_InitSound(SOUND_SIGNAL_REWARD); self._imgTri1:DOFade(1, 0.3); self._rectTri1:DOAnchorPos({x = -72, y = 95, z = 0}, 0.3); self._textGroup1:DOSizeDelta({x = 192, y = 52, z = 0}, 0.6); end); self:Interval(7.5, 1, function() self._imgFinish1:DOSizeDelta({x = 192, y = 10, z = 0}, 0.6); end); self:Interval(7.8, 1, function() self:_InitSound(SOUND_SIGNAL_REWARD); self._textGroup2:DOSizeDelta({x = 192, y = 52, z = 0}, 0.6); end); self:Interval(8.1, 1, function() self:_InitSound(SOUND_SIGNAL_REWARD); self._textGroup3:DOSizeDelta({x = 192, y = 52, z = 0}, 0.6); end); self:Interval(8.4, 1, function() self:_InitSound(SOUND_SIGNAL_REWARD); self._textGroup4:DOSizeDelta({x = 192, y = 34, z = 0}, 0.6); end); self:Interval(8.7, 1, function() self._imgTri2:DOFade(1, 0.3); self._rectTri2:DOAnchorPos({x = -72, y = -151, z = 0}, 0.3); end); self:Interval(9.0, 1, function() self:_InitSound(SOUND_SIGNAL_TICK); self._panelImgDiamond:DOSizeDelta({x = 145, y = 35}, 0.5); end); self:Interval(9.5, 1, function() self._redDiamondText.text = reward; self._redDiamondText.color = {r = 0.75, g = 0.29, b = 0.25, a = 1}; self._blackDiamondText.text = reward; self._blackDiamondText.color = {r = 0.06, g = 0.06, b = 0.06, a = 0.51}; self._panelImgDiamond.pivot = {x = 1, y = 1}; self._panelImgDiamond.anchoredPosition = {x = 145, y = -7.5, z = 0}; self._panelImgDiamond:DOSizeDelta({x = 0, y = 35}, 0.3); end); self:Interval(10.0, 1, function() self._redDiamondText:DOFade(0, 0.3); self._blackDiamondText:DOFade(0.51, 0.3); end); self:Interval(10.8, 1, function() CS.Torappu.Activity.ActivityUtil.DoShowGainedItems(response.rewards); end); self:Interval(10.9, 1, function() self.m_processSwitch.isShow = false; self.m_finishedSwitch.isShow = true; self.m_viewModel:MarkGachaFinish(); self:_RefreshContent(); end); end function GridGachaMainDlg:_ShowTriangle(line) line.triangleSwitch.isShow = true; line._rectTri:DOAnchorPos({x = 15.5, y = 5, z = 0}, 0.16); end function GridGachaMainDlg:_SwitchFlash(switch, times, flag, signal) for i = 1, times - 1 do self:Interval(i * LINE_FLASH_TIME, 1, function() if signal ~= nil and flag then self:_InitSound(signal); end switch.isShow = flag; end); self:Interval(i * LINE_FLASH_TIME + LINE_FLASH_TIME / 2, 1, function() if signal ~= nil and not flag then self:_InitSound(signal); end switch.isShow = not flag; end); end self:Interval(times * LINE_FLASH_TIME, 1, function() if signal ~= nil and flag then self:_InitSound(signal); end switch.isShow = flag; end); end function GridGachaMainDlg:_HorizonLineRandom(times) for i = 1, times do local pos = CS.Torappu.RandomUtil.Range(1, DFT_POOL_HORIZON_COUNT); local line = self.m_horizonLineView[pos]; self:Interval(i * LINE_RANDOM_FLASH_TIME, 1, function() line.gachaRandomSwitch.isShow = true; end); self:Interval(i * LINE_RANDOM_FLASH_TIME + LINE_RANDOM_FLASH_TIME / 2, 1, function() line.gachaRandomSwitch.isShow = false; end); end end function GridGachaMainDlg:_VerticalLineRandom(times) for i = 1, times do local pos = CS.Torappu.RandomUtil.Range(1, DFT_POOL_VERTICAL_COUNT); local line = self.m_verticalLineView[pos]; self:Interval(i * LINE_RANDOM_FLASH_TIME, 1, function() line.gachaRandomSwitch.isShow = true; end); self:Interval(i * LINE_RANDOM_FLASH_TIME + LINE_RANDOM_FLASH_TIME / 2, 1, function() line.gachaRandomSwitch.isShow = false; end); end end function GridGachaMainDlg:_OnGetRewardResponseNoAnime(response) if self.m_viewModel == nil then return end local openedPosition = response.openedPosition; local addGrandPosition = response.addGrandPosition; local horizonLine = self.m_horizonLineView[openedPosition[2] + 1]; local verticalLine = self.m_verticalLineView[openedPosition[1] + 1]; local openedType = response.openedType; local reward = response.rewards[1]["count"]; local pack = nil; local scanShineImage = nil; self.m_viewModel:InitData(self.m_actId, self.m_poolCount); self.m_viewModel:MarkGachaStart(); self.m_confirmSwitch.isShow = false; self.m_processSwitch.isShow = true; self:Interval(0.05, 1, function() self._imgScanLine:DOAnchorPos({x = 584, y = 0}, 0.6); self:_InitSound(SOUND_SIGNAL_SCAN); end); if openedType ~= 2 then self:_CreateOrGetViewFromTable(self.m_viewMap, CalculatePosition(openedPosition[1], openedPosition[2]), self._package, self._layout); end pack = self.m_viewMap[CalculatePosition(openedPosition[1], openedPosition[2])]; if openedType ~= 2 then scanShineImage = pack._panelScanShine; else scanShineImage = pack._panelGrandScanShine; end local timeDelta = 0.6 * (openedPosition[2] + 1)/ DFT_POOL_VERTICAL_COUNT; if timeDelta > 0.62 then timeDelta = 0.62; end self:Interval(0.05 + timeDelta, 1, function() scanShineImage:DOFade(1, 0.1); end); self:Interval(0.8, 1, function() self:_SwitchFlash(horizonLine.gachaRandomSwitch, 1, true, SOUND_SIGNAL_BLINK); self:_SwitchFlash(verticalLine.gachaRandomSwitch, 1, true, SOUND_SIGNAL_BLINK); end); self:Interval(0.96, 1, function() self:_ShowTriangle(horizonLine); self:_ShowTriangle(verticalLine); end); self:Interval(1.12, 1, function() self:_InitSound(SOUND_SIGNAL_LASER); horizonLine._rectRedLine:DOSizeDelta({x = 1, y = RED_LINE_LENGTH}, 0.4); verticalLine._rectRedLine:DOSizeDelta({x = 1, y = RED_LINE_LENGTH}, 0.4); scanShineImage:DOFade(0, 0.2); end); self:Interval(1.62, 1, function() self:_SwitchFlash(horizonLine.lineEndSwitch, 1, true); self:_SwitchFlash(verticalLine.lineEndSwitch, 1, true); end); self:Interval(1.8, 1, function() horizonLine._rectRedLine.anchorMin = {x = 0, y = 0}; horizonLine._rectRedLine.anchorMax = {x = 0, y = 0}; horizonLine._rectRedLine.pivot = {x = 0, y = 0}; horizonLine._rectRedLine:DOSizeDelta({x = 1, y = 0}, 0.4); verticalLine._rectRedLine.pivot = {x = 0, y = 0}; verticalLine._rectRedLine.anchorMin = {x = 0, y = 0}; verticalLine._rectRedLine.anchorMax = {x = 0, y = 0}; verticalLine._rectRedLine:DOSizeDelta({x = 1, y = 0}, 0.4); end); self:Interval(1.9, 1, function() horizonLine._rectBlackLine.sizeDelta = {x = 1, y = BLACK_LINE_LENGTH}; verticalLine._rectBlackLine.sizeDelta = {x = 1, y = BLACK_LINE_LENGTH}; end); self:Interval(2.3, 1, function() self:_SwitchFlash(horizonLine.lineEndSwitch, 1, false); self:_SwitchFlash(verticalLine.lineEndSwitch, 1, false); end); self:Interval(2.46, 1, function() horizonLine.triangleSwitch.isShow = false; verticalLine.triangleSwitch.isShow = false; end); if(openedType ~= 2) then pack._imgCritical.color = {r = 1, g = 1, b = 1, a = 0}; pack._panelReward.alpha = 0; pack._shineRect.anchoredPosition = {x = 0, y = 15.6, z = 0}; pack._rewardRect.anchoredPosition = {x = 0, y = 12, z = 0}; self:Interval(1.8 + 0.4 * (openedPosition[1] - 1) / DFT_POOL_VERTICAL_COUNT, 1, function() self:_InitSound(SOUND_SIGNAL_LOCATE); pack._panelReward:DOFade(1, 0.15); pack._shineRect:DOAnchorPos({x = 0, y = 0, z = 0}, 0.15); pack._rewardRect:DOAnchorPos({x = 0, y = 0, z = 0}, 0.15); end); if(openedType == 1) then self:Interval(2.3, 1, function() pack._panelCritical.anchoredPosition = {x = 0, y = 12, z = 0}; pack._imgCritical:DOFade(1, 0.3); pack._panelCritical:DOAnchorPos({x = 0, y = 0, z = 0}, 0.15); end); end elseif openedType == 2 then self:Interval(2.3, 1, function() self:_InitSound(SOUND_SIGNAL_LOCATE); pack._panelCritical.anchoredPosition = {x = 0, y = 12, z = 0}; pack._imgCritical:DOFade(1, 0.3); pack._panelCritical:DOAnchorPos({x = 0, y = 0, z = 0}, 0.15); end); self:Interval(2.6, 1, function() pack._panelGrandShine:DOSizeDelta({x = 171, y = 171}, 0.15); end); end self._bannerText.text = self.m_gridGachaText[openedType + 1]; if openedType == 0 then self._panelBannerNormal:SetActive(true); elseif openedType == 1 then self._panelBannerCritical:SetActive(true); else self._panelBannerGrand:SetActive(true); end self:Interval(2.85, 1, function() self:_InitSound(SOUND_SIGNAL_POPUP); self._maskBanner:DOSizeDelta({x = 1206, y = 650}, 0.2); end); self:Interval(3.45, 1, function() CS.Torappu.Activity.ActivityUtil.DoShowGainedItems(response.rewards); end); self:Interval(3.5, 1, function() self.m_processSwitch.isShow = false; self.m_finishedSwitch.isShow = true; self.m_viewModel:MarkGachaFinish(); self:_RefreshContent(); end); end
412
0.944533
1
0.944533
game-dev
MEDIA
0.663022
game-dev
0.972767
1
0.972767
dingzhen-vape/MeteorCN
11,390
src/main/java/meteordevelopment/meteorclient/mixin/ClientPlayerInteractionManagerMixin.java
/* * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client). * Copyright (c) Meteor Development. */ package meteordevelopment.meteorclient.mixin; import meteordevelopment.meteorclient.MeteorClient; import meteordevelopment.meteorclient.events.entity.DropItemsEvent; import meteordevelopment.meteorclient.events.entity.player.*; import meteordevelopment.meteorclient.mixininterface.IClientPlayerInteractionManager; import meteordevelopment.meteorclient.systems.modules.Modules; import meteordevelopment.meteorclient.systems.modules.misc.InventoryTweaks; import meteordevelopment.meteorclient.systems.modules.player.BreakDelay; import meteordevelopment.meteorclient.systems.modules.player.Reach; import meteordevelopment.meteorclient.systems.modules.player.SpeedMine; import meteordevelopment.meteorclient.utils.player.Rotations; import meteordevelopment.meteorclient.utils.world.BlockUtils; import net.minecraft.block.BlockState; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.network.ClientPlayerInteractionManager; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket; import net.minecraft.screen.PlayerScreenHandler; import net.minecraft.screen.ScreenHandler; import net.minecraft.screen.slot.SlotActionType; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.BlockView; import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Final; 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.Inject; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; import static meteordevelopment.meteorclient.MeteorClient.mc; @Mixin(ClientPlayerInteractionManager.class) public abstract class ClientPlayerInteractionManagerMixin implements IClientPlayerInteractionManager { @Shadow private int blockBreakingCooldown; @Shadow protected abstract void syncSelectedSlot(); @Shadow public abstract void clickSlot(int syncId, int slotId, int button, SlotActionType actionType, PlayerEntity player); @Shadow @Final private ClientPlayNetworkHandler networkHandler; @Inject(method = "clickSlot", at = @At("HEAD"), cancellable = true) private void onClickSlot(int syncId, int slotId, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo info) { if (actionType == SlotActionType.THROW && slotId >= 0 && slotId < player.currentScreenHandler.slots.size()) { if (MeteorClient.EVENT_BUS.post(DropItemsEvent.get(player.currentScreenHandler.slots.get(slotId).getStack())).isCancelled()) info.cancel(); } else if (slotId == -999) { // Clicking outside of inventory if (MeteorClient.EVENT_BUS.post(DropItemsEvent.get(player.currentScreenHandler.getCursorStack())).isCancelled()) info.cancel(); } } @Inject(method = "clickSlot", at = @At("HEAD"), cancellable = true) public void onClickArmorSlot(int syncId, int slotId, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo ci) { if (!Modules.get().get(InventoryTweaks.class).armorStorage()) return; ScreenHandler screenHandler = player.currentScreenHandler; if (screenHandler instanceof PlayerScreenHandler) { if (slotId >= 5 && slotId <= 8) { int armorSlot = (8 - slotId) + 36; if (actionType == SlotActionType.PICKUP && !screenHandler.getCursorStack().isEmpty()) { clickSlot(syncId, 17, armorSlot, SlotActionType.SWAP, player); //armor slot <-> inv slot clickSlot(syncId, 17, button, SlotActionType.PICKUP, player); //inv slot <-> cursor slot clickSlot(syncId, 17, armorSlot, SlotActionType.SWAP, player); //armor slot <-> inv slot ci.cancel(); } else if (actionType == SlotActionType.SWAP) { if (button >= 10) { clickSlot(syncId, 45, armorSlot, SlotActionType.SWAP, player); ci.cancel(); } else { clickSlot(syncId, 36 + button, armorSlot, SlotActionType.SWAP, player); //invert swap ci.cancel(); } } } } } @Inject(method = "attackBlock", at = @At("HEAD"), cancellable = true) private void onAttackBlock(BlockPos blockPos, Direction direction, CallbackInfoReturnable<Boolean> info) { if (MeteorClient.EVENT_BUS.post(StartBreakingBlockEvent.get(blockPos, direction)).isCancelled()) info.cancel(); else { SpeedMine sm = Modules.get().get(SpeedMine.class); BlockState state = mc.world.getBlockState(blockPos); if (!sm.instamine() || !sm.filter(state.getBlock())) return; if (state.calcBlockBreakingDelta(mc.player, mc.world, blockPos) > 0.5f) { mc.world.breakBlock(blockPos, true, mc.player); networkHandler.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, blockPos, direction)); networkHandler.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, blockPos, direction)); info.setReturnValue(true); } } } @Inject(method = "interactBlock", at = @At("HEAD"), cancellable = true) public void interactBlock(ClientPlayerEntity player, Hand hand, BlockHitResult hitResult, CallbackInfoReturnable<ActionResult> cir) { if (MeteorClient.EVENT_BUS.post(InteractBlockEvent.get(player.getMainHandStack().isEmpty() ? Hand.OFF_HAND : hand, hitResult)).isCancelled()) cir.setReturnValue(ActionResult.FAIL); } @Inject(method = "attackEntity", at = @At("HEAD"), cancellable = true) private void onAttackEntity(PlayerEntity player, Entity target, CallbackInfo info) { if (MeteorClient.EVENT_BUS.post(AttackEntityEvent.get(target)).isCancelled()) info.cancel(); } @Inject(method = "interactEntity", at = @At("HEAD"), cancellable = true) private void onInteractEntity(PlayerEntity player, Entity entity, Hand hand, CallbackInfoReturnable<ActionResult> info) { if (MeteorClient.EVENT_BUS.post(InteractEntityEvent.get(entity, hand)).isCancelled()) info.setReturnValue(ActionResult.FAIL); } @Inject(method = "dropCreativeStack", at = @At("HEAD"), cancellable = true) private void onDropCreativeStack(ItemStack stack, CallbackInfo info) { if (MeteorClient.EVENT_BUS.post(DropItemsEvent.get(stack)).isCancelled()) info.cancel(); } @Inject(method = "getReachDistance", at = @At("HEAD"), cancellable = true) private void onGetReachDistance(CallbackInfoReturnable<Float> info) { info.setReturnValue(Modules.get().get(Reach.class).blockReach()); } @Inject(method = "hasExtendedReach", at = @At("HEAD"), cancellable = true) private void onHasExtendedReach(CallbackInfoReturnable<Boolean> info) { if (Modules.get().isActive(Reach.class)) info.setReturnValue(false); } @Redirect(method = "updateBlockBreakingProgress", at = @At(value = "FIELD", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;blockBreakingCooldown:I", opcode = Opcodes.PUTFIELD, ordinal = 1)) private void creativeBreakDelayChange(ClientPlayerInteractionManager interactionManager, int value) { BlockBreakingCooldownEvent event = MeteorClient.EVENT_BUS.post(BlockBreakingCooldownEvent.get(value)); blockBreakingCooldown = event.cooldown; } @Redirect(method = "updateBlockBreakingProgress", at = @At(value = "FIELD", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;blockBreakingCooldown:I", opcode = Opcodes.PUTFIELD, ordinal = 2)) private void survivalBreakDelayChange(ClientPlayerInteractionManager interactionManager, int value) { BlockBreakingCooldownEvent event = MeteorClient.EVENT_BUS.post(BlockBreakingCooldownEvent.get(value)); blockBreakingCooldown = event.cooldown; } @Redirect(method = "attackBlock", at = @At(value = "FIELD", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;blockBreakingCooldown:I", opcode = Opcodes.PUTFIELD)) private void creativeBreakDelayChange2(ClientPlayerInteractionManager interactionManager, int value) { BlockBreakingCooldownEvent event = MeteorClient.EVENT_BUS.post(BlockBreakingCooldownEvent.get(value)); blockBreakingCooldown = event.cooldown; } @Redirect(method = "method_41930", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;calcBlockBreakingDelta(Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos;)F")) private float deltaChange(BlockState blockState, PlayerEntity player, BlockView world, BlockPos pos) { float delta = blockState.calcBlockBreakingDelta(player, world, pos); if (Modules.get().get(BreakDelay.class).noInstaBreak.get() && delta >= 1) { BlockBreakingCooldownEvent event = MeteorClient.EVENT_BUS.post(BlockBreakingCooldownEvent.get(blockBreakingCooldown)); blockBreakingCooldown = event.cooldown; return 0; } return delta; } @Inject(method = "breakBlock", at = @At("HEAD"), cancellable = true) private void onBreakBlock(BlockPos blockPos, CallbackInfoReturnable<Boolean> info) { final BreakBlockEvent event = BreakBlockEvent.get(blockPos); MeteorClient.EVENT_BUS.post(event); if (event.isCancelled()) { info.setReturnValue(false); info.cancel(); } } @Inject(method = "interactItem", at = @At("HEAD"), cancellable = true) private void onInteractItem(PlayerEntity player, Hand hand, CallbackInfoReturnable<ActionResult> info) { InteractItemEvent event = MeteorClient.EVENT_BUS.post(InteractItemEvent.get(hand)); if (event.toReturn != null) info.setReturnValue(event.toReturn); } @Inject(method = "cancelBlockBreaking", at = @At("HEAD"), cancellable = true) private void onCancelBlockBreaking(CallbackInfo info) { if (BlockUtils.breaking) info.cancel(); } @ModifyArgs(method = "interactItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/packet/c2s/play/PlayerMoveC2SPacket$Full;<init>(DDDFFZ)V")) private void onInteractItem(Args args) { if (Rotations.rotating) { args.set(3, Rotations.serverYaw); args.set(4, Rotations.serverPitch); } } @Override public void syncSelected() { syncSelectedSlot(); } }
412
0.953166
1
0.953166
game-dev
MEDIA
0.90681
game-dev
0.928236
1
0.928236
gsitgithub/SubMicroTrading
2,196
Generated/model/internal/version/1.0.0/src/com/rr/model/generated/internal/events/recycle/RecoveryVagueOrderRejectRecycler.java
/******************************************************************************* * Copyright (c) 2015 Low Latency Trading Limited : Author Richard Rose * 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.rr.model.generated.internal.events.recycle; import com.rr.model.generated.internal.events.impl.RecoveryVagueOrderRejectImpl; import com.rr.core.pool.Recycler; import com.rr.core.pool.SuperPool; import com.rr.core.pool.RuntimePoolingException; public class RecoveryVagueOrderRejectRecycler implements Recycler<RecoveryVagueOrderRejectImpl> { private SuperPool<RecoveryVagueOrderRejectImpl> _superPool; private RecoveryVagueOrderRejectImpl _root; private int _recycleSize; private int _count = 0; public RecoveryVagueOrderRejectRecycler( int recycleSize, SuperPool<RecoveryVagueOrderRejectImpl> superPool ) { _superPool = superPool; _recycleSize = recycleSize; try { _root = RecoveryVagueOrderRejectImpl.class.newInstance(); } catch( Exception e ) { throw new RuntimePoolingException( "Unable to create recycle root for RecoveryVagueOrderRejectImpl : " + e.getMessage(), e ); } } @Override public void recycle( RecoveryVagueOrderRejectImpl obj ) { if ( obj.getNext() == null ) { obj.reset(); obj.setNext( _root.getNext() ); _root.setNext( obj ); if ( ++_count == _recycleSize ) { _superPool.returnChain( _root.getNext() ); _root.setNext( null ); _count = 0; } } } }
412
0.800869
1
0.800869
game-dev
MEDIA
0.519625
game-dev
0.73819
1
0.73819
PotRooms/StarResonanceData
1,288
lua/table/gen/StoryMessageTableMgr.lua
local StoryMessageTableRow local mgr = require("utility.table_manager") local TableInitUtility = Panda.TableInitUtility local super = require("table.table_manager_base") local StoryMessageTableMgr = class("StoryMessageTableMgr", super) function StoryMessageTableMgr:ctor(ptr, fields) super.ctor(self, ptr, fields) end function StoryMessageTableMgr:GetRow(key, notErrorWhenNotFound) local ret = self.__rows[key] if ret ~= nil then return ret end ret = super.GetRow(self, key, "int") if not ret then if not notErrorWhenNotFound then logError("StoryMessageTableMgr:GetRow key:{0} failed in scene:{1}", key, self.GetCurrentSceneId()) end return nil end return ret end function StoryMessageTableMgr:GetDatas() return super.GetDatas(self) end function StoryMessageTableMgr:ClearCache() local mgr = require("utility.table_manager") self.__rows = {} setmetatable(self.__rows, mgr.table_manager_mt) end local wrapper return { __init = function(ptr, fields) wrapper = StoryMessageTableMgr.new(ptr, fields) end, GetRow = function(key, notErrorWhenNotFound) return wrapper:GetRow(key, notErrorWhenNotFound) end, GetDatas = function() return wrapper:GetDatas() end, ClearCache = function() wrapper:ClearCache() end }
412
0.804844
1
0.804844
game-dev
MEDIA
0.853216
game-dev
0.534071
1
0.534071
hieki-chan/Supermarket-Simulator-Prototype
2,743
Library/PackageCache/com.unity.timeline@1.7.6/Editor/Window/TimelineWindow_TimeCursor.cs
using System; using UnityEngine; using UnityEngine.Timeline; using UnityEngine.Playables; namespace UnityEditor.Timeline { partial class TimelineWindow { TimeAreaItem m_PlayHead; void TimeCursorGUI(TimelineItemArea area) { DrawTimeOnSlider(); if (!CanDrawTimeCursor(area)) return; if (m_PlayHead == null || m_PlayHead.style != styles.timeCursor) { m_PlayHead = new TimeAreaItem(styles.timeCursor, OnTrackHeadDrag); m_PlayHead.AddManipulator(new PlayheadContextMenu(m_PlayHead)); } var headerMode = area == TimelineItemArea.Header; DrawTimeCursor(headerMode, !headerMode); } bool CanDrawTimeCursor(TimelineItemArea area) { if (!currentMode.ShouldShowTimeCursor(state)) return false; if (treeView == null || state.editSequence.asset == null || (state.editSequence.asset != null && state.IsEditingAnEmptyTimeline())) return false; if (area == TimelineItemArea.Lines && !state.TimeIsInRange((float)state.editSequence.time)) return false; return true; } void DrawTimeOnSlider() { if (currentMode.ShouldShowTimeCursor(state)) { var colorDimFactor = EditorGUIUtility.isProSkin ? 0.7f : 0.9f; var c = styles.timeCursor.normal.textColor * colorDimFactor; float time = Mathf.Max((float)state.editSequence.time, 0); float duration = (float)state.editSequence.duration; m_TimeArea.DrawTimeOnSlider(time, c, duration, DirectorStyles.kDurationGuiThickness); } } void DrawTimeCursor(bool drawHead, bool drawline) { m_PlayHead.HandleManipulatorsEvents(state); if (Event.current.type == EventType.MouseDown && Event.current.button == 0) { if (state.timeAreaRect.Contains(Event.current.mousePosition)) { state.SetPlaying(false); m_PlayHead.HandleManipulatorsEvents(state); state.editSequence.time = Math.Max(0.0, state.GetSnappedTimeAtMousePosition(Event.current.mousePosition)); } } m_PlayHead.drawLine = drawline; m_PlayHead.drawHead = drawHead; m_PlayHead.Draw(sequenceContentRect, state, state.editSequence.time); } void OnTrackHeadDrag(double newTime) { state.editSequence.time = Math.Max(0.0, newTime); m_PlayHead.showTooltip = true; } } }
412
0.889625
1
0.889625
game-dev
MEDIA
0.945887
game-dev
0.990829
1
0.990829
magefree/mage
1,653
Mage.Sets/src/mage/cards/w/WhereAncientsTread.java
package mage.cards.w; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldAllTriggeredAbility; import mage.abilities.effects.common.DamageTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.ComparisonType; import mage.filter.FilterPermanent; import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.mageobject.PowerPredicate; import mage.target.common.TargetAnyTarget; import java.util.UUID; /** * @author Plopman */ public final class WhereAncientsTread extends CardImpl { private static final FilterPermanent filter = new FilterControlledCreaturePermanent("a creature you control with power 5 or greater"); static { filter.add(new PowerPredicate(ComparisonType.MORE_THAN, 4)); } public WhereAncientsTread(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{4}{R}"); // Whenever a creature with power 5 or greater you control enters, you may have Where Ancients Tread deal 5 damage to any target. Ability ability = new EntersBattlefieldAllTriggeredAbility( new DamageTargetEffect(5) .setText("you may have {this} deal 5 damage to any target"), filter, true ); ability.addTarget(new TargetAnyTarget()); this.addAbility(ability); } private WhereAncientsTread(final WhereAncientsTread card) { super(card); } @Override public WhereAncientsTread copy() { return new WhereAncientsTread(this); } }
412
0.963716
1
0.963716
game-dev
MEDIA
0.956277
game-dev
0.974309
1
0.974309
dragon66/icafe
29,329
src/com/icafe4j/image/tiff/TiffTag.java
/** * COPYRIGHT (C) 2014-2019 WEN YU (YUWEN_66@YAHOO.COM) ALL RIGHTS RESERVED. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Any modifications to this file must keep this entire header intact. */ package com.icafe4j.image.tiff; import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import com.icafe4j.string.StringUtils; /** * TiffField tag enumeration. * * @author Wen Yu, yuwen_66@yahoo.com * @version 1.0 01/04/2013 */ public enum TiffTag implements Tag { // Definition includes all baseline and extended tags. NEW_SUBFILE_TYPE("New Subfile Type", (short)0x00FE, Attribute.BASELINE) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown new subfile type value: " + value; switch(intValue) { case 0: description = "Default value 0"; break; case 1: description = "Reduced-resolution image data"; break; case 2: description = "A single page of a multi-page image"; break; case 4: description = "A transparency mask for another image"; break; } return description; } public FieldType getFieldType() { return FieldType.LONG; } }, SUBFILE_TYPE("Subfile Type", (short)0x00FF, Attribute.BASELINE) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Unknown subfile type value: " + value; switch(intValue) { case 0: description = "Default value 0"; break; case 1: description = "Full-resolution image data"; break; case 2: description = "Reduced-resolution image data"; break; case 3: description = "A single page of a multi-page image"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, IMAGE_WIDTH("Image Width", (short)0x0100, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, IMAGE_LENGTH("Image Length", (short)0x0101, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, BITS_PER_SAMPLE("Bits Per Sample", (short)0x0102, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, COMPRESSION("Compression", (short)0x0103, Attribute.BASELINE) { public String getFieldAsString(Object value) { return TiffFieldEnum.Compression.fromValue(((int[])value)[0]).getDescription(); } public FieldType getFieldType() { return FieldType.SHORT; } }, PHOTOMETRIC_INTERPRETATION("Photometric Interpretation", (short)0x0106, Attribute.BASELINE) { public String getFieldAsString(Object value) { return TiffFieldEnum.PhotoMetric.fromValue(((int[])value)[0]).getDescription(); } public FieldType getFieldType() { return FieldType.SHORT; } }, THRESHOLDING("Thresholding", (short)0x0107, Attribute.BASELINE) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Unknown thresholding value: " + value; switch(intValue) { case 1: description = "No dithering or halftoning has been applied to the image data"; break; case 2: description = "An ordered dither or halftone technique has been applied to the image data"; break; case 3: description = "A randomized process such as error diffusion has been applied to the image data"; break; } return description; } }, CELL_WIDTH("Cell Width", (short)0x0108, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, CELL_LENGTH("Cell Length", (short)0x0109, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, FILL_ORDER("Fill Order", (short)0x010A, Attribute.BASELINE) { public String getFieldAsString(Object value) { // We only has two values for this tag, so we use an array instead of a map String[] values = {"Msb2Lsb", "Lsb2Msb"}; int intValue = ((int[])value)[0]; if(intValue != 1 && intValue != 2) return "Warning: unknown fill order value: " + intValue; return values[intValue-1]; } public FieldType getFieldType() { return FieldType.SHORT; } }, DOCUMENT_NAME("Document Name", (short)0x010D, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.ASCII; } }, IMAGE_DESCRIPTION("Image Description", (short)0x010E, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } public boolean isCritical() { return false; } }, MAKE("Make", (short)0x010F, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } public boolean isCritical() { return false; } }, MODEL("Model", (short)0x0110, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } }, STRIP_OFFSETS("Strip Offsets", (short)0x0111, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, ORIENTATION("Orientation", (short)0x0112, Attribute.BASELINE) { public String getFieldAsString(Object value) { String[] values = {"TopLeft", "TopRight", "BottomRight", "BottomLeft", "LeftTop", "RightTop", "RightBottom", "LeftBottom"}; int intValue = ((int[])value)[0]; if(intValue >= 1 && intValue <= 8) return values[intValue - 1]; return "Warning: orientation value: " + intValue; } }, SAMPLES_PER_PIXEL("Samples Per Pixel", (short)0x0115, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, ROWS_PER_STRIP("Rows Per Strip", (short)0x0116, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, STRIP_BYTE_COUNTS("Strip Byte Counts", (short)0x0117, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, MIN_SAMPLE_VALUE("Min Sample Value", (short)0x0118, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, MAX_SAMPLE_VALUE("Max Sample Value", (short)0x0119, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, X_RESOLUTION("XResolution", (short)0x011A, Attribute.BASELINE) { public String getFieldAsString(Object value) { int[] intValues = (int[])value; if(intValues.length != 2) throw new IllegalArgumentException("Wrong number of XResolution data number: " + intValues.length); //formatting numbers up to 3 decimal places in Java DecimalFormat df = new DecimalFormat("#,###,###.##"); return StringUtils.rationalToString(df, true, intValues); } public FieldType getFieldType() { return FieldType.RATIONAL; } }, Y_RESOLUTION("YResolution", (short)0x011B, Attribute.BASELINE) { public String getFieldAsString(Object value) { int[] intValues = (int[])value; if(intValues.length != 2) throw new IllegalArgumentException("Wrong number of YResolution data number: " + intValues.length); //formatting numbers up to 3 decimal places in Java DecimalFormat df = new DecimalFormat("#,###,###.##"); return StringUtils.rationalToString(df, true, intValues); } public FieldType getFieldType() { return FieldType.RATIONAL; } }, PLANAR_CONFIGURATTION("Planar Configuration", (short)0x011C, Attribute.BASELINE) { public String getFieldAsString(Object value) { return TiffFieldEnum.PlanarConfiguration.fromValue(((int[])value)[0]).getDescription(); } public FieldType getFieldType() { return FieldType.SHORT; } }, PAGE_NAME("Page Name", (short)0x011D, Attribute.EXTENDED), X_POSITION("XPosition", (short)0x011E, Attribute.EXTENDED), Y_POSITION("YPosition", (short)0x011F, Attribute.EXTENDED), FREE_OFFSETS("Free Offsets", (short)0x0120, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; } }, FREE_BYTE_COUNTS("Free Byte Counts", (short)0x0121, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.LONG; } }, /** * The precision of the information contained in the GrayResponseCurve. * Because optical density is specified in terms of fractional numbers, * this field is necessary to interpret the stored integer information. * For example, if GrayScaleResponseUnits is set to 4 (ten-thousandths * of a unit), and a GrayScaleResponseCurve number for gray level 4 is * 3455, then the resulting actual value is 0.3455. */ GRAY_RESPONSE_UNIT("Gray Response Unit", (short)0x0122, Attribute.BASELINE) { public String getFieldAsString(Object value) { // String[] values = {"Number represents tenths of a unit", "Number represents hundredths of a unit", "Number represents thousandths of a unit", "Number represents ten-thousandths of a unit", "Number represents hundred-thousandths of a unit"}; // Valid values are from 1 to 5 int intValue = ((int[])value)[0]; if(intValue >= 1 && intValue <= 5) return values[intValue - 1]; return "Warning: unknown resolution unit value: " + intValue; } public FieldType getFieldType() { return FieldType.SHORT; } }, GRAY_RESPONSE_CURVE("Gray Response Curve", (short)0x0123, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, T4_OPTIONS("T4 Options", (short)0x0124, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown T4 options value: " + intValue; switch(intValue) { case 0: description = "Basic 1-dimensional coding"; break; case 1: description = "2-dimensional coding"; break; case 2: description = "Uncompressed mode"; break; case 4: description = "Fill bits have been added as necessary before EOL codes such that EOL always ends on a byte boundary"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, T6_OPTIONS("T6 Options", (short)0x0125, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown T6 options value: " + intValue; switch(intValue) { case 2: description = "Uncompressed mode"; break; case 0: description = "Default value 0"; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, RESOLUTION_UNIT("Resolution Unit", (short)0x0128, Attribute.BASELINE) { public String getFieldAsString(Object value) { // We only has three values for this tag, so we use an array instead of a map String[] values = {"No absolute unit of measurement (Used for images that may have a non-square aspect ratio, but no meaningful absolute dimensions)", "Inch", "Centimeter"}; int intValue = ((int[])value)[0]; if(intValue != 1 && intValue != 2 && intValue != 3) return "Warning: unknown resolution unit value: " + intValue; return values[intValue-1]; } public FieldType getFieldType() { return FieldType.SHORT; } }, PAGE_NUMBER("Page Number", (short)0x0129, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.SHORT; } }, TRANSFER_FUNCTION("Transfer Function", (short)0x012D, Attribute.EXTENDED), SOFTWARE("Software", (short)0x0131, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } public boolean isCritical() { return false; } }, DATETIME("DateTime", (short)0x0132, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } }, ARTIST("Artist", (short)0x013B, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } }, HOST_COMPUTER("Host Computer", (short)0x013C, Attribute.BASELINE), PREDICTOR("Predictor", (short)0x013D, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Unknown predictor value: " + intValue; switch(intValue) { case 1: description = "No prediction scheme used before coding"; break; case 2: description = "Horizontal differencing"; break; case 3: description = "Floating point horizontal differencing"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, WHITE_POINT("White Point", (short)0x013E, Attribute.EXTENDED), PRIMARY_CHROMATICITIES("PrimaryChromaticities", (short)0x013F, Attribute.EXTENDED), COLORMAP("ColorMap", (short)0x0140, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.SHORT; } }, HALTONE_HINTS("Halftone Hints", (short)0x0141, Attribute.EXTENDED), TILE_WIDTH("Tile Width", (short)0x0142, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, TILE_LENGTH("Tile Length", (short)0x0143, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, TILE_OFFSETS("Tile Offsets", (short)0x0144, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, TILE_BYTE_COUNTS("Tile Byte Counts", (short)0x0145, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, BAD_FAX_LINES("Bad Fax Lines", (short)0x0146, Attribute.EXTENDED), CLEAN_FAX_DATA("Clean Fax Data", (short)0x0147, Attribute.EXTENDED), CONSECUTIVE_BAD_FAX_LINES("ConsecutiveBadFaxLines", (short)0x0148, Attribute.EXTENDED), SUB_IFDS("Sub IFDs", (short)0x014A, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; // Or IFD } }, INK_SET("Ink Set", (short)0x014C, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown InkSet value: " + intValue; switch(intValue) { case 1: description = "CMYK"; break; case 2: description = "Not CMYK"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, INK_NAMES("Ink Names", (short)0x014D, Attribute.EXTENDED), NUMBER_OF_INKS("Number Of Inks", (short)0x014E, Attribute.EXTENDED), DOT_RANGE("Dot Range", (short)0x0150, Attribute.EXTENDED), TARGET_PRINTER("Target Printer", (short)0x0151, Attribute.EXTENDED), EXTRA_SAMPLES("Extra Samples", (short)0x0152, Attribute.BASELINE) { public String getFieldAsString(Object value) { // We only has three values for this tag, so we use an array instead of a map String[] values = {"Unspecified data", "Associated alpha data (with pre-multiplied color)", "Unassociated alpha data"}; int intValue = ((int[])value)[0]; if(intValue >= 0 && intValue <= 2) return values[intValue]; return "Warning: unknown extra samples value: " + intValue; } public FieldType getFieldType() { return FieldType.SHORT; } }, SAMPLE_FORMAT("Sample Format", (short)0x0153, Attribute.EXTENDED) { public String getFieldAsString(Object value) { String[] values = {"Unsigned integer data", "Two's complement signed integer data", "IEEE floating point data", "Undefined data format", "Complex integer data", "Complex IEED floating point data"}; int intValue = ((int[])value)[0]; if(intValue >= 1 && intValue <= 6) return values[intValue - 1]; return "Warning: unknown sample format value: " + intValue; } }, S_MIN_SAMPLE_VALUE("S Min Sample Value", (short)0x0154, Attribute.EXTENDED), S_MAX_SAMPLE_VALUE("S Max Sample Value", (short)0x0155, Attribute.EXTENDED), TRANSFER_RANGE("Transfer Range", (short)0x0156, Attribute.EXTENDED), CLIP_PATH("Clip Path", (short)0x0157, Attribute.EXTENDED), X_CLIP_PATH_UNITS("X Clip Path Units", (short)0x0158, Attribute.EXTENDED), Y_CLIP_PATH_UNITS("Y Clip Path Units", (short)0x0159, Attribute.EXTENDED), INDEXED("Indexed", (short)0x015A, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown Indexed value: " + intValue; switch(intValue) { case 0: description = "Not indexde"; break; case 1: description = "Indexed"; break; } return description; } }, JPEG_TABLES("JPEGTables - optional, for new-style JPEG compression", (short)0x015B, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.UNDEFINED; } }, OPI_PROXY("OPI Proxy", (short)0x015F, Attribute.EXTENDED), GLOBAL_PARAMETERS_IFD("Global Parameters IFD", (short)0x0190, Attribute.EXTENDED), PROFILE_TYPE("Profile Type", (short)0x0191, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown profile type value: " + intValue; switch(intValue) { case 0: description = "Unspecified"; break; case 1: description = "Group 3 fax"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, FAX_PROFILE("Fax Profile", (short)0x0192, Attribute.EXTENDED) { public String getFieldAsString(Object value) { String[] values = {"Does not conform to a profile defined for TIFF for facsimile", "Minimal black & white lossless, Profile S", "Extended black & white lossless, Profile F", "Lossless JBIG black & white, Profile J", "Lossy color and grayscale, Profile C", "Lossless color and grayscale, Profile L", "Mixed Raster Content, Profile M"}; int intValue = ((int[])value)[0]; if(intValue >= 0 && intValue <= 6) return values[intValue]; return "Warning: unknown fax profile value: " + intValue; } public FieldType getFieldType() { return FieldType.SHORT; } }, CODING_METHODS("Coding Methods", (short)0x0193, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Unknown coding method value: " + intValue; switch(intValue) { case 1: description = "Unspecified compression"; break; case 2: description = "1-dimensional coding, ITU-T Rec. T.4 (MH - Modified Huffman)"; break; case 4: description = "2-dimensional coding, ITU-T Rec. T.4 (MR - Modified Read)"; break; case 8: description = "2-dimensional coding, ITU-T Rec. T.6 (MMR - Modified MR)"; break; case 16: description = "ITU-T Rec. T.82 coding, using ITU-T Rec. T.85 (JBIG)"; break; case 32: description = "ITU-T Rec. T.81 (Baseline JPEG)"; break; case 64: description = "ITU-T Rec. T.82 coding, using ITU-T Rec. T.43 (JBIG color)"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, VERSION_YEAR("Version Year", (short)0x0194, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.BYTE; } }, MODE_NUMBER("Mode Number", (short)0x0195, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.BYTE; } }, DECODE("Decode", (short)0x01B1, Attribute.EXTENDED), DEFAULT_IMAGE_COLOR("Default Image Color", (short)0x01B2, Attribute.EXTENDED), JPEG_PROC("JPEG Proc", (short)0x0200, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.SHORT; } }, JPEG_INTERCHANGE_FORMAT("JPEG Interchange Format/Jpeg IF Offset", (short)0x0201, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, JPEG_INTERCHANGE_FORMAT_LENGTH("JPEG Interchange Format Length/Jpeg IF Byte Count", (short)0x0202, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, JPEG_RESTART_INTERVAL("JPEG Restart Interval", (short)0x0203, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.SHORT; } }, JPEG_LOSSLESS_PREDICTORS("JPEG Lossless Predictors", (short)0x0205, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.SHORT; } }, JPEG_POINT_TRANSFORMS("JPEG Point Transforms", (short)0x0206, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.SHORT; } }, JPEG_Q_TABLES("JPEG Q Tables", (short)0x0207, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, JPEG_DC_TABLES("JPEG DC Tables", (short)0x0208, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, JPEG_AC_TABLES("JPEG AC Tables", (short)0x0209, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, YCbCr_COEFFICIENTS("YCbCr Coefficients", (short)0x0211, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.RATIONAL; } }, YCbCr_SUB_SAMPLING("YCbCr SubSampling", (short)0x0212, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.SHORT; } }, YCbCr_POSITIONING("YCbCr Positioning", (short)0x0213, Attribute.EXTENDED) { public String getFieldAsString(Object value) { // int intValue = ((int[])value)[0]; String description = "Warning: unknown YCbCr positioning value: " + intValue; switch(intValue) { case 1: description = "Centered"; break; case 2: description = "Cosited"; break; } return description; } public FieldType getFieldType() { return FieldType.SHORT; } }, REFERENCE_BLACK_WHITE("Reference Black White", (short)0x0214, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.RATIONAL; } }, STRIP_ROW_COUNTS("Strip Row Counts", (short)0x022F, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; } }, XMP("XMP", (short)0x02BC, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.BYTE; } }, RATING("Rating", (short)0x4746, Attribute.PRIVATE), RATING_PERCENT("Rating Percent", (short)0x4749, Attribute.PRIVATE), IMAGE_ID("Image ID", (short)0x800D, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.ASCII; } }, MATTEING("Matteing", (short)0x80e3, Attribute.PRIVATE), COPYRIGHT("Copyright", (short)0x8298, Attribute.BASELINE) { public FieldType getFieldType() { return FieldType.ASCII; } }, // (International Press Telecommunications Council) metadata. IPTC("Rich Tiff IPTC", (short)0x83BB, Attribute.PRIVATE) { public FieldType getFieldType() { return FieldType.UNDEFINED; // Or BYTE } }, IT8_SITE("IT8 Site", (short)0x84e0, Attribute.PRIVATE), IT8_COLOR_SEQUENCE("IT8 Color Sequence", (short)0x84e1, Attribute.PRIVATE), IT8_HEADER("IT8 Header", (short)0x84e2, Attribute.PRIVATE), IT8_RASTER_PADDING("IT8 Raster Padding", (short)0x84e3, Attribute.PRIVATE), IT8_BITS_PER_RUN_LENGTH("IT8 Bits Per Run Length", (short)0x84e4, Attribute.PRIVATE), IT8_BITS_PER_EXTENDED_RUN_LENGTH("IT8 Bits Per Extended Run Length", (short)0x84e5, Attribute.PRIVATE), IT8_COLOR_TABLE("IT8 Color Table", (short)0x84e6, Attribute.PRIVATE), IT8_IMAGE_COLOR_INDICATOR("IT8 Image Color Indicator", (short)0x84e7, Attribute.PRIVATE), IT8_BKG_COLOR_INDICATOR("IT8 Bkg Color Indicator", (short)0x84e8, Attribute.PRIVATE), IT8_IMAGE_COLOR_VALUE("IT8 Image Color Value", (short)0x84e9, Attribute.PRIVATE), IT8_BKG_COLOR_VALUE("IT8 Bkg Color Value", (short)0x84ea, Attribute.PRIVATE), IT8_PIXEL_INTENSITY_RANGE("IT8 Pixel Intensity Range", (short)0x84eb, Attribute.PRIVATE), IT8_TRANSPARENCY_INDICATOR("IT8 Transparency Indicator", (short)0x84ec, Attribute.PRIVATE), IT8_COLOR_CHARACTERIZATION("IT8 Color Characterization", (short)0x84ed, Attribute.PRIVATE), IT8_HC_USAGE("IT8 HC Usage", (short)0x84ee, Attribute.PRIVATE), IPTC2("Rich Tiff IPTC", (short)0x8568, Attribute.PRIVATE), FRAME_COUNT("Frame Count", (short)0x85b8, Attribute.PRIVATE), // Photoshop image resources PHOTOSHOP("Photoshop", (short)0x8649, Attribute.PRIVATE) { public FieldType getFieldType() { return FieldType.BYTE; } }, // The following tag is for ExifSubIFD EXIF_SUB_IFD("Exif Sub IFD", (short)0x8769, Attribute.PRIVATE) { public FieldType getFieldType() { return FieldType.LONG; } }, IMAGE_LAYER("Image Layer", (short)0x87ac, Attribute.EXTENDED) { public FieldType getFieldType() { return FieldType.LONG; // Or SHORT } }, ICC_PROFILE("ICC Profile", (short)0x8773, Attribute.PRIVATE) { public FieldType getFieldType() { return FieldType.UNDEFINED; } }, // The following tag is for GPSSubIFD GPS_SUB_IFD("GPS Sub IFD", (short)0x8825, Attribute.PRIVATE) { public FieldType getFieldType() { return FieldType.LONG; } }, DATE_TIME_ORIGINAL("DateTime Original", (short)0x9003, Attribute.UNKNOWN), /* Photoshop-specific TIFF tag. Starts with a null-terminated character * string of "Adobe Photoshop Document Data Block" */ IMAGE_SOURCE_DATA("Image Source Data", (short)0x935C, Attribute.PRIVATE), WINDOWS_XP_TITLE("WindowsXP Title", (short) 0x9c9b, Attribute.PRIVATE) { public String getFieldAsString(Object value) { // byte[] byteValue = (byte[]) value; String description = ""; try { description = new String(byteValue, "UTF-16LE").trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return description; } public boolean isCritical() { return false; } }, WINDOWS_XP_COMMENT("WindowsXP Comment", (short)0x9c9c, Attribute.PRIVATE) { public String getFieldAsString(Object value) { // byte[] byteValue = (byte[])value; String description = ""; try { description = new String(byteValue, "UTF-16LE").trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return description; } public boolean isCritical() { return false; } }, WINDOWS_XP_AUTHOR("WindowsXP Author", (short)0x9c9d, Attribute.PRIVATE) { public String getFieldAsString(Object value) { // byte[] byteValue = (byte[])value; String description = ""; try { description = new String(byteValue, "UTF-16LE").trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return description; } public boolean isCritical() { return false; } }, WINDOWS_XP_KEYWORDS("WindowsXP Keywords", (short)0x9c9e, Attribute.PRIVATE){ public String getFieldAsString(Object value) { // byte[] byteValue = (byte[])value; String description = ""; try { description = new String(byteValue, "UTF-16LE").trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return description; } public boolean isCritical() { return false; } }, WINDOWS_XP_SUBJECT("WindowsXP Subject", (short) 0x9c9f, Attribute.PRIVATE) { public String getFieldAsString(Object value) { // byte[] byteValue = (byte[]) value; String description = ""; try { description = new String(byteValue, "UTF-16LE").trim(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return description; } public boolean isCritical() { return false; } }, // Ranking unknown tag the least significant. UNKNOWN("Unknown", (short)0xffff, Attribute.UNKNOWN); public enum Attribute { BASELINE, EXTENDED, PRIVATE, UNKNOWN; @Override public String toString() { return StringUtils.capitalizeFully(name()); } } private static final Map<Short, TiffTag> tagMap = new HashMap<Short, TiffTag>(); static { for(TiffTag tiffTag : values()) { tagMap.put(tiffTag.getValue(), tiffTag); } } public static Tag fromShort(short value) { TiffTag tiffTag = tagMap.get(value); if (tiffTag == null) return UNKNOWN; return tiffTag; } private final String name; private final short value; private final Attribute attribute; private TiffTag(String name, short value, Attribute attribute) { this.name = name; this.value = value; this.attribute = attribute; } public Attribute getAttribute() { return attribute; } /** * Intended to be overridden by certain tags to provide meaningful string * representation of the field value such as compression, photo metric interpretation etc. * * @param value field value to be mapped to a string * @return a string representation of the field value or empty string if no meaningful string * representation exists. */ public String getFieldAsString(Object value) { return ""; } public FieldType getFieldType() { return FieldType.UNKNOWN; } public String getName() { return this.name; } public short getValue() { return this.value; } public boolean isCritical() { return true; } @Override public String toString() { if (this == UNKNOWN) return name; return name + " [Value: " + StringUtils.shortToHexStringMM(value) +"] (" + getAttribute() + ")"; } }
412
0.752502
1
0.752502
game-dev
MEDIA
0.153773
game-dev
0.920695
1
0.920695
magmafoundation/Magma-Neo
1,432
patches/net/minecraft/client/gui/components/AbstractWidget.java.patch
--- a/net/minecraft/client/gui/components/AbstractWidget.java +++ b/net/minecraft/client/gui/components/AbstractWidget.java @@ -123,6 +_,8 @@ renderScrollingString(p_281857_, p_282790_, this.getMessage(), i, this.getY(), j, this.getY() + this.getHeight(), p_282944_); } + /** @deprecated Neo: Use {@link #onClick(double, double, int)} instead. */ + @Deprecated public void onClick(double p_93634_, double p_93635_) { } @@ -139,7 +_,7 @@ boolean flag = this.clicked(p_93641_, p_93642_); if (flag) { this.playDownSound(Minecraft.getInstance().getSoundManager()); - this.onClick(p_93641_, p_93642_); + this.onClick(p_93641_, p_93642_, p_93643_); return true; } } @@ -253,6 +_,19 @@ @Override public void setFocused(boolean p_93693_) { this.focused = p_93693_; + } + + public static final int UNSET_FG_COLOR = -1; + protected int packedFGColor = UNSET_FG_COLOR; + public int getFGColor() { + if (packedFGColor != UNSET_FG_COLOR) return packedFGColor; + return this.active ? 16777215 : 10526880; // White : Light Grey + } + public void setFGColor(int color) { + this.packedFGColor = color; + } + public void clearFGColor() { + this.packedFGColor = UNSET_FG_COLOR; } @Override
412
0.89842
1
0.89842
game-dev
MEDIA
0.872699
game-dev
0.827699
1
0.827699
quiverteam/Engine
8,005
src/game/server/gameweaponmanager.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "gameweaponmanager.h" #include "saverestore_utlvector.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //========================================================= //========================================================= class CGameWeaponManager; static CUtlVector<CGameWeaponManager *> g_Managers; //========================================================= //========================================================= class CGameWeaponManager : public CBaseEntity { DECLARE_CLASS( CGameWeaponManager, CBaseEntity ); DECLARE_DATADESC(); public: void Spawn(); CGameWeaponManager() { m_flAmmoMod = 1.0f; m_bExpectingWeapon = false; g_Managers.AddToTail( this ); } ~CGameWeaponManager() { g_Managers.FindAndRemove( this ); } void Think(); void InputSetMaxPieces( inputdata_t &inputdata ); void InputSetAmmoModifier( inputdata_t &inputdata ); string_t m_iszWeaponName; int m_iMaxPieces; float m_flAmmoMod; bool m_bExpectingWeapon; CUtlVector<EHANDLE> m_ManagedNonWeapons; }; BEGIN_DATADESC( CGameWeaponManager ) //fields DEFINE_KEYFIELD( m_iszWeaponName, FIELD_STRING, "weaponname" ), DEFINE_KEYFIELD( m_iMaxPieces, FIELD_INTEGER, "maxpieces" ), DEFINE_KEYFIELD( m_flAmmoMod, FIELD_FLOAT, "ammomod" ), DEFINE_FIELD( m_bExpectingWeapon, FIELD_BOOLEAN ), // funcs DEFINE_FUNCTION( Think ), // inputs DEFINE_INPUTFUNC( FIELD_INTEGER, "SetMaxPieces", InputSetMaxPieces ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetAmmoModifier", InputSetAmmoModifier ), DEFINE_UTLVECTOR( m_ManagedNonWeapons, FIELD_EHANDLE ), END_DATADESC() LINK_ENTITY_TO_CLASS( game_weapon_manager, CGameWeaponManager ); void CreateWeaponManager( const char *pWeaponName, int iMaxPieces ) { CGameWeaponManager *pManager = (CGameWeaponManager *)CreateEntityByName( "game_weapon_manager"); if( pManager ) { pManager->m_iszWeaponName = MAKE_STRING( pWeaponName ); pManager->m_iMaxPieces = iMaxPieces; DispatchSpawn( pManager ); } } void WeaponManager_AmmoMod( CBaseCombatWeapon *pWeapon ) { for ( int i = 0; i < g_Managers.Count(); i++ ) { if ( g_Managers[i]->m_iszWeaponName == pWeapon->m_iClassname ) { int iNewClip = (int)(pWeapon->m_iClip1 * g_Managers[i]->m_flAmmoMod); int iNewRandomClip = iNewClip + RandomInt( -2, 2 ); if ( iNewRandomClip > pWeapon->GetMaxClip1() ) { iNewRandomClip = pWeapon->GetMaxClip1(); } else if ( iNewRandomClip <= 0 ) { //Drop at least one bullet. iNewRandomClip = 1; } pWeapon->m_iClip1 = iNewRandomClip; } } } void WeaponManager_AddManaged( CBaseEntity *pWeapon ) { for ( int i = 0; i < g_Managers.Count(); i++ ) { if ( g_Managers[i]->m_iszWeaponName == pWeapon->m_iClassname ) { Assert( g_Managers[i]->m_ManagedNonWeapons.Find( pWeapon ) == g_Managers[i]->m_ManagedNonWeapons.InvalidIndex() ); g_Managers[i]->m_ManagedNonWeapons.AddToTail( pWeapon ); break; } } } void WeaponManager_RemoveManaged( CBaseEntity *pWeapon ) { for ( int i = 0; i < g_Managers.Count(); i++ ) { if ( g_Managers[i]->m_iszWeaponName == pWeapon->m_iClassname ) { int j = g_Managers[i]->m_ManagedNonWeapons.Find( pWeapon ); if ( j != g_Managers[i]->m_ManagedNonWeapons.InvalidIndex() ) { g_Managers[i]->m_ManagedNonWeapons.FastRemove( j ); } } } } //--------------------------------------------------------- //--------------------------------------------------------- void CGameWeaponManager::Spawn() { SetThink( &CGameWeaponManager::Think ); SetNextThink( gpGlobals->curtime ); CBaseEntity *pEntity = CreateEntityByName( STRING(m_iszWeaponName) ); if ( !pEntity ) { DevMsg("%s removed itself!\n", GetDebugName() ); UTIL_Remove(this); } else { m_bExpectingWeapon = ( dynamic_cast<CBaseCombatWeapon *>(pEntity) != NULL ); UTIL_Remove(pEntity); } } //--------------------------------------------------------- // Count of all the weapons in the world of my type and // see if we have a surplus. If there is a surplus, try // to find suitable candidates for removal. // // Right now we just remove the first weapons we find that // are behind the player, or are out of the player's PVS. // Later, we may want to score the results so that we // removed the farthest gun that's not in the player's // viewcone, etc. // // Some notes and thoughts: // // This code is designed NOT to remove weapons that are // hand-placed by level designers. It should only clean // up weapons dropped by dead NPCs, which is useful in // situations where enemies are spawned in for a sustained // period of time. // // Right now we PREFER to remove weapons that are not in the // player's PVS, but this could be opposite of what we // really want. We may only want to conduct the cleanup on // weapons that are IN the player's PVS. //--------------------------------------------------------- void CGameWeaponManager::Think() { int i; // Don't have to think all that often. SetNextThink( gpGlobals->curtime + 2.0 ); const char *pszWeaponName = STRING( m_iszWeaponName ); CUtlVector<CBaseEntity *> candidates( 0, 64 ); if ( m_bExpectingWeapon ) { CBaseCombatWeapon *pWeapon = NULL; // Firstly, count the total number of weapons of this type in the world. // Also count how many of those can potentially be removed. pWeapon = assert_cast<CBaseCombatWeapon *>(gEntList.FindEntityByClassname( pWeapon, pszWeaponName )); while( pWeapon ) { if( !pWeapon->IsEffectActive( EF_NODRAW ) && pWeapon->IsRemoveable() ) { candidates.AddToTail( pWeapon ); } pWeapon = assert_cast<CBaseCombatWeapon *>(gEntList.FindEntityByClassname( pWeapon, pszWeaponName )); } } else { for ( i = 0; i < m_ManagedNonWeapons.Count(); i++) { CBaseEntity *pEntity = m_ManagedNonWeapons[i]; if ( pEntity ) { Assert( pEntity->m_iClassname == m_iszWeaponName ); if ( !pEntity->IsEffectActive( EF_NODRAW ) ) { candidates.AddToTail( pEntity ); } } else { m_ManagedNonWeapons.FastRemove( i-- ); } } } // Calculate the surplus. int surplus = candidates.Count() - m_iMaxPieces; // Based on what the player can see, try to clean up the world by removing weapons that // the player cannot see right at the moment. CBaseEntity *pCandidate; for ( i = 0; i < candidates.Count() && surplus > 0; i++ ) { bool fRemovedOne = false; pCandidate = candidates[i]; Assert( !pCandidate->IsEffectActive( EF_NODRAW ) ); if ( gpGlobals->maxClients == 1 ) { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); // Nodraw serves as a flag that this weapon is already being removed since // all we're really doing inside this loop is marking them for removal by // the entity system. We don't want to count the same weapon as removed // more than once. if( !UTIL_FindClientInPVS( pCandidate->edict() ) ) { fRemovedOne = true; } else if( !pPlayer->FInViewCone( pCandidate ) ) { fRemovedOne = true; } else if ( UTIL_DistApprox( pPlayer->GetAbsOrigin(), pCandidate->GetAbsOrigin() ) > (30*12) ) { fRemovedOne = true; } } else { fRemovedOne = true; } if( fRemovedOne ) { pCandidate->AddEffects( EF_NODRAW ); UTIL_Remove( pCandidate ); DevMsg( 2, "Surplus %s removed\n", pszWeaponName); surplus--; } } } //--------------------------------------------------------- //--------------------------------------------------------- void CGameWeaponManager::InputSetMaxPieces( inputdata_t &inputdata ) { m_iMaxPieces = inputdata.value.Int(); } //--------------------------------------------------------- //--------------------------------------------------------- void CGameWeaponManager::InputSetAmmoModifier( inputdata_t &inputdata ) { m_flAmmoMod = inputdata.value.Float(); }
412
0.971078
1
0.971078
game-dev
MEDIA
0.991495
game-dev
0.945854
1
0.945854
nkmk/python-snippets
1,364
notebook/dict_get_key_from_value.py
d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'} value = d['key1'] print(value) # aaa keys = [k for k, v in d.items() if v == 'aaa'] print(keys) # ['key1', 'key2'] keys = [k for k, v in d.items() if v == 'bbb'] print(keys) # ['key3'] keys = [k for k, v in d.items() if v == 'xxx'] print(keys) # [] key = [k for k, v in d.items() if v == 'aaa'][0] print(key) # key1 key = [k for k, v in d.items() if v == 'bbb'][0] print(key) # key3 # key = [k for k, v in d.items() if v == 'xxx'][0] # print(key) # IndexError: list index out of range def get_keys_from_value(d, val): return [k for k, v in d.items() if v == val] keys = get_keys_from_value(d, 'aaa') print(keys) # ['key1', 'key2'] def get_key_from_value(d, val): keys = [k for k, v in d.items() if v == val] if keys: return keys[0] return None key = get_key_from_value(d, 'aaa') print(key) # key1 key = get_key_from_value(d, 'bbb') print(key) # key3 key = get_key_from_value(d, 'xxx') print(key) # None d_num = {'key1': 1, 'key2': 2, 'key3': 3} keys = [k for k, v in d_num.items() if v >= 2] print(keys) # ['key2', 'key3'] keys = [k for k, v in d_num.items() if v % 2 == 1] print(keys) # ['key1', 'key3'] d_str = {'key1': 'aaa@xxx.com', 'key2': 'bbb@yyy.net', 'key3': 'ccc@zzz.com'} keys = [k for k, v in d_str.items() if v.endswith('com')] print(keys) # ['key1', 'key3']
412
0.592745
1
0.592745
game-dev
MEDIA
0.297796
game-dev
0.536533
1
0.536533
erigontech/erigon
3,016
execution/stagedsync/stagebuilder.go
// Copyright 2024 The Erigon Authors // This file is part of Erigon. // // Erigon 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. // // Erigon is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with Erigon. If not, see <http://www.gnu.org/licenses/>. package stagedsync import ( "context" "github.com/erigontech/erigon/common/log/v3" "github.com/erigontech/erigon/db/kv" "github.com/erigontech/erigon/db/wrap" "github.com/erigontech/erigon/execution/stagedsync/stages" "github.com/erigontech/erigon/execution/types" "github.com/erigontech/erigon/node/gointerfaces/remoteproto" ) type ChainEventNotifier interface { OnNewHeader(newHeadersRlp [][]byte) OnNewPendingLogs(types.Logs) OnLogs([]*remoteproto.SubscribeLogsReply) HasLogSubscriptions() bool } func MiningStages( ctx context.Context, createBlockCfg MiningCreateBlockCfg, executeBlockCfg ExecuteBlockCfg, sendersCfg SendersCfg, execCfg MiningExecCfg, finish MiningFinishCfg, astridEnabled bool, ) []*Stage { return []*Stage{ { ID: stages.MiningCreateBlock, Description: "Mining: construct new block from txn pool", Forward: func(badBlockUnwind bool, s *StageState, u Unwinder, txc wrap.TxContainer, logger log.Logger) error { return SpawnMiningCreateBlockStage(s, txc, createBlockCfg, ctx.Done(), logger) }, Unwind: func(u *UnwindState, s *StageState, txc wrap.TxContainer, logger log.Logger) error { return nil }, Prune: func(u *PruneState, tx kv.RwTx, logger log.Logger) error { return nil }, }, { ID: stages.MiningExecution, Description: "Mining: execute new block from txn pool", Forward: func(badBlockUnwind bool, s *StageState, u Unwinder, txc wrap.TxContainer, logger log.Logger) error { return SpawnMiningExecStage(s, txc, execCfg, sendersCfg, executeBlockCfg, ctx, logger, nil) }, Unwind: func(u *UnwindState, s *StageState, txc wrap.TxContainer, logger log.Logger) error { return nil }, Prune: func(u *PruneState, tx kv.RwTx, logger log.Logger) error { return nil }, }, { ID: stages.MiningFinish, Description: "Mining: create and propagate valid block", Forward: func(badBlockUnwind bool, s *StageState, u Unwinder, txc wrap.TxContainer, logger log.Logger) error { return SpawnMiningFinishStage(s, txc.Tx, finish, ctx.Done(), logger) }, Unwind: func(u *UnwindState, s *StageState, txc wrap.TxContainer, logger log.Logger) error { return nil }, Prune: func(u *PruneState, tx kv.RwTx, logger log.Logger) error { return nil }, }, } }
412
0.925126
1
0.925126
game-dev
MEDIA
0.300521
game-dev
0.95621
1
0.95621
eaglerforge/EaglerForge-old
3,204
sources/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenConnectOption.java
package net.lax1dude.eaglercraft.v1_8.sp.gui; import net.lax1dude.eaglercraft.v1_8.sp.lan.LANServerController; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiMultiplayer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreenServerList; import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenConnectOption extends GuiScreen { private final GuiMultiplayer guiScreen; private String title; private String prompt; private final GuiNetworkSettingsButton relaysButton; public GuiScreenConnectOption(GuiMultiplayer guiScreen) { this.guiScreen = guiScreen; this.relaysButton = new GuiNetworkSettingsButton(this); } public void initGui() { title = I18n.format("selectServer.direct"); prompt = I18n.format("directConnect.prompt"); buttonList.clear(); buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 - 60 + 90, I18n.format("directConnect.serverJoin"))); buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 4 - 60 + 115, I18n.format("directConnect.lanWorld"))); buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 - 60 + 155, I18n.format("gui.cancel"))); } protected void actionPerformed(GuiButton par1GuiButton) { if(par1GuiButton.id == 0) { guiScreen.cancelDirectConnect(); mc.displayGuiScreen(guiScreen); }else if(par1GuiButton.id == 1) { mc.displayGuiScreen(new GuiScreenServerList(guiScreen, guiScreen.getSelectedServer())); }else if(par1GuiButton.id == 2) { if(LANServerController.supported()) { guiScreen.cancelDirectConnect(); mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenLANConnect(guiScreen))); }else { mc.displayGuiScreen(new GuiScreenLANNotSupported(this)); } } } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRendererObj, title, this.width / 2, this.height / 4 - 60 + 20, 16777215); this.drawCenteredString(this.fontRendererObj, prompt, this.width / 2, this.height / 4 - 60 + 55, 0x999999); super.drawScreen(par1, par2, par3); relaysButton.drawScreen(par1, par2); } protected void mouseClicked(int par1, int par2, int par3) { relaysButton.mouseClicked(par1, par2, par3); super.mouseClicked(par1, par2, par3); } }
412
0.831582
1
0.831582
game-dev
MEDIA
0.552546
game-dev
0.555206
1
0.555206
EOS-team/EOS
15,530
src/embodied-intelligence/src/3D_human_pose_recognition/ios_sdk/UnityDEBUG/ForDebug/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/CanvasUpdateRegistry.cs
using System; using System.Collections.Generic; using UnityEngine.UI.Collections; namespace UnityEngine.UI { /// <summary> /// Values of 'update' called on a Canvas update. /// </summary> /// <remarks> If modifying also modify m_CanvasUpdateProfilerStrings to match.</remarks> public enum CanvasUpdate { /// <summary> /// Called before layout. /// </summary> Prelayout = 0, /// <summary> /// Called for layout. /// </summary> Layout = 1, /// <summary> /// Called after layout. /// </summary> PostLayout = 2, /// <summary> /// Called before rendering. /// </summary> PreRender = 3, /// <summary> /// Called late, before render. /// </summary> LatePreRender = 4, /// <summary> /// Max enum value. Always last. /// </summary> MaxUpdateValue = 5 } /// <summary> /// This is an element that can live on a Canvas. /// </summary> public interface ICanvasElement { /// <summary> /// Rebuild the element for the given stage. /// </summary> /// <param name="executing">The current CanvasUpdate stage being rebuild.</param> void Rebuild(CanvasUpdate executing); /// <summary> /// Get the transform associated with the ICanvasElement. /// </summary> Transform transform { get; } /// <summary> /// Callback sent when this ICanvasElement has completed layout. /// </summary> void LayoutComplete(); /// <summary> /// Callback sent when this ICanvasElement has completed Graphic rebuild. /// </summary> void GraphicUpdateComplete(); /// <summary> /// Used if the native representation has been destroyed. /// </summary> /// <returns>Return true if the element is considered destroyed.</returns> bool IsDestroyed(); } /// <summary> /// A place where CanvasElements can register themselves for rebuilding. /// </summary> public class CanvasUpdateRegistry { private static CanvasUpdateRegistry s_Instance; private bool m_PerformingLayoutUpdate; private bool m_PerformingGraphicUpdate; // This list matches the CanvasUpdate enum above. Keep in sync private string[] m_CanvasUpdateProfilerStrings = new string[] { "CanvasUpdate.Prelayout", "CanvasUpdate.Layout", "CanvasUpdate.PostLayout", "CanvasUpdate.PreRender", "CanvasUpdate.LatePreRender" }; private const string m_CullingUpdateProfilerString = "ClipperRegistry.Cull"; private readonly IndexedSet<ICanvasElement> m_LayoutRebuildQueue = new IndexedSet<ICanvasElement>(); private readonly IndexedSet<ICanvasElement> m_GraphicRebuildQueue = new IndexedSet<ICanvasElement>(); protected CanvasUpdateRegistry() { Canvas.willRenderCanvases += PerformUpdate; } /// <summary> /// Get the singleton registry instance. /// </summary> public static CanvasUpdateRegistry instance { get { if (s_Instance == null) s_Instance = new CanvasUpdateRegistry(); return s_Instance; } } private bool ObjectValidForUpdate(ICanvasElement element) { var valid = element != null; var isUnityObject = element is Object; if (isUnityObject) valid = (element as Object) != null; //Here we make use of the overloaded UnityEngine.Object == null, that checks if the native object is alive. return valid; } private void CleanInvalidItems() { // So MB's override the == operator for null equality, which checks // if they are destroyed. This is fine if you are looking at a concrete // mb, but in this case we are looking at a list of ICanvasElement // this won't forward the == operator to the MB, but just check if the // interface is null. IsDestroyed will return if the backend is destroyed. var layoutRebuildQueueCount = m_LayoutRebuildQueue.Count; for (int i = layoutRebuildQueueCount - 1; i >= 0; --i) { var item = m_LayoutRebuildQueue[i]; if (item == null) { m_LayoutRebuildQueue.RemoveAt(i); continue; } if (item.IsDestroyed()) { m_LayoutRebuildQueue.RemoveAt(i); item.LayoutComplete(); } } var graphicRebuildQueueCount = m_GraphicRebuildQueue.Count; for (int i = graphicRebuildQueueCount - 1; i >= 0; --i) { var item = m_GraphicRebuildQueue[i]; if (item == null) { m_GraphicRebuildQueue.RemoveAt(i); continue; } if (item.IsDestroyed()) { m_GraphicRebuildQueue.RemoveAt(i); item.GraphicUpdateComplete(); } } } private static readonly Comparison<ICanvasElement> s_SortLayoutFunction = SortLayoutList; private void PerformUpdate() { UISystemProfilerApi.BeginSample(UISystemProfilerApi.SampleType.Layout); CleanInvalidItems(); m_PerformingLayoutUpdate = true; m_LayoutRebuildQueue.Sort(s_SortLayoutFunction); for (int i = 0; i <= (int)CanvasUpdate.PostLayout; i++) { UnityEngine.Profiling.Profiler.BeginSample(m_CanvasUpdateProfilerStrings[i]); for (int j = 0; j < m_LayoutRebuildQueue.Count; j++) { var rebuild = m_LayoutRebuildQueue[j]; try { if (ObjectValidForUpdate(rebuild)) rebuild.Rebuild((CanvasUpdate)i); } catch (Exception e) { Debug.LogException(e, rebuild.transform); } } UnityEngine.Profiling.Profiler.EndSample(); } for (int i = 0; i < m_LayoutRebuildQueue.Count; ++i) m_LayoutRebuildQueue[i].LayoutComplete(); m_LayoutRebuildQueue.Clear(); m_PerformingLayoutUpdate = false; UISystemProfilerApi.EndSample(UISystemProfilerApi.SampleType.Layout); UISystemProfilerApi.BeginSample(UISystemProfilerApi.SampleType.Render); // now layout is complete do culling... UnityEngine.Profiling.Profiler.BeginSample(m_CullingUpdateProfilerString); ClipperRegistry.instance.Cull(); UnityEngine.Profiling.Profiler.EndSample(); m_PerformingGraphicUpdate = true; for (var i = (int)CanvasUpdate.PreRender; i < (int)CanvasUpdate.MaxUpdateValue; i++) { UnityEngine.Profiling.Profiler.BeginSample(m_CanvasUpdateProfilerStrings[i]); for (var k = 0; k < m_GraphicRebuildQueue.Count; k++) { try { var element = m_GraphicRebuildQueue[k]; if (ObjectValidForUpdate(element)) element.Rebuild((CanvasUpdate)i); } catch (Exception e) { Debug.LogException(e, m_GraphicRebuildQueue[k].transform); } } UnityEngine.Profiling.Profiler.EndSample(); } for (int i = 0; i < m_GraphicRebuildQueue.Count; ++i) m_GraphicRebuildQueue[i].GraphicUpdateComplete(); m_GraphicRebuildQueue.Clear(); m_PerformingGraphicUpdate = false; UISystemProfilerApi.EndSample(UISystemProfilerApi.SampleType.Render); } private static int ParentCount(Transform child) { if (child == null) return 0; var parent = child.parent; int count = 0; while (parent != null) { count++; parent = parent.parent; } return count; } private static int SortLayoutList(ICanvasElement x, ICanvasElement y) { Transform t1 = x.transform; Transform t2 = y.transform; return ParentCount(t1) - ParentCount(t2); } /// <summary> /// Try and add the given element to the layout rebuild list. /// Will not return if successfully added. /// </summary> /// <param name="element">The element that is needing rebuilt.</param> public static void RegisterCanvasElementForLayoutRebuild(ICanvasElement element) { instance.InternalRegisterCanvasElementForLayoutRebuild(element); } /// <summary> /// Try and add the given element to the layout rebuild list. /// </summary> /// <param name="element">The element that is needing rebuilt.</param> /// <returns> /// True if the element was successfully added to the rebuilt list. /// False if either already inside a Graphic Update loop OR has already been added to the list. /// </returns> public static bool TryRegisterCanvasElementForLayoutRebuild(ICanvasElement element) { return instance.InternalRegisterCanvasElementForLayoutRebuild(element); } private bool InternalRegisterCanvasElementForLayoutRebuild(ICanvasElement element) { if (m_LayoutRebuildQueue.Contains(element)) return false; /* TODO: this likely should be here but causes the error to show just resizing the game view (case 739376) if (m_PerformingLayoutUpdate) { Debug.LogError(string.Format("Trying to add {0} for layout rebuild while we are already inside a layout rebuild loop. This is not supported.", element)); return false; }*/ return m_LayoutRebuildQueue.AddUnique(element); } /// <summary> /// Try and add the given element to the rebuild list. /// Will not return if successfully added. /// </summary> /// <param name="element">The element that is needing rebuilt.</param> public static void RegisterCanvasElementForGraphicRebuild(ICanvasElement element) { instance.InternalRegisterCanvasElementForGraphicRebuild(element); } /// <summary> /// Try and add the given element to the rebuild list. /// </summary> /// <param name="element">The element that is needing rebuilt.</param> /// <returns> /// True if the element was successfully added to the rebuilt list. /// False if either already inside a Graphic Update loop OR has already been added to the list. /// </returns> public static bool TryRegisterCanvasElementForGraphicRebuild(ICanvasElement element) { return instance.InternalRegisterCanvasElementForGraphicRebuild(element); } private bool InternalRegisterCanvasElementForGraphicRebuild(ICanvasElement element) { if (m_PerformingGraphicUpdate) { Debug.LogError(string.Format("Trying to add {0} for graphic rebuild while we are already inside a graphic rebuild loop. This is not supported.", element)); return false; } return m_GraphicRebuildQueue.AddUnique(element); } /// <summary> /// Remove the given element from both the graphic and the layout rebuild lists. /// </summary> /// <param name="element"></param> public static void UnRegisterCanvasElementForRebuild(ICanvasElement element) { instance.InternalUnRegisterCanvasElementForLayoutRebuild(element); instance.InternalUnRegisterCanvasElementForGraphicRebuild(element); } /// <summary> /// Disable the given element from both the graphic and the layout rebuild lists. /// </summary> /// <param name="element"></param> public static void DisableCanvasElementForRebuild(ICanvasElement element) { instance.InternalDisableCanvasElementForLayoutRebuild(element); instance.InternalDisableCanvasElementForGraphicRebuild(element); } private void InternalUnRegisterCanvasElementForLayoutRebuild(ICanvasElement element) { if (m_PerformingLayoutUpdate) { Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element)); return; } element.LayoutComplete(); instance.m_LayoutRebuildQueue.Remove(element); } private void InternalUnRegisterCanvasElementForGraphicRebuild(ICanvasElement element) { if (m_PerformingGraphicUpdate) { Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element)); return; } element.GraphicUpdateComplete(); instance.m_GraphicRebuildQueue.Remove(element); } private void InternalDisableCanvasElementForLayoutRebuild(ICanvasElement element) { if (m_PerformingLayoutUpdate) { Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element)); return; } element.LayoutComplete(); instance.m_LayoutRebuildQueue.DisableItem(element); } private void InternalDisableCanvasElementForGraphicRebuild(ICanvasElement element) { if (m_PerformingGraphicUpdate) { Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element)); return; } element.GraphicUpdateComplete(); instance.m_GraphicRebuildQueue.DisableItem(element); } /// <summary> /// Are graphics layouts currently being calculated.. /// </summary> /// <returns>True if the rebuild loop is CanvasUpdate.Prelayout, CanvasUpdate.Layout or CanvasUpdate.Postlayout</returns> public static bool IsRebuildingLayout() { return instance.m_PerformingLayoutUpdate; } /// <summary> /// Are graphics currently being rebuild. /// </summary> /// <returns>True if the rebuild loop is CanvasUpdate.PreRender or CanvasUpdate.Render</returns> public static bool IsRebuildingGraphics() { return instance.m_PerformingGraphicUpdate; } } }
412
0.815271
1
0.815271
game-dev
MEDIA
0.454746
game-dev
0.951132
1
0.951132