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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
goldeneye-source/ges-code | 1,133 | game/client/weapons_resource.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef WEAPONS_RESOURCE_H
#define WEAPONS_RESOURCE_H
#pragma once
#include "shareddefs.h"
#include "weapon_parse.h"
#include "utldict.h"
#include "hud.h"
class C_BaseCombatWeapon;
class CHudTexture;
//-----------------------------------------------------------------------------
// Purpose: Stores data about the Weapon Definitions passed to the client when
// the client first connects to a server.
//-----------------------------------------------------------------------------
class WeaponsResource
{
public:
WeaponsResource( void );
~WeaponsResource( void );
void Init( void );
void Reset( void );
// Sprite handling
void LoadWeaponSprites( WEAPON_FILE_INFO_HANDLE hWeaponFileInfo );
void LoadAllWeaponSprites( void );
// Ammo Handling
CHudTexture *GetAmmoIconFromWeapon( int iAmmoId );
const FileWeaponInfo_t *GetWeaponFromAmmo( int iAmmoId );
};
extern WeaponsResource gWR;
#endif // WEAPONS_RESOURCE_H
| 0 | 0.743298 | 1 | 0.743298 | game-dev | MEDIA | 0.983713 | game-dev | 0.552294 | 1 | 0.552294 |
ezEngine/ezEngine | 15,309 | Code/ThirdParty/Kraut/KrautGenerator/Lod/Implementation/TreeStructureLodGenerator.cpp | #include <KrautGenerator/PCH.h>
#include <KrautGenerator/Description/LodDesc.h>
#include <KrautGenerator/Description/TreeStructureDesc.h>
#include <KrautGenerator/Lod/TreeStructureLod.h>
#include <KrautGenerator/Lod/TreeStructureLodGenerator.h>
#include <KrautGenerator/Mesh/Mesh.h>
#include <KrautGenerator/TreeStructure/TreeStructure.h>
namespace Kraut
{
void GenerateVertexRing(VertexRing& out_VertexRing, const Kraut::SpawnNodeDesc& spawnDesc, const Kraut::BranchNode* pPrevNode, const Kraut::BranchNode* pCurNode, const Kraut::BranchNode* pNextNode, float fVertexRingDetail, float fPosAlongBranch, const aeVec3& vNormalAnchor, aeUInt32 uiVertices);
void GenerateVertexRing(VertexRing& out_VertexRing, const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::BranchStructure& branchStructure, aeInt32 iPrevNodeIdx, aeInt32 iCurNodeIdx, aeInt32 iNextNodeIdx, float fVertexRingDetail, const aeVec3& vNormalAnchor);
void TreeStructureLodGenerator::GenerateTreeStructureLod()
{
if (m_pLodDesc == nullptr)
{
Kraut::LodDesc lod;
lod.m_fTipDetail = 0.03f;
lod.m_fVertexRingDetail = 0.04f;
GenerateFullDetailLod(*m_pTreeStructureDesc, lod, *m_pTreeStructure);
}
else
{
GenerateTreeStructureLod(*m_pTreeStructureDesc, *m_pLodDesc, *m_pTreeStructure);
}
}
void TreeStructureLodGenerator::GenerateFullDetailLod(const Kraut::TreeStructureDesc& structureDesc, const Kraut::LodDesc& lodDesc, const Kraut::TreeStructure& structure)
{
m_pTreeStructureLod->m_BranchLODs.clear();
m_pTreeStructureLod->m_BranchLODs.resize(structure.m_BranchStructures.size());
for (aeUInt32 b = 0; b < structure.m_BranchStructures.size(); ++b)
{
GenerateFullDetailLod(m_pTreeStructureLod->m_BranchLODs[b], structureDesc, lodDesc, structure.m_BranchStructures[b]);
}
}
void TreeStructureLodGenerator::GenerateTreeStructureLod(const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::LodDesc& lodDesc, const Kraut::TreeStructure& structure)
{
m_pTreeStructureLod->m_BranchLODs.clear();
m_pTreeStructureLod->m_BranchLODs.resize(structure.m_BranchStructures.size());
for (aeUInt32 b = 0; b < structure.m_BranchStructures.size(); ++b)
{
GenerateBranchLod(treeStructureDesc, lodDesc, structure.m_BranchStructures[b], m_pTreeStructureLod->m_BranchLODs[b]);
}
}
static float GetDistanceToLineSQR(const aeVec3& A, const aeVec3& vLineDir, const aeVec3& P)
{
// bring P into the space of the line AB
const aeVec3 P2 = P - A;
const float fProjectedLength = vLineDir.Dot(P2);
const aeVec3 vProjectedPos = fProjectedLength * vLineDir;
return (vProjectedPos - P2).GetLengthSquared();
}
static float GetNodeFlareThickness(const Kraut::SpawnNodeDesc& spawnDesc, const Kraut::BranchStructure& branchStructure, aeUInt32 uiNode)
{
if ((spawnDesc.m_uiFlares == 0) || (spawnDesc.m_fFlareWidth <= 1.0f))
return branchStructure.m_Nodes[uiNode].m_fThickness;
float fPosAlongBranch = uiNode / (float)(branchStructure.m_Nodes.size() - 1);
float fFlareCurve = spawnDesc.m_FlareWidthCurve.GetValueAt(fPosAlongBranch);
float fFlareThickness = (1.0f + fFlareCurve * (spawnDesc.m_fFlareWidth - 1.0f));
float fRet = branchStructure.m_Nodes[uiNode].m_fThickness * fFlareThickness;
return fRet;
}
void TreeStructureLodGenerator::GenerateBranchLod(const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::LodDesc& lodDesc, const Kraut::BranchStructure& branchStructure, Kraut::BranchStructureLod& branchStructureLod)
{
branchStructureLod.m_NodeIDs.clear();
branchStructureLod.m_NodeIDs.reserve(branchStructure.m_Nodes.size());
if (branchStructure.m_Type == Kraut::BranchType::None)
return;
const Kraut::SpawnNodeDesc& bnd = treeStructureDesc.m_BranchTypes[branchStructure.m_Type];
if (branchStructure.m_Nodes.size() < 4)
return;
const float fMaxCurvatureDistanceSQR = aeMath::Square(lodDesc.m_fCurvatureThreshold * 0.01f);
aeInt32 iAnchor0 = 0;
aeInt32 iAnchor1 = 1;
aeVec3 vDir = (branchStructure.m_Nodes[iAnchor1].m_vPosition - branchStructure.m_Nodes[iAnchor0].m_vPosition).GetNormalized();
float fMinRadius = aeMath::Min(GetNodeFlareThickness(bnd, branchStructure, iAnchor0), GetNodeFlareThickness(bnd, branchStructure, iAnchor1));
float fMaxRadius = aeMath::Max(GetNodeFlareThickness(bnd, branchStructure, iAnchor0), GetNodeFlareThickness(bnd, branchStructure, iAnchor1));
if (branchStructure.m_iUmbrellaBuddyID != -1)
{
const auto& buddyLod = m_pTreeStructureLod->m_BranchLODs[branchStructure.m_iUmbrellaBuddyID];
if (!buddyLod.m_NodeIDs.empty())
{
branchStructureLod.m_NodeIDs = buddyLod.m_NodeIDs;
return;
}
}
branchStructureLod.m_NodeIDs.push_back(iAnchor0);
const float fSegmentLength = treeStructureDesc.m_BranchTypes[branchStructure.m_Type].m_iSegmentLengthCM / 100.0f;
float fAccuLength = 0.0f;
const aeUInt32 uiMaxNodes = branchStructure.m_Nodes.size();
for (aeUInt32 n = 2; n < uiMaxNodes; ++n)
{
const float fAnchorRotation = ((float)iAnchor0 / (float)(uiMaxNodes - 1)) * bnd.m_fFlareRotation;
//aeVec3 vPos = Branch.m_Nodes[n].m_vPosition;
//aeVec3 vDirToPos = (vPos - Branch.m_Nodes[iAnchor0].m_vPosition).GetNormalized ();
fMinRadius = aeMath::Min(fMinRadius, GetNodeFlareThickness(bnd, branchStructure, n));
fMaxRadius = aeMath::Max(fMaxRadius, GetNodeFlareThickness(bnd, branchStructure, n));
// do not insert nodes unless the segment length is reached
// all manually painted branches have a segment length of ~10cm, independent from the specified segment length
// so this allows to skip nodes to reduce complexity
if (fAccuLength < fSegmentLength)
{
fAccuLength += (branchStructure.m_Nodes[n].m_vPosition - branchStructure.m_Nodes[n - 1].m_vPosition).GetLength();
continue;
}
// if the branch curvature is below the threshold angle
//if (/*(!Branch.m_Nodes[n-1].m_bHasChildBranches) && */(vDirToPos.Dot (vDir) >= fMaxDeviation))
{
// check whether the thickness threshold is reached
const float fAnchor0Thickness = GetNodeFlareThickness(bnd, branchStructure, iAnchor0);
const float fAnchor1Thickness = GetNodeFlareThickness(bnd, branchStructure, n);
// compute the distance between the last anchor and the current node
float fMaxLength = 0;
for (aeUInt32 a = iAnchor0 + 1; a <= n; ++a)
fMaxLength += (branchStructure.m_Nodes[a].m_vPosition - branchStructure.m_Nodes[a - 1].m_vPosition).GetLength();
bool bFullFillsThicknessReq = true;
bool bFullFillsCurvatureReq = true;
const aeVec3 vLineDir = (branchStructure.m_Nodes[n].m_vPosition - branchStructure.m_Nodes[iAnchor0].m_vPosition).GetNormalized();
// go through all nodes between the last anchor and this node and compute the interpolated thickness
// because the polygon will "interpolate" the thickness from anchor0 to anchor1, thus we need to know that
// to check how much the "desired" thickness deviates from the low-poly mesh thickness
float fPieceLength = 0;
for (aeUInt32 a = iAnchor0 + 1; a <= n; ++a)
{
fPieceLength += (branchStructure.m_Nodes[a].m_vPosition - branchStructure.m_Nodes[a - 1].m_vPosition).GetLength();
const float fDesiredThickness = aeMath::Lerp(fAnchor0Thickness, fAnchor1Thickness, (fPieceLength / fMaxLength));
// the interpolated thickness and the desired thickness should match within some threshold
if (aeMath::Abs(1.0f - (GetNodeFlareThickness(bnd, branchStructure, a) / fDesiredThickness)) > lodDesc.m_fThicknessThreshold)
{
bFullFillsThicknessReq = false;
break;
}
const float fFlareRotation = ((float)a / (float)(uiMaxNodes - 1)) * bnd.m_fFlareRotation;
const float fRotationDiff = (aeMath::Abs(fFlareRotation - fAnchorRotation) / 360.0f) / 50;
if (GetDistanceToLineSQR(branchStructure.m_Nodes[iAnchor0].m_vPosition, vLineDir, branchStructure.m_Nodes[a].m_vPosition) + fRotationDiff > fMaxCurvatureDistanceSQR)
{
bFullFillsCurvatureReq = false;
break;
}
}
if (bFullFillsThicknessReq && bFullFillsCurvatureReq)
{
iAnchor1 = n;
continue;
}
}
// if this code is reached, some threshold is not reached and a new node must be inserted
fAccuLength = 0.0f;
branchStructureLod.m_NodeIDs.push_back(iAnchor1);
// reset the next direction, and thickness thresholds
vDir = (branchStructure.m_Nodes[n].m_vPosition - branchStructure.m_Nodes[iAnchor1].m_vPosition).GetNormalized();
fMinRadius = aeMath::Min(GetNodeFlareThickness(bnd, branchStructure, n), GetNodeFlareThickness(bnd, branchStructure, iAnchor1));
fMaxRadius = aeMath::Max(GetNodeFlareThickness(bnd, branchStructure, n), GetNodeFlareThickness(bnd, branchStructure, iAnchor1));
// set the new anchors
iAnchor0 = iAnchor1;
iAnchor1 = n;
}
branchStructureLod.m_NodeIDs.push_back(iAnchor1);
if (iAnchor1 != uiMaxNodes - 1)
branchStructureLod.m_NodeIDs.push_back(uiMaxNodes - 1);
GrowBranchTip(branchStructureLod, treeStructureDesc, lodDesc, branchStructure);
}
void TreeStructureLodGenerator::GenerateFullDetailLod(BranchStructureLod& branchStructureLod, const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::LodDesc& lodDesc, const Kraut::BranchStructure& branchStructure)
{
branchStructureLod.m_NodeIDs.clear();
branchStructureLod.m_NodeIDs.reserve(branchStructure.m_Nodes.size());
if (branchStructure.m_Type == Kraut::BranchType::None)
return;
for (aeUInt32 n = 0; n < branchStructure.m_Nodes.size(); ++n)
{
branchStructureLod.m_NodeIDs.push_back(n);
}
GrowBranchTip(branchStructureLod, treeStructureDesc, lodDesc, branchStructure);
}
void TreeStructureLodGenerator::GrowBranchTip(BranchStructureLod& branchStructureLod, const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::LodDesc& lodDesc, const Kraut::BranchStructure& branchStructure)
{
if (!treeStructureDesc.m_BranchTypes[branchStructure.m_Type].m_bEnable[Kraut::BranchGeometryType::Branch])
return;
if (branchStructure.m_Nodes.size() <= 2)
return;
const float fRoundness = treeStructureDesc.m_BranchTypes[branchStructure.m_Type].m_fRoundnessFactor;
if (fRoundness < 0.01f)
return;
const aeInt32 iSegments = aeMath::Max(1, (aeInt32)(branchStructure.m_Nodes.back().m_fThickness / lodDesc.m_fTipDetail));
const float fSegmentLength = branchStructure.m_Nodes.back().m_fThickness / iSegments;
if (fSegmentLength < 0.001f)
return;
const aeVec3 vPos = branchStructure.m_Nodes.back().m_vPosition;
const float fThickness = branchStructure.m_Nodes.back().m_fThickness;
const aeUInt32 uiSecondLastNodeIdx = branchStructureLod.m_NodeIDs[branchStructureLod.m_NodeIDs.size() - 2];
const aeVec3 vDir = (vPos - branchStructure.m_Nodes[uiSecondLastNodeIdx].m_vPosition).GetNormalized() * fSegmentLength;
if ((!vDir.IsValid()) || (vDir.IsZeroVector(0.00001f)))
return;
Kraut::BranchNode n;
n.m_vPosition = vPos;
branchStructureLod.m_TipNodes.clear();
branchStructureLod.m_TipNodes.reserve(iSegments);
for (aeInt32 i = 0; i < iSegments; ++i)
{
n.m_vPosition += vDir;
const float fFactor = ((i + 1.0f) / iSegments);
const float fCos = aeMath::Sqrt(1.0f - fFactor * fFactor);
n.m_fThickness = fCos;
n.m_fThickness *= fThickness;
branchStructureLod.m_TipNodes.push_back(n);
}
branchStructureLod.m_TipNodes.back().m_fThickness = 0.001f;
GenerateLodTipTexCoordV(branchStructureLod, treeStructureDesc, branchStructure, lodDesc.m_fVertexRingDetail);
}
void TreeStructureLodGenerator::GenerateLodBranchVertexRing(const BranchStructureLod& branchStructureLod, Kraut::VertexRing& out_VertexRing, const Kraut::TreeStructureDesc& structureDesc, const Kraut::BranchStructure& branchStructure, aeUInt32 uiNodeIdx, const aeVec3& vNormalAnchor, float fVertexRingDetail)
{
aeInt32 iPrevNode = ((aeInt32)uiNodeIdx) - 1;
aeInt32 iNextNode = ((aeInt32)uiNodeIdx) + 1;
iPrevNode = aeMath::Max(iPrevNode, 0);
iNextNode = aeMath::Min(iNextNode, (aeInt32)(branchStructureLod.m_NodeIDs.size()) - 1);
Kraut::GenerateVertexRing(out_VertexRing, structureDesc, branchStructure, branchStructureLod.m_NodeIDs[iPrevNode], branchStructureLod.m_NodeIDs[uiNodeIdx], branchStructureLod.m_NodeIDs[iNextNode], fVertexRingDetail, vNormalAnchor);
}
void TreeStructureLodGenerator::GenerateLodTipVertexRing(const BranchStructureLod& branchStructureLod, Kraut::VertexRing& out_VertexRing, const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::BranchStructure& branchStructure, aeUInt32 uiNodeIdx, const aeVec3& vNormalAnchor, aeUInt32 uiRingVertices)
{
aeInt32 iPrevNode = ((aeInt32)uiNodeIdx) - 1;
aeInt32 iNextNode = ((aeInt32)uiNodeIdx) + 1;
iNextNode = aeMath::Min(iNextNode, (aeInt32)(branchStructureLod.m_TipNodes.size()) - 1);
const Kraut::BranchNode* pPrevNode = nullptr;
if (iPrevNode < 0)
pPrevNode = &branchStructure.m_Nodes[branchStructureLod.m_NodeIDs.back()];
else
pPrevNode = &branchStructureLod.m_TipNodes[iPrevNode];
const Kraut::BranchNode* pCurNode = &branchStructureLod.m_TipNodes[uiNodeIdx];
const Kraut::BranchNode* pNextNode = &branchStructureLod.m_TipNodes[iNextNode];
const Kraut::SpawnNodeDesc& spawnDesc = treeStructureDesc.m_BranchTypes[branchStructure.m_Type];
Kraut::GenerateVertexRing(out_VertexRing, spawnDesc, pPrevNode, pCurNode, pNextNode, 0.0f, 1.0f, vNormalAnchor, uiRingVertices);
}
void TreeStructureLodGenerator::GenerateLodTipTexCoordV(BranchStructureLod& branchStructureLod, const Kraut::TreeStructureDesc& treeStructureDesc, const Kraut::BranchStructure& branchStructure, float fVertexRingDetail)
{
Kraut::VertexRing VertexRing;
const aeVec3 vNormalAnchor = branchStructure.m_Nodes.back().m_vPosition;
float fPrevTexCoordV = branchStructure.m_Nodes.back().m_fTexCoordV;
aeVec3 vLastPos = vNormalAnchor;
float fLastBranchDiameter = branchStructure.m_fLastDiameter;
AE_CHECK_DEV(fLastBranchDiameter > 0.0f, "Can't compute LOD V texcoord before doing this on the full branch.");
for (aeUInt32 n = 0; n < branchStructureLod.m_TipNodes.size(); ++n)
{
GenerateLodTipVertexRing(branchStructureLod, VertexRing, treeStructureDesc, branchStructure, n, vNormalAnchor, 24);
const float fDist = (vLastPos - branchStructureLod.m_TipNodes[n].m_vPosition).GetLength();
float fNextTexCoordV = fPrevTexCoordV + (fDist / fLastBranchDiameter);
if (VertexRing.m_fDiameter > 0.1f)
{
fLastBranchDiameter = VertexRing.m_fDiameter;
}
branchStructureLod.m_TipNodes[n].m_fTexCoordV = fNextTexCoordV;
fPrevTexCoordV = fNextTexCoordV;
vLastPos = branchStructureLod.m_TipNodes[n].m_vPosition;
}
}
} // namespace Kraut
| 0 | 0.901901 | 1 | 0.901901 | game-dev | MEDIA | 0.439394 | game-dev,graphics-rendering | 0.839738 | 1 | 0.839738 |
magefree/mage | 1,686 | Mage.Sets/src/mage/cards/g/GiftOfEstates.java | package mage.cards.g;
import mage.abilities.condition.common.OpponentControlsMoreCondition;
import mage.abilities.decorator.ConditionalOneShotEffect;
import mage.abilities.effects.common.search.SearchLibraryPutInHandEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.FilterCard;
import mage.filter.StaticFilters;
import mage.target.common.TargetCardInLibrary;
import java.util.UUID;
/**
* @author LevelX2
*/
public final class GiftOfEstates extends CardImpl {
private static final FilterCard filter = new FilterCard("Plains cards");
static {
filter.add(SubType.PLAINS.getPredicate());
}
public GiftOfEstates(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{W}");
// If an opponent controls more lands than you, search your library for up to three Plains cards, reveal them, and put them into your hand. Then shuffle your library.
this.getSpellAbility().addEffect(new ConditionalOneShotEffect(
new SearchLibraryPutInHandEffect(
new TargetCardInLibrary(0, 3, filter), true
), new OpponentControlsMoreCondition(StaticFilters.FILTER_LANDS), "if an opponent controls " +
"more lands than you, search your library for up to three Plains cards, " +
"reveal them, put them into your hand, then shuffle"
));
}
private GiftOfEstates(final GiftOfEstates card) {
super(card);
}
@Override
public GiftOfEstates copy() {
return new GiftOfEstates(this);
}
}
| 0 | 0.962559 | 1 | 0.962559 | game-dev | MEDIA | 0.958423 | game-dev | 0.973415 | 1 | 0.973415 |
BenjaminSchulte/SureInstinct | 1,061 | aoba-build/src/libmaker/include/maker/game/GameSfxAssetType.hpp | #pragma once
#include <aoba/sfx/Sfx.hpp>
#include "GameAssetType.hpp"
namespace Maker {
class GameSfxAsset : public GameAsset<Aoba::Sfx> {
public:
//! Constructor
GameSfxAsset(const GameAssetType<Aoba::Sfx> *type, GameProject *project, const QString &id)
: GameAsset<Aoba::Sfx>(type, project, id)
{}
//! Creates the asset
Aoba::Sfx *configure(const GameConfigNode &config) override;
//! Converts the asset to YAML assets.yml
bool toYaml(YAML::Emitter &node) const override {
node << YAML::Flow << YAML::BeginMap << YAML::Key << "from_file" << YAML::Value << mProject->relativeAssetFile(mAsset->file()).toStdString() << YAML::EndMap;
return true;
}
};
class GameSfxAssetType : public GameAssetType<Aoba::Sfx> {
public:
//! Loads the palette
GameSfxAsset *create(const QString &id) const override;
protected:
//! Loads the type configuration
Aoba::SfxAssetSet *configure(const GameConfigNode &node) override;
//! Creates the asset resolver
Aoba::ScriptAssetResolver *createAssetResolver() const override;
};
} | 0 | 0.797169 | 1 | 0.797169 | game-dev | MEDIA | 0.973956 | game-dev | 0.612309 | 1 | 0.612309 |
Synxis/SPARK | 6,765 | include/Extensions/Actions/SPK_SpawnParticlesAction.h | //////////////////////////////////////////////////////////////////////////////////
// SPARK particle engine //
// Copyright (C) 2008-2013 - Julien Fryer - julienfryer@gmail.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 H_SPK_SPAWNPARTICLESACTION
#define H_SPK_SPAWNPARTICLESACTION
#include <deque>
namespace SPK
{
/**
* @brief An action that allows particles to spawn punctually at another particle's position
*
* This allows to have some particles spawn at some particle's position when the action is triggered.<br>
* Note that this is only for a punctual spawning. For a continuous spawning, consider using an EmitterAttacher.<br>
* <br>
* To set up particle spawning, an base Emitter is used. The emitter and its zone are copied and the copied emitter is transformed accordingly to
* the particle's position when an action is triggered.<br>
* <br>
* A pool of copied emitter is used internally to avoid creating too many emitters.
*/
class SPK_PREFIX SpawnParticlesAction : public Action
{
public :
//////////////////////////////
// Constructor / Destructor //
//////////////////////////////
/**
* @brief Creates a new spawnParticles action
* @param minNb : the minimum number of spawned particles
* @param maxNb : the maximum number of spawned particles
* @param group : the group in which to spawn particles
* @param emitter : the emitter used to spawn particles
*/
static Ref<SpawnParticlesAction> create(
unsigned int minNb = 1,
unsigned int maxNb = 1,
const Ref<Group>& group = SPK_NULL_REF,
const Ref<Emitter>& emitter = SPK_NULL_REF);
/////////////////////////
// Number of particles //
/////////////////////////
/**
* @brief Sets the number of particle to spawn
* Note that this sets both the minimum and maximum number
* @param nb : the number of particles to spawn
*/
void setNb(unsigned int nb);
/**
* @brief Sets the number of particle to spawn
* The actual number of particle spawn is generated within [min,max]
* @param min : the minimum number of particles to spawn
* @param max : the maximum number of particles to spawn
*/
void setNb(unsigned int min,unsigned int max);
/**
* @brief Gets the minimum number of particles to spawn
* @return the minimum number of particles to spawn
*/
unsigned int getMinNb() const;
/**
* @brief Gets the maximum number of particles to spawn
* @return the maximum number of particles to spawn
*/
unsigned int getMaxNb() const;
//////////////////
// Base emitter //
//////////////////
/**
* @brief Sets the base emitter used to spawn particles
* The emitter is copied for every particle and is transformed accordingly to particle's position.<br>
* Note that the zone of the emitter must not be shared as its zone is copied as well, else the base emitter is considered as invalid.
* @param emitter : the base emitter used to create emitters
*/
void setEmitter(const Ref<Emitter>& emitter);
/**
* @brief Gets the base emitter
* If the base emitter is modified, a call to resetPool() will allow the changes to take effects
* @return the base emitter
*/
const Ref<Emitter>& getEmitter() const;
/////////////////
// Group index //
/////////////////
/**
* @brief Sets the index of the group in which to spawn particles
* The index is the index of the group within the parent system.<br>
* Note that setting the group index to the index of the group which owns the spawn particle action may result in infinitely growing group.
* @param index : the index of the group in the parent system in which to spawn particles
*/
void setTargetGroup(const Ref<Group>& group);
/**
* @brief Gets the index of the group within the parent system in which to spawn particles
* @return the index of the group in which to spawn particles
*/
const Ref<Group>& getTargetGroup() const;
///////////////
// Interface //
///////////////
/** @brief Resets the pool of particles */
void resetPool();
virtual void apply(Particle& particle) const;
virtual Ref<SPKObject> findByName(const std::string& name);
public :
spark_description(SpawnParticlesAction, Action)
(
spk_attribute(Ref<Emitter>, emitter, setEmitter, getEmitter);
spk_attribute(Ref<Group>, targetGroup, setTargetGroup, getTargetGroup);
spk_attribute(Pair<unsigned int>, quantity, setNb, getMinNb, getMaxNb);
);
private :
unsigned int minNb;
unsigned int maxNb;
Ref<Emitter> baseEmitter;
Ref<Group> targetGroup;
mutable std::deque<Ref<Emitter> > emitterPool;
SpawnParticlesAction(
unsigned int minNb = 1,
unsigned int maxNb = 1,
const Ref<Group>& group = SPK_NULL_REF,
const Ref<Emitter>& emitter = SPK_NULL_REF);
SpawnParticlesAction(const SpawnParticlesAction& action);
bool checkValidity() const;
const Ref<Emitter>& getNextAvailableEmitter() const;
};
inline void SpawnParticlesAction::setNb(unsigned int nb)
{
setNb(nb,nb);
}
inline unsigned int SpawnParticlesAction::getMinNb() const
{
return minNb;
}
inline unsigned int SpawnParticlesAction::getMaxNb() const
{
return maxNb;
}
inline Ref<SpawnParticlesAction> SpawnParticlesAction::create(
unsigned int minNb,
unsigned int maxNb,
const Ref<Group>& group,
const Ref<Emitter>& emitter)
{
return SPK_NEW(SpawnParticlesAction,minNb,maxNb,group,emitter);
}
inline const Ref<Emitter>& SpawnParticlesAction::getEmitter() const
{
return baseEmitter;
}
inline void SpawnParticlesAction::setTargetGroup(const Ref<Group>& group)
{
targetGroup = group;
}
inline const Ref<Group>& SpawnParticlesAction::getTargetGroup() const
{
return targetGroup;
}
}
#endif
| 0 | 0.90938 | 1 | 0.90938 | game-dev | MEDIA | 0.880247 | game-dev | 0.848165 | 1 | 0.848165 |
CombatExtended-Continued/CombatExtended | 15,227 | Source/CombatExtended/CombatExtended/WorldObjects/WorldObjectDamageWorker.cs | using CombatExtended.WorldObjects;
using HarmonyLib;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Verse;
namespace CombatExtended;
public class WorldObjectDamageWorker
{
#region WorldObject
public virtual float ApplyDamage(HealthComp healthComp, ThingDef shellDef)
{
var damage = CalculateDamage(shellDef.GetProjectile(), healthComp.parent.Faction) / healthComp.ArmorDamageMultiplier;
healthComp.Health -= damage;
return damage;
}
public virtual float CalculateDamage(ThingDef projectile, Faction faction)
{
var empModifier = 0.03f;
if (faction != null)
{
if ((int)faction.def.techLevel > (int)TechLevel.Medieval)
{
empModifier = Mathf.Pow(3.3f, (int)faction.def.techLevel) / 1800f / ((int)faction.def.techLevel - 2f);
}
if (faction.def.pawnGroupMakers.SelectMany(x => x.options).All(k => k.kind.RaceProps.IsMechanoid))
{
empModifier = 1f;
}
}
var result = FragmentsPotentialDamage(projectile) + FirePotentialDamage(projectile) + EMPPotentialDamage(projectile, empModifier) + OtherPotentialDamage(projectile);
//Damage calculated as in-map damage, needs to be converted into world object damage. 3500f experimentally obtained
result /= 3500f;
//manual overwrite
if (projectile.projectile is ProjectilePropertiesCE projectileProperties && projectileProperties.shellingProps.damage > 0f)
{
result = projectileProperties.shellingProps.damage;
}
//Crit/Miss imitation
result *= Rand.Range(0.4f, 1.5f);
return result;
}
protected const float fragDamageMultipler = 0.04f;
protected virtual float FragmentsPotentialDamage(ThingDef projectile)
{
var result = 0f;
var fragProp = projectile.GetCompProperties<CompProperties_Fragments>();
if (projectile.projectile is ProjectilePropertiesCE props && fragProp != null)
{
foreach (var frag in fragProp.fragments)
{
result += frag.count * frag.thingDef.projectile.damageAmountBase * fragDamageMultipler;
}
}
return result;
}
protected virtual float EMPPotentialDamage(ThingDef projectile, float modifier = 0.03f)
{
float result = 0f;
if (projectile.projectile is ProjectilePropertiesCE props && props.damageDef == DamageDefOf.EMP)
{
result += props.damageAmountBase * modifier;
for (int i = 1; i < props.explosionRadius; i++)
{
result += modifier * DamageAtRadius(projectile, i) * Mathf.Pow(2, i);
}
}
return result;
}
protected virtual float FirePotentialDamage(ThingDef projectile)
{
const float prometheumDamagePerCell = 3;
float result = 0f;
if (projectile.projectile is ProjectilePropertiesCE props && props.damageDef == CE_DamageDefOf.PrometheumFlame)
{
result += props.damageAmountBase;
for (int i = 1; i < props.explosionRadius; i++)
{
result += DamageAtRadius(projectile, i) * Mathf.Pow(2, i);
}
if (props.preExplosionSpawnThingDef == CE_ThingDefOf.FilthPrometheum)
{
result += props.preExplosionSpawnChance * (Mathf.PI * props.explosionRadius * props.explosionRadius) * prometheumDamagePerCell; // damage per cell with preExplosionSpawn Chance
}
}
return result;
}
protected virtual float OtherPotentialDamage(ThingDef projectile)
{
float result = 0f;
if (projectile.projectile is ProjectilePropertiesCE props)
{
if (props.damageDef == DamageDefOf.EMP || props.damageDef == CE_DamageDefOf.PrometheumFlame)
{
return 0f;
}
result += props.damageAmountBase;
for (int i = 1; i < props.explosionRadius; i++)
{
result += DamageAtRadius(projectile, i) * Mathf.Pow(2, i);
}
var extension = props.damageDef.GetModExtension<DamageDefExtensionCE>();
if (extension != null && extension.worldDamageMultiplier >= 0.0f)
{
result *= extension.worldDamageMultiplier;
}
}
return result;
}
public static float DamageAtRadius(ThingDef projectile, int radius)
{
if (!projectile.projectile.explosionDamageFalloff)
{
return projectile.projectile.damageAmountBase;
}
float t = radius / projectile.projectile.explosionRadius;
return Mathf.Max(GenMath.RoundRandom(Mathf.Lerp((float)projectile.projectile.damageAmountBase, (float)projectile.projectile.damageAmountBase * 0.2f, t)), 1);
}
#endregion
#region Attrition
protected static Map map = null;
public static void BeginAttrition(Map map) { WorldObjectDamageWorker.map = map; }
public static void EndAttrition() { map = null; }
public virtual void OnExploded(IntVec3 cell, ThingDef shell) { }
public virtual void ProcessShell(ThingDef shell)
{
int radius = (int)shell.projectile.explosionRadius;
int dmg = shell.projectile.damageAmountBase;
IntVec3 cell;
RoofDef roof;
int count = 0;
do
{
cell = new IntVec3((int)CE_Utility.RandomGaussian(1, map.Size.x - 1), 0, (int)CE_Utility.RandomGaussian(1, map.Size.z - 1));
roof = cell.GetRoof(map);
count++;
} while (count <= 7 && roof == RoofDefOf.RoofRockThick);
if (roof != RoofDefOf.RoofRockThick && TryExplode(cell, shell))
{
OnExploded(cell, shell);
}
}
protected virtual bool TryExplode(IntVec3 centerCell, ThingDef shellDef)
{
var radius = (int)shellDef.GetProjectile().projectile.explosionRadius;
if (!centerCell.InBounds(map))
{
return false;
}
ProcessFragmentsComp(shellDef);
DamageToPawns(shellDef);
IEnumerable<IntVec3> cellsToAffect = ExplosionCellsToHit(centerCell, map, radius);
foreach (var cellToAffect in cellsToAffect)
{
List<Thing> things = cellToAffect.GetThingList(map).Except(map.mapPawns.AllPawns).ToList();
if (Controller.settings.DebugDisplayAttritionInfo)
{
map.debugDrawer.FlashCell(cellToAffect, duration: 1000);
}
var filthMade = false;
var damageCell = (int)DamageAtRadius(shellDef, (int)centerCell.DistanceTo(cellToAffect));
for (int i = 0; i < things.Count; i++)
{
Thing thing = things[i];
if (!thing.def.useHitPoints)
{
continue;
}
thing.hitPointsInt -= damageCell * (thing.IsPlant() ? 3 : 1);
if (thing.hitPointsInt > 0)
{
if (!filthMade && Rand.Chance(0.5f))
{
ScatterDebrisUtility.ScatterFilthAroundThing(thing, map, ThingDefOf.Filth_RubbleBuilding);
filthMade = true;
}
if (Rand.Chance(0.1f))
{
FireUtility.TryStartFireIn(cellToAffect, map, Rand.Range(0.5f, 1.5f), null);
}
}
else
{
thing.DeSpawn(DestroyMode.Vanish);
thing.Destroy(DestroyMode.Vanish);
// if (thing.def.category == ThingCategory.Plant && (thing.def.plant?.IsTree ?? false))
// {
// //Todo: 1.5 burned trees
// Thing burntTree = ThingMaker.MakeThing(ThingDefOf.BurnedTree);
// burntTree.positionInt = cellToAffect;
// burntTree.SpawnSetup(map, false);
// if (!filthMade && Rand.Chance(0.5f))
// {
// ScatterDebrisUtility.ScatterFilthAroundThing(burntTree, map, ThingDefOf.Filth_Ash);
// filthMade = true;
// }
// }
if (thing.def.MakeFog)
{
map.fogGrid.Notify_FogBlockerRemoved(thing);
}
ThingDef filth = thing.def.filthLeaving ?? (Rand.Chance(0.5f) ? ThingDefOf.Filth_Ash : ThingDefOf.Filth_RubbleBuilding);
if (!filthMade && FilthMaker.TryMakeFilth(cellToAffect, map, filth, Rand.Range(1, 3), FilthSourceFlags.Any))
{
filthMade = true;
}
}
}
map.snowGrid.SetDepth(cellToAffect, 0);
map.roofGrid.SetRoof(cellToAffect, null);
if (Rand.Chance(0.33f) && map.terrainGrid.CanRemoveTopLayerAt(cellToAffect))
{
map.terrainGrid.RemoveTopLayer(cellToAffect, false);
}
}
return true;
}
protected virtual void DamageToPawns(ThingDef shellDef)
{
var projDef = shellDef.GetProjectile();
if (Rand.Chance(0.05f))
{
int countAffectedPawns = Rand.Range(1, Math.Min(map.mapPawns.AllPawnsSpawnedCount, (int)projDef.projectile.explosionRadius));
for (int affectNum = 0; affectNum < countAffectedPawns; affectNum++)
{
if (map.mapPawns.AllPawnsSpawned.Where(x => !x.Faction.IsPlayerSafe()).ToList().TryRandomElementByWeight((x => x.Faction.HostileTo(Faction.OfPlayer) ? 1f : 0.2f), out Pawn pawn))
{
DamagePawn(pawn, projDef);
}
}
}
}
protected virtual void DamagePawn(Pawn pawn, ThingDef projDef)
{
BattleLogEntry_DamageTaken battleLogEntry_DamageTaken = new BattleLogEntry_DamageTaken(pawn, CE_RulePackDefOf.DamageEvent_ShellingExplosion, null);
Find.BattleLog.Add(battleLogEntry_DamageTaken);
var num = WorldObjectDamageWorker.DamageAtRadius(projDef, Rand.Range(0, (int)projDef.projectile.explosionRadius));
DamageInfo dinfo = new DamageInfo(projDef.projectile.damageDef, (float)num, 0f, -1f, null, null, null, DamageInfo.SourceCategory.ThingOrUnknown, null, true, true);
dinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
pawn.TakeDamage(dinfo).AssociateWithLog(battleLogEntry_DamageTaken);
ResetVisualDamageEffects(pawn);
}
protected HashSet<IntVec3> addedCellsAffectedOnlyByDamage = new HashSet<IntVec3>();
public virtual IEnumerable<IntVec3> ExplosionCellsToHit(IntVec3 center, Map map, float radius, IntVec3? needLOSToCell1 = null, IntVec3? needLOSToCell2 = null, FloatRange? affectedAngle = null)
{
var roofed = center.Roofed(map);
var aboveRoofs = false;
var openCells = new List<IntVec3>();
var adjWallCells = new List<IntVec3>();
var num = GenRadial.NumCellsInRadius(radius);
for (var i = 0; i < num; i++)
{
var intVec = center + GenRadial.RadialPattern[i];
if (intVec.InBounds(map))
{
//Added code
if (aboveRoofs)
{
if ((!roofed && GenSight.LineOfSight(center, intVec, map, false, null, 0, 0))
|| !intVec.Roofed(map))
{
openCells.Add(intVec);
}
}
else if (GenSight.LineOfSight(center, intVec, map, true, null, 0, 0))
{
if (needLOSToCell1.HasValue || needLOSToCell2.HasValue)
{
bool flag = needLOSToCell1.HasValue && GenSight.LineOfSight(needLOSToCell1.Value, intVec, map, false, null, 0, 0);
bool flag2 = needLOSToCell2.HasValue && GenSight.LineOfSight(needLOSToCell2.Value, intVec, map, false, null, 0, 0);
if (!flag && !flag2)
{
continue;
}
}
openCells.Add(intVec);
}
}
}
foreach (var intVec2 in openCells)
{
if (intVec2.Walkable(map))
{
for (var k = 0; k < 4; k++)
{
var intVec3 = intVec2 + GenAdj.CardinalDirections[k];
if (intVec3.InHorDistOf(center, radius) && intVec3.InBounds(map) && !intVec3.Standable(map) && intVec3.GetEdifice(map) != null && !openCells.Contains(intVec3) && adjWallCells.Contains(intVec3))
{
adjWallCells.Add(intVec3);
}
}
}
}
return openCells.Concat(adjWallCells);
}
void ProcessFragmentsComp(ThingDef shellDef)
{
var projDef = shellDef.GetProjectile();
if (projDef.HasComp(typeof(CompFragments)))
{
var frags = projDef.GetCompProperties<CompProperties_Fragments>();
if (Rand.Chance(0.33f))
{
int countAffectedPawns = Rand.Range(1, Math.Min(map.mapPawns.AllPawnsSpawnedCount, 5));
for (int affectNum = 0; affectNum < countAffectedPawns; affectNum++)
{
if (map.mapPawns.AllPawnsSpawned.Where(x => !x.Faction.IsPlayerSafe()).ToList().TryRandomElementByWeight((x => x.Faction.HostileTo(Faction.OfPlayer) ? 1f : 0.2f), out Pawn pawn))
{
var hitsCount = Rand.Range(3, 9);
for (int i = 0; i < hitsCount; i++)
{
if (pawn.Map == null)
{
break;
}
var frag = GenSpawn.Spawn(frags.fragments.RandomElementByWeight(x => x.count).thingDef, pawn.Position, pawn.Map) as ProjectileCE;
frag.Impact(pawn);
}
ResetVisualDamageEffects(pawn);
}
}
}
}
}
public static void ResetVisualDamageEffects(Pawn pawn)
{
var draw = pawn.drawer;
(new Traverse(draw).Field("jitterer").GetValue() as JitterHandler)?.ProcessPostTickVisuals(10000);
//Todo: find renderer.graphics
//draw.renderer.graphics.flasher.lastDamageTick = -9999;
}
#endregion
}
| 0 | 0.935201 | 1 | 0.935201 | game-dev | MEDIA | 0.995056 | game-dev | 0.915205 | 1 | 0.915205 |
GreenJAB/fixed-minecraft | 3,358 | src/main/java/net/greenjab/fixedminecraft/mixin/mobs/ArmorStandEntityMixin.java | package net.greenjab.fixedminecraft.mixin.mobs;
import com.llamalad7.mixinextras.sugar.Local;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.decoration.ArmorStandEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
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.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Arrays;
@Mixin(ArmorStandEntity.class)
public abstract class ArmorStandEntityMixin extends LivingEntity {
@Shadow
public abstract void setShowArms(boolean showArms);
@Shadow
public abstract boolean shouldShowArms();
public ArmorStandEntityMixin(EntityType<? extends ArmorStandEntityMixin> entityType, World world) {
super(entityType, world);
}
@Redirect(method = "interactAt", at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;isEmpty()Z"))
private boolean injected(ItemStack instance, @Local(argsOnly = true) PlayerEntity player, @Local(ordinal = 0)ItemStack itemStack) {
if (!player.isSneaking()) {
if (itemStack.isOf(Items.STICK)) {
if (!this.shouldShowArms()) {
this.setShowArms(true);
if (!player.isCreative()) itemStack.decrement(1);
return true;
}
}
if (itemStack.isOf(Items.SHEARS)) {
if (this.shouldShowArms()) {
this.setShowArms(false);
if (!player.getAbilities().creativeMode) this.dropItem((ServerWorld) player.getEntityWorld(), Items.STICK);
if (!player.getAbilities().creativeMode) itemStack.damage(1, player);
ItemStack[] items = {this.getMainHandStack(), this.getOffHandStack()};
for (ItemStack stack : items) {
if (!stack.isEmpty()) {
this.dropStack((ServerWorld) player.getEntityWorld(), stack);
}
}
this.equipStack(EquipmentSlot.MAINHAND, Items.AIR.getDefaultStack());
this.equipStack(EquipmentSlot.OFFHAND, Items.AIR.getDefaultStack());
}
}
}
return itemStack.isEmpty();
}
@Inject(method = "interactAt", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/decoration/ArmorStandEntity;equip(Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/entity/EquipmentSlot;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;)Z"), cancellable = true)
private void notStick(PlayerEntity player, Vec3d hitPos, Hand hand, CallbackInfoReturnable<ActionResult> cir, @Local ItemStack itemStack){
if (itemStack.isOf(Items.STICK)) {
cir.setReturnValue(ActionResult.FAIL);
}
}
}
| 0 | 0.863404 | 1 | 0.863404 | game-dev | MEDIA | 0.999233 | game-dev | 0.968332 | 1 | 0.968332 |
sporchia/alttp_vt_randomizer | 1,113 | app/Region/Inverted/PalaceOfDarkness.php | <?php
namespace ALttP\Region\Inverted;
use ALttP\Region;
/**
* Palace of Darkness Region and it's Locations contained within
*/
class PalaceOfDarkness extends Region\Standard\PalaceOfDarkness
{
/**
* Initalize the requirements for Entry and Completetion of the Region as well as access to all Locations contained
* within for No Glitches
*
* @return $this
*/
public function initalize()
{
parent::initalize();
$this->can_enter = function ($locations, $items) {
return ($this->world->config('itemPlacement') !== 'basic'
|| (
($this->world->config('mode.weapons') === 'swordless'
|| $items->hasSword())
&& $items->hasHealth(7)
&& $items->hasABottle()))
&& ($this->world->getRegion('North East Dark World')->canEnter($locations, $items)
|| ($this->world->config('canOneFrameClipOW', false)
&& $this->world->getRegion('West Death Mountain')));
};
return $this;
}
}
| 0 | 0.825536 | 1 | 0.825536 | game-dev | MEDIA | 0.974991 | game-dev | 0.617954 | 1 | 0.617954 |
KoffeinFlummi/AGM | 1,171 | AGM_Core/functions/fn_isInBuilding.sqf | /*
* Author: commy2
*
* Check if the unit is in a building. Will return true if the unit is sitting in a bush.
*
* Argument:
* 0: Unit (Object)
*
* Return value:
* Is the unit in a building? (Bool)
*/
#define DISTANCE 10
private ["_unit", "_position", "_positionX", "_positionY", "_positionZ", "_intersections"];
_unit = _this select 0;
_position = eyePos _unit;
_positionX = _position select 0;
_positionY = _position select 1;
_positionZ = _position select 2;
_intersections = 0;
if (lineIntersects [_position, [_positionX, _positionY, _positionZ + DISTANCE]]) then {
_intersections = _intersections + 1;
};
if (lineIntersects [_position, [_positionX + DISTANCE, _positionY, _positionZ]]) then {
_intersections = _intersections + 1;
};
if (lineIntersects [_position, [_positionX - DISTANCE, _positionY, _positionZ]]) then {
_intersections = _intersections + 1;
};
if (lineIntersects [_position, [_positionX, _positionY + DISTANCE, _positionZ]]) then {
_intersections = _intersections + 1;
};
if (lineIntersects [_position, [_positionX, _positionY - DISTANCE, _positionZ]]) then {
_intersections = _intersections + 1;
};
_intersections > 3
| 0 | 0.779611 | 1 | 0.779611 | game-dev | MEDIA | 0.899696 | game-dev | 0.821188 | 1 | 0.821188 |
iortcw/iortcw | 15,254 | SP/code/SDL2/include/SDL_scancode.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_scancode.h
*
* Defines keyboard scancodes.
*/
#ifndef SDL_scancode_h_
#define SDL_scancode_h_
#include "SDL_stdinc.h"
/**
* \brief The SDL keyboard scancode representation.
*
* Values of this type are used to represent keyboard keys, among other places
* in the \link SDL_Keysym::scancode key.keysym.scancode \endlink field of the
* SDL_Event structure.
*
* The values in this enumeration are based on the USB usage page standard:
* https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
*/
typedef enum
{
SDL_SCANCODE_UNKNOWN = 0,
/**
* \name Usage page 0x07
*
* These values are from usage page 0x07 (USB keyboard page).
*/
/* @{ */
SDL_SCANCODE_A = 4,
SDL_SCANCODE_B = 5,
SDL_SCANCODE_C = 6,
SDL_SCANCODE_D = 7,
SDL_SCANCODE_E = 8,
SDL_SCANCODE_F = 9,
SDL_SCANCODE_G = 10,
SDL_SCANCODE_H = 11,
SDL_SCANCODE_I = 12,
SDL_SCANCODE_J = 13,
SDL_SCANCODE_K = 14,
SDL_SCANCODE_L = 15,
SDL_SCANCODE_M = 16,
SDL_SCANCODE_N = 17,
SDL_SCANCODE_O = 18,
SDL_SCANCODE_P = 19,
SDL_SCANCODE_Q = 20,
SDL_SCANCODE_R = 21,
SDL_SCANCODE_S = 22,
SDL_SCANCODE_T = 23,
SDL_SCANCODE_U = 24,
SDL_SCANCODE_V = 25,
SDL_SCANCODE_W = 26,
SDL_SCANCODE_X = 27,
SDL_SCANCODE_Y = 28,
SDL_SCANCODE_Z = 29,
SDL_SCANCODE_1 = 30,
SDL_SCANCODE_2 = 31,
SDL_SCANCODE_3 = 32,
SDL_SCANCODE_4 = 33,
SDL_SCANCODE_5 = 34,
SDL_SCANCODE_6 = 35,
SDL_SCANCODE_7 = 36,
SDL_SCANCODE_8 = 37,
SDL_SCANCODE_9 = 38,
SDL_SCANCODE_0 = 39,
SDL_SCANCODE_RETURN = 40,
SDL_SCANCODE_ESCAPE = 41,
SDL_SCANCODE_BACKSPACE = 42,
SDL_SCANCODE_TAB = 43,
SDL_SCANCODE_SPACE = 44,
SDL_SCANCODE_MINUS = 45,
SDL_SCANCODE_EQUALS = 46,
SDL_SCANCODE_LEFTBRACKET = 47,
SDL_SCANCODE_RIGHTBRACKET = 48,
SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return
* key on ISO keyboards and at the right end
* of the QWERTY row on ANSI keyboards.
* Produces REVERSE SOLIDUS (backslash) and
* VERTICAL LINE in a US layout, REVERSE
* SOLIDUS and VERTICAL LINE in a UK Mac
* layout, NUMBER SIGN and TILDE in a UK
* Windows layout, DOLLAR SIGN and POUND SIGN
* in a Swiss German layout, NUMBER SIGN and
* APOSTROPHE in a German layout, GRAVE
* ACCENT and POUND SIGN in a French Mac
* layout, and ASTERISK and MICRO SIGN in a
* French Windows layout.
*/
SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code
* instead of 49 for the same key, but all
* OSes I've seen treat the two codes
* identically. So, as an implementor, unless
* your keyboard generates both of those
* codes and your OS treats them differently,
* you should generate SDL_SCANCODE_BACKSLASH
* instead of this code. As a user, you
* should not rely on this code because SDL
* will never generate it with most (all?)
* keyboards.
*/
SDL_SCANCODE_SEMICOLON = 51,
SDL_SCANCODE_APOSTROPHE = 52,
SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI
* and ISO keyboards). Produces GRAVE ACCENT and
* TILDE in a US Windows layout and in US and UK
* Mac layouts on ANSI keyboards, GRAVE ACCENT
* and NOT SIGN in a UK Windows layout, SECTION
* SIGN and PLUS-MINUS SIGN in US and UK Mac
* layouts on ISO keyboards, SECTION SIGN and
* DEGREE SIGN in a Swiss German layout (Mac:
* only on ISO keyboards), CIRCUMFLEX ACCENT and
* DEGREE SIGN in a German layout (Mac: only on
* ISO keyboards), SUPERSCRIPT TWO and TILDE in a
* French Windows layout, COMMERCIAL AT and
* NUMBER SIGN in a French Mac layout on ISO
* keyboards, and LESS-THAN SIGN and GREATER-THAN
* SIGN in a Swiss German, German, or French Mac
* layout on ANSI keyboards.
*/
SDL_SCANCODE_COMMA = 54,
SDL_SCANCODE_PERIOD = 55,
SDL_SCANCODE_SLASH = 56,
SDL_SCANCODE_CAPSLOCK = 57,
SDL_SCANCODE_F1 = 58,
SDL_SCANCODE_F2 = 59,
SDL_SCANCODE_F3 = 60,
SDL_SCANCODE_F4 = 61,
SDL_SCANCODE_F5 = 62,
SDL_SCANCODE_F6 = 63,
SDL_SCANCODE_F7 = 64,
SDL_SCANCODE_F8 = 65,
SDL_SCANCODE_F9 = 66,
SDL_SCANCODE_F10 = 67,
SDL_SCANCODE_F11 = 68,
SDL_SCANCODE_F12 = 69,
SDL_SCANCODE_PRINTSCREEN = 70,
SDL_SCANCODE_SCROLLLOCK = 71,
SDL_SCANCODE_PAUSE = 72,
SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but
does send code 73, not 117) */
SDL_SCANCODE_HOME = 74,
SDL_SCANCODE_PAGEUP = 75,
SDL_SCANCODE_DELETE = 76,
SDL_SCANCODE_END = 77,
SDL_SCANCODE_PAGEDOWN = 78,
SDL_SCANCODE_RIGHT = 79,
SDL_SCANCODE_LEFT = 80,
SDL_SCANCODE_DOWN = 81,
SDL_SCANCODE_UP = 82,
SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards
*/
SDL_SCANCODE_KP_DIVIDE = 84,
SDL_SCANCODE_KP_MULTIPLY = 85,
SDL_SCANCODE_KP_MINUS = 86,
SDL_SCANCODE_KP_PLUS = 87,
SDL_SCANCODE_KP_ENTER = 88,
SDL_SCANCODE_KP_1 = 89,
SDL_SCANCODE_KP_2 = 90,
SDL_SCANCODE_KP_3 = 91,
SDL_SCANCODE_KP_4 = 92,
SDL_SCANCODE_KP_5 = 93,
SDL_SCANCODE_KP_6 = 94,
SDL_SCANCODE_KP_7 = 95,
SDL_SCANCODE_KP_8 = 96,
SDL_SCANCODE_KP_9 = 97,
SDL_SCANCODE_KP_0 = 98,
SDL_SCANCODE_KP_PERIOD = 99,
SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO
* keyboards have over ANSI ones,
* located between left shift and Y.
* Produces GRAVE ACCENT and TILDE in a
* US or UK Mac layout, REVERSE SOLIDUS
* (backslash) and VERTICAL LINE in a
* US or UK Windows layout, and
* LESS-THAN SIGN and GREATER-THAN SIGN
* in a Swiss German, German, or French
* layout. */
SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */
SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag,
* not a physical key - but some Mac keyboards
* do have a power key. */
SDL_SCANCODE_KP_EQUALS = 103,
SDL_SCANCODE_F13 = 104,
SDL_SCANCODE_F14 = 105,
SDL_SCANCODE_F15 = 106,
SDL_SCANCODE_F16 = 107,
SDL_SCANCODE_F17 = 108,
SDL_SCANCODE_F18 = 109,
SDL_SCANCODE_F19 = 110,
SDL_SCANCODE_F20 = 111,
SDL_SCANCODE_F21 = 112,
SDL_SCANCODE_F22 = 113,
SDL_SCANCODE_F23 = 114,
SDL_SCANCODE_F24 = 115,
SDL_SCANCODE_EXECUTE = 116,
SDL_SCANCODE_HELP = 117,
SDL_SCANCODE_MENU = 118,
SDL_SCANCODE_SELECT = 119,
SDL_SCANCODE_STOP = 120,
SDL_SCANCODE_AGAIN = 121, /**< redo */
SDL_SCANCODE_UNDO = 122,
SDL_SCANCODE_CUT = 123,
SDL_SCANCODE_COPY = 124,
SDL_SCANCODE_PASTE = 125,
SDL_SCANCODE_FIND = 126,
SDL_SCANCODE_MUTE = 127,
SDL_SCANCODE_VOLUMEUP = 128,
SDL_SCANCODE_VOLUMEDOWN = 129,
/* not sure whether there's a reason to enable these */
/* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */
/* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */
/* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */
SDL_SCANCODE_KP_COMMA = 133,
SDL_SCANCODE_KP_EQUALSAS400 = 134,
SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see
footnotes in USB doc */
SDL_SCANCODE_INTERNATIONAL2 = 136,
SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */
SDL_SCANCODE_INTERNATIONAL4 = 138,
SDL_SCANCODE_INTERNATIONAL5 = 139,
SDL_SCANCODE_INTERNATIONAL6 = 140,
SDL_SCANCODE_INTERNATIONAL7 = 141,
SDL_SCANCODE_INTERNATIONAL8 = 142,
SDL_SCANCODE_INTERNATIONAL9 = 143,
SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */
SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */
SDL_SCANCODE_LANG3 = 146, /**< Katakana */
SDL_SCANCODE_LANG4 = 147, /**< Hiragana */
SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */
SDL_SCANCODE_LANG6 = 149, /**< reserved */
SDL_SCANCODE_LANG7 = 150, /**< reserved */
SDL_SCANCODE_LANG8 = 151, /**< reserved */
SDL_SCANCODE_LANG9 = 152, /**< reserved */
SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */
SDL_SCANCODE_SYSREQ = 154,
SDL_SCANCODE_CANCEL = 155,
SDL_SCANCODE_CLEAR = 156,
SDL_SCANCODE_PRIOR = 157,
SDL_SCANCODE_RETURN2 = 158,
SDL_SCANCODE_SEPARATOR = 159,
SDL_SCANCODE_OUT = 160,
SDL_SCANCODE_OPER = 161,
SDL_SCANCODE_CLEARAGAIN = 162,
SDL_SCANCODE_CRSEL = 163,
SDL_SCANCODE_EXSEL = 164,
SDL_SCANCODE_KP_00 = 176,
SDL_SCANCODE_KP_000 = 177,
SDL_SCANCODE_THOUSANDSSEPARATOR = 178,
SDL_SCANCODE_DECIMALSEPARATOR = 179,
SDL_SCANCODE_CURRENCYUNIT = 180,
SDL_SCANCODE_CURRENCYSUBUNIT = 181,
SDL_SCANCODE_KP_LEFTPAREN = 182,
SDL_SCANCODE_KP_RIGHTPAREN = 183,
SDL_SCANCODE_KP_LEFTBRACE = 184,
SDL_SCANCODE_KP_RIGHTBRACE = 185,
SDL_SCANCODE_KP_TAB = 186,
SDL_SCANCODE_KP_BACKSPACE = 187,
SDL_SCANCODE_KP_A = 188,
SDL_SCANCODE_KP_B = 189,
SDL_SCANCODE_KP_C = 190,
SDL_SCANCODE_KP_D = 191,
SDL_SCANCODE_KP_E = 192,
SDL_SCANCODE_KP_F = 193,
SDL_SCANCODE_KP_XOR = 194,
SDL_SCANCODE_KP_POWER = 195,
SDL_SCANCODE_KP_PERCENT = 196,
SDL_SCANCODE_KP_LESS = 197,
SDL_SCANCODE_KP_GREATER = 198,
SDL_SCANCODE_KP_AMPERSAND = 199,
SDL_SCANCODE_KP_DBLAMPERSAND = 200,
SDL_SCANCODE_KP_VERTICALBAR = 201,
SDL_SCANCODE_KP_DBLVERTICALBAR = 202,
SDL_SCANCODE_KP_COLON = 203,
SDL_SCANCODE_KP_HASH = 204,
SDL_SCANCODE_KP_SPACE = 205,
SDL_SCANCODE_KP_AT = 206,
SDL_SCANCODE_KP_EXCLAM = 207,
SDL_SCANCODE_KP_MEMSTORE = 208,
SDL_SCANCODE_KP_MEMRECALL = 209,
SDL_SCANCODE_KP_MEMCLEAR = 210,
SDL_SCANCODE_KP_MEMADD = 211,
SDL_SCANCODE_KP_MEMSUBTRACT = 212,
SDL_SCANCODE_KP_MEMMULTIPLY = 213,
SDL_SCANCODE_KP_MEMDIVIDE = 214,
SDL_SCANCODE_KP_PLUSMINUS = 215,
SDL_SCANCODE_KP_CLEAR = 216,
SDL_SCANCODE_KP_CLEARENTRY = 217,
SDL_SCANCODE_KP_BINARY = 218,
SDL_SCANCODE_KP_OCTAL = 219,
SDL_SCANCODE_KP_DECIMAL = 220,
SDL_SCANCODE_KP_HEXADECIMAL = 221,
SDL_SCANCODE_LCTRL = 224,
SDL_SCANCODE_LSHIFT = 225,
SDL_SCANCODE_LALT = 226, /**< alt, option */
SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */
SDL_SCANCODE_RCTRL = 228,
SDL_SCANCODE_RSHIFT = 229,
SDL_SCANCODE_RALT = 230, /**< alt gr, option */
SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */
SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered
* by any of the above, but since there's a
* special KMOD_MODE for it I'm adding it here
*/
/* @} *//* Usage page 0x07 */
/**
* \name Usage page 0x0C
*
* These values are mapped from usage page 0x0C (USB consumer page).
*/
/* @{ */
SDL_SCANCODE_AUDIONEXT = 258,
SDL_SCANCODE_AUDIOPREV = 259,
SDL_SCANCODE_AUDIOSTOP = 260,
SDL_SCANCODE_AUDIOPLAY = 261,
SDL_SCANCODE_AUDIOMUTE = 262,
SDL_SCANCODE_MEDIASELECT = 263,
SDL_SCANCODE_WWW = 264,
SDL_SCANCODE_MAIL = 265,
SDL_SCANCODE_CALCULATOR = 266,
SDL_SCANCODE_COMPUTER = 267,
SDL_SCANCODE_AC_SEARCH = 268,
SDL_SCANCODE_AC_HOME = 269,
SDL_SCANCODE_AC_BACK = 270,
SDL_SCANCODE_AC_FORWARD = 271,
SDL_SCANCODE_AC_STOP = 272,
SDL_SCANCODE_AC_REFRESH = 273,
SDL_SCANCODE_AC_BOOKMARKS = 274,
/* @} *//* Usage page 0x0C */
/**
* \name Walther keys
*
* These are values that Christian Walther added (for mac keyboard?).
*/
/* @{ */
SDL_SCANCODE_BRIGHTNESSDOWN = 275,
SDL_SCANCODE_BRIGHTNESSUP = 276,
SDL_SCANCODE_DISPLAYSWITCH = 277, /**< display mirroring/dual display
switch, video mode switch */
SDL_SCANCODE_KBDILLUMTOGGLE = 278,
SDL_SCANCODE_KBDILLUMDOWN = 279,
SDL_SCANCODE_KBDILLUMUP = 280,
SDL_SCANCODE_EJECT = 281,
SDL_SCANCODE_SLEEP = 282,
SDL_SCANCODE_APP1 = 283,
SDL_SCANCODE_APP2 = 284,
/* @} *//* Walther keys */
/**
* \name Usage page 0x0C (additional media keys)
*
* These values are mapped from usage page 0x0C (USB consumer page).
*/
/* @{ */
SDL_SCANCODE_AUDIOREWIND = 285,
SDL_SCANCODE_AUDIOFASTFORWARD = 286,
/* @} *//* Usage page 0x0C (additional media keys) */
/* Add any other keys here. */
SDL_NUM_SCANCODES = 512 /**< not a key, just marks the number of scancodes
for array bounds */
} SDL_Scancode;
#endif /* SDL_scancode_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.74946 | 1 | 0.74946 | game-dev | MEDIA | 0.46433 | game-dev | 0.568029 | 1 | 0.568029 |
ServUO/ServUO | 19,265 | Ultima/Art.cs | #region References
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Security.Cryptography;
#endregion
namespace Ultima
{
public sealed class Art
{
private static FileIndex m_FileIndex = new FileIndex(
"Artidx.mul", "Art.mul", "artLegacyMUL.uop", 0x10000 /*0x13FDC*/, 4, ".tga", 0x13FDC, false);
private static Bitmap[] m_Cache;
private static bool[] m_Removed;
private static readonly Hashtable m_patched = new Hashtable();
public static bool Modified = false;
private static byte[] m_StreamBuffer;
private static byte[] Validbuffer;
private struct CheckSums
{
public byte[] checksum;
public int pos;
public int length;
public int index;
}
private static List<CheckSums> checksumsLand;
private static List<CheckSums> checksumsStatic;
static Art()
{
m_Cache = new Bitmap[0xFFFF];
m_Removed = new bool[0xFFFF];
}
public static int GetMaxItemID()
{
if (GetIdxLength() >= 0x13FDC)
{
return 0xFFFF;
}
if (GetIdxLength() == 0xC000)
{
return 0x7FFF;
}
return 0x3FFF;
}
public static bool IsUOAHS()
{
return (GetIdxLength() >= 0x13FDC);
}
public static ushort GetLegalItemID(int itemID, bool checkmaxid = true)
{
if (itemID < 0)
{
return 0;
}
if (checkmaxid)
{
int max = GetMaxItemID();
if (itemID > max)
{
return 0;
}
}
return (ushort)itemID;
}
public static int GetIdxLength()
{
return (int)(m_FileIndex.IdxLength / 12);
}
/// <summary>
/// ReReads Art.mul
/// </summary>
public static void Reload()
{
m_FileIndex = new FileIndex(
"Artidx.mul", "Art.mul", "artLegacyMUL.uop", 0x10000 /*0x13FDC*/, 4, ".tga", 0x13FDC, false);
m_Cache = new Bitmap[0xFFFF];
m_Removed = new bool[0xFFFF];
m_patched.Clear();
Modified = false;
}
/// <summary>
/// Sets bmp of index in <see cref="m_Cache" /> of Static
/// </summary>
/// <param name="index"></param>
/// <param name="bmp"></param>
public static void ReplaceStatic(int index, Bitmap bmp)
{
index = GetLegalItemID(index);
index += 0x4000;
m_Cache[index] = bmp;
m_Removed[index] = false;
if (m_patched.Contains(index))
{
m_patched.Remove(index);
}
Modified = true;
}
/// <summary>
/// Sets bmp of index in <see cref="m_Cache" /> of Land
/// </summary>
/// <param name="index"></param>
/// <param name="bmp"></param>
public static void ReplaceLand(int index, Bitmap bmp)
{
index &= 0x3FFF;
m_Cache[index] = bmp;
m_Removed[index] = false;
if (m_patched.Contains(index))
{
m_patched.Remove(index);
}
Modified = true;
}
/// <summary>
/// Removes Static index <see cref="m_Removed" />
/// </summary>
/// <param name="index"></param>
public static void RemoveStatic(int index)
{
index = GetLegalItemID(index);
index += 0x4000;
m_Removed[index] = true;
Modified = true;
}
/// <summary>
/// Removes Land index <see cref="m_Removed" />
/// </summary>
/// <param name="index"></param>
public static void RemoveLand(int index)
{
index &= 0x3FFF;
m_Removed[index] = true;
Modified = true;
}
/// <summary>
/// Tests if Static is definied (width and hight check)
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static unsafe bool IsValidStatic(int index)
{
index = GetLegalItemID(index);
index += 0x4000;
if (m_Removed[index])
{
return false;
}
if (m_Cache[index] != null)
{
return true;
}
int length, extra;
bool patched;
Stream stream = m_FileIndex.Seek(index, out length, out extra, out patched);
if (stream == null)
{
return false;
}
if (Validbuffer == null)
{
Validbuffer = new byte[4];
}
stream.Seek(4, SeekOrigin.Current);
stream.Read(Validbuffer, 0, 4);
fixed (byte* b = Validbuffer)
{
var dat = (short*)b;
if (*dat++ <= 0 || *dat <= 0)
{
return false;
}
return true;
}
}
/// <summary>
/// Tests if LandTile is definied
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static bool IsValidLand(int index)
{
index &= 0x3FFF;
if (m_Removed[index])
{
return false;
}
if (m_Cache[index] != null)
{
return true;
}
int length, extra;
bool patched;
return m_FileIndex.Valid(index, out length, out extra, out patched);
}
/// <summary>
/// Returns Bitmap of LandTile (with Cache)
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static Bitmap GetLand(int index)
{
bool patched;
return GetLand(index, out patched);
}
/// <summary>
/// Returns Bitmap of LandTile (with Cache) and verdata bool
/// </summary>
/// <param name="index"></param>
/// <param name="patched"></param>
/// <returns></returns>
public static Bitmap GetLand(int index, out bool patched)
{
index &= 0x3FFF;
if (m_patched.Contains(index))
{
patched = (bool)m_patched[index];
}
else
{
patched = false;
}
if (m_Removed[index])
{
return null;
}
if (m_Cache[index] != null)
{
return m_Cache[index];
}
int length, extra;
Stream stream = m_FileIndex.Seek(index, out length, out extra, out patched);
if (stream == null)
{
return null;
}
if (patched)
{
m_patched[index] = true;
}
if (Files.CacheData)
{
return m_Cache[index] = LoadLand(stream, length);
}
else
{
return LoadLand(stream, length);
}
}
public static byte[] GetRawLand(int index)
{
index &= 0x3FFF;
int length, extra;
bool patched;
Stream stream = m_FileIndex.Seek(index, out length, out extra, out patched);
if (stream == null)
{
return null;
}
var buffer = new byte[length];
stream.Read(buffer, 0, length);
stream.Close();
return buffer;
}
/// <summary>
/// Returns Bitmap of Static (with Cache)
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static Bitmap GetStatic(int index, bool checkmaxid = true)
{
bool patched;
return GetStatic(index, out patched, checkmaxid);
}
/// <summary>
/// Returns Bitmap of Static (with Cache) and verdata bool
/// </summary>
/// <param name="index"></param>
/// <param name="patched"></param>
/// <returns></returns>
public static Bitmap GetStatic(int index, out bool patched, bool checkmaxid = true)
{
index = GetLegalItemID(index, checkmaxid);
index += 0x4000;
if (m_patched.Contains(index))
{
patched = (bool)m_patched[index];
}
else
{
patched = false;
}
if (m_Removed[index])
{
return null;
}
if (m_Cache[index] != null)
{
return m_Cache[index];
}
int length, extra;
Stream stream = m_FileIndex.Seek(index, out length, out extra, out patched);
if (stream == null)
{
return null;
}
if (patched)
{
m_patched[index] = true;
}
if (Files.CacheData)
{
return m_Cache[index] = LoadStatic(stream, length);
}
else
{
return LoadStatic(stream, length);
}
}
public static byte[] GetRawStatic(int index)
{
index = GetLegalItemID(index);
index += 0x4000;
int length, extra;
bool patched;
Stream stream = m_FileIndex.Seek(index, out length, out extra, out patched);
if (stream == null)
{
return null;
}
var buffer = new byte[length];
stream.Read(buffer, 0, length);
stream.Close();
return buffer;
}
public static unsafe void Measure(Bitmap bmp, out int xMin, out int yMin, out int xMax, out int yMax)
{
xMin = yMin = 0;
xMax = yMax = -1;
if (bmp == null || bmp.Width <= 0 || bmp.Height <= 0)
{
return;
}
BitmapData bd = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, Settings.PixelFormat);
int delta = (bd.Stride >> 1) - bd.Width;
int lineDelta = bd.Stride >> 1;
var pBuffer = (ushort*)bd.Scan0;
ushort* pLineEnd = pBuffer + bd.Width;
ushort* pEnd = pBuffer + (bd.Height * lineDelta);
bool foundPixel = false;
int x = 0, y = 0;
while (pBuffer < pEnd)
{
while (pBuffer < pLineEnd)
{
ushort c = *pBuffer++;
if ((c & 0x8000) != 0)
{
if (!foundPixel)
{
foundPixel = true;
xMin = xMax = x;
yMin = yMax = y;
}
else
{
if (x < xMin)
{
xMin = x;
}
if (y < yMin)
{
yMin = y;
}
if (x > xMax)
{
xMax = x;
}
if (y > yMax)
{
yMax = y;
}
}
}
++x;
}
pBuffer += delta;
pLineEnd += lineDelta;
++y;
x = 0;
}
bmp.UnlockBits(bd);
}
private static unsafe Bitmap LoadStatic(Stream stream, int length)
{
Bitmap bmp;
if (m_StreamBuffer == null || m_StreamBuffer.Length < length)
{
m_StreamBuffer = new byte[length];
}
stream.Read(m_StreamBuffer, 0, length);
stream.Close();
fixed (byte* data = m_StreamBuffer)
{
var bindata = (ushort*)data;
int count = 2;
//bin.ReadInt32();
int width = bindata[count++];
int height = bindata[count++];
if (width <= 0 || height <= 0)
{
return null;
}
var lookups = new int[height];
int start = (height + 4);
for (int i = 0; i < height; ++i)
{
lookups[i] = (start + (bindata[count++]));
}
bmp = new Bitmap(width, height, Settings.PixelFormat);
BitmapData bd = bmp.LockBits(
new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, Settings.PixelFormat);
var line = (ushort*)bd.Scan0;
int delta = bd.Stride >> 1;
for (int y = 0; y < height; ++y, line += delta)
{
count = lookups[y];
ushort* cur = line;
ushort* end;
int xOffset, xRun;
while (((xOffset = bindata[count++]) + (xRun = bindata[count++])) != 0)
{
if (xOffset > delta)
{
break;
}
cur += xOffset;
if (xOffset + xRun > delta)
{
break;
}
end = cur + xRun;
while (cur < end)
{
*cur++ = (ushort)(bindata[count++] ^ 0x8000);
}
}
}
bmp.UnlockBits(bd);
}
return bmp;
}
private static unsafe Bitmap LoadLand(Stream stream, int length)
{
var bmp = new Bitmap(44, 44, Settings.PixelFormat);
BitmapData bd = bmp.LockBits(new Rectangle(0, 0, 44, 44), ImageLockMode.WriteOnly, Settings.PixelFormat);
if (m_StreamBuffer == null || m_StreamBuffer.Length < length)
{
m_StreamBuffer = new byte[length];
}
stream.Read(m_StreamBuffer, 0, length);
stream.Close();
fixed (byte* bindata = m_StreamBuffer)
{
var bdata = (ushort*)bindata;
int xOffset = 21;
int xRun = 2;
var line = (ushort*)bd.Scan0;
int delta = bd.Stride >> 1;
for (int y = 0; y < 22; ++y, --xOffset, xRun += 2, line += delta)
{
ushort* cur = line + xOffset;
ushort* end = cur + xRun;
while (cur < end)
{
*cur++ = (ushort)(*bdata++ | 0x8000);
}
}
xOffset = 0;
xRun = 44;
for (int y = 0; y < 22; ++y, ++xOffset, xRun -= 2, line += delta)
{
ushort* cur = line + xOffset;
ushort* end = cur + xRun;
while (cur < end)
{
*cur++ = (ushort)(*bdata++ | 0x8000);
}
}
}
bmp.UnlockBits(bd);
return bmp;
}
/// <summary>
/// Saves mul
/// </summary>
/// <param name="path"></param>
public static unsafe void Save(string path)
{
checksumsLand = new List<CheckSums>();
checksumsStatic = new List<CheckSums>();
string idx = Path.Combine(path, "artidx.mul");
string mul = Path.Combine(path, "art.mul");
using (
FileStream fsidx = new FileStream(idx, FileMode.Create, FileAccess.Write, FileShare.Write),
fsmul = new FileStream(mul, FileMode.Create, FileAccess.Write, FileShare.Write))
{
var memidx = new MemoryStream();
var memmul = new MemoryStream();
var sha = new SHA256Managed();
//StreamWriter Tex = new StreamWriter(new FileStream("d:/artlog.txt", FileMode.Create, FileAccess.ReadWrite));
using (BinaryWriter binidx = new BinaryWriter(memidx), binmul = new BinaryWriter(memmul))
{
for (int index = 0; index < GetIdxLength(); index++)
{
Files.FireFileSaveEvent();
if (m_Cache[index] == null)
{
if (index < 0x4000)
{
m_Cache[index] = GetLand(index);
}
else
{
m_Cache[index] = GetStatic(index - 0x4000, false);
}
}
Bitmap bmp = m_Cache[index];
if ((bmp == null) || (m_Removed[index]))
{
binidx.Write(-1); // lookup
binidx.Write(0); // length
binidx.Write(-1); // extra
//Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, (int)-1, (int)-1));
}
else if (index < 0x4000)
{
var ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
byte[] checksum = sha.ComputeHash(ms.ToArray());
CheckSums sum;
if (compareSaveImagesLand(checksum, out sum))
{
binidx.Write(sum.pos); //lookup
binidx.Write(sum.length);
binidx.Write(0);
//Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, (int)sum.pos, (int)sum.length));
//Tex.WriteLine(System.String.Format("0x{0:X4} -> 0x{1:X4}", sum.index, index));
continue;
}
//land
BitmapData bd = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, Settings.PixelFormat);
var line = (ushort*)bd.Scan0;
int delta = bd.Stride >> 1;
binidx.Write((int)binmul.BaseStream.Position); //lookup
var length = (int)binmul.BaseStream.Position;
int x = 22;
int y = 0;
int linewidth = 2;
for (int m = 0; m < 22; ++m, ++y, line += delta, linewidth += 2)
{
--x;
ushort* cur = line;
for (int n = 0; n < linewidth; ++n)
{
binmul.Write((ushort)(cur[x + n] ^ 0x8000));
}
}
x = 0;
linewidth = 44;
y = 22;
line = (ushort*)bd.Scan0;
line += delta * 22;
for (int m = 0; m < 22; m++, y++, line += delta, ++x, linewidth -= 2)
{
ushort* cur = line;
for (int n = 0; n < linewidth; n++)
{
binmul.Write((ushort)(cur[x + n] ^ 0x8000));
}
}
int start = length;
length = (int)binmul.BaseStream.Position - length;
binidx.Write(length);
binidx.Write(0);
bmp.UnlockBits(bd);
var s = new CheckSums
{
pos = start,
length = length,
checksum = checksum,
index = index
};
//Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, start, length));
checksumsLand.Add(s);
}
else
{
var ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
byte[] checksum = sha.ComputeHash(ms.ToArray());
CheckSums sum;
if (compareSaveImagesStatic(checksum, out sum))
{
binidx.Write(sum.pos); //lookup
binidx.Write(sum.length);
binidx.Write(0);
//Tex.WriteLine(System.String.Format("0x{0:X4} -> 0x{1:X4}", sum.index, index));
//Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, sum.pos, sum.length));
continue;
}
// art
BitmapData bd = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, Settings.PixelFormat);
var line = (ushort*)bd.Scan0;
int delta = bd.Stride >> 1;
binidx.Write((int)binmul.BaseStream.Position); //lookup
var length = (int)binmul.BaseStream.Position;
binmul.Write(1234); // header
binmul.Write((short)bmp.Width);
binmul.Write((short)bmp.Height);
var lookup = (int)binmul.BaseStream.Position;
int streamloc = lookup + bmp.Height * 2;
int width = 0;
for (int i = 0; i < bmp.Height; ++i) // fill lookup
{
binmul.Write(width);
}
int X = 0;
for (int Y = 0; Y < bmp.Height; ++Y, line += delta)
{
ushort* cur = line;
width = (int)(binmul.BaseStream.Position - streamloc) / 2;
binmul.BaseStream.Seek(lookup + Y * 2, SeekOrigin.Begin);
binmul.Write(width);
binmul.BaseStream.Seek(streamloc + width * 2, SeekOrigin.Begin);
int i = 0;
int j = 0;
X = 0;
while (i < bmp.Width)
{
i = X;
for (i = X; i <= bmp.Width; ++i)
{
//first pixel set
if (i < bmp.Width)
{
if (cur[i] != 0)
{
break;
}
}
}
if (i < bmp.Width)
{
for (j = (i + 1); j < bmp.Width; ++j)
{
//next non set pixel
if (cur[j] == 0)
{
break;
}
}
binmul.Write((short)(i - X)); //xoffset
binmul.Write((short)(j - i)); //run
for (int p = i; p < j; ++p)
{
binmul.Write((ushort)(cur[p] ^ 0x8000));
}
X = j;
}
}
binmul.Write((short)0); //xOffset
binmul.Write((short)0); //Run
}
int start = length;
length = (int)binmul.BaseStream.Position - length;
binidx.Write(length);
binidx.Write(0);
bmp.UnlockBits(bd);
var s = new CheckSums
{
pos = start,
length = length,
checksum = checksum,
index = index
};
//Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, start, length));
checksumsStatic.Add(s);
}
}
memidx.WriteTo(fsidx);
memmul.WriteTo(fsmul);
}
}
}
private static bool compareSaveImagesLand(byte[] newchecksum, out CheckSums sum)
{
sum = new CheckSums();
for (int i = 0; i < checksumsLand.Count; ++i)
{
byte[] cmp = checksumsLand[i].checksum;
if (((cmp == null) || (newchecksum == null)) || (cmp.Length != newchecksum.Length))
{
return false;
}
bool valid = true;
for (int j = 0; j < cmp.Length; ++j)
{
if (cmp[j] != newchecksum[j])
{
valid = false;
break;
}
}
if (valid)
{
sum = checksumsLand[i];
return true;
}
}
return false;
}
private static bool compareSaveImagesStatic(byte[] newchecksum, out CheckSums sum)
{
sum = new CheckSums();
for (int i = 0; i < checksumsStatic.Count; ++i)
{
byte[] cmp = checksumsStatic[i].checksum;
if (((cmp == null) || (newchecksum == null)) || (cmp.Length != newchecksum.Length))
{
return false;
}
bool valid = true;
for (int j = 0; j < cmp.Length; ++j)
{
if (cmp[j] != newchecksum[j])
{
valid = false;
break;
}
}
if (valid)
{
sum = checksumsStatic[i];
return true;
}
}
return false;
}
}
} | 0 | 0.951947 | 1 | 0.951947 | game-dev | MEDIA | 0.292928 | game-dev | 0.964751 | 1 | 0.964751 |
BuildCraft/BuildCraft | 3,434 | src_old_license/buildcraft/transport/pluggable/PlugPluggable.java | package buildcraft.transport.pluggable;
import io.netty.buffer.ByteBuf;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import buildcraft.BuildCraftTransport;
import buildcraft.api.transport.IPipeTile;
import buildcraft.api.transport.pluggable.PipePluggable;
import buildcraft.core.lib.utils.MatrixTranformations;
import buildcraft.transport.client.model.ModelKeyPlug;
public class PlugPluggable extends PipePluggable {
public enum Material {
COBBLESTONE(0);
public final int id;
public static final TIntObjectMap<Material> ID_MAP = new TIntObjectHashMap<>();
Material(int id) {
this.id = id;
}
}
static {
for (Material m : Material.values()) {
Material.ID_MAP.put(m.id, m);
}
}
private Material material;
public PlugPluggable() {
material = Material.COBBLESTONE;
}
public PlugPluggable(int id) {
super();
material = Material.ID_MAP.get(id);
if (material == null) {
material = Material.COBBLESTONE;
}
}
public PlugPluggable(Material material) {
this.material = material;
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
nbt.setByte("id", (byte) material.id);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
int id = nbt.hasKey("id") ? nbt.getByte("id") : 0;
material = Material.ID_MAP.get(id);
if (material == null) {
material = Material.COBBLESTONE;
}
}
@Override
public ItemStack[] getDropItems(IPipeTile pipe) {
return new ItemStack[] { new ItemStack(BuildCraftTransport.plugItem, 1, material.id) };
}
@Override
public boolean isBlocking(IPipeTile pipe, EnumFacing direction) {
return true;
}
@Override
public AxisAlignedBB getBoundingBox(EnumFacing side) {
float[][] bounds = new float[3][2];
// X START - END
bounds[0][0] = 0.25F;
bounds[0][1] = 0.75F;
// Y START - END
bounds[1][0] = 0.125F;
bounds[1][1] = 0.251F;
// Z START - END
bounds[2][0] = 0.25F;
bounds[2][1] = 0.75F;
MatrixTranformations.transform(bounds, side);
return new AxisAlignedBB(bounds[0][0], bounds[1][0], bounds[2][0], bounds[0][1], bounds[1][1], bounds[2][1]);
}
@Override
@SideOnly(Side.CLIENT)
public ModelKeyPlug getModelRenderKey(EnumWorldBlockLayer layer, EnumFacing side) {
if (layer == EnumWorldBlockLayer.CUTOUT) {
return new ModelKeyPlug(side, material);
}
return null;
}
@Override
public void writeData(ByteBuf data) {
data.writeByte(material.id);
}
@Override
public void readData(ByteBuf data) {
material = Material.ID_MAP.get(data.readByte());
if (material == null) {
material = Material.COBBLESTONE;
}
}
@Override
public boolean requiresRenderUpdate(PipePluggable o) {
return ((PlugPluggable) o).material != material;
}
}
| 0 | 0.888759 | 1 | 0.888759 | game-dev | MEDIA | 0.996839 | game-dev | 0.958072 | 1 | 0.958072 |
MonsterEOS/monstereos | 6,808 | services/frontend/src/modules/battles/ArenasScreen.tsx | import * as React from "react"
import { connect } from "react-redux"
import {
State,
pushNotification,
GlobalConfig,
NOTIFICATION_ERROR,
NOTIFICATION_SUCCESS,
} from "../../store"
import { Link } from "react-router-dom"
import PageContainer from "../shared/PageContainer"
import TitleBar from "../shared/TitleBar"
import {
Arena,
getCurrentBattle,
getAvailableMonstersToBattle,
} from "./battles"
import { loadArenas, quickBattle } from "../../utils/eos"
import BattleCard from "./BattleCard"
import { getEosAccount } from "../../utils/scatter"
import { MonsterProps } from "../monsters/monsters"
import BattleMonsterPickModal from "./BattleMonsterPickModal"
import { requestNotificationPermission } from "../../utils/browserNotifications"
interface Props {
globalConfig: GlobalConfig
dispatchPushNotification: any
scatter: any
identity: string
history: any
myMonsters: MonsterProps[]
}
interface ReactState {
arenas: Arena[]
showMonstersSelection: boolean
arenaHost: string
}
class ArenasScreen extends React.Component<Props, ReactState> {
public state = { arenas: [], showMonstersSelection: false, arenaHost: "" }
private refreshHandler: any = 0
private isMyMounted: boolean = true
public componentDidMount() {
this.refresh()
requestNotificationPermission()
}
public componentWillUnmount() {
console.info("unmounting arena")
this.isMyMounted = false
if (this.refreshHandler) {
console.info("erasing arena refresh handler")
clearTimeout(this.refreshHandler)
this.refreshHandler = 0
}
}
public render() {
const { identity, myMonsters } = this.props
const { battle_max_arenas } = this.props.globalConfig
const { arenas, showMonstersSelection } = this.state
const arenasCounter = (
<ArenasCounter
availableArenas={battle_max_arenas - arenas.length}
maxArenas={battle_max_arenas}
/>
)
const currentBattle = getCurrentBattle(arenas, identity)
const availableMonsters = getAvailableMonstersToBattle(myMonsters)
const battleButton = currentBattle ? (
<Link className="button is-warning" to={`/arenas/${currentBattle.host}`}>
Reconnect to Battle
</Link>
) : identity ? (
<a
className="button is-danger is-large"
onClick={() =>
this.setState({ showMonstersSelection: true, arenaHost: "" })
}
>
Quick Battle
</a>
) : null
const availableToBattle =
!!identity && !currentBattle && availableMonsters.length > 0
return (
<PageContainer>
<TitleBar
notMobile
intro="WELCOME TO THE"
title="ARENA"
menu={[arenasCounter, battleButton]}
/>
{arenas.map((arena: Arena, index: number) => (
<BattleCard
key={index}
myBattle={!!currentBattle && currentBattle.host === arena.host}
availableToBattle={availableToBattle}
joinBattle={() =>
this.setState({
showMonstersSelection: true,
arenaHost: arena.host,
})
}
arena={arena}
/>
))}
{showMonstersSelection && (
<BattleMonsterPickModal closeModal={this.confirmSelection} />
)}
</PageContainer>
)
}
private refresh = async () => {
const { arenas: currentArenas } = this.state
const { identity, history } = this.props
try {
const arenas = await loadArenas()
if (!this.isMyMounted) {
return
}
// AutoRedirect to my Battle
const myBattle = getCurrentBattle(arenas, identity)
if (myBattle) {
history.push(`/arenas/${myBattle.host}`)
}
// start notifications after initial load
if (this.refreshHandler) {
this.notifyNewArenas(currentArenas, arenas)
}
this.setState({ arenas })
} catch (error) {
console.error("Fail to load Arenas", error)
// dispatchPushNotification("Fail to load Arenas")
}
// refresh arenas each 5 seconds
this.refreshHandler = setTimeout(this.refresh, 5 * 1000)
}
private notifyNewArenas(currentArenas: Arena[], newArenas: Arena[]) {
const { dispatchPushNotification } = this.props
newArenas.forEach(arena => {
const oldArena = currentArenas.find(
currentArena => currentArena.host === arena.host,
)
if (!oldArena) {
const notification = `${arena.host} created a new arena. Go battle!`
console.info(notification)
dispatchPushNotification(notification, NOTIFICATION_SUCCESS, true)
}
})
}
private confirmSelection = async (pets: number[]) => {
console.info("selected pets >>> ", pets)
// const { arenaHost } = this.state
const { dispatchPushNotification } = this.props
if (pets && pets.length) {
if (pets.length > 1) {
// TODO: current 1v1 mode only
return dispatchPushNotification(
"You can only select 1 monster",
NOTIFICATION_ERROR,
)
// } else if (arenaHost) {
// this.doJoinBattle(arenaHost, pets)
} else {
this.doQuickBattle(pets)
}
} else {
this.setState({ showMonstersSelection: false, arenaHost: "" })
}
}
private doQuickBattle = async (pets: number[]) => {
const { scatter, dispatchPushNotification } = this.props
quickBattle(scatter, 1, pets)
.then(() => {
dispatchPushNotification("Joining Battle...", NOTIFICATION_SUCCESS)
// history.push(`/arenas/${identity}`)
this.refresh()
})
.catch((err: any) => {
dispatchPushNotification(
`Fail to Battle ${err.eosError}`,
NOTIFICATION_ERROR,
)
})
}
// private doJoinBattle = async (host: string, pets: number[]) => {
// const { scatter, dispatchPushNotification, history } = this.props
// joinBattle(scatter, host, pets)
// .then(() => {
// dispatchPushNotification("Joining Battle...", NOTIFICATION_SUCCESS)
// history.push(`/arenas/${host}`)
// })
// .catch((err: any) => {
// dispatchPushNotification(`Fail to Join Battle ${err.eosError}`, NOTIFICATION_ERROR)
// })
// }
}
const ArenasCounter = ({ availableArenas, maxArenas }: any) => (
<span>
Available Arenas: {availableArenas}/{maxArenas}
</span>
)
const mapStateToProps = (state: State) => {
return {
globalConfig: state.globalConfig,
scatter: state.scatter,
identity: getEosAccount(state.identity),
myMonsters: state.myMonsters,
}
}
const mapDispatchToProps = {
dispatchPushNotification: pushNotification,
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ArenasScreen)
| 0 | 0.97251 | 1 | 0.97251 | game-dev | MEDIA | 0.368945 | game-dev | 0.975392 | 1 | 0.975392 |
EgorKulikov/yaal | 1,887 | archive/2013.10/2013.10.01 - Codeforces Round #203/TaskE.java | package net.egork;
import net.egork.io.IOUtils;
import net.egork.misc.MiscUtils;
import net.egork.io.InputReader;
import net.egork.io.OutputWriter;
public class TaskE {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int edgeCount = in.readInt();
int relaxCount = in.readInt();
int[] relaxBy = IOUtils.readIntArray(in, relaxCount);
MiscUtils.decreaseByOne(relaxBy);
boolean[] isRelaxed = new boolean[count];
for (int i : relaxBy)
isRelaxed[i] = true;
if (count == relaxCount || edgeCount > count * (count - 1) / 2 - (relaxCount - 1)) {
out.printLine(-1);
return;
}
int noRelaxSample = -1;
int firstRelaxSample = -1;
int secondRelaxSample = -1;
for (int i = 0; i < count; i++) {
if (isRelaxed[i]) {
if (firstRelaxSample == -1)
firstRelaxSample = i;
else
secondRelaxSample = i;
} else
noRelaxSample = i;
}
boolean[][] edges = new boolean[count][count];
edges[firstRelaxSample][secondRelaxSample] = edges[secondRelaxSample][firstRelaxSample] = true;
addEdge(firstRelaxSample, noRelaxSample, out, edges);
edgeCount--;
addEdge(secondRelaxSample, noRelaxSample, out, edges);
edgeCount--;
for (int i = 0; i < count; i++) {
if (i != firstRelaxSample && i != secondRelaxSample && i != noRelaxSample) {
addEdge(secondRelaxSample, i, out, edges);
edgeCount--;
}
}
for (int i = 0; i < count && edgeCount > 0; i++) {
for (int j = i + 1; j < count && edgeCount > 0; j++) {
if ((i != firstRelaxSample || !isRelaxed[j]) && (j != firstRelaxSample || !isRelaxed[i])) {
if (addEdge(i, j, out, edges))
edgeCount--;
}
}
}
}
private boolean addEdge(int i, int j, OutputWriter out, boolean[][] edges) {
if (edges[i][j])
return false;
edges[i][j] = edges[j][i] = true;
out.printLine(i + 1, j + 1);
return true;
}
}
| 0 | 0.640492 | 1 | 0.640492 | game-dev | MEDIA | 0.539043 | game-dev | 0.771458 | 1 | 0.771458 |
onitama/OpenHSP | 2,836 | src/hsp3dish/extlib/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_BOX_BOX__COLLISION_ALGORITHM_H
#define BT_BOX_BOX__COLLISION_ALGORITHM_H
#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
class btPersistentManifold;
///box-box collision detection
class btBoxBoxCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
bool m_ownManifold;
btPersistentManifold* m_manifoldPtr;
public:
btBoxBoxCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci)
: btActivatingCollisionAlgorithm(ci) {}
virtual void processCollision(const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut);
virtual btScalar calculateTimeOfImpact(btCollisionObject* body0, btCollisionObject* body1, const btDispatcherInfo& dispatchInfo, btManifoldResult* resultOut);
btBoxBoxCollisionAlgorithm(btPersistentManifold* mf, const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap);
virtual ~btBoxBoxCollisionAlgorithm();
virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
{
if (m_manifoldPtr && m_ownManifold)
{
manifoldArray.push_back(m_manifoldPtr);
}
}
struct CreateFunc : public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap, const btCollisionObjectWrapper* body1Wrap)
{
int bbsize = sizeof(btBoxBoxCollisionAlgorithm);
void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize);
return new (ptr) btBoxBoxCollisionAlgorithm(0, ci, body0Wrap, body1Wrap);
}
};
};
#endif //BT_BOX_BOX__COLLISION_ALGORITHM_H
| 0 | 0.859596 | 1 | 0.859596 | game-dev | MEDIA | 0.973336 | game-dev | 0.700481 | 1 | 0.700481 |
awgil/ffxiv_bossmod | 15,001 | BossMod/Modules/Endwalker/Savage/P8S1Hephaistos/P8S1States.cs | namespace BossMod.Endwalker.Savage.P8S1Hephaistos;
class P8S1States : StateMachineBuilder
{
public P8S1States(BossModule module) : base(module)
{
SimplePhase(0, SinglePhase, "Single phase")
.Raw.Update = () => Module.PrimaryActor.IsDestroyed;
}
private void SinglePhase(uint id)
{
GenesisOfFlame(id, 6.2f);
VolcanicTorchesSunforge(id + 0x10000, 3.2f);
Flameviper(id + 0x20000, 2);
Dictionary<AID, (uint seqID, Action<uint> buildState)> fork = new()
{
[AID.ReforgedReflectionCentaur] = (1, ForkCentaur),
[AID.ReforgedReflectionSnake] = (2, ForkSnake)
};
CastStartFork(id + 0x30000, fork, 9.4f, "Centaur -or- Snake");
}
private void ForkCentaur(uint id)
{
Centaur1(id);
Intermission(id + 0x10000, 14.4f);
Snake1(id + 0x20000, 9.5f);
FourfoldFires(id + 0x30000, 15.4f);
Flameviper(id + 0x40000, 2);
Centaur2(id + 0x50000, 9.4f);
Flameviper(id + 0x60000, 7.6f);
Snake2(id + 0x70000, 9.4f);
GenesisOfFlame(id + 0x80000, 8.1f);
Enrage(id + 0x90000, 8.2f);
}
private void ForkSnake(uint id)
{
Snake1(id);
Intermission(id + 0x10000, 15.4f);
Centaur1(id + 0x20000, 9.5f);
FourfoldFires(id + 0x30000, 14.4f);
Flameviper(id + 0x40000, 2);
Snake2(id + 0x50000, 9.4f);
Flameviper(id + 0x60000, 8);
Centaur2(id + 0x70000, 9.4f);
GenesisOfFlame(id + 0x80000, 7.6f);
Enrage(id + 0x90000, 8.2f);
}
private void GenesisOfFlame(uint id, float delay)
{
Cast(id, AID.GenesisOfFlame, delay, 5, "Raidwide")
.SetHint(StateMachine.StateHint.Raidwide);
}
private void VolcanicTorchesSunforge(uint id, float delay)
{
CastMulti(id, [AID.ConceptualOctaflare, AID.ConceptualTetraflare], delay, 3)
.ActivateOnEnter<TetraOctaFlareConceptual>();
Cast(id + 0x10, AID.VolcanicTorches, 3.2f, 3)
.ActivateOnEnter<VolcanicTorches>(); // casts start ~4s later
CastStartMulti(id + 0x20, [AID.SunforgeCenter, AID.SunforgeSides], 8.5f);
ComponentCondition<VolcanicTorches>(id + 0x30, 5.5f, comp => comp.NumCasts > 0, "Torches")
.ActivateOnEnter<SunforgeCenterHint>()
.ActivateOnEnter<SunforgeSidesHint>()
.DeactivateOnExit<VolcanicTorches>()
.DeactivateOnExit<SunforgeCenterHint>()
.DeactivateOnExit<SunforgeSidesHint>();
CastEnd(id + 0x40, 1.4f)
.ActivateOnEnter<SunforgeCenter>()
.ActivateOnEnter<SunforgeSides>()
.ExecOnEnter<TetraOctaFlareConceptual>(comp => comp.Show());
// note: sunforge aoe happens ~0.1s before flares
ComponentCondition<TetraOctaFlareConceptual>(id + 0x50, 1.1f, comp => !comp.Active, "Sunforge + stack/spread")
.DeactivateOnExit<TetraOctaFlareConceptual>()
.DeactivateOnExit<SunforgeCenter>()
.DeactivateOnExit<SunforgeSides>()
.SetHint(StateMachine.StateHint.Raidwide);
}
private void Flameviper(uint id, float delay)
{
Cast(id, AID.Flameviper, delay, 5, "Tankbuster hit 1")
.ActivateOnEnter<Flameviper>()
.SetHint(StateMachine.StateHint.Tankbuster);
ComponentCondition<Flameviper>(id + 2, 3.4f, comp => comp.NumCasts > 0, "Tankbuster hit 2")
.DeactivateOnExit<Flameviper>()
.SetHint(StateMachine.StateHint.Tankbuster);
}
private void Intermission(uint id, float delay)
{
Cast(id, AID.IllusoryCreation, delay, 3);
Cast(id + 0x10, AID.CreationOnCommand, 3.2f, 3)
.ActivateOnEnter<SunforgeCenterIntermission>() // note that sunforges start ~0.8s after cast ends
.ActivateOnEnter<SunforgeSidesIntermission>();
Cast(id + 0x20, AID.ManifoldFlames, 3.2f, 5)
.ActivateOnEnter<ManifoldFlames>();
// note: sunforges resolves ~0.1s before flares
ComponentCondition<NestOfFlamevipersBaited>(id + 0x30, 0.8f, comp => comp.Active, "Spread in safe cells")
.ActivateOnEnter<NestOfFlamevipersBaited>()
.DeactivateOnExit<ManifoldFlames>()
.DeactivateOnExit<SunforgeCenterIntermission>()
.DeactivateOnExit<SunforgeSidesIntermission>();
// +3.9s: start of second set of sunforges; but we activate components only after baits are done to reduce clutter
ComponentCondition<NestOfFlamevipersBaited>(id + 0x40, 4.2f, comp => !comp.Active, "Baits")
.DeactivateOnExit<NestOfFlamevipersBaited>();
CastStartMulti(id + 0x50, [AID.NestOfFlamevipers, AID.Tetraflare], 2.3f)
.ActivateOnEnter<SunforgeCenterIntermission>() // note that sunforges start ~0.3s before baits
.ActivateOnEnter<SunforgeSidesIntermission>()
.ActivateOnEnter<TetraOctaFlareImmediate>()
.ActivateOnEnter<NestOfFlamevipersEveryone>();
CastEnd(id + 0x51, 5);
// +0.4s: sunforges resolve
Condition(id + 0x60, 0.8f, () => !Module.FindComponent<NestOfFlamevipersEveryone>()!.Active && !Module.FindComponent<TetraOctaFlareImmediate>()!.Active, "Spread/stack in pairs")
.DeactivateOnExit<SunforgeCenterIntermission>()
.DeactivateOnExit<SunforgeSidesIntermission>()
.DeactivateOnExit<TetraOctaFlareImmediate>()
.DeactivateOnExit<NestOfFlamevipersEveryone>();
ComponentCondition<VolcanicTorches>(id + 0x70, 2.3f, comp => comp.Casters.Count > 0)
.ActivateOnEnter<VolcanicTorches>();
CastStart(id + 0x71, AID.GenesisOfFlame, 9.2f);
ComponentCondition<VolcanicTorches>(id + 0x72, 0.8f, comp => comp.Casters.Count == 0, "Torches")
.DeactivateOnExit<VolcanicTorches>();
CastEnd(id + 0x73, 4.2f, "Raidwide")
.SetHint(StateMachine.StateHint.Raidwide);
}
private void FourfoldFires(uint id, float delay)
{
CastMulti(id, [AID.ConceptualOctaflare, AID.ConceptualTetraflare], delay, 3)
.ActivateOnEnter<TetraOctaFlareConceptual>();
Cast(id + 0x10, AID.FourfoldFires, 3.2f, 3);
ComponentCondition<AbyssalFires>(id + 0x12, 5.8f, comp => comp.NumCasts > 0, "Proximity aoes")
.ActivateOnEnter<AbyssalFires>()
.DeactivateOnExit<AbyssalFires>();
Cast(id + 0x20, AID.CthonicVent, 0.4f, 3);
// +0.8f: vents cast start
ComponentCondition<CthonicVent>(id + 0x30, 5.8f, comp => comp.NumTotalCasts > 0, "Vent 1")
.ActivateOnEnter<CthonicVent>();
CastStartMulti(id + 0x40, [AID.Tetraflare, AID.Octaflare], 4.4f);
ComponentCondition<CthonicVent>(id + 0x50, 4.7f, comp => comp.NumTotalCasts > 2, "Vent 2")
.ActivateOnEnter<TetraOctaFlareImmediate>();
CastEnd(id + 0x60, 0.3f);
ComponentCondition<TetraOctaFlareImmediate>(id + 0x61, 0.8f, comp => !comp.Active, "Spread/stack in pairs")
.DeactivateOnExit<TetraOctaFlareImmediate>();
CastStartMulti(id + 0x70, [AID.SunforgeCenter, AID.SunforgeSides], 5.7f);
ComponentCondition<CthonicVent>(id + 0x80, 2.2f, comp => comp.NumTotalCasts > 4, "Vent 3")
.ActivateOnEnter<SunforgeCenterHint>()
.ActivateOnEnter<SunforgeSidesHint>()
.DeactivateOnExit<CthonicVent>()
.DeactivateOnExit<SunforgeCenterHint>()
.DeactivateOnExit<SunforgeSidesHint>();
CastEnd(id + 0x90, 4.7f)
.ActivateOnEnter<SunforgeCenter>()
.ActivateOnEnter<SunforgeSides>()
.ExecOnEnter<TetraOctaFlareConceptual>(comp => comp.Show());
// note: sunforge aoe happens ~0.1s before flares
ComponentCondition<TetraOctaFlareConceptual>(id + 0xA0, 1.1f, comp => !comp.Active, "Sunforge + stack/spread")
.DeactivateOnExit<TetraOctaFlareConceptual>()
.DeactivateOnExit<SunforgeCenter>()
.DeactivateOnExit<SunforgeSides>()
.SetHint(StateMachine.StateHint.Raidwide);
}
private void CentaurStart(uint id, float delay)
{
if (delay >= 0)
CastStart(id, AID.ReforgedReflectionCentaur, delay);
CastEnd(id + 1, 3)
.ActivateOnEnter<Footprint>();
ComponentCondition<Footprint>(id + 2, 6.5f, comp => comp.NumCasts > 0, "Centaur knockback")
.DeactivateOnExit<Footprint>();
}
// if delay is negative, cast-start state is not created
private void Centaur1(uint id, float delay = -1)
{
CentaurStart(id, delay);
Cast(id + 0x100, AID.RearingRampage, 0.9f, 5, "First raidwide")
.ActivateOnEnter<UpliftStompDead>()
.SetHint(StateMachine.StateHint.Raidwide);
// +1s: first set of uplifts
ComponentCondition<RearingRampageSecond>(id + 0x110, 2.2f, comp => comp.NumCasts > 0)
.ActivateOnEnter<RearingRampageSecond>()
.SetHint(StateMachine.StateHint.Raidwide);
// +1s: second set of uplifts
ComponentCondition<RearingRampageSecond>(id + 0x120, 2.1f, comp => comp.NumCasts > 1)
.DeactivateOnExit<RearingRampageSecond>()
.SetHint(StateMachine.StateHint.Raidwide);
// +1s: third set of uplifts
ComponentCondition<RearingRampageLast>(id + 0x130, 2.1f, comp => comp.NumCasts > 0)
.ActivateOnEnter<RearingRampageLast>()
.DeactivateOnExit<RearingRampageLast>()
.SetHint(StateMachine.StateHint.Raidwide);
ComponentCondition<UpliftStompDead>(id + 0x140, 1, comp => comp.NumUplifts >= 8, "Last uplift");
Cast(id + 0x150, AID.StompDead, 1.2f, 5);
ComponentCondition<UpliftStompDead>(id + 0x152, 0.3f, comp => comp.NumStomps > 0, "First stomp");
ComponentCondition<UpliftStompDead>(id + 0x153, 2.3f, comp => comp.NumStomps > 1);
ComponentCondition<UpliftStompDead>(id + 0x154, 2.3f, comp => comp.NumStomps > 2);
ComponentCondition<UpliftStompDead>(id + 0x155, 2.3f, comp => comp.NumStomps > 3, "Last stomp")
.DeactivateOnExit<UpliftStompDead>();
}
private void Centaur2(uint id, float delay)
{
CentaurStart(id, delay);
CastMulti(id + 0x100, [AID.QuadrupedalImpact, AID.QuadrupedalCrush], 1.1f, 5)
.ActivateOnEnter<QuadrupedalImpact>()
.ActivateOnEnter<QuadrupedalCrush>();
Condition(id + 0x102, 0.9f, () => Module.FindComponent<QuadrupedalImpact>()!.NumCasts + Module.FindComponent<QuadrupedalCrush>()!.NumCasts > 0, "Knockback or aoe")
.DeactivateOnExit<QuadrupedalImpact>()
.DeactivateOnExit<QuadrupedalCrush>();
CastMulti(id + 0x110, [AID.ConceptualTetraflareCentaur, AID.ConceptualDiflare], 2.7f, 3)
.ActivateOnEnter<CentaurTetraflare>()
.ActivateOnEnter<CentaurDiflare>();
Cast(id + 0x120, AID.BlazingFootfalls, 3.2f, 12, "Boss disappear")
.ActivateOnEnter<BlazingFootfalls>()
.SetHint(StateMachine.StateHint.DowntimeStart); // boss becomes untargetable right at cast end
ComponentCondition<BlazingFootfalls>(id + 0x130, 0.7f, comp => comp.NumMechanicsDone > 0);
// +1.1s: di/tetra flare resolve
ComponentCondition<BlazingFootfalls>(id + 0x140, 4.8f, comp => comp.NumMechanicsDone > 1, "Knockback/aoe 1"); // right after this torchest start
ComponentCondition<BlazingFootfalls>(id + 0x150, 3.7f, comp => comp.NumMechanicsDone > 2, "Horizonal")
.ActivateOnEnter<VolcanicTorches>();
ComponentCondition<BlazingFootfalls>(id + 0x160, 2.8f, comp => comp.NumMechanicsDone > 3, "Knockback/aoe 2")
.DeactivateOnExit<BlazingFootfalls>();
ComponentCondition<VolcanicTorches>(id + 0x170, 3.5f, comp => comp.NumCasts > 0, "Torches")
.DeactivateOnExit<VolcanicTorches>();
Targetable(id + 0x180, true, 0.8f, "Boss reappear");
}
// returns state on entering which mechanic-specific component should be activated
private State SnakeStart(uint id, float delay)
{
if (delay >= 0)
CastStart(id, AID.ReforgedReflectionSnake, delay);
CastEnd(id + 1, 3)
.ActivateOnEnter<SnakingKick>();
ComponentCondition<SnakingKick>(id + 2, 7.3f, comp => comp.NumCasts > 0, "Snake aoe")
.DeactivateOnExit<SnakingKick>();
Cast(id + 0x10, AID.Gorgomanteia, 3.2f, 3);
// +0.7s: debuffs are applied
var s = CastStart(id + 0x20, AID.IntoTheShadows, 3.2f);
CastEnd(id + 0x21, 3);
return s;
}
// if delay is negative, cast-start state is not created
private void Snake1(uint id, float delay = -1)
{
SnakeStart(id, delay)
.ActivateOnEnter<Snake1>();
ComponentCondition<Snake1>(id + 0x110, 15.2f, comp => comp.NumCasts > 0, "First snakes appear");
ComponentCondition<Snake1>(id + 0x120, 2.5f, comp => comp.NumEyeCasts > 0, "First order petrify");
ComponentCondition<Snake1>(id + 0x121, 3.0f, comp => comp.NumBloodCasts > 0, "First order explode");
ComponentCondition<Snake1>(id + 0x130, 2.5f, comp => comp.NumCasts > 2, "Second snakes appear");
ComponentCondition<Snake1>(id + 0x140, 2.5f, comp => comp.NumEyeCasts > 2, "Second order petrify");
ComponentCondition<Snake1>(id + 0x141, 3.0f, comp => comp.NumBloodCasts > 2, "Second order explode")
.DeactivateOnExit<Snake1>();
Cast(id + 0x150, AID.Ektothermos, 4.6f, 5, "Raidwide")
.SetHint(StateMachine.StateHint.Raidwide);
}
private void Snake2(uint id, float delay)
{
SnakeStart(id, delay)
.ActivateOnEnter<Snake2>();
// +6.0s: petrifaction casts start
// +8.0s: gorgospit animations
// +10.0s: gorgospit casts start
// +14.0s: petrifaction casts end
ComponentCondition<Snake2>(id + 0x110, 15.2f, comp => comp.NumCasts > 0, "Snakes appear")
.ActivateOnEnter<Gorgospit>();
// +1.0s: gorgospit casts end
ComponentCondition<Snake2>(id + 0x120, 2.5f, comp => comp.NumEyeCasts > 0, "First order petrify/explode");
Cast(id + 0x130, AID.IllusoryCreationSnakes, 1.6f, 3);
// +0.8s: gorgospit animations
ComponentCondition<Snake2>(id + 0x140, 1.4f, comp => comp.NumEyeCasts > 4, "Second order petrify/explode");
// +1.5s: gorgospit cast start
// +7.5s: gorgospit cast end
ComponentCondition<Snake2>(id + 0x150, 9, comp => comp.NumCrownCasts > 0, "Blockable petrify")
.DeactivateOnExit<Gorgospit>();
ComponentCondition<Snake2>(id + 0x151, 1, comp => comp.NumBreathCasts > 0, "Party stacks")
.DeactivateOnExit<Snake2>();
}
private void Enrage(uint id, float delay)
{
Targetable(id, false, delay, "Enrage");
Cast(id + 0x10, AID.Enrage, 0.1f, 5, "Finish");
}
}
| 0 | 0.940016 | 1 | 0.940016 | game-dev | MEDIA | 0.668307 | game-dev | 0.817242 | 1 | 0.817242 |
IUDevman/gamesense-client | 9,316 | src/main/java/com/gamesense/client/module/modules/render/HoleESP.java | package com.gamesense.client.module.modules.render;
import com.gamesense.api.event.events.RenderEvent;
import com.gamesense.api.setting.values.*;
import com.gamesense.api.util.player.PlayerUtil;
import com.gamesense.api.util.render.GSColor;
import com.gamesense.api.util.render.RenderUtil;
import com.gamesense.api.util.world.EntityUtil;
import com.gamesense.api.util.world.GeometryMasks;
import com.gamesense.api.util.world.HoleUtil;
import com.gamesense.client.module.Category;
import com.gamesense.client.module.Module;
import com.google.common.collect.Sets;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @reworked by 0b00101010 on 14/01/2021
*/
@Module.Declaration(name = "HoleESP", category = Category.Render)
public class HoleESP extends Module {
public IntegerSetting range = registerInteger("Range", 5, 1, 20);
ModeSetting customHoles = registerMode("Show", Arrays.asList("Single", "Double", "Custom"), "Single");
ModeSetting type = registerMode("Render", Arrays.asList("Outline", "Fill", "Both"), "Both");
ModeSetting mode = registerMode("Mode", Arrays.asList("Air", "Ground", "Flat", "Slab", "Double"), "Air");
BooleanSetting hideOwn = registerBoolean("Hide Own", false);
BooleanSetting flatOwn = registerBoolean("Flat Own", false);
DoubleSetting slabHeight = registerDouble("Slab Height", 0.5, 0.1, 1.5);
IntegerSetting width = registerInteger("Width", 1, 1, 10);
ColorSetting bedrockColor = registerColor("Bedrock Color", new GSColor(0, 255, 0));
ColorSetting obsidianColor = registerColor("Obsidian Color", new GSColor(255, 0, 0));
ColorSetting customColor = registerColor("Custom Color", new GSColor(0, 0, 255));
IntegerSetting ufoAlpha = registerInteger("UFOAlpha", 255, 0, 255);
private ConcurrentHashMap<AxisAlignedBB, GSColor> holes;
public void onUpdate() {
if (mc.player == null || mc.world == null) {
return;
}
if (holes == null) {
holes = new ConcurrentHashMap<>();
} else {
holes.clear();
}
int range = (int) Math.ceil(this.range.getValue());
HashSet<BlockPos> possibleHoles = Sets.newHashSet();
List<BlockPos> blockPosList = EntityUtil.getSphere(PlayerUtil.getPlayerPos(), range, range, false, true, 0);
for (BlockPos pos : blockPosList) {
if (!mc.world.getBlockState(pos).getBlock().equals(Blocks.AIR)) {
continue;
}
if (mc.world.getBlockState(pos.add(0, -1, 0)).getBlock().equals(Blocks.AIR)) {
continue;
}
if (!mc.world.getBlockState(pos.add(0, 1, 0)).getBlock().equals(Blocks.AIR)) {
continue;
}
if (mc.world.getBlockState(pos.add(0, 2, 0)).getBlock().equals(Blocks.AIR)) {
possibleHoles.add(pos);
}
}
possibleHoles.forEach(pos -> {
HoleUtil.HoleInfo holeInfo = HoleUtil.isHole(pos, false, false);
HoleUtil.HoleType holeType = holeInfo.getType();
if (holeType != HoleUtil.HoleType.NONE) {
HoleUtil.BlockSafety holeSafety = holeInfo.getSafety();
AxisAlignedBB centreBlocks = holeInfo.getCentre();
if (centreBlocks == null)
return;
GSColor colour;
if (holeSafety == HoleUtil.BlockSafety.UNBREAKABLE) {
colour = new GSColor(bedrockColor.getValue(), 255);
} else {
colour = new GSColor(obsidianColor.getValue(), 255);
}
if (holeType == HoleUtil.HoleType.CUSTOM) {
colour = new GSColor(customColor.getValue(), 255);
}
String mode = customHoles.getValue();
if (mode.equalsIgnoreCase("Custom") && (holeType == HoleUtil.HoleType.CUSTOM || holeType == HoleUtil.HoleType.DOUBLE)) {
holes.put(centreBlocks, colour);
} else if (mode.equalsIgnoreCase("Double") && holeType == HoleUtil.HoleType.DOUBLE) {
holes.put(centreBlocks, colour);
} else if (holeType == HoleUtil.HoleType.SINGLE) {
holes.put(centreBlocks, colour);
}
}
});
}
public void onWorldRender(RenderEvent event) {
if (mc.player == null || mc.world == null || holes == null || holes.isEmpty()) {
return;
}
holes.forEach(this::renderHoles);
}
private void renderHoles(AxisAlignedBB hole, GSColor color) {
switch (type.getValue()) {
case "Outline": {
renderOutline(hole, color);
break;
}
case "Fill": {
renderFill(hole, color);
break;
}
case "Both": {
renderOutline(hole, color);
renderFill(hole, color);
break;
}
}
}
private void renderFill(AxisAlignedBB hole, GSColor color) {
GSColor fillColor = new GSColor(color, 50);
int ufoAlpha = (this.ufoAlpha.getValue() * 50) / 255;
if (hideOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) return;
switch (mode.getValue()) {
case "Air": {
if (flatOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) {
RenderUtil.drawBox(hole, true, 1, fillColor, ufoAlpha, GeometryMasks.Quad.DOWN);
} else {
RenderUtil.drawBox(hole, true, 1, fillColor, ufoAlpha, GeometryMasks.Quad.ALL);
}
break;
}
case "Ground": {
RenderUtil.drawBox(hole.offset(0, -1, 0), true, 1, new GSColor(fillColor, ufoAlpha), fillColor.getAlpha(), GeometryMasks.Quad.ALL);
break;
}
case "Flat": {
RenderUtil.drawBox(hole, true, 1, fillColor, ufoAlpha, GeometryMasks.Quad.DOWN);
break;
}
case "Slab": {
if (flatOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) {
RenderUtil.drawBox(hole, true, 1, fillColor, ufoAlpha, GeometryMasks.Quad.DOWN);
} else {
RenderUtil.drawBox(hole, false, slabHeight.getValue(), fillColor, ufoAlpha, GeometryMasks.Quad.ALL);
}
break;
}
case "Double": {
if (flatOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) {
RenderUtil.drawBox(hole, true, 1, fillColor, ufoAlpha, GeometryMasks.Quad.DOWN);
} else {
RenderUtil.drawBox(hole.setMaxY(hole.maxY + 1), true, 2, fillColor, ufoAlpha, GeometryMasks.Quad.ALL);
}
break;
}
}
}
private void renderOutline(AxisAlignedBB hole, GSColor color) {
GSColor outlineColor = new GSColor(color, 255);
if (hideOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) return;
switch (mode.getValue()) {
case "Air": {
if (flatOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) {
RenderUtil.drawBoundingBoxWithSides(hole, width.getValue(), outlineColor, ufoAlpha.getValue(), GeometryMasks.Quad.DOWN);
} else {
RenderUtil.drawBoundingBox(hole, width.getValue(), outlineColor, ufoAlpha.getValue());
}
break;
}
case "Ground": {
RenderUtil.drawBoundingBox(hole.offset(0, -1, 0), width.getValue(), new GSColor(outlineColor, ufoAlpha.getValue()), outlineColor.getAlpha());
break;
}
case "Flat": {
RenderUtil.drawBoundingBoxWithSides(hole, width.getValue(), outlineColor, ufoAlpha.getValue(), GeometryMasks.Quad.DOWN);
break;
}
case "Slab": {
if (this.flatOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) {
RenderUtil.drawBoundingBoxWithSides(hole, width.getValue(), outlineColor, ufoAlpha.getValue(), GeometryMasks.Quad.DOWN);
} else {
RenderUtil.drawBoundingBox(hole.setMaxY(hole.minY + slabHeight.getValue()), width.getValue(), outlineColor, ufoAlpha.getValue());
}
break;
}
case "Double": {
if (this.flatOwn.getValue() && hole.intersects(mc.player.getEntityBoundingBox())) {
RenderUtil.drawBoundingBoxWithSides(hole, width.getValue(), outlineColor, ufoAlpha.getValue(), GeometryMasks.Quad.DOWN);
} else {
RenderUtil.drawBoundingBox(hole.setMaxY(hole.maxY + 1), width.getValue(), outlineColor, ufoAlpha.getValue());
}
break;
}
}
}
} | 0 | 0.901702 | 1 | 0.901702 | game-dev | MEDIA | 0.567394 | game-dev,graphics-rendering | 0.955031 | 1 | 0.955031 |
dart-lang/core | 1,709 | pkgs/async/lib/src/restartable_timer.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
/// A non-periodic timer that can be restarted any number of times.
///
/// Once restarted (via [reset]), the timer counts down from its original
/// duration again.
class RestartableTimer implements Timer {
/// The duration of the timer.
final Duration _duration;
/// The callback to call when the timer fires.
final ZoneCallback _callback;
/// The timer for the current or most recent countdown.
///
/// This timer is canceled and overwritten every time this [RestartableTimer]
/// is reset.
Timer _timer;
/// Creates a new timer.
///
/// The [_callback] function is invoked after the given [_duration]. Unlike a
/// normal non-periodic [Timer], [_callback] may be called more than once.
RestartableTimer(this._duration, this._callback)
: _timer = Timer(_duration, _callback);
@override
bool get isActive => _timer.isActive;
/// Restarts the timer so that it counts down from its original duration
/// again.
///
/// This restarts the timer even if it has already fired or has been canceled.
void reset() {
_timer.cancel();
_timer = Timer(_duration, _callback);
}
@override
void cancel() {
_timer.cancel();
}
/// The number of durations preceding the most recent timer event on the most
/// recent countdown.
///
/// Calls to [reset] will also reset the tick so subsequent tick values may
/// not be strictly larger than previous values.
@override
int get tick => _timer.tick;
}
| 0 | 0.810727 | 1 | 0.810727 | game-dev | MEDIA | 0.331132 | game-dev | 0.80172 | 1 | 0.80172 |
Tantares/Resurfaced | 1,094 | Source/Technicolor/UIUtils.cs | using System;
using KSP.UI;
using KSP.UI.TooltipTypes;
using UnityEngine;
namespace Technicolor;
/// <summary>
/// Get a reference in a child of a type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <param name="parent"></param>
/// <returns></returns>
public static class UIUtils
{
public static T FindChildOfType<T>(string name, Transform parent)
{
var result = default(T);
try
{
result = parent.FindDeepChild(name).GetComponent<T>();
}
catch (NullReferenceException e)
{
Debug.LogError($"Couldn't find {name} in children of {parent.name}");
}
return result;
}
public static Tooltip_Text FindTextTooltipPrefab()
{
if (HighLogic.LoadedSceneIsEditor)
{
var sorterBase = GameObject.FindObjectOfType<UIListSorter>();
var sortByNameButton = sorterBase.gameObject.GetChild("StateButtonName");
return sortByNameButton.GetComponent<TooltipController_Text>().prefab;
}
else
{
return GameObject.FindObjectOfType<TooltipController_Text>().prefab;
}
}
}
| 0 | 0.827869 | 1 | 0.827869 | game-dev | MEDIA | 0.958378 | game-dev | 0.820279 | 1 | 0.820279 |
Baystation12/Baystation12 | 6,616 | code/modules/organs/internal/_internal.dm | /****************************************************
INTERNAL ORGANS DEFINES
****************************************************/
/obj/item/organ/internal
var/dead_icon // Icon to use when the organ has died.
var/surface_accessible = FALSE
var/relative_size = 25 // Relative size of the organ. Roughly % of space they take in the target projection :D
var/min_bruised_damage = 10 // Damage before considered bruised
var/damage_reduction = 0.5 //modifier for internal organ injury
/obj/item/organ/internal/Initialize()
if(max_damage)
min_bruised_damage = floor(max_damage / 4)
. = ..()
if(iscarbon(loc) && !istype(src, /obj/item/organ/internal/augment))
var/mob/living/carbon/human/holder = loc
holder.internal_organs |= src
if(ishuman(holder))
var/obj/item/organ/external/external = holder.get_organ(parent_organ)
if(!external)
CRASH("[src] spawned in [holder] without a parent organ: [parent_organ].")
external.internal_organs |= src
/obj/item/organ/internal/Destroy()
if(owner)
owner.internal_organs.Remove(src)
owner.internal_organs_by_name[organ_tag] = null
owner.internal_organs_by_name -= organ_tag
while(null in owner.internal_organs)
owner.internal_organs -= null
var/obj/item/organ/external/E = owner.organs_by_name[parent_organ]
if(istype(E)) E.internal_organs -= src
return ..()
/obj/item/organ/internal/set_dna(datum/dna/new_dna)
..()
if(species && species.organs_icon)
icon = species.organs_icon
//disconnected the organ from it's owner but does not remove it, instead it becomes an implant that can be removed with implant surgery
//TODO move this to organ/internal once the FPB port comes through
/obj/item/organ/proc/cut_away(mob/living/user)
var/obj/item/organ/external/parent = owner.get_organ(parent_organ)
if(istype(parent)) //TODO ensure that we don't have to check this.
removed(user, 0)
parent.implants += src
/obj/item/organ/internal/removed(mob/living/user, drop_organ=1, detach=1)
if(owner)
owner.internal_organs_by_name[organ_tag] = null
owner.internal_organs_by_name -= organ_tag
owner.internal_organs_by_name -= null
owner.internal_organs -= src
if(detach)
var/obj/item/organ/external/affected = owner.get_organ(parent_organ)
if(affected)
affected.internal_organs -= src
status |= ORGAN_CUT_AWAY
..()
/obj/item/organ/internal/replaced(mob/living/carbon/human/target, obj/item/organ/external/affected)
if(!istype(target))
return 0
if(status & ORGAN_CUT_AWAY)
return 0 //organs don't work very well in the body when they aren't properly attached
// robotic organs emulate behavior of the equivalent flesh organ of the species
if(BP_IS_ROBOTIC(src) || !species)
species = target.species
..()
STOP_PROCESSING(SSobj, src)
target.internal_organs |= src
affected.internal_organs |= src
target.internal_organs_by_name[organ_tag] = src
return 1
/obj/item/organ/internal/die()
..()
if((status & ORGAN_DEAD) && dead_icon)
icon_state = dead_icon
/obj/item/organ/internal/remove_rejuv()
if(owner)
owner.internal_organs -= src
owner.internal_organs_by_name[organ_tag] = null
owner.internal_organs_by_name -= organ_tag
while(null in owner.internal_organs)
owner.internal_organs -= null
var/obj/item/organ/external/E = owner.organs_by_name[parent_organ]
if(istype(E)) E.internal_organs -= src
..()
/obj/item/organ/internal/is_usable()
return ..() && !is_broken()
/obj/item/organ/internal/robotize()
..()
min_bruised_damage += 5
min_broken_damage += 10
/obj/item/organ/internal/proc/getToxLoss()
if(BP_IS_ROBOTIC(src))
return damage * 0.5
return damage
/obj/item/organ/internal/proc/bruise()
damage = max(damage, min_bruised_damage)
/obj/item/organ/internal/proc/is_damaged()
return damage > 0
/obj/item/organ/internal/proc/is_bruised()
return damage >= min_bruised_damage
/obj/item/organ/internal/proc/set_max_damage(ndamage)
max_damage = floor(ndamage)
min_broken_damage = floor(0.75 * max_damage)
min_bruised_damage = floor(0.25 * max_damage)
/obj/item/organ/internal/take_general_damage(amount, silent = FALSE)
take_internal_damage(amount, silent)
/obj/item/organ/internal/proc/take_internal_damage(amount, silent=0)
if(BP_IS_ROBOTIC(src))
damage = clamp(damage + (amount * 0.8), 0, max_damage)
else
damage = clamp(damage + amount, 0, max_damage)
//only show this if the organ is not robotic
if(owner && can_feel_pain() && parent_organ && (amount > 5 || prob(10)))
var/obj/item/organ/external/parent = owner.get_organ(parent_organ)
if(parent && !silent)
var/degree = ""
if(is_bruised())
degree = " a lot"
if(damage < 5)
degree = " a bit"
owner.custom_pain("Something inside your [parent.name] hurts[degree].", amount, affecting = parent)
/obj/item/organ/internal/proc/get_visible_state()
if(damage > max_damage)
. = "bits and pieces of a destroyed "
else if(is_broken())
. = "broken "
else if(is_bruised())
. = "badly damaged "
else if(damage > 5)
. = "damaged "
if(status & ORGAN_DEAD)
if(can_recover())
. = "decaying [.]"
else
. = "necrotic [.]"
. = "[.][name]"
/obj/item/organ/internal/Process()
..()
handle_regeneration()
/obj/item/organ/internal/proc/handle_regeneration()
if(!damage || BP_IS_ROBOTIC(src) || !owner || owner.chem_effects[CE_TOXIN] || owner.is_asystole())
return
if(damage < 0.1*max_damage)
heal_damage(0.1)
/obj/item/organ/internal/proc/surgical_fix(mob/user)
if(damage > min_broken_damage)
var/scarring = damage/max_damage
scarring = 1 - 0.3 * scarring ** 2 // Between ~15 and 30 percent loss
var/new_max_dam = floor(scarring * max_damage)
if(new_max_dam < max_damage)
to_chat(user, SPAN_WARNING("Not every part of [src] could be saved, some dead tissue had to be removed, making it more suspectable to damage in the future."))
set_max_damage(new_max_dam)
heal_damage(damage)
/obj/item/organ/internal/proc/get_scarring_level()
var/initial_max = initial(max_damage)
return (initial_max - max_damage) * 100 / initial_max
/obj/item/organ/internal/get_scan_results(tag = FALSE)
. = ..()
var/scar_level = get_scarring_level()
if(scar_level > 0.01)
. += tag ? "<span style='font-weight: bold; color: [COLOR_MEDICAL_SCARRING]'>[get_wound_severity(get_scarring_level())] scarring</span>" : "[get_wound_severity(get_scarring_level())] scarring"
/obj/item/organ/internal/emp_act(severity)
if(!BP_IS_ROBOTIC(src))
return
var/rand_modifier = rand(1, 3)
switch (severity)
if (EMP_ACT_HEAVY)
take_internal_damage(5 * rand_modifier)
if (EMP_ACT_LIGHT)
take_internal_damage(2 * rand_modifier)
..()
| 0 | 0.68303 | 1 | 0.68303 | game-dev | MEDIA | 0.871715 | game-dev | 0.692496 | 1 | 0.692496 |
magefree/mage | 1,636 | Mage.Sets/src/mage/cards/s/StagBeetle.java |
package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.EntersBattlefieldAbility;
import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.counters.CounterType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.AnotherPredicate;
/**
*
* @author LoneFox
*/
public final class StagBeetle extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("other creatures");
static {
filter.add(AnotherPredicate.instance);
}
public StagBeetle(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{G}{G}");
this.subtype.add(SubType.INSECT);
this.power = new MageInt(0);
this.toughness = new MageInt(0);
// Stag Beetle enters the battlefield with X +1/+1 counters on it, where X is the number of other creatures on the battlefield.
this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(),
new PermanentsOnBattlefieldCount(filter), false),
"with X +1/+1 counters on it, where X is the number of other creatures on the battlefield"));
}
private StagBeetle(final StagBeetle card) {
super(card);
}
@Override
public StagBeetle copy() {
return new StagBeetle(this);
}
}
| 0 | 0.930068 | 1 | 0.930068 | game-dev | MEDIA | 0.787113 | game-dev | 0.978949 | 1 | 0.978949 |
webbukkit/dynmap | 19,648 | fabric-1.19.4/src/main/java/org/dynmap/fabric_1_19_4/FabricServer.java | package org.dynmap.fabric_1_19_4;
import com.mojang.authlib.GameProfile;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.minecraft.block.AbstractSignBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.network.message.MessageType;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.server.BannedIpList;
import net.minecraft.server.BannedPlayerList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralTextContent;
import net.minecraft.text.Text;
import net.minecraft.util.UserCache;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import org.dynmap.DynmapChunk;
import org.dynmap.DynmapWorld;
import org.dynmap.Log;
import org.dynmap.DynmapCommonAPIListener;
import org.dynmap.common.BiomeMap;
import org.dynmap.common.DynmapListenerManager;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.common.DynmapServerInterface;
import org.dynmap.fabric_1_19_4.event.BlockEvents;
import org.dynmap.fabric_1_19_4.event.ServerChatEvents;
import org.dynmap.utils.MapChunkCache;
import org.dynmap.utils.VisibilityLimit;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
/**
* Server access abstraction class
*/
public class FabricServer extends DynmapServerInterface {
/* Server thread scheduler */
private final Object schedlock = new Object();
private final DynmapPlugin plugin;
private final MinecraftServer server;
private final Registry<Biome> biomeRegistry;
private long cur_tick;
private long next_id;
private long cur_tick_starttime;
private PriorityQueue<TaskRecord> runqueue = new PriorityQueue<TaskRecord>();
public FabricServer(DynmapPlugin plugin, MinecraftServer server) {
this.plugin = plugin;
this.server = server;
this.biomeRegistry = server.getRegistryManager().get(RegistryKeys.BIOME);
}
private Optional<GameProfile> getProfileByName(String player) {
UserCache cache = server.getUserCache();
return cache.findByName(player);
}
public final Registry<Biome> getBiomeRegistry() {
return biomeRegistry;
}
private Biome[] biomelist = null;
public final Biome[] getBiomeList(Registry<Biome> biomeRegistry) {
if (biomelist == null) {
biomelist = new Biome[256];
Iterator<Biome> iter = biomeRegistry.iterator();
while (iter.hasNext()) {
Biome b = iter.next();
int bidx = biomeRegistry.getRawId(b);
if (bidx >= biomelist.length) {
biomelist = Arrays.copyOf(biomelist, bidx + biomelist.length);
}
biomelist[bidx] = b;
}
}
return biomelist;
}
@Override
public int getBlockIDAt(String wname, int x, int y, int z) {
return -1;
}
@SuppressWarnings("deprecation") /* Not much I can do... fix this if it breaks. */
@Override
public int isSignAt(String wname, int x, int y, int z) {
World world = plugin.getWorldByName(wname).getWorld();
BlockPos pos = new BlockPos(x, y, z);
if (!world.isChunkLoaded(pos))
return -1;
Block block = world.getBlockState(pos).getBlock();
return (block instanceof AbstractSignBlock ? 1 : 0);
}
@Override
public void scheduleServerTask(Runnable run, long delay) {
/* Add task record to queue */
synchronized (schedlock) {
TaskRecord tr = new TaskRecord(cur_tick + delay, next_id++, new FutureTask<Object>(run, null));
runqueue.add(tr);
}
}
@Override
public DynmapPlayer[] getOnlinePlayers() {
if (server.getPlayerManager() == null) return new DynmapPlayer[0];
List<ServerPlayerEntity> players = server.getPlayerManager().getPlayerList();
int playerCount = players.size();
DynmapPlayer[] dplay = new DynmapPlayer[players.size()];
for (int i = 0; i < playerCount; i++) {
ServerPlayerEntity player = players.get(i);
dplay[i] = plugin.getOrAddPlayer(player);
}
return dplay;
}
@Override
public void reload() {
plugin.onDisable();
plugin.onEnable();
plugin.onStart();
}
@Override
public DynmapPlayer getPlayer(String name) {
List<ServerPlayerEntity> players = server.getPlayerManager().getPlayerList();
for (ServerPlayerEntity player : players) {
if (player.getName().getString().equalsIgnoreCase(name)) {
return plugin.getOrAddPlayer(player);
}
}
return null;
}
@Override
public Set<String> getIPBans() {
BannedIpList bl = server.getPlayerManager().getIpBanList();
Set<String> ips = new HashSet<String>();
for (String s : bl.getNames()) {
ips.add(s);
}
return ips;
}
@Override
public <T> Future<T> callSyncMethod(Callable<T> task) {
return callSyncMethod(task, 0);
}
public <T> Future<T> callSyncMethod(Callable<T> task, long delay) {
FutureTask<T> ft = new FutureTask<T>(task);
/* Add task record to queue */
synchronized (schedlock) {
TaskRecord tr = new TaskRecord(cur_tick + delay, next_id++, ft);
runqueue.add(tr);
}
return ft;
}
void clearTaskQueue() {
this.runqueue.clear();
}
@Override
public String getServerName() {
String sn;
if (server.isSingleplayer())
sn = "Integrated";
else
sn = server.getServerIp();
if (sn == null) sn = "Unknown Server";
return sn;
}
@Override
public boolean isPlayerBanned(String pid) {
PlayerManager scm = server.getPlayerManager();
BannedPlayerList bl = scm.getUserBanList();
try {
return bl.contains(getProfileByName(pid).get());
} catch (NoSuchElementException e) {
/* If this profile doesn't exist, default to "banned" for good measure. */
return true;
}
}
@Override
public String stripChatColor(String s) {
return DynmapPlugin.patternControlCode.matcher(s).replaceAll("");
}
private Set<DynmapListenerManager.EventType> registered = new HashSet<DynmapListenerManager.EventType>();
@Override
public boolean requestEventNotification(DynmapListenerManager.EventType type) {
if (registered.contains(type)) {
return true;
}
switch (type) {
case WORLD_LOAD:
case WORLD_UNLOAD:
/* Already called for normal world activation/deactivation */
break;
case WORLD_SPAWN_CHANGE:
/*TODO
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onSpawnChange(SpawnChangeEvent evt) {
DynmapWorld w = new BukkitWorld(evt.getWorld());
core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w);
}
}, DynmapPlugin.this);
*/
break;
case PLAYER_JOIN:
case PLAYER_QUIT:
/* Already handled */
break;
case PLAYER_BED_LEAVE:
/*TODO
pm.registerEvents(new Listener() {
@EventHandler(priority=EventPriority.MONITOR)
public void onPlayerBedLeave(PlayerBedLeaveEvent evt) {
DynmapPlayer p = new BukkitPlayer(evt.getPlayer());
core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p);
}
}, DynmapPlugin.this);
*/
break;
case PLAYER_CHAT:
if (plugin.chathandler == null) {
plugin.setChatHandler(new DynmapPlugin.ChatHandler(plugin));
ServerChatEvents.EVENT.register((player, message) -> plugin.chathandler.handleChat(player, message));
}
break;
case BLOCK_BREAK:
/* Already handled by BlockEvents logic */
break;
case SIGN_CHANGE:
BlockEvents.SIGN_CHANGE_EVENT.register((world, pos, lines, material, player) -> {
plugin.core.processSignChange("fabric", FabricWorld.getWorldName(plugin, world),
pos.getX(), pos.getY(), pos.getZ(), lines, player.getName().getString());
});
break;
default:
Log.severe("Unhandled event type: " + type);
return false;
}
registered.add(type);
return true;
}
@Override
public boolean sendWebChatEvent(String source, String name, String msg) {
return DynmapCommonAPIListener.fireWebChatEvent(source, name, msg);
}
@Override
public void broadcastMessage(String msg) {
Text component = Text.literal(msg);
server.getPlayerManager().broadcast(component, false);
Log.info(stripChatColor(msg));
}
@Override
public String[] getBiomeIDs() {
BiomeMap[] b = BiomeMap.values();
String[] bname = new String[b.length];
for (int i = 0; i < bname.length; i++) {
bname[i] = b[i].toString();
}
return bname;
}
@Override
public double getCacheHitRate() {
if (plugin.sscache != null)
return plugin.sscache.getHitRate();
return 0.0;
}
@Override
public void resetCacheStats() {
if (plugin.sscache != null)
plugin.sscache.resetStats();
}
@Override
public DynmapWorld getWorldByName(String wname) {
return plugin.getWorldByName(wname);
}
@Override
public DynmapPlayer getOfflinePlayer(String name) {
/*
OfflinePlayer op = getServer().getOfflinePlayer(name);
if(op != null) {
return new BukkitPlayer(op);
}
*/
return null;
}
@Override
public Set<String> checkPlayerPermissions(String player, Set<String> perms) {
if (isPlayerBanned(player)) {
return Collections.emptySet();
}
Set<String> rslt = plugin.hasOfflinePermissions(player, perms);
if (rslt == null) {
rslt = new HashSet<String>();
if (plugin.isOp(player)) {
rslt.addAll(perms);
}
}
return rslt;
}
@Override
public boolean checkPlayerPermission(String player, String perm) {
if (isPlayerBanned(player)) {
return false;
}
return plugin.hasOfflinePermission(player, perm);
}
/**
* Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread
*/
@Override
public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks,
boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) {
FabricMapChunkCache c = (FabricMapChunkCache) w.getChunkCache(chunks);
if (c == null) {
return null;
}
if (w.visibility_limits != null) {
for (VisibilityLimit limit : w.visibility_limits) {
c.setVisibleRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if (w.hidden_limits != null) {
for (VisibilityLimit limit : w.hidden_limits) {
c.setHiddenRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
if (!c.setChunkDataTypes(blockdata, biome, highesty, rawbiome)) {
Log.severe("CraftBukkit build does not support biome APIs");
}
if (chunks.size() == 0) /* No chunks to get? */ {
c.loadChunks(0);
return c;
}
//Now handle any chunks in server thread that are already loaded (on server thread)
final FabricMapChunkCache cc = c;
Future<Boolean> f = this.callSyncMethod(new Callable<Boolean>() {
public Boolean call() throws Exception {
// Update busy state on world
//FabricWorld fw = (FabricWorld) cc.getWorld();
//TODO
//setBusy(fw.getWorld());
cc.getLoadedChunks();
return true;
}
}, 0);
try {
f.get();
} catch (CancellationException cx) {
return null;
} catch (InterruptedException cx) {
return null;
} catch (ExecutionException xx) {
Log.severe("Exception while loading chunks", xx.getCause());
return null;
} catch (Exception ix) {
Log.severe(ix);
return null;
}
if (!w.isLoaded()) {
return null;
}
// Now, do rest of chunk reading from calling thread
c.readChunks(chunks.size());
return c;
}
@Override
public int getMaxPlayers() {
return server.getMaxPlayerCount();
}
@Override
public int getCurrentPlayers() {
return server.getPlayerManager().getCurrentPlayerCount();
}
public void tickEvent(MinecraftServer server) {
cur_tick_starttime = System.nanoTime();
long elapsed = cur_tick_starttime - plugin.lasttick;
plugin.lasttick = cur_tick_starttime;
plugin.avgticklen = ((plugin.avgticklen * 99) / 100) + (elapsed / 100);
plugin.tps = (double) 1E9 / (double) plugin.avgticklen;
// Tick core
if (plugin.core != null) {
plugin.core.serverTick(plugin.tps);
}
boolean done = false;
TaskRecord tr = null;
while (!plugin.blockupdatequeue.isEmpty()) {
DynmapPlugin.BlockUpdateRec r = plugin.blockupdatequeue.remove();
BlockState bs = r.w.getBlockState(new BlockPos(r.x, r.y, r.z));
int idx = Block.STATE_IDS.getRawId(bs);
if (!org.dynmap.hdmap.HDBlockModels.isChangeIgnoredBlock(DynmapPlugin.stateByID[idx])) {
if (plugin.onblockchange_with_id)
plugin.mapManager.touch(r.wid, r.x, r.y, r.z, "blockchange[" + idx + "]");
else
plugin.mapManager.touch(r.wid, r.x, r.y, r.z, "blockchange");
}
}
long now;
synchronized (schedlock) {
cur_tick++;
now = System.nanoTime();
tr = runqueue.peek();
/* Nothing due to run */
if ((tr == null) || (tr.getTickToRun() > cur_tick) || ((now - cur_tick_starttime) > plugin.perTickLimit)) {
done = true;
} else {
tr = runqueue.poll();
}
}
while (!done) {
tr.run();
synchronized (schedlock) {
tr = runqueue.peek();
now = System.nanoTime();
/* Nothing due to run */
if ((tr == null) || (tr.getTickToRun() > cur_tick) || ((now - cur_tick_starttime) > plugin.perTickLimit)) {
done = true;
} else {
tr = runqueue.poll();
}
}
}
while (!plugin.msgqueue.isEmpty()) {
DynmapPlugin.ChatMessage cm = plugin.msgqueue.poll();
DynmapPlayer dp = null;
if (cm.sender != null)
dp = plugin.getOrAddPlayer(cm.sender);
else
dp = new FabricPlayer(plugin, null);
plugin.core.listenerManager.processChatEvent(DynmapListenerManager.EventType.PLAYER_CHAT, dp, cm.message);
}
// Check for generated chunks
if ((cur_tick % 20) == 0) {
}
}
private Optional<ModContainer> getModContainerById(String id) {
return FabricLoader.getInstance().getModContainer(id);
}
@Override
public boolean isModLoaded(String name) {
return FabricLoader.getInstance().getModContainer(name).isPresent();
}
@Override
public String getModVersion(String name) {
Optional<ModContainer> mod = getModContainerById(name); // Try case sensitive lookup
return mod.map(modContainer -> modContainer.getMetadata().getVersion().getFriendlyString()).orElse(null);
}
@Override
public double getServerTPS() {
return plugin.tps;
}
@Override
public String getServerIP() {
if (server.isSingleplayer())
return "0.0.0.0";
else
return server.getServerIp();
}
@Override
public File getModContainerFile(String name) {
Optional<ModContainer> container = getModContainerById(name); // Try case sensitive lookup
if (container.isPresent()) {
Path path = container.get().getRootPath();
if (path.getFileSystem().provider().getScheme().equals("jar")) {
path = Paths.get(path.getFileSystem().toString());
}
return path.toFile();
}
return null;
}
@Override
public List<String> getModList() {
return FabricLoader.getInstance()
.getAllMods()
.stream()
.map(container -> container.getMetadata().getId())
.collect(Collectors.toList());
}
@Override
public Map<Integer, String> getBlockIDMap() {
Map<Integer, String> map = new HashMap<Integer, String>();
return map;
}
@Override
public InputStream openResource(String modid, String rname) {
if (modid == null) modid = "minecraft";
if ("minecraft".equals(modid)) {
return MinecraftServer.class.getClassLoader().getResourceAsStream(rname);
} else {
if (rname.startsWith("/") || rname.startsWith("\\")) {
rname = rname.substring(1);
}
final String finalModid = modid;
final String finalRname = rname;
return getModContainerById(modid).map(container -> {
try {
return Files.newInputStream(container.getPath(finalRname));
} catch (IOException e) {
Log.severe("Failed to load resource of mod :" + finalModid, e);
return null;
}
}).orElse(null);
}
}
/**
* Get block unique ID map (module:blockid)
*/
@Override
public Map<String, Integer> getBlockUniqueIDMap() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
/**
* Get item unique ID map (module:itemid)
*/
@Override
public Map<String, Integer> getItemUniqueIDMap() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
}
| 0 | 0.949806 | 1 | 0.949806 | game-dev | MEDIA | 0.889654 | game-dev | 0.972268 | 1 | 0.972268 |
StrickenFromHistory/PocketMonstersOnline | 19,562 | Client/src/org/pokenet/client/backend/ClientMap.java | package org.pokenet.client.backend;
import java.util.Iterator;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.tiled.Layer;
import org.newdawn.slick.tiled.TiledMap;
import org.pokenet.client.GameClient;
import org.pokenet.client.backend.entity.HMObject;
import org.pokenet.client.backend.entity.Player;
import org.pokenet.client.backend.entity.Player.Direction;
/**
* Represents a map to be rendered on screen
*
* @author shadowkanji
* @author ZombieBear
*
*/
public class ClientMap extends TiledMap {
// map offset modifiers
private int m_xOffsetModifier;
private int m_yOffsetModifier;
private int m_xOffset;
private int m_yOffset;
private int m_mapX;
private int m_mapY;
public int m_x;
public int m_y;
private boolean m_isCurrent = false;
private ClientMapMatrix m_mapMatrix;
private int m_walkableLayer;
private String m_name;
private Image m_grassOverlay;
/**
* Default constructor
*
* @param f
* @param tileSetsLocation
* @throws SlickException
*/
public ClientMap(String tileSetsLocation)
throws SlickException {
super(tileSetsLocation);
String respath = System.getProperty("res.path");
if(respath==null)
respath="";
try {
m_grassOverlay = new Image(respath+"res/ui/grass_overlay.png", false);
} catch (Exception e) {
e.printStackTrace();
}
m_xOffsetModifier = Integer.parseInt(getMapProperty("xOffsetModifier",
"0").trim());
m_yOffsetModifier = Integer.parseInt(getMapProperty("yOffsetModifier",
"0").trim());
m_xOffset = m_xOffsetModifier;
m_yOffset = m_yOffsetModifier;
}
/**
* Returns true if this map is/should be rendering on screen
*
* @return
*/
public boolean isRendering() {
int drawWidth = getXOffset() + getWidth() * 32;
int drawHeight = getYOffset() + getHeight() * 32;
if (!(drawWidth < -32 && getXOffset() < -32 || drawWidth > 832
&& getXOffset() > 832)
&& !(drawHeight < -32 && getYOffset() < -32 || drawHeight > 632
&& getYOffset() > 632)) {
return true;
}
return false;
}
/**
* Returns the X offset of this map
*
* @return
*/
public int getXOffset() {
return m_xOffset;
}
/**
* Returns the Y offset of this map
*
* @return
*/
public int getYOffset() {
return m_yOffset;
}
/**
* Returns the index of the walkable layer
*
* @return
*/
public int getWalkableLayer() {
return m_walkableLayer;
}
/**
* Set to true if this is at 1,1 in the map matrix
*
* @param b
*/
public void setCurrent(boolean b) {
m_isCurrent = b;
}
/**
* Returns true if this is 1,1 in the map matrix
*
* @return
*/
public boolean isCurrent() {
return m_isCurrent;
}
/**
* Sets the map matrix
*
* @param m
*/
public void setMapMatrix(ClientMapMatrix m) {
m_mapMatrix = m;
}
/**
* Sets the map x (in map matrix)
*
* @param x
*/
public void setMapX(int x) {
m_mapX = x;
}
/**
* Sets the map y (in map matrix)
*
* @param y
*/
public void setMapY(int y) {
m_mapY = y;
}
/**
* Returns the x offset modifier
*
* @return
*/
public int getXOffsetModifier() {
return m_xOffsetModifier;
}
/**
* Returns the y offset modifier
*
* @return
*/
public int getYOffsetModifier() {
return m_yOffsetModifier;
}
/**
* Returns true if x or y if off the map
*
* @param x
* @param y
* @return
*/
private boolean isNewMap(int x, int y) {
return x < 0 || x >= this.getWidth() * 32 || y < 0
|| y + 8 >= this.getHeight() * 32;
}
/**
* Reinitializes a map after shifting in the map matrix
*/
public void reinitialize(){
m_xOffsetModifier = Integer.parseInt(getMapProperty("xOffsetModifier", "0").trim());
m_yOffsetModifier = Integer.parseInt(getMapProperty("yOffsetModifier", "0").trim());
m_xOffset = m_xOffsetModifier;
m_yOffset = m_yOffsetModifier;
}
/**
* Returns true if the player is colliding with an object
*
* @param p
* @param d
* @return
*/
public boolean isColliding(Player p, Direction d) {
int newX = 0, newY = 0;
switch (d) {
case Up:
newX = p.getServerX();
newY = p.getServerY() - 32;
break;
case Down:
newX = p.getServerX();
newY = p.getServerY() + 32;
break;
case Left:
newX = p.getServerX() - 32;
newY = p.getServerY();
break;
case Right:
newX = p.getServerX() + 32;
newY = p.getServerY();
break;
}
if (isNewMap(newX, newY))
return false;
for (HMObject m_hmObj : m_mapMatrix.getHMObjects()){
if (m_hmObj.getX() == newX && m_hmObj.getY() == newY){
return true;
}
}
int collisionLayer = 0;
int waterLayer = 0;
int ledgeLayer = 0;
for (int i = 0; i < getLayerCount(); i++){
//Test for collisions
if (getLayer(i).name.equals("Collisions") && collisionLayer == 0){
collisionLayer = getLayer(i).getTileID(newX / 32,
(newY + 8) / 32);
} else if (getLayer(i).name.equals("Water") && waterLayer == 0
&& GameClient.getInstance().getOurPlayer().getTrainerLevel() < 25){
waterLayer = getLayer(i).getTileID(newX / 32,
(newY + 8) / 32);
} else { //Test for ledges
if (p.getDirection() != Direction.Left
&& getLayer("LedgesLeft") != null){
ledgeLayer = getLayer("LedgesLeft").getTileID(newX / 32,
(newY + 8) / 32);
}
if (p.getDirection() != Direction.Right
&& getLayer("LedgesRight") != null
&& ledgeLayer == 0){
ledgeLayer = getLayer("LedgesRight").getTileID(newX / 32,
(newY + 8) / 32);
}
if (p.getDirection() != Direction.Down
&& getLayer("LedgesDown") != null
&& ledgeLayer == 0){
ledgeLayer = getLayer("LedgesDown").getTileID(newX / 32,
(newY + 8) / 32);
}
}
}
if (ledgeLayer + collisionLayer + waterLayer != 0)
return true;
/* Check NPCs */
for(int i = 0; i < m_mapMatrix.getPlayers().size(); i++) {
Player tmp = m_mapMatrix.getPlayers().get(i);
if(tmp.getUsername().equalsIgnoreCase("!NPC!") &&
tmp.getX() == newX && tmp.getY() == newY)
return true;
}
return false;
}
/**
* Returns true if a reflection should be drawn
*
* @param p
* @return
*/
public boolean shouldReflect(Player p) {
int newX = 0, newY = 0;
newX = p.getServerX();
newY = p.getServerY() + 32;
try {
if (getTileProperty(
getLayer("Water").getTileID(newX / 32, (newY + 8) / 32),
"Reflection", "").equalsIgnoreCase("true"))
return true;
if (getTileProperty(
getLayer("Walkable").getTileID(newX / 32, (newY + 8) / 32),
"Reflection", "").equalsIgnoreCase("true"))
return true;
for (int i = 0; i < getLayerCount(); i++) {
if (getTileProperty(
getLayer(i).getTileID(newX / 32, (newY + 8) / 32),
"Reflection", "").equalsIgnoreCase("true"))
return true;
}
} catch (Exception e) {
}
return false;
}
/**
* Returns true if the grass overlay should be drawn
*
* @param p
* @return
*/
public boolean isOnGrass(Player p) {
int newX = 0, newY = 0;
newX = p.getServerX();
newY = p.getServerY();
try {
if (getTileProperty(
getLayer("Walkable").getTileID(newX / 32, (newY + 8) / 32),
"Grass", "").equalsIgnoreCase("true"))
return true;
for (int i = 0; i < getLayerCount(); i++) {
if (getTileProperty(
getLayer(i).getTileID(newX / 32, (newY + 8) / 32),
"Grass", "").equalsIgnoreCase("true"))
return true;
}
} catch (Exception e) {
}
return false;
}
/**
* Returns true if a the previous grass overlay should be drawn
*
* @param p
* @return
*/
public boolean wasOnGrass(Player p) {
int newX = 0, newY = 0;
newX = p.getServerX();
newY = p.getServerY();
switch (p.getDirection()) {
case Up:
newY += 32;
break;
case Down:
newY -= 32;
break;
case Left:
newX += 32;
break;
case Right:
newX -= 32;
break;
}
try {
if (getTileProperty(
getLayer("Walkable").getTileID(newX / 32, (newY + 8) / 32),
"Grass", "").equalsIgnoreCase("true"))
return true;
for (int i = 0; i < getLayerCount(); i++) {
if (getTileProperty(
getLayer(i).getTileID(newX / 32, (newY + 8) / 32),
"Grass", "").equalsIgnoreCase("true"))
return true;
}
} catch (Exception e) {
}
return false;
}
/**
* Returns a layer by its index
*
* @param layer
* @return
*/
private Layer getLayer(int layer) {
return (Layer) layers.get(layer);
}
/**
* Returns a layer by its name
*
* @param layer
* @return
*/
private Layer getLayer(String layer) {
int idx = this.getLayerIndex(layer);
return (idx < 0 ? null : getLayer(idx));
}
/**
* Sets the y offset and recalibrates surrounding maps if calibrate is true
*
* @param offset
* @param calibrate
*/
public void setYOffset(int offset, boolean calibrate) {
m_yOffset = offset;
if (calibrate) {
// 0, 1 -- Left
ClientMap map = m_mapMatrix.getMap(m_mapX - 1, m_mapY);
if (map != null)
map.setYOffset(offset - getYOffsetModifier()
+ map.getYOffsetModifier(), false);
// 2, 1 -- Right
map = m_mapMatrix.getMap(m_mapX + 1, m_mapY);
if (map != null)
map.setYOffset(offset - getYOffsetModifier()
+ map.getYOffsetModifier(), false);
// 1, 0 -- Top
map = m_mapMatrix.getMap(m_mapX, m_mapY - 1);
if (map != null)
map.setYOffset(offset - map.getHeight() * 32, false);
// 1, 2 -- Bottom
map = m_mapMatrix.getMap(m_mapX, m_mapY + 1);
if (map != null) {
map.setYOffset(offset + getHeight() * 32, false);
}
// 2, 0 -- Upper Right
map = m_mapMatrix.getMap(m_mapX + 1, m_mapY - 1);
if (map != null) {
if (m_mapMatrix.getMap(2, 1) != null) { // The right map exists
map.setYOffset(m_mapMatrix.getMap(2, 1).m_yOffset
- map.getHeight() * 32, false);
} else if (m_mapMatrix.getMap(1, 0) != null) { // The top map
// exists
map.setYOffset(m_mapMatrix.getMap(1, 0).m_yOffset
- m_mapMatrix.getMap(1, 0).m_yOffsetModifier
+ map.getYOffsetModifier(), false);
} else { // Try in previous way
map.setYOffset(offset - map.getHeight() * 32, false);
}
}
// 0, 0 -- Upper Left
map = m_mapMatrix.getMap(m_mapX - 1, m_mapY - 1);
if (map != null) { // The top map exists
if (m_mapMatrix.getMap(0, 1) != null) { // The left map exists
map.setYOffset(m_mapMatrix.getMap(0, 1).m_yOffset
- map.getHeight() * 32, false);
} else if (m_mapMatrix.getMap(1, 0) != null) { // The top map
// exists
map.setYOffset(m_mapMatrix.getMap(1, 0).m_yOffset
- m_mapMatrix.getMap(1, 0).m_yOffsetModifier
+ map.getYOffsetModifier(), false);
} else { // Try in previous way
map.setYOffset(offset - map.getHeight() * 32, false);
}
}
// 2, 2 -- Lower Right
map = m_mapMatrix.getMap(m_mapX + 1, m_mapY + 1);
if (map != null) {
if (m_mapMatrix.getMap(1, 2) != null) { // The bottom map exists
map.setYOffset(m_mapMatrix.getMap(1, 2).m_yOffset
- m_mapMatrix.getMap(1, 2).m_yOffsetModifier
+ map.getYOffsetModifier(), false);
} else if (m_mapMatrix.getMap(2, 1) != null) { // The right map
// exists
map.setYOffset(m_mapMatrix.getMap(2, 1).m_yOffset
+ m_mapMatrix.getMap(2, 1).getHeight() * 32, false);
} else { // Try in previous way
System.out.println("else");
map.setYOffset(offset + getHeight() * 32, false);
}
}
// 0, 2 -- Lower Left
map = m_mapMatrix.getMap(m_mapX - 1, m_mapY + 1);
if (map != null) {
if (m_mapMatrix.getMap(0, 1) != null) { // The left map exists
map.setYOffset(m_mapMatrix.getMap(0, 1).m_yOffset
+ m_mapMatrix.getMap(0, 1).getHeight() * 32, false);
} else if (m_mapMatrix.getMap(1, 2) != null) { // The bottom map
// exists
map.setYOffset(m_mapMatrix.getMap(1, 2).m_yOffset
- m_mapMatrix.getMap(1, 2).m_yOffsetModifier
+ map.getYOffsetModifier(), false);
} else {
map.setYOffset(offset + getHeight() * 32, false);
}
}
}
}
/**
* Sets the x offset and recalibrates surrounding maps if calibrate is set
* to true
*
* @param offset
* @param calibrate
*/
public void setXOffset(int offset, boolean calibrate) {
m_xOffset = offset;
if (calibrate) {
// int thisX = (this.getXOffset() + (this.getWidth() * 32));
// 0, 1 -- Left
ClientMap map = m_mapMatrix.getMap(m_mapX - 1, m_mapY);
if (map != null)
map.setXOffset(offset - map.getWidth() * 32 - m_xOffsetModifier
+ map.getXOffsetModifier(), false);
// 2, 1 -- Right
map = m_mapMatrix.getMap(m_mapX + 1, m_mapY);
if (map != null)
map.setXOffset(offset + getWidth() * 32 - getXOffsetModifier()
+ map.getXOffsetModifier(), false);
// 1, 0 -- Up
map = m_mapMatrix.getMap(m_mapX, m_mapY - 1);
if (map != null)
map.setXOffset(offset - getXOffsetModifier()
+ map.getXOffsetModifier(), false);
// 1, 2 -- Down
map = m_mapMatrix.getMap(m_mapX, m_mapY + 1);
if (map != null)
map.setXOffset(offset - getXOffsetModifier()
+ map.getXOffsetModifier(), false);
// 0, 0 -- Upper Left
map = m_mapMatrix.getMap(m_mapX - 1, m_mapY - 1);
if (map != null) {
if (m_mapMatrix.getMap(0, 1) != null) { // The left map exists
map.setXOffset(m_mapMatrix.getMap(0, 1).m_xOffset
- m_mapMatrix.getMap(0, 1).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else if (m_mapMatrix.getMap(1, 0) != null) { // The top map
// exists
map.setXOffset(m_mapMatrix.getMap(1, 0).m_xOffset
- map.getWidth() * 32
- m_mapMatrix.getMap(1, 0).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else { // Try in previous way
map.setXOffset(offset - map.getWidth() * 32
- getXOffsetModifier() + map.getXOffsetModifier(),
false);
}
}
// 2, 0 -- Upper Right
map = m_mapMatrix.getMap(m_mapX + 1, m_mapY - 1);
if (map != null) {
if (m_mapMatrix.getMap(2, 1) != null) { // The right map exists
map.setXOffset(m_mapMatrix.getMap(2, 1).m_xOffset
- m_mapMatrix.getMap(2, 1).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else if (m_mapMatrix.getMap(1, 0) != null) { // The top map
// exists
map.setXOffset(m_mapMatrix.getMap(1, 0).m_xOffset
+ m_mapMatrix.getMap(1, 0).getWidth() * 32
- m_mapMatrix.getMap(1, 0).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else { // Try in previous way
map.setXOffset(offset - map.getWidth() * 32
- getXOffsetModifier() + map.getXOffsetModifier(),
false);
}
}
// 2, 2 -- Lower Right
map = m_mapMatrix.getMap(m_mapX + 1, m_mapY + 1);
if (map != null) {
if (m_mapMatrix.getMap(2, 1) != null) { // The right map exists
map.setXOffset(m_mapMatrix.getMap(2, 1).m_xOffset
- m_mapMatrix.getMap(2, 1).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else if (m_mapMatrix.getMap(1, 2) != null) { // The Bottom map
// exists
map.setXOffset(m_mapMatrix.getMap(1, 2).m_xOffset
+ m_mapMatrix.getMap(1, 2).getWidth() * 32
- m_mapMatrix.getMap(1, 2).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else { // Try in previous way
map.setXOffset(offset + getWidth() * 32
- getXOffsetModifier() + map.getXOffsetModifier(),
false);
}
}
// 0, 2 -- Lower Left
map = m_mapMatrix.getMap(m_mapX - 1, m_mapY + 1);
if (map != null) {
if (m_mapMatrix.getMap(0, 1) != null) { // The left map exists
map.setXOffset(m_mapMatrix.getMap(0, 1).m_xOffset
- m_mapMatrix.getMap(0, 1).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else if (m_mapMatrix.getMap(1, 2) != null) { // The bottom map
// exists
map.setXOffset(m_mapMatrix.getMap(1, 2).m_xOffset
- map.getWidth() * 32
- m_mapMatrix.getMap(1, 2).m_xOffsetModifier
+ map.getXOffsetModifier(), false);
} else { // Try in previous way
map.setXOffset(offset + getWidth() * 32
- getXOffsetModifier() + map.getXOffsetModifier(),
false);
}
}
}
}
@Override
public void render(int x, int y, int sx, int sy, int width, int height,
boolean lineByLine) {
for (int ty = 0; ty < height; ty++) {
for (int i = 0; i < layers.size(); i++) {
Layer layer = (Layer) layers.get(i);
if (!m_isCurrent) {
layer.render(x, y, sx, sy, width, ty, lineByLine,
tileWidth, tileHeight);
} else if (!layer.name.equalsIgnoreCase("WalkBehind")) {
layer.render(x, y, sx, sy, width, ty, lineByLine,
tileWidth, tileHeight);
}
}
}
}
/**
* Renders the player, water reflections, grass overlays, and the WalkBehind
* layer.
*
* @param g
*/
public void renderTop(Graphics g) {
synchronized (m_mapMatrix.getPlayers()) {
Player p;
Iterator<Player> it = m_mapMatrix.getPlayers().iterator();
while (it.hasNext()) {
p = it.next();
ClientMap m_curMap = m_mapMatrix.getCurrentMap();
int m_xOffset = m_curMap.getXOffset();
int m_yOffset = m_curMap.getYOffset();
if (p != null && p.getSprite() != 0
&& (p.getCurrentImage() != null)) {
// Draw the player
p.getCurrentImage().draw(m_xOffset + p.getX() - 4,
m_yOffset + p.getY());
if (m_curMap.shouldReflect(p)) {
// If there's a reflection, flip the player's image, set
// his alpha so its more translucent, and then draw it.
Image m_reflection = p.getCurrentImage()
.getFlippedCopy(false, true);
m_reflection.setAlpha((float) 0.05);
if (p.getSprite() != -1)
m_reflection.draw(m_xOffset + p.getX() - 4,
m_yOffset + p.getY() + 32);
else {
m_reflection.draw(m_xOffset + p.getX() - 4,
m_yOffset + p.getY() + 8);
}
}
if (m_curMap.wasOnGrass(p) && m_curMap.isOnGrass(p)) {
switch (p.getDirection()) {
case Up:
m_grassOverlay.draw(m_xOffset + p.getServerX(),
m_yOffset + p.getServerY() + 32 + 8);
break;
case Left:
m_grassOverlay.copy().draw(
m_xOffset + p.getServerX() + 32,
m_yOffset + p.getServerY() + 8);
break;
case Right:
m_grassOverlay.copy().draw(
m_xOffset + p.getServerX() - 32,
m_yOffset + p.getServerY() + 8);
break;
}
}
if (m_curMap.isOnGrass(p) && p.getY() <= p.getServerY()) {
m_grassOverlay.draw(m_xOffset + p.getServerX(),
m_yOffset + p.getServerY() + 9);
}
// Draw the walk behind layer
g.scale(2, 2);
try{
for (int i = 0; i < getLayer("WalkBehind").height; i++) {
getLayer("WalkBehind").render(
getXOffset() / 2,
getYOffset() / 2,
0,
0,
(int) (GameClient.getInstance().getDisplay()
.getWidth() - getXOffset()) / 32 + 32,
i, false, 16, 16);
}
} catch (Exception e) {}
g.resetTransform();
// Draw player names
if(!p.getUsername().equalsIgnoreCase("!NPC!"))
g.drawString(p.getUsername(), m_xOffset
+ (p.getX() - (g.getFont()
.getWidth(p.getUsername()) / 2)) + 16,
m_yOffset + p.getY() - 36);
}
}
}
}
/**
* Returns the map's name
*
* @return the map's name
*/
public String getName() {
return m_name;
}
/**
* Sets the map's name
*
* @param name
*/
public void setName(String name) {
m_name = name;
}
public int getMapX() {
return m_mapX;
}
public int getMapY() {
return m_mapY;
}
}
| 0 | 0.97394 | 1 | 0.97394 | game-dev | MEDIA | 0.749328 | game-dev | 0.993308 | 1 | 0.993308 |
Space-Stories/space-station-14 | 3,656 | Content.Server/NPC/HTN/PrimitiveTasks/Operators/Interactions/InteractWithOperator.cs | using Content.Server.Interaction;
using Content.Shared.CombatMode;
using Content.Shared.DoAfter;
using Content.Shared.Timing;
namespace Content.Server.NPC.HTN.PrimitiveTasks.Operators.Interactions;
public sealed partial class InteractWithOperator : HTNOperator
{
[Dependency] private readonly IEntityManager _entManager = default!;
private SharedDoAfterSystem _doAfterSystem = default!;
public override void Initialize(IEntitySystemManager sysManager)
{
base.Initialize(sysManager);
_doAfterSystem = sysManager.GetEntitySystem<SharedDoAfterSystem>();
}
/// <summary>
/// Key that contains the target entity.
/// </summary>
[DataField(required: true)]
public string TargetKey = default!;
/// <summary>
/// Exit with failure if doafter wasn't raised
/// </summary>
[DataField]
public bool ExpectDoAfter = false;
public string CurrentDoAfter = "CurrentInteractWithDoAfter";
// Ensure that CurrentDoAfter doesn't exist as we enter this operator,
// the code currently relies on the result of a TryGetValue
public override void Startup(NPCBlackboard blackboard)
{
blackboard.Remove<ushort>(CurrentDoAfter);
}
// Not really sure if we should clean it up, I guess some operator could use it
public override void TaskShutdown(NPCBlackboard blackboard, HTNOperatorStatus status)
{
blackboard.Remove<ushort>(CurrentDoAfter);
}
public override HTNOperatorStatus Update(NPCBlackboard blackboard, float frameTime)
{
var owner = blackboard.GetValue<EntityUid>(NPCBlackboard.Owner);
// Handle ongoing doAfter, and store the doAfter.nextId so we can detect if we started one
ushort nextId = 0;
if (_entManager.TryGetComponent<DoAfterComponent>(owner, out var doAfter))
{
// if CurrentDoAfter contains something, we have an active doAfter
if (blackboard.TryGetValue<ushort>(CurrentDoAfter, out var doAfterId, _entManager))
{
var status = _doAfterSystem.GetStatus(owner, doAfterId, null);
return status switch
{
DoAfterStatus.Running => HTNOperatorStatus.Continuing,
DoAfterStatus.Finished => HTNOperatorStatus.Finished,
_ => HTNOperatorStatus.Failed
};
}
nextId = doAfter.NextId;
}
if (_entManager.TryGetComponent<UseDelayComponent>(owner, out var useDelay) && _entManager.System<UseDelaySystem>().IsDelayed((owner, useDelay)) ||
!blackboard.TryGetValue<EntityUid>(TargetKey, out var moveTarget, _entManager) ||
!_entManager.TryGetComponent<TransformComponent>(moveTarget, out var targetXform))
{
return HTNOperatorStatus.Continuing;
}
if (_entManager.TryGetComponent<CombatModeComponent>(owner, out var combatMode))
{
_entManager.System<SharedCombatModeSystem>().SetInCombatMode(owner, false, combatMode);
}
_entManager.System<InteractionSystem>().UserInteraction(owner, targetXform.Coordinates, moveTarget);
// Detect doAfter, save it, and don't exit from this operator
if (doAfter != null && nextId != doAfter.NextId)
{
blackboard.SetValue(CurrentDoAfter, nextId);
return HTNOperatorStatus.Continuing;
}
// We shouldn't arrive here if we start a doafter, so fail if we expected a doafter
if(ExpectDoAfter)
return HTNOperatorStatus.Failed;
return HTNOperatorStatus.Finished;
}
}
| 0 | 0.892524 | 1 | 0.892524 | game-dev | MEDIA | 0.92479 | game-dev | 0.967864 | 1 | 0.967864 |
aysihuniks/NClaim | 2,817 | src/main/java/nesoi/aysihuniks/nclaim/utils/FarmerListener.java | package nesoi.aysihuniks.nclaim.utils;
import nesoi.aysihuniks.nclaim.NClaim;
import nesoi.aysihuniks.nclaim.api.events.*;
import nesoi.aysihuniks.nclaim.model.Claim;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.nandayo.dapi.message.ChannelType;
import xyz.geik.farmer.Main;
import xyz.geik.farmer.api.handlers.FarmerBoughtEvent;
import xyz.geik.farmer.api.managers.FarmerManager;
import xyz.geik.farmer.model.Farmer;
import xyz.geik.farmer.model.user.FarmerPerm;
import xyz.geik.farmer.model.user.User;
import java.util.Optional;
import java.util.UUID;
public class FarmerListener implements Listener {
@EventHandler
public void buyClaim(ClaimCreateEvent event) {
String claimId = event.getClaim().getClaimId();
if(Main.getConfigFile().getSettings().isAutoCreateFarmer()) {
new Farmer("nclaim_" + claimId, 0, event.getSender().getUniqueId());
ChannelType.CHAT.send(event.getSender(), Main.getLangFile().getMessages().getBoughtFarmer());
}
}
@EventHandler
public void addCoop(ClaimCoopAddEvent event) {
Claim claim = event.getClaim();
if (!FarmerManager.getFarmers().containsKey(claim.getClaimId())) return;
Player coopPlayer = event.getCoopPlayer();
FarmerManager.getFarmers().get(claim.getClaimId()).addUser(coopPlayer.getUniqueId(), coopPlayer.getName(), FarmerPerm.COOP);
}
@EventHandler
public void kickCoop(ClaimCoopRemoveEvent event) {
Claim claim = event.getClaim();
if (!FarmerManager.getFarmers().containsKey(claim.getClaimId())) return;
UUID coopPlayer = event.getCoopPlayerUUID();
Optional<User> user = FarmerManager.getFarmers().get(claim.getClaimId()).getUsers().stream().filter(u -> u.getUuid().equals(coopPlayer)).findFirst();
user.ifPresent(FarmerManager.getFarmers().get(claim.getClaimId())::removeUser);
}
@EventHandler
public void removeClaim(ClaimRemoveEvent event) {
Claim claim = event.getClaim();
if (!FarmerManager.getFarmers().containsKey(claim.getClaimId())) return;
FarmerManager.getFarmers().remove(claim.getClaimId());
}
@EventHandler
public void buyFarmer(FarmerBoughtEvent event) {
String farmerRegionId = event.getFarmer().getRegionID();
Optional<Claim> claim = Claim.getClaims().stream()
.filter(c -> c.getClaimId().equals(farmerRegionId))
.findFirst();
if (!claim.isPresent()) return;
for (UUID coopPlayer : claim.get().getCoopPlayers()) {
String playerName = NClaim.inst().getServer().getOfflinePlayer(coopPlayer).getName();
event.getFarmer().addUser(coopPlayer, playerName, FarmerPerm.COOP);
}
}
}
| 0 | 0.846068 | 1 | 0.846068 | game-dev | MEDIA | 0.499295 | game-dev,web-backend | 0.921171 | 1 | 0.921171 |
mini2Dx/mini2Dx | 9,040 | ui/src/main/java/org/mini2Dx/ui/element/CustomUiElement.java | /*******************************************************************************
* Copyright 2019 See AUTHORS file
*
* 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 org.mini2Dx.ui.element;
import org.mini2Dx.gdx.utils.Array;
import org.mini2Dx.core.Graphics;
import org.mini2Dx.core.serialization.annotation.ConstructorArg;
import org.mini2Dx.core.serialization.annotation.Field;
import org.mini2Dx.ui.UiContainer;
import org.mini2Dx.ui.event.ActionEvent;
import org.mini2Dx.ui.event.ActionEventPool;
import org.mini2Dx.ui.event.EventTrigger;
import org.mini2Dx.ui.event.params.EventTriggerParams;
import org.mini2Dx.ui.layout.ScreenSize;
import org.mini2Dx.ui.listener.ActionListener;
import org.mini2Dx.ui.render.CustomUiElementRenderNode;
import org.mini2Dx.ui.render.ImageRenderNode;
import org.mini2Dx.ui.render.ParentRenderNode;
import org.mini2Dx.ui.render.UiContainerRenderTree;
import org.mini2Dx.ui.style.StyleRule;
/**
* Base class for implementing custom {@link UiElement}s
*/
public abstract class CustomUiElement extends UiElement implements Actionable {
private Array<ActionListener> actionListeners;
private CustomUiElementRenderNode renderNode;
@Field(optional=true)
private boolean enabled = true;
/**
* Constructor. Generates a unique ID for this {@link Checkbox}
*/
public CustomUiElement() {
this(null);
}
/**
* Constructor
*
* @param id
* The unique ID for this {@link Checkbox}
*/
public CustomUiElement(@ConstructorArg(clazz = String.class, name = "id") String id) {
this(id, 0f, 0f, 20f, 20f);
}
/**
* Constructor
* @param x The x coordinate of this element relative to its parent
* @param y The y coordinate of this element relative to its parent
* @param width The width of this element
* @param height The height of this element
*/
public CustomUiElement(@ConstructorArg(clazz = Float.class, name = "x") float x,
@ConstructorArg(clazz = Float.class, name = "y") float y,
@ConstructorArg(clazz = Float.class, name = "width") float width,
@ConstructorArg(clazz = Float.class, name = "height") float height) {
this(null, x, y, width, height);
}
/**
* Constructor
* @param id The unique ID for this element (if null an ID will be generated)
* @param x The x coordinate of this element relative to its parent
* @param y The y coordinate of this element relative to its parent
* @param width The width of this element
* @param height The height of this element
*/
public CustomUiElement(@ConstructorArg(clazz = String.class, name = "id") String id,
@ConstructorArg(clazz = Float.class, name = "x") float x,
@ConstructorArg(clazz = Float.class, name = "y") float y,
@ConstructorArg(clazz = Float.class, name = "width") float width,
@ConstructorArg(clazz = Float.class, name = "height") float height) {
super(id, x, y, width, height);
}
/**
* Update the UI state
* @param uiContainer The root {@link UiElement}
* @param delta The time since the last update
*/
public abstract void update(UiContainerRenderTree uiContainer, float delta);
/**
* Interpoalte the UI state
* @param alpha
*/
public abstract void interpolate(float alpha);
/**
* Render the {@link UiElement}
* @param g The {@link Graphics} context
* @param renderNode The {@link org.mini2Dx.ui.render.RenderNode} detailing where to render the element
*/
public abstract void render(Graphics g, CustomUiElementRenderNode renderNode);
/**
* An overridable method that is called when the mouse moves
* @param mouseX The mouse screen X coordinate
* @param mouseY The mouse screen Y coordinate
*/
public void onMouseMoved(int mouseX, int mouseY) {}
/**
* An overridable method that is called when the mouse/touch is pressed down on this element
* @param mouseX The mouse/touch screen X coordinate
* @param mouseY The mouse/touch screen Y coordinate
* @param pointer The pointer ID
* @param button The button ID (see Input.buttons)
*/
public void onMouseDown(int mouseX, int mouseY, int pointer, int button) {}
/**
* An overridable method that is called when the mouse/touch is released after being pressed down on this element
* @param mouseX The mouse/touch screen X coordinate
* @param mouseY The mouse/touch screen Y coordinate
* @param pointer The pointer ID
* @param button The button ID (see Input.buttons)
*/
public void onMouseUp(int mouseX, int mouseY, int pointer, int button) {}
@Override
public void attach(ParentRenderNode<?, ?> parentRenderNode) {
if (renderNode != null) {
return;
}
renderNode = new CustomUiElementRenderNode(parentRenderNode, this);
parentRenderNode.addChild(renderNode);
}
@Override
public void detach(ParentRenderNode<?, ?> parentRenderNode) {
if (renderNode == null) {
return;
}
parentRenderNode.removeChild(renderNode);
renderNode = null;
}
@Override
public void invokeBeginHover() {
if(renderNode == null) {
return;
}
renderNode.beginFakeHover();
}
@Override
public void invokeEndHover() {
if(renderNode == null) {
return;
}
renderNode.endFakeHover();
}
@Override
public void setVisibility(Visibility visibility) {
if (visibility == null) {
return;
}
if (this.visibility == visibility) {
return;
}
this.visibility = visibility;
if (renderNode == null) {
return;
}
renderNode.setDirty();
}
@Override
public void setStyleId(String styleId) {
if (styleId == null) {
return;
}
if (this.styleId.equals(styleId)) {
return;
}
this.styleId = styleId;
if (renderNode == null) {
return;
}
renderNode.setDirty();
}
@Override
public void setZIndex(int zIndex) {
this.zIndex = zIndex;
if (renderNode == null) {
return;
}
renderNode.setDirty();
}
@Override
public StyleRule getStyleRule() {
if(!UiContainer.isThemeApplied()) {
return null;
}
return UiContainer.getTheme().getColumnStyleRule(styleId, ScreenSize.XS);
}
@Override
public boolean isRenderNodeDirty() {
if (renderNode == null) {
return true;
}
return renderNode.isDirty();
}
@Override
public void setRenderNodeDirty() {
if (renderNode == null) {
return;
}
renderNode.setDirty();
}
@Override
public boolean isInitialLayoutOccurred() {
if (renderNode == null) {
return false;
}
return renderNode.isInitialLayoutOccurred();
}
@Override
public boolean isInitialUpdateOccurred() {
if(renderNode == null) {
return false;
}
return renderNode.isInitialUpdateOccurred();
}
@Override
public void notifyActionListenersOfBeginEvent(EventTrigger eventTrigger, EventTriggerParams eventTriggerParams) {
if(actionListeners == null) {
return;
}
ActionEvent event = ActionEventPool.allocate();
event.set(this, eventTrigger, eventTriggerParams);
for(int i = actionListeners.size - 1; i >= 0; i--) {
actionListeners.get(i).onActionBegin(event);
}
ActionEventPool.release(event);
}
@Override
public void notifyActionListenersOfEndEvent(EventTrigger eventTrigger, EventTriggerParams eventTriggerParams) {
if(actionListeners == null) {
return;
}
ActionEvent event = ActionEventPool.allocate();
event.set(this, eventTrigger, eventTriggerParams);
for(int i = actionListeners.size - 1; i >= 0; i--) {
actionListeners.get(i).onActionEnd(event);
}
ActionEventPool.release(event);
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public void addActionListener(ActionListener listener) {
if(actionListeners == null) {
actionListeners = new Array<ActionListener>(true, 1, ActionListener.class);
}
actionListeners.add(listener);
}
@Override
public void removeActionListener(ActionListener listener) {
if(actionListeners == null) {
return;
}
actionListeners.removeValue(listener, false);
}
@Override
public int getRenderX() {
if(renderNode == null) {
return Integer.MIN_VALUE;
}
return renderNode.getOuterRenderX();
}
@Override
public int getRenderY() {
if(renderNode == null) {
return Integer.MIN_VALUE;
}
return renderNode.getOuterRenderY();
}
@Override
public int getRenderWidth() {
if(renderNode == null) {
return -1;
}
return renderNode.getOuterRenderWidth();
}
@Override
public int getRenderHeight() {
if(renderNode == null) {
return -1;
}
return renderNode.getOuterRenderHeight();
}
}
| 0 | 0.920902 | 1 | 0.920902 | game-dev | MEDIA | 0.616501 | game-dev | 0.968566 | 1 | 0.968566 |
Secrets-of-Sosaria/World | 1,346 | Data/Scripts/Items/Magical/Gifts/Armor/Plate/GiftPlateGloves.cs | using System;
using Server.Items;
namespace Server.Items
{
[FlipableAttribute( 0x1414, 0x1418 )]
public class GiftPlateGloves : BaseGiftArmor
{
public override int BasePhysicalResistance{ get{ return 5; } }
public override int BaseFireResistance{ get{ return 3; } }
public override int BaseColdResistance{ get{ return 2; } }
public override int BasePoisonResistance{ get{ return 3; } }
public override int BaseEnergyResistance{ get{ return 2; } }
public override int InitMinHits{ get{ return 50; } }
public override int InitMaxHits{ get{ return 65; } }
public override int AosStrReq{ get{ return 70; } }
public override int OldStrReq{ get{ return 30; } }
public override int OldDexBonus{ get{ return -2; } }
public override int ArmorBase{ get{ return 40; } }
public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Plate; } }
[Constructable]
public GiftPlateGloves() : base( 0x1414 )
{
Weight = 2.0;
}
public GiftPlateGloves( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
if ( Weight == 1.0 )
Weight = 2.0;
}
}
} | 0 | 0.731099 | 1 | 0.731099 | game-dev | MEDIA | 0.907076 | game-dev | 0.822513 | 1 | 0.822513 |
bohdon/GameItemsPlugin | 5,174 | Plugins/GameItems/Source/GameItems/Public/GameItemContainerComponent.h | // Copyright Bohdon Sayre, All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameItemCollectionInterface.h"
#include "GameItemContainerInterface.h"
#include "Components/ActorComponent.h"
#include "GameItemContainerComponent.generated.h"
class UGameItem;
class UGameItemContainerDef;
class UGameItemContainerLink;
class USaveGame;
/**
* Defines a container.
*/
USTRUCT(BlueprintType)
struct FGameItemContainerSpec
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (GameplayTagFilter="GameItemContainerIdTagsCategory"))
FGameplayTag ContainerId;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<UGameItemContainerDef> ContainerDef;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FText DisplayName;
};
/**
* Defines a container link to add to all matching containers.
*/
USTRUCT(BlueprintType)
struct FGameItemContainerLinkSpec
{
GENERATED_BODY()
/** The container link class to create for each matching container. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ContainerLink")
TSubclassOf<UGameItemContainerLink> ContainerLinkClass;
/** The container to link with. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ContainerLink", meta = (GameplayTagFilter="GameItemContainerIdTagsCategory"))
FGameplayTag LinkedContainerId;
/** Apply this link to all containers matching this query. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ContainerLink", meta = (GameplayTagFilter="GameItemContainerTagsCategory"))
FGameplayTagQuery ContainerQuery;
};
/**
* Component that provides a collection of game item containers.
*/
UCLASS(ClassGroup=(Custom), meta=(BlueprintSpawnableComponent))
class GAMEITEMS_API UGameItemContainerComponent
: public UActorComponent,
public IGameItemContainerInterface,
public IGameItemCollectionInterface
{
GENERATED_BODY()
public:
UGameItemContainerComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
/** The definitions for all additional containers to create at startup. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta = (TitleProperty = "{ContainerId}"), Category = "GameItems")
TArray<FGameItemContainerSpec> StartupContainers;
/** The container links to add on any containers created by this component. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta = (TitleProperty = "{LinkedContainerId} {ContainerLinkClass}"), Category = "GameItems")
TArray<FGameItemContainerLinkSpec> ContainerLinks;
/** Whether this container collection should be saved. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SaveGame")
bool bEnableSaveGame = false;
/** The id of this container collection for save games. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta = (EditCondition = "bEnableSaveGame"), Category = "SaveGame")
FName SaveCollectionId;
/** Should this game item collection be saved to player save data? */
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Meta = (EditCondition = "bEnableSaveGame"), Category = "SaveGame")
bool bIsPlayerCollection = false;
/** Return true if an item is slotted in a container with any of the given tags. */
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GameItems", meta = (GameplayTagFilter = "GameItemContainerTagsCategory"))
bool IsItemSlotted(UGameItem* Item, FGameplayTagContainer ContainerTags) const;
/**
* Create a new item container.
* @return The new container, or null if a container already exists with the same id.
*/
UFUNCTION(BlueprintCallable, Category = "GameItems", Meta = (GameplayTagFilter="GameItemContainerIdTagsCategory"))
UGameItemContainer* CreateContainer(FGameplayTag ContainerId, TSubclassOf<UGameItemContainerDef> ContainerDef = nullptr);
/** Create and add the default items for any newly created containers. */
UFUNCTION(BlueprintCallable, Category = "GameItems")
void CreateDefaultItems(bool bForce = false);
virtual void InitializeComponent() override;
virtual void ReadyForReplication() override;
virtual bool ReplicateSubobjects(UActorChannel* Channel, FOutBunch* Bunch, FReplicationFlags* RepFlags) override;
// IGameItemContainerInterface
virtual TArray<UGameItemContainer*> GetAllItemContainers() const override;
virtual UGameItemContainer* GetItemContainer(FGameplayTag ContainerId) const override;
// IGameItemCollectionInterface
virtual int32 GetTotalMatchingItemCount(const UGameItem* Item) const override;
virtual int32 GetTotalMatchingItemCountByDef(TSubclassOf<UGameItemDef> ItemDef) const override;
/** Write all containers and items to a save game. */
UFUNCTION(BlueprintCallable, Category = "GameItems")
void CommitSaveGame(USaveGame* SaveGame);
/** Load all containers and items from a save game. */
UFUNCTION(BlueprintCallable, Category = "GameItems")
void LoadSaveGame(USaveGame* SaveGame);
protected:
UPROPERTY(Transient)
TMap<FGameplayTag, UGameItemContainer*> Containers;
/** Create all startup containers. */
void CreateStartupContainers();
/** Update all container link rules to assign any containers that aren't set yet. */
void ResolveContainerLinks();
void AddContainer(UGameItemContainer* Container);
};
| 0 | 0.828546 | 1 | 0.828546 | game-dev | MEDIA | 0.947326 | game-dev | 0.842978 | 1 | 0.842978 |
lyming99/lol_master_app | 3,082 | lib/controllers/desktop/hero/desk_hero_base_attr_controller.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'package:lol_master_app/entities/hero/hero_base_attr.dart';
import 'package:lol_master_app/util/mvc.dart';
import 'package:lol_master_app/views/desktop/hero/desk_hero_detail_view.dart';
import 'desk_hero_detail_controller.dart';
class HeroAttr {
String? name;
String? value;
HeroAttr({
this.name,
this.value,
});
}
/// 英雄属性控制器
class DeskHeroBaseAttrController extends MvcController {
DeskHeroDetailController? heroDetailController;
List<HeroAttr> heroAttrs = [
HeroAttr(name: "攻击力", value: "91"),
HeroAttr(name: "攻击速度", value: "0.77"),
HeroAttr(name: "攻击距离", value: "125"),
HeroAttr(name: "移动速度", value: "350"),
HeroAttr(name: "生命值", value: "1240"),
HeroAttr(name: "魔法值", value: "566"),
HeroAttr(name: "护甲值", value: "56.0"),
HeroAttr(name: "魔抗值", value: "42.3"),
];
int heroLevel = 1;
@override
void onInitState(BuildContext context, MvcViewState state) {
super.onInitState(context, state);
heroDetailController =
context.findAncestorWidgetOfExactType<DeskHeroDetailView>()?.controller;
updateLevel(1);
}
/// 调节等级,根据等级和成长值计算英雄的属性
void updateLevel(double value) {
heroLevel = value.toInt();
var heroInfo = heroDetailController?.hero;
if (heroInfo == null) {
return;
}
var baseAttr = heroInfo.baseAttr;
if (baseAttr == null) {
return;
}
heroAttrs = [
HeroAttr(
name: "攻击力",
value:
"${(baseAttr.attackdamage + baseAttr.attackdamageperlevel * (heroLevel - 1)).floor()}"),
HeroAttr(name: "攻击范围", value: "${baseAttr.attackrange}"),
HeroAttr(
name: "暴击率",
value:
"${(baseAttr.crit + baseAttr.critperlevel * (heroLevel - 1))}"),
HeroAttr(
name: "攻击速度",
value: (baseAttr.attackspeed +
(baseAttr.attackspeed *
baseAttr.attackspeedperlevel /
100 *
(heroLevel - 1)))
.toStringAsFixed(3)),
HeroAttr(name: "移动速度", value: "${baseAttr.movespeed}"),
HeroAttr(
name: "生命值",
value:
"${(baseAttr.hp + baseAttr.hpperlevel * (heroLevel - 1)).toInt()}"),
HeroAttr(
name: "生命回复",
value: (baseAttr.hpregen + baseAttr.hpregenperlevel * (heroLevel - 1))
.toStringAsFixed(2)),
HeroAttr(
name: "魔法值",
value:
"${(baseAttr.mp + baseAttr.mpperlevel * (heroLevel - 1)).toInt()}"),
HeroAttr(
name: "魔法回复",
value: (baseAttr.mpregen + baseAttr.mpregenperlevel * (heroLevel - 1))
.toStringAsFixed(1)),
HeroAttr(
name: "护甲值",
value:
"${(baseAttr.armor + baseAttr.armorperlevel * (heroLevel - 1)).toInt()}"),
HeroAttr(
name: "魔抗值",
value:
"${(baseAttr.spellblock + baseAttr.spellblockperlevel * (heroLevel - 1)).toInt()}"),
];
notifyListeners();
}
}
| 0 | 0.885337 | 1 | 0.885337 | game-dev | MEDIA | 0.729361 | game-dev | 0.600735 | 1 | 0.600735 |
CCBlueX/LiquidBounce | 4,060 | src/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/movement/speed/SpeedYawOffset.kt | /*
* This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
*
* Copyright (c) 2015 - 2025 CCBlueX
*
* LiquidBounce is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiquidBounce is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
*/
package net.ccbluex.liquidbounce.features.module.modules.movement.speed
import net.ccbluex.liquidbounce.config.types.NamedChoice
import net.ccbluex.liquidbounce.config.types.nesting.ToggleableConfigurable
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
import net.ccbluex.liquidbounce.utils.aiming.RotationsConfigurable
import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
import net.ccbluex.liquidbounce.utils.kotlin.Priority
/**
* Makes you go faster by strategically strafing
*/
object SpeedYawOffset : ToggleableConfigurable(ModuleSpeed, "YawOffset", false) {
private val yawOffsetMode by enumChoice("YawOffsetMode", YawOffsetMode.AIR)
private val rotationsConfigurable = RotationsConfigurable(this)
private var yaw = 0f
@Suppress("unused")
private val yawOffsetHandler = handler<RotationUpdateEvent> {
when (yawOffsetMode) {
YawOffsetMode.GROUND -> groundYawOffset() // makes you strafe more on ground
YawOffsetMode.AIR -> airYawOffset() // 45deg strafe on air
YawOffsetMode.CONSTANT -> constantYawOffset()
}
val rotation = Rotation(player.yaw - yaw, player.pitch)
RotationManager.setRotationTarget(
rotationsConfigurable.toRotationTarget(rotation),
Priority.NOT_IMPORTANT,
ModuleSpeed
)
}
private fun groundYawOffset(): Float {
yaw = if (player.isOnGround) {
when {
mc.options.forwardKey.isPressed && mc.options.leftKey.isPressed -> 45f
mc.options.forwardKey.isPressed && mc.options.rightKey.isPressed -> -45f
mc.options.backKey.isPressed && mc.options.leftKey.isPressed -> 135f
mc.options.backKey.isPressed && mc.options.rightKey.isPressed -> -135f
mc.options.backKey.isPressed -> 180f
mc.options.leftKey.isPressed -> 90f
mc.options.rightKey.isPressed -> -90f
else -> 0f
}
} else {
0f
}
return 0f
}
private fun constantYawOffset(): Float {
yaw = when {
mc.options.forwardKey.isPressed && mc.options.leftKey.isPressed -> 45f
mc.options.forwardKey.isPressed && mc.options.rightKey.isPressed -> -45f
mc.options.backKey.isPressed && mc.options.leftKey.isPressed -> 135f
mc.options.backKey.isPressed && mc.options.rightKey.isPressed -> -135f
mc.options.backKey.isPressed -> 180f
mc.options.leftKey.isPressed -> 90f
mc.options.rightKey.isPressed -> -90f
else -> 0f
}
return 0f
}
private fun airYawOffset(): Float {
yaw = when {
!player.isOnGround &&
mc.options.forwardKey.isPressed &&
!mc.options.leftKey.isPressed &&
!mc.options.rightKey.isPressed
-> -45f
else -> 0f
}
return 0f
}
private enum class YawOffsetMode(override val choiceName: String) : NamedChoice {
GROUND("Ground"),
AIR("Air"),
CONSTANT("Constant")
}
}
| 0 | 0.686711 | 1 | 0.686711 | game-dev | MEDIA | 0.856103 | game-dev | 0.786332 | 1 | 0.786332 |
qnpiiz/rich-2.0 | 1,430 | src/main/java/net/minecraft/world/gen/layer/DeepOceanLayer.java | package net.minecraft.world.gen.layer;
import net.minecraft.world.gen.INoiseRandom;
import net.minecraft.world.gen.layer.traits.ICastleTransformer;
public enum DeepOceanLayer implements ICastleTransformer
{
INSTANCE;
public int apply(INoiseRandom context, int north, int west, int south, int east, int center)
{
if (LayerUtil.isShallowOcean(center))
{
int i = 0;
if (LayerUtil.isShallowOcean(north))
{
++i;
}
if (LayerUtil.isShallowOcean(west))
{
++i;
}
if (LayerUtil.isShallowOcean(east))
{
++i;
}
if (LayerUtil.isShallowOcean(south))
{
++i;
}
if (i > 3)
{
if (center == 44)
{
return 47;
}
if (center == 45)
{
return 48;
}
if (center == 0)
{
return 24;
}
if (center == 46)
{
return 49;
}
if (center == 10)
{
return 50;
}
return 24;
}
}
return center;
}
}
| 0 | 0.885106 | 1 | 0.885106 | game-dev | MEDIA | 0.55245 | game-dev | 0.92859 | 1 | 0.92859 |
mollnn/conditional-mixture | 66,395 | mts3/ext/embree/kernels/common/rtcore.cpp | // Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#define RTC_EXPORT_API
#include "default.h"
#include "device.h"
#include "scene.h"
#include "context.h"
#include "../geometry/filter.h"
#include "../../include/embree3/rtcore_ray.h"
using namespace embree;
RTC_NAMESPACE_BEGIN;
/* mutex to make API thread safe */
static MutexSys g_mutex;
RTC_API RTCDevice rtcNewDevice(const char* config)
{
RTC_CATCH_BEGIN;
RTC_TRACE(rtcNewDevice);
Lock<MutexSys> lock(g_mutex);
Device* device = new Device(config);
return (RTCDevice) device->refInc();
RTC_CATCH_END(nullptr);
return (RTCDevice) nullptr;
}
RTC_API void rtcRetainDevice(RTCDevice hdevice)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcRetainDevice);
RTC_VERIFY_HANDLE(hdevice);
Lock<MutexSys> lock(g_mutex);
device->refInc();
RTC_CATCH_END(nullptr);
}
RTC_API void rtcReleaseDevice(RTCDevice hdevice)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcReleaseDevice);
RTC_VERIFY_HANDLE(hdevice);
Lock<MutexSys> lock(g_mutex);
device->refDec();
RTC_CATCH_END(nullptr);
}
RTC_API ssize_t rtcGetDeviceProperty(RTCDevice hdevice, RTCDeviceProperty prop)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetDeviceProperty);
RTC_VERIFY_HANDLE(hdevice);
Lock<MutexSys> lock(g_mutex);
return device->getProperty(prop);
RTC_CATCH_END(device);
return 0;
}
RTC_API void rtcSetDeviceProperty(RTCDevice hdevice, const RTCDeviceProperty prop, ssize_t val)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetDeviceProperty);
const bool internal_prop = (size_t)prop >= 1000000 && (size_t)prop < 1000004;
if (!internal_prop) RTC_VERIFY_HANDLE(hdevice); // allow NULL device for special internal settings
Lock<MutexSys> lock(g_mutex);
device->setProperty(prop,val);
RTC_CATCH_END(device);
}
RTC_API RTCError rtcGetDeviceError(RTCDevice hdevice)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetDeviceError);
if (device == nullptr) return Device::getThreadErrorCode();
else return device->getDeviceErrorCode();
RTC_CATCH_END(device);
return RTC_ERROR_UNKNOWN;
}
RTC_API void rtcSetDeviceErrorFunction(RTCDevice hdevice, RTCErrorFunction error, void* userPtr)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetDeviceErrorFunction);
RTC_VERIFY_HANDLE(hdevice);
device->setErrorFunction(error, userPtr);
RTC_CATCH_END(device);
}
RTC_API void rtcSetDeviceMemoryMonitorFunction(RTCDevice hdevice, RTCMemoryMonitorFunction memoryMonitor, void* userPtr)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetDeviceMemoryMonitorFunction);
device->setMemoryMonitorFunction(memoryMonitor, userPtr);
RTC_CATCH_END(device);
}
RTC_API RTCBuffer rtcNewBuffer(RTCDevice hdevice, size_t byteSize)
{
RTC_CATCH_BEGIN;
RTC_TRACE(rtcNewBuffer);
RTC_VERIFY_HANDLE(hdevice);
Buffer* buffer = new Buffer((Device*)hdevice, byteSize);
return (RTCBuffer)buffer->refInc();
RTC_CATCH_END((Device*)hdevice);
return nullptr;
}
RTC_API RTCBuffer rtcNewSharedBuffer(RTCDevice hdevice, void* ptr, size_t byteSize)
{
RTC_CATCH_BEGIN;
RTC_TRACE(rtcNewSharedBuffer);
RTC_VERIFY_HANDLE(hdevice);
Buffer* buffer = new Buffer((Device*)hdevice, byteSize, ptr);
return (RTCBuffer)buffer->refInc();
RTC_CATCH_END((Device*)hdevice);
return nullptr;
}
RTC_API void* rtcGetBufferData(RTCBuffer hbuffer)
{
Buffer* buffer = (Buffer*)hbuffer;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetBufferData);
RTC_VERIFY_HANDLE(hbuffer);
return buffer->data();
RTC_CATCH_END2(buffer);
return nullptr;
}
RTC_API void rtcRetainBuffer(RTCBuffer hbuffer)
{
Buffer* buffer = (Buffer*)hbuffer;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcRetainBuffer);
RTC_VERIFY_HANDLE(hbuffer);
buffer->refInc();
RTC_CATCH_END2(buffer);
}
RTC_API void rtcReleaseBuffer(RTCBuffer hbuffer)
{
Buffer* buffer = (Buffer*)hbuffer;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcReleaseBuffer);
RTC_VERIFY_HANDLE(hbuffer);
buffer->refDec();
RTC_CATCH_END2(buffer);
}
RTC_API RTCScene rtcNewScene (RTCDevice hdevice)
{
RTC_CATCH_BEGIN;
RTC_TRACE(rtcNewScene);
RTC_VERIFY_HANDLE(hdevice);
Scene* scene = new Scene((Device*)hdevice);
return (RTCScene) scene->refInc();
RTC_CATCH_END((Device*)hdevice);
return nullptr;
}
RTC_API RTCDevice rtcGetSceneDevice(RTCScene hscene)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetSceneDevice);
RTC_VERIFY_HANDLE(hscene);
return (RTCDevice)scene->device->refInc(); // user will own one additional device reference
RTC_CATCH_END2(scene);
return (RTCDevice)nullptr;
}
RTC_API void rtcSetSceneProgressMonitorFunction(RTCScene hscene, RTCProgressMonitorFunction progress, void* ptr)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetSceneProgressMonitorFunction);
RTC_VERIFY_HANDLE(hscene);
Lock<MutexSys> lock(g_mutex);
scene->setProgressMonitorFunction(progress,ptr);
RTC_CATCH_END2(scene);
}
RTC_API void rtcSetSceneBuildQuality (RTCScene hscene, RTCBuildQuality quality)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetSceneBuildQuality);
RTC_VERIFY_HANDLE(hscene);
if (quality != RTC_BUILD_QUALITY_LOW &&
quality != RTC_BUILD_QUALITY_MEDIUM &&
quality != RTC_BUILD_QUALITY_HIGH)
throw std::runtime_error("invalid build quality");
scene->setBuildQuality(quality);
RTC_CATCH_END2(scene);
}
RTC_API void rtcSetSceneFlags (RTCScene hscene, RTCSceneFlags flags)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetSceneFlags);
RTC_VERIFY_HANDLE(hscene);
scene->setSceneFlags(flags);
RTC_CATCH_END2(scene);
}
RTC_API RTCSceneFlags rtcGetSceneFlags(RTCScene hscene)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetSceneFlags);
RTC_VERIFY_HANDLE(hscene);
return scene->getSceneFlags();
RTC_CATCH_END2(scene);
return RTC_SCENE_FLAG_NONE;
}
RTC_API void rtcCommitScene (RTCScene hscene)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcCommitScene);
RTC_VERIFY_HANDLE(hscene);
scene->commit(false);
RTC_CATCH_END2(scene);
}
RTC_API void rtcJoinCommitScene (RTCScene hscene)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcJoinCommitScene);
RTC_VERIFY_HANDLE(hscene);
scene->commit(true);
RTC_CATCH_END2(scene);
}
RTC_API void rtcGetSceneBounds(RTCScene hscene, RTCBounds* bounds_o)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetSceneBounds);
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
BBox3fa bounds = scene->bounds.bounds();
bounds_o->lower_x = bounds.lower.x;
bounds_o->lower_y = bounds.lower.y;
bounds_o->lower_z = bounds.lower.z;
bounds_o->align0 = 0;
bounds_o->upper_x = bounds.upper.x;
bounds_o->upper_y = bounds.upper.y;
bounds_o->upper_z = bounds.upper.z;
bounds_o->align1 = 0;
RTC_CATCH_END2(scene);
}
RTC_API void rtcGetSceneLinearBounds(RTCScene hscene, RTCLinearBounds* bounds_o)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetSceneBounds);
RTC_VERIFY_HANDLE(hscene);
if (bounds_o == nullptr)
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"invalid destination pointer");
if (scene->isModified())
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
bounds_o->bounds0.lower_x = scene->bounds.bounds0.lower.x;
bounds_o->bounds0.lower_y = scene->bounds.bounds0.lower.y;
bounds_o->bounds0.lower_z = scene->bounds.bounds0.lower.z;
bounds_o->bounds0.align0 = 0;
bounds_o->bounds0.upper_x = scene->bounds.bounds0.upper.x;
bounds_o->bounds0.upper_y = scene->bounds.bounds0.upper.y;
bounds_o->bounds0.upper_z = scene->bounds.bounds0.upper.z;
bounds_o->bounds0.align1 = 0;
bounds_o->bounds1.lower_x = scene->bounds.bounds1.lower.x;
bounds_o->bounds1.lower_y = scene->bounds.bounds1.lower.y;
bounds_o->bounds1.lower_z = scene->bounds.bounds1.lower.z;
bounds_o->bounds1.align0 = 0;
bounds_o->bounds1.upper_x = scene->bounds.bounds1.upper.x;
bounds_o->bounds1.upper_y = scene->bounds.bounds1.upper.y;
bounds_o->bounds1.upper_z = scene->bounds.bounds1.upper.z;
bounds_o->bounds1.align1 = 0;
RTC_CATCH_END2(scene);
}
RTC_API void rtcCollide (RTCScene hscene0, RTCScene hscene1, RTCCollideFunc callback, void* userPtr)
{
Scene* scene0 = (Scene*) hscene0;
Scene* scene1 = (Scene*) hscene1;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcCollide);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene0);
RTC_VERIFY_HANDLE(hscene1);
if (scene0->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene got not committed");
if (scene1->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene got not committed");
if (scene0->device != scene1->device) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scenes are from different devices");
auto nUserPrims0 = scene0->getNumPrimitives (Geometry::MTY_USER_GEOMETRY, false);
auto nUserPrims1 = scene1->getNumPrimitives (Geometry::MTY_USER_GEOMETRY, false);
if (scene0->numPrimitives() != nUserPrims0 && scene1->numPrimitives() != nUserPrims1) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scenes must only contain user geometries with a single timestep");
#endif
scene0->intersectors.collide(scene0,scene1,callback,userPtr);
RTC_CATCH_END(scene0->device);
}
inline bool pointQuery(Scene* scene, RTCPointQuery* query, RTCPointQueryContext* userContext, RTCPointQueryFunction queryFunc, void* userPtr)
{
bool changed = false;
if (userContext->instStackSize > 0)
{
const AffineSpace3fa transform = AffineSpace3fa_load_unaligned((AffineSpace3fa*)userContext->world2inst[userContext->instStackSize-1]);
float similarityScale = 0.f;
const bool similtude = similarityTransform(transform, &similarityScale);
assert((similtude && similarityScale > 0) || (!similtude && similarityScale == 0.f));
PointQuery query_inst;
query_inst.p = xfmPoint(transform, Vec3fa(query->x, query->y, query->z));
query_inst.radius = query->radius * similarityScale;
query_inst.time = query->time;
PointQueryContext context_inst(scene, (PointQuery*)query,
similtude ? POINT_QUERY_TYPE_SPHERE : POINT_QUERY_TYPE_AABB,
queryFunc, userContext, similarityScale, userPtr);
changed = scene->intersectors.pointQuery((PointQuery*)&query_inst, &context_inst);
}
else
{
PointQueryContext context(scene, (PointQuery*)query,
POINT_QUERY_TYPE_SPHERE, queryFunc, userContext, 1.f, userPtr);
changed = scene->intersectors.pointQuery((PointQuery*)query, &context);
}
return changed;
}
RTC_API bool rtcPointQuery(RTCScene hscene, RTCPointQuery* query, RTCPointQueryContext* userContext, RTCPointQueryFunction queryFunc, void* userPtr)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcPointQuery);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
RTC_VERIFY_HANDLE(userContext);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene got not committed");
if (((size_t)query) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "query not aligned to 16 bytes");
if (((size_t)userContext) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "context not aligned to 16 bytes");
#endif
return pointQuery(scene, query, userContext, queryFunc, userPtr);
RTC_CATCH_END2_FALSE(scene);
}
RTC_API bool rtcPointQuery4 (const int* valid, RTCScene hscene, RTCPointQuery4* query, struct RTCPointQueryContext* userContext, RTCPointQueryFunction queryFunc, void** userPtrN)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcPointQuery4);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene got not committed");
if (((size_t)valid) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 16 bytes");
if (((size_t)query) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "query not aligned to 16 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<4; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(point_query.travs,cnt,cnt,cnt);
bool changed = false;
PointQuery4* query4 = (PointQuery4*)query;
PointQuery query1;
for (size_t i=0; i<4; i++) {
if (!valid[i]) continue;
query4->get(i,query1);
changed |= pointQuery(scene, (RTCPointQuery*)&query1, userContext, queryFunc, userPtrN?userPtrN[i]:NULL);
query4->set(i,query1);
}
return changed;
RTC_CATCH_END2_FALSE(scene);
}
RTC_API bool rtcPointQuery8 (const int* valid, RTCScene hscene, RTCPointQuery8* query, struct RTCPointQueryContext* userContext, RTCPointQueryFunction queryFunc, void** userPtrN)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcPointQuery8);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene got not committed");
if (((size_t)valid) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 16 bytes");
if (((size_t)query) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "query not aligned to 16 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<4; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(point_query.travs,cnt,cnt,cnt);
bool changed = false;
PointQuery8* query8 = (PointQuery8*)query;
PointQuery query1;
for (size_t i=0; i<8; i++) {
if (!valid[i]) continue;
query8->get(i,query1);
changed |= pointQuery(scene, (RTCPointQuery*)&query1, userContext, queryFunc, userPtrN?userPtrN[i]:NULL);
query8->set(i,query1);
}
return changed;
RTC_CATCH_END2_FALSE(scene);
}
RTC_API bool rtcPointQuery16 (const int* valid, RTCScene hscene, RTCPointQuery16* query, struct RTCPointQueryContext* userContext, RTCPointQueryFunction queryFunc, void** userPtrN)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcPointQuery16);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene got not committed");
if (((size_t)valid) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 16 bytes");
if (((size_t)query) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "query not aligned to 16 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<4; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(point_query.travs,cnt,cnt,cnt);
bool changed = false;
PointQuery16* query16 = (PointQuery16*)query;
PointQuery query1;
for (size_t i=0; i<16; i++) {
if (!valid[i]) continue;
PointQuery query1; query16->get(i,query1);
changed |= pointQuery(scene, (RTCPointQuery*)&query1, userContext, queryFunc, userPtrN?userPtrN[i]:NULL);
query16->set(i,query1);
}
return changed;
RTC_CATCH_END2_FALSE(scene);
}
RTC_API void rtcIntersect1 (RTCScene hscene, RTCIntersectContext* user_context, RTCRayHit* rayhit)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersect1);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)rayhit) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 16 bytes");
#endif
STAT3(normal.travs,1,1,1);
IntersectContext context(scene,user_context);
scene->intersectors.intersect(*rayhit,&context);
#if defined(DEBUG)
((RayHit*)rayhit)->verifyHit();
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersect4 (const int* valid, RTCScene hscene, RTCIntersectContext* user_context, RTCRayHit4* rayhit)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersect4);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)valid) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 16 bytes");
if (((size_t)rayhit) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit not aligned to 16 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<4; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(normal.travs,cnt,cnt,cnt);
IntersectContext context(scene,user_context);
#if !defined(EMBREE_RAY_PACKETS)
RayHit4* ray4 = (RayHit4*) rayhit;
for (size_t i=0; i<4; i++) {
if (!valid[i]) continue;
RayHit ray1; ray4->get(i,ray1);
scene->intersectors.intersect((RTCRayHit&)ray1,&context);
ray4->set(i,ray1);
}
#else
scene->intersectors.intersect4(valid,*rayhit,&context);
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersect8 (const int* valid, RTCScene hscene, RTCIntersectContext* user_context, RTCRayHit8* rayhit)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersect8);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)valid) & 0x1F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 32 bytes");
if (((size_t)rayhit) & 0x1F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit not aligned to 32 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<8; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(normal.travs,cnt,cnt,cnt);
IntersectContext context(scene,user_context);
#if !defined(EMBREE_RAY_PACKETS)
RayHit8* ray8 = (RayHit8*) rayhit;
for (size_t i=0; i<8; i++) {
if (!valid[i]) continue;
RayHit ray1; ray8->get(i,ray1);
scene->intersectors.intersect((RTCRayHit&)ray1,&context);
ray8->set(i,ray1);
}
#else
if (likely(scene->intersectors.intersector8))
scene->intersectors.intersect8(valid,*rayhit,&context);
else
scene->device->rayStreamFilters.intersectSOA(scene,(char*)rayhit,8,1,sizeof(RTCRayHit8),&context);
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersect16 (const int* valid, RTCScene hscene, RTCIntersectContext* user_context, RTCRayHit16* rayhit)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersect16);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)valid) & 0x3F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 64 bytes");
if (((size_t)rayhit) & 0x3F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit not aligned to 64 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<16; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(normal.travs,cnt,cnt,cnt);
IntersectContext context(scene,user_context);
#if !defined(EMBREE_RAY_PACKETS)
RayHit16* ray16 = (RayHit16*) rayhit;
for (size_t i=0; i<16; i++) {
if (!valid[i]) continue;
RayHit ray1; ray16->get(i,ray1);
scene->intersectors.intersect((RTCRayHit&)ray1,&context);
ray16->set(i,ray1);
}
#else
if (likely(scene->intersectors.intersector16))
scene->intersectors.intersect16(valid,*rayhit,&context);
else
scene->device->rayStreamFilters.intersectSOA(scene,(char*)rayhit,16,1,sizeof(RTCRayHit16),&context);
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersect1M (RTCScene hscene, RTCIntersectContext* user_context, RTCRayHit* rayhit, unsigned int M, size_t byteStride)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersect1M);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)rayhit ) & 0x03) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 4 bytes");
#endif
STAT3(normal.travs,M,M,M);
IntersectContext context(scene,user_context);
/* fast codepath for single rays */
if (likely(M == 1)) {
if (likely(rayhit->ray.tnear <= rayhit->ray.tfar))
scene->intersectors.intersect(*rayhit,&context);
}
/* codepath for streams */
else {
scene->device->rayStreamFilters.intersectAOS(scene,rayhit,M,byteStride,&context);
}
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcIntersect1M not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersect1Mp (RTCScene hscene, RTCIntersectContext* user_context, RTCRayHit** rn, unsigned int M)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersect1Mp);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)rn) & 0x03) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 4 bytes");
#endif
STAT3(normal.travs,M,M,M);
IntersectContext context(scene,user_context);
/* fast codepath for single rays */
if (likely(M == 1)) {
if (likely(rn[0]->ray.tnear <= rn[0]->ray.tfar))
scene->intersectors.intersect(*rn[0],&context);
}
/* codepath for streams */
else {
scene->device->rayStreamFilters.intersectAOP(scene,rn,M,&context);
}
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcIntersect1Mp not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersectNM (RTCScene hscene, RTCIntersectContext* user_context, struct RTCRayHitN* rayhit, unsigned int N, unsigned int M, size_t byteStride)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersectNM);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)rayhit) & 0x03) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 4 bytes");
#endif
STAT3(normal.travs,N*M,N*M,N*M);
IntersectContext context(scene,user_context);
/* code path for single ray streams */
if (likely(N == 1))
{
/* fast code path for streams of size 1 */
if (likely(M == 1)) {
if (likely(((RTCRayHit*)rayhit)->ray.tnear <= ((RTCRayHit*)rayhit)->ray.tfar))
scene->intersectors.intersect(*(RTCRayHit*)rayhit,&context);
}
/* normal codepath for single ray streams */
else {
scene->device->rayStreamFilters.intersectAOS(scene,(RTCRayHit*)rayhit,M,byteStride,&context);
}
}
/* code path for ray packet streams */
else {
scene->device->rayStreamFilters.intersectSOA(scene,(char*)rayhit,N,M,byteStride,&context);
}
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcIntersectNM not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcIntersectNp (RTCScene hscene, RTCIntersectContext* user_context, const RTCRayHitNp* rayhit, unsigned int N)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcIntersectNp);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)rayhit->ray.org_x ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.org_x not aligned to 4 bytes");
if (((size_t)rayhit->ray.org_y ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.org_y not aligned to 4 bytes");
if (((size_t)rayhit->ray.org_z ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.org_z not aligned to 4 bytes");
if (((size_t)rayhit->ray.dir_x ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.dir_x not aligned to 4 bytes");
if (((size_t)rayhit->ray.dir_y ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.dir_y not aligned to 4 bytes");
if (((size_t)rayhit->ray.dir_z ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.dir_z not aligned to 4 bytes");
if (((size_t)rayhit->ray.tnear ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.dir_x not aligned to 4 bytes");
if (((size_t)rayhit->ray.tfar ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.tnear not aligned to 4 bytes");
if (((size_t)rayhit->ray.time ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.time not aligned to 4 bytes");
if (((size_t)rayhit->ray.mask ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->ray.mask not aligned to 4 bytes");
if (((size_t)rayhit->hit.Ng_x ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.Ng_x not aligned to 4 bytes");
if (((size_t)rayhit->hit.Ng_y ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.Ng_y not aligned to 4 bytes");
if (((size_t)rayhit->hit.Ng_z ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.Ng_z not aligned to 4 bytes");
if (((size_t)rayhit->hit.u ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.u not aligned to 4 bytes");
if (((size_t)rayhit->hit.v ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.v not aligned to 4 bytes");
if (((size_t)rayhit->hit.geomID) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.geomID not aligned to 4 bytes");
if (((size_t)rayhit->hit.primID) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.primID not aligned to 4 bytes");
if (((size_t)rayhit->hit.instID) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "rayhit->hit.instID not aligned to 4 bytes");
#endif
STAT3(normal.travs,N,N,N);
IntersectContext context(scene,user_context);
scene->device->rayStreamFilters.intersectSOP(scene,rayhit,N,&context);
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcIntersectNp not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccluded1 (RTCScene hscene, RTCIntersectContext* user_context, RTCRay* ray)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccluded1);
STAT3(shadow.travs,1,1,1);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)ray) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 16 bytes");
#endif
IntersectContext context(scene,user_context);
scene->intersectors.occluded(*ray,&context);
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccluded4 (const int* valid, RTCScene hscene, RTCIntersectContext* user_context, RTCRay4* ray)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccluded4);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)valid) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 16 bytes");
if (((size_t)ray) & 0x0F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 16 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<4; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(shadow.travs,cnt,cnt,cnt);
IntersectContext context(scene,user_context);
#if !defined(EMBREE_RAY_PACKETS)
RayHit4* ray4 = (RayHit4*) ray;
for (size_t i=0; i<4; i++) {
if (!valid[i]) continue;
RayHit ray1; ray4->get(i,ray1);
scene->intersectors.occluded((RTCRay&)ray1,&context);
ray4->geomID[i] = ray1.geomID;
}
#else
scene->intersectors.occluded4(valid,*ray,&context);
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccluded8 (const int* valid, RTCScene hscene, RTCIntersectContext* user_context, RTCRay8* ray)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccluded8);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)valid) & 0x1F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 32 bytes");
if (((size_t)ray) & 0x1F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 32 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<8; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(shadow.travs,cnt,cnt,cnt);
IntersectContext context(scene,user_context);
#if !defined(EMBREE_RAY_PACKETS)
RayHit8* ray8 = (RayHit8*) ray;
for (size_t i=0; i<8; i++) {
if (!valid[i]) continue;
RayHit ray1; ray8->get(i,ray1);
scene->intersectors.occluded((RTCRay&)ray1,&context);
ray8->set(i,ray1);
}
#else
if (likely(scene->intersectors.intersector8))
scene->intersectors.occluded8(valid,*ray,&context);
else
scene->device->rayStreamFilters.occludedSOA(scene,(char*)ray,8,1,sizeof(RTCRay8),&context);
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccluded16 (const int* valid, RTCScene hscene, RTCIntersectContext* user_context, RTCRay16* ray)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccluded16);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)valid) & 0x3F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 64 bytes");
if (((size_t)ray) & 0x3F) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 64 bytes");
#endif
STAT(size_t cnt=0; for (size_t i=0; i<16; i++) cnt += ((int*)valid)[i] == -1;);
STAT3(shadow.travs,cnt,cnt,cnt);
IntersectContext context(scene,user_context);
#if !defined(EMBREE_RAY_PACKETS)
RayHit16* ray16 = (RayHit16*) ray;
for (size_t i=0; i<16; i++) {
if (!valid[i]) continue;
RayHit ray1; ray16->get(i,ray1);
scene->intersectors.occluded((RTCRay&)ray1,&context);
ray16->set(i,ray1);
}
#else
if (likely(scene->intersectors.intersector16))
scene->intersectors.occluded16(valid,*ray,&context);
else
scene->device->rayStreamFilters.occludedSOA(scene,(char*)ray,16,1,sizeof(RTCRay16),&context);
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccluded1M(RTCScene hscene, RTCIntersectContext* user_context, RTCRay* ray, unsigned int M, size_t byteStride)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccluded1M);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)ray) & 0x03) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 4 bytes");
#endif
STAT3(shadow.travs,M,M,M);
IntersectContext context(scene,user_context);
/* fast codepath for streams of size 1 */
if (likely(M == 1)) {
if (likely(ray->tnear <= ray->tfar))
scene->intersectors.occluded (*ray,&context);
}
/* codepath for normal streams */
else {
scene->device->rayStreamFilters.occludedAOS(scene,ray,M,byteStride,&context);
}
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcOccluded1M not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccluded1Mp(RTCScene hscene, RTCIntersectContext* user_context, RTCRay** ray, unsigned int M)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccluded1Mp);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)ray) & 0x03) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 4 bytes");
#endif
STAT3(shadow.travs,M,M,M);
IntersectContext context(scene,user_context);
/* fast codepath for streams of size 1 */
if (likely(M == 1)) {
if (likely(ray[0]->tnear <= ray[0]->tfar))
scene->intersectors.occluded (*ray[0],&context);
}
/* codepath for normal streams */
else {
scene->device->rayStreamFilters.occludedAOP(scene,ray,M,&context);
}
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcOccluded1Mp not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccludedNM(RTCScene hscene, RTCIntersectContext* user_context, RTCRayN* ray, unsigned int N, unsigned int M, size_t byteStride)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccludedNM);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (byteStride < sizeof(RTCRayHit)) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"byteStride too small");
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)ray) & 0x03) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "ray not aligned to 4 bytes");
#endif
STAT3(shadow.travs,N*M,N*N,N*N);
IntersectContext context(scene,user_context);
/* codepath for single rays */
if (likely(N == 1))
{
/* fast path for streams of size 1 */
if (likely(M == 1)) {
if (likely(((RTCRay*)ray)->tnear <= ((RTCRay*)ray)->tfar))
scene->intersectors.occluded (*(RTCRay*)ray,&context);
}
/* codepath for normal ray streams */
else {
scene->device->rayStreamFilters.occludedAOS(scene,(RTCRay*)ray,M,byteStride,&context);
}
}
/* code path for ray packet streams */
else {
scene->device->rayStreamFilters.occludedSOA(scene,(char*)ray,N,M,byteStride,&context);
}
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcOccludedNM not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcOccludedNp(RTCScene hscene, RTCIntersectContext* user_context, const RTCRayNp* ray, unsigned int N)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcOccludedNp);
#if defined (EMBREE_RAY_PACKETS)
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
if (scene->isModified()) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"scene not committed");
if (((size_t)ray->org_x ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "org_x not aligned to 4 bytes");
if (((size_t)ray->org_y ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "org_y not aligned to 4 bytes");
if (((size_t)ray->org_z ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "org_z not aligned to 4 bytes");
if (((size_t)ray->dir_x ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "dir_x not aligned to 4 bytes");
if (((size_t)ray->dir_y ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "dir_y not aligned to 4 bytes");
if (((size_t)ray->dir_z ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "dir_z not aligned to 4 bytes");
if (((size_t)ray->tnear ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "dir_x not aligned to 4 bytes");
if (((size_t)ray->tfar ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "tnear not aligned to 4 bytes");
if (((size_t)ray->time ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "time not aligned to 4 bytes");
if (((size_t)ray->mask ) & 0x03 ) throw_RTCError(RTC_ERROR_INVALID_ARGUMENT, "mask not aligned to 4 bytes");
#endif
STAT3(shadow.travs,N,N,N);
IntersectContext context(scene,user_context);
scene->device->rayStreamFilters.occludedSOP(scene,ray,N,&context);
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"rtcOccludedNp not supported");
#endif
RTC_CATCH_END2(scene);
}
RTC_API void rtcRetainScene (RTCScene hscene)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcRetainScene);
RTC_VERIFY_HANDLE(hscene);
scene->refInc();
RTC_CATCH_END2(scene);
}
RTC_API void rtcReleaseScene (RTCScene hscene)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcReleaseScene);
RTC_VERIFY_HANDLE(hscene);
scene->refDec();
RTC_CATCH_END2(scene);
}
RTC_API void rtcSetGeometryInstancedScene(RTCGeometry hgeometry, RTCScene hscene)
{
Geometry* geometry = (Geometry*) hgeometry;
Ref<Scene> scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryInstancedScene);
RTC_VERIFY_HANDLE(hgeometry);
RTC_VERIFY_HANDLE(hscene);
geometry->setInstancedScene(scene);
RTC_CATCH_END2(geometry);
}
AffineSpace3fa loadTransform(RTCFormat format, const float* xfm)
{
AffineSpace3fa space = one;
switch (format)
{
case RTC_FORMAT_FLOAT3X4_ROW_MAJOR:
space = AffineSpace3fa(Vec3fa(xfm[ 0], xfm[ 4], xfm[ 8]),
Vec3fa(xfm[ 1], xfm[ 5], xfm[ 9]),
Vec3fa(xfm[ 2], xfm[ 6], xfm[10]),
Vec3fa(xfm[ 3], xfm[ 7], xfm[11]));
break;
case RTC_FORMAT_FLOAT3X4_COLUMN_MAJOR:
space = AffineSpace3fa(Vec3fa(xfm[ 0], xfm[ 1], xfm[ 2]),
Vec3fa(xfm[ 3], xfm[ 4], xfm[ 5]),
Vec3fa(xfm[ 6], xfm[ 7], xfm[ 8]),
Vec3fa(xfm[ 9], xfm[10], xfm[11]));
break;
case RTC_FORMAT_FLOAT4X4_COLUMN_MAJOR:
space = AffineSpace3fa(Vec3fa(xfm[ 0], xfm[ 1], xfm[ 2]),
Vec3fa(xfm[ 4], xfm[ 5], xfm[ 6]),
Vec3fa(xfm[ 8], xfm[ 9], xfm[10]),
Vec3fa(xfm[12], xfm[13], xfm[14]));
break;
default:
throw_RTCError(RTC_ERROR_INVALID_OPERATION, "invalid matrix format");
break;
}
return space;
}
void storeTransform(const AffineSpace3fa& space, RTCFormat format, float* xfm)
{
switch (format)
{
case RTC_FORMAT_FLOAT3X4_ROW_MAJOR:
xfm[ 0] = space.l.vx.x; xfm[ 1] = space.l.vy.x; xfm[ 2] = space.l.vz.x; xfm[ 3] = space.p.x;
xfm[ 4] = space.l.vx.y; xfm[ 5] = space.l.vy.y; xfm[ 6] = space.l.vz.y; xfm[ 7] = space.p.y;
xfm[ 8] = space.l.vx.z; xfm[ 9] = space.l.vy.z; xfm[10] = space.l.vz.z; xfm[11] = space.p.z;
break;
case RTC_FORMAT_FLOAT3X4_COLUMN_MAJOR:
xfm[ 0] = space.l.vx.x; xfm[ 1] = space.l.vx.y; xfm[ 2] = space.l.vx.z;
xfm[ 3] = space.l.vy.x; xfm[ 4] = space.l.vy.y; xfm[ 5] = space.l.vy.z;
xfm[ 6] = space.l.vz.x; xfm[ 7] = space.l.vz.y; xfm[ 8] = space.l.vz.z;
xfm[ 9] = space.p.x; xfm[10] = space.p.y; xfm[11] = space.p.z;
break;
case RTC_FORMAT_FLOAT4X4_COLUMN_MAJOR:
xfm[ 0] = space.l.vx.x; xfm[ 1] = space.l.vx.y; xfm[ 2] = space.l.vx.z; xfm[ 3] = 0.f;
xfm[ 4] = space.l.vy.x; xfm[ 5] = space.l.vy.y; xfm[ 6] = space.l.vy.z; xfm[ 7] = 0.f;
xfm[ 8] = space.l.vz.x; xfm[ 9] = space.l.vz.y; xfm[10] = space.l.vz.z; xfm[11] = 0.f;
xfm[12] = space.p.x; xfm[13] = space.p.y; xfm[14] = space.p.z; xfm[15] = 1.f;
break;
default:
throw_RTCError(RTC_ERROR_INVALID_OPERATION, "invalid matrix format");
break;
}
}
RTC_API void rtcSetGeometryTransform(RTCGeometry hgeometry, unsigned int timeStep, RTCFormat format, const void* xfm)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryTransform);
RTC_VERIFY_HANDLE(hgeometry);
RTC_VERIFY_HANDLE(xfm);
const AffineSpace3fa transform = loadTransform(format, (const float*)xfm);
geometry->setTransform(transform, timeStep);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryTransformQuaternion(RTCGeometry hgeometry, unsigned int timeStep, const RTCQuaternionDecomposition* qd)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryTransformQuaternion);
RTC_VERIFY_HANDLE(hgeometry);
RTC_VERIFY_HANDLE(qd);
AffineSpace3fx transform;
transform.l.vx.x = qd->scale_x;
transform.l.vy.y = qd->scale_y;
transform.l.vz.z = qd->scale_z;
transform.l.vy.x = qd->skew_xy;
transform.l.vz.x = qd->skew_xz;
transform.l.vz.y = qd->skew_yz;
transform.l.vx.y = qd->translation_x;
transform.l.vx.z = qd->translation_y;
transform.l.vy.z = qd->translation_z;
transform.p.x = qd->shift_x;
transform.p.y = qd->shift_y;
transform.p.z = qd->shift_z;
// normalize quaternion
Quaternion3f q(qd->quaternion_r, qd->quaternion_i, qd->quaternion_j, qd->quaternion_k);
q = normalize(q);
transform.l.vx.w = q.i;
transform.l.vy.w = q.j;
transform.l.vz.w = q.k;
transform.p.w = q.r;
geometry->setQuaternionDecomposition(transform, timeStep);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcGetGeometryTransform(RTCGeometry hgeometry, float time, RTCFormat format, void* xfm)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryTransform);
const AffineSpace3fa transform = geometry->getTransform(time);
storeTransform(transform, format, (float*)xfm);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcFilterIntersection(const struct RTCIntersectFunctionNArguments* const args_i, const struct RTCFilterFunctionNArguments* filter_args)
{
IntersectFunctionNArguments* args = (IntersectFunctionNArguments*) args_i;
isa::reportIntersection1(args, filter_args);
}
RTC_API void rtcFilterOcclusion(const struct RTCOccludedFunctionNArguments* const args_i, const struct RTCFilterFunctionNArguments* filter_args)
{
OccludedFunctionNArguments* args = (OccludedFunctionNArguments*) args_i;
isa::reportOcclusion1(args,filter_args);
}
RTC_API RTCGeometry rtcNewGeometry (RTCDevice hdevice, RTCGeometryType type)
{
Device* device = (Device*) hdevice;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcNewGeometry);
RTC_VERIFY_HANDLE(hdevice);
switch (type)
{
case RTC_GEOMETRY_TYPE_TRIANGLE:
{
#if defined(EMBREE_GEOMETRY_TRIANGLE)
createTriangleMeshTy createTriangleMesh = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createTriangleMesh);
Geometry* geom = createTriangleMesh(device);
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_TRIANGLE is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_QUAD:
{
#if defined(EMBREE_GEOMETRY_QUAD)
createQuadMeshTy createQuadMesh = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createQuadMesh);
Geometry* geom = createQuadMesh(device);
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_QUAD is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_SPHERE_POINT:
case RTC_GEOMETRY_TYPE_DISC_POINT:
case RTC_GEOMETRY_TYPE_ORIENTED_DISC_POINT:
{
#if defined(EMBREE_GEOMETRY_POINT)
createPointsTy createPoints = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_builder_cpu_features, createPoints);
Geometry *geom;
switch(type) {
case RTC_GEOMETRY_TYPE_SPHERE_POINT:
geom = createPoints(device, Geometry::GTY_SPHERE_POINT);
break;
case RTC_GEOMETRY_TYPE_DISC_POINT:
geom = createPoints(device, Geometry::GTY_DISC_POINT);
break;
case RTC_GEOMETRY_TYPE_ORIENTED_DISC_POINT:
geom = createPoints(device, Geometry::GTY_ORIENTED_DISC_POINT);
break;
default:
geom = nullptr;
break;
}
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_POINT is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_CONE_LINEAR_CURVE:
case RTC_GEOMETRY_TYPE_ROUND_LINEAR_CURVE:
case RTC_GEOMETRY_TYPE_FLAT_LINEAR_CURVE:
case RTC_GEOMETRY_TYPE_ROUND_BEZIER_CURVE:
case RTC_GEOMETRY_TYPE_FLAT_BEZIER_CURVE:
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BEZIER_CURVE:
case RTC_GEOMETRY_TYPE_ROUND_BSPLINE_CURVE:
case RTC_GEOMETRY_TYPE_FLAT_BSPLINE_CURVE:
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BSPLINE_CURVE:
case RTC_GEOMETRY_TYPE_ROUND_HERMITE_CURVE:
case RTC_GEOMETRY_TYPE_FLAT_HERMITE_CURVE:
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_HERMITE_CURVE:
case RTC_GEOMETRY_TYPE_ROUND_CATMULL_ROM_CURVE:
case RTC_GEOMETRY_TYPE_FLAT_CATMULL_ROM_CURVE:
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_CATMULL_ROM_CURVE:
{
#if defined(EMBREE_GEOMETRY_CURVE)
createLineSegmentsTy createLineSegments = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createLineSegments);
createCurvesTy createCurves = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createCurves);
Geometry* geom;
switch (type) {
case RTC_GEOMETRY_TYPE_CONE_LINEAR_CURVE : geom = createLineSegments (device,Geometry::GTY_CONE_LINEAR_CURVE); break;
case RTC_GEOMETRY_TYPE_ROUND_LINEAR_CURVE : geom = createLineSegments (device,Geometry::GTY_ROUND_LINEAR_CURVE); break;
case RTC_GEOMETRY_TYPE_FLAT_LINEAR_CURVE : geom = createLineSegments (device,Geometry::GTY_FLAT_LINEAR_CURVE); break;
//case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_LINEAR_CURVE : geom = createLineSegments (device,Geometry::GTY_ORIENTED_LINEAR_CURVE); break;
case RTC_GEOMETRY_TYPE_ROUND_BEZIER_CURVE : geom = createCurves(device,Geometry::GTY_ROUND_BEZIER_CURVE); break;
case RTC_GEOMETRY_TYPE_FLAT_BEZIER_CURVE : geom = createCurves(device,Geometry::GTY_FLAT_BEZIER_CURVE); break;
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BEZIER_CURVE : geom = createCurves(device,Geometry::GTY_ORIENTED_BEZIER_CURVE); break;
case RTC_GEOMETRY_TYPE_ROUND_BSPLINE_CURVE : geom = createCurves(device,Geometry::GTY_ROUND_BSPLINE_CURVE); break;
case RTC_GEOMETRY_TYPE_FLAT_BSPLINE_CURVE : geom = createCurves(device,Geometry::GTY_FLAT_BSPLINE_CURVE); break;
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BSPLINE_CURVE : geom = createCurves(device,Geometry::GTY_ORIENTED_BSPLINE_CURVE); break;
case RTC_GEOMETRY_TYPE_ROUND_HERMITE_CURVE : geom = createCurves(device,Geometry::GTY_ROUND_HERMITE_CURVE); break;
case RTC_GEOMETRY_TYPE_FLAT_HERMITE_CURVE : geom = createCurves(device,Geometry::GTY_FLAT_HERMITE_CURVE); break;
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_HERMITE_CURVE : geom = createCurves(device,Geometry::GTY_ORIENTED_HERMITE_CURVE); break;
case RTC_GEOMETRY_TYPE_ROUND_CATMULL_ROM_CURVE : geom = createCurves(device,Geometry::GTY_ROUND_CATMULL_ROM_CURVE); break;
case RTC_GEOMETRY_TYPE_FLAT_CATMULL_ROM_CURVE : geom = createCurves(device,Geometry::GTY_FLAT_CATMULL_ROM_CURVE); break;
case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_CATMULL_ROM_CURVE : geom = createCurves(device,Geometry::GTY_ORIENTED_CATMULL_ROM_CURVE); break;
default: geom = nullptr; break;
}
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_CURVE is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_SUBDIVISION:
{
#if defined(EMBREE_GEOMETRY_SUBDIVISION)
createSubdivMeshTy createSubdivMesh = nullptr;
SELECT_SYMBOL_DEFAULT_AVX(device->enabled_cpu_features,createSubdivMesh);
//SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createSubdivMesh); // FIXME: this does not work for some reason?
Geometry* geom = createSubdivMesh(device);
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_SUBDIVISION is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_USER:
{
#if defined(EMBREE_GEOMETRY_USER)
createUserGeometryTy createUserGeometry = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createUserGeometry);
Geometry* geom = createUserGeometry(device);
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_USER is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_INSTANCE:
{
#if defined(EMBREE_GEOMETRY_INSTANCE)
createInstanceTy createInstance = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createInstance);
Geometry* geom = createInstance(device);
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_INSTANCE is not supported");
#endif
}
case RTC_GEOMETRY_TYPE_GRID:
{
#if defined(EMBREE_GEOMETRY_GRID)
createGridMeshTy createGridMesh = nullptr;
SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512(device->enabled_cpu_features,createGridMesh);
Geometry* geom = createGridMesh(device);
return (RTCGeometry) geom->refInc();
#else
throw_RTCError(RTC_ERROR_UNKNOWN,"RTC_GEOMETRY_TYPE_GRID is not supported");
#endif
}
default:
throw_RTCError(RTC_ERROR_UNKNOWN,"invalid geometry type");
}
RTC_CATCH_END(device);
return nullptr;
}
RTC_API void rtcSetGeometryUserPrimitiveCount(RTCGeometry hgeometry, unsigned int userPrimitiveCount)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryUserPrimitiveCount);
RTC_VERIFY_HANDLE(hgeometry);
if (unlikely(geometry->getType() != Geometry::GTY_USER_GEOMETRY))
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"operation only allowed for user geometries");
geometry->setNumPrimitives(userPrimitiveCount);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryTimeStepCount(RTCGeometry hgeometry, unsigned int timeStepCount)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryTimeStepCount);
RTC_VERIFY_HANDLE(hgeometry);
if (timeStepCount > RTC_MAX_TIME_STEP_COUNT)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"number of time steps is out of range");
geometry->setNumTimeSteps(timeStepCount);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryTimeRange(RTCGeometry hgeometry, float startTime, float endTime)
{
Ref<Geometry> geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryTimeRange);
RTC_VERIFY_HANDLE(hgeometry);
if (startTime > endTime)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"startTime has to be smaller or equal to the endTime");
geometry->setTimeRange(BBox1f(startTime,endTime));
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryVertexAttributeCount(RTCGeometry hgeometry, unsigned int N)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryVertexAttributeCount);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setVertexAttributeCount(N);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryTopologyCount(RTCGeometry hgeometry, unsigned int N)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryTopologyCount);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setTopologyCount(N);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryBuildQuality (RTCGeometry hgeometry, RTCBuildQuality quality)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryBuildQuality);
RTC_VERIFY_HANDLE(hgeometry);
if (quality != RTC_BUILD_QUALITY_LOW &&
quality != RTC_BUILD_QUALITY_MEDIUM &&
quality != RTC_BUILD_QUALITY_HIGH &&
quality != RTC_BUILD_QUALITY_REFIT)
throw std::runtime_error("invalid build quality");
geometry->setBuildQuality(quality);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryMaxRadiusScale(RTCGeometry hgeometry, float maxRadiusScale)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryMaxRadiusScale);
RTC_VERIFY_HANDLE(hgeometry);
#if RTC_MIN_WIDTH
if (maxRadiusScale < 1.0f) throw_RTCError(RTC_ERROR_INVALID_OPERATION,"maximal radius scale has to be larger or equal to 1");
geometry->setMaxRadiusScale(maxRadiusScale);
#else
throw_RTCError(RTC_ERROR_INVALID_OPERATION,"min-width feature is not enabled");
#endif
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryMask (RTCGeometry hgeometry, unsigned int mask)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryMask);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setMask(mask);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometrySubdivisionMode (RTCGeometry hgeometry, unsigned topologyID, RTCSubdivisionMode mode)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometrySubdivisionMode);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setSubdivisionMode(topologyID,mode);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryVertexAttributeTopology(RTCGeometry hgeometry, unsigned int vertexAttributeID, unsigned int topologyID)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryVertexAttributeTopology);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setVertexAttributeTopology(vertexAttributeID, topologyID);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryBuffer(RTCGeometry hgeometry, RTCBufferType type, unsigned int slot, RTCFormat format, RTCBuffer hbuffer, size_t byteOffset, size_t byteStride, size_t itemCount)
{
Geometry* geometry = (Geometry*) hgeometry;
Ref<Buffer> buffer = (Buffer*)hbuffer;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryBuffer);
RTC_VERIFY_HANDLE(hgeometry);
RTC_VERIFY_HANDLE(hbuffer);
if (geometry->device != buffer->device)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"inputs are from different devices");
if (itemCount > 0xFFFFFFFFu)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"buffer too large");
geometry->setBuffer(type, slot, format, buffer, byteOffset, byteStride, (unsigned int)itemCount);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetSharedGeometryBuffer(RTCGeometry hgeometry, RTCBufferType type, unsigned int slot, RTCFormat format, const void* ptr, size_t byteOffset, size_t byteStride, size_t itemCount)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetSharedGeometryBuffer);
RTC_VERIFY_HANDLE(hgeometry);
if (itemCount > 0xFFFFFFFFu)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"buffer too large");
Ref<Buffer> buffer = new Buffer(geometry->device, itemCount*byteStride, (char*)ptr + byteOffset);
geometry->setBuffer(type, slot, format, buffer, 0, byteStride, (unsigned int)itemCount);
RTC_CATCH_END2(geometry);
}
RTC_API void* rtcSetNewGeometryBuffer(RTCGeometry hgeometry, RTCBufferType type, unsigned int slot, RTCFormat format, size_t byteStride, size_t itemCount)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetNewGeometryBuffer);
RTC_VERIFY_HANDLE(hgeometry);
if (itemCount > 0xFFFFFFFFu)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"buffer too large");
/* vertex buffers need to get overallocated slightly as elements are accessed using SSE loads */
size_t bytes = itemCount*byteStride;
if (type == RTC_BUFFER_TYPE_VERTEX || type == RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE)
bytes += (16 - (byteStride%16))%16;
Ref<Buffer> buffer = new Buffer(geometry->device, bytes);
geometry->setBuffer(type, slot, format, buffer, 0, byteStride, (unsigned int)itemCount);
return buffer->data();
RTC_CATCH_END2(geometry);
return nullptr;
}
RTC_API void* rtcGetGeometryBufferData(RTCGeometry hgeometry, RTCBufferType type, unsigned int slot)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryBufferData);
RTC_VERIFY_HANDLE(hgeometry);
return geometry->getBuffer(type, slot);
RTC_CATCH_END2(geometry);
return nullptr;
}
RTC_API void rtcEnableGeometry (RTCGeometry hgeometry)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcEnableGeometry);
RTC_VERIFY_HANDLE(hgeometry);
geometry->enable();
RTC_CATCH_END2(geometry);
}
RTC_API void rtcUpdateGeometryBuffer (RTCGeometry hgeometry, RTCBufferType type, unsigned int slot)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcUpdateGeometryBuffer);
RTC_VERIFY_HANDLE(hgeometry);
geometry->updateBuffer(type, slot);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcDisableGeometry (RTCGeometry hgeometry)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcDisableGeometry);
RTC_VERIFY_HANDLE(hgeometry);
geometry->disable();
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryTessellationRate (RTCGeometry hgeometry, float tessellationRate)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryTessellationRate);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setTessellationRate(tessellationRate);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryUserData (RTCGeometry hgeometry, void* ptr)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryUserData);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setUserData(ptr);
RTC_CATCH_END2(geometry);
}
RTC_API void* rtcGetGeometryUserData (RTCGeometry hgeometry)
{
Geometry* geometry = (Geometry*) hgeometry; // no ref counting here!
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryUserData);
RTC_VERIFY_HANDLE(hgeometry);
return geometry->getUserData();
RTC_CATCH_END2(geometry);
return nullptr;
}
RTC_API void rtcSetGeometryBoundsFunction (RTCGeometry hgeometry, RTCBoundsFunction bounds, void* userPtr)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryBoundsFunction);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setBoundsFunction(bounds,userPtr);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryDisplacementFunction (RTCGeometry hgeometry, RTCDisplacementFunctionN displacement)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryDisplacementFunction);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setDisplacementFunction(displacement);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryIntersectFunction (RTCGeometry hgeometry, RTCIntersectFunctionN intersect)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryIntersectFunction);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setIntersectFunctionN(intersect);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryPointQueryFunction(RTCGeometry hgeometry, RTCPointQueryFunction pointQuery)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryPointQueryFunction);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setPointQueryFunction(pointQuery);
RTC_CATCH_END2(geometry);
}
RTC_API unsigned int rtcGetGeometryFirstHalfEdge(RTCGeometry hgeometry, unsigned int faceID)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryFirstHalfEdge);
return geometry->getFirstHalfEdge(faceID);
RTC_CATCH_END2(geometry);
return -1;
}
RTC_API unsigned int rtcGetGeometryFace(RTCGeometry hgeometry, unsigned int edgeID)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryFace);
return geometry->getFace(edgeID);
RTC_CATCH_END2(geometry);
return -1;
}
RTC_API unsigned int rtcGetGeometryNextHalfEdge(RTCGeometry hgeometry, unsigned int edgeID)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryNextHalfEdge);
return geometry->getNextHalfEdge(edgeID);
RTC_CATCH_END2(geometry);
return -1;
}
RTC_API unsigned int rtcGetGeometryPreviousHalfEdge(RTCGeometry hgeometry, unsigned int edgeID)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryPreviousHalfEdge);
return geometry->getPreviousHalfEdge(edgeID);
RTC_CATCH_END2(geometry);
return -1;
}
RTC_API unsigned int rtcGetGeometryOppositeHalfEdge(RTCGeometry hgeometry, unsigned int topologyID, unsigned int edgeID)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryOppositeHalfEdge);
return geometry->getOppositeHalfEdge(topologyID,edgeID);
RTC_CATCH_END2(geometry);
return -1;
}
RTC_API void rtcSetGeometryOccludedFunction (RTCGeometry hgeometry, RTCOccludedFunctionN occluded)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetOccludedFunctionN);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setOccludedFunctionN(occluded);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryIntersectFilterFunction (RTCGeometry hgeometry, RTCFilterFunctionN filter)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryIntersectFilterFunction);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setIntersectionFilterFunctionN(filter);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcSetGeometryOccludedFilterFunction (RTCGeometry hgeometry, RTCFilterFunctionN filter)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcSetGeometryOccludedFilterFunction);
RTC_VERIFY_HANDLE(hgeometry);
geometry->setOcclusionFilterFunctionN(filter);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcInterpolate(const RTCInterpolateArguments* const args)
{
Geometry* geometry = (Geometry*) args->geometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcInterpolate);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(args->geometry);
#endif
geometry->interpolate(args);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcInterpolateN(const RTCInterpolateNArguments* const args)
{
Geometry* geometry = (Geometry*) args->geometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcInterpolateN);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(args->geometry);
#endif
geometry->interpolateN(args);
RTC_CATCH_END2(geometry);
}
RTC_API void rtcCommitGeometry (RTCGeometry hgeometry)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcCommitGeometry);
RTC_VERIFY_HANDLE(hgeometry);
return geometry->commit();
RTC_CATCH_END2(geometry);
}
RTC_API unsigned int rtcAttachGeometry (RTCScene hscene, RTCGeometry hgeometry)
{
Scene* scene = (Scene*) hscene;
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcAttachGeometry);
RTC_VERIFY_HANDLE(hscene);
RTC_VERIFY_HANDLE(hgeometry);
if (scene->device != geometry->device)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"inputs are from different devices");
return scene->bind(RTC_INVALID_GEOMETRY_ID,geometry);
RTC_CATCH_END2(scene);
return -1;
}
RTC_API void rtcAttachGeometryByID (RTCScene hscene, RTCGeometry hgeometry, unsigned int geomID)
{
Scene* scene = (Scene*) hscene;
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcAttachGeometryByID);
RTC_VERIFY_HANDLE(hscene);
RTC_VERIFY_HANDLE(hgeometry);
RTC_VERIFY_GEOMID(geomID);
if (scene->device != geometry->device)
throw_RTCError(RTC_ERROR_INVALID_ARGUMENT,"inputs are from different devices");
scene->bind(geomID,geometry);
RTC_CATCH_END2(scene);
}
RTC_API void rtcDetachGeometry (RTCScene hscene, unsigned int geomID)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcDetachGeometry);
RTC_VERIFY_HANDLE(hscene);
RTC_VERIFY_GEOMID(geomID);
scene->detachGeometry(geomID);
RTC_CATCH_END2(scene);
}
RTC_API void rtcRetainGeometry (RTCGeometry hgeometry)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcRetainGeometry);
RTC_VERIFY_HANDLE(hgeometry);
geometry->refInc();
RTC_CATCH_END2(geometry);
}
RTC_API void rtcReleaseGeometry (RTCGeometry hgeometry)
{
Geometry* geometry = (Geometry*) hgeometry;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcReleaseGeometry);
RTC_VERIFY_HANDLE(hgeometry);
geometry->refDec();
RTC_CATCH_END2(geometry);
}
RTC_API RTCGeometry rtcGetGeometry (RTCScene hscene, unsigned int geomID)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometry);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
RTC_VERIFY_GEOMID(geomID);
#endif
return (RTCGeometry) scene->get(geomID);
RTC_CATCH_END2(scene);
return nullptr;
}
RTC_API RTCGeometry rtcGetGeometryThreadSafe (RTCScene hscene, unsigned int geomID)
{
Scene* scene = (Scene*) hscene;
RTC_CATCH_BEGIN;
RTC_TRACE(rtcGetGeometryThreadSafe);
#if defined(DEBUG)
RTC_VERIFY_HANDLE(hscene);
RTC_VERIFY_GEOMID(geomID);
#endif
Ref<Geometry> geom = scene->get_locked(geomID);
return (RTCGeometry) geom.ptr;
RTC_CATCH_END2(scene);
return nullptr;
}
RTC_NAMESPACE_END
| 0 | 0.967575 | 1 | 0.967575 | game-dev | MEDIA | 0.265887 | game-dev | 0.984064 | 1 | 0.984064 |
luna-rs/luna | 3,973 | src/main/java/io/luna/net/msg/in/DropItemMessageReader.java | package io.luna.net.msg.in;
import io.luna.LunaContext;
import io.luna.game.event.impl.DropItemEvent;
import io.luna.game.model.chunk.ChunkUpdatableView;
import io.luna.game.model.def.ItemDefinition;
import io.luna.game.model.item.GroundItem;
import io.luna.game.model.item.Item;
import io.luna.game.model.mob.Player;
import io.luna.game.model.mob.dialogue.DestroyItemDialogueInterface;
import io.luna.net.codec.ByteOrder;
import io.luna.net.codec.ValueType;
import io.luna.net.msg.GameMessage;
import io.luna.net.msg.GameMessageReader;
import io.luna.util.logging.LoggingSettings.FileOutputType;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import world.player.Sounds;
import static org.apache.logging.log4j.util.Unbox.box;
/**
* A {@link GameMessageReader} implementation that intercepts data for when an item is dropped.
*
* @author lare96
*/
public final class DropItemMessageReader extends GameMessageReader<DropItemEvent> {
/**
* An asynchronous logger that will handle item drop logs.
*/
private static final Logger logger = FileOutputType.ITEM_DROP.getLogger();
/**
* The logging level.
*/
private static final Level ITEM_DROP = FileOutputType.ITEM_DROP.getLevel();
@Override
public DropItemEvent decode(Player player, GameMessage msg) {
int index = msg.getPayload().getShort(false, ByteOrder.LITTLE);
int itemId = msg.getPayload().getShort(false, ByteOrder.LITTLE, ValueType.ADD);
int widgetId = msg.getPayload().getShort(false, ByteOrder.LITTLE, ValueType.ADD);
return new DropItemEvent(player, itemId, widgetId, index);
}
@Override
public boolean validate(Player player, DropItemEvent event) {
int itemId = event.getItemId();
int index = event.getIndex();
if (event.getWidgetId() != 3214 || // Click didn't come from inventory.
!ItemDefinition.isIdValid(itemId) || // Item ID invalid.
event.getIndex() < 0 || // Index < 0.
event.getIndex() >= player.getInventory().capacity()) { // Index exceeds inventory capacity.
return false;
}
// Check if inventory item ID is equal to event item ID.
return player.getInventory().contains(index, itemId);
}
@Override
public void handle(Player player, DropItemEvent event) {
Item inventoryItem = player.getInventory().get(event.getIndex());
ItemDefinition itemDef = inventoryItem.getItemDef();
dropItem(player.getContext(), player, inventoryItem, itemDef, event);
logger.log(ITEM_DROP, "{}: {}(x{})", player.getUsername(), itemDef.getName(), box(inventoryItem.getAmount()));
}
/**
* Drops {@code inventoryItem} if it's tradeable, otherwise opens the {@link DestroyItemDialogueInterface}.
*
* @param ctx The context instance.
* @param player The player.
* @param inventoryItem The inventory item.
* @param event The event instance.
*/
private void dropItem(LunaContext ctx, Player player, Item inventoryItem, ItemDefinition itemDef, DropItemEvent event) {
if (itemDef.isTradeable() && !itemDef.getInventoryActions().contains("Destroy")) {
GroundItem groundItem = new GroundItem(ctx, inventoryItem,
player.getPosition(), ChunkUpdatableView.localView(player));
if (ctx.getWorld().getItems().register(groundItem)) {
player.getInventory().set(event.getIndex(), null);
player.playSound(Sounds.DROP_ITEM);
player.getInterfaces().close();
} else {
player.sendMessage("You cannot drop this here.");
}
} else {
DestroyItemDialogueInterface destroyItemInterface =
new DestroyItemDialogueInterface(event.getIndex(), inventoryItem.getId());
player.getInterfaces().open(destroyItemInterface);
}
}
} | 0 | 0.873913 | 1 | 0.873913 | game-dev | MEDIA | 0.897529 | game-dev | 0.9556 | 1 | 0.9556 |
jaspervdj/JVGS | 7,715 | src/game/Level.cpp | #include "Level.h"
#include "EntityEventManager.h"
#include "Entity.h"
#include "FollowCamera.h"
#include "SimpleCamera.h"
#include "CameraFactory.h"
#include "../core/LogManager.h"
using namespace jvgs::core;
#include "../video/VideoManager.h"
using namespace jvgs::video;
#include "../audio/AudioManager.h"
using namespace jvgs::audio;
#include "../tinyxml/tinyxml.h"
using namespace jvgs::sketch;
using namespace jvgs::math;
#include <iostream>
using namespace std;
namespace jvgs
{
namespace game
{
/* Filling. */
map<string, CameraFactory*> createCameraFactories()
{
map<string, CameraFactory*> cameraFactories;
static TCameraFactory<FollowCamera> followCameraFactory;
cameraFactories["followcamera"] = &followCameraFactory;
static TCameraFactory<SimpleCamera> simpleCameraFactory;
cameraFactories["simplecamera"] = &simpleCameraFactory;
return cameraFactories;
}
/* Implementation. */
map<string, CameraFactory*> Level::cameraFactories =
createCameraFactories();
void Level::loadData(TiXmlElement *element)
{
/* Play some music. */
if(element->Attribute("music")) {
string music = element->Attribute("music");
AudioManager *audioManager = AudioManager::getInstance();
audioManager->playMusic(music);
}
/* Load the world. */
if(element->Attribute("world")) {
if(world)
delete world;
string worldFileName = element->Attribute("world");
world = new Sketch(worldFileName);
collisionDetector = new CollisionDetector(world);
boundingBox = BoundingBox(Vector2D(0.0f, 0.0f),
world->getSize());
} else {
LogManager::getInstance()->warning(
"No world attribute specified in the level xml.");
world = 0;
}
/* Walk through the file, adding entities. */
TiXmlElement *entityElement = element->FirstChildElement("entity");
while(entityElement) {
Entity *entity = new Entity(entityElement, this);
addEntity(entity);
entityElement = entityElement->NextSiblingElement("entity");
}
/* Add the camera. */
TiXmlElement *cameraElement = element->FirstChildElement("camera");
if(cameraElement) {
if(!cameraElement->Attribute("type"))
LogManager::getInstance()->error(
"Camera element always needs a type attribute.");
if(camera)
delete camera;
string type = cameraElement->Attribute("type");
map<string, CameraFactory*>::iterator result =
cameraFactories.find(type);
if(result != cameraFactories.end()) {
camera = result->second->create(cameraElement, this);
} else {
LogManager::getInstance()->error("No camera %s",
type.c_str());
}
} else {
camera = 0;
}
}
Level::Level()
{
world = 0;
collisionDetector = 0;
camera = 0;
}
Level::Level(TiXmlElement *element)
{
world = 0;
collisionDetector = 0;
camera = 0;
load(element);
}
Level::Level(const string &fileName)
{
world = 0;
collisionDetector = 0;
camera = 0;
load(fileName);
}
Level::~Level()
{
if(world)
delete world;
if(collisionDetector)
delete collisionDetector;
for(vector<Entity*>::iterator iterator = entities.begin();
iterator != entities.end(); iterator++)
delete (*iterator);
if(camera)
delete camera;
}
Sketch *Level::getWorld() const
{
return world;
}
CollisionDetector *Level::getCollisionDetector() const
{
return collisionDetector;
}
int Level::getNumberOfEntities() const
{
return (int) entities.size();
}
Entity *Level::getEntity(int index) const
{
return entities[index];
}
void Level::addEntity(Entity *entity)
{
/* Guard from id duplicates. */
if(getEntityById(entity->getId()))
LogManager::getInstance()->warning("Duplicate entity id: %s",
entity->getId().c_str());
entities.push_back(entity);
entitiesById[entity->getId()] = entity;
EntityEventManager::getInstance()->spawn(entity);
}
Entity *Level::getEntityById(const string &id)
{
map<string, Entity*>::iterator result = entitiesById.find(id);
if(result != entitiesById.end())
return result->second;
else
return 0;
}
void Level::update(float ms)
{
if(camera)
camera->update(ms);
for(vector<Entity*>::iterator iterator = entities.begin();
iterator != entities.end(); iterator++) {
Entity *entity = *iterator;
entity->update(ms);
/* When below the level, they become garbage. */
if(entity->getPosition().getY() - entity->getRadius().getY() >
world->getSize().getY())
entity->setGarbage();
}
/* Flush all events, so there are no event references remaining
* on the queue, making this a good time for clearing the
* garbage. */
EntityEventManager::getInstance()->flush();
/* Remove garbage. */
vector<Entity*> originalEntities = entities;
entities.clear();
for(vector<Entity*>::iterator iterator = originalEntities.begin();
iterator != originalEntities.end(); iterator++) {
if(!(*iterator)->isGarbage()) {
entities.push_back(*iterator);
} else {
entitiesById.erase((*iterator)->getId());
delete (*iterator);
}
}
}
void Level::render()
{
BoundingBox *cameraBoundingBox;
if(camera) {
camera->transform();
cameraBoundingBox = camera->getBoundingBox();
}
if(world)
world->render(cameraBoundingBox);
Entity *entity;
for(vector<Entity*>::iterator iterator = entities.begin();
iterator != entities.end(); iterator++) {
entity = *iterator;
if(camera) {
/* Try not too render all entities by using a bounding box
* test. */
if(entity->getBoundingBox()->intersectsWith(
cameraBoundingBox))
entity->render();
/* No camera, so we could be anywhere. Render anyway. */
} else {
entity->render();
}
}
}
}
}
| 0 | 0.960241 | 1 | 0.960241 | game-dev | MEDIA | 0.694621 | game-dev | 0.89638 | 1 | 0.89638 |
bouletmarc/D2R-BMBot | 6,324 | Bots/Mephisto.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static MapAreaStruc;
public class Mephisto
{
Form1 Form1_0;
public int CurrentStep = 0;
public bool ScriptDone = false;
public void SetForm1(Form1 form1_1)
{
Form1_0 = form1_1;
}
public void ResetVars()
{
CurrentStep = 0;
ScriptDone = false;
}
public void DetectCurrentStep()
{
if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.DuranceOfHateLevel2) CurrentStep = 1;
if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.DuranceOfHateLevel3) CurrentStep = 2;
}
public void RunScript()
{
Form1_0.Town_0.ScriptTownAct = 5; //set to town act 5 when running this script
if (!Form1_0.Running || !Form1_0.GameStruc_0.IsInGame())
{
ScriptDone = true;
return;
}
if (Form1_0.Town_0.GetInTown())
{
Form1_0.SetGameStatus("GO TO WP");
CurrentStep = 0;
Form1_0.Town_0.GoToWPArea(3, 8);
}
else
{
if (CurrentStep == 0)
{
Form1_0.SetGameStatus("DOING MEPHISTO");
Form1_0.Battle_0.CastDefense();
Form1_0.WaitDelay(15);
if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.DuranceOfHateLevel2)
{
CurrentStep++;
}
else
{
DetectCurrentStep();
if (CurrentStep == 0)
{
Form1_0.Town_0.FastTowning = false;
Form1_0.Town_0.GoToTown();
}
}
}
if (CurrentStep == 1)
{
//####
if (Form1_0.PlayerScan_0.levelNo == (int)Enums.Area.DuranceOfHateLevel3)
{
CurrentStep++;
return;
}
//####
Form1_0.PathFinding_0.MoveToExit(Enums.Area.DuranceOfHateLevel3);
CurrentStep++;
}
if (CurrentStep == 2)
{
//####
if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.DuranceOfHateLevel2)
{
CurrentStep = 1;
return;
}
//####
/*X: 22561,
Y: 9553,*/
if (Form1_0.Mover_0.MoveToLocation(17568, 8069))
{
CurrentStep++;
}
}
if (CurrentStep == 3)
{
//####
if ((Enums.Area)Form1_0.PlayerScan_0.levelNo == Enums.Area.DuranceOfHateLevel2)
{
CurrentStep = 1;
return;
}
//####
Form1_0.Potions_0.CanUseSkillForRegen = false;
Form1_0.SetGameStatus("KILLING MEPHISTO");
Form1_0.MobsStruc_0.DetectThisMob("getBossName", "Mephisto", false, 200, new List<long>());
if (Form1_0.MobsStruc_0.GetMobs("getBossName", "Mephisto", false, 200, new List<long>()))
{
if (Form1_0.MobsStruc_0.MobsHP > 0)
{
Form1_0.Battle_0.RunBattleScriptOnThisMob("getBossName", "Mephisto", new List<long>());
}
else
{
if (Form1_0.Battle_0.EndBossBattle())
{
Form1_0.Town_0.FastTowning = false;
Form1_0.Town_0.UseLastTP = false;
ScriptDone = true;
//Position ThisFinalPosition = Form1_0.MapAreaStruc_0.GetPositionOfObject("object", "portal", 102 - 1, new List<int>() { });
//if (Form1_0.Mover_0.MoveToLocation(ThisFinalPosition.X, ThisFinalPosition.Y))
/*while (Form1_0.PlayerScan_0.levelNo == (int)Enums.Area.DuranceOfHateLevel3)
{
Form1_0.ItemsStruc_0.GetItems(true);
if (Form1_0.Mover_0.MoveToLocation(17601, 8070))
{
Position itemScreenPos = Form1_0.GameStruc_0.World2Screen(Form1_0.PlayerScan_0.xPosFinal, Form1_0.PlayerScan_0.yPosFinal, 17601, 8070);
//Position itemScreenPos = Form1_0.GameStruc_0.World2Screen(Form1_0.PlayerScan_0.xPosFinal, Form1_0.PlayerScan_0.yPosFinal, ThisFinalPosition.X, ThisFinalPosition.Y);
Form1_0.KeyMouse_0.MouseClicc_RealPos(itemScreenPos.X, itemScreenPos.Y - 15);
Form1_0.PlayerScan_0.GetPositions();
}
}
Form1_0.WaitDelay(CharConfig.MephistoRedPortalEnterDelay);
Form1_0.Town_0.FastTowning = false;
Form1_0.Town_0.UseLastTP = false;
ScriptDone = true;*/
return;
//Form1_0.LeaveGame(true);
}
}
}
else
{
Form1_0.method_1("Mephisto not detected!", Color.Red);
//baal not detected...
Form1_0.ItemsStruc_0.GetItems(true);
if (Form1_0.MobsStruc_0.GetMobs("getBossName", "Mephisto", false, 200, new List<long>())) return; //redetect baal?
Form1_0.ItemsStruc_0.GrabAllItemsForGold();
if (Form1_0.MobsStruc_0.GetMobs("getBossName", "Mephisto", false, 200, new List<long>())) return; //redetect baal?
Form1_0.Potions_0.CanUseSkillForRegen = true;
if (Form1_0.Battle_0.EndBossBattle()) ScriptDone = true;
return;
}
}
}
}
}
| 0 | 0.77564 | 1 | 0.77564 | game-dev | MEDIA | 0.718859 | game-dev | 0.785684 | 1 | 0.785684 |
OpenNefia/OpenNefia | 4,004 | OpenNefia.Core/Rendering/MapDrawable/MapDrawablesManager.cs | using OpenNefia.Core.Game;
using OpenNefia.Core.GameController;
using OpenNefia.Core.GameObjects;
using OpenNefia.Core.IoC;
using OpenNefia.Core.Maps;
using OpenNefia.Core.Timing;
using OpenNefia.Core.UI.Element;
namespace OpenNefia.Core.Rendering
{
/// <summary>
/// Displays and updates animatable graphics in worldspace.
/// </summary>
public interface IMapDrawablesManager : IDrawable
{
void Clear();
void Enqueue(IMapDrawable drawable, MapCoordinates pos, int zOrder = 0);
void Enqueue(IMapDrawable drawable, EntityUid ent, int zOrder = 0);
bool HasActiveDrawables();
void WaitForDrawables();
}
public class MapDrawablesManager : BaseDrawable, IMapDrawablesManager
{
[Dependency] private readonly IEntityManager _entityMan = default!;
[Dependency] private readonly IMapManager _mapMan = default!;
[Dependency] private readonly ICoords _coords = default!;
[Dependency] private readonly IGameController _gameController = default!;
private class Entry : IComparable<Entry>
{
public IMapDrawable Drawable;
public int ZOrder;
public Entry(IMapDrawable drawable, int zOrder = 0)
{
Drawable = drawable;
ZOrder = zOrder;
}
public int CompareTo(Entry? other)
{
if (ZOrder == other?.ZOrder)
{
return Drawable == other.Drawable ? 0 : -1;
}
return ZOrder.CompareTo(other?.ZOrder);
}
}
private SortedSet<Entry> _active = new();
public void Enqueue(IMapDrawable drawable, MapCoordinates pos, int zOrder = 0)
{
if (pos.MapId != _mapMan.ActiveMap?.Id)
return;
var screenPos = _coords.TileToScreen(pos.Position);
drawable.ScreenOffset = Position / _coords.TileScale;
drawable.ScreenLocalPos = screenPos;
drawable.OnEnqueue();
_active.Add(new Entry(drawable, zOrder));
}
public void Enqueue(IMapDrawable drawable, EntityUid ent, int zOrder = 0)
{
if (!_entityMan.TryGetComponent<SpatialComponent>(ent, out var spatial))
return;
Enqueue(drawable, spatial.MapPosition, zOrder);
}
public void Clear()
{
_active.Clear();
}
public bool HasActiveDrawables() => _active.Count > 0;
/// <summary>
/// Called from update code.
/// </summary>
public void WaitForDrawables()
{
while (HasActiveDrawables())
{
var dt = Love.Timer.GetDelta();
var frameArgs = new FrameEventArgs(dt, stepInput: false);
_gameController.Update(frameArgs);
Update(dt);
_gameController.Draw();
_gameController.SystemStep(stepInput: false);
}
}
public override void Update(float dt)
{
foreach (var entry in _active)
{
var drawable = entry.Drawable;
drawable.Update(dt);
drawable.ScreenOffset = this.Position /_coords.TileScale;
// TODO very bad idea. should not scale drawable position by TileScale. makes use of Draw(_coords.TileScale) and DrawRegion(_coords.TileScale) impossible
drawable.SetPosition(drawable.ScreenLocalPos.X + drawable.ScreenOffset.X, drawable.ScreenLocalPos.Y + drawable.ScreenOffset.Y);
}
_active.RemoveWhere(entry => entry.Drawable.IsFinished);
}
public override void Draw()
{
foreach (var entry in _active)
{
if (!entry.Drawable.IsFinished)
{
entry.Drawable.Draw();
}
}
}
}
}
| 0 | 0.929245 | 1 | 0.929245 | game-dev | MEDIA | 0.659048 | game-dev | 0.954867 | 1 | 0.954867 |
ProjectIgnis/CardScripts | 2,274 | official/c45593826.lua | --彼岸の悪鬼 ドラゴネル
--Draghig, Malebranche of the Burning Abyss
local s,id=GetID()
function s.initial_effect(c)
--self destroy
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_SELF_DESTROY)
e1:SetCondition(s.sdcon)
c:RegisterEffect(e1)
--Special Summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_HAND)
e2:SetCountLimit(1,id)
e2:SetCondition(s.sscon)
e2:SetTarget(s.sstg)
e2:SetOperation(s.ssop)
c:RegisterEffect(e2)
--to deck top
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(id,1))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCountLimit(1,id)
e3:SetTarget(s.dttg)
e3:SetOperation(s.dtop)
c:RegisterEffect(e3)
end
s.listed_series={SET_BURNING_ABYSS}
function s.sdfilter(c)
return not c:IsFaceup() or not c:IsSetCard(SET_BURNING_ABYSS)
end
function s.sdcon(e)
return Duel.IsExistingMatchingCard(s.sdfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
end
function s.filter(c)
return c:IsSpellTrap()
end
function s.sscon(e,tp,eg,ep,ev,re,r,rp)
return not Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_ONFIELD,0,1,nil)
end
function s.sstg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function s.ssop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
function s.dttg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsSetCard,tp,LOCATION_DECK,0,1,nil,SET_BURNING_ABYSS) end
end
function s.dtop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(id,2))
local g=Duel.SelectMatchingCard(tp,Card.IsSetCard,tp,LOCATION_DECK,0,1,1,nil,SET_BURNING_ABYSS)
local tc=g:GetFirst()
if tc then
Duel.ShuffleDeck(tp)
Duel.MoveSequence(tc,0)
Duel.ConfirmDecktop(tp,1)
end
end | 0 | 0.820439 | 1 | 0.820439 | game-dev | MEDIA | 0.989272 | game-dev | 0.914044 | 1 | 0.914044 |
mikecann/Unity-Ash | 3,500 | Assets/Unity-Ash/Source/Core/Engine.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Ash.Core
{
public class Engine : IEngine
{
private List<SystemPriorityPair> _systems;
private FamiliesContainer _families;
private IFamilyFactory _familyFactory;
private List<IEntity> _entities;
public Engine(IFamilyFactory familyFactory = null)
{
Current = this;
_familyFactory = familyFactory ?? new ComponentMatchingFamilyFactory();
_systems = new List<SystemPriorityPair>();
_families = new FamiliesContainer();
_entities = new List<IEntity>();
}
public void AddEntity(IEntity entity)
{
foreach (var pair in _families)
pair.EntityAdded(entity);
entity.ComponentAdded.AddListener(OnComponentAdded);
entity.ComponentRemoved.AddListener(OnComponentRemoved);
_entities.Add(entity);
}
private void OnComponentRemoved(IEntity entity, Type component)
{
_families.Lock();
foreach (var pair in _families)
pair.ComponentRemoved(entity, component);
_families.UnLock();
}
private void OnComponentAdded(IEntity entity, Type component)
{
_families.Lock();
foreach (var pair in _families)
pair.ComponentAdded(entity, component);
_families.UnLock();
}
public void RemoveEntity(IEntity entity)
{
foreach (var pair in _families)
pair.EntityRemoved(entity);
entity.ComponentAdded.RemoveListener(OnComponentAdded);
entity.ComponentRemoved.RemoveListener(OnComponentRemoved);
_entities.Remove(entity);
}
public void AddSystem(ISystem system, int priority)
{
_systems.Add(new SystemPriorityPair(system, priority));
_systems = _systems.OrderBy(s => s.Priority).ToList();
system.AddedToEngine(this);
}
public void RemoveSystem(ISystem system)
{
_systems.RemoveAll(s => s.System == system);
system.RemovedFromEngine(this);
}
public INodeList<T> GetNodes<T>() where T : Node
{
var type = typeof (T);
IFamily<T> family;
if (_families.Contains(type))
family = _families.Get(type) as IFamily<T>;
else
{
family = _familyFactory.Produce<T>();
_families.Add(type, family);
foreach (var entity in _entities)
family.EntityAdded(entity);
}
return family.Nodes;
}
public void ReleaseNodes<T>(INodeList<T> nodes)
{
var type = typeof(T);
if (!_families.Contains(type))
return;
_families.Remove(type);
}
public void Update(float delta)
{
foreach (var family in _families)
family.BeforeUpdate();
foreach (var prioritizedSystem in _systems)
prioritizedSystem.System.Update(delta);
_families.Lock();
foreach (var family in _families)
family.AfterUpdate();
_families.UnLock();
}
public static IEngine Current { get; set; }
}
}
| 0 | 0.863901 | 1 | 0.863901 | game-dev | MEDIA | 0.927017 | game-dev | 0.882602 | 1 | 0.882602 |
geniesinc/GeniesIRL | 9,479 | Assets/Samples/XR Interaction Toolkit/3.0.7/visionOS/Scripts/Input Bridge/SpatialTouchInputReader.cs | using System;
using System.Collections.Generic;
using Unity.XR.CoreUtils.Bindings.Variables;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.XR.Interaction.Toolkit.Inputs.Readers;
namespace UnityEngine.XR.Interaction.Toolkit.Samples.VisionOS
{
/// <summary>
/// Flag enabled pointer kind enum to indicate which pointer kinds are supported by this input reader.
/// </summary>
[Flags]
public enum SupportedPointerKind
{
None = 0,
Touch = 1,
IndirectPinch = 2,
DirectPinch = 4,
}
/// <summary>
/// Input reader that binds to visionOS touch input, and implements an input queue to ensure only one input state change occurs per frame.
/// </summary>
[DefaultExecutionOrder(XRInteractionUpdateOrder.k_XRInputDeviceButtonReader)]
public class SpatialTouchInputReader : MonoBehaviour, IXRInputButtonReader
{
[SerializeField]
[Tooltip("Bind to primary or secondary touch input.")]
bool m_IsPrimaryTouch = true;
/// <summary>
/// Bind to primary or secondary touch input.
/// </summary>
public bool isPrimaryTouch
{
get => m_IsPrimaryTouch;
set => m_IsPrimaryTouch = value;
}
[SerializeField]
[Tooltip("Time in seconds to wait to auto-release if no new touch event arrives. Can be important in volume mode since some events get cancelled incorrectly. Set to 0 to disable.")]
float m_ReleaseTimeOutDelay = 0.1f;
/// <summary>
/// Time in seconds to wait to auto-release if no new touch event arrives.
/// Can be important in volume mode since some events get cancelled incorrectly.
/// Set to 0 to disable.
/// </summary>
public float releaseTimeOutDelay
{
get => m_ReleaseTimeOutDelay;
set => m_ReleaseTimeOutDelay = value;
}
[SerializeField]
[Tooltip("Supported pointer kinds.")]
SupportedPointerKind m_SupportedPointerKind = SupportedPointerKind.DirectPinch | SupportedPointerKind.IndirectPinch;
/// <summary>
/// which pointer kinds are supported by this input reader.
/// </summary>
public SupportedPointerKind supportedPointerKind
{
get => m_SupportedPointerKind;
set => m_SupportedPointerKind = value;
}
/// <summary>
/// True if a touch event is currently active and input was not ended or cancelled.
/// </summary>
public IReadOnlyBindableVariable<bool> hasActiveTouch => m_HasActiveTouch;
readonly BindableVariable<bool> m_HasActiveTouch = new BindableVariable<bool>();
#pragma warning disable CS0649 // Field is never assigned to, and will always have its default value
bool m_IsPerformed;
bool m_WasPerformedThisFrame;
bool m_WasCompletedThisFrame;
#pragma warning restore CS0649
#if POLYSPATIAL_1_1_OR_NEWER
readonly Vector3 m_HiddenPosition = new Vector3(0f, -100f, 0f);
SpatialPointerInput m_SpatialPointerInput;
bool m_InputEnabled;
float m_TimeSinceLastTouch;
SpatialPointerState m_LastSpatialPointerState;
readonly Queue<SpatialPointerState> m_SpatialPointerStateQueue = new Queue<SpatialPointerState>();
#endif
void OnEnable()
{
#if POLYSPATIAL_1_1_OR_NEWER
m_SpatialPointerInput ??= new SpatialPointerInput();
if (m_SpatialPointerInput == null)
return;
m_SpatialPointerInput.Enable();
if (m_IsPrimaryTouch)
{
m_SpatialPointerInput.Touch.PrimaryTouch.performed += OnTouchPerformed;
m_SpatialPointerInput.Touch.PrimaryTouch.canceled += OnTouchPerformed;
}
else
{
m_SpatialPointerInput.Touch.SecondaryTouch.performed += OnTouchPerformed;
m_SpatialPointerInput.Touch.SecondaryTouch.canceled += OnTouchPerformed;
}
m_InputEnabled = true;
#endif
}
void OnDisable()
{
#if POLYSPATIAL_1_1_OR_NEWER
m_SpatialPointerStateQueue.Clear();
ExitInput();
if (!m_InputEnabled)
return;
if (m_IsPrimaryTouch)
{
m_SpatialPointerInput.Touch.PrimaryTouch.performed -= OnTouchPerformed;
m_SpatialPointerInput.Touch.PrimaryTouch.canceled -= OnTouchPerformed;
}
else
{
m_SpatialPointerInput.Touch.SecondaryTouch.performed -= OnTouchPerformed;
m_SpatialPointerInput.Touch.SecondaryTouch.canceled -= OnTouchPerformed;
}
m_SpatialPointerInput.Disable();
m_InputEnabled = false;
#endif
}
void Update()
{
#if POLYSPATIAL_1_1_OR_NEWER
bool hasTouch = m_SpatialPointerStateQueue.Count > 0;
// Check if input has timed out
if (!hasTouch && m_IsPerformed && m_ReleaseTimeOutDelay > 0)
{
m_TimeSinceLastTouch += Time.unscaledDeltaTime;
if (m_TimeSinceLastTouch > m_ReleaseTimeOutDelay)
ExitInput();
}
while (m_SpatialPointerStateQueue.Count > 0)
{
var state = m_SpatialPointerStateQueue.Dequeue();
if (!IsSpatialPointerKindSupported(state.Kind))
{
if (m_IsPerformed)
{
ExitInput();
break;
}
continue;
}
m_TimeSinceLastTouch = 0f;
bool isPhaseActive = state.phase.IsActive();
// If phase is active and the input is already active, empty the queue with latest transform state
if (m_IsPerformed && isPhaseActive)
{
UpdateTransform(state);
continue;
}
// If phase does not match input state, update input state and transform, and wait a frame for more changes
if (m_IsPerformed != isPhaseActive)
{
UpdateIsPerformed(isPhaseActive);
if (isPhaseActive)
UpdateTransform(state);
else
ResetTransform();
break;
}
}
#endif
}
#if POLYSPATIAL_1_1_OR_NEWER
/// <summary>
/// Tries to get the last valid pointer state.
/// </summary>
/// <returns>False if <see cref="hasActiveTouch"/> is false</returns>
public bool TryGetPointerState(out SpatialPointerState pointerState)
{
pointerState = m_LastSpatialPointerState;
return m_HasActiveTouch.Value;
}
void OnTouchPerformed(InputAction.CallbackContext context)
{
var device = context.ReadValue<SpatialPointerState>();
m_SpatialPointerStateQueue.Enqueue(device);
}
void ExitInput()
{
UpdateIsPerformed(false);
ResetTransform();
}
void ResetTransform()
{
transform.SetPositionAndRotation(m_HiddenPosition, Quaternion.identity);
m_HasActiveTouch.Value = false;
}
void UpdateIsPerformed(bool inputActive)
{
bool wasPerformedLastFrame = m_IsPerformed;
m_IsPerformed = inputActive;
m_WasPerformedThisFrame = m_IsPerformed && !wasPerformedLastFrame;
m_WasCompletedThisFrame = !m_IsPerformed && wasPerformedLastFrame;
}
void UpdateTransform(SpatialPointerState touchState)
{
// Update transform
Vector3 targetPosition = touchState.Kind == SpatialPointerKind.Touch ? touchState.interactionPosition : touchState.inputDevicePosition;
transform.SetPositionAndRotation(targetPosition, touchState.inputDeviceRotation);
// Update last state
m_LastSpatialPointerState = touchState;
m_HasActiveTouch.Value = touchState.phase.IsActive();
}
static SupportedPointerKind MapPointerKind(SpatialPointerKind pointerKind)
{
return pointerKind switch
{
SpatialPointerKind.DirectPinch => SupportedPointerKind.DirectPinch,
SpatialPointerKind.IndirectPinch => SupportedPointerKind.IndirectPinch,
SpatialPointerKind.Touch => SupportedPointerKind.Touch,
_ => SupportedPointerKind.None,
};
}
bool IsSpatialPointerKindSupported(SpatialPointerKind pointerKind) => IsSupportedPointerKind(MapPointerKind(pointerKind));
bool IsSupportedPointerKind(SupportedPointerKind pointerKind) => (m_SupportedPointerKind & pointerKind) != 0;
#endif
public float ReadValue() => m_IsPerformed ? 1f : 0f;
public bool TryReadValue(out float value)
{
value = ReadValue();
return true;
}
public bool ReadIsPerformed() => m_IsPerformed;
public bool ReadWasPerformedThisFrame() => m_WasPerformedThisFrame;
public bool ReadWasCompletedThisFrame() => m_WasCompletedThisFrame;
}
}
| 0 | 0.935765 | 1 | 0.935765 | game-dev | MEDIA | 0.361339 | game-dev | 0.965411 | 1 | 0.965411 |
Dark-Basic-Software-Limited/Dark-Basic-Pro | 4,588 | SDK/BULLET/bullet-2.81-rev2613/src/vectormath/scalar/boolInVec.h | /*
Copyright (C) 2009 Sony Computer Entertainment Inc.
All rights reserved.
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 _BOOLINVEC_H
#define _BOOLINVEC_H
#include <math.h>
namespace Vectormath {
class floatInVec;
//--------------------------------------------------------------------------------------------------
// boolInVec class
//
class boolInVec
{
private:
unsigned int mData;
public:
// Default constructor; does no initialization
//
inline boolInVec( ) { };
// Construct from a value converted from float
//
inline boolInVec(floatInVec vec);
// Explicit cast from bool
//
explicit inline boolInVec(bool scalar);
// Explicit cast to bool
//
inline bool getAsBool() const;
#ifndef _VECTORMATH_NO_SCALAR_CAST
// Implicit cast to bool
//
inline operator bool() const;
#endif
// Boolean negation operator
//
inline const boolInVec operator ! () const;
// Assignment operator
//
inline boolInVec& operator = (boolInVec vec);
// Boolean and assignment operator
//
inline boolInVec& operator &= (boolInVec vec);
// Boolean exclusive or assignment operator
//
inline boolInVec& operator ^= (boolInVec vec);
// Boolean or assignment operator
//
inline boolInVec& operator |= (boolInVec vec);
};
// Equal operator
//
inline const boolInVec operator == (boolInVec vec0, boolInVec vec1);
// Not equal operator
//
inline const boolInVec operator != (boolInVec vec0, boolInVec vec1);
// And operator
//
inline const boolInVec operator & (boolInVec vec0, boolInVec vec1);
// Exclusive or operator
//
inline const boolInVec operator ^ (boolInVec vec0, boolInVec vec1);
// Or operator
//
inline const boolInVec operator | (boolInVec vec0, boolInVec vec1);
// Conditionally select between two values
//
inline const boolInVec select(boolInVec vec0, boolInVec vec1, boolInVec select_vec1);
} // namespace Vectormath
//--------------------------------------------------------------------------------------------------
// boolInVec implementation
//
#include "floatInVec.h"
namespace Vectormath {
inline
boolInVec::boolInVec(floatInVec vec)
{
*this = (vec != floatInVec(0.0f));
}
inline
boolInVec::boolInVec(bool scalar)
{
mData = -(int)scalar;
}
inline
bool
boolInVec::getAsBool() const
{
return (mData > 0);
}
#ifndef _VECTORMATH_NO_SCALAR_CAST
inline
boolInVec::operator bool() const
{
return getAsBool();
}
#endif
inline
const boolInVec
boolInVec::operator ! () const
{
return boolInVec(!mData);
}
inline
boolInVec&
boolInVec::operator = (boolInVec vec)
{
mData = vec.mData;
return *this;
}
inline
boolInVec&
boolInVec::operator &= (boolInVec vec)
{
*this = *this & vec;
return *this;
}
inline
boolInVec&
boolInVec::operator ^= (boolInVec vec)
{
*this = *this ^ vec;
return *this;
}
inline
boolInVec&
boolInVec::operator |= (boolInVec vec)
{
*this = *this | vec;
return *this;
}
inline
const boolInVec
operator == (boolInVec vec0, boolInVec vec1)
{
return boolInVec(vec0.getAsBool() == vec1.getAsBool());
}
inline
const boolInVec
operator != (boolInVec vec0, boolInVec vec1)
{
return !(vec0 == vec1);
}
inline
const boolInVec
operator & (boolInVec vec0, boolInVec vec1)
{
return boolInVec(vec0.getAsBool() & vec1.getAsBool());
}
inline
const boolInVec
operator | (boolInVec vec0, boolInVec vec1)
{
return boolInVec(vec0.getAsBool() | vec1.getAsBool());
}
inline
const boolInVec
operator ^ (boolInVec vec0, boolInVec vec1)
{
return boolInVec(vec0.getAsBool() ^ vec1.getAsBool());
}
inline
const boolInVec
select(boolInVec vec0, boolInVec vec1, boolInVec select_vec1)
{
return (select_vec1.getAsBool() == 0) ? vec0 : vec1;
}
} // namespace Vectormath
#endif // boolInVec_h
| 0 | 0.916842 | 1 | 0.916842 | game-dev | MEDIA | 0.915485 | game-dev | 0.806196 | 1 | 0.806196 |
SM64-TAS-ABC/STROOP | 2,891 | STROOP/Map/MapObjectMarioSlidingArrow.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using OpenTK.Graphics.OpenGL;
using STROOP.Utilities;
using STROOP.Structs.Configurations;
using STROOP.Structs;
using OpenTK;
using System.Windows.Forms;
using System.Xml.Linq;
namespace STROOP.Map
{
public class MapObjectMarioSlidingArrow : MapObjectArrow
{
private readonly PositionAngle _posAngle;
public MapObjectMarioSlidingArrow(PositionAngle posAngle)
: base()
{
_posAngle = posAngle;
}
public override PositionAngle GetPositionAngle()
{
return _posAngle;
}
protected override double GetYaw()
{
return WatchVariableSpecialUtilities.GetMarioSlidingAngle();
}
protected override double GetPitch()
{
return Config.Stream.GetShort(MarioConfig.StructAddress + MarioConfig.FacingPitchOffset);
}
protected override double GetRecommendedSize()
{
return WatchVariableSpecialUtilities.GetMarioSlidingSpeed();
}
public override void SetDragPositionTopDownView(double? x = null, double? y = null, double? z = null)
{
if (!x.HasValue || !z.HasValue) return;
PositionAngle posAngle = GetPositionAngle();
double dist = MoreMath.GetDistanceBetween(posAngle.X, posAngle.Z, x.Value, z.Value);
double angle = MoreMath.AngleTo_AngleUnits(posAngle.X, posAngle.Z, x.Value, z.Value);
double xDiff = x.Value - posAngle.X;
double zDiff = z.Value - posAngle.Z;
if (_useRecommendedArrowLength)
{
Config.Stream.SetValue((float)xDiff, MarioConfig.StructAddress + MarioConfig.SlidingSpeedXOffset);
Config.Stream.SetValue((float)zDiff, MarioConfig.StructAddress + MarioConfig.SlidingSpeedZOffset);
}
else
{
GetParentMapTracker().SetSize((float)(Scales ? dist : dist * Config.CurrentMapGraphics.MapViewScaleValue));
WatchVariableSpecialUtilities.SetMarioSlidingAngle(angle);
}
}
protected override void SetRecommendedSize(double size)
{
WatchVariableSpecialUtilities.SetMarioSlidingSpeed(size);
}
protected override void SetYaw(double yaw)
{
WatchVariableSpecialUtilities.SetMarioSlidingAngle(yaw);
}
public override string GetName()
{
return "Mario Sliding Arrow for " + _posAngle.GetMapName();
}
public override List<XAttribute> GetXAttributes()
{
return new List<XAttribute>()
{
new XAttribute("positionAngle", _posAngle),
};
}
}
}
| 0 | 0.931469 | 1 | 0.931469 | game-dev | MEDIA | 0.409087 | game-dev | 0.933623 | 1 | 0.933623 |
drewdru/ponyTown | 15,714 | src/scripts/server/maps/islandMap.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const lodash_1 = require("lodash");
const entities = require("../../common/entities");
const paths_1 = require("../paths");
const world_1 = require("../world");
const mapUtils_1 = require("../mapUtils");
const serverMap_1 = require("../serverMap");
const rect_1 = require("../../common/rect");
const controllerUtils_1 = require("../controllerUtils");
const entityUtils_1 = require("../entityUtils");
const playerUtils_1 = require("../playerUtils");
const constants_1 = require("../../common/constants");
const controllers_1 = require("../controllers");
const serverRegion_1 = require("../serverRegion");
const utils_1 = require("../../common/utils");
const islandMapData = JSON.parse(fs.readFileSync(paths_1.pathTo('src', 'maps', 'island.json'), 'utf8'));
let islandMapTemplate;
function createIslandMap(world, instanced, template = false) {
if (!template && !islandMapTemplate) {
islandMapTemplate = createIslandMap(mapUtils_1.worldForTemplates, false, true);
}
const map = (instanced && islandMapTemplate) ?
serverMap_1.serverMapInstanceFromTemplate(islandMapTemplate) :
serverMap_1.createServerMap('island', 1 /* Island */, 7, 7, 3 /* Water */, instanced ? 1 /* Party */ : 0 /* Public */);
map.usage = instanced ? 1 /* Party */ : 0 /* Public */;
map.spawnArea = rect_1.rect(43.4, 20, 3.3, 2.5);
map.spawns.set('house', rect_1.rect(27, 24, 2, 2));
if (islandMapTemplate) {
serverMap_1.copyMapTiles(map, islandMapTemplate);
}
else {
serverMap_1.deserializeMap(map, islandMapData);
}
const goto = instanced ? 'house' : 'public-house';
const add = (entity) => world.addEntity(entity, map);
const addEntities = (entities) => entities.map(add);
add(entities.house(28, 23)).interact = (_, client) => world_1.goToMap(world, client, goto);
add(entities.triggerHouseDoor(27.40, 22.87)).trigger = (_, client) => world_1.goToMap(world, client, goto);
add(controllerUtils_1.createBoxOfLanterns(25.5, 25.5));
const boxOfFruits = add(entities.boxFruits(20.72, 20.88));
entityUtils_1.setEntityName(boxOfFruits, 'Box of fruits');
const giftPile = add(entities.giftPileInteractive(37.66, 18.21));
giftPile.interact = (_, client) => entityUtils_1.updateEntityOptions(client.pony, playerUtils_1.getNextToyOrExtra(client));
entityUtils_1.setEntityName(giftPile, 'Toy stash');
const types = entities.stashEntities.map(e => e.type);
const itemSign = add(entities.signQuest(24.41, 25.00));
itemSign.interact = (_, client) => {
const index = types.indexOf(client.pony.options.hold || 0);
playerUtils_1.holdItem(client.pony, types[(index + 1) % types.length]);
};
entityUtils_1.setEntityName(itemSign, 'Item stash');
const addTorch = controllerUtils_1.createAddLight(world, map, entities.torch);
addTorch(25.00, 24.00);
addTorch(39.69, 18.38);
addTorch(39.66, 21.67);
addTorch(23.34, 38.46);
addTorch(28.16, 31.79);
addTorch(29.13, 38.17);
addTorch(30.84, 29.42);
addTorch(29.69, 25.00);
addTorch(20.00, 27.88);
addTorch(22.63, 30.54);
addTorch(19.22, 32.08);
addTorch(25.50, 26.79);
addTorch(15.94, 26.42);
addTorch(15.88, 29.75);
// pier
const px = 1 / constants_1.tileWidth;
const plankWidth = 78 / constants_1.tileWidth;
const plankHeight = 12 / constants_1.tileHeight;
const plankOffsets = [0, -1, 0, -2, -1, -1, 0, -2, -1, 0].map(x => x / constants_1.tileWidth);
addEntities(entities.fullBoat(45.06, 24));
add(entities.pierLeg(41.31, 20.54));
add(entities.pierLeg(43.00, 22.58));
add(entities.pierLeg(44.84, 22.58));
add(entities.pierLeg(46.65, 22.58));
add(entities.barrel(46.83, 23.35));
add(entities.lanternOn(46.19, 23.38));
add(entities.lanternOn(42.63, 21.42));
add(entities.lanternOn(47.00, 18.96));
add(entities.triggerBoat(45.5, 24.8)).interact = (_, client) => world_1.goToMap(world, client, '', 'harbor');
add(controllerUtils_1.createSignWithText(43, 23.5, 'Return to land', `Hop on the boat to return to the mainland`));
for (let y = 0; y < 10; y++) {
const minX = y < 5 ? 0 : 1;
const maxX = (y % 2) ? 4 : 3;
const baseX = 40 + ((y % 2) ? 0 : (plankWidth / 2)) + plankOffsets[y];
const baseY = 19 - (9 / constants_1.tileHeight);
for (let x = minX; x < maxX; x++) {
if ((x === minX && (y % 2)) || (x === (maxX - 1) && (y % 2))) {
const ox = x === minX ? (18 / constants_1.tileWidth) : (-18 / constants_1.tileWidth);
const plank = lodash_1.sample(entities.planksShort);
add(plank(baseX + ox + x * plankWidth, baseY + y * plankHeight));
}
else {
const plank = lodash_1.sample(entities.planks);
add(plank(baseX + x * plankWidth, baseY + y * plankHeight));
}
}
}
add(entities.plankShadow(41.31, 20.58));
add(entities.plankShadowShort(43.03, 21.08));
add(entities.plankShadowShort(43, 21.08 + plankHeight * 2));
const baseY = 18.58;
const baseX = 46.71;
add(entities.plankShadowShort(baseX, baseY));
add(entities.plankShadowShort(baseX + 2 * px, baseY + plankHeight));
add(entities.plankShadowShort(baseX, baseY + plankHeight * 2));
add(entities.plankShadowShort(baseX + 1 * px, baseY + plankHeight * 3));
add(entities.plankShadowShort(baseX - 1 * px, baseY + plankHeight * 4));
add(entities.plankShadowShort(baseX + 2 * px, baseY + plankHeight * 5));
add(entities.plankShadowShort(baseX, baseY + plankHeight * 6));
add(entities.plankShadowShort(baseX + 1 * px, baseY + plankHeight * 7));
add(entities.plankShadowShort(baseX - 1 * px, baseY + plankHeight * 8));
add(entities.plankShadowShort(baseX + 3 * px, baseY + plankHeight * 9));
add(entities.collider3x1(40, 18));
add(entities.collider3x1(43, 18));
add(entities.collider2x1(46, 18));
add(entities.collider1x3(47, 19));
add(entities.collider1x3(47, 22));
add(entities.collider3x1(40, 21));
add(entities.collider1x3(42, 22));
add(entities.collider1x1(43, 24));
add(entities.collider3x1(42, 25));
add(entities.collider3x1(45, 25));
add(entities.collider1x3(47.6, 23));
add(entities.collider1x3(41.5, 22));
// lone boat
addEntities(entities.fullBoat(27.12, 42, false));
add(entities.plankShort3(27.43, 39.67));
add(entities.plankShort3(27.46, 40.21));
add(entities.plankShort3(27.43, 40.75));
add(entities.plankShort3(27.46, 41.21));
add(entities.pierLeg(27.96, 40.88));
add(entities.pierLeg(27.02, 40.79));
add(entities.plankShadowShort(27.5, 39.67));
add(entities.plankShadowShort(27.5 + 1 * px, 39.67 + plankHeight));
add(entities.plankShadowShort(27.5, 39.67 + plankHeight * 2));
add(entities.plankShadowShort(27.5 + 1 * px, 39.67 + plankHeight * 3));
add(entities.lanternOn(28.77, 42.27));
add(entities.collider3x1(24, 41));
add(entities.collider2x1(24, 42));
add(entities.collider1x2(26, 40));
add(entities.collider1x2(28, 40));
add(entities.collider2x1(28, 41));
add(entities.collider3x1(24, 43));
add(entities.collider3x1(27, 43));
add(entities.collider1x1(29, 42));
add(entities.collider1x3(29.7, 41));
add(entities.collider1x3(23.5, 41));
const addWoodenFence = controllerUtils_1.createWoodenFenceMaker(world, map);
addWoodenFence(20, 20, 4);
addWoodenFence(20, 20, 4, false, true);
addWoodenFence(24, 20, 4, false, true);
addWoodenFence(20, 24, 1, true, true);
addWoodenFence(23, 24, 1, true, false, true);
addEntities(entities.tree(22.41, 18.21, 0));
addEntities(entities.tree(30.44, 23.46, 1 + 4));
addEntities(entities.tree5(34.53, 27.04, 0));
addEntities(entities.tree5(19.28, 21.75, 1));
add(entities.pumpkin(23.22, 20.58));
add(entities.pumpkin(20.53, 22.29));
add(entities.pumpkin(20.91, 23.08));
add(entities.largeLeafedBush2(35.03, 26.71));
add(entities.largeLeafedBush4(34.13, 27.54));
add(entities.largeLeafedBush2(20.34, 24.42));
add(entities.largeLeafedBush3(19.72, 24.04));
add(entities.largeLeafedBush3(23.03, 38.67));
add(entities.largeLeafedBush4(23.72, 38.04));
add(entities.barrel(39.53, 18.96));
add(entities.barrel(38.78, 18.38));
add(entities.barrel(38.47, 19.21));
add(entities.barrel(24.63, 23.50));
add(entities.treeStump1(20.25, 36.46));
add(entities.lanternOn(20.75, 37.00));
add(entities.lanternOn(36.06, 34.25));
add(entities.lanternOn(37.63, 36.83));
add(entities.lanternOn(37.84, 26.94));
add(entities.waterRock1(22.63, 41.83));
add(entities.waterRock1(28.56, 13.75));
add(entities.waterRock1(16.25, 20.88));
add(entities.waterRock1(40.62, 29.62));
add(entities.waterRock1(40.63, 17.96));
add(entities.waterRock2(40.22, 17.50));
add(entities.waterRock2(20.34, 15.75));
add(entities.waterRock2(15.41, 34.13));
add(entities.waterRock2(36.50, 40.63));
add(entities.waterRock3(36.13, 40.96));
add(entities.waterRock3(41.63, 34.38));
add(entities.waterRock3(15.16, 34.67));
add(entities.waterRock3(20.88, 15.50));
add(entities.waterRock4(36.56, 41.13));
add(entities.waterRock4(40.72, 17.29));
add(entities.waterRock4(28.22, 13.25));
add(entities.waterRock5(28.66, 13.17));
add(entities.waterRock5(16.84, 20.42));
add(entities.waterRock5(14.44, 30.50));
add(entities.waterRock5(23.13, 41.88));
add(entities.waterRock5(30.44, 39.71));
add(entities.waterRock5(41.84, 34.83));
add(entities.waterRock5(36.63, 14.75));
add(entities.waterRock6(36.25, 14.54));
add(entities.waterRock6(14.84, 34.29));
add(entities.waterRock6(40.44, 38.71));
add(entities.waterRock7(42.13, 34.42));
add(entities.waterRock7(20.34, 15.25));
add(entities.waterRock7(28.78, 40.79));
add(entities.waterRock7(22.66, 42.08));
add(entities.waterRock8(22.25, 41.92));
add(entities.waterRock8(14.13, 30.79));
add(entities.waterRock8(16.28, 20.21));
add(entities.waterRock8(42.19, 34.79));
add(entities.waterRock9(36.78, 14.29));
add(entities.waterRock9(13.97, 30.33));
add(entities.waterRock10(14.50, 25.83));
add(entities.waterRock10(18.88, 40.75));
add(entities.waterRock11(25.37, 13.75));
add(entities.waterRock11(18.44, 40.58));
add(entities.waterRock11(15.41, 24.33));
add(entities.waterRock4(15.13, 23.96));
add(entities.waterRock11(35.38, 31.08));
add(entities.waterRock8(35.09, 30.71));
add(entities.waterRock3(34.03, 29.79));
add(entities.waterRock4(34.31, 29.67));
add(entities.waterRock4(24.50, 35.92));
add(entities.waterRock3(33.44, 38.21));
add(entities.waterRock4(33.16, 37.92));
add(entities.waterRock1(25.50, 17.79));
add(entities.waterRock9(25.66, 18.13));
add(entities.waterRock4(25.97, 17.79));
add(entities.flower3Pickable(30.25, 24.92)).interact = (_, { pony }) => playerUtils_1.holdItem(pony, entities.flowerPick.type);
add(entities.bench1(37.78, 24.96));
add(entities.benchSeat(37.75, 28.29));
add(entities.benchBack(37.75, 29.17));
// small island bit
addEntities(entities.tree(9.16, 16.50, 2 + 8));
add(entities.waterRock1(5.34, 23.71));
add(entities.waterRock1(13.28, 14.33));
add(entities.waterRock1(11.19, 24.83));
add(entities.waterRock3(10.94, 25.21));
add(entities.waterRock3(6.31, 18.92));
add(entities.waterRock3(13.59, 14.71));
add(entities.waterRock5(13.84, 14.17));
add(entities.waterRock4(11.38, 25.13));
add(entities.waterRock6(6.41, 15.92));
add(entities.waterRock8(5.16, 23.13));
add(entities.waterRock10(6.06, 16.33));
add(entities.waterRock11(14.66, 20.75));
add(entities.torch(9.31, 17.83));
add(entities.torch(9.44, 21.67));
add(entities.torch(12.75, 18.29));
if (world.season === 1 /* Summer */ || world.season === 8 /* Spring */) {
add(entities.flowerPatch1(21.16, 26.04));
add(entities.flowerPatch3(35.81, 34.75));
add(entities.flowerPatch3(23.09, 32.29));
add(entities.flowerPatch5(19.63, 33.04));
add(entities.flowerPatch5(37.38, 26.42));
add(entities.flowerPatch5(18.75, 26.38));
add(entities.flowerPatch5(35.38, 33.88));
add(entities.flowerPatch6(25.78, 31.04));
add(entities.flowerPatch6(33.00, 33.79));
add(entities.flowerPatch6(38.72, 26.00));
add(entities.flowerPatch3(11.34, 19.33));
add(entities.flowerPatch6(11.09, 17.79));
add(entities.flowerPatch7(8.63, 21.67));
}
if (world.season === 2 /* Autumn */) {
add(entities.leafpileStickRed(31.00, 22.75));
add(entities.leaves5(18.41, 21.46));
add(entities.leaves2(21.59, 18.17));
add(entities.leaves2(23.56, 18.00));
add(entities.leaves1(22.00, 17.21));
add(entities.leaves1(22.47, 20.00));
add(entities.leaves2(33.69, 25.42));
add(entities.leaves1(33.47, 26.75));
add(entities.leaves1(35.66, 27.08));
add(entities.leaves3(30.31, 24.04));
add(entities.leaves1(31.56, 23.00));
add(entities.leaves1(29.47, 23.21));
add(entities.leaves3(8.84, 17.04));
add(entities.leaves2(8.91, 15.25));
add(entities.leaves1(10.44, 16.46));
}
addEntities(mapUtils_1.createBunny([
utils_1.point(22.19, 27.25),
utils_1.point(19.75, 26.13),
utils_1.point(18.44, 29.04),
utils_1.point(20.41, 31.42),
utils_1.point(19.94, 33.04),
utils_1.point(22.88, 33.67),
utils_1.point(24.91, 31.25),
utils_1.point(26.09, 32.50),
utils_1.point(26.34, 34.83),
utils_1.point(32.50, 35.46),
utils_1.point(34.03, 34.67),
utils_1.point(36.06, 36.50),
utils_1.point(36.47, 35.33),
utils_1.point(36.22, 34.63),
utils_1.point(33.63, 34.83),
utils_1.point(31.88, 33.25),
utils_1.point(32.00, 28.46),
utils_1.point(33.22, 25.75),
utils_1.point(35.09, 24.75),
utils_1.point(36.13, 25.67),
utils_1.point(36.72, 27.38),
utils_1.point(38.31, 27.42),
utils_1.point(38.63, 26.54),
utils_1.point(37.31, 26.63),
utils_1.point(36.06, 26.42),
utils_1.point(35.34, 24.29),
utils_1.point(33.13, 25.83),
utils_1.point(30.06, 25.13),
utils_1.point(26.50, 26.38),
utils_1.point(24.66, 28.25),
utils_1.point(22.25, 28.50),
utils_1.point(20.97, 27.00),
utils_1.point(19.13, 27.13),
utils_1.point(20.69, 29.25),
utils_1.point(22.34, 29.42),
utils_1.point(21.53, 31.46),
utils_1.point(23.50, 31.54),
utils_1.point(23.81, 29.71),
]));
map.controllers.push(new controllers_1.TorchController(world, map));
map.controllers.push(new controllers_1.UpdateController(map));
if (DEVELOPMENT) {
mapUtils_1.addSpawnPointIndicators(world, map);
}
if (!islandMapTemplate) {
mapUtils_1.generateTileIndicesAndColliders(map);
}
return map;
}
exports.createIslandMap = createIslandMap;
function resetIslandMap(map) {
serverMap_1.copyMapTiles(map, islandMapTemplate);
for (const region of map.regions) {
region.clients = [];
mapUtils_1.removePonies(region.entities);
mapUtils_1.removePonies(region.movables);
serverRegion_1.resetRegionUpdates(region);
}
}
exports.resetIslandMap = resetIslandMap;
//# sourceMappingURL=islandMap.js.map | 0 | 0.696698 | 1 | 0.696698 | game-dev | MEDIA | 0.856999 | game-dev | 0.882749 | 1 | 0.882749 |
akhuting/gms083 | 11,801 | src/main/resources/scripts/npc/2040016.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Pi
Ludibrium Village (220000300)
Refining NPC:
* Minerals
* Jewels
* Moon/Star Rocks
* Crystals (minus Dark)
* Processed Wood/Screws
* Arrows/Bronze Arrows/Steel Arrows
*/
var status = 0;
var selectedType = -1;
var selectedItem = -1;
var item;
var mats;
var matQty;
var cost;
var qty;
var equip;
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == 1)
status++;
else
cm.dispose();
if (status == 0 && mode == 1) {
var selStr = "Hm? Who might you be? Oh, you've heard about my forging skills? In that case, I'd be glad to process some of your ores... for a fee.#b"
var options = new Array("Refine a mineral ore","Refine a jewel ore","Refine a rare jewel","Refine a crystal ore","Create materials","Create Arrows");
for (var i = 0; i < options.length; i++){
selStr += "\r\n#L" + i + "# " + options[i] + "#l";
}
cm.sendSimple(selStr);
}
else if (status == 1 && mode == 1) {
selectedType = selection;
if (selectedType == 0){ //mineral refine
var selStr = "So, what kind of mineral ore would you like to refine?#b";
var minerals = new Array ("Bronze","Steel","Mithril","Adamantium","Silver","Orihalcon","Gold");
for (var i = 0; i < minerals.length; i++){
selStr += "\r\n#L" + i + "# " + minerals[i] + "#l";
}
equip = false;
cm.sendSimple(selStr);
}
else if (selectedType == 1){ //jewel refine
var selStr = "So, what kind of jewel ore would you like to refine?#b";
var jewels = new Array ("Garnet","Amethyst","Aquamarine","Emerald","Opal","Sapphire","Topaz","Diamond","Black Crystal");
for (var i = 0; i < jewels.length; i++){
selStr += "\r\n#L" + i + "# " + jewels[i] + "#l";
}
equip = false;
cm.sendSimple(selStr);
}
else if (selectedType == 2){ //rock refine
var selStr = "A rare jewel? Which one were you thinking of?#b";
var items = new Array ("Moon Rock","Star Rock");
for (var i = 0; i < items.length; i++){
selStr += "\r\n#L" + i + "# " + items[i] + "#l";
}
equip = false;
cm.sendSimple(selStr);
}
else if (selectedType == 3){ //crystal refine
var selStr = "Crystal ore? I love refining those!#b";
var crystals = new Array ("Power Crystal","Wisdom Crystal","DEX Crystal","LUK Crystal");
for (var i = 0; i < crystals.length; i++){
selStr += "\r\n#L" + i + "# " + crystals[i] + "#l";
}
equip = false;
cm.sendSimple(selStr);
}
else if (selectedType == 4){ //material refine
var selStr = "Materials? I know of a few materials that I can make for you...#b";
var materials = new Array ("Make Processed Wood with Tree Branch","Make Processed Wood with Firewood","Make Screws (packs of 15)");
for (var i = 0; i < materials.length; i++){
selStr += "\r\n#L" + i + "# " + materials[i] + "#l";
}
equip = false;
cm.sendSimple(selStr);
}
else if (selectedType == 5){ //arrow refine
var selStr = "Arrows? Not a problem at all.#b";
var arrows = new Array ("Arrow for Bow","Arrow for Crossbow","Bronze Arrow for Bow","Bronze Arrow for Crossbow","Steel Arrow for Bow","Steel Arrow for Crossbow");
for (var i = 0; i < arrows.length; i++){
selStr += "\r\n#L" + i + "# " + arrows[i] + "#l";
}
equip = true;
cm.sendSimple(selStr);
}
if (equip)
status++;
}
else if (status == 2 && mode == 1) {
selectedItem = selection;
if (selectedType == 0){ //mineral refine
var itemSet = new Array(4011000,4011001,4011002,4011003,4011004,4011005,4011006);
var matSet = new Array(4010000,4010001,4010002,4010003,4010004,4010005,4010006);
var matQtySet = new Array(10,10,10,10,10,10,10);
var costSet = new Array(270,270,270,450,450,450,720);
item = itemSet[selectedItem];
mats = matSet[selectedItem];
matQty = matQtySet[selectedItem];
cost = costSet[selectedItem];
}
else if (selectedType == 1){ //jewel refine
var itemSet = new Array(4021000,4021001,4021002,4021003,4021004,4021005,4021006,4021007,4021008);
var matSet = new Array(4020000,4020001,4020002,4020003,4020004,4020005,4020006,4020007,4020008);
var matQtySet = new Array(10,10,10,10,10,10,10,10,10);
var costSet = new Array (450,450,450,450,450,450,450,900,2700);
item = itemSet[selectedItem];
mats = matSet[selectedItem];
matQty = matQtySet[selectedItem];
cost = costSet[selectedItem];
}
else if (selectedType == 2){ //rock refine
var itemSet = new Array(4011007,4021009);
var matSet = new Array(new Array(4011000,4011001,4011002,4011003,4011004,4011005,4011006), new Array(4021000,4021001,4021002,4021003,4021004,4021005,4021006,4021007,4021008));
var matQtySet = new Array(new Array(1,1,1,1,1,1,1),new Array(1,1,1,1,1,1,1,1,1));
var costSet = new Array(9000,13500);
item = itemSet[selectedItem];
mats = matSet[selectedItem];
matQty = matQtySet[selectedItem];
cost = costSet[selectedItem];
}
else if (selectedType == 3){ //crystal refine
var itemSet = new Array (4005000,4005001,4005002,4005003);
var matSet = new Array(4004000,4004001,4004002,4004003);
var matQtySet = new Array (10,10,10,10);
var costSet = new Array (4500,4500,4500,4500);
item = itemSet[selectedItem];
mats = matSet[selectedItem];
matQty = matQtySet[selectedItem];
cost = costSet[selectedItem];
}
else if (selectedType == 4){ //material refine
var itemSet = new Array (4003001,4003001,4003000);
var matSet = new Array(4000003,4000018,new Array (4011000,4011001));
var matQtySet = new Array (10,5,new Array (1,1));
var costSet = new Array (0,0,0);
item = itemSet[selectedItem];
mats = matSet[selectedItem];
matQty = matQtySet[selectedItem];
cost = costSet[selectedItem];
}
var prompt = "So, you want me to make some #t" + item + "#s? In that case, how many do you want me to make?";
cm.sendGetNumber(prompt,1,1,100)
}
else if (status == 3 && mode == 1) {
if (equip)
{
selectedItem = selection;
qty = 1;
}
else
qty = (selection > 0) ? selection : (selection < 0 ? -selection : 1);
// thanks kvmba for noticing arrow selection crashing players
if (selectedType == 5){ //arrow refine
var itemSet = new Array(2060000,2061000,2060001,2061001,2060002,2061002);
var matSet = new Array(new Array (4003001,4003004),new Array (4003001,4003004),new Array (4011000,4003001,4003004),new Array (4011000,4003001,4003004),
new Array (4011001,4003001,4003005),new Array (4011001,4003001,4003005));
var matQtySet = new Array (new Array (1,1),new Array (1,1),new Array (1,3,10),new Array (1,3,10),new Array (1,5,15),new Array (1,5,15));
var costSet = new Array (0,0,0,0,0,0);
item = itemSet[selectedItem];
mats = matSet[selectedItem];
matQty = matQtySet[selectedItem];
cost = costSet[selectedItem];
}
var prompt = "You want me to make ";
if (qty == 1)
prompt += "a #t" + item + "#?";
else
prompt += qty + " #t" + item + "#?";
prompt += " In that case, I'm going to need specific items from you in order to make it. Make sure you have room in your inventory, though!#b";
if (mats instanceof Array){
for(var i = 0; i < mats.length; i++){
prompt += "\r\n#i"+mats[i]+"# " + matQty[i] * qty + " #t" + mats[i] + "#";
}
}
else {
prompt += "\r\n#i"+mats+"# " + matQty * qty + " #t" + mats + "#";
}
if (cost > 0)
prompt += "\r\n#i4031138# " + cost * qty + " meso";
cm.sendYesNo(prompt);
}
else if (status == 4 && mode == 1) {
var complete = true;
var recvItem = item, recvQty;
if (item >= 2060000 && item <= 2060002) //bow arrows
recvQty = 1000 - (item - 2060000) * 100;
else if (item >= 2061000 && item <= 2061002) //xbow arrows
recvQty = 1000 - (item - 2061000) * 100;
else if (item == 4003000)//screws
recvQty = 15 * qty;
else
recvQty = qty;
if(!cm.canHold(recvItem, recvQty)) {
cm.sendOk("I'm afraid you have no slots available for this transaction.");
}
else if (cm.getMeso() < cost * qty)
{
cm.sendOk("I'm afraid you cannot afford my services.");
}
else
{
if (mats instanceof Array) {
for(var i = 0; complete && i < mats.length; i++)
{
if (matQty[i] * qty == 1) {
if (!cm.haveItem(mats[i] * qty))
{
complete = false;
}
}
else {
if (!cm.haveItem(mats[i],matQty[i] * qty)) complete=false;
}
}
}
else {
if (!cm.haveItem(mats, matQty * qty)) complete=false;
}
if (!complete)
cm.sendOk("Hold it, I can't finish that without all of the proper materials. Bring them first, then we'll talk.");
else {
if (mats instanceof Array) {
for (var i = 0; i < mats.length; i++){
cm.gainItem(mats[i], -matQty[i] * qty);
}
}
else
cm.gainItem(mats, -matQty * qty);
if (cost > 0)
cm.gainMeso(-cost * qty);
cm.gainItem(recvItem, recvQty);
cm.sendOk("All done. If you need anything else, you know where to find me.");
}
}
cm.dispose();
}
} | 0 | 0.521922 | 1 | 0.521922 | game-dev | MEDIA | 0.794658 | game-dev | 0.82299 | 1 | 0.82299 |
grzybeek/grzyClothTool | 5,351 | CodeWalker/CodeWalker.Core/GameFiles/FileTypes/YptFile.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace CodeWalker.GameFiles
{
[TypeConverter(typeof(ExpandableObjectConverter))]
public class YptFile : GameFile, PackedFile
{
public ParticleEffectsList PtfxList { get; set; }
public Dictionary<uint, DrawableBase> DrawableDict { get; set; }
public Dictionary<MetaHash, ParticleEffectRule> EffectDict { get; set; }
public ParticleEffectRule[] AllEffects { get; set; }
public string ErrorMessage { get; set; }
#if DEBUG
public ResourceAnalyzer Analyzer { get; set; }
#endif
public YptFile() : base(null, GameFileType.Ypt)
{
}
public YptFile(RpfFileEntry entry) : base(entry, GameFileType.Ypt)
{
}
public void Load(byte[] data, RpfFileEntry entry)
{
Name = entry.Name;
RpfFileEntry = entry;
RpfResourceFileEntry resentry = entry as RpfResourceFileEntry;
if (resentry == null)
{
throw new Exception("File entry wasn't a resource! (is it binary data?)");
}
ResourceDataReader rd = new ResourceDataReader(resentry, data);
//MemoryUsage = 0;
try
{
PtfxList = rd.ReadBlock<ParticleEffectsList>();
//Drawable.Owner = this;
//MemoryUsage += Drawable.MemoryUsage; //uses decompressed filesize now...
}
catch (Exception ex)
{
ErrorMessage = ex.ToString();
}
BuildDrawableDict();
BuildParticleDict();
#if DEBUG
Analyzer = new ResourceAnalyzer(rd);
#endif
Loaded = true;
}
public byte[] Save()
{
byte[] data = ResourceBuilder.Build(PtfxList, 68); //ypt is type/version 68...
return data;
}
private void BuildDrawableDict()
{
var dDict = PtfxList?.DrawableDictionary;
if ((dDict?.Drawables?.data_items != null) && (dDict?.Hashes != null))
{
DrawableDict = new Dictionary<uint, DrawableBase>();
var drawables = dDict.Drawables.data_items;
var hashes = dDict.Hashes;
for (int i = 0; (i < drawables.Length) && (i < hashes.Length); i++)
{
var drawable = drawables[i];
var hash = hashes[i];
DrawableDict[hash] = drawable;
drawable.Owner = this;
}
//for (int i = 0; (i < drawables.Length) && (i < hashes.Length); i++)
//{
// var drawable = drawables[i];
// var hash = hashes[i];
// if ((drawable.Name == null) || (drawable.Name.EndsWith("#dd")))
// {
// string hstr = JenkIndex.TryGetString(hash);
// if (!string.IsNullOrEmpty(hstr))
// {
// drawable.Name = hstr;
// }
// else
// {
// drawable.Name = "0x" + hash.ToString("X").PadLeft(8, '0');
// }
// }
//}
}
}
private void BuildParticleDict()
{
var pdict = PtfxList?.EffectRuleDictionary;
if (pdict?.EffectRules?.data_items != null)
{
EffectDict = new Dictionary<MetaHash, ParticleEffectRule>();
var elist = new List<ParticleEffectRule>();
foreach (var e in pdict.EffectRules.data_items)
{
EffectDict[e.NameHash] = e;
elist.Add(e);
}
elist.Sort((a, b) => { return (a.Name?.Value ?? "").CompareTo(b.Name?.Value ?? ""); });
AllEffects = elist.ToArray();
}
}
}
public class YptXml : MetaXmlBase
{
public static string GetXml(YptFile ypt, string outputFolder = "")
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(XmlHeader);
if (ypt?.PtfxList != null)
{
ParticleEffectsList.WriteXmlNode(ypt.PtfxList, sb, 0, outputFolder);
}
return sb.ToString();
}
}
public class XmlYpt
{
public static YptFile GetYpt(string xml, string inputFolder = "")
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return GetYpt(doc, inputFolder);
}
public static YptFile GetYpt(XmlDocument doc, string inputFolder = "")
{
YptFile r = new YptFile();
var ddsfolder = inputFolder;
var node = doc.DocumentElement;
if (node != null)
{
r.PtfxList = ParticleEffectsList.ReadXmlNode(node, ddsfolder);
}
r.Name = Path.GetFileName(inputFolder);
return r;
}
}
}
| 0 | 0.836647 | 1 | 0.836647 | game-dev | MEDIA | 0.862469 | game-dev | 0.985569 | 1 | 0.985569 |
dotnet/dotnet | 10,707 | src/roslyn/src/RoslynAnalyzers/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetCallbacks.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
namespace Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis
{
/// <summary>
/// Common callbacks for <see cref="PropertySetAnalysis"/>.
/// </summary>
internal static class PropertySetCallbacks
{
/// <summary>
/// A <see cref="PropertyMapper.PointsToAbstractValueCallback"/> for flagging assigning null to a property.
/// </summary>
/// <param name="pointsToAbstractValue">Value assigned to the property.</param>
/// <returns>Flagged if null, Unflagged if not null, MaybeFlagged otherwise.</returns>
public static PropertySetAbstractValueKind FlagIfNull(PointsToAbstractValue pointsToAbstractValue)
{
return pointsToAbstractValue.NullState switch
{
NullAbstractValue.Null => PropertySetAbstractValueKind.Flagged,
NullAbstractValue.NotNull => PropertySetAbstractValueKind.Unflagged,
NullAbstractValue.MaybeNull => PropertySetAbstractValueKind.MaybeFlagged,
_ => PropertySetAbstractValueKind.Unknown,
};
}
/// <summary>
/// Enumerates literal values to map to a property set abstract value.
/// </summary>
/// <param name="valueContentAbstractValue">Abstract value containing the literal values to examine.</param>
/// <param name="badLiteralValuePredicate">Predicate function to determine if a literal value is bad.</param>
/// <returns>Mapped kind.</returns>
/// <remarks>
/// All literal values are bad => Flagged
/// Some but not all literal are bad => MaybeFlagged
/// All literal values are known and none are bad => Unflagged
/// Otherwise => Unknown
/// </remarks>
public static PropertySetAbstractValueKind EvaluateLiteralValues(
ValueContentAbstractValue valueContentAbstractValue,
Func<object?, bool> badLiteralValuePredicate)
{
switch (valueContentAbstractValue.NonLiteralState)
{
case ValueContainsNonLiteralState.No:
if (valueContentAbstractValue.LiteralValues.IsEmpty)
{
return PropertySetAbstractValueKind.Unflagged;
}
bool allValuesBad = true;
bool someValuesBad = false;
foreach (object? literalValue in valueContentAbstractValue.LiteralValues)
{
if (badLiteralValuePredicate(literalValue))
{
someValuesBad = true;
}
else
{
allValuesBad = false;
}
if (!allValuesBad && someValuesBad)
{
break;
}
}
if (allValuesBad)
{
// We know all values are bad, so we can say Flagged.
return PropertySetAbstractValueKind.Flagged;
}
else if (someValuesBad)
{
// We know all values but some values are bad, so we can say MaybeFlagged.
return PropertySetAbstractValueKind.MaybeFlagged;
}
else
{
// We know all values are good, so we can say Unflagged.
return PropertySetAbstractValueKind.Unflagged;
}
case ValueContainsNonLiteralState.Maybe:
if (valueContentAbstractValue.LiteralValues.Any(badLiteralValuePredicate))
{
// We don't know all values but know some values are bad, so we can say MaybeFlagged.
return PropertySetAbstractValueKind.MaybeFlagged;
}
else
{
// We don't know all values but didn't find any bad value, so we can say who knows.
return PropertySetAbstractValueKind.Unknown;
}
default:
return PropertySetAbstractValueKind.Unknown;
}
}
/// <summary>
/// A <see cref="HazardousUsageEvaluator.EvaluationCallback"/> for all properties flagged being hazardous, treating all
/// unknown as maybe flagged.
/// </summary>
/// <param name="propertySetAbstractValue">PropertySetAbstract value.</param>
/// <returns>If all properties are flagged, then flagged; if at least one property is unflagged, then unflagged;
/// otherwise (including all unknown) maybe flagged.</returns>
public static HazardousUsageEvaluationResult HazardousIfAllFlaggedOrAllUnknown(
PropertySetAbstractValue propertySetAbstractValue)
{
return HazardousIfAllFlagged(propertySetAbstractValue, assumeAllUnknownInsecure: true);
}
/// <summary>
/// A <see cref="HazardousUsageEvaluator.EvaluationCallback"/> for all properties flagged being hazardous, treating all
/// unknown as unflagged.
/// </summary>
/// <param name="propertySetAbstractValue">PropertySetAbstract value.</param>
/// <returns>If all properties are flagged, then flagged; if at least one property is unflagged, then unflagged;
/// otherwise (excluding all unknown) maybe flagged.</returns>
public static HazardousUsageEvaluationResult HazardousIfAllFlaggedAndAtLeastOneKnown(
PropertySetAbstractValue propertySetAbstractValue)
{
return HazardousIfAllFlagged(propertySetAbstractValue, assumeAllUnknownInsecure: false);
}
/// <summary>
/// A <see cref="HazardousUsageEvaluator.InvocationEvaluationCallback"/> for all properties flagged being hazardous,
/// treating all unknown as maybe flagged.
/// </summary>
/// <param name="methodSymbol">Ignored. If your scenario cares about the method, don't use this.</param>
/// <param name="propertySetAbstractValue">PropertySetAbstract value.</param>
/// <returns>If all properties are flagged, then flagged; if all properties are unflagged, then unflagged; otherwise
/// (including all unknown) maybe flagged.</returns>
[SuppressMessage("Usage", "CA1801", Justification = "Intentionally ignored; have to match delegate signature")]
[SuppressMessage("Usage", "IDE0060", Justification = "Intentionally ignored; have to match delegate signature")]
public static HazardousUsageEvaluationResult HazardousIfAllFlaggedOrAllUnknown(
IMethodSymbol methodSymbol,
PropertySetAbstractValue propertySetAbstractValue)
{
return HazardousIfAllFlagged(propertySetAbstractValue, assumeAllUnknownInsecure: true);
}
/// <summary>
/// A <see cref="HazardousUsageEvaluator.InvocationEvaluationCallback"/> for all properties flagged being hazardous,
/// treating all unknown as unflagged
/// </summary>
/// <param name="methodSymbol">Ignored. If your scenario cares about the method, don't use this.</param>
/// <param name="propertySetAbstractValue">PropertySetAbstract value.</param>
/// <returns>If all properties are flagged, then flagged; if all properties are unflagged, then unflagged; otherwise
/// (excluding all unknown) maybe flagged.</returns>
[SuppressMessage("Usage", "CA1801", Justification = "Intentionally ignored; have to match delegate signature")]
[SuppressMessage("Usage", "IDE0060", Justification = "Intentionally ignored; have to match delegate signature")]
public static HazardousUsageEvaluationResult HazardousIfAllFlaggedAndAtLeastOneKnown(
IMethodSymbol methodSymbol,
PropertySetAbstractValue propertySetAbstractValue)
{
return HazardousIfAllFlagged(propertySetAbstractValue, assumeAllUnknownInsecure: false);
}
/// <summary>
/// A <see cref="HazardousUsageEvaluator.EvaluationCallback"/> for all properties flagged being hazardous.
/// </summary>
/// <param name="propertySetAbstractValue">PropertySetAbstract value.</param>
/// <returns>If all properties are flagged, then flagged; if at least one property is unflagged, then unflagged; otherwise (including all unknown) maybe flagged.</returns>
private static HazardousUsageEvaluationResult HazardousIfAllFlagged(
PropertySetAbstractValue propertySetAbstractValue,
bool assumeAllUnknownInsecure)
{
if (propertySetAbstractValue.KnownValuesCount == 0)
{
// No known values implies all properties are PropertySetAbstractValueKind.Unknown.
return assumeAllUnknownInsecure
? HazardousUsageEvaluationResult.MaybeFlagged
: HazardousUsageEvaluationResult.Unflagged;
}
bool allFlagged = true;
bool atLeastOneUnflagged = false;
for (int i = 0; i < propertySetAbstractValue.KnownValuesCount; i++)
{
if (propertySetAbstractValue[i] != PropertySetAbstractValueKind.Flagged)
{
allFlagged = false;
}
if (propertySetAbstractValue[i] == PropertySetAbstractValueKind.Unflagged)
{
atLeastOneUnflagged = true;
break;
}
}
if (allFlagged)
{
return HazardousUsageEvaluationResult.Flagged;
}
else if (atLeastOneUnflagged)
{
return HazardousUsageEvaluationResult.Unflagged;
}
else
{
// Mix of flagged and unknown.
return HazardousUsageEvaluationResult.MaybeFlagged;
}
}
}
}
| 0 | 0.776729 | 1 | 0.776729 | game-dev | MEDIA | 0.174979 | game-dev | 0.760617 | 1 | 0.760617 |
sebbas/blender-mantaflow | 8,769 | extern/bullet2/src/LinearMath/btTransform.h | /*
Copyright (c) 2003-2006 Gino van den Bergen / 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_TRANSFORM_H
#define BT_TRANSFORM_H
#include "btMatrix3x3.h"
#ifdef BT_USE_DOUBLE_PRECISION
#define btTransformData btTransformDoubleData
#else
#define btTransformData btTransformFloatData
#endif
/**@brief The btTransform class supports rigid transforms with only translation and rotation and no scaling/shear.
*It can be used in combination with btVector3, btQuaternion and btMatrix3x3 linear algebra classes. */
ATTRIBUTE_ALIGNED16(class) btTransform {
///Storage for the rotation
btMatrix3x3 m_basis;
///Storage for the translation
btVector3 m_origin;
public:
/**@brief No initialization constructor */
btTransform() {}
/**@brief Constructor from btQuaternion (optional btVector3 )
* @param q Rotation from quaternion
* @param c Translation from Vector (default 0,0,0) */
explicit SIMD_FORCE_INLINE btTransform(const btQuaternion& q,
const btVector3& c = btVector3(btScalar(0), btScalar(0), btScalar(0)))
: m_basis(q),
m_origin(c)
{}
/**@brief Constructor from btMatrix3x3 (optional btVector3)
* @param b Rotation from Matrix
* @param c Translation from Vector default (0,0,0)*/
explicit SIMD_FORCE_INLINE btTransform(const btMatrix3x3& b,
const btVector3& c = btVector3(btScalar(0), btScalar(0), btScalar(0)))
: m_basis(b),
m_origin(c)
{}
/**@brief Copy constructor */
SIMD_FORCE_INLINE btTransform (const btTransform& other)
: m_basis(other.m_basis),
m_origin(other.m_origin)
{
}
/**@brief Assignment Operator */
SIMD_FORCE_INLINE btTransform& operator=(const btTransform& other)
{
m_basis = other.m_basis;
m_origin = other.m_origin;
return *this;
}
/**@brief Set the current transform as the value of the product of two transforms
* @param t1 Transform 1
* @param t2 Transform 2
* This = Transform1 * Transform2 */
SIMD_FORCE_INLINE void mult(const btTransform& t1, const btTransform& t2) {
m_basis = t1.m_basis * t2.m_basis;
m_origin = t1(t2.m_origin);
}
/* void multInverseLeft(const btTransform& t1, const btTransform& t2) {
btVector3 v = t2.m_origin - t1.m_origin;
m_basis = btMultTransposeLeft(t1.m_basis, t2.m_basis);
m_origin = v * t1.m_basis;
}
*/
/**@brief Return the transform of the vector */
SIMD_FORCE_INLINE btVector3 operator()(const btVector3& x) const
{
return x.dot3(m_basis[0], m_basis[1], m_basis[2]) + m_origin;
}
/**@brief Return the transform of the vector */
SIMD_FORCE_INLINE btVector3 operator*(const btVector3& x) const
{
return (*this)(x);
}
/**@brief Return the transform of the btQuaternion */
SIMD_FORCE_INLINE btQuaternion operator*(const btQuaternion& q) const
{
return getRotation() * q;
}
/**@brief Return the basis matrix for the rotation */
SIMD_FORCE_INLINE btMatrix3x3& getBasis() { return m_basis; }
/**@brief Return the basis matrix for the rotation */
SIMD_FORCE_INLINE const btMatrix3x3& getBasis() const { return m_basis; }
/**@brief Return the origin vector translation */
SIMD_FORCE_INLINE btVector3& getOrigin() { return m_origin; }
/**@brief Return the origin vector translation */
SIMD_FORCE_INLINE const btVector3& getOrigin() const { return m_origin; }
/**@brief Return a quaternion representing the rotation */
btQuaternion getRotation() const {
btQuaternion q;
m_basis.getRotation(q);
return q;
}
/**@brief Set from an array
* @param m A pointer to a 16 element array (12 rotation(row major padded on the right by 1), and 3 translation */
void setFromOpenGLMatrix(const btScalar *m)
{
m_basis.setFromOpenGLSubMatrix(m);
m_origin.setValue(m[12],m[13],m[14]);
}
/**@brief Fill an array representation
* @param m A pointer to a 16 element array (12 rotation(row major padded on the right by 1), and 3 translation */
void getOpenGLMatrix(btScalar *m) const
{
m_basis.getOpenGLSubMatrix(m);
m[12] = m_origin.x();
m[13] = m_origin.y();
m[14] = m_origin.z();
m[15] = btScalar(1.0);
}
/**@brief Set the translational element
* @param origin The vector to set the translation to */
SIMD_FORCE_INLINE void setOrigin(const btVector3& origin)
{
m_origin = origin;
}
SIMD_FORCE_INLINE btVector3 invXform(const btVector3& inVec) const;
/**@brief Set the rotational element by btMatrix3x3 */
SIMD_FORCE_INLINE void setBasis(const btMatrix3x3& basis)
{
m_basis = basis;
}
/**@brief Set the rotational element by btQuaternion */
SIMD_FORCE_INLINE void setRotation(const btQuaternion& q)
{
m_basis.setRotation(q);
}
/**@brief Set this transformation to the identity */
void setIdentity()
{
m_basis.setIdentity();
m_origin.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
}
/**@brief Multiply this Transform by another(this = this * another)
* @param t The other transform */
btTransform& operator*=(const btTransform& t)
{
m_origin += m_basis * t.m_origin;
m_basis *= t.m_basis;
return *this;
}
/**@brief Return the inverse of this transform */
btTransform inverse() const
{
btMatrix3x3 inv = m_basis.transpose();
return btTransform(inv, inv * -m_origin);
}
/**@brief Return the inverse of this transform times the other transform
* @param t The other transform
* return this.inverse() * the other */
btTransform inverseTimes(const btTransform& t) const;
/**@brief Return the product of this transform and the other */
btTransform operator*(const btTransform& t) const;
/**@brief Return an identity transform */
static const btTransform& getIdentity()
{
static const btTransform identityTransform(btMatrix3x3::getIdentity());
return identityTransform;
}
void serialize(struct btTransformData& dataOut) const;
void serializeFloat(struct btTransformFloatData& dataOut) const;
void deSerialize(const struct btTransformData& dataIn);
void deSerializeDouble(const struct btTransformDoubleData& dataIn);
void deSerializeFloat(const struct btTransformFloatData& dataIn);
};
SIMD_FORCE_INLINE btVector3
btTransform::invXform(const btVector3& inVec) const
{
btVector3 v = inVec - m_origin;
return (m_basis.transpose() * v);
}
SIMD_FORCE_INLINE btTransform
btTransform::inverseTimes(const btTransform& t) const
{
btVector3 v = t.getOrigin() - m_origin;
return btTransform(m_basis.transposeTimes(t.m_basis),
v * m_basis);
}
SIMD_FORCE_INLINE btTransform
btTransform::operator*(const btTransform& t) const
{
return btTransform(m_basis * t.m_basis,
(*this)(t.m_origin));
}
/**@brief Test if two transforms have all elements equal */
SIMD_FORCE_INLINE bool operator==(const btTransform& t1, const btTransform& t2)
{
return ( t1.getBasis() == t2.getBasis() &&
t1.getOrigin() == t2.getOrigin() );
}
///for serialization
struct btTransformFloatData
{
btMatrix3x3FloatData m_basis;
btVector3FloatData m_origin;
};
struct btTransformDoubleData
{
btMatrix3x3DoubleData m_basis;
btVector3DoubleData m_origin;
};
SIMD_FORCE_INLINE void btTransform::serialize(btTransformData& dataOut) const
{
m_basis.serialize(dataOut.m_basis);
m_origin.serialize(dataOut.m_origin);
}
SIMD_FORCE_INLINE void btTransform::serializeFloat(btTransformFloatData& dataOut) const
{
m_basis.serializeFloat(dataOut.m_basis);
m_origin.serializeFloat(dataOut.m_origin);
}
SIMD_FORCE_INLINE void btTransform::deSerialize(const btTransformData& dataIn)
{
m_basis.deSerialize(dataIn.m_basis);
m_origin.deSerialize(dataIn.m_origin);
}
SIMD_FORCE_INLINE void btTransform::deSerializeFloat(const btTransformFloatData& dataIn)
{
m_basis.deSerializeFloat(dataIn.m_basis);
m_origin.deSerializeFloat(dataIn.m_origin);
}
SIMD_FORCE_INLINE void btTransform::deSerializeDouble(const btTransformDoubleData& dataIn)
{
m_basis.deSerializeDouble(dataIn.m_basis);
m_origin.deSerializeDouble(dataIn.m_origin);
}
#endif //BT_TRANSFORM_H
| 0 | 0.971469 | 1 | 0.971469 | game-dev | MEDIA | 0.969238 | game-dev | 0.893668 | 1 | 0.893668 |
sigp/lighthouse | 6,426 | beacon_node/http_api/src/block_rewards.rs | use beacon_chain::{BeaconChain, BeaconChainError, BeaconChainTypes, WhenSlotSkipped};
use eth2::lighthouse::{BlockReward, BlockRewardsQuery};
use lru::LruCache;
use state_processing::BlockReplayer;
use std::num::NonZeroUsize;
use std::sync::Arc;
use tracing::{debug, warn};
use types::beacon_block::BlindedBeaconBlock;
use types::non_zero_usize::new_non_zero_usize;
use warp_utils::reject::{beacon_state_error, custom_bad_request, unhandled_error};
const STATE_CACHE_SIZE: NonZeroUsize = new_non_zero_usize(2);
/// Fetch block rewards for blocks from the canonical chain.
pub fn get_block_rewards<T: BeaconChainTypes>(
query: BlockRewardsQuery,
chain: Arc<BeaconChain<T>>,
) -> Result<Vec<BlockReward>, warp::Rejection> {
let start_slot = query.start_slot;
let end_slot = query.end_slot;
let prior_slot = start_slot - 1;
if start_slot > end_slot || start_slot == 0 {
return Err(custom_bad_request(format!(
"invalid start and end: {}, {}",
start_slot, end_slot
)));
}
let end_block_root = chain
.block_root_at_slot(end_slot, WhenSlotSkipped::Prev)
.map_err(unhandled_error)?
.ok_or_else(|| custom_bad_request(format!("block at end slot {} unknown", end_slot)))?;
let blocks = chain
.store
.load_blocks_to_replay(start_slot, end_slot, end_block_root)
.map_err(|e| unhandled_error(BeaconChainError::from(e)))?;
let state_root = chain
.state_root_at_slot(prior_slot)
.map_err(unhandled_error)?
.ok_or_else(|| custom_bad_request(format!("prior state at slot {} unknown", prior_slot)))?;
// This branch is reached from the HTTP API. We assume the user wants
// to cache states so that future calls are faster.
let mut state = chain
.get_state(&state_root, Some(prior_slot), true)
.and_then(|maybe_state| maybe_state.ok_or(BeaconChainError::MissingBeaconState(state_root)))
.map_err(unhandled_error)?;
state
.build_caches(&chain.spec)
.map_err(beacon_state_error)?;
let mut reward_cache = Default::default();
let mut block_rewards = Vec::with_capacity(blocks.len());
let block_replayer = BlockReplayer::new(state, &chain.spec)
.pre_block_hook(Box::new(|state, block| {
state.build_all_committee_caches(&chain.spec)?;
// Compute block reward.
let block_reward = chain.compute_block_reward(
block.message(),
block.canonical_root(),
state,
&mut reward_cache,
query.include_attestations,
)?;
block_rewards.push(block_reward);
Ok(())
}))
.state_root_iter(
chain
.forwards_iter_state_roots_until(prior_slot, end_slot)
.map_err(unhandled_error)?,
)
.no_signature_verification()
.minimal_block_root_verification()
.apply_blocks(blocks, None)
.map_err(unhandled_error)?;
if block_replayer.state_root_miss() {
warn!(%start_slot, %end_slot, "Block reward state root miss");
}
drop(block_replayer);
Ok(block_rewards)
}
/// Compute block rewards for blocks passed in as input.
pub fn compute_block_rewards<T: BeaconChainTypes>(
blocks: Vec<BlindedBeaconBlock<T::EthSpec>>,
chain: Arc<BeaconChain<T>>,
) -> Result<Vec<BlockReward>, warp::Rejection> {
let mut block_rewards = Vec::with_capacity(blocks.len());
let mut state_cache = LruCache::new(STATE_CACHE_SIZE);
let mut reward_cache = Default::default();
for block in blocks {
let parent_root = block.parent_root();
// Check LRU cache for a constructed state from a previous iteration.
let state = if let Some(state) = state_cache.get(&(parent_root, block.slot())) {
debug!(
?parent_root,
slot = %block.slot(),
"Re-using cached state for block rewards"
);
state
} else {
debug!(
?parent_root,
slot = %block.slot(),
"Fetching state for block rewards"
);
let parent_block = chain
.get_blinded_block(&parent_root)
.map_err(unhandled_error)?
.ok_or_else(|| {
custom_bad_request(format!(
"parent block not known or not canonical: {:?}",
parent_root
))
})?;
// This branch is reached from the HTTP API. We assume the user wants
// to cache states so that future calls are faster.
let parent_state = chain
.get_state(&parent_block.state_root(), Some(parent_block.slot()), true)
.map_err(unhandled_error)?
.ok_or_else(|| {
custom_bad_request(format!(
"no state known for parent block: {:?}",
parent_root
))
})?;
let block_replayer = BlockReplayer::new(parent_state, &chain.spec)
.no_signature_verification()
.state_root_iter([Ok((parent_block.state_root(), parent_block.slot()))].into_iter())
.minimal_block_root_verification()
.apply_blocks(vec![], Some(block.slot()))
.map_err(unhandled_error::<BeaconChainError>)?;
if block_replayer.state_root_miss() {
warn!(
parent_slot = %parent_block.slot(),
slot = %block.slot(),
"Block reward state root miss"
);
}
let mut state = block_replayer.into_state();
state
.build_all_committee_caches(&chain.spec)
.map_err(beacon_state_error)?;
state_cache.get_or_insert((parent_root, block.slot()), || state)
};
// Compute block reward.
let block_reward = chain
.compute_block_reward(
block.to_ref(),
block.canonical_root(),
state,
&mut reward_cache,
true,
)
.map_err(unhandled_error)?;
block_rewards.push(block_reward);
}
Ok(block_rewards)
}
| 0 | 0.995537 | 1 | 0.995537 | game-dev | MEDIA | 0.413956 | game-dev | 0.990317 | 1 | 0.990317 |
Neroware/GodotRx | 3,080 | addons/reactivex/scheduler/threadedtimeoutscheduler.gd | extends PeriodicScheduler
class_name ThreadedTimeoutScheduler
## A scheduler that schedules work via a threaded timer.
func _init(verify_ = null):
if not verify_ == "GDRx":
push_warning("Warning! Must only instance Scheduler from GDRx singleton!")
## Returns singleton
static func singleton() -> ThreadedTimeoutScheduler:
return GDRx.ThreadedTimeoutScheduler_
## Schedules an action to be executed.
## [br]
## [b]Args:[/b]
## [br]
## [code]action[/code] Action to be executed.
## [br]
## [code]state[/code] [Optional] state to be given to the action function.
## [br][br]
## [b]Returns:[/b]
## [br]
## The disposable object used to cancel the scheduled action
## (best effort).
func schedule(action : Callable, state = null) -> DisposableBase:
var sad : SingleAssignmentDisposable = SingleAssignmentDisposable.new()
var interval = func():
sad.disposable = self.invoke_action(action, state)
var disposed = RefValue.Set(false)
var dispose = func():
disposed.v = true
var timer_thread = RefValue.Null()
var timer = func():
OS.delay_msec(0)
if not disposed.v:
interval.call()
GDRx.THREAD_MANAGER.finish(timer_thread.v)
timer_thread.v = GDRx.concur.default_thread_factory.call(timer)
timer_thread.v.start()
return CompositeDisposable.new([sad, Disposable.new(dispose)])
## Schedules an action to be executed after duetime.
## [br]
## [b]Args:[/b]
## [br]
## [code]duetime[/code] Relative time after which to execute the action.
## [br]
## [code]action[/code] Action to be executed.
## [br]
## [code]state[/code] [Optional] state to be given to the action function.
## [br][br]
##
## [b]Returns:[/b]
## [br]
## The disposable object used to cancel the scheduled action
## (best effort).
func schedule_relative(duetime, action : Callable, state = null) -> DisposableBase:
var seconds : float = duetime
if seconds <= 0.0:
return self.schedule(action, state)
var sad : SingleAssignmentDisposable = SingleAssignmentDisposable.new()
var interval = func():
sad.disposable = self.invoke_action(action, state)
var disposed = RefValue.Set(false)
var dispose = func():
disposed.v = true
var timer_thread = RefValue.Null()
var timer = func():
OS.delay_msec((1000.0 * seconds) as int)
if not disposed.v:
interval.call()
GDRx.THREAD_MANAGER.finish(timer_thread.v)
timer_thread.v = GDRx.concur.default_thread_factory.call(timer)
timer_thread.v.start()
return CompositeDisposable.new([sad, Disposable.new(dispose)])
## Schedules an action to be executed at duetime.
## [br]
## [b]Args:[/b]
## [br]
## [code]duetime[/code] Absolute time at which to execute the action.
## [br]
## [code]action[/code] Action to be executed.
## [br]
## [code]state[/code] [Optional] state to be given to the action function.
## [br][br]
##
## [b]Returns:[/b]
## [br]
## The disposable object used to cancel the scheduled action
## (best effort).
func schedule_absolute(duetime, action : Callable, state = null) -> DisposableBase:
return self.schedule_relative(duetime - self.now(), action, state)
| 0 | 0.701168 | 1 | 0.701168 | game-dev | MEDIA | 0.371351 | game-dev | 0.939912 | 1 | 0.939912 |
ss14Starlight/space-station-14 | 2,848 | Content.Client/UserInterface/Systems/Chat/Controls/ChannelFilterButton.cs | using System.Numerics;
using Content.Client.Resources;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface.Controls;
namespace Content.Client.UserInterface.Systems.Chat.Controls;
public sealed class ChannelFilterButton : ChatPopupButton<ChannelFilterPopup>
{
private static readonly Color ColorNormal = Color.FromHex("#7b7e9e");
private static readonly Color ColorHovered = Color.FromHex("#9699bb");
private static readonly Color ColorPressed = Color.FromHex("#789B8C");
private readonly TextureRect? _textureRect;
private readonly ChatUIController _chatUIController;
private const int FilterDropdownOffset = 120;
public ChannelFilterButton()
{
_chatUIController = UserInterfaceManager.GetUIController<ChatUIController>();
var filterTexture = IoCManager.Resolve<IResourceCache>()
.GetTexture("/Textures/Interface/Nano/filter.svg.96dpi.png");
AddChild(
(_textureRect = new TextureRect
{
Texture = filterTexture,
HorizontalAlignment = HAlignment.Center,
VerticalAlignment = VAlignment.Center
})
);
_chatUIController.FilterableChannelsChanged += Popup.SetChannels;
_chatUIController.UnreadMessageCountsUpdated += Popup.UpdateUnread;
Popup.SetChannels(_chatUIController.FilterableChannels);
}
protected override UIBox2 GetPopupPosition()
{
var globalPos = GlobalPosition;
var (minX, minY) = Popup.MinSize;
return UIBox2.FromDimensions(
globalPos - new Vector2(FilterDropdownOffset, 0),
new Vector2(Math.Max(minX, Popup.MinWidth), minY));
}
private void UpdateChildColors()
{
if (_textureRect == null) return;
switch (DrawMode)
{
case DrawModeEnum.Normal:
_textureRect.ModulateSelfOverride = ColorNormal;
break;
case DrawModeEnum.Pressed:
_textureRect.ModulateSelfOverride = ColorPressed;
break;
case DrawModeEnum.Hover:
_textureRect.ModulateSelfOverride = ColorHovered;
break;
case DrawModeEnum.Disabled:
break;
}
}
protected override void DrawModeChanged()
{
base.DrawModeChanged();
UpdateChildColors();
}
protected override void StylePropertiesChanged()
{
base.StylePropertiesChanged();
UpdateChildColors();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
return;
_chatUIController.FilterableChannelsChanged -= Popup.SetChannels;
_chatUIController.UnreadMessageCountsUpdated -= Popup.UpdateUnread;
}
}
| 0 | 0.973288 | 1 | 0.973288 | game-dev | MEDIA | 0.552567 | game-dev | 0.974063 | 1 | 0.974063 |
JohnEarnest/StoneSoup | 11,695 | Dungine/Readme.md | Dungeon Engine
==============
This game is a top-down tile based adventure game. It introduces 2D arrays and working with images in Processing, and can be extended to produce games in the vein of Chip's Challenge, Zelda or even a simple version of Pacman.
Tutorial
--------
Like every game we write in Processing, we will begin by defining `setup()` and `draw()` procedures. In `setup` we will initialize the size of our window.
void setup() {
size(640, 640);
}
void draw() {
// more here later.
}
For this program, we will be working with bitmapped images. Let's make an image of a player and display it onscreen. Save your program, draw a player image in your favorite graphics editor, and then save your image as a 64x64 PNG in a directory called `data`, inside the directory where your program is saved. Images you wish to use in your program will always reside in this `data` directory. To use images in our program, we must do three things.
Declare a (global) variable of type `PImage` for storing the image:
PImage player;
Somewhere during `setup()`, initialize the `PImage` by using `loadImage()`:
void setup() {
size(640, 640);
player = loadImage("player.png");
}
Somewhere during `draw()`, call `image()`, to draw a `PImage` to the screen:
void draw() {
background(0, 0, 0);
image(player, 100, 100);
}
In our game, we're going to use a grid of 64x64 images- "tiles"- to make up the world. Since we're going to use many different tiles to represent walls, doors, items and so on, let's use an array to load up our images, allowing us to reference them by a numeric index.
Begin by creating 64x64 graphics for a background texture, a floor texture, and a solid wall. As before, we'll declare variables to store our images and load the images before we can display them.
PImage[] tiles = new PImage[3];
void setup() {
tiles[0] = loadImage("background.png");
tiles[1] = loadImage("ground.png");
tiles[2] = loadImage("wall.png");
}
Since our window is 640x640 and our tiles are 64x64, we can fit a 10x10 grid of tiles on the screen at once. We can use another array to store a grid of tile indices to draw. First, declare your 10x10 grid as a literal:
int[][] grid = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 2, 2, 2, 2, 2, 2, 2, 0, 0 },
{ 0, 2, 1, 1, 1, 2, 1, 2, 2, 0 },
{ 0, 2, 1, 1, 1, 2, 1, 2, 2, 0 },
{ 0, 2, 1, 1, 1, 2, 1, 2, 2, 0 },
{ 0, 2, 1, 1, 1, 1, 1, 2, 0, 0 },
{ 0, 2, 2, 2, 2, 1, 2, 2, 0, 0 },
{ 0, 0, 0, 0, 2, 1, 2, 0, 0, 0 },
{ 0, 0, 0, 0, 2, 2, 2, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
Since we'd like this literal representation of the array to map directly to how things are oriented on the screen, the outer subscript of the array will represent the y-axis while the inner subscript will represent the x-axis. Make sure you don't mix this up later!
Now we want to use that array to draw appropriate tiles to the screen. We'll use a pair of nested loops to keep track of the x and y coordinates of the tile we wish to draw, look up an element of the grid array and then use the resulting value as an index into our array of tiles.
void draw() {
for(int y = 0; y < 10; y++) {
for(int x = 0; x < 10; x++) {
image(tiles[grid[y][x]], x * 64, y * 64);
}
}
}
Notice that we're multiplying x and y by 64 before we draw the image. This is because x and y represent a position counted in _tiles_, whereas `image()` takes coordinates counted in _pixels_. One tile is 64 pixels, so to convert units we just multiply. When you're working on this program, remember to consider the units that a value represents- _tiles_ or _pixels_?
The next step in making this into a game is to add a player we can control. The player should move in response to the cursor keys and it shouldn't be able to move through walls.
We'll need variables to keep track of the player's position (in _tiles_, since we want the player to move in discrete steps):
int px = 3;
int py = 2;
We'll need to load the image for the player, and since we'll store it as a tile we need to bump up the size of our tiles array:
void setup() {
// ...
tiles[3] = loadImage("player.png");
}
And naturally we'll need code in `draw()` to diplay the player after the grid is drawn:
void draw() {
// ...
image(tiles[3], px * 64, py * 64);
}
Next, getting the player to move. I'm going to write a procedure for moving the player to a particular position which I will call `move()`. We will provide a pair of coordinates for the player's new position, and this procedure will either update the player's position or, if these coordinates are impassible, leave the player's position unchanged. Based on our code so far, we know that a tile is impassible if it is part of the background (0) or a wall (2).
void move(int nx, int ny) {
int tile = grid[ny][nx];
if (tile == 0 || tile == 2) { return; }
// we now must be on a passable tile.
px = nx;
py = ny;
}
Making the player move in response to cursor keys is straightforward. We'll write a `keyReleased()` procedure and check `keyCode` to identify the cursor keys. When one is pressed, we'll call our `move()` procedure with an appropriate new position based on the player's current position.
void keyReleased() {
if (keyCode == UP ) { move(px , py - 1); }
if (keyCode == DOWN ) { move(px , py + 1); }
if (keyCode == LEFT ) { move(px - 1, py ); }
if (keyCode == RIGHT) { move(px + 1, py ); }
}
The player should be able to move around, but should not be able to move through walls. Let's extend the functionality we developed so that we can have items to pick up. I'd like to add some precious gems that can be collected when the player walks over them.
As before, we need to load a new graphic for the gems, which will be represented by tile 4. We can place gems by simply modifying the numbers in `grid`. To keep track of how many gems the player has picked up, we'll need a variable:
int gems = 0;
And we can use the `text()` procedure in `draw()` to display a gem counter onscreen:
void draw() {
// ...
text("gems: " + gems, 10, 10);
}
To allow the player to pick the gems up, we'll extend `move()`. When the player successfully moves onto a location which has tile 4 we should add one to `gems` and then change the tile the player is standing on to ground (1), making the gem disappear.
void move(int nx, int ny) {
int tile = grid[ny][nx];
if (tile == 0 || tile == 2) { return; }
px = nx;
py = ny;
if (grid[py][px] == 4) {
gems += 1;
grid[py][px] = 1;
}
}
Now that we can collect gems, it makes sense to add a simple puzzle element which relies on them. I'll add a tile which represents a door (tile 5) which is impassible unless you have 3 or more gems. When you walk onto the door tile with enough gems, it takes 3 away and disappears. Once you've added the appropriate door tile to the game, we just have to make some small additions to `move()`.
Before we update the player's position, we check if they're trying to move onto a door without enough gems and bail out if that's the case:
if (tile == 5 && gems < 3) { return; }
If we manage to update the player's position, we can then take away the gems and change the tile into normal ground:
if (grid[py][px] == 5) {
gems -= 3;
grid[py][px] = 1;
}
Success! We have a tile grid, a player, collision and objects in the world which can be interacted with by walking on them.
Future Directions
-----------------
One of the first things many students wish to add to their game is multiple levels. To begin, we need to add a degree of indirection to `grid`. Rather than directly initializing `grid` with the map, make several named arrays with levels and point `grid` to one of them:
int[][] level1 = {
// ...
};
int[][] level2 = {
// ...
};
int[][] grid = level1;
Now we can determine what level we're on by comparing grid with one of those other arrays using `==` and we can redirect grid to a different level by reassigning it. Imagine we wanted to make it so that standing on tile type 7 while on level 1 teleports us to tile (3, 5) on level 2. We could add the following logic to `move()` before repositioning the player:
if (tile == 7 && grid == level1) {
grid = level2;
px = 3;
py = 5;
return;
}
The `return` ensures that after changing the level no other teleporters are activated and the player position is not changed afterwards. In this example we made any tile 7 work as a teleporter but if we have several which go to different locations we might check the player's position rather than the tile the player is standing on.
You could also change levels when the player walks off the edge of one board, creating the appearance that the player has walked onto the new level from the opposite edge:
if (py < 0 && grid == level1) {
grid = level2;
py = 9;
return;
}
It's important to do this type of check _before_ you look up the current tile, since the new player coordinates will be outside the bounds of the `grid` array.
If you wanted to create a more linear series of levels with less repeated logic, you could instead create a variable to keep track of the level index and make `grid` a three dimensional array, where the outermost index of the array is used to select the current level. In this case you could easily write logic for tile types that send the player to the next or previous level by adding to or subtracting from the level index. Try it!
Another addition many students ask about is some type of mobile game entity, like an enemy that chases the player or obstacles that move. Adding a combat system is beyond the scope of this tutorial, but let's add a bothersome blob which follows the character around. We'll need to load the blob's image, keep track of its position and we will need an additional variable which will be used to regulate the speed of the blob's movement:
PImage blob;
int timer = 0;
int bx = 6;
int by = 2;
In a direct parallel to how we defined `move()` for the player's movement, we'll define a `moveBlob()` procedure for the blob. `moveBlob` will be much simpler than `move()` because the blob doesn't need to be able to open doors or pick up gems:
void moveBlob(int nx, int ny) {
int tile = grid[ny][nx];
if (tile == 0 || tile == 2 || tile == 5) { return; }
bx = nx;
by = ny;
}
Note that since we have separate code defining tiles which are "solid" to the player and the blob, we might create tiles which act differently for them. This is a simple idea that can be the basis of interesting puzzles. (Or bugs, if done accidentally!)
In `draw`, add some logic to draw the blob on the screen and increment `timer`. If the timer is high enough, move the blob once and reset the timer. By adjusting the timer cutoff you can alter the speed at which the blob appears to move.
void draw() {
// ...
image(blob, bx * 64, by * 64);
timer++;
if (timer >= 50) {
timer = 0;
if (px > bx) { moveBlob(bx + 1, by ); }
else if (px < bx) { moveBlob(bx - 1, by ); }
else if (py > by) { moveBlob(bx , by + 1); }
else if (py < by) { moveBlob(bx , by - 1); }
}
}
The chain of `if...else if...` statements determines the correct direction in which to move the blob at each step. We use `else if` because we only wish to have the blob move _once_, orthogonally, per "turn". As an alternative to this timer-based approach, you could place the logic that calls `moveBlob()` in the player's `move()` method where it is triggered when the player moves rather than in `draw()` where it is triggered 60 times per second- the former may be more appropriate for turn-based puzzle games. | 0 | 0.857268 | 1 | 0.857268 | game-dev | MEDIA | 0.57394 | game-dev,graphics-rendering | 0.710994 | 1 | 0.710994 |
MelonModding/MelonUtilities | 3,532 | src/main/java/MelonUtilities/command/commands/CrewCommandOld.djava | package MelonUtilities.command.crew;
import MelonUtilities.utility.syntax.SyntaxBuilder;
import net.minecraft.core.net.command.Command;
import net.minecraft.core.net.command.CommandHandler;
import net.minecraft.core.net.command.CommandSource;
import net.minecraft.core.net.command.TextFormatting;
public class CrewCommandOld extends Command {
public static SyntaxBuilder syntax = new SyntaxBuilder();
private final static String COMMAND = "crew";
public CrewCommandOld(){super(COMMAND, "c");}
public static void buildRoleSyntax(){
syntax.clear();
syntax.append("title", TextFormatting.LIGHT_GRAY + "< Command Syntax >");
syntax.append("create", "title", TextFormatting.LIGHT_GRAY + " > /crew create <crew name>");
syntax.append("delete", "title", TextFormatting.LIGHT_GRAY + " > /crew delete <crew name>");
syntax.append("invite", "title", TextFormatting.LIGHT_GRAY + " > /crew invite <username>");
syntax.append("kick", "title", TextFormatting.LIGHT_GRAY + " > /crew kick <username>");
syntax.append("tag", "title", TextFormatting.LIGHT_GRAY + " > /crew tag <mode>");
syntax.append("tagView", "tag", TextFormatting.LIGHT_GRAY + " > view");
syntax.append("tagVisible", "tag", TextFormatting.LIGHT_GRAY + " > visible true/false");
syntax.append("tagEdit", "tag", TextFormatting.LIGHT_GRAY + " > edit <mode>");
syntax.append("tagEditDisplay", "tagEdit", TextFormatting.LIGHT_GRAY + " > display <mode>");
syntax.append("tagEditDisplayName", "tagEditDisplay", TextFormatting.LIGHT_GRAY + " > name <display name>");
syntax.append("tagEditDisplayColor", "tagEditDisplay", TextFormatting.LIGHT_GRAY + " > color <color/hex>");
syntax.append("tagEditDisplayUnderline", "tagEditDisplay", TextFormatting.LIGHT_GRAY + " > underline true/false");
syntax.append("tagEditDisplayBold", "tagEditDisplay", TextFormatting.LIGHT_GRAY + " > bold true/false");
syntax.append("tagEditDisplayItalics", "tagEditDisplay", TextFormatting.LIGHT_GRAY + " > italics true/false");
syntax.append("tagEditBorder", "tagEdit", TextFormatting.LIGHT_GRAY + " > border <mode>");
syntax.append("tagEditBorderColor", "tagEditBorder", TextFormatting.LIGHT_GRAY + " > color <color/hex>");
syntax.append("tagEditBorderType", "tagEditBorder", TextFormatting.LIGHT_GRAY + " > none/bracket/caret/curly");
syntax.append("tagEditBorderCustom", "tagEditBorder", TextFormatting.LIGHT_GRAY + " > custom [<affix>]");
syntax.append("tagEditBorderCustomAffix", "tagEditBorderCustom", TextFormatting.LIGHT_GRAY + " > prefix/suffix <custom affix>");
syntax.append("etc", TextFormatting.LIGHT_GRAY + " etc.");
}
@Override
public boolean execute(CommandHandler commandHandler, CommandSource commandSource, String[] strings) {
return false;
}
@Override
public boolean opRequired(String[] strings) {
return false;
}
@Override
public void sendCommandSyntax(CommandHandler commandHandler, CommandSource commandSource) {
}
}
| 0 | 0.775912 | 1 | 0.775912 | game-dev | MEDIA | 0.342085 | game-dev | 0.831337 | 1 | 0.831337 |
1176892094/Astraia | 8,129 | Assets/Astraia/Runtime/04.网络库/08.网络组件/NetworkObserver.cs | // // *********************************************************************************
// // # Project: Astraia
// // # Unity: 6000.3.5f1
// // # Author: 云谷千羽
// // # Version: 1.0.0
// // # History: 2025-09-27 21:09:40
// // # Recently: 2025-09-27 21:09:40
// // # Copyright: 2024, 云谷千羽
// // # Description: This is an automatically generated comment.
// // *********************************************************************************
using System;
using System.Collections.Generic;
using Astraia.Common;
using UnityEngine;
namespace Astraia.Net
{
public class NetworkObserver : MonoBehaviour, IEvent<ServerDisconnect>, IEvent<ServerObserver>
{
private readonly Dictionary<int, NetworkEntity> players = new Dictionary<int, NetworkEntity>();
private readonly HashSet<int> clients = new HashSet<int>();
private readonly List<int> copies = new List<int>();
private GameObject pool;
private Grid<int> grids;
private double waitTime;
[SerializeField] private Vector2Int gridCell = new Vector2Int(5, 3);
[SerializeField] private Vector2Int gridSize = new Vector2Int(15, 15);
[SerializeField] private float interval = 0.5f;
private void Awake()
{
grids = new Grid<int>(1024, gridCell);
NetworkManager.Server.observer = this;
}
private void OnEnable()
{
EventManager.Listen<ServerObserver>(this);
EventManager.Listen<ServerDisconnect>(this);
}
private void OnDisable()
{
EventManager.Remove<ServerObserver>(this);
EventManager.Remove<ServerDisconnect>(this);
}
public void Execute(ServerDisconnect message)
{
players.Remove(message.client);
}
public void Execute(ServerObserver message)
{
players[message.entity.client] = message.entity;
}
private void Update()
{
if (NetworkManager.isServer)
{
grids.Clear();
foreach (var client in NetworkManager.Server.clients.Values)
{
if (players.TryGetValue(client, out var player) && player)
{
grids.Add(EntityToGrid(player.transform.position), client);
}
}
if (waitTime + interval <= Time.unscaledTimeAsDouble)
{
foreach (var entity in NetworkManager.Server.spawns.Values)
{
if (entity.visible != Visible.Show)
{
Rebuild(entity, false);
}
}
waitTime = Time.unscaledTimeAsDouble;
}
}
}
private Vector2Int EntityToGrid(Vector3 position)
{
var x = Mathf.Max(1, gridSize.x / 2);
var y = Mathf.Max(1, gridSize.y / 2);
return new Vector2Int(Mathf.FloorToInt(position.x / x), Mathf.FloorToInt(position.y / y));
}
public void Rebuild(NetworkEntity entity, bool reload)
{
clients.Clear();
if (entity.visible != Visible.Hide)
{
grids.Set(EntityToGrid(entity.transform.position), clients);
}
if (entity.client != null)
{
clients.Add(entity.client);
}
var queries = NetworkSpawner.Query(entity);
foreach (NetworkClient client in clients)
{
if (client.isReady && (reload || !queries.Contains(client)))
{
NetworkSpawner.Spawn(entity, client);
}
}
copies.Clear();
foreach (var client in queries)
{
copies.Add(client);
}
foreach (NetworkClient client in copies)
{
if (!clients.Contains(client))
{
NetworkSpawner.Despawn(entity, client);
client.Send(new DespawnMessage(entity.objectId));
}
}
entity.gameObject.SetActive(clients.Count > 0);
}
public bool OnExecute(NetworkEntity entity, NetworkClient client)
{
var entityGrid = EntityToGrid(entity.transform.position);
if (players.TryGetValue(client, out var player) && player)
{
var playerGrid = entityGrid - EntityToGrid(player.transform.position);
return Mathf.Abs(playerGrid.x) <= 1 && Mathf.Abs(playerGrid.y) <= 1;
}
return false;
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
var x = Mathf.Max(1, gridSize.x / 2);
var y = Mathf.Max(1, gridSize.y / 2);
foreach (var player in players.Values)
{
if (player)
{
var target = player.transform.position;
var source = EntityToGrid(target);
var origin = new Vector3(source.x * x, source.y * y, target.z);
var center = origin + new Vector3(x / 2f, y / 2f, 0f);
Gizmos.color = Color.cyan;
for (var dx = 0; dx < gridCell.x; dx++)
{
for (var dy = 0; dy < gridCell.y; dy++)
{
var posX = Mathf.RoundToInt(dx - (gridCell.x - 1) / 2f);
var posY = Mathf.RoundToInt(dy - (gridCell.y - 1) / 2f);
var nb = new Vector2Int(source.x + posX, source.y + posY);
var nbOrigin = new Vector3(nb.x * x, nb.y * y, target.z);
var nbCenter = nbOrigin + new Vector3(x / 2f, y / 2f, 0f);
Gizmos.DrawWireCube(nbCenter, new Vector3(x, y, 0));
}
}
Gizmos.color = Color.green;
Gizmos.DrawWireCube(center, new Vector3(x, y, 0));
}
}
}
#endif
[Serializable]
private struct Grid<T>
{
private readonly Dictionary<Vector2Int, ICollection<T>> grids;
private readonly Vector2Int[] direction;
public Grid(int capacity, Vector2Int size)
{
direction = new Vector2Int[size.x * size.y];
for (var x = 0; x < size.x; x++)
{
for (var y = 0; y < size.y; y++)
{
var posX = Mathf.RoundToInt(x - (size.x - 1) / 2f);
var posY = Mathf.RoundToInt(y - (size.y - 1) / 2f);
direction[y * size.x + x] = new Vector2Int(posX, posY);
}
}
grids = new Dictionary<Vector2Int, ICollection<T>>(capacity);
}
public void Add(Vector2Int position, T value)
{
if (!grids.TryGetValue(position, out var items))
{
items = new HashSet<T>(128);
grids[position] = items;
}
items.Add(value);
}
public void Set(Vector2Int position, ICollection<T> result)
{
result.Clear();
foreach (var offset in direction)
{
if (grids.TryGetValue(position + offset, out var items))
{
foreach (var item in items)
{
result.Add(item);
}
}
}
}
public void Clear()
{
foreach (var items in grids.Values)
{
items.Clear();
}
}
}
}
} | 0 | 0.894977 | 1 | 0.894977 | game-dev | MEDIA | 0.468318 | game-dev,networking | 0.976463 | 1 | 0.976463 |
Justin-sky/Nice-Lua | 5,784 | Assets/EasyTouchBundle/EasyTouch/Plugins/Components/QuickDrag.cs | /***********************************************
EasyTouch V
Copyright © 2014-2015 The Hedgehog Team
http://www.thehedgehogteam.com/Forum/
The.Hedgehog.Team@gmail.com
**********************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using HedgehogTeam.EasyTouch;
namespace HedgehogTeam.EasyTouch{
[AddComponentMenu("EasyTouch/Quick Drag")]
public class QuickDrag: QuickBase {
#region Events
[System.Serializable] public class OnDragStart : UnityEvent<Gesture>{}
[System.Serializable] public class OnDrag : UnityEvent<Gesture>{}
[System.Serializable] public class OnDragEnd : UnityEvent<Gesture>{}
[SerializeField]
public OnDragStart onDragStart;
[SerializeField]
public OnDrag onDrag;
[SerializeField]
public OnDragEnd onDragEnd;
#endregion
#region Members
public bool isStopOncollisionEnter = false;
private Vector3 deltaPosition;
private bool isOnDrag = false;
private Gesture lastGesture;
#endregion
#region Monobehaviour CallBack
public QuickDrag(){
quickActionName = "QuickDrag"+ System.Guid.NewGuid().ToString().Substring(0,7);
axesAction = AffectedAxesAction.XY;
}
public override void OnEnable(){
base.OnEnable();
EasyTouch.On_TouchStart += On_TouchStart;
EasyTouch.On_TouchDown += On_TouchDown;
EasyTouch.On_TouchUp += On_TouchUp;
EasyTouch.On_Drag += On_Drag;
EasyTouch.On_DragStart += On_DragStart;
EasyTouch.On_DragEnd += On_DragEnd;
}
public override void OnDisable(){
base.OnDisable();
UnsubscribeEvent();
}
void OnDestroy(){
UnsubscribeEvent();
}
void UnsubscribeEvent(){
EasyTouch.On_TouchStart -= On_TouchStart;
EasyTouch.On_TouchDown -= On_TouchDown;
EasyTouch.On_TouchUp -= On_TouchUp;
EasyTouch.On_Drag -= On_Drag;
EasyTouch.On_DragStart -= On_DragStart;
EasyTouch.On_DragEnd -= On_DragEnd;
}
void OnCollisionEnter(){
if (isStopOncollisionEnter && isOnDrag){
StopDrag();
}
}
#endregion
#region EasyTouch Event
void On_TouchStart (Gesture gesture){
if ( realType == GameObjectType.UI){
if (gesture.isOverGui ){
if ((gesture.pickedUIElement == gameObject || gesture.pickedUIElement.transform.IsChildOf( transform)) && fingerIndex==-1){
fingerIndex = gesture.fingerIndex;
transform.SetAsLastSibling();
onDragStart.Invoke(gesture);
isOnDrag = true;
}
}
}
}
void On_TouchDown (Gesture gesture){
if (isOnDrag && fingerIndex == gesture.fingerIndex && realType == GameObjectType.UI){
if (gesture.isOverGui ){
if ((gesture.pickedUIElement == gameObject || gesture.pickedUIElement.transform.IsChildOf( transform)) ){
transform.position += (Vector3)gesture.deltaPosition;
if (gesture.deltaPosition != Vector2.zero){
onDrag.Invoke(gesture);
}
lastGesture = gesture;
}
}
}
}
void On_TouchUp (Gesture gesture){
if (fingerIndex == gesture.fingerIndex && realType == GameObjectType.UI){
lastGesture = gesture;
StopDrag();
}
}
// At the drag beginning
void On_DragStart( Gesture gesture){
if (realType != GameObjectType.UI){
if ((!enablePickOverUI && gesture.pickedUIElement == null) || enablePickOverUI){
if (gesture.pickedObject == gameObject && !isOnDrag){
isOnDrag = true;
fingerIndex = gesture.fingerIndex;
// the world coordinate from touch
Vector3 position = gesture.GetTouchToWorldPoint(gesture.pickedObject.transform.position);
deltaPosition = position - transform.position;
//
if (resetPhysic){
if (cachedRigidBody){
cachedRigidBody.isKinematic = true;
}
if (cachedRigidBody2D){
cachedRigidBody2D.isKinematic = true;
}
}
onDragStart.Invoke(gesture);
}
}
}
}
// During the drag
void On_Drag(Gesture gesture){
if (fingerIndex == gesture.fingerIndex){
if (realType == GameObjectType.Obj_2D || realType == GameObjectType.Obj_3D){
// Verification that the action on the object
if (gesture.pickedObject == gameObject && fingerIndex == gesture.fingerIndex){
// the world coordinate from touch
Vector3 position = gesture.GetTouchToWorldPoint(gesture.pickedObject.transform.position)-deltaPosition;
transform.position = GetPositionAxes( position);
if (gesture.deltaPosition != Vector2.zero){
onDrag.Invoke(gesture);
}
lastGesture = gesture;
}
}
}
}
// End of drag
void On_DragEnd(Gesture gesture){
if (fingerIndex == gesture.fingerIndex){
lastGesture = gesture;
StopDrag();
}
}
#endregion
#region Private Method
private Vector3 GetPositionAxes(Vector3 position){
Vector3 axes = position;
switch (axesAction){
case AffectedAxesAction.X:
axes = new Vector3(position.x,transform.position.y,transform.position.z);
break;
case AffectedAxesAction.Y:
axes = new Vector3(transform.position.x,position.y,transform.position.z);
break;
case AffectedAxesAction.Z:
axes = new Vector3(transform.position.x,transform.position.y,position.z);
break;
case AffectedAxesAction.XY:
axes = new Vector3(position.x,position.y,transform.position.z);
break;
case AffectedAxesAction.XZ:
axes = new Vector3(position.x,transform.position.y,position.z);
break;
case AffectedAxesAction.YZ:
axes = new Vector3(transform.position.x,position.y,position.z);
break;
}
return axes;
}
#endregion
#region Public Method
public void StopDrag(){
fingerIndex = -1;
if (resetPhysic){
if (cachedRigidBody){
cachedRigidBody.isKinematic = isKinematic;
}
if (cachedRigidBody2D){
cachedRigidBody2D.isKinematic = isKinematic2D;
}
}
isOnDrag = false;
onDragEnd.Invoke(lastGesture);
}
#endregion
}
} | 0 | 0.88471 | 1 | 0.88471 | game-dev | MEDIA | 0.867718 | game-dev | 0.900644 | 1 | 0.900644 |
RealityStop/Bolt.Addons.Community | 10,095 | Editor/Code/Generators/Nodes/Variables/GetMachineVariableGenerator.cs | using System;
using System.Linq;
using Unity.VisualScripting;
using Unity.VisualScripting.Community;
using Unity.VisualScripting.Community.Libraries.CSharp;
using Unity.VisualScripting.Community.Libraries.Humility;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
#if VISUAL_SCRIPTING_1_7
using SMachine = Unity.VisualScripting.ScriptMachine;
#else
using SMachine = Unity.VisualScripting.FlowMachine;
#endif
namespace Unity.VisualScripting.Community
{
[NodeGenerator(typeof(GetMachineVariableNode))]
public class GetMachineVariableNodeGenerator : LocalVariableGenerator
{
private GetMachineVariableNode Unit => unit as GetMachineVariableNode;
public GetMachineVariableNodeGenerator(Unit unit) : base(unit)
{
}
public override string GenerateValue(ValueOutput output, ControlGenerationData data)
{
if (Unit.name.hasValidConnection)
{
return MakeClickableForThisUnit(CodeUtility.ErrorTooltip("Name can not have a connected value!", "Error Generating GetMachineVariableNode", "null".ConstructHighlight()));
}
else
{
return GenerateDisconnectedVariableCode(data);
}
}
private string GenerateDisconnectedVariableCode(ControlGenerationData data)
{
var name = (Unit.defaultValues[Unit.name.key] as string).LegalMemberName();
variableType = GetVariableType(name, data, true);
data.CreateSymbol(Unit, variableType);
var expectedType = data.GetExpectedType();
var hasExpectedType = expectedType != null;
#if VISUAL_SCRIPTING_1_7
var isExpectedType =
(hasExpectedType && variableType != null && expectedType.IsAssignableFrom(variableType)) ||
(hasExpectedType && IsVariableDefined(data, name) && !string.IsNullOrEmpty(GetVariableDeclaration(data, name).typeHandle.Identification) && expectedType.IsAssignableFrom(Type.GetType(GetVariableDeclaration(data, name).typeHandle.Identification))) ||
(hasExpectedType && data.TryGetVariableType(data.GetVariableName(name), out Type targetType) && expectedType.IsAssignableFrom(targetType));
#else
var isExpectedType =
(hasExpectedType && variableType != null && expectedType.IsAssignableFrom(variableType)) ||
(hasExpectedType && IsVariableDefined(data, name) && expectedType.IsAssignableFrom(GetVariableDeclaration(data, name).value?.GetType())) ||
(hasExpectedType && data.TryGetVariableType(data.GetVariableName(name), out Type targetType) && expectedType.IsAssignableFrom(targetType));
#endif
data.SetCurrentExpectedTypeMet(isExpectedType, variableType);
if (!Unit.target.hasValidConnection && Unit.defaultValues[Unit.target.key] == null)
{
if (!data.ContainsNameInAnyScope(name))
return MakeClickableForThisUnit(CodeUtility.ErrorTooltip($"Variable '{name}' could not be found in this script ensure it's defined in the Graph Variables.", "Error Generating GetMachineVariableNode", ""));
return MakeClickableForThisUnit(data.GetVariableName(name).VariableHighlight());
}
else
return GenerateValue(Unit.target, data) + MakeClickableForThisUnit(".") + GenerateValue(Unit.name, data);
}
private Type GetVariableType(string name, ControlGenerationData data, bool checkDecleration)
{
if (checkDecleration)
{
var isDefined = IsVariableDefined(data, name);
if (isDefined)
{
var declaration = GetVariableDeclaration(data, name);
#if VISUAL_SCRIPTING_1_7
return declaration?.typeHandle.Identification != null
? Type.GetType(declaration.typeHandle.Identification)
: null;
#else
return declaration?.value != null
? declaration.value.GetType()
: null;
#endif
}
}
var target = GetTarget(data);
ControlGenerationData targetData = null;
if (target != null && CodeGenerator.GetSingleDecorator(GetTarget(data).gameObject) is ICreateGenerationData generationData)
{
targetData = generationData.GetGenerationData();
}
Type targetType = null;
return targetData?.TryGetVariableType(targetData?.GetVariableName(name), out targetType) ?? false ? targetType : data.GetExpectedType() ?? typeof(object);
}
private bool IsVariableDefined(ControlGenerationData data, string name)
{
var target = GetTarget(data);
return target != null && VisualScripting.Variables.Graph(target.GetReference()).IsDefined(name);
}
private VariableDeclaration GetVariableDeclaration(ControlGenerationData data, string name)
{
var target = GetTarget(data);
if (target != null)
{
return VisualScripting.Variables.Graph(target.GetReference()).GetDeclaration(name);
}
return null;
}
private SMachine GetTarget(ControlGenerationData data)
{
if (!Unit.target.hasValidConnection && Unit.defaultValues[Unit.target.key] == null && data.TryGetGraphPointer(out var graphPointer))
{
var reference = graphPointer.AsReference();
return reference.rootObject is SMachine scriptMachine ? scriptMachine : null;
}
else if (!Unit.target.hasValidConnection && Unit.defaultValues[Unit.target.key] != null)
{
return Unit.defaultValues[Unit.target.key].ConvertTo<SMachine>();
}
else
{
if (data.TryGetGraphPointer(out var _graphPointer))
{
if (Unit.target.hasValidConnection && CanPredictConnection(Unit.target, data))
{
try
{
return Flow.Predict<SMachine>(Unit.target.GetPesudoSource(), _graphPointer.AsReference());
}
catch (InvalidOperationException ex)
{
Debug.LogError(ex);
return null; // Don't break code view so just log the error and return null.
}
}
else
{
return null;
}
}
return null;
}
}
public override string GenerateValue(ValueInput input, ControlGenerationData data)
{
if (input == Unit.target && !input.hasValidConnection && Unit.defaultValues[input.key] == null)
{
return "";
}
if (input == Unit.target)
{
if (!input.hasValidConnection)
{
var machine = Unit.defaultValues[Unit.target.key] as SMachine;
var machineName = GetMachineName(machine);
data.TryGetGameObject(out var gameObject);
if (machine.gameObject.GetComponents<MonoBehaviour>().Any(m => m.GetType().Name == machineName))
return (gameObject != machine.gameObject ? machine.gameObject.As().Code(false, Unit) + MakeClickableForThisUnit(".") : "") + MakeClickableForThisUnit($"GetComponent<{machineName.TypeHighlight()}>()");
else
return MakeClickableForThisUnit(CodeUtility.InfoTooltip($"{machineName} could not be found on the target GameObject. Ensure that the ScriptMachine is compiled into a C# script and attached to the correct GameObject.",
(gameObject != machine.gameObject ? machine.gameObject.As().Code(false) + "." : "") + $"GetComponent<{machineName.TypeHighlight()}>()"));
}
var target = GetTarget(data);
if (target != null)
{
var machineName = GetMachineName(target);
data.TryGetGameObject(out var gameObject);
if (target.gameObject.GetComponents<MonoBehaviour>().Any(m => m.GetType().Name == machineName))
return (gameObject != target.gameObject ? target.gameObject.As().Code(false, Unit) + MakeClickableForThisUnit(".") : "") + MakeClickableForThisUnit($"GetComponent<{machineName.TypeHighlight()}>()");
else
return MakeClickableForThisUnit(CodeUtility.InfoTooltip($"{machineName} could not be found on the target GameObject. Ensure that the ScriptMachine is compiled into a C# script and attached to the correct GameObject.",
(gameObject != target.gameObject ? target.gameObject.As().Code(false) + "." : "") + $"GetComponent<{machineName.TypeHighlight()}>()"));
}
return MakeClickableForThisUnit($"/* Could not find target for variable {CodeUtility.CleanCode(GenerateValue(Unit.name, data)).RemoveHighlights().RemoveMarkdown()} */".WarningHighlight());
}
if (input == Unit.name && !input.hasValidConnection)
{
return MakeClickableForThisUnit(Unit.defaultValues[input.key].ToString().VariableHighlight());
}
return base.GenerateValue(input, data);
}
private string GetMachineName(SMachine machine)
{
return !string.IsNullOrEmpty(machine.nest?.graph.title)
? machine.nest.graph.title.LegalMemberName()
: machine.gameObject.name.Capitalize().First().Letter() + $"_{typeof(SMachine).Name}_" + Array.IndexOf(machine.gameObject.GetComponents<SMachine>(), machine);
}
}
} | 0 | 0.814179 | 1 | 0.814179 | game-dev | MEDIA | 0.869602 | game-dev | 0.844125 | 1 | 0.844125 |
akhuting/gms083 | 4,556 | src/main/resources/scripts/quest/21010.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : kevintjuh93
*/
importPackage(Packages.client);
var status = -1;
function start(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 15 && mode == 0) {
qm.sendNext("Oh, no need to decline my offer. It's no big deal. It's just a potion. Well, let me know if you change your mind.");
qm.dispose();
return;
}
//status -= 2;
}
if (status == 0) {
qm.sendNext("Hm, what's a human doing on this island? Wait, it's #p1201000#. What are you doing here, #p1201000#? And who's that beside you? Is it someone you know, #p1201000#? What? The hero, you say?");
} else if (status == 1) {
qm.sendNextPrev(" #i4001170#");//gms like
} else if (status == 2) {
qm.sendNextPrev("Ah, this must be the hero you and your clan have been waiting for. Am I right, #p1201000#? Ah, I knew you weren't just accompanying an average passerby...");
} else if (status == 3) {
qm.sendAcceptDecline("Oh, but it seems our hero has become very weak since the Black Mage's curse. It's only makes sense, considering that the hero has been asleep for hundreds of years. #bHere, I'll give you a HP Recovery Potion.#k");//nexon probably forgot to remove the '.' before '#k', lol
} else if (status == 4) {
if (qm.getPlayer().getHp() >= 50) {
qm.getPlayer().updateHp(25);
}
if (!qm.isQuestStarted(21010) && !qm.isQuestCompleted(21010)) {
qm.gainItem(2000022, 1);
qm.forceStartQuest();
}
qm.sendNext("Drink it first. Then we'll talk.", 9);
} else if (status == 5) {
qm.sendNextPrev("#b(How do I drink the potion? I don't remember..)", 3);
} else if (status == 6) {
qm.guideHint(14);
qm.dispose();
}
}
function end(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 1 && mode == 0)
qm.dispose();
else{
qm.dispose();
return;
}
}
if (status == 0) {
if (qm.c.getPlayer().getHp() < 50) {
qm.sendNext("You have't drank the potion yet.");
qm.dispose();
} else {
qm.sendNext("We've been digging and digging inside the Ice Cave in the hope of finding a hero, but I never thought I'd actually see the day... The prophecy was true! You were right, #p1201000#! Now that one of the legendary heroes has returned, we have no reason to fear the Black Mage!");
}
} else if (status == 1) {
qm.sendOk("Oh, I've kept you too long. I'm sorry, I got a little carried away. I'm sure the other Penguins feel the same way. I know you're busy, but could you #bstop and talk to the other Penguins#k on your way to town? They would be so honored.\r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0# \r\n#i2000022# 5 #t2000022#\r\n#i2000023# 5 #t2000023#\r\n\r\n#fUI/UIWindow.img/QuestIcon/8/0# 16 exp");
} else if (status == 2) {
if(qm.isQuestStarted(21010) && !qm.isQuestCompleted(21010)) {
qm.gainExp(16);
qm.gainItem(2000022, 3);
qm.gainItem(2000023, 3);
qm.forceCompleteQuest();
}
qm.sendNext("Oh, you've leveled up! You may have even received some skill points. In Maple World, you can acquire 3 skill points every time you level up. Press the #bK key #kto view the Skill window.", 9);
} else if (status == 3) {
qm.sendNextPrev("#b(Everyone's been so nice to me, but I just can't remember anything. Am I really a hero? I should check my skills and see. But how do I check them?)", 3);
} else if (status == 4) {
qm.guideHint(15);
qm.dispose();
}
}
| 0 | 0.813814 | 1 | 0.813814 | game-dev | MEDIA | 0.970844 | game-dev | 0.949764 | 1 | 0.949764 |
mintlu8/bevy_rectray | 8,237 | src/pipeline.rs | use std::mem;
use bevy::ecs::hierarchy::Children;
use bevy::transform::components::Transform;
use bevy::{
ecs::{
change_detection::DetectChanges,
entity::Entity,
system::{Local, Query, Res},
world::Ref,
},
math::{Quat, StableInterpolate},
time::{Time, Virtual},
};
use crate::OutOfFrameBehavior;
use crate::{
hierarchy::RectrayFrame,
layout::{Container, LayoutControl, LayoutInfo, LayoutItem, LayoutOutput},
rect::{ParentInfo, RotatedRect},
transform::{Dimension, Transform2D},
};
use crate::{rect::Transform2, transform::InterpolateTransform};
type REntity<'t> = (
Entity,
&'t Dimension,
&'t Transform2D,
&'t OutOfFrameBehavior,
&'t LayoutControl,
);
fn exp_decay_interpolate(transform: &mut Transform, target: Transform, fac: f32, dt: f32) {
transform
.translation
.smooth_nudge(&target.translation, fac, dt);
transform.scale.smooth_nudge(&target.scale, fac, dt);
let mut angle = transform.rotation.to_axis_angle().1;
let to = target.rotation.to_axis_angle().1;
angle.smooth_nudge(&to, fac, dt);
transform.rotation = Quat::from_rotation_z(angle);
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::needless_pass_by_ref_mut)]
fn propagate(
parent: ParentInfo,
entity: Entity,
dt: f32,
mut_query: &mut Query<REntity>,
layout_query: &mut Query<&mut Container>,
child_query: &Query<&Children>,
queue: &mut Vec<(Entity, ParentInfo)>,
transform_query: &mut Query<(&mut Transform, &mut RotatedRect, Ref<InterpolateTransform>)>,
) {
if !mut_query.contains(entity) {
return;
}
let Ok((entity, dim, transform, behavior, ..)) = mut_query.get(entity) else {
return;
};
let dimension = dim.0;
if let Ok(mut layout) = layout_query.get_mut(entity) {
let children = child_query
.get(entity)
.map(|x| x.iter().copied())
.into_iter()
.flatten();
let mut other_entities = Vec::new();
let mut args = Vec::new();
for child in children {
if !mut_query.contains(child) {
continue;
}
if let Ok((_, child_dim, child_transform, .., control)) = mut_query.get(child) {
match control {
LayoutControl::IgnoreLayout => {
other_entities.push((child, child_transform.get_parent_anchor()))
}
control => {
args.push(LayoutItem {
entity: child,
anchor: child_transform.get_parent_anchor(),
dimension: child_dim.0,
control: *control,
});
}
};
}
}
let margin = layout.margin;
let LayoutOutput {
mut entity_anchors,
dimension: new_dim,
max_count,
} = layout.place(&LayoutInfo { dimension, margin }, args);
layout.maximum = max_count;
let padding = layout.padding * 2.0;
let fac = new_dim / (new_dim + padding);
let size = new_dim + padding;
if !fac.is_nan() {
entity_anchors.iter_mut().for_each(|(_, anc)| *anc *= fac);
}
let rect = RotatedRect::construct(&parent, transform, size, parent.frame);
let info = ParentInfo {
dimension: new_dim,
center: transform.get_center(),
anchor: None,
affine: parent
.affine
.mul(rect.transform2_at(transform.get_center())),
frame: parent.frame,
frame_rect: parent.frame_rect,
};
queue.extend(
entity_anchors
.into_iter()
.map(|(e, anc)| (e, info.with_anchor(anc))),
);
if let Ok((mut t, mut r, interpolate)) = transform_query.get_mut(entity) {
*r = rect.under_transform2(parent.affine);
let result = rect.transform_at(transform.get_center());
match &*interpolate {
_ if interpolate.is_changed() => *t = result,
InterpolateTransform::None => *t = result,
InterpolateTransform::ExponentialDecay(fac) => {
exp_decay_interpolate(&mut t, result, *fac, dt);
}
}
}
for (child, _) in other_entities {
queue.push((child, info))
}
return;
}
let rect = match behavior {
OutOfFrameBehavior::None => {
RotatedRect::construct(&parent, transform, dimension, parent.frame)
}
OutOfFrameBehavior::Nudge => {
let mut rect = RotatedRect::construct(&parent, transform, dimension, parent.frame);
let frame_space_rect = rect.under_transform2(parent.affine);
frame_space_rect.nudge_inside_ext(parent.frame_rect, &mut rect.center);
rect
}
OutOfFrameBehavior::AnchorSwap { .. } => {
let mut result = RotatedRect::construct(&parent, transform, dimension, parent.frame);
for anchor in behavior.iter_anchor_swaps() {
let rect = RotatedRect::construct2(
&parent,
transform,
anchor.to_parent_anchor().into(),
anchor.to_anchor().into(),
dimension,
parent.frame,
);
let frame_space_rect = rect.under_transform2(parent.affine);
if frame_space_rect.is_inside(parent.frame_rect) {
result = rect;
break;
}
}
result
}
};
if let Ok(children) = child_query.get(entity) {
let info = ParentInfo {
dimension,
anchor: None,
center: transform.get_center(),
affine: parent
.affine
.mul(rect.transform2_at(transform.get_center())),
frame: parent.frame,
frame_rect: parent.frame_rect,
};
for child in children.iter().copied() {
queue.push((child, info))
}
}
if let Ok((mut t, mut r, interpolate)) = transform_query.get_mut(entity) {
*r = rect.under_transform2(parent.affine);
let result = rect.transform_at(transform.get_center());
match &*interpolate {
_ if interpolate.is_changed() => *t = result,
InterpolateTransform::None => *t = result,
InterpolateTransform::ExponentialDecay(fac) => {
exp_decay_interpolate(&mut t, result, *fac, dt);
}
}
}
}
/// The main computation step.
pub fn compute_transform_2d(
mut queue_a: Local<Vec<(Entity, ParentInfo)>>,
mut queue_b: Local<Vec<(Entity, ParentInfo)>>,
time: Res<Time<Virtual>>,
root_query: Query<(Entity, &RectrayFrame, &Children)>,
mut entity_query: Query<REntity>,
mut layout_query: Query<&mut Container>,
child_query: Query<&Children>,
mut transform_query: Query<(&mut Transform, &mut RotatedRect, Ref<InterpolateTransform>)>,
) {
let dt = time.delta_secs();
for (frame, root, children) in root_query.iter() {
for child in children.iter().copied() {
queue_a.push((
child,
ParentInfo {
dimension: root.dimension,
center: root.at,
anchor: None,
affine: Transform2::IDENTITY,
frame,
frame_rect: root.rect(),
},
))
}
}
while !queue_a.is_empty() {
mem::swap::<Vec<_>>(queue_a.as_mut(), queue_b.as_mut());
for (entity, parent) in queue_b.drain(..) {
propagate(
parent,
entity,
dt,
&mut entity_query,
&mut layout_query,
&child_query,
&mut queue_a,
&mut transform_query,
);
}
}
}
| 0 | 0.986592 | 1 | 0.986592 | game-dev | MEDIA | 0.336177 | game-dev | 0.916433 | 1 | 0.916433 |
BlueLightJapan/BlueLight | 2,644 | src/pocketmine/command/defaults/GarbageCollectorCommand.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\command\defaults;
use pocketmine\command\CommandSender;
use pocketmine\utils\TextFormat;
class GarbageCollectorCommand extends VanillaCommand{
public function __construct(string $name){
parent::__construct(
$name,
"%pocketmine.command.gc.description",
"%pocketmine.command.gc.usage"
);
$this->setPermission("pocketmine.command.gc");
}
public function execute(CommandSender $sender, string $commandLabel, array $args){
if(!$this->testPermission($sender)){
return true;
}
$chunksCollected = 0;
$entitiesCollected = 0;
$tilesCollected = 0;
$memory = memory_get_usage();
foreach($sender->getServer()->getLevels() as $level){
$diff = [count($level->getChunks()), count($level->getEntities()), count($level->getTiles())];
$level->doChunkGarbageCollection();
$level->unloadChunks(true);
$chunksCollected += $diff[0] - count($level->getChunks());
$entitiesCollected += $diff[1] - count($level->getEntities());
$tilesCollected += $diff[2] - count($level->getTiles());
$level->clearCache(true);
}
$cyclesCollected = $sender->getServer()->getMemoryManager()->triggerGarbageCollector();
$sender->sendMessage(TextFormat::GREEN . "---- " . TextFormat::WHITE . "Garbage collection result" . TextFormat::GREEN . " ----");
$sender->sendMessage(TextFormat::GOLD . "Chunks: " . TextFormat::RED . number_format($chunksCollected));
$sender->sendMessage(TextFormat::GOLD . "Entities: " . TextFormat::RED . number_format($entitiesCollected));
$sender->sendMessage(TextFormat::GOLD . "Tiles: " . TextFormat::RED . number_format($tilesCollected));
$sender->sendMessage(TextFormat::GOLD . "Cycles: " . TextFormat::RED . number_format($cyclesCollected));
$sender->sendMessage(TextFormat::GOLD . "Memory freed: " . TextFormat::RED . number_format(round((($memory - memory_get_usage()) / 1024) / 1024, 2)) . " MB");
return true;
}
}
| 0 | 0.938162 | 1 | 0.938162 | game-dev | MEDIA | 0.780898 | game-dev | 0.934837 | 1 | 0.934837 |
resonance-audio/resonance-audio | 1,708 | platforms/unity/UnityIntegration/Assets/ResonanceAudio/Demos/Scripts/ResonanceAudioDemo/ResonanceAudioDemoManager.cs | // Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
/// Class that manages the ResonanceAudioDemo scene.
public class ResonanceAudioDemoManager : MonoBehaviour {
/// Main camera.
public Camera mainCamera;
/// Cube controller.
public ResonanceAudioDemoCubeController cube;
void Start() {
Screen.sleepTimeout = SleepTimeout.NeverSleep;
}
void Update() {
#if !UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.Escape)) {
Application.Quit();
}
#endif // !UNITY_EDITOR
// Raycast against the cube.
Ray ray = mainCamera.ViewportPointToRay(0.5f * Vector2.one);
RaycastHit hit;
bool cubeHit = Physics.Raycast(ray, out hit) && hit.transform == cube.transform;
// Update the state of the cube.
cube.SetGazedAt(cubeHit);
if (cubeHit) {
if((Input.touchCount == 0 && Input.GetMouseButtonDown(0)) || // LMB for desktop.
(Input.touchCount > 0 && Input.GetTouch(0).tapCount > 1 && // Double-tap for mobile.
Input.GetTouch(0).phase == TouchPhase.Began)) {
// Teleport the cube to its next location.
cube.TeleportRandomly();
}
}
}
}
| 0 | 0.797388 | 1 | 0.797388 | game-dev | MEDIA | 0.628388 | game-dev | 0.932291 | 1 | 0.932291 |
grayj/Jedi-Academy | 5,131 | codemp/game/g_timer.c | //rww - rewrite from C++ SP version.
//This is here only to make porting from SP easier, it's really sort of nasty (being static
//now). Basically it's slower and takes more memory.
#include "g_local.h"
//typedef map < string, int > timer_m;
#define MAX_GTIMERS 16384
typedef struct gtimer_s
{
const char *name;
int time;
struct gtimer_s *next; // In either free list or current list
} gtimer_t;
gtimer_t g_timerPool[ MAX_GTIMERS ];
gtimer_t *g_timers[ MAX_GENTITIES ];
gtimer_t *g_timerFreeList;
/*
-------------------------
TIMER_Clear
-------------------------
*/
void TIMER_Clear( void )
{
int i;
for (i = 0; i < MAX_GENTITIES; i++)
{
g_timers[i] = NULL;
}
for (i = 0; i < MAX_GTIMERS - 1; i++)
{
g_timerPool[i].next = &g_timerPool[i+1];
}
g_timerPool[MAX_GTIMERS-1].next = NULL;
g_timerFreeList = &g_timerPool[0];
}
/*
-------------------------
TIMER_Clear
-------------------------
*/
void TIMER_Clear2( gentity_t *ent )
{
// rudimentary safety checks, might be other things to check?
if ( ent && ent->s.number > 0 && ent->s.number < MAX_GENTITIES )
{
gtimer_t *p = g_timers[ent->s.number];
// No timers at all -> do nothing
if (!p)
{
return;
}
// Find the end of this ents timer list
while (p->next)
{
p = p->next;
}
// Splice the lists
p->next = g_timerFreeList;
g_timerFreeList = g_timers[ent->s.number];
g_timers[ent->s.number] = NULL;
return;
}
}
//New C "lookup" func.
//Returns existing timer in array if
gtimer_t *TIMER_GetNew(int num, const char *identifier)
{
gtimer_t *p = g_timers[num];
// Search for an existing timer with this name
while (p)
{
if (!Q_stricmp(p->name, identifier))
{ // Found it
return p;
}
p = p->next;
}
// No existing timer with this name was found, so grab one from the free list
if (!g_timerFreeList)
return NULL;
p = g_timerFreeList;
g_timerFreeList = g_timerFreeList->next;
p->next = g_timers[num];
g_timers[num] = p;
return p;
}
//don't return the first free if it doesn't already exist, return null.
gtimer_t *TIMER_GetExisting(int num, const char *identifier)
{
gtimer_t *p = g_timers[num];
while (p)
{
if (!Q_stricmp(p->name, identifier))
{ // Found it
return p;
}
p = p->next;
}
return NULL;
}
/*
-------------------------
TIMER_Set
-------------------------
*/
void TIMER_Set( gentity_t *ent, const char *identifier, int duration )
{
gtimer_t *timer = TIMER_GetNew(ent->s.number, identifier);
if (!timer)
{
return;
}
timer->name = identifier;
timer->time = level.time + duration;
}
/*
-------------------------
TIMER_Get
-------------------------
*/
int TIMER_Get( gentity_t *ent, const char *identifier )
{
gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier);
if (!timer)
{
return -1;
}
return timer->time;
}
/*
-------------------------
TIMER_Done
-------------------------
*/
qboolean TIMER_Done( gentity_t *ent, const char *identifier )
{
gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier);
if (!timer)
{
return qtrue;
}
return (timer->time < level.time);
}
/*
-------------------------
TIMER_RemoveHelper
Scans an entities timer list to remove a given
timer from the list and put it on the free list
Doesn't do much error checking, only called below
-------------------------
*/
void TIMER_RemoveHelper( int num, gtimer_t *timer )
{
gtimer_t *p = g_timers[num];
// Special case: first timer in list
if (p == timer)
{
g_timers[num] = g_timers[num]->next;
p->next = g_timerFreeList;
g_timerFreeList = p;
return;
}
// Find the predecessor
while (p->next != timer)
{
p = p->next;
}
// Rewire
p->next = p->next->next;
timer->next = g_timerFreeList;
g_timerFreeList = timer;
return;
}
/*
-------------------------
TIMER_Done2
Returns false if timer has been
started but is not done...or if
timer was never started
-------------------------
*/
qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove )
{
gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier);
qboolean res;
if (!timer)
{
return qfalse;
}
res = (timer->time < level.time);
if (res && remove)
{
// Put it back on the free list
TIMER_RemoveHelper(ent->s.number, timer);
}
return res;
}
/*
-------------------------
TIMER_Exists
-------------------------
*/
qboolean TIMER_Exists( gentity_t *ent, const char *identifier )
{
gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier);
if (!timer)
{
return qfalse;
}
return qtrue;
}
/*
-------------------------
TIMER_Remove
Utility to get rid of any timer
-------------------------
*/
void TIMER_Remove( gentity_t *ent, const char *identifier )
{
gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier);
if (!timer)
{
return;
}
// Put it back on the free list
TIMER_RemoveHelper(ent->s.number, timer);
}
/*
-------------------------
TIMER_Start
-------------------------
*/
qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration )
{
if ( TIMER_Done( self, identifier ) )
{
TIMER_Set( self, identifier, duration );
return qtrue;
}
return qfalse;
}
| 0 | 0.885016 | 1 | 0.885016 | game-dev | MEDIA | 0.356045 | game-dev | 0.810107 | 1 | 0.810107 |
viridia/quill | 11,743 | examples/controls.rs | //! Example of a simple UI layout
#![feature(impl_trait_in_assoc_type)]
use bevy::{color::palettes, prelude::*, ui};
use bevy_mod_picking::DefaultPickingPlugins;
use bevy_mod_stylebuilder::*;
use bevy_quill::*;
use bevy_quill_obsidian::{
colors,
controls::{
Button, ButtonVariant, Checkbox, ColorGradient, Dialog, DialogFooter, DialogHeader,
GradientSlider, MenuButton, MenuDivider, MenuItem, MenuPopup, Slider, SpinBox, Swatch,
},
ObsidianUiPlugin,
};
fn style_test(ss: &mut StyleBuilder) {
ss.display(Display::Flex)
.flex_direction(FlexDirection::Column)
.position(ui::PositionType::Absolute)
.padding(3)
.left(0)
.right(0)
.top(0)
.bottom(0)
.row_gap(4)
.background_color(colors::U2);
}
fn style_row(ss: &mut StyleBuilder) {
ss.display(Display::Flex)
.flex_direction(FlexDirection::Row)
.align_items(ui::AlignItems::Center)
.column_gap(4);
}
fn style_swatch(ss: &mut StyleBuilder) {
ss.width(24).height(24);
}
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
DefaultPickingPlugins,
QuillPlugin,
ObsidianUiPlugin,
))
.add_systems(Startup, setup_view_root)
.add_systems(Update, close_on_esc)
.run();
}
fn setup_view_root(mut commands: Commands) {
let camera = commands
.spawn((Camera2dBundle {
camera: Camera::default(),
camera_2d: Camera2d {},
..default()
},))
.id();
commands.spawn(ButtonsDemo { camera }.to_root());
}
#[derive(Clone, PartialEq)]
struct ButtonsDemo {
camera: Entity,
}
impl ViewTemplate for ButtonsDemo {
type View = impl View;
fn create(&self, cx: &mut Cx) -> Self::View {
let checked = cx.create_mutable(true);
let disabled = cx.create_mutable(false);
let dialog_open = cx.create_mutable(false);
let on_checked = cx.create_callback(move |value: In<bool>, world: &mut World| {
checked.set(world, *value);
// info!("Checked: {}", *value);
});
let spin_value = cx.create_mutable::<f32>(50.);
let slider_value = cx.create_mutable::<f32>(50.);
let color_value = cx.create_mutable::<Srgba>(Srgba::new(1.0, 0.0, 0.0, 1.0));
let color = color_value.get(cx);
Element::<NodeBundle>::new()
.insert_dyn(TargetCamera, self.camera)
.style(style_test)
.children((
"Checkbox",
Element::<NodeBundle>::new().style(style_row).children((
Checkbox::new()
.checked(checked.get(cx))
.on_change(on_checked)
.label("Checkbox"),
Checkbox::new()
.disabled(disabled.get(cx))
.checked(checked.get(cx))
.on_change(on_checked)
.label("Checkbox (disabled)"),
Checkbox::new()
.checked(disabled.get(cx))
.on_change(
cx.create_callback(move |value: In<bool>, world: &mut World| {
disabled.set(world, *value);
// info!("Disabled: {}", *value);
}),
)
.label("Disable"),
)),
"Swatch",
Element::<NodeBundle>::new().style(style_row).children((
Swatch::new(palettes::css::RED).style(style_swatch),
Swatch::new(colors::U1).style(style_swatch),
Swatch::new(Srgba::new(0.5, 1.0, 0.0, 0.5)).style(style_swatch),
)),
"Spinbox",
Element::<NodeBundle>::new()
.style(style_row)
.children((SpinBox::new()
.style(|sb: &mut StyleBuilder| {
sb.width(100);
})
.value(spin_value.get(cx))
.on_change(cx.create_callback(
move |value: In<f32>, world: &mut World| {
spin_value.set(world, *value);
},
)),)),
"Slider",
Element::<NodeBundle>::new().style(style_row).children((
" Normal:",
Slider::new()
.range(0. ..=100.)
.style(|sb: &mut StyleBuilder| {
sb.width(100);
})
.value(slider_value.get(cx))
.on_change(
cx.create_callback(move |value: In<f32>, world: &mut World| {
slider_value.set(world, *value);
}),
),
" Compact:",
Slider::new()
.range(0. ..=100.)
.style(|sb: &mut StyleBuilder| {
sb.width(50);
})
.value(slider_value.get(cx))
.on_change(
cx.create_callback(move |value: In<f32>, world: &mut World| {
slider_value.set(world, *value);
}),
),
" Precision:",
Slider::new()
.range(0. ..=100.)
.style(|sb: &mut StyleBuilder| {
sb.width(100);
})
.precision(2)
.value(slider_value.get(cx))
.on_change(
cx.create_callback(move |value: In<f32>, world: &mut World| {
slider_value.set(world, *value);
}),
),
" Labeled:",
Slider::new()
.range(0. ..=100.)
.style(|sb: &mut StyleBuilder| {
sb.width(100);
})
.label("Gain")
.value(slider_value.get(cx))
.on_change(
cx.create_callback(move |value: In<f32>, world: &mut World| {
slider_value.set(world, *value);
}),
),
" Custom Format:",
Slider::new()
.range(0. ..=100.)
.style(|sb: &mut StyleBuilder| {
sb.width(100);
})
.formatted_value(format!("{:.0} dB", slider_value.get(cx)))
.value(slider_value.get(cx))
.on_change(
cx.create_callback(move |value: In<f32>, world: &mut World| {
slider_value.set(world, *value);
}),
),
)),
"GradientSlider",
GradientSlider::new()
.gradient(ColorGradient::new(&[
Srgba::new(color.red, 0.0, color.blue, 1.0),
Srgba::new(color.red, 1.0, color.blue, 1.0),
]))
.min(0.)
.max(255.)
.value(color.green * 255.0)
.style(|sb: &mut StyleBuilder| {
sb.width(100);
})
.precision(1)
.on_change(
cx.create_callback(move |value: In<f32>, world: &mut World| {
color_value.update(world, |mut state| state.green = *value / 255.0);
}),
),
"Dialog",
Element::<NodeBundle>::new().style(style_row).children((
Button::new()
.on_click(cx.create_callback(move |world: &mut World| {
dialog_open.set(world, true);
}))
.children("Open..."),
Dialog::new()
.width(ui::Val::Px(400.))
.open(dialog_open.get(cx))
.on_close(cx.create_callback(move |world: &mut World| {
dialog_open.set(world, false);
}))
.children((
DialogHeader::new().children("Dialog Header"),
DialogFooter::new().children((
Button::new()
.children("Cancel")
.on_click(cx.create_callback(move |world: &mut World| {
dialog_open.set(world, false);
})),
Button::new()
.children("Close")
.variant(ButtonVariant::Primary)
.autofocus(true)
.on_click(cx.create_callback(move |world: &mut World| {
dialog_open.set(world, false);
})),
)),
)),
)),
"MenuButton",
Element::<NodeBundle>::new()
.style(style_row)
.children((MenuButton::new().children("Menu").popup(
MenuPopup::new().children((
MenuItem::new()
.label("Alpha Male")
.on_click(cx.create_callback(|| {
println!("Alpha item clicked");
})),
MenuItem::new()
.label("Beta Test")
.on_click(cx.create_callback(|| {
println!("Beta item clicked");
})),
MenuItem::new()
.label("Delta Sleep")
.on_click(cx.create_callback(|| {
println!("Delta item clicked");
})),
MenuItem::new()
.label("Gamma Ray")
.on_click(cx.create_callback(|| {
println!("Gamma item clicked");
})),
MenuDivider,
MenuItem::new()
.label("Omega Point")
.on_click(cx.create_callback(|| {
println!("Omega item clicked");
})),
)),
),)),
))
}
}
pub fn close_on_esc(input: Res<ButtonInput<KeyCode>>, mut exit: EventWriter<AppExit>) {
if input.just_pressed(KeyCode::Escape) {
exit.send(AppExit::Success);
}
}
| 0 | 0.97733 | 1 | 0.97733 | game-dev | MEDIA | 0.738905 | game-dev | 0.947176 | 1 | 0.947176 |
AtomicGameEngine/AtomicGameEngine | 13,831 | Source/AtomicEditor/Editors/SceneEditor3D/SceneEditOp.cpp | //
// Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
//
// 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 <Atomic/IO/Log.h>
#include <Atomic/Scene/Node.h>
#include <Atomic/Scene/Component.h>
#include <Atomic/Scene/PrefabComponent.h>
#include <Atomic/Scene/Scene.h>
#include "SceneEditOp.h"
#include "SceneEditor3DEvents.h"
namespace AtomicEditor
{
SelectionEditOp::SelectionEditOp(Scene *scene) : SceneEditOp(scene, SCENEEDIT_SELECTION)
{
}
SelectionEditOp::~SelectionEditOp()
{
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
EditNode* enode = editNodes_[i];
for (unsigned j = 0; j < enode->components_.Size(); j++)
delete enode->components_[j];
delete enode;
}
}
bool SelectionEditOp::EraseNode(Node *node)
{
PODVector<EditNode*>::Iterator itr = editNodes_.Begin();
while (itr != editNodes_.End())
{
if ((*itr)->node_ == node)
{
for (unsigned j = 0; j < (*itr)->components_.Size(); j++)
delete (*itr)->components_[j];
delete *itr;
editNodes_.Erase(itr);
break;
}
itr++;
}
return editNodes_.Size() == 0;
}
void SelectionEditOp::AddNode(Node* node)
{
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
if (editNodes_[i]->node_ == node)
return;
}
EditNode* enode = new EditNode();
enode->node_ = node;
enode->parentBegin_ = enode->parentEnd_ = node->GetParent();
node->Serializable::Save(enode->stateBegin_);
enode->stateBegin_.Seek(0);
enode->stateEnd_ = enode->stateBegin_;
const Vector<SharedPtr<Component>>& components = node->GetComponents();
for (unsigned j = 0; j < components.Size(); j++)
{
Component* component = components[j];
EditComponent* ecomponent = new EditComponent();
ecomponent->component_ = component;
ecomponent->nodeBegin_ = ecomponent->nodeEnd_ = node;
component->Serializable::Save(ecomponent->stateBegin_);
ecomponent->stateBegin_.Seek(0);
ecomponent->stateEnd_ = ecomponent->stateBegin_;
enode->components_.Push(ecomponent);
}
editNodes_.Push(enode);
}
void SelectionEditOp::NodeAdded(Node* node, Node* parent)
{
AddNode(node);
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
if (editNodes_[i]->node_ == node)
{
editNodes_[i]->parentBegin_ = 0;
editNodes_[i]->parentEnd_ = parent;
return;
}
}
}
void SelectionEditOp::NodeRemoved(Node* node, Node* parent)
{
AddNode(node);
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
if (editNodes_[i]->node_ == node)
{
editNodes_[i]->parentBegin_ = parent;
editNodes_[i]->parentEnd_ = 0;
return;
}
}
}
void SelectionEditOp::SetNodes(Vector<SharedPtr<Node> > &nodes)
{
// Generate initial snapshot
for (unsigned i = 0; i < nodes.Size(); i++)
{
AddNode(nodes[i]);
}
}
bool SelectionEditOp::Commit()
{
// See if any nodes, components have been edited
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
EditNode* enode = editNodes_[i];
if (enode->parentBegin_ != enode->parentEnd_)
return true;
if (!CompareStates(enode->stateBegin_, enode->stateEnd_))
return true;
for (unsigned j = 0; j < enode->components_.Size(); j++)
{
EditComponent* ecomponent = enode->components_[j];
if (ecomponent->nodeBegin_ != ecomponent->nodeEnd_)
return true;
if (!CompareStates(ecomponent->stateBegin_, ecomponent->stateEnd_))
return true;
}
}
return false;
}
void SelectionEditOp::RegisterEdit()
{
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
EditNode* enode = editNodes_[i];
enode->stateEnd_.Clear();
enode->node_->Serializable::Save(enode->stateEnd_);
enode->stateEnd_.Seek(0);
enode->parentEnd_ = enode->node_->GetParent();
for (unsigned j = 0; j < enode->components_.Size(); j++)
{
EditComponent* ecomponent = enode->components_[j];
ecomponent->stateEnd_.Clear();
ecomponent->component_->Serializable::Save(ecomponent->stateEnd_);
ecomponent->stateEnd_.Seek(0);
ecomponent->nodeEnd_ = ecomponent->component_->GetNode();
}
}
}
bool SelectionEditOp::Undo()
{
scene_->SendEvent(E_SCENEEDITSTATECHANGESBEGIN);
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
EditNode* enode = editNodes_[i];
Node* node = enode->node_;
bool changed = !CompareStates(enode->stateBegin_, enode->stateEnd_);
if (changed && !node->Serializable::Load(enode->stateBegin_))
{
ATOMIC_LOGERRORF("Unable to Undo node serializable");
return false;
}
if (changed)
{
VariantMap eventData;
eventData[SceneEditStateChange::P_SERIALIZABLE] = node;
node->SendEvent(E_SCENEEDITSTATECHANGE, eventData);
}
enode->stateBegin_.Seek(0);
if (node->GetParent() != enode->parentBegin_)
{
if(enode->parentBegin_.NotNull())
{
// moving back to original parent
if (node->GetParent())
{
VariantMap nodeRemovedEventData;
nodeRemovedEventData[SceneEditNodeRemoved::P_NODE] = node;
nodeRemovedEventData[SceneEditNodeRemoved::P_PARENT] = node->GetParent();
nodeRemovedEventData[SceneEditNodeRemoved::P_SCENE] = scene_;
scene_->SendEvent(E_SCENEEDITNODEREMOVED, nodeRemovedEventData);
}
node->Remove();
enode->parentBegin_->AddChild(node);
VariantMap nodeAddedEventData;
nodeAddedEventData[SceneEditNodeAdded::P_NODE] = node;
nodeAddedEventData[SceneEditNodeAdded::P_PARENT] = enode->parentBegin_;
nodeAddedEventData[SceneEditNodeAdded::P_SCENE] = scene_;
scene_->SendEvent(E_SCENEEDITNODEADDED, nodeAddedEventData);
}
else
{
VariantMap nodeRemovedEventData;
nodeRemovedEventData[SceneEditNodeRemoved::P_NODE] = node;
nodeRemovedEventData[SceneEditNodeRemoved::P_PARENT] = enode->parentEnd_;
nodeRemovedEventData[SceneEditNodeRemoved::P_SCENE] = scene_;
scene_->SendEvent(E_SCENEEDITNODEREMOVED, nodeRemovedEventData);
node->Remove();
}
}
for (unsigned j = 0; j < enode->components_.Size(); j++)
{
EditComponent* ecomponent = enode->components_[j];
Component* component = ecomponent->component_;
changed = !CompareStates(ecomponent->stateBegin_, ecomponent->stateEnd_);
if (changed && !component->Serializable::Load(ecomponent->stateBegin_))
{
ATOMIC_LOGERRORF("Unable to Undo component serializable");
return false;
}
if (changed)
{
VariantMap eventData;
eventData[SceneEditStateChange::P_SERIALIZABLE] = component;
component->SendEvent(E_SCENEEDITSTATECHANGE, eventData);
}
ecomponent->stateBegin_.Seek(0);
if (component->GetNode() != ecomponent->nodeBegin_)
{
component->Remove();
bool add = ecomponent->nodeBegin_.NotNull();
VariantMap caData;
caData[SceneEditComponentAddedRemoved::P_SCENE] = scene_;
caData[SceneEditComponentAddedRemoved::P_COMPONENT] = component;
if (add)
{
ecomponent->nodeBegin_->AddComponent(component, 0, REPLICATED);
caData[SceneEditComponentAddedRemoved::P_NODE] = ecomponent->nodeBegin_;
caData[SceneEditComponentAddedRemoved::P_REMOVED] = false;
}
else
{
caData[SceneEditComponentAddedRemoved::P_NODE] = ecomponent->nodeEnd_;
caData[SceneEditComponentAddedRemoved::P_REMOVED] = true;
}
scene_->SendEvent(E_SCENEEDITCOMPONENTADDEDREMOVED, caData);
}
}
}
scene_->SendEvent(E_SCENEEDITSTATECHANGESEND);
return true;
}
bool SelectionEditOp::Redo()
{
scene_->SendEvent(E_SCENEEDITSTATECHANGESBEGIN);
for (unsigned i = 0; i < editNodes_.Size(); i++)
{
EditNode* enode = editNodes_[i];
Node* node = enode->node_;
bool changed = !CompareStates(enode->stateBegin_, enode->stateEnd_);
if ( changed && !node->Serializable::Load(enode->stateEnd_))
{
ATOMIC_LOGERRORF("Unable to Redo node serializable");
return false;
}
enode->stateEnd_.Seek(0);
if (changed)
{
VariantMap eventData;
eventData[SceneEditStateChange::P_SERIALIZABLE] = node;
node->SendEvent(E_SCENEEDITSTATECHANGE, eventData);
}
if (node->GetParent() != enode->parentEnd_)
{
if(enode->parentEnd_.NotNull())
{
if (node->GetParent())
{
VariantMap nodeRemovedEventData;
nodeRemovedEventData[SceneEditNodeRemoved::P_NODE] = node;
nodeRemovedEventData[SceneEditNodeRemoved::P_PARENT] = node->GetParent();
nodeRemovedEventData[SceneEditNodeRemoved::P_SCENE] = scene_;
scene_->SendEvent(E_SCENEEDITNODEREMOVED, nodeRemovedEventData);
}
node->Remove();
enode->parentEnd_->AddChild(node);
VariantMap nodeAddedEventData;
nodeAddedEventData[SceneEditNodeAdded::P_NODE] = node;
nodeAddedEventData[SceneEditNodeAdded::P_PARENT] = enode->parentEnd_;
nodeAddedEventData[SceneEditNodeAdded::P_SCENE] = scene_;
scene_->SendEvent(E_SCENEEDITNODEADDED, nodeAddedEventData);
}
else
{
VariantMap nodeRemovedEventData;
nodeRemovedEventData[SceneEditNodeRemoved::P_NODE] = node;
nodeRemovedEventData[SceneEditNodeRemoved::P_PARENT] = enode->parentBegin_;
nodeRemovedEventData[SceneEditNodeRemoved::P_SCENE] = scene_;
scene_->SendEvent(E_SCENEEDITNODEREMOVED, nodeRemovedEventData);
node->Remove();
}
}
for (unsigned j = 0; j < enode->components_.Size(); j++)
{
EditComponent* ecomponent = enode->components_[j];
Component* component = ecomponent->component_;
changed = !CompareStates(ecomponent->stateBegin_, ecomponent->stateEnd_);
if ( changed && !component->Serializable::Load(ecomponent->stateEnd_))
{
ATOMIC_LOGERRORF("Unable to Redo component serializable");
return false;
}
ecomponent->stateEnd_.Seek(0);
if (changed)
{
VariantMap eventData;
eventData[SceneEditStateChange::P_SERIALIZABLE] = component;
component->SendEvent(E_SCENEEDITSTATECHANGE, eventData);
}
if (component->GetNode() != ecomponent->nodeEnd_)
{
component->Remove();
bool add = ecomponent->nodeEnd_.NotNull();
VariantMap caData;
caData[SceneEditComponentAddedRemoved::P_SCENE] = scene_;
caData[SceneEditComponentAddedRemoved::P_COMPONENT] = component;
if (add)
{
ecomponent->nodeEnd_->AddComponent(component, 0, REPLICATED);
caData[SceneEditComponentAddedRemoved::P_NODE] = ecomponent->nodeEnd_;
caData[SceneEditComponentAddedRemoved::P_REMOVED] = false;
}
else
{
caData[SceneEditComponentAddedRemoved::P_NODE] = ecomponent->nodeBegin_;
caData[SceneEditComponentAddedRemoved::P_REMOVED] = true;
}
scene_->SendEvent(E_SCENEEDITCOMPONENTADDEDREMOVED, caData);
}
}
}
scene_->SendEvent(E_SCENEEDITSTATECHANGESEND);
return true;
}
}
| 0 | 0.918983 | 1 | 0.918983 | game-dev | MEDIA | 0.717314 | game-dev | 0.907594 | 1 | 0.907594 |
PhoenixBladez/SpiritMod | 1,269 | Items/Sets/FloatingItems/FloatingItemWorld.cs | using System;
using System.Linq;
using Terraria;
using Terraria.ModLoader;
using Terraria.Utilities;
namespace SpiritMod.Items.Sets.FloatingItems
{
public class FloatingItemWorld : ModWorld
{
public WeightedRandom<int> floatingItemPool = new WeightedRandom<int>();
public override void Initialize()
{
var types = typeof(FloatingItem).Assembly.GetTypes();
foreach (var type in types)
{
if (typeof(FloatingItem).IsAssignableFrom(type) && !type.IsAbstract)
{
var v = Activator.CreateInstance(type) as FloatingItem;
if (!floatingItemPool.elements.Any(x => x.Item1 == mod.ItemType(type.Name)))
floatingItemPool.Add(mod.ItemType(type.Name), v.SpawnWeight);
}
}
}
public override void PreUpdate()
{
if (Main.rand.NextBool(3500))
{
int x = Main.rand.Next(600, Main.maxTilesX);
if (Main.rand.NextBool(2))
x = Main.rand.Next(Main.maxTilesX * 15, Main.maxTilesX * 16 - 600);
int y = (int)(Main.worldSurface * 0.35) + 400;
for (; Framing.GetTileSafely(x / 16, y / 16).liquid < 200; y += 16)
{
if (y / 16 > Main.worldSurface) //If we somehow miss all water, exit
return;
}
y += 40;
ItemUtils.NewItemWithSync(Main.myPlayer, x, y, 4, 4, floatingItemPool);
}
}
}
}
| 0 | 0.737732 | 1 | 0.737732 | game-dev | MEDIA | 0.989206 | game-dev | 0.923695 | 1 | 0.923695 |
bungaku-moe/Azure-Gravure | 3,693 | Assets/Live2D/Cubism/Core/CubismPart.cs | /**
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
using Live2D.Cubism.Core.Unmanaged;
using Live2D.Cubism.Framework;
using UnityEngine;
namespace Live2D.Cubism.Core
{
/// <summary>
/// Single <see cref="CubismModel"/> part.
/// </summary>
[CubismDontMoveOnReimport]
public sealed class CubismPart : MonoBehaviour
{
#region Factory Methods
/// <summary>
/// Creates parts for a <see cref="CubismModel"/>.
/// </summary>
/// <param name="unmanagedModel">Handle to unmanaged model.</param>
/// <returns>Parts root.</returns>
internal static GameObject CreateParts(CubismUnmanagedModel unmanagedModel)
{
var root = new GameObject("Parts");
// Create parts.
var unmanagedParts = unmanagedModel.Parts;
var buffer = new CubismPart[unmanagedParts.Count];
for (var i = 0; i < buffer.Length; ++i)
{
var proxy = new GameObject();
buffer[i] = proxy.AddComponent<CubismPart>();
buffer[i].transform.SetParent(root.transform);
buffer[i].Reset(unmanagedModel, i);
}
return root;
}
#endregion
/// <summary>
/// Unmanaged parts from unmanaged model.
/// </summary>
private CubismUnmanagedParts UnmanagedParts { get; set; }
/// <summary>
/// <see cref="UnmanagedIndex"/> backing field.
/// </summary>
[SerializeField, HideInInspector]
private int _unmanagedIndex = -1;
/// <summary>
/// Position in unmanaged arrays.
/// </summary>
public int UnmanagedIndex
{
get { return _unmanagedIndex; }
private set { _unmanagedIndex = value; }
}
/// <summary>
/// Copy of Id.
/// </summary>
public string Id
{
get
{
// Pull data.
return UnmanagedParts.Ids[UnmanagedIndex];
}
}
/// <summary>
/// Current opacity.
/// </summary>
[SerializeField, HideInInspector]
public float Opacity;
/// <summary>
/// Parent part position in unmanaged arrays.
/// </summary>
public int UnmanagedParentIndex
{
get
{
if (UnmanagedIndex > 0)
{
// Pull data.
return UnmanagedParts.ParentIndices[UnmanagedIndex];
}
return -1;
}
}
/// <summary>
/// Revives instance.
/// </summary>
/// <param name="unmanagedModel">TaskableModel to unmanaged unmanagedModel.</param>
internal void Revive(CubismUnmanagedModel unmanagedModel)
{
UnmanagedParts = unmanagedModel.Parts;
}
/// <summary>
/// Restores instance to initial state.
/// </summary>
/// <param name="unmanagedModel">TaskableModel to unmanaged unmanagedModel.</param>
/// <param name="unmanagedIndex">Position in unmanaged arrays.</param>
private void Reset(CubismUnmanagedModel unmanagedModel, int unmanagedIndex)
{
Revive(unmanagedModel);
UnmanagedIndex = unmanagedIndex;
name = Id;
Opacity = UnmanagedParts.Opacities[unmanagedIndex];
}
}
}
| 0 | 0.835343 | 1 | 0.835343 | game-dev | MEDIA | 0.555194 | game-dev | 0.807984 | 1 | 0.807984 |
Da-Teach/Questor | 16,020 | Questor.Modules/Drones.cs | // ------------------------------------------------------------------------------
// <copyright from='2010' to='2015' company='THEHACKERWITHIN.COM'>
// Copyright (c) TheHackerWithin.COM. All Rights Reserved.
//
// Please look in the accompanying license.htm file for the license that
// applies to this source code. (a copy can also be found at:
// http://www.thehackerwithin.com/license.htm)
// </copyright>
// -------------------------------------------------------------------------------
namespace Questor.Modules
{
using System;
using System.Linq;
using DirectEve;
/// <summary>
/// The drones class will manage any and all drone related combat
/// </summary>
/// <remarks>
/// Drones will always work their way from lowest value target to highest value target and will only attack entities (not structures)
/// </remarks>
public class Drones
{
private double _armorPctTotal;
private int _lastDroneCount;
private DateTime _lastEngageCommand;
private DateTime _lastRecallCommand;
private int _recallCount;
private DateTime _lastLaunch;
private DateTime _lastRecall;
private long _lastTarget;
private DateTime _launchTimeout;
private int _launchTries;
private double _shieldPctTotal;
private double _structurePctTotal;
public bool recall = false;
public DroneState State { get; set; }
private double GetShieldPctTotal()
{
if (Cache.Instance.ActiveDrones.Count() == 0)
return 0;
return Cache.Instance.ActiveDrones.Sum(d => d.ShieldPct);
}
private double GetArmorPctTotal()
{
if (Cache.Instance.ActiveDrones.Count() == 0)
return 0;
return Cache.Instance.ActiveDrones.Sum(d => d.ArmorPct);
}
private double GetStructurePctTotal()
{
if (Cache.Instance.ActiveDrones.Count() == 0)
return 0;
return Cache.Instance.ActiveDrones.Sum(d => d.StructurePct);
}
/// <summary>
/// Return the best possible target
/// </summary>
/// <remarks>
/// Note this GetTarget works differently then the one from Combat
/// </remarks>
/// <returns></returns>
private EntityCache GetTarget()
{
// Find the first active weapon's target
var droneTarget = Cache.Instance.EntityById(_lastTarget);
// Return best possible target
return Cache.Instance.GetBestTarget(droneTarget, Settings.Instance.DroneControlRange, true);
}
/// <summary>
/// Engage the target
/// </summary>
private void EngageTarget()
{
var target = GetTarget();
// Nothing to engage yet, probably retargeting
if (target == null)
return;
if (target.IsBadIdea)
return;
// Is our current target still the same and is the last Engage command no longer then 15s ago?
if (_lastTarget == target.Id && DateTime.Now.Subtract(_lastEngageCommand).TotalSeconds < 15)
return;
// Are we still actively shooting at the target?
var mustEngage = false;
foreach (var drone in Cache.Instance.ActiveDrones)
mustEngage |= drone.FollowId != target.Id;
if (!mustEngage)
return;
// Is the last target our current active target?
if (target.IsActiveTarget)
{
// Save target id (so we do not constantly switch)
_lastTarget = target.Id;
// Engage target
Logging.Log("Drones: Engaging drones on [" + target.Name + "][ID: " + target.Id + "]" + Math.Round(target.Distance / 1000, 0) + "k away]");
Cache.Instance.DirectEve.ExecuteCommand(DirectCmd.CmdDronesEngage);
_lastEngageCommand = DateTime.Now;
}
else // Make the target active
{
target.MakeActiveTarget();
Logging.Log("Drones: Making [" + target.Name + "][ID: " + target.Id + "]" + Math.Round(target.Distance/1000,0) + "k away] the active target for drone engagement.");
}
}
public void ProcessState()
{
if (!Settings.Instance.UseDrones)
return;
switch (State)
{
case DroneState.WaitingForTargets:
// Are we in the right state ?
if (Cache.Instance.ActiveDrones.Count() > 0)
{
// Apparently not, we have drones out, go into fight mode
State = DroneState.Fighting;
break;
}
// Should we launch drones?
var launch = true;
// Always launch if we're scrambled
if (!Cache.Instance.PriorityTargets.Any(pt => pt.IsWarpScramblingMe))
{
// Are we done with this mission pocket?
launch &= !Cache.Instance.IsMissionPocketDone;
// If above minimums
launch &= Cache.Instance.DirectEve.ActiveShip.ShieldPercentage >= Settings.Instance.DroneMinimumShieldPct;
launch &= Cache.Instance.DirectEve.ActiveShip.ArmorPercentage >= Settings.Instance.DroneMinimumArmorPct;
launch &= Cache.Instance.DirectEve.ActiveShip.CapacitorPercentage >= Settings.Instance.DroneMinimumCapacitorPct;
// yes if there are targets to kill
launch &= Cache.Instance.TargetedBy.Count(e => !e.IsSentry && e.CategoryId == (int)CategoryID.Entity && e.IsNpc && !e.IsContainer && e.GroupId != (int)Group.LargeCollidableStructure && e.Distance < Settings.Instance.DroneControlRange) > 0;
// If drones get aggro'd within 30 seconds, then wait (5 * _recallCount + 5) seconds since the last recall
if (_lastLaunch < _lastRecall && _lastRecall.Subtract(_lastLaunch).TotalSeconds < 30)
{
if (_lastRecall.AddSeconds(5 * _recallCount + 5) < DateTime.Now)
{
// Increase recall count and allow the launch
_recallCount++;
// Never let _recallCount go above 5
if (_recallCount > 5)
_recallCount = 5;
}
else
{
// Do not launch the drones until the delay has passed
launch = false;
}
}
else // Drones have been out for more then 30s
_recallCount = 0;
}
if (launch)
{
// Reset launch tries
_launchTries = 0;
_lastLaunch = DateTime.Now;
State = DroneState.Launch;
}
break;
case DroneState.Launch:
// Launch all drones
recall = false;
_launchTimeout = DateTime.Now;
Cache.Instance.DirectEve.ActiveShip.LaunchAllDrones();
State = DroneState.Launching;
break;
case DroneState.Launching:
// We haven't launched anything yet, keep waiting
if (Cache.Instance.ActiveDrones.Count() == 0)
{
if (DateTime.Now.Subtract(_launchTimeout).TotalSeconds > 10)
{
// Relaunch if tries < 10
if (_launchTries < 10)
{
_launchTries++;
State = DroneState.Launch;
break;
}
else
State = DroneState.OutOfDrones;
}
break;
}
// Are we done launching?
if (_lastDroneCount == Cache.Instance.ActiveDrones.Count())
State = DroneState.Fighting;
break;
case DroneState.OutOfDrones:
//if (DateTime.Now.Subtract(_launchTimeout).TotalSeconds > 1000)
//{
// State = DroneState.WaitingForTargets;
//}
break;
case DroneState.Fighting:
// Should we recall our drones? This is a possible list of reasons why we should
// Are we done (for now) ?
if (Cache.Instance.TargetedBy.Count(e => !e.IsSentry && e.IsNpc && e.Distance < Settings.Instance.DroneControlRange) == 0)
{
Logging.Log("Drones: Recalling drones because no NPC is targeting us within dronerange");
recall = true;
}
if (Cache.Instance.IsMissionPocketDone)
{
Logging.Log("Drones: Recalling drones because we are done with this pocket.");
recall = true;
}
else if (_shieldPctTotal > GetShieldPctTotal())
{
Logging.Log("Drones: Recalling drones because we have lost shields! [Old: " + _shieldPctTotal.ToString("N2") + "][New: " + GetShieldPctTotal().ToString("N2") + "]");
recall = true;
}
else if (_armorPctTotal > GetArmorPctTotal())
{
Logging.Log("Drones: Recalling drones because we have lost armor! [Old:" + _armorPctTotal.ToString("N2") + "][New: " + GetArmorPctTotal().ToString("N2") + "]");
recall = true;
}
else if (_structurePctTotal > GetStructurePctTotal())
{
Logging.Log("Drones: Recalling drones because we have lost structure! [Old:" + _structurePctTotal.ToString("N2") + "][New: " + GetStructurePctTotal().ToString("N2") + "]");
recall = true;
}
else if (Cache.Instance.ActiveDrones.Count() < _lastDroneCount)
{
// Did we lose a drone? (this should be covered by total's as well though)
Logging.Log("Drones: Recalling drones because we have lost a drone! [Old:" + _lastDroneCount + "][New: " + Cache.Instance.ActiveDrones.Count() + "]");
recall = true;
}
else
{
// Default to long range recall
var lowShieldWarning = Settings.Instance.LongRangeDroneRecallShieldPct;
var lowArmorWarning = Settings.Instance.LongRangeDroneRecallArmorPct;
var lowCapWarning = Settings.Instance.LongRangeDroneRecallCapacitorPct;
if (Cache.Instance.ActiveDrones.Average(d => d.Distance) < (Settings.Instance.DroneControlRange/2d))
{
lowShieldWarning = Settings.Instance.DroneRecallShieldPct;
lowArmorWarning = Settings.Instance.DroneRecallArmorPct;
lowCapWarning = Settings.Instance.DroneRecallCapacitorPct;
}
if (Cache.Instance.DirectEve.ActiveShip.ShieldPercentage < lowShieldWarning)
{
Logging.Log("Drones: Recalling drones due to shield [" + Cache.Instance.DirectEve.ActiveShip.ShieldPercentage + "%] below [" + lowShieldWarning + "%] minimum");
recall = true;
}
else if (Cache.Instance.DirectEve.ActiveShip.ArmorPercentage < lowArmorWarning)
{
Logging.Log("Drones: Recalling drones due to armor [" + Cache.Instance.DirectEve.ActiveShip.ArmorPercentage + "%] below [" + lowArmorWarning + "%] minimum");
recall = true;
}
else if (Cache.Instance.DirectEve.ActiveShip.CapacitorPercentage < lowCapWarning)
{
Logging.Log("Drones: Recalling drones due to capacitor [" + Cache.Instance.DirectEve.ActiveShip.CapacitorPercentage + "%] below [" + lowCapWarning + "%] minimum");
recall = true;
}
}
if (Cache.Instance.ActiveDrones.Count() == 0)
{
Logging.Log("Drones: Apparently we have lost all our drones");
recall = true;
}
else
{
var isPanicking = false;
isPanicking |= Cache.Instance.DirectEve.ActiveShip.ShieldPercentage < Settings.Instance.MinimumShieldPct;
isPanicking |= Cache.Instance.DirectEve.ActiveShip.ArmorPercentage < Settings.Instance.MinimumArmorPct;
isPanicking |= Cache.Instance.DirectEve.ActiveShip.CapacitorPercentage < Settings.Instance.MinimumCapacitorPct;
if (Cache.Instance.PriorityTargets.Any(pt => pt.IsWarpScramblingMe) && recall)
{
Logging.Log("Drones: Overriding drone recall, we are scrambled!");
recall = false;
}
}
// Recall or engage
if (recall)
State = DroneState.Recalling;
else
{
EngageTarget();
// We lost a drone and did not recall, assume panicking and launch (if any) additional drones
if (Cache.Instance.ActiveDrones.Count() < _lastDroneCount)
State = DroneState.Launch;
}
break;
case DroneState.Recalling:
// Are we done?
if (Cache.Instance.ActiveDrones.Count() == 0)
{
_lastRecall = DateTime.Now;
recall = false;
State = DroneState.WaitingForTargets;
break;
}
// Give recall command every 5 seconds
if (DateTime.Now.Subtract(_lastRecallCommand).TotalSeconds > 5)
{
Cache.Instance.DirectEve.ExecuteCommand(DirectCmd.CmdDronesReturnToBay);
_lastRecallCommand = DateTime.Now;
}
break;
}
// Update health values
_shieldPctTotal = GetShieldPctTotal();
_armorPctTotal = GetArmorPctTotal();
_structurePctTotal = GetStructurePctTotal();
_lastDroneCount = Cache.Instance.ActiveDrones.Count();
}
}
} | 0 | 0.832792 | 1 | 0.832792 | game-dev | MEDIA | 0.988807 | game-dev | 0.950845 | 1 | 0.950845 |
flipperdevices/flipperzero-good-faps | 6,091 | air_arkanoid/levels/level_settings.c | #include "level_settings.h"
/**** Menu ****/
typedef enum {
Sound = 0,
ShowFPS,
Back,
} MenuOption;
typedef struct {
int selected;
} MenuContext;
static void menu_update(Entity* entity, GameManager* manager, void* context) {
UNUSED(entity);
MenuContext* menu_context = context;
GameContext* game_context = game_manager_game_context_get(manager);
InputState input = game_manager_input_get(manager);
if(input.pressed & GameKeyUp || input.pressed & GameKeyDown || input.pressed & GameKeyOk) {
game_sound_play(game_context, &sequence_sound_menu);
}
if(input.pressed & GameKeyBack) {
game_manager_next_level_set(manager, game_context->levels.menu);
}
if(input.pressed & GameKeyUp) {
menu_context->selected--;
if(menu_context->selected < Sound) {
menu_context->selected = Back;
}
}
if(input.pressed & GameKeyDown) {
menu_context->selected++;
if(menu_context->selected > Back) {
menu_context->selected = Sound;
}
}
if(input.pressed & GameKeyOk) {
switch(menu_context->selected) {
case Sound:
game_switch_sound(game_context);
break;
case ShowFPS:
game_switch_show_fps(game_context);
break;
case Back:
game_manager_next_level_set(manager, game_context->levels.menu);
break;
default:
break;
}
}
if(input.pressed & GameKeyRight || input.pressed & GameKeyLeft) {
switch(menu_context->selected) {
case Sound:
game_switch_sound(game_context);
break;
case ShowFPS:
game_switch_show_fps(game_context);
break;
default:
break;
}
}
}
static void menu_render(Entity* entity, GameManager* manager, Canvas* canvas, void* context) {
UNUSED(entity);
MenuContext* menu_context = context;
GameContext* game_context = game_manager_game_context_get(manager);
FuriString* line = furi_string_alloc_set("Sound: ");
if(menu_context->selected == Sound) {
furi_string_set(line, ">Sound: ");
}
if(game_context->settings.sound) {
furi_string_cat(line, "On");
} else {
furi_string_cat(line, "Off");
}
canvas_draw_str_aligned(
canvas, 64 + 3, 18, AlignLeft, AlignCenter, furi_string_get_cstr(line));
furi_string_set(line, "FPS: ");
if(menu_context->selected == ShowFPS) {
furi_string_set(line, ">FPS: ");
}
if(game_context->settings.show_fps) {
furi_string_cat(line, "On");
} else {
furi_string_cat(line, "Off");
}
canvas_draw_str_aligned(
canvas, 64 + 3, 33, AlignLeft, AlignCenter, furi_string_get_cstr(line));
furi_string_set(line, "Back");
if(menu_context->selected == Back) {
furi_string_set(line, ">Back");
}
canvas_draw_str_aligned(
canvas, 64 + 3, 48, AlignLeft, AlignCenter, furi_string_get_cstr(line));
furi_string_free(line);
}
static const EntityDescription menu_desc = {
.start = NULL,
.stop = NULL,
.update = menu_update,
.render = menu_render,
.collision = NULL,
.event = NULL,
.context_size = sizeof(MenuContext),
};
/**** IMU Debug ****/
typedef struct {
float pitch;
float roll;
float yaw;
bool imu_present;
} IMUDebugContext;
static void imu_debug_start(Entity* self, GameManager* manager, void* ctx) {
UNUSED(self);
IMUDebugContext* context = ctx;
context->pitch = 0;
context->roll = 0;
context->yaw = 0;
GameContext* game_context = game_manager_game_context_get(manager);
context->imu_present = game_context->imu_present;
}
static void imu_debug_update(Entity* self, GameManager* manager, void* ctx) {
UNUSED(self);
IMUDebugContext* context = (IMUDebugContext*)ctx;
GameContext* game_context = game_manager_game_context_get(manager);
if(game_context->imu_present) {
context->pitch = imu_pitch_get(game_context->imu);
context->roll = imu_roll_get(game_context->imu);
context->yaw = imu_yaw_get(game_context->imu);
}
}
static void imu_debug_render(Entity* self, GameManager* manager, Canvas* canvas, void* context) {
UNUSED(self);
UNUSED(manager);
Vector pos = {32, 32};
const float radius = 30;
const float max_angle = 45;
const float bubble_radius = 3;
canvas_draw_circle(canvas, pos.x, pos.y, radius);
IMUDebugContext* imu_debug_context = context;
if(imu_debug_context->imu_present) {
const float pitch = -CLAMP(imu_debug_context->pitch, max_angle, -max_angle);
const float roll = -CLAMP(imu_debug_context->roll, max_angle, -max_angle);
const float max_bubble_len = radius - bubble_radius - 2;
Vector ball = {
max_bubble_len * (pitch / max_angle),
max_bubble_len * (roll / max_angle),
};
float bubble_len = sqrtf(ball.x * ball.x + ball.y * ball.y);
if(bubble_len > max_bubble_len) {
ball.x = ball.x * max_bubble_len / bubble_len;
ball.y = ball.y * max_bubble_len / bubble_len;
}
ball = vector_add(pos, ball);
canvas_draw_disc(canvas, ball.x, ball.y, bubble_radius);
} else {
canvas_draw_str_aligned(canvas, pos.x, pos.y + 1, AlignCenter, AlignCenter, "No IMU");
}
}
static const EntityDescription imu_debug_desc = {
.start = imu_debug_start,
.stop = NULL,
.update = imu_debug_update,
.render = imu_debug_render,
.collision = NULL,
.event = NULL,
.context_size = sizeof(IMUDebugContext),
};
/**** Level ****/
static void level_settings_alloc(Level* level, GameManager* manager, void* ctx) {
UNUSED(ctx);
UNUSED(manager);
level_add_entity(level, &imu_debug_desc);
level_add_entity(level, &menu_desc);
}
const LevelBehaviour level_settings = {
.alloc = level_settings_alloc,
.free = NULL,
.start = NULL,
.stop = NULL,
.context_size = 0,
}; | 0 | 0.794135 | 1 | 0.794135 | game-dev | MEDIA | 0.470177 | game-dev | 0.780515 | 1 | 0.780515 |
id-Software/DOOM-3-BFG | 8,077 | neo/d3xp/menus/MenuScreen_Shell_NewGame.cpp | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "../../idLib/precompiled.h"
#include "../Game_local.h"
const static int NUM_NEW_GAME_OPTIONS = 8;
/*
========================
idMenuScreen_Shell_NewGame::Initialize
========================
*/
void idMenuScreen_Shell_NewGame::Initialize( idMenuHandler * data ) {
idMenuScreen::Initialize( data );
if ( data != NULL ) {
menuGUI = data->GetGUI();
}
SetSpritePath( "menuNewGame" );
options = new (TAG_SWF) idMenuWidget_DynamicList();
idList< idList< idStr, TAG_IDLIB_LIST_MENU >, TAG_IDLIB_LIST_MENU > menuOptions;
idList< idStr > option;
option.Append( "#str_swf_doom3" ); // doom 3
menuOptions.Append( option );
option.Clear();
option.Append( "#str_swf_resurrection" ); // resurrection of evil
menuOptions.Append( option );
option.Clear();
option.Append( "#str_swf_lost_episodes" ); // lost episodes
menuOptions.Append( option );
options->SetListData( menuOptions );
options->SetNumVisibleOptions( NUM_NEW_GAME_OPTIONS );
options->SetSpritePath( GetSpritePath(), "info", "options" );
options->SetWrappingAllowed( true );
while ( options->GetChildren().Num() < NUM_NEW_GAME_OPTIONS ) {
idMenuWidget_Button * const buttonWidget = new (TAG_SWF) idMenuWidget_Button();
buttonWidget->AddEventAction( WIDGET_EVENT_PRESS ).Set( WIDGET_ACTION_PRESS_FOCUSED, options->GetChildren().Num() );
buttonWidget->Initialize( data );
options->AddChild( buttonWidget );
}
options->Initialize( data );
AddChild( options );
btnBack = new (TAG_SWF) idMenuWidget_Button();
btnBack->Initialize( data );
btnBack->SetLabel( "#str_swf_campaign" );
btnBack->SetSpritePath( GetSpritePath(), "info", "btnBack" );
btnBack->AddEventAction( WIDGET_EVENT_PRESS ).Set( WIDGET_ACTION_GO_BACK );
AddChild( btnBack );
options->AddEventAction( WIDGET_EVENT_SCROLL_DOWN ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_SCROLL_DOWN_START_REPEATER, WIDGET_EVENT_SCROLL_DOWN ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_UP ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_SCROLL_UP_START_REPEATER, WIDGET_EVENT_SCROLL_UP ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_DOWN_RELEASE ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_STOP_REPEATER, WIDGET_EVENT_SCROLL_DOWN_RELEASE ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_UP_RELEASE ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_STOP_REPEATER, WIDGET_EVENT_SCROLL_UP_RELEASE ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_DOWN_LSTICK ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_SCROLL_DOWN_START_REPEATER, WIDGET_EVENT_SCROLL_DOWN_LSTICK ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_UP_LSTICK ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_SCROLL_UP_START_REPEATER, WIDGET_EVENT_SCROLL_UP_LSTICK ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_DOWN_LSTICK_RELEASE ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_STOP_REPEATER, WIDGET_EVENT_SCROLL_DOWN_LSTICK_RELEASE ) );
options->AddEventAction( WIDGET_EVENT_SCROLL_UP_LSTICK_RELEASE ).Set( new (TAG_SWF) idWidgetActionHandler( options, WIDGET_ACTION_EVENT_STOP_REPEATER, WIDGET_EVENT_SCROLL_UP_LSTICK_RELEASE ) );
}
/*
========================
idMenuScreen_Shell_NewGame::Update
========================
*/
void idMenuScreen_Shell_NewGame::Update() {
if ( menuData != NULL ) {
idMenuWidget_CommandBar * cmdBar = menuData->GetCmdBar();
if ( cmdBar != NULL ) {
cmdBar->ClearAllButtons();
idMenuWidget_CommandBar::buttonInfo_t * buttonInfo;
buttonInfo = cmdBar->GetButton( idMenuWidget_CommandBar::BUTTON_JOY2 );
if ( menuData->GetPlatform() != 2 ) {
buttonInfo->label = "#str_00395";
}
buttonInfo->action.Set( WIDGET_ACTION_GO_BACK );
buttonInfo = cmdBar->GetButton( idMenuWidget_CommandBar::BUTTON_JOY1 );
if ( menuData->GetPlatform() != 2 ) {
buttonInfo->label = "#str_SWF_SELECT";
}
buttonInfo->action.Set( WIDGET_ACTION_PRESS_FOCUSED );
}
}
idSWFScriptObject & root = GetSWFObject()->GetRootObject();
if ( BindSprite( root ) ) {
idSWFTextInstance * heading = GetSprite()->GetScriptObject()->GetNestedText( "info", "txtHeading" );
if ( heading != NULL ) {
heading->SetText( "#str_02207" ); // NEW GAME
heading->SetStrokeInfo( true, 0.75f, 1.75f );
}
idSWFSpriteInstance * gradient = GetSprite()->GetScriptObject()->GetNestedSprite( "info", "gradient" );
if ( gradient != NULL && heading != NULL ) {
gradient->SetXPos( heading->GetTextLength() );
}
}
if ( btnBack != NULL ) {
btnBack->BindSprite( root );
}
idMenuScreen::Update();
}
/*
========================
idMenuScreen_Shell_NewGame::ShowScreen
========================
*/
void idMenuScreen_Shell_NewGame::ShowScreen( const mainMenuTransition_t transitionType ) {
idMenuScreen::ShowScreen( transitionType );
}
/*
========================
idMenuScreen_Shell_NewGame::HideScreen
========================
*/
void idMenuScreen_Shell_NewGame::HideScreen( const mainMenuTransition_t transitionType ) {
idMenuScreen::HideScreen( transitionType );
}
/*
========================
idMenuScreen_Shell_NewGame::HandleAction h
========================
*/
bool idMenuScreen_Shell_NewGame::HandleAction( idWidgetAction & action, const idWidgetEvent & event, idMenuWidget * widget, bool forceHandled ) {
if ( menuData != NULL ) {
if ( menuData->ActiveScreen() != SHELL_AREA_NEW_GAME ) {
return false;
}
}
widgetAction_t actionType = action.GetType();
const idSWFParmList & parms = action.GetParms();
switch ( actionType ) {
case WIDGET_ACTION_GO_BACK: {
if ( menuData != NULL ) {
menuData->SetNextScreen( SHELL_AREA_CAMPAIGN, MENU_TRANSITION_SIMPLE );
}
return true;
}
case WIDGET_ACTION_PRESS_FOCUSED: {
if ( options == NULL ) {
return true;
}
int selectionIndex = options->GetViewIndex();
if ( parms.Num() == 1 ) {
selectionIndex = parms[0].ToInteger();
}
if ( selectionIndex != options->GetFocusIndex() ) {
options->SetViewIndex( selectionIndex );
options->SetFocusIndex( selectionIndex );
}
idMenuHandler_Shell * shell = dynamic_cast< idMenuHandler_Shell * >( menuData );
if ( shell != NULL ) {
shell->SetNewGameType( selectionIndex );
menuData->SetNextScreen( SHELL_AREA_DIFFICULTY, MENU_TRANSITION_SIMPLE );
}
return true;
}
}
return idMenuWidget::HandleAction( action, event, widget, forceHandled );
} | 0 | 0.983304 | 1 | 0.983304 | game-dev | MEDIA | 0.97717 | game-dev | 0.920188 | 1 | 0.920188 |
bagaturchess/Bagatur | 3,863 | PGNProcessor/src/bagaturchess/tools/pgn/impl/PGNInputStream.java | /*
* BagaturChess (UCI chess engine and tools)
* Copyright (C) 2005 Krasimir I. Topchiyski (k_topchiyski@yahoo.com)
*
* Open Source project location: http://sourceforge.net/projects/bagaturchess/develop
* SVN repository https://bagaturchess.svn.sourceforge.net/svnroot/bagaturchess
*
* This file is part of BagaturChess program.
*
* BagaturChess is open software: you can redistribute it and/or modify
* it under the terms of the Eclipse Public License version 1.0 as published by
* the Eclipse Foundation.
*
* BagaturChess 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
* Eclipse Public License for more details.
*
* You should have received a copy of the Eclipse Public License version 1.0
* along with BagaturChess. If not, see <http://www.eclipse.org/legal/epl-v10.html/>.
*
*/
package bagaturchess.tools.pgn.impl;
/**
*
* PGN grammar can be found here
* http://www.very-best.de/pgn-spec.htm.
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class PGNInputStream {
//FileInputStream to PGN file
InputStream mNativeIS = null;
//Internal string buffer for current game
StringBuffer mPGNGameBuf = new StringBuffer();
private int mBufferSize = Math.max( PGNConstants.PGN_GAME_PREFIX.length,
PGNConstants.PGN_GAME_SUFFIX.length );
private byte[] mTempByteBuffer = new byte[ mBufferSize ];
private PGNGameCounter mPGNGameCounter;
private static void shiftLeftByteArray( byte[] aCurBuf, int aNewByte ) {
for ( int i = 0; i < aCurBuf.length - 1; i++ ) {
aCurBuf[ i ] = aCurBuf[ i + 1 ];
}
aCurBuf[ aCurBuf.length - 1 ] = ( byte ) aNewByte;
}
//Tests if aCurBuf ands with aTemplateArr
//Size of aTemplateArr is less then aCurBuf
private static boolean endsWithArray( byte[] aCurBuf, int[] aTemplateArr ) {
boolean result = false;
int sizeDif = aCurBuf.length - aTemplateArr.length;
for ( int i = aTemplateArr.length - 1; i >= 0; i-- ) {
if ( ( byte ) aTemplateArr[ i ] != aCurBuf[ i + sizeDif ] )
break;
if ( i == 0 )
//after 'result = true' possibly break for-cycle
result = true;
}
return result;
}
public PGNInputStream( InputStream pPGNFileInputStream) {
mNativeIS = pPGNFileInputStream;
}
public PGNInputStream( String pAbsoluteFilePathToPGN)
throws FileNotFoundException {
mNativeIS = new FileInputStream( pAbsoluteFilePathToPGN );
}
public PGNGame readGame()
throws IOException {
PGNGame tempPGNGame = null;
int tempInt;
boolean isInGame = false;
mPGNGameBuf.delete( 0, mPGNGameBuf.length() );
while ( ( tempInt = mNativeIS.read() ) != -1 ) {
shiftLeftByteArray( mTempByteBuffer, tempInt );
if ( endsWithArray( mTempByteBuffer, PGNConstants.PGN_GAME_PREFIX ) ) {
mPGNGameBuf.append( ( char ) PGNConstants.PGN_GAME_PREFIX[ PGNConstants.PGN_GAME_PREFIX.length - 1 ] );
isInGame = true;
} else if ( endsWithArray( mTempByteBuffer, PGNConstants.PGN_GAME_SUFFIX )
&& !endsWithArray( mTempByteBuffer, PGNConstants.PGN_GAME_DELIM ) ) {
if ( isInGame ) {
mPGNGameBuf.delete( mPGNGameBuf.length() - PGNConstants.PGN_GAME_SUFFIX.length + 1, mPGNGameBuf.length() );
break;
}
} else {
if ( isInGame ) {
mPGNGameBuf.append( ( char ) tempInt );
}
}
}
if ( mPGNGameBuf.length() > 0 ) {
tempPGNGame = new PGNGame();
tempPGNGame.load(mPGNGameBuf);
}
return tempPGNGame;
}
public void close()
throws IOException {
mNativeIS.close();
}
}
| 0 | 0.823502 | 1 | 0.823502 | game-dev | MEDIA | 0.538139 | game-dev | 0.883914 | 1 | 0.883914 |
project-topaz/topaz | 1,210 | scripts/globals/spells/bluemagic/feather_barrier.lua | -----------------------------------------
-- Spell: Feather Barrier
-- Enhances evasion
-- Spell cost: 29 MP
-- Monster Type: Birds
-- Spell Type: Magical (Wind)
-- Blue Magic Points: 2
-- Stat Bonus: None
-- Level: 56
-- Casting Time: 2 seconds
-- Recast Time: 120 seconds
-- Duration: 30 Seconds
--
-- Combos: Resist Gravity
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local typeEffect = tpz.effect.EVASION_BOOST
local power = 10
local duration = 30
if (caster:hasStatusEffect(tpz.effect.DIFFUSION)) then
local diffMerit = caster:getMerit(tpz.merit.DIFFUSION)
if (diffMerit > 0) then
duration = duration + (duration/100)* diffMerit
end
caster:delStatusEffect(tpz.effect.DIFFUSION)
end
if (target:addStatusEffect(typeEffect, power, 0, duration) == false) then
spell:setMsg(tpz.msg.basic.MAGIC_NO_EFFECT)
end
return typeEffect
end
| 0 | 0.56968 | 1 | 0.56968 | game-dev | MEDIA | 0.970308 | game-dev | 0.971799 | 1 | 0.971799 |
air/encounter | 5,146 | js/State.js | 'use strict';
var State = {};
State.ATTRACT = 'attract';
State.WAIT_FOR_ENEMY = 'waitForEnemy';
State.COMBAT = 'combat';
State.WAIT_FOR_PORTAL = 'waitForPortal';
State.WARP = 'warp';
State.PLAYER_HIT = 'playerHit';
State.GAME_OVER = 'gameOver';
State.current = null;
State.actors = new Actors();
State.enemiesRemaining = null;
State.isPaused = false;
State.score = 0;
// called once at startup. Go into our first state
State.init = function()
{
Attract.init();
Grid.init(); // reads the camera draw distance and sizes the Grid.viewport
Ground.init();
Sound.init();
Display.init();
Player.init();
Missile.init();
Camera.init();
Controls.init();
Touch.init(); // FIXME depends on Controls.init
Radar.init();
Portal.init();
WhitePortal.init();
BlackPortal.init();
Warp.init();
GUI.init(); // depends on Controls.init
Indicators.init();
Explode.init();
Level.init();
State.setupAttract();
};
// Setup a new combat level, either on game start or moving out of warp.
// Level number is optional; by default rely on the state in Level.
State.initLevel = function(levelNumber)
{
if (levelNumber)
{
Level.set(levelNumber);
}
log('initialising level ' + Level.number);
Display.setSkyColour(Level.current.skyColor);
Display.setHorizonColour(Level.current.horizonColor);
Camera.useFirstPersonMode();
Controls.useEncounterControls();
Player.resetPosition();
Grid.reset();
Enemy.reset();
Indicators.reset();
State.actors.reset();
State.resetEnemyCounter();
};
State.resetEnemyCounter = function()
{
State.enemiesRemaining = Level.current.enemyCount;
};
State.setupAttract = function()
{
State.current = State.ATTRACT;
log('State: ' + State.current);
Attract.show();
};
State.setupWaitForEnemy = function()
{
State.current = State.WAIT_FOR_ENEMY;
log('State: ' + State.current);
Display.update();
Enemy.startSpawnTimer();
};
State.setupWaitForPortal = function()
{
State.current = State.WAIT_FOR_PORTAL;
log('State: ' + State.current);
Display.update();
BlackPortal.startSpawnTimer();
};
State.setupCombat = function()
{
State.current = State.COMBAT;
log('State: ' + State.current);
};
State.setupPlayerHitInCombat = function()
{
State.current = State.PLAYER_HIT;
log('State: ' + State.current);
Display.showShieldLossStatic();
if (Player.shieldsLeft < 0)
{
State.setupGameOver();
}
};
State.setupGameOver = function()
{
State.current = State.GAME_OVER;
log('State: ' + State.current);
Display.setText('GAME OVER. PRESS FIRE');
};
State.setupWarp = function()
{
State.current = State.WARP;
log('State: ' + State.current);
Warp.setup();
};
State.enemyKilled = function()
{
log('enemy destroyed');
State.enemiesRemaining -= 1;
if (State.enemiesRemaining > 0)
{
State.setupWaitForEnemy();
}
else
{
State.setupWaitForPortal();
}
};
State.updateWaitForEnemy = function(timeDeltaMillis)
{
State.performNormalLevelUpdates(timeDeltaMillis);
Enemy.spawnIfReady();
Radar.update();
};
State.updateWaitForPortal = function(timeDeltaMillis)
{
State.performNormalLevelUpdates(timeDeltaMillis);
BlackPortal.update(timeDeltaMillis);
Radar.update();
TWEEN.update();
};
State.updateCombat = function(timeDeltaMillis)
{
State.performNormalLevelUpdates(timeDeltaMillis);
Radar.update();
Indicators.update(); // needed for flickering effects only
TWEEN.update(); // white portal animations
};
State.updatePlayerHitInCombat = function(timeDeltaMillis)
{
Display.updateShieldLossStatic();
if (clock.oldTime > (Player.timeOfDeath + Encounter.PLAYER_DEATH_TIMEOUT_MS))
{
Display.hideShieldLossStatic();
Indicators.reset();
State.actors.reset();
Player.isAlive = true;
State.setupWaitForEnemy();
}
};
State.updateGameOver = function(timeDeltaMillis)
{
if (Keys.shooting && clock.oldTime > (Player.timeOfDeath + Encounter.PLAYER_DEATH_TIMEOUT_MS))
{
Display.hideShieldLossStatic();
Keys.shooting = false;
State.setupAttract();
}
};
State.performNormalLevelUpdates = function(timeDeltaMillis)
{
Controls.current.update(timeDeltaMillis);
Player.update(timeDeltaMillis);
Camera.update(timeDeltaMillis);
Grid.update();
// update non-Player game State.actors
if (!State.isPaused)
{
State.actors.update(timeDeltaMillis);
Controls.interpretKeys(timeDeltaMillis);
}
};
// called from util.js
function update(timeDeltaMillis)
{
switch (State.current)
{
case State.ATTRACT:
Attract.update(timeDeltaMillis);
break;
case State.COMBAT:
State.updateCombat(timeDeltaMillis);
break;
case State.WAIT_FOR_PORTAL:
State.updateWaitForPortal(timeDeltaMillis);
break;
case State.WAIT_FOR_ENEMY:
State.updateWaitForEnemy(timeDeltaMillis);
break;
case State.WARP:
Warp.update(timeDeltaMillis);
break;
case State.PLAYER_HIT:
State.updatePlayerHitInCombat(timeDeltaMillis);
break;
case State.GAME_OVER:
State.updateGameOver(timeDeltaMillis);
break;
default:
panic('unknown state: ', State.current);
}
}
| 0 | 0.818807 | 1 | 0.818807 | game-dev | MEDIA | 0.975007 | game-dev | 0.828862 | 1 | 0.828862 |
crawl/crawl | 11,790 | crawl-ref/source/attitude-change.cc | /**
* @file
* @brief Monster attitude changing due to religion.
**/
#include "AppHdr.h"
#include "attitude-change.h"
#include <sstream>
#include "act-iter.h"
#include "branch.h"
#include "coordit.h"
#include "database.h"
#include "env.h"
#include "fineff.h"
#include "god-abil.h"
#include "god-companions.h"
#include "god-passive.h" // passive_t::convert_orcs
#include "libutil.h"
#include "message.h"
#include "mon-behv.h"
#include "mon-death.h"
#include "mon-tentacle.h"
#include "religion.h"
#include "state.h"
#include "travel.h"
// Called whenever an already existing monster changes its attitude, possibly
// temporarily.
void mons_att_changed(monster* mon)
{
const mon_attitude_type att = mon->temp_attitude();
const monster_type mc = mons_base_type(*mon);
if (mons_is_tentacle_head(mc)
|| mons_is_solo_tentacle(mc))
{
for (monster_iterator mi; mi; ++mi)
if (mi->is_child_tentacle_of(mon))
{
mi->attitude = att;
if (!mons_is_solo_tentacle(mc))
{
for (monster_iterator connect; connect; ++connect)
{
if (connect->is_child_tentacle_of(*mi))
connect->attitude = att;
}
}
// It's almost always flipping between hostile and friendly;
// enslaving a pacified starspawn is still a shock.
mi->stop_constricting_all();
}
}
if (mon->attitude == ATT_HOSTILE
&& (mons_is_god_gift(*mon, GOD_BEOGH)
|| mons_is_god_gift(*mon, GOD_YREDELEMNUL)))
{
remove_companion(mon);
}
if (mon->has_ench(ENCH_AWAKEN_FOREST))
mon->del_ench(ENCH_AWAKEN_FOREST);
mon->remove_summons(true);
}
static void _jiyva_convert_slime(monster* slime);
static void _fedhas_neutralise_plant(monster* plant);
/// For followers of Beogh, decide whether orcs will join you.
void beogh_follower_convert(monster* mons, bool orc_hit)
{
if (you.religion != GOD_BEOGH || crawl_state.game_is_arena())
return;
const bool deathbed = orc_hit || !mons->alive();
if (!will_have_passive(passive_t::convert_orcs)
|| mons_genus(mons->type) != MONS_ORC
|| mons->is_summoned()
|| mons->is_shapeshifter()
|| testbits(mons->flags, MF_ATT_CHANGE_ATTEMPT)
|| mons->friendly()
|| mons->has_ench(ENCH_FIRE_CHAMPION)
|| mons->flags & MF_APOSTLE_BAND
// If marked for vengeance, only deathbed conversion.
|| (mons->has_ench(ENCH_VENGEANCE_TARGET) && !deathbed))
{
return;
}
mons->flags |= MF_ATT_CHANGE_ATTEMPT;
const int hd = mons->get_experience_level();
if (have_passive(passive_t::convert_orcs)
&& random2(you.piety() / 15) + random2(4 + you.experience_level / 3)
> random2(hd) + hd + random2(5))
{
conv_t ctype = conv_t::sight;
if (deathbed)
{
ctype = mons->has_ench(ENCH_VENGEANCE_TARGET) ? conv_t::vengeance
: conv_t::deathbed;
}
beogh_convert_orc(mons, ctype);
stop_running();
}
}
void slime_convert(monster* mons)
{
if (have_passive(passive_t::neutral_slimes) && mons_is_slime(*mons)
&& !mons->neutral()
&& !mons->friendly()
&& !mons->is_shapeshifter()
&& !testbits(mons->flags, MF_ATT_CHANGE_ATTEMPT))
{
mons->flags |= MF_ATT_CHANGE_ATTEMPT;
_jiyva_convert_slime(mons);
stop_running();
}
}
void fedhas_neutralise(monster* mons)
{
if (have_passive(passive_t::friendly_plants)
&& mons->attitude == ATT_HOSTILE
&& fedhas_neutralises(*mons)
&& !testbits(mons->flags, MF_ATT_CHANGE_ATTEMPT))
{
_fedhas_neutralise_plant(mons);
mons->flags |= MF_ATT_CHANGE_ATTEMPT;
del_exclude(mons->pos());
}
}
// Make divine summons disappear on penance or excommunication from the god in question
void dismiss_god_summons(god_type god)
{
for (monster_iterator mi; mi; ++mi)
{
if (is_follower(**mi)
&& mi->is_summoned()
&& mons_is_god_gift(**mi, god))
{
// The monster disappears.
monster_die(**mi, KILL_RESET, NON_MONSTER);
}
}
}
static void _print_converted_orc_speech(const string& key,
monster* mon,
msg_channel_type channel)
{
string msg = getSpeakString("beogh_converted_orc_" + key);
if (!msg.empty())
{
msg = do_mon_str_replacements(msg, *mon);
strip_channel_prefix(msg, channel);
mprf(channel, "%s", msg.c_str());
}
}
// Orcs may turn good neutral when encountering followers of Beogh and leave you alone
void beogh_convert_orc(monster* orc, conv_t conv)
{
ASSERT(orc); // XXX: change to monster &orc
ASSERT(mons_genus(orc->type) == MONS_ORC);
switch (conv)
{
case conv_t::vengeance_follower:
_print_converted_orc_speech("reaction_battle_follower", orc,
MSGCH_FRIEND_ENCHANT);
_print_converted_orc_speech("speech_vengeance_follower", orc,
MSGCH_TALK);
break;
case conv_t::vengeance:
_print_converted_orc_speech("reaction_battle", orc,
MSGCH_FRIEND_ENCHANT);
_print_converted_orc_speech("speech_vengeance", orc,
MSGCH_TALK);
break;
case conv_t::deathbed_follower:
_print_converted_orc_speech("reaction_battle_follower", orc,
MSGCH_FRIEND_ENCHANT);
_print_converted_orc_speech("speech_battle_follower", orc,
MSGCH_TALK);
break;
case conv_t::deathbed:
_print_converted_orc_speech("reaction_battle", orc,
MSGCH_FRIEND_ENCHANT);
_print_converted_orc_speech("speech_battle", orc, MSGCH_TALK);
break;
case conv_t::sight:
_print_converted_orc_speech("reaction_sight", orc,
MSGCH_FRIEND_ENCHANT);
if (!one_chance_in(3))
_print_converted_orc_speech("speech_sight", orc, MSGCH_TALK);
break;
case conv_t::resurrection:
_print_converted_orc_speech("resurrection", orc,
MSGCH_FRIEND_ENCHANT);
break;
}
// Count as having gotten vengeance.
if (orc->has_ench(ENCH_VENGEANCE_TARGET))
{
orc->del_ench(ENCH_VENGEANCE_TARGET);
beogh_progress_vengeance();
}
if (!orc->alive())
{
orc->hit_points = max(1, random_range(orc->max_hit_points / 5,
orc->max_hit_points * 2 / 5));
}
record_monster_defeat(orc, KILL_PACIFIED);
mons_pacify(*orc, ATT_GOOD_NEUTRAL, true);
// put the actual revival at the end of the round
// But first verify that the orc is still here! (They may have left the
// floor immediately when pacified!)
if ((conv == conv_t::deathbed
|| conv == conv_t::deathbed_follower
|| conv == conv_t::vengeance
|| conv == conv_t::vengeance_follower)
&& orc->alive())
{
avoided_death_fineff::schedule(orc);
}
}
static void _fedhas_neutralise_plant(monster* plant)
{
if (!plant
|| !fedhas_neutralises(*plant)
|| plant->attitude != ATT_HOSTILE
|| testbits(plant->flags, MF_ATT_CHANGE_ATTEMPT))
{
return;
}
plant->attitude = ATT_GOOD_NEUTRAL;
plant->flags |= MF_WAS_NEUTRAL;
mons_att_changed(plant);
}
static void _jiyva_convert_slime(monster* slime)
{
ASSERT(slime); // XXX: change to monster &slime
ASSERT(mons_is_slime(*slime));
behaviour_event(slime, ME_ALERT);
if (you.can_see(*slime))
{
if (mons_genus(slime->type) == MONS_FLOATING_EYE)
{
mprf(MSGCH_GOD, "%s stares at you suspiciously for a moment, "
"then relaxes.",
slime->name(DESC_THE).c_str());
}
else
{
mprf(MSGCH_GOD, "%s trembles before you.",
slime->name(DESC_THE).c_str());
}
}
slime->attitude = ATT_GOOD_NEUTRAL;
slime->flags |= MF_WAS_NEUTRAL;
mons_make_god_gift(*slime, GOD_JIYVA);
mons_att_changed(slime);
}
void gozag_set_bribe(monster* traitor)
{
// Try to bribe the monster.
const int bribability = gozag_type_bribable(traitor->type);
if (bribability <= 0 || traitor->friendly() || traitor->is_summoned())
return;
const monster* leader = traitor->get_band_leader();
if (leader)
{
if (leader->has_ench(ENCH_FRIENDLY_BRIBED)
|| leader->props.exists(FRIENDLY_BRIBE_KEY))
{
traitor->props[FRIENDLY_BRIBE_KEY].get_bool() = true;
}
else if (leader->has_ench(ENCH_NEUTRAL_BRIBED)
|| leader->props.exists(NEUTRAL_BRIBE_KEY))
{
traitor->props[NEUTRAL_BRIBE_KEY].get_bool() = true;
}
}
else if (x_chance_in_y(bribability, GOZAG_MAX_BRIBABILITY))
{
// Sometimes get permanent followers
if (one_chance_in(3))
traitor->props[FRIENDLY_BRIBE_KEY].get_bool() = true;
else
traitor->props[NEUTRAL_BRIBE_KEY].get_bool() = true;
}
}
void gozag_check_bribe(monster* traitor)
{
branch_type branch = gozag_fixup_branch(you.where_are_you);
if (branch_bribe[branch] == 0)
return; // Do nothing if branch isn't currently bribed.
const int base_cost = max(1, exp_value(*traitor, true, true) / 20);
int cost = 0;
string msg;
if (traitor->props.exists(FRIENDLY_BRIBE_KEY))
{
traitor->props.erase(FRIENDLY_BRIBE_KEY);
traitor->add_ench(mon_enchant(ENCH_FRIENDLY_BRIBED, 0, 0,
INFINITE_DURATION));
msg = getSpeakString(traitor->name(DESC_DBNAME, true)
+ " Gozag permabribe");
if (msg.empty())
msg = getSpeakString("Gozag permabribe");
// Actual allies deduct more gold.
cost = 2 * base_cost;
}
else if (traitor->props.exists(NEUTRAL_BRIBE_KEY))
{
traitor->props.erase(NEUTRAL_BRIBE_KEY);
traitor->add_ench(ENCH_NEUTRAL_BRIBED);
msg = getSpeakString(traitor->name(DESC_DBNAME, true)
+ " Gozag bribe");
if (msg.empty())
msg = getSpeakString("Gozag bribe");
cost = base_cost;
}
if (!msg.empty())
{
msg_channel_type channel = MSGCH_FRIEND_ENCHANT;
msg = do_mon_str_replacements(msg, *traitor);
strip_channel_prefix(msg, channel);
mprf(channel, "%s", msg.c_str());
// !msg.empty means a monster was bribed.
gozag_deduct_bribe(branch, cost);
}
}
void gozag_break_bribe(monster* victim)
{
ASSERT(victim); // XXX: change to monster &victim
if (!victim->has_ench(ENCH_NEUTRAL_BRIBED)
&& !victim->has_ench(ENCH_FRIENDLY_BRIBED))
{
return;
}
// Un-bribe the victim.
victim->del_ench(ENCH_NEUTRAL_BRIBED);
victim->del_ench(ENCH_FRIENDLY_BRIBED);
// Make other nearby bribed monsters un-bribed, too.
for (monster_iterator mi; mi; ++mi)
if (mi->can_see(*victim))
gozag_break_bribe(*mi);
}
// Conversions and bribes.
void do_conversions(monster* target)
{
beogh_follower_convert(target);
gozag_check_bribe(target);
}
| 0 | 0.86788 | 1 | 0.86788 | game-dev | MEDIA | 0.876806 | game-dev | 0.95166 | 1 | 0.95166 |
narknon/WukongB1 | 3,195 | Source/b1/Public/BGUTamerBase.h | #pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "UObject/NoExportTypes.h"
#include "GameFramework/Actor.h"
#include "ETamerType.h"
#include "TamerHighLODRootMeshConfig.h"
#include "BGUTamerBase.generated.h"
class APlayerState;
class UCapsuleComponent;
class USkeletalMeshComponent;
class UStaticMeshComponent;
UCLASS(Blueprintable)
class B1_API ABGUTamerBase : public AActor {
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
bool bBeginPlayFromLevelStreaming;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Replicated, meta=(AllowPrivateAccess=true))
APlayerState* SpawnedPlayerState;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Replicated, meta=(AllowPrivateAccess=true))
FString SpawnedTamerGuid;
UPROPERTY(EditAnywhere, Replicated, Transient, meta=(AllowPrivateAccess=true))
ETamerType TamerType;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
bool bEnableShowLODMesh;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 LODMaxDistance;
private:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Instanced, meta=(AllowPrivateAccess=true))
USkeletalMeshComponent* Mesh;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Instanced, meta=(AllowPrivateAccess=true))
UCapsuleComponent* CapsuleComponent;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Instanced, meta=(AllowPrivateAccess=true))
UStaticMeshComponent* LowLODMesh;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Export, Transient, meta=(AllowPrivateAccess=true))
TSet<USkeletalMeshComponent*> HighLODMeshComponents;
public:
ABGUTamerBase(const FObjectInitializer& ObjectInitializer);
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
UFUNCTION(BlueprintCallable)
void SetLODMeshVisible(bool invisible);
protected:
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void PostInitializeComponentsCS();
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void OnPropertyChanged(const FString& MemberName, const FString& PropertyName);
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void OnPostEditMove(bool bFisnish);
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void OnConstructionCS(const FTransform& Transform);
UFUNCTION(BlueprintCallable, BlueprintNativeEvent)
bool GetHighLODMeshConfig(FTamerHighLODRootMeshConfig& OutMeshConfig);
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
bool GetActorGuidCS(FString& OutActorGuid) const;
public:
UFUNCTION(BlueprintCallable, BlueprintPure)
bool GetActorGuid(FString& OutActorGuid) const;
protected:
UFUNCTION(BlueprintCallable)
void ForceRefreshDetailView();
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void BeginPlayCS();
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void ApplyWorldOffsetCS(const FVector& InOffset, bool bWorldShift);
};
| 0 | 0.913503 | 1 | 0.913503 | game-dev | MEDIA | 0.900741 | game-dev | 0.555188 | 1 | 0.555188 |
proletariatgames/unreal.hx | 1,692 | Haxe/Externs/UE4.21/unreal/moviescenetracks/UMovieSceneEventTrack.hx | /**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal.moviescenetracks;
/**
WARNING: This type was defined as MinimalAPI on its declaration. Because of that, its properties/methods are inaccessible
Implements a movie scene track that triggers discrete events during playback.
**/
@:umodule("MovieSceneTracks")
@:glueCppIncludes("Tracks/MovieSceneEventTrack.h")
@:uextern @:uclass extern class UMovieSceneEventTrack extends unreal.moviescene.UMovieSceneNameableTrack {
/**
Defines a list of object bindings on which to trigger the events in this track. When empty, events will trigger in the default event contexts for the playback environment (such as the level blueprint, or widget).
**/
@:uproperty public var EventReceivers : unreal.TArray<unreal.moviescene.FMovieSceneObjectBindingID>;
/**
Defines where in the evaluation to trigger events
**/
@:uproperty public var EventPosition : unreal.moviescenetracks.EFireEventsAtPosition;
/**
If events should be fired when passed playing the sequence backwards.
**/
@:uproperty public var bFireEventsWhenBackwards : Bool;
/**
If events should be fired when passed playing the sequence forwards.
**/
@:uproperty public var bFireEventsWhenForwards : Bool;
}
| 0 | 0.613672 | 1 | 0.613672 | game-dev | MEDIA | 0.944044 | game-dev | 0.569207 | 1 | 0.569207 |
rsdn/nemerle | 4,702 | snippets/power-race.n | // REFERENCE: Curses.dll
class Car
{
mutable pos : int;
mutable crash_state : bool;
win : Curses.Window;
dc : Curses.DrawingContext;
public this (dc : Curses.DrawingContext)
{
this.dc = dc;
win = dc.Window;
pos = win.Width / 2;
}
public Draw () : void
{
mutable y = win.Height - 7;
def down (off) { dc.Move (pos + off, y); ++y; };
dc.ChangeAttrs (Curses.Attributes.A_BOLD, true);
if (crash_state) {
dc.Foreground = Curses.Color.Yellow;
crash_state = false;
} else
dc.Foreground = Curses.Color.Red;
down (2); dc.Add ("/\\");
down (2); dc.Add ("||");
down (1); dc.Add ("/");
dc.Foreground = Curses.Color.Blue; dc.Add ("%%");
dc.Foreground = Curses.Color.Red; dc.Add("\\");
down (0); dc.Add ("[]");
dc.Foreground = Curses.Color.Yellow; dc.Add ("%%");
dc.Foreground = Curses.Color.Red; dc.Add("[]");
down (2); dc.Add ("~~");
}
public Move (ch : int) : void
{
def move (delta) {
def new_pos = pos + delta;
when (new_pos >= 0 && new_pos <= win.Width - 7) {
pos = new_pos;
Game.NeedUpdate ();
}
};
if (ch == Curses.KeyCode.KEY_LEFT || ch == ('z' :> int) || ch == ('Z' :> int))
move (-1)
else if (ch == Curses.KeyCode.KEY_RIGHT || ch == ('x' :> int) || ch == ('X' :> int))
move (+1)
else
();
}
public Position : int
{
get { pos + 3 - win.Width / 2 }
}
public Crash () : void
{
crash_state = true;
}
}
class Road
{
mutable current : int;
mutable target : int;
mutable last_update : int;
mutable forward_pos : int;
positions : array [int];
dc : Curses.DrawingContext;
public this (dc : Curses.DrawingContext)
{
this.dc = dc;
positions = array (dc.Window.Height);
forward_pos = 1000000000;
}
public Draw () : void
{
def draw_line (y) {
dc.Move (positions [y] + dc.Window.Width / 2 - 20, y);
dc.Foreground = Curses.Color.Green;
dc.Add ("..----=");
dc.Foreground = Curses.Color.White;
dc.Add ("#");
dc.Foreground = Curses.Color.Black;
dc.Add ("###########");
when (((y + forward_pos) / 3) % 2 == 1)
dc.Foreground = Curses.Color.White;
dc.Add ("#");
dc.Foreground = Curses.Color.Black;
dc.Add ("###########");
dc.Foreground = Curses.Color.White;
dc.Add ("#");
dc.Foreground = Curses.Color.Green;
dc.Add ("=----..");
};
dc.ChangeAttrs (Curses.Attributes.A_BOLD, true);
for (mutable i = 0; i < dc.Window.Height; ++i)
draw_line (i);
}
public Update () : void
{
when (Game.Ticks - last_update > 5) {
last_update = Game.Ticks;
when (current == target)
target = Game.Random.Next (-30, 30);
when (Game.Random.Next (3) == 0)
if (current < target)
++current
else
--current;
for (mutable i = positions.Length - 1; i > 0; --i)
positions[i] = positions[i - 1];
positions[0] = current;
--forward_pos;
Game.NeedUpdate ();
}
}
public CrashTest (pos : int) : bool
{
def y = dc.Window.Height - 3;
def x = positions[y];
(pos < x - 12 || pos > x + 12)
}
}
module Game {
Main () : void
{
Init ();
MainLoop ();
}
Init () : void
{
unless (Curses.Setup.Initialize ())
throw System.Exception ("cannot initialize curses");
Curses.Misc.ReportTimeouts = true;
Curses.Misc.DockCursor ();
def time = System.TimeSpan (100000L); // 1/100th sec
def t = Curses.Timeout (time, time);
t.Fired += (fun (_, _) { ++Ticks; });
Random = System.Random ();
dc = Curses.Window.Screen.DrawingContext;
car = Car (dc);
road = Road (dc);
need_update = true;
}
public NeedUpdate () : void
{
need_update = true;
}
MaybeUpdate () : void
{
when (need_update) {
need_update = false;
dc.Clear ();
road.Draw ();
car.Draw ();
dc.Refresh ();
}
}
MainLoop () : void
{
def handle_char (ch) {
car.Move (ch);
when (ch == 27 || ch == ('q' :> int) || ch == ('Q' :> int))
Curses.Setup.Exit (0);
when (ch != -1 && ch != 0) {
handle_char (Curses.Input.GetNextChar ());
}
};
while (true) {
MaybeUpdate ();
handle_char (Curses.Input.GetNextChar ());
road.Update ();
when (road.CrashTest (car.Position))
car.Crash ();
}
}
// private variables
mutable need_update : bool;
mutable car : Car;
mutable road : Road;
mutable dc : Curses.DrawingContext;
public mutable Ticks : int;
public mutable Random : System.Random;
}
| 0 | 0.897749 | 1 | 0.897749 | game-dev | MEDIA | 0.645152 | game-dev | 0.854306 | 1 | 0.854306 |
AdamEisfeld/PhyKit | 27,177 | PhyKit-shared/bullet/BulletCollision/Gimpact/btGImpactShape.h | /*! \file btGImpactShape.h
\author Francisco Len Njera
*/
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef GIMPACT_SHAPE_H
#define GIMPACT_SHAPE_H
#include "BulletCollision/CollisionShapes/btCollisionShape.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "BulletCollision/CollisionShapes/btStridingMeshInterface.h"
#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
#include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
#include "BulletCollision/CollisionShapes/btConcaveShape.h"
#include "BulletCollision/CollisionShapes/btTetrahedronShape.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btMatrix3x3.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btGImpactQuantizedBvh.h" // box tree class
//! declare Quantized trees, (you can change to float based trees)
typedef btGImpactQuantizedBvh btGImpactBoxSet;
enum eGIMPACT_SHAPE_TYPE
{
CONST_GIMPACT_COMPOUND_SHAPE = 0,
CONST_GIMPACT_TRIMESH_SHAPE_PART,
CONST_GIMPACT_TRIMESH_SHAPE
};
//! Helper class for tetrahedrons
class btTetrahedronShapeEx : public btBU_Simplex1to4
{
public:
btTetrahedronShapeEx()
{
m_numVertices = 4;
}
SIMD_FORCE_INLINE void setVertices(
const btVector3& v0, const btVector3& v1,
const btVector3& v2, const btVector3& v3)
{
m_vertices[0] = v0;
m_vertices[1] = v1;
m_vertices[2] = v2;
m_vertices[3] = v3;
recalcLocalAabb();
}
};
//! Base class for gimpact shapes
class btGImpactShapeInterface : public btConcaveShape
{
protected:
btAABB m_localAABB;
bool m_needs_update;
btVector3 localScaling;
btGImpactBoxSet m_box_set; // optionally boxset
//! use this function for perfofm refit in bounding boxes
//! use this function for perfofm refit in bounding boxes
virtual void calcLocalAABB()
{
lockChildShapes();
if (m_box_set.getNodeCount() == 0)
{
m_box_set.buildSet();
}
else
{
m_box_set.update();
}
unlockChildShapes();
m_localAABB = m_box_set.getGlobalBox();
}
public:
btGImpactShapeInterface()
{
m_shapeType = GIMPACT_SHAPE_PROXYTYPE;
m_localAABB.invalidate();
m_needs_update = true;
localScaling.setValue(1.f, 1.f, 1.f);
}
//! performs refit operation
/*!
Updates the entire Box set of this shape.
\pre postUpdate() must be called for attemps to calculating the box set, else this function
will does nothing.
\post if m_needs_update == true, then it calls calcLocalAABB();
*/
SIMD_FORCE_INLINE void updateBound()
{
if (!m_needs_update) return;
calcLocalAABB();
m_needs_update = false;
}
//! If the Bounding box is not updated, then this class attemps to calculate it.
/*!
\post Calls updateBound() for update the box set.
*/
void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
{
btAABB transformedbox = m_localAABB;
transformedbox.appy_transform(t);
aabbMin = transformedbox.m_min;
aabbMax = transformedbox.m_max;
}
//! Tells to this object that is needed to refit the box set
virtual void postUpdate()
{
m_needs_update = true;
}
//! Obtains the local box, which is the global calculated box of the total of subshapes
SIMD_FORCE_INLINE const btAABB& getLocalBox()
{
return m_localAABB;
}
virtual int getShapeType() const
{
return GIMPACT_SHAPE_PROXYTYPE;
}
/*!
\post You must call updateBound() for update the box set.
*/
virtual void setLocalScaling(const btVector3& scaling)
{
localScaling = scaling;
postUpdate();
}
virtual const btVector3& getLocalScaling() const
{
return localScaling;
}
virtual void setMargin(btScalar margin)
{
m_collisionMargin = margin;
int i = getNumChildShapes();
while (i--)
{
btCollisionShape* child = getChildShape(i);
child->setMargin(margin);
}
m_needs_update = true;
}
//! Subshape member functions
//!@{
//! Base method for determinig which kind of GIMPACT shape we get
virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const = 0;
//! gets boxset
SIMD_FORCE_INLINE const btGImpactBoxSet* getBoxSet() const
{
return &m_box_set;
}
//! Determines if this class has a hierarchy structure for sorting its primitives
SIMD_FORCE_INLINE bool hasBoxSet() const
{
if (m_box_set.getNodeCount() == 0) return false;
return true;
}
//! Obtains the primitive manager
virtual const btPrimitiveManagerBase* getPrimitiveManager() const = 0;
//! Gets the number of children
virtual int getNumChildShapes() const = 0;
//! if true, then its children must get transforms.
virtual bool childrenHasTransform() const = 0;
//! Determines if this shape has triangles
virtual bool needsRetrieveTriangles() const = 0;
//! Determines if this shape has tetrahedrons
virtual bool needsRetrieveTetrahedrons() const = 0;
virtual void getBulletTriangle(int prim_index, btTriangleShapeEx& triangle) const = 0;
virtual void getBulletTetrahedron(int prim_index, btTetrahedronShapeEx& tetrahedron) const = 0;
//! call when reading child shapes
virtual void lockChildShapes() const
{
}
virtual void unlockChildShapes() const
{
}
//! if this trimesh
SIMD_FORCE_INLINE void getPrimitiveTriangle(int index, btPrimitiveTriangle& triangle) const
{
getPrimitiveManager()->get_primitive_triangle(index, triangle);
}
//! Retrieves the bound from a child
/*!
*/
virtual void getChildAabb(int child_index, const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
{
btAABB child_aabb;
getPrimitiveManager()->get_primitive_box(child_index, child_aabb);
child_aabb.appy_transform(t);
aabbMin = child_aabb.m_min;
aabbMax = child_aabb.m_max;
}
//! Gets the children
virtual btCollisionShape* getChildShape(int index) = 0;
//! Gets the child
virtual const btCollisionShape* getChildShape(int index) const = 0;
//! Gets the children transform
virtual btTransform getChildTransform(int index) const = 0;
//! Sets the children transform
/*!
\post You must call updateBound() for update the box set.
*/
virtual void setChildTransform(int index, const btTransform& transform) = 0;
//!@}
//! virtual method for ray collision
virtual void rayTest(const btVector3& rayFrom, const btVector3& rayTo, btCollisionWorld::RayResultCallback& resultCallback) const
{
(void)rayFrom;
(void)rayTo;
(void)resultCallback;
}
//! Function for retrieve triangles.
/*!
It gives the triangles in local space
*/
virtual void processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const
{
(void)callback;
(void)aabbMin;
(void)aabbMax;
}
//! Function for retrieve triangles.
/*!
It gives the triangles in local space
*/
virtual void processAllTrianglesRay(btTriangleCallback* /*callback*/, const btVector3& /*rayFrom*/, const btVector3& /*rayTo*/) const
{
}
//!@}
};
//! btGImpactCompoundShape allows to handle multiple btCollisionShape objects at once
/*!
This class only can manage Convex subshapes
*/
class btGImpactCompoundShape : public btGImpactShapeInterface
{
public:
//! compound primitive manager
class CompoundPrimitiveManager : public btPrimitiveManagerBase
{
public:
virtual ~CompoundPrimitiveManager() {}
btGImpactCompoundShape* m_compoundShape;
CompoundPrimitiveManager(const CompoundPrimitiveManager& compound)
: btPrimitiveManagerBase()
{
m_compoundShape = compound.m_compoundShape;
}
CompoundPrimitiveManager(btGImpactCompoundShape* compoundShape)
{
m_compoundShape = compoundShape;
}
CompoundPrimitiveManager()
{
m_compoundShape = NULL;
}
virtual bool is_trimesh() const
{
return false;
}
virtual int get_primitive_count() const
{
return (int)m_compoundShape->getNumChildShapes();
}
virtual void get_primitive_box(int prim_index, btAABB& primbox) const
{
btTransform prim_trans;
if (m_compoundShape->childrenHasTransform())
{
prim_trans = m_compoundShape->getChildTransform(prim_index);
}
else
{
prim_trans.setIdentity();
}
const btCollisionShape* shape = m_compoundShape->getChildShape(prim_index);
shape->getAabb(prim_trans, primbox.m_min, primbox.m_max);
}
virtual void get_primitive_triangle(int prim_index, btPrimitiveTriangle& triangle) const
{
btAssert(0);
(void)prim_index;
(void)triangle;
}
};
protected:
CompoundPrimitiveManager m_primitive_manager;
btAlignedObjectArray<btTransform> m_childTransforms;
btAlignedObjectArray<btCollisionShape*> m_childShapes;
public:
btGImpactCompoundShape(bool children_has_transform = true)
{
(void)children_has_transform;
m_primitive_manager.m_compoundShape = this;
m_box_set.setPrimitiveManager(&m_primitive_manager);
}
virtual ~btGImpactCompoundShape()
{
}
//! if true, then its children must get transforms.
virtual bool childrenHasTransform() const
{
if (m_childTransforms.size() == 0) return false;
return true;
}
//! Obtains the primitive manager
virtual const btPrimitiveManagerBase* getPrimitiveManager() const
{
return &m_primitive_manager;
}
//! Obtains the compopund primitive manager
SIMD_FORCE_INLINE CompoundPrimitiveManager* getCompoundPrimitiveManager()
{
return &m_primitive_manager;
}
//! Gets the number of children
virtual int getNumChildShapes() const
{
return m_childShapes.size();
}
//! Use this method for adding children. Only Convex shapes are allowed.
void addChildShape(const btTransform& localTransform, btCollisionShape* shape)
{
btAssert(shape->isConvex());
m_childTransforms.push_back(localTransform);
m_childShapes.push_back(shape);
}
//! Use this method for adding children. Only Convex shapes are allowed.
void addChildShape(btCollisionShape* shape)
{
btAssert(shape->isConvex());
m_childShapes.push_back(shape);
}
//! Gets the children
virtual btCollisionShape* getChildShape(int index)
{
return m_childShapes[index];
}
//! Gets the children
virtual const btCollisionShape* getChildShape(int index) const
{
return m_childShapes[index];
}
//! Retrieves the bound from a child
/*!
*/
virtual void getChildAabb(int child_index, const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
{
if (childrenHasTransform())
{
m_childShapes[child_index]->getAabb(t * m_childTransforms[child_index], aabbMin, aabbMax);
}
else
{
m_childShapes[child_index]->getAabb(t, aabbMin, aabbMax);
}
}
//! Gets the children transform
virtual btTransform getChildTransform(int index) const
{
btAssert(m_childTransforms.size() == m_childShapes.size());
return m_childTransforms[index];
}
//! Sets the children transform
/*!
\post You must call updateBound() for update the box set.
*/
virtual void setChildTransform(int index, const btTransform& transform)
{
btAssert(m_childTransforms.size() == m_childShapes.size());
m_childTransforms[index] = transform;
postUpdate();
}
//! Determines if this shape has triangles
virtual bool needsRetrieveTriangles() const
{
return false;
}
//! Determines if this shape has tetrahedrons
virtual bool needsRetrieveTetrahedrons() const
{
return false;
}
virtual void getBulletTriangle(int prim_index, btTriangleShapeEx& triangle) const
{
(void)prim_index;
(void)triangle;
btAssert(0);
}
virtual void getBulletTetrahedron(int prim_index, btTetrahedronShapeEx& tetrahedron) const
{
(void)prim_index;
(void)tetrahedron;
btAssert(0);
}
//! Calculates the exact inertia tensor for this shape
virtual void calculateLocalInertia(btScalar mass, btVector3& inertia) const;
virtual const char* getName() const
{
return "GImpactCompound";
}
virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const
{
return CONST_GIMPACT_COMPOUND_SHAPE;
}
};
//! This class manages a sub part of a mesh supplied by the btStridingMeshInterface interface.
/*!
- Simply create this shape by passing the btStridingMeshInterface to the constructor btGImpactMeshShapePart, then you must call updateBound() after creating the mesh
- When making operations with this shape, you must call <b>lock</b> before accessing to the trimesh primitives, and then call <b>unlock</b>
- You can handle deformable meshes with this shape, by calling postUpdate() every time when changing the mesh vertices.
*/
class btGImpactMeshShapePart : public btGImpactShapeInterface
{
public:
//! Trimesh primitive manager
/*!
Manages the info from btStridingMeshInterface object and controls the Lock/Unlock mechanism
*/
class TrimeshPrimitiveManager : public btPrimitiveManagerBase
{
public:
btScalar m_margin;
btStridingMeshInterface* m_meshInterface;
btVector3 m_scale;
int m_part;
int m_lock_count;
const unsigned char* vertexbase;
int numverts;
PHY_ScalarType type;
int stride;
const unsigned char* indexbase;
int indexstride;
int numfaces;
PHY_ScalarType indicestype;
TrimeshPrimitiveManager()
{
m_meshInterface = NULL;
m_part = 0;
m_margin = 0.01f;
m_scale = btVector3(1.f, 1.f, 1.f);
m_lock_count = 0;
vertexbase = 0;
numverts = 0;
stride = 0;
indexbase = 0;
indexstride = 0;
numfaces = 0;
}
TrimeshPrimitiveManager(const TrimeshPrimitiveManager& manager)
: btPrimitiveManagerBase()
{
m_meshInterface = manager.m_meshInterface;
m_part = manager.m_part;
m_margin = manager.m_margin;
m_scale = manager.m_scale;
m_lock_count = 0;
vertexbase = 0;
numverts = 0;
stride = 0;
indexbase = 0;
indexstride = 0;
numfaces = 0;
}
TrimeshPrimitiveManager(
btStridingMeshInterface* meshInterface, int part)
{
m_meshInterface = meshInterface;
m_part = part;
m_scale = m_meshInterface->getScaling();
m_margin = 0.1f;
m_lock_count = 0;
vertexbase = 0;
numverts = 0;
stride = 0;
indexbase = 0;
indexstride = 0;
numfaces = 0;
}
virtual ~TrimeshPrimitiveManager() {}
void lock()
{
if (m_lock_count > 0)
{
m_lock_count++;
return;
}
m_meshInterface->getLockedReadOnlyVertexIndexBase(
&vertexbase, numverts,
type, stride, &indexbase, indexstride, numfaces, indicestype, m_part);
m_lock_count = 1;
}
void unlock()
{
if (m_lock_count == 0) return;
if (m_lock_count > 1)
{
--m_lock_count;
return;
}
m_meshInterface->unLockReadOnlyVertexBase(m_part);
vertexbase = NULL;
m_lock_count = 0;
}
virtual bool is_trimesh() const
{
return true;
}
virtual int get_primitive_count() const
{
return (int)numfaces;
}
SIMD_FORCE_INLINE int get_vertex_count() const
{
return (int)numverts;
}
SIMD_FORCE_INLINE void get_indices(int face_index, unsigned int& i0, unsigned int& i1, unsigned int& i2) const
{
if (indicestype == PHY_SHORT)
{
unsigned short* s_indices = (unsigned short*)(indexbase + face_index * indexstride);
i0 = s_indices[0];
i1 = s_indices[1];
i2 = s_indices[2];
}
else if (indicestype == PHY_INTEGER)
{
unsigned int* i_indices = (unsigned int*)(indexbase + face_index * indexstride);
i0 = i_indices[0];
i1 = i_indices[1];
i2 = i_indices[2];
}
else
{
btAssert(indicestype == PHY_UCHAR);
unsigned char* i_indices = (unsigned char*)(indexbase + face_index * indexstride);
i0 = i_indices[0];
i1 = i_indices[1];
i2 = i_indices[2];
}
}
SIMD_FORCE_INLINE void get_vertex(unsigned int vertex_index, btVector3& vertex) const
{
if (type == PHY_DOUBLE)
{
double* dvertices = (double*)(vertexbase + vertex_index * stride);
vertex[0] = btScalar(dvertices[0] * m_scale[0]);
vertex[1] = btScalar(dvertices[1] * m_scale[1]);
vertex[2] = btScalar(dvertices[2] * m_scale[2]);
}
else
{
float* svertices = (float*)(vertexbase + vertex_index * stride);
vertex[0] = svertices[0] * m_scale[0];
vertex[1] = svertices[1] * m_scale[1];
vertex[2] = svertices[2] * m_scale[2];
}
}
virtual void get_primitive_box(int prim_index, btAABB& primbox) const
{
btPrimitiveTriangle triangle;
get_primitive_triangle(prim_index, triangle);
primbox.calc_from_triangle_margin(
triangle.m_vertices[0],
triangle.m_vertices[1], triangle.m_vertices[2], triangle.m_margin);
}
virtual void get_primitive_triangle(int prim_index, btPrimitiveTriangle& triangle) const
{
unsigned int indices[3];
get_indices(prim_index, indices[0], indices[1], indices[2]);
get_vertex(indices[0], triangle.m_vertices[0]);
get_vertex(indices[1], triangle.m_vertices[1]);
get_vertex(indices[2], triangle.m_vertices[2]);
triangle.m_margin = m_margin;
}
SIMD_FORCE_INLINE void get_bullet_triangle(int prim_index, btTriangleShapeEx& triangle) const
{
unsigned int indices[3];
get_indices(prim_index, indices[0], indices[1], indices[2]);
get_vertex(indices[0], triangle.m_vertices1[0]);
get_vertex(indices[1], triangle.m_vertices1[1]);
get_vertex(indices[2], triangle.m_vertices1[2]);
triangle.setMargin(m_margin);
}
};
protected:
TrimeshPrimitiveManager m_primitive_manager;
public:
btGImpactMeshShapePart()
{
m_box_set.setPrimitiveManager(&m_primitive_manager);
}
btGImpactMeshShapePart(btStridingMeshInterface* meshInterface, int part);
virtual ~btGImpactMeshShapePart();
//! if true, then its children must get transforms.
virtual bool childrenHasTransform() const
{
return false;
}
//! call when reading child shapes
virtual void lockChildShapes() const;
virtual void unlockChildShapes() const;
//! Gets the number of children
virtual int getNumChildShapes() const
{
return m_primitive_manager.get_primitive_count();
}
//! Gets the children
virtual btCollisionShape* getChildShape(int index)
{
(void)index;
btAssert(0);
return NULL;
}
//! Gets the child
virtual const btCollisionShape* getChildShape(int index) const
{
(void)index;
btAssert(0);
return NULL;
}
//! Gets the children transform
virtual btTransform getChildTransform(int index) const
{
(void)index;
btAssert(0);
return btTransform();
}
//! Sets the children transform
/*!
\post You must call updateBound() for update the box set.
*/
virtual void setChildTransform(int index, const btTransform& transform)
{
(void)index;
(void)transform;
btAssert(0);
}
//! Obtains the primitive manager
virtual const btPrimitiveManagerBase* getPrimitiveManager() const
{
return &m_primitive_manager;
}
SIMD_FORCE_INLINE TrimeshPrimitiveManager* getTrimeshPrimitiveManager()
{
return &m_primitive_manager;
}
virtual void calculateLocalInertia(btScalar mass, btVector3& inertia) const;
virtual const char* getName() const
{
return "GImpactMeshShapePart";
}
virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const
{
return CONST_GIMPACT_TRIMESH_SHAPE_PART;
}
//! Determines if this shape has triangles
virtual bool needsRetrieveTriangles() const
{
return true;
}
//! Determines if this shape has tetrahedrons
virtual bool needsRetrieveTetrahedrons() const
{
return false;
}
virtual void getBulletTriangle(int prim_index, btTriangleShapeEx& triangle) const
{
m_primitive_manager.get_bullet_triangle(prim_index, triangle);
}
virtual void getBulletTetrahedron(int prim_index, btTetrahedronShapeEx& tetrahedron) const
{
(void)prim_index;
(void)tetrahedron;
btAssert(0);
}
SIMD_FORCE_INLINE int getVertexCount() const
{
return m_primitive_manager.get_vertex_count();
}
SIMD_FORCE_INLINE void getVertex(int vertex_index, btVector3& vertex) const
{
m_primitive_manager.get_vertex(vertex_index, vertex);
}
SIMD_FORCE_INLINE void setMargin(btScalar margin)
{
m_primitive_manager.m_margin = margin;
postUpdate();
}
SIMD_FORCE_INLINE btScalar getMargin() const
{
return m_primitive_manager.m_margin;
}
virtual void setLocalScaling(const btVector3& scaling)
{
m_primitive_manager.m_scale = scaling;
postUpdate();
}
virtual const btVector3& getLocalScaling() const
{
return m_primitive_manager.m_scale;
}
SIMD_FORCE_INLINE int getPart() const
{
return (int)m_primitive_manager.m_part;
}
virtual void processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const;
virtual void processAllTrianglesRay(btTriangleCallback* callback, const btVector3& rayFrom, const btVector3& rayTo) const;
};
//! This class manages a mesh supplied by the btStridingMeshInterface interface.
/*!
Set of btGImpactMeshShapePart parts
- Simply create this shape by passing the btStridingMeshInterface to the constructor btGImpactMeshShape, then you must call updateBound() after creating the mesh
- You can handle deformable meshes with this shape, by calling postUpdate() every time when changing the mesh vertices.
*/
class btGImpactMeshShape : public btGImpactShapeInterface
{
btStridingMeshInterface* m_meshInterface;
protected:
btAlignedObjectArray<btGImpactMeshShapePart*> m_mesh_parts;
void buildMeshParts(btStridingMeshInterface* meshInterface)
{
for (int i = 0; i < meshInterface->getNumSubParts(); ++i)
{
btGImpactMeshShapePart* newpart = new btGImpactMeshShapePart(meshInterface, i);
m_mesh_parts.push_back(newpart);
}
}
//! use this function for perfofm refit in bounding boxes
virtual void calcLocalAABB()
{
m_localAABB.invalidate();
int i = m_mesh_parts.size();
while (i--)
{
m_mesh_parts[i]->updateBound();
m_localAABB.merge(m_mesh_parts[i]->getLocalBox());
}
}
public:
btGImpactMeshShape(btStridingMeshInterface* meshInterface)
{
m_meshInterface = meshInterface;
buildMeshParts(meshInterface);
}
virtual ~btGImpactMeshShape()
{
int i = m_mesh_parts.size();
while (i--)
{
btGImpactMeshShapePart* part = m_mesh_parts[i];
delete part;
}
m_mesh_parts.clear();
}
btStridingMeshInterface* getMeshInterface()
{
return m_meshInterface;
}
const btStridingMeshInterface* getMeshInterface() const
{
return m_meshInterface;
}
int getMeshPartCount() const
{
return m_mesh_parts.size();
}
btGImpactMeshShapePart* getMeshPart(int index)
{
return m_mesh_parts[index];
}
const btGImpactMeshShapePart* getMeshPart(int index) const
{
return m_mesh_parts[index];
}
virtual void setLocalScaling(const btVector3& scaling)
{
localScaling = scaling;
int i = m_mesh_parts.size();
while (i--)
{
btGImpactMeshShapePart* part = m_mesh_parts[i];
part->setLocalScaling(scaling);
}
m_needs_update = true;
}
virtual void setMargin(btScalar margin)
{
m_collisionMargin = margin;
int i = m_mesh_parts.size();
while (i--)
{
btGImpactMeshShapePart* part = m_mesh_parts[i];
part->setMargin(margin);
}
m_needs_update = true;
}
//! Tells to this object that is needed to refit all the meshes
virtual void postUpdate()
{
int i = m_mesh_parts.size();
while (i--)
{
btGImpactMeshShapePart* part = m_mesh_parts[i];
part->postUpdate();
}
m_needs_update = true;
}
virtual void calculateLocalInertia(btScalar mass, btVector3& inertia) const;
//! Obtains the primitive manager
virtual const btPrimitiveManagerBase* getPrimitiveManager() const
{
btAssert(0);
return NULL;
}
//! Gets the number of children
virtual int getNumChildShapes() const
{
btAssert(0);
return 0;
}
//! if true, then its children must get transforms.
virtual bool childrenHasTransform() const
{
btAssert(0);
return false;
}
//! Determines if this shape has triangles
virtual bool needsRetrieveTriangles() const
{
btAssert(0);
return false;
}
//! Determines if this shape has tetrahedrons
virtual bool needsRetrieveTetrahedrons() const
{
btAssert(0);
return false;
}
virtual void getBulletTriangle(int prim_index, btTriangleShapeEx& triangle) const
{
(void)prim_index;
(void)triangle;
btAssert(0);
}
virtual void getBulletTetrahedron(int prim_index, btTetrahedronShapeEx& tetrahedron) const
{
(void)prim_index;
(void)tetrahedron;
btAssert(0);
}
//! call when reading child shapes
virtual void lockChildShapes() const
{
btAssert(0);
}
virtual void unlockChildShapes() const
{
btAssert(0);
}
//! Retrieves the bound from a child
/*!
*/
virtual void getChildAabb(int child_index, const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
{
(void)child_index;
(void)t;
(void)aabbMin;
(void)aabbMax;
btAssert(0);
}
//! Gets the children
virtual btCollisionShape* getChildShape(int index)
{
(void)index;
btAssert(0);
return NULL;
}
//! Gets the child
virtual const btCollisionShape* getChildShape(int index) const
{
(void)index;
btAssert(0);
return NULL;
}
//! Gets the children transform
virtual btTransform getChildTransform(int index) const
{
(void)index;
btAssert(0);
return btTransform();
}
//! Sets the children transform
/*!
\post You must call updateBound() for update the box set.
*/
virtual void setChildTransform(int index, const btTransform& transform)
{
(void)index;
(void)transform;
btAssert(0);
}
virtual eGIMPACT_SHAPE_TYPE getGImpactShapeType() const
{
return CONST_GIMPACT_TRIMESH_SHAPE;
}
virtual const char* getName() const
{
return "GImpactMesh";
}
virtual void rayTest(const btVector3& rayFrom, const btVector3& rayTo, btCollisionWorld::RayResultCallback& resultCallback) const;
//! Function for retrieve triangles.
/*!
It gives the triangles in local space
*/
virtual void processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const;
virtual void processAllTrianglesRay(btTriangleCallback* callback, const btVector3& rayFrom, const btVector3& rayTo) const;
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btGImpactMeshShapeData
{
btCollisionShapeData m_collisionShapeData;
btStridingMeshInterfaceData m_meshInterface;
btVector3FloatData m_localScaling;
float m_collisionMargin;
int m_gimpactSubType;
};
SIMD_FORCE_INLINE int btGImpactMeshShape::calculateSerializeBufferSize() const
{
return sizeof(btGImpactMeshShapeData);
}
#endif //GIMPACT_MESH_SHAPE_H
| 0 | 0.975389 | 1 | 0.975389 | game-dev | MEDIA | 0.62049 | game-dev | 0.9647 | 1 | 0.9647 |
openvehicles/Open-Vehicle-Monitoring-System-3 | 3,263 | plugins/pwrmon/pwrmon.js | /**
* Module plugin: PwrMon – Trip Power/Energy Chart
* Version 1.3 by Michael Balzer <dexter@dexters-web.de>
*
* This module records trip metrics by odometer distance.
* History data is stored in a file and automatically restored on reboot/reload.
*
* Installation:
* - Save as /store/scripts/lib/pwrmon.js
* - Add to /store/scripts/ovmsmain.js: pwrmon = require("lib/pwrmon");
* - Issue "script reload"
* - Install "pwrmon.htm" web plugin
*
* Configuration:
* No live config currently, see constants for customization.
*
* Usage:
* - pwrmon.dump('CBOR') -- dump (print) recorded history data in CBOR format (binary)
* - pwrmon.dump() -- dump (print) recorded history data in JSON format
* - pwrmon.data() -- get a copy of the history data object
*/
const minSampleDistance = 0.3; // [km]
const minRecordDistance = 50; // [km]
const storeDistance = 1; // [km]
const storeFile = "/store/usr/pwrmon.cbor"; // empty = no storage
const maxEntries = Math.ceil(minRecordDistance / minSampleDistance);
const tickerEvent = "ticker.1";
var history = {
"time": [],
"v.p.odometer": [],
"v.p.altitude": [],
"v.b.energy.used": [],
"v.b.energy.recd": [],
};
var lastOdo = 0;
var saveOdo = 0;
var listen_sdmount = null;
// Saving to VFS may cause short blockings, so only allow when vehicle is off:
function allowSave() {
return !OvmsMetrics.Value("v.e.on") && !OvmsMetrics.Value("v.c.charging");
}
// Ticker:
function ticker() {
if (!OvmsMetrics.Value("v.e.on")) {
lastOdo = 0;
return;
}
var m = OvmsMetrics.GetValues(history, true);
if (m["v.p.odometer"] - lastOdo < minSampleDistance)
return;
lastOdo = m["v.p.odometer"];
m.time = new Date().getTime() / 1000;
Object.keys(m).forEach(function(key) {
if (history[key].push(m[key]) > maxEntries)
history[key].splice(0, 1);
});
if (storeFile && allowSave() && lastOdo - saveOdo >= storeDistance) {
saveOdo = lastOdo;
VFS.Save({ path: storeFile, data: CBOR.encode(history) });
}
}
// History dump:
function dump(fmt) {
fmt = String(fmt).toUpperCase();
if (fmt == "CBOR")
write(CBOR.encode(history));
else if (fmt == "HEX")
print(Duktape.enc('hex', CBOR.encode(history)));
else
print(Duktape.enc('jc', history));
}
// History copy:
function data() {
return Object.assign({}, history);
}
// Init:
function loadStoreFile() {
VFS.Load({
path: storeFile,
binary: true,
done: function(data) {
print(storeFile + " loaded\n");
history = CBOR.decode(data);
startRecording();
},
fail: function(error) {
print(storeFile + ": " + this.error + "\n");
if (!listen_sdmount && storeFile.startsWith("/sd/") && this.error == "volume not mounted") {
// retry once after SD mount:
listen_sdmount = PubSub.subscribe("sd.mounted", loadStoreFile);
} else {
startRecording();
}
}
});
}
function startRecording() {
if (listen_sdmount) {
PubSub.unsubscribe(listen_sdmount);
listen_sdmount = null;
}
PubSub.subscribe(tickerEvent, ticker);
}
if (storeFile) {
loadStoreFile();
} else {
startRecording();
}
// API methods:
exports.dump = dump;
exports.data = data;
| 0 | 0.923791 | 1 | 0.923791 | game-dev | MEDIA | 0.264176 | game-dev | 0.980797 | 1 | 0.980797 |
jswigart/omni-bot | 15,737 | Installer/Files/rtcw/nav/wl_ufo.gm | global Map =
{
Quiet = true,
FocusPrimary = false,
Checkpoint_south_flag = "CHECKPOINT_south_flag",
FLAG_UFO_Documents = "FLAG_UFO_Documents",
Cappoint_transmitter = "CAPPOINT_transmitter",
Plant_allied_obj1 = "PLANT_Main_Gate",
Plant_allied_obj1a = "PLANT_South_Gate",
Mount_sentry_MG = "MOUNTMG42_sentry_MG",
Repair_sentry_MG = "REPAIRMG42_sentry_MG",
Snipe_phase1_blue_snipe1 = "SNIPE_phase1_blue_snipe1",
Snipe_phase1_red_snipe1 = "SNIPE_phase1_red_snipe1",
//initially disabled so they airstrike faster
DispenseAmmoDisable = true,
DontDispenseAmmo = true,
DispenseAmmoTime = 3,
MainStatus = true,
SouthStatus = true,
DocStatus = true,
Suicide = MAP_SUICIDE,
Navigation =
{
window =
{
navigate = function( _this )
{
_this.Bot.PressButton( BTN.JUMP );
sleep( 0.25 );
_this.Bot.HoldButton( BTN.SPRINT, 3 );
_this.Bot.HoldButton( BTN.CROUCH, 1 );
sleep( 3 );
},
},
boxes =
{
navigate = function( _this )
{
_this.Bot.PressButton( BTN.JUMP );
sleep( 0.25 );
},
},
rail =
{
navigate = function( _this )
{
_this.Bot.PressButton( BTN.JUMP );
sleep( 0.25 );
},
},
},
south_flag_Allies_Captured = function( trigger )
{
if ( TestMap ) {
return;
}
SetAvailableMapGoals( TEAM.AXIS, false, "AIRSTRIKE_.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.south.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.main.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.d.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_phase1.*" );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Mount_sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Repair_sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, true, "ARTILLERY_S_rSpawnkill.*" );
if ( Map.DocStatus ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_ufo.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_docs.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "AIRSTRIKE_rBridgeAS_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "PANZER_rRoof.*" );
}
},
south_flag_Axis_Captured = function( trigger )
{
if ( TestMap ) {
return;
}
SetAvailableMapGoals( TEAM.AXIS, false, "PANZER_rRoof.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "ARTILLERY_S_rSpawnkill.*" );
},
allied_obj1a_Destroyed = function( trigger )
{
if ( TestMap ) {
return;
}
Map.SouthStatus = false;
SetAvailableMapGoals( TEAM.ALLIES, false, "AIRSTRIKE_.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.FLAG_UFO_Documents );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Checkpoint_south_flag );
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_doc_attack.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_phase1.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_phase1_blue.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "SNIPE_phase1_red.*" );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Mount_sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Repair_sentry_MG );
if ( Map.MainStatus && Map.DocStatus ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_phase1.south.*" );
}
if ( !Map.DocStatus ) {
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_trans.*" );
}
if ( !Map.MainStatus && Map.DocStatus ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_ufo.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_docs.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.south.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.main.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.d.*" );
}
//soldiers should switch to panzer
RTCWUtil.SwitchWeapon( WEAPON.PANZERFAUST );
if ( Map.Suicide ) {
RTCWUtil.SetSuicide( TEAM.AXIS, CLASS.LIEUTENANT, 0, 0 );
}
},
allied_obj1_Destroyed = function( trigger )
{
if ( TestMap ) {
return;
}
Map.MainStatus = false;
Map.DontDispenseAmmo = false;
Util.EnableGoal( "ROUTE_main_gate_defense" );
SetAvailableMapGoals( TEAM.ALLIES, false, "AIRSTRIKE_.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.FLAG_UFO_Documents );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Checkpoint_south_flag );
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_doc_attack.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_phase1.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_phase1_blue.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "SNIPE_phase1_red.*" );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Mount_sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, false, Map.Repair_sentry_MG );
SetAvailableMapGoals( TEAM.ALLIES, false, "ARTILLERY_S_bInitial.*" );
if ( Map.SouthStatus && Map.DocStatus ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_phase1.main.*" );
}
if ( !Map.DocStatus ) {
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_trans.*" );
}
if ( !Map.SouthStatus && Map.DocStatus ) {
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_ufo.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_docs.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.south.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.main.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.d.*" );
}
//soldiers should switch to panzer
RTCWUtil.SwitchWeapon( WEAPON.PANZERFAUST );
if ( Map.Suicide ) {
RTCWUtil.SetSuicide( TEAM.AXIS, CLASS.LIEUTENANT, 0, 0 );
}
},
main_planted = function( trigger )
{
if ( TestMap ) {
return;
}
Util.DisableGoal( "DEFUSE_Main_Gate.*" );
},
main_defused = function( trigger )
{
if ( TestMap ) {
return;
}
},
south_planted = function( trigger )
{
if ( TestMap ) {
return;
}
Util.DisableGoal( "DEFUSE_South_Gate.*" );
},
south_defused = function( trigger )
{
if ( TestMap ) {
return;
}
},
The_UFO_Documents_Taken = function( trigger )
{
if ( TestMap ) {
return;
}
Map.DocStatus = false;
Map.DontDispenseAmmo = true;
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_trans.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_flex_trans.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_ufo.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_docs.*" );
//two humans can boost over fence
if ( !Map.SouthStatus || !Map.MainStatus ) {
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_trans.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "SNIPE_phase1_blue.*" );
}
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_doc_attack.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.south.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.main.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_phase1.d.*" );
SetAvailableMapGoals( TEAM.AXIS, false, Map.sentry_MG );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.FLAG_UFO_Documents );
SetAvailableMapGoals( TEAM.ALLIES, true, "PANZER_axis_spawn_north" );
SetAvailableMapGoals( TEAM.AXIS, false, "PANZER_rRoof" );
//activate some AS goals for Axis
SetAvailableMapGoals( TEAM.AXIS, false, "AIRSTRIKE_.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "AIRSTRIKE_red_as[12]_trans" );
},
docs_returned = function( trigger )
{
if ( TestMap ) {
return;
}
Map.DocStatus = true;
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_trans.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_flex_trans.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_trans.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_ufo.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_docs.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_doc_attack.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.FLAG_UFO_Documents );
if ( Map.SouthStatus && Map.MainStatus ) {
SetAvailableMapGoals( TEAM.ALLIES, true, "SNIPE_phase1_blue.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_phase1_red.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_phase1.south.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_phase1.main.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "ATTACK_doc_attack.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_phase1.d.*" );
SetAvailableMapGoals( TEAM.AXIS, true, Map.sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_ufo.*" );
SetAvailableMapGoals( TEAM.AXIS, false, "DEFEND_docs.*" );
SetAvailableMapGoals( TEAM.AXIS, true, Map.sentry_MG );
SetAvailableMapGoals( TEAM.ALLIES, false, Map.FLAG_UFO_Documents );
}
if ( !Map.MainStatus ) {
Map.DontDispenseAmmo = false;
}
//clear the AS goals
SetAvailableMapGoals( TEAM.AXIS, false, "AIRSTRIKE_.*" );
SetAvailableMapGoals( TEAM.ALLIES, false, "PANZER_axis_spawn_north" );
SetAvailableMapGoals( TEAM.AXIS, true, "PANZER_rRoof" );
},
transmitter_Captured = function( trigger )
{
if ( TestMap ) {
return;
}
},
two_minute = function( trigger )
{
if ( TestMap ) {
return;
}
//time is low, so start focusing on main obj
Map.FocusPrimary = true;
SetAvailableMapGoals( TEAM.AXIS, true, Map.FLAG_UFO_Documents );
},
//thirty_second = function( trigger )
//{
//
//},
};
global OnMapLoad = function()
{
if ( TestMapOn ) {
RTCWUtil.AutoTestMap();
}
OnTrigger( "The Main Gate has been breached!", Map.allied_obj1_Destroyed );
OnTrigger( "The South Gate has been breached!", Map.allied_obj1a_Destroyed );
OnTrigger( "Allies have stolen The UFO Documents!", Map.The_UFO_Documents_Taken );
OnTrigger( "Flag returned UFO Documents!", Map.docs_returned );
OnTrigger( "Allies Transmitted the UFO Documents!", Map.transmitter_Captured );
OnTrigger( "Axis Regain Control of The Reinforcement Point!", Map.south_flag_Axis_Captured );
OnTrigger( "Allies Capture The Reinforcement Point!", Map.south_flag_Allies_Captured );
OnTrigger( "Planted at The Main Gate.", Map.main_planted );
OnTrigger( "Defused at The Main Gate.", Map.main_defused );
OnTrigger( "Planted at The South Gate.", Map.south_planted );
OnTrigger( "Defused at The South Gate.", Map.south_defused );
OnTrigger( "two minute warning.", Map.two_minute );
//OnTrigger( "thirty second warning.", Map.thirty_second );
Util.SetMaxUsersInProgress( 8, Map.FLAG_UFO_Documents );
Util.SetMaxUsersInProgress( 1, "ATTACK.*" );
Util.SetMaxUsersInProgress( 1, "DEFEND.*" );
Util.SetMaxUsersInProgress( 1, "MOUNT.*" );
Util.SetMaxUsersInProgress( 1, "REPAIR.*" );
SetMapGoalProperties( "SNIPE_.*", {mincamptime = 999, maxcamptime = 999} );
SetMapGoalProperties( "PANZER_.*", {mincamptime = 30, maxcamptime = 60} );
SetMapGoalProperties( "ATTACK_.*", {mincamptime = 15, maxcamptime = 30} );
SetMapGoalProperties( "DEFEND_.*", {mincamptime = 30, maxcamptime = 45} );
SetMapGoalProperties( "MOUNT.*", {mincamptime = 30, maxcamptime = 45} );
RTCWUtil.SetPrimaryGoals( 1.0 );
SetGoalPriority( "DEFEND_phase1.south.*", 0.6 );
SetGoalPriority( "DEFEND_phase1.main.*", 0.6 );
SetGoalPriority( "DEFEND_docs.*", 0.6 );
SetGoalPriority( "DEFEND_trans.*", 0.6 );
SetGoalPriority( "ARTILLERY_S.*", 1.0 );
Util.DisableGoal( ".*", true );
Util.DisableGoal( "ROUTE_main_gate_defense" );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_allied_obj1 );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Plant_allied_obj1a );
SetAvailableMapGoals( TEAM.ALLIES, true, Map.Cappoint_transmitter );
SetAvailableMapGoals( TEAM.ALLIES, true, "SNIPE_phase1_blue.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "ATTACK_phase1.*" );
SetAvailableMapGoals( TEAM.ALLIES, true, "AIRSTRIKE_blue_as[123]_phase1.*" );
//SetAvailableMapGoals( TEAM.ALLIES, true, "ARTILLERY_S_bInitial.*" );
SetAvailableMapGoals( TEAM.AXIS, true, Map.Mount_sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, true, Map.Repair_sentry_MG );
SetAvailableMapGoals( TEAM.AXIS, true, "SNIPE_phase1_red.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "DEFEND_phase1_d.*" );
SetAvailableMapGoals( TEAM.AXIS, true, "AIRSTRIKE_red_as[123]_phase1.*" );
if ( Map.Suicide ) {
RTCWUtil.SetSuicide( TEAM.AXIS, CLASS.LIEUTENANT, 1, 1 );
}
MapRoutes =
{
PLANT_South_Gate =
{
ROUTE_AlliesSpawn = { ROUTE_south_route = {}, },
},
PLANT_Main_Gate =
{
ROUTE_AlliesSpawn =
{
ROUTE_hill_route = {},
ROUTE_north_route = {},
},
},
FLAG_UFO_Documents =
{
ROUTE_AlliesSpawn =
{
ROUTE_hill_route =
{
ROUTE_main_gate =
{
ROUTE_trans_route =
{
ROUTE_spawn_stairs =
{
ROUTE_spawn_route = {},
ROUTE_upper_ufo =
{
Weight = 2,
ROUTE_upper_west = {},
ROUTE_upper_east = {},
},
},
},
ROUTE_north_alley =
{
ROUTE_garage =
{
ROUTE_duct =
{
ROUTE_roof = {},
ROUTE_duct_exit = {},
},
ROUTE_stairs = { Weight = 4, },
},
},
},
},
ROUTE_south_route =
{
ROUTE_south_gate =
{
ROUTE_nw_corner =
{
ROUTE_garage =
{
ROUTE_duct =
{
ROUTE_roof = {},
ROUTE_duct_exit = {},
},
ROUTE_stairs = { Weight = 4, },
},
},
ROUTE_mid_alley =
{
ROUTE_garage =
{
ROUTE_duct =
{
ROUTE_roof = {},
ROUTE_duct_exit = {},
},
ROUTE_stairs = { Weight = 4, },
},
},
},
},
},
ROUTE_CPSpawn =
{
ROUTE_nw_corner =
{
ROUTE_garage =
{
ROUTE_duct =
{
ROUTE_roof = {},
ROUTE_duct_exit = {},
},
ROUTE_stairs = { Weight = 4, },
},
},
ROUTE_mid_alley =
{
ROUTE_garage =
{
ROUTE_duct =
{
ROUTE_roof = {},
ROUTE_duct_exit = {},
},
ROUTE_stairs = { Weight = 4, },
},
},
ROUTE_main_gate =
{
Weight = 2,
ROUTE_trans_route =
{
ROUTE_spawn_stairs =
{
ROUTE_spawn_route = {},
ROUTE_upper_ufo =
{
Weight = 2,
ROUTE_upper_west = {},
ROUTE_upper_east = {},
},
},
},
},
},
},
CAPPOINT_transmitter =
{
ROUTE_DocSteal =
{
ROUTE_nw_corner =
{
ROUTE_main_gate =
{
ROUTE_trans_stairs = {},
ROUTE_trans_ladder = {},
},
},
ROUTE_trans_ladder = {},
ROUTE_north_alley =
{
ROUTE_trans_stairs = {},
},
ROUTE_duct =
{
Weight = 2,
ROUTE_trans_ladder = {},
ROUTE_north_alley =
{
ROUTE_trans_stairs = {},
},
},
},
},
MOUNTMG42_sentry_MG =
{
ROUTE_AxisSpawn = { ROUTE_main_gate_defense = {}, }
},
};
MapRoutes.FLAG_UFO_Documents.CPSpawn2 = MapRoutes.FLAG_UFO_Documents.CPSpawn;
MapRoutes.ATTACK_doc_attack1 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.ATTACK_doc_attack2 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.ATTACK_doc_attack3 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.ATTACK_doc_attack4 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.ATTACK_doc_attack5 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.ATTACK_doc_attack6 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.ATTACK_doc_attack7 = MapRoutes.FLAG_UFO_Documents;
MapRoutes.DEFEND_phase1_main_d1 = MapRoutes.MOUNTMG42_sentry_MG;
MapRoutes.DEFEND_phase1_main_d2 = MapRoutes.MOUNTMG42_sentry_MG;
MapRoutes.DEFEND_phase1_main_d3 = MapRoutes.MOUNTMG42_sentry_MG;
MapRoutes.DEFEND_phase1_d1 = MapRoutes.MOUNTMG42_sentry_MG;
MapRoutes.DEFEND_phase1_d2 = MapRoutes.MOUNTMG42_sentry_MG;
MapRoutes.DEFEND_phase1_d5 = MapRoutes.MOUNTMG42_sentry_MG;
Util.Routes( MapRoutes );
Util.MapDebugPrint( "OnMapLoad" );
};
global OnBotJoin = function( bot )
{
bot.TargetBreakableDist = 80.0;
RTCWUtil.SelectWeapon( bot, WEAPON.MAUSER );
//default spawn
bot.ChangeSpawnPoint( 0 );
};
| 0 | 0.893135 | 1 | 0.893135 | game-dev | MEDIA | 0.950942 | game-dev | 0.792508 | 1 | 0.792508 |
emscripten-core/emscripten | 12,816 | test/third_party/bullet/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btCompoundShape.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btAabbUtil2.h"
#include "btManifoldResult.h"
btCompoundCollisionAlgorithm::btCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped)
:btActivatingCollisionAlgorithm(ci,body0,body1),
m_isSwapped(isSwapped),
m_sharedManifold(ci.m_manifold)
{
m_ownsManifold = false;
btCollisionObject* colObj = m_isSwapped? body1 : body0;
btAssert (colObj->getCollisionShape()->isCompound());
btCompoundShape* compoundShape = static_cast<btCompoundShape*>(colObj->getCollisionShape());
m_compoundShapeRevision = compoundShape->getUpdateRevision();
preallocateChildAlgorithms(body0,body1);
}
void btCompoundCollisionAlgorithm::preallocateChildAlgorithms(btCollisionObject* body0,btCollisionObject* body1)
{
btCollisionObject* colObj = m_isSwapped? body1 : body0;
btCollisionObject* otherObj = m_isSwapped? body0 : body1;
btAssert (colObj->getCollisionShape()->isCompound());
btCompoundShape* compoundShape = static_cast<btCompoundShape*>(colObj->getCollisionShape());
int numChildren = compoundShape->getNumChildShapes();
int i;
m_childCollisionAlgorithms.resize(numChildren);
for (i=0;i<numChildren;i++)
{
if (compoundShape->getDynamicAabbTree())
{
m_childCollisionAlgorithms[i] = 0;
} else
{
btCollisionShape* tmpShape = colObj->getCollisionShape();
btCollisionShape* childShape = compoundShape->getChildShape(i);
colObj->internalSetTemporaryCollisionShape( childShape );
m_childCollisionAlgorithms[i] = m_dispatcher->findAlgorithm(colObj,otherObj,m_sharedManifold);
colObj->internalSetTemporaryCollisionShape( tmpShape );
}
}
}
void btCompoundCollisionAlgorithm::removeChildAlgorithms()
{
int numChildren = m_childCollisionAlgorithms.size();
int i;
for (i=0;i<numChildren;i++)
{
if (m_childCollisionAlgorithms[i])
{
m_childCollisionAlgorithms[i]->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(m_childCollisionAlgorithms[i]);
}
}
}
btCompoundCollisionAlgorithm::~btCompoundCollisionAlgorithm()
{
removeChildAlgorithms();
}
struct btCompoundLeafCallback : btDbvt::ICollide
{
public:
btCollisionObject* m_compoundColObj;
btCollisionObject* m_otherObj;
btDispatcher* m_dispatcher;
const btDispatcherInfo& m_dispatchInfo;
btManifoldResult* m_resultOut;
btCollisionAlgorithm** m_childCollisionAlgorithms;
btPersistentManifold* m_sharedManifold;
btCompoundLeafCallback (btCollisionObject* compoundObj,btCollisionObject* otherObj,btDispatcher* dispatcher,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut,btCollisionAlgorithm** childCollisionAlgorithms,btPersistentManifold* sharedManifold)
:m_compoundColObj(compoundObj),m_otherObj(otherObj),m_dispatcher(dispatcher),m_dispatchInfo(dispatchInfo),m_resultOut(resultOut),
m_childCollisionAlgorithms(childCollisionAlgorithms),
m_sharedManifold(sharedManifold)
{
}
void ProcessChildShape(btCollisionShape* childShape,int index)
{
btAssert(index>=0);
btCompoundShape* compoundShape = static_cast<btCompoundShape*>(m_compoundColObj->getCollisionShape());
btAssert(index<compoundShape->getNumChildShapes());
//backup
btTransform orgTrans = m_compoundColObj->getWorldTransform();
btTransform orgInterpolationTrans = m_compoundColObj->getInterpolationWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(index);
btTransform newChildWorldTrans = orgTrans*childTrans ;
//perform an AABB check first
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
childShape->getAabb(newChildWorldTrans,aabbMin0,aabbMax0);
m_otherObj->getCollisionShape()->getAabb(m_otherObj->getWorldTransform(),aabbMin1,aabbMax1);
if (TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
m_compoundColObj->setWorldTransform( newChildWorldTrans);
m_compoundColObj->setInterpolationWorldTransform(newChildWorldTrans);
//the contactpoint is still projected back using the original inverted worldtrans
btCollisionShape* tmpShape = m_compoundColObj->getCollisionShape();
m_compoundColObj->internalSetTemporaryCollisionShape( childShape );
if (!m_childCollisionAlgorithms[index])
m_childCollisionAlgorithms[index] = m_dispatcher->findAlgorithm(m_compoundColObj,m_otherObj,m_sharedManifold);
///detect swapping case
if (m_resultOut->getBody0Internal() == m_compoundColObj)
{
m_resultOut->setShapeIdentifiersA(-1,index);
} else
{
m_resultOut->setShapeIdentifiersB(-1,index);
}
m_childCollisionAlgorithms[index]->processCollision(m_compoundColObj,m_otherObj,m_dispatchInfo,m_resultOut);
if (m_dispatchInfo.m_debugDraw && (m_dispatchInfo.m_debugDraw->getDebugMode() & btIDebugDraw::DBG_DrawAabb))
{
btVector3 worldAabbMin,worldAabbMax;
m_dispatchInfo.m_debugDraw->drawAabb(aabbMin0,aabbMax0,btVector3(1,1,1));
m_dispatchInfo.m_debugDraw->drawAabb(aabbMin1,aabbMax1,btVector3(1,1,1));
}
//revert back transform
m_compoundColObj->internalSetTemporaryCollisionShape( tmpShape);
m_compoundColObj->setWorldTransform( orgTrans );
m_compoundColObj->setInterpolationWorldTransform(orgInterpolationTrans);
}
}
void Process(const btDbvtNode* leaf)
{
int index = leaf->dataAsInt;
btCompoundShape* compoundShape = static_cast<btCompoundShape*>(m_compoundColObj->getCollisionShape());
btCollisionShape* childShape = compoundShape->getChildShape(index);
if (m_dispatchInfo.m_debugDraw && (m_dispatchInfo.m_debugDraw->getDebugMode() & btIDebugDraw::DBG_DrawAabb))
{
btVector3 worldAabbMin,worldAabbMax;
btTransform orgTrans = m_compoundColObj->getWorldTransform();
btTransformAabb(leaf->volume.Mins(),leaf->volume.Maxs(),0.,orgTrans,worldAabbMin,worldAabbMax);
m_dispatchInfo.m_debugDraw->drawAabb(worldAabbMin,worldAabbMax,btVector3(1,0,0));
}
ProcessChildShape(childShape,index);
}
};
void btCompoundCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
btCollisionObject* colObj = m_isSwapped? body1 : body0;
btCollisionObject* otherObj = m_isSwapped? body0 : body1;
btAssert (colObj->getCollisionShape()->isCompound());
btCompoundShape* compoundShape = static_cast<btCompoundShape*>(colObj->getCollisionShape());
///btCompoundShape might have changed:
////make sure the internal child collision algorithm caches are still valid
if (compoundShape->getUpdateRevision() != m_compoundShapeRevision)
{
///clear and update all
removeChildAlgorithms();
preallocateChildAlgorithms(body0,body1);
}
btDbvt* tree = compoundShape->getDynamicAabbTree();
//use a dynamic aabb tree to cull potential child-overlaps
btCompoundLeafCallback callback(colObj,otherObj,m_dispatcher,dispatchInfo,resultOut,&m_childCollisionAlgorithms[0],m_sharedManifold);
///we need to refresh all contact manifolds
///note that we should actually recursively traverse all children, btCompoundShape can nested more then 1 level deep
///so we should add a 'refreshManifolds' in the btCollisionAlgorithm
{
int i;
btManifoldArray manifoldArray;
for (i=0;i<m_childCollisionAlgorithms.size();i++)
{
if (m_childCollisionAlgorithms[i])
{
m_childCollisionAlgorithms[i]->getAllContactManifolds(manifoldArray);
for (int m=0;m<manifoldArray.size();m++)
{
if (manifoldArray[m]->getNumContacts())
{
resultOut->setPersistentManifold(manifoldArray[m]);
resultOut->refreshContactPoints();
resultOut->setPersistentManifold(0);//??necessary?
}
}
manifoldArray.resize(0);
}
}
}
if (tree)
{
btVector3 localAabbMin,localAabbMax;
btTransform otherInCompoundSpace;
otherInCompoundSpace = colObj->getWorldTransform().inverse() * otherObj->getWorldTransform();
otherObj->getCollisionShape()->getAabb(otherInCompoundSpace,localAabbMin,localAabbMax);
const ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds=btDbvtVolume::FromMM(localAabbMin,localAabbMax);
//process all children, that overlap with the given AABB bounds
tree->collideTV(tree->m_root,bounds,callback);
} else
{
//iterate over all children, perform an AABB check inside ProcessChildShape
int numChildren = m_childCollisionAlgorithms.size();
int i;
for (i=0;i<numChildren;i++)
{
callback.ProcessChildShape(compoundShape->getChildShape(i),i);
}
}
{
//iterate over all children, perform an AABB check inside ProcessChildShape
int numChildren = m_childCollisionAlgorithms.size();
int i;
btManifoldArray manifoldArray;
btCollisionShape* childShape = 0;
btTransform orgTrans;
btTransform orgInterpolationTrans;
btTransform newChildWorldTrans;
btVector3 aabbMin0,aabbMax0,aabbMin1,aabbMax1;
for (i=0;i<numChildren;i++)
{
if (m_childCollisionAlgorithms[i])
{
childShape = compoundShape->getChildShape(i);
//if not longer overlapping, remove the algorithm
orgTrans = colObj->getWorldTransform();
orgInterpolationTrans = colObj->getInterpolationWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(i);
newChildWorldTrans = orgTrans*childTrans ;
//perform an AABB check first
childShape->getAabb(newChildWorldTrans,aabbMin0,aabbMax0);
otherObj->getCollisionShape()->getAabb(otherObj->getWorldTransform(),aabbMin1,aabbMax1);
if (!TestAabbAgainstAabb2(aabbMin0,aabbMax0,aabbMin1,aabbMax1))
{
m_childCollisionAlgorithms[i]->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm(m_childCollisionAlgorithms[i]);
m_childCollisionAlgorithms[i] = 0;
}
}
}
}
}
btScalar btCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
btCollisionObject* colObj = m_isSwapped? body1 : body0;
btCollisionObject* otherObj = m_isSwapped? body0 : body1;
btAssert (colObj->getCollisionShape()->isCompound());
btCompoundShape* compoundShape = static_cast<btCompoundShape*>(colObj->getCollisionShape());
//We will use the OptimizedBVH, AABB tree to cull potential child-overlaps
//If both proxies are Compound, we will deal with that directly, by performing sequential/parallel tree traversals
//given Proxy0 and Proxy1, if both have a tree, Tree0 and Tree1, this means:
//determine overlapping nodes of Proxy1 using Proxy0 AABB against Tree1
//then use each overlapping node AABB against Tree0
//and vise versa.
btScalar hitFraction = btScalar(1.);
int numChildren = m_childCollisionAlgorithms.size();
int i;
btTransform orgTrans;
btScalar frac;
for (i=0;i<numChildren;i++)
{
//temporarily exchange parent btCollisionShape with childShape, and recurse
btCollisionShape* childShape = compoundShape->getChildShape(i);
//backup
orgTrans = colObj->getWorldTransform();
const btTransform& childTrans = compoundShape->getChildTransform(i);
//btTransform newChildWorldTrans = orgTrans*childTrans ;
colObj->setWorldTransform( orgTrans*childTrans );
btCollisionShape* tmpShape = colObj->getCollisionShape();
colObj->internalSetTemporaryCollisionShape( childShape );
frac = m_childCollisionAlgorithms[i]->calculateTimeOfImpact(colObj,otherObj,dispatchInfo,resultOut);
if (frac<hitFraction)
{
hitFraction = frac;
}
//revert back
colObj->internalSetTemporaryCollisionShape( tmpShape);
colObj->setWorldTransform( orgTrans);
}
return hitFraction;
}
| 0 | 0.932773 | 1 | 0.932773 | game-dev | MEDIA | 0.954993 | game-dev | 0.953296 | 1 | 0.953296 |
PMC-Unga-Marines/Unga-Marines | 3,688 | code/game/objects/machinery/artillery/mlrs.dm | /obj/item/mortar_kit/mlrs
name = "\improper TA-40L multiple rocket launcher system"
desc = "A manual, crew-operated and towable multiple rocket launcher system piece used by the TerraGov Marine Corps, it is meant to saturate an area with munitions to total up to large amounts of firepower, it thus has high scatter when firing to accomplish such a task. Fires in only bursts of up to 16 rockets, it can hold 32 rockets in total. Uses 60mm Rockets."
icon_state = "mlrs"
icon = 'icons/obj/artillery/mlrs.dmi'
max_integrity = 400
item_flags = TWOHANDED
deploy_flags = IS_DEPLOYABLE|DEPLOYED_NO_PICKUP|DEPLOY_ON_INITIALIZE
w_class = WEIGHT_CLASS_HUGE
deployable_item = /obj/machinery/deployable/mortar/howitzer/mlrs
/obj/machinery/deployable/mortar/howitzer/mlrs/perform_firing_visuals()
return
/obj/machinery/deployable/mortar/howitzer/mlrs //TODO why in the seven hells is this a howitzer child??????
pixel_x = 0
anchored = FALSE // You can move this.
fire_sound = 'sound/weapons/guns/fire/rocket_arty.ogg'
reload_sound = 'sound/weapons/guns/interact/tat36_reload.ogg'
fall_sound = 'sound/weapons/guns/misc/rocket_whistle.ogg'
minimum_range = 20
allowed_shells = list(
/obj/item/mortal_shell/rocket/mlrs,
/obj/item/mortal_shell/rocket/mlrs/gas,
/obj/item/mortal_shell/rocket/mlrs/tangle,
)
cool_off_time = 60 SECONDS
fire_delay = 0.15 SECONDS
fire_amount = 16
reload_time = 0.25 SECONDS
max_rounds = 32
offset_per_turfs = 25
spread = 3.5
max_spread = 6.5
//this checks for box of rockets, otherwise will go to normal attackby for mortars
/obj/machinery/deployable/mortar/howitzer/mlrs/attackby(obj/item/I, mob/user, params)
if(firing)
user.balloon_alert(user, "The barrel is steaming hot. Wait till it cools off")
return
if(!istype(I, /obj/item/storage/box/mlrs_rockets) && !istype(I, /obj/item/storage/box/mlrs_rockets_gas) && !istype(I, /obj/item/storage/box/mlrs_rockets_tangle))
return ..()
var/obj/item/storage/box/rocket_box = I
//prompt user and ask how many rockets to load
var/numrockets = tgui_input_number(user, "How many rockets do you wish to load?)", "Quantity to Load", 0, 16, 0)
if(numrockets < 1 || !can_interact(user))
return
//loop that continues loading until a invalid condition is met
var/rocketsloaded = 0
while(rocketsloaded < numrockets)
//verify it has rockets
if(!istype(rocket_box.contents[1], /obj/item/mortal_shell/rocket/mlrs))
user.balloon_alert(user, "Out of rockets")
return
var/obj/item/mortal_shell/mortar_shell = rocket_box.contents[1]
if(length(chamber_items) >= max_rounds)
user.balloon_alert(user, "You cannot fit more")
return
if(!(mortar_shell.type in allowed_shells))
user.balloon_alert(user, "This shell doesn't fit")
return
if(busy)
user.balloon_alert(user, "Someone else is using this")
return
user.visible_message(span_notice("[user] starts loading \a [mortar_shell.name] into [src]."),
span_notice("You start loading \a [mortar_shell.name] into [src]."))
playsound(loc, reload_sound, 50, 1)
busy = TRUE
if(!do_after(user, reload_time, NONE, src, BUSY_ICON_HOSTILE))
busy = FALSE
return
busy = FALSE
user.visible_message(span_notice("[user] loads \a [mortar_shell.name] into [src]."),
span_notice("You load \a [mortar_shell.name] into [src]."))
chamber_items += mortar_shell
rocket_box.storage_datum.remove_from_storage(mortar_shell, null, user)
rocketsloaded++
user.balloon_alert(user, "Right click to fire")
/obj/machinery/deployable/mortar/howitzer/mlrs/record_shell_fired()
GLOB.round_statistics.rocket_shells_fired++
SSblackbox.record_feedback(FEEDBACK_TALLY, "round_statistics", 1, "rocket_shells_fired")
| 0 | 0.916841 | 1 | 0.916841 | game-dev | MEDIA | 0.992515 | game-dev | 0.592058 | 1 | 0.592058 |
ixray-team/ixray-1.6-stcop | 2,377 | gamedata_cs/scripts/db.script | --[[------------------------------------------------------------------------------------------------
База данных живых онлайновых объектов, зон и рестрикторов, актёра
Чугай Александр
--------------------------------------------------------------------------------------------------]]
zone_by_name = {}
sl_by_name = {}
bridge_by_name = {}
script_ids = {}
storage = {}
sound = {}
actor = nil
actor_proxy = actor_proxy.actor_proxy()
heli = {}
camp_storage = {}
story_by_id = {}
smart_terrain_by_id = {}
trader = nil
info_restr = {}
strn_by_respawn = {}
heli_enemies = {}
heli_enemy_count = 0
anim_obj_by_name = {}
goodwill = {sympathy = {}, relations = {}}
signal_light = {}
no_weap_zones = {}
function add_enemy( obj )
heli_enemies[heli_enemy_count] = obj
heli_enemy_count = heli_enemy_count + 1
end
function delete_enemy( e_index )
heli_enemies[e_index] = nil
end
function add_obj( obj )
printf("adding object %s",obj:name())
storage[obj:id()].object = obj
end
function del_obj( obj )
storage [obj:id()] = nil
end
function add_zone( zone )
zone_by_name[zone:name()] = zone
--storage[zone:id()].object = obj
end
function del_zone( zone )
zone_by_name[zone:name()] = nil
--storage[zone:id()].object = nil
end
function add_bridge( bridge, binder )
printf("adding bridge %s",bridge:name())
bridge_by_name[bridge:name()] = binder
add_obj( bridge )
end
function del_bridge( bridge )
bridge_by_name[bridge:name()] = nil
del_obj( bridge )
end
function add_sl( sl )
sl_by_name[sl:name()] = sl
add_obj( sl )
end
function del_sl( sl )
sl_by_name[sl:name()] = nil
del_obj( sl )
end
function add_actor( obj )
actor = obj
actor_proxy:net_spawn( obj )
add_obj( obj )
end
function del_actor()
del_obj( actor )
actor_proxy:net_destroy()
actor = nil
end
function add_heli(obj)
heli[obj:id()] = obj
end
function del_heli(obj)
heli[obj:id()] = nil
end
function add_smart_terrain( obj )
smart_terrain_by_id[obj.id] = obj
end
function del_smart_terrain( obj )
smart_terrain_by_id[obj.id] = nil
end
function add_anim_obj(anim_obj, binder)
anim_obj_by_name[anim_obj:name()] = binder
add_obj(anim_obj)
end
function del_anim_obj(anim_obj)
anim_obj_by_name[anim_obj:name()] = nil
del_obj(anim_obj)
end
| 0 | 0.530763 | 1 | 0.530763 | game-dev | MEDIA | 0.898741 | game-dev | 0.840352 | 1 | 0.840352 |
GregTechCE/GregTech | 6,102 | src/main/java/gregtech/api/gui/widgets/SliderWidget.java | package gregtech.api.gui.widgets;
import com.google.common.base.Preconditions;
import gregtech.api.gui.GuiTextures;
import gregtech.api.gui.IRenderContext;
import gregtech.api.gui.Widget;
import gregtech.api.gui.resources.TextureArea;
import gregtech.api.util.Position;
import gregtech.api.util.Size;
import gregtech.api.util.function.FloatConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.MathHelper;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.BiFunction;
public class SliderWidget extends Widget {
public static final BiFunction<String, Float, String> DEFAULT_TEXT_SUPPLIER = (name, value) -> I18n.format(name, value.intValue());
private int sliderWidth = 8;
private TextureArea backgroundArea = GuiTextures.SLIDER_BACKGROUND;
private TextureArea sliderIcon = GuiTextures.SLIDER_ICON;
private BiFunction<String, Float, String> textSupplier = DEFAULT_TEXT_SUPPLIER;
private int textColor = 0xFFFFFF;
private final float min;
private final float max;
private final String name;
private final FloatConsumer responder;
private boolean isPositionSent;
private String displayString;
private float sliderPosition;
public boolean isMouseDown;
public SliderWidget(String name, int xPosition, int yPosition, int width, int height, float min, float max, float currentValue, FloatConsumer responder) {
super(new Position(xPosition, yPosition), new Size(width, height));
Preconditions.checkNotNull(responder, "responder");
Preconditions.checkNotNull(name, "name");
this.min = min;
this.max = max;
this.name = name;
this.responder = responder;
this.sliderPosition = (currentValue - min) / (max - min);
}
public SliderWidget setSliderIcon(@Nonnull TextureArea sliderIcon) {
Preconditions.checkNotNull(sliderIcon, "sliderIcon");
this.sliderIcon = sliderIcon;
return this;
}
public SliderWidget setBackground(@Nullable TextureArea background) {
this.backgroundArea = background;
return this;
}
public SliderWidget setSliderWidth(int sliderWidth) {
this.sliderWidth = sliderWidth;
return this;
}
public SliderWidget setTextColor(int textColor) {
this.textColor = textColor;
return this;
}
@Override
public void detectAndSendChanges() {
if (!isPositionSent) {
writeUpdateInfo(1, buffer -> buffer.writeFloat(sliderPosition));
this.isPositionSent = true;
}
}
public float getSliderValue() {
return this.min + (this.max - this.min) * this.sliderPosition;
}
protected String getDisplayString() {
return textSupplier.apply(name, getSliderValue());
}
@Override
public void drawInBackground(int mouseX, int mouseY, IRenderContext context) {
Position pos = getPosition();
Size size = getSize();
if (backgroundArea != null) {
backgroundArea.draw(pos.x, pos.y, size.width, size.height);
}
if(displayString == null) {
this.displayString = getDisplayString();
}
sliderIcon.draw(pos.x + (int) (this.sliderPosition * (float) (size.width - 8)), pos.y, sliderWidth, size.height);
FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;
fontRenderer.drawString(displayString,
pos.x + size.width / 2 - fontRenderer.getStringWidth(displayString) / 2,
pos.y + size.height / 2 - fontRenderer.FONT_HEIGHT / 2, textColor);
GlStateManager.color(1.0f, 1.0f, 1.0f);
}
@Override
public boolean mouseDragged(int mouseX, int mouseY, int button, long timeDragged) {
if (this.isMouseDown) {
Position pos = getPosition();
Size size = getSize();
this.sliderPosition = (float) (mouseX - (pos.x + 4)) / (float) (size.width - 8);
if (this.sliderPosition < 0.0F) {
this.sliderPosition = 0.0F;
}
if (this.sliderPosition > 1.0F) {
this.sliderPosition = 1.0F;
}
this.displayString = this.getDisplayString();
writeClientAction(1, buffer -> buffer.writeFloat(sliderPosition));
return true;
}
return false;
}
@Override
public boolean mouseClicked(int mouseX, int mouseY, int button) {
if (isMouseOverElement(mouseX, mouseY)) {
Position pos = getPosition();
Size size = getSize();
this.sliderPosition = (float) (mouseX - (pos.x + 4)) / (float) (size.width - 8);
if (this.sliderPosition < 0.0F) {
this.sliderPosition = 0.0F;
}
if (this.sliderPosition > 1.0F) {
this.sliderPosition = 1.0F;
}
this.displayString = this.getDisplayString();
writeClientAction(1, buffer -> buffer.writeFloat(sliderPosition));
this.isMouseDown = true;
return true;
}
return false;
}
@Override
public boolean mouseReleased(int mouseX, int mouseY, int button) {
this.isMouseDown = false;
return false;
}
@Override
public void handleClientAction(int id, PacketBuffer buffer) {
if (id == 1) {
this.sliderPosition = buffer.readFloat();
this.sliderPosition = MathHelper.clamp(sliderPosition, 0.0f, 1.0f);
this.responder.apply(getSliderValue());
}
}
@Override
public void readUpdateInfo(int id, PacketBuffer buffer) {
if (id == 1) {
this.sliderPosition = buffer.readFloat();
this.sliderPosition = MathHelper.clamp(sliderPosition, 0.0f, 1.0f);
this.displayString = getDisplayString();
}
}
}
| 0 | 0.860294 | 1 | 0.860294 | game-dev | MEDIA | 0.610831 | game-dev | 0.976643 | 1 | 0.976643 |
PhoenixBladez/SpiritMod | 9,580 | NPCs/BloodGazer/BloodGazerProjs.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SpiritMod.Mechanics.Trails;
using SpiritMod.NPCs.Boss.SteamRaider;
using SpiritMod.Prim;
using SpiritMod.VerletChains;
using System;
using System.IO;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
namespace SpiritMod.NPCs.BloodGazer
{
public class BloodGazerEyeShot : ModProjectile
{
public override string Texture => "Terraria/Projectile_1";
public override void SetStaticDefaults() => DisplayName.SetDefault("Blood Shot");
public override void SetDefaults()
{
//projectile.CloneDefaults(ProjectileID.WoodenArrowHostile);
projectile.width = 10;
projectile.height = 10;
projectile.hostile = true;
projectile.alpha = 255;
projectile.penetrate = 1;
projectile.timeLeft = 180;
}
bool primsCreated = false;
public override void AI()
{
if (projectile.velocity.Length() < 22)
projectile.velocity *= 1.02f;
if (!primsCreated && !Main.dedServ) {
primsCreated = true;
SpiritMod.primitives.CreateTrail(new RipperPrimTrail(projectile));
}
}
public override void Kill(int timeLeft)
{
Main.PlaySound(new LegacySoundStyle(SoundID.NPCHit, 8).WithPitchVariance(0.2f).WithVolume(0.3f), projectile.Center);
for (int i = 0; i < 20; i++) {
Dust.NewDustPerfect(projectile.Center, 5, Main.rand.NextFloat(0.25f, 0.5f) * projectile.velocity.RotatedBy(3.14f + Main.rand.NextFloat(-0.4f, 0.4f)));
}
}
}
public class BloodGazerEyeShotWavy : BloodGazerEyeShot
{
public override string Texture => "Terraria/Projectile_1";
public override void SetStaticDefaults() => DisplayName.SetDefault("Blood Shot");
public override bool PreAI()
{
projectile.position -= projectile.velocity;
projectile.position += projectile.velocity.RotatedBy(Math.Sin(projectile.timeLeft/6f) * MathHelper.PiOver4 * projectile.ai[0]);
return true;
}
}
public class RunicEye : ModProjectile, IDrawAdditive
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Runic Eye");
Main.projFrames[projectile.type] = 5;
}
public override void SetDefaults()
{
projectile.Size = Vector2.One * 10;
projectile.tileCollide = false;
projectile.friendly = projectile.hostile = false;
projectile.alpha = 255;
projectile.scale = 1.5f;
}
public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor)
{
Texture2D tex = Main.projectileTexture[projectile.type];
Texture2D pupiltex = ModContent.GetTexture(Texture + "_pupil");
void DrawEye(Vector2 position, float Opacity)
{
spriteBatch.Draw(tex, position - Main.screenPosition, projectile.DrawFrame(), Color.White * Opacity, 0, projectile.DrawFrame().Size() / 2, projectile.scale, SpriteEffects.None, 0);
spriteBatch.Draw(pupiltex, position + (Vector2.UnitY * 8) + (Vector2.UnitX.RotatedBy(projectile.rotation) * projectile.localAI[0]) - Main.screenPosition, null, Color.White * Opacity,
0, pupiltex.Size() / 2, projectile.scale * 0.75f, SpriteEffects.None, 0);
}
switch (projectile.ai[0])
{
case 0://fade in
case 3:
for (int i = 0; i < 4; i++)
{
Vector2 pos = new Vector2(0, projectile.alpha / 3f);
pos = pos.RotatedBy((i / 4f * MathHelper.TwoPi) + MathHelper.ToRadians(projectile.alpha * 0.2f));
DrawEye(pos + projectile.Center, projectile.Opacity / 2);
}
break;
case 1:
case 2:
DrawEye(projectile.Center, projectile.Opacity);
for (int i = 0; i < 3; i++)
{
Vector2 pos = new Vector2(0, 5) * (float)(Math.Sin(Main.GlobalTime * 6) / 4 + 0.75);
pos = pos.RotatedBy(i / 3f * MathHelper.TwoPi);
DrawEye(pos + projectile.Center, projectile.Opacity / 2);
}
if (projectile.localAI[1] < 30f)
{
Texture2D raytelegraph = mod.GetTexture("Textures/Medusa_Ray");
float Opacity = Math.Min((projectile.localAI[1] + projectile.localAI[0]) / 25f, 0.5f);
spriteBatch.Draw(raytelegraph, projectile.Center + (Vector2.UnitX.RotatedBy(projectile.rotation) * projectile.localAI[0]) - Main.screenPosition, null, Color.Red * Opacity,
projectile.rotation, new Vector2(0, raytelegraph.Height / 2), new Vector2(24f, 0.5f * projectile.scale), SpriteEffects.None, 0);
}
break;
}
return false;
}
public void AdditiveCall(SpriteBatch spriteBatch)
{
Texture2D bloom = mod.GetTexture("Effects/Masks/CircleGradient");
spriteBatch.Draw(bloom, projectile.Center - Main.screenPosition, null, Color.Red * projectile.Opacity * 0.5f, 0, bloom.Size() / 2, new Vector2(1, 0.75f) * projectile.scale / 2, SpriteEffects.None, 0);
}
public override bool CanDamage() => false;
public NPC Parent => Main.npc[(int)projectile.ai[1]];
public Player Target => Main.player[Parent.target];
public virtual bool ShootProj => true;
public override void AI()
{
if(Parent.type != ModContent.NPCType<BloodGazer>() || !Parent.active || Target.dead || !Target.active) {
projectile.Kill();
return;
}
projectile.frameCounter++;
if(projectile.frameCounter > 10)
{
projectile.frame++;
projectile.frameCounter = 0;
if (projectile.frame >= Main.projFrames[projectile.type])
projectile.frame = 0;
}
switch (projectile.ai[0])
{
case 0://fade in
projectile.rotation = projectile.AngleTo(Target.Center);
projectile.alpha = (int)MathHelper.Lerp(projectile.alpha, 0, 0.06f);
if (projectile.alpha <= 1){
projectile.ai[0]++;
projectile.alpha = 0;
}
break;
case 1: //aim at player
projectile.rotation = Utils.AngleLerp(projectile.rotation, projectile.AngleTo(Target.Center), 0.12f);
projectile.localAI[0] = MathHelper.Lerp(projectile.localAI[0], 10f, 0.07f);
if(projectile.localAI[0] > 7.5){ //move from center to edge
projectile.localAI[0] = 10f;
projectile.ai[0]++;
}
break;
case 2: //shoot projectile
if(++projectile.localAI[1] == 30 && ShootProj)
{
if (Main.netMode != NetmodeID.Server)
Main.PlaySound(SoundID.Item, (int)projectile.Center.X, (int)projectile.Center.Y, 12, 1, -1f);
if(Main.netMode != NetmodeID.MultiplayerClient)
Projectile.NewProjectileDirect(projectile.Center + (Vector2.UnitX.RotatedBy(projectile.rotation) * projectile.localAI[0]),
Vector2.UnitX.RotatedBy(projectile.rotation) * 10, ModContent.ProjectileType<BrimstoneLaser>(), projectile.damage, 1f, Main.myPlayer).netUpdate = true;
}
if (projectile.localAI[1] == 40)
projectile.ai[0]++;
break;
case 3: //fade out
projectile.localAI[0] = MathHelper.Lerp(projectile.localAI[0], 0, 0.12f);
projectile.alpha = (int)MathHelper.Lerp(projectile.alpha, 255, 0.06f);
if (projectile.alpha >= 230)
projectile.Kill();
break;
}
}
}
internal class BrimstoneLaser : StarLaser, ITrailProjectile
{
public override string Texture => "Terraria/Projectile_1";
public override void SetStaticDefaults() => DisplayName.SetDefault("Brimstone Laser");
public override void SetDefaults()
{
base.SetDefaults();
projectile.timeLeft *= 2;
}
public override void AI()
{
projectile.ai[0]++;
}
new public void DoTrailCreation(TrailManager tManager)
{
tManager.CreateTrail(projectile, new StandardColorTrail(Color.Red * 0.8f), new RoundCap(), new DefaultTrailPosition(), 15f, 1950f, new ImageShader(mod.GetTexture("Textures/Trails/Trail_2"), Vector2.One));
tManager.CreateTrail(projectile, new StandardColorTrail(Color.Red * 0.5f), new RoundCap(), new DefaultTrailPosition(), 30f, 1950f);
}
}
public class MortarEye : ModProjectile
{
public override string Texture => "SpiritMod/NPCs/BloodGazer/BloodGazerEye";
public override void SetStaticDefaults() => DisplayName.SetDefault("Detatched Eye");
public override void SetDefaults()
{
projectile.Size = Vector2.One * 30;
projectile.hostile = true;
}
public override void AI()
{
if (projectile.localAI[0] == 0)
{
projectile.localAI[0]++;
InitializeChain(Main.npc[(int)projectile.ai[0]].Center);
}
projectile.velocity.Y += 0.35f;
NPC parent = Main.npc[(int)projectile.ai[0]];
if(!parent.active || parent.type != ModContent.NPCType<BloodGazer>())
{
projectile.Kill();
return;
}
chain.Update(Main.npc[(int)projectile.ai[0]].Center, projectile.Center);
}
private Chain chain;
public void InitializeChain(Vector2 position) => chain = new Chain(8, 8, position, new ChainPhysics(0.9f, 0.5f, 0f), false, true);
public override bool PreDraw(SpriteBatch spriteBatch, Color drawColor)
{
if (chain == null)
return false;
Texture2D chaintex = ModContent.GetTexture(Texture + "_chain");
chain.Draw(spriteBatch, chaintex);
Texture2D tex = Main.projectileTexture[projectile.type];
spriteBatch.Draw(tex, chain.EndPosition - new Vector2(chaintex.Height / 2, -chaintex.Width / 2).RotatedBy(chain.EndRotation) - Main.screenPosition, tex.Bounds, drawColor, chain.EndRotation, tex.Bounds.Size() / 2, projectile.scale, SpriteEffects.None, 0);
return false;
}
public override void Kill(int timeLeft)
{
if (Main.netMode != NetmodeID.Server)
Main.PlaySound(SoundID.NPCDeath22, projectile.Center);
Gore.NewGoreDirect(projectile.position, projectile.velocity / 2, mod.GetGoreSlot("Gores/Gazer/GazerEye"), 1f).timeLeft = 10;
foreach (var segment in chain.Segments)
Gore.NewGoreDirect(segment.Vertex2.Position, projectile.velocity / 2, mod.GetGoreSlot("Gores/Gazer/GazerChain"), 1f).timeLeft = 10;
}
}
}
| 0 | 0.848468 | 1 | 0.848468 | game-dev | MEDIA | 0.987247 | game-dev | 0.990861 | 1 | 0.990861 |
klikli-dev/occultism | 5,159 | src/main/java/com/klikli_dev/occultism/common/ritual/ResurrectFamiliarRitual.java | /*
* MIT License
*
* Copyright 2020 klikli-dev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package com.klikli_dev.occultism.common.ritual;
import com.klikli_dev.occultism.common.blockentity.GoldenSacrificialBowlBlockEntity;
import com.klikli_dev.occultism.common.entity.familiar.FamiliarEntity;
import com.klikli_dev.occultism.common.entity.spirit.demonicpartner.DemonicPartner;
import com.klikli_dev.occultism.crafting.recipe.RitualRecipe;
import com.klikli_dev.occultism.registry.OccultismAdvancements;
import com.klikli_dev.occultism.registry.OccultismItems;
import com.klikli_dev.occultism.registry.OccultismSounds;
import com.klikli_dev.occultism.util.EntityUtil;
import com.klikli_dev.occultism.util.ItemNBTUtil;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;
public class ResurrectFamiliarRitual extends SummonRitual {
public ResurrectFamiliarRitual(RitualRecipe recipe) {
super(recipe, true);
}
@Override
public void finish(Level level, BlockPos goldenBowlPosition, GoldenSacrificialBowlBlockEntity blockEntity,
@Nullable ServerPlayer castingPlayer, ItemStack activationItem) {
//manually call content of Ritual.finish(), because we cannot access it via super
level.playSound(null, goldenBowlPosition, OccultismSounds.POOF.get(), SoundSource.BLOCKS, 0.7f,
0.7f);
if(castingPlayer != null){
castingPlayer.displayClientMessage(Component.translatable(this.getFinishedMessage(castingPlayer)), true);
OccultismAdvancements.RITUAL.get().trigger( castingPlayer, this);
}
var shard = activationItem.copy();
activationItem.shrink(1); //remove original activation item.
((ServerLevel) level).sendParticles(ParticleTypes.LARGE_SMOKE, goldenBowlPosition.getX() + 0.5,
goldenBowlPosition.getY() + 0.5, goldenBowlPosition.getZ() + 0.5, 1, 0, 0, 0, 0);
//copied and modified from soul gem item
if (shard.has(DataComponents.ENTITY_DATA)) {
//whenever we have an entity stored we can do nothing but release it
var entityData = shard.get(DataComponents.ENTITY_DATA).getUnsafe();
var type = EntityUtil.entityTypeFromNbt(entityData);
BlockPos spawnPos = goldenBowlPosition;
//remove position from tag to allow the entity to spawn where it should be
entityData.remove("Pos");
//type.spawn uses the sub-tag EntityTag
CompoundTag wrapper = new CompoundTag();
wrapper.put("EntityTag", entityData);
Entity entity = type.create(level);
entity.load(entityData);
if (blockEntity.getTier(blockEntity.getBlockState()) == 3) {
entity.absMoveTo(spawnPos.getX() + 0.5, spawnPos.getY() + 1, spawnPos.getZ() + 0.5, 0, 0);
} else {
entity.absMoveTo(spawnPos.getX() + 0.5, spawnPos.getY(), spawnPos.getZ() + 0.5, 0, 0);
}
level.addFreshEntity(entity);
if (entity instanceof FamiliarEntity familiar && castingPlayer != null)
familiar.setFamiliarOwner(castingPlayer);
if (entity instanceof DemonicPartner partner && castingPlayer != null)
partner.setOwnerUUID(castingPlayer.getUUID());
}
ItemStack flame = OccultismItems.FLAME_AUTOMATION.toStack();
ItemNBTUtil.setBoundSpiritName(flame,
this.recipe.getRitualDummy().toString().substring(2).replace("occultism:ritual_dummy/",""));
this.dropResult(level, goldenBowlPosition, blockEntity, castingPlayer, flame, false);
}
}
| 0 | 0.899006 | 1 | 0.899006 | game-dev | MEDIA | 0.944466 | game-dev | 0.881884 | 1 | 0.881884 |
hornyyy/Osu-Toy | 2,932 | osu.Game/Screens/Select/FooterButtonMods.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Screens.Play.HUD;
using osu.Game.Rulesets.Mods;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Screens.Select
{
public class FooterButtonMods : FooterButton, IHasCurrentValue<IReadOnlyList<Mod>>
{
public Bindable<IReadOnlyList<Mod>> Current
{
get => modDisplay.Current;
set => modDisplay.Current = value;
}
protected readonly OsuSpriteText MultiplierText;
private readonly ModDisplay modDisplay;
private Color4 lowMultiplierColour;
private Color4 highMultiplierColour;
public FooterButtonMods()
{
ButtonContentContainer.Add(modDisplay = new ModDisplay
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
DisplayUnrankedText = false,
Scale = new Vector2(0.8f),
ExpansionMode = ExpansionMode.AlwaysContracted,
});
ButtonContentContainer.Add(MultiplierText = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.GetFont(weight: FontWeight.Bold),
});
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
SelectedColour = colours.Yellow;
DeselectedColour = SelectedColour.Opacity(0.5f);
lowMultiplierColour = colours.Red;
highMultiplierColour = colours.Green;
Text = @"mods";
Hotkey = Key.F1;
}
protected override void LoadComplete()
{
base.LoadComplete();
Current.BindValueChanged(_ => updateMultiplierText(), true);
}
private void updateMultiplierText()
{
double multiplier = Current.Value?.Aggregate(1.0, (current, mod) => current * mod.ScoreMultiplier) ?? 1;
MultiplierText.Text = multiplier.Equals(1.0) ? string.Empty : $"{multiplier:N2}x";
if (multiplier > 1.0)
MultiplierText.FadeColour(highMultiplierColour, 200);
else if (multiplier < 1.0)
MultiplierText.FadeColour(lowMultiplierColour, 200);
else
MultiplierText.FadeColour(Color4.White, 200);
if (Current.Value?.Count > 0)
modDisplay.FadeIn();
else
modDisplay.FadeOut();
}
}
}
| 0 | 0.754225 | 1 | 0.754225 | game-dev | MEDIA | 0.78393 | game-dev | 0.945531 | 1 | 0.945531 |
marrub--/GLOOME | 3,430 | src/d_main.h | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// $Log:$
//
// DESCRIPTION:
// System specific interface stuff.
//
//-----------------------------------------------------------------------------
#ifndef __D_MAIN__
#define __D_MAIN__
#include "doomtype.h"
#include "gametype.h"
struct event_t;
//
// D_DoomMain()
// Not a globally visible function, just included for source reference,
// calls all startup code, parses command line options.
// If not overrided by user input, calls N_AdvanceDemo.
//
struct CRestartException
{
char dummy;
};
void D_DoomMain (void);
void D_Display ();
//
// BASE LEVEL
//
void D_PageTicker (void);
void D_AdvanceDemo (void);
void D_StartTitle (void);
bool D_AddFile (TArray<FString> &wadfiles, const char *file, bool check = true, int position = -1);
// [RH] Set this to something to draw an icon during the next screen refresh.
extern const char *D_DrawIcon;
struct WadStuff
{
WadStuff() : Type(0) {}
FString Path;
FString Name;
int Type;
};
struct FIWADInfo
{
FString Name; // Title banner text for this IWAD
FString Autoname; // Name of autoload ini section for this IWAD
FString Configname; // Name of config section for this IWAD
FString Required; // Requires another IWAD
DWORD FgColor; // Foreground color for title banner
DWORD BkColor; // Background color for title banner
EGameType gametype; // which game are we playing?
FString MapInfo; // Base mapinfo to load
TArray<FString> Load; // Wads to be loaded with this one.
TArray<FString> Lumps; // Lump names for identification
int flags;
int preload;
FIWADInfo() { flags = 0; preload = -1; FgColor = 0; BkColor= 0xc0c0c0; gametype = GAME_Doom; }
};
struct FStartupInfo
{
FString Name;
DWORD FgColor; // Foreground color for title banner
DWORD BkColor; // Background color for title banner
FString Song;
int Type;
enum
{
DefaultStartup,
DoomStartup,
HereticStartup,
HexenStartup,
StrifeStartup,
};
};
extern FStartupInfo DoomStartupInfo;
//==========================================================================
//
// IWAD identifier class
//
//==========================================================================
struct FIWadManager
{
private:
TArray<FIWADInfo> mIWads;
TArray<FString> mIWadNames;
TArray<int> mLumpsFound;
void ParseIWadInfo(const char *fn, const char *data, int datasize);
void ParseIWadInfos(const char *fn);
void ClearChecks();
void CheckLumpName(const char *name);
int GetIWadInfo();
int ScanIWAD (const char *iwad);
int CheckIWAD (const char *doomwaddir, WadStuff *wads);
int IdentifyVersion (TArray<FString> &wadfiles, const char *iwad, const char *zdoom_wad);
public:
const FIWADInfo *FindIWAD(TArray<FString> &wadfiles, const char *iwad, const char *basewad);
};
#endif
| 0 | 0.877833 | 1 | 0.877833 | game-dev | MEDIA | 0.938175 | game-dev | 0.590026 | 1 | 0.590026 |
Engine-Room/Flywheel | 2,230 | common/src/main/java/dev/engine_room/flywheel/impl/visualization/storage/BlockEntityStorage.java | package dev.engine_room.flywheel.impl.visualization.storage;
import org.jetbrains.annotations.Nullable;
import dev.engine_room.flywheel.api.visual.BlockEntityVisual;
import dev.engine_room.flywheel.api.visualization.VisualizationContext;
import dev.engine_room.flywheel.lib.visualization.VisualizationHelper;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
public class BlockEntityStorage extends Storage<BlockEntity> {
private final Long2ObjectMap<BlockEntityVisual<?>> posLookup = new Long2ObjectOpenHashMap<>();
@Nullable
public BlockEntityVisual<?> visualAtPos(long pos) {
return posLookup.get(pos);
}
@Override
public boolean willAccept(BlockEntity blockEntity) {
if (blockEntity.isRemoved()) {
return false;
}
if (!VisualizationHelper.canVisualize(blockEntity)) {
return false;
}
Level level = blockEntity.getLevel();
if (level == null) {
return false;
}
if (level.isEmptyBlock(blockEntity.getBlockPos())) {
return false;
}
BlockPos pos = blockEntity.getBlockPos();
BlockGetter existingChunk = level.getChunkForCollisions(pos.getX() >> 4, pos.getZ() >> 4);
return existingChunk != null;
}
@Override
@Nullable
protected BlockEntityVisual<?> createRaw(VisualizationContext visualizationContext, BlockEntity obj, float partialTick) {
var visualizer = VisualizationHelper.getVisualizer(obj);
if (visualizer == null) {
return null;
}
var visual = visualizer.createVisual(visualizationContext, obj, partialTick);
BlockPos blockPos = obj.getBlockPos();
posLookup.put(blockPos.asLong(), visual);
return visual;
}
@Override
public void remove(BlockEntity obj) {
posLookup.remove(obj.getBlockPos()
.asLong());
super.remove(obj);
}
@Override
public void recreateAll(VisualizationContext visualizationContext, float partialTick) {
posLookup.clear();
super.recreateAll(visualizationContext, partialTick);
}
@Override
public void invalidate() {
posLookup.clear();
super.invalidate();
}
}
| 0 | 0.89989 | 1 | 0.89989 | game-dev | MEDIA | 0.672591 | game-dev | 0.941831 | 1 | 0.941831 |
godotengine/godot | 3,367 | scene/3d/physics/joints/joint_3d.h | /**************************************************************************/
/* joint_3d.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* 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. */
/**************************************************************************/
#pragma once
#include "scene/3d/node_3d.h"
#include "scene/3d/physics/physics_body_3d.h"
class Joint3D : public Node3D {
GDCLASS(Joint3D, Node3D);
RID ba, bb;
RID joint;
NodePath a;
NodePath b;
int solver_priority = 1;
bool exclude_from_collision = true;
String warning;
bool configured = false;
protected:
void _disconnect_signals();
void _body_exit_tree();
void _update_joint(bool p_only_free = false);
void _notification(int p_what);
virtual void _configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) = 0;
static void _bind_methods();
_FORCE_INLINE_ bool is_configured() const { return configured; }
public:
virtual PackedStringArray get_configuration_warnings() const override;
void set_node_a(const NodePath &p_node_a);
NodePath get_node_a() const;
void set_node_b(const NodePath &p_node_b);
NodePath get_node_b() const;
void set_solver_priority(int p_priority);
int get_solver_priority() const;
void set_exclude_nodes_from_collision(bool p_enable);
bool get_exclude_nodes_from_collision() const;
RID get_rid() const { return joint; }
Joint3D();
~Joint3D();
};
| 0 | 0.889212 | 1 | 0.889212 | game-dev | MEDIA | 0.926974 | game-dev | 0.619187 | 1 | 0.619187 |
latte-soft/builtinplugins | 1,816 | src/BuiltInPlugins/TerrainEditor/Src/Util/BiomeGenerators/Canyons.luau | local l_script_FirstAncestor_0 = script:FindFirstAncestor("TerrainEditor");
local l_Generation_0 = l_script_FirstAncestor_0.Src.Util.Generation;
local v2 = require(l_Generation_0.Filter);
local _ = require(l_Generation_0.NoisySeed);
local _ = require(l_Generation_0.Perlin);
local v5 = require(l_Generation_0.ProcessPerlin);
local _ = require(l_script_FirstAncestor_0.Src.Types);
return function(v7, v8, v9)
local v10 = {
Enum.Material.Rock,
Enum.Material.Mud,
Enum.Material.Sand,
Enum.Material.Sand,
Enum.Material.Sandstone,
Enum.Material.Sandstone,
Enum.Material.Sandstone,
Enum.Material.Sandstone,
Enum.Material.Sandstone,
Enum.Material.Sandstone
};
return function(v11, v12, _)
local l_X_0 = v11.X;
local l_Y_0 = v11.Y;
local l_Z_0 = v11.Z;
local v17 = Vector3.new(l_X_0, 0, l_Z_0);
local l_WaterLevel_0 = v9.WaterLevel;
local v19 = v2.RidgeFlipped(v5(v7(v17, 2, 200)));
local v20 = v2.RidgeFlipped(v5(v7(Vector3.new(l_X_0 + v7(v17, 5, 20) * 20, 0, l_Z_0 + v7(v17, 9, 20) * 20), 2, 200)));
local v21 = v2.Threshold(v20, 0, 0.05);
return ((((((((((0.42 + v5(v7(v11, 2, 70)) * 0.05) + v19 * 0.05) + v21 * 0.04) + v2.Threshold(v20, 0.05, 0) * 0.08) + v2.Threshold(v20, 0.05, 0.075) * 0.04) + v2.Threshold(v20, 0.125, 0) * 0.01) + v2.Threshold(v20, 0.0575, 0.2725) * 0.01) + v2.Threshold(v19, 0.33, 0.12) * 0.06) + v2.Threshold(v20, 0.45, 0) * 0.14) + v2.Threshold(v20, 0.45, 0.04) * 0.025) + v2.Threshold(v20, 0.49, 0) * 0.02, if 1 - v12 < l_WaterLevel_0 + 0.015 then Enum.Material.Sand else if v21 > 0 and v21 < 1 then Enum.Material.Sand else Enum.Material.Sandstone, v10[math.ceil((1 - v8((Vector3.new(1, l_Y_0, 2)))) * 10)];
end;
end;
| 0 | 0.685664 | 1 | 0.685664 | game-dev | MEDIA | 0.774653 | game-dev | 0.922592 | 1 | 0.922592 |
scalableminds/webknossos | 3,416 | frontend/javascripts/viewer/model/accessors/tracing_accessor.ts | import _ from "lodash";
import type { TracingType } from "types/api_types";
import { TracingTypeEnum } from "types/api_types";
import type { Vector3 } from "viewer/constants";
import type { SaveQueueType } from "viewer/model/actions/save_actions";
import type { UserBoundingBox } from "viewer/store";
import type {
EditableMapping,
ReadOnlyTracing,
SkeletonTracing,
StoreAnnotation,
VolumeTracing,
WebknossosState,
} from "viewer/store";
import BoundingBox from "../bucket_data_handling/bounding_box";
import { reuseInstanceOnEquality } from "./accessor_helpers";
export function maybeGetSomeTracing(
annotation: StoreAnnotation,
): SkeletonTracing | VolumeTracing | ReadOnlyTracing | null {
if (annotation.skeleton != null) {
return annotation.skeleton;
} else if (annotation.volumes.length > 0) {
return annotation.volumes[0];
} else if (annotation.readOnly != null) {
return annotation.readOnly;
}
return null;
}
export function getSomeTracing(
annotation: StoreAnnotation,
): SkeletonTracing | VolumeTracing | ReadOnlyTracing {
const maybeSomeTracing = maybeGetSomeTracing(annotation);
if (maybeSomeTracing == null) {
throw new Error("The active annotation does not contain skeletons nor volume data");
}
return maybeSomeTracing;
}
export function getTracingType(annotation: StoreAnnotation): TracingType {
if (annotation.skeleton != null && annotation.volumes.length > 0) {
return TracingTypeEnum.hybrid;
} else if (annotation.skeleton != null) {
return TracingTypeEnum.skeleton;
} else if (annotation.volumes.length > 0) {
return TracingTypeEnum.volume;
}
throw new Error("The active annotation does not contain skeletons nor volume data");
}
export function selectTracing(
state: WebknossosState,
tracingType: SaveQueueType,
tracingId: string,
): SkeletonTracing | VolumeTracing | EditableMapping {
let tracing;
switch (tracingType) {
case "skeleton": {
tracing = state.annotation.skeleton;
break;
}
case "volume": {
tracing = state.annotation.volumes.find(
(volumeTracing) => volumeTracing.tracingId === tracingId,
);
break;
}
case "mapping": {
tracing = state.annotation.mappings.find((mapping) => mapping.tracingId === tracingId);
break;
}
default: {
throw new Error(`Unknown tracing type: ${tracingType}`);
}
}
if (tracing == null) {
throw new Error(`${tracingType} object with id ${tracingId} not found`);
}
return tracing;
}
function _getTaskBoundingBoxes(state: WebknossosState) {
const { annotation, task } = state;
if (task == null) return {};
const layers = _.compact([annotation.skeleton, ...annotation.volumes]);
return Object.fromEntries(layers.map((l) => [l.tracingId, l.boundingBox]));
}
export const getTaskBoundingBoxes = reuseInstanceOnEquality(_getTaskBoundingBoxes);
export const getUserBoundingBoxesFromState = (state: WebknossosState): UserBoundingBox[] => {
const maybeSomeTracing = maybeGetSomeTracing(state.annotation);
return maybeSomeTracing != null ? maybeSomeTracing.userBoundingBoxes : [];
};
export const getUserBoundingBoxesThatContainPosition = (
state: WebknossosState,
position: Vector3,
): UserBoundingBox[] => {
const bboxes = getUserBoundingBoxesFromState(state);
return bboxes.filter((el) => new BoundingBox(el.boundingBox).containsPoint(position));
};
| 0 | 0.938435 | 1 | 0.938435 | game-dev | MEDIA | 0.449313 | game-dev | 0.972689 | 1 | 0.972689 |
ARM-software/gator | 32,496 | daemon/events-Mali-G51_hw.xml | <!-- Copyright (C) 2017-2025 by Arm Limited. All rights reserved. -->
<category name="Mali Job Manager" per_cpu="no">
<event counter="ARM_Mali-G51_GPU_ACTIVE" description="The number of cycles when the GPU has a workload of any type queued for processing" name="GPU active" title="Mali GPU Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_IRQ_ACTIVE" description="The number of cycles when the GPU has a pending interrupt" name="GPU interrupt active" title="Mali GPU Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS0_JOBS" description="The number of jobs processed by the GPU fragment queue" name="Fragment jobs" title="Mali GPU Jobs" units="jobs"/>
<event counter="ARM_Mali-G51_JS0_TASKS" description="The number of fragment tasks processed" name="Fragment tasks" title="Mali GPU Tasks" units="tasks"/>
<event counter="ARM_Mali-G51_JS0_ACTIVE" description="The number of cycles when work is queued for processing in the GPU fragment queue" name="Fragment queue active" title="Mali GPU Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS0_WAIT_FLUSH" description="The number of cycles when queued fragment work is waiting for a cache flush" name="Fragment queue cache flush stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS0_WAIT_READ" description="The number of cycles when queued fragment work is waiting for a descriptor load" name="Fragment queue descriptor read stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS0_WAIT_ISSUE" description="The number of cycles when queued fragment work is waiting for an available processor" name="Fragment queue job issue stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS0_WAIT_DEPEND" description="The number of cycles when queued fragment work is waiting for dependent work to complete" name="Fragment queue job dependency stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS0_WAIT_FINISH" description="The number of cycles when the GPU is waiting for issued fragment work to complete" name="Fragment queue job finish stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_JOBS" description="The number of jobs processed by the GPU non-fragment queue" name="Non-fragment jobs" title="Mali GPU Jobs" units="jobs"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_TASKS" description="The number of non-fragment tasks processed" name="Non-fragment tasks" title="Mali GPU Tasks" units="tasks"/>
<event counter="ARM_Mali-G51_JS1_ACTIVE" description="The number of cycles when work is queued in the GPU non-fragment queue" name="Non-fragment queue active" title="Mali GPU Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_WAIT_FLUSH" description="The number of cycles when queued non-fragment work is waiting for a cache flush" name="Non-fragment queue cache flush stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_WAIT_READ" description="The number number of cycles where queued non-fragment work is waiting for a descriptor load" name="Non-fragment queue descriptor read stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_WAIT_ISSUE" description="The number of cycles when queued non-fragment work is waiting for an available processor" name="Non-fragment queue job issue stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_WAIT_DEPEND" description="The number of cycles when queued non-fragment work is waiting for dependent work to complete" name="Non-fragment queue job dependency stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS1_WAIT_FINISH" description="The number of cycles when the GPU is waiting for issued non-fragment work to complete" name="Non-fragment queue job finish stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_JOBS" description="The number of jobs processed by the GPU reserved queue" name="Reserved jobs" title="Mali GPU Jobs" units="jobs"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_TASKS" description="The number of reserved tasks processed" name="Reserved tasks" title="Mali GPU Tasks" units="tasks"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_ACTIVE" description="The number of cycles when work is queued in the GPU reserved queue" name="Reserved queue active" title="Mali GPU Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_WAIT_FLUSH" description="The number of cycles when queued reserved work is waiting for a cache flush" name="Reserved queue cache flush stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_WAIT_READ" description="The number of cycles when queued reserved work is waiting for a descriptor load" name="Reserved queue descriptor read stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_WAIT_ISSUE" description="The number of cycles when queued reserved work is waiting for an available processor" name="Reserved queue job issue stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_WAIT_DEPEND" description="The number of cycles when queued reserved work is waiting for dependent work to complete" name="Reserved queue job dependency stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_JS2_WAIT_FINISH" description="The number of cycles when the GPU is waiting for issued reserved work to complete" name="Reserved queue job finish stall" title="Mali GPU Wait Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_CACHE_FLUSH" description="The number of GPU L2 cache flushes performed" name="L2 cache flushes" title="Mali GPU Cache Flushes" units="requests"/>
</category>
<category name="Mali Tiler" per_cpu="no">
<event advanced="yes" counter="ARM_Mali-G51_TILER_ACTIVE" description="The number of cycles when the tiler has a workload queued for processing" name="Tiler active" title="Mali GPU Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_TRIANGLES" description="The number of input triangle primitives" name="Triangle primitives" title="Mali Input Primitives" units="primitives"/>
<event counter="ARM_Mali-G51_LINES" description="The number of input line primitives" name="Line primitives" title="Mali Input Primitives" units="primitives"/>
<event counter="ARM_Mali-G51_POINTS" description="The number of input point primitives" name="Point primitives" title="Mali Input Primitives" units="primitives"/>
<event advanced="yes" counter="ARM_Mali-G51_FRONT_FACING" description="The number of front-facing triangles that are visible after culling" name="Front-facing primitives" title="Mali Visible Primitives" units="primitives"/>
<event advanced="yes" counter="ARM_Mali-G51_BACK_FACING" description="The number of back-facing triangles that are visible after culling" name="Back-facing primitives" title="Mali Visible Primitives" units="primitives"/>
<event counter="ARM_Mali-G51_PRIM_VISIBLE" description="The number of primitives that are visible after culling" name="Visible primitives" title="Mali Primitive Culling" units="primitives"/>
<event counter="ARM_Mali-G51_PRIM_CULLED" description="The number of primitives that are culled by facing or frustum XY plane tests" name="Facing or XY plane test culled primitives" title="Mali Primitive Culling" units="primitives"/>
<event counter="ARM_Mali-G51_PRIM_CLIPPED" description="The number of primitives that are culled by frustum Z plane tests" name="Z plane test culled primitives" title="Mali Primitive Culling" units="primitives"/>
<event counter="ARM_Mali-G51_PRIM_SAT_CULLED" description="The number of primitives culled by the sample coverage test" name="Sample test culled primitives" title="Mali Primitive Culling" units="primitives"/>
<event advanced="yes" counter="ARM_Mali-G51_BUS_READ" description="The number of internal bus data read cycles made by the tiler" name="Read beats" title="Mali Tiler L2 Accesses" units="beats"/>
<event advanced="yes" counter="ARM_Mali-G51_BUS_WRITE" description="The number of internal bus data write cycles made by the tiler" name="Write beats" title="Mali Tiler L2 Accesses" units="beats"/>
<event counter="ARM_Mali-G51_IDVS_POS_SHAD_REQ" description="The number of position shading requests in the tiler geometry flow" name="Position shading requests" title="Mali Tiler Shading Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_IDVS_POS_SHAD_STALL" description="The number of cycles when the tiler has a stalled position shading request" name="Position shading stall" title="Mali Tiler Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_IDVS_POS_FIFO_FULL" description="The number of cycles when the tiler has a stalled position shading buffer" name="Position FIFO full stall" title="Mali Tiler Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_VCACHE_HIT" description="The number of position lookups that result in a hit in the vertex cache" name="Position cache hits" title="Mali Tiler Vertex Cache" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_VCACHE_MISS" description="The number of position lookups that miss in the vertex cache" name="Position cache misses" title="Mali Tiler Vertex Cache" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_IDVS_VBU_HIT" description="The number of varying lookups that result in a hit in the vertex cache" name="Varying cache hits" title="Mali Tiler Vertex Cache" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_IDVS_VBU_MISS" description="The number of varying lookups that miss in the vertex cache" name="Varying cache misses" title="Mali Tiler Vertex Cache" units="requests"/>
<event counter="ARM_Mali-G51_IDVS_VAR_SHAD_REQ" description="The number of varying shading requests in the tiler geometry flow" name="Varying shading requests" title="Mali Tiler Shading Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_IDVS_VAR_SHAD_STALL" description="The number of cycles when the tiler has a stalled varying shading request" name="Varying shading stall" title="Mali Tiler Stall Cycles" units="cycles"/>
</category>
<category name="Mali Shader Core" per_cpu="no">
<event counter="ARM_Mali-G51_FRAG_ACTIVE" description="The number of cycles when the shader core is processing a fragment workload" name="Fragment active" title="Mali Shader Core Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_FRAG_PRIMITIVES" description="The number of primitives loaded from the tile list by the fragment front-end" name="Loaded primitives" title="Mali Fragment Primitives" units="primitives"/>
<event counter="ARM_Mali-G51_FRAG_PRIM_RAST" description="The number of primitives being rasterized" name="Rasterized primitives" title="Mali Fragment Primitives" units="primitives"/>
<event counter="ARM_Mali-G51_FRAG_FPK_ACTIVE" description="The number of cycles when at least one quad is present in the pre-pipe quad queue" name="Fragment FPK buffer active" title="Mali Shader Core Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_FRAG_WARPS" description="The number of fragment warps created" name="Fragment warps" title="Mali Shader Warps" units="warps"/>
<event counter="ARM_Mali-G51_FRAG_PARTIAL_WARPS" description="The number of fragment warps containing helper threads that do not correspond to a hit sample point" name="Partial fragment warps" title="Mali Shader Warps" units="warps"/>
<event counter="ARM_Mali-G51_FRAG_QUADS_RAST" description="The number of fine quads generated by the rasterization phase" name="Rasterized fine quads" title="Mali Fragment Quads" units="quads"/>
<event counter="ARM_Mali-G51_FRAG_QUADS_EZS_TEST" description="The number of quads that are undergoing early depth and stencil testing" name="Early ZS tested quads" title="Mali Fragment ZS Quads" units="quads"/>
<event counter="ARM_Mali-G51_FRAG_QUADS_EZS_UPDATE" description="The number of quads undergoing early depth and stencil testing, that are capable of updating the framebuffer" name="Early ZS updated quads" title="Mali Fragment ZS Quads" units="quads"/>
<event counter="ARM_Mali-G51_FRAG_QUADS_EZS_KILL" description="The number of quads killed by early depth and stencil testing" name="Early ZS killed quads" title="Mali Fragment ZS Quads" units="quads"/>
<event counter="ARM_Mali-G51_FRAG_LZS_TEST" description="The number of quads undergoing late depth and stencil testing" name="Late ZS tested quads" title="Mali Fragment ZS Quads" units="quads"/>
<event counter="ARM_Mali-G51_FRAG_LZS_KILL" description="The number of quads killed by late depth and stencil testing" name="Late ZS killed quads" title="Mali Fragment ZS Quads" units="quads"/>
<event counter="ARM_Mali-G51_FRAG_PTILES" description="The number of tiles processed by the shader core" name="Tiles" title="Mali Shader Core Tiles" units="tiles"/>
<event counter="ARM_Mali-G51_FRAG_TRANS_ELIM" description="The number of tiles killed by transaction elimination" name="Killed unchanged tiles" title="Mali Shader Core Tiles" units="tiles"/>
<event counter="ARM_Mali-G51_QUAD_FPK_KILLER" description="The number of quads that are valid occluders for hidden surface removal" name="Occluding quads" title="Mali Fragment FPK Quads" units="quads"/>
<event counter="ARM_Mali-G51_COMPUTE_ACTIVE" description="The number of cycles when the shader core is processing some non-fragment workload" name="Non-fragment active" title="Mali Shader Core Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_COMPUTE_TASKS" description="The number of non-fragment tasks issued to the shader core" name="Non-fragment tasks" title="Mali Shader Core Tasks" units="tasks"/>
<event counter="ARM_Mali-G51_COMPUTE_WARPS" description="The number of non-fragment warps created" name="Non-fragment warps" title="Mali Shader Warps" units="warps"/>
<event counter="ARM_Mali-G51_EXEC_CORE_ACTIVE" description="The number of cycles when the shader core is processing at least one warp" name="Execution core active" title="Mali Shader Core Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_EXEC_ACTIVE" description="The number of cycles when the programmable shader core is processing at least one thread" name="Execution engine active" title="Mali Shader Core Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_EXEC_INSTR_COUNT" description="The number of instructions run per warp" name="Executed instructions" title="Mali ALU Instructions" units="instructions"/>
<event counter="ARM_Mali-G51_EXEC_INSTR_DIVERGED" description="The number of instructions run per warp that have control flow divergence" name="Diverged instructions" title="Mali ALU Instructions" units="instructions"/>
<event advanced="yes" counter="ARM_Mali-G51_EXEC_INSTR_STARVING" description="The number of cycles when no new threads are available to run" name="Execution engine starvation" title="Mali Shader Core Stall Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_TEX_MSGI_NUM_QUADS" description="The number of quad-width texture operations processed by the texture unit" name="Texture requests" title="Mali Texture Unit Quads" units="quads"/>
<event counter="ARM_Mali-G51_TEX_DFCH_NUM_PASSES" description="The number of quad-width filtering passes" name="Texture issues" title="Mali Texture Unit Quads" units="issues"/>
<event counter="ARM_Mali-G51_TEX_DFCH_NUM_PASSES_MISS" description="The number of quad-width filtering passes that miss in the resource or sampler descriptor cache" name="Descriptor misses" title="Mali Texture Unit Quads" units="requests"/>
<event counter="ARM_Mali-G51_TEX_DFCH_NUM_PASSES_MIP_MAP" description="The number of quad-width filtering passes that use a mipmapped texture" name="Mipmapped texture issues" title="Mali Texture Unit Quads" units="issues"/>
<event counter="ARM_Mali-G51_TEX_TIDX_NUM_SPLIT_MIP_MAP" description="The number of quad-width filtering passes that use a trilinear filter" name="Trilinear filtered issues" title="Mali Texture Unit Quads" units="issues"/>
<event counter="ARM_Mali-G51_TEX_TFCH_NUM_LINES_FETCHED" description="The number of texture line fetches from the L2 cache" name="Line fetches" title="Mali Texture Unit Cache" units="issues"/>
<event counter="ARM_Mali-G51_TEX_TFCH_NUM_LINES_FETCHED_BLOCK_COMPRESSED" description="The number of texture line fetches from the L2 cache that are block compressed textures" name="Compressed line fetches" title="Mali Texture Unit Cache" units="issues"/>
<event counter="ARM_Mali-G51_TEX_TFCH_NUM_OPERATIONS" description="The number of texture cache lookup cycles" name="Cache lookup" title="Mali Texture Unit Cache Cycles" units="requests"/>
<event counter="ARM_Mali-G51_TEX_FILT_NUM_OPERATIONS" description="The number of texture filtering issue cycles" name="Texture filtering active" title="Mali Texture Unit Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_LS_MEM_READ_FULL" description="The number of full-width load/store cache reads" name="Full read" title="Mali Load/Store Unit Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_LS_MEM_READ_SHORT" description="The number of partial-width load/store cache reads" name="Partial read" title="Mali Load/Store Unit Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_LS_MEM_WRITE_FULL" description="The number of full-width load/store cache writes" name="Full write" title="Mali Load/Store Unit Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_LS_MEM_WRITE_SHORT" description="The number of partial-width load/store cache writes" name="Partial write" title="Mali Load/Store Unit Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_LS_MEM_ATOMIC" description="The number of load/store atomic accesses" name="Atomic access" title="Mali Load/Store Unit Cycles" units="cycles"/>
<event counter="ARM_Mali-G51_VARY_INSTR" description="The number of warp-width interpolation operations processed by the varying unit" name="Interpolation requests" title="Mali Varying Unit Requests" units="requests"/>
<event counter="ARM_Mali-G51_VARY_SLOT_32" description="The number of 32-bit interpolation slots issued by the varying unit" name="32-bit interpolation issues" title="Mali Varying Unit Issues" units="issues"/>
<event counter="ARM_Mali-G51_VARY_SLOT_16" description="The number of 16-bit interpolation slots issued by the varying unit" name="16-bit interpolation issues" title="Mali Varying Unit Issues" units="issues"/>
<event advanced="yes" counter="ARM_Mali-G51_ATTR_INSTR" description="The number of instructions run by the attribute unit" name="Attribute requests" title="Mali Attribute Unit Requests" units="instructions"/>
<event counter="ARM_Mali-G51_BEATS_RD_FTC" description="The number of read beats received by the fixed-function fragment front-end" name="Fragment L2 read beats" title="Mali Shader Core L2 Reads" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_RD_FTC_EXT" description="The number of read beats received by the fixed-function fragment front-end that required an external memory access because of an L2 cache miss" name="Fragment external read beats" title="Mali Shader Core External Reads" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_RD_LSC" description="The number of read beats received by the load/store unit" name="Load/store L2 read beats" title="Mali Shader Core L2 Reads" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_RD_LSC_EXT" description="The number of read beats received by the load/store unit that required an external memory access because of an L2 cache miss" name="Load/store external read beats" title="Mali Shader Core External Reads" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_RD_TEX" description="The number of read beats received by the texture unit" name="Texture L2 read beats" title="Mali Shader Core L2 Reads" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_RD_TEX_EXT" description="The number of read beats received by the texture unit that required an external memory access because of an L2 cache miss" name="Texture external read beats" title="Mali Shader Core External Reads" units="beats"/>
<event advanced="yes" counter="ARM_Mali-G51_BEATS_RD_OTHER" description="The number of read beats received by a unit that is not specifically identified" name="Other L2 read beats" title="Mali Shader Core L2 Reads" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_WR_LSC_OTHER" description="The number of write beats by the load/store unit that are because of any reason other than write-back" name="Load/store other write beats" title="Mali Shader Core Writes" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_WR_TIB" description="The number of write beats sent by the tile write-back unit" name="Tile unit write beats" title="Mali Shader Core Writes" units="beats"/>
<event counter="ARM_Mali-G51_BEATS_WR_LSC_WB" description="The number of write beats by the load/store unit that are because of write-back" name="Load/store write-back write beats" title="Mali Shader Core Writes" units="beats"/>
</category>
<category name="Mali Memory System" per_cpu="no">
<event advanced="yes" counter="ARM_Mali-G51_MMU_REQUESTS" description="The number of main MMU address translations performed" name="MMU lookups" title="Mali Stage 1 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_TABLE_READS_L3" description="The number of level 3 translation table reads" name="L3 table reads" title="Mali Stage 1 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_TABLE_READS_L2" description="The number of level 2 translation table reads" name="L2 table reads" title="Mali Stage 1 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_HIT_L3" description="The number of level 3 translation table reads that hit in the main MMU TLB" name="L3 table read hits" title="Mali Stage 1 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_HIT_L2" description="The number of level 2 translation table reads that hit in the main MMU TLB" name="L2 table read hits" title="Mali Stage 1 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_S2_REQUESTS" description="The number of main MMU stage 2 address translations performed" name="MMU lookups" title="Mali Stage 2 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_S2_TABLE_READS_L3" description="The number of stage 2 level 3 translation table reads" name="L3 table reads" title="Mali Stage 2 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_S2_TABLE_READS_L2" description="The number of stage 2 level 2 translation table reads" name="L2 table reads" title="Mali Stage 2 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_S2_HIT_L3" description="The number of stage 2 level 3 translation table reads that hit in the main MMU TLB" name="L3 table read hits" title="Mali Stage 2 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_MMU_S2_HIT_L2" description="The number of stage 2 level 2 translation table reads that hit in the main MMU TLB" name="L2 table read hits" title="Mali Stage 2 MMU Translations" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_RD_MSG_IN" description="The number of L2 cache read requests from internal requesters" name="Read requests" title="Mali L2 Cache Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_RD_MSG_IN_STALL" description="The number of cycles L2 cache read requests from internal requesters are stalled" name="Read stall" title="Mali L2 Cache Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_WR_MSG_IN" description="The number of L2 cache write requests from internal requesters" name="Write requests" title="Mali L2 Cache Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_WR_MSG_IN_STALL" description="The number of cycles when L2 cache write requests from internal requesters are stalled" name="Write stall" title="Mali L2 Cache Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_SNP_MSG_IN" description="The number of L2 snoop requests from internal requesters" name="Snoop requests" title="Mali L2 Cache Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_SNP_MSG_IN_STALL" description="The number of cycles when L2 cache snoop requests from internal requesters are stalled" name="Snoop stall" title="Mali L2 Cache Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_RD_MSG_OUT" description="The number of L1 cache read requests sent by the L2 cache to an internal requester" name="L1 read requests" title="Mali L2 Cache Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_RD_MSG_OUT_STALL" description="The number of cycles when L1 cache read requests sent by the L2 cache to an internal requester are stalled" name="L1 read stall" title="Mali L2 Cache Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_WR_MSG_OUT" description="The number of L1 cache write responses sent by the L2 cache to an internal requester" name="L1 write requests" title="Mali L2 Cache Requests" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_ANY_LOOKUP" description="The number of L2 cache lookups performed" name="Any lookups" title="Mali L2 Cache Lookups" units="requests"/>
<event counter="ARM_Mali-G51_L2_READ_LOOKUP" description="The number of L2 cache read lookups performed" name="Read lookups" title="Mali L2 Cache Lookups" units="requests"/>
<event counter="ARM_Mali-G51_L2_WRITE_LOOKUP" description="The number of L2 cache write lookups performed" name="Write lookups" title="Mali L2 Cache Lookups" units="requests"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_SNOOP_LOOKUP" description="The number of coherency snoop lookups performed that were triggered by an external requester" name="External snoop lookups" title="Mali L2 Cache Lookups" units="requests"/>
<event counter="ARM_Mali-G51_L2_EXT_READ" description="The number of external read transactions" name="Read transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_READ_NOSNP" description="The number of external non-coherent read transactions" name="ReadNoSnoop transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_READ_UNIQUE" description="The number of external coherent read unique transactions" name="ReadUnique transactions" title="Mali External Bus Accesses" units="transactions"/>
<event counter="ARM_Mali-G51_L2_EXT_READ_BEATS" description="The number of external bus data read cycles" name="Read beats" title="Mali External Bus Beats" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_AR_STALL" description="The number of cycles when a read is stalled waiting for the external bus" name="Read stall" title="Mali External Bus Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_AR_CNT_Q1" description="The number of read transactions initiated when 0-25% of the maximum are in use" name="0-25% outstanding" title="Mali External Bus Outstanding Reads" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_AR_CNT_Q2" description="The number of read transactions initiated when 25-50% of the maximum are in use" name="25-50% outstanding" title="Mali External Bus Outstanding Reads" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_AR_CNT_Q3" description="The number of read transactions initiated when 50-75% of the maximum are in use" name="50-75% outstanding" title="Mali External Bus Outstanding Reads" units="transactions"/>
<event counter="ARM_Mali-G51_L2_EXT_RRESP_0_127" description="The number of data beats returned 0-127 cycles after the read request" name="0-127 cycles" title="Mali External Bus Read Latency" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_RRESP_128_191" description="The number of data beats returned 128-191 cycles after the read request" name="128-191 cycles" title="Mali External Bus Read Latency" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_RRESP_192_255" description="The number of data beats returned 192-255 cycles after the read request" name="192-255 cycles" title="Mali External Bus Read Latency" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_RRESP_256_319" description="The number of data beats returned 256-319 cycles after the read request" name="256-319 cycles" title="Mali External Bus Read Latency" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_RRESP_320_383" description="The number of data beats returned 320-383 cycles after the read request" name="320-383 cycles" title="Mali External Bus Read Latency" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_WRITE" description="The number of external write transactions" name="Write transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_WRITE_NOSNP_FULL" description="The number of external non-coherent full write transactions" name="WriteNoSnoopFull transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_WRITE_NOSNP_PTL" description="The number of external non-coherent partial write transactions" name="WriteNoSnoopPartial transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_WRITE_SNP_FULL" description="The number of external coherent full write transactions" name="WriteSnoopFull transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_WRITE_SNP_PTL" description="The number of external coherent partial write transactions" name="WriteSnoopPartial transactions" title="Mali External Bus Accesses" units="transactions"/>
<event counter="ARM_Mali-G51_L2_EXT_WRITE_BEATS" description="The number of external bus data write cycles" name="Write beats" title="Mali External Bus Beats" units="beats"/>
<event counter="ARM_Mali-G51_L2_EXT_W_STALL" description="The number of cycles when a write is stalled waiting for the external bus" name="Write stall" title="Mali External Bus Stall Cycles" units="cycles"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_AW_CNT_Q1" description="The number of write transactions initiated when 0-25% of the maximum are in use" name="0-25% outstanding" title="Mali External Bus Outstanding Writes" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_AW_CNT_Q2" description="The number of write transactions initiated when 25-50% of the maximum are in use" name="25-50% outstanding" title="Mali External Bus Outstanding Writes" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_AW_CNT_Q3" description="The number of write transactions initiated when 50-75% of the maximum are in use" name="50-75% outstanding" title="Mali External Bus Outstanding Writes" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_SNOOP" description="The number of coherency snoops triggered by external requesters" name="Snoop transactions" title="Mali External Bus Accesses" units="transactions"/>
<event advanced="yes" counter="ARM_Mali-G51_L2_EXT_SNOOP_STALL" description="The number of cycles when a coherency snoop triggered by external requester is stalled" name="Snoop stall" title="Mali External Bus Stall Cycles" units="cycles"/>
</category>
| 0 | 0.87877 | 1 | 0.87877 | game-dev | MEDIA | 0.733904 | game-dev | 0.538556 | 1 | 0.538556 |
HenryRLee/PokerHandEvaluator | 2,434 | python/tests/test_evalator_omaha.py | from __future__ import annotations
import unittest
from itertools import combinations
from phevaluator import Card
from phevaluator import _evaluate_cards
from phevaluator import _evaluate_omaha_cards
from phevaluator import evaluate_omaha_cards
from phevaluator import sample_cards
def evaluate_omaha_exhaustive(community_cards: list[int], hole_cards: list[int]) -> int:
"""Evaluate omaha cards with `_evaluate_cards`."""
return min(
_evaluate_cards(c1, c2, c3, h1, h2)
for c1, c2, c3 in combinations(community_cards, 3)
for h1, h2 in combinations(hole_cards, 2)
)
class TestEvaluatorOmaha(unittest.TestCase):
def test_omaha(self) -> None:
"""Test two functions yield the same results.
Compare:
`_evaluate_omaha_cards`
`_evaluate_cards`
"""
total = 10000
for _ in range(total):
cards = sample_cards(9)
community_cards = cards[:5]
hole_cards = cards[5:]
with self.subTest(cards):
self.assertEqual(
_evaluate_omaha_cards(community_cards, hole_cards),
evaluate_omaha_exhaustive(community_cards, hole_cards),
)
def test_evaluator_interface(self) -> None:
# int, str and Card can be passed to evaluate_omaha_cards()
# fmt: off
rank1 = evaluate_omaha_cards(
48, 49, 47, 43, 35, # community cards
51, 50, 39, 34, # hole cards
)
rank2 = evaluate_omaha_cards(
"Ac", "Ad", "Ks", "Qs", "Ts", # community cards
"As", "Ah", "Js", "Th", # hole cards
)
rank3 = evaluate_omaha_cards(
"AC", "AD", "KS", "QS", "TS", # community cards
"AS", "AH", "JS", "TH", # hole cards
)
rank4 = evaluate_omaha_cards(
Card("Ac"), Card("Ad"), Card("Ks"), Card("Qs"), Card("Ts"), # community cards # noqa: E501
Card("As"), Card("Ah"), Card("Js"), Card("Th"), # hole cards
)
rank5 = evaluate_omaha_cards(
48, "Ad", "KS", Card(43), Card("Ts"), # community cards
Card("AS"), 50, "Js", "TH", # hole cards
)
# fmt: on
self.assertEqual(rank1, rank2)
self.assertEqual(rank1, rank3)
self.assertEqual(rank1, rank4)
self.assertEqual(rank1, rank5)
| 0 | 0.624852 | 1 | 0.624852 | game-dev | MEDIA | 0.697655 | game-dev,testing-qa | 0.727144 | 1 | 0.727144 |
VisualGMQ/NickelEngine | 6,185 | engine/engine/3rdlibs/physx/physx/source/physxextensions/src/serialization/Xml/SnJointRepXSerializer.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2024 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxMetaDataObjects.h"
#include "PxExtensionMetaDataObjects.h"
#include "ExtJointMetaDataExtensions.h"
#include "SnJointRepXSerializer.h"
namespace physx {
template<typename TJointType>
inline TJointType* createJoint( PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1 )
{
PX_UNUSED(physics);
PX_UNUSED(actor0);
PX_UNUSED(actor1);
PX_UNUSED(localFrame0);
PX_UNUSED(localFrame1);
return NULL;
}
template<>
inline PxD6Joint* createJoint<PxD6Joint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxD6JointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<>
inline PxDistanceJoint* createJoint<PxDistanceJoint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxDistanceJointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<>
inline PxContactJoint* createJoint<PxContactJoint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxContactJointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<>
inline PxFixedJoint* createJoint<PxFixedJoint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxFixedJointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<>
inline PxPrismaticJoint* createJoint<PxPrismaticJoint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxPrismaticJointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<>
inline PxRevoluteJoint* createJoint<PxRevoluteJoint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxRevoluteJointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<>
inline PxSphericalJoint* createJoint<PxSphericalJoint>(PxPhysics& physics,
PxRigidActor* actor0, const PxTransform& localFrame0,
PxRigidActor* actor1, const PxTransform& localFrame1)
{
return PxSphericalJointCreate( physics, actor0, localFrame0, actor1, localFrame1 );
}
template<typename TJointType>
PxRepXObject PxJointRepXSerializer<TJointType>::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection )
{
PxRigidActor* actor0 = NULL;
PxRigidActor* actor1 = NULL;
PxTransform localPose0 = PxTransform(PxIdentity);
PxTransform localPose1 = PxTransform(PxIdentity);
bool ok = true;
if ( inReader.gotoChild( "Actors" ) )
{
ok = readReference<PxRigidActor>( inReader, *inCollection, "actor0", actor0 );
ok &= readReference<PxRigidActor>( inReader, *inCollection, "actor1", actor1 );
inReader.leaveChild();
}
TJointType* theJoint = !ok ? NULL : createJoint<TJointType>( inArgs.physics, actor0, localPose0, actor1, localPose1 );
if ( theJoint )
{
PxConstraint* constraint = theJoint->getConstraint();
PX_ASSERT( constraint );
inCollection->add( *constraint );
this->fileToObjectImpl( theJoint, inReader, inAllocator, inArgs, inCollection );
}
return PxCreateRepXObject(theJoint);
}
template<typename TJointType>
void PxJointRepXSerializer<TJointType>::objectToFileImpl( const TJointType* inObj, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& )
{
writeAllProperties( inObj, inWriter, inTempBuffer, *inCollection );
}
// explicit template instantiations
template struct PxJointRepXSerializer<PxFixedJoint>;
template struct PxJointRepXSerializer<PxDistanceJoint>;
template struct PxJointRepXSerializer<PxContactJoint>;
template struct PxJointRepXSerializer<PxD6Joint>;
template struct PxJointRepXSerializer<PxPrismaticJoint>;
template struct PxJointRepXSerializer<PxRevoluteJoint>;
template struct PxJointRepXSerializer<PxSphericalJoint>;
}
| 0 | 0.713047 | 1 | 0.713047 | game-dev | MEDIA | 0.633788 | game-dev | 0.731701 | 1 | 0.731701 |
Dark-Basic-Software-Limited/GameGuruRepo | 42,623 | GameGuru Core/Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/CMultiplayerC.cpp |
//
// Multiplayer DLL
//
//////////////////////////////////////////////////////////////////////////////////
// INCLUDES / LIBS ///////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
#ifdef DARKSDK_COMPILE
#pragma comment ( lib, "dplayx.lib" )
#endif
// Includes
#include ".\..\error\cerror.h"
#include ".\..\core\globstruct.h"
#include "network\CNetwork.h"
#include "network\NetQueue.h"
#ifdef DARKSDK_COMPILE
#include ".\..\..\..\DarkGDK\Code\Include\DarkSDKBitmap.h"
#include ".\..\..\..\DarkGDK\Code\Include\DarkSDKImage.h"
#include ".\..\..\..\DarkGDK\Code\Include\DarkSDKSound.h"
#include ".\..\..\..\DarkGDK\Code\Include\DarkSDKBasic3D.h"
#include ".\..\..\..\DarkGDK\Code\Include\DarkSDKMemblocks.h"
#endif
#include "cmultiplayerc.h"
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// GLOBALS ///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// leefix - 131108 - DarkGDK does not want another global instance
#ifdef DARKSDK_COMPILE
#define DBPRO_GLOBAL static
#endif
// Global Shared Data Pointer (passed in from core)
DBPRO_GLOBAL GlobStruct* g_pGlob = NULL;
DBPRO_GLOBAL PTR_FuncCreateStr g_pCreateDeleteStringFunction = NULL;
// Global Internal Data
DBPRO_GLOBAL char m_pWorkString[256];
DBPRO_GLOBAL CNetwork* pCNetwork = NULL;
DWORD gInternalErrorCode = 0;
DBPRO_GLOBAL bool gbAlwaysHaveFocus = false;
// Used to call memblockDLL for memblock return ptr function
typedef int ( *MEMBLOCKS_GetMemblockExist ) ( int );
typedef DWORD ( *MEMBLOCKS_GetMemblockPtr ) ( int );
typedef DWORD ( *MEMBLOCKS_GetMemblockSize ) ( int );
typedef void ( *MEMBLOCKS_MemblockFromMedia ) ( int, int );
typedef void ( *MEMBLOCKS_MediaFromMemblock ) ( int, int );
typedef void ( *MEMBLOCKS_MakeMemblock ) ( int, int );
typedef void ( *MEMBLOCKS_DeleteMemblock ) ( int );
DBPRO_GLOBAL MEMBLOCKS_GetMemblockExist g_Memblock_GetMemblockExist;
DBPRO_GLOBAL MEMBLOCKS_GetMemblockPtr g_Memblock_GetMemblockPtr;
DBPRO_GLOBAL MEMBLOCKS_GetMemblockSize g_Memblock_GetMemblockSize;
DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromImage;
DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromBitmap;
DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromSound;
DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromMesh;
DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_ImageFromMemblock;
DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_BitmapFromMemblock;
DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_SoundFromMemblock;
DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_MeshFromMemblock;
DBPRO_GLOBAL MEMBLOCKS_MakeMemblock g_Memblock_MakeMemblock;
DBPRO_GLOBAL MEMBLOCKS_DeleteMemblock g_Memblock_DeleteMemblock;
// Used to call mediaDLLs
typedef int ( *MEDIA_GetExist ) ( int );
DBPRO_GLOBAL MEDIA_GetExist g_Image_GetExist;
DBPRO_GLOBAL MEDIA_GetExist g_Bitmap_GetExist;
DBPRO_GLOBAL MEDIA_GetExist g_Sound_GetExist;
DBPRO_GLOBAL MEDIA_GetExist g_Basic3D_GetExist;
// local checklist work vars
DBPRO_GLOBAL bool g_bCreateChecklistNow = false;
DBPRO_GLOBAL DWORD g_dwMaxStringSizeInEnum = 0;
// Internal Data DBV1
DBPRO_GLOBAL bool gbNetDataExists=false;
DBPRO_GLOBAL int gdwNetDataType=0;
DBPRO_GLOBAL DWORD gdwNetDataPlayerFrom=0;
DBPRO_GLOBAL DWORD gdwNetDataPlayerTo=0;
DBPRO_GLOBAL DWORD gpNetDataDWORD=NULL;
DBPRO_GLOBAL DWORD gpNetDataDWORDSize=0;
DBPRO_GLOBAL int gPlayerIDDatabase[256];
DBPRO_GLOBAL bool gbPlayerIDDatabaseFlagged[256];
// External Data DBV1
extern CNetQueue* gpNetQueue;
extern int gGameSessionActive;
extern bool gbSystemSessionLost;
extern int gSystemPlayerCreated;
extern int gSystemPlayerDestroyed;
extern int gSystemSessionIsNowHosting;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//
// Internal Functions
//
DARKSDK void Constructor ( void )
{
gpNetDataDWORD = NULL;
//pCNetwork = NULL;
}
DARKSDK void FreeNet ( void )
{
if(gdwNetDataType>=3 && gpNetDataDWORD)
{
//delete (char*)gpNetDataDWORD;
// mike - 250604
delete [ ] ( char* ) gpNetDataDWORD;
gpNetDataDWORD=NULL;
}
if(pCNetwork)
{
pCNetwork->CloseNetGame();
delete pCNetwork;
pCNetwork=NULL;
}
}
DARKSDK void Destructor ( void )
{
FreeNet();
}
DARKSDK void RefreshD3D ( int iMode )
{
}
DARKSDK void SetErrorHandler ( LPVOID pErrorHandlerPtr )
{
// Update error handler pointer
g_pErrorHandler = (CRuntimeErrorHandler*)pErrorHandlerPtr;
}
DARKSDK void PassCoreData( LPVOID pGlobPtr )
{
// Held in Core, used here..
g_pGlob = (GlobStruct*)pGlobPtr;
g_pCreateDeleteStringFunction = g_pGlob->CreateDeleteString;
#ifndef DARKSDK_COMPILE
// memblock DLL ptrs
g_Memblock_GetMemblockExist = ( MEMBLOCKS_GetMemblockExist ) GetProcAddress ( g_pGlob->g_Memblocks, "?MemblockExist@@YAHH@Z" );
g_Memblock_GetMemblockPtr = ( MEMBLOCKS_GetMemblockPtr ) GetProcAddress ( g_pGlob->g_Memblocks, "?GetMemblockPtr@@YAKH@Z" );
g_Memblock_GetMemblockSize = ( MEMBLOCKS_GetMemblockSize ) GetProcAddress ( g_pGlob->g_Memblocks, "?GetMemblockSize@@YAHH@Z" );
g_Memblock_MemblockFromImage = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromImage@@YAXHH@Z" );
g_Memblock_MemblockFromBitmap = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromBitmap@@YAXHH@Z" );
g_Memblock_MemblockFromSound = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromSound@@YAXHH@Z" );
g_Memblock_MemblockFromMesh = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromMesh@@YAXHH@Z" );
g_Memblock_ImageFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateImageFromMemblock@@YAXHH@Z" );
g_Memblock_BitmapFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateBitmapFromMemblock@@YAXHH@Z" );
g_Memblock_SoundFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateSoundFromMemblock@@YAXHH@Z" );
g_Memblock_MeshFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMeshFromMemblock@@YAXHH@Z" );
g_Memblock_MakeMemblock = ( MEMBLOCKS_MakeMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?MakeMemblock@@YAXHH@Z" );
g_Memblock_DeleteMemblock = ( MEMBLOCKS_DeleteMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?DeleteMemblock@@YAXH@Z" );
// media DLL ptrs
g_Image_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Image, "?GetExistEx@@YAHH@Z" );
g_Bitmap_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Bitmap, "?BitmapExist@@YAHH@Z" );
g_Sound_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Sound, "?GetSoundExist@@YAHH@Z" );
g_Basic3D_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Basic3D, "?GetMeshExist@@YAHH@Z" );
#else
g_Memblock_GetMemblockExist = dbMemblockExist;
g_Memblock_GetMemblockPtr = dbGetMemblockPtr;
g_Memblock_GetMemblockSize = ( MEMBLOCKS_GetMemblockSize )dbGetMemblockSize;
g_Memblock_MemblockFromImage = dbMakeMemblockFromImage;
g_Memblock_MemblockFromBitmap = dbMakeMemblockFromBitmap;
g_Memblock_MemblockFromSound = dbMakeMemblockFromSound;
g_Memblock_MemblockFromMesh = dbMakeMemblockFromMesh;
g_Memblock_ImageFromMemblock = dbMakeImageFromMemblock;
g_Memblock_BitmapFromMemblock = dbMakeBitmapFromMemblock;
g_Memblock_SoundFromMemblock = dbMakeSoundFromMemblock;
g_Memblock_MeshFromMemblock = dbMakeMeshFromMemblock;
g_Memblock_MakeMemblock = dbMakeMemblock;
g_Memblock_DeleteMemblock = dbDeleteMemblock;
g_Image_GetExist = dbImageExist;
g_Bitmap_GetExist =dbBitmapExist;
g_Sound_GetExist = dbSoundExist;
g_Basic3D_GetExist =dbObjectExist;
#endif
}
DBPRO_GLOBAL LPSTR GetReturnStringFromWorkString(void)
{
LPSTR pReturnString=NULL;
if(m_pWorkString)
{
DWORD dwSize=strlen(m_pWorkString);
g_pCreateDeleteStringFunction((DWORD*)&pReturnString, dwSize+1);
strcpy(pReturnString, m_pWorkString);
}
return pReturnString;
}
DARKSDK bool QuickStartInit(int* sessionnumber)
{
bool bCreationValid=true;
if(pCNetwork==NULL)
{
pCNetwork = new CNetwork;
if(pCNetwork->SetNetConnections(-1)!=0)
{
if(pCNetwork->FindNetSessions("")!=0)
{
if(pCNetwork->SetNetSessions(1)!=0)
{
// QuickStart Success - reassign session number to 1
if(sessionnumber) *sessionnumber=0;
}
else
{
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSETSESSION);
bCreationValid=false;
}
}
else
{
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOFINDSESSION);
bCreationValid=false;
}
}
else
{
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCONNECT);
bCreationValid=false;
}
}
return bCreationValid;
}
DARKSDK int findseqidindatabase(int dpid)
{
int free=-1, got=-1;
for(int s=1; s<256; s++)
{
if(gPlayerIDDatabase[s]==0 && free==-1) free=s;
if(gPlayerIDDatabase[s]==dpid) { got=s; break; }
}
if(got==-1)
{
if(free!=-1)
{
gPlayerIDDatabase[free]=dpid;
return free;
}
else
return -1;
}
else
return got;
}
DARKSDK void CoreSendNetMsg(int type, int playerid, DWORD* pMessageData, DWORD dwSize, int guarenteed)
{
if(pCNetwork && gGameSessionActive>0)
{
// Get Player Id
bool bSendValid=true;
if(playerid==0) playerid=ALLPLAYERS;
if(playerid!=0)
{
// Find player ID from database
playerid=gPlayerIDDatabase[playerid];
if(playerid==0)
{
// Player not exist - send nothing
bSendValid=false;
}
}
// If send is valid
if(bSendValid)
{
// Build MSG Data
DWORD size;
char* pData;
char* pStr;
switch(type)
{
// Integer Message
case 1 :
size = 4;
pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &type, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), pMessageData, size);
break;
// Float Message
case 2 :
size = 4;
pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &type, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), pMessageData, size);
break;
// String Message
case 3 :
pStr = (char*)pMessageData;
size = strlen(pStr) + 1;
pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &type, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), pStr, size);
break;
// Memblock Message
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
size = dwSize;
pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size);
memcpy(pData, &type, sizeof(int));
memcpy(pData+sizeof(int), &size, sizeof(DWORD));
memcpy(pData+sizeof(int)+sizeof(DWORD), pMessageData, size);
break;
}
if(guarenteed==1)
{
if(pCNetwork->SendNetMsgGUA(playerid, (tagNetData*)pData)==0)
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSENDMESSAGE);
}
else
{
if(pCNetwork->SendNetMsg(playerid, (tagNetData*)pData)==0)
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSENDMESSAGE);
}
// Free MSG Data
if(pData)
{
GlobalFree(pData);
pData=NULL;
}
}
else
RunTimeWarning(RUNTIMEERROR_MPPLAYERNOTEXIST);
}
else
RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION);
}
//
// Command Functions
//
DARKSDK void CreateNetGame(LPSTR gamename, LPSTR name, int playermax)
{
if(gGameSessionActive==0)
{
// lee - 220306 - u6b4 - validation check, prevent crashing
if ( gamename==NULL || name==NULL )
{
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME);
return;
}
// Easy Quick-Start if connection and session not set..
bool bCreationValid=QuickStartInit(NULL);
// Net Game Creation Here
if(bCreationValid)
{
if(strcmp(gamename,"")!=0)
{
if(strcmp(name,"")!=0)
{
if(playermax>=2 && playermax<=255)
{
if(pCNetwork->CreateNetGame(gamename, name, playermax, DPSESSION_MIGRATEHOST)!=0)
{
// Clear PlayerID Database
gGameSessionActive=1;
ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase));
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME);
}
else
RunTimeError(RUNTIMEERROR_MPCREATEBETWEEN2AND255);
}
else
RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME);
}
else
RunTimeError(RUNTIMEERROR_MPMUSTGIVEGAMENAME);
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME);
}
else
RunTimeWarning(RUNTIMEERROR_MPSESSIONEXISTS);
}
DARKSDK void CreateNetGameEx(LPSTR gamename, LPSTR name, int playermax, int flagnum)
{
if(gGameSessionActive==0)
{
// lee - 220306 - u6b4 - validation check, prevent crashing
if ( gamename==NULL || name==NULL )
{
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME);
return;
}
// Easy Quick-Start if connection and session not set..
bool bCreationValid=QuickStartInit(NULL);
// Net Game Creation Here
if(bCreationValid)
{
if(strcmp(gamename,"")!=0)
{
if(strcmp(name,"")!=0)
{
if(playermax>=2 && playermax<=255)
{
DWORD flags=0;
if(flagnum==1) flags |= DPSESSION_MIGRATEHOST;
if(flagnum==2) flags |= DPSESSION_CLIENTSERVER;
if(pCNetwork->CreateNetGame(gamename, name, playermax, flags)!=0)
{
// Clear PlayerID Database
gGameSessionActive=1;
ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase));
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME);
}
else
RunTimeError(RUNTIMEERROR_MPCREATEBETWEEN2AND255);
}
else
RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME);
}
else
RunTimeError(RUNTIMEERROR_MPMUSTGIVEGAMENAME);
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME);
}
else
RunTimeWarning(RUNTIMEERROR_MPSESSIONEXISTS);
}
DARKSDK void JoinNetGame(int sessionnum, LPSTR name)
{
if(gGameSessionActive==0)
{
// lee - 220306 - u6b4 - validation check, prevent crashing
if ( name==NULL )
{
RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME);
return;
}
// Easy Quick-Start if connection and session not set..
sessionnum-=1;
bool bCreationValid=QuickStartInit(&sessionnum);
// Net Game Creation Here
if(bCreationValid)
{
if(sessionnum>=0 && sessionnum<MAX_SESSIONS)
{
if(pCNetwork->SetNetSessions(sessionnum)!=0)
{
if(strcmp(name,"")!=0)
{
int iResult = pCNetwork->JoinNetGame(name);
if(iResult==1)
{
// Clear PlayerID Database
gGameSessionActive=2;
ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase));
}
else
{
if(iResult==2)
RunTimeWarning(RUNTIMEERROR_MPNOTCREATEDPLAYER);
else
{
if(iResult==3)
RunTimeWarning(RUNTIMEERROR_MPTOOMANYPLAYERS);
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOJOINGAME);
}
}
}
else
RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME);
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSETSESSION);
}
else
RunTimeError(RUNTIMEERROR_MPSESSIONNUMINVALID);
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOJOINGAME);
}
else
RunTimeWarning(RUNTIMEERROR_MPSESSIONEXISTS);
}
DARKSDK void InternalJoinNetGame(int sessionnum, LPSTR name)
{
if(gGameSessionActive==0)
{
// lee - 220306 - u6b4 - validation check, prevent crashing
if ( name==NULL ) return;
// Easy Quick-Start if connection and session not set..
sessionnum-=1;
bool bCreationValid=QuickStartInit(&sessionnum);
// Net Game Creation Here
if(bCreationValid)
{
if(sessionnum>=0 && sessionnum<MAX_SESSIONS)
{
if(pCNetwork->SetNetSessions(sessionnum)!=0)
{
if(strcmp(name,"")!=0)
{
int iResult = pCNetwork->JoinNetGame(name);
if(iResult==1)
{
// Clear PlayerID Database
gGameSessionActive=2;
ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase));
}
}
}
}
}
}
}
DARKSDK void CloseNetGame(void)
{
// Clear PlayerID Database
gGameSessionActive=0;
ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase));
// General network termination
FreeNet();
}
DARKSDK void PerformChecklistForNetConnections(void)
{
if(pCNetwork==NULL) pCNetwork = new CNetwork;
char* data[MAX_CONNECTIONS];
ZeroMemory(data, sizeof(data));
// Generate Checklist
g_pGlob->checklistqty=0;
g_pGlob->checklistexists=true;
g_pGlob->checklisthasvalues=false;
g_pGlob->checklisthasstrings=true;
if(pCNetwork->GetNetConnections(data))
{
g_dwMaxStringSizeInEnum=0;
g_bCreateChecklistNow=false;
for(int pass=0; pass<2; pass++)
{
if(pass==1)
{
// Ensure checklist is large enough
g_bCreateChecklistNow=true;
for(int c=0; c<g_pGlob->checklistqty; c++)
GlobExpandChecklist(c, g_dwMaxStringSizeInEnum);
}
// Run through...
DWORD ci=0;
for(DWORD i=0; i<MAX_CONNECTIONS; i++)
{
if(g_bCreateChecklistNow==true) strcpy(g_pGlob->checklist[i].string, "");
if(data[i])
{
if(g_bCreateChecklistNow==true)
{
if(ci<g_pGlob->dwChecklistArraySize)
{
strcpy(g_pGlob->checklist[i].string, data[i]);
if(i+1>ci) ci=i+1;
}
}
else
{
DWORD dwSize = strlen(data[i]);
if(dwSize>g_dwMaxStringSizeInEnum) g_dwMaxStringSizeInEnum=dwSize;
if(i+1>ci) ci=i+1;
}
}
}
g_pGlob->checklistqty=ci;
}
}
else
g_pGlob->checklistqty=0;
}
DARKSDK void SetNetConnections(int index)
{
if(pCNetwork==NULL) pCNetwork = new CNetwork;
index-=1;
if(index>=0 && index<MAX_CONNECTIONS)
{
if(pCNetwork->SetNetConnections(index)!=0)
{
if(pCNetwork->FindNetSessions("")==0)
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOFINDSESSION);
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCONNECT);
}
else
RunTimeError(RUNTIMEERROR_MPCONNECTIONNUMINVALID);
}
DARKSDK void SetNetConnectionsEx(int index, LPSTR ipaddress)
{
if(pCNetwork==NULL) pCNetwork = new CNetwork;
index-=1;
if(index>=0 && index<MAX_CONNECTIONS)
{
if(pCNetwork->SetNetConnections(index)!=0)
{
if(pCNetwork->FindNetSessions(ipaddress)==0)
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOFINDSESSION);
}
else
RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCONNECT);
}
else
RunTimeError(RUNTIMEERROR_MPCONNECTIONNUMINVALID);
}
DARKSDK void PerformChecklistForNetSessions(void)
{
if(pCNetwork==NULL) pCNetwork = new CNetwork;
char* data[MAX_SESSIONS];
ZeroMemory(data, sizeof(data));
// Generate Checklist
g_pGlob->checklistqty=0;
g_pGlob->checklistexists=true;
g_pGlob->checklisthasvalues=false;
g_pGlob->checklisthasstrings=true;
if(pCNetwork->GetNetSessions(data))
{
g_dwMaxStringSizeInEnum=0;
g_bCreateChecklistNow=false;
for(int pass=0; pass<2; pass++)
{
if(pass==1)
{
// Ensure checklist is large enough
g_bCreateChecklistNow=true;
for(int c=0; c<g_pGlob->checklistqty; c++)
GlobExpandChecklist(c, g_dwMaxStringSizeInEnum);
}
DWORD ci=0;
for(DWORD i=0; i<MAX_SESSIONS; i++)
{
if(g_bCreateChecklistNow==true)
{
// ensure only validf checklist items are cleared
if( i <g_pGlob->dwChecklistArraySize)
strcpy ( g_pGlob->checklist[i].string, "" );
if(data[i])
{
if(ci<g_pGlob->dwChecklistArraySize)
{
strcpy(g_pGlob->checklist[i].string, data[i]);
if(i+1>ci) ci=i+1;
//// mike - 250604 - stores extra data
g_pGlob->checklisthasvalues=true;
g_pGlob->checklist [ i ].valuea = netSession[i].iPlayers;
g_pGlob->checklist [ i ].valueb = netSession[i].iMaxPlayers;
}
}
}
else
{
if(data[i]) if(i+1>ci) ci=i+1;
}
}
g_pGlob->checklistqty=ci;
}
}
else
g_pGlob->checklistqty=0;
}
DARKSDK void PerformChecklistForNetPlayers(void)
{
DPID dpids[256];
char* data[256];
ZeroMemory(dpids, sizeof(dpids));
ZeroMemory(data, sizeof(data));
g_pGlob->checklistqty=0;
g_pGlob->checklistexists=true;
g_pGlob->checklisthasvalues=true;
g_pGlob->checklisthasstrings=true;
if(gGameSessionActive>0)
{
// Update checklist with player names and ids
DWORD playernum=pCNetwork->GetNetPlayers(data, dpids);
if(playernum>255)
playernum=255;
if(playernum>0)
{
// Reset lafs for player removal
ZeroMemory(gbPlayerIDDatabaseFlagged, sizeof(gbPlayerIDDatabaseFlagged));
g_pGlob->checklistqty=playernum;
for(int c=0; c<g_pGlob->checklistqty; c++)
{
if ( data [ c ] )
{
GlobExpandChecklist(c, 255);
strcpy(g_pGlob->checklist[c].string, "");
//strcpy(g_pGlob->checklist[c].string, "bob");
g_pGlob->checklist[c].valuea = findseqidindatabase(dpids[c]);
gbPlayerIDDatabaseFlagged[g_pGlob->checklist[c].valuea]=true;
g_pGlob->checklist[c].valueb = dpids[c];
g_pGlob->checklist[c].valuec = 0;
g_pGlob->checklist[c].valued = 0;
if(dpids[c]==pCNetwork->GetLocalPlayerDPID()) g_pGlob->checklist[c].valuec = 1;
if(dpids[c]==pCNetwork->GetServerPlayerDPID()) g_pGlob->checklist[c].valued = 1;
strcpy(g_pGlob->checklist[c].string, data[c]);
}
}
for(int s=1; s<256; s++)
if(gbPlayerIDDatabaseFlagged[s]==false)
gPlayerIDDatabase[s]=0;
}
}
/*
DPID dpids[256];
char* data[256];
ZeroMemory(dpids, sizeof(dpids));
ZeroMemory(data, sizeof(data));
// Generate Checklist
g_pGlob->checklistqty=0;
g_pGlob->checklistexists=true;
g_pGlob->checklisthasvalues=true;
g_pGlob->checklisthasstrings=true;
if(gGameSessionActive>0)
{
// Update checklist with player names and ids
DWORD playernum=pCNetwork->GetNetPlayers(data, dpids);
if(playernum>255) playernum=255;
if(playernum>0)
{
// Reset lafs for player removal
ZeroMemory(gbPlayerIDDatabaseFlagged, sizeof(gbPlayerIDDatabaseFlagged));
g_dwMaxStringSizeInEnum=0;
g_bCreateChecklistNow=false;
for(int pass=0; pass<2; pass++)
{
if(pass==1)
{
// Ensure checklist is large enough
g_bCreateChecklistNow=true;
for(int c=0; c<g_pGlob->checklistqty; c++)
GlobExpandChecklist(c, g_dwMaxStringSizeInEnum);
}
DWORD ci=0;
for(DWORD i=0; i<playernum; i++)
{
if(g_bCreateChecklistNow==true)
{
strcpy(g_pGlob->checklist[i].string, "");
if(data[i])
{
if(ci<g_pGlob->dwChecklistArraySize)
{
g_pGlob->checklist[i].valuea = findseqidindatabase(dpids[i]);
gbPlayerIDDatabaseFlagged[g_pGlob->checklist[i].valuea]=true;
g_pGlob->checklist[i].valueb = dpids[i];
g_pGlob->checklist[i].valuec = 0;
g_pGlob->checklist[i].valued = 0;
if(dpids[i]==pCNetwork->GetLocalPlayerDPID()) g_pGlob->checklist[i].valuec = 1;
if(dpids[i]==pCNetwork->GetServerPlayerDPID()) g_pGlob->checklist[i].valued = 1;
strcpy(g_pGlob->checklist[i].string, data[i]);
if(i+1>ci) ci=i+1;
}
}
}
else
{
if(data[i])
if(i+1>ci) ci=i+1;
}
}
g_pGlob->checklistqty=ci;
}
// Delete players from database no longer in list
for(int s=1; s<256; s++)
if(gbPlayerIDDatabaseFlagged[s]==false)
gPlayerIDDatabase[s]=0;
}
else
g_pGlob->checklistqty=0;
}
else
g_pGlob->checklistqty=0;
*/
}
DARKSDK void CreatePlayer(LPSTR playername)
{
if(pCNetwork && gGameSessionActive>0)
{
if(pCNetwork->CreatePlayer(playername)==0)
RunTimeWarning(RUNTIMEERROR_MPNOTCREATEDPLAYER);
}
else
RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION);
}
DARKSDK int CreatePlayerEx(LPSTR playername)
{
int playerid=0;
if(pCNetwork && gGameSessionActive>0)
{
if((playerid=pCNetwork->CreatePlayer(playername))!=0)
{
// Return sequenced id from dpid
playerid = findseqidindatabase(playerid);
}
else
RunTimeWarning(RUNTIMEERROR_MPNOTCREATEDPLAYER);
}
else
RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION);
return playerid;
}
DARKSDK void DestroyPlayer(int playerid)
{
if(pCNetwork && gGameSessionActive>0)
{
if(playerid>=1 && playerid<=256)
{
int playerindex = gPlayerIDDatabase[playerid];
if(playerindex!=0)
{
if(pCNetwork->DestroyPlayer(playerindex))
{
gPlayerIDDatabase[playerid]=0;
}
else
RunTimeWarning(RUNTIMEERROR_MPCANNOTDELETEPLAYER);
}
else
RunTimeWarning(RUNTIMEERROR_MPPLAYERNOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_MPPLAYERNUMINVALID);
}
else
RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION);
}
DARKSDK void SendNetMsgL(int playerid, int MessageData)
{
CoreSendNetMsg(1, playerid, (DWORD*)&MessageData, 0, 0);
}
DARKSDK void SendNetMsgF(int playerid, DWORD MessageData)
{
CoreSendNetMsg(2, playerid, &MessageData, 0, 0);
}
DARKSDK void SendNetMsgS(int playerid, LPSTR pMessageData)
{
CoreSendNetMsg(3, playerid, (DWORD*)pMessageData, 0, 0);
}
DARKSDK void SendNetMsgMemblock(int playerid, int mbi)
{
if(mbi>=1 && mbi<=255)
{
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
if(pMemblockData)
{
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
CoreSendNetMsg(4, playerid, (DWORD*)pMemblockData, dwMemblockSize, 0);
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKNOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKRANGEILLEGAL);
}
DARKSDK void SendNetMsgMemblockEx(int playerid, int mbi, int gua)
{
if(mbi>=1 && mbi<=255)
{
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
if(pMemblockData)
{
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
CoreSendNetMsg(4, playerid, (DWORD*)pMemblockData, dwMemblockSize, gua);
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKNOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKRANGEILLEGAL);
}
DARKSDK void SendNetMsgImage(int playerid, int imageindex, int gua)
{
if(imageindex>=1 && imageindex<=MAXIMUMVALUE)
{
if ( g_Image_GetExist(imageindex) )
{
int mbi=257;
g_Memblock_MemblockFromImage(mbi, imageindex);
DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi);
DWORD dwSize = g_Memblock_GetMemblockSize(mbi);
CoreSendNetMsg(5, playerid, pPtr, dwSize, gua);
}
else
RunTimeError(RUNTIMEERROR_IMAGENOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_IMAGEILLEGALNUMBER);
}
DARKSDK void SendNetMsgBitmap(int playerid, int bitmapindex, int gua)
{
if(bitmapindex>=0 && bitmapindex<MAXIMUMVALUE)
{
if(bitmapindex==0 || g_Bitmap_GetExist(bitmapindex))
{
int mbi=257;
g_Memblock_MemblockFromBitmap(mbi, bitmapindex);
DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi);
DWORD dwSize = g_Memblock_GetMemblockSize(mbi);
CoreSendNetMsg(6, playerid, pPtr, dwSize, gua);
}
else
RunTimeError(RUNTIMEERROR_BITMAPNOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_BITMAPILLEGALNUMBER);
}
DARKSDK void SendNetMsgSound(int playerid, int soundindex, int gua)
{
if(soundindex>=1 && soundindex<MAXIMUMVALUE)
{
if(g_Sound_GetExist(soundindex))
{
int mbi=257;
g_Memblock_MemblockFromSound(mbi, soundindex);
DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi);
DWORD dwSize = g_Memblock_GetMemblockSize(mbi);
CoreSendNetMsg(7, playerid, pPtr, dwSize, gua);
}
else
RunTimeError(RUNTIMEERROR_SOUNDNOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_SOUNDNUMBERILLEGAL);
}
DARKSDK void SendNetMsgMesh(int playerid, int meshindex, int gua)
{
if(meshindex>0 && meshindex<MAXIMUMVALUE)
{
if(g_Basic3D_GetExist(meshindex))
{
int mbi=257;
g_Memblock_MemblockFromMesh(mbi, meshindex);
DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi);
DWORD dwSize = g_Memblock_GetMemblockSize(mbi);
CoreSendNetMsg(8, playerid, pPtr, dwSize, gua);
}
else
RunTimeError(RUNTIMEERROR_B3DMESHNOTEXIST);
}
else
RunTimeError(RUNTIMEERROR_B3DMESHNUMBERILLEGAL);
}
DARKSDK void GetNetMsg(void)
{
if(pCNetwork && gGameSessionActive>0)
{
QueuePacketStruct packet;
packet.pMsg=NULL;
if(pCNetwork->GetOneNetMsgOffQueue(&packet)!=0)
{
if(packet.pMsg)
{
// Remove old data
if(gdwNetDataType>=3 && gpNetDataDWORD)
{
delete (char*)gpNetDataDWORD;
gpNetDataDWORD=NULL;
}
// Prepare new data
gbNetDataExists=true;
gdwNetDataType=packet.pMsg->id;
gdwNetDataPlayerFrom=packet.idFrom;
gdwNetDataPlayerTo=packet.idTo;
// Create Data
switch(gdwNetDataType)
{
case 1 : // Integer
memcpy((int*)&gpNetDataDWORD, &packet.pMsg->msg, 4);
break;
case 2 : // Float
memcpy((float*)&gpNetDataDWORD, &packet.pMsg->msg, 4);
break;
case 3 : // String
if(packet.pMsg->size>0)
{
gpNetDataDWORD=(DWORD)new char[packet.pMsg->size];
memcpy((char*)gpNetDataDWORD, &packet.pMsg->msg, packet.pMsg->size);
}
break;
case 4 : // Memblock
gpNetDataDWORDSize=packet.pMsg->size;
if(gpNetDataDWORDSize>0)
{
gpNetDataDWORD=(DWORD)new char[gpNetDataDWORDSize];
memcpy((char*)gpNetDataDWORD, &packet.pMsg->msg, gpNetDataDWORDSize);
}
break;
case 5 : // Image
case 6 : // Bitmap
case 7 : // Sound
case 8 : // Mesh
gpNetDataDWORDSize=packet.pMsg->size;
if(gpNetDataDWORDSize>0)
{
gpNetDataDWORD=(DWORD)new char[gpNetDataDWORDSize];
memcpy((char*)gpNetDataDWORD, &packet.pMsg->msg, gpNetDataDWORDSize);
}
break;
}
// Free MSG Data
if(packet.pMsg)
{
GlobalFree(packet.pMsg);
packet.pMsg=NULL;
}
}
else
{
gdwNetDataType=0;
gbNetDataExists=false;
}
}
else
{
gdwNetDataType=0;
gbNetDataExists=false;
}
}
else
RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION);
}
DARKSDK int NetMsgExists(void)
{
int iResult=0;
if(pCNetwork && gGameSessionActive>0)
iResult=(int)gbNetDataExists;
return iResult;
}
DARKSDK int NetMsgType(void)
{
return gdwNetDataType;
}
DARKSDK int NetMsgPlayerFrom(void)
{
return findseqidindatabase(gdwNetDataPlayerFrom);
}
DARKSDK int NetMsgPlayerTo(void)
{
return findseqidindatabase(gdwNetDataPlayerTo);
}
DARKSDK int NetMsgInteger(void)
{
if(gdwNetDataType==1)
return *(int*)&gpNetDataDWORD;
return 0;
}
DARKSDK DWORD NetMsgFloat(void)
{
if(gdwNetDataType==2) return gpNetDataDWORD;
return 0;
}
DARKSDK DWORD NetMsgString(DWORD pDestStr)
{
strcpy(m_pWorkString, "");
if(pCNetwork && gpNetDataDWORD && gGameSessionActive>0 && gdwNetDataType==3)
strcpy(m_pWorkString, (char*)gpNetDataDWORD);
// Create and return string
if(pDestStr) g_pCreateDeleteStringFunction((DWORD*)&pDestStr, 0);
LPSTR pReturnString=GetReturnStringFromWorkString();
// mike - 250604 - clear
delete (char*)gpNetDataDWORD;
gpNetDataDWORD = NULL;
return (DWORD)pReturnString;
}
DARKSDK void NetMsgMemblock(int mbi)
{
if(gdwNetDataType==4)
{
if(mbi>=1 && mbi<=255)
{
if(gpNetDataDWORDSize>0)
{
// Free existing memblock
if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi);
// Create memblock
g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize );
if(g_Memblock_GetMemblockExist(mbi))
{
// Put message in memblock
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize);
// mike - 250604 - clear
delete (char*)gpNetDataDWORD;
gpNetDataDWORD = NULL;
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKCREATIONFAILED);
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKCREATIONFAILED);
}
else
RunTimeError(RUNTIMEERROR_MEMBLOCKRANGEILLEGAL);
}
}
DARKSDK void NetMsgImage(int imageindex)
{
if(gdwNetDataType==5)
{
int mbi=257;
if(imageindex>=1 && imageindex<=MAXIMUMVALUE)
{
if(gpNetDataDWORDSize>0)
{
// Free existing memblock
if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi);
// Create memblock
g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize );
if(g_Memblock_GetMemblockExist(mbi))
{
// Put message in memblock
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize);
// Turn memblock into media
g_Memblock_ImageFromMemblock(imageindex,mbi);
}
else
RunTimeError(RUNTIMEERROR_B3DERROR);
}
}
else
RunTimeError(RUNTIMEERROR_IMAGEILLEGALNUMBER);
}
}
DARKSDK void NetMsgBitmap(int bitmapindex)
{
if(gdwNetDataType==6)
{
int mbi=257;
if(bitmapindex>=0 && bitmapindex<MAXIMUMVALUE)
{
if(gpNetDataDWORDSize>0)
{
// Free existing memblock
if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi);
// Create memblock
g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize );
if(g_Memblock_GetMemblockExist(mbi))
{
// Put message in memblock
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize);
// Turn memblock into media
g_Memblock_BitmapFromMemblock(bitmapindex,mbi);
}
else
RunTimeError(RUNTIMEERROR_B3DERROR);
}
}
else
RunTimeError(RUNTIMEERROR_BITMAPILLEGALNUMBER);
}
}
DARKSDK void NetMsgSound(int soundindex)
{
if(gdwNetDataType==7)
{
int mbi=257;
if(soundindex>=1 && soundindex<MAXIMUMVALUE)
{
if(gpNetDataDWORDSize>0)
{
// Free existing memblock
if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi);
// Create memblock
g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize );
if(g_Memblock_GetMemblockExist(mbi))
{
// Put message in memblock
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize);
// Turn memblock into media
g_Memblock_SoundFromMemblock(soundindex,mbi);
}
else
RunTimeError(RUNTIMEERROR_SOUNDERROR);
}
}
else
RunTimeError(RUNTIMEERROR_SOUNDNUMBERILLEGAL);
}
}
DARKSDK void NetMsgMesh(int meshindex)
{
if(gdwNetDataType==8)
{
int mbi=257;
if(meshindex>0 && meshindex<MAXIMUMVALUE)
{
if(gpNetDataDWORDSize>0)
{
// Free existing memblock
if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi);
// Create memblock
g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize );
if(g_Memblock_GetMemblockExist(mbi))
{
// Put message in memblock
LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi);
DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi);
memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize);
// Turn memblock into media
g_Memblock_MeshFromMemblock(meshindex,mbi);
}
else
RunTimeError(RUNTIMEERROR_B3DERROR);
}
}
else
RunTimeError(RUNTIMEERROR_B3DMESHNUMBERILLEGAL);
}
}
DARKSDK int NetSessionExists(void)
{
if(gGameSessionActive>0)
return 1;
return 0;
}
DARKSDK int NetSessionLost(void)
{
int iValue=(int)gbSystemSessionLost;
if(pCNetwork) pCNetwork->GetSysNetMsgIfAny();
gbSystemSessionLost=false;
return iValue;
}
DARKSDK int NetPlayerCreated(void)
{
int iValue=0;
if(pCNetwork) pCNetwork->GetSysNetMsgIfAny();
if(gSystemPlayerCreated>0)
{
iValue=findseqidindatabase(gSystemPlayerCreated);
gSystemPlayerCreated=0;
}
return iValue;
}
DARKSDK int NetPlayerDestroyed(void)
{
int iValue=0;
if(pCNetwork) pCNetwork->GetSysNetMsgIfAny();
if(gSystemPlayerDestroyed>0)
{
iValue=findseqidindatabase(gSystemPlayerDestroyed);
gSystemPlayerDestroyed=0;
}
return iValue;
}
DARKSDK int NetSessionIsNowHosting(void)
{
int iValue;
if(pCNetwork) pCNetwork->GetSysNetMsgIfAny();
iValue=gSystemSessionIsNowHosting;
gSystemSessionIsNowHosting=0;
return iValue;
}
/*
void AlwaysActiveOn(void)
{
// Not Implemented in DBPRO V1 RELEASE
RunTimeError(RUNTIMEERROR_COMMANDNOWOBSOLETE);
}
void AlwaysActiveOff(void)
{
// Not Implemented in DBPRO V1 RELEASE
RunTimeError(RUNTIMEERROR_COMMANDNOWOBSOLETE);
}
*/
//
// New Multiplayer Commands
//
DARKSDK int MagicNetGame(DWORD lpGameName, DWORD lpPlayerName, int PlayerMax, int FlagNum )
{
// Player Num is returned
int iPlayerNumber=0;
// First try to join
InternalJoinNetGame(1, (LPSTR)lpPlayerName);
if(gGameSessionActive==0)
{
// Ok, create as fresh host to new game
CreateNetGameEx( (LPSTR)lpGameName, (LPSTR)lpPlayerName, PlayerMax, FlagNum );
iPlayerNumber=findseqidindatabase(pCNetwork->m_LocalPlayerDPID);
}
else
{
// In Magic creation, Order of players handled by ore-filling existing players
char* data[256];
DPID dpids[256];
ZeroMemory(data, sizeof(data));
ZeroMemory(dpids, sizeof(dpids));
DWORD playernum=pCNetwork->GetNetPlayers(data, dpids);
for(DWORD i=0; i<playernum; i++)
if(data[i])
if(pCNetwork->m_LocalPlayerDPID!=dpids[i])
int ExistingPlayerNumber = findseqidindatabase(dpids[i]);
// Get number if this player
iPlayerNumber=findseqidindatabase(pCNetwork->m_LocalPlayerDPID);
}
return iPlayerNumber;
}
DARKSDK int NetBufferSize(void)
{
if(gpNetQueue)
return gpNetQueue->QueueSize();
else
return 0;
}
//////////////////////////////////////////////////////////////////////////////////
// DARK SDK SECTION //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
#ifdef DARKSDK_COMPILE
void ConstructorMultiplayer ( void )
{
Constructor ( );
}
void DestructorMultiplayer ( void )
{
Destructor ( );
}
void SetErrorHandlerMultiplayer ( LPVOID pErrorHandlerPtr )
{
SetErrorHandler ( pErrorHandlerPtr );
}
void PassCoreDataMultiplayer ( LPVOID pGlobPtr )
{
PassCoreData ( pGlobPtr );
}
void RefreshD3DMultiplayer ( int iMode )
{
RefreshD3D ( iMode );
}
void dbCreateNetGame(LPSTR gamename, LPSTR name, int playermax)
{
CreateNetGame( gamename, name, playermax);
}
void dbCreateNetGame (LPSTR gamename, LPSTR name, int playermax, int flagnum)
{
CreateNetGameEx( gamename, name, playermax, flagnum);
}
void dbJoinNetGame(int sessionnum, LPSTR name)
{
JoinNetGame( sessionnum, name);
}
void dbFreeNetGame(void)
{
CloseNetGame();
}
void dbPerformChecklistForNetConnections(void)
{
PerformChecklistForNetConnections();
}
void dbSetNetConnections(int index)
{
SetNetConnections(index);
}
void dbSetNetConnections(int index, LPSTR ipaddress)
{
SetNetConnectionsEx( index, ipaddress);
}
void dbPerformChecklistForNetSessions(void)
{
PerformChecklistForNetSessions();
}
void dbPerformChecklistForNetPlayers(void)
{
PerformChecklistForNetPlayers();
}
void dbCreateNetPlayer(LPSTR playername)
{
CreatePlayer( playername);
}
int dbCreateNetPlayerEx(LPSTR playername)
{
return CreatePlayerEx( playername);
}
void dbDestroyNetPlayer(int playerid)
{
DestroyPlayer( playerid);
}
void dbSendNetMessageInteger(int playerid, int MessageData)
{
SendNetMsgL( playerid, MessageData);
}
void dbSendNetMessageFloat(int playerid, float MessageData)
{
SendNetMsgF( playerid, ( DWORD ) MessageData);
}
void dbSendNetMessageString(int playerid, LPSTR pMessageData)
{
SendNetMsgS( playerid, pMessageData);
}
void dbSendNetMessageMemblock(int playerid, int mbi)
{
SendNetMsgMemblock( playerid, mbi);
}
void dbSendNetMessageMemblock(int playerid, int mbi, int gua)
{
SendNetMsgMemblockEx( playerid, mbi, gua);
}
void dbSendNetMessageImage(int playerid, int imageindex, int gua)
{
SendNetMsgImage( playerid, imageindex, gua);
}
void dbSendNetMessageBitmap(int playerid, int bitmapindex, int gua)
{
SendNetMsgBitmap( playerid, bitmapindex, gua);
}
void dbSendNetMessageSound(int playerid, int soundindex, int gua)
{
SendNetMsgSound( playerid, soundindex, gua);
}
void dbSendNetMessageMesh(int playerid, int meshindex, int gua)
{
SendNetMsgMesh( playerid, meshindex, gua);
}
void dbGetNetMessage(void)
{
GetNetMsg ( );
}
int dbNetMessageInteger(void)
{
return NetMsgInteger ( );
}
float dbNetMessageFloat(void)
{
DWORD dwReturn = NetMsgFloat ( );
return *( float* ) &dwReturn;
}
char* dbNetMessageString(void)
{
static char* szReturn = NULL;
DWORD dwReturn = NetMsgString ( NULL );
szReturn = ( char* ) dwReturn;
return szReturn;
}
void dbNetMessageMemblock(int mbi)
{
NetMsgMemblock( mbi);
}
void dbNetMessageImage(int imageindex)
{
NetMsgImage( imageindex);
}
void dbNetMessageBitmap(int bitmapindex)
{
NetMsgBitmap( bitmapindex);
}
void dbNetMessageSound(int soundindex)
{
NetMsgSound( soundindex);
}
void dbNetMessageMesh(int meshindex)
{
NetMsgMesh( meshindex);
}
int dbNetMessageExists(void)
{
return NetMsgExists();
}
int dbNetMessageType(void)
{
return NetMsgType ( );
}
int dbNetMessagePlayerFrom(void)
{
return NetMsgPlayerFrom();
}
int dbNetMessagePlayerTo(void)
{
return NetMsgPlayerTo();
}
int dbNetSessionExists(void)
{
return NetSessionExists();
}
int dbNetSessionLost(void)
{
return NetSessionLost();
}
int dbNetPlayerCreated(void)
{
return NetPlayerCreated();
}
int dbNetPlayerDestroyed(void)
{
// lee - 300706 - fixed recursive error
return NetPlayerDestroyed();
}
int dbNetGameNowHosting(void)
{
return NetSessionIsNowHosting();
}
int dbDefaultNetGame(char* lpGameName, char* lpPlayerName, int PlayerMax, int FlagNum )
{
return MagicNetGame( ( DWORD ) lpGameName, ( DWORD ) lpPlayerName, PlayerMax, FlagNum );
}
int dbNetBufferSize(void)
{
return NetBufferSize ();
}
// lee - 300706 - GDK fixes
void dbFreeNetPlayer ( int playerid ) { dbDestroyNetPlayer ( playerid ); }
void dbSetNetConnection ( int index ) { SetNetConnections ( index ); }
void dbSetNetConnection ( int index, LPSTR ipaddress ) { dbSetNetConnections ( index, ipaddress ); }
int dbNetGameExists ( void ) { return dbNetSessionExists (); }
int dbNetGameLost ( void ) { return dbNetSessionLost (); }
#endif
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// | 0 | 0.917413 | 1 | 0.917413 | game-dev | MEDIA | 0.263048 | game-dev | 0.948261 | 1 | 0.948261 |
plusls/plusls-carpet-addition | 1,510 | src/main/java/com/plusls/carpet/mixin/MixinSettingsManager.java | package com.plusls.carpet.mixin;
import carpet.settings.SettingsManager;
import carpet.utils.Messenger;
import carpet.utils.Translations;
import com.plusls.carpet.ModInfo;
import net.minecraft.server.command.ServerCommandSource;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(SettingsManager.class)
public class MixinSettingsManager {
@Inject(
method = "listAllSettings",
slice = @Slice(
from = @At(
value = "CONSTANT",
args = "stringValue=ui.version", // after printed fabric-carpet version
ordinal = 0
)
),
at = @At(
value = "INVOKE",
target = "Lcarpet/settings/SettingsManager;getCategories()Ljava/lang/Iterable;",
ordinal = 0
),
remap = false
)
private void printAdditionVersion(ServerCommandSource source, CallbackInfoReturnable<Integer> cir) {
Messenger.m(source,
String.format("g %s ", "Plusls Carpet Addition"),
String.format("g %s: ", Translations.tr("ui.version", "version")),
String.format("g %s", ModInfo.MOD_VERSION)
);
}
}
| 0 | 0.904622 | 1 | 0.904622 | game-dev | MEDIA | 0.740264 | game-dev | 0.898967 | 1 | 0.898967 |
FoxMCTeam/TenacityRecode-master | 1,609 | src/java/net/minecraft/block/BlockStandingSign.java | package net.minecraft.block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public class BlockStandingSign extends BlockSign
{
public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15);
public BlockStandingSign()
{
this.setDefaultState(this.blockState.getBaseState().withProperty(ROTATION, Integer.valueOf(0)));
}
/**
* Called when a neighboring block changes.
*/
public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock)
{
if (!worldIn.getBlockState(pos.down()).getBlock().getMaterial().isSolid())
{
this.dropBlockAsItem(worldIn, pos, state, 0);
worldIn.setBlockToAir(pos);
}
super.onNeighborBlockChange(worldIn, pos, state, neighborBlock);
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(ROTATION, Integer.valueOf(meta));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((Integer)state.getValue(ROTATION)).intValue();
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {ROTATION});
}
}
| 0 | 0.882177 | 1 | 0.882177 | game-dev | MEDIA | 0.9902 | game-dev | 0.890469 | 1 | 0.890469 |
EliaFantini/RocketMan-a-VR-videogame-created-with-Unity | 1,819 | CS-440/Assets/Oculus/SampleFramework/Core/Locomotion/Scripts/TeleportTransition.cs | /************************************************************************************
See SampleFramework license.txt for license terms. Unless required by applicable law
or agreed to in writing, the sample code is provided “AS IS” WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the license for specific
language governing permissions and limitations under the license.
************************************************************************************/
using UnityEngine;
using System.Collections;
/// <summary>
/// Teleport transitions manage the actual relocation of the player from the current position and orientation
/// to the teleport destination.
/// All teleport transition behaviors derive from this class, primarily for type safety
/// within the LocomotionTeleport to track the current transition type.
/// </summary>
public abstract class TeleportTransition : TeleportSupport
{
protected override void AddEventHandlers()
{
LocomotionTeleport.EnterStateTeleporting += LocomotionTeleportOnEnterStateTeleporting;
base.AddEventHandlers();
}
protected override void RemoveEventHandlers()
{
LocomotionTeleport.EnterStateTeleporting -= LocomotionTeleportOnEnterStateTeleporting;
base.RemoveEventHandlers();
}
/// <summary>
/// When the teleport state is entered, simply move the player to the new location
/// without any delay or other side effects.
/// If the transition is not immediate, the transition handler will need to set the LocomotionTeleport.IsTeleporting
/// to true for the duration of the transition, setting it to false when the transition is finished which will
/// then allow the teleport state machine to switch to the PostTeleport state.
/// </summary>
protected abstract void LocomotionTeleportOnEnterStateTeleporting();
}
| 0 | 0.700688 | 1 | 0.700688 | game-dev | MEDIA | 0.956715 | game-dev | 0.681887 | 1 | 0.681887 |
GregTechCEu/GregTech | 10,581 | src/main/java/gregtech/api/util/GTTransferUtils.java | package gregtech.api.util;
import gregtech.api.capability.IMultipleTankHandler;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidActionResult;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.items.ItemHandlerHelper;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.Predicate;
public class GTTransferUtils {
public static int transferFluids(@NotNull IFluidHandler sourceHandler, @NotNull IFluidHandler destHandler) {
return transferFluids(sourceHandler, destHandler, Integer.MAX_VALUE, fluidStack -> true);
}
public static int transferFluids(@NotNull IFluidHandler sourceHandler, @NotNull IFluidHandler destHandler,
int transferLimit) {
return transferFluids(sourceHandler, destHandler, transferLimit, fluidStack -> true);
}
public static int transferFluids(@NotNull IFluidHandler sourceHandler, @NotNull IFluidHandler destHandler,
int transferLimit, @NotNull Predicate<FluidStack> fluidFilter) {
int fluidLeftToTransfer = transferLimit;
for (IFluidTankProperties tankProperties : sourceHandler.getTankProperties()) {
FluidStack currentFluid = tankProperties.getContents();
if (currentFluid == null || currentFluid.amount == 0 || !fluidFilter.test(currentFluid)) {
continue;
}
currentFluid.amount = fluidLeftToTransfer;
FluidStack fluidStack = sourceHandler.drain(currentFluid, false);
if (GTUtility.isEmpty(fluidStack)) {
continue;
}
int canInsertAmount = destHandler.fill(fluidStack, false);
if (canInsertAmount > 0) {
fluidStack.amount = canInsertAmount;
fluidStack = sourceHandler.drain(fluidStack, true);
if (!GTUtility.isEmpty(fluidStack)) {
destHandler.fill(fluidStack, true);
fluidLeftToTransfer -= fluidStack.amount;
if (fluidLeftToTransfer == 0) {
break;
}
}
}
}
return transferLimit - fluidLeftToTransfer;
}
public static boolean transferExactFluidStack(@NotNull IFluidHandler sourceHandler,
@NotNull IFluidHandler destHandler, FluidStack fluidStack) {
int amount = fluidStack.amount;
FluidStack sourceFluid = sourceHandler.drain(fluidStack, false);
if (GTUtility.isEmpty(sourceFluid) || sourceFluid.amount != amount) {
return false;
}
int canInsertAmount = destHandler.fill(sourceFluid, false);
if (canInsertAmount == amount) {
sourceFluid = sourceHandler.drain(sourceFluid, true);
if (!GTUtility.isEmpty(sourceFluid)) {
destHandler.fill(sourceFluid, true);
return true;
}
}
return false;
}
public static void moveInventoryItems(IItemHandler sourceInventory, IItemHandler targetInventory) {
for (int srcIndex = 0; srcIndex < sourceInventory.getSlots(); srcIndex++) {
ItemStack sourceStack = sourceInventory.extractItem(srcIndex, Integer.MAX_VALUE, true);
if (sourceStack.isEmpty()) {
continue;
}
ItemStack remainder = insertItem(targetInventory, sourceStack, true);
int amountToInsert = sourceStack.getCount() - remainder.getCount();
if (amountToInsert > 0) {
sourceStack = sourceInventory.extractItem(srcIndex, amountToInsert, false);
insertItem(targetInventory, sourceStack, false);
}
}
}
/**
* Simulates the insertion of items into a target inventory, then optionally performs the insertion.
* <br />
* <br />
* Simulating will not modify any of the input parameters. Insertion will either succeed completely, or fail
* without modifying anything.
* This method should be called with {@code simulate} {@code true} first, then {@code simulate} {@code false},
* only if it returned {@code true}.
*
* @param handler the target inventory
* @param simulate whether to simulate ({@code true}) or actually perform the insertion ({@code false})
* @param items the items to insert into {@code handler}.
* @return {@code true} if the insertion succeeded, {@code false} otherwise.
*/
public static boolean addItemsToItemHandler(final IItemHandler handler,
final boolean simulate,
final List<ItemStack> items) {
// determine if there is sufficient room to insert all items into the target inventory
if (simulate) {
OverlayedItemHandler overlayedItemHandler = new OverlayedItemHandler(handler);
Object2IntMap<ItemStack> stackKeyMap = GTHashMaps.fromItemStackCollection(items);
for (Object2IntMap.Entry<ItemStack> entry : stackKeyMap.object2IntEntrySet()) {
int amountToInsert = entry.getIntValue();
int amount = overlayedItemHandler.insertStackedItemStack(entry.getKey(), amountToInsert);
if (amount > 0) {
return false;
}
}
return true;
}
// perform the merge.
items.forEach(stack -> insertItem(handler, stack, false));
return true;
}
/**
* Simulates the insertion of fluid into a target fluid handler, then optionally performs the insertion.
* <br />
* <br />
* Simulating will not modify any of the input parameters. Insertion will either succeed completely, or fail
* without modifying anything.
* This method should be called with {@code simulate} {@code true} first, then {@code simulate} {@code false},
* only if it returned {@code true}.
*
* @param fluidHandler the target inventory
* @param simulate whether to simulate ({@code true}) or actually perform the insertion ({@code false})
* @param fluidStacks the items to insert into {@code fluidHandler}.
* @return {@code true} if the insertion succeeded, {@code false} otherwise.
*/
public static boolean addFluidsToFluidHandler(IMultipleTankHandler fluidHandler,
boolean simulate,
List<FluidStack> fluidStacks) {
if (simulate) {
OverlayedFluidHandler overlayedFluidHandler = new OverlayedFluidHandler(fluidHandler);
for (FluidStack fluidStack : fluidStacks) {
int inserted = overlayedFluidHandler.insertFluid(fluidStack, fluidStack.amount);
if (inserted != fluidStack.amount) {
return false;
}
}
return true;
}
for (FluidStack fluidStack : fluidStacks) {
fluidHandler.fill(fluidStack, true);
}
return true;
}
/**
* Inserts items by trying to fill slots with the same item first, and then fill empty slots.
*/
public static ItemStack insertItem(IItemHandler handler, ItemStack stack, boolean simulate) {
if (handler == null || stack.isEmpty()) {
return stack;
}
IntList emptySlots = new IntArrayList();
int slots = handler.getSlots();
for (int i = 0; i < slots; i++) {
ItemStack slotStack = handler.getStackInSlot(i);
if (slotStack.isEmpty()) {
emptySlots.add(i);
} else if (ItemHandlerHelper.canItemStacksStack(stack, slotStack)) {
stack = handler.insertItem(i, stack, simulate);
if (stack.isEmpty()) {
return ItemStack.EMPTY;
}
}
}
for (int slot : emptySlots) {
stack = handler.insertItem(slot, stack, simulate);
if (stack.isEmpty()) {
return ItemStack.EMPTY;
}
}
return stack;
}
/**
* Only inerts to empty slots. Perfect for not stackable items
*/
public static ItemStack insertToEmpty(IItemHandler handler, ItemStack stack, boolean simulate) {
if (handler == null || stack.isEmpty()) {
return stack;
}
int slots = handler.getSlots();
for (int i = 0; i < slots; i++) {
ItemStack slotStack = handler.getStackInSlot(i);
if (slotStack.isEmpty()) {
stack = handler.insertItem(i, stack, simulate);
if (stack.isEmpty()) {
return ItemStack.EMPTY;
}
}
}
return stack;
}
// TODO try to remove this one day
public static void fillInternalTankFromFluidContainer(IFluidHandler fluidHandler,
IItemHandlerModifiable itemHandler, int inputSlot,
int outputSlot) {
ItemStack inputContainerStack = itemHandler.extractItem(inputSlot, 1, true);
FluidActionResult result = FluidUtil.tryEmptyContainer(inputContainerStack, fluidHandler, Integer.MAX_VALUE,
null, false);
if (result.isSuccess()) {
ItemStack remainingItem = result.getResult();
if (ItemStack.areItemStacksEqual(inputContainerStack, remainingItem))
return; // do not fill if item stacks match
if (!remainingItem.isEmpty() && !itemHandler.insertItem(outputSlot, remainingItem, true).isEmpty())
return; // do not fill if can't put remaining item
FluidUtil.tryEmptyContainer(inputContainerStack, fluidHandler, Integer.MAX_VALUE, null, true);
itemHandler.extractItem(inputSlot, 1, false);
itemHandler.insertItem(outputSlot, remainingItem, false);
}
}
}
| 0 | 0.859649 | 1 | 0.859649 | game-dev | MEDIA | 0.772394 | game-dev | 0.968416 | 1 | 0.968416 |
odtheking/OdinFabric | 5,760 | src/main/kotlin/com/odtheking/odin/clickgui/ClickGUI.kt | package com.odtheking.odin.clickgui
import com.odtheking.odin.OdinMod
import com.odtheking.odin.OdinMod.mc
import com.odtheking.odin.clickgui.settings.impl.ColorSetting
import com.odtheking.odin.config.Config
import com.odtheking.odin.events.GuiEvent
import com.odtheking.odin.features.Category
import com.odtheking.odin.features.impl.render.ClickGUIModule
import com.odtheking.odin.utils.Color
import com.odtheking.odin.utils.Colors
import com.odtheking.odin.utils.ui.HoverHandler
import com.odtheking.odin.utils.ui.animations.LinearAnimation
import com.odtheking.odin.utils.ui.rendering.NVGRenderer
import meteordevelopment.orbit.EventHandler
import net.minecraft.client.gui.screen.Screen
import net.minecraft.text.Text
import kotlin.math.sign
import com.odtheking.odin.utils.ui.mouseX as odinMouseX
import com.odtheking.odin.utils.ui.mouseY as odinMouseY
/**
* Renders all the modules.
*
* Backend made by Aton, with some changes
* Design mostly made by Stivais
*
* @author Stivais, Aton
* @see [Panel]
*/
object ClickGUI : Screen(Text.of("Click GUI")) {
private val panels: ArrayList<Panel> = arrayListOf<Panel>().apply {
if (Category.entries.any { ClickGUIModule.panelSetting[it] == null }) ClickGUIModule.resetPositions()
for (category in Category.entries) add(Panel(category))
}
private var openAnim = LinearAnimation<Float>(400)
val gray38 = Color(38, 38, 38)
val gray26 = Color(26, 26, 26)
init {
OdinMod.EVENT_BUS.subscribe(this)
}
@EventHandler
fun render(event: GuiEvent.NVGRender) {
if (mc.currentScreen != this) return
NVGRenderer.beginFrame(mc.window.width.toFloat(), mc.window.height.toFloat())
if (openAnim.isAnimating()) {
NVGRenderer.translate(0f, openAnim.get(-10f, 0f))
NVGRenderer.globalAlpha(openAnim.get(0f, 1f))
}
for (i in 0 until panels.size) {
panels[i].draw(odinMouseX, odinMouseY)
}
SearchBar.draw(mc.window.width / 2f - 175f, mc.window.height - 110f, odinMouseX, odinMouseY)
desc.render()
NVGRenderer.endFrame()
}
override fun mouseScrolled(
mouseX: Double,
mouseY: Double,
horizontalAmount: Double,
verticalAmount: Double
): Boolean {
val actualAmount = (verticalAmount.sign * 16).toInt()
for (i in panels.size - 1 downTo 0) {
if (panels[i].handleScroll(actualAmount)) return true
}
return super.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount)
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
SearchBar.mouseClicked(odinMouseX, odinMouseY, button)
for (i in panels.size - 1 downTo 0) {
if (panels[i].mouseClicked(odinMouseX, odinMouseY, button)) return true
}
return super.mouseClicked(mouseX, mouseY, button)
}
override fun mouseReleased(mouseX: Double, mouseY: Double, state: Int): Boolean {
SearchBar.mouseReleased()
for (i in panels.size - 1 downTo 0) {
panels[i].mouseReleased(state)
}
return super.mouseReleased(mouseX, mouseY, state)
}
override fun charTyped(chr: Char, modifiers: Int): Boolean {
SearchBar.keyTyped(chr)
for (i in panels.size - 1 downTo 0) {
if (panels[i].keyTyped(chr)) return true
}
return super.charTyped(chr, modifiers)
}
override fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean {
SearchBar.keyPressed(keyCode)
for (i in panels.size - 1 downTo 0) {
if (panels[i].keyPressed(keyCode, scanCode)) return true
}
return super.keyPressed(keyCode, scanCode, modifiers)
}
override fun init() {
openAnim.start()
super.init()
}
override fun close() {
for (panel in panels.filter { it.panelSetting.extended }.reversed()) {
for (moduleButton in panel.moduleButtons.filter { it.extended }) {
for (setting in moduleButton.representableSettings) {
if (setting is ColorSetting) setting.section = null
setting.listening = false
}
}
}
Config.save()
super.close()
}
override fun shouldPause(): Boolean = false
private var desc = Description("", 0f, 0f, HoverHandler(150))
/** Sets the description without creating a new data class which isn't optimal */
fun setDescription(text: String, x: Float, y: Float, hoverHandler: HoverHandler) {
desc.text = text
desc.x = x
desc.y = y
desc.hoverHandler = hoverHandler
}
data class Description(var text: String, var x: Float, var y: Float, var hoverHandler: HoverHandler) {
fun render() {
if (text.isEmpty() || hoverHandler.percent() <= 0) return
val area = NVGRenderer.wrappedTextBounds(text, 300f, 16f, NVGRenderer.defaultFont)
NVGRenderer.rect(x, y, area[2] - area[0] + 16f, area[3] - area[1] + 16f, gray38.rgba, 5f)
NVGRenderer.hollowRect(
x,
y,
area[2] - area[0] + 16f,
area[3] - area[1] + 16f,
1.5f,
ClickGUIModule.clickGUIColor.rgba,
5f
)
NVGRenderer.drawWrappedString(text, x + 8f, y + 8f, 300f, 16f, Colors.WHITE.rgba, NVGRenderer.defaultFont)
}
}
val movementImage = NVGRenderer.createImage("/assets/odin/MovementIcon.svg")
val hueImage = NVGRenderer.createImage("/assets/odin/HueGradient.png")
val chevronImage = NVGRenderer.createImage("/assets/odin/chevron.svg")
} | 0 | 0.935577 | 1 | 0.935577 | game-dev | MEDIA | 0.8171 | game-dev | 0.970983 | 1 | 0.970983 |
Slimefun/Slimefun4 | 9,390 | src/main/java/me/mrCookieSlime/Slimefun/api/inventory/BlockMenuPreset.java | package me.mrCookieSlime.Slimefun.api.inventory;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.Validate;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem;
import io.github.thebusybiscuit.slimefun4.implementation.Slimefun;
import io.github.thebusybiscuit.slimefun4.utils.ChestMenuUtils;
import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.ChestMenu;
import me.mrCookieSlime.Slimefun.api.item_transport.ItemTransportFlow;
// This class will be deprecated, relocated and rewritten in a future version.
public abstract class BlockMenuPreset extends ChestMenu {
private final Set<Integer> occupiedSlots = new HashSet<>();
private final String inventoryTitle;
private final String id;
// -1 means "automatically update according to the contents"
private int size = -1;
private final boolean universal;
private boolean locked;
protected BlockMenuPreset(@Nonnull String id, @Nonnull String title) {
this(id, title, false);
}
protected BlockMenuPreset(@Nonnull String id, @Nonnull String title, boolean universal) {
super(title);
Validate.notNull(id, "You need to specify an id!");
this.id = id;
this.inventoryTitle = title;
this.universal = universal;
init();
Slimefun.getRegistry().getMenuPresets().put(id, this);
}
private void checkIfLocked() {
if (locked) {
throw new UnsupportedOperationException("You cannot modify the BlockMenuPreset anymore, modify the individual instances instead.");
}
}
public abstract void init();
/**
* This method returns whether a given {@link Player} is allowed to open the
* {@link BlockMenu} of that {@link Block}.
* Override this as necessary.
*
* @param b
* The {@link Block} trying to be opened
* @param p
* The {@link Player} who wants to open the {@link BlockMenu}
*
* @return Whether that {@link Player} is allowed
*/
public abstract boolean canOpen(@Nonnull Block b, @Nonnull Player p);
public abstract int[] getSlotsAccessedByItemTransport(ItemTransportFlow flow);
/**
* This method is called whenever an {@link ItemStack} changes.
* You can override this as necessary if you need to listen to these events
*
* @param menu
* The {@link Inventory} affected by this
* @param slot
* The affected slot
* @param previous
* The {@link ItemStack} in that slot before the operation
* @param next
* The {@link ItemStack} that it changes to
*
* @return The new outcome of this operation
*/
@Nullable
protected ItemStack onItemStackChange(@Nonnull DirtyChestMenu menu, int slot, @Nullable ItemStack previous, @Nullable ItemStack next) {
// Override this as necessary
return next;
}
public void newInstance(@Nonnull BlockMenu menu, @Nonnull Block b) {
// This method can optionally be overridden by implementations
}
public int[] getSlotsAccessedByItemTransport(DirtyChestMenu menu, ItemTransportFlow flow, ItemStack item) {
// This method will default to that method, it can be overridden by subclasses though
return getSlotsAccessedByItemTransport(flow);
}
@Override
public void replaceExistingItem(int slot, ItemStack item) {
throw new UnsupportedOperationException("BlockMenuPreset does not support this method.");
}
/**
* This method will draw unclickable background items into this {@link BlockMenuPreset}.
*
* @param item
* The {@link ItemStack} that should be used as background
* @param slots
* The slots which should be treated as background
*/
public void drawBackground(@Nonnull ItemStack item, @Nonnull int[] slots) {
Validate.notNull(item, "The background item cannot be null!");
checkIfLocked();
for (int slot : slots) {
addItem(slot, item, ChestMenuUtils.getEmptyClickHandler());
}
}
/**
* This method will draw unclickable background items into this {@link BlockMenuPreset}.
*
* @param slots
* The slots which should be treated as background
*/
public void drawBackground(@Nonnull int[] slots) {
drawBackground(ChestMenuUtils.getBackground(), slots);
}
@Override
public ChestMenu addItem(int slot, @Nullable ItemStack item) {
checkIfLocked();
occupiedSlots.add(slot);
return super.addItem(slot, item);
}
@Override
public ChestMenu addMenuClickHandler(int slot, MenuClickHandler handler) {
checkIfLocked();
return super.addMenuClickHandler(slot, handler);
}
@Nonnull
public ChestMenu setSize(int size) {
checkIfLocked();
if (size % 9 == 0 && size >= 0 && size < 55) {
this.size = size;
return this;
} else {
throw new IllegalArgumentException("The size of a BlockMenuPreset must be a multiple of 9 and within the bounds 0-54, received: " + size);
}
}
/**
* This method returns the size of this {@link BlockMenuPreset}.
* If the size has not been determined yet, this will return -1.
*
* @return The size of this {@link BlockMenuPreset}
*/
public int getSize() {
return size;
}
private boolean isSizeAutomaticallyInferred() {
return size == -1;
}
/**
* This returns the title of this {@link BlockMenuPreset}, the title will
* be visible in every {@link InventoryView} for any menu created using this {@link BlockMenuPreset}.
*
* @return The inventory title for this {@link BlockMenuPreset}
*/
public String getTitle() {
return inventoryTitle;
}
/**
* This method returns whether this {@link BlockMenuPreset} will spawn a {@link UniversalBlockMenu}.
*
* @return Whether this {@link BlockMenuPreset} is universal
*/
public boolean isUniversal() {
return universal;
}
@Nonnull
public Set<Integer> getPresetSlots() {
return occupiedSlots;
}
@Nonnull
public Set<Integer> getInventorySlots() {
Set<Integer> emptySlots = new HashSet<>();
if (isSizeAutomaticallyInferred()) {
for (int i = 0; i < toInventory().getSize(); i++) {
if (!occupiedSlots.contains(i)) {
emptySlots.add(i);
}
}
} else {
for (int i = 0; i < size; i++) {
if (!occupiedSlots.contains(i)) {
emptySlots.add(i);
}
}
}
return emptySlots;
}
protected void clone(@Nonnull DirtyChestMenu menu) {
menu.setPlayerInventoryClickable(true);
for (int slot : occupiedSlots) {
menu.addItem(slot, getItemInSlot(slot));
}
if (size > -1) {
menu.addItem(size - 1, null);
}
if (menu instanceof BlockMenu blockMenu) {
newInstance(blockMenu, blockMenu.getLocation());
}
for (int slot = 0; slot < 54; slot++) {
if (getMenuClickHandler(slot) != null) {
menu.addMenuClickHandler(slot, getMenuClickHandler(slot));
}
}
menu.addMenuOpeningHandler(getMenuOpeningHandler());
menu.addMenuCloseHandler(getMenuCloseHandler());
}
public void newInstance(@Nonnull BlockMenu menu, @Nonnull Location l) {
Validate.notNull(l, "Cannot create a new BlockMenu without a Location");
Slimefun.runSync(() -> {
locked = true;
try {
newInstance(menu, l.getBlock());
} catch (Exception | LinkageError x) {
getSlimefunItem().error("An Error occurred while trying to create a BlockMenu", x);
}
});
}
/**
* This returns the id of the associated {@link SlimefunItem}.
* It also doubles as the id for this {@link BlockMenuPreset}.
*
* @return Our identifier
*/
@Nonnull
public String getID() {
return id;
}
/**
* This returns the {@link SlimefunItem} associated with this {@link BlockMenuPreset}.
*
* @return The associated {@link SlimefunItem}
*/
@Nonnull
public SlimefunItem getSlimefunItem() {
return SlimefunItem.getById(id);
}
@Nullable
public static BlockMenuPreset getPreset(@Nullable String id) {
return id == null ? null : Slimefun.getRegistry().getMenuPresets().get(id);
}
public static boolean isInventory(String id) {
return Slimefun.getRegistry().getMenuPresets().containsKey(id);
}
public static boolean isUniversalInventory(String id) {
BlockMenuPreset preset = Slimefun.getRegistry().getMenuPresets().get(id);
return preset != null && preset.isUniversal();
}
}
| 0 | 0.950735 | 1 | 0.950735 | game-dev | MEDIA | 0.871444 | game-dev | 0.968135 | 1 | 0.968135 |
cgyarvin/urbit | 8,278 | jupiter/sys/201/ship.watt | => |%
++ bill ,[p=time q=*]
++ brig ,[o=(unit bill) v=(map span brig)]
++ buck ,*
++ deed :: hull action
$| ~ :: no operation
$% [%feed p=buck] :: typeless input
[%fish p=term q=quid r=pane s=fish] :: listen: set
[%give p=gift] :: release: output
:: [%halt p=term] :: listen: suspend
[%hunt p=term q=quid r=pane s=hunt] :: listen: sequence
[%more p=(list deed)] :: many dark deeds
[%post p=path q=*] :: apply: sequence
[%save p=path q=brig] :: apply: store
:: [%thaw p=term] :: listen: resume
[%wait p=term q=time r=wait] :: listen: time
[%want p=(list path) q=want] :: listen: block
[%wind p=date] :: apply: set time
==
++ date time
++ fact ,[p=path q=bill]
++ fish _|+(fact *deed)
++ frog $_
^? |%
++ boot
|= loc=path
[p=*deed q=^?(..poke)]
::
++ peek
|= [now=date cam=lens rel=path]
*brig
::
++ poke
|= [now=date cam=lens man=buck]
[p=*deed q=^?(..poke)]
--
++ gift ,*
++ lens _|+(path *brig)
++ hunt _|+([@ path bill] *deed)
++ pane $|(date [p=date q=date])
++ quid ,[p=root q=(list $|(span _|+(* span)))]
++ root $|(~ [~ p=@])
++ want _|+((list ,[p=path q=bill]) *deed)
++ wait _|+(date *deed)
--
|%
::
++ deem
|= yal=(list deed) ^- deed
?~(yal ~ (deet i.yal $(yal t.yal)))
::
++ deet
|= [yin=deed yag=deed]
^- deed
?: =(~ yin) yag
?: =(~ yag) yin
?: ?=([%more *] yag)
?: ?=([%more *] yin)
[%more (weld p.yin p.yag)]
[%more yin p.yag]
[%more yin yag ~]
::
++ hull
|= :* loc=path :: global root path
egg=frog :: business logic
==
=+ :* tar=*brig :: static storage
arc=*sail :: control state
==
|%
++ film :: namespace
^- lens
|= hip=path ^- brig
?~ hip [~ ~]
?. =(%r i.hip) [~ ~]
=> .(hip t.hip)
|- ^- brig
?~ hip
tar
=+ yiq=(~(get by v.tar) i.hip)
?~ yiq [~ ~]
$(hip t.hip, tar u.yiq)
::
++ hark :: deed by time
|= wen=date ^- [p=deed q=_..hark]
=+ taw=wit.arc
=+ vad=*(list deed)
|- ^- [p=deed q=_..hark]
?: |(?=(~ wit.arc) (lth wen p.i.wit.arc))
[(deem (flop vad)) ..hark(wit.arc taw)]
$(vad [(q.i.wit.arc wen) vad], taw t.taw)
::
++ have :: deed by want
|= mow=fact ^- [p=deed q=_..have]
=+ vad=*(list deed)
=+ nod=(~(tap by wan.arc) ~)
=+ nud=`_nod`~
|- ^- [p=deed q=_..have]
?~ nod
[(deem vad) ..have(wan.arc (~(gas by `_wan.arc`~) nud))]
=+ ^= tif ^- [p=(unit ,_i.nod) q=(unit deed)]
=+ lov=&
=+ wiz=p.q.i.nod
=+ ^= kyn
|- ^- [p=? q=_wiz]
?~ wiz
[lov ~]
=+ zaq=$(wiz t.wiz)
?: ?=(^ q.i.wiz)
[p.zaq [i.wiz q.zaq]]
?: =(p.mow p.i.wiz)
[p.zaq [[p.mow ~ q.mow] q.zaq]]
[| [i.wiz q.zaq]]
?: p.kyn
=+ ^= nyq
|- ^- (list ,[p=path q=bill])
?~(q.kyn ~ [[p.i.q.kyn (need q.i.q.kyn)] $(q.kyn t.q.kyn)])
[~ [~ (q.q.i.nod nyq)]]
[[~ p.i.nod [q.kyn q.q.i.nod]] ~]
%= $
nod t.nod
nud ?~(p.tif nud [u.p.tif nud])
vad ?~(q.tif vad [u.q.tif vad])
==
::
++ hasp :: deed by step
|= [mow=fact cam=lens] ^- [p=deed q=_..hasp]
=+ wap=(flop p.mow)
?~ wap [~ ..hasp]
=+ vec=(slay i.wap)
?. &(?=(^ vec) ?=([%% %ud *] u.vec))
[~ ..hasp]
=+ syf=(~(tap by hut.arc) ~)
=+ vad=*(list deed)
=+ yos=|
=+ paw=(flop t.wap)
|- ^- [p=deed q=_..hasp]
?~ syf
:- (deem vad)
?. yos
..hasp
..hasp(ear.arc (~(put by ear.arc) paw q.p.u.vec))
?. &((quiz paw q.q.i.syf) =(q.p.u.vec (trot paw cam)))
$(syf t.syf)
$(syf t.syf, yos &, vad [(s.q.i.syf q.p.u.vec paw q.mow) vad])
::
++ hast :: deed by name
|= mow=fact ^- deed
=+ syf=(~(tap by fis.arc) ~)
=+ vad=*(list deed)
|- ^- deed
?~ syf
(deem vad)
?. (quiz p.mow q.q.i.syf)
$(syf t.syf)
$(syf t.syf, vad [(s.q.i.syf mow) vad])
::
++ hear
|= [mow=fact cam=lens]
^- [p=deed q=_..hear]
=+ hen=*(list deed)
=+ hoy=(have mow)
=> .(..hear q.hoy, hen [p.hoy hen])
=+ zir=(hast mow)
=> .(hen [(hast mow) hen])
=+ fym=(hasp mow cam)
[(deem p.fym hen) q.fym]
::
++ kick
|= tod=deed
^- [p=(list fact) q=(list gift) r=deed s=_..kick]
?- tod
[%feed *]
!!
[%fish *] :: [p=term q=quid r=pane s=fish]
!!
[%give *] :: [p=gift]
!!
[%hunt *] :: [p=term q=quid r=pane s=hunt]
!!
[%more *] :: [p=(list deed)]
!!
[%post *] :: [p=path q=*]
!!
[%save *] :: [p=path q=brig]
!!
[%wait *] :: [p=term q=time r=_wait:weed]
!!
[%want *] :: [p=(list path) q=_want:weed]
!!
[%wind *] :: [p=date]
!!
==
::
++ kill
|= tod=deed ^- [p=(list fact) q=(list gift) r=_..kill]
=+ [saw=(list fact) dor=(list gift)]
|- ^- [p=(list fact) q=(list gift) r=_..kill]
?~ tod
[saw dor ..kill]
=+ was=(kiss tod)
=> .(..kill r.was)
=+ yaw=(know nuw)
=> .(..kill q.yaw)
=+ was=(kiss p.yaw)
%= $
nuw p.was
saw :(weld p.was nuw saw)
dor (weld q.was dor)
..kill r.was
==
::
++ kiss
|= [now=date cam=lens tod=deed]
=+ [saw=(list fact) dor=(list gift)]
|- ^- [p=(list fact) q=(list gift) r=_..kiss]
?: =(~ tod)
[dor saw ..kiss]
=+ was=(kick now cam tod)
$(saw (weld p.was saw), dor (weld q.was dor), tod r.was, ..kiss s.was)
::
++ know
|= [nuw=(list fact) cam=lens] ^- [p=deed q=_..know]
=- [(deem p.gim) q.gim]
^= gim
=+ gim=[p=*(list deed) q=..know]
|- ^+ gim
?~ nuw
gim
=+ yoy=(hear(..know q.gim) i.gim)
$(gim [[p.yoy p.gim] q.yoy])
::
++ land
|= rum=room ^- path
?~ p.rum
q.rum
(weld (flop (slag p.p.rum (flop loc))) q.rum)
::
++ trot :: first unused index
|= yop=path ^- @ud
=+ yef=(~(get by ear.arc) yop)
=+ tiv=?~(yef 0 u.yef)
=+ poy=(flop yop)
|- ^- @ud
=+ dar=(cam (flop `_poy`[(rent %ud tiv) poy]))
?~(o.dar tiv $(tiv +(tiv)))
--
::
++ sail
$: ear=(map path ,@)
fis=(map term ,[p=? q=quid r=date s=fish])
hut=(map term ,[p=? q=quid r=date s=hunt])
wan=(map term ,[p=(list ,[p=path q=(unit bill)]) q=want])
wit=(list ,[p=date q=wait])
==
::
++ quiz
|= [hap=path qid=quid]
^- ?
=+ ^= pre
?~ p.qid ~
=+ col=(flop loc)
|- ^- path
?~ col ~
?: =(0 p.p.qid)
(flop col)
$(col t.col, p.p.qid (dec p.p.qid))
=+ ^= rel
|- ^- (unit path)
?~ pre [~ hap]
?~ hap ~
?.(=(i.pre i.hap) ~ $(pre t.pre, hap t.hap))
?~ rel |
|- ^- ?
?~ hap |
?~ q.qid &
?& ?@ i.q.qid
=(i.hap i.q.qid)
=(i.hap (i.q.qid i.hap))
$(hap t.hap, q.qid t.q.qid)
==
--
| 0 | 0.860627 | 1 | 0.860627 | game-dev | MEDIA | 0.158377 | game-dev | 0.692806 | 1 | 0.692806 |
snumprlab/hima | 157,400 | bots/swarmbrain.py | import re
import time
import random
import asyncio
from openai import OpenAI
from typing import Union
from sc2.unit import Unit
from sc2.constants import *
from sc2.bot_ai import BotAI
from sc2.position import Point2, Point3
class SwarmBrain(BotAI):
def __init__(self, args):
super().__init__()
if args.mode == 'bot':
self.opposite_race = args.opposite_race
elif args.mode == 'agent':
self.opposite_race = args.own_race
self.LLM_api_mode = args.LLM_api_mode
self.temperature = args.temperature
self.chat = OpenAI(api_key=args.LLM_api_key)
stage_info = self.overmind_brain_initial()
print(stage_info)
early_units, mid_units, late_units = self.extract_units_info(stage_info)
print("Early stage units:", early_units)
early_values = self.assign_values(early_units)
print("Mid stage units:", mid_units)
mid_values = self.assign_values(mid_units)
print("Late stage units:", late_units)
late_values = self.assign_values(late_units)
strategy = self.overmind_brain_initial2()
print(strategy)
results = {}
for line in strategy.strip().split('\n'):
question, answer = line.split(':')
question = question.strip()
answer = answer.strip()
if answer == 'False':
results[question] = False
elif answer == 'True':
results[question] = True
drone_attack = results['Question 1']
counterattack = results['Question 2']
output1 = self.overmind_brain_1()
print(output1)
matches = re.findall(r'\(.*?\)->\(.*?\)->\(.*?\)', output1)
command_first = []
for match in matches:
command_first.append(match)
self.early_zergling_num, self.early_baneling_num, self.early_roach_num, self.early_ravager_num, self.early_hydralisk_num, self.early_infestor_num, self.early_swarm_host_num, self.early_mutalisk_num, self.early_corruptor_num, self.early_viper_num, self.early_ultralisk_num, self.early_brood_lord_num = early_values
self.mid_zergling_num, self.mid_baneling_num, self.mid_roach_num, self.mid_ravager_num, self.mid_hydralisk_num, self.mid_infestor_num, self.mid_swarm_host_num, self.mid_mutalisk_num, self.mid_corruptor_num, self.mid_viper_num, self.mid_ultralisk_num, self.mid_brood_lord_num = mid_values
self.late_zergling_num, self.late_baneling_num, self.late_roach_num, self.late_ravager_num, self.late_hydralisk_num, self.late_infestor_num, self.late_swarm_host_num, self.late_mutalisk_num, self.late_corruptor_num, self.late_viper_num, self.late_ultralisk_num, self.late_brood_lord_num = late_values
self.start_location_label = None
self.parsed_commands = []
self.command_list = command_first
self.building_tasks = []
self.attack_tasks = []
self.mineral_location_labels = {
(31.5, 26.5): "A1",
(28.5, 50.5): "A2",
(61.5, 45.5): "A3",
(28.5, 79.5): "A4",
(87.5, 25.5): "A5",
(85.5, 49.5): "A6",
(28.5, 110.5): "A7",
(30.5, 142.5): "A8",
(128.5, 143.5): "B1",
(131.5, 119.5): "B2",
(98.5, 124.5): "B3",
(131.5, 90.5): "B4",
(72.5, 144.5): "B5",
(74.5, 120.5): "B6",
(131.5, 59.5): "B7",
(129.5, 27.5): "B8",
}
self.mineral_location_labels_reverse = {
"A1": (31.5, 26.5),
"A2": (28.5, 50.5),
"A3": (61.5, 45.5),
"A4": (28.5, 79.5),
"A5": (87.5, 25.5),
"A6": (85.5, 49.5),
"A7": (28.5, 110.5),
"A8": (30.5, 142.5),
"B1": (128.5, 143.5),
"B2": (131.5, 119.5),
"B3": (98.5, 124.5),
"B4": (131.5, 90.5),
"B5": (72.5, 144.5),
"B6": (74.5, 120.5),
"B7": (131.5, 59.5),
"B8": (129.5, 27.5)
}
self.existing_hatchery_locations = []
self.worker_aggressive = drone_attack
self.counterattack = counterattack
self.hatchery_queen_pairs = {}
self.waiting_for_hatchery = True
self.is_attack_command_issued = False
self.previous_enemy_units = {}
self.previous_enemy_units_attack = {}
self.previous_enemy_damage = 0
self.previous_enemy_buildings = {}
self.previous_commands = []
self.base_being_attacked = False
self.defence = False
self.spread_distance = 13
self.game_stage = 0
self.attack_wave = 0
self.fight_back = False
self.queen_spread_progress = {}
async def on_start(self):
# # self.client.game_step = 2
# # await self.client.debug_show_map()
start_location_key = tuple(self.start_location)
# print("start_location_key ", start_location_key)
self.start_location_label = self.mineral_location_labels.get(start_location_key)
if self.start_location_label:
print(f"Our starting location is at {self.start_location_label}")
else:
print("Could not determine the start location label.")
self.command_list = self.filter_commands(self.command_list,
['Queen', 'Gather minerals', 'Extractor', 'Mineral', 'Overlord',
'Move', 'Zergling', 'Creep'])
if self.start_location_label == "A1":
Overmind_commands = self.command_list
new_command_list = []
if self.start_location_label == "B1":
for command in self.command_list:
def replace(match):
char, num = match.group(1), match.group(2)
return 'B' + num if char == 'A' else 'A' + num
command = re.sub(r'(A|B)(\d+)', replace, command)
new_command_list.append(command)
Overmind_commands = new_command_list
pattern = re.compile(r'\(([^)]+)\)')
for command in Overmind_commands:
parts = pattern.findall(command)
self.parsed_commands.append(parts)
# print("self.parsed_commands:", self.parsed_commands)
async def can_attack(self, location):
enemy_units_at_location = self.enemy_units.closer_than(15, location)
return enemy_units_at_location.exists
async def llm_attack_enemy(self):
if self.is_attack_command_issued:
pass
else:
if self.start_location_label == "A1":
enemy_base_list = ["B2", "B4", "B1", "B3"]
rally_point = Point2(self.mineral_location_labels_reverse["B7"])
elif self.start_location_label == "B1":
enemy_base_list = ["A2", "A4", "A1", "A3"]
rally_point = Point2(self.mineral_location_labels_reverse["A7"])
avenager_units_types = [
UnitTypeId.ZERGLING, UnitTypeId.ROACH,
UnitTypeId.RAVAGER, UnitTypeId.BANELING, UnitTypeId.HYDRALISK, UnitTypeId.INFESTOR,
UnitTypeId.SWARMHOSTMP, UnitTypeId.MUTALISK, UnitTypeId.CORRUPTOR, UnitTypeId.VIPER,
UnitTypeId.ULTRALISK, UnitTypeId.BROODLORD
]
defensive_units = self.units.filter(lambda unit: unit.type_id in avenager_units_types)
for enemy_base_label in enemy_base_list:
print("enemy_base_label:", enemy_base_label)
enemy_base_location = Point2(self.mineral_location_labels_reverse[enemy_base_label])
if await self.can_attack(enemy_base_location):
for defender in defensive_units:
defender.attack(enemy_base_location)
self.is_attack_command_issued = True
break
if not self.is_attack_command_issued:
for defender in defensive_units:
defender.move(rally_point)
def count_units_around_minerals(self):
check_radius = 10
if self.start_location_label == "A1":
enemy_mineral_positions = ["B1", "B2", "B3", "B4"]
elif self.start_location_label == "B1":
enemy_mineral_positions = ["A1", "A2", "A3", "A4"]
units_count_around_minerals = {}
count_all = 0
for label in enemy_mineral_positions:
location = self.mineral_location_labels_reverse[label]
count = self.get_units_around_location(location, check_radius)
units_count_around_minerals[label] = count
count_all += count
return units_count_around_minerals, count_all
async def attack_enemy(self):
if self.start_location_label == "A1":
enemy_base_list = ["B2", "B4", "B1", "B3"]
point1 = Point2(self.mineral_location_labels_reverse["B3"])
rally_point = point1.position.to2.towards(self.game_info.map_center, 10.0)
elif self.start_location_label == "B1":
enemy_base_list = ["A2", "A4", "A1", "A3"]
point1 = Point2(self.mineral_location_labels_reverse["A3"])
rally_point = point1.position.to2.towards(self.game_info.map_center, 10.0)
avenger_units_types = [
UnitTypeId.ZERGLING, UnitTypeId.OVERSEER, UnitTypeId.ROACH,
UnitTypeId.RAVAGER, UnitTypeId.BANELING, UnitTypeId.HYDRALISK, UnitTypeId.INFESTOR,
UnitTypeId.SWARMHOSTMP, UnitTypeId.MUTALISK, UnitTypeId.CORRUPTOR, UnitTypeId.VIPER,
UnitTypeId.ULTRALISK, UnitTypeId.BROODLORD
]
_, count_all = self.count_units_around_minerals()
if count_all > 10:
rally_point = self.enemy_start_locations[0]
avenger_units = self.units.filter(lambda unit: unit.type_id in avenger_units_types)
total_avenger_units = avenger_units.amount
if total_avenger_units == 0:
return
units_at_rally_point = avenger_units.closer_than(10, rally_point).amount # 假设的最接近距离,根据需要进行调整
required_ratio = 0.75
if units_at_rally_point / total_avenger_units >= required_ratio:
for avenger in avenger_units:
avenger.attack(Point2(self.mineral_location_labels_reverse[enemy_base_list[0]]))
else:
for avenger in avenger_units:
if avenger.distance_to(rally_point) > 10:
avenger.move(rally_point)
async def detect_enemy_invasion(self):
if self.start_location_label == "A1":
enemy_base_list = ["B2", "B4", "B1", "B3"]
rally_point = Point2(self.mineral_location_labels_reverse["B7"])
elif self.start_location_label == "B1":
enemy_base_list = ["A2", "A4", "A1", "A3"]
rally_point = Point2(self.mineral_location_labels_reverse["A7"])
enemy_close_distance = 20
chase_limit = 30
defensive_units_types = [
UnitTypeId.QUEEN, UnitTypeId.ZERGLING, UnitTypeId.OVERSEER, UnitTypeId.ROACH,
UnitTypeId.RAVAGER, UnitTypeId.BANELING, UnitTypeId.HYDRALISK, UnitTypeId.INFESTOR,
UnitTypeId.SWARMHOSTMP, UnitTypeId.MUTALISK, UnitTypeId.CORRUPTOR, UnitTypeId.VIPER,
UnitTypeId.ULTRALISK, UnitTypeId.BROODLORD
]
counterattack_units_types = [
UnitTypeId.ZERGLING, UnitTypeId.OVERSEER, UnitTypeId.ROACH,
UnitTypeId.RAVAGER, UnitTypeId.BANELING, UnitTypeId.HYDRALISK, UnitTypeId.INFESTOR,
UnitTypeId.SWARMHOSTMP, UnitTypeId.MUTALISK, UnitTypeId.CORRUPTOR, UnitTypeId.VIPER,
UnitTypeId.ULTRALISK, UnitTypeId.BROODLORD
]
base_count = self.townhalls.amount
no_enemy_count = 0
for hatchery in self.townhalls:
close_enemies = self.enemy_units.closer_than(
enemy_close_distance, hatchery.position).exclude_type(UnitTypeId.SCV)
if close_enemies.exists:
self.attack_wave += 1
hatchery_label = self.mineral_location_labels.get(hatchery.position)
print("Detect enemy around", hatchery_label)
self.base_being_attacked = True
defensive_units = self.units.filter(
lambda unit: unit.type_id in defensive_units_types
)
for defender in defensive_units:
closest_enemy = close_enemies.closest_to(defender)
if defender.distance_to(closest_enemy) < chase_limit:
defender.attack(closest_enemy)
else:
defender.move(hatchery.position)
self.defence = True
else:
no_enemy_count += 1
if no_enemy_count == base_count:
if not self.defence and not self.fight_back:
if self.base_being_attacked:
print("Enemy has been defeated.")
print("Whether we should counterattack:", self.counterattack)
self.fight_back = True
defensive_units = self.units.filter(lambda unit: unit.type_id in counterattack_units_types)
for defender in defensive_units:
defender.attack(Point2(self.mineral_location_labels_reverse[enemy_base_list[0]]))
self.base_being_attacked = False
elif self.defence:
self.defence = False
def get_units_distribution(self):
distribution = {}
for mineral_position, location_label in self.mineral_location_labels.items():
units_near_townhall = self.units.closer_than(20, mineral_position)
larvas_near_townhall = units_near_townhall.of_type({UnitTypeId.LARVA})
drones_near_townhall = units_near_townhall.of_type({UnitTypeId.DRONE})
overlords_near_townhall = units_near_townhall.of_type({UnitTypeId.OVERLORD})
queens_near_townhall = units_near_townhall.of_type({UnitTypeId.QUEEN})
zerglings_near_townhall = units_near_townhall.of_type({UnitTypeId.ZERGLING})
overseers_near_townhall = units_near_townhall.of_type({UnitTypeId.OVERSEER})
roaches_near_townhall = units_near_townhall.of_type({UnitTypeId.ROACH})
ravagers_near_townhall = units_near_townhall.of_type({UnitTypeId.RAVAGER})
banelings_near_townhall = units_near_townhall.of_type({UnitTypeId.BANELING})
hydralisks_near_townhall = units_near_townhall.of_type({UnitTypeId.HYDRALISK})
infestors_near_townhall = units_near_townhall.of_type({UnitTypeId.INFESTOR})
swarmhosts_near_townhall = units_near_townhall.of_type({UnitTypeId.SWARMHOSTMP})
mutalisks_near_townhall = units_near_townhall.of_type({UnitTypeId.MUTALISK})
corruptors_near_townhall = units_near_townhall.of_type({UnitTypeId.CORRUPTOR})
vipers_near_townhall = units_near_townhall.of_type({UnitTypeId.VIPER})
ultralisks_near_townhall = units_near_townhall.of_type({UnitTypeId.ULTRALISK})
broodlord_near_townhall = units_near_townhall.of_type({UnitTypeId.BROODLORD})
# Now collect the summary for this point
unit_summary = f""
if larvas_near_townhall.amount > 0:
unit_summary += f"{larvas_near_townhall.amount} Larvas are idling"
if drones_near_townhall.amount > 0:
unit_summary += f", {drones_near_townhall.amount} Drones are gathering mineral and gas in Hatchery"
if overlords_near_townhall.amount > 0:
unit_summary += f", {overlords_near_townhall.amount} Overlords are idling"
if queens_near_townhall.amount > 0:
unit_summary += f", {queens_near_townhall.amount} Queens are idling"
if zerglings_near_townhall.amount > 0:
unit_summary += f", {zerglings_near_townhall.amount} Zerglings are idling"
if overseers_near_townhall.amount > 0:
unit_summary += f", {overseers_near_townhall.amount} Overseers are idling"
if roaches_near_townhall.amount > 0:
unit_summary += f", {roaches_near_townhall.amount} Roaches are idling"
if ravagers_near_townhall.amount > 0:
unit_summary += f", {ravagers_near_townhall.amount} Ravagers are idling"
if banelings_near_townhall.amount > 0:
unit_summary += f", {banelings_near_townhall.amount} Banelings are idling"
if hydralisks_near_townhall.amount > 0:
unit_summary += f", {hydralisks_near_townhall.amount} Hydralisks are idling"
if infestors_near_townhall.amount > 0:
unit_summary += f", {infestors_near_townhall.amount} Infestors are idling"
if swarmhosts_near_townhall.amount > 0:
unit_summary += f", {swarmhosts_near_townhall.amount} Swarm Hosts are idling"
if mutalisks_near_townhall.amount > 0:
unit_summary += f", {mutalisks_near_townhall.amount} Mutalisks are idling"
if corruptors_near_townhall.amount > 0:
unit_summary += f", {corruptors_near_townhall.amount} Corruptors are idling"
if vipers_near_townhall.amount > 0:
unit_summary += f", {vipers_near_townhall.amount} Vipers are idling"
if ultralisks_near_townhall.amount > 0:
unit_summary += f", {ultralisks_near_townhall.amount} Ultralisks are idling"
if broodlord_near_townhall.amount > 0:
unit_summary += f", {broodlord_near_townhall.amount} Brood Lords are idling"
if unit_summary == "":
continue
# Assign the summary to the distribution dict
distribution[location_label] = unit_summary
return distribution
def get_units_all(self):
drones = self.units(UnitTypeId.DRONE).amount
overlords = self.units(UnitTypeId.OVERLORD).amount
queens = self.units(UnitTypeId.QUEEN).amount
zerglings = self.units(UnitTypeId.ZERGLING).amount
overseers = self.units(UnitTypeId.OVERSEER).amount
roaches = self.units(UnitTypeId.ROACH).amount
ravagers = self.units(UnitTypeId.RAVAGER).amount
banelings = self.units(UnitTypeId.BANELING).amount
hydralisks = self.units(UnitTypeId.HYDRALISK).amount
infestors = self.units(UnitTypeId.INFESTOR).amount
swarmhosts = self.units(UnitTypeId.SWARMHOSTMP).amount
mutalisks = self.units(UnitTypeId.MUTALISK).amount
corruptors = self.units(UnitTypeId.CORRUPTOR).amount
vipers = self.units(UnitTypeId.VIPER).amount
ultralisks = self.units(UnitTypeId.ULTRALISK).amount
broodlords = self.units(UnitTypeId.BROODLORD).amount
summary = f""
if drones > 0:
summary += f"{drones} Drones"
if overlords > 0:
if summary:
summary += f", {overlords} Overlords"
else:
summary += f"{overlords} Overlords"
if queens > 0:
if summary:
summary += f", {queens} Queens"
else:
summary += f"{queens} Queens"
if zerglings > 0:
if summary:
summary += f", {zerglings} Zerglings"
else:
summary += f"{zerglings} Zerglings"
if overseers > 0:
if summary:
summary += f", {overseers} Overseers"
else:
summary += f"{overseers} Overseers"
if roaches > 0:
if summary:
summary += f", {roaches} Roaches"
else:
summary += f"{roaches} Roaches"
if ravagers > 0:
if summary:
summary += f", {ravagers} Ravagers"
else:
summary += f"{ravagers} Ravagers"
if banelings > 0:
if summary:
summary += f", {banelings} Banelings"
else:
summary += f"{banelings} Banelings"
if hydralisks > 0:
if summary:
summary += f", {hydralisks} Hydralisks"
else:
summary += f"{hydralisks} Hydralisks"
if infestors > 0:
if summary:
summary += f", {infestors} Infestors"
else:
summary += f"{infestors} Infestors"
if swarmhosts > 0:
if summary:
summary += f", {swarmhosts} Swarm Hosts"
else:
summary += f"{swarmhosts} Swarm Hosts"
if mutalisks > 0:
if summary:
summary += f", {mutalisks} Mutalisks"
else:
summary += f"{mutalisks} Mutalisks"
if corruptors > 0:
if summary:
summary += f", {corruptors} Corruptors"
else:
summary += f"{corruptors} Corruptors"
if vipers > 0:
if summary:
summary += f", {vipers} Vipers"
else:
summary += f"{vipers} Vipers"
if ultralisks > 0:
if summary:
summary += f", {ultralisks} Ultralisks"
else:
summary += f"{ultralisks} Ultralisks"
if broodlords > 0:
if summary:
summary += f", {broodlords} Brood Lords"
else:
summary += f"{broodlords} Brood Lords"
return summary
def get_units_all_attack(self):
zerglings = self.units(UnitTypeId.ZERGLING).amount
roaches = self.units(UnitTypeId.ROACH).amount
ravagers = self.units(UnitTypeId.RAVAGER).amount
banelings = self.units(UnitTypeId.BANELING).amount
hydralisks = self.units(UnitTypeId.HYDRALISK).amount
infestors = self.units(UnitTypeId.INFESTOR).amount
swarmhosts = self.units(UnitTypeId.SWARMHOSTMP).amount
mutalisks = self.units(UnitTypeId.MUTALISK).amount
corruptors = self.units(UnitTypeId.CORRUPTOR).amount
vipers = self.units(UnitTypeId.VIPER).amount
ultralisks = self.units(UnitTypeId.ULTRALISK).amount
broodlords = self.units(UnitTypeId.BROODLORD).amount
army_damage = zerglings * 5 + roaches * 16 + ravagers * 16 + banelings * 16 + hydralisks * 12 + mutalisks * 9 + corruptors * 14 + ultralisks * 35 + broodlords * 20
summary = f""
if zerglings > 0:
summary += f"{zerglings} Zerglings"
if roaches > 0:
if summary:
summary += f", {roaches} Roaches"
else:
summary += f"{roaches} Roaches"
if ravagers > 0:
if summary:
summary += f", {ravagers} Ravagers"
else:
summary += f"{ravagers} Ravagers"
if banelings > 0:
if summary:
summary += f", {banelings} Banelings"
else:
summary += f"{banelings} Banelings"
if hydralisks > 0:
if summary:
summary += f", {hydralisks} Hydralisks"
else:
summary += f"{hydralisks} Hydralisks"
if infestors > 0:
if summary:
summary += f", {infestors} Infestors"
else:
summary += f"{infestors} Infestors"
if swarmhosts > 0:
if summary:
summary += f", {swarmhosts} Swarm Hosts"
else:
summary += f"{swarmhosts} Swarm Hosts"
if mutalisks > 0:
if summary:
summary += f", {mutalisks} Mutalisks"
else:
summary += f"{mutalisks} Mutalisks"
if corruptors > 0:
if summary:
summary += f", {corruptors} Corruptors"
else:
summary += f"{corruptors} Corruptors"
if vipers > 0:
if summary:
summary += f", {vipers} Vipers"
else:
summary += f"{vipers} Vipers"
if ultralisks > 0:
if summary:
summary += f", {ultralisks} Ultralisks"
else:
summary += f"{ultralisks} Ultralisks"
if broodlords > 0:
if summary:
summary += f", {broodlords} Brood Lords"
else:
summary += f"{broodlords} Brood Lords"
return summary, army_damage
def get_buildings_distribution(self):
distribution = {}
for townhall in self.townhalls.ready:
townhall_location_label = self.mineral_location_labels.get(townhall.position)
buildings_near_townhall = self.structures.closer_than(20, townhall.position)
extractor_near_townhall = buildings_near_townhall.of_type({UnitTypeId.EXTRACTOR})
spawningpool_near_townhall = buildings_near_townhall.of_type({UnitTypeId.SPAWNINGPOOL})
evolutionchamber_near_townhall = buildings_near_townhall.of_type({UnitTypeId.EVOLUTIONCHAMBER})
roachwarren_near_townhall = buildings_near_townhall.of_type({UnitTypeId.ROACHWARREN})
banelingnest_near_townhall = buildings_near_townhall.of_type({UnitTypeId.BANELINGNEST})
spinecrawler_near_townhall = buildings_near_townhall.of_type({UnitTypeId.SPINECRAWLER})
sporecrawler_near_townhall = buildings_near_townhall.of_type({UnitTypeId.SPORECRAWLER})
hydraliskden_near_townhall = buildings_near_townhall.of_type({UnitTypeId.HYDRALISKDEN})
infestationpit_near_townhall = buildings_near_townhall.of_type({UnitTypeId.INFESTATIONPIT})
spire_near_townhall = buildings_near_townhall.of_type({UnitTypeId.SPIRE})
nydusnetwork_near_townhall = buildings_near_townhall.of_type({UnitTypeId.NYDUSNETWORK})
ultraliskcavern_near_townhall = buildings_near_townhall.of_type({UnitTypeId.ULTRALISKCAVERN})
greaterspire_near_townhall = buildings_near_townhall.of_type({UnitTypeId.GREATERSPIRE})
unit_summary = f"1 {townhall.name.lower()}"
if extractor_near_townhall.amount > 0:
unit_summary += f", {extractor_near_townhall.amount} Extractor"
if spawningpool_near_townhall.amount > 0:
unit_summary += f", {spawningpool_near_townhall.amount} Spawning Pool"
if evolutionchamber_near_townhall.amount > 0:
unit_summary += f", {evolutionchamber_near_townhall.amount} Evolution Chamber"
if roachwarren_near_townhall.amount > 0:
unit_summary += f", {roachwarren_near_townhall.amount} Roach Warren"
if banelingnest_near_townhall.amount > 0:
unit_summary += f", {banelingnest_near_townhall.amount} Baneling Nest"
if spinecrawler_near_townhall.amount > 0:
unit_summary += f", {spinecrawler_near_townhall.amount} Spine Crawler"
if sporecrawler_near_townhall.amount > 0:
unit_summary += f", {sporecrawler_near_townhall.amount} Spore Crawler"
if hydraliskden_near_townhall.amount > 0:
unit_summary += f", {hydraliskden_near_townhall.amount} Hydralisk Den"
if infestationpit_near_townhall.amount > 0:
unit_summary += f", {infestationpit_near_townhall.amount} Infestation Pit"
if spire_near_townhall.amount > 0:
unit_summary += f", {spire_near_townhall.amount} Spire"
if nydusnetwork_near_townhall.amount > 0:
unit_summary += f", {nydusnetwork_near_townhall.amount} Nydus Network"
if ultraliskcavern_near_townhall.amount > 0:
unit_summary += f", {ultraliskcavern_near_townhall.amount} Ultralisk Cavern"
if greaterspire_near_townhall.amount > 0:
unit_summary += f", {greaterspire_near_townhall.amount} Greater Spire"
distribution[townhall_location_label] = unit_summary
return distribution
def get_buildings_all(self):
hatchery = self.structures(UnitTypeId.HATCHERY).amount
lair = self.structures(UnitTypeId.LAIR).amount
hive = self.structures(UnitTypeId.HIVE).amount
extractor = self.structures(UnitTypeId.EXTRACTOR).amount
spawningpool = self.structures(UnitTypeId.SPAWNINGPOOL).amount
evolutionchamber = self.structures(UnitTypeId.EVOLUTIONCHAMBER).amount
roachwarren = self.structures(UnitTypeId.ROACHWARREN).amount
banelingnest = self.structures(UnitTypeId.BANELINGNEST).amount
spinecrawler = self.structures(UnitTypeId.SPINECRAWLER).amount
sporecrawler = self.structures(UnitTypeId.SPORECRAWLER).amount
hydraliskden = self.structures(UnitTypeId.HYDRALISKDEN).amount
infestationpit = self.structures(UnitTypeId.INFESTATIONPIT).amount
spire = self.structures(UnitTypeId.SPIRE).amount
nydusnetwork = self.structures(UnitTypeId.NYDUSNETWORK).amount
ultraliskcavern = self.structures(UnitTypeId.ULTRALISKCAVERN).amount
greaterspire = self.structures(UnitTypeId.GREATERSPIRE).amount
summary = f""
if hatchery > 0:
summary += f"{hatchery} Hatchery"
if lair > 0:
summary += f", {lair} Lair"
if hive > 0:
summary += f", {hive} Hive"
if extractor > 0:
summary += f", {extractor} Extractor"
if spawningpool > 0:
summary += f", {spawningpool} Spawningpool"
if evolutionchamber > 0:
summary += f", {evolutionchamber} Evolution Chamber"
if roachwarren > 0:
summary += f", {roachwarren} Roach Warren"
if banelingnest > 0:
summary += f", {banelingnest} Baneling Nest"
if spinecrawler > 0:
summary += f", {spinecrawler} Spine Crawler"
if sporecrawler > 0:
summary += f", {sporecrawler} Spore Crawler"
if hydraliskden > 0:
summary += f", {hydraliskden} Hydralisk Den"
if infestationpit > 0:
summary += f", {infestationpit} Infestation Pit"
if spire > 0:
summary += f", {spire} Spire"
if nydusnetwork > 0:
summary += f", {nydusnetwork} Nydus Network"
if ultraliskcavern > 0:
summary += f", {ultraliskcavern} Ultralisk Cavern"
if greaterspire > 0:
summary += f", {greaterspire} Greater Spire"
return summary
def get_tech(self):
tech_info = []
for upgrade in self.state.upgrades:
upgrade_name = upgrade.name
tech_info.append(upgrade_name)
return tech_info
def get_enemy_units(self):
if len(self.enemy_units) == 0:
return {}
distribution = {}
for mineral_position, location_label in self.mineral_location_labels.items():
units_near_mineral = self.enemy_units.closer_than(25, mineral_position)
scv_near_mineral = units_near_mineral.of_type({UnitTypeId.SCV})
marine_near_mineral = units_near_mineral.of_type({UnitTypeId.MARINE})
reaper_near_mineral = units_near_mineral.of_type({UnitTypeId.REAPER})
marauder_near_mineral = units_near_mineral.of_type({UnitTypeId.MARAUDER})
ghost_near_mineral = units_near_mineral.of_type({UnitTypeId.GHOST})
hellion_near_mineral = units_near_mineral.of_type({UnitTypeId.HELLION})
widowmine_near_mineral = units_near_mineral.of_type({UnitTypeId.WIDOWMINE})
cyclone_near_mineral = units_near_mineral.of_type({UnitTypeId.CYCLONE})
siegetank_near_mineral = units_near_mineral.of_type({UnitTypeId.SIEGETANK})
hellbat_near_mineral = units_near_mineral.of_type({UnitTypeId.HELLBATACGLUESCREENDUMMY})
thor_near_mineral = units_near_mineral.of_type({UnitTypeId.THOR})
viking_near_mineral = units_near_mineral.of_type({UnitTypeId.VIKING})
medivac_near_mineral = units_near_mineral.of_type({UnitTypeId.MEDIVAC})
liberator_near_mineral = units_near_mineral.of_type({UnitTypeId.LIBERATOR})
raven_near_mineral = units_near_mineral.of_type({UnitTypeId.RAVEN})
banshee_near_mineral = units_near_mineral.of_type({UnitTypeId.BANSHEE})
battlecruiser_near_mineral = units_near_mineral.of_type({UnitTypeId.BATTLECRUISER})
unit_summary = f""
if scv_near_mineral.amount > 0:
unit_summary += f"{scv_near_mineral.amount} SCVs"
if marine_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {marine_near_mineral.amount} Marines"
else:
unit_summary += f"{marine_near_mineral.amount} Marines"
if reaper_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {reaper_near_mineral.amount} Reapers"
else:
unit_summary += f"{reaper_near_mineral.amount} Reapers"
if marauder_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {marauder_near_mineral.amount} Marauders"
else:
unit_summary += f"{marauder_near_mineral.amount} Marauders"
if ghost_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {ghost_near_mineral.amount} Ghosts"
else:
unit_summary += f"{ghost_near_mineral.amount} Ghosts"
if hellion_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {hellion_near_mineral.amount} Hellions"
else:
unit_summary += f"{hellion_near_mineral.amount} Hellions"
if widowmine_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {widowmine_near_mineral.amount} Widow Mines"
else:
unit_summary += f"{widowmine_near_mineral.amount} Widow Mines"
if cyclone_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {cyclone_near_mineral.amount} Cyclones"
else:
unit_summary += f"{cyclone_near_mineral.amount} Cyclones"
if siegetank_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {siegetank_near_mineral.amount} Siege Tanks"
else:
unit_summary += f"{siegetank_near_mineral.amount} Siege Tanks"
if hellbat_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {hellbat_near_mineral.amount} Hellbats"
else:
unit_summary += f"{hellbat_near_mineral.amount} Hellbats"
if thor_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {thor_near_mineral.amount} Thors"
else:
unit_summary += f"{thor_near_mineral.amount} Thors"
if viking_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {viking_near_mineral.amount} Vikings"
else:
unit_summary += f"{viking_near_mineral.amount} Vikings"
if medivac_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {medivac_near_mineral.amount} Medivacs"
else:
unit_summary += f"{medivac_near_mineral.amount} Medivacs"
if liberator_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {liberator_near_mineral.amount} Liberators"
else:
unit_summary += f"{liberator_near_mineral.amount} Liberators"
if raven_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {raven_near_mineral.amount} Ravens"
else:
unit_summary += f"{raven_near_mineral.amount} Ravens"
if banshee_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {banshee_near_mineral.amount} Banshees"
else:
unit_summary += f"{banshee_near_mineral.amount} Banshees"
if battlecruiser_near_mineral.amount > 0:
if unit_summary:
unit_summary += f", {battlecruiser_near_mineral.amount} Battle Cruisers"
else:
unit_summary += f"{battlecruiser_near_mineral.amount} Battle Cruisers"
if unit_summary == "":
continue
distribution[location_label] = unit_summary
return distribution
def get_enemy_units_all(self):
marines = self.enemy_units(UnitTypeId.MARINE).amount
reapers = self.enemy_units(UnitTypeId.REAPER).amount
marauders = self.enemy_units(UnitTypeId.MARAUDER).amount
ghosts = self.enemy_units(UnitTypeId.GHOST).amount
hellions = self.enemy_units(UnitTypeId.HELLION).amount
widowmines = self.enemy_units(UnitTypeId.WIDOWMINE).amount
cyclones = self.enemy_units(UnitTypeId.CYCLONE).amount
siegetanks = self.enemy_units(UnitTypeId.SIEGETANK).amount
hellbats = self.enemy_units(UnitTypeId.HELLBATACGLUESCREENDUMMY).amount
thors = self.enemy_units(UnitTypeId.THOR).amount
vikings = self.enemy_units(UnitTypeId.VIKING).amount
medivacs = self.enemy_units(UnitTypeId.MEDIVAC).amount
liberators = self.enemy_units(UnitTypeId.LIBERATOR).amount
ravens = self.enemy_units(UnitTypeId.RAVEN).amount
banshees = self.enemy_units(UnitTypeId.BANSHEE).amount
battlecruisers = self.enemy_units(UnitTypeId.BATTLECRUISER).amount
enemy_damage = marines * 6 + reapers * 4 + marauders * 10 + ghosts * 10 + hellions * 8 + widowmines * 125 + cyclones * 11 + siegetanks * 40 + hellbats * 18 + thors * 30 + vikings * 12 + liberators * 5 + banshees * 12 + battlecruisers * 8
summary = f""
if marines > 0:
summary += f"{marines} Marines"
if reapers > 0:
if summary:
summary += f", {reapers} Reapers"
else:
summary += f", {reapers} Reapers"
if marauders > 0:
if summary:
summary += f", {marauders} Marauders"
else:
summary += f"{marauders} Marauders"
if ghosts > 0:
if summary:
summary += f", {ghosts} Ghosts"
else:
summary += f"{ghosts} Ghosts"
if hellions > 0:
if summary:
summary += f", {hellions} Hellions"
else:
summary += f"{hellions} Hellions"
if widowmines > 0:
if summary:
summary += f", {widowmines} Widow Mines"
else:
summary += f", {widowmines} Widow Mines"
if cyclones > 0:
if summary:
summary += f", {cyclones} Cyclones"
else:
summary += f"{cyclones} Cyclones"
if siegetanks > 0:
if summary:
summary += f", {siegetanks} Siege Tanks"
else:
summary += f"{siegetanks} Siege Tanks"
if hellbats > 0:
if summary:
summary += f", {hellbats} Hellbats"
else:
summary += f"{hellbats} Hellbats"
if thors > 0:
if summary:
summary += f", {thors} Thors"
else:
summary += f"{thors} Thors"
if vikings > 0:
if summary:
summary += f", {vikings} Vikings"
else:
summary += f"{vikings} Vikings"
if medivacs > 0:
if summary:
summary += f", {medivacs} Medivacs"
else:
summary += f"{medivacs} Medivacs"
if liberators > 0:
if summary:
summary += f", {liberators} Liberators"
else:
summary += f"{liberators} Liberators"
if ravens > 0:
if summary:
summary += f", {ravens} Ravens"
else:
summary += f"{ravens} Ravens"
if banshees > 0:
if summary:
summary += f", {banshees} Banshees"
else:
summary += f"{banshees} Banshees"
if battlecruisers > 0:
if summary:
summary += f", {battlecruisers} Battlecruisers"
else:
summary += f"{battlecruisers} Battlecruisers"
return summary, enemy_damage
def get_enemy_buildings(self):
if len(self.enemy_structures) == 0:
return {}
distribution = {}
for mineral_position, location_label in self.mineral_location_labels.items():
units_near_mineral = self.enemy_structures.closer_than(25, mineral_position)
commandcenter_near_townhall = units_near_mineral.of_type({UnitTypeId.COMMANDCENTER})
refinery_near_townhall = units_near_mineral.of_type({UnitTypeId.REFINERY})
supplydepot_near_townhall = units_near_mineral.of_type({UnitTypeId.SUPPLYDEPOT})
engineeringbay_near_townhall = units_near_mineral.of_type({UnitTypeId.ENGINEERINGBAY})
missileturret_near_townhall = units_near_mineral.of_type({UnitTypeId.MISSILETURRET})
sensortower_near_townhall = units_near_mineral.of_type({UnitTypeId.SENSORTOWER})
planetaryfortress_near_townhall = units_near_mineral.of_type({UnitTypeId.PLANETARYFORTRESS})
barracks_near_townhall = units_near_mineral.of_type({UnitTypeId.BARRACKS})
bunker_near_townhall = units_near_mineral.of_type({UnitTypeId.BUNKER})
ghostacademy_near_townhall = units_near_mineral.of_type({UnitTypeId.GHOSTACADEMY})
factory_near_townhall = units_near_mineral.of_type({UnitTypeId.FACTORY})
orbitalcommand_near_townhall = units_near_mineral.of_type({UnitTypeId.ORBITALCOMMAND})
armory_near_townhall = units_near_mineral.of_type({UnitTypeId.ARMORY})
starport_near_townhall = units_near_mineral.of_type({UnitTypeId.STARPORT})
fusioncore_near_townhall = units_near_mineral.of_type({UnitTypeId.FUSIONCORE})
unit_summary = f""
if commandcenter_near_townhall.amount > 0:
unit_summary += f"{commandcenter_near_townhall.amount} Command Center"
if refinery_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {refinery_near_townhall.amount} Refinery"
else:
unit_summary += f"{refinery_near_townhall.amount} Refinery"
if supplydepot_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {supplydepot_near_townhall.amount} Supply Depot"
else:
unit_summary += f"{supplydepot_near_townhall.amount} Supply Depot"
if engineeringbay_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {engineeringbay_near_townhall.amount} Engineering Bay"
else:
unit_summary += f"{engineeringbay_near_townhall.amount} Engineering Bay"
if missileturret_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {missileturret_near_townhall.amount} Missile Turret"
else:
unit_summary += f"{missileturret_near_townhall.amount} Missile Turret"
if sensortower_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {sensortower_near_townhall.amount} Sensor Tower"
else:
unit_summary += f"{sensortower_near_townhall.amount} Sensor Tower"
if planetaryfortress_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {planetaryfortress_near_townhall.amount} Planetary Fortress"
else:
unit_summary += f"{planetaryfortress_near_townhall.amount} Planetary Fortress"
if barracks_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {barracks_near_townhall.amount} Barracks"
else:
unit_summary += f"{barracks_near_townhall.amount} Barracks"
if bunker_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {bunker_near_townhall.amount} Bunker"
else:
unit_summary += f"{bunker_near_townhall.amount} Bunker"
if ghostacademy_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {ghostacademy_near_townhall.amount} Ghost Academy"
else:
unit_summary += f"{ghostacademy_near_townhall.amount} Ghost Academy"
if factory_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {factory_near_townhall.amount} Factory"
else:
unit_summary += f"{factory_near_townhall.amount} Factory"
if orbitalcommand_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {orbitalcommand_near_townhall.amount} Orbital Command"
else:
unit_summary += f"{orbitalcommand_near_townhall.amount} Orbital Command"
if armory_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {armory_near_townhall.amount} Armory"
else:
unit_summary += f", {armory_near_townhall.amount} Armory"
if starport_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {starport_near_townhall.amount} Starport"
else:
unit_summary += f"{starport_near_townhall.amount} Starport"
if fusioncore_near_townhall.amount > 0:
if unit_summary:
unit_summary += f", {fusioncore_near_townhall.amount} Fusion Core"
else:
unit_summary += f"{fusioncore_near_townhall.amount} Fusion Core"
if unit_summary == "":
continue
distribution[location_label] = unit_summary
return distribution
def filter_commands(self, commands, target_objects):
filtered_commands = [cmd for cmd in commands if not any(obj in cmd for obj in target_objects)]
return filtered_commands
def id_game_stage(self):
if self.supply_cap <= 60:
return 0 # early
elif self.supply_cap > 60:
return 1 # mid
elif self.supply_cap > 100:
return 2 # late
def detect_stage(self, text):
if 'early' in text and 'mid' not in text:
return 0
elif 'early' in text and 'mid' in text:
return 1
elif 'late' in text:
return 2
return self.id_game_stage()
def get_units_around_location(self, location, radius):
units_around = [unit for unit in self.units if self.distance(unit.position, location) < radius]
return len(units_around)
def distance(self, point1, point2):
return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5
async def early_game_production(self):
await self.Drone_ReflexNet()
if self.early_zergling_num != 0:
await self.Zergling_ReflexNet()
if self.early_roach_num != 0:
await self.Roach_ReflexNet()
async def mid_game_production(self):
await self.Drone_ReflexNet()
if self.mid_roach_num != 0:
await self.Roach_ReflexNet()
if self.mid_ravager_num != 0:
await self.Ravager_ReflexNet()
if self.mid_hydralisk_num != 0:
await self.Hydralisk_ReflexNet()
if self.mid_zergling_num != 0:
await self.Zergling_ReflexNet()
async def late_game_production(self):
if self.minerals < 1000:
await self.Drone_ReflexNet()
if self.late_roach_num != 0:
await self.Roach_ReflexNet()
if self.late_ravager_num != 0:
await self.Ravager_ReflexNet()
if self.late_zergling_num != 0:
await self.Zergling_ReflexNet()
if self.late_ultralisk_num != 0:
await self.Ultralisk_ReflexNet()
if self.late_hydralisk_num != 0:
await self.Hydralisk_ReflexNet()
if self.late_corruptor_num != 0:
await self.Corruptor_ReflexNet()
# await self.infestor_ReflexNet()
async def morphing(self):
if self.waiting_for_hatchery == True and self.minerals <= 400:
print("No morphing due to waiting_for_hatchery")
return
# print("morphing")
# Roach
if self.structures(UnitTypeId.ROACHWARREN).ready.exists:
if self.game_stage == 0: # Early Stage
roach_thre = self.early_roach_num
if self.units(UnitTypeId.ROACH).amount < self.early_roach_num:
if self.can_afford(UnitTypeId.ROACH) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ROACH)
print("early larva.train(UnitTypeId.ROACH)")
elif self.game_stage == 1: # Mid Stage
roach_thre = self.mid_roach_num
if self.units(UnitTypeId.ROACH).amount < self.mid_roach_num:
if self.can_afford(UnitTypeId.ROACH) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ROACH)
print("mid larva.train(UnitTypeId.ROACH)")
elif self.game_stage == 2: # Late Stage
roach_thre = self.late_roach_num
if self.units(UnitTypeId.ROACH).amount < self.late_roach_num:
if self.can_afford(UnitTypeId.ROACH) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ROACH)
print("late larva.train(UnitTypeId.ROACH)")
# Ravager
if self.can_afford(UnitTypeId.RAVAGER) and self.units(UnitTypeId.ROACH).exists and self.supply_left > 0:
if self.game_stage == 0: # Early Stage
if self.units(UnitTypeId.RAVAGER).amount < self.early_ravager_num:
roach = self.units(UnitTypeId.ROACH).ready.idle
if roach.exists:
roach.random(AbilityId.MORPHTORAVAGER_RAVAGER)
elif self.game_stage == 1: # Mid Stage
if self.units(UnitTypeId.RAVAGER).amount < self.mid_ravager_num:
roach = self.units(UnitTypeId.ROACH).ready.idle
if roach.exists:
roach.random(AbilityId.MORPHTORAVAGER_RAVAGER)
elif self.game_stage == 2: # Late Stage
if self.units(UnitTypeId.ROACH).amount < self.late_ravager_num:
roach = self.units(UnitTypeId.ROACH).ready.idle
if roach.exists:
roach.random(AbilityId.MORPHTORAVAGER_RAVAGER)
# Hydralisk
if self.structures(UnitTypeId.HYDRALISKDEN).ready.exists:
if self.game_stage == 0:
hydralisk_num = self.early_hydralisk_num
elif self.game_stage == 1:
hydralisk_num = self.mid_hydralisk_num
elif self.game_stage == 2:
hydralisk_num = self.late_hydralisk_num
if self.units(UnitTypeId.HYDRALISK).amount < hydralisk_num:
if self.can_afford(UnitTypeId.HYDRALISK) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.HYDRALISK)
print("train hydralisk")
# Zergling
if self.structures(UnitTypeId.SPAWNINGPOOL).ready.exists:
if self.game_stage == 0: # Early Stage
if self.units(UnitTypeId.ZERGLING).amount < self.early_zergling_num:
if self.can_afford(UnitTypeId.ZERGLING) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ZERGLING)
print("early larva.train(UnitTypeId.ZERGLING)")
elif self.game_stage == 1: # Mid Stage
if self.units(UnitTypeId.ZERGLING).amount < self.mid_zergling_num:
if self.can_afford(UnitTypeId.ZERGLING) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ZERGLING)
print("mid larva.train(UnitTypeId.ZERGLING)")
elif self.game_stage == 2: # Late Stage
if self.units(UnitTypeId.ZERGLING).amount < self.late_zergling_num:
if self.can_afford(UnitTypeId.ZERGLING) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ZERGLING)
print("late larva.train(UnitTypeId.ZERGLING)")
# Baneling
if self.structures(UnitTypeId.BANELINGNEST).ready.exists and self.supply_left > 0 and self.can_afford(
UnitTypeId.BANELING):
if self.game_stage == 0: # Early Stage
if self.units(UnitTypeId.BANELING).amount < self.early_baneling_num:
zergling = self.units(UnitTypeId.ZERGLING).ready.idle
if zergling.exists:
zergling.random(AbilityId.MORPHTOBANELING_BANELING)
elif self.game_stage == 1: # Mid Stage
if self.units(UnitTypeId.BANELING).amount < self.mid_baneling_num:
zergling = self.units(UnitTypeId.ZERGLING).ready.idle
if zergling.exists:
zergling.random(AbilityId.MORPHTOBANELING_BANELING)
elif self.game_stage == 2: # Late Stage
if self.units(UnitTypeId.BANELING).amount < self.late_baneling_num:
zergling = self.units(UnitTypeId.ZERGLING).ready.idle
if zergling.exists:
zergling.random(AbilityId.MORPHTOBANELING_BANELING)
# Ultralisk
if self.structures(UnitTypeId.ULTRALISKCAVERN).ready.exists:
ultralisk_num = 0
if self.game_stage == 0:
ultralisk_num = self.early_ultralisk_num
elif self.game_stage == 1:
ultralisk_num = self.mid_ultralisk_num
elif self.game_stage == 2:
ultralisk_num = self.late_ultralisk_num
if self.units(UnitTypeId.ULTRALISK).amount < ultralisk_num:
if self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ULTRALISK)
# Corruptor
if self.structures(UnitTypeId.SPIRE).ready.exists:
corruptor_num = 0
if self.game_stage == 0:
corruptor_num = self.early_corruptor_num
elif self.game_stage == 1:
corruptor_num = self.mid_corruptor_num
elif self.game_stage == 2:
corruptor_num = self.late_corruptor_num
if self.units(UnitTypeId.CORRUPTOR).amount <= corruptor_num:
if self.can_afford(UnitTypeId.CORRUPTOR) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.CORRUPTOR)
async def on_step(self, iteration: int):
# if self.enemy_units:
# await self.client.debug_kill_unit(self.enemy_units)
await self.Drone_ReflexNet()
await self.morphing()
await self.Queen_ReflexNet()
await self.distribute_workers()
await self.auto_build_extractors()
await self.auto_research()
await self.queen_spread()
await self.Ravager_ReflexNet()
if self.id_game_stage() == 0:
self.game_stage = 0
await self.early_game_production()
elif self.id_game_stage() == 1:
self.game_stage = 1
await self.mid_game_production()
elif self.id_game_stage() == 2:
self.game_stage = 2
await self.late_game_production()
await self.Overlord_ReflexNet()
await self.handle_commands()
await self.detect_enemy_invasion()
if iteration % 60 == 0:
if len(self.parsed_commands) < 10:
building_task = asyncio.create_task(self.overmind_building_iter())
self.building_tasks.append(building_task)
finished_tasks = [task for task in self.building_tasks if task.done()]
for task in finished_tasks:
result = task.result()
print("building result:", result)
self.building_tasks.remove(task)
if iteration % 150 == 0:
if self.army_count > 15:
attack_tasks = asyncio.create_task(self.overmind_attack_iter())
self.attack_tasks.append(attack_tasks)
finished_tasks = [task for task in self.attack_tasks if task.done()]
for task in finished_tasks:
result = task.result()
print("attack result:", result)
self.attack_tasks.remove(task)
def time_exceeds(self, minutes):
minutes_passed, seconds_passed = map(int, self.time_formatted.split(':'))
total_seconds_passed = (minutes_passed * 60) + seconds_passed
threshold_seconds = minutes * 60
return total_seconds_passed > threshold_seconds
async def build_buildings(self, name, i, location):
if "Drone" in name:
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if "Hatchery" in name:
print("Hatchery in name")
if self.can_afford(UnitTypeId.HATCHERY):
pos = Point2(self.mineral_location_labels_reverse[location])
if not self.time_exceeds(4) and self.army_count <= 15 and self.townhalls.amount == 2:
return
if await self.can_place(UnitTypeId.HATCHERY, pos):
success = self.workers.collecting.random.build(UnitTypeId.HATCHERY, pos)
if success:
self.waiting_for_hatchery = False
print("self.waiting_for_hatchery set to False")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
else:
print("cannot place Hatchery!", location)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Spawning Pool" in name:
# print("Spawning Pool in name")
if self.already_pending(UnitTypeId.SPAWNINGPOOL):
print("SPAWNINGPOOL in pending")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
# print("Already have SPAWNINGPOOL:", self.structures(UnitTypeId.SPAWNINGPOOL).amount)
if self.structures(UnitTypeId.SPAWNINGPOOL).amount >= 1:
# print("Already have SPAWNINGPOOL:", self.structures(UnitTypeId.SPAWNINGPOOL).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.SPAWNINGPOOL) and self.already_pending(UnitTypeId.SPAWNINGPOOL) == 0:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.SPAWNINGPOOL,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.SPAWNINGPOOL, placement_position)
# print("Build success:", success)
if success:
# print("Successfully built Spawning Pool")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Evolution Chamber" in name:
if self.already_pending(UnitTypeId.EVOLUTIONCHAMBER):
# print("Evolution Chamber in pending")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
# print("Already have EVOLUTIONCHAMBER:", self.structures(UnitTypeId.EVOLUTIONCHAMBER).amount)
if self.structures(UnitTypeId.EVOLUTIONCHAMBER).amount >= 1:
# print("Already have EVOLUTIONCHAMBER:", self.structures(UnitTypeId.EVOLUTIONCHAMBER).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.EVOLUTIONCHAMBER) and self.structures(
UnitTypeId.SPAWNINGPOOL).exists and not self.structures(
UnitTypeId.EVOLUTIONCHAMBER).ready.exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.EVOLUTIONCHAMBER,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.EVOLUTIONCHAMBER, placement_position)
# print("Build success:", success)
if success:
# print("Successfully built Evolution Chamber")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.waiting_for_hatchery == True:
return
if "Extractor" in name:
# print("Extractor in name")
if self.can_afford(UnitTypeId.EXTRACTOR):
base_location = Point2(self.mineral_location_labels_reverse[location])
if self.townhalls.closer_than(2.0, base_location).ready.exists:
hatchery = self.townhalls.closer_than(2.0, base_location).ready.first
for vg in self.vespene_geyser.closer_than(10, hatchery):
drone: Unit = self.workers.random
drone.build_gas(vg)
# print("Successfully built gas")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
# print("Deleted command_list at index", i)
break
elif "Spine Crawler" in name:
if self.can_afford(UnitTypeId.SPINECRAWLER):
base_location = Point2(self.mineral_location_labels_reverse[location])
spine_near_townhall = self.structures(UnitTypeId.SPINECRAWLER).closer_than(15, base_location).amount
if spine_near_townhall >= 1:
# print("Already have SPINECRAWLER:", spine_near_townhall)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
next_place = self.game_info.map_center
if self.start_location_label == "A1":
next_place = Point2(self.mineral_location_labels_reverse["A2"])
elif self.start_location_label == "B1":
next_place = Point2(self.mineral_location_labels_reverse["B2"])
pos = base_location.position.to2.towards(next_place, 5.0)
placement_position = await self.find_placement(UnitTypeId.SPINECRAWLER,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.SPINECRAWLER, placement_position)
if success:
# print("Successfully built Spine Crawler")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Spore Crawler" in name:
if self.can_afford(UnitTypeId.SPORECRAWLER):
# Don't want too many spore crawler around base
base_location = Point2(self.mineral_location_labels_reverse[location])
spore_near_townhall = self.structures(UnitTypeId.SPORECRAWLER).closer_than(15, base_location).amount
if spore_near_townhall >= 1:
# print("Already have SPORECRAWLER:", spore_near_townhall)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.SPORECRAWLER,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.SPORECRAWLER, placement_position)
if success:
# print("Successfully built Spore Crawler")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if not self.time_exceeds(5):
return
elif "Lair" in name:
# print("Lair in name")
if self.can_afford(UnitTypeId.LAIR):
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
hatchery = self.townhalls.closer_than(2.0, base_location).ready.first
success = hatchery.build(UnitTypeId.LAIR)
if success:
# print("Successfully built Lair")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Roach Warren" in name:
if self.already_pending(UnitTypeId.ROACHWARREN):
# print("ROACHWARREN is already pending")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.structures(UnitTypeId.ROACHWARREN).amount >= 1:
# print("Already have ROACHWARREN:", self.structures(UnitTypeId.ROACHWARREN).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.ROACHWARREN) and not self.structures(
UnitTypeId.ROACHWARREN).ready.exists and self.structures(UnitTypeId.SPAWNINGPOOL).ready.exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.ROACHWARREN,
near=pos)
if await self.can_place_single(UnitTypeId.ROACHWARREN, placement_position):
drone: Unit = self.workers.closest_to(placement_position)
success = drone.build(UnitTypeId.ROACHWARREN, placement_position)
if success:
# print("Successfully built Roach Warren")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Baneling Nest" in name:
if self.structures(UnitTypeId.BANELINGNEST).amount >= 1 and self.already_pending(UnitTypeId.BANELINGNEST):
# print("Already have BANELINGNEST:", self.structures(UnitTypeId.BANELINGNEST).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.BANELINGNEST) and not self.structures(
UnitTypeId.BANELINGNEST).exists and not self.already_pending(UnitTypeId.BANELINGNEST):
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.BANELINGNEST,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.BANELINGNEST, placement_position)
if success:
# print("Successfully built Baneling Nest")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Hydralisk" in name:
if self.structures(UnitTypeId.HYDRALISKDEN).amount >= 1:
# print("Already have HYDRALISKDEN:", self.structures(UnitTypeId.HYDRALISKDEN).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.HYDRALISKDEN) and not self.structures(
UnitTypeId.HYDRALISKDEN).ready.exists and self.townhalls(UnitTypeId.LAIR).ready.exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.HYDRALISKDEN,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.HYDRALISKDEN, placement_position)
if success:
# print("Successfully built Hydralisk den")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Infestation Pit" in name:
if self.structures(UnitTypeId.INFESTATIONPIT).amount >= 1:
# print("Already have INFESTATIONPIT:", self.structures(UnitTypeId.INFESTATIONPIT).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if not self.townhalls(UnitTypeId.LAIR).ready.exists and not self.already_pending(UnitTypeId.LAIR):
if self.can_afford(UnitTypeId.LAIR):
hatchery = self.townhalls(UnitTypeId.HATCHERY).ready.first
success = hatchery.build(UnitTypeId.LAIR)
if self.can_afford(UnitTypeId.INFESTATIONPIT) and not self.structures(
UnitTypeId.INFESTATIONPIT).ready.exists and self.townhalls(UnitTypeId.LAIR).ready.exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 5.0)
placement_position = await self.find_placement(UnitTypeId.ROACHWARREN,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.INFESTATIONPIT, placement_position)
if success:
# print("Successfully built Infestation Pit")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Spire" in name:
if self.structures(UnitTypeId.SPIRE).amount >= 1 and not self.already_pending(UnitTypeId.SPIRE):
# print("Already have SPIRE:", self.structures(UnitTypeId.SPIRE).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.SPIRE) and not self.structures(
UnitTypeId.SPIRE).exists and self.townhalls(UnitTypeId.LAIR).ready.exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
pos = base_location.position.to2.towards(self.game_info.map_center, 6.0)
placement_position = await self.find_placement(UnitTypeId.SPIRE,
near=pos)
success = self.workers.collecting.random.build(UnitTypeId.SPIRE, placement_position)
if success:
# print("Successfully built Spire")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
# print("self.time_exceeds(10):", self.time_exceeds(10))
if not self.time_exceeds(10):
return
elif "Hive" in name:
# print("Hive in name")
if self.can_afford(UnitTypeId.HIVE) and self.structures(
UnitTypeId.LAIR).ready.exists and self.structures(UnitTypeId.INFESTATIONPIT).ready.exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
hatchery = self.townhalls.closer_than(2.0, base_location).ready.first
success = hatchery.build(UnitTypeId.HIVE)
if success:
# print("Successfully built Hive")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Ultralisk Cavern" in name:
if self.townhalls(UnitTypeId.LAIR).exists:
if not self.townhalls(UnitTypeId.HIVE).ready.exists and not self.already_pending(UnitTypeId.HIVE):
if self.can_afford(UnitTypeId.HIVE):
lair = self.townhalls(UnitTypeId.LAIR).ready.first
success = lair.build(UnitTypeId.HIVE)
else:
if self.can_afford(UnitTypeId.LAIR):
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
hatchery = self.townhalls.closer_than(2.0, base_location).ready.first
success = hatchery.build(UnitTypeId.LAIR)
if success:
print("build Lair success")
if self.structures(UnitTypeId.ULTRALISKCAVERN).amount >= 1:
# print("Already have ULTRALISKCAVERN:", self.structures(UnitTypeId.ULTRALISKCAVERN).amount)
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if self.can_afford(UnitTypeId.ULTRALISKCAVERN) and self.townhalls(
UnitTypeId.HIVE).ready.exists and not self.structures(UnitTypeId.ULTRALISKCAVERN).exists:
if self.start_location_label == "A1":
base_location = Point2(self.mineral_location_labels_reverse["A1"])
elif self.start_location_label == "B1":
base_location = Point2(self.mineral_location_labels_reverse["B1"])
if self.start_location_label == "A1":
next_place = Point2(self.mineral_location_labels_reverse["A2"])
elif self.start_location_label == "B1":
next_place = Point2(self.mineral_location_labels_reverse["B2"])
pos2 = base_location.position.to2.towards(next_place, 5.0)
placement_position = await self.find_placement(UnitTypeId.ULTRALISKCAVERN,
near=pos2)
success = self.workers.collecting.random.build(UnitTypeId.ULTRALISKCAVERN, placement_position)
if success:
# print("Successfully built Ultralisk Cavern")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Greater Spire" in name:
if not self.townhalls(UnitTypeId.HIVE).ready.exists and not self.already_pending(UnitTypeId.HIVE):
if self.can_afford(UnitTypeId.HIVE) and self.townhalls(UnitTypeId.LAIR).exists:
lair = self.townhalls(UnitTypeId.LAIR).ready.first
success = lair.build(UnitTypeId.HIVE)
if success:
print("Build Hive")
if self.can_afford(UnitTypeId.GREATERSPIRE) and self.structures(UnitTypeId.SPIRE).ready.exists:
spire = self.structures(UnitTypeId.SPIRE).ready.first
success = spire.build(UnitTypeId.GREATERSPIRE)
if success:
print("Build Greater Spire")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
else:
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
async def build_units(self, name, i):
if "Drone" in name:
# print("build drone")
if self.can_afford(UnitTypeId.DRONE) and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.DRONE)
# print("Successfully built Drone")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
elif "Zergling" in name:
if self.can_afford(UnitTypeId.ZERGLING) and self.structures(
UnitTypeId.SPAWNINGPOOL).ready.exists and self.units(
UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ZERGLING)
# print("Successfully built Zergling")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Roach" in name:
if self.can_afford(UnitTypeId.ROACH) and self.structures(
UnitTypeId.ROACHWARREN).ready.exists and self.units(
UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ROACH)
# print("Successfully built Roach")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
elif "Ravager" in name:
if self.can_afford(UnitTypeId.RAVAGER) and self.units(UnitTypeId.ROACH).exists and self.supply_left > 0:
roach = self.units(UnitTypeId.ROACH).ready.idle
if roach.exists:
roach.random(AbilityId.MORPHTORAVAGER_RAVAGER)
elif "Hydralisk" in name:
if self.can_afford(UnitTypeId.HYDRALISK) and self.structures(
UnitTypeId.HYDRALISKDEN).ready.exists and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.HYDRALISK)
# print("Successfully built Hydralisk")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
def check_loc(self, input_str):
loc_list = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"]
for loc in loc_list:
if loc in input_str:
return loc
return ""
def find_safety(self, position):
friendly_location = min(self.structures.ready,
key=lambda unit: unit.position.distance_to(position)).position
return friendly_location
async def Drone_ReflexNet(self):
# print("Drone_ReflexNet")
await self.autocreating_drones()
for drone in self.workers.idle:
if self.townhalls.ready.exists:
closest_hatchery = self.townhalls.ready.closest_to(drone)
closest_minerals = self.mineral_field.closer_than(30, closest_hatchery).closest_to(closest_hatchery)
drone.gather(closest_minerals)
for drone in self.workers:
threats = self.enemy_units.closer_than(5, drone)
if threats:
# print("Drone detected enemy!")
no_threats = threats.filter(lambda unit: unit.can_attack_ground and unit.type_id == UnitTypeId.SCV)
low_threats = threats.filter(lambda unit: unit.can_attack_ground and unit.type_id == UnitTypeId.MARINE)
high_threats = threats.filter(
lambda
unit: unit.can_attack_ground and unit.type_id != UnitTypeId.MARINE and unit.type_id != UnitTypeId.SCV)
if self.worker_aggressive == False:
if low_threats.amount > 0 and low_threats.amount <= 2:
for d in self.workers.closer_than(5, drone):
d.attack(low_threats.closest_to(d))
if high_threats.exists:
enemy_center = high_threats.center
for d in self.workers.closer_than(5, drone):
retreat_point = d.position.towards_with_random_angle(enemy_center, -5)
d.move(retreat_point)
continue
if not self.enemy_units.closer_than(10, drone):
bases = self.townhalls(UnitTypeId.HATCHERY).ready
if bases:
base = max(bases, key=lambda b: b.ideal_harvesters - b.assigned_harvesters)
drone.gather(self.mineral_field.closest_to(base))
else:
if high_threats.exists:
for d in self.workers.closer_than(8, drone):
d.attack(high_threats.closest_to(d))
if low_threats.exists:
for d in self.workers.closer_than(8, drone):
d.attack(low_threats.closest_to(d))
async def autocreating_drones(self):
all_hatcheries = self.townhalls.ready
mineral_fields = self.mineral_field
drones = self.units(UnitTypeId.DRONE)
drones_per_mineral_patch = 2
for hatchery in all_hatcheries:
nearby_mineral_patches = mineral_fields.closer_than(10, hatchery)
optimal_drones = drones_per_mineral_patch * nearby_mineral_patches.amount
hatchery_drones = drones.closer_than(10, hatchery)
if len(hatchery_drones) < optimal_drones:
if self.can_afford(UnitTypeId.DRONE) and self.larva:
self.train(UnitTypeId.DRONE, amount=3)
async def auto_build_extractors(self):
for hatchery in self.townhalls.ready:
if self.workers.closer_than(10, hatchery).amount > 14:
if self.can_afford(UnitTypeId.EXTRACTOR):
for vg in self.vespene_geyser.closer_than(10, hatchery):
drone: Unit = self.workers.random
drone.build_gas(vg)
async def auto_research(self):
if self.units(UnitTypeId.OVERLORD).amount >= 5:
if self.can_afford(UpgradeId.OVERLORDSPEED) and self.townhalls.exists:
self.research(UpgradeId.OVERLORDSPEED)
if self.units(UnitTypeId.ZERGLING).amount >= 5:
if self.structures(UnitTypeId.SPAWNINGPOOL).ready.exists and self.can_afford(
UpgradeId.ZERGLINGMOVEMENTSPEED):
self.research(UpgradeId.ZERGLINGMOVEMENTSPEED)
if self.units(UnitTypeId.BANELING).amount >= 4 and self.structures(
UnitTypeId.BANELINGNEST).ready.exists and self.already_pending_upgrade(
UpgradeId.CENTRIFICALHOOKS) == 0:
if self.can_afford(UpgradeId.CENTRIFICALHOOKS):
success = self.research(UpgradeId.CENTRIFICALHOOKS)
# if not success:
# print("CENTRIFICALHOOKS failed:", success)
if self.units(UnitTypeId.ZERGLING).amount >= 8 and self.structures(
UnitTypeId.EVOLUTIONCHAMBER).ready.exists and self.already_pending_upgrade(
UpgradeId.ZERGMELEEWEAPONSLEVEL1) == 0:
if self.can_afford(UpgradeId.ZERGMELEEWEAPONSLEVEL1):
success = self.research(UpgradeId.ZERGMELEEWEAPONSLEVEL1)
# if not success:
# print("ZERGMELEEWEAPONSLEVEL1 failed!", success)
if self.units(UnitTypeId.ROACH).amount >= 5 and self.structures(
UnitTypeId.EVOLUTIONCHAMBER).ready.exists and self.already_pending_upgrade(
UpgradeId.ZERGMISSILEWEAPONSLEVEL1) == 0:
if self.can_afford(UpgradeId.ZERGMISSILEWEAPONSLEVEL1):
success = self.research(UpgradeId.ZERGMISSILEWEAPONSLEVEL1)
# if not success:
# print("ZERGMISSILEWEAPONSLEVEL1 failed!", success)
if self.units(UnitTypeId.ROACH).amount >= 8 and self.structures(
UnitTypeId.EVOLUTIONCHAMBER).ready.exists and self.already_pending_upgrade(
UpgradeId.ZERGGROUNDARMORSLEVEL1) == 0:
if self.can_afford(UpgradeId.ZERGGROUNDARMORSLEVEL1):
success = self.research(UpgradeId.ZERGGROUNDARMORSLEVEL1)
# if not success:
# print("ZERGGROUNDARMORSLEVEL1 failed!", success)
if self.structures(UnitTypeId.EVOLUTIONCHAMBER).ready.exists and self.structures(UnitTypeId.LAIR).ready.exists:
if self.can_afford(UpgradeId.ZERGMELEEWEAPONSLEVEL2) and self.already_pending_upgrade(
UpgradeId.ZERGMELEEWEAPONSLEVEL2) == 0:
success = self.research(UpgradeId.ZERGMELEEWEAPONSLEVEL2)
# if not success:
# print("ZERGMELEEWEAPONSLEVEL2 failed! ", success)
if self.can_afford(UpgradeId.ZERGMISSILEWEAPONSLEVEL2) and self.already_pending_upgrade(
UpgradeId.ZERGMISSILEWEAPONSLEVEL2) == 0:
success = self.research(UpgradeId.ZERGMISSILEWEAPONSLEVEL2)
# if not success:
# print("ZERGMELEEWEAPONSLEVEL2 failed!", success)
if self.can_afford(UpgradeId.ZERGGROUNDARMORSLEVEL2) and self.already_pending_upgrade(
UpgradeId.ZERGGROUNDARMORSLEVEL2) == 0:
success = self.research(UpgradeId.ZERGGROUNDARMORSLEVEL2)
# if not success:
# print("ZERGGROUNDARMORSLEVEL2 failed!", success)
if self.structures(UnitTypeId.EVOLUTIONCHAMBER).ready.exists and self.structures(UnitTypeId.HIVE).ready.exists:
if self.can_afford(UpgradeId.ZERGMELEEWEAPONSLEVEL3) and self.already_pending_upgrade(
UpgradeId.ZERGMELEEWEAPONSLEVEL3) == 0:
success = self.research(UpgradeId.ZERGMELEEWEAPONSLEVEL3)
# if not success:
# print("ZERGMELEEWEAPONSLEVEL3 failed!", success)
if self.can_afford(UpgradeId.ZERGMISSILEWEAPONSLEVEL3) and self.already_pending_upgrade(
UpgradeId.ZERGMISSILEWEAPONSLEVEL3) == 0:
success = self.research(UpgradeId.ZERGMISSILEWEAPONSLEVEL3)
# if not success:
# print("ZERGMISSILEWEAPONSLEVEL3 failed!", success)
if self.can_afford(UpgradeId.ZERGGROUNDARMORSLEVEL3) and self.already_pending_upgrade(
UpgradeId.ZERGGROUNDARMORSLEVEL3) == 0:
success = self.research(UpgradeId.ZERGGROUNDARMORSLEVEL3)
# if not success:
# print("ZERGGROUNDARMORSLEVEL3 failed!", success)
if self.units(UnitTypeId.ROACH).amount > 5:
if self.can_afford(UpgradeId.GLIALRECONSTITUTION) and not self.already_pending_upgrade(
UpgradeId.GLIALRECONSTITUTION):
success = self.research(UpgradeId.GLIALRECONSTITUTION)
# if not success:
# print("GLIALRECONSTITUTION failed:", success)
if self.units(UnitTypeId.HYDRALISK).amount > 5:
if self.can_afford(UpgradeId.EVOLVEMUSCULARAUGMENTS):
success = self.research(UpgradeId.EVOLVEMUSCULARAUGMENTS)
if not success:
print("EVOLVEMUSCULARAUGMENTS failed!", success)
async def overlord_random_scout(self, overlord):
if overlord.is_idle:
all_coordinates = list(self.expansion_locations.keys())
scout_position = random.choice(all_coordinates)
overlord.move(scout_position)
async def Overlord_ReflexNet(self):
if self.supply_cap < 44:
if self.supply_left < 3 and not self.already_pending(UnitTypeId.OVERLORD):
larvas = self.units(UnitTypeId.LARVA)
if larvas.exists and self.can_afford(UnitTypeId.OVERLORD):
# print("train overlord supply_left:", self.supply_left)
larvas.random.train(UnitTypeId.OVERLORD)
elif self.supply_cap >= 44 and self.supply_cap != 200:
if self.supply_left >= 0 and self.supply_left < 5:
larvas = self.units(UnitTypeId.LARVA)
if larvas.exists and self.can_afford(UnitTypeId.OVERLORD):
# print("train overlord supply_left:", self.supply_left)
larvas.random.train(UnitTypeId.OVERLORD)
for overlord in self.units(UnitTypeId.OVERLORD):
threats = self.enemy_units.filter(lambda unit: unit.can_attack_air).closer_than(15, overlord)
if threats:
# self.detect_threat(threats)
if self.base_being_attacked == False:
retreat_point = self.find_safety(overlord.position)
overlord.move(retreat_point)
else:
overlord.move(self.start_location)
else:
await self.overlord_random_scout(overlord)
async def overlord_scout(self, i, location):
if location == "":
return
loc = Point2(self.mineral_location_labels_reverse[location])
overlords = self.units(UnitTypeId.OVERLORD)
if overlords.exists:
closest_overlord = overlords.closest_to(loc)
closest_overlord.move(loc)
# print("Successfully move Overlord")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
async def zergling_command(self, name, action, i, location):
if 'baneling' in name.lower():
if self.can_afford(UnitTypeId.BANELING) and self.structures(
UnitTypeId.BANELINGNEST).ready.exists and self.supply_left > 0:
zergling = self.units(UnitTypeId.ZERGLING).ready.idle
if zergling.exists:
zergling.random(AbilityId.MORPHTOBANELING_BANELING)
# print("Successfully morph Baneling")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if location == "":
return
loc = Point2(self.mineral_location_labels_reverse[location])
keywords = ['move', 'attack']
if any(keyword.lower() in action.lower() for keyword in keywords):
# await self.attack_enemy()
# for zergling in self.units(UnitTypeId.ZERGLING).ready:
# zergling.attack(loc)
# print("Successfully move Zergling")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
async def roach_command(self, name, action, i, location):
if 'ravager' in name.lower():
if self.can_afford(UnitTypeId.RAVAGER) and self.structures(
UnitTypeId.ROACHWARREN).ready.exists and self.supply_left > 0:
roach = self.units(UnitTypeId.ROACH).ready.idle
if roach.exists:
roach.random(AbilityId.MORPHTORAVAGER_RAVAGER)
# print("Successfully morph Ravager")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
if location == "":
return
loc = Point2(self.mineral_location_labels_reverse[location])
keywords = ['move', 'attack']
if any(keyword.lower() in action.lower() for keyword in keywords):
# await self.attack_enemy()
for roach in self.units(UnitTypeId.ZERGLING).ready:
roach.attack(loc)
# print("Successfully move roach")
if i < len(self.parsed_commands):
del self.parsed_commands[i]
return
async def Zergling_ReflexNet(self):
# print("Zergling_ReflexNet")
for zergling in self.units(UnitTypeId.ZERGLING).ready:
threats = self.enemy_units.closer_than(15, zergling)
if threats:
# print("zergling detected enemy!")
sigetank = threats.filter(lambda unit: unit.type_id == UnitTypeId.SIEGETANK)
if sigetank.exists:
sigetank_attack = sigetank.closest_to(zergling)
# print("zergling attack sigetank!")
zergling.attack(sigetank_attack)
async def Queen_ReflexNet(self):
# print("Queen_ReflexNet")
all_hatcheries = self.townhalls.ready
len_hatcheries = self.townhalls.ready.amount
if self.units(UnitTypeId.QUEEN).amount < len_hatcheries * 4:
if self.can_afford(UnitTypeId.QUEEN) and self.structures(
UnitTypeId.SPAWNINGPOOL).ready.exists and not self.already_pending(UnitTypeId.QUEEN):
self.train(UnitTypeId.QUEEN)
for hatchery in all_hatcheries:
queens_nearby = self.units(UnitTypeId.QUEEN).closer_than(8, hatchery)
if not queens_nearby.exists and self.base_being_attacked == False:
if self.can_afford(UnitTypeId.QUEEN) and self.structures(UnitTypeId.SPAWNINGPOOL).ready.exists:
self.train(UnitTypeId.QUEEN)
if self.hatchery_queen_pairs.get(hatchery.tag) is None:
queens_nearby = self.units(UnitTypeId.QUEEN).idle.closer_than(8, hatchery)
if queens_nearby:
assignable_queens = [q for q in queens_nearby if
q.energy >= 25 and q.tag not in self.hatchery_queen_pairs.values()]
if assignable_queens:
closest_queen = assignable_queens[0]
self.hatchery_queen_pairs[hatchery.tag] = closest_queen.tag
queen_tag = self.hatchery_queen_pairs.get(hatchery.tag)
if queen_tag is not None:
queen = self.units(UnitTypeId.QUEEN).find_by_tag(queen_tag)
if queen:
abilities = await self.get_available_abilities(queen)
if AbilityId.EFFECT_INJECTLARVA in abilities:
queen(AbilityId.EFFECT_INJECTLARVA, hatchery)
else:
# print("Queen dead")
del self.hatchery_queen_pairs[hatchery.tag]
async def queen_spread(self):
hatcheries = self.townhalls(UnitTypeId.HATCHERY) | self.townhalls(UnitTypeId.LAIR) | self.townhalls(
UnitTypeId.HIVE)
self.existing_hatchery_locations = []
for label, coordinate in self.mineral_location_labels_reverse.items():
hatchery = hatcheries.closer_than(8, Point2(coordinate)).ready
if hatchery.exists:
self.existing_hatchery_locations.append(label)
print("existing_hatchery_locations:", self.existing_hatchery_locations)
spread_sequence_A = ["A1", "A2", "A3", "B5"]
spread_sequence_B = ["B1", "B2", "B3", "A5"]
spread_sequence = spread_sequence_A if self.start_location_label == "A1" else spread_sequence_B
for queen in self.units(UnitTypeId.QUEEN).idle:
if queen.tag not in self.hatchery_queen_pairs.values():
if queen.energy >= 25:
if queen.tag not in self.queen_spread_progress:
self.queen_spread_progress[queen.tag] = 0
current_progress = self.queen_spread_progress[queen.tag] # 0, 1, 2
if current_progress >= len(spread_sequence):
continue
current_target_label = spread_sequence[current_progress] # "A1", "A2", "A4", "A3", "A7", "A4", "B4"
# print("current_target_label:", current_target_label)
next_target_label = spread_sequence[(current_progress + 1) % len(spread_sequence)]
# print("next_target_label:", next_target_label)
current_target = Point2(self.mineral_location_labels_reverse[current_target_label])
next_target = Point2(self.mineral_location_labels_reverse[next_target_label])
if self.start_location_label == "A1":
if next_target_label in ["B4"] and not await self.is_hatchery_ready_at(next_target_label):
continue
elif self.start_location_label == "B1":
if next_target_label in ["A4"] and not await self.is_hatchery_ready_at(next_target_label):
continue
spread_position = await self.find_creep_placement(AbilityId.BUILD_CREEPTUMOR_QUEEN,
current_target.towards(next_target,
self.spread_distance))
if spread_position:
queen(AbilityId.BUILD_CREEPTUMOR_QUEEN, spread_position)
self.queen_spread_progress[queen.tag] = current_progress + 1
self.spread_distance = self.spread_distance + 3
async def find_creep_placement(self, ability, center, max_radius=5, step=1):
for r in range(0, max_radius, step):
position = await self.find_placement(ability, center, max_distance=r)
if position:
return position
return None
async def is_hatchery_ready_at(self, location_label):
target_location = Point2(self.mineral_location_labels_reverse[location_label])
hatcheries = self.units(UnitTypeId.HATCHERY).ready
for hatchery in hatcheries:
if hatchery.position.to2.distance_to(target_location) < 5: # 5可根据实际情况调整为合适的距离
return True
return False
def get_high_priority_targets_roach(self, enemies):
high_priority = enemies.of_type({UnitTypeId.SIEGETANK, UnitTypeId.THOR, UnitTypeId.MARAUDER})
if high_priority.exists:
return high_priority
return enemies
def position_around_unit(self, pos: Union[Unit, Point2, Point3], distance: int = 1, step_size: int = 1,
exclude_out_of_bounds: bool = True):
pos = pos.position.rounded
positions = {
pos.offset(Point2((x, y)))
for x in range(-distance, distance + 1, step_size) for y in range(-distance, distance + 1, step_size)
if (x, y) != (0, 0)
}
# filter positions outside map size
if exclude_out_of_bounds:
positions = {
p
for p in positions
if 0 <= p[0] < self.game_info.pathing_grid.width and 0 <= p[1] < self.game_info.pathing_grid.height
}
return positions
async def Roach_ReflexNet(self):
# print("Roach_ReflexNet")
for roach in self.units(UnitTypeId.ROACH):
enemies_in_range = self.enemy_units.filter(lambda u: u.distance_to(roach) < 9)
if enemies_in_range:
if roach.weapon_cooldown == 0:
high_priority_targets = self.get_high_priority_targets_roach(enemies_in_range)
target = min(high_priority_targets, key=lambda u: u.health + u.shield)
roach.attack(target)
else:
stutter_step_positions = self.position_around_unit(roach, distance=4)
# filter in pathing grid
stutter_step_positions = {p for p in stutter_step_positions if self.in_pathing_grid(p)}
# find position furthest away from enemies and closest to unit
enemies_in_range = self.enemy_units.filter(lambda u: roach.target_in_range(u, -0.5))
if stutter_step_positions and enemies_in_range:
retreat_position = max(
stutter_step_positions,
key=lambda x: x.distance_to(enemies_in_range.center) - x.distance_to(roach),
)
roach.move(retreat_position)
async def Ravager_ReflexNet(self):
# print("Ravager_ReflexNet")
for ravager in self.units(UnitTypeId.RAVAGER):
enemies_in_range = self.enemy_units.filter(lambda u: u.distance_to(ravager) < 9)
if enemies_in_range:
high_priority_targets = self.get_high_priority_targets_roach(enemies_in_range)
if high_priority_targets:
target = min(high_priority_targets, key=lambda t: t.health + t.shield)
if ravager(AbilityId.EFFECT_CORROSIVEBILE, target.position):
# Ravager weapon is ready, find the highest priority target
stutter_step_positions = self.position_around_unit(ravager, distance=4)
# filter in pathing grid
stutter_step_positions = {p for p in stutter_step_positions if self.in_pathing_grid(p)}
# find position furthest away from enemies and closest to unit
enemies_in_range = self.enemy_units.filter(lambda u: ravager.target_in_range(u, -0.5))
if stutter_step_positions and enemies_in_range:
retreat_position = max(
stutter_step_positions,
key=lambda x: x.distance_to(enemies_in_range.center) - x.distance_to(ravager),
)
ravager.move(retreat_position)
else:
stutter_step_positions = self.position_around_unit(ravager, distance=4)
# filter in pathing grid
stutter_step_positions = {p for p in stutter_step_positions if self.in_pathing_grid(p)}
# find position furthest away from enemies and closest to unit
enemies_in_range = self.enemy_units.filter(lambda u: ravager.target_in_range(u, -0.5))
if stutter_step_positions and enemies_in_range:
retreat_position = max(
stutter_step_positions,
key=lambda x: x.distance_to(enemies_in_range.center) - x.distance_to(ravager),
)
ravager.move(retreat_position)
async def Hydralisk_ReflexNet(self):
# print("Hydralisk_ReflexNet")
if self.units(UnitTypeId.HYDRALISK).ready.exists:
for hydralisk in self.units(UnitTypeId.HYDRALISK).ready:
threats = self.enemy_units.closer_than(6, hydralisk)
if threats:
# print("hydralisk detected enemy!")
medivac = threats.filter(lambda unit: unit.type_id == UnitTypeId.MEDIVAC)
if medivac.exists:
medivac_attack = medivac.closest_to(hydralisk)
# print("hydralisk attack medivac!")
hydralisk.attack(medivac_attack)
async def Ultralisk_ReflexNet(self):
# print("Ultralisk_ReflexNet")
if self.structures(UnitTypeId.ULTRALISKCAVERN).ready.exists:
ultralisk_num = 0
if self.game_stage == 0:
ultralisk_num = self.early_ultralisk_num
elif self.game_stage == 1:
ultralisk_num = self.mid_ultralisk_num
elif self.game_stage == 2:
ultralisk_num = self.late_ultralisk_num
if self.units(UnitTypeId.ULTRALISK).amount < ultralisk_num:
if self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.ULTRALISK)
def get_high_priority_targets_corruptor(self, enemies):
high_priority = enemies.of_type({UnitTypeId.MEDIVAC, UnitTypeId.RAVEN})
if high_priority.exists:
return high_priority
return enemies
def get_high_priority_targets_infestor(self, enemies):
high_priority = enemies.of_type({UnitTypeId.MARINE, UnitTypeId.MARAUDER})
if high_priority.exists:
return high_priority
return enemies
async def Corruptor_ReflexNet(self):
# print("Corruptor_ReflexNet")
for corruptor in self.units(UnitTypeId.CORRUPTOR):
if self.enemy_units:
if corruptor.weapon_cooldown == 0:
enemies_in_range = self.enemy_units.filter(lambda u: corruptor.target_in_range(u))
if enemies_in_range:
high_priority_targets = self.get_high_priority_targets_corruptor(enemies_in_range)
target = min(high_priority_targets, key=lambda u: u.health + u.shield)
corruptor.attack(target)
else:
stutter_step_positions = self.position_around_unit(corruptor, distance=4)
# filter in pathing grid
stutter_step_positions = {p for p in stutter_step_positions if self.in_pathing_grid(p)}
# find position furthest away from enemies and closest to unit
enemies_in_range = self.enemy_units.filter(lambda u: corruptor.target_in_range(u, -0.5))
if stutter_step_positions and enemies_in_range:
retreat_position = max(
stutter_step_positions,
key=lambda x: x.distance_to(enemies_in_range.center) - x.distance_to(corruptor),
)
corruptor.move(retreat_position)
if self.units(UnitTypeId.CORRUPTOR).exists and self.supply_left > 2:
if self.structures(UnitTypeId.GREATERSPIRE).ready.exists and self.structures(UnitTypeId.HIVE).ready.exists:
corruptor = self.units(UnitTypeId.CORRUPTOR).random
corruptor(AbilityId.TRAIN_SWARMHOST)
async def infestor_ReflexNet(self):
# print("infestor_ReflexNet")
if self.structures(UnitTypeId.INFESTATIONPIT).ready.exists and self.structures(
UnitTypeId.INFESTATIONPIT).ready.exists:
infestor_num = 0
if self.game_stage == 0:
infestor_num = self.early_infestor_num
elif self.game_stage == 1:
infestor_num = self.mid_infestor_num
elif self.game_stage == 2:
infestor_num = self.late_infestor_num
if self.units(UnitTypeId.INFESTOR).amount <= infestor_num and self.units(UnitTypeId.LARVA).exists:
larva = self.units(UnitTypeId.LARVA).random
larva.train(UnitTypeId.INFESTOR)
for infestor in self.units(UnitTypeId.INFESTOR):
enemies_in_range = self.enemy_units.filter(lambda u: u.distance_to(infestor) < 9)
if enemies_in_range:
high_priority_targets = self.get_high_priority_targets_infestor(enemies_in_range)
target = min(high_priority_targets, key=lambda t: t.health + t.shield)
if infestor(AbilityId.FUNGALGROWTH_FUNGALGROWTH, target.position):
# Ravager weapon is ready, find the highest priority target
stutter_step_positions = self.position_around_unit(infestor, distance=5)
# filter in pathing grid
stutter_step_positions = {p for p in stutter_step_positions if self.in_pathing_grid(p)}
# find position furthest away from enemies and closest to unit
enemies_in_range = self.enemy_units.filter(lambda u: infestor.target_in_range(u, -0.5))
if stutter_step_positions and enemies_in_range:
retreat_position = max(
stutter_step_positions,
key=lambda x: x.distance_to(enemies_in_range.center) - x.distance_to(infestor),
)
infestor.move(retreat_position)
else:
stutter_step_positions = self.position_around_unit(infestor, distance=4)
# filter in pathing grid
stutter_step_positions = {p for p in stutter_step_positions if self.in_pathing_grid(p)}
# find position furthest away from enemies and closest to unit
enemies_in_range = self.enemy_units.filter(lambda u: infestor.target_in_range(u, -0.5))
if stutter_step_positions and enemies_in_range:
retreat_position = max(
stutter_step_positions,
key=lambda x: x.distance_to(enemies_in_range.center) - x.distance_to(infestor),
)
infestor.move(retreat_position)
async def handle_commands(self):
# if self.start_location_label == "A1":
# base_location = Point2(self.mineral_location_labels_reverse["A1"])
# elif self.start_location_label == "B1":
# base_location = Point2(self.mineral_location_labels_reverse["B1"])
filtered_commands = []
for command_list in self.parsed_commands:
if len(command_list) != 3:
continue
action, location = command_list[1], command_list[2]
if 'Build' in action and ', ' in location:
building, loc_code = location.rsplit(', ', 1)
base_location_coords = self.mineral_location_labels_reverse.get(loc_code)
if base_location_coords and "Hatchery" in command_list[2]:
base_location = Point2(base_location_coords)
hatchery = self.townhalls.closer_than(2.0, base_location).ready
if hatchery.exists:
print("Hatchery exists in", loc_code)
self.waiting_for_hatchery = False
continue
else:
if "Hatchery" in building and self.minerals <= 400:
self.waiting_for_hatchery = True
print("self.waiting_for_hatchery set to True")
filtered_commands.append(command_list)
self.parsed_commands = filtered_commands
print("filtered self.parsed_commands:", self.parsed_commands)
for command_list in self.parsed_commands:
i = self.parsed_commands.index(command_list)
if "Drone" in command_list[0]:
# print("Drone")
location = self.check_loc(command_list[2])
# print("command_list[2] ", command_list[2])
# print("location ", location)
if location == "":
if self.start_location_label == "A1":
location = "A1"
elif self.start_location_label == "B1":
location = "B1"
await self.build_buildings(command_list[2], i, location)
elif "Larva" in command_list[0]:
# print("Larva")
await self.build_units(command_list[2], i)
elif "Overlord" in command_list[0]:
location = self.check_loc(command_list[2])
await self.overlord_scout(i, location)
elif "Zergling" in command_list[0]:
action = command_list[1]
location = self.check_loc(command_list[2])
await self.zergling_command(command_list[2], action, i, location)
elif "Roach" in command_list[0]:
action = command_list[1]
location = self.check_loc(command_list[2])
await self.roach_command(command_list[2], action, i, location)
else:
if i < len(self.parsed_commands):
del self.parsed_commands[i]
print("Deleted command_list at index", i)
async def build_drones_for_second_hatchery(self):
second_hatchery = self.townhalls.ready.exclude_type({UnitTypeId.HATCHERY}).closest_to(self.start_location)
if second_hatchery and second_hatchery.assigned_harvesters < second_hatchery.ideal_harvesters:
larvas = self.units(UnitTypeId.LARVA).closer_than(10.0, second_hatchery)
if larvas.exists and self.can_afford(UnitTypeId.DRONE):
larva = larvas.random
larva.train(UnitTypeId.DRONE)
def extract_units_info(self, stage_info):
early_match = re.search(r'Early stage:(.*?)Mid stage:', stage_info, re.DOTALL)
mid_match = re.search(r'Mid stage:(.*?)Late stage:', stage_info, re.DOTALL)
late_match = re.search(r'Late stage:(.*)', stage_info, re.DOTALL)
early_stage_text = early_match.group(1).strip() if early_match else ""
mid_stage_text = mid_match.group(1).strip() if mid_match else ""
late_stage_text = late_match.group(1).strip() if late_match else ""
pattern = r'(?<=Zergling: )\d+|(?<=Baneling: )\d+|(?<=Roach: )\d+|(?<=Ravager: )\d+|(?<=Hydralisk: )\d+|(?<=Infestor: )\d+|(?<=Swarm host: )\d+|(?<=Mutalisk: )\d+|(?<=Corruptor: )\d+|(?<=Viper: )\d+|(?<=Ultralisk: )\d+|(?<=Brood Lord: )\d+'
def extract_numbers(text):
matches = re.findall(pattern, text)
return [int(match) for match in matches]
early_stage_units = extract_numbers(early_stage_text)
mid_stage_units = extract_numbers(mid_stage_text)
late_stage_units = extract_numbers(late_stage_text)
return early_stage_units, mid_stage_units, late_stage_units
def assign_values(self, units_list):
zergling_num = units_list[0]
baneling_num = units_list[1]
roach_num = units_list[2]
ravager_num = units_list[3]
hydralisk_num = units_list[4]
infestor_num = units_list[5]
swarm_host_num = units_list[6]
mutalisk_num = units_list[7]
corruptor_num = units_list[8]
viper_num = units_list[9]
ultralisk_num = units_list[10]
brood_lord_num = units_list[11]
return (zergling_num, baneling_num, roach_num, ravager_num,
hydralisk_num, infestor_num, swarm_host_num, mutalisk_num,
corruptor_num, viper_num, ultralisk_num, brood_lord_num)
async def overmind_brain_iter(self, game_time, current_units, current_buildings, current_tech, current_enemy_units,
current_enemy_buildings, previous_commands):
prompt = f'''
You are an intelligent brain of Zerg swarm in StarCraft II game.
You are very aggressive and know all the dependencies between Zerg units, Zerg buildings, and Zerg technological research.
You and {self.opposite_race} players are on a square map with 16 mines evenly distributed on the map, as shown in the following matrix:
[[A8, B5, 0, B1],
[A7, B6, B3, B2],
[A4, 0, 0, B4],
[A2, A3, A6, B7],
[A1, 0, A5, B8]]
Currently, your base is at position A1 and the {self.opposite_race} base is at position B1. 0 represents no mine, and other letters represent the mine number.
---Current battle situation
game time: {game_time}
Your current Units consists of:
{{
{current_units}
...
Omitting means no units
}}
Your current Buildings consists of :
{{
{current_buildings}
...
Omitting means no Buildings
}}
Your Zerg has developed these technological research:
{{
{current_tech}
}}
You have detected enemy units in:
{{
{current_enemy_units}
...
Omitting means no units
}}
You have detected enemy buildings in:
{{
{current_enemy_buildings}
...
Omitting means no Buildings
}}
---
--- rule
You need to analyze the game progression by following a structured protocol based on the game situation. Make sure to include the following perspectives in your analysis:
1. Current Stage of the Match: Determine the current game stage based on the game time and types of our units, whether it’s early, middle, or late stage.
2. The Condition of Our Forces: Assess our current status in dimensions of:
2.1 Our Zerg Units and Buildings: Scrutinize the state of Zerg Units and Buildings.
2.2 Our Zerg Technology: Analyze the current status of the Zerg technological research based on the unlocked research.
3. Our current Zerg Operational Strategy: Devise a reasonable strategy based on our current situation, opponent’s situation, and scouting intel.
4. Opponent's situation: Assess opponent’s current status in dimensions of:
4.1 Opponent's Units and Buildings: Analyze state of opponent’s Units and Buildings.
4.1 Opponent's Tactical Plan and our Potential Risks: Based on detected opponent’s Units and Buildings, predict the opponent's attack timing to prepare defensive measures in advance.
5. Scouting Intel: Stress the importance of recent and consistent scouting reports to stay updated on the enemy's unit composition, positioning, and possible incoming attacks or expansions.
6. Eliminate Repeated instructions: Based on "Your commands in previous round", analysis which commands are not needed to execute again.
7. Avoid problematic commands: Analysis the problematic commands in "Avoid problematic commands", and avoid the problematic commands this time.
---
---Game Key Decisions Memory
The key decisions in your memory, you can refer to these decisions for strategic deployment.
{{
Based on previous competition experience, you found that:
1. Remember to build Baneling Nest to enable morph Baneling to cause more damage.
2. You can morph many Zerglings to Banelings to cause more damage to the enemy's Marine, Marauder and Siege tanks.
3. You can morph many Roaches to Ravagers to cause more damage to the enemy's Marine, Marauder and Siege tanks.
4. At the early and mid stage of the game, a mixed army of Zergling, Baneling, Roach and Ravager can be unstoppable.
5. Remember to build the Infestation Pit to unlock the build of Lair.
6. Remember to build Hydralisk Den to unlock powerful Hydralisk to cause more damage.
7. Remember to build Ultralisk Cavern to unlock the powerful Ultralisk.
8. Remember to build Greater Spire to unlock the powerful Brood Lord.
}}
---
---Self-Verification (Avoid problematic commands)
These are the experiences you have gained through self-verification, please try to avoid these situations.
{{
'0': (Drone, A1)->(Expand Creep)->(A2)
Problem: Since "Drone" cannot expand creep (only Queens can), this instruction is unreasonable.
'1': (Drone, A1)->(Build)->(Queen Nest, A1)
Problem: This instruction is unreasonable. Drones cannot build Queen Nests; they are constructed by Drones transforming into the structure.
'2': (Drone, A1)->(Build)->(Overlord)
Problem: The problem is that "Drone" cannot hatch "Overlord", only "Larva" can hatch "Overlord".
'3': (Drone, A1)->(Build)->(Drone)
Problem: The problem is that "Drone" cannot hatch "Drone", only "Larva" can hatch "Drone".
}}
---
---Your commands in previous round
{{
}}
---
Based on the current battle situation and Units and Buildings from both sides, following the rules above, a brief step-by-step analysis can be done from our strategy, Units and Buildings, economic, technical perspectives, And "Your commands in last round".
Then, formulate 20 actionable, specific decisions (include the target location, like A1, A2, etc.) from the following action list.
These decisions should be numbered from 0, denoting the order in which they ought to be executed, with 0 signifying the most immediate and crucial action.
Note:
1. Game Key Decisions Memory is the key decisions in your memory, you can refer to these decisions for strategic deployment.
2. Self-Verification (Avoid problematic commands) is the experiences you have gained through self-verification, please try to avoid these situations.
3. Please reflect the 'Game Key Decisions Memory' and 'Self-Verification (Avoid problematic commands)' in the analysis of the results.
4. "Command Target" means the unit you want to command, such as "Drone", "Overlord", etc.
"Action" means the actions you want the unit to do, such as "Move", "Morph", etc.
"Target" means the objection, like "A1". Please see the example.
There's an example:
{{
‘0’: (Zergling, A1)->(Move)->(A4), //It means send Zerglings at A1 to A4
‘1’: (Drone, A1)->(Gather gas)->(Extractor1, A1) // It means send Drones at A1 to gathering gas at Extractor1 at A1
‘2’: (Zergling, A1)->(Morph)->(Baneling) //It means Zergling at A1 need to morph to Baneling
...
}}
For instance:
RESPONSE FORMAT:
1. Current Stage of the Match;
2. Our Zerg Units and Buildings;
3. Our current Zerg Operational Strategy;
4. Opponent's Units and Buildings;
5. Opponent's Tactical Plan and our Potential Risks;
6. Scouting Intel;
7. Analyze based on 'Game Key Decisions Memory' and 'Self-Verification (Avoid problematic commands)'.
8. Based on above analysis, each instruction should follow the below format:
{{
‘0’: (Command Target)->(Action)->(Target),
‘1’: (Command Target)->(Action)->(Target),
‘2’: (Command Target)->(Action)->(Target),
...
}}
'''
prompt = prompt.format(game_time=game_time, current_units=current_units, current_buildings=current_buildings,
current_tech=current_tech, current_enemy_units=current_enemy_units,
current_enemy_buildings=current_enemy_buildings)
print("prompt:\n", prompt)
output = self.llm_gpt35_turbo(prompt, True)
return output
def overmind_brain_1(self):
prompt = f'''
You are an intelligent brain of Zerg swarm in StarCraft II game.
You are very aggressive and know all the dependencies between Zerg units, Zerg buildings, and Zerg technological research.
Your task is to generate construction commands for Zerg buildings.
You and {self.opposite_race} players are on a square map with 16 mines evenly distributed on the map, as shown in the following matrix:
[[A8, B5, 0, B1],
[A7, B6, B3, B2],
[A4, 0, 0, B4],
[A2, A3, A6, B7],
[A1, 0, A5, B8]]
Currently, your base is at position A1 and the {self.opposite_race} base is at position B1. 0 represents no mine, and other letters represent the mine number.
---Current battle situation
game time: 00:00
The Units you currently have are: 12 Drone, 1 Overlord.
The Buildings you currently have are: 1 Hatchery
The Enemy Units you curently detect are: Nothing.
The Enemy Buildings you curently detect are: Nothing.
---
--- rule
You need to analyze the game progression by following a structured protocol based on the game situation. Make sure to include the following perspectives in your analysis:
1. Current Stage of the Match: Determine the current game stage based on the game time and types of our units, whether it’s early, middle, or late stage.
2. The Condition of Our Forces: Assess our current status in dimensions of:
2.1 Our Zerg Units and Buildings: Scrutinize the state of Zerg Units and Buildings.
2.2 Our Zerg Technology: Analyze the current status of the Zerg technological research based on the unlocked research.
3. Our current Zerg Operational Strategy: Devise a reasonable strategy based on our current situation, opponent’s situation, and scouting intel.
4. Opponent's situation: Assess opponent’s current status in dimensions of:
4.1 Opponent's Units and Buildings: Analyze state of opponent’s Units and Buildings.
4.1 Opponent's Tactical Plan and our Potential Risks: Based on detected opponent’s Units and Buildings, predict the opponent's attack timing to prepare defensive measures in advance.
5. Scouting Intel: Stress the importance of recent and consistent scouting reports to stay updated on the enemy's unit composition, positioning, and possible incoming attacks or expansions.
6. Eliminate Repeated instructions: Based on "Your commands in previous round", analysis which commands are not needed to execute again.
7. Avoid problematic commands: Analysis the problematic commands in "Avoid problematic commands", and avoid the problematic commands this time.
---
---Game Key Decisions Memory
The key decisions in your memory, you can refer to these decisions for strategic deployment.
{{
Based on previous competition experience, you found that:
0. Remember to build more hatchery to expend the economy, like (Drone, A1)->(Build)->(Hatchery, A1), (Drone, A1)->(Build)->(Hatchery, A2), (Drone, A1)->(Build)->(Hatchery, A3).
1. Remember to build Baneling Nest to enable morph Baneling to cause more damage.
2. You can morph many Zerglings to Banelings to cause more damage to the enemy's Marine, Marauder and Siege tanks.
3. You can morph many Roaches to Ravagers to cause more damage to the enemy's Marine, Marauder and Siege tanks.
4. At the early and mid stage of the game, a mixed army of Zergling, Baneling, Roach and Ravager can be unstoppable.
5. Remember to build the Infestation Pit to unlock the build of Lair.
6. Remember to build Hydralisk Den to unlock powerful Hydralisk to cause more damage.
7. Remember to build Ultralisk Cavern to unlock the powerful Ultralisk.
8. Remember to build Greater Spire to unlock the powerful Brood Lord.
}}
---
---Self-Verification (Avoid problematic commands)
These are the experiences you have gained through self-verification, please try to avoid these situations.
{{
'0': (Drone, A1)->(Expand Creep)->(A2)
Problem: Since "Drone" cannot expand creep (only Queens can), this instruction is unreasonable.
'1': (Drone, A1)->(Build)->(Queen Nest, A1)
Problem: This instruction is unreasonable. Drones cannot build Queen Nests; they are constructed by Drones transforming into the structure.
'2': (Drone, A1)->(Build)->(Overlord)
Problem: The problem is that "Drone" cannot hatch "Overlord", only "Larva" can hatch "Overlord".
'3': (Drone, A1)->(Build)->(Drone)
Problem: The problem is that "Drone" cannot hatch "Drone", only "Larva" can hatch "Drone".
}}
---
---Your commands in previous round
{{
}}
---
Based on the current battle situation and Units and Buildings from both sides, following the rules above, a brief step-by-step analysis can be done from our strategy, Units and Buildings, economic, technical perspectives, And "Your commands in last round".
Then, formulate 20 actionable, specific decisions (include the target location, like A1, A2, etc.) from the following action list.
These decisions should be numbered from 0, denoting the order in which they ought to be executed, with 0 signifying the most immediate and crucial action.
Note:
1. Game Key Decisions Memory is the key decisions in your memory, you can refer to these decisions for strategic deployment.
2. Self-Verification (Avoid problematic commands) is the experiences you have gained through self-verification, please try to avoid these situations.
3. Please reflect the 'Game Key Decisions Memory' and 'Self-Verification (Avoid problematic commands)' in the analysis of the results.
4. "Command Target" means the unit you want to command, such as "Drone", "Overlord", etc.
"Action" means the actions you want the unit to do, such as "Move", "Morph", etc.
"Target" means the objection, like "A1". Please see the example.
There's an example:
{{
‘0’: (Zergling, A1)->(Move)->(A4), //It means send Zerglings at A1 to A4
‘1’: (Drone, A1)->(Gather gas)->(Extractor1, A1) // It means send Drones at A1 to gathering gas at Extractor1 at A1
‘2’: (Zergling, A1)->(Morph)->(Baneling) //It means Zergling at A1 need to morph to Baneling
...
}}
For instance:
RESPONSE FORMAT:
1. Current Stage of the Match;
2. Our Zerg Units and Buildings;
3. Our current Zerg Operational Strategy;
4. Opponent's Units and Buildings;
5. Opponent's Tactical Plan and our Potential Risks;
6. Scouting Intel;
7. Analyze based on 'Game Key Decisions Memory' and 'Self-Verification (Avoid problematic commands)'.
8. Based on above analysis, each instruction should follow the below format:
{{
‘0’: (Command Target)->(Action)->(Target),
‘1’: (Command Target)->(Action)->(Target),
‘2’: (Command Target)->(Action)->(Target),
...
}}
'''
output1 = self.llm_gpt35_turbo(prompt, True)
return output1
def overmind_brain_initial(self):
prompt = f'''
You are an intelligent brain of Zerg swarm in StarCraft II game.
You are very aggressive and know all the dependencies between Zerg units, Zerg buildings, and Zerg technological research.
Your task is to analyze how many different Zerg units are needed at different stages of the game when facing powerful {self.opposite_race} players
---rule
The value given must be an exact value, for instance:
Zergling: 20
---
For instance:
RESPONSE FORMAT:
Early stage:
Zergling: [num]
Baneling: [num]
Roach: [num]
Ravager: [num]
Hydralisk: [num]
Infestor: [num]
Swarm host: [num]
Mutalisk: [num]
Corruptor: [num]
Viper: [num]
Ultralisk: [num]
Brood Lord: [num]
Mid stage:
Zergling: [num]
Baneling: [num]
Roach: [num]
Ravager: [num]
Hydralisk: [num]
Infestor: [num]
Swarm host: [num]
Mutalisk: [num]
Corruptor: [num]
Viper: [num]
Ultralisk: [num]
Brood Lord: [num]
Late stage:
Zergling: [num]
Baneling: [num]
Roach: [num]
Ravager: [num]
Hydralisk: [num]
Infestor: [num]
Swarm host: [num]
Mutalisk: [num]
Corruptor: [num]
Viper: [num]
Ultralisk: [num]
Brood Lord: [num]
'''
output1 = self.llm_gpt35_turbo(prompt, True)
return output1
def overmind_brain_initial2(self):
prompt = '''
You are an intelligent brain of Zerg swarm in StarCraft II game.
You are very aggressive and know all the dependencies between Zerg units, Zerg buildings, and Zerg technological research.
Now, you need to answer the following questions:
Question 1: When the enemy's army launched an attack on your base, and you sent out all the attacking units, but the whole army was wiped out, you still have some Drones mining, will you send out all your Drones at this time to make the final resistance? If yes, answer True, otherwise answer False.
overmind_brain_initial2
Question 2: When the enemy's army launched an attack on your base, you sent out all the attacking units, and all the enemy troops were defeated. At this time, you still have some attacking units. Will you send out your attacking units to counterattack the enemy's base? If yes, answer True, otherwise answer False.
RESPONSE FORMAT:
Question 1:
Question 2:
'''
output1 = self.llm_gpt35_turbo(prompt, True)
return output1
async def overmindbrain_iter(self):
game_time = self.time_formatted
tmp_current_units = []
current_units = self.get_units_distribution()
print("our units:")
for location, units_summary in current_units.items():
if self.start_location_label == "B1":
location = location.replace('B', 'A')
print(f"At point {location}, there are: {units_summary}")
tmp_current_units.append(f"At point {location}, there are: {units_summary}")
tmp_current_buildings = []
current_buildings = self.get_buildings_distribution()
print("our buildings:")
for location, units_summary in current_buildings.items():
if self.start_location_label == "B1":
location = location.replace('B', 'A')
print(f"At point {location}, there are: {units_summary}")
tmp_current_buildings.append(f"At point {location}, there are: {units_summary}")
current_tech = self.get_tech()
print("our tech:")
print("current_tech:", current_tech)
tmp_current_enemy_units = []
current_enemy_units = self.get_enemy_units()
if current_enemy_units == "":
current_enemy_units = self.previous_enemy_units
self.previous_enemy_units = current_enemy_units
for location, units_summary in current_enemy_units.items():
if self.start_location_label == "B1":
location = location.replace('A', 'B')
print(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_units.append(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_buildings = []
current_enemy_buildings = self.get_enemy_buildings()
if current_enemy_buildings == "":
current_enemy_buildings = self.previous_enemy_buildings
self.previous_enemy_buildings = current_enemy_buildings
print("enemy buildings:")
for location, units_summary in current_enemy_buildings.items():
if self.start_location_label == "B1":
location = location.replace('A', 'B')
print(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_buildings.append(f"At point {location}, there are: {units_summary}")
output = await self.overmind_brain_iter(game_time, tmp_current_units, tmp_current_buildings, current_tech,
tmp_current_enemy_units,
tmp_current_enemy_buildings, self.previous_commands)
print(output)
# self.game_stage = self.detect_stage(output)
matches = re.findall(r'\(.*?\)->\(.*?\)->\(.*?\)', output)
temp_commands = []
for match in matches:
temp_commands.append(match)
self.previous_commands = temp_commands
temp_commands = self.filter_commands(temp_commands,
['Queen', 'Gather minerals', 'Extractor', 'Mineral', 'Overlord', 'Move',
'Zergling', 'Creep'])
temp_commands_reverse = []
if self.start_location_label == "A1":
temp_commands_reverse = temp_commands
elif self.start_location_label == "B1":
for command in temp_commands:
def replace(match):
char, num = match.group(1), match.group(2)
return 'B' + num if char == 'A' else 'A' + num
command = re.sub(r'(A|B)(\d+)', replace, command)
temp_commands_reverse.append(command)
pattern = re.compile(r'\(([^)]+)\)')
for command in temp_commands_reverse:
parts = pattern.findall(command)
self.parsed_commands.append(parts)
print("self.parsed_commands:", self.parsed_commands)
async def overmind_building_iter(self):
game_time = self.time_formatted
current_units = self.get_units_all()
print("[Building] our units:", current_units)
current_buildings = self.get_buildings_all()
print("[Building] our buildings:", current_buildings)
tmp_current_enemy_units = []
current_enemy_units = self.get_enemy_units()
if current_enemy_units == "":
current_enemy_units = self.previous_enemy_units
self.previous_enemy_units = current_enemy_units
for location, units_summary in current_enemy_units.items():
if self.start_location_label == "B1":
location = location.replace('A', 'B')
print(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_units.append(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_buildings = []
current_enemy_buildings = self.get_enemy_buildings()
if current_enemy_buildings == "":
current_enemy_buildings = self.previous_enemy_buildings
self.previous_enemy_buildings = current_enemy_buildings
print("enemy buildings:")
for location, units_summary in current_enemy_buildings.items():
if self.start_location_label == "B1":
location = location.replace('A', 'B')
print(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_buildings.append(f"At point {location}, there are: {units_summary}")
print("[Building] previous_commands:", self.previous_commands)
output = await self.overmind_building_iter2(self.opposite_race, game_time, current_units, current_buildings,
tmp_current_enemy_units,
tmp_current_enemy_buildings, self.previous_commands)
print(output)
# self.game_stage = self.detect_stage(output)
matches = re.findall(r'\(.*?\)->\(.*?\)->\(.*?\)', output)
temp_commands = []
for match in matches:
temp_commands.append(match)
self.previous_commands = temp_commands
temp_commands = self.filter_commands(temp_commands,
['Queen', 'Gather minerals', 'Extractor', 'Mineral', 'Overlord', 'Move',
'Zergling', 'Creep'])
temp_commands_reverse = []
if self.start_location_label == "A1":
temp_commands_reverse = temp_commands
elif self.start_location_label == "B1":
for command in temp_commands:
def replace(match):
char, num = match.group(1), match.group(2)
return 'B' + num if char == 'A' else 'A' + num
command = re.sub(r'(A|B)(\d+)', replace, command)
temp_commands_reverse.append(command)
pattern = re.compile(r'\(([^)]+)\)')
for command in temp_commands_reverse:
parts = pattern.findall(command)
self.parsed_commands.append(parts)
print("self.parsed_commands:", self.parsed_commands)
async def overmind_building_iter2(self, opposite_race, game_time, current_units, current_buildings, current_enemy_units,
current_enemy_buildings, previous_commands):
prompt = '''
You are an intelligent brain of Zerg swarm in StarCraft II game.
You are very aggressive and know all the dependencies between Zerg units, Zerg buildings, and Zerg technological research.
Your task is to generate construction commands for Zerg buildings.
You and {opposite_race} players are on a square map with 16 mines evenly distributed on the map, as shown in the following matrix:
[[A8, B5, 0, B1],
[A7, B6, B3, B2],
[A4, 0, 0, B4],
[A2, A3, A6, B7],
[A1, 0, A5, B8]]
Currently, your base is at position A1 and the {opposite_race} base is at position B1. 0 represents no mine, and other letters represent the mine number.
---Current battle situation
game time: {game_time}
The Units you currently have are: {current_units}
The Buildings you currently have are: {current_buildings}
The Enemy Units you curently detect are: {current_enemy_units}
The Enemy Buildings you curently detect are: {current_enemy_buildings}
---
--- rule
You need to analyze the game progression by following a structured protocol based on the game situation. Make sure to include the following perspectives in your analysis:
1. Current Stage of the Match: Determine the current game stage based on the game time and types of our units, whether it’s early, middle, or late stage.
2. The Condition of Our Forces: Assess our current status in dimensions of:
2.1 Our Zerg Units and Buildings: Scrutinize the state of Zerg Units and Buildings.
2.2 Our Zerg Technology: Analyze the current status of the Zerg technological research based on the unlocked research.
3. Our current Zerg Operational Strategy: Devise a reasonable strategy based on our current situation, opponent’s situation, and scouting intel.
4. Opponent's situation: Assess opponent’s current status in dimensions of:
4.1 Opponent's Units and Buildings: Analyze state of opponent’s Units and Buildings.
4.1 Opponent's Tactical Plan and our Potential Risks: Based on detected opponent’s Units and Buildings, predict the opponent's attack timing to prepare defensive measures in advance.
5. Scouting Intel: Stress the importance of recent and consistent scouting reports to stay updated on the enemy's unit composition, positioning, and possible incoming attacks or expansions.
6. Eliminate Repeated instructions: Based on "Your commands in previous round", analysis which commands are not needed to execute again.
7. Avoid problematic commands: Analysis the problematic commands in "Avoid problematic commands", and avoid the problematic commands this time.
---
---Game Key Decisions Memory
The key decisions in your memory, you can refer to these decisions for strategic deployment.
{{
Based on previous competition experience, you found that:
0. Remember to build more hatchery to expend the economy, like (Drone, A1)->(Build)->(Hatchery, A1), (Drone, A1)->(Build)->(Hatchery, A2), (Drone, A1)->(Build)->(Hatchery, A3).
1. Remember to build Baneling Nest to enable morph Baneling to cause more damage.
2. You can morph many Zerglings to Banelings to cause more damage to the enemy's Marine, Marauder and Siege tanks.
3. You can morph many Roaches to Ravagers to cause more damage to the enemy's Marine, Marauder and Siege tanks.
4. At the early and mid stage of the game, a mixed army of Zergling, Baneling, Roach and Ravager can be unstoppable.
5. Remember to build the Infestation Pit to unlock the build of Lair.
6. Remember to build Hydralisk Den to unlock powerful Hydralisk to cause more damage.
7. Remember to build Ultralisk Cavern to unlock the powerful Ultralisk.
8. Remember to build Greater Spire to unlock the powerful Brood Lord.
}}
---Self-Verification (Avoid problematic commands)
These are the experiences you have gained through self-verification, please try to avoid these situations.
{{
'0': (Drone, A1)->(Expand Creep)->(A2)
Problem: Since "Drone" cannot expand creep (only Queens can), this instruction is unreasonable.
'1': (Drone, A1)->(Build)->(Queen Nest, A1)
Problem: This instruction is unreasonable. Drones cannot build Queen Nests; they are constructed by Drones transforming into the structure.
'2': (Drone, A1)->(Build)->(Overlord)
Problem: The problem is that "Drone" cannot hatch "Overlord", only "Larva" can hatch "Overlord".
'3': (Drone, A1)->(Build)->(Drone)
Problem: The problem is that "Drone" cannot hatch "Drone", only "Larva" can hatch "Drone".
}}
---
---Your commands in previous round
{{
}}
---
Based on the current battle situation and Units and Buildings from both sides, following the rules above, a brief step-by-step analysis can be done from our strategy, Units and Buildings, economic, technical perspectives, And "Your commands in last round".
Then, formulate 20 actionable, specific decisions (include the target location, like A1, A2, etc.) from the following action list.
These decisions should be numbered from 0, denoting the order in which they ought to be executed, with 0 signifying the most immediate and crucial action.
Note:
1. Game Key Decisions Memory is the key decisions in your memory, you can refer to these decisions for strategic deployment.
2. Self-Verification (Avoid problematic commands) is the experiences you have gained through self-verification, please try to avoid these situations.
3. Please reflect the 'Game Key Decisions Memory' and 'Self-Verification (Avoid problematic commands)' in the analysis of the results.
4. "Command Target" means the unit you want to command, such as "Drone", "Overlord", etc.
"Action" means the actions you want the unit to do, such as "Move", "Morph", etc.
"Target" means the objection, like "A1". Please see the example.
There's an example:
{{
‘0’: (Zergling, A1)->(Move)->(A4), //It means send Zerglings at A1 to A4
‘1’: (Drone, A1)->(Gather gas)->(Extractor1, A1) // It means send Drones at A1 to gathering gas at Extractor1 at A1
‘2’: (Zergling, A1)->(Morph)->(Baneling) //It means Zergling at A1 need to morph to Baneling
...
}}
For instance:
RESPONSE FORMAT:
1. Current Stage of the Match;
2. Our Zerg Units and Buildings;
3. Our current Zerg Operational Strategy;
4. Opponent's Units and Buildings;
5. Opponent's Tactical Plan and our Potential Risks;
6. Scouting Intel;
7. Analyze based on 'Game Key Decisions Memory' and 'Self-Verification (Avoid problematic commands)'.
8. Based on above analysis, each instruction should follow the below format:
{{
‘0’: (Command Target)->(Action)->(Target),
‘1’: (Command Target)->(Action)->(Target),
‘2’: (Command Target)->(Action)->(Target),
...
}}
'''
prompt = prompt.format(opposite_race=opposite_race, game_time=game_time, current_units=current_units, current_buildings=current_buildings,
current_enemy_units=current_enemy_units,
current_enemy_buildings=current_enemy_buildings)
print("Building prompt:\n", prompt)
output = self.llm_gpt35_turbo(prompt, True)
return output
async def overmind_attack_module(self, game_time, current_units, army_damage, current_enemy_units,
current_enemy_buildings, enemy_damage):
prompt = '''
You are an intelligent brain of Zerg swarm in StarCraft II game.
You are very aggressive and know all the dependencies between Zerg units, Zerg buildings, and Zerg technological research.
---Current battle situation
game time: {game_time}
You have: {current_units}.
The total damage of your army: {army_damage}.
Enemy units you currently detect are: {current_enemy_units}.
The Enemy buildings you currently detect are: {current_enemy_buildings}.
The total damage of enemy army: {enemy_damage}.
---
--- rule
You need to analyze the suitable time to attack enemy by following a structured protocol based on the game situation. Make sure to include the following perspectives in your analysis:
1. Our Zerg Units: Based on the current match stage, analyze whether the current status of Zerg units to suitable to launch an attack.
2. Enemy's Units: First analyze the enemy's units , and then analyze whether the our Zerg units can defeat the enemy's units.
3. Enemy's Buildings: Based on the enemy's buildings, analyze the enemy's strategy.
4 Current Stage of the Match: Determine the current game stage based on the game time and types of our units, whether it’s early, middle, or late stage.
5. Whether to attack: True if it is appropriate to launch an attack now, False otherwise.
---
---Game Key Decisions Memory
The key decisions in your memory, you can refer to these decisions for strategic deployment.
{{
Based on previous competition experience, you found that:
}}
---
Based on the Units and Buildings from both sides, following the rules above, a brief step-by-step analysis can be done from Zerg units and buildings, technical perspectives, and Enemy's units and buildings.
Note:
1. Game Key Decisions Memory is the key decisions in your memory, you can refer to these decisions for strategic deployment.
For instance:
RESPONSE FORMAT:
1. Our Zerg Units;
2. Enemy's Units;
3. Enemy's Buildings;
4. Current Stage of the Match;
5. Whether to attack;
6. True (if it's the suitable time to attack, otherwise is false)
'''
prompt = prompt.format(game_time=game_time, current_units=current_units, army_damage=army_damage,
current_enemy_units=current_enemy_units,
current_enemy_buildings=current_enemy_buildings,
enemy_damage=enemy_damage)
print("Attack prompt:\n", prompt)
output = self.llm_gpt35_turbo(prompt, True)
return output
async def overmind_attack_iter(self):
print("overmind_attack_iter")
game_time = self.time_formatted
current_units, army_damage = self.get_units_all_attack()
print("[Attack] our units:", current_units)
current_enemy_units_attack, enemy_damage = self.get_enemy_units_all()
if current_enemy_units_attack == "":
current_enemy_units_attack = self.previous_enemy_units_attack
self.previous_enemy_units_attack = current_enemy_units_attack
print("enemy units:", current_enemy_units_attack)
if enemy_damage == 0:
enemy_damage = self.previous_enemy_damage
self.previous_enemy_damage = enemy_damage
tmp_current_enemy_buildings = []
current_enemy_buildings = self.get_enemy_buildings()
if current_enemy_buildings == "":
current_enemy_buildings = self.previous_enemy_buildings
self.previous_enemy_buildings = current_enemy_buildings
print("enemy buildings:")
for location, units_summary in current_enemy_buildings.items():
if self.start_location_label == "B1":
location = location.replace('A', 'B')
print(f"At point {location}, there are: {units_summary}")
tmp_current_enemy_buildings.append(f"At point {location}, there are: {units_summary}")
output = await self.overmind_attack_module(game_time, current_units, army_damage, current_enemy_units_attack,
tmp_current_enemy_buildings, enemy_damage)
if "True" in output:
print("Need to attack")
avenager_units_types = [
UnitTypeId.ZERGLING, UnitTypeId.ROACH,
UnitTypeId.RAVAGER, UnitTypeId.BANELING, UnitTypeId.HYDRALISK, UnitTypeId.INFESTOR,
UnitTypeId.SWARMHOSTMP, UnitTypeId.MUTALISK, UnitTypeId.CORRUPTOR, UnitTypeId.VIPER,
UnitTypeId.ULTRALISK, UnitTypeId.BROODLORD
]
avenager_units = self.units.filter(
lambda unit: unit.type_id in avenager_units_types
)
for avenager in avenager_units:
avenager.attack(self.enemy_start_locations[0])
# await self.llm_attack_enemy()
else:
print("Do not Need to attack! Retreat to base")
if self.start_location_label == 'A1':
if 'A3' in self.existing_hatchery_locations:
retreat_base = 'A3'
else:
retreat_base = self.existing_hatchery_locations[-1]
elif self.start_location_label == 'B1':
if 'B3' in self.existing_hatchery_locations:
retreat_base = 'B3'
else:
retreat_base = self.existing_hatchery_locations[-1]
retreat_point = Point2(self.mineral_location_labels_reverse[retreat_base])
avenager_units_types = [
UnitTypeId.ZERGLING, UnitTypeId.ROACH,
UnitTypeId.RAVAGER, UnitTypeId.BANELING, UnitTypeId.HYDRALISK, UnitTypeId.INFESTOR,
UnitTypeId.SWARMHOSTMP, UnitTypeId.MUTALISK, UnitTypeId.CORRUPTOR, UnitTypeId.VIPER,
UnitTypeId.ULTRALISK, UnitTypeId.BROODLORD
]
defensive_units = self.units.filter(
lambda unit: unit.type_id in avenager_units_types
)
for defender in defensive_units:
defender.move(retreat_point)
self.is_attack_command_issued = False
def llm_gpt35_turbo(self, prompt: str, if_print_log: bool = False):
self.messages = [
{"role": "user", "content": prompt}
]
while True:
try:
output = self.chat.chat.completions.create(
model=self.LLM_api_mode,
messages=self.messages,
temperature=self.temperature
)
response = output.choices[0].message.content
break
except:
time.sleep(1)
return response
| 0 | 0.808771 | 1 | 0.808771 | game-dev | MEDIA | 0.941153 | game-dev | 0.879817 | 1 | 0.879817 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.