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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ibinti/bugvm | 2,505 | Core/soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityEdge.java | /* Soot - a J*va Optimization Framework
* Copyright (C) 2005 Antoine Mine
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* Implementation of the paper "A Combined Pointer and Purity Analysis for
* Java Programs" by Alexandru Salcianu and Martin Rinard, within the
* Soot Optimization Framework.
*
* by Antoine Mine, 2005/01/24
*/
package soot.jimple.toolkits.annotation.purity;
/**
* An edge in a purity graph.
* Each edge has a soruce PurityNode, a taget PurityNode, and a field label
* (we use a String here).
* To represent an array element, the convention is to use the [] field label.
* Edges are mmuable and hashable. They compare equal only if they link
* equal nodes and have equal labels.
*
*/
public class PurityEdge
{
private String field;
private PurityNode source, target;
private boolean inside;
PurityEdge(PurityNode source, String field, PurityNode target, boolean inside)
{
this.source = source;
this.field = field;
this.target = target;
this.inside = inside;
}
public String getField() { return field; }
public PurityNode getTarget() { return target; }
public PurityNode getSource() { return source; }
public boolean isInside() { return inside; }
public int hashCode()
{ return field.hashCode()+target.hashCode()+source.hashCode()+(inside?69:0); }
public boolean equals(Object o)
{
if (!(o instanceof PurityEdge)) return false;
PurityEdge e = (PurityEdge)o;
return source.equals(e.source) && field.equals(e.field)
&& target.equals(e.target) && inside==e.inside;
}
public String toString()
{
if (inside)
return source.toString()+" = "+field+" => "+target.toString();
else
return source.toString()+" - "+field+" -> "+target.toString();
}
}
| 0 | 0.589303 | 1 | 0.589303 | game-dev | MEDIA | 0.183202 | game-dev | 0.572923 | 1 | 0.572923 |
OSGeo/gdal | 37,002 | frmts/gtiff/gtiffrasterband_write.cpp | /******************************************************************************
*
* Project: GeoTIFF Driver
* Purpose: Write/set operations on GTiffRasterBand
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1998, 2002, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2007-2015, Even Rouault <even dot rouault at spatialys dot com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "gtiffrasterband.h"
#include "gtiffdataset.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "cpl_vsi_virtual.h"
#include "gdal_priv_templates.hpp"
#include "gdal_priv.h"
#include "gtiff.h"
#include "tifvsi.h"
/************************************************************************/
/* SetDefaultRAT() */
/************************************************************************/
CPLErr GTiffRasterBand::SetDefaultRAT(const GDALRasterAttributeTable *poRAT)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
return GDALPamRasterBand::SetDefaultRAT(poRAT);
}
/************************************************************************/
/* IWriteBlock() */
/************************************************************************/
CPLErr GTiffRasterBand::IWriteBlock(int nBlockXOff, int nBlockYOff,
void *pImage)
{
m_poGDS->Crystalize();
if (m_poGDS->m_bDebugDontWriteBlocks)
return CE_None;
if (m_poGDS->m_bWriteError)
{
// Report as an error if a previously loaded block couldn't be written
// correctly.
return CE_Failure;
}
const int nBlockId = ComputeBlockId(nBlockXOff, nBlockYOff);
/* -------------------------------------------------------------------- */
/* Handle case of "separate" images */
/* -------------------------------------------------------------------- */
if (m_poGDS->m_nPlanarConfig == PLANARCONFIG_SEPARATE ||
m_poGDS->nBands == 1)
{
const CPLErr eErr =
m_poGDS->WriteEncodedTileOrStrip(nBlockId, pImage, true);
return eErr;
}
/* -------------------------------------------------------------------- */
/* Handle case of pixel interleaved (PLANARCONFIG_CONTIG) images. */
/* -------------------------------------------------------------------- */
// Why 10 ? Somewhat arbitrary
constexpr int MAX_BANDS_FOR_DIRTY_CHECK = 10;
GDALRasterBlock *apoBlocks[MAX_BANDS_FOR_DIRTY_CHECK] = {};
const int nBands = m_poGDS->nBands;
bool bAllBlocksDirty = false;
/* -------------------------------------------------------------------- */
/* If all blocks are cached and dirty then we do not need to reload */
/* the tile/strip from disk */
/* -------------------------------------------------------------------- */
if (nBands <= MAX_BANDS_FOR_DIRTY_CHECK)
{
bAllBlocksDirty = true;
for (int iBand = 0; iBand < nBands; ++iBand)
{
if (iBand + 1 != nBand)
{
apoBlocks[iBand] =
cpl::down_cast<GTiffRasterBand *>(
m_poGDS->GetRasterBand(iBand + 1))
->TryGetLockedBlockRef(nBlockXOff, nBlockYOff);
if (apoBlocks[iBand] == nullptr)
{
bAllBlocksDirty = false;
}
else if (!apoBlocks[iBand]->GetDirty())
{
apoBlocks[iBand]->DropLock();
apoBlocks[iBand] = nullptr;
bAllBlocksDirty = false;
}
}
else
apoBlocks[iBand] = nullptr;
}
#if DEBUG_VERBOSE
if (bAllBlocksDirty)
CPLDebug("GTIFF", "Saved reloading block %d", nBlockId);
else
CPLDebug("GTIFF", "Must reload block %d", nBlockId);
#endif
}
{
const CPLErr eErr = m_poGDS->LoadBlockBuf(nBlockId, !bAllBlocksDirty);
if (eErr != CE_None)
{
if (nBands <= MAX_BANDS_FOR_DIRTY_CHECK)
{
for (int iBand = 0; iBand < nBands; ++iBand)
{
if (apoBlocks[iBand] != nullptr)
apoBlocks[iBand]->DropLock();
}
}
return eErr;
}
}
/* -------------------------------------------------------------------- */
/* On write of pixel interleaved data, we might as well flush */
/* out any other bands that are dirty in our cache. This is */
/* especially helpful when writing compressed blocks. */
/* -------------------------------------------------------------------- */
const int nWordBytes = m_poGDS->m_nBitsPerSample / 8;
for (int iBand = 0; iBand < nBands; ++iBand)
{
const GByte *pabyThisImage = nullptr;
GDALRasterBlock *poBlock = nullptr;
if (iBand + 1 == nBand)
{
pabyThisImage = static_cast<GByte *>(pImage);
}
else
{
if (nBands <= MAX_BANDS_FOR_DIRTY_CHECK)
poBlock = apoBlocks[iBand];
else
poBlock = cpl::down_cast<GTiffRasterBand *>(
m_poGDS->GetRasterBand(iBand + 1))
->TryGetLockedBlockRef(nBlockXOff, nBlockYOff);
if (poBlock == nullptr)
continue;
if (!poBlock->GetDirty())
{
poBlock->DropLock();
continue;
}
pabyThisImage = static_cast<GByte *>(poBlock->GetDataRef());
}
GByte *pabyOut = m_poGDS->m_pabyBlockBuf + iBand * nWordBytes;
GDALCopyWords64(pabyThisImage, eDataType, nWordBytes, pabyOut,
eDataType, nWordBytes * nBands,
static_cast<GPtrDiff_t>(nBlockXSize) * nBlockYSize);
if (poBlock != nullptr)
{
poBlock->MarkClean();
poBlock->DropLock();
}
}
if (bAllBlocksDirty)
{
// We can synchronously write the block now.
const CPLErr eErr = m_poGDS->WriteEncodedTileOrStrip(
nBlockId, m_poGDS->m_pabyBlockBuf, true);
m_poGDS->m_bLoadedBlockDirty = false;
return eErr;
}
m_poGDS->m_bLoadedBlockDirty = true;
return CE_None;
}
/************************************************************************/
/* SetDescription() */
/************************************************************************/
void GTiffRasterBand::SetDescription(const char *pszDescription)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (pszDescription == nullptr)
pszDescription = "";
if (m_osDescription != pszDescription)
m_poGDS->m_bMetadataChanged = true;
m_osDescription = pszDescription;
}
/************************************************************************/
/* SetOffset() */
/************************************************************************/
CPLErr GTiffRasterBand::SetOffset(double dfNewValue)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (!m_bHaveOffsetScale || dfNewValue != m_dfOffset)
m_poGDS->m_bMetadataChanged = true;
m_bHaveOffsetScale = true;
m_dfOffset = dfNewValue;
return CE_None;
}
/************************************************************************/
/* SetScale() */
/************************************************************************/
CPLErr GTiffRasterBand::SetScale(double dfNewValue)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (!m_bHaveOffsetScale || dfNewValue != m_dfScale)
m_poGDS->m_bMetadataChanged = true;
m_bHaveOffsetScale = true;
m_dfScale = dfNewValue;
return CE_None;
}
/************************************************************************/
/* SetUnitType() */
/************************************************************************/
CPLErr GTiffRasterBand::SetUnitType(const char *pszNewValue)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
CPLString osNewValue(pszNewValue ? pszNewValue : "");
if (osNewValue.compare(m_osUnitType) != 0)
m_poGDS->m_bMetadataChanged = true;
m_osUnitType = std::move(osNewValue);
return CE_None;
}
/************************************************************************/
/* SetMetadata() */
/************************************************************************/
CPLErr GTiffRasterBand::SetMetadata(char **papszMD, const char *pszDomain)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (m_poGDS->m_bStreamingOut && m_poGDS->m_bCrystalized)
{
ReportError(CE_Failure, CPLE_NotSupported,
"Cannot modify metadata at that point in a streamed "
"output file");
return CE_Failure;
}
CPLErr eErr = CE_None;
if (eAccess == GA_Update)
{
if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
{
if (papszMD != nullptr || GetMetadata(pszDomain) != nullptr)
{
m_poGDS->m_bMetadataChanged = true;
// Cancel any existing metadata from PAM file.
if (GDALPamRasterBand::GetMetadata(pszDomain) != nullptr)
GDALPamRasterBand::SetMetadata(nullptr, pszDomain);
}
}
}
else
{
CPLDebug(
"GTIFF",
"GTiffRasterBand::SetMetadata() goes to PAM instead of TIFF tags");
eErr = GDALPamRasterBand::SetMetadata(papszMD, pszDomain);
}
if (eErr == CE_None)
{
eErr = m_oGTiffMDMD.SetMetadata(papszMD, pszDomain);
}
return eErr;
}
/************************************************************************/
/* SetMetadataItem() */
/************************************************************************/
CPLErr GTiffRasterBand::SetMetadataItem(const char *pszName,
const char *pszValue,
const char *pszDomain)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (m_poGDS->m_bStreamingOut && m_poGDS->m_bCrystalized)
{
ReportError(CE_Failure, CPLE_NotSupported,
"Cannot modify metadata at that point in a streamed "
"output file");
return CE_Failure;
}
CPLErr eErr = CE_None;
if (eAccess == GA_Update)
{
if (pszDomain == nullptr || !EQUAL(pszDomain, "_temporary_"))
{
m_poGDS->m_bMetadataChanged = true;
// Cancel any existing metadata from PAM file.
if (GDALPamRasterBand::GetMetadataItem(pszName, pszDomain) !=
nullptr)
GDALPamRasterBand::SetMetadataItem(pszName, nullptr, pszDomain);
}
}
else
{
CPLDebug("GTIFF", "GTiffRasterBand::SetMetadataItem() goes to PAM "
"instead of TIFF tags");
eErr = GDALPamRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
}
if (eErr == CE_None)
{
eErr = m_oGTiffMDMD.SetMetadataItem(pszName, pszValue, pszDomain);
}
return eErr;
}
/************************************************************************/
/* SetColorInterpretation() */
/************************************************************************/
CPLErr GTiffRasterBand::SetColorInterpretation(GDALColorInterp eInterp)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (eInterp == m_eBandInterp)
return CE_None;
m_eBandInterp = eInterp;
if (eAccess != GA_Update)
{
CPLDebug("GTIFF",
"ColorInterpretation %s for band %d goes to PAM "
"instead of TIFF tag",
GDALGetColorInterpretationName(eInterp), nBand);
return GDALPamRasterBand::SetColorInterpretation(eInterp);
}
m_poGDS->m_bNeedsRewrite = true;
m_poGDS->m_bMetadataChanged = true;
// Try to autoset TIFFTAG_PHOTOMETRIC = PHOTOMETRIC_RGB if possible.
if (m_poGDS->nBands >= 3 && m_poGDS->m_nCompression != COMPRESSION_JPEG &&
m_poGDS->m_nPhotometric != PHOTOMETRIC_RGB &&
CSLFetchNameValue(m_poGDS->m_papszCreationOptions, "PHOTOMETRIC") ==
nullptr &&
((nBand == 1 && eInterp == GCI_RedBand) ||
(nBand == 2 && eInterp == GCI_GreenBand) ||
(nBand == 3 && eInterp == GCI_BlueBand)))
{
if (m_poGDS->GetRasterBand(1)->GetColorInterpretation() ==
GCI_RedBand &&
m_poGDS->GetRasterBand(2)->GetColorInterpretation() ==
GCI_GreenBand &&
m_poGDS->GetRasterBand(3)->GetColorInterpretation() == GCI_BlueBand)
{
m_poGDS->m_nPhotometric = PHOTOMETRIC_RGB;
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_PHOTOMETRIC,
m_poGDS->m_nPhotometric);
// We need to update the number of extra samples.
uint16_t *v = nullptr;
uint16_t count = 0;
const uint16_t nNewExtraSamplesCount =
static_cast<uint16_t>(m_poGDS->nBands - 3);
if (m_poGDS->nBands >= 4 &&
TIFFGetField(m_poGDS->m_hTIFF, TIFFTAG_EXTRASAMPLES, &count,
&v) &&
count > nNewExtraSamplesCount)
{
uint16_t *const pasNewExtraSamples = static_cast<uint16_t *>(
CPLMalloc(nNewExtraSamplesCount * sizeof(uint16_t)));
memcpy(pasNewExtraSamples, v + count - nNewExtraSamplesCount,
nNewExtraSamplesCount * sizeof(uint16_t));
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_EXTRASAMPLES,
nNewExtraSamplesCount, pasNewExtraSamples);
CPLFree(pasNewExtraSamples);
}
}
return CE_None;
}
// On the contrary, cancel the above if needed
if (m_poGDS->m_nCompression != COMPRESSION_JPEG &&
m_poGDS->m_nPhotometric == PHOTOMETRIC_RGB &&
CSLFetchNameValue(m_poGDS->m_papszCreationOptions, "PHOTOMETRIC") ==
nullptr &&
((nBand == 1 && eInterp != GCI_RedBand) ||
(nBand == 2 && eInterp != GCI_GreenBand) ||
(nBand == 3 && eInterp != GCI_BlueBand)))
{
m_poGDS->m_nPhotometric = PHOTOMETRIC_MINISBLACK;
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_PHOTOMETRIC,
m_poGDS->m_nPhotometric);
// We need to update the number of extra samples.
uint16_t *v = nullptr;
uint16_t count = 0;
const uint16_t nNewExtraSamplesCount =
static_cast<uint16_t>(m_poGDS->nBands - 1);
if (m_poGDS->nBands >= 2)
{
TIFFGetField(m_poGDS->m_hTIFF, TIFFTAG_EXTRASAMPLES, &count, &v);
if (nNewExtraSamplesCount > count)
{
uint16_t *const pasNewExtraSamples = static_cast<uint16_t *>(
CPLMalloc(nNewExtraSamplesCount * sizeof(uint16_t)));
for (int i = 0;
i < static_cast<int>(nNewExtraSamplesCount - count); ++i)
pasNewExtraSamples[i] = EXTRASAMPLE_UNSPECIFIED;
if (count > 0)
{
memcpy(pasNewExtraSamples + nNewExtraSamplesCount - count,
v, count * sizeof(uint16_t));
}
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_EXTRASAMPLES,
nNewExtraSamplesCount, pasNewExtraSamples);
CPLFree(pasNewExtraSamples);
}
}
}
// Mark non-RGB in extrasamples.
if (eInterp != GCI_RedBand && eInterp != GCI_GreenBand &&
eInterp != GCI_BlueBand)
{
uint16_t *v = nullptr;
uint16_t count = 0;
if (TIFFGetField(m_poGDS->m_hTIFF, TIFFTAG_EXTRASAMPLES, &count, &v) &&
count > 0)
{
const int nBaseSamples = m_poGDS->m_nSamplesPerPixel - count;
if (eInterp == GCI_AlphaBand)
{
for (int i = 1; i <= m_poGDS->nBands; ++i)
{
if (i != nBand &&
m_poGDS->GetRasterBand(i)->GetColorInterpretation() ==
GCI_AlphaBand)
{
if (i == nBaseSamples + 1 &&
CSLFetchNameValue(m_poGDS->m_papszCreationOptions,
"ALPHA") != nullptr)
{
ReportError(
CE_Warning, CPLE_AppDefined,
"Band %d was already identified as alpha band, "
"and band %d is now marked as alpha too. "
"Presumably ALPHA creation option is not "
"needed",
i, nBand);
}
else
{
ReportError(
CE_Warning, CPLE_AppDefined,
"Band %d was already identified as alpha band, "
"and band %d is now marked as alpha too",
i, nBand);
}
}
}
}
if (nBand > nBaseSamples && nBand - nBaseSamples - 1 < count)
{
// We need to allocate a new array as (current) libtiff
// versions will not like that we reuse the array we got from
// TIFFGetField().
uint16_t *pasNewExtraSamples = static_cast<uint16_t *>(
CPLMalloc(count * sizeof(uint16_t)));
memcpy(pasNewExtraSamples, v, count * sizeof(uint16_t));
if (eInterp == GCI_AlphaBand)
{
pasNewExtraSamples[nBand - nBaseSamples - 1] =
GTiffGetAlphaValue(
CPLGetConfigOption("GTIFF_ALPHA", nullptr),
DEFAULT_ALPHA_TYPE);
}
else
{
pasNewExtraSamples[nBand - nBaseSamples - 1] =
EXTRASAMPLE_UNSPECIFIED;
}
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_EXTRASAMPLES, count,
pasNewExtraSamples);
CPLFree(pasNewExtraSamples);
return CE_None;
}
}
}
if (m_poGDS->m_nPhotometric != PHOTOMETRIC_MINISBLACK &&
CSLFetchNameValue(m_poGDS->m_papszCreationOptions, "PHOTOMETRIC") ==
nullptr)
{
m_poGDS->m_nPhotometric = PHOTOMETRIC_MINISBLACK;
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_PHOTOMETRIC,
m_poGDS->m_nPhotometric);
}
return CE_None;
}
/************************************************************************/
/* SetColorTable() */
/************************************************************************/
CPLErr GTiffRasterBand::SetColorTable(GDALColorTable *poCT)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
/* -------------------------------------------------------------------- */
/* Check if this is even a candidate for applying a PCT. */
/* -------------------------------------------------------------------- */
if (eAccess == GA_Update)
{
if (nBand != 1)
{
ReportError(CE_Failure, CPLE_NotSupported,
"SetColorTable() can only be called on band 1.");
return CE_Failure;
}
if (m_poGDS->m_nSamplesPerPixel != 1 &&
m_poGDS->m_nSamplesPerPixel != 2)
{
ReportError(CE_Failure, CPLE_NotSupported,
"SetColorTable() not supported for multi-sample TIFF "
"files.");
return CE_Failure;
}
if (eDataType != GDT_Byte && eDataType != GDT_UInt16)
{
ReportError(
CE_Failure, CPLE_NotSupported,
"SetColorTable() only supported for Byte or UInt16 bands "
"in TIFF format.");
return CE_Failure;
}
// Clear any existing PAM color table
if (GDALPamRasterBand::GetColorTable() != nullptr)
{
GDALPamRasterBand::SetColorTable(nullptr);
GDALPamRasterBand::SetColorInterpretation(GCI_Undefined);
}
}
/* -------------------------------------------------------------------- */
/* Is this really a request to clear the color table? */
/* -------------------------------------------------------------------- */
if (poCT == nullptr || poCT->GetColorEntryCount() == 0)
{
if (eAccess == GA_Update)
{
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_PHOTOMETRIC,
PHOTOMETRIC_MINISBLACK);
TIFFUnsetField(m_poGDS->m_hTIFF, TIFFTAG_COLORMAP);
}
m_poGDS->m_poColorTable.reset();
return CE_None;
}
/* -------------------------------------------------------------------- */
/* Write out the colortable, and update the configuration. */
/* -------------------------------------------------------------------- */
CPLErr eErr = CE_None;
if (eAccess == GA_Update)
{
int nColors = 65536;
if (eDataType == GDT_Byte)
nColors = 256;
unsigned short *panTRed = static_cast<unsigned short *>(
CPLMalloc(sizeof(unsigned short) * nColors));
unsigned short *panTGreen = static_cast<unsigned short *>(
CPLMalloc(sizeof(unsigned short) * nColors));
unsigned short *panTBlue = static_cast<unsigned short *>(
CPLMalloc(sizeof(unsigned short) * nColors));
if (m_poGDS->m_nColorTableMultiplier == 0)
m_poGDS->m_nColorTableMultiplier =
GTiffDataset::DEFAULT_COLOR_TABLE_MULTIPLIER_257;
for (int iColor = 0; iColor < nColors; ++iColor)
{
if (iColor < poCT->GetColorEntryCount())
{
GDALColorEntry sRGB;
poCT->GetColorEntryAsRGB(iColor, &sRGB);
panTRed[iColor] = GTiffDataset::ClampCTEntry(
iColor, 1, sRGB.c1, m_poGDS->m_nColorTableMultiplier);
panTGreen[iColor] = GTiffDataset::ClampCTEntry(
iColor, 2, sRGB.c2, m_poGDS->m_nColorTableMultiplier);
panTBlue[iColor] = GTiffDataset::ClampCTEntry(
iColor, 3, sRGB.c3, m_poGDS->m_nColorTableMultiplier);
}
else
{
panTRed[iColor] = 0;
panTGreen[iColor] = 0;
panTBlue[iColor] = 0;
}
}
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_PHOTOMETRIC,
PHOTOMETRIC_PALETTE);
TIFFSetField(m_poGDS->m_hTIFF, TIFFTAG_COLORMAP, panTRed, panTGreen,
panTBlue);
CPLFree(panTRed);
CPLFree(panTGreen);
CPLFree(panTBlue);
// libtiff 3.X needs setting this in all cases (creation or update)
// whereas libtiff 4.X would just need it if there
// was no color table before.
m_poGDS->m_bNeedsRewrite = true;
}
else
{
eErr = GDALPamRasterBand::SetColorTable(poCT);
}
m_poGDS->m_poColorTable.reset(poCT->Clone());
m_eBandInterp = GCI_PaletteIndex;
return eErr;
}
/************************************************************************/
/* SetNoDataValue() */
/************************************************************************/
CPLErr GTiffRasterBand::SetNoDataValue(double dfNoData)
{
const auto SetNoDataMembers = [this, dfNoData]()
{
m_bNoDataSet = true;
m_dfNoDataValue = dfNoData;
m_poGDS->m_bNoDataSet = true;
m_poGDS->m_dfNoDataValue = dfNoData;
if (eDataType == GDT_Int64 && GDALIsValueExactAs<int64_t>(dfNoData))
{
m_bNoDataSetAsInt64 = true;
m_nNoDataValueInt64 = static_cast<int64_t>(dfNoData);
m_poGDS->m_bNoDataSetAsInt64 = true;
m_poGDS->m_nNoDataValueInt64 = static_cast<int64_t>(dfNoData);
}
else if (eDataType == GDT_UInt64 &&
GDALIsValueExactAs<uint64_t>(dfNoData))
{
m_bNoDataSetAsUInt64 = true;
m_nNoDataValueUInt64 = static_cast<uint64_t>(dfNoData);
m_poGDS->m_bNoDataSetAsUInt64 = true;
m_poGDS->m_nNoDataValueUInt64 = static_cast<uint64_t>(dfNoData);
}
};
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (m_poGDS->m_bNoDataSet &&
(m_poGDS->m_dfNoDataValue == dfNoData ||
(std::isnan(m_poGDS->m_dfNoDataValue) && std::isnan(dfNoData))))
{
ResetNoDataValues(false);
SetNoDataMembers();
return CE_None;
}
if (m_poGDS->nBands > 1 && m_poGDS->m_eProfile == GTiffProfile::GDALGEOTIFF)
{
int bOtherBandHasNoData = FALSE;
const int nOtherBand = nBand > 1 ? 1 : 2;
double dfOtherNoData = m_poGDS->GetRasterBand(nOtherBand)
->GetNoDataValue(&bOtherBandHasNoData);
if (bOtherBandHasNoData && dfOtherNoData != dfNoData)
{
ReportError(
CE_Warning, CPLE_AppDefined,
"Setting nodata to %.17g on band %d, but band %d has nodata "
"at %.17g. The TIFFTAG_GDAL_NODATA only support one value "
"per dataset. This value of %.17g will be used for all bands "
"on re-opening",
dfNoData, nBand, nOtherBand, dfOtherNoData, dfNoData);
}
}
if (m_poGDS->m_bStreamingOut && m_poGDS->m_bCrystalized)
{
ReportError(
CE_Failure, CPLE_NotSupported,
"Cannot modify nodata at that point in a streamed output file");
return CE_Failure;
}
CPLErr eErr = CE_None;
if (eAccess == GA_Update)
{
m_poGDS->m_bNoDataChanged = true;
int bSuccess = FALSE;
CPL_IGNORE_RET_VAL(GDALPamRasterBand::GetNoDataValue(&bSuccess));
if (bSuccess)
{
// Cancel any existing nodata from PAM file.
eErr = GDALPamRasterBand::DeleteNoDataValue();
}
}
else
{
CPLDebug("GTIFF", "SetNoDataValue() goes to PAM instead of TIFF tags");
eErr = GDALPamRasterBand::SetNoDataValue(dfNoData);
}
if (eErr == CE_None)
{
ResetNoDataValues(true);
SetNoDataMembers();
}
return eErr;
}
/************************************************************************/
/* SetNoDataValueAsInt64() */
/************************************************************************/
CPLErr GTiffRasterBand::SetNoDataValueAsInt64(int64_t nNoData)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (m_poGDS->m_bNoDataSetAsInt64 && m_poGDS->m_nNoDataValueInt64 == nNoData)
{
ResetNoDataValues(false);
m_bNoDataSetAsInt64 = true;
m_nNoDataValueInt64 = nNoData;
return CE_None;
}
if (m_poGDS->nBands > 1 && m_poGDS->m_eProfile == GTiffProfile::GDALGEOTIFF)
{
int bOtherBandHasNoData = FALSE;
const int nOtherBand = nBand > 1 ? 1 : 2;
const auto nOtherNoData =
m_poGDS->GetRasterBand(nOtherBand)
->GetNoDataValueAsInt64(&bOtherBandHasNoData);
if (bOtherBandHasNoData && nOtherNoData != nNoData)
{
ReportError(CE_Warning, CPLE_AppDefined,
"Setting nodata to " CPL_FRMT_GIB
" on band %d, but band %d has nodata "
"at " CPL_FRMT_GIB
". The TIFFTAG_GDAL_NODATA only support one value "
"per dataset. This value of " CPL_FRMT_GIB
" will be used for all bands "
"on re-opening",
static_cast<GIntBig>(nNoData), nBand, nOtherBand,
static_cast<GIntBig>(nOtherNoData),
static_cast<GIntBig>(nNoData));
}
}
if (m_poGDS->m_bStreamingOut && m_poGDS->m_bCrystalized)
{
ReportError(
CE_Failure, CPLE_NotSupported,
"Cannot modify nodata at that point in a streamed output file");
return CE_Failure;
}
CPLErr eErr = CE_None;
if (eAccess == GA_Update)
{
m_poGDS->m_bNoDataChanged = true;
int bSuccess = FALSE;
CPL_IGNORE_RET_VAL(GDALPamRasterBand::GetNoDataValueAsInt64(&bSuccess));
if (bSuccess)
{
// Cancel any existing nodata from PAM file.
eErr = GDALPamRasterBand::DeleteNoDataValue();
}
}
else
{
CPLDebug("GTIFF", "SetNoDataValue() goes to PAM instead of TIFF tags");
eErr = GDALPamRasterBand::SetNoDataValueAsInt64(nNoData);
}
if (eErr == CE_None)
{
ResetNoDataValues(true);
m_poGDS->m_bNoDataSetAsInt64 = true;
m_poGDS->m_nNoDataValueInt64 = nNoData;
}
return eErr;
}
/************************************************************************/
/* SetNoDataValueAsUInt64() */
/************************************************************************/
CPLErr GTiffRasterBand::SetNoDataValueAsUInt64(uint64_t nNoData)
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (m_poGDS->m_bNoDataSetAsUInt64 &&
m_poGDS->m_nNoDataValueUInt64 == nNoData)
{
ResetNoDataValues(false);
m_bNoDataSetAsUInt64 = true;
m_nNoDataValueUInt64 = nNoData;
return CE_None;
}
if (m_poGDS->nBands > 1 && m_poGDS->m_eProfile == GTiffProfile::GDALGEOTIFF)
{
int bOtherBandHasNoData = FALSE;
const int nOtherBand = nBand > 1 ? 1 : 2;
const auto nOtherNoData =
m_poGDS->GetRasterBand(nOtherBand)
->GetNoDataValueAsUInt64(&bOtherBandHasNoData);
if (bOtherBandHasNoData && nOtherNoData != nNoData)
{
ReportError(CE_Warning, CPLE_AppDefined,
"Setting nodata to " CPL_FRMT_GUIB
" on band %d, but band %d has nodata "
"at " CPL_FRMT_GUIB
". The TIFFTAG_GDAL_NODATA only support one value "
"per dataset. This value of " CPL_FRMT_GUIB
" will be used for all bands "
"on re-opening",
static_cast<GUIntBig>(nNoData), nBand, nOtherBand,
static_cast<GUIntBig>(nOtherNoData),
static_cast<GUIntBig>(nNoData));
}
}
if (m_poGDS->m_bStreamingOut && m_poGDS->m_bCrystalized)
{
ReportError(
CE_Failure, CPLE_NotSupported,
"Cannot modify nodata at that point in a streamed output file");
return CE_Failure;
}
CPLErr eErr = CE_None;
if (eAccess == GA_Update)
{
m_poGDS->m_bNoDataChanged = true;
int bSuccess = FALSE;
CPL_IGNORE_RET_VAL(
GDALPamRasterBand::GetNoDataValueAsUInt64(&bSuccess));
if (bSuccess)
{
// Cancel any existing nodata from PAM file.
eErr = GDALPamRasterBand::DeleteNoDataValue();
}
}
else
{
CPLDebug("GTIFF", "SetNoDataValue() goes to PAM instead of TIFF tags");
eErr = GDALPamRasterBand::SetNoDataValueAsUInt64(nNoData);
}
if (eErr == CE_None)
{
ResetNoDataValues(true);
m_poGDS->m_bNoDataSetAsUInt64 = true;
m_poGDS->m_nNoDataValueUInt64 = nNoData;
m_bNoDataSetAsUInt64 = true;
m_nNoDataValueUInt64 = nNoData;
}
return eErr;
}
/************************************************************************/
/* ResetNoDataValues() */
/************************************************************************/
void GTiffRasterBand::ResetNoDataValues(bool bResetDatasetToo)
{
if (bResetDatasetToo)
{
m_poGDS->m_bNoDataSet = false;
m_poGDS->m_dfNoDataValue = DEFAULT_NODATA_VALUE;
}
m_bNoDataSet = false;
m_dfNoDataValue = DEFAULT_NODATA_VALUE;
if (bResetDatasetToo)
{
m_poGDS->m_bNoDataSetAsInt64 = false;
m_poGDS->m_nNoDataValueInt64 = GDAL_PAM_DEFAULT_NODATA_VALUE_INT64;
}
m_bNoDataSetAsInt64 = false;
m_nNoDataValueInt64 = GDAL_PAM_DEFAULT_NODATA_VALUE_INT64;
if (bResetDatasetToo)
{
m_poGDS->m_bNoDataSetAsUInt64 = false;
m_poGDS->m_nNoDataValueUInt64 = GDAL_PAM_DEFAULT_NODATA_VALUE_UINT64;
}
m_bNoDataSetAsUInt64 = false;
m_nNoDataValueUInt64 = GDAL_PAM_DEFAULT_NODATA_VALUE_UINT64;
}
/************************************************************************/
/* DeleteNoDataValue() */
/************************************************************************/
CPLErr GTiffRasterBand::DeleteNoDataValue()
{
m_poGDS->LoadGeoreferencingAndPamIfNeeded();
if (m_poGDS->m_bStreamingOut && m_poGDS->m_bCrystalized)
{
ReportError(
CE_Failure, CPLE_NotSupported,
"Cannot modify nodata at that point in a streamed output file");
return CE_Failure;
}
if (eAccess == GA_Update)
{
if (m_poGDS->m_bNoDataSet)
m_poGDS->m_bNoDataChanged = true;
}
else
{
CPLDebug("GTIFF",
"DeleteNoDataValue() goes to PAM instead of TIFF tags");
}
CPLErr eErr = GDALPamRasterBand::DeleteNoDataValue();
if (eErr == CE_None)
{
ResetNoDataValues(true);
}
return eErr;
}
/************************************************************************/
/* NullBlock() */
/* */
/* Set the block data to the null value if it is set, or zero */
/* if there is no null data value. */
/************************************************************************/
void GTiffRasterBand::NullBlock(void *pData)
{
const GPtrDiff_t nWords =
static_cast<GPtrDiff_t>(nBlockXSize) * nBlockYSize;
const int nChunkSize = std::max(1, GDALGetDataTypeSizeBytes(eDataType));
int l_bNoDataSet = FALSE;
if (eDataType == GDT_Int64)
{
const auto nVal = GetNoDataValueAsInt64(&l_bNoDataSet);
if (!l_bNoDataSet)
{
memset(pData, 0, nWords * nChunkSize);
}
else
{
GDALCopyWords64(&nVal, GDT_Int64, 0, pData, eDataType, nChunkSize,
nWords);
}
}
else if (eDataType == GDT_UInt64)
{
const auto nVal = GetNoDataValueAsUInt64(&l_bNoDataSet);
if (!l_bNoDataSet)
{
memset(pData, 0, nWords * nChunkSize);
}
else
{
GDALCopyWords64(&nVal, GDT_UInt64, 0, pData, eDataType, nChunkSize,
nWords);
}
}
else
{
double dfNoData = GetNoDataValue(&l_bNoDataSet);
if (!l_bNoDataSet)
{
#ifdef ESRI_BUILD
if (m_poGDS->m_nBitsPerSample >= 2)
memset(pData, 0, nWords * nChunkSize);
else
memset(pData, 1, nWords * nChunkSize);
#else
memset(pData, 0, nWords * nChunkSize);
#endif
}
else
{
// Will convert nodata value to the right type and copy efficiently.
GDALCopyWords64(&dfNoData, GDT_Float64, 0, pData, eDataType,
nChunkSize, nWords);
}
}
}
| 0 | 0.980875 | 1 | 0.980875 | game-dev | MEDIA | 0.437683 | game-dev | 0.989794 | 1 | 0.989794 |
Xeno69/Domination | 7,312 | co30_Domination.Altis/revive/fn_buttonclickrespawn.sqf | // by Xeno
//#define __DEBUG__
#include "..\x_macros.sqf"
if (!hasInterface) exitWith {};
__TRACE_1("","d_beam_target")
if (d_beam_target isEqualTo "") exitWith {
__TRACE("exit, beam target empty")
};
private _respawn_pos = [0, 0, 0];
private _respawn_target = nil;
__TRACE("black out")
"xr_revtxt" cutText [localize "STR_DOM_MISSIONSTRING_917", "BLACK OUT", 0.2];
player setVariable ["xr_hasusedmapclickspawn", true];
if (d_beam_target == "D_BASE_D") then {
#ifndef __TT__
_respawn_pos = markerPos "base_spawn_1";
#else
_respawn_pos = [markerPos "base_spawn_2", markerPos "base_spawn_1"] select (d_player_side == blufor);
#endif
if (!d_carrier) then {
_respawn_pos set [2, 0];
} else {
_respawn_pos set [2, (getPosASL D_FLAG_BASE) # 2];
};
d_player_in_base = true;
} else {
if (d_beam_target == "D_SQL_D") then {
__TRACE_1("DSQLD","d_beam_target")
if (leader (group player) != player && {[leader (group player)] call d_fnc_iseligibletospawnnewunit}) then {
_respawn_target = leader (group player);
__TRACE_1("1","_respawn_target")
} else {
// are any squadmates alive and eligible as a spawn target?
__TRACE("in squadmate search")
{
if (_x != player && {[_x] call d_fnc_iseligibletospawnnewunit}) exitWith {
_respawn_target = _x;
__TRACE_1("2","_respawn_target")
};
} forEach (units player);
};
// failed to find a respawn target
if (isNil "_respawn_target") exitWith {
__TRACE("_respawn_target is nil")
};
__TRACE_1("3","_respawn_target")
_respawn_pos = [(vehicle _respawn_target) modelToWorldVisual [0, -8, 0], getPosASL _respawn_target] select (isNull objectParent _respawn_target);
_respawn_pos set [2, _respawn_target distance (getPos _respawn_target)];
if (_respawn_pos distance2D [0, 0, 0] >= 60) then {
if (d_with_ranked || {d_database_found}) then {
[_respawn_target, 12] remoteExecCall ["d_fnc_addscore", 2];
};
#ifndef __TT__
d_player_in_base = _respawn_pos inArea d_base_array;
#else
d_player_in_base = _respawn_pos inArea (d_base_array # 0) || {player inArea (d_base_array # 1)};
#endif
};
} else {
private _uidx = d_add_resp_points_uni find d_beam_target;
if (_uidx != -1) then {
_respawn_pos = (d_additional_respawn_points # _uidx) # 1;
if (surfaceIsWater _respawn_pos) then {
_respawn_pos set [2, ((d_additional_respawn_points # _uidx) # 5) # 2];
};
d_player_in_base = false;
} else {
private _mrs = missionNamespace getVariable [d_beam_target, objNull];
if (alive _mrs) then {
if (isNil "d_alt_map_pos") then {
_respawn_pos = _mrs call d_fnc_posbehindvec;
(boundingBoxReal _mrs) params ["_p1", "_p2"];
private _maxHeight = abs ((_p2 # 2) - (_p1 # 2)) / 2;
_respawn_pos set [2, (_mrs distance (getPos _mrs)) - _maxHeight];
_respawn_pos set [1, (_respawn_pos # 1) - 1]; // 1m behind
} else {
_respawn_pos = d_alt_map_pos;
_respawn_pos set [2, 0];
};
d_player_in_base = false;
} else {
#ifndef __TT__
_respawn_pos = markerPos "base_spawn_1";
#else
_respawn_pos = [markerPos "base_spawn_2", markerPos "base_spawn_1"] select (d_player_side == blufor);
#endif
if (!d_carrier) then {
_respawn_pos set [2, 0];
} else {
_respawn_pos set [2, (getPosASL D_FLAG_BASE) # 2];
};
d_player_in_base = true;
};
};
};
};
if (!d_player_in_base && {!isNil {player getVariable "d_old_eng_can_repfuel"}}) then {
d_eng_can_repfuel = false;
};
player setVariable ["d_old_eng_can_repfuel", nil];
__TRACE_1("","_respawn_pos")
sleep 1;
__TRACE("stopspect = true")
xr_stopspect = true;
player setVariable ["xr_plno3dd", true, true];
player setVariable ["xr_pluncon", false, true];
player setCaptive false;
sleep 0.5;
private _mhqobj = objNull;
if (d_beam_target != "D_BASE_D" && {d_beam_target != "D_SQL_D" && {!(d_beam_target in d_add_resp_points_uni)}}) then {
private _rpnetts = _respawn_pos nearEntities ["All", 25];
private _fidx = _rpnetts findIf {_x getVariable ["d_vec_type", ""] == "MHQ"};
if (_fidx > -1) then {
_mhqobj = _rpnetts # _fidx;
};
};
__TRACE_1("","_mhqobj")
if (!isNull _mhqobj) then {
if !(_mhqobj isKindOf "Ship") then {
[player, 105] remoteExecCall ["xr_fnc_handlenet"];
private _newppos = _mhqobj call d_fnc_posbehindvec;
(boundingBoxReal _mhqobj) params ["_p1", "_p2"];
private _maxHeight = abs ((_p2 # 2) - (_p1 # 2)) / 2;
_newppos set [2, (_mhqobj distance (getPos _mhqobj)) - _maxHeight];
player setDir (getDirVisual _mhqobj);
player setVehiclePosition [_newppos, [], 0, "NONE"]; // CAN_COLLIDE ?
} else {
player switchMove "";
player moveInCargo _mhqobj;
};
{player reveal _x} forEach ((player nearEntities [["Man", "Air", "Car", "Motorcycle", "Tank", "Ship"], 100]) + (player nearSupplies 100));
if ((player nearEntities ["ReammoBox_F", 30]) isNotEqualTo []) then {
call d_fnc_retrieve_layoutgear;
};
} else {
private _domovevec = false;
if (d_beam_target != "D_SQL_D") then {
call d_fnc_retrieve_layoutgear;
} else {
private _emptycargo = [0, (vehicle _respawn_target) emptyPositions "cargo"] select (!isNull objectParent _respawn_target);
if (_emptycargo > 0) then {
_domovevec = true;
};
};
if (!_domovevec) then {
[player, 105] remoteExecCall ["xr_fnc_handlenet"];
player allowDamage false;
if (_respawn_pos distance2D [0, 0, 0] < 60) then {
#ifndef __TT__
_respawn_pos = markerPos "base_spawn_1";
#else
_respawn_pos = [markerPos "base_spawn_2", markerPos "base_spawn_1"] select (d_player_side == blufor);
#endif
if (!d_carrier) then {
_respawn_pos set [2, 0];
} else {
_respawn_pos set [2, (getPosASL D_FLAG_BASE) # 2];
};
d_player_in_base = true;
};
if (surfaceIsWater _respawn_pos) then {
__TRACE("is water")
player setPosASL _respawn_pos;
} else {
if (d_beam_target == "D_BASE_D") then {
player setVehiclePosition [_respawn_pos, [], 2, "NONE"];
if (d_vn) then {
if (markerPos "base_spawn_1" distance2D [15712, 7157.78, 0] < 10) then {
private _pasl = getPosASL player;
_pasl set [2, 14.981];
player setPosASL _pasl;
};
};
} else {
player setVehiclePosition [_respawn_pos, [], 0, "NONE"];
};
};
player allowDamage true;
} else {
player switchMove "";
player moveInCargo (vehicle _respawn_target);
};
};
player setVariable ["xr_plno3dd", nil, true];
d_last_beam_target = d_beam_target;
d_beam_target = "";
player setDamage 0;
__TRACE("MapClickRespawn, black in")
"xr_revtxt" cutText [localize "STR_DOM_MISSIONSTRING_918", "BLACK IN", 6];
if (xr_max_lives != -1) then {
0 spawn {
scriptName "spawn_buttonclickrespawn";
sleep 7;
if (xr_max_lives != -1) then {
hintSilent format [localize "STR_DOM_MISSIONSTRING_933", player getVariable "xr_lives"];
};
if (d_with_ai && {alive player && {!(player getVariable "xr_pluncon")}}) then {[] spawn d_fnc_moveai};
};
};
if (d_database_found) then {
player setVariable ["d_move_opos", getPosWorld player];
player setVariable ["d_move_stop", nil];
};
0 spawn {
scriptName "spawn_buttonclickrespawn2";
if (!d_ifa3 && {!d_spe && {d_without_nvg == 1 && {player call d_fnc_hasnvgoggles && {player getVariable ["d_currentvisionmode", 0] == 1}}}}) then {
player actionNow ["NVGoggles", player];
};
};
__TRACE("MapClickRespawn done") | 0 | 0.900495 | 1 | 0.900495 | game-dev | MEDIA | 0.986371 | game-dev | 0.576002 | 1 | 0.576002 |
MoeMod/CSMoE | 12,162 | SourceSDK/tier1/utlsymbol.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Defines a symbol table
//
// $Header: $
// $NoKeywords: $
//=============================================================================//
#pragma warning (disable:4514)
#include "utlsymbol.h"
#include "KeyValues.h"
#include "tier0/threadtools.h"
#include "tier0/memdbgon.h"
#include "stringpool.h"
#include "utlhashtable.h"
#include "utlstring.h"
// Ensure that everybody has the right compiler version installed. The version
// number can be obtained by looking at the compiler output when you type 'cl'
// and removing the last two digits and the periods: 16.00.40219.01 becomes 160040219
#ifdef _MSC_FULL_VER
#if _MSC_FULL_VER > 160000000
// VS 2010
#if _MSC_FULL_VER < 160040219
#error You must install VS 2010 SP1
#endif
#else
// VS 2005
#if _MSC_FULL_VER < 140050727
#error You must install VS 2005 SP1
#endif
#endif
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define INVALID_STRING_INDEX CStringPoolIndex( 0xFFFF, 0xFFFF )
#define MIN_STRING_POOL_SIZE 2048
//-----------------------------------------------------------------------------
// globals
//-----------------------------------------------------------------------------
CUtlSymbolTableMT* CUtlSymbol::s_pSymbolTable = 0;
bool CUtlSymbol::s_bAllowStaticSymbolTable = true;
//-----------------------------------------------------------------------------
// symbol methods
//-----------------------------------------------------------------------------
void CUtlSymbol::Initialize()
{
// If this assert fails, then the module that this call is in has chosen to disallow
// use of the static symbol table. Usually, it's to prevent confusion because it's easy
// to accidentally use the global symbol table when you really want to use a specific one.
Assert( s_bAllowStaticSymbolTable );
// necessary to allow us to create global symbols
static bool symbolsInitialized = false;
if (!symbolsInitialized)
{
s_pSymbolTable = new CUtlSymbolTableMT;
symbolsInitialized = true;
}
}
//-----------------------------------------------------------------------------
// Purpose: Singleton to delete table on exit from module
//-----------------------------------------------------------------------------
class CCleanupUtlSymbolTable
{
public:
~CCleanupUtlSymbolTable()
{
delete CUtlSymbol::s_pSymbolTable;
CUtlSymbol::s_pSymbolTable = NULL;
}
};
static CCleanupUtlSymbolTable g_CleanupSymbolTable;
CUtlSymbolTableMT* CUtlSymbol::CurrTable()
{
Initialize();
return s_pSymbolTable;
}
//-----------------------------------------------------------------------------
// string->symbol->string
//-----------------------------------------------------------------------------
CUtlSymbol::CUtlSymbol( const char* pStr )
{
m_Id = CurrTable()->AddString( pStr );
}
const char* CUtlSymbol::String( ) const
{
return CurrTable()->String(m_Id);
}
void CUtlSymbol::DisableStaticSymbolTable()
{
s_bAllowStaticSymbolTable = false;
}
//-----------------------------------------------------------------------------
// checks if the symbol matches a string
//-----------------------------------------------------------------------------
bool CUtlSymbol::operator==( const char* pStr ) const
{
if (m_Id == UTL_INVAL_SYMBOL)
return false;
return strcmp( String(), pStr ) == 0;
}
//-----------------------------------------------------------------------------
// symbol table stuff
//-----------------------------------------------------------------------------
inline const char* CUtlSymbolTable::StringFromIndex( const CStringPoolIndex &index ) const
{
Assert( index.m_iPool < m_StringPools.Count() );
Assert( index.m_iOffset < m_StringPools[index.m_iPool]->m_TotalLen );
return &m_StringPools[index.m_iPool]->m_Data[index.m_iOffset];
}
bool CUtlSymbolTable::CLess::operator()( const CStringPoolIndex &i1, const CStringPoolIndex &i2 ) const
{
// Need to do pointer math because CUtlSymbolTable is used in CUtlVectors, and hence
// can be arbitrarily moved in memory on a realloc. Yes, this is portable. In reality,
// right now at least, because m_LessFunc is the first member of CUtlRBTree, and m_Lookup
// is the first member of CUtlSymbolTabke, this == pTable
CUtlSymbolTable *pTable = (CUtlSymbolTable *)( (byte *)this - offsetof(CUtlSymbolTable::CTree, m_LessFunc) ) - offsetof(CUtlSymbolTable, m_Lookup );
const char* str1 = (i1 == INVALID_STRING_INDEX) ? pTable->m_pUserSearchString :
pTable->StringFromIndex( i1 );
const char* str2 = (i2 == INVALID_STRING_INDEX) ? pTable->m_pUserSearchString :
pTable->StringFromIndex( i2 );
if ( !str1 && str2 )
return false;
if ( !str2 && str1 )
return true;
if ( !str1 && !str2 )
return false;
if ( !pTable->m_bInsensitive )
return V_strcmp( str1, str2 ) < 0;
else
return V_stricmp( str1, str2 ) < 0;
}
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CUtlSymbolTable::CUtlSymbolTable( int growSize, int initSize, bool caseInsensitive ) :
m_Lookup( growSize, initSize ), m_bInsensitive( caseInsensitive ), m_StringPools( 8 )
{
}
CUtlSymbolTable::~CUtlSymbolTable()
{
// Release the stringpool string data
RemoveAll();
}
CUtlSymbol CUtlSymbolTable::Find( const char* pString ) const
{
if (!pString)
return CUtlSymbol();
// Store a special context used to help with insertion
m_pUserSearchString = pString;
// Passing this special invalid symbol makes the comparison function
// use the string passed in the context
UtlSymId_t idx = m_Lookup.Find( INVALID_STRING_INDEX );
#ifdef _DEBUG
m_pUserSearchString = NULL;
#endif
return CUtlSymbol( idx );
}
int CUtlSymbolTable::FindPoolWithSpace( int len ) const
{
for ( int i=0; i < m_StringPools.Count(); i++ )
{
StringPool_t *pPool = m_StringPools[i];
if ( (pPool->m_TotalLen - pPool->m_SpaceUsed) >= len )
{
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------------
// Finds and/or creates a symbol based on the string
//-----------------------------------------------------------------------------
CUtlSymbol CUtlSymbolTable::AddString( const char* pString )
{
if (!pString)
return CUtlSymbol( UTL_INVAL_SYMBOL );
CUtlSymbol id = Find( pString );
if (id.IsValid())
return id;
int len = V_strlen(pString) + 1;
// Find a pool with space for this string, or allocate a new one.
int iPool = FindPoolWithSpace( len );
if ( iPool == -1 )
{
// Add a new pool.
int newPoolSize = max( len, MIN_STRING_POOL_SIZE );
StringPool_t *pPool = (StringPool_t*)malloc( sizeof( StringPool_t ) + newPoolSize - 1 );
pPool->m_TotalLen = newPoolSize;
pPool->m_SpaceUsed = 0;
iPool = m_StringPools.AddToTail( pPool );
}
// Copy the string in.
StringPool_t *pPool = m_StringPools[iPool];
Assert( pPool->m_SpaceUsed < 0xFFFF ); // This should never happen, because if we had a string > 64k, it
// would have been given its entire own pool.
unsigned short iStringOffset = pPool->m_SpaceUsed;
memcpy( &pPool->m_Data[pPool->m_SpaceUsed], pString, len );
pPool->m_SpaceUsed += len;
// didn't find, insert the string into the vector.
CStringPoolIndex index;
index.m_iPool = iPool;
index.m_iOffset = iStringOffset;
UtlSymId_t idx = m_Lookup.Insert( index );
return CUtlSymbol( idx );
}
//-----------------------------------------------------------------------------
// Look up the string associated with a particular symbol
//-----------------------------------------------------------------------------
const char* CUtlSymbolTable::String( CUtlSymbol id ) const
{
if (!id.IsValid())
return "";
Assert( m_Lookup.IsValidIndex((UtlSymId_t)id) );
return StringFromIndex( m_Lookup[id] );
}
//-----------------------------------------------------------------------------
// Remove all symbols in the table.
//-----------------------------------------------------------------------------
void CUtlSymbolTable::RemoveAll()
{
m_Lookup.Purge();
for ( int i=0; i < m_StringPools.Count(); i++ )
free( m_StringPools[i] );
m_StringPools.RemoveAll();
}
class CUtlFilenameSymbolTable::HashTable : public CUtlStableHashtable<CUtlConstString>
{
};
CUtlFilenameSymbolTable::CUtlFilenameSymbolTable()
{
m_Strings = new HashTable;
}
CUtlFilenameSymbolTable::~CUtlFilenameSymbolTable()
{
delete m_Strings;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pFileName -
// Output : FileNameHandle_t
//-----------------------------------------------------------------------------
FileNameHandle_t CUtlFilenameSymbolTable::FindOrAddFileName( const char *pFileName )
{
if ( !pFileName )
{
return NULL;
}
// find first
FileNameHandle_t hFileName = FindFileName( pFileName );
if ( hFileName )
{
return hFileName;
}
// Fix slashes+dotslashes and make lower case first..
char fn[ MAX_PATH ];
Q_strncpy( fn, pFileName, sizeof( fn ) );
Q_RemoveDotSlashes( fn );
#ifdef _WIN32
Q_strlower( fn );
#endif
// Split the filename into constituent parts
char basepath[ MAX_PATH ];
Q_ExtractFilePath( fn, basepath, sizeof( basepath ) );
char filename[ MAX_PATH ];
Q_strncpy( filename, fn + Q_strlen( basepath ), sizeof( filename ) );
// not found, lock and look again
FileNameHandleInternal_t handle;
m_lock.LockForWrite();
handle.path = m_Strings->Insert( basepath ) + 1;
handle.file = m_Strings->Insert( filename ) + 1;
//handle.path = m_StringPool.FindStringHandle( basepath );
//handle.file = m_StringPool.FindStringHandle( filename );
//if ( handle.path != m_Strings.InvalidHandle() && handle.file )
//{
// found
// m_lock.UnlockWrite();
// return *( FileNameHandle_t * )( &handle );
//}
// safely add it
//handle.path = m_StringPool.ReferenceStringHandle( basepath );
//handle.file = m_StringPool.ReferenceStringHandle( filename );
m_lock.UnlockWrite();
return *( FileNameHandle_t * )( &handle );
}
FileNameHandle_t CUtlFilenameSymbolTable::FindFileName( const char *pFileName )
{
if ( !pFileName )
{
return NULL;
}
// Fix slashes+dotslashes and make lower case first..
char fn[ MAX_PATH ];
Q_strncpy( fn, pFileName, sizeof( fn ) );
Q_RemoveDotSlashes( fn );
#ifdef _WIN32
Q_strlower( fn );
#endif
// Split the filename into constituent parts
char basepath[ MAX_PATH ];
Q_ExtractFilePath( fn, basepath, sizeof( basepath ) );
char filename[ MAX_PATH ];
Q_strncpy( filename, fn + Q_strlen( basepath ), sizeof( filename ) );
FileNameHandleInternal_t handle;
Assert( (uint16)(m_Strings->InvalidHandle() + 1) == 0 );
m_lock.LockForRead();
handle.path = m_Strings->Find(basepath) + 1;
handle.file = m_Strings->Find(filename) + 1;
//handle.path = m_StringPool.FindStringHandle(basepath);
//handle.file = m_StringPool.FindStringHandle(filename);
m_lock.UnlockRead();
if ( handle.path == 0 || handle.file == 0 )
return NULL;
return *( FileNameHandle_t * )( &handle );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : handle -
// Output : const char
//-----------------------------------------------------------------------------
bool CUtlFilenameSymbolTable::String( const FileNameHandle_t& handle, char *buf, int buflen )
{
buf[ 0 ] = 0;
FileNameHandleInternal_t *internal = ( FileNameHandleInternal_t * )&handle;
if ( !internal || !internal->file || !internal->path )
{
return false;
}
m_lock.LockForRead();
//const char *path = m_StringPool.HandleToString(internal->path);
//const char *fn = m_StringPool.HandleToString(internal->file);
const char *path = (*m_Strings)[ internal->path - 1 ].Get();
const char *fn = (*m_Strings)[ internal->file - 1].Get();
m_lock.UnlockRead();
if ( !path || !fn )
{
return false;
}
Q_strncpy( buf, path, buflen );
Q_strncat( buf, fn, buflen, COPY_ALL_CHARACTERS );
return true;
}
void CUtlFilenameSymbolTable::RemoveAll()
{
m_Strings->Purge();
}
| 0 | 0.981471 | 1 | 0.981471 | game-dev | MEDIA | 0.592065 | game-dev | 0.963976 | 1 | 0.963976 |
Fluorohydride/ygopro-scripts | 1,957 | c46874015.lua | --六武衆推参!
function c46874015.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c46874015.target)
e1:SetOperation(c46874015.activate)
c:RegisterEffect(e1)
end
function c46874015.filter(c,e,tp)
return c:IsSetCard(0x103d) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c46874015.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c46874015.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c46874015.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c46874015.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c46874015.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then
local fid=e:GetHandler():GetFieldID()
tc:RegisterFlagEffect(46874015,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,1,fid)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetLabel(fid)
e1:SetLabelObject(tc)
e1:SetCondition(c46874015.descon)
e1:SetOperation(c46874015.desop)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetCountLimit(1)
Duel.RegisterEffect(e1,tp)
end
end
function c46874015.descon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
return tc:GetFlagEffectLabel(46874015)==e:GetLabel()
end
function c46874015.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetLabelObject(),REASON_EFFECT)
end
| 0 | 0.944977 | 1 | 0.944977 | game-dev | MEDIA | 0.986252 | game-dev | 0.936001 | 1 | 0.936001 |
BLACKujira/SekaiTools | 1,910 | SekaiTools/Assets/Scripts/UI/ButtonGenerator2D.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SekaiTools.UI
{
public class ButtonGenerator2D : ButtonGeneratorBase
{
List<Button> buttons = new List<Button>();
[Header("Components")]
public RectTransform scorllContent;
[Header("Prefab")]
public Button buttonPrefab;
[Header("Settings")]
public int numberPerLine;
public float distanceX;
public float distanceY;
public override void Generate(int count, Action<Button, int> initialize, Action<int> onClick)
{
scorllContent.sizeDelta = new Vector2(
scorllContent.sizeDelta.x,
distanceY * ((count / numberPerLine) + ((count % numberPerLine) == 0 ? 0 : 1)));
for (int i = 0; i < count; i++)
{
int id = i;
Button button = Instantiate(buttonPrefab, scorllContent);
initialize(button, id);
button.onClick.AddListener(() => onClick(id));
button.GetComponent<RectTransform>().anchoredPosition = new Vector2(
distanceX * (id % numberPerLine),
-distanceY * (id / numberPerLine));
buttons.Add(button);
}
}
public override void ClearButtons()
{
foreach (var button in buttons)
{
Destroy(button.gameObject);
}
buttons = new List<Button>();
}
public override void AddButton(Button buttonPrefab, Action<Button> initialize, Action onClick)
{
throw new NotImplementedException();
}
public override void AddButton(Action<Button> initialize, Action onClick)
{
throw new NotImplementedException();
}
}
} | 0 | 0.753599 | 1 | 0.753599 | game-dev | MEDIA | 0.68867 | game-dev,desktop-app | 0.747841 | 1 | 0.747841 |
randomguy3725/MoonLight | 19,810 | src/main/java/net/minecraft/world/gen/ChunkProviderHell.java | package net.minecraft.world.gen;
import java.util.List;
import java.util.Random;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.block.state.pattern.BlockHelper;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.util.MathHelper;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenFire;
import net.minecraft.world.gen.feature.WorldGenGlowStone1;
import net.minecraft.world.gen.feature.WorldGenGlowStone2;
import net.minecraft.world.gen.feature.WorldGenHellLava;
import net.minecraft.world.gen.feature.WorldGenMinable;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraft.world.gen.structure.MapGenNetherBridge;
public class ChunkProviderHell implements IChunkProvider
{
private final World worldObj;
private final boolean field_177466_i;
private final Random hellRNG;
private double[] slowsandNoise = new double[256];
private double[] gravelNoise = new double[256];
private double[] netherrackExclusivityNoise = new double[256];
private double[] noiseField;
private final NoiseGeneratorOctaves netherNoiseGen1;
private final NoiseGeneratorOctaves netherNoiseGen2;
private final NoiseGeneratorOctaves netherNoiseGen3;
private final NoiseGeneratorOctaves slowsandGravelNoiseGen;
private final NoiseGeneratorOctaves netherrackExculsivityNoiseGen;
public final NoiseGeneratorOctaves netherNoiseGen6;
public final NoiseGeneratorOctaves netherNoiseGen7;
private final WorldGenFire field_177470_t = new WorldGenFire();
private final WorldGenGlowStone1 field_177469_u = new WorldGenGlowStone1();
private final WorldGenGlowStone2 field_177468_v = new WorldGenGlowStone2();
private final WorldGenerator field_177467_w = new WorldGenMinable(Blocks.quartz_ore.getDefaultState(), 14, BlockHelper.forBlock(Blocks.netherrack));
private final WorldGenHellLava field_177473_x = new WorldGenHellLava(Blocks.flowing_lava, true);
private final WorldGenHellLava field_177472_y = new WorldGenHellLava(Blocks.flowing_lava, false);
private final GeneratorBushFeature field_177471_z = new GeneratorBushFeature(Blocks.brown_mushroom);
private final GeneratorBushFeature field_177465_A = new GeneratorBushFeature(Blocks.red_mushroom);
private final MapGenNetherBridge genNetherBridge = new MapGenNetherBridge();
private final MapGenBase netherCaveGenerator = new MapGenCavesHell();
double[] noiseData1;
double[] noiseData2;
double[] noiseData3;
double[] noiseData4;
double[] noiseData5;
public ChunkProviderHell(World worldIn, boolean p_i45637_2_, long seed)
{
this.worldObj = worldIn;
this.field_177466_i = p_i45637_2_;
this.hellRNG = new Random(seed);
this.netherNoiseGen1 = new NoiseGeneratorOctaves(this.hellRNG, 16);
this.netherNoiseGen2 = new NoiseGeneratorOctaves(this.hellRNG, 16);
this.netherNoiseGen3 = new NoiseGeneratorOctaves(this.hellRNG, 8);
this.slowsandGravelNoiseGen = new NoiseGeneratorOctaves(this.hellRNG, 4);
this.netherrackExculsivityNoiseGen = new NoiseGeneratorOctaves(this.hellRNG, 4);
this.netherNoiseGen6 = new NoiseGeneratorOctaves(this.hellRNG, 10);
this.netherNoiseGen7 = new NoiseGeneratorOctaves(this.hellRNG, 16);
worldIn.setSeaLevel(63);
}
public void func_180515_a(int p_180515_1_, int p_180515_2_, ChunkPrimer p_180515_3_)
{
int i = 4;
int j = this.worldObj.getSeaLevel() / 2 + 1;
int k = i + 1;
int l = 17;
int i1 = i + 1;
this.noiseField = this.initializeNoiseField(this.noiseField, p_180515_1_ * i, 0, p_180515_2_ * i, k, l, i1);
for (int j1 = 0; j1 < i; ++j1)
{
for (int k1 = 0; k1 < i; ++k1)
{
for (int l1 = 0; l1 < 16; ++l1)
{
double d0 = 0.125D;
double d1 = this.noiseField[((j1) * i1 + k1) * l + l1];
double d2 = this.noiseField[((j1) * i1 + k1 + 1) * l + l1];
double d3 = this.noiseField[((j1 + 1) * i1 + k1) * l + l1];
double d4 = this.noiseField[((j1 + 1) * i1 + k1 + 1) * l + l1];
double d5 = (this.noiseField[((j1) * i1 + k1) * l + l1 + 1] - d1) * d0;
double d6 = (this.noiseField[((j1) * i1 + k1 + 1) * l + l1 + 1] - d2) * d0;
double d7 = (this.noiseField[((j1 + 1) * i1 + k1) * l + l1 + 1] - d3) * d0;
double d8 = (this.noiseField[((j1 + 1) * i1 + k1 + 1) * l + l1 + 1] - d4) * d0;
for (int i2 = 0; i2 < 8; ++i2)
{
double d9 = 0.25D;
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * d9;
double d13 = (d4 - d2) * d9;
for (int j2 = 0; j2 < 4; ++j2)
{
double d14 = 0.25D;
double d15 = d10;
double d16 = (d11 - d10) * d14;
for (int k2 = 0; k2 < 4; ++k2)
{
IBlockState iblockstate = null;
if (l1 * 8 + i2 < j)
{
iblockstate = Blocks.lava.getDefaultState();
}
if (d15 > 0.0D)
{
iblockstate = Blocks.netherrack.getDefaultState();
}
int l2 = j2 + j1 * 4;
int i3 = i2 + l1 * 8;
int j3 = k2 + k1 * 4;
p_180515_3_.setBlockState(l2, i3, j3, iblockstate);
d15 += d16;
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
}
public void func_180516_b(int p_180516_1_, int p_180516_2_, ChunkPrimer p_180516_3_)
{
int i = this.worldObj.getSeaLevel() + 1;
double d0 = 0.03125D;
this.slowsandNoise = this.slowsandGravelNoiseGen.generateNoiseOctaves(this.slowsandNoise, p_180516_1_ * 16, p_180516_2_ * 16, 0, 16, 16, 1, d0, d0, 1.0D);
this.gravelNoise = this.slowsandGravelNoiseGen.generateNoiseOctaves(this.gravelNoise, p_180516_1_ * 16, 109, p_180516_2_ * 16, 16, 1, 16, d0, 1.0D, d0);
this.netherrackExclusivityNoise = this.netherrackExculsivityNoiseGen.generateNoiseOctaves(this.netherrackExclusivityNoise, p_180516_1_ * 16, p_180516_2_ * 16, 0, 16, 16, 1, d0 * 2.0D, d0 * 2.0D, d0 * 2.0D);
for (int j = 0; j < 16; ++j)
{
for (int k = 0; k < 16; ++k)
{
boolean flag = this.slowsandNoise[j + k * 16] + this.hellRNG.nextDouble() * 0.2D > 0.0D;
boolean flag1 = this.gravelNoise[j + k * 16] + this.hellRNG.nextDouble() * 0.2D > 0.0D;
int l = (int)(this.netherrackExclusivityNoise[j + k * 16] / 3.0D + 3.0D + this.hellRNG.nextDouble() * 0.25D);
int i1 = -1;
IBlockState iblockstate = Blocks.netherrack.getDefaultState();
IBlockState iblockstate1 = Blocks.netherrack.getDefaultState();
for (int j1 = 127; j1 >= 0; --j1)
{
if (j1 < 127 - this.hellRNG.nextInt(5) && j1 > this.hellRNG.nextInt(5))
{
IBlockState iblockstate2 = p_180516_3_.getBlockState(k, j1, j);
if (iblockstate2.getBlock() != null && iblockstate2.getBlock().getMaterial() != Material.air)
{
if (iblockstate2.getBlock() == Blocks.netherrack)
{
if (i1 == -1)
{
if (l <= 0)
{
iblockstate = null;
iblockstate1 = Blocks.netherrack.getDefaultState();
}
else if (j1 >= i - 4 && j1 <= i + 1)
{
iblockstate = Blocks.netherrack.getDefaultState();
iblockstate1 = Blocks.netherrack.getDefaultState();
if (flag1)
{
iblockstate = Blocks.gravel.getDefaultState();
iblockstate1 = Blocks.netherrack.getDefaultState();
}
if (flag)
{
iblockstate = Blocks.soul_sand.getDefaultState();
iblockstate1 = Blocks.soul_sand.getDefaultState();
}
}
if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air))
{
iblockstate = Blocks.lava.getDefaultState();
}
i1 = l;
if (j1 >= i - 1)
{
p_180516_3_.setBlockState(k, j1, j, iblockstate);
}
else
{
p_180516_3_.setBlockState(k, j1, j, iblockstate1);
}
}
else if (i1 > 0)
{
--i1;
p_180516_3_.setBlockState(k, j1, j, iblockstate1);
}
}
}
else
{
i1 = -1;
}
}
else
{
p_180516_3_.setBlockState(k, j1, j, Blocks.bedrock.getDefaultState());
}
}
}
}
}
public Chunk provideChunk(int x, int z)
{
this.hellRNG.setSeed((long)x * 341873128712L + (long)z * 132897987541L);
ChunkPrimer chunkprimer = new ChunkPrimer();
this.func_180515_a(x, z, chunkprimer);
this.func_180516_b(x, z, chunkprimer);
this.netherCaveGenerator.generate(this, this.worldObj, x, z, chunkprimer);
if (this.field_177466_i)
{
this.genNetherBridge.generate(this, this.worldObj, x, z, chunkprimer);
}
Chunk chunk = new Chunk(this.worldObj, chunkprimer, x, z);
BiomeGenBase[] abiomegenbase = this.worldObj.getWorldChunkManager().loadBlockGeneratorData(null, x * 16, z * 16, 16, 16);
byte[] abyte = chunk.getBiomeArray();
for (int i = 0; i < abyte.length; ++i)
{
abyte[i] = (byte)abiomegenbase[i].biomeID;
}
chunk.resetRelightChecks();
return chunk;
}
private double[] initializeNoiseField(double[] p_73164_1_, int p_73164_2_, int p_73164_3_, int p_73164_4_, int p_73164_5_, int p_73164_6_, int p_73164_7_)
{
if (p_73164_1_ == null)
{
p_73164_1_ = new double[p_73164_5_ * p_73164_6_ * p_73164_7_];
}
double d0 = 684.412D;
double d1 = 2053.236D;
this.noiseData4 = this.netherNoiseGen6.generateNoiseOctaves(this.noiseData4, p_73164_2_, p_73164_3_, p_73164_4_, p_73164_5_, 1, p_73164_7_, 1.0D, 0.0D, 1.0D);
this.noiseData5 = this.netherNoiseGen7.generateNoiseOctaves(this.noiseData5, p_73164_2_, p_73164_3_, p_73164_4_, p_73164_5_, 1, p_73164_7_, 100.0D, 0.0D, 100.0D);
this.noiseData1 = this.netherNoiseGen3.generateNoiseOctaves(this.noiseData1, p_73164_2_, p_73164_3_, p_73164_4_, p_73164_5_, p_73164_6_, p_73164_7_, d0 / 80.0D, d1 / 60.0D, d0 / 80.0D);
this.noiseData2 = this.netherNoiseGen1.generateNoiseOctaves(this.noiseData2, p_73164_2_, p_73164_3_, p_73164_4_, p_73164_5_, p_73164_6_, p_73164_7_, d0, d1, d0);
this.noiseData3 = this.netherNoiseGen2.generateNoiseOctaves(this.noiseData3, p_73164_2_, p_73164_3_, p_73164_4_, p_73164_5_, p_73164_6_, p_73164_7_, d0, d1, d0);
int i = 0;
double[] adouble = new double[p_73164_6_];
for (int j = 0; j < p_73164_6_; ++j)
{
adouble[j] = Math.cos((double)j * Math.PI * 6.0D / (double)p_73164_6_) * 2.0D;
double d2 = j;
if (j > p_73164_6_ / 2)
{
d2 = p_73164_6_ - 1 - j;
}
if (d2 < 4.0D)
{
d2 = 4.0D - d2;
adouble[j] -= d2 * d2 * d2 * 10.0D;
}
}
for (int l = 0; l < p_73164_5_; ++l)
{
for (int i1 = 0; i1 < p_73164_7_; ++i1)
{
double d3 = 0.0D;
for (int k = 0; k < p_73164_6_; ++k)
{
double d4 = 0.0D;
double d5 = adouble[k];
double d6 = this.noiseData2[i] / 512.0D;
double d7 = this.noiseData3[i] / 512.0D;
double d8 = (this.noiseData1[i] / 10.0D + 1.0D) / 2.0D;
if (d8 < 0.0D)
{
d4 = d6;
}
else if (d8 > 1.0D)
{
d4 = d7;
}
else
{
d4 = d6 + (d7 - d6) * d8;
}
d4 = d4 - d5;
if (k > p_73164_6_ - 4)
{
double d9 = (float)(k - (p_73164_6_ - 4)) / 3.0F;
d4 = d4 * (1.0D - d9) + -10.0D * d9;
}
if ((double)k < d3)
{
double d10 = (d3 - (double)k) / 4.0D;
d10 = MathHelper.clamp_double(d10, 0.0D, 1.0D);
d4 = d4 * (1.0D - d10) + -10.0D * d10;
}
p_73164_1_[i] = d4;
++i;
}
}
}
return p_73164_1_;
}
public boolean chunkExists(int x, int z)
{
return true;
}
public void populate(IChunkProvider chunkProvider, int x, int z)
{
BlockFalling.fallInstantly = true;
BlockPos blockpos = new BlockPos(x * 16, 0, z * 16);
ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(x, z);
this.genNetherBridge.generateStructure(this.worldObj, this.hellRNG, chunkcoordintpair);
for (int i = 0; i < 8; ++i)
{
this.field_177472_y.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16) + 8, this.hellRNG.nextInt(120) + 4, this.hellRNG.nextInt(16) + 8));
}
for (int j = 0; j < this.hellRNG.nextInt(this.hellRNG.nextInt(10) + 1) + 1; ++j)
{
this.field_177470_t.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16) + 8, this.hellRNG.nextInt(120) + 4, this.hellRNG.nextInt(16) + 8));
}
for (int k = 0; k < this.hellRNG.nextInt(this.hellRNG.nextInt(10) + 1); ++k)
{
this.field_177469_u.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16) + 8, this.hellRNG.nextInt(120) + 4, this.hellRNG.nextInt(16) + 8));
}
for (int l = 0; l < 10; ++l)
{
this.field_177468_v.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16) + 8, this.hellRNG.nextInt(128), this.hellRNG.nextInt(16) + 8));
}
if (this.hellRNG.nextBoolean())
{
this.field_177471_z.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16) + 8, this.hellRNG.nextInt(128), this.hellRNG.nextInt(16) + 8));
}
if (this.hellRNG.nextBoolean())
{
this.field_177465_A.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16) + 8, this.hellRNG.nextInt(128), this.hellRNG.nextInt(16) + 8));
}
for (int i1 = 0; i1 < 16; ++i1)
{
this.field_177467_w.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16), this.hellRNG.nextInt(108) + 10, this.hellRNG.nextInt(16)));
}
for (int j1 = 0; j1 < 16; ++j1)
{
this.field_177473_x.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16), this.hellRNG.nextInt(108) + 10, this.hellRNG.nextInt(16)));
}
BlockFalling.fallInstantly = false;
}
public boolean populateChunk(IChunkProvider chunkProvider, Chunk chunkIn, int x, int z)
{
return false;
}
public boolean saveChunks(boolean saveAllChunks, IProgressUpdate progressCallback)
{
return true;
}
public void saveExtraData()
{
}
public boolean unloadQueuedChunks()
{
return false;
}
public boolean canSave()
{
return true;
}
public String makeString()
{
return "HellRandomLevelSource";
}
public List<BiomeGenBase.SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos)
{
if (creatureType == EnumCreatureType.MONSTER)
{
if (this.genNetherBridge.func_175795_b(pos))
{
return this.genNetherBridge.getSpawnList();
}
if (this.genNetherBridge.isPositionInStructure(this.worldObj, pos) && this.worldObj.getBlockState(pos.down()).getBlock() == Blocks.nether_brick)
{
return this.genNetherBridge.getSpawnList();
}
}
BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(pos);
return biomegenbase.getSpawnableList(creatureType);
}
public BlockPos getStrongholdGen(World worldIn, String structureName, BlockPos position)
{
return null;
}
public int getLoadedChunkCount()
{
return 0;
}
public void recreateStructures(Chunk chunkIn, int x, int z)
{
this.genNetherBridge.generate(this, this.worldObj, x, z, null);
}
public Chunk provideChunk(BlockPos blockPosIn)
{
return this.provideChunk(blockPosIn.getX() >> 4, blockPosIn.getZ() >> 4);
}
}
| 0 | 0.836639 | 1 | 0.836639 | game-dev | MEDIA | 0.992143 | game-dev | 0.955154 | 1 | 0.955154 |
HouQiming/jacy | 4,703 | wrapper/sdl/src/joystick/iphoneos/SDLUIAccelerationDelegate.m | /*
Simple DirectMedia Layer
Copyright (C) 1997-2014 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.
*/
#import "SDLUIAccelerationDelegate.h"
/* needed for SDL_IPHONE_MAX_GFORCE macro */
#import "../../../include/SDL_config_iphoneos.h"
static SDLUIAccelerationDelegate *sharedDelegate=nil;
@implementation SDLUIAccelerationDelegate
/*
Returns a shared instance of the SDLUIAccelerationDelegate, creating the shared delegate if it doesn't exist yet.
*/
+(SDLUIAccelerationDelegate *)sharedDelegate {
if (sharedDelegate == nil) {
sharedDelegate = [[SDLUIAccelerationDelegate alloc] init];
}
return sharedDelegate;
}
/*
UIAccelerometerDelegate delegate method. Invoked by the UIAccelerometer instance when it has new data for us.
We just take the data and mark that we have new data available so that the joystick system will pump it to the
events system when SDL_SYS_JoystickUpdate is called.
*/
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
hasNewData = YES;
}
/*
getLastOrientation -- put last obtained accelerometer data into Sint16 array
Called from the joystick system when it needs the accelerometer data.
Function grabs the last data sent to the accelerometer and converts it
from floating point to Sint16, which is what the joystick system expects.
To do the conversion, the data is first clamped onto the interval
[-SDL_IPHONE_MAX_G_FORCE, SDL_IPHONE_MAX_G_FORCE], then the data is multiplied
by MAX_SINT16 so that it is mapped to the full range of an Sint16.
You can customize the clamped range of this function by modifying the
SDL_IPHONE_MAX_GFORCE macro in SDL_config_iphoneos.h.
Once converted to Sint16, the accelerometer data no longer has coherent units.
You can convert the data back to units of g-force by multiplying it
in your application's code by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
*/
-(void)getLastOrientation:(Sint16 *)data {
#define MAX_SINT16 0x7FFF
/* clamp the data */
if (x > SDL_IPHONE_MAX_GFORCE) x = SDL_IPHONE_MAX_GFORCE;
else if (x < -SDL_IPHONE_MAX_GFORCE) x = -SDL_IPHONE_MAX_GFORCE;
if (y > SDL_IPHONE_MAX_GFORCE) y = SDL_IPHONE_MAX_GFORCE;
else if (y < -SDL_IPHONE_MAX_GFORCE) y = -SDL_IPHONE_MAX_GFORCE;
if (z > SDL_IPHONE_MAX_GFORCE) z = SDL_IPHONE_MAX_GFORCE;
else if (z < -SDL_IPHONE_MAX_GFORCE) z = -SDL_IPHONE_MAX_GFORCE;
/* pass in data mapped to range of SInt16 */
data[0] = (x / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[1] = (y / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[2] = (z / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
}
/*
Initialize SDLUIAccelerationDelegate. Since we don't have any data yet,
just set our last received data to zero, and indicate we don't have any;
*/
-(id)init {
self = [super init];
x = y = z = 0.0;
hasNewData = NO;
return self;
}
-(void)dealloc {
sharedDelegate = nil;
[self shutdown];
[super dealloc];
}
/*
Lets our delegate start receiving accelerometer updates.
*/
-(void)startup {
[UIAccelerometer sharedAccelerometer].delegate = self;
isRunning = YES;
}
/*
Stops our delegate from receiving accelerometer updates.
*/
-(void)shutdown {
if ([UIAccelerometer sharedAccelerometer].delegate == self) {
[UIAccelerometer sharedAccelerometer].delegate = nil;
}
isRunning = NO;
}
/*
Our we currently receiving accelerometer updates?
*/
-(BOOL)isRunning {
return isRunning;
}
/*
Do we have any data that hasn't been pumped into SDL's event system?
*/
-(BOOL)hasNewData {
return hasNewData;
}
/*
When the joystick system grabs the new data, it sets this to NO.
*/
-(void)setHasNewData:(BOOL)value {
hasNewData = value;
}
@end
| 0 | 0.836035 | 1 | 0.836035 | game-dev | MEDIA | 0.71998 | game-dev | 0.641778 | 1 | 0.641778 |
asantee/ethanon | 6,235 | toolkit/Source/src/box2d/Box2D/Dynamics/Joints/b2FrictionJoint.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
}
b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
}
void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
// Solve angular friction
{
float32 Cdot = wB - wA;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2FrictionJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2FrictionJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2FrictionJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2FrictionJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2FrictionJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2FrictionJoint::GetMaxTorque() const
{
return m_maxTorque;
}
| 0 | 0.94234 | 1 | 0.94234 | game-dev | MEDIA | 0.97388 | game-dev | 0.965267 | 1 | 0.965267 |
manisha-v/Number-Cruncher | 31,082 | Codes/Minor2d/Library/PackageCache/com.unity.timeline@1.2.18/Editor/treeview/TimelineTrackGUI.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.IMGUI.Controls;
using UnityEditor.StyleSheets;
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using Object = UnityEngine.Object;
namespace UnityEditor.Timeline
{
class TimelineTrackGUI : TimelineGroupGUI, IClipCurveEditorOwner, IRowGUI
{
struct TrackDrawData
{
public bool m_AllowsRecording;
public bool m_ShowTrackBindings;
public bool m_HasBinding;
public bool m_IsSubTrack;
public PlayableBinding m_Binding;
public UnityEngine.Object m_TrackBinding;
public Texture m_TrackIcon;
}
static class Styles
{
public static readonly string kArmForRecordDisabled = L10n.Tr("Recording is not permitted when Track Offsets are set to Auto. Track Offset settings can be changed in the track menu of the base track.");
public static Texture2D kProblemIcon = DirectorStyles.GetBackgroundImage(DirectorStyles.Instance.warning);
}
static GUIContent s_ArmForRecordContentOn;
static GUIContent s_ArmForRecordContentOff;
static GUIContent s_ArmForRecordDisabled;
bool m_InlineCurvesSkipped;
int m_TrackHash = -1;
int m_BlendHash = -1;
int m_LastDirtyIndex = -1;
readonly InfiniteTrackDrawer m_InfiniteTrackDrawer;
TrackItemsDrawer m_ItemsDrawer;
TrackDrawData m_TrackDrawData;
TrackDrawOptions m_TrackDrawOptions;
readonly TrackEditor m_TrackEditor;
readonly GUIContent m_DefaultTrackIcon;
public override bool expandable
{
get { return hasChildren; }
}
internal InlineCurveEditor inlineCurveEditor { get; set; }
public ClipCurveEditor clipCurveEditor { get; private set; }
public bool inlineCurvesSelected
{
get { return SelectionManager.IsCurveEditorFocused(this); }
set
{
if (!value && SelectionManager.IsCurveEditorFocused(this))
SelectionManager.SelectInlineCurveEditor(null);
else
SelectionManager.SelectInlineCurveEditor(this);
}
}
bool IClipCurveEditorOwner.showLoops
{
get { return false; }
}
TrackAsset IClipCurveEditorOwner.owner
{
get { return track; }
}
static bool DoesTrackAllowsRecording(TrackAsset track)
{
// if the root animation track is in auto mode, recording is not allowed
var animTrack = TimelineUtility.GetSceneReferenceTrack(track) as AnimationTrack;
if (animTrack != null)
return animTrack.trackOffset != TrackOffset.Auto;
return false;
}
bool? m_TrackHasAnimatableParameters;
bool trackHasAnimatableParameters
{
get
{
// cache this value to avoid the recomputation
if (!m_TrackHasAnimatableParameters.HasValue)
m_TrackHasAnimatableParameters = track.HasAnyAnimatableParameters() ||
track.clips.Any(c => c.HasAnyAnimatableParameters());
return m_TrackHasAnimatableParameters.Value;
}
}
public bool locked
{
get { return track.lockedInHierarchy; }
}
public bool showMarkers
{
get { return track.GetShowMarkers(); }
}
public bool muted
{
get { return track.muted; }
}
public List<TimelineClipGUI> clips
{
get
{
return m_ItemsDrawer.clips == null ? new List<TimelineClipGUI>(0) : m_ItemsDrawer.clips.ToList();
}
}
TrackAsset IRowGUI.asset { get { return track; } }
bool showTrackRecordingDisabled
{
get
{
// if the root animation track is in auto mode, recording is not allowed
var animTrack = TimelineUtility.GetSceneReferenceTrack(track) as AnimationTrack;
return animTrack != null && animTrack.trackOffset == TrackOffset.Auto;
}
}
public TimelineTrackGUI(TreeViewController tv, TimelineTreeViewGUI w, int id, int depth, TreeViewItem parent, string displayName, TrackAsset sequenceActor)
: base(tv, w, id, depth, parent, displayName, sequenceActor, false)
{
AnimationTrack animationTrack = sequenceActor as AnimationTrack;
if (animationTrack != null)
m_InfiniteTrackDrawer = new InfiniteTrackDrawer(new AnimationTrackKeyDataSource(animationTrack));
else if (sequenceActor.HasAnyAnimatableParameters() && !sequenceActor.clips.Any())
m_InfiniteTrackDrawer = new InfiniteTrackDrawer(new TrackPropertyCurvesDataSource(sequenceActor));
UpdateInfiniteClipEditor(w.TimelineWindow);
var bindings = track.outputs.ToArray();
m_TrackDrawData.m_HasBinding = bindings.Length > 0;
if (m_TrackDrawData.m_HasBinding)
m_TrackDrawData.m_Binding = bindings[0];
m_TrackDrawData.m_IsSubTrack = IsSubTrack();
m_TrackDrawData.m_AllowsRecording = DoesTrackAllowsRecording(sequenceActor);
m_DefaultTrackIcon = TrackResourceCache.GetTrackIcon(track);
m_TrackEditor = CustomTimelineEditorCache.GetTrackEditor(sequenceActor);
try
{
m_TrackDrawOptions = m_TrackEditor.GetTrackOptions(track, null);
}
catch (Exception e)
{
Debug.LogException(e);
m_TrackDrawOptions = CustomTimelineEditorCache.GetDefaultTrackEditor().GetTrackOptions(track, null);
}
m_TrackDrawOptions.errorText = null; // explicitly setting to null for an uninitialized state
RebuildGUICacheIfNecessary();
}
public override float GetVerticalSpacingBetweenTracks()
{
if (track != null && track.isSubTrack)
return 1.0f; // subtracks have less of a gap than tracks
return base.GetVerticalSpacingBetweenTracks();
}
void UpdateInfiniteClipEditor(TimelineWindow window)
{
if (clipCurveEditor != null || track == null || !track.ShouldShowInfiniteClipEditor())
return;
var dataSource = CurveDataSource.Create(this);
clipCurveEditor = new ClipCurveEditor(dataSource, window, track);
}
void DetectTrackChanged()
{
if (Event.current.type == EventType.Layout)
{
// incremented when a track or it's clips changed
if (m_LastDirtyIndex != track.DirtyIndex)
{
try
{
m_TrackEditor.OnTrackChanged(track);
}
catch (Exception e)
{
Debug.LogException(e);
}
m_LastDirtyIndex = track.DirtyIndex;
}
OnTrackChanged();
}
}
// Called when the source track data, including it's clips have changed has changed.
void OnTrackChanged()
{
// recompute blends if necessary
int newBlendHash = BlendHash();
if (m_BlendHash != newBlendHash)
{
UpdateClipOverlaps();
m_BlendHash = newBlendHash;
}
RebuildGUICacheIfNecessary();
}
void UpdateDrawData(WindowState state)
{
if (Event.current.type == EventType.Layout)
{
m_TrackDrawData.m_ShowTrackBindings = false;
m_TrackDrawData.m_TrackBinding = null;
if (state.editSequence.director != null && showSceneReference)
{
m_TrackDrawData.m_ShowTrackBindings = state.GetWindow().currentMode.ShouldShowTrackBindings(state);
m_TrackDrawData.m_TrackBinding = state.editSequence.director.GetGenericBinding(track);
}
var lastError = m_TrackDrawOptions.errorText;
var lastHeight = m_TrackDrawOptions.minimumHeight;
try
{
m_TrackDrawOptions = m_TrackEditor.GetTrackOptions(track, m_TrackDrawData.m_TrackBinding);
}
catch (Exception e)
{
Debug.LogException(e);
m_TrackDrawOptions = CustomTimelineEditorCache.GetDefaultTrackEditor().GetTrackOptions(track, m_TrackDrawData.m_TrackBinding);
}
m_TrackDrawData.m_AllowsRecording = DoesTrackAllowsRecording(track);
m_TrackDrawData.m_TrackIcon = m_TrackDrawOptions.icon;
if (m_TrackDrawData.m_TrackIcon == null)
m_TrackDrawData.m_TrackIcon = m_DefaultTrackIcon.image;
// track height has changed. need to update gui
if (!Mathf.Approximately(lastHeight, m_TrackDrawOptions.minimumHeight))
state.Refresh();
}
}
public override void Draw(Rect headerRect, Rect contentRect, WindowState state)
{
DetectTrackChanged();
UpdateDrawData(state);
UpdateInfiniteClipEditor(state.GetWindow());
var trackHeaderRect = headerRect;
var trackContentRect = contentRect;
float inlineCurveHeight = contentRect.height - GetTrackContentHeight(state);
bool hasInlineCurve = inlineCurveHeight > 0.0f;
if (hasInlineCurve)
{
trackHeaderRect.height -= inlineCurveHeight;
trackContentRect.height -= inlineCurveHeight;
}
if (Event.current.type == EventType.Repaint)
{
m_TreeViewRect = trackContentRect;
}
if (s_ArmForRecordContentOn == null)
s_ArmForRecordContentOn = new GUIContent(DirectorStyles.GetBackgroundImage(DirectorStyles.Instance.autoKey, StyleState.active));
if (s_ArmForRecordContentOff == null)
s_ArmForRecordContentOff = new GUIContent(DirectorStyles.GetBackgroundImage(DirectorStyles.Instance.autoKey));
if (s_ArmForRecordDisabled == null)
s_ArmForRecordDisabled = new GUIContent(DirectorStyles.GetBackgroundImage(DirectorStyles.Instance.autoKey), Styles.kArmForRecordDisabled);
track.SetCollapsed(!isExpanded);
RebuildGUICacheIfNecessary();
// Prevents from drawing outside of bounds, but does not effect layout or markers
bool isOwnerDrawSucceed = false;
Vector2 visibleTime = state.timeAreaShownRange;
if (drawer != null)
isOwnerDrawSucceed = drawer.DrawTrack(trackContentRect, track, visibleTime, state);
if (!isOwnerDrawSucceed)
{
using (new GUIViewportScope(trackContentRect))
DrawBackground(trackContentRect, track, visibleTime, state);
if (m_InfiniteTrackDrawer != null)
m_InfiniteTrackDrawer.DrawTrack(trackContentRect, track, visibleTime, state);
// draw after user customization so overlay text shows up
using (new GUIViewportScope(trackContentRect))
m_ItemsDrawer.Draw(trackContentRect, state);
}
DrawTrackHeader(trackHeaderRect, state);
if (hasInlineCurve)
{
var curvesHeaderRect = headerRect;
curvesHeaderRect.yMin = trackHeaderRect.yMax;
var curvesContentRect = contentRect;
curvesContentRect.yMin = trackContentRect.yMax;
DrawInlineCurves(curvesHeaderRect, curvesContentRect, state);
}
DrawTrackColorKind(headerRect);
DrawTrackState(contentRect, contentRect, track);
}
void DrawInlineCurves(Rect curvesHeaderRect, Rect curvesContentRect, WindowState state)
{
if (!track.GetShowInlineCurves())
return;
// Inline curves are not within the editor window -- case 952571
if (!IsInlineCurvesEditorInBounds(ToWindowSpace(curvesHeaderRect), curvesContentRect.height, state))
{
m_InlineCurvesSkipped = true;
return;
}
// If inline curves were skipped during the last event; we want to avoid rendering them until
// the next Layout event. Otherwise, we still get the RTE prevented above when the user resizes
// the timeline window very fast. -- case 952571
if (m_InlineCurvesSkipped && Event.current.type != EventType.Layout)
return;
m_InlineCurvesSkipped = false;
if (inlineCurveEditor == null)
inlineCurveEditor = new InlineCurveEditor(this);
curvesHeaderRect.x += DirectorStyles.kBaseIndent;
curvesHeaderRect.width -= DirectorStyles.kBaseIndent;
inlineCurveEditor.Draw(curvesHeaderRect, curvesContentRect, state);
}
static bool IsInlineCurvesEditorInBounds(Rect windowSpaceTrackRect, float inlineCurveHeight, WindowState state)
{
var legalHeight = state.windowHeight;
var trackTop = windowSpaceTrackRect.y;
var inlineCurveOffset = windowSpaceTrackRect.height - inlineCurveHeight;
return legalHeight - trackTop - inlineCurveOffset > 0;
}
void DrawErrorIcon(Rect position, WindowState state)
{
Rect bindingLabel = position;
bindingLabel.x = position.xMax + 3;
bindingLabel.width = state.bindingAreaWidth;
EditorGUI.LabelField(position, m_ProblemIcon);
}
void DrawBackground(Rect trackRect, TrackAsset trackAsset, Vector2 visibleTime, WindowState state)
{
bool canDrawRecordBackground = IsRecording(state);
if (canDrawRecordBackground)
{
DrawRecordingTrackBackground(trackRect, trackAsset, visibleTime, state);
}
else
{
Color trackBackgroundColor;
if (SelectionManager.Contains(track))
{
trackBackgroundColor = state.IsEditingASubTimeline() ?
DirectorStyles.Instance.customSkin.colorTrackSubSequenceBackgroundSelected :
DirectorStyles.Instance.customSkin.colorTrackBackgroundSelected;
}
else
{
trackBackgroundColor = state.IsEditingASubTimeline() ?
DirectorStyles.Instance.customSkin.colorTrackSubSequenceBackground :
DirectorStyles.Instance.customSkin.colorTrackBackground;
}
EditorGUI.DrawRect(trackRect, trackBackgroundColor);
}
}
float InlineCurveHeight()
{
return track.GetShowInlineCurves() && CanDrawInlineCurve()
? TimelineWindowViewPrefs.GetInlineCurveHeight(track)
: 0.0f;
}
public override float GetHeight(WindowState state)
{
var height = GetTrackContentHeight(state);
if (CanDrawInlineCurve())
height += InlineCurveHeight();
return height;
}
float GetTrackContentHeight(WindowState state)
{
float height = m_TrackDrawOptions.minimumHeight;
if (height <= 0.0f)
height = TrackEditor.DefaultTrackHeight;
height = Mathf.Clamp(height, TrackEditor.MinimumTrackHeight, TrackEditor.MaximumTrackHeight);
return height * state.trackScale;
}
static bool CanDrawIcon(GUIContent icon)
{
return icon != null && icon != GUIContent.none && icon.image != null;
}
bool showSceneReference
{
get
{
return track != null &&
m_TrackDrawData.m_HasBinding &&
!m_TrackDrawData.m_IsSubTrack &&
m_TrackDrawData.m_Binding.sourceObject != null &&
m_TrackDrawData.m_Binding.outputTargetType != null &&
typeof(Object).IsAssignableFrom(m_TrackDrawData.m_Binding.outputTargetType);
}
}
void DrawTrackHeader(Rect trackHeaderRect, WindowState state)
{
using (new GUIViewportScope(trackHeaderRect))
{
Rect rect = trackHeaderRect;
DrawHeaderBackground(trackHeaderRect);
rect.x += m_Styles.trackSwatchStyle.fixedWidth;
const float buttonSize = WindowConstants.trackHeaderButtonSize;
const float padding = WindowConstants.trackHeaderButtonPadding;
var buttonRect = new Rect(trackHeaderRect.xMax - buttonSize - padding, rect.y + ((rect.height - buttonSize) / 2f), buttonSize, buttonSize);
rect.x += DrawTrackIconKind(rect, state);
DrawTrackBinding(rect, trackHeaderRect);
if (track is GroupTrack)
return;
buttonRect.x -= Spaced(DrawTrackDropDownMenu(buttonRect));
buttonRect.x -= Spaced(DrawLockMarkersButton(buttonRect, state));
buttonRect.x -= Spaced(DrawInlineCurveButton(buttonRect, state));
buttonRect.x -= Spaced(DrawMuteButton(buttonRect, state));
buttonRect.x -= Spaced(DrawLockButton(buttonRect, state));
buttonRect.x -= Spaced(DrawRecordButton(buttonRect, state));
buttonRect.x -= Spaced(DrawCustomTrackButton(buttonRect, state));
}
}
void DrawHeaderBackground(Rect headerRect)
{
Color backgroundColor = SelectionManager.Contains(track)
? DirectorStyles.Instance.customSkin.colorSelection
: DirectorStyles.Instance.customSkin.colorTrackHeaderBackground;
var bgRect = headerRect;
bgRect.x += m_Styles.trackSwatchStyle.fixedWidth;
bgRect.width -= m_Styles.trackSwatchStyle.fixedWidth;
EditorGUI.DrawRect(bgRect, backgroundColor);
}
void DrawTrackColorKind(Rect rect)
{
// subtracks don't draw the color, the parent does that.
if (track != null && track.isSubTrack)
return;
if (rect.width <= 0) return;
using (new GUIColorOverride(m_TrackDrawOptions.trackColor))
{
rect.width = m_Styles.trackSwatchStyle.fixedWidth;
GUI.Label(rect, GUIContent.none, m_Styles.trackSwatchStyle);
}
}
float DrawTrackIconKind(Rect rect, WindowState state)
{
// no icons on subtracks
if (track != null && track.isSubTrack)
return 0.0f;
rect.yMin += (rect.height - 16f) / 2f;
rect.width = 16.0f;
rect.height = 16.0f;
if (!string.IsNullOrEmpty(m_TrackDrawOptions.errorText))
{
m_ProblemIcon.image = Styles.kProblemIcon;
m_ProblemIcon.tooltip = m_TrackDrawOptions.errorText;
if (CanDrawIcon(m_ProblemIcon))
DrawErrorIcon(rect, state);
}
else
{
var content = GUIContent.Temp(m_TrackDrawData.m_TrackIcon, m_DefaultTrackIcon.tooltip);
if (CanDrawIcon(content))
GUI.Box(rect, content, GUIStyle.none);
}
return rect.width;
}
void DrawTrackBinding(Rect rect, Rect headerRect)
{
if (m_TrackDrawData.m_ShowTrackBindings)
{
DoTrackBindingGUI(rect, headerRect);
return;
}
var textStyle = m_Styles.trackHeaderFont;
textStyle.normal.textColor = SelectionManager.Contains(track) ? Color.white : m_Styles.customSkin.colorTrackFont;
string trackName = track.name;
EditorGUI.BeginChangeCheck();
// by default the size is just the width of the string (for selection purposes)
rect.width = m_Styles.trackHeaderFont.CalcSize(new GUIContent(trackName)).x;
// if we are editing, supply the entire width of the header
if (GUIUtility.keyboardControl == track.GetInstanceID())
rect.width = (headerRect.xMax - rect.xMin) - (5 * WindowConstants.trackHeaderButtonSize);
trackName = EditorGUI.DelayedTextField(rect, GUIContent.none, track.GetInstanceID(), track.name, textStyle);
if (EditorGUI.EndChangeCheck())
{
TimelineUndo.PushUndo(track, "Rename Track");
track.name = trackName;
}
}
float DrawTrackDropDownMenu(Rect rect)
{
rect.y += WindowConstants.trackOptionButtonVerticalPadding;
if (GUI.Button(rect, GUIContent.none, m_Styles.trackOptions))
{
// the drop down will apply to all selected tracks
if (!SelectionManager.Contains(track))
{
SelectionManager.Clear();
SelectionManager.Add(track);
}
SequencerContextMenu.ShowTrackContextMenu(SelectionManager.SelectedTracks().ToArray(), null);
}
return WindowConstants.trackHeaderButtonSize;
}
bool CanDrawInlineCurve()
{
// Note: A track with animatable parameters always has inline curves.
return trackHasAnimatableParameters || TimelineUtility.TrackHasAnimationCurves(track);
}
float DrawInlineCurveButton(Rect rect, WindowState state)
{
if (!CanDrawInlineCurve())
{
return 0.0f;
}
// Override enable state to display "Show Inline Curves" button in disabled state.
bool prevEnabledState = GUI.enabled;
GUI.enabled = true;
var newValue = GUI.Toggle(rect, track.GetShowInlineCurves(), GUIContent.none, DirectorStyles.Instance.curves);
GUI.enabled = prevEnabledState;
if (newValue != track.GetShowInlineCurves())
{
track.SetShowInlineCurves(newValue);
state.GetWindow().treeView.CalculateRowRects();
}
return WindowConstants.trackHeaderButtonSize;
}
float DrawRecordButton(Rect rect, WindowState state)
{
if (m_TrackDrawData.m_AllowsRecording)
{
bool isPlayerDisabled = state.editSequence.director != null && !state.editSequence.director.isActiveAndEnabled;
GameObject goBinding = m_TrackDrawData.m_TrackBinding as GameObject;
if (goBinding == null)
{
Component c = m_TrackDrawData.m_TrackBinding as Component;
if (c != null)
goBinding = c.gameObject;
}
if (goBinding == null && m_TrackDrawData.m_IsSubTrack)
{
goBinding = ParentTrack().GetGameObjectBinding(state.editSequence.director);
}
bool isTrackBindingValid = goBinding != null;
bool trackErrorDisableButton = !string.IsNullOrEmpty(m_TrackDrawOptions.errorText) && isTrackBindingValid && goBinding.activeInHierarchy;
bool disableButton = track.lockedInHierarchy || isPlayerDisabled || trackErrorDisableButton || !isTrackBindingValid;
using (new EditorGUI.DisabledScope(disableButton))
{
if (IsRecording(state))
{
state.editorWindow.Repaint();
float remainder = Time.realtimeSinceStartup % 1;
var animatedContent = s_ArmForRecordContentOn;
if (remainder < 0.22f)
{
animatedContent = GUIContent.none;
}
if (GUI.Button(rect, animatedContent, GUIStyle.none) || isPlayerDisabled || !isTrackBindingValid)
{
state.UnarmForRecord(track);
}
}
else
{
if (GUI.Button(rect, s_ArmForRecordContentOff, GUIStyle.none))
{
state.ArmForRecord(track);
}
}
return WindowConstants.trackHeaderButtonSize;
}
}
if (showTrackRecordingDisabled)
{
using (new EditorGUI.DisabledScope(true))
GUI.Button(rect, s_ArmForRecordDisabled, GUIStyle.none);
return k_ButtonSize;
}
return 0.0f;
}
float DrawCustomTrackButton(Rect rect, WindowState state)
{
if (drawer.DrawTrackHeaderButton(rect, track, state))
{
return WindowConstants.trackHeaderButtonSize;
}
return 0.0f;
}
float DrawLockMarkersButton(Rect rect, WindowState state)
{
if (track.GetMarkerCount() == 0)
return 0.0f;
var markersShown = showMarkers;
var style = TimelineWindow.styles.collapseMarkers;
if (Event.current.type == EventType.Repaint)
style.Draw(rect, GUIContent.none, false, false, markersShown, false);
// Override enable state to display "Show Marker" button in disabled state.
bool prevEnabledState = GUI.enabled;
GUI.enabled = true;
if (GUI.Button(rect, DirectorStyles.markerCollapseButton, GUIStyle.none))
{
state.GetWindow().SetShowTrackMarkers(track, !markersShown);
}
GUI.enabled = prevEnabledState;
return WindowConstants.trackHeaderButtonSize;
}
static void ObjectBindingField(Rect position, Object obj, PlayableBinding binding)
{
bool allowScene =
typeof(GameObject).IsAssignableFrom(binding.outputTargetType) ||
typeof(Component).IsAssignableFrom(binding.outputTargetType);
using (var check = new EditorGUI.ChangeCheckScope())
{
// FocusType.Passive so it never gets focused when pressing tab
int controlId = GUIUtility.GetControlID("s_ObjectFieldHash".GetHashCode(), FocusType.Passive, position);
var newObject = UnityEditorInternals.DoObjectField(EditorGUI.IndentedRect(position), obj, binding.outputTargetType, controlId, allowScene);
if (check.changed)
{
BindingUtility.Bind(TimelineEditor.inspectedDirector, binding.sourceObject as TrackAsset, newObject);
}
}
}
void DoTrackBindingGUI(Rect rect, Rect headerRect)
{
var bindingRect = new Rect(
rect.xMin,
rect.y + (rect.height - WindowConstants.trackHeaderButtonSize) / 2f,
headerRect.xMax - WindowConstants.trackHeaderMaxButtonsWidth - rect.xMin,
WindowConstants.trackHeaderButtonSize);
if (bindingRect.Contains(Event.current.mousePosition) && TimelineDragging.IsDraggingEvent() && DragAndDrop.objectReferences.Length == 1)
{
TimelineDragging.HandleBindingDragAndDrop(track, BindingUtility.GetRequiredBindingType(m_TrackDrawData.m_Binding));
Event.current.Use();
}
else
{
if (m_TrackDrawData.m_Binding.outputTargetType != null && typeof(Object).IsAssignableFrom(m_TrackDrawData.m_Binding.outputTargetType))
{
ObjectBindingField(bindingRect, m_TrackDrawData.m_TrackBinding, m_TrackDrawData.m_Binding);
}
}
}
bool IsRecording(WindowState state)
{
return state.recording && state.IsArmedForRecord(track);
}
// background to draw during recording
void DrawRecordingTrackBackground(Rect trackRect, TrackAsset trackAsset, Vector2 visibleTime, WindowState state)
{
if (drawer != null)
drawer.DrawRecordingBackground(trackRect, trackAsset, visibleTime, state);
}
void UpdateClipOverlaps()
{
TrackExtensions.ComputeBlendsFromOverlaps(track.clips);
}
internal void RebuildGUICacheIfNecessary()
{
if (m_TrackHash == track.Hash())
return;
m_ItemsDrawer = new TrackItemsDrawer(this);
m_TrackHash = track.Hash();
}
int BlendHash()
{
var hash = 0;
foreach (var clip in track.clips)
{
hash = HashUtility.CombineHash(hash,
(clip.duration - clip.start).GetHashCode(),
((int)clip.blendInCurveMode).GetHashCode(),
((int)clip.blendOutCurveMode).GetHashCode());
}
return hash;
}
// callback when the corresponding graph is rebuilt. This can happen, but not have the GUI rebuilt.
public override void OnGraphRebuilt()
{
RefreshCurveEditor();
}
void RefreshCurveEditor()
{
var window = TimelineWindow.instance;
if (track != null && window != null && window.state != null)
{
bool hasEditor = clipCurveEditor != null;
bool shouldHaveEditor = track.ShouldShowInfiniteClipEditor();
if (hasEditor != shouldHaveEditor)
window.state.AddEndFrameDelegate((x, currentEvent) =>
{
x.Refresh();
return true;
});
}
}
}
}
| 0 | 0.955295 | 1 | 0.955295 | game-dev | MEDIA | 0.8243 | game-dev | 0.883204 | 1 | 0.883204 |
smunaut/doom_riscv | 2,657 | src/d_event.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.
//
// DESCRIPTION:
//
//
//-----------------------------------------------------------------------------
#ifndef __D_EVENT__
#define __D_EVENT__
#include "doomtype.h"
//
// Event handling.
//
// Input event types.
typedef enum
{
ev_keydown,
ev_keyup,
ev_mouse,
ev_joystick
} evtype_t;
// Event structure.
typedef struct
{
evtype_t type;
int data1; // keys / mouse/joystick buttons
int data2; // mouse/joystick x move
int data3; // mouse/joystick y move
} event_t;
typedef enum
{
ga_nothing,
ga_loadlevel,
ga_newgame,
ga_loadgame,
ga_savegame,
ga_playdemo,
ga_completed,
ga_victory,
ga_worlddone,
ga_screenshot
} gameaction_t;
//
// Button/action code definitions.
//
typedef enum
{
// Press "Fire".
BT_ATTACK = 1,
// Use button, to open doors, activate switches.
BT_USE = 2,
// Flag: game events, not really buttons.
BT_SPECIAL = 128,
BT_SPECIALMASK = 3,
// Flag, weapon change pending.
// If true, the next 3 bits hold weapon num.
BT_CHANGE = 4,
// The 3bit weapon mask and shift, convenience.
BT_WEAPONMASK = (8+16+32),
BT_WEAPONSHIFT = 3,
// Pause the game.
BTS_PAUSE = 1,
// Save the game at each console.
BTS_SAVEGAME = 2,
// Savegame slot numbers
// occupy the second byte of buttons.
BTS_SAVEMASK = (4+8+16),
BTS_SAVESHIFT = 2,
} buttoncode_t;
//
// GLOBAL VARIABLES
//
#define MAXEVENTS 64
extern event_t events[MAXEVENTS];
extern int eventhead;
extern int eventtail;
extern gameaction_t gameaction;
#endif
//-----------------------------------------------------------------------------
//
// $Log:$
//
//-----------------------------------------------------------------------------
| 0 | 0.629024 | 1 | 0.629024 | game-dev | MEDIA | 0.913287 | game-dev | 0.607082 | 1 | 0.607082 |
narknon/FF7R2UProj | 8,278 | Source/EndDataObject/Public/EndDataTableBattleCharaSpec.h | #pragma once
#include "CoreMinimal.h"
#include "EndDataTableRowBase.h"
#include "EndDataTableBattleCharaSpec.generated.h"
USTRUCT(BlueprintType)
struct FEndDataTableBattleCharaSpec : public FEndDataTableRowBase {
GENERATED_BODY()
public:
private:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName CharaSpecID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FString TextLabel;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 MenuListSortKey;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 DeadDirection;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FString DeadTextLabel;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 EnemyCategory;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ParameterTableName;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 HPDirect;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 HP;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 BP;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float BurstTime;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName BurstCameraSequenceID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 PhysicsAttack;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 MagicAttack;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 PhysicsDefense;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 MagicDefense;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 PropertyResist0;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 PropertyResist1;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> AttributeResist_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> CactusMissionAttributeResist_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName BreakTableID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 BreakValueEndurance;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 RateDamageResist;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 FixDamageResist;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> BPDamageCorrectionProperty_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> BPDamageCorrectionAttribute_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 BreakDamageCorrectionType;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> StatusChangeResist_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> SpecialResist_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 PetrifyDamageLimit;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 KeepValue;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 TargetPriority;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName PossessionItemID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ResponseAreaDaylightID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ResponseAreaDarkID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ResponseAreaNoiseID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 CautionType;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 Hate;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float AbilityTargetCorrectionDirectionAngle;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FName> AbilityId_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName BeginBattleAbilityID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName AddBeginBattleAbilityID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<FName> PartsID_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName Shield;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName BCAName;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 ReactionTableIndex;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName HitReactionAbilityID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 HitReactionAbilityCountMin;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 HitReactionAbilityCountMax;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 HitReactionAbilityCountTypeBits;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<uint8> EffectiveValue_Array;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 CharacterKindID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName EnemyBookID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ReplaceTargetIconName;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ReplaceCameraLockSocketName;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
FName ReplaceDisplayNameSocketName;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float ReactionSensingRangeAngle;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float ReactionSensingRangeRadiusShort;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float ReactionSensingRangeRadiusMiddle;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float ReactionSensingRangeRadiusLong;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float ReactionSensingDamageNotifyReactionTime;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float ReactionSensingMovePredictionReactionTime;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 AIControllerIndex;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float OverrideRadius;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 LogCharacterType;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
uint8 OverrideDynamicBattleAreaSize;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float OverrideEncountForceBattleInCloseEnemiesSqrDist;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 FlagBit0;
public:
ENDDATAOBJECT_API FEndDataTableBattleCharaSpec();
};
| 0 | 0.878921 | 1 | 0.878921 | game-dev | MEDIA | 0.920379 | game-dev | 0.65798 | 1 | 0.65798 |
SolarMoonQAQ/Spark-Core | 1,727 | src/main/kotlin/cn/solarmoon/spark_core/animation/presets/DynamicStateAnimApplier.kt | package cn.solarmoon.spark_core.animation.presets
import cn.solarmoon.spark_core.event.ChangePresetAnimEvent
import net.neoforged.bus.api.SubscribeEvent
/**
* DynamicStateAnimApplier listens for entity state changes and applies registered animation overrides.
* This allows for dynamic replacement of default animations based on per-entity configurations managed
* by AnimStateMachineManager.
*/
object DynamicStateAnimApplier {
@SubscribeEvent
fun onEntityStateAnimationChange(event: ChangePresetAnimEvent.EntityUseState) {
// val entity = event.entity // event.entity is LivingEntity
// val state = event.state // This is an instance of a class like EntityStates.Idle, EntityStates.Walk, etc.
//
// // state.name is the key (String?) for the default animation for this state.
// // We use this key to check if there's an override registered for this entity and state.
// val animationStateKey = state.name
//
// if (animationStateKey != null) {
// // entity.id is available on LivingEntity (which extends Entity)
// val overrideAnimation = AnimStateMachineManager.getEntityAnimationOverride(entity.stringUUID, animationStateKey)
//
// if (overrideAnimation != null) {
// // An override TypedAnimation was found and is valid (checked within getEntityAnimationOverride).
// // Set it as the new animation to be played.
// event.newAnim = overrideAnimation
// }
// // If no override is found, or if the found override was invalid and removed,
// // the event proceeds with its original newAnim (usually the default animation for the state).
// }
}
} | 0 | 0.81782 | 1 | 0.81782 | game-dev | MEDIA | 0.922049 | game-dev | 0.813891 | 1 | 0.813891 |
ForestryMC/ForestryMC | 1,726 | src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.core.gui.widgets;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import forestry.core.gui.GuiUtil;
import forestry.core.gui.tooltips.ToolTip;
import forestry.core.utils.ItemTooltipUtil;
public abstract class ItemStackWidgetBase extends Widget {
public ItemStackWidgetBase(WidgetManager widgetManager, int xPos, int yPos) {
super(widgetManager, xPos, yPos);
}
protected abstract ItemStack getItemStack();
@Override
public void draw(int startX, int startY) {
ItemStack itemStack = getItemStack();
if (!itemStack.isEmpty()) {
RenderHelper.enableGUIStandardItemLighting();
GuiUtil.drawItemStack(manager.gui, itemStack, xPos + startX, yPos + startY);
RenderHelper.disableStandardItemLighting();
}
}
@SideOnly(Side.CLIENT)
@Override
public ToolTip getToolTip(int mouseX, int mouseY) {
ItemStack itemStack = getItemStack();
ToolTip tip = new ToolTip();
if (!itemStack.isEmpty()) {
tip.add(ItemTooltipUtil.getInformation(itemStack));
}
return tip;
}
}
| 0 | 0.723955 | 1 | 0.723955 | game-dev | MEDIA | 0.966301 | game-dev | 0.667782 | 1 | 0.667782 |
ashishps1/awesome-low-level-design | 3,622 | design-patterns/java/state/VendingMachineNaive.java | public class VendingMachineNaive {
private enum State {
IDLE,
ITEM_SELECTED,
HAS_MONEY,
DISPENSING
}
private State currentState = State.IDLE;
private String selectedItem = "";
private double insertedAmount = 0.0;
public void selectItem(String itemCode) {
switch (currentState) {
case IDLE:
selectedItem = itemCode;
System.out.println("Item '" + itemCode + "' selected. Please insert coin.");
currentState = State.ITEM_SELECTED;
break;
case ITEM_SELECTED:
System.out.println("Item already selected: '" + selectedItem + "'. Insert coin or cancel.");
break;
case HAS_MONEY:
System.out.println("Payment already received for item '" + selectedItem + "'. Dispense in progress.");
break;
case DISPENSING:
System.out.println("Cannot select new item. Currently dispensing.");
break;
}
}
public void insertCoin(double amount) {
switch (currentState) {
case IDLE:
System.out.println("No item selected. Please select an item before inserting coins.");
break;
case ITEM_SELECTED:
insertedAmount = amount;
System.out.println("Inserted $" + amount + " for item '" + selectedItem + "'. Ready to dispense.");
currentState = State.HAS_MONEY;
break;
case HAS_MONEY:
System.out.println("Money already inserted. Please wait or press dispense.");
break;
case DISPENSING:
System.out.println("Currently dispensing. Please wait.");
break;
}
}
public void dispenseItem() {
switch (currentState) {
case IDLE:
System.out.println("No item selected. Nothing to dispense.");
break;
case ITEM_SELECTED:
System.out.println("Please insert coin before dispensing.");
break;
case HAS_MONEY:
System.out.println("Dispensing item '" + selectedItem + "'...");
currentState = State.DISPENSING;
// Simulate delay and completion
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Item dispensed successfully.");
resetMachine();
break;
case DISPENSING:
System.out.println("Already dispensing. Please wait.");
break;
}
}
public void cancelTransaction() {
switch (currentState) {
case IDLE:
System.out.println("Nothing to cancel.");
break;
case ITEM_SELECTED:
System.out.println("Transaction cancelled. Returning to IDLE.");
resetMachine();
break;
case HAS_MONEY:
System.out.println("Transaction cancelled. Refunding $" + insertedAmount + ".");
resetMachine();
break;
case DISPENSING:
System.out.println("Cannot cancel. Item is being dispensed.");
break;
}
}
private void resetMachine() {
selectedItem = "";
insertedAmount = 0.0;
currentState = State.IDLE;
}
} | 0 | 0.774236 | 1 | 0.774236 | game-dev | MEDIA | 0.162918 | game-dev | 0.858205 | 1 | 0.858205 |
kmatheussen/radium | 29,129 | pluginhost/JuceLibraryCode/modules_old4/juce_box2d/box2d/Dynamics/b2World.cpp | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2World.h"
#include "b2Body.h"
#include "b2Fixture.h"
#include "b2Island.h"
#include "Joints/b2PulleyJoint.h"
#include "Contacts/b2Contact.h"
#include "Contacts/b2ContactSolver.h"
#include "../Collision/b2Collision.h"
#include "../Collision/b2BroadPhase.h"
#include "../Collision/Shapes/b2CircleShape.h"
#include "../Collision/Shapes/b2EdgeShape.h"
#include "../Collision/Shapes/b2ChainShape.h"
#include "../Collision/Shapes/b2PolygonShape.h"
#include "../Collision/b2TimeOfImpact.h"
#include "../Common/b2Draw.h"
#include "../Common/b2Timer.h"
#include <new>
b2World::b2World(const b2Vec2& gravity)
{
m_destructionListener = NULL;
m_debugDraw = NULL;
m_bodyList = NULL;
m_jointList = NULL;
m_bodyCount = 0;
m_jointCount = 0;
m_warmStarting = true;
m_continuousPhysics = true;
m_subStepping = false;
m_stepComplete = true;
m_allowSleep = true;
m_gravity = gravity;
m_flags = e_clearForces;
m_inv_dt0 = 0.0f;
m_contactManager.m_allocator = &m_blockAllocator;
memset(&m_profile, 0, sizeof(b2Profile));
}
b2World::~b2World()
{
// Some shapes allocate using b2Alloc.
b2Body* b = m_bodyList;
while (b)
{
b2Body* bNext = b->m_next;
b2Fixture* f = b->m_fixtureList;
while (f)
{
b2Fixture* fNext = f->m_next;
f->m_proxyCount = 0;
f->Destroy(&m_blockAllocator);
f = fNext;
}
b = bNext;
}
}
void b2World::SetDestructionListener(b2DestructionListener* listener)
{
m_destructionListener = listener;
}
void b2World::SetContactFilter(b2ContactFilter* filter)
{
m_contactManager.m_contactFilter = filter;
}
void b2World::SetContactListener(b2ContactListener* listener)
{
m_contactManager.m_contactListener = listener;
}
void b2World::SetDebugDraw(b2Draw* debugDraw)
{
m_debugDraw = debugDraw;
}
b2Body* b2World::CreateBody(const b2BodyDef* def)
{
b2Assert(IsLocked() == false);
if (IsLocked())
{
return NULL;
}
void* mem = m_blockAllocator.Allocate(sizeof(b2Body));
b2Body* b = new (mem) b2Body(def, this);
// Add to world doubly linked list.
b->m_prev = NULL;
b->m_next = m_bodyList;
if (m_bodyList)
{
m_bodyList->m_prev = b;
}
m_bodyList = b;
++m_bodyCount;
return b;
}
void b2World::DestroyBody(b2Body* b)
{
b2Assert(m_bodyCount > 0);
b2Assert(IsLocked() == false);
if (IsLocked())
{
return;
}
// Delete the attached joints.
b2JointEdge* je = b->m_jointList;
while (je)
{
b2JointEdge* je0 = je;
je = je->next;
if (m_destructionListener)
{
m_destructionListener->SayGoodbye(je0->joint);
}
DestroyJoint(je0->joint);
b->m_jointList = je;
}
b->m_jointList = NULL;
// Delete the attached contacts.
b2ContactEdge* ce = b->m_contactList;
while (ce)
{
b2ContactEdge* ce0 = ce;
ce = ce->next;
m_contactManager.Destroy(ce0->contact);
}
b->m_contactList = NULL;
// Delete the attached fixtures. This destroys broad-phase proxies.
b2Fixture* f = b->m_fixtureList;
while (f)
{
b2Fixture* f0 = f;
f = f->m_next;
if (m_destructionListener)
{
m_destructionListener->SayGoodbye(f0);
}
f0->DestroyProxies(&m_contactManager.m_broadPhase);
f0->Destroy(&m_blockAllocator);
f0->~b2Fixture();
m_blockAllocator.Free(f0, sizeof(b2Fixture));
b->m_fixtureList = f;
b->m_fixtureCount -= 1;
}
b->m_fixtureList = NULL;
b->m_fixtureCount = 0;
// Remove world body list.
if (b->m_prev)
{
b->m_prev->m_next = b->m_next;
}
if (b->m_next)
{
b->m_next->m_prev = b->m_prev;
}
if (b == m_bodyList)
{
m_bodyList = b->m_next;
}
--m_bodyCount;
b->~b2Body();
m_blockAllocator.Free(b, sizeof(b2Body));
}
b2Joint* b2World::CreateJoint(const b2JointDef* def)
{
b2Assert(IsLocked() == false);
if (IsLocked())
{
return NULL;
}
b2Joint* j = b2Joint::Create(def, &m_blockAllocator);
// Connect to the world list.
j->m_prev = NULL;
j->m_next = m_jointList;
if (m_jointList)
{
m_jointList->m_prev = j;
}
m_jointList = j;
++m_jointCount;
// Connect to the bodies' doubly linked lists.
j->m_edgeA.joint = j;
j->m_edgeA.other = j->m_bodyB;
j->m_edgeA.prev = NULL;
j->m_edgeA.next = j->m_bodyA->m_jointList;
if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA;
j->m_bodyA->m_jointList = &j->m_edgeA;
j->m_edgeB.joint = j;
j->m_edgeB.other = j->m_bodyA;
j->m_edgeB.prev = NULL;
j->m_edgeB.next = j->m_bodyB->m_jointList;
if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB;
j->m_bodyB->m_jointList = &j->m_edgeB;
b2Body* bodyA = def->bodyA;
b2Body* bodyB = def->bodyB;
// If the joint prevents collisions, then flag any contacts for filtering.
if (def->collideConnected == false)
{
b2ContactEdge* edge = bodyB->GetContactList();
while (edge)
{
if (edge->other == bodyA)
{
// Flag the contact for filtering at the next time step (where either
// body is awake).
edge->contact->FlagForFiltering();
}
edge = edge->next;
}
}
// Note: creating a joint doesn't wake the bodies.
return j;
}
void b2World::DestroyJoint(b2Joint* j)
{
b2Assert(IsLocked() == false);
if (IsLocked())
{
return;
}
bool collideConnected = j->m_collideConnected;
// Remove from the doubly linked list.
if (j->m_prev)
{
j->m_prev->m_next = j->m_next;
}
if (j->m_next)
{
j->m_next->m_prev = j->m_prev;
}
if (j == m_jointList)
{
m_jointList = j->m_next;
}
// Disconnect from island graph.
b2Body* bodyA = j->m_bodyA;
b2Body* bodyB = j->m_bodyB;
// Wake up connected bodies.
bodyA->SetAwake(true);
bodyB->SetAwake(true);
// Remove from body 1.
if (j->m_edgeA.prev)
{
j->m_edgeA.prev->next = j->m_edgeA.next;
}
if (j->m_edgeA.next)
{
j->m_edgeA.next->prev = j->m_edgeA.prev;
}
if (&j->m_edgeA == bodyA->m_jointList)
{
bodyA->m_jointList = j->m_edgeA.next;
}
j->m_edgeA.prev = NULL;
j->m_edgeA.next = NULL;
// Remove from body 2
if (j->m_edgeB.prev)
{
j->m_edgeB.prev->next = j->m_edgeB.next;
}
if (j->m_edgeB.next)
{
j->m_edgeB.next->prev = j->m_edgeB.prev;
}
if (&j->m_edgeB == bodyB->m_jointList)
{
bodyB->m_jointList = j->m_edgeB.next;
}
j->m_edgeB.prev = NULL;
j->m_edgeB.next = NULL;
b2Joint::Destroy(j, &m_blockAllocator);
b2Assert(m_jointCount > 0);
--m_jointCount;
// If the joint prevents collisions, then flag any contacts for filtering.
if (collideConnected == false)
{
b2ContactEdge* edge = bodyB->GetContactList();
while (edge)
{
if (edge->other == bodyA)
{
// Flag the contact for filtering at the next time step (where either
// body is awake).
edge->contact->FlagForFiltering();
}
edge = edge->next;
}
}
}
//
void b2World::SetAllowSleeping(bool flag)
{
if (flag == m_allowSleep)
{
return;
}
m_allowSleep = flag;
if (m_allowSleep == false)
{
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->SetAwake(true);
}
}
}
// Find islands, integrate and solve constraints, solve position constraints
void b2World::Solve(const b2TimeStep& step)
{
m_profile.solveInit = 0.0f;
m_profile.solveVelocity = 0.0f;
m_profile.solvePosition = 0.0f;
// Size the island for the worst case.
b2Island island(m_bodyCount,
m_contactManager.m_contactCount,
m_jointCount,
&m_stackAllocator,
m_contactManager.m_contactListener);
// Clear all the island flags.
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->m_flags &= ~b2Body::e_islandFlag;
}
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
{
c->m_flags &= ~b2Contact::e_islandFlag;
}
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
j->m_islandFlag = false;
}
// Build and simulate all awake islands.
int32 stackSize = m_bodyCount;
b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*));
for (b2Body* seed = m_bodyList; seed; seed = seed->m_next)
{
if (seed->m_flags & b2Body::e_islandFlag)
{
continue;
}
if (seed->IsAwake() == false || seed->IsActive() == false)
{
continue;
}
// The seed can be dynamic or kinematic.
if (seed->GetType() == b2_staticBody)
{
continue;
}
// Reset island and stack.
island.Clear();
int32 stackCount = 0;
stack[stackCount++] = seed;
seed->m_flags |= b2Body::e_islandFlag;
// Perform a depth first search (DFS) on the constraint graph.
while (stackCount > 0)
{
// Grab the next body off the stack and add it to the island.
b2Body* b = stack[--stackCount];
b2Assert(b->IsActive() == true);
island.Add(b);
// Make sure the body is awake.
b->SetAwake(true);
// To keep islands as small as possible, we don't
// propagate islands across static bodies.
if (b->GetType() == b2_staticBody)
{
continue;
}
// Search all contacts connected to this body.
for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next)
{
b2Contact* contact = ce->contact;
// Has this contact already been added to an island?
if (contact->m_flags & b2Contact::e_islandFlag)
{
continue;
}
// Is this contact solid and touching?
if (contact->IsEnabled() == false ||
contact->IsTouching() == false)
{
continue;
}
// Skip sensors.
bool sensorA = contact->m_fixtureA->m_isSensor;
bool sensorB = contact->m_fixtureB->m_isSensor;
if (sensorA || sensorB)
{
continue;
}
island.Add(contact);
contact->m_flags |= b2Contact::e_islandFlag;
b2Body* other = ce->other;
// Was the other body already added to this island?
if (other->m_flags & b2Body::e_islandFlag)
{
continue;
}
b2Assert(stackCount < stackSize);
stack[stackCount++] = other;
other->m_flags |= b2Body::e_islandFlag;
}
// Search all joints connect to this body.
for (b2JointEdge* je = b->m_jointList; je; je = je->next)
{
if (je->joint->m_islandFlag == true)
{
continue;
}
b2Body* other = je->other;
// Don't simulate joints connected to inactive bodies.
if (other->IsActive() == false)
{
continue;
}
island.Add(je->joint);
je->joint->m_islandFlag = true;
if (other->m_flags & b2Body::e_islandFlag)
{
continue;
}
b2Assert(stackCount < stackSize);
stack[stackCount++] = other;
other->m_flags |= b2Body::e_islandFlag;
}
}
b2Profile profile;
island.Solve(&profile, step, m_gravity, m_allowSleep);
m_profile.solveInit += profile.solveInit;
m_profile.solveVelocity += profile.solveVelocity;
m_profile.solvePosition += profile.solvePosition;
// Post solve cleanup.
for (int32 i = 0; i < island.m_bodyCount; ++i)
{
// Allow static bodies to participate in other islands.
b2Body* b = island.m_bodies[i];
if (b->GetType() == b2_staticBody)
{
b->m_flags &= ~b2Body::e_islandFlag;
}
}
}
m_stackAllocator.Free(stack);
{
b2Timer timer;
// Synchronize fixtures, check for out of range bodies.
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
// If a body was not in an island then it did not move.
if ((b->m_flags & b2Body::e_islandFlag) == 0)
{
continue;
}
if (b->GetType() == b2_staticBody)
{
continue;
}
// Update fixtures (for broad-phase).
b->SynchronizeFixtures();
}
// Look for new contacts.
m_contactManager.FindNewContacts();
m_profile.broadphase = timer.GetMilliseconds();
}
}
// Find TOI contacts and solve them.
void b2World::SolveTOI(const b2TimeStep& step)
{
b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener);
if (m_stepComplete)
{
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->m_flags &= ~b2Body::e_islandFlag;
b->m_sweep.alpha0 = 0.0f;
}
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
{
// Invalidate TOI
c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
c->m_toiCount = 0;
c->m_toi = 1.0f;
}
}
// Find TOI events and solve them.
for (;;)
{
// Find the first TOI.
b2Contact* minContact = NULL;
float32 minAlpha = 1.0f;
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
{
// Is this contact disabled?
if (c->IsEnabled() == false)
{
continue;
}
// Prevent excessive sub-stepping.
if (c->m_toiCount > b2_maxSubSteps)
{
continue;
}
float32 alpha = 1.0f;
if (c->m_flags & b2Contact::e_toiFlag)
{
// This contact has a valid cached TOI.
alpha = c->m_toi;
}
else
{
b2Fixture* fA = c->GetFixtureA();
b2Fixture* fB = c->GetFixtureB();
// Is there a sensor?
if (fA->IsSensor() || fB->IsSensor())
{
continue;
}
b2Body* bA = fA->GetBody();
b2Body* bB = fB->GetBody();
b2BodyType typeA = bA->m_type;
b2BodyType typeB = bB->m_type;
b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody);
bool activeA = bA->IsAwake() && typeA != b2_staticBody;
bool activeB = bB->IsAwake() && typeB != b2_staticBody;
// Is at least one body active (awake and dynamic or kinematic)?
if (activeA == false && activeB == false)
{
continue;
}
bool collideA = bA->IsBullet() || typeA != b2_dynamicBody;
bool collideB = bB->IsBullet() || typeB != b2_dynamicBody;
// Are these two non-bullet dynamic bodies?
if (collideA == false && collideB == false)
{
continue;
}
// Compute the TOI for this contact.
// Put the sweeps onto the same time interval.
float32 alpha0 = bA->m_sweep.alpha0;
if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0)
{
alpha0 = bB->m_sweep.alpha0;
bA->m_sweep.Advance(alpha0);
}
else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0)
{
alpha0 = bA->m_sweep.alpha0;
bB->m_sweep.Advance(alpha0);
}
b2Assert(alpha0 < 1.0f);
int32 indexA = c->GetChildIndexA();
int32 indexB = c->GetChildIndexB();
// Compute the time of impact in interval [0, minTOI]
b2TOIInput input;
input.proxyA.Set(fA->GetShape(), indexA);
input.proxyB.Set(fB->GetShape(), indexB);
input.sweepA = bA->m_sweep;
input.sweepB = bB->m_sweep;
input.tMax = 1.0f;
b2TOIOutput output;
b2TimeOfImpact(&output, &input);
// Beta is the fraction of the remaining portion of the .
float32 beta = output.t;
if (output.state == b2TOIOutput::e_touching)
{
alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f);
}
else
{
alpha = 1.0f;
}
c->m_toi = alpha;
c->m_flags |= b2Contact::e_toiFlag;
}
if (alpha < minAlpha)
{
// This is the minimum TOI found so far.
minContact = c;
minAlpha = alpha;
}
}
if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha)
{
// No more TOI events. Done!
m_stepComplete = true;
break;
}
// Advance the bodies to the TOI.
b2Fixture* fA = minContact->GetFixtureA();
b2Fixture* fB = minContact->GetFixtureB();
b2Body* bA = fA->GetBody();
b2Body* bB = fB->GetBody();
b2Sweep backup1 = bA->m_sweep;
b2Sweep backup2 = bB->m_sweep;
bA->Advance(minAlpha);
bB->Advance(minAlpha);
// The TOI contact likely has some new contact points.
minContact->Update(m_contactManager.m_contactListener);
minContact->m_flags &= ~b2Contact::e_toiFlag;
++minContact->m_toiCount;
// Is the contact solid?
if (minContact->IsEnabled() == false || minContact->IsTouching() == false)
{
// Restore the sweeps.
minContact->SetEnabled(false);
bA->m_sweep = backup1;
bB->m_sweep = backup2;
bA->SynchronizeTransform();
bB->SynchronizeTransform();
continue;
}
bA->SetAwake(true);
bB->SetAwake(true);
// Build the island
island.Clear();
island.Add(bA);
island.Add(bB);
island.Add(minContact);
bA->m_flags |= b2Body::e_islandFlag;
bB->m_flags |= b2Body::e_islandFlag;
minContact->m_flags |= b2Contact::e_islandFlag;
// Get contacts on bodyA and bodyB.
b2Body* bodies[2] = {bA, bB};
for (int32 i = 0; i < 2; ++i)
{
b2Body* body = bodies[i];
if (body->m_type == b2_dynamicBody)
{
for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
{
if (island.m_bodyCount == island.m_bodyCapacity)
{
break;
}
if (island.m_contactCount == island.m_contactCapacity)
{
break;
}
b2Contact* contact = ce->contact;
// Has this contact already been added to the island?
if (contact->m_flags & b2Contact::e_islandFlag)
{
continue;
}
// Only add static, kinematic, or bullet bodies.
b2Body* other = ce->other;
if (other->m_type == b2_dynamicBody &&
body->IsBullet() == false && other->IsBullet() == false)
{
continue;
}
// Skip sensors.
bool sensorA = contact->m_fixtureA->m_isSensor;
bool sensorB = contact->m_fixtureB->m_isSensor;
if (sensorA || sensorB)
{
continue;
}
// Tentatively advance the body to the TOI.
b2Sweep backup = other->m_sweep;
if ((other->m_flags & b2Body::e_islandFlag) == 0)
{
other->Advance(minAlpha);
}
// Update the contact points
contact->Update(m_contactManager.m_contactListener);
// Was the contact disabled by the user?
if (contact->IsEnabled() == false)
{
other->m_sweep = backup;
other->SynchronizeTransform();
continue;
}
// Are there contact points?
if (contact->IsTouching() == false)
{
other->m_sweep = backup;
other->SynchronizeTransform();
continue;
}
// Add the contact to the island
contact->m_flags |= b2Contact::e_islandFlag;
island.Add(contact);
// Has the other body already been added to the island?
if (other->m_flags & b2Body::e_islandFlag)
{
continue;
}
// Add the other body to the island.
other->m_flags |= b2Body::e_islandFlag;
if (other->m_type != b2_staticBody)
{
other->SetAwake(true);
}
island.Add(other);
}
}
}
b2TimeStep subStep;
subStep.dt = (1.0f - minAlpha) * step.dt;
subStep.inv_dt = 1.0f / subStep.dt;
subStep.dtRatio = 1.0f;
subStep.positionIterations = 20;
subStep.velocityIterations = step.velocityIterations;
subStep.warmStarting = false;
island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex);
// Reset island flags and synchronize broad-phase proxies.
for (int32 i = 0; i < island.m_bodyCount; ++i)
{
b2Body* body = island.m_bodies[i];
body->m_flags &= ~b2Body::e_islandFlag;
if (body->m_type != b2_dynamicBody)
{
continue;
}
body->SynchronizeFixtures();
// Invalidate all contact TOIs on this displaced body.
for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
{
ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
}
}
// Commit fixture proxy movements to the broad-phase so that new contacts are created.
// Also, some contacts can be destroyed.
m_contactManager.FindNewContacts();
if (m_subStepping)
{
m_stepComplete = false;
break;
}
}
}
void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations)
{
b2Timer stepTimer;
// If new fixtures were added, we need to find the new contacts.
if (m_flags & e_newFixture)
{
m_contactManager.FindNewContacts();
m_flags &= ~e_newFixture;
}
m_flags |= e_locked;
b2TimeStep step;
step.dt = dt;
step.velocityIterations = velocityIterations;
step.positionIterations = positionIterations;
if (dt > 0.0f)
{
step.inv_dt = 1.0f / dt;
}
else
{
step.inv_dt = 0.0f;
}
step.dtRatio = m_inv_dt0 * dt;
step.warmStarting = m_warmStarting;
// Update contacts. This is where some contacts are destroyed.
{
b2Timer timer;
m_contactManager.Collide();
m_profile.collide = timer.GetMilliseconds();
}
// Integrate velocities, solve velocity constraints, and integrate positions.
if (m_stepComplete && step.dt > 0.0f)
{
b2Timer timer;
Solve(step);
m_profile.solve = timer.GetMilliseconds();
}
// Handle TOI events.
if (m_continuousPhysics && step.dt > 0.0f)
{
b2Timer timer;
SolveTOI(step);
m_profile.solveTOI = timer.GetMilliseconds();
}
if (step.dt > 0.0f)
{
m_inv_dt0 = step.inv_dt;
}
if (m_flags & e_clearForces)
{
ClearForces();
}
m_flags &= ~e_locked;
m_profile.step = stepTimer.GetMilliseconds();
}
void b2World::ClearForces()
{
for (b2Body* body = m_bodyList; body; body = body->GetNext())
{
body->m_force.SetZero();
body->m_torque = 0.0f;
}
}
struct b2WorldQueryWrapper
{
bool QueryCallback(int32 proxyId)
{
b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId);
return callback->ReportFixture(proxy->fixture);
}
const b2BroadPhase* broadPhase;
b2QueryCallback* callback;
};
void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const
{
b2WorldQueryWrapper wrapper;
wrapper.broadPhase = &m_contactManager.m_broadPhase;
wrapper.callback = callback;
m_contactManager.m_broadPhase.Query(&wrapper, aabb);
}
struct b2WorldRayCastWrapper
{
float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId)
{
void* userData = broadPhase->GetUserData(proxyId);
b2FixtureProxy* proxy = (b2FixtureProxy*)userData;
b2Fixture* fixture = proxy->fixture;
int32 index = proxy->childIndex;
b2RayCastOutput output;
bool hit = fixture->RayCast(&output, input, index);
if (hit)
{
float32 fraction = output.fraction;
b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
return callback->ReportFixture(fixture, point, output.normal, fraction);
}
return input.maxFraction;
}
const b2BroadPhase* broadPhase;
b2RayCastCallback* callback;
};
void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const
{
b2WorldRayCastWrapper wrapper;
wrapper.broadPhase = &m_contactManager.m_broadPhase;
wrapper.callback = callback;
b2RayCastInput input;
input.maxFraction = 1.0f;
input.p1 = point1;
input.p2 = point2;
m_contactManager.m_broadPhase.RayCast(&wrapper, input);
}
void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color)
{
switch (fixture->GetType())
{
case b2Shape::e_circle:
{
b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
b2Vec2 center = b2Mul(xf, circle->m_p);
float32 radius = circle->m_radius;
b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f));
m_debugDraw->DrawSolidCircle(center, radius, axis, color);
}
break;
case b2Shape::e_edge:
{
b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
m_debugDraw->DrawSegment(v1, v2, color);
}
break;
case b2Shape::e_chain:
{
b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
int32 count = chain->m_count;
const b2Vec2* vertices = chain->m_vertices;
b2Vec2 v1 = b2Mul(xf, vertices[0]);
for (int32 i = 1; i < count; ++i)
{
b2Vec2 v2 = b2Mul(xf, vertices[i]);
m_debugDraw->DrawSegment(v1, v2, color);
m_debugDraw->DrawCircle(v1, 0.05f, color);
v1 = v2;
}
}
break;
case b2Shape::e_polygon:
{
b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
int32 vertexCount = poly->m_vertexCount;
b2Assert(vertexCount <= b2_maxPolygonVertices);
b2Vec2 vertices[b2_maxPolygonVertices];
for (int32 i = 0; i < vertexCount; ++i)
{
vertices[i] = b2Mul(xf, poly->m_vertices[i]);
}
m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color);
}
break;
default:
break;
}
}
void b2World::DrawJoint(b2Joint* joint)
{
b2Body* bodyA = joint->GetBodyA();
b2Body* bodyB = joint->GetBodyB();
const b2Transform& xf1 = bodyA->GetTransform();
const b2Transform& xf2 = bodyB->GetTransform();
b2Vec2 x1 = xf1.p;
b2Vec2 x2 = xf2.p;
b2Vec2 p1 = joint->GetAnchorA();
b2Vec2 p2 = joint->GetAnchorB();
b2Color color(0.5f, 0.8f, 0.8f);
switch (joint->GetType())
{
case e_distanceJoint:
m_debugDraw->DrawSegment(p1, p2, color);
break;
case e_pulleyJoint:
{
b2PulleyJoint* pulley = (b2PulleyJoint*)joint;
b2Vec2 s1 = pulley->GetGroundAnchorA();
b2Vec2 s2 = pulley->GetGroundAnchorB();
m_debugDraw->DrawSegment(s1, p1, color);
m_debugDraw->DrawSegment(s2, p2, color);
m_debugDraw->DrawSegment(s1, s2, color);
}
break;
case e_mouseJoint:
// don't draw this
break;
default:
m_debugDraw->DrawSegment(x1, p1, color);
m_debugDraw->DrawSegment(p1, p2, color);
m_debugDraw->DrawSegment(x2, p2, color);
}
}
void b2World::DrawDebugData()
{
if (m_debugDraw == NULL)
{
return;
}
uint32 flags = m_debugDraw->GetFlags();
if (flags & b2Draw::e_shapeBit)
{
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
const b2Transform& xf = b->GetTransform();
for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
{
if (b->IsActive() == false)
{
DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f));
}
else if (b->GetType() == b2_staticBody)
{
DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f));
}
else if (b->GetType() == b2_kinematicBody)
{
DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f));
}
else if (b->IsAwake() == false)
{
DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f));
}
else
{
DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f));
}
}
}
}
if (flags & b2Draw::e_jointBit)
{
for (b2Joint* j = m_jointList; j; j = j->GetNext())
{
DrawJoint(j);
}
}
if (flags & b2Draw::e_pairBit)
{
b2Color color(0.3f, 0.9f, 0.9f);
for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext())
{
//b2Fixture* fixtureA = c->GetFixtureA();
//b2Fixture* fixtureB = c->GetFixtureB();
//b2Vec2 cA = fixtureA->GetAABB().GetCenter();
//b2Vec2 cB = fixtureB->GetAABB().GetCenter();
//m_debugDraw->DrawSegment(cA, cB, color);
}
}
if (flags & b2Draw::e_aabbBit)
{
b2Color color(0.9f, 0.3f, 0.9f);
b2BroadPhase* bp = &m_contactManager.m_broadPhase;
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
if (b->IsActive() == false)
{
continue;
}
for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
{
for (int32 i = 0; i < f->m_proxyCount; ++i)
{
b2FixtureProxy* proxy = f->m_proxies + i;
b2AABB aabb = bp->GetFatAABB(proxy->proxyId);
b2Vec2 vs[4];
vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
m_debugDraw->DrawPolygon(vs, 4, color);
}
}
}
}
if (flags & b2Draw::e_centerOfMassBit)
{
for (b2Body* b = m_bodyList; b; b = b->GetNext())
{
b2Transform xf = b->GetTransform();
xf.p = b->GetWorldCenter();
m_debugDraw->DrawTransform(xf);
}
}
}
int32 b2World::GetProxyCount() const
{
return m_contactManager.m_broadPhase.GetProxyCount();
}
int32 b2World::GetTreeHeight() const
{
return m_contactManager.m_broadPhase.GetTreeHeight();
}
int32 b2World::GetTreeBalance() const
{
return m_contactManager.m_broadPhase.GetTreeBalance();
}
float32 b2World::GetTreeQuality() const
{
return m_contactManager.m_broadPhase.GetTreeQuality();
}
void b2World::Dump()
{
if ((m_flags & e_locked) == e_locked)
{
return;
}
b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y);
b2Log("m_world->SetGravity(g);\n");
b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount);
b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount);
int32 i = 0;
for (b2Body* b = m_bodyList; b; b = b->m_next)
{
b->m_islandIndex = i;
b->Dump();
++i;
}
i = 0;
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
j->m_index = i;
++i;
}
// First pass on joints, skip gear joints.
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
if (j->m_type == e_gearJoint)
{
continue;
}
b2Log("{\n");
j->Dump();
b2Log("}\n");
}
// Second pass on joints, only gear joints.
for (b2Joint* j = m_jointList; j; j = j->m_next)
{
if (j->m_type != e_gearJoint)
{
continue;
}
b2Log("{\n");
j->Dump();
b2Log("}\n");
}
b2Log("b2Free(joints);\n");
b2Log("b2Free(bodies);\n");
b2Log("joints = NULL;\n");
b2Log("bodies = NULL;\n");
}
| 0 | 0.972715 | 1 | 0.972715 | game-dev | MEDIA | 0.863419 | game-dev | 0.988995 | 1 | 0.988995 |
MTVehicles/MinetopiaVehicles | 3,200 | src/main/java/nl/mtvehicles/core/commands/vehiclesubs/VehicleHelp.java | package nl.mtvehicles.core.commands.vehiclesubs;
import nl.mtvehicles.core.Main;
import nl.mtvehicles.core.infrastructure.enums.Message;
import nl.mtvehicles.core.infrastructure.models.MTVSubCommand;
import nl.mtvehicles.core.infrastructure.modules.ConfigModule;
/**
* <b>/vehicle help</b> - list of all MTV commands.
*/
public class VehicleHelp extends MTVSubCommand {
public VehicleHelp() {
this.setPlayerCommand(true);
}
@Override
public boolean execute() {
sendMessage(String.format("&2&lMinetopiaVehicles Commands: (%s)", Main.instance.getDescription().getVersion()));
sendMessage("");
sendMessage(String.format("&2/vehicle &ainfo &f- &2%s", desc(Message.HELP_INFO)));
sendMessage(String.format("&2/vehicle &apublic &f- &2%s", desc(Message.HELP_PUBLIC)));
sendMessage(String.format("&2/vehicle &aprivate &f- &2%s", desc(Message.HELP_PRIVATE)));
sendMessage(String.format("&2/vehicle &aaddrider &f- &2%s", desc(Message.HELP_ADD_RIDER)));
sendMessage(String.format("&2/vehicle &aaddmember &f- &2%s", desc(Message.HELP_ADD_MEMBER)));
sendMessage(String.format("&2/vehicle &aremoverider &f- &2%s", desc(Message.HELP_REMOVE_RIDER)));
sendMessage(String.format("&2/vehicle &aremovemember &f- &2%s", desc(Message.HELP_REMOVE_MEMBER)));
sendMessage(String.format("&2/vehicle &abuy &f- &2%s", desc(Message.HELP_NEW_BUY)));
if (sender.hasPermission("mtvehicles.admin")) {
sendMessage("");
sendMessage(String.format("&2/vehicle &alanguage &f- &2%s", desc(Message.ADMIN_LANGUAGE)));
sendMessage(String.format("&2/vehicle &aversion &f- &2%s", desc(Message.ADMIN_VERSION)));
sendMessage(String.format("&2/vehicle &arefill &f- &2%s", desc(Message.ADMIN_REFILL)));
sendMessage(String.format("&2/vehicle &arepair &f- &2%s", desc(Message.ADMIN_REPAIR)));
sendMessage(String.format("&2/vehicle &aedit &f- &2%s", desc(Message.ADMIN_EDIT)));
sendMessage(String.format("&2/vehicle &amenu &f- &2%s", desc(Message.ADMIN_MENU)));
sendMessage(String.format("&2/vehicle &afuel &f- &2%s", desc(Message.ADMIN_FUEL)));
sendMessage(String.format("&2/vehicle &arestore &f- &2%s", desc(Message.ADMIN_RESTORE)));
sendMessage(String.format("&2/vehicle &areload &f- &2%s", desc(Message.ADMIN_RELOAD)));
sendMessage(String.format("&2/vehicle &agive &f- &2%s", desc(Message.ADMIN_NEW_GIVE)));
sendMessage(String.format("&2/vehicle &asetowner &f- &2%s", desc(Message.ADMIN_SETOWNER)));
sendMessage(String.format("&2/vehicle &aupdate &f- &2%s", desc(Message.ADMIN_UPDATE)));
sendMessage(String.format("&2/vehicle &adelete &f- &2%s", desc(Message.ADMIN_DELETE)));
sendMessage(String.format("&2/vehicle &agivefuel &f- &2%s", desc(Message.ADMIN_GIVEFUEL)));
}
sendMessage("");
sendMessage("&7&oDownload it for free at mtvehicles.nl (Maintained by Nikd0, gmrrh and Tiakin)");
return true;
}
private String desc(Message message){
return ConfigModule.messagesConfig.getMessage(message);
}
}
| 0 | 0.621904 | 1 | 0.621904 | game-dev | MEDIA | 0.359301 | game-dev | 0.67231 | 1 | 0.67231 |
SkelletonX/DDTank4.1 | 1,819 | Source Server/Game.Logic/PetEffects/RemoveAttackLv1.cs | using Game.Logic.Phy.Object;
using System;
namespace Game.Logic.PetEffects
{
public class RemoveAttackLv1 : BasePetEffect
{
private int int_0;
private int int_1;
private int int_2;
private int int_3;
private int int_4;
private int int_5;
private int int_6;
public RemoveAttackLv1(int count, int probability, int type, int skillId, int delay, string elementID) : base(ePetEffectType.RemoveAttackLv1, elementID)
{
this.int_1 = count;
this.int_4 = count;
this.int_2 = ((probability == -1) ? 10000 : probability);
this.int_0 = type;
this.int_3 = delay;
this.int_5 = skillId;
}
public override bool Start(Living living)
{
RemoveAttackLv1 aE = living.PetEffectList.GetOfType(ePetEffectType.RemoveAttackLv1) as RemoveAttackLv1;
if (aE != null)
{
aE.int_2 = ((this.int_2 > aE.int_2) ? this.int_2 : aE.int_2);
return true;
}
return base.Start(living);
}
protected override void OnAttachedToPlayer(Player player)
{
player.PlayerBuffSkillPet += new PlayerEventHandle(this.method_0);
}
protected override void OnRemovedFromPlayer(Player player)
{
player.PlayerBuffSkillPet -= new PlayerEventHandle(this.method_0);
}
private void method_0(Player player_0)
{
if (player_0.PetEffects.CurrentUseSkill == this.int_5)
{
player_0.AddPetEffect(new RemoveAttackLv1A(2, this.int_2, this.int_0, this.int_5, this.int_3, base.Info.ID.ToString()), 0);
Console.WriteLine("REMOVE 20% ATTACK");
}
}
}
}
| 0 | 0.811389 | 1 | 0.811389 | game-dev | MEDIA | 0.915933 | game-dev | 0.657728 | 1 | 0.657728 |
Pomax/Pjs-2D-Game-Engine | 3,088 | docs/tutorial/sketches/mario/sketch08.pde | final int screenWidth = 512;
final int screenHeight = 432;
float DOWN_FORCE = 2;
float ACCELERATION = 1.3;
float DAMPENING = 0.75;
void initialize() {
frameRate(30);
addScreen("level", new MarioLevel(4*width, height));
}
class MarioLevel extends Level {
MarioLevel(float levelWidth, float levelHeight) {
super(levelWidth, levelHeight);
setViewBox(0,0,screenWidth,screenHeight);
addLevelLayer("layer", new MarioLayer(this));
}
}
class MarioLayer extends LevelLayer {
Mario mario;
MarioLayer(Level owner) {
super(owner);
setBackgroundColor(color(0, 100, 190));
addBackgroundSprite(new TilingSprite(new Sprite("graphics/backgrounds/sky.gif"),0,0,width,height));
addBoundary(new Boundary(0,height-48,width,height-48));
addBoundary(new Boundary(-1,0, -1,height));
addBoundary(new Boundary(width+1,height, width+1,0));
showBoundaries = true;
mario = new Mario(32, height-64);
addPlayer(mario);
addGround("ground", -32,height-48, width+32,height);
}
/**
* Add some ground.
*/
void addGround(String tileset, float x1, float y1, float x2, float y2) {
TilingSprite groundline = new TilingSprite(new Sprite("graphics/backgrounds/"+tileset+"-top.gif"), x1,y1,x2,y1+16);
addBackgroundSprite(groundline);
TilingSprite groundfiller = new TilingSprite(new Sprite("graphics/backgrounds/"+tileset+"-filler.gif"), x1,y1+16,x2,y2);
addBackgroundSprite(groundfiller);
addBoundary(new Boundary(x1,y1,x2,y1));
}
void draw() {
super.draw();
viewbox.track(parent, mario);
}
}
class Mario extends Player {
float speed = 2;
Mario(float x, float y) {
super("Mario");
setupStates();
setPosition(x,y);
handleKey('W');
handleKey('A');
handleKey('D');
setForces(0,DOWN_FORCE);
setAcceleration(0,ACCELERATION);
setImpulseCoefficients(DAMPENING,DAMPENING);
}
void setupStates() {
addState(new State("idle", "graphics/mario/small/Standing-mario.gif"));
addState(new State("running", "graphics/mario/small/Running-mario.gif", 1, 4));
State dead = new State("dead", "graphics/mario/small/Dead-mario.gif", 1, 2);
dead.setAnimationSpeed(0.25);
dead.setDuration(100);
addState(dead);
State jumping = new State("jumping", "graphics/mario/small/Jumping-mario.gif");
jumping.setDuration(15);
addState(jumping);
setCurrentState("idle");
}
void handleStateFinished(State which) {
setCurrentState("idle");
}
void handleInput() {
if(isKeyDown('A') || isKeyDown('D')) {
if (isKeyDown('A')) {
setHorizontalFlip(true);
addImpulse(-speed, 0);
}
if (isKeyDown('D')) {
setHorizontalFlip(false);
addImpulse(speed, 0);
}
}
if(isKeyDown('W') && active.name!="jumping" && boundaries.size()>0) {
addImpulse(0,-35);
setCurrentState("jumping");
}
if (active.mayChange()) {
if(isKeyDown('A') || isKeyDown('D')) {
setCurrentState("running");
}
else { setCurrentState("idle"); }
}
}
} | 0 | 0.556908 | 1 | 0.556908 | game-dev | MEDIA | 0.892825 | game-dev | 0.964347 | 1 | 0.964347 |
Return-To-The-Roots/s25client | 5,804 | libs/s25main/figures/nofWarehouseWorker.cpp | // Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org)
//
// SPDX-License-Identifier: GPL-2.0-or-later
#include "nofWarehouseWorker.h"
#include "EventManager.h"
#include "GamePlayer.h"
#include "SerializedGameData.h"
#include "Ware.h"
#include "buildings/nobBaseWarehouse.h"
#include "random/Random.h"
#include "world/GameWorld.h"
#include "nodeObjs/noFlag.h"
#include "nodeObjs/noRoadNode.h"
nofWarehouseWorker::nofWarehouseWorker(const MapPoint pos, const unsigned char player, std::unique_ptr<Ware> ware,
const bool task)
: noFigure(Job::Helper, pos, player, world->GetSpecObj<noFlag>(world->GetNeighbour(pos, Direction::SouthEast))),
carried_ware(std::move(ware)), shouldBringWareIn(task), fat((RANDOM_RAND(2)) != 0)
{
// Zur Inventur hinzufügen, sind ja sonst nicht registriert
world->GetPlayer(player).IncreaseInventoryJob(Job::Helper, 1);
/// Straße (also die 1-er-Straße vor dem Lagerhaus) setzen
cur_rs = static_cast<noFlag*>(GetGoal())->GetRoute(Direction::NorthWest);
RTTR_Assert(cur_rs->GetLength() == 1);
rs_dir = true;
}
nofWarehouseWorker::~nofWarehouseWorker() = default;
void nofWarehouseWorker::Destroy()
{
// Ware vernichten (abmelden)
RTTR_Assert(!carried_ware); // TODO Check if this holds true and remove the LooseWare below
LooseWare();
}
void nofWarehouseWorker::Serialize(SerializedGameData& sgd) const
{
noFigure::Serialize(sgd);
sgd.PushObject(carried_ware, true);
sgd.PushBool(shouldBringWareIn);
sgd.PushBool(fat);
}
nofWarehouseWorker::nofWarehouseWorker(SerializedGameData& sgd, const unsigned obj_id)
: noFigure(sgd, obj_id), carried_ware(sgd.PopObject<Ware>(GO_Type::Ware)), shouldBringWareIn(sgd.PopBool()),
fat(sgd.PopBool())
{}
void nofWarehouseWorker::Draw(DrawPoint drawPt)
{
// Trage ich ne Ware oder nicht?
if(carried_ware)
DrawWalkingCarrier(drawPt, carried_ware->type, fat);
else
DrawWalkingCarrier(drawPt, boost::none, fat);
}
void nofWarehouseWorker::GoalReached()
{
const nobBaseWarehouse* wh = world->GetSpecObj<nobBaseWarehouse>(world->GetNeighbour(pos, Direction::NorthWest));
if(!shouldBringWareIn)
{
// Ware an der Fahne ablegen ( wenn noch genug Platz ist, 8 max pro Flagge!)
// außerdem ggf. Waren wieder mit reinnehmen, deren Ziel zerstört wurde
// ( dann ist goal = location )
if(world->GetSpecObj<noFlag>(pos)->HasSpaceForWare() && carried_ware->GetGoal() != carried_ware->GetLocation()
&& carried_ware->GetGoal() != wh)
{
carried_ware->WaitAtFlag(world->GetSpecObj<noFlag>(pos));
// Ware soll ihren weiteren Weg berechnen
carried_ware->RecalcRoute();
// Ware ablegen
world->GetSpecObj<noFlag>(pos)->AddWare(std::move(carried_ware));
} else
// ansonsten Ware wieder mit reinnehmen
carried_ware->Carry(world->GetSpecObj<noRoadNode>(world->GetNeighbour(pos, Direction::NorthWest)));
} else
{
// Ware aufnehmen
carried_ware = world->GetSpecObj<noFlag>(pos)->SelectWare(Direction::NorthWest, false, this);
if(carried_ware)
carried_ware->Carry(world->GetSpecObj<noRoadNode>(world->GetNeighbour(pos, Direction::NorthWest)));
}
// Wieder ins Schloss gehen
StartWalking(Direction::NorthWest);
InitializeRoadWalking(wh->GetRoute(Direction::SouthEast), 0, false);
}
void nofWarehouseWorker::Walked()
{
// Wieder im Schloss angekommen
if(!shouldBringWareIn)
{
// If I still cary a ware than either the flag was full or I should not bring it there (goal=warehouse or goal
// destroyed -> goal=location) So re-add it to waiting wares or to inventory
if(carried_ware)
{
// Ware ins Lagerhaus einlagern (falls es noch existiert und nicht abgebrannt wurde)
if(world->GetNO(pos)->GetType() == NodalObjectType::Building)
{
auto* wh = world->GetSpecObj<nobBaseWarehouse>(pos);
if(carried_ware->GetGoal() == carried_ware->GetLocation() || carried_ware->GetGoal() == wh)
wh->AddWare(std::move(carried_ware));
else
wh->AddWaitingWare(std::move(carried_ware));
} else
{
// Lagerhaus abgebrannt --> Ware vernichten
LooseWare();
}
// Ich trage keine Ware mehr
RTTR_Assert(carried_ware == nullptr);
}
} else
{
if(carried_ware)
{
// Ware ins Lagerhaus einlagern (falls es noch existiert und nicht abgebrannt wurde)
if(world->GetNO(pos)->GetType() == NodalObjectType::Building)
world->GetSpecObj<nobBaseWarehouse>(pos)->AddWare(std::move(carried_ware));
else
{
// Lagerhaus abgebrannt --> Ware vernichten
LooseWare();
}
// Ich trage keine Ware mehr
RTTR_Assert(carried_ware == nullptr);
}
}
// dann mich killen
GetEvMgr().AddToKillList(world->RemoveFigure(pos, *this));
// Von der Inventur wieder abziehen
world->GetPlayer(player).DecreaseInventoryJob(Job::Helper, 1);
}
void nofWarehouseWorker::AbrogateWorkplace()
{
LooseWare();
StartWandering();
}
void nofWarehouseWorker::LooseWare()
{
// Wenn ich noch ne Ware in der Hand habe, muss die gelöscht werden
if(carried_ware)
{
carried_ware->WareLost(player);
carried_ware->Destroy();
carried_ware.reset();
}
}
void nofWarehouseWorker::HandleDerivedEvent(const unsigned /*id*/) {}
void nofWarehouseWorker::CarryWare(Ware* /*ware*/) {}
| 0 | 0.984037 | 1 | 0.984037 | game-dev | MEDIA | 0.847848 | game-dev | 0.940426 | 1 | 0.940426 |
Dark-Basic-Software-Limited/AGKRepo | 4,561 | AGK/AgkIde/bullet/BulletCollision/CollisionShapes/btTriangleShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_OBB_TRIANGLE_MINKOWSKI_H
#define BT_OBB_TRIANGLE_MINKOWSKI_H
#include "btConvexShape.h"
#include "btBoxShape.h"
ATTRIBUTE_ALIGNED16(class) btTriangleShape : public btPolyhedralConvexShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btVector3 m_vertices1[3];
virtual int getNumVertices() const
{
return 3;
}
btVector3& getVertexPtr(int index)
{
return m_vertices1[index];
}
const btVector3& getVertexPtr(int index) const
{
return m_vertices1[index];
}
virtual void getVertex(int index,btVector3& vert) const
{
vert = m_vertices1[index];
}
virtual int getNumEdges() const
{
return 3;
}
virtual void getEdge(int i,btVector3& pa,btVector3& pb) const
{
getVertex(i,pa);
getVertex((i+1)%3,pb);
}
virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax)const
{
// btAssert(0);
getAabbSlow(t,aabbMin,aabbMax);
}
btVector3 localGetSupportingVertexWithoutMargin(const btVector3& dir)const
{
btVector3 dots = dir.dot3(m_vertices1[0], m_vertices1[1], m_vertices1[2]);
return m_vertices1[dots.maxAxis()];
}
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
for (int i=0;i<numVectors;i++)
{
const btVector3& dir = vectors[i];
btVector3 dots = dir.dot3(m_vertices1[0], m_vertices1[1], m_vertices1[2]);
supportVerticesOut[i] = m_vertices1[dots.maxAxis()];
}
}
btTriangleShape() : btPolyhedralConvexShape ()
{
m_shapeType = TRIANGLE_SHAPE_PROXYTYPE;
}
btTriangleShape(const btVector3& p0,const btVector3& p1,const btVector3& p2) : btPolyhedralConvexShape ()
{
m_shapeType = TRIANGLE_SHAPE_PROXYTYPE;
m_vertices1[0] = p0;
m_vertices1[1] = p1;
m_vertices1[2] = p2;
}
virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i) const
{
getPlaneEquation(i,planeNormal,planeSupport);
}
virtual int getNumPlanes() const
{
return 1;
}
void calcNormal(btVector3& normal) const
{
normal = (m_vertices1[1]-m_vertices1[0]).cross(m_vertices1[2]-m_vertices1[0]);
normal.normalize();
}
virtual void getPlaneEquation(int i, btVector3& planeNormal,btVector3& planeSupport) const
{
(void)i;
calcNormal(planeNormal);
planeSupport = m_vertices1[0];
}
virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const
{
(void)mass;
btAssert(0);
inertia.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
}
virtual bool isInside(const btVector3& pt,btScalar tolerance) const
{
btVector3 normal;
calcNormal(normal);
//distance to plane
btScalar dist = pt.dot(normal);
btScalar planeconst = m_vertices1[0].dot(normal);
dist -= planeconst;
if (dist >= -tolerance && dist <= tolerance)
{
//inside check on edge-planes
int i;
for (i=0;i<3;i++)
{
btVector3 pa,pb;
getEdge(i,pa,pb);
btVector3 edge = pb-pa;
btVector3 edgeNormal = edge.cross(normal);
edgeNormal.normalize();
btScalar dist = pt.dot( edgeNormal);
btScalar edgeConst = pa.dot(edgeNormal);
dist -= edgeConst;
if (dist < -tolerance)
return false;
}
return true;
}
return false;
}
//debugging
virtual const char* getName()const
{
return "Triangle";
}
virtual int getNumPreferredPenetrationDirections() const
{
return 2;
}
virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const
{
calcNormal(penetrationVector);
if (index)
penetrationVector *= btScalar(-1.);
}
};
#endif //BT_OBB_TRIANGLE_MINKOWSKI_H
| 0 | 0.935338 | 1 | 0.935338 | game-dev | MEDIA | 0.982759 | game-dev | 0.99391 | 1 | 0.99391 |
SkyblockerMod/Skyblocker | 6,825 | src/main/java/de/hysky/skyblocker/SkyblockerScreen.java | package de.hysky.skyblocker;
import de.hysky.skyblocker.annotations.Init;
import de.hysky.skyblocker.config.SkyblockerConfigManager;
import de.hysky.skyblocker.skyblock.Tips;
import de.hysky.skyblocker.utils.scheduler.Scheduler;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gl.RenderPipelines;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.ConfirmLinkScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.*;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.OrderedText;
import net.minecraft.text.StringVisitable;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.Language;
import java.time.LocalDate;
public class SkyblockerScreen extends Screen {
private static final int SPACING = 8;
private static final int BUTTON_WIDTH = 210;
private static final int HALF_BUTTON_WIDTH = 101; //Same as (210 - 8) / 2
private static final Text TITLE;
private static final Identifier ICON;
private static final Text CONFIGURATION_TEXT = Text.translatable("text.skyblocker.config");
private static final Text SOURCE_TEXT = Text.translatable("text.skyblocker.source");
private static final Text REPORT_BUGS_TEXT = Text.translatable("menu.reportBugs");
private static final Text WEBSITE_TEXT = Text.translatable("text.skyblocker.website");
private static final Text TRANSLATE_TEXT = Text.translatable("text.skyblocker.translate");
private static final Text MODRINTH_TEXT = Text.translatable("text.skyblocker.modrinth");
private static final Text DISCORD_TEXT = Text.translatable("text.skyblocker.discord");
private ThreePartsLayoutWidget layout;
private MultilineTextWidget tip;
static {
LocalDate date = LocalDate.now();
if (date.getMonthValue() == 4 && date.getDayOfMonth() == 1) {
TITLE = Text.literal("Skibidiblocker " + SkyblockerMod.VERSION);
ICON = SkyblockerMod.id("icons.png");
} else {
TITLE = Text.literal("Skyblocker " + SkyblockerMod.VERSION);
ICON = SkyblockerMod.id("icon.png");
}
}
public SkyblockerScreen() {
super(TITLE);
}
@Init
public static void initClass() {
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
dispatcher.register(ClientCommandManager.literal(SkyblockerMod.NAMESPACE)
.executes(Scheduler.queueOpenScreenCommand(SkyblockerScreen::new)));
});
}
@Override
protected void init() {
this.layout = new ThreePartsLayoutWidget(this, 50, 100);
this.layout.addHeader(new IconTextWidget(this.getTitle(), this.textRenderer, ICON));
GridWidget gridWidget = this.layout.addBody(new GridWidget()).setSpacing(SPACING);
gridWidget.getMainPositioner().alignHorizontalCenter();
GridWidget.Adder adder = gridWidget.createAdder(2);
adder.add(ButtonWidget.builder(CONFIGURATION_TEXT, button -> this.openConfig()).width(BUTTON_WIDTH).build(), 2);
adder.add(ButtonWidget.builder(SOURCE_TEXT, ConfirmLinkScreen.opening(this, "https://github.com/SkyblockerMod/Skyblocker")).width(HALF_BUTTON_WIDTH).build());
adder.add(ButtonWidget.builder(REPORT_BUGS_TEXT, ConfirmLinkScreen.opening(this, "https://github.com/SkyblockerMod/Skyblocker/issues")).width(HALF_BUTTON_WIDTH).build());
adder.add(ButtonWidget.builder(WEBSITE_TEXT, ConfirmLinkScreen.opening(this, "https://hysky.de/")).width(HALF_BUTTON_WIDTH).build());
adder.add(ButtonWidget.builder(TRANSLATE_TEXT, ConfirmLinkScreen.opening(this, "https://translate.hysky.de/")).width(HALF_BUTTON_WIDTH).build());
adder.add(ButtonWidget.builder(MODRINTH_TEXT, ConfirmLinkScreen.opening(this, "https://modrinth.com/mod/skyblocker-liap")).width(HALF_BUTTON_WIDTH).build());
adder.add(ButtonWidget.builder(DISCORD_TEXT, ConfirmLinkScreen.opening(this, "https://discord.gg/aNNJHQykck")).width(HALF_BUTTON_WIDTH).build());
adder.add(ButtonWidget.builder(ScreenTexts.DONE, button -> this.close()).width(BUTTON_WIDTH).build(), 2);
GridWidget footerGridWidget = this.layout.addFooter(new GridWidget()).setSpacing(SPACING).setRowSpacing(0);
footerGridWidget.getMainPositioner().alignHorizontalCenter();
GridWidget.Adder footerAdder = footerGridWidget.createAdder(2);
footerAdder.add(tip = new MultilineTextWidget(Tips.nextTip(), this.textRenderer).setCentered(true).setMaxWidth((int) (this.width * 0.7)), 2);
footerAdder.add(ButtonWidget.builder(Text.translatable("skyblocker.tips.previous"), button -> {
tip.setMessage(Tips.previousTip());
layout.refreshPositions();
}).build());
footerAdder.add(ButtonWidget.builder(Text.translatable("skyblocker.tips.next"), button -> {
tip.setMessage(Tips.nextTip());
layout.refreshPositions();
}).build());
this.layout.refreshPositions();
this.layout.forEachChild(this::addDrawableChild);
}
@Override
protected void refreshWidgetPositions() {
super.refreshWidgetPositions();
this.layout.refreshPositions();
}
private void openConfig() {
this.client.setScreen(SkyblockerConfigManager.createGUI(this));
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
super.render(context, mouseX, mouseY, delta);
}
private static class IconTextWidget extends TextWidget {
private final Identifier icon;
IconTextWidget(Text message, TextRenderer textRenderer, Identifier icon) {
super(message, textRenderer);
this.icon = icon;
}
@Override
public void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
Text text = this.getMessage();
TextRenderer textRenderer = this.getTextRenderer();
int width = this.getWidth();
int textWidth = textRenderer.getWidth(text);
float horizontalAlignment = 0.5f; // default
//17 = (32 + 2) / 2 • 32 + 2 is the width of the icon + spacing between icon and text
int x = this.getX() + 17 + Math.round(horizontalAlignment * (float) (width - textWidth));
int y = this.getY() + (this.getHeight() - textRenderer.fontHeight) / 2;
OrderedText orderedText = textWidth > width ? this.trim(text, width) : text.asOrderedText();
int iconX = x - 34;
int iconY = y - 13;
context.drawTextWithShadow(textRenderer, orderedText, x, y, this.getTextColor());
context.drawTexture(RenderPipelines.GUI_TEXTURED, this.icon, iconX, iconY, 0, 0, 32, 32, 32, 32);
}
private OrderedText trim(Text text, int width) {
TextRenderer textRenderer = this.getTextRenderer();
StringVisitable stringVisitable = textRenderer.trimToWidth(text, width - textRenderer.getWidth(ScreenTexts.ELLIPSIS));
return Language.getInstance().reorder(StringVisitable.concat(stringVisitable, ScreenTexts.ELLIPSIS));
}
}
}
| 0 | 0.909051 | 1 | 0.909051 | game-dev | MEDIA | 0.591494 | game-dev | 0.960203 | 1 | 0.960203 |
Swofty-Developments/HypixelSkyBlock | 2,018 | type.skyblockgeneric/src/main/java/net/swofty/type/skyblockgeneric/data/datapoints/DatapointIntegerList.java | package net.swofty.type.skyblockgeneric.data.datapoints;
import net.swofty.commons.protocol.Serializer;
import net.swofty.type.skyblockgeneric.data.SkyBlockDatapoint;
import java.util.ArrayList;
import java.util.List;
public class DatapointIntegerList extends SkyBlockDatapoint<List<Integer>> {
public DatapointIntegerList(String key, ArrayList<Integer> value) {
super(key, value, new Serializer<>() {
@Override
public String serialize(List<Integer> value) {
ArrayList<String> list = new ArrayList<>(value.size());
for (Integer i : value)
list.add(String.valueOf(i));
return String.join(",", list);
}
@Override
public List<Integer> deserialize(String json) {
if (json.isEmpty())
return new ArrayList<>();
String[] split = json.split(",");
ArrayList<Integer> list = new ArrayList<>(split.length);
for (String s : split)
list.add(Integer.parseInt(s));
return list;
}
@Override
public List<Integer> clone(List<Integer> value) {
return new ArrayList<>(value);
}
});
}
public DatapointIntegerList(String key) {
this(key, new ArrayList<>());
}
public void add(Integer value) {
List<Integer> current = getValue();
current.add(value);
setValue(current);
}
public void remove(Integer value) {
List<Integer> current = getValue();
current.remove(value);
setValue(current);
}
public boolean has(Integer value) {
return getValue().contains(value);
}
/**
* @param value
* @return true if it was added, false if it wasn't
*/
public boolean hasOrAdd(Integer value) {
if (has(value))
return false;
add(value);
return true;
}
}
| 0 | 0.642887 | 1 | 0.642887 | game-dev | MEDIA | 0.293709 | game-dev | 0.748516 | 1 | 0.748516 |
VirtueSky/sunflower | 5,083 | VirtueSky/Localization/Runtime/Locale.cs | using System;
using System.Linq;
using UnityEngine;
using VirtueSky.DataStorage;
namespace VirtueSky.Localization
{
public sealed class Locale
{
private static Locale instance;
private Language _currentLanguage = Language.English;
/// <summary>
/// Raised when <see cref="CurrentLanguage"/> has been changed.
/// </summary>
private event EventHandler<LocaleChangedEventArgs> OnLocaleChangedEvent;
private static Locale Instance
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
Debug.LogError("Locale only avaiable when application playing!");
return null;
}
#endif
if (instance == null)
{
instance = new Locale();
instance.SetDefaultLanguage();
}
return instance;
}
}
public static Language CurrentLanguage
{
get => Instance._currentLanguage;
set
{
if (Instance._currentLanguage != value)
{
Instance._currentLanguage = value;
SetCurrentLanguageCode(value);
var oldValue = Instance._currentLanguage;
Instance._currentLanguage = value;
Instance.OnLanguageChanged(new LocaleChangedEventArgs(oldValue, value));
}
}
}
public static EventHandler<LocaleChangedEventArgs> LocaleChangedEvent
{
get => Instance.OnLocaleChangedEvent;
set => Instance.OnLocaleChangedEvent = value;
}
private void OnLanguageChanged(LocaleChangedEventArgs e)
{
OnLocaleChangedEvent?.Invoke(this, e);
}
/// <summary>
/// Sets the <see cref="CurrentLanguage"/> as <see cref="Application.systemLanguage"/>.
/// </summary>
public void SetSystemLanguage()
{
CurrentLanguage = Application.systemLanguage;
}
/// <summary>
/// Sets the <see cref="CurrentLanguage"/> to default language defined in <see cref="LocaleSettings"/>.
/// </summary>
public void SetDefaultLanguage()
{
CurrentLanguage = LocaleSettings.AvailableLanguages.FirstOrDefault();
}
/// <summary>
/// Finds all localized assets with type given. Finds all assets in the project if in Editor; otherwise,
/// finds only that loaded in memory.
/// </summary>
/// <returns>Array of specified localized assets.</returns>
public static T[] FindAllLocalizedAssets<T>() where T : ScriptableLocaleBase
{
#if UNITY_EDITOR
string[] guids = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(T)}");
var assets = new T[guids.Length];
for (var i = 0; i < guids.Length; ++i)
{
string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
assets[i] = UnityEditor.AssetDatabase.LoadAssetAtPath<T>(assetPath);
Debug.Assert(assets[i]);
}
return assets;
#else
return Resources.FindObjectsOfTypeAll<T>();
#endif
}
/// <summary>
/// Finds all localized assets.
/// </summary>
/// <seealso cref="FindAllLocalizedAssets{T}"/>
/// <returns>Array of localized assets.</returns>
public static ScriptableLocaleBase[] FindAllLocalizedAssets()
{
return FindAllLocalizedAssets<ScriptableLocaleBase>();
}
const string KEY_LANGUAGE = "KEY_LANGUAGE";
public static string GetCurrentLanguageCode() => GameData.Get(KEY_LANGUAGE, "");
public static void SetCurrentLanguageCode(Language language) => GameData.Set(KEY_LANGUAGE, language.Code);
public static void SetCurrentLanguageCode(string languageCode) => GameData.Set(KEY_LANGUAGE, languageCode);
public static void LoadLanguageSetting()
{
var list = LocaleSettings.AvailableLanguages;
string lang = GetCurrentLanguageCode();
// for first time when user not choose lang to display
// use system language, if you don't use detect system language use first language in list available laguages
if (string.IsNullOrEmpty(lang))
{
var index = 0;
if (LocaleSettings.DetectDeviceLanguage)
{
var nameSystemLang = UnityEngine.Application.systemLanguage.ToString();
index = list.FindIndex(x => x.Name == nameSystemLang);
if (index < 0) index = 0;
}
lang = list[index].Code;
SetCurrentLanguageCode(lang);
}
int i = list.FindIndex(x => x.Code == lang);
Locale.CurrentLanguage = list[i];
}
}
} | 0 | 0.895339 | 1 | 0.895339 | game-dev | MEDIA | 0.926388 | game-dev | 0.898745 | 1 | 0.898745 |
aadnk/ProtocolLib | 7,494 | src/main/java/com/comphenix/protocol/reflect/cloning/AggregateCloner.java | /*
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package com.comphenix.protocol.reflect.cloning;
import com.comphenix.protocol.reflect.instances.DefaultInstances;
import com.comphenix.protocol.reflect.instances.ExistingGenerator;
import com.comphenix.protocol.reflect.instances.InstanceProvider;
import com.google.common.base.Function;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Implements a cloning procedure by trying multiple methods in turn until one is successful.
*
* @author Kristian
*/
public class AggregateCloner implements Cloner {
/**
* Supplies the cloner factories with necessary parameters.
*
* @author Kristian
*/
public static class BuilderParameters {
// Can only be modified by the builder
private InstanceProvider instanceProvider;
private Cloner aggregateCloner;
// Used to construct the different types
private InstanceProvider typeConstructor;
private BuilderParameters() {
// Only allow inner classes to construct it.
}
/**
* Retrieve the instance provider last set in the builder.
* @return Current instance provider.
*/
public InstanceProvider getInstanceProvider() {
return instanceProvider;
}
/**
* Retrieve the aggregate cloner that is being built.
* @return The parent cloner.
*/
public Cloner getAggregateCloner() {
return aggregateCloner;
}
}
/**
* Represents a builder for aggregate (combined) cloners.
*
* @author Kristian
*/
public static class Builder {
private final List<Function<BuilderParameters, Cloner>> factories = new ArrayList<>();
private final BuilderParameters parameters;
/**
* Create a new aggregate builder.
*/
public Builder() {
this.parameters = new BuilderParameters();
}
/**
* Set the instance provider supplied to all cloners in this builder.
* @param provider - new instance provider.
* @return The current builder.
*/
public Builder instanceProvider(InstanceProvider provider) {
this.parameters.instanceProvider = provider;
return this;
}
/**
* Add the next cloner that will be considered in turn.
* @param type - the type of the next cloner.
* @return This builder.
*/
public Builder andThen(final Class<? extends Cloner> type) {
// Use reflection to generate a factory on the fly
return andThen(param -> {
final Object result = param.typeConstructor.create(type);
if (result == null) throw new IllegalStateException("Constructed NULL instead of " + type);
if (type.isAssignableFrom(result.getClass())) return (Cloner) result;
else throw new IllegalStateException("Constructed " + result.getClass() + " instead of " + type);
});
}
/**
* Add the next cloner that will be considered in turn.
* @param factory - factory constructing the next cloner.
* @return This builder.
*/
public Builder andThen(Function<BuilderParameters, Cloner> factory) {
factories.add(factory);
return this;
}
/**
* Build a new aggregate cloner using the supplied values.
* @return A new aggregate cloner.
*/
public AggregateCloner build() {
AggregateCloner newCloner = new AggregateCloner();
// The parameters we will pass to our cloners
Cloner paramCloner = new NullableCloner(newCloner);
InstanceProvider paramProvider = parameters.instanceProvider;
// Initialize parameters
parameters.aggregateCloner = paramCloner;
parameters.typeConstructor = DefaultInstances.fromArray(
ExistingGenerator.fromObjectArray(new Object[] { paramCloner, paramProvider })
);
// Build every cloner in the correct order
final List<Cloner> cloners = new ArrayList<>();
for (int i = 0; i < factories.size(); i++) {
Cloner cloner = factories.get(i).apply(parameters);
// See if we were successful
if (cloner != null) cloners.add(cloner);
else throw new IllegalArgumentException(String.format("Cannot create cloner from %s (%s)", factories.get(i), i));
}
// We're done
newCloner.setCloners(cloners);
return newCloner;
}
}
/**
* Represents a default aggregate cloner.
*/
public static final AggregateCloner DEFAULT = newBuilder().
instanceProvider(DefaultInstances.DEFAULT).
andThen(BukkitCloner.class).
andThen(ImmutableDetector.class).
andThen(CollectionCloner.class).
andThen(FieldCloner.class).
build();
// List of clone methods
private List<Cloner> cloners;
private WeakReference<Object> lastObject;
private int lastResult;
/**
* Begins constructing a new aggregate cloner.
* @return A builder for a new aggregate cloner.
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* Construct a new, empty aggregate cloner.
*/
private AggregateCloner() {
// Only used by our builder above.
}
/**
* Retrieves a view of the current list of cloners.
* @return Current cloners.
*/
public List<Cloner> getCloners() {
return Collections.unmodifiableList(cloners);
}
/**
* Set the cloners that will be used.
* @param cloners - the cloners that will be used.
*/
private void setCloners(Collection<? extends Cloner> cloners) {
this.cloners = new ArrayList<>(cloners);
}
@Override
public boolean canClone(Object source) {
// Optimize a bit
lastResult = getFirstCloner(source);
lastObject = new WeakReference<>(source);
return lastResult >= 0 && lastResult < cloners.size();
}
/**
* Retrieve the index of the first cloner capable of cloning the given object.
* <p>
* Returns an invalid index if no cloner is able to clone the object.
* @param source - the object to clone.
* @return The index of the cloner object.
*/
private int getFirstCloner(Object source) {
for (int i = 0; i < cloners.size(); i++) {
if (cloners.get(i).canClone(source))
return i;
}
return cloners.size();
}
@Override
public Object clone(Object source) {
if (source == null)
throw new IllegalAccessError("source cannot be NULL.");
int index = 0;
// Are we dealing with the same object?
if (lastObject != null && lastObject.get() == source) {
index = lastResult;
} else {
index = getFirstCloner(source);
}
// Make sure the object is valid
if (index < cloners.size()) {
Cloner cloner = cloners.get(index);
// try {
return cloner.clone(source);
// } catch (Exception ex) {
// throw new RuntimeException("Failed to clone " + source + " (" + source.getClass() + ") with " + cloner, ex);
// }
}
// Damn - failure
throw new IllegalArgumentException("Cannot clone " + source + " ( " + source.getClass() + "): No cloner is suitable.");
}
}
| 0 | 0.788509 | 1 | 0.788509 | game-dev | MEDIA | 0.221147 | game-dev | 0.709803 | 1 | 0.709803 |
PacktPublishing/CPP-Game-Development-By-Example | 24,731 | Chapter08/8.OpenGLProject/OpenGLProject/Dependencies/bullet/include/BulletCollision/NarrowPhaseCollision/btMprPenetration.h |
/***
* ---------------------------------
* Copyright (c)2012 Daniel Fiser <danfis@danfis.cz>
*
* This file was ported from mpr.c file, part of libccd.
* The Minkoski Portal Refinement implementation was ported
* to OpenCL by Erwin Coumans for the Bullet 3 Physics library.
* The original MPR idea and implementation is by Gary Snethen
* in XenoCollide, see http://github.com/erwincoumans/xenocollide
*
* Distributed under the OSI-approved BSD License (the "License");
* see <http://www.opensource.org/licenses/bsd-license.php>.
* This software is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the License for more information.
*/
///2014 Oct, Erwin Coumans, Use templates to avoid void* casts
#ifndef BT_MPR_PENETRATION_H
#define BT_MPR_PENETRATION_H
#define BT_DEBUG_MPR1
#include "LinearMath/btTransform.h"
#include "LinearMath/btAlignedObjectArray.h"
//#define MPR_AVERAGE_CONTACT_POSITIONS
struct btMprCollisionDescription
{
btVector3 m_firstDir;
int m_maxGjkIterations;
btScalar m_maximumDistanceSquared;
btScalar m_gjkRelError2;
btMprCollisionDescription()
: m_firstDir(0,1,0),
m_maxGjkIterations(1000),
m_maximumDistanceSquared(1e30f),
m_gjkRelError2(1.0e-6)
{
}
virtual ~btMprCollisionDescription()
{
}
};
struct btMprDistanceInfo
{
btVector3 m_pointOnA;
btVector3 m_pointOnB;
btVector3 m_normalBtoA;
btScalar m_distance;
};
#ifdef __cplusplus
#define BT_MPR_SQRT sqrtf
#else
#define BT_MPR_SQRT sqrt
#endif
#define BT_MPR_FMIN(x, y) ((x) < (y) ? (x) : (y))
#define BT_MPR_FABS fabs
#define BT_MPR_TOLERANCE 1E-6f
#define BT_MPR_MAX_ITERATIONS 1000
struct _btMprSupport_t
{
btVector3 v; //!< Support point in minkowski sum
btVector3 v1; //!< Support point in obj1
btVector3 v2; //!< Support point in obj2
};
typedef struct _btMprSupport_t btMprSupport_t;
struct _btMprSimplex_t
{
btMprSupport_t ps[4];
int last; //!< index of last added point
};
typedef struct _btMprSimplex_t btMprSimplex_t;
inline btMprSupport_t* btMprSimplexPointW(btMprSimplex_t *s, int idx)
{
return &s->ps[idx];
}
inline void btMprSimplexSetSize(btMprSimplex_t *s, int size)
{
s->last = size - 1;
}
#ifdef DEBUG_MPR
inline void btPrintPortalVertex(_btMprSimplex_t* portal, int index)
{
printf("portal[%d].v = %f,%f,%f, v1=%f,%f,%f, v2=%f,%f,%f\n", index, portal->ps[index].v.x(),portal->ps[index].v.y(),portal->ps[index].v.z(),
portal->ps[index].v1.x(),portal->ps[index].v1.y(),portal->ps[index].v1.z(),
portal->ps[index].v2.x(),portal->ps[index].v2.y(),portal->ps[index].v2.z());
}
#endif //DEBUG_MPR
inline int btMprSimplexSize(const btMprSimplex_t *s)
{
return s->last + 1;
}
inline const btMprSupport_t* btMprSimplexPoint(const btMprSimplex_t* s, int idx)
{
// here is no check on boundaries
return &s->ps[idx];
}
inline void btMprSupportCopy(btMprSupport_t *d, const btMprSupport_t *s)
{
*d = *s;
}
inline void btMprSimplexSet(btMprSimplex_t *s, size_t pos, const btMprSupport_t *a)
{
btMprSupportCopy(s->ps + pos, a);
}
inline void btMprSimplexSwap(btMprSimplex_t *s, size_t pos1, size_t pos2)
{
btMprSupport_t supp;
btMprSupportCopy(&supp, &s->ps[pos1]);
btMprSupportCopy(&s->ps[pos1], &s->ps[pos2]);
btMprSupportCopy(&s->ps[pos2], &supp);
}
inline int btMprIsZero(float val)
{
return BT_MPR_FABS(val) < FLT_EPSILON;
}
inline int btMprEq(float _a, float _b)
{
float ab;
float a, b;
ab = BT_MPR_FABS(_a - _b);
if (BT_MPR_FABS(ab) < FLT_EPSILON)
return 1;
a = BT_MPR_FABS(_a);
b = BT_MPR_FABS(_b);
if (b > a){
return ab < FLT_EPSILON * b;
}else{
return ab < FLT_EPSILON * a;
}
}
inline int btMprVec3Eq(const btVector3* a, const btVector3 *b)
{
return btMprEq((*a).x(), (*b).x())
&& btMprEq((*a).y(), (*b).y())
&& btMprEq((*a).z(), (*b).z());
}
template <typename btConvexTemplate>
inline void btFindOrigin(const btConvexTemplate& a, const btConvexTemplate& b, const btMprCollisionDescription& colDesc,btMprSupport_t *center)
{
center->v1 = a.getObjectCenterInWorld();
center->v2 = b.getObjectCenterInWorld();
center->v = center->v1 - center->v2;
}
inline void btMprVec3Set(btVector3 *v, float x, float y, float z)
{
v->setValue(x,y,z);
}
inline void btMprVec3Add(btVector3 *v, const btVector3 *w)
{
*v += *w;
}
inline void btMprVec3Copy(btVector3 *v, const btVector3 *w)
{
*v = *w;
}
inline void btMprVec3Scale(btVector3 *d, float k)
{
*d *= k;
}
inline float btMprVec3Dot(const btVector3 *a, const btVector3 *b)
{
float dot;
dot = btDot(*a,*b);
return dot;
}
inline float btMprVec3Len2(const btVector3 *v)
{
return btMprVec3Dot(v, v);
}
inline void btMprVec3Normalize(btVector3 *d)
{
float k = 1.f / BT_MPR_SQRT(btMprVec3Len2(d));
btMprVec3Scale(d, k);
}
inline void btMprVec3Cross(btVector3 *d, const btVector3 *a, const btVector3 *b)
{
*d = btCross(*a,*b);
}
inline void btMprVec3Sub2(btVector3 *d, const btVector3 *v, const btVector3 *w)
{
*d = *v - *w;
}
inline void btPortalDir(const btMprSimplex_t *portal, btVector3 *dir)
{
btVector3 v2v1, v3v1;
btMprVec3Sub2(&v2v1, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 1)->v);
btMprVec3Sub2(&v3v1, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 1)->v);
btMprVec3Cross(dir, &v2v1, &v3v1);
btMprVec3Normalize(dir);
}
inline int portalEncapsulesOrigin(const btMprSimplex_t *portal,
const btVector3 *dir)
{
float dot;
dot = btMprVec3Dot(dir, &btMprSimplexPoint(portal, 1)->v);
return btMprIsZero(dot) || dot > 0.f;
}
inline int portalReachTolerance(const btMprSimplex_t *portal,
const btMprSupport_t *v4,
const btVector3 *dir)
{
float dv1, dv2, dv3, dv4;
float dot1, dot2, dot3;
// find the smallest dot product of dir and {v1-v4, v2-v4, v3-v4}
dv1 = btMprVec3Dot(&btMprSimplexPoint(portal, 1)->v, dir);
dv2 = btMprVec3Dot(&btMprSimplexPoint(portal, 2)->v, dir);
dv3 = btMprVec3Dot(&btMprSimplexPoint(portal, 3)->v, dir);
dv4 = btMprVec3Dot(&v4->v, dir);
dot1 = dv4 - dv1;
dot2 = dv4 - dv2;
dot3 = dv4 - dv3;
dot1 = BT_MPR_FMIN(dot1, dot2);
dot1 = BT_MPR_FMIN(dot1, dot3);
return btMprEq(dot1, BT_MPR_TOLERANCE) || dot1 < BT_MPR_TOLERANCE;
}
inline int portalCanEncapsuleOrigin(const btMprSimplex_t *portal,
const btMprSupport_t *v4,
const btVector3 *dir)
{
float dot;
dot = btMprVec3Dot(&v4->v, dir);
return btMprIsZero(dot) || dot > 0.f;
}
inline void btExpandPortal(btMprSimplex_t *portal,
const btMprSupport_t *v4)
{
float dot;
btVector3 v4v0;
btMprVec3Cross(&v4v0, &v4->v, &btMprSimplexPoint(portal, 0)->v);
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 1)->v, &v4v0);
if (dot > 0.f){
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 2)->v, &v4v0);
if (dot > 0.f){
btMprSimplexSet(portal, 1, v4);
}else{
btMprSimplexSet(portal, 3, v4);
}
}else{
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 3)->v, &v4v0);
if (dot > 0.f){
btMprSimplexSet(portal, 2, v4);
}else{
btMprSimplexSet(portal, 1, v4);
}
}
}
template <typename btConvexTemplate>
inline void btMprSupport(const btConvexTemplate& a, const btConvexTemplate& b,
const btMprCollisionDescription& colDesc,
const btVector3& dir, btMprSupport_t *supp)
{
btVector3 seperatingAxisInA = dir* a.getWorldTransform().getBasis();
btVector3 seperatingAxisInB = -dir* b.getWorldTransform().getBasis();
btVector3 pInA = a.getLocalSupportWithMargin(seperatingAxisInA);
btVector3 qInB = b.getLocalSupportWithMargin(seperatingAxisInB);
supp->v1 = a.getWorldTransform()(pInA);
supp->v2 = b.getWorldTransform()(qInB);
supp->v = supp->v1 - supp->v2;
}
template <typename btConvexTemplate>
static int btDiscoverPortal(const btConvexTemplate& a, const btConvexTemplate& b,
const btMprCollisionDescription& colDesc,
btMprSimplex_t *portal)
{
btVector3 dir, va, vb;
float dot;
int cont;
// vertex 0 is center of portal
btFindOrigin(a,b,colDesc, btMprSimplexPointW(portal, 0));
// vertex 0 is center of portal
btMprSimplexSetSize(portal, 1);
btVector3 zero = btVector3(0,0,0);
btVector3* org = &zero;
if (btMprVec3Eq(&btMprSimplexPoint(portal, 0)->v, org)){
// Portal's center lies on origin (0,0,0) => we know that objects
// intersect but we would need to know penetration info.
// So move center little bit...
btMprVec3Set(&va, FLT_EPSILON * 10.f, 0.f, 0.f);
btMprVec3Add(&btMprSimplexPointW(portal, 0)->v, &va);
}
// vertex 1 = support in direction of origin
btMprVec3Copy(&dir, &btMprSimplexPoint(portal, 0)->v);
btMprVec3Scale(&dir, -1.f);
btMprVec3Normalize(&dir);
btMprSupport(a,b,colDesc, dir, btMprSimplexPointW(portal, 1));
btMprSimplexSetSize(portal, 2);
// test if origin isn't outside of v1
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 1)->v, &dir);
if (btMprIsZero(dot) || dot < 0.f)
return -1;
// vertex 2
btMprVec3Cross(&dir, &btMprSimplexPoint(portal, 0)->v,
&btMprSimplexPoint(portal, 1)->v);
if (btMprIsZero(btMprVec3Len2(&dir))){
if (btMprVec3Eq(&btMprSimplexPoint(portal, 1)->v, org)){
// origin lies on v1
return 1;
}else{
// origin lies on v0-v1 segment
return 2;
}
}
btMprVec3Normalize(&dir);
btMprSupport(a,b,colDesc, dir, btMprSimplexPointW(portal, 2));
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 2)->v, &dir);
if (btMprIsZero(dot) || dot < 0.f)
return -1;
btMprSimplexSetSize(portal, 3);
// vertex 3 direction
btMprVec3Sub2(&va, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Sub2(&vb, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Cross(&dir, &va, &vb);
btMprVec3Normalize(&dir);
// it is better to form portal faces to be oriented "outside" origin
dot = btMprVec3Dot(&dir, &btMprSimplexPoint(portal, 0)->v);
if (dot > 0.f){
btMprSimplexSwap(portal, 1, 2);
btMprVec3Scale(&dir, -1.f);
}
while (btMprSimplexSize(portal) < 4){
btMprSupport(a,b,colDesc, dir, btMprSimplexPointW(portal, 3));
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 3)->v, &dir);
if (btMprIsZero(dot) || dot < 0.f)
return -1;
cont = 0;
// test if origin is outside (v1, v0, v3) - set v2 as v3 and
// continue
btMprVec3Cross(&va, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 3)->v);
dot = btMprVec3Dot(&va, &btMprSimplexPoint(portal, 0)->v);
if (dot < 0.f && !btMprIsZero(dot)){
btMprSimplexSet(portal, 2, btMprSimplexPoint(portal, 3));
cont = 1;
}
if (!cont){
// test if origin is outside (v3, v0, v2) - set v1 as v3 and
// continue
btMprVec3Cross(&va, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 2)->v);
dot = btMprVec3Dot(&va, &btMprSimplexPoint(portal, 0)->v);
if (dot < 0.f && !btMprIsZero(dot)){
btMprSimplexSet(portal, 1, btMprSimplexPoint(portal, 3));
cont = 1;
}
}
if (cont){
btMprVec3Sub2(&va, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Sub2(&vb, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Cross(&dir, &va, &vb);
btMprVec3Normalize(&dir);
}else{
btMprSimplexSetSize(portal, 4);
}
}
return 0;
}
template <typename btConvexTemplate>
static int btRefinePortal(const btConvexTemplate& a, const btConvexTemplate& b,const btMprCollisionDescription& colDesc,
btMprSimplex_t *portal)
{
btVector3 dir;
btMprSupport_t v4;
for (int i=0;i<BT_MPR_MAX_ITERATIONS;i++)
//while (1)
{
// compute direction outside the portal (from v0 throught v1,v2,v3
// face)
btPortalDir(portal, &dir);
// test if origin is inside the portal
if (portalEncapsulesOrigin(portal, &dir))
return 0;
// get next support point
btMprSupport(a,b,colDesc, dir, &v4);
// test if v4 can expand portal to contain origin and if portal
// expanding doesn't reach given tolerance
if (!portalCanEncapsuleOrigin(portal, &v4, &dir)
|| portalReachTolerance(portal, &v4, &dir))
{
return -1;
}
// v1-v2-v3 triangle must be rearranged to face outside Minkowski
// difference (direction from v0).
btExpandPortal(portal, &v4);
}
return -1;
}
static void btFindPos(const btMprSimplex_t *portal, btVector3 *pos)
{
btVector3 zero = btVector3(0,0,0);
btVector3* origin = &zero;
btVector3 dir;
size_t i;
float b[4], sum, inv;
btVector3 vec, p1, p2;
btPortalDir(portal, &dir);
// use barycentric coordinates of tetrahedron to find origin
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 2)->v);
b[0] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 3)->v);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 2)->v);
b[1] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 0)->v);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 0)->v,
&btMprSimplexPoint(portal, 1)->v);
b[2] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 3)->v);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 1)->v);
b[3] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 0)->v);
sum = b[0] + b[1] + b[2] + b[3];
if (btMprIsZero(sum) || sum < 0.f){
b[0] = 0.f;
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 3)->v);
b[1] = btMprVec3Dot(&vec, &dir);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 1)->v);
b[2] = btMprVec3Dot(&vec, &dir);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 2)->v);
b[3] = btMprVec3Dot(&vec, &dir);
sum = b[1] + b[2] + b[3];
}
inv = 1.f / sum;
btMprVec3Copy(&p1, origin);
btMprVec3Copy(&p2, origin);
for (i = 0; i < 4; i++){
btMprVec3Copy(&vec, &btMprSimplexPoint(portal, i)->v1);
btMprVec3Scale(&vec, b[i]);
btMprVec3Add(&p1, &vec);
btMprVec3Copy(&vec, &btMprSimplexPoint(portal, i)->v2);
btMprVec3Scale(&vec, b[i]);
btMprVec3Add(&p2, &vec);
}
btMprVec3Scale(&p1, inv);
btMprVec3Scale(&p2, inv);
#ifdef MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(pos, &p1);
btMprVec3Add(pos, &p2);
btMprVec3Scale(pos, 0.5);
#else
btMprVec3Copy(pos, &p2);
#endif//MPR_AVERAGE_CONTACT_POSITIONS
}
inline float btMprVec3Dist2(const btVector3 *a, const btVector3 *b)
{
btVector3 ab;
btMprVec3Sub2(&ab, a, b);
return btMprVec3Len2(&ab);
}
inline float _btMprVec3PointSegmentDist2(const btVector3 *P,
const btVector3 *x0,
const btVector3 *b,
btVector3 *witness)
{
// The computation comes from solving equation of segment:
// S(t) = x0 + t.d
// where - x0 is initial point of segment
// - d is direction of segment from x0 (|d| > 0)
// - t belongs to <0, 1> interval
//
// Than, distance from a segment to some point P can be expressed:
// D(t) = |x0 + t.d - P|^2
// which is distance from any point on segment. Minimization
// of this function brings distance from P to segment.
// Minimization of D(t) leads to simple quadratic equation that's
// solving is straightforward.
//
// Bonus of this method is witness point for free.
float dist, t;
btVector3 d, a;
// direction of segment
btMprVec3Sub2(&d, b, x0);
// precompute vector from P to x0
btMprVec3Sub2(&a, x0, P);
t = -1.f * btMprVec3Dot(&a, &d);
t /= btMprVec3Len2(&d);
if (t < 0.f || btMprIsZero(t)){
dist = btMprVec3Dist2(x0, P);
if (witness)
btMprVec3Copy(witness, x0);
}else if (t > 1.f || btMprEq(t, 1.f)){
dist = btMprVec3Dist2(b, P);
if (witness)
btMprVec3Copy(witness, b);
}else{
if (witness){
btMprVec3Copy(witness, &d);
btMprVec3Scale(witness, t);
btMprVec3Add(witness, x0);
dist = btMprVec3Dist2(witness, P);
}else{
// recycling variables
btMprVec3Scale(&d, t);
btMprVec3Add(&d, &a);
dist = btMprVec3Len2(&d);
}
}
return dist;
}
inline float btMprVec3PointTriDist2(const btVector3 *P,
const btVector3 *x0, const btVector3 *B,
const btVector3 *C,
btVector3 *witness)
{
// Computation comes from analytic expression for triangle (x0, B, C)
// T(s, t) = x0 + s.d1 + t.d2, where d1 = B - x0 and d2 = C - x0 and
// Then equation for distance is:
// D(s, t) = | T(s, t) - P |^2
// This leads to minimization of quadratic function of two variables.
// The solution from is taken only if s is between 0 and 1, t is
// between 0 and 1 and t + s < 1, otherwise distance from segment is
// computed.
btVector3 d1, d2, a;
float u, v, w, p, q, r;
float s, t, dist, dist2;
btVector3 witness2;
btMprVec3Sub2(&d1, B, x0);
btMprVec3Sub2(&d2, C, x0);
btMprVec3Sub2(&a, x0, P);
u = btMprVec3Dot(&a, &a);
v = btMprVec3Dot(&d1, &d1);
w = btMprVec3Dot(&d2, &d2);
p = btMprVec3Dot(&a, &d1);
q = btMprVec3Dot(&a, &d2);
r = btMprVec3Dot(&d1, &d2);
btScalar div = (w * v - r * r);
if (btMprIsZero(div))
{
s=-1;
} else
{
s = (q * r - w * p) / div;
t = (-s * r - q) / w;
}
if ((btMprIsZero(s) || s > 0.f)
&& (btMprEq(s, 1.f) || s < 1.f)
&& (btMprIsZero(t) || t > 0.f)
&& (btMprEq(t, 1.f) || t < 1.f)
&& (btMprEq(t + s, 1.f) || t + s < 1.f)){
if (witness){
btMprVec3Scale(&d1, s);
btMprVec3Scale(&d2, t);
btMprVec3Copy(witness, x0);
btMprVec3Add(witness, &d1);
btMprVec3Add(witness, &d2);
dist = btMprVec3Dist2(witness, P);
}else{
dist = s * s * v;
dist += t * t * w;
dist += 2.f * s * t * r;
dist += 2.f * s * p;
dist += 2.f * t * q;
dist += u;
}
}else{
dist = _btMprVec3PointSegmentDist2(P, x0, B, witness);
dist2 = _btMprVec3PointSegmentDist2(P, x0, C, &witness2);
if (dist2 < dist){
dist = dist2;
if (witness)
btMprVec3Copy(witness, &witness2);
}
dist2 = _btMprVec3PointSegmentDist2(P, B, C, &witness2);
if (dist2 < dist){
dist = dist2;
if (witness)
btMprVec3Copy(witness, &witness2);
}
}
return dist;
}
template <typename btConvexTemplate>
static void btFindPenetr(const btConvexTemplate& a, const btConvexTemplate& b,
const btMprCollisionDescription& colDesc,
btMprSimplex_t *portal,
float *depth, btVector3 *pdir, btVector3 *pos)
{
btVector3 dir;
btMprSupport_t v4;
unsigned long iterations;
btVector3 zero = btVector3(0,0,0);
btVector3* origin = &zero;
iterations = 1UL;
for (int i=0;i<BT_MPR_MAX_ITERATIONS;i++)
//while (1)
{
// compute portal direction and obtain next support point
btPortalDir(portal, &dir);
btMprSupport(a,b,colDesc, dir, &v4);
// reached tolerance -> find penetration info
if (portalReachTolerance(portal, &v4, &dir)
|| iterations ==BT_MPR_MAX_ITERATIONS)
{
*depth = btMprVec3PointTriDist2(origin,&btMprSimplexPoint(portal, 1)->v,&btMprSimplexPoint(portal, 2)->v,&btMprSimplexPoint(portal, 3)->v,pdir);
*depth = BT_MPR_SQRT(*depth);
if (btMprIsZero((*pdir).x()) && btMprIsZero((*pdir).y()) && btMprIsZero((*pdir).z()))
{
*pdir = dir;
}
btMprVec3Normalize(pdir);
// barycentric coordinates:
btFindPos(portal, pos);
return;
}
btExpandPortal(portal, &v4);
iterations++;
}
}
static void btFindPenetrTouch(btMprSimplex_t *portal,float *depth, btVector3 *dir, btVector3 *pos)
{
// Touching contact on portal's v1 - so depth is zero and direction
// is unimportant and pos can be guessed
*depth = 0.f;
btVector3 zero = btVector3(0,0,0);
btVector3* origin = &zero;
btMprVec3Copy(dir, origin);
#ifdef MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v1);
btMprVec3Add(pos, &btMprSimplexPoint(portal, 1)->v2);
btMprVec3Scale(pos, 0.5);
#else
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v2);
#endif
}
static void btFindPenetrSegment(btMprSimplex_t *portal,
float *depth, btVector3 *dir, btVector3 *pos)
{
// Origin lies on v0-v1 segment.
// Depth is distance to v1, direction also and position must be
// computed
#ifdef MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v1);
btMprVec3Add(pos, &btMprSimplexPoint(portal, 1)->v2);
btMprVec3Scale(pos, 0.5f);
#else
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v2);
#endif//MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(dir, &btMprSimplexPoint(portal, 1)->v);
*depth = BT_MPR_SQRT(btMprVec3Len2(dir));
btMprVec3Normalize(dir);
}
template <typename btConvexTemplate>
inline int btMprPenetration( const btConvexTemplate& a, const btConvexTemplate& b,
const btMprCollisionDescription& colDesc,
float *depthOut, btVector3* dirOut, btVector3* posOut)
{
btMprSimplex_t portal;
// Phase 1: Portal discovery
int result = btDiscoverPortal(a,b,colDesc, &portal);
//sepAxis[pairIndex] = *pdir;//or -dir?
switch (result)
{
case 0:
{
// Phase 2: Portal refinement
result = btRefinePortal(a,b,colDesc, &portal);
if (result < 0)
return -1;
// Phase 3. Penetration info
btFindPenetr(a,b,colDesc, &portal, depthOut, dirOut, posOut);
break;
}
case 1:
{
// Touching contact on portal's v1.
btFindPenetrTouch(&portal, depthOut, dirOut, posOut);
result=0;
break;
}
case 2:
{
btFindPenetrSegment( &portal, depthOut, dirOut, posOut);
result=0;
break;
}
default:
{
//if (res < 0)
//{
// Origin isn't inside portal - no collision.
result = -1;
//}
}
};
return result;
};
template<typename btConvexTemplate, typename btMprDistanceTemplate>
inline int btComputeMprPenetration( const btConvexTemplate& a, const btConvexTemplate& b, const
btMprCollisionDescription& colDesc, btMprDistanceTemplate* distInfo)
{
btVector3 dir,pos;
float depth;
int res = btMprPenetration(a,b,colDesc,&depth, &dir, &pos);
if (res==0)
{
distInfo->m_distance = -depth;
distInfo->m_pointOnB = pos;
distInfo->m_normalBtoA = -dir;
distInfo->m_pointOnA = pos-distInfo->m_distance*dir;
return 0;
}
return -1;
}
#endif //BT_MPR_PENETRATION_H
| 0 | 0.840241 | 1 | 0.840241 | game-dev | MEDIA | 0.876325 | game-dev | 0.984054 | 1 | 0.984054 |
electronicarts/CnC_Red_Alert | 13,409 | CODE/TEMPLATE.CPP | /*
** Command & Conquer Red Alert(tm)
** Copyright 2025 Electronic Arts 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 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Header: /CounterStrike/TEMPLATE.CPP 1 3/03/97 10:25a Joe_bostic $ */
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : Command & Conquer *
* *
* File Name : TEMPLATE.CPP *
* *
* Programmer : Joe L. Bostic *
* *
* Start Date : May 17, 1994 *
* *
* Last Update : January 23, 1995 [JLB] *
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* TemplateClass::Init -- Resets the template object system. *
* TemplateClass::Mark -- Lifts or drops a template object. *
* TemplateClass::Select -- Select the template object. *
* TemplateClass::TemplateClass -- Template object constructor. *
* TemplateClass::Unlimbo -- Places a template object into the game/map system. *
* TemplateClass::delete -- Returns a template object to the pool. *
* TemplateClass::new -- Allocates a template object from pool *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#include "function.h"
#include "template.h"
/***********************************************************************************************
* TemplateClass::Init -- Resets the template object system. *
* *
* This routine resets the template object system. It is called *
* prior to loading a new scenario. *
* *
* INPUT: none *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 05/24/1994 JLB : Created. *
*=============================================================================================*/
void TemplateClass::Init(void)
{
Templates.Free_All();
}
/***********************************************************************************************
* TemplateClass::Mark -- Lifts or drops a template object. *
* *
* This routine handles placing or removing a template object. This *
* entails marking the map as appropriate and redisplaying affected *
* cells. *
* *
* INPUT: mark -- The marking operation to perform. *
* *
* OUTPUT: bool; Was the template successfully marked? *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 05/17/1994 JLB : Created. *
* 12/23/1994 JLB : Examines low level legality before processing. *
*=============================================================================================*/
bool TemplateClass::Mark(MarkType mark)
{
assert(Templates.ID(this) == ID);
assert(IsActive);
static bool noup = false;
void const * iset = Get_Image_Data();
if (iset && ObjectClass::Mark(mark)) {
void * map = Get_Icon_Set_Map(iset);
for (int y = 0; y < Class->Height; y++) {
for (int x = 0; x < Class->Width; x++) {
CELL cell = Coord_Cell(Coord) + y*MAP_CELL_W + x;
if (Map.In_Radar(cell)) {
CellClass * cellptr = &Map[cell];
int number = y*Class->Width + x;
/*
** Determine if this logical icon actually maps to a real icon. If no real
** icon is associated with this logical position, then don't do any action
** since none is required.
*/
char * mapptr = (char*)map;
bool real = (mapptr[number] != -1);
if (real) {
/*
** Lift the terrain object from the map.
*/
if (mark == MARK_UP && !noup) {
if (cellptr->TType == Class->Type && cellptr->TIcon == number) {
cellptr->TType = TEMPLATE_NONE;
cellptr->TIcon = 0;
}
}
/*
** Place the terrain object down.
*/
if (mark == MARK_DOWN) {
if (*this == TEMPLATE_CLEAR1) {
cellptr->TType = TEMPLATE_NONE;
cellptr->TIcon = 0;
} else {
cellptr->TType = Class->Type;
cellptr->TIcon = number;
}
/*
** Make sure that no overlays or smudges exist after
** placing the template down.
*/
cellptr->Smudge = SMUDGE_NONE;
cellptr->SmudgeData = 0;
cellptr->Overlay = OVERLAY_NONE;
cellptr->OverlayData = 0;
}
cellptr->Redraw_Objects();
cellptr->Recalc_Attributes();
}
}
}
}
/*
** When marking this template down onto the map, the map template numbers are update
** but the template is removed from existence. Make sure that the deletion of the
** template object doesn't also lift the template numbers up from the map.
*/
if (mark == MARK_DOWN) {
noup = true;
delete this;
noup = false;
}
return(true);
}
return(false);
}
/***********************************************************************************************
* TemplateClass::new -- Allocates a template object from pool *
* *
* This routine is used to allocate a template object from the *
* template object pool. *
* *
* INPUT: size -- The size of a template object (not used). *
* *
* OUTPUT: Returns with a pointer to an available template object. *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 05/17/1994 JLB : Created. *
*=============================================================================================*/
void * TemplateClass::operator new(size_t )
{
void * ptr = Templates.Allocate();
if (ptr) {
((TemplateClass *)ptr)->IsActive = true;
}
return(ptr);
}
/***********************************************************************************************
* TemplateClass::delete -- Returns a template object to the pool. *
* *
* This routine will return a template object to the template object *
* pool. A template so returned is available for allocation again. *
* *
* INPUT: ptr -- Pointer to the object to be returned. *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 05/17/1994 JLB : Created. *
*=============================================================================================*/
void TemplateClass::operator delete(void * ptr)
{
if (ptr) {
((TemplateClass *)ptr)->IsActive = false;
}
Templates.Free((TemplateClass *)ptr);
}
/***********************************************************************************************
* TemplateClass::TemplateClass -- Template object constructor. *
* *
* This is the constructor for a template object. *
* *
* INPUT: type -- The template object this is to become. *
* *
* pos -- The position on the map to place the object. *
* *
* OUTPUT: none *
* *
* WARNINGS: none *
* *
* HISTORY: *
* 05/17/1994 JLB : Created. *
*=============================================================================================*/
TemplateClass::TemplateClass(TemplateType type, CELL pos) :
ObjectClass(RTTI_TEMPLATE, Templates.ID(this)),
Class(TemplateTypes.Ptr((int)type))
{
if (pos != -1) {
Unlimbo(Cell_Coord(pos));
}
}
| 0 | 0.944871 | 1 | 0.944871 | game-dev | MEDIA | 0.690128 | game-dev | 0.965293 | 1 | 0.965293 |
Monkestation/Monkestation2.0 | 5,746 | monkestation/code/modules/client/verbs/looc.dm | // LOOC ported from Bee, which was in turn ported from Citadel
GLOBAL_VAR_INIT(looc_allowed, TRUE)
/client/verb/looc(msg as text)
set name = "LOOC"
set desc = "Local OOC, seen only by those in view."
set category = "OOC"
if(GLOB.say_disabled) //This is here to try to identify lag problems
to_chat(usr, span_danger("Speech is currently admin-disabled."))
return
if(!mob)
return
VALIDATE_CLIENT(src)
if(is_banned_from(mob.ckey, "OOC"))
to_chat(src, "<span class='danger'>You have been banned from OOC and LOOC.</span>")
return
if(!CHECK_BITFIELD(prefs.chat_toggles, CHAT_OOC))
to_chat(src, span_danger("You have OOC (and therefore LOOC) muted."))
return
msg = trim(sanitize(msg), MAX_MESSAGE_LEN)
if(!length(msg))
return
var/raw_msg = msg
var/list/filter_result = is_ooc_filtered(msg)
if (!CAN_BYPASS_FILTER(usr) && filter_result)
REPORT_CHAT_FILTER_TO_USER(usr, filter_result)
log_filter("LOOC", msg, filter_result)
return
// Protect filter bypassers from themselves.
// Demote hard filter results to soft filter results if necessary due to the danger of accidentally speaking in OOC.
var/list/soft_filter_result = filter_result || is_soft_ooc_filtered(msg)
if (soft_filter_result)
if(tgui_alert(usr, "Your message contains \"[soft_filter_result[CHAT_FILTER_INDEX_WORD]]\". \"[soft_filter_result[CHAT_FILTER_INDEX_REASON]]\", Are you sure you want to say it?", "Soft Blocked Word", list("Yes", "No")) != "Yes")
return
message_admins("[ADMIN_LOOKUPFLW(usr)] has passed the soft filter for \"[soft_filter_result[CHAT_FILTER_INDEX_WORD]]\" they may be using a disallowed term. Message: \"[msg]\"")
log_admin_private("[key_name(usr)] has passed the soft filter for \"[soft_filter_result[CHAT_FILTER_INDEX_WORD]]\" they may be using a disallowed term. Message: \"[msg]\"")
// letting mentors use this as they might actually use this to help people. this cannot possibly go wrong! :clueless:
if(!holder)
if(!CONFIG_GET(flag/looc_enabled))
to_chat(src, span_danger("LOOC is disabled."))
return
if(!GLOB.dooc_allowed && (mob.stat == DEAD) && SSticker.current_state < GAME_STATE_FINISHED && !mentor_datum?.check_for_rights(R_MENTOR))
to_chat(usr, span_danger("LOOC for dead mobs has been turned off."))
return
if(CHECK_BITFIELD(prefs.muted, MUTE_OOC))
to_chat(src, span_danger("You cannot use LOOC (muted)."))
return
if(handle_spam_prevention(msg, MUTE_OOC))
return
if(findtext(msg, "byond://"))
to_chat(src, span_danger("Advertising other servers is not allowed."))
log_admin("[key_name(src)] has attempted to advertise in LOOC: [msg]")
return
if(mob.stat && SSticker.current_state < GAME_STATE_FINISHED && !mentor_datum?.check_for_rights(R_MENTOR))
to_chat(src, span_danger("You cannot salt in LOOC while unconscious or dead."))
return
if(isdead(mob) && SSticker.current_state < GAME_STATE_FINISHED && !mentor_datum?.check_for_rights(R_MENTOR))
to_chat(src, span_danger("You cannot use LOOC while ghosting."))
return
if(is_banned_from(ckey, "OOC"))
to_chat(src, span_danger("You have been banned from OOC."))
return
if(QDELETED(src))
return
msg = emoji_parse(msg)
mob.log_talk(raw_msg, LOG_OOC, tag = "LOOC")
var/list/hearers = list()
for(var/mob/hearer in get_hearers_in_view(9, mob))
var/client/client = hearer.client
if(QDELETED(client) || !CHECK_BITFIELD(client.prefs.chat_toggles, CHAT_OOC))
continue
hearers[client] = TRUE
if((client in GLOB.admins) && is_admin_looc_omnipotent(client))
continue
to_chat(hearer, span_looc("[span_prefix("LOOC:")] <EM>[span_name("[mob.name]")]:</EM> <span class='message linkify'>[msg]</span>"), type = MESSAGE_TYPE_LOOC, avoid_highlighting = (hearer == mob))
if(client.prefs.read_preference(/datum/preference/toggle/enable_runechat_looc))
hearer.create_chat_message(mob, /datum/language/common, "\[LOOC: [raw_msg]\]", runechat_flags = LOOC_MESSAGE)
for(var/client/client in GLOB.admins)
if(!CHECK_BITFIELD(client.prefs.chat_toggles, CHAT_OOC) || !is_admin_looc_omnipotent(client))
continue
var/prefix = "[hearers[client] ? "" : "(R)"]LOOC"
if(client.prefs.read_preference(/datum/preference/toggle/enable_runechat_looc))
client.mob?.create_chat_message(mob, /datum/language/common, "\[LOOC: [raw_msg]\]", runechat_flags = LOOC_MESSAGE)
to_chat(client, span_looc("[span_prefix("[prefix]:")] <EM>[ADMIN_LOOKUPFLW(mob)]:</EM> <span class='message linkify'>[msg]</span>"), type = MESSAGE_TYPE_LOOC, avoid_highlighting = (client == src))
/// Logging for messages sent in LOOC
/proc/log_looc(text, list/data)
logger.Log(LOG_CATEGORY_GAME_LOOC, text, data)
//admin tool
/proc/toggle_looc(toggle = null)
if(!isnull(toggle)) //if we're specifically en/disabling ooc
GLOB.looc_allowed = toggle
else //otherwise just toggle it
GLOB.looc_allowed = !GLOB.looc_allowed
to_chat(world, "<span class='oocplain bold'>LOOC channel has been globally [GLOB.looc_allowed ? "enabled" : "disabled"].</span>")
ADMIN_VERB(togglelooc, R_ADMIN, FALSE, "Toggle LOOC", "Shows the range of cameras on the station.", ADMIN_CATEGORY_SERVER)
toggle_looc()
log_admin("[key_name(user)] toggled LOOC.")
message_admins("[key_name_admin(user)] toggled LOOC.")
SSblackbox.record_feedback("nested tally", "admin_toggle", 1, list("Toggle LOOC", "[GLOB.looc_allowed ? "Enabled" : "Disabled"]")) //If you are copy-pasting this, ensure the 2nd parameter is unique to the new proc!
/proc/is_admin_looc_omnipotent(client/admin)
if(QDELETED(admin))
return FALSE
switch(admin.prefs.read_preference(/datum/preference/choiced/admin_hear_looc))
if("Always")
return TRUE
if("When Observing")
return isdead(admin.mob) || admin.mob.stat == DEAD
else
return FALSE
| 0 | 0.933127 | 1 | 0.933127 | game-dev | MEDIA | 0.577154 | game-dev | 0.983669 | 1 | 0.983669 |
bcgit/bc-csharp | 1,069 | crypto/test/src/pqc/crypto/lms/test/LmsVectorUtilities.cs | using System.IO;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Pqc.Crypto.Lms.Tests
{
public class LmsVectorUtilities
{
public static byte[] ExtractPrefixedBytes(string vectorFromRFC)
{
MemoryStream bos = new MemoryStream();
byte[] hexByte;
foreach (string line in vectorFromRFC.Split('\n'))
{
int start = line.IndexOf('$');
if (start > -1)
{
++start;
int end = line.IndexOf('#');
string hex;
if (end < 0)
{
hex = line.Substring(start).Trim();
}
else
{
hex = line.Substring(start, end - start).Trim();
}
hexByte = Hex.Decode(hex);
bos.Write(hexByte, 0, hexByte.Length);
}
}
return bos.ToArray();
}
}
}
| 0 | 0.572397 | 1 | 0.572397 | game-dev | MEDIA | 0.252854 | game-dev | 0.940707 | 1 | 0.940707 |
shinyquagsire23/OpenJKDF2 | 5,318 | src/Gui/jkGUIObjectives.c | #include "jkGUIObjectives.h"
#include "General/Darray.h"
#include "General/stdBitmap.h"
#include "General/stdFont.h"
#include "General/stdStrTable.h"
#include "General/stdFileUtil.h"
#include "Engine/rdMaterial.h" // TODO move stdVBuffer
#include "stdPlatform.h"
#include "jk.h"
#include "Gui/jkGUIRend.h"
#include "Gui/jkGUI.h"
#include "World/jkPlayer.h"
#include "Win95/stdDisplay.h"
#include "Cog/jkCog.h"
#include "Main/jkStrings.h"
#include "General/stdString.h"
static jkGuiStringEntry jkGuiObjectives_aTexts[50];
static jkGuiElement jkGuiObjectives_elements[6] = {
{ELEMENT_TEXT, 0, 11, "GUI_OBJECTIVES", 3, {0x32, 0x32, 0x1F4, 20}, 1, 0, 0, 0, 0, 0, {0}, 0},
{ELEMENT_TEXT, 0, 9, 0, 3, {0x32, 0x50, 0x1F4, 20}, 1, 0, 0, 0, 0, 0, {0}, 0},
{ELEMENT_CUSTOM, 0, 8, 0, 0, {0x28, 0x6E, 0x208, 0x122}, 1, 0, 0, jkGuiObjectives_CustomRender, 0, 0, {0}, 0},
{ELEMENT_TEXT, 0, 8, 0, 3, {0x28, 0x190, 0x208, 20}, 1, 0, 0, 0, 0, 0, {0}, 0},
{ELEMENT_PICBUTTON, 1, 0, 0, 20, {-1, -1, -1, -1}, 1, 0, 0, 0, 0, 0, {0}, 0},
{ELEMENT_END, 0, 0, 0, 0, {0}, 0, 0, 0, 0, 0, 0, {0}, 0}
};
static jkGuiMenu jkGuiObjectives_menu = {jkGuiObjectives_elements, -1, 0xFFFF, 0xFFFF, 0xF, 0, 0, jkGui_stdBitmaps, jkGui_stdFonts, 0, 0, "thermloop01.wav", "thrmlpu2.wav", 0, 0, 0, 0, 0, 0};
void jkGuiObjectives_CustomRender(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *vbuf, int bRedraw)
{
rdRect drawRect;
if (bRedraw) {
jkGuiRend_CopyVBuffer(menu, &element->rect);
}
drawRect.y = element->rect.y;
int num_objectives = 0;
int font_height = stdFont_sub_4357C0(menu->fonts[8], jkGuiObjectives_aTexts[0].str, &element->rect);
for (int i = 0; i < 50; i++)
{
jkGuiStringEntry* pTextEnt = &jkGuiObjectives_aTexts[i];
int goal_flags = (__int64)sithInventory_GetBinAmount(sithPlayer_pLocalPlayerThing, i + SITHBIN_GOAL00);
if ( (goal_flags & GOAL_EXISTS) != 0 )
{
if ( pTextEnt->str )
{
++num_objectives;
drawRect.width = element->rect.width - 30;
drawRect.x = element->rect.x + 30;
drawRect.height = font_height + stdFont_GetHeight(menu->fonts[element->textType]);
int font_idx = (uint8_t)((goal_flags & GOAL_SECRET) | 0x10) >> 1;
stdFont_Draw2(vbuf, menu->fonts[font_idx], drawRect.x, drawRect.y, &drawRect, pTextEnt->str, 1);
int font_height_2 = stdFont_sub_4357C0(menu->fonts[font_idx], pTextEnt->str, &drawRect);
stdDisplay_VBufferCopy(
vbuf,
jkGui_stdBitmaps[JKGUI_BM_OBJECTIVESCHECK]->mipSurfaces[(uint8_t)(goal_flags & GOAL_COMPLETE) >> 1],
element->rect.x,
drawRect.y + ((unsigned int)(font_height_2 - (*jkGui_stdBitmaps[JKGUI_BM_OBJECTIVESCHECK]->mipSurfaces)->format.height) >> 1),
0,
1);
font_height = stdFont_GetHeight(menu->fonts[element->textType]) + font_height_2;
drawRect.y += font_height;
}
}
}
if ( !num_objectives )
{
stdFont_Draw1(vbuf, menu->fonts[element->textType], element->rect.x + 30, element->rect.y, element->rect.width, jkStrings_GetUniStringWithFallback("GUI_NO_OBJECTIVES"), 1);
}
}
int jkGuiObjectives_Show()
{
int v0; // ebx
int v1; // esi
jkGuiStringEntry *v2; // edi
wchar_t *v3; // eax
int v4; // esi
flex_d_t v5; // st7
wchar_t *v6; // eax
wchar_t *v7; // eax
wchar_t *v9; // [esp-4h] [ebp-90h]
wchar_t v10[32]; // [esp+Ch] [ebp-80h] BYREF
char key[64]; // [esp+4Ch] [ebp-40h] BYREF
_memset(jkGuiObjectives_aTexts, 0, sizeof(jkGuiObjectives_aTexts));
v0 = (__int64)sithInventory_GetBinAmount(sithPlayer_pLocalPlayerThing, 99);
if ( v0 )
{
for (v1 = 0; v1 < 50; v1++)
{
v2 = &jkGuiObjectives_aTexts[v1];
stdString_snprintf(key, 64, "GOAL_%05d", v0 + v1);
// Added: Allow openjkdf2_i8n.uni to override everything
#ifdef QOL_IMPROVEMENTS
v3 = stdStrTable_GetUniString(&jkStrings_tableExtOver, key);
if ( !v3 )
#endif
v3 = stdStrTable_GetUniString(&jkCog_strings, key);
if ( v3 )
v2->str = v3;
}
}
v4 = (__int64)sithPlayer_GetBinAmt(SITHBIN_SECRETS);
v5 = sithPlayer_GetBinAmt(SITHBIN_MAXSECRETS);
if ( (int)(__int64)v5 <= 0 )
{
v9 = jkStrings_GetUniStringWithFallback("GUI_NO_SECRETS");
v7 = jkStrings_GetUniStringWithFallback("GUI_SECRETS_FOUND");
jk_snwprintf(v10, 0x20u, L"%ls %ls", v7, v9);
}
else
{
v6 = jkStrings_GetUniStringWithFallback("GUI_SECRETS_FOUND");
jk_snwprintf(v10, 0x20u, L"%ls %d/%d", v6, v4, (unsigned int)(__int64)v5);
}
jkGuiObjectives_elements[3].wstr = v10;
jkGuiObjectives_elements[1].wstr = jkGui_sub_412ED0();
return jkGuiRend_DisplayAndReturnClicked(&jkGuiObjectives_menu);
}
void jkGuiObjectives_Startup()
{
jkGui_InitMenu(&jkGuiObjectives_menu, jkGui_stdBitmaps[JKGUI_BM_BK_FIELD_LOG]);
}
void jkGuiObjectives_Shutdown()
{
;
}
| 0 | 0.927843 | 1 | 0.927843 | game-dev | MEDIA | 0.652445 | game-dev | 0.832688 | 1 | 0.832688 |
RCInet/LastEpoch_Mods | 1,499 | AssetBundleExport/Library/PackageCache/com.unity.ugui@9496653a3df6/Tests/Editor/UGUI/EventSystem/EventTriggerRemoveDuringExecution.cs | using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
public class EventTriggerRemoveDuringExecution
{
[Test]
[Description("ArgumentOutOfRange Exception is thrown when removing handler in callback in EventTrigger (case 1401557)")]
public void EventTrigger_DoesNotThrowExceptionWhenRemovingEventDuringExecution()
{
var go = new GameObject();
var eventTrigger = go.AddComponent<EventTrigger>();
var eventSystem = go.AddComponent<EventSystem>();
var entry1 = new EventTrigger.Entry { eventID = EventTriggerType.PointerDown };
var entry2 = new EventTrigger.Entry { eventID = EventTriggerType.PointerDown };
bool executed1 = false;
bool executed2 = false;
entry1.callback.AddListener(e =>
{
executed1 = true;
eventTrigger.triggers.Remove(entry2);
});
entry2.callback.AddListener(e => executed2 = true);
eventTrigger.triggers.Add(entry1);
eventTrigger.triggers.Add(entry2);
Assert.DoesNotThrow(() => eventTrigger.OnPointerDown(new PointerEventData(eventSystem)));
Assert.True(executed1, "Expected Event 1 to be called but it was not.");
Assert.False(executed2, "Expected Event 2 to not be called as it was removed by event 1.");
Assert.That(eventTrigger.triggers, Does.Not.Contains(entry2));
Assert.That(eventTrigger.triggers, Does.Contain(entry1));
Object.DestroyImmediate(go);
}
}
| 0 | 0.753413 | 1 | 0.753413 | game-dev | MEDIA | 0.910628 | game-dev | 0.683667 | 1 | 0.683667 |
dudykr/stc | 1,318 | crates/stc_ts_file_analyzer/src/util/graph.rs | use std::{
cmp::Ordering,
hash::{Hash, Hasher},
marker::PhantomData,
};
// Used to get a `Copy` type
pub(crate) struct Inliner<T>
where
T: Eq,
{
inner: Vec<T>,
}
impl<T> Inliner<T>
where
T: Eq,
{
pub fn inline(&mut self, t: T) -> NodeId<T> {
for (index, item) in self.inner.iter().enumerate() {
if *item == t {
return NodeId(index, PhantomData);
}
}
self.inner.push(t);
NodeId(self.inner.len() - 1, PhantomData)
}
}
impl<T> Default for Inliner<T>
where
T: Eq,
{
fn default() -> Self {
Self { inner: Default::default() }
}
}
pub(crate) struct NodeId<T>(usize, PhantomData<T>);
impl<T> Clone for NodeId<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for NodeId<T> {}
impl<T> PartialEq for NodeId<T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T> Eq for NodeId<T> {}
impl<T> PartialOrd for NodeId<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for NodeId<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl<T> Hash for NodeId<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
| 0 | 0.932132 | 1 | 0.932132 | game-dev | MEDIA | 0.443468 | game-dev | 0.946397 | 1 | 0.946397 |
datvm/TimberbornMods | 1,099 | BuildingHP/Services/Renovations/Providers/ReinforceRenovationProviders.cs | namespace BuildingHP.Services.Renovations.Providers;
public abstract class BaseReinforceRenovationProvider(DefaultRenovationProviderDependencies di) : DefaultRenovationProvider(di)
{
public int ExtraHP => (int)RenovationSpec.Parameters[0];
public override string? CanRenovate(BuildingRenovationComponent building)
{
var reinf = building.GetComponentFast<BuildingReinforcementComponent>();
return reinf.Delta is null || ExtraHP > reinf.Delta.Value
? null
: t.T("LV.BHP.HigherReinforce");
}
}
public class Reinforce1RenovationProvider(DefaultRenovationProviderDependencies di) : BaseReinforceRenovationProvider(di)
{
public override string Id { get; } = "Reinforce1";
}
public class Reinforce2RenovationProvider(DefaultRenovationProviderDependencies di) : BaseReinforceRenovationProvider(di)
{
public override string Id { get; } = "Reinforce2";
}
public class Reinforce3RenovationProvider(DefaultRenovationProviderDependencies di) : BaseReinforceRenovationProvider(di)
{
public override string Id { get; } = "Reinforce3";
}
| 0 | 0.907267 | 1 | 0.907267 | game-dev | MEDIA | 0.509874 | game-dev | 0.723392 | 1 | 0.723392 |
tdouguo/KIT | 2,811 | kit-unity/Common/UnityExtend/UI/PageScroll.cs | // ----------------------------------------------------------------------------------------------------
// Copyright © Guo jin ming. All rights reserved.
// Homepage: https://kylin.app/
// E-Mail: kevin@kylin.app
// ----------------------------------------------------------------------------------------------------
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Kit
{
public class PageScroll : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
private ScrollRect scrollRect;
private float targetHorizontalPosition = 0f;
private bool isDraging = false;
[SerializeField] private float[] pageRatio = null;
public float speed = 5f;
public int maxPage = 1;
public int page = 0;
public UnityAction<PageScroll> onSwitchPageEvent = null;
private void Awake()
{
scrollRect = transform.GetComponent<ScrollRect>();
float _meanRatio = 1f / (maxPage - 1);
pageRatio = new float[maxPage];
float _tempRatio = 0;
for (int i = 0; i < pageRatio.Length; i++)
{
pageRatio[i] = _tempRatio;
_tempRatio += _meanRatio;
}
}
private void Update()
{
//如果不判断。当在拖拽的时候要也会执行插值,所以会出现闪烁的效果
//这里只要在拖动结束的时候。在进行插值
if (!isDraging)
{
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,
targetHorizontalPosition, Time.deltaTime * speed);
}
}
#region .... EventSystem
/// <summary>
/// 拖动开始
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
isDraging = true;
}
#endregion
/// <summary>
/// 拖拽结束
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
isDraging = false;
// 得到 水平滑动的 值 (0-1)
float posX = scrollRect.horizontalNormalizedPosition;
int index = 0;
float offset = Mathf.Abs(posX - pageRatio[index]);
// 与 前后比较 距离最短
for (int i = 1; i < pageRatio.Length; i++)
{
// 距离 最短
float offsetTemp = Mathf.Abs(posX - pageRatio[i]);
if (offset > offsetTemp)
{
index = i;
offset = offsetTemp;
}
}
targetHorizontalPosition = pageRatio[index];
//ToggleArray[index].isOn = true;
}
}
}
| 0 | 0.777324 | 1 | 0.777324 | game-dev | MEDIA | 0.52685 | game-dev | 0.879274 | 1 | 0.879274 |
doldecomp/sms | 6,508 | include/Enemy/Hinokuri2.hpp | #ifndef ENEMY_HINOKURI2_HPP
#define ENEMY_HINOKURI2_HPP
#include <Enemy/Enemy.hpp>
#include <Enemy/EnemyManager.hpp>
#include <Enemy/FeetInv.hpp>
class TWaterEmitInfo;
class TMBindShadowBody;
class THino2Params : public TSpineEnemyParams {
public:
THino2Params(const char*);
// TODO: did they really have accessors for all of these or nah???
// fabricated
int getSLFreezeTimerLv0() { return mSLFreezeTimerLv0.get(); }
int getSLDamageTimer() { return mSLDamageTimer.get(); }
f32 getSLDamageHeadScale() { return mSLDamageHeadScale.get(); }
/* 0xA8 */ TParamRT<f32> mSLMarchSpeedLv0;
/* 0xBC */ TParamRT<f32> mSLMarchSpeedLv1;
/* 0xD0 */ TParamRT<f32> mSLMarchSpeedLv2;
/* 0xE4 */ TParamRT<f32> mSLTurnSpeedLv0;
/* 0xF8 */ TParamRT<f32> mSLTurnSpeedLv1;
/* 0x10C */ TParamRT<f32> mSLTurnSpeedLv2;
/* 0x120 */ TParamRT<f32> mSLBodyScale;
/* 0x134 */ TParamRT<f32> mSLWalkShake;
/* 0x148 */ TParamRT<f32> mSLJumpShake;
/* 0x15C */ TParamRT<f32> mSLGravityY;
/* 0x170 */ TParamRT<s32> mSLPrePolWait;
/* 0x184 */ TParamRT<s32> mSLPolWaitCount;
/* 0x198 */ TParamRT<s32> mSLPolIntervalMin;
/* 0x1AC */ TParamRT<s32> mSLPolIntervalMax;
/* 0x1C0 */ TParamRT<f32> mSLDamageHeadScale;
/* 0x1D4 */ TParamRT<s32> mSLDamageTimer;
/* 0x1E8 */ TParamRT<f32> mSLHeadHitR;
/* 0x1FC */ TParamRT<f32> mSLHeadHitH;
/* 0x210 */ TParamRT<f32> mSLBodyHitR;
/* 0x224 */ TParamRT<f32> mSLBodyHitH;
/* 0x238 */ TParamRT<f32> mSLBodyHitR0;
/* 0x24C */ TParamRT<f32> mSLBodyHitH0;
/* 0x260 */ TParamRT<f32> mSLBankProp;
/* 0x274 */ TParamRT<f32> mSLBankLimit;
/* 0x288 */ TParamRT<f32> mSLJumpQuakeLen;
/* 0x29C */ TParamRT<f32> mSLStampProb;
/* 0x2B0 */ TParamRT<s32> mSLStampCount;
/* 0x2C4 */ TParamRT<f32> mSLStampQuakeLen;
/* 0x2D8 */ TParamRT<f32> mSLWaterEmitPos;
/* 0x2EC */ TParamRT<u8> mSLHitPointMaxLv0;
/* 0x300 */ TParamRT<u8> mSLHitPointMaxLv1;
/* 0x314 */ TParamRT<u8> mSLHitPointMaxLv2;
/* 0x328 */ TParamRT<s32> mSLFreezeTimerLv0;
/* 0x33C */ TParamRT<s32> mSLInvincibleTimer;
/* 0x350 */ TParamRT<f32> mSLWalkSpeedRateLv0;
};
class THinokuri2Manager : public TEnemyManager {
public:
THinokuri2Manager(const char*);
virtual void load(JSUMemoryInputStream&);
void createModelData();
TSpineEnemy* createEnemyInstance();
};
class THino2MtxCalc : public TMtxCalcFootInv {
public:
THino2MtxCalc(u16, u16, u16, u16, u16, u16, f32);
virtual void calc(u16);
// fabricated
void setTransform(J3DAnmTransform* trans) { mOne[0] = trans; }
void addTransform(J3DAnmTransform* trans)
{
if (mOne[0] != trans) {
mOne[1] = mOne[0];
mOne[0] = trans;
unk78 = 1.0f;
}
}
public:
/* 0x78 */ f32 unk78;
};
class THinokuri2;
class THino2Hit : public THitActor {
public:
THino2Hit(THinokuri2* owner, int joint_idx, const char* name);
virtual void perform(u32, JDrama::TGraphics*);
virtual BOOL receiveMessage(THitActor* sender, u32 message);
public:
/* 0x68 */ THinokuri2* mOwner;
/* 0x6C */ int mJointIdx;
};
class THino2Mask {
public:
THino2Mask(THinokuri2*);
void setMatrix(MtxPtr);
void breakMask();
void startDamageMotion();
void perform(u32, JDrama::TGraphics*);
// fabricated
void reset()
{
unk4 = 2;
unk8 = 0;
unk1C.zero();
unk28.zero();
unk34.set(0.0f, 0.0f, -5.0f);
unk40.set(0.0f, 0.0f, 5.0f);
}
MtxPtr getUnk4C() { return unk4C; }
public:
/* 0x0 */ THinokuri2* unk0;
/* 0x4 */ int unk4;
/* 0x8 */ int unk8;
/* 0xC */ int unkC;
/* 0x10 */ MActor* unk10;
/* 0x14 */ MActor* unk14;
/* 0x18 */ MActor* unk18;
/* 0x1C */ JGeometry::TVec3<f32> unk1C;
/* 0x28 */ JGeometry::TVec3<f32> unk28;
/* 0x34 */ JGeometry::TVec3<f32> unk34;
/* 0x40 */ JGeometry::TVec3<f32> unk40;
/* 0x4C */ Mtx unk4C;
};
class THinokuri2 : public TSpineEnemy {
public:
THinokuri2(const char*);
virtual void perform(u32, JDrama::TGraphics*);
virtual BOOL receiveMessage(THitActor* sender, u32 message);
virtual void init(TLiveManager*);
virtual void moveObject();
virtual void kill();
virtual void reset();
void emitPolParticle();
void stopPolParticle();
void updatePolTrans();
void resetPolInterval();
void invalidateCollisionAll();
void validateCollisionAll();
void emitWaterParticle();
void shakeCamera(int);
void makeQuake(f32);
void setLevel(int);
void generateEnemy();
void updateAnmSound();
void changeBck(int);
BOOL receiveMessageLv0(THitActor*, u32);
BOOL receiveMessageLv1(THitActor*, u32);
BOOL receiveMessageLv2(THitActor*, u32);
// fabricated
THino2Params* getSaveParam() const
{
return (THino2Params*)TSpineEnemy::getSaveParam();
}
// fabricated
u8 calcHitPoints()
{
switch (mLevel) {
case 0:
return getSaveParam()->mSLHitPointMaxLv0.get();
break;
case 1:
return getSaveParam()->mSLHitPointMaxLv1.get();
break;
case 2:
return getSaveParam()->mSLHitPointMaxLv2.get();
break;
default:
if (getSaveParam())
return getSaveParam()->mSLHitPointMax.get();
break;
}
return 1;
}
// fabricated
int getCurrentBck() const { return mCurrentBck; }
int getUnk160() const { return mWaitTimer; }
void setUnk160(int v) { mWaitTimer = v; }
s32 getLevel() const { return mLevel; }
public:
/* 0x150 */ TMBindShadowBody* unk150;
/* 0x154 */ int mCurrentBck;
/* 0x158 */ int unk158;
/* 0x15C */ u32 unk15C;
/* 0x160 */ int mWaitTimer;
/* 0x164 */ int unk164;
/* 0x168 */ int unk168;
/* 0x16C */ THino2Hit* mHead;
/* 0x170 */ THino2Hit* mBody;
/* 0x174 */ THino2Hit* unk174;
/* 0x178 */ THino2Hit* unk178;
/* 0x17C */ int mJointIdxMessageCameFrom;
/* 0x180 */ BOOL unk180;
/* 0x184 */ u32 unk184;
/* 0x188 */ int unk188;
/* 0x18C */ int unk18C;
/* 0x190 */ int unk190;
/* 0x194 */ f32 unk194;
/* 0x198 */ f32 unk198;
/* 0x19C */ TWaterEmitInfo* unk19C;
/* 0x1A0 */ THino2MtxCalc* unk1A0;
/* 0x1A4 */ THino2Mask* unk1A4;
/* 0x1A8 */ s32 mLevel;
};
DECLARE_NERVE(TNerveHino2Appear, TLiveActor);
DECLARE_NERVE(TNerveHino2GraphWander, TLiveActor);
DECLARE_NERVE(TNerveHino2Fly, TLiveActor);
DECLARE_NERVE(TNerveHino2JumpIn, TLiveActor);
DECLARE_NERVE(TNerveHino2Landing, TLiveActor);
DECLARE_NERVE(TNerveHino2Turn, TLiveActor);
DECLARE_NERVE(TNerveHino2PrePol, TLiveActor);
DECLARE_NERVE(TNerveHino2Pollute, TLiveActor);
DECLARE_NERVE(TNerveHino2Damage, TLiveActor);
DECLARE_NERVE(TNerveHino2Squat, TLiveActor);
DECLARE_NERVE(TNerveHino2Burst, TLiveActor);
DECLARE_NERVE(TNerveHino2Die, TLiveActor);
DECLARE_NERVE(TNerveHino2Stamp, TLiveActor);
DECLARE_NERVE(TNerveHino2Freeze, TLiveActor);
DECLARE_NERVE(TNerveHino2WaitAnm, TLiveActor);
#endif
| 0 | 0.757173 | 1 | 0.757173 | game-dev | MEDIA | 0.618073 | game-dev | 0.572034 | 1 | 0.572034 |
dwjclark11/Scion2D | 7,907 | _Games/Asteroids/Asteroids/SCION_2D/content/scripts/collision_system.lua | --[[
Copyright 2025 @JADE-ite Games Studios. All rights reserved
--]]
-------------------------------------------------------------------
-- @class CollisionData
-- @brief Represents information about a collision event.
-- Stores entity ID, damage amount, and destruction flag.
-------------------------------------------------------------------
CollisionData = S2D_Class("CollisionData")
-------------------------------------------------------------------
-- @brief Initializes a new CollisionData object.
-- @param params table Table containing collision data parameters:
-- - id (integer) Entity ID involved in the collision.
-- - damage (integer) Optional damage value (default = 10).
-- - bDestroy (boolean) Whether entity should be destroyed (default = false).
-------------------------------------------------------------------
function CollisionData:Init(params)
self.id = params.id
self.damage = params.damage or 10
self.bDestroy = params.bDestroy or false
end
-------------------------------------------------------------------
-- @class CollisionSystem
-- @brief Manages collision detection and resolution.
-- Handles asteroid, projectile, ship, and pickup interactions.
-------------------------------------------------------------------
CollisionSystem = S2D_Class("CollisionSystem")
-------------------------------------------------------------------
-- @brief Initializes the collision system.
-- @param params table Optional parameters (currently unused).
-------------------------------------------------------------------
function CollisionSystem:Init(params)
params = params or {}
self.collisionEventDispatcher = EventDispatcher(DispatcherType.Lua)
self.collisionHandler = LuaEventHandler( function(event) self:HandleEvent(event) end )
self.pickupHandler = LuaEventHandler( function (event) self:HandlePickups(event) end )
self.collisionEventDispatcher:addHandler(self.collisionHandler, LuaEvent)
self.collisionEventDispatcher:addHandler(self.pickupHandler, LuaEvent)
self.entitiesToDestroy = {}
end
-------------------------------------------------------------------
-- @brief Updates the collision system.
-- Runs circle collision detection for all relevant entities.
-------------------------------------------------------------------
function CollisionSystem:Update()
self:UpdateCircleCollision()
end
-------------------------------------------------------------------
-- @brief Detects and processes circle collider collisions.
-- Iterates through entities, checks intersections, and dispatches events.
-------------------------------------------------------------------
function CollisionSystem:UpdateCircleCollision()
local reg = Registry()
local entities = reg:getEntities( CircleCollider )
self.entitiesToDestroy = {}
entities:for_each(
function(entity_a)
entities:for_each(
function(entity_b)
if entity_a:id() == entity_b:id() then
goto continue
end
if self:Intersect(entity_a, entity_b) then
self.collisionEventDispatcher:emitEvent( LuaEvent( { entityA = entity_a:id(), entityB = entity_b:id() } ))
end
::continue::
end
)
end
)
for k, v in pairs(self.entitiesToDestroy) do
local entity = Entity(v.id)
if entity:group() == "asteroids" then
gAsteroidHandler:DestroyAsteroid(entity:id())
elseif entity:group() == "projectiles" then
gProjectileHandler:DestroyProjectile(entity:id())
elseif entity:name() == "PlayerShip" then
gShipHandler:TakeDamage(v)
end
end
-- Handle enqueued events
self.collisionEventDispatcher:update()
end
-------------------------------------------------------------------
-- @brief Gets the center position of an entity for collision checks.
-- @param entity Entity The entity whose center is calculated.
-- @return vec2 The center position of the entity.
-------------------------------------------------------------------
function CollisionSystem:GetCenter(entity)
local transform = entity:getComponent(Transform)
local sprite = entity:getComponent(Sprite)
local centerSprite = vec2(sprite.width / 2, sprite.height / 2)
local center = transform.position + centerSprite
return center
end
-------------------------------------------------------------------
-- @brief Checks if two entities intersect using circle colliders.
-- @param entity_a Entity First entity.
-- @param entity_b Entity Second entity.
-- @return boolean True if entities intersect, false otherwise.
-------------------------------------------------------------------
function CollisionSystem:Intersect(entity_a, entity_b)
local a_center = self:GetCenter(entity_a)
local b_center = self:GetCenter(entity_b)
local difference = a_center - b_center
-- Calculate the distance squared
local distanceSq = difference:lengthSq()
-- Get the circle collider for the radius
local circle_a = entity_a:getComponent(CircleCollider)
local circle_b = entity_b:getComponent(CircleCollider)
local radSum = circle_a.radius + circle_b.radius
local radSqr = radSum * radSum
return distanceSq <= radSqr
end
-------------------------------------------------------------------
-- @brief Handles collision events between entities.
-- @param event LuaEvent The collision event containing entity IDs.
-------------------------------------------------------------------
function CollisionSystem:HandleEvent(event)
local entityA = Entity(event.data.entityA)
local entityB = Entity(event.data.entityB)
local group_a = entityA:group()
local group_b = entityB:group()
if group_a == group_b then
return
end
local collider_a = entityA:getComponent(CircleCollider)
local collider_b = entityB:getComponent(CircleCollider)
if collider_a.bColliding or collider_b.bColliding then
return
end
local name_a = entityA:name()
local name_b = entityB:name()
if group_a == "projectiles" and group_b == "asteroids" then
collider_a.bColliding = true
collider_b.bColliding = true
S2D_InsertUnique(self.entitiesToDestroy,
CollisionData:Create({ id = entityB:id(), bDestroy = true })
)
S2D_InsertUnique(self.entitiesToDestroy,
CollisionData:Create({ id = entityA:id(), bDestroy = true })
)
elseif group_b == "projectiles" and group_a == "asteroids" then
collider_a.bColliding = true
collider_b.bColliding = true
S2D_InsertUnique(self.entitiesToDestroy,
CollisionData:Create({ id = entityA:id(), bDestroy = true })
)
S2D_InsertUnique(self.entitiesToDestroy,
CollisionData:Create({ id = entityB:id(), bDestroy = true })
)
elseif name_a == "PlayerShip" and group_b == "asteroids" then
collider_a.bColliding = true
S2D_InsertUnique(self.entitiesToDestroy,
CollisionData:Create({ id = entityA:id(), damage = 25 })
)
elseif name_b == "PlayerShip" and group_a == "asteroids" then
collider_b.bColliding = true
S2D_InsertUnique(self.entitiesToDestroy,
CollisionData:Create({ id = entityB:id(), damage = 25 })
)
elseif name_a == "PlayerShip" and group_b == "pickups" then
self.collisionEventDispatcher:enqueueEvent(
LuaEvent(
{ bIsPickup = true, shipID = entityA:id(), pickupID = entityB:id() }
)
)
elseif name_b == "PlayerShip" and group_a == "pickups" then
self.collisionEventDispatcher:enqueueEvent(
LuaEvent(
{ bIsPickup = true, shipID = entityB:id(), pickupID = entityA:id() }
)
)
end
end
-------------------------------------------------------------------
-- @brief Handles pickup collision events.
-- @param event LuaEvent Event containing ship and pickup IDs.
-------------------------------------------------------------------
function CollisionSystem:HandlePickups(event)
if not event.data.bIsPickup then
return
end
local ship = gShipHandler:GetShipByID(event.data.shipID)
if not ship then
S2D_warn("Failed to handle pickup. Ship is not valid")
return
end
gPickupHandler:OnHandlePickup(event.data.pickupID, ship)
end
| 0 | 0.83173 | 1 | 0.83173 | game-dev | MEDIA | 0.940584 | game-dev | 0.803726 | 1 | 0.803726 |
turesnake/tprPix | 2,284 | src/Script/gameObjs/majorGos/artifacts/StoneWall.cpp | /*
* ========================= StoneWall.cpp ==========================
* -- tpr --
* CREATE -- 2019.11.16
* MODIFY --
* ----------------------------------------------------------
*/
#include "pch.h"
#include "Script/gameObjs/majorGos/artifacts/StoneWall.h"
//-------------------- Engine --------------------//
#include "animSubspeciesId.h"
#include "dyParams.h"
#include "GoSpecFromJson.h"
#include "assemble_go.h"
//-------------------- Script --------------------//
using namespace std::placeholders;
namespace gameObjs {//------------- namespace gameObjs ----------------
struct StoneWall_PvtBinary{
int tmp {};
};
void StoneWall::init(GameObj &goRef_,const DyParam &dyParams_ ){
//================ go.pvtBinary =================//
auto *pvtBp = goRef_.init_pvtBinary<StoneWall_PvtBinary>();
//========== 标准化装配 ==========//
assemble_regularGo( goRef_, dyParams_ );
//================ bind callback funcs =================//
//-- 故意将 首参数this 绑定到 保留类实例 dog_a 身上
goRef_.RenderUpdate = std::bind( &StoneWall::OnRenderUpdate, _1 );
goRef_.LogicUpdate = std::bind( &StoneWall::OnLogicUpdate, _1 );
//-------- actionSwitch ---------//
goRef_.actionSwitch.bind_func( std::bind( &StoneWall::OnActionSwitch, _1, _2 ) );
goRef_.actionSwitch.signUp( ActionSwitchType::Idle );
//================ go self vals =================//
}
void StoneWall::OnRenderUpdate( GameObj &goRef_ ){
//=====================================//
// ptr rebind
//-------------------------------------//
//auto *pvtBp = goRef_.get_pvtBinaryPtr<StoneWall_PvtBinary>();
//=====================================//
// 将 确认要渲染的 goMeshs,添加到 renderPool
//-------------------------------------//
goRef_.goMeshSet.render_all_goMeshs_without_callback();
}
void StoneWall::bind( GameObj &goRef_ ){}
void StoneWall::rebind( GameObj &goRef_ ){}
void StoneWall::OnLogicUpdate( GameObj &goRef_ ){}
void StoneWall::OnActionSwitch( GameObj &goRef_, ActionSwitchType type_ ){
tprAssert(0);
}
}//------------- namespace gameObjs: end ----------------
| 0 | 0.843177 | 1 | 0.843177 | game-dev | MEDIA | 0.883848 | game-dev | 0.544725 | 1 | 0.544725 |
magefree/mage | 2,829 | Mage.Sets/src/mage/cards/t/TwoHandedAxe.java | package mage.cards.t;
import mage.abilities.Ability;
import mage.abilities.common.AttacksAttachedTriggeredAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.continuous.BoostTargetEffect;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.DoubleStrikeAbility;
import mage.abilities.keyword.EquipAbility;
import mage.cards.AdventureCard;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.common.TargetControlledCreaturePermanent;
import mage.target.targetpointer.FixedTarget;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class TwoHandedAxe extends AdventureCard {
public TwoHandedAxe(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, new CardType[]{CardType.INSTANT}, "{2}{R}", "Sweeping Cleave", "{1}{R}");
this.subtype.add(SubType.EQUIPMENT);
// Whenever equipped creature attacks, double its power until end of turn.
this.addAbility(new AttacksAttachedTriggeredAbility(
new TwoHandedAxeEffect(), AttachmentType.EQUIPMENT, false, SetTargetPointer.PERMANENT
));
// Equip {1}{R}
this.addAbility(new EquipAbility(Outcome.AddAbility, new ManaCostsImpl<>("{1}{R}"), false));
// Sweeping Cleave
// Target creature you control gains double strike until end of turn.
this.getSpellCard().getSpellAbility().addEffect(new GainAbilityTargetEffect(DoubleStrikeAbility.getInstance()));
this.getSpellCard().getSpellAbility().addTarget(new TargetControlledCreaturePermanent());
this.finalizeAdventure();
}
private TwoHandedAxe(final TwoHandedAxe card) {
super(card);
}
@Override
public TwoHandedAxe copy() {
return new TwoHandedAxe(this);
}
}
class TwoHandedAxeEffect extends OneShotEffect {
TwoHandedAxeEffect() {
super(Outcome.Benefit);
staticText = "double its power until end of turn";
}
private TwoHandedAxeEffect(final TwoHandedAxeEffect effect) {
super(effect);
}
@Override
public TwoHandedAxeEffect copy() {
return new TwoHandedAxeEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent permanent = game.getPermanent(getTargetPointer().getFirst(game, source));
if (permanent == null || permanent.getPower().getValue() == 0) {
return false;
}
game.addEffect(new BoostTargetEffect(
permanent.getPower().getValue(), 0
).setTargetPointer(new FixedTarget(permanent, game)), source);
return true;
}
}
| 0 | 0.976047 | 1 | 0.976047 | game-dev | MEDIA | 0.982837 | game-dev | 0.995083 | 1 | 0.995083 |
Goob-Station/Goob-Station-MRP | 8,598 | Content.Shared/Storage/EntitySystems/SecretStashSystem.cs | using Content.Shared.Popups;
using Content.Shared.Storage.Components;
using Content.Shared.Destructible;
using Content.Shared.Hands.Components;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Item;
using Robust.Shared.Containers;
using Content.Shared.Interaction;
using Content.Shared.Tools.Systems;
using Content.Shared.Examine;
namespace Content.Shared.Storage.EntitySystems
{
/// <summary>
/// Secret Stash allows an item to be hidden within.
/// </summary>
public sealed class SecretStashSystem : EntitySystem
{
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly SharedHandsSystem _handsSystem = default!;
[Dependency] private readonly SharedContainerSystem _containerSystem = default!;
[Dependency] private readonly SharedItemSystem _item = default!;
[Dependency] private readonly SharedToolSystem _tool = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SecretStashComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<SecretStashComponent, DestructionEventArgs>(OnDestroyed);
SubscribeLocalEvent<SecretStashComponent, StashPryDoAfterEvent>(OnSecretStashPried);
SubscribeLocalEvent<SecretStashComponent, InteractUsingEvent>(OnInteractUsing);
SubscribeLocalEvent<SecretStashComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<SecretStashComponent, ExaminedEvent>(OnExamine);
}
private void OnInit(EntityUid uid, SecretStashComponent component, ComponentInit args)
{
component.ItemContainer = _containerSystem.EnsureContainer<ContainerSlot>(uid, "stash", out _);
}
private void OnDestroyed(EntityUid uid, SecretStashComponent component, DestructionEventArgs args)
{
_containerSystem.EmptyContainer(component.ItemContainer);
}
/// <summary>
/// Is there something inside secret stash item container?
/// </summary>
public bool HasItemInside(EntityUid uid, SecretStashComponent? component = null)
{
if (!Resolve(uid, ref component))
return false;
return component.ItemContainer.ContainedEntity != null;
}
private void OnInteractUsing(EntityUid uid, SecretStashComponent component, InteractUsingEvent args)
{
if (args.Handled)
return;
if (!component.OpenableStash)
return;
// is player trying place or lift off cistern lid?
if (_tool.UseTool(args.Used, args.User, uid, component.PryDoorTime, component.PryingQuality, new StashPryDoAfterEvent()))
args.Handled = true;
// maybe player is trying to hide something inside cistern?
else if (component.ToggleOpen)
{
TryHideItem(uid, args.User, args.Used);
args.Handled = true;
}
}
private void OnInteractHand(EntityUid uid, SecretStashComponent component, InteractHandEvent args)
{
if (args.Handled)
return;
if (!component.OpenableStash)
return;
// trying to get something from stash?
if (component.ToggleOpen)
{
var gotItem = TryGetItem(uid, args.User);
if (gotItem)
{
args.Handled = true;
return;
}
}
args.Handled = true;
}
private void OnSecretStashPried(EntityUid uid, SecretStashComponent component, StashPryDoAfterEvent args)
{
if (args.Cancelled)
return;
ToggleOpen(uid, component);
}
public void ToggleOpen(EntityUid uid, SecretStashComponent? component = null, MetaDataComponent? meta = null)
{
if (!Resolve(uid, ref component))
return;
component.ToggleOpen = !component.ToggleOpen;
UpdateAppearance(uid, component);
Dirty(uid, component, meta);
}
private void UpdateAppearance(EntityUid uid, SecretStashComponent? component = null)
{
if (!Resolve(uid, ref component))
return;
_appearance.SetData(uid, StashVisuals.DoorVisualState, component.ToggleOpen ? DoorVisualState.DoorOpen : DoorVisualState.DoorClosed);
}
/// <summary>
/// Tries to hide item inside secret stash from hands of user.
/// </summary>
/// <returns>True if item was hidden inside stash</returns>
public bool TryHideItem(EntityUid uid, EntityUid userUid, EntityUid itemToHideUid,
SecretStashComponent? component = null, ItemComponent? item = null,
HandsComponent? hands = null)
{
if (!Resolve(uid, ref component))
return false;
if (!Resolve(itemToHideUid, ref item))
return false;
if (!Resolve(userUid, ref hands))
return false;
// check if secret stash is already occupied
var container = component.ItemContainer;
if (container.ContainedEntity != null)
{
var msg = Loc.GetString("comp-secret-stash-action-hide-container-not-empty");
_popupSystem.PopupClient(msg, uid, userUid);
return false;
}
// check if item is too big to fit into secret stash
if (_item.GetSizePrototype(item.Size) > _item.GetSizePrototype(component.MaxItemSize))
{
var msg = Loc.GetString("comp-secret-stash-action-hide-item-too-big",
("item", itemToHideUid), ("stash", GetSecretPartName(uid, component)));
_popupSystem.PopupClient(msg, uid, userUid);
return false;
}
// try to move item from hands to stash container
if (!_handsSystem.TryDropIntoContainer(userUid, itemToHideUid, container))
{
return false;
}
// all done, show success message
var successMsg = Loc.GetString("comp-secret-stash-action-hide-success",
("item", itemToHideUid), ("this", GetSecretPartName(uid, component)));
_popupSystem.PopupClient(successMsg, uid, userUid);
return true;
}
/// <summary>
/// Try get item and place it in users hand.
/// If user can't take it by hands, will drop item from container.
/// </summary>
/// <returns>True if user received item</returns>
public bool TryGetItem(EntityUid uid, EntityUid userUid, SecretStashComponent? component = null,
HandsComponent? hands = null)
{
if (!Resolve(uid, ref component))
return false;
if (!Resolve(userUid, ref hands))
return false;
// check if secret stash has something inside
var container = component.ItemContainer;
if (container.ContainedEntity == null)
{
return false;
}
_handsSystem.PickupOrDrop(userUid, container.ContainedEntity.Value, handsComp: hands);
// show success message
var successMsg = Loc.GetString("comp-secret-stash-action-get-item-found-something",
("stash", GetSecretPartName(uid, component)));
_popupSystem.PopupClient(successMsg, uid, userUid);
return true;
}
private void OnExamine(EntityUid uid, SecretStashComponent component, ExaminedEvent args)
{
if (args.IsInDetailsRange && component.ToggleOpen)
{
if (HasItemInside(uid))
{
var msg = Loc.GetString(component.ExamineStash);
args.PushMarkup(msg);
}
}
}
private string GetSecretPartName(EntityUid uid, SecretStashComponent stash)
{
if (stash.SecretPartName != "")
return Loc.GetString(stash.SecretPartName);
var entityName = Loc.GetString("comp-secret-stash-secret-part-name", ("this", uid));
return entityName;
}
}
}
| 0 | 0.967557 | 1 | 0.967557 | game-dev | MEDIA | 0.820545 | game-dev | 0.983183 | 1 | 0.983183 |
GregTechCEu/GregTech | 25,330 | src/main/java/gregtech/api/metatileentity/multiblock/MultiblockControllerBase.java | package gregtech.api.metatileentity.multiblock;
import gregtech.api.GregTechAPI;
import gregtech.api.block.VariantActiveBlock;
import gregtech.api.capability.GregtechCapabilities;
import gregtech.api.capability.IMultiblockController;
import gregtech.api.capability.IMultipleRecipeMaps;
import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.metatileentity.MetaTileEntityHolder;
import gregtech.api.metatileentity.interfaces.IGregTechTileEntity;
import gregtech.api.pattern.BlockPattern;
import gregtech.api.pattern.BlockWorldState;
import gregtech.api.pattern.MultiblockShapeInfo;
import gregtech.api.pattern.PatternMatchContext;
import gregtech.api.pattern.TraceabilityPredicate;
import gregtech.api.pipenet.tile.IPipeTile;
import gregtech.api.unification.material.Material;
import gregtech.api.util.BlockInfo;
import gregtech.api.util.GTLog;
import gregtech.api.util.GTUtility;
import gregtech.api.util.RelativeDirection;
import gregtech.api.util.world.DummyWorld;
import gregtech.client.renderer.ICubeRenderer;
import gregtech.client.renderer.handler.MultiblockPreviewRenderer;
import gregtech.client.renderer.texture.Textures;
import gregtech.client.renderer.texture.cube.SimpleOrientedCubeRenderer;
import gregtech.common.blocks.MetaBlocks;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import codechicken.lib.raytracer.CuboidRayTraceResult;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.pipeline.ColourMultiplier;
import codechicken.lib.render.pipeline.IVertexOperation;
import codechicken.lib.vec.Matrix4;
import codechicken.lib.vec.Rotation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import static gregtech.api.capability.GregtechDataCodes.*;
public abstract class MultiblockControllerBase extends MetaTileEntity implements IMultiblockController {
@Nullable
public BlockPattern structurePattern;
private final Map<MultiblockAbility<Object>, AbilityInstances> multiblockAbilities = new HashMap<>();
private final List<IMultiblockPart> multiblockParts = new ArrayList<>();
private boolean structureFormed;
protected EnumFacing upwardsFacing = EnumFacing.NORTH;
protected boolean isFlipped;
public MultiblockControllerBase(ResourceLocation metaTileEntityId) {
super(metaTileEntityId);
}
@Override
public void onPlacement(EntityLivingBase placer) {
super.onPlacement(placer);
reinitializeStructurePattern();
}
public void reinitializeStructurePattern() {
this.structurePattern = createStructurePattern();
}
@Override
public void update() {
super.update();
if (!getWorld().isRemote) {
if (getOffsetTimer() % 20 == 0 || isFirstTick()) {
checkStructurePattern();
}
// DummyWorld is the world for the JEI preview. We do not want to update the Multi in this world,
// besides initially forming it in checkStructurePattern
if (isStructureFormed() && !(getWorld() instanceof DummyWorld)) {
updateFormedValid();
}
}
}
/**
* Called when the multiblock is formed and validation predicate is matched
*/
protected abstract void updateFormedValid();
/**
* @return structure pattern of this multiblock
*/
@NotNull
protected abstract BlockPattern createStructurePattern();
public EnumFacing getUpwardsFacing() {
return upwardsFacing;
}
public void setUpwardsFacing(EnumFacing upwardsFacing) {
if (!allowsExtendedFacing()) return;
if (upwardsFacing == null || upwardsFacing == EnumFacing.UP || upwardsFacing == EnumFacing.DOWN) {
GTLog.logger.error("Tried to set upwards facing to invalid facing {}! Skipping", upwardsFacing);
return;
}
if (this.upwardsFacing != upwardsFacing) {
this.upwardsFacing = upwardsFacing;
if (getWorld() != null && !getWorld().isRemote) {
notifyBlockUpdate();
markDirty();
writeCustomData(UPDATE_UPWARDS_FACING, buf -> buf.writeByte(upwardsFacing.getIndex()));
if (structurePattern != null) {
structurePattern.clearCache();
checkStructurePattern();
}
}
}
}
public boolean isFlipped() {
return isFlipped;
}
/** <strong>Should not be called outside of structure formation logic!</strong> */
@ApiStatus.Internal
protected void setFlipped(boolean isFlipped) {
if (this.isFlipped != isFlipped) {
this.isFlipped = isFlipped;
notifyBlockUpdate();
markDirty();
writeCustomData(UPDATE_FLIP, buf -> buf.writeBoolean(isFlipped));
}
}
@SideOnly(Side.CLIENT)
public abstract ICubeRenderer getBaseTexture(IMultiblockPart sourcePart);
public boolean shouldRenderOverlay(IMultiblockPart sourcePart) {
return true;
}
/**
* Override this method to change the Controller overlay
*
* @return The overlay to render on the Multiblock Controller
*/
@SideOnly(Side.CLIENT)
@NotNull
protected ICubeRenderer getFrontOverlay() {
return Textures.MULTIBLOCK_WORKABLE_OVERLAY;
}
@SideOnly(Side.CLIENT)
public TextureAtlasSprite getFrontDefaultTexture() {
return getFrontOverlay().getParticleSprite();
}
public static TraceabilityPredicate tilePredicate(@NotNull BiFunction<BlockWorldState, MetaTileEntity, Boolean> predicate,
@Nullable Supplier<BlockInfo[]> candidates) {
return new TraceabilityPredicate(blockWorldState -> {
TileEntity tileEntity = blockWorldState.getTileEntity();
if (!(tileEntity instanceof IGregTechTileEntity))
return false;
MetaTileEntity metaTileEntity = ((IGregTechTileEntity) tileEntity).getMetaTileEntity();
if (predicate.apply(blockWorldState, metaTileEntity)) {
if (metaTileEntity instanceof IMultiblockPart) {
Set<IMultiblockPart> partsFound = blockWorldState.getMatchContext().getOrCreate("MultiblockParts",
HashSet::new);
partsFound.add((IMultiblockPart) metaTileEntity);
}
return true;
}
return false;
}, candidates);
}
public static TraceabilityPredicate metaTileEntities(MetaTileEntity... metaTileEntities) {
ResourceLocation[] ids = Arrays.stream(metaTileEntities).filter(Objects::nonNull)
.map(tile -> tile.metaTileEntityId).toArray(ResourceLocation[]::new);
return tilePredicate((state, tile) -> ArrayUtils.contains(ids, tile.metaTileEntityId),
getCandidates(metaTileEntities));
}
private static Supplier<BlockInfo[]> getCandidates(MetaTileEntity... metaTileEntities) {
return () -> Arrays.stream(metaTileEntities).filter(Objects::nonNull).map(tile -> {
// TODO
MetaTileEntityHolder holder = new MetaTileEntityHolder();
holder.setMetaTileEntity(tile);
holder.getMetaTileEntity().onPlacement();
holder.getMetaTileEntity().setFrontFacing(EnumFacing.SOUTH);
return new BlockInfo(tile.getBlock().getDefaultState(), holder);
}).toArray(BlockInfo[]::new);
}
private static Supplier<BlockInfo[]> getCandidates(IBlockState... allowedStates) {
return () -> Arrays.stream(allowedStates).map(state -> new BlockInfo(state, null)).toArray(BlockInfo[]::new);
}
public static TraceabilityPredicate abilities(MultiblockAbility<?>... allowedAbilities) {
return tilePredicate((state, tile) -> {
if (tile instanceof IMultiblockAbilityPart<?>abilityPart) {
for (var ability : abilityPart.getAbilities()) {
if (ArrayUtils.contains(allowedAbilities, ability))
return true;
}
}
return false;
}, getCandidates(Arrays.stream(allowedAbilities)
.flatMap(ability -> MultiblockAbility.REGISTRY.get(ability).stream())
.toArray(MetaTileEntity[]::new)));
}
public static TraceabilityPredicate states(IBlockState... allowedStates) {
return new TraceabilityPredicate(blockWorldState -> {
IBlockState state = blockWorldState.getBlockState();
if (state.getBlock() instanceof VariantActiveBlock) {
blockWorldState.getMatchContext().getOrPut("VABlock", new LinkedList<>()).add(blockWorldState.getPos());
}
return ArrayUtils.contains(allowedStates, state);
}, getCandidates(allowedStates));
}
/**
* Use this predicate for Frames in your Multiblock. Allows for Framed Pipes as well as normal Frame blocks.
*/
public static TraceabilityPredicate frames(Material... frameMaterials) {
return states(Arrays.stream(frameMaterials).map(m -> MetaBlocks.FRAMES.get(m).getBlock(m))
.toArray(IBlockState[]::new))
.or(new TraceabilityPredicate(blockWorldState -> {
TileEntity tileEntity = blockWorldState.getTileEntity();
if (!(tileEntity instanceof IPipeTile)) {
return false;
}
IPipeTile<?, ?> pipeTile = (IPipeTile<?, ?>) tileEntity;
return ArrayUtils.contains(frameMaterials, pipeTile.getFrameMaterial());
}));
}
public static TraceabilityPredicate blocks(Block... block) {
return new TraceabilityPredicate(
blockWorldState -> ArrayUtils.contains(block, blockWorldState.getBlockState().getBlock()),
getCandidates(Arrays.stream(block).map(Block::getDefaultState).toArray(IBlockState[]::new)));
}
public static TraceabilityPredicate air() {
return TraceabilityPredicate.AIR;
}
public static TraceabilityPredicate any() {
return TraceabilityPredicate.ANY;
}
public static TraceabilityPredicate heatingCoils() {
return TraceabilityPredicate.HEATING_COILS.get();
}
public TraceabilityPredicate selfPredicate() {
return metaTileEntities(this).setCenter();
}
@Override
public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) {
ICubeRenderer baseTexture = getBaseTexture(null);
pipeline = ArrayUtils.add(pipeline,
new ColourMultiplier(GTUtility.convertRGBtoOpaqueRGBA_CL(getPaintingColorForRendering())));
if (baseTexture instanceof SimpleOrientedCubeRenderer) {
baseTexture.renderOriented(renderState, translation, pipeline, getFrontFacing());
} else {
baseTexture.render(renderState, translation, pipeline);
}
if (allowsExtendedFacing()) {
double degree = Math.PI / 2 * (upwardsFacing == EnumFacing.EAST ? -1 :
upwardsFacing == EnumFacing.SOUTH ? 2 : upwardsFacing == EnumFacing.WEST ? 1 : 0);
Rotation rotation = new Rotation(degree, frontFacing.getXOffset(), frontFacing.getYOffset(),
frontFacing.getZOffset());
translation.translate(0.5, 0.5, 0.5);
if (frontFacing == EnumFacing.DOWN && upwardsFacing.getAxis() == EnumFacing.Axis.Z) {
translation.apply(new Rotation(Math.PI, 0, 1, 0));
}
translation.apply(rotation);
translation.scale(1.0000f);
translation.translate(-0.5, -0.5, -0.5);
}
}
@SideOnly(Side.CLIENT)
@Override
public Pair<TextureAtlasSprite, Integer> getParticleTexture() {
return Pair.of(getBaseTexture(null).getParticleSprite(), getPaintingColorForRendering());
}
/**
* Override to disable Multiblock pattern from being added to Jei
*/
public boolean shouldShowInJei() {
return true;
}
/**
* Used if MultiblockPart Abilities need to be sorted a certain way, like
* Distillation Tower and Assembly Line.
*/
protected Function<BlockPos, Integer> multiblockPartSorter() {
return BlockPos::hashCode;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void checkStructurePattern() {
if (structurePattern == null) return;
PatternMatchContext context = structurePattern.checkPatternFastAt(getWorld(), getPos(),
getFrontFacing().getOpposite(), getUpwardsFacing(), allowsFlip());
if (context != null && !structureFormed) {
Set<IMultiblockPart> rawPartsSet = context.getOrCreate("MultiblockParts", HashSet::new);
ArrayList<IMultiblockPart> parts = new ArrayList<>(rawPartsSet);
for (IMultiblockPart part : parts) {
if (part.isAttachedToMultiBlock()) {
if (!part.canPartShare()) {
return;
}
}
}
this.setFlipped(context.neededFlip());
parts.sort(Comparator.comparing(it -> multiblockPartSorter().apply(((MetaTileEntity) it).getPos())));
Map<MultiblockAbility<Object>, AbilityInstances> abilities = new HashMap<>();
for (IMultiblockPart part : parts) {
if (part instanceof IMultiblockAbilityPart abilityPart) {
List<MultiblockAbility> abilityList = abilityPart.getAbilities();
for (MultiblockAbility ability : abilityList) {
if (!checkAbilityPart(ability, ((MetaTileEntity) abilityPart).getPos()))
continue;
AbilityInstances instances = abilities.computeIfAbsent(ability,
AbilityInstances::new);
abilityPart.registerAbilities(instances);
}
}
}
this.multiblockParts.addAll(parts);
this.multiblockAbilities.putAll(abilities);
parts.forEach(part -> part.addToMultiBlock(this));
this.structureFormed = true;
writeCustomData(STRUCTURE_FORMED, buf -> buf.writeBoolean(true));
formStructure(context);
} else if (context == null && structureFormed) {
invalidateStructure();
} else if (context != null) {
// ensure flip is ok, possibly not necessary but good to check just in case
if (context.neededFlip() != isFlipped()) {
setFlipped(context.neededFlip());
}
}
}
/**
* Checks if a multiblock ability at a given block pos should be added to the ability instances
*
* @return true if the ability should be added to this multiblocks ability instances
*/
protected <T> boolean checkAbilityPart(MultiblockAbility<T> ability, BlockPos pos) {
return true;
}
protected void formStructure(PatternMatchContext context) {}
public void invalidateStructure() {
this.multiblockParts.forEach(part -> part.removeFromMultiBlock(this));
this.multiblockAbilities.clear();
this.multiblockParts.clear();
this.structureFormed = false;
this.setFlipped(false);
writeCustomData(STRUCTURE_FORMED, buf -> buf.writeBoolean(false));
}
@Override
public void onRemoval() {
super.onRemoval();
if (!getWorld().isRemote && structureFormed) {
invalidateStructure();
}
}
public <T> List<T> getAbilities(MultiblockAbility<T> ability) {
return Collections.unmodifiableList(multiblockAbilities.getOrDefault(ability, AbilityInstances.EMPTY).cast());
}
public List<IMultiblockPart> getMultiblockParts() {
return Collections.unmodifiableList(multiblockParts);
}
@Override
public void readFromNBT(NBTTagCompound data) {
super.readFromNBT(data);
if (data.hasKey("UpwardsFacing")) {
this.upwardsFacing = EnumFacing.VALUES[data.getByte("UpwardsFacing")];
}
if (data.hasKey("IsFlipped")) {
this.isFlipped = data.getBoolean("IsFlipped");
}
this.reinitializeStructurePattern();
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound data) {
super.writeToNBT(data);
data.setByte("UpwardsFacing", (byte) upwardsFacing.getIndex());
data.setBoolean("IsFlipped", isFlipped);
return data;
}
@Override
public void writeInitialSyncData(PacketBuffer buf) {
super.writeInitialSyncData(buf);
buf.writeBoolean(structureFormed);
buf.writeByte(upwardsFacing.getIndex());
buf.writeBoolean(isFlipped);
}
@Override
public void receiveInitialSyncData(PacketBuffer buf) {
super.receiveInitialSyncData(buf);
this.structureFormed = buf.readBoolean();
this.upwardsFacing = EnumFacing.VALUES[buf.readByte()];
this.isFlipped = buf.readBoolean();
}
@Override
public void receiveCustomData(int dataId, PacketBuffer buf) {
super.receiveCustomData(dataId, buf);
if (dataId == STRUCTURE_FORMED) {
this.structureFormed = buf.readBoolean();
if (!structureFormed) {
GregTechAPI.soundManager.stopTileSound(getPos());
}
} else if (dataId == UPDATE_UPWARDS_FACING) {
this.upwardsFacing = EnumFacing.VALUES[buf.readByte()];
scheduleRenderUpdate();
} else if (dataId == UPDATE_FLIP) {
this.isFlipped = buf.readBoolean();
}
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing side) {
T result = super.getCapability(capability, side);
if (result != null)
return result;
if (capability == GregtechCapabilities.CAPABILITY_MULTIBLOCK_CONTROLLER) {
return GregtechCapabilities.CAPABILITY_MULTIBLOCK_CONTROLLER.cast(this);
}
return null;
}
public boolean isStructureFormed() {
return structureFormed;
}
@Override
public void setFrontFacing(EnumFacing frontFacing) {
EnumFacing oldFrontFacing = getFrontFacing();
super.setFrontFacing(frontFacing);
// Set the upwards facing in a way that makes it "look like" the upwards facing wasn't changed
if (allowsExtendedFacing()) {
EnumFacing newUpwardsFacing = RelativeDirection.simulateAxisRotation(frontFacing, oldFrontFacing,
getUpwardsFacing());
setUpwardsFacing(newUpwardsFacing);
}
if (getWorld() != null && !getWorld().isRemote && structurePattern != null) {
// clear cache since the cache has no concept of pre-existing facing
// for the controller block (or any block) in the structure
structurePattern.clearCache();
// recheck structure pattern immediately to avoid a slight "lag"
// on deforming when rotating a multiblock controller
checkStructurePattern();
}
}
@Override
public void addToolUsages(ItemStack stack, @Nullable World world, List<String> tooltip, boolean advanced) {
if (this instanceof IMultipleRecipeMaps) {
tooltip.add(I18n.format("gregtech.tool_action.screwdriver.toggle_mode_covers"));
} else {
tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers"));
}
if (allowsExtendedFacing()) {
tooltip.add(I18n.format("gregtech.tool_action.wrench.extended_facing"));
} else {
tooltip.add(I18n.format("gregtech.tool_action.wrench.set_facing"));
}
super.addToolUsages(stack, world, tooltip, advanced);
}
@Override
public boolean onRightClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing,
CuboidRayTraceResult hitResult) {
if (super.onRightClick(playerIn, hand, facing, hitResult))
return true;
if (this.getWorld().isRemote && !this.isStructureFormed() && playerIn.isSneaking() &&
playerIn.getHeldItem(hand).isEmpty()) {
MultiblockPreviewRenderer.renderMultiBlockPreview(this, 60000);
return true;
}
return false;
}
@Override
public boolean onWrenchClick(EntityPlayer playerIn, EnumHand hand, EnumFacing wrenchSide,
CuboidRayTraceResult hitResult) {
if (wrenchSide == getFrontFacing() && allowsExtendedFacing()) {
if (!getWorld().isRemote) {
setUpwardsFacing(playerIn.isSneaking() ? upwardsFacing.rotateYCCW() : upwardsFacing.rotateY());
}
return true;
}
return super.onWrenchClick(playerIn, hand, wrenchSide, hitResult);
}
@Override
public boolean isValidFrontFacing(EnumFacing facing) {
return allowsExtendedFacing() || super.isValidFrontFacing(facing);
}
// todo tooltip on multis saying if this is enabled or disabled?
/** Whether this multi can be rotated or face upwards. */
public boolean allowsExtendedFacing() {
return true;
}
/** Set this to false only if your multiblock is set up such that it could have a wall-shared controller. */
public boolean allowsFlip() {
return true;
}
public List<MultiblockShapeInfo> getMatchingShapes() {
if (this.structurePattern == null) {
this.reinitializeStructurePattern();
if (this.structurePattern == null) {
return Collections.emptyList();
}
}
int[][] aisleRepetitions = this.structurePattern.aisleRepetitions;
return repetitionDFS(new ArrayList<>(), aisleRepetitions, new Stack<>());
}
private List<MultiblockShapeInfo> repetitionDFS(List<MultiblockShapeInfo> pages, int[][] aisleRepetitions,
Stack<Integer> repetitionStack) {
if (repetitionStack.size() == aisleRepetitions.length) {
int[] repetition = new int[repetitionStack.size()];
for (int i = 0; i < repetitionStack.size(); i++) {
repetition[i] = repetitionStack.get(i);
}
pages.add(new MultiblockShapeInfo(Objects.requireNonNull(this.structurePattern).getPreview(repetition)));
} else {
for (int i = aisleRepetitions[repetitionStack.size()][0]; i <=
aisleRepetitions[repetitionStack.size()][1]; i++) {
repetitionStack.push(i);
repetitionDFS(pages, aisleRepetitions, repetitionStack);
repetitionStack.pop();
}
}
return pages;
}
@SideOnly(Side.CLIENT)
public String[] getDescription() {
String key = String.format("gregtech.multiblock.%s.description", metaTileEntityId.getPath());
return I18n.hasKey(key) ? new String[] { I18n.format(key) } : new String[0];
}
@Override
public int getDefaultPaintingColor() {
return 0xFFFFFF;
}
public void explodeMultiblock(float explosionPower) {
List<IMultiblockPart> parts = new ArrayList<>(getMultiblockParts());
for (IMultiblockPart part : parts) {
part.removeFromMultiBlock(this);
((MetaTileEntity) part).doExplosion(explosionPower);
}
doExplosion(explosionPower);
}
/**
* @param part the part to check
* @return if the multiblock part is terrain and weather resistant
*/
public boolean isMultiblockPartWeatherResistant(@NotNull IMultiblockPart part) {
return false;
}
}
| 0 | 0.944683 | 1 | 0.944683 | game-dev | MEDIA | 0.899689 | game-dev | 0.868319 | 1 | 0.868319 |
Holic75/KingmakerRebalance | 8,330 | CallOfTheWild/NewMechanics/BuffMechanics.cs | using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes.Spells;
using Kingmaker.UnitLogic;
using Kingmaker.UnitLogic.Buffs;
using Kingmaker.UnitLogic.Buffs.Blueprints;
using Kingmaker.UnitLogic.Buffs.Components;
using Kingmaker.UnitLogic.Mechanics.Actions;
using Kingmaker.UnitLogic.Parts;
using Kingmaker.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CallOfTheWild.BuffMechanics
{
public class UnitPartStoreBuff : AdditiveUnitPart
{
public void removeAllBuffsByBlueprint(BlueprintBuff buff)
{
var found_buffs = buffs.FindAll(b => b.Blueprint == buff).OfType<Buff>().ToArray();
buffs.RemoveAll(b => b.Blueprint == buff);
foreach (var b in found_buffs)
{
b?.Remove();
}
}
}
public class StoreBuff : BuffLogic
{
public override void OnFactActivate()
{
this.Buff.Context.MaybeCaster?.Ensure<UnitPartStoreBuff>().addBuff(this.Buff);
}
public override void OnFactDeactivate()
{
this.Buff.Context.MaybeCaster?.Get<UnitPartStoreBuff>()?.removeBuff(this.Buff);
}
}
public class RemoveStoredBuffs : ContextAction
{
public BlueprintBuff buff;
public override string GetCaption()
{
return "Remove unique buff";
}
public override void RunAction()
{
var part_store_buff = this.Target.Unit?.Get<UnitPartStoreBuff>();
if (part_store_buff == null)
{
return;
}
part_store_buff.removeAllBuffsByBlueprint(buff);
}
}
public class SuppressBuffsCorrect : OwnedGameLogicComponent<UnitDescriptor>
{
public BlueprintBuff[] Buffs = new BlueprintBuff[0];
public SpellSchool[] Schools = new SpellSchool[0];
public SpellDescriptorWrapper Descriptor;
public override void OnFactActivate()
{
var partBuffSuppress = this.Owner.Ensure<UnitPartBuffSuppressSaved>();
if (this.Descriptor != SpellDescriptor.None)
partBuffSuppress.Suppress((SpellDescriptor)this.Descriptor);
if (!((IList<SpellSchool>)this.Schools).Empty<SpellSchool>())
partBuffSuppress.Suppress(this.Schools);
foreach (BlueprintBuff buff in this.Buffs)
partBuffSuppress.Suppress(buff);
}
public override void OnFactDeactivate()
{
var partBuffSuppress = this.Owner.Get<UnitPartBuffSuppressSaved>();
if (!(bool)((UnitPart)partBuffSuppress))
{
UberDebug.LogError((object)"UnitPartSuppressBuff is missing", (object[])Array.Empty<object>());
}
else
{
if (this.Descriptor != SpellDescriptor.None)
partBuffSuppress.Release((SpellDescriptor)this.Descriptor);
if (!((IList<SpellSchool>)this.Schools).Empty<SpellSchool>())
partBuffSuppress.Release(this.Schools);
foreach (BlueprintBuff buff in this.Buffs)
partBuffSuppress.Release(buff);
}
}
}
public class UnitPartBuffSuppressSaved : UnitPart
{
[JsonProperty]
private readonly List<SpellDescriptor> m_SpellDescriptors = new List<SpellDescriptor>();
[JsonProperty]
private readonly List<BlueprintBuff> m_Buffs = new List<BlueprintBuff>();
[JsonProperty]
private readonly List<SpellSchool> m_SpellSchools = new List<SpellSchool>();
private static IEnumerable<SpellDescriptor> GetValues(
SpellDescriptor spellDescriptor)
{
return EnumUtils.GetValues<SpellDescriptor>().Where<SpellDescriptor>((Func<SpellDescriptor, bool>)(v =>
{
if (v != SpellDescriptor.None)
return (ulong)(spellDescriptor & v) > 0UL;
return false;
}));
}
public void Suppress(SpellSchool[] spellSchools)
{
foreach (SpellSchool spellSchool in spellSchools)
this.m_SpellSchools.Add(spellSchool);
}
public void Suppress(SpellDescriptor spellDescriptor)
{
foreach (SpellDescriptor spellDescriptor1 in UnitPartBuffSuppressSaved.GetValues(spellDescriptor))
this.m_SpellDescriptors.Add(spellDescriptor1);
this.Update();
}
public void Suppress(BlueprintBuff buff)
{
this.m_Buffs.Add(buff);
this.Update();
}
public void Release(SpellSchool[] spellSchools)
{
foreach (SpellSchool spellSchool in spellSchools)
this.m_SpellSchools.Remove(spellSchool);
this.Update();
this.TryRemovePart();
}
public void Release(SpellDescriptor spellDescriptor)
{
foreach (SpellDescriptor spellDescriptor1 in UnitPartBuffSuppressSaved.GetValues(spellDescriptor))
this.m_SpellDescriptors.Remove(spellDescriptor1);
this.Update();
this.TryRemovePart();
}
public void Release(BlueprintBuff buff)
{
this.m_Buffs.Remove(buff);
this.Update();
this.TryRemovePart();
}
private void TryRemovePart()
{
if (this.m_Buffs.Any<BlueprintBuff>() || this.m_SpellDescriptors.Any<SpellDescriptor>() || this.m_SpellSchools.Any<SpellSchool>())
return;
this.Owner.Remove<UnitPartBuffSuppress>();
}
public bool IsSuppressed(Buff buff)
{
if (!this.m_Buffs.Contains(buff.Blueprint) && !UnitPartBuffSuppressSaved.GetValues(buff.Context.SpellDescriptor).Any<SpellDescriptor>((Func<SpellDescriptor, bool>)(d => this.m_SpellDescriptors.Contains(d))))
return this.m_SpellSchools.Contains(buff.Context.SpellSchool);
return true;
}
private void Update()
{
foreach (Buff buff in this.Owner.Buffs)
{
bool flag = this.IsSuppressed(buff);
if (buff.IsSuppressed != flag)
{
if (flag && buff.Active)
buff.Deactivate();
buff.IsSuppressed = flag;
if (!flag && !buff.Active)
buff.Activate();
}
}
}
}
public class RemoveUniqueBuff : ContextAction
{
public BlueprintBuff buff;
public override string GetCaption()
{
return "Remove unique buff";
}
public override void RunAction()
{
var unit_part_unique_buff = this.Target.Unit?.Get<UnitPartUniqueBuffs>();
if (unit_part_unique_buff == null)
{
return;
}
var buff_to_remove = unit_part_unique_buff.Buffs.Find(b => b.Blueprint == buff);
if (buff_to_remove != null)
{
unit_part_unique_buff.RemoveBuff(buff_to_remove);
buff_to_remove.Remove();
}
}
}
[Harmony12.HarmonyPatch(typeof(Buff))]
[Harmony12.HarmonyPatch("Activate", Harmony12.MethodType.Normal)]
class Buff_Activate_Patch
{
static bool Prefix(Buff __instance)
{
var partBuffSuppress = __instance.Owner.Get<UnitPartBuffSuppressSaved>();
__instance.IsSuppressed = partBuffSuppress != null && partBuffSuppress.IsSuppressed(__instance);
if (__instance.IsSuppressed)
return false;
return true;
}
}
//prevent creating buff fx on suppressed buffs
[Harmony12.HarmonyPatch(typeof(Buff))]
[Harmony12.HarmonyPatch("SpawnParticleEffect", Harmony12.MethodType.Normal)]
class Buff_SpawnParticleEffect_Patch
{
static bool Prefix(Buff __instance)
{
if (!__instance.Active)
{
return false;
}
return true;
}
}
}
| 0 | 0.596622 | 1 | 0.596622 | game-dev | MEDIA | 0.948637 | game-dev | 0.825069 | 1 | 0.825069 |
qreal/qreal | 8,087 | plugins/robots/thirdparty/Box2D/Dynamics/Joints/b2MotorJoint.cpp | /*
* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2MotorJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB)
{
bodyA = bA;
bodyB = bB;
b2Vec2 xB = bodyB->GetPosition();
linearOffset = bodyA->GetLocalPoint(xB);
float32 angleA = bodyA->GetAngle();
float32 angleB = bodyB->GetAngle();
angularOffset = angleB - angleA;
}
b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def)
: b2Joint(def)
{
m_linearOffset = def->linearOffset;
m_angularOffset = def->angularOffset;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
m_correctionFactor = def->correctionFactor;
}
void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, -m_localCenterA);
m_rB = b2Mul(qB, -m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset);
m_angularError = aB - aA - m_angularOffset;
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
float32 inv_h = data.step.inv_dt;
// Solve angular friction
{
float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError;
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2MotorJoint::GetAnchorA() const
{
return m_bodyA->GetPosition();
}
b2Vec2 b2MotorJoint::GetAnchorB() const
{
return m_bodyB->GetPosition();
}
b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2MotorJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2MotorJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2MotorJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2MotorJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2MotorJoint::SetCorrectionFactor(float32 factor)
{
b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f);
m_correctionFactor = factor;
}
float32 b2MotorJoint::GetCorrectionFactor() const
{
return m_correctionFactor;
}
void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset)
{
if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_linearOffset = linearOffset;
}
}
const b2Vec2& b2MotorJoint::GetLinearOffset() const
{
return m_linearOffset;
}
void b2MotorJoint::SetAngularOffset(float32 angularOffset)
{
if (angularOffset != m_angularOffset)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_angularOffset = angularOffset;
}
}
float32 b2MotorJoint::GetAngularOffset() const
{
return m_angularOffset;
}
void b2MotorJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2MotorJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y);
b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 0 | 0.929799 | 1 | 0.929799 | game-dev | MEDIA | 0.987672 | game-dev | 0.972026 | 1 | 0.972026 |
victords/super-bombinhas | 13,132 | stage_menu.rb | # Copyright 2019 Victor David Santos
#
# This file is part of Super Bombinhas.
#
# Super Bombinhas 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.
#
# Super Bombinhas 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 Super Bombinhas. If not, see <https://www.gnu.org/licenses/>.
require_relative 'global'
require_relative 'options'
class MenuImage < MenuElement
def initialize(x, y, img)
@x = x
@y = y
@img = Res.img img
end
def draw
@img.draw @x, @y, 0, 2, 2
end
end
class MenuPanel < MenuElement
def initialize(x, y, w, h)
@x = x
@y = y
@w = w
@h = h
end
def draw
G.window.draw_quad @x, @y, C::PANEL_COLOR,
@x + @w, @y, C::PANEL_COLOR,
@x, @y + @h, C::PANEL_COLOR,
@x + @w, @y + @h, C::PANEL_COLOR, 0
end
end
class BombButton < Button
include FormElement
def initialize(x, bomb, form)
super(x: x, y: 240, width: 80, height: 80) {
SB.player.set_bomb(bomb)
SB.state = :main
form.reset
}
@bomb = SB.player.bomb(bomb)
@bomb_img = Res.img "icon_Bomba#{bomb.capitalize}"
end
def draw
G.window.draw_quad @x, @y, C::PANEL_COLOR,
@x + @w, @y, C::PANEL_COLOR,
@x, @y + @h, C::PANEL_COLOR,
@x + @w, @y + @h, C::PANEL_COLOR, 0
@bomb_img.draw @x + 40 - @bomb_img.width, @y + 25 - @bomb_img.height, 0, 2, 2
SB.text_helper.write_breaking(@bomb.name, @x + 40, @y + 48, 64, :center, 0, 255, 0, 1.5, 1.5, -3)
end
end
class ItemEffect
attr_reader :dead
def initialize(x, y, target_x, target_y)
@x = x; @y = y; @target_x = target_x; @target_y = target_y
@d_x = target_x - x; @d_y = target_y - y
@time = 0
@effects = []
end
def update
if @time >= 30
unless @finished
@effects << Effect.new(@target_x - 16, @target_y - 16, :fx_glow2, 3, 2)
@finished = true
end
else
pos_x = @x + (@time / 30.0) * @d_x
pos_y = @y + (@time / 30.0) * @d_y
@effects << Effect.new(pos_x - 7, pos_y - 7, :fx_Glow1, 3, 2,7, [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0])
@time += 1
end
@effects.each do |e|
e.update
@effects.delete(e) if e.dead
end
@dead = true if @finished && @effects.empty?
end
def draw(map, scale_x, scale_y)
@effects.each do |e|
e.draw(map, scale_x, scale_y)
end
end
end
class StageMenu
class << self
def initialize(custom = false, editor = false)
options_comps = [MenuPanel.new(10, 90, 780, 450)]
options_comps.concat(Options.get_menu)
@stage_menu = Form.new([
MenuImage.new(280, 180, :ui_stageMenu),
MenuButton.new(207, :resume, true) {
SB.state = :main
},
MenuButton.new(257, :change_bomb) {
@stage_menu.go_to_section 1
},
MenuButton.new(307, :options) {
Options.set_temp
@stage_menu.go_to_section 2
},
MenuButton.new(357, :exit) {
if editor
SB.editor_stop_test
else
SB.save_and_exit
@stage_menu.reset
end
}
], [], options_comps, custom ? [
MenuButton.new(400, :exit, false) {
if editor
SB.editor_stop_test
else
SB.leave_custom_stage(true)
end
}
] : [
MenuButton.new(400, :continue, false, 219) {
SB.next_stage
},
MenuButton.new(400, :exit, false, 409) {
SB.next_stage false
}
])
set_bomb_screen_comps
Options.form = @stage_menu
@alpha = 0
@effects = []
@lives_icon = Res.img :icon_lives
@hp_icon = Res.img :icon_hp
@score_icon = Res.img :icon_score
@star_icon = Res.img :icon_star
@selected_item = Res.img :ui_startupItem
@ready = true
end
def set_bomb_screen_comps
sec = @stage_menu.section(1)
sec.clear
p = SB.player
x = 400 - (40 + (p.bomb_count - 1) * 50)
Player::BOMB_TYPES.each do |type|
sec.add(BombButton.new(x, type, @stage_menu)) if p.has_bomb?(type)
x += 100
end
sec.add(MenuButton.new(550, :back, true) {
@stage_menu.go_to_section 0
})
end
def update_main
@effects.each do |e|
e.update
@effects.delete(e) if e.dead
end
if SB.player.dead?
@dead_text = SB.player.lives + SB.stage.life_count == 0 ? :game_over : :dead if @dead_text.nil?
@alpha += 17 if @alpha < 255
elsif @dead_text
@dead_text = nil
@alpha = 0
end
end
def update_end
if @stage_end_timer < 30 * @stage_end_comps.length
if SB.key_pressed?(:confirm)
@stage_end_timer = 30 * @stage_end_comps.length
else
@stage_end_timer += 1
end
end
@stage_menu.update if @stage_end_timer >= 30 * @stage_end_comps.length
@stage_end_comps.each_with_index do |c, i|
c.update_movement if @stage_end_timer >= i * 30
end
end
def update_paused
if SB.key_pressed?(:pause)
SB.state = :main
@stage_menu.reset
return
end
@stage_menu.update
end
def end_stage(unlock_bomb, next_bonus, next_movie, bonus = false)
p = MenuPanel.new(-600, 150, 400, unlock_bomb ? 350 : 300)
p.init_movement
p.move_to 200, 150
t1 = MenuText.new(SB.player.dead? || SB.stage.time == 0 ? :too_bad : :stage_complete, 1200, 160, 400, :center, 3)
t1.init_movement
t1.move_to 400, 160
t2 = MenuText.new(:score, 210, 820)
t2.init_movement
t2.move_to 210, 220
t3 = MenuNumber.new(SB.player.stage_score, 590, 820, :right)
t3.init_movement
t3.move_to 590, 220
@stage_end_comps = [p, t1, t2, t3]
if bonus
if SB.stage.won_reward
x = SB.casual? ? 360 : 372
t4 = MenuImage.new(x, 905, SB.casual? ? :icon_score : :icon_lives)
t4.move_to x, 305
t4.init_movement
x = SB.casual? ? 420 : 413
t5 = MenuText.new(SB.casual? ? (SB.stage.reward * 1000).to_s : "x #{SB.stage.reward}", x, 905, 400, :center)
t5.init_movement
t5.move_to x, 305
@stage_end_comps << t4 << t5
end
else
t4 = MenuText.new(:total, 210, 860)
t4.init_movement
t4.move_to 210, 260
t5 = MenuNumber.new(SB.player.score, 590, 860, :right, next_bonus ? 0xff0000 : 0)
t5.init_movement
t5.move_to 590, 260
t6 = MenuText.new(:stars, 210, 900)
t6.init_movement
t6.move_to 210, 300
t7 = MenuText.new("#{SB.stage.star_count}/#{C::STARS_PER_STAGE}", 590, 900, 300, :right)
t7.init_movement
t7.move_to(590, 300)
@stage_end_comps << t4 << t5 << t6 << t7
unless SB.stage.world == C::LAST_WORLD
t8 = MenuText.new(:spec_taken, 210, 940)
t8.init_movement
t8.move_to 210, 340
t9 = MenuText.new(SB.player.specs.index(SB.stage.id) ? :yes : :no, 590, 940, 300, :right)
t9.init_movement
t9.move_to 590, 340
@stage_end_comps << t8 << t9
end
if SB.stage.star_count >= C::STARS_PER_STAGE
t10 = MenuText.new(:all_stars_found, 590, 968, 300, :right)
t10.init_movement
t10.move_to(590, 368)
@stage_end_comps << t10
end
end
@stage_end_timer = 0
if unlock_bomb or next_bonus or next_movie
@stage_menu.section(3).clear
@stage_menu.section(3).add(MenuButton.new(unlock_bomb ? 440 : 400, :continue) {
SB.check_next_stage
})
if unlock_bomb
@stage_menu.section(3).add(MenuText.new(:can_play, 210, 400, 400, :left, SB.lang == :indonesian ? 1.5 : 2))
@stage_menu.section(3).add(MenuImage.new(558, 394, get_next_bomb_icon))
end
@continue_only = true
elsif @continue_only
@stage_menu.section(3).clear
@stage_menu.section(3).add(MenuButton.new(400, :continue, false, 219) {
SB.check_next_stage
})
@stage_menu.section(3).add(MenuButton.new(400, :exit, false, 409) {
SB.check_next_stage false
})
@continue_only = false
end
@stage_menu.go_to_section 3
end
def get_next_bomb_icon
case SB.player.last_world
when 1 then :icon_BombaVermelha
when 2 then :icon_BombaAmarela
when 3 then :icon_BombaVerde
else :icon_BombaBranca
end
end
def update_lang
@stage_menu.update_lang if @ready
end
def play_get_item_effect(origin_x, origin_y, type = nil)
@effects << ItemEffect.new(origin_x, origin_y,
type == :life ? 20 : type == :star ? 372 : type == :health ? 114 : 770,
type.nil? ? 30 : 19)
end
def draw
if SB.state == :main || SB.state == :editor
st = SB.stage
unless st.starting > 0
draw_player_stats
unless st.is_bonus
@star_icon.draw(363, 10, 0, 2, 2)
SB.text_helper.write_line("#{st.star_count}/#{C::STARS_PER_STAGE}", 411, 8, :center, 0xffffff, 255, :border)
end
SB.text_helper.write_line(st.time.to_s, 400, 570, :center, 0xffffff, 255, :border) if st.time
end
@effects.each do |e|
e.draw(nil, 2, 2)
end
draw_player_dead if SB.player.dead?
elsif SB.state == :paused
draw_menu
else # :stage_end
draw_stage_stats
end
end
def draw_player_stats
p = SB.player
G.window.draw_quad 4, 4, C::PANEL_COLOR,
SB.casual? ? 104 : 204, 4, C::PANEL_COLOR,
SB.casual? ? 104 : 204, 60, C::PANEL_COLOR,
4, 60, C::PANEL_COLOR, 0
unless SB.casual?
@lives_icon.draw 12, 9, 0, 2, 2
SB.font.draw_text(p.lives >= 0 ? p.lives + SB.stage.life_count : '∞', 40, 8, 0, 2, 2, 0xff000000)
end
@hp_icon.draw SB.casual? ? 12 : 105, 9, 0, 2, 2
SB.font.draw_text "#{p.bomb.hp}/#{p.bomb.max_hp > 0 ? p.bomb.max_hp : '∞'}", SB.casual? ? 42 : 135, 8, 0, 2, 2, 0xff000000
@score_icon.draw 10, 32, 0, 2, 2
SB.font.draw_text p.stage_score, 40, 30, 0, 2, 2, 0xff000000
########## ITEM ##########
if p.items.size > 0
p.items.each_with_index do |(k, v), i|
x = 754 - 40 * (p.items.size - i - 1)
@selected_item.draw(x - 8, 6, 0, 2, 2) if k == p.cur_item_type
v[0][:obj].icon.draw(x, 14, 0, 2, 2, k == p.cur_item_type ? 0xffffffff : C::DISABLED_COLOR)
SB.text_helper.write_line(v.length.to_s, x + 36, 28, :right, 0xffffff, k == p.cur_item_type ? 255 : 127, :border)
end
end
##########################
######### ABILITY ########
b = p.bomb
icon = if b.type == :verde
'explode'
elsif b.type == :branca
'time'
else
nil
end
if icon
color = b.can_use_ability ? 0xffffffff : C::DISABLED_COLOR
G.window.draw_quad 750, 66, color,
790, 66, color,
790, 106, color,
750, 106, color, 0
@selected_item.draw(746, 62, 0, 2, 2)
Res.img("icon_#{icon}").draw(754, 70, 0, 2, 2, color)
SB.text_helper.write_line((b.cooldown.to_f / 60).ceil.to_s, 790, 84, :right, 0xffffff, 255, :border) unless b.can_use_ability
end
##########################
end
def draw_player_dead
c = ((@alpha / 2) << 24)
G.window.draw_quad 0, 0, c,
C::SCREEN_WIDTH, 0, c,
0, C::SCREEN_HEIGHT, c,
C::SCREEN_WIDTH, C::SCREEN_HEIGHT, c, 0
SB.text_helper.write_line(SB.text(@dead_text), 400, 250, :center, 0xffffff, @alpha, :border, 0, 1, 255, 1, 3, 3)
unless SB.stage.is_bonus
SB.text_helper.write_line SB.text(:restart), 400, 300, :center, 0xffffff, @alpha, :border, 0, 1, 255, 1
end
end
def draw_menu
G.window.draw_quad 0, 0, 0x80000000,
C::SCREEN_WIDTH, 0, 0x80000000,
0, C::SCREEN_HEIGHT, 0x80000000,
C::SCREEN_WIDTH, C::SCREEN_HEIGHT, 0x80000000, 0
@stage_menu.draw
end
def draw_stage_stats
@stage_end_comps.each { |c| c.draw }
@stage_menu.draw if @stage_end_timer >= @stage_end_comps.length * 30
end
end
end
| 0 | 0.597825 | 1 | 0.597825 | game-dev | MEDIA | 0.823218 | game-dev | 0.871707 | 1 | 0.871707 |
coddicat/DebounceThrottle | 2,010 | DebounceThrottle/ThrottleDispatcher.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace DebounceThrottle
{
/// <summary>
/// The Throttle dispatcher, on the other hand, limits the invocation of an action to a specific time interval. This means that the action will only be executed once within the given time frame, regardless of how many times it is called.
/// </summary>
public class ThrottleDispatcher : ThrottleDispatcher<bool>
{
public ThrottleDispatcher(
TimeSpan interval,
bool delayAfterExecution = false,
bool resetIntervalOnException = false)
: base(interval, delayAfterExecution, resetIntervalOnException)
{
}
/// <summary>
/// ThrottleAsync method manages the throttling of the action invocation.
/// </summary>
/// <param name="function">The function returns the Task to be invoked asynchronously.</param>
/// <param name="cancellationToken">An optional CancellationToken.</param>
/// <returns></returns>
public Task ThrottleAsync(Func<Task> function, CancellationToken cancellationToken = default)
{
return base.ThrottleAsync(async () =>
{
await function.Invoke();
return true;
}, cancellationToken);
}
/// <summary>
/// Throttle method manages the throttling of the action invocation in a synchronous manner.
/// </summary>
/// <param name="action">The action to be invoked.</param>
/// <param name="cancellationToken">An optional CancellationToken.</param>
public void Throttle(Action action, CancellationToken cancellationToken = default)
{
Func<Task<bool>> actionAsync = () => Task.Run(() =>
{
action.Invoke();
return true;
}, cancellationToken);
Task _ = ThrottleAsync(actionAsync, cancellationToken);
}
}
} | 0 | 0.764743 | 1 | 0.764743 | game-dev | MEDIA | 0.215048 | game-dev | 0.75491 | 1 | 0.75491 |
ggnkua/Atari_ST_Sources | 19,416 | C/Jeffrey M. Bilger/DANG_SRC/SELECT.C | /* loads up main selection screen
user can select
1 -enter city
2 -load char
3 -save char
4 -roll a char
*/
struct character
{
char name[15]; /* NO! Set these to char *name and then */
char align[15]; /* name = "blahh.." OR do char name[]="blah!" */
char class[15]; /* you're defining an array of one element */
int lvl; /* thats a ptr to a char! too redundant! */
long int exp;
long int hp;
int ac,str,inte,wis,dex,con;
int weapon_num,armor_num;
int backpack[10]; /* holds unique #. I'll have 1
main array that will hold number,
name so we can look it up. Set to -1, means EMPTY */
char weapon[15];
char armor[15];
char spell[15];
long int max_hp,max_sp;
int spell_num;
long int sp;
long int gold;
int user_items[25]; /* holds food,h2o,keys,etc.. */
int current_spells_active[5]; /*0=treasure Finding, 1=Fleetness, 2=Protection
3=Strength 4=Charm */
int hunger_thurst_status[2]; /*0 not hungry/thirsty.. 10 FAMISHED */
/* 0 is hunger 1 is thirst */
long int bank_balance;
int x_loc,y_loc, /* current x,y location */
weather,count,way,time,loc,current_sky,
current_sound,clock,am_pm,sound;
char dir;
};
struct character user;
char name[20],align,class;
int buffer[200]; /* holds the char info for disk loading and saving */
int pointer[37];
#define rnd(t) abs(Random()%(t)) /*returns a number from 0 to (t-1) */
char temp_[32000], /* Temp buffer where file is read in */
*hld,
*iff_in, *iff_out; /* Pointers for DEGAS unpack() routine */
#include <stdio.h>
#include <gemdefs.h>
#include <osbind.h>
int contrl[12];
int intin[256], ptsin[256];
int intout[256], ptsout[256];
int savepal[16],newpal[16],junkbuff[46];
int filehandle;
char input[] = "select.pc1";
int handle;
int button,x,y;
int stats[10];
int choice; /* if == 1 then you rolled and accepted a character */
char pix1[] ="START0.DAT";
char pix2[] ="START1.DAT";
main()
{
char command[20];
char *scr1,*scr2,*scr3,*screen;
char in;
int type;
MFDB theMFDB; /* Screen definition structure */
char string[30];
appl_init();
handle = open_workstation(&theMFDB);
v_hide_c(handle); /*hide the mouse */
pt_set(pointer,4,2);
pointer[2]=1;
pointer[3]=3;
pointer[4]=2;
stuffbits(&pointer[5],"0000000000000000");
stuffbits(&pointer[6],"0001111100000000");
stuffbits(&pointer[7],"0001111000000000");
stuffbits(&pointer[8],"0001000110000000");
stuffbits(&pointer[9],"0000000001100000");
for(type=10;type<21;type++)
stuffbits(&pointer[type],"0000000000000000");
stuffbits(&pointer[5],"0000000000000000");
stuffbits(&pointer[6],"0011111000000000");
stuffbits(&pointer[7],"0011110000000000");
stuffbits(&pointer[8],"0011001110000000");
stuffbits(&pointer[9],"0000000011100000");
for(type=10;type<21;type++)
stuffbits(&pointer[type],"0000000000000000");
scr1 = malloc(32768+256); /*allocate memory for 2nd screen */
if ((long) scr1 & 0xff)
scr1 = scr1 + (0x100 - (long)scr1 & 0xff);
screen = (char *)Physbase(); /* get ptr to physbase */
type = 2; /* *.pc1 pic */
read_stuff(pix1,scr1,type); /* intro screen */
Setscreen(scr1,scr1,-1); /* display the pic */
Setpalette(newpal); /* tel sys to use these colors! */
command[0] = strlen("intro 11000 -q -l");
strcpy(&command[1],"intro 11000 -q -l");
Pexec(0,"MUSIC",command,command); /* loop until keypress */
fade_to_black();
Setscreen(screen,screen,-1);
read_stuff(pix2,scr1,type); /* title screen */
Setscreen(scr1,scr1,-1); /* display the pic */
Setpalette(newpal); /* tel sys to use these colors! */
in=Bconin(2);
fade_to_black();
Setscreen(screen,screen,-1);
read_stuff(input,scr1,type); /* Selection screen onto the temp scr*/
Setscreen(scr1,scr1,-1); /* display the pic */
Setpalette(newpal); /* tel sys to use these colors! */
vsc_form(handle,pointer); /* make our new mouse ptr active */
v_show_c(handle,0);
do /* loop until keypress */
{
vq_mouse(handle,&button,&x,&y);
if(button == 1 && (x>14 && x<42)) /* if left button pressed... */
{
if( y>35 && y<61) enter_city(scr1);
if( y>67 && y<93) load_character();
if( y>100 && y<127) save_character();
if( y>134 && y<161) roll();
}
} while ( 1 ); /* while no input */
Setscreen(screen,screen,-1);
Setpalette(savepal); /* restore palette */
v_clsvwk(handle);
appl_exit();
}
/*************************/
load_character()
{FILE *ifp;
char in;
int x;
clear();
v_gtext(handle,188,37,"Load a Character");
loadchar(buffer);
display();
}
/************************************/
save_character()
{
FILE *ofp;
char out;
int x;
clear();
v_gtext(handle,188,37,"Save a Character");
savechar(buffer);
v_gtext(handle,188,53,"Character saved");
}
/******************************8/
stats[]
*/
roll()
{
int x;
clear();
v_gtext(handle,188,37,"Roll a Character");
do
{
choice = 0; /* reset choice to 0 */
user.lvl = 1;
user.exp = 0L;
user.ac = 15;
user.weapon_num = 0;
user.armor_num = 0;
user.spell_num = 0;
user.bank_balance = 0L;
user.x_loc = 19; /* x,y location */
user.y_loc = 16;
user.weather = 0;
user.time = 0;
user.count = 1;
user.way = 1;
user.loc = 206; /* initial room # */
user.current_sky = 0;
user.current_sound = 0;
user.sound = 1;
user.clock = 1;
user.am_pm = 1;
user.dir = 'N'; /* face north! */
for(x=0;x<10;x++) user.backpack[x] = -1;
for(x=0;x<25;x++) user.user_items[x] = 0;
for(x=0;x<2;x++) user.hunger_thurst_status[x] = 0;
user.str = user.inte = user.wis = user.dex = user.con = 7; /* base */
user.str += rnd(12);
user.inte += rnd(12);
user.wis += rnd(12);
user.dex += rnd(12);
user.con += rnd(12);
user.hp = user.sp = user.gold = 5L; /* base */
user.hp += (long int) rnd(20);
user.sp += (long int) rnd(20);
user.gold += (long int) rnd(20);
user.max_hp = user.hp;
user.max_sp = user.sp;
strcpy(user.weapon,"None");
strcpy(user.armor,"None");
strcpy(user.spell,"None");
display();
v_gtext(handle,188,141,"Accept");
v_gtext(handle,248,141,"Reroll");
do /* loop until mouse press */
{
vq_mouse(handle,&button,&x,&y);
if( button == 1 && (y>133 && y<150)) /* if left button pressed and in y range */
{
if(x > 187 && x<230) choice = 1; /* accept!! */
if(x >247 && x < 320) choice = -1; /* reroll */
}
}while(choice == 0);
}while(choice == -1); /* reroll */
v_hide_c(handle); /*hide the mouse */
if( choice == 1 )
{
clear();
vs_curaddress(handle,7,30);
v_gtext(handle,188,54,"Name:");
Cconrs(name);
clear();
v_gtext(handle,188,53,"Alignment:");
v_gtext(handle,188,61,"G)ood");
v_gtext(handle,188,69,"N)eutral");
v_gtext(handle,188,77,"E)vil");
do
{
align = Bconin(2);
} while( (align != 'G' && align != 'g') && (align != 'N' && align != 'n')
&& (align != 'E' && align != 'e') );
clear();
v_gtext(handle,188,53,"Class:");
v_gtext(handle,188,61,"F)ighter");
v_gtext(handle,188,69,"M)age");
v_gtext(handle,188,77,"T)hief");
do
{
class = Bconin(2);
} while( (class != 'F' && class != 'f') && (class != 'M' && class != 'm')
&& (class != 'T' && class != 't') );
strcpy(user.name,&(name[2]));
if(align == 'G' || align == 'g') strcpy(user.align,"Good");
if(align == 'N' || align == 'n') strcpy(user.align,"Neutral");
if(align == 'E' || align == 'e') strcpy(user.align,"Evil");
if(class == 'F' || class == 'f') strcpy(user.class,"Fighter");
if(class == 'M' || class == 'm') strcpy(user.class,"Mage");
if(class == 'T' || class == 't') strcpy(user.class,"Thief");
clear();
v_gtext(handle,188,53,"Be sure to SAVE");
v_gtext(handle,188,61,"your character..");
}
v_show_c(handle,0);
}
/****************************/
display()
{
char string[30];
clear();
v_gtext(handle,188,53,user.name);
v_gtext(handle,188,61,user.align);
v_gtext(handle,188,69,user.class);
if(user.str < 10)
sprintf(string," STR: %d",user.str);
else
sprintf(string," STR:%d",user.str);
v_gtext(handle,188,77,string);
if(user.dex < 10)
sprintf(string," DEX: %d",user.dex);
else
sprintf(string," DEX:%d",user.dex);
v_gtext(handle,188,85,string);
if(user.inte < 10)
sprintf(string," INT: %d",user.inte);
else
sprintf(string," INT:%d",user.inte);
v_gtext(handle,188,93,string);
if(user.wis < 10)
sprintf(string," WIS: %d",user.wis);
else
sprintf(string," WIS:%d",user.wis);
v_gtext(handle,188,101,string);
if(user.con < 10)
sprintf(string," CON: %d",user.con);
else
sprintf(string," CON:%d",user.con);
v_gtext(handle,188,109,string);
if(user.hp < 10L)
sprintf(string," HP : %ld",user.hp);
else
sprintf(string," HP :%ld",user.hp);
v_gtext(handle,188,117,string);
if(user.sp < 10L)
sprintf(string," SP : %ld",user.sp);
else
sprintf(string," SP :%ld",user.sp);
v_gtext(handle,188,125,string);
}
/****************************/
clear()
{
int h,y=37;
for(h=0;h<14;h++)
{
v_gtext(handle,188,y," ");
y +=8;
}
}
/***************************/
enter_city(scr1)
char *scr1;
{
free(scr1);
clear();
v_gtext(handle,188,45,"Loading....");
Pexec(0,"CITY","","");
exit(1); /* and quit when exit city */
}
/* load degas compressed pics */
/************************/
read_stuff(hold,adrr,type)
char hold[];
register char *adrr;
int type;
{
char buf[130];
int lines,i;
filehandle = Fopen(hold,0);
for(i=0; i<16;i++)
savepal[i]=Setcolor(i,-1);
/* read header data */
i=Fread(filehandle,2L,buf);
/* read 16 words(32 bytes) of palette data into newpal array */
i =Fread(filehandle,32L,newpal);
if(type == 1) /* if .pi1 pic */
{
i =Fread(filehandle,32000L,adrr);/* read pic image in */
/* Close file */
Fclose(filehandle);
return(1); /* and quit */
}
/* else it's compressed.. */
i=Fread(filehandle,32000L,temp_); /* read image onto back screen*/
/* Close file */
Fclose(filehandle);
lines = 200; /* Low, med-res */
iff_in = temp_; /* iff_in pts to temp_buf*/
iff_out = adrr; /* iff_out pts to pic_buffer*/
do
unpack(0); /* Unpack a line at a time */
while (--lines);
}
/************************/
/***********************/
/*---------------------------------------------------------------------------*/
/* |--------- DEGAS ---------| */
/* UNCOMPRESSED COMPRESSED */
/* NEO low med mono low med mono TINY */
/* typ... 0 1 2 3 4 5 6 7 */
/* Unpacks a single scan line & updates iff_in & iff_out global pointers
/ byt == 0 to 127 copy next [byt+1] bytes
Unpack routine --if-< byt == -1 to -127 copy next byte [-byt+1] times
\ byt == 128 NO-OP */
unpack(rez)
int rez;
{
register char *src_ptr, *dst_ptr, /* ptrs to source/dest */
byt, cnt; /* byt holds the ACTUAL compressed data code(control byte ) */
register int minus128 = -128,
len;
char linbuf[320]; /* Oversize just in case! */
int llen;
if (rez < 2) len = 160;
else len = 80;
llen = len;
src_ptr = iff_in; /* iff_in is ptr to compressed data */
dst_ptr = &linbuf[0]; /* linbuf WILL hold an ENTIRE Uncompressed scan line. 4 bitplanes * 80 = 320 max! */
while (len > 0)
{
byt = *src_ptr++; /* get byte value at address scr_ptr, THEN inc scr_ptr+1 */
if (byt >= 0) /* If ctrl code >= 0 then use the next x+1 bytes*/
{
++byt; /* inc byt +1 */
do
{
*dst_ptr++ = *src_ptr++; /* get byte value from address source, and inc the 2 ptrs */
--len; /* one byte down.. */
}
while (--byt); /* do this byt TIMES (remember byt here = byt+1 */
}
else
if (byt != minus128) /* else if ctrl code NOT = -128*/
{ /*Then use the next byte -x+1 times, (-x) cause x will be negative and - - = + */
cnt = -byt + 1; /* cnt = -x + 1 */
byt = *src_ptr++; /* byt = THE very next byte past the ctrl code(or ctrl byte! */
do {
*dst_ptr++ = byt; /* store that byte */
--len;
}
while (--cnt); /* keep doing it cnt times */
}
}
ilbm_st(linbuf, iff_out, rez); /* convert the format line */
iff_in = src_ptr; /* Update global pointers */
iff_out += llen;
} /* end of module uncompress() */
/*---------------------------------------------------------------------------*/
ilbm_st(src_ptr, dst_ptr, rez) /* Convert ILBM format line to ST format */
int *src_ptr, *dst_ptr, rez;
{
int x, *p0_ptr, *p1_ptr, *p2_ptr, *p3_ptr;
if (rez==0)
{ /* Low-res */
p0_ptr = src_ptr;
p1_ptr = src_ptr + 20;
p2_ptr = src_ptr + 40;
p3_ptr = src_ptr + 60;
for (x=0; x<20; ++x)
{
*dst_ptr++ = *p0_ptr++;
*dst_ptr++ = *p1_ptr++;
*dst_ptr++ = *p2_ptr++;
*dst_ptr++ = *p3_ptr++;
}
}
else if (rez==1)
{ /* Med-res */
p0_ptr = src_ptr;
p1_ptr = src_ptr + 40;
for (x=0; x<40; ++x)
{
*dst_ptr++ = *p0_ptr++;
*dst_ptr++ = *p1_ptr++;
}
}
else
{ /* Monochrome */
for (x=0; x<40; ++x)
*dst_ptr++ = *src_ptr++;
}
}
/*---------------------------------------------------------------------------*/
fade_to_black()
{
int h;
for(h=0;h<16;h++)
Setcolor(h,0x000);
}
/**********************/
/*
the load and save character routines.
*/
/*********************/
loadchar(i)
int i[];
{
long int hold;
int k,fd;
if( (fd = Fopen("char.dat",2)) < 0) printf("Error cant open file\n");
Fread(fd,(long)400,i); /* read 400 bytes*/
strcpy(user.name,i);
strcpy(user.align,&i[15]);
strcpy(user.class,&(i[30]));
user.lvl= i[45];
create_LW_from_two_words( &user.exp, i[46], i[48] );
user.ac = i[51];
create_LW_from_two_words( &user.hp, i[52], i[54] );
user.str =i[56];
user.inte=i[57];
user.wis=i[58];
user.dex=i[59];
user.con=i[60];
user.weapon_num=i[61];
user.armor_num=i[62];
for(k=0;k<10;k++)
user.backpack[k]=i[63+k];
strcpy(user.weapon,&(i[73]));
strcpy(user.armor,&(i[88]));
strcpy(user.spell,&(i[103]));
create_LW_from_two_words( &user.max_hp, i[118], i[120] );
create_LW_from_two_words( &user.max_sp, i[122], i[124] );
user.spell_num=i[126];
create_LW_from_two_words( &user.sp, i[127], i[129] );
create_LW_from_two_words( &user.gold, i[131], i[133] );
for(k=0;k<25;k++)
user.user_items[k]=i[135+k];
for(k=0;k<5;k++)
user.current_spells_active[k]=i[160+k];
for(k=0;k<2;k++)
user.hunger_thurst_status[k]=i[165+k];
create_LW_from_two_words( &user.bank_balance, i[168], i[170] );
user.x_loc=i[173];
user.y_loc=i[174];
user.weather=i[175];
user.count=i[176];
user.way=i[177];
user.time=i[178];
user.loc=i[179];
user.current_sky=i[180];
user.current_sound=i[181];
user.clock=i[182];
user.am_pm=i[183];
user.sound=i[184];
user.count=i[185];
user.dir=i[186];
Fclose(fd);
}
/*********************/
/* ints are 2 bytes
chars are 1 byte
longs are 4 bytes
ALL strings must be terminated with \0 or NULL!!!
*/
savechar(b)
int b[];
{
int pp,k,fd;
strcpy(b,user.name);
strcpy(&b[15],user.align);
strcpy(&(b[30]),user.class);
b[45] = user.lvl;
extract_LW_into_two_words( user.exp,&(b[46]) , &(b[48]));
b[51] = user.ac;
extract_LW_into_two_words( user.hp , &(b[52]) , &(b[54]) );
b[56]=user.str;
b[57]=user.inte;
b[58]=user.wis;
b[59]=user.dex;
b[60]=user.con;
b[61]=user.weapon_num;
b[62]=user.armor_num;
for(k=0;k<10;k++)
b[63+k]=user.backpack[k];
strcpy(&(b[73]),user.weapon);
strcpy(&(b[88]),user.armor);
strcpy(&(b[103]),user.spell);
extract_LW_into_two_words( user.max_hp , &(b[118]) , &(b[120]) );
extract_LW_into_two_words( user.max_sp , &(b[122]) , &(b[124]) );
b[126]=user.spell_num;
extract_LW_into_two_words( user.sp , &(b[127]) , &(b[129]) );
extract_LW_into_two_words( user.gold , &(b[131]) , &(b[134]) );
for(k=0;k<25;k++)
b[135+k]=user.user_items[k];
for(k=0;k<5;k++)
b[160+k]=user.current_spells_active[k];
for(k=0;k<2;k++)
b[165+k]=user.hunger_thurst_status[k];
extract_LW_into_two_words( user.bank_balance , &(b[168]) , &(b[170]) );
b[173]=user.x_loc; /* global x&y coords _ OTHERS*/
b[174]=user.y_loc;
b[175]=user.weather;
b[176]=user.count;
b[177]=user.way;
b[178]=user.time;
b[179]=user.loc;
b[180]=user.current_sky;
b[181]=user.current_sound;
b[182]=user.clock;
b[183]=user.am_pm;
b[184]=user.sound;
b[185]=user.count;
b[186]=user.dir;
if( (fd = Fopen("char.dat",2)) < 0) printf("Error cant open file\n");
Fwrite(fd,(long)400,b); /*write 9 bytes to file */
Fclose(fd);
}
/*************************************************************/
extract_LW_into_two_words( data , MSW , LSW )
long int data;
int *MSW,*LSW;
/* This procedure will take a longword(data) and break
it up into 2 words
Input: data --> the long word
Output: MSW --> the Most Signifigant Word
LSw --> the Least Sig. Word
*/
{
long int result;
/* Extract MSW */
result = data & 0xffff0000;
result = result >> 16;
*MSW = result; /* store it in an int */
result = data & 0x0000ffff; /* extract LSW */
*LSW = result; /*store it */
}
/**********************************************************/
create_LW_from_two_words( result, MSW, LSW )
/* Creates a long word from two words */
long int *result;
int MSW,LSW;
{
long int lower_word;
/* This code will form a long int
from 2 ints */
*result = MSW; /* get MSW */
*result = *result << 16; /* put into upper word */
lower_word = LSW; /* get LSW */
lower_word = lower_word & 0x0000ffff; /* it gets sign extended, so mask
out upper word */
*result +=lower_word; /* add to get final result */
}
| 0 | 0.76639 | 1 | 0.76639 | game-dev | MEDIA | 0.773473 | game-dev | 0.742059 | 1 | 0.742059 |
siconos/siconos | 1,145 | mechanisms/src/MBTB/MBTB_FC3DContactRelation.hpp |
#ifndef MBTB_FC3DCONTACTRELATION
#define MBTB_FC3DCONTACTRELATION
#include "MechanismsFwd.hpp"
#include <SiconosKernel.hpp>
#include "MBTB_Contact.hpp"
//! It is a relation dedicated for the unilateral constraint with Coulomb friction.
/*!
Aggregation to the class MBTB_Contact, the member _pContact contains the CAD information.
It derivates from siconos::NewtonEuler3DR. This class does the link between CAD and Siconos.
*/
class MBTB_FC3DContactRelation : public NewtonEuler3DR
{
protected:
//! The member containing the CAD properties.
MBTB_Contact * _pContact;
MBTB_FC3DContactRelation();
public :
/** Constructor
* \param _pContact [in] a pointer to the MBTB_Contact. Must be allocated/free by the caller.
*/
MBTB_FC3DContactRelation(MBTB_Contact * _pContact);
/** This function has to compute the distance between the objects.
* \param time the given time
* \param q0 the position
* \param y the output
*/
virtual void computeh(double time, const BlockVector& q0, SiconosVector& y) override;
//! Doing nothing.
virtual ~MBTB_FC3DContactRelation();
ACCEPT_STD_VISITORS();
};
#endif
| 0 | 0.932515 | 1 | 0.932515 | game-dev | MEDIA | 0.620282 | game-dev | 0.664478 | 1 | 0.664478 |
TheNewEconomy/TNE-Bukkit | 2,075 | TNE/src/net/tnemc/core/menu/impl/balance/BalanceMenu.java | package net.tnemc.core.menu.impl.balance;
import net.tnemc.core.TNE;
import net.tnemc.core.common.WorldVariant;
import net.tnemc.core.common.account.TNEAccount;
import net.tnemc.core.common.account.WorldFinder;
import net.tnemc.core.common.api.IDFinder;
import net.tnemc.core.common.currency.TNECurrency;
import net.tnemc.core.common.currency.formatter.CurrencyFormatter;
import net.tnemc.core.menu.Menu;
import net.tnemc.core.menu.icons.balance.BalCurrencyIcon;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
/**
* The New Economy Minecraft Server Plugin
* <p>
* Created by creatorfromhell on 8/11/2021.
* <p>
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ or send a letter to
* Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
* Created by creatorfromhell on 06/30/2017.
*/
public class BalanceMenu extends Menu {
private String switchMenu;
public BalanceMenu() {
super("balance_menu", ChatColor.GOLD + "Your Money", 1);
}
@Override
public Inventory buildInventory(Player player) {
TNE.debug("=====START DisplayScreen.initializeCurrencies =====");
String world = (String)TNE.menuManager().getViewerData(IDFinder.getID(player), "action_world");
final TNEAccount account = TNE.manager().getAccount(player.getUniqueId());
TNE.debug("Player: " + player);
TNE.debug("World: " + world);
if(world == null) world = WorldFinder.getWorld(player, WorldVariant.ACTUAL);
int i = 1;
for(TNECurrency currency : TNE.instance().api().getCurrencies(world)) {
icons.put(i, new BalCurrencyIcon(currency, CurrencyFormatter.format(currency, world, account.getHoldings(world, currency), ""), world, i));
i++;
}
Integer size = icons.size() / 9;
if((icons.size() % 9) > 0) size++;
if(size < 10) rows = 1;
else rows = (size / 9);
return super.buildInventory(player);
}
} | 0 | 0.836571 | 1 | 0.836571 | game-dev | MEDIA | 0.806358 | game-dev | 0.852481 | 1 | 0.852481 |
9ght-code/NullPointer | 11,165 | Nullpointer/Libraries/include/SDL2/SDL_keyboard.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2024 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_keyboard.h
*
* Include file for SDL keyboard event handling
*/
#ifndef SDL_keyboard_h_
#define SDL_keyboard_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_keycode.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The SDL keysym structure, used in key events.
*
* \note If you are looking for translated character input, see the ::SDL_TEXTINPUT event.
*/
typedef struct SDL_Keysym
{
SDL_Scancode scancode; /**< SDL physical key code - see ::SDL_Scancode for details */
SDL_Keycode sym; /**< SDL virtual key code - see ::SDL_Keycode for details */
Uint16 mod; /**< current key modifiers */
Uint32 unused;
} SDL_Keysym;
/* Function prototypes */
/**
* Query the window which currently has keyboard focus.
*
* \returns the window with keyboard focus.
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetKeyboardFocus(void);
/**
* Get a snapshot of the current state of the keyboard.
*
* The pointer returned is a pointer to an internal SDL array. It will be
* valid for the whole lifetime of the application and should not be freed by
* the caller.
*
* A array element with a value of 1 means that the key is pressed and a value
* of 0 means that it is not. Indexes into this array are obtained by using
* SDL_Scancode values.
*
* Use SDL_PumpEvents() to update the state array.
*
* This function gives you the current state after all events have been
* processed, so if a key or button has been pressed and released before you
* process events, then the pressed state will never show up in the
* SDL_GetKeyboardState() calls.
*
* Note: This function doesn't take into account whether shift has been
* pressed or not.
*
* \param numkeys if non-NULL, receives the length of the returned array
* \returns a pointer to an array of key states.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_PumpEvents
* \sa SDL_ResetKeyboard
*/
extern DECLSPEC const Uint8 *SDLCALL SDL_GetKeyboardState(int *numkeys);
/**
* Clear the state of the keyboard
*
* This function will generate key up events for all pressed keys.
*
* \since This function is available since SDL 2.24.0.
*
* \sa SDL_GetKeyboardState
*/
extern DECLSPEC void SDLCALL SDL_ResetKeyboard(void);
/**
* Get the current key modifier state for the keyboard.
*
* \returns an OR'd combination of the modifier keys for the keyboard. See
* SDL_Keymod for details.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyboardState
* \sa SDL_SetModState
*/
extern DECLSPEC SDL_Keymod SDLCALL SDL_GetModState(void);
/**
* Set the current key modifier state for the keyboard.
*
* The inverse of SDL_GetModState(), SDL_SetModState() allows you to impose
* modifier key states on your application. Simply pass your desired modifier
* states into `modstate`. This value may be a bitwise, OR'd combination of
* SDL_Keymod values.
*
* This does not change the keyboard state, only the key modifier flags that
* SDL reports.
*
* \param modstate the desired SDL_Keymod for the keyboard
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetModState
*/
extern DECLSPEC void SDLCALL SDL_SetModState(SDL_Keymod modstate);
/**
* Get the key code corresponding to the given scancode according to the
* current keyboard layout.
*
* See SDL_Keycode for details.
*
* \param scancode the desired SDL_Scancode to query
* \returns the SDL_Keycode that corresponds to the given SDL_Scancode.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyName
* \sa SDL_GetScancodeFromKey
*/
extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromScancode(SDL_Scancode scancode);
/**
* Get the scancode corresponding to the given key code according to the
* current keyboard layout.
*
* See SDL_Scancode for details.
*
* \param key the desired SDL_Keycode to query
* \returns the SDL_Scancode that corresponds to the given SDL_Keycode.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromScancode
* \sa SDL_GetScancodeName
*/
extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromKey(SDL_Keycode key);
/**
* Get a human-readable name for a scancode.
*
* See SDL_Scancode for details.
*
* **Warning**: The returned name is by design not stable across platforms,
* e.g. the name for `SDL_SCANCODE_LGUI` is "Left GUI" under Linux but "Left
* Windows" under Microsoft Windows, and some scancodes like
* `SDL_SCANCODE_NONUSBACKSLASH` don't have any name at all. There are even
* scancodes that share names, e.g. `SDL_SCANCODE_RETURN` and
* `SDL_SCANCODE_RETURN2` (both called "Return"). This function is therefore
* unsuitable for creating a stable cross-platform two-way mapping between
* strings and scancodes.
*
* \param scancode the desired SDL_Scancode to query
* \returns a pointer to the name for the scancode. If the scancode doesn't
* have a name this function returns an empty string ("").
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetScancodeFromKey
* \sa SDL_GetScancodeFromName
*/
extern DECLSPEC const char *SDLCALL SDL_GetScancodeName(SDL_Scancode scancode);
/**
* Get a scancode from a human-readable name.
*
* \param name the human-readable scancode name
* \returns the SDL_Scancode, or `SDL_SCANCODE_UNKNOWN` if the name wasn't
* recognized; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromName
* \sa SDL_GetScancodeFromKey
* \sa SDL_GetScancodeName
*/
extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromName(const char *name);
/**
* Get a human-readable name for a key.
*
* See SDL_Scancode and SDL_Keycode for details.
*
* \param key the desired SDL_Keycode to query
* \returns a pointer to a UTF-8 string that stays valid at least until the
* next call to this function. If you need it around any longer, you
* must copy it. If the key doesn't have a name, this function
* returns an empty string ("").
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromName
* \sa SDL_GetKeyFromScancode
* \sa SDL_GetScancodeFromKey
*/
extern DECLSPEC const char *SDLCALL SDL_GetKeyName(SDL_Keycode key);
/**
* Get a key code from a human-readable name.
*
* \param name the human-readable key name
* \returns key code, or `SDLK_UNKNOWN` if the name wasn't recognized; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromScancode
* \sa SDL_GetKeyName
* \sa SDL_GetScancodeFromName
*/
extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromName(const char *name);
/**
* Start accepting Unicode text input events.
*
* This function will start accepting Unicode text input events in the focused
* SDL window, and start emitting SDL_TextInputEvent (SDL_TEXTINPUT) and
* SDL_TextEditingEvent (SDL_TEXTEDITING) events. Please use this function in
* pair with SDL_StopTextInput().
*
* On some platforms using this function activates the screen keyboard.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_SetTextInputRect
* \sa SDL_StopTextInput
*/
extern DECLSPEC void SDLCALL SDL_StartTextInput(void);
/**
* Check whether or not Unicode text input events are enabled.
*
* \returns SDL_TRUE if text input events are enabled else SDL_FALSE.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputActive(void);
/**
* Stop receiving any text input events.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
*/
extern DECLSPEC void SDLCALL SDL_StopTextInput(void);
/**
* Dismiss the composition window/IME without disabling the subsystem.
*
* \since This function is available since SDL 2.0.22.
*
* \sa SDL_StartTextInput
* \sa SDL_StopTextInput
*/
extern DECLSPEC void SDLCALL SDL_ClearComposition(void);
/**
* Returns if an IME Composite or Candidate window is currently shown.
*
* \since This function is available since SDL 2.0.22.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputShown(void);
/**
* Set the rectangle used to type Unicode text inputs. Native input methods
* will place a window with word suggestions near it, without covering the
* text being inputted.
*
* To start text input in a given location, this function is intended to be
* called before SDL_StartTextInput, although some platforms support moving
* the rectangle even while text input (and a composition) is active.
*
* Note: If you want to use the system native IME window, try setting hint
* **SDL_HINT_IME_SHOW_UI** to **1**, otherwise this function won't give you
* any feedback.
*
* \param rect the SDL_Rect structure representing the rectangle to receive
* text (ignored if NULL)
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
*/
extern DECLSPEC void SDLCALL SDL_SetTextInputRect(const SDL_Rect *rect);
/**
* Check whether the platform has screen keyboard support.
*
* \returns SDL_TRUE if the platform has some screen keyboard support or
* SDL_FALSE if not.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
* \sa SDL_IsScreenKeyboardShown
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasScreenKeyboardSupport(void);
/**
* Check whether the screen keyboard is shown for given window.
*
* \param window the window for which screen keyboard should be queried
* \returns SDL_TRUE if screen keyboard is shown or SDL_FALSE if not.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_HasScreenKeyboardSupport
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenKeyboardShown(SDL_Window *window);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_keyboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.849792 | 1 | 0.849792 | game-dev | MEDIA | 0.857574 | game-dev | 0.519771 | 1 | 0.519771 |
doldecomp/melee | 16,708 | src/melee/ft/chara/ftMasterHand/ftMh_Init.c | #include "ftMh_Init.h"
#include "ftMh_BackAirplane1.h"
#include "ftMh_BackAirplane2.h"
#include "ftMh_BackAirplane3.h"
#include "ftMh_BackCrush_0.h"
#include "ftMh_BackCrush_1.h"
#include "ftMh_BackDisappear.h"
#include "ftMh_Damage_0.h"
#include "ftMh_Drill.h"
#include "ftMh_Entry.h"
#include "ftMh_FingerBeam.h"
#include "ftMh_FingerGun.h"
#include "ftMh_FingerGun3.h"
#include "ftMh_PaperCrush.h"
#include "ftMh_Poke.h"
#include "ftMh_RockCrush.h"
#include "ftMh_Slam.h"
#include "ftMh_Slap.h"
#include "ftMh_Squeeze.h"
#include "ftMh_Squeezing.h"
#include "ftMh_Sweep.h"
#include "ftMh_SweepWait.h"
#include "ftMh_TagApplaud.h"
#include "ftMh_TagCrush.h"
#include "ftMh_TagRockPaper.h"
#include "ftMh_Throw.h"
#include "ftMh_Wait1_0.h"
#include "ftMh_Wait1_2.h"
#include "ftMh_Walk.h"
#include "types.h"
#include <placeholder.h>
#include <platform.h>
#include "ft/ftbosslib.h"
#include "ft/ftcamera.h"
#include "ft/inlines.h"
#include "ft/types.h"
#include "it/it_26B1.h"
#include <common_structs.h>
#include <dolphin/mtx.h>
MotionState ftMh_Init_MotionStateTable[ftMh_MS_SelfCount] = {
{
// ftMh_MS_Wait1_0 = 341
ftMh_SM_Wait1_0,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Wait1_0_Anim,
ftMh_Wait1_0_IASA,
ftMh_Wait1_0_Phys,
ftMh_Wait1_0_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Wait2_0 = 342
ftMh_SM_Wait2_0,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Wait1_0_Anim,
ftMh_Wait1_0_IASA,
ftMh_Wait1_0_Phys,
ftMh_Wait1_0_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Entry = 343
ftMh_SM_Entry,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Entry_Anim,
ftMh_Entry_IASA,
ftMh_Entry_Phys,
ftMh_Entry_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Damage = 344
ftMh_SM_Damage,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Damage_Anim,
ftMh_Damage_IASA,
ftMh_Damage_Phys,
ftMh_Damage_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Damage2 = 345
ftMh_SM_Damage2,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_MS_345_Anim,
ftMh_Damage_IASA,
ftMh_Damage_Phys,
ftMh_Damage_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_WaitSweep = 346
ftMh_SM_WaitSweep,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_WaitSweep_Anim,
ftMh_WaitSweep_IASA,
ftMh_WaitSweep_Phys,
ftMh_WaitSweep_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_SweepLoop = 347
ftMh_SM_SweepLoop,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_SweepLoop_Anim,
ftMh_SweepLoop_IASA,
ftMh_SweepLoop_Phys,
ftMh_SweepLoop_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_SweepWait = 348
ftMh_SM_SweepWait,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_SweepWait_Anim,
ftMh_SweepWait_IASA,
ftMh_SweepWait_Phys,
ftMh_SweepWait_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Slap = 349
ftMh_SM_Slap,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Slap_Anim,
ftMh_Slap_IASA,
ftMh_Slap_Phys,
ftMh_Slap_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Walk2 = 350
ftMh_SM_Walk2,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Walk2_Anim,
ftMh_Walk2_IASA,
ftMh_Walk2_Phys,
ftMh_Walk2_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_WalkLoop = 351
ftMh_SM_WalkLoop,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_WalkLoop_Anim,
ftMh_WalkLoop_IASA,
ftMh_WalkLoop_Phys,
ftMh_WalkLoop_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_WalkWait = 352
ftMh_SM_WalkWait,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_WalkWait_Anim,
ftMh_WalkWait_IASA,
ftMh_WalkWait_Phys,
ftMh_WalkWait_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_WalkShoot = 353
ftMh_SM_WalkShoot,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_WalkShoot_Anim,
ftMh_WalkShoot_IASA,
ftMh_WalkShoot_Phys,
ftMh_WalkShoot_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Drill = 354
ftMh_SM_Drill,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Drill_Anim,
ftMh_Drill_IASA,
ftMh_Drill_Phys,
ftMh_Drill_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_RockCrushUp = 355
ftMh_SM_RockCrushUp,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_RockCrushUp_Anim,
ftMh_RockCrushUp_IASA,
ftMh_RockCrushUp_Phys,
ftMh_RockCrushUp_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_RockCrushWait = 356
ftMh_SM_RockCrushWait,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_RockCrushWait_Anim,
ftMh_RockCrushWait_IASA,
ftMh_RockCrushWait_Phys,
ftMh_RockCrushWait_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_RockCrushDown = 357
ftMh_SM_RockCrushDown,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_RockCrushDown_Anim,
ftMh_RockCrushDown_IASA,
ftMh_RockCrushDown_Phys,
ftMh_RockCrushDown_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_PaperCrush = 358
ftMh_SM_PaperCrush,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_PaperCrush_Anim,
ftMh_PaperCrush_IASA,
ftMh_PaperCrush_Phys,
ftMh_PaperCrush_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Poke1 = 359
ftMh_SM_Poke1,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Poke1_Anim,
ftMh_Poke1_IASA,
ftMh_Poke1_Phys,
ftMh_Poke1_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Poke2 = 360
ftMh_SM_Poke2,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Poke2_Anim,
ftMh_Poke1_IASA,
ftMh_Poke1_Phys,
ftMh_Poke1_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_FingerBeamStart = 361
ftMh_SM_FingerBeamStart,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_FingerBeamStart_Anim,
ftMh_FingerBeamStart_IASA,
ftMh_FingerBeamStart_Phys,
ftMh_FingerBeamStart_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_FingerBeamLoop = 362
ftMh_SM_FingerBeamLoop,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_FingerBeamLoop_Anim,
ftMh_FingerBeamLoop_IASA,
ftMh_FingerBeamLoop_Phys,
ftMh_FingerBeamLoop_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_FingerBeamEnd = 363
ftMh_SM_FingerBeamEnd,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_FingerBeamEnd_Anim,
ftMh_FingerBeamEnd_IASA,
ftMh_FingerBeamEnd_Phys,
ftMh_FingerBeamEnd_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_FingerGun1 = 364
ftMh_SM_FingerGun1,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_FingerGun1_Anim,
ftMh_FingerGun1_IASA,
ftMh_FingerGun1_Phys,
ftMh_FingerGun1_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_FingerGun2 = 365
ftMh_SM_FingerGun2,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_FingerGun2_Anim,
ftMh_FingerGun2_IASA,
ftMh_FingerGun2_Phys,
ftMh_FingerGun2_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_FingerGun3 = 366
ftMh_SM_FingerGun3,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_FingerGun3_Anim,
ftMh_FingerGun3_IASA,
ftMh_FingerGun3_Phys,
ftMh_FingerGun3_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_BackAirplane1 = 367
ftMh_SM_BackAirplane1,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_BackAirplane1_Anim,
ftMh_BackAirplane1_IASA,
ftMh_BackAirplane1_Phys,
ftMh_BackAirplane1_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_BackAirplane2 = 368
ftMh_SM_BackAirplane2,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_BackAirplane2_Anim,
ftMh_BackAirplane2_IASA,
ftMh_BackAirplane2_Phys,
ftMh_BackAirplane2_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_BackAirplane3 = 369
ftMh_SM_BackAirplane3,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_BackAirplane3_Anim,
ftMh_BackAirplane3_IASA,
ftMh_BackAirplane3_Phys,
ftMh_BackAirplane3_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_BackPunch = 370
ftMh_SM_BackPunch,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_BackPunch_Anim,
ftMh_BackPunch_IASA,
ftMh_BackPunch_Phys,
ftMh_BackPunch_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_BackCrush = 371
ftMh_SM_BackCrush,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_BackCrush_Anim,
ftMh_BackCrush_IASA,
ftMh_BackCrush_Phys,
ftMh_BackCrush_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_BackDisappear = 372
ftMh_SM_BackDisappear,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_BackDisappear_Anim,
ftMh_BackDisappear_IASA,
ftMh_BackDisappear_Phys,
ftMh_BackDisappear_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Wait1_1 = 373
ftMh_SM_Wait1_1,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Wait1_1_Anim,
ftMh_Wait1_1_IASA,
ftMh_Wait1_1_Phys,
ftMh_Wait1_1_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Grab = 374
ftMh_SM_Grab,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Grab_Anim,
ftMh_Grab_IASA,
ftMh_Grab_Phys,
ftMh_Grab_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Cancel = 375
ftMh_SM_Cancel,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Cancel_Anim,
ftMh_Cancel_IASA,
ftMh_Cancel_Phys,
ftMh_Cancel_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Squeezing0 = 376
ftMh_SM_Squeezing0,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Squeezing_Anim,
ftMh_Squeezing_IASA,
ftMh_Squeezing_Phys,
ftMh_Squeezing_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Squeezing1 = 377
ftMh_SM_Squeezing1,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Squeezing_Anim,
ftMh_Squeezing_IASA,
ftMh_Squeezing_Phys,
ftMh_Squeezing_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Squeeze = 378
ftMh_SM_Squeeze,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Squeeze_Anim,
ftMh_Squeeze_IASA,
ftMh_Squeeze_Phys,
ftMh_Squeeze_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Throw = 379
ftMh_SM_Throw,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Throw_Anim,
ftMh_Throw_IASA,
ftMh_Throw_Phys,
ftMh_Throw_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Slam = 380
ftMh_SM_Slam,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Slam_Anim,
ftMh_Slam_IASA,
ftMh_Slam_Phys,
ftMh_Slam_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Fail = 381
ftMh_SM_Fail,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Fail_Anim,
ftMh_Fail_IASA,
ftMh_Fail_Phys,
ftMh_Fail_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagCrush = 382
ftMh_SM_TagCrush,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagCrush_Anim,
ftMh_TagCrush_IASA,
ftMh_TagCrush_Phys,
ftMh_TagCrush_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagApplaud = 383
ftMh_SM_TagApplaud,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagApplaud_Anim,
ftMh_TagApplaud_IASA,
ftMh_TagApplaud_Phys,
ftMh_TagApplaud_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagRockPaper = 384
ftMh_SM_TagRockPaper,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagRockPaper_Anim,
ftMh_TagRockPaper_IASA,
ftMh_TagRockPaper_Phys,
ftMh_TagRockPaper_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagGrab = 385
ftMh_SM_TagGrab,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagGrab_Anim,
ftMh_TagGrab_IASA,
ftMh_TagGrab_Phys,
ftMh_TagGrab_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagSqueeze = 386
ftMh_SM_TagSqueeze,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagSqueeze_Anim,
ftMh_TagSqueeze_IASA,
ftMh_TagSqueeze_Phys,
ftMh_TagSqueeze_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagFail = 387
ftMh_SM_TagFail,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagFail_Anim,
ftMh_TagFail_IASA,
ftMh_TagFail_Phys,
ftMh_TagFail_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_TagCancel = 388
ftMh_SM_TagCancel,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_TagCancel_Anim,
ftMh_TagCancel_IASA,
ftMh_TagCancel_Phys,
ftMh_TagCancel_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Wait1_2 = 389
ftMh_SM_Wait1_2,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Wait1_2_Anim,
NULL,
ftMh_Wait1_2_Phys,
ftMh_Wait1_2_Coll,
ftCamera_UpdateCameraBox,
},
{
// ftMh_MS_Wait2_1 = 390
ftMh_SM_Wait2_1,
Ft_MF_None,
FtMoveId_Default << 24,
ftMh_Wait1_2_Anim,
NULL,
ftMh_Wait1_2_Phys,
ftMh_Wait1_2_Coll,
ftCamera_UpdateCameraBox,
},
};
char ftMh_Init_DatFilename[] = "PlMh.dat";
char ftMh_Init_DataName[] = "ftDataMasterhand";
char ftMh_Init_803D4090[] = "PlMhNr.dat";
char ftMh_Init_803D409C[] = "PlyMasterhand_Share_joint";
char ftMh_Init_AnimDatFilename[] = "PlMhAJ.dat";
Fighter_CostumeStrings ftMh_Init_CostumeStrings[] = {
{ ftMh_Init_803D4090, ftMh_Init_803D409C, NULL },
};
void ftMh_Init_OnDeath(HSD_GObj* gobj) {}
void ftMh_Init_OnLoad(HSD_GObj* gobj)
{
ftMasterHand_SpecialAttrs* ftData_attr;
Fighter* fp = gobj->user_data;
ftData* ftdata = fp->ft_data;
ftData_attr = ftdata->ext_attr;
{
UNK_T* items = ftdata->x48_items;
PUSH_ATTRS(fp, ftMasterHand_SpecialAttrs);
ftBossLib_8015BDB4(gobj);
it_8026B3F8(items[0], 125);
it_8026B3F8(items[1], 126);
fp->no_normal_motion = true;
fp->x2229_b6 = true;
fp->no_kb = true;
fp->x222A_b0 = true;
fp->x222A_b1 = true;
fp->x2229_b3 = true;
fp->cur_pos.x = ftData_attr->x30_pos2.x;
fp->cur_pos.y = ftData_attr->x30_pos2.y;
fp->cur_pos.z = 0;
fp->mv.mh.unk0.x34 = 0;
fp->mv.mh.unk0.x38 = 0;
fp->mv.mh.unk0.x3C = 0;
fp->mv.mh.unk0.x40 = 0;
fp->mv.mh.unk0.x28 = -1;
fp->mv.mh.unk0.x2C = -1;
fp->mv.mh.unk0.x30 = -1;
fp->mv.mh.unk0.x1C = 0;
fp->mv.mh.unk0.x20 = 0;
fp->fv.mh.x222C = ftBossLib_8015C244(gobj, &fp->cur_pos);
fp->fv.mh.x2238 = 1;
fp->fv.mh.x224C = 0;
fp->fv.mh.x2250 = ftMh_MS_SweepLoop;
fp->fv.mh.x2254 = 0;
fp->x1A88.level = 1;
ftBossLib_8015BD24(fp->x1A88.level, &fp->fv.mh.x223C, fp->fv.mh.x2238,
ftData_attr->x18, ftData_attr->x20,
ftData_attr->x1C);
}
}
void ftMh_Init_LoadSpecialAttrs(HSD_GObj* gobj)
{
COPY_ATTRS(gobj, ftMasterHand_SpecialAttrs);
}
| 0 | 0.769666 | 1 | 0.769666 | game-dev | MEDIA | 0.777658 | game-dev | 0.643149 | 1 | 0.643149 |
Pugstorm/CoreKeeperModSDK | 21,926 | Packages/com.unity.netcode/Runtime/Snapshot/GhostPredictionSmoothingSystem.cs | using System;
using Unity.Entities;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections;
using Unity.NetCode.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Jobs;
using System.Runtime.InteropServices;
using Unity.Assertions;
using Unity.Burst.Intrinsics;
namespace Unity.NetCode
{
/// <summary>
/// Singleton used to register a <see cref="SmoothingAction"/> for a certain component type.
/// The <see cref="SmoothingAction"/> is used to change the component value over time correct misprediction. Two different types of
/// smoothing action can be registered:
/// <para>- A smoothing action without argument. See <see cref="RegisterSmoothingAction{T}"/></para>
/// <para>- A smoothing action that take a component data as argument. See <see cref="RegisterSmoothingAction{T,U}"/></para>
/// </summary>
public struct GhostPredictionSmoothing : IComponentData
{
internal GhostPredictionSmoothing(NativeParallelHashMap<ComponentType, SmoothingActionState> actions, NativeList<ComponentType> userComp, EntityQuery singletonQuery)
{
m_SmoothingActions = actions;
m_UserSpecifiedComponentData = userComp;
m_SingletonQuery = singletonQuery;
}
/// <summary>
/// All the smoothing action must have this signature. The smoothing actions must also be burst compatible.
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SmoothingActionDelegate(IntPtr currentData, IntPtr previousData, IntPtr userData);
internal unsafe struct SmoothingActionState
{
public int compIndex;
public int compSize;
public int serializerIndex;
public int entityIndex;
public int userTypeId;
public int userTypeSize;
public byte* backupData;
public PortableFunctionPointer<SmoothingActionDelegate> action;
}
NativeList<ComponentType> m_UserSpecifiedComponentData;
NativeParallelHashMap<ComponentType, SmoothingActionState> m_SmoothingActions;
EntityQuery m_SingletonQuery;
/// <summary>
/// Register a smoothing function that does not take any argument for the specified component type.
/// </summary>
/// <param name="entityManager">The EntityManager in the destination world</param>
/// <param name="action">A burstable function pointer to the method that implement the smooting</param>
/// <typeparam name="T">The component type. Must implement the IComponentData interface</typeparam>
/// <returns>True if the action has been registered. False, in case of error or if the action has been already registered</returns>
public bool RegisterSmoothingAction<T>(EntityManager entityManager, PortableFunctionPointer<SmoothingActionDelegate> action) where T : struct, IComponentData
{
var type = ComponentType.ReadWrite<T>();
if (type.IsBuffer)
{
UnityEngine.Debug.LogError("Smoothing actions are not supported for buffers");
return false;
}
if (m_SmoothingActions.ContainsKey(type))
{
UnityEngine.Debug.LogError($"There is already a action registered for the type {type.ToString()}");
return false;
}
var actionData = new SmoothingActionState
{
action = action,
compIndex = -1,
compSize = -1,
serializerIndex = -1,
entityIndex = -1,
backupData = null,
userTypeId = -1,
userTypeSize = -1
};
m_SmoothingActions.Add(type, actionData);
if (!m_SingletonQuery.HasSingleton<GhostPredictionSmoothingSystem.SmoothingAction>())
{
entityManager.CreateEntity(ComponentType.ReadOnly<GhostPredictionSmoothingSystem.SmoothingAction>());
}
return true;
}
/// <summary>
/// Register a smoothing function that take a user specified component data as argument.
/// A maximum of 8 different component data type can be used to pass data to the smoothing functions.
/// There is no limitation in the number of smoothing action, component type pairs that can be registed.
/// </summary>
/// <param name="entityManager">The EntityManager in the destination world</param>
/// <param name="action">A burstable function pointer to the method that implement the smooting</param>
/// <typeparam name="T">The component type. Must implement the IComponentData interface</typeparam>
/// <typeparam name="U">The user data type that should be passed as argument to the function</typeparam>
/// <returns>True if the action has been registered. False, in case of error or if the action has been already registered</returns>
public bool RegisterSmoothingAction<T, U>(EntityManager entityManager, PortableFunctionPointer<SmoothingActionDelegate> action)
where T : struct, IComponentData
where U : struct, IComponentData
{
if (!RegisterSmoothingAction<T>(entityManager, action))
return false;
var type = ComponentType.ReadWrite<T>();
var userType = ComponentType.ReadWrite<U>();
var userTypeId = -1;
for (int i = 0; i < m_UserSpecifiedComponentData.Length; ++i)
{
if (userType == m_UserSpecifiedComponentData[i])
{
userTypeId = i;
break;
}
}
if (userTypeId == -1)
{
if (m_UserSpecifiedComponentData.Length == 8)
{
UnityEngine.Debug.LogError("There can only be 8 components registered as user data.");
m_SmoothingActions.Remove(type);
return false;
}
m_UserSpecifiedComponentData.Add(userType);
userTypeId = m_UserSpecifiedComponentData.Length - 1;
}
var actionState = m_SmoothingActions[type];
actionState.userTypeId = userTypeId;
actionState.userTypeSize = UnsafeUtility.SizeOf<U>();
m_SmoothingActions[type] = actionState;
return true;
}
}
/// <summary>
/// System that corrects the client prediction errors, by applying the smoothing actions
/// registerd to the <see cref="GhostPredictionSmoothing"/> singleton to to all predicted ghost that miss-predict.
/// </summary>
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)]
[UpdateInGroup(typeof(PredictedSimulationSystemGroup), OrderLast = true)]
[UpdateBefore(typeof(GhostPredictionHistorySystem))]
[BurstCompile]
public partial struct GhostPredictionSmoothingSystem : ISystem
{
EntityQuery m_PredictionQuery;
NativeList<ComponentType> m_UserSpecifiedComponentData;
NativeParallelHashMap<ComponentType, GhostPredictionSmoothing.SmoothingActionState> m_SmoothingActions;
internal struct SmoothingAction : IComponentData {}
ComponentTypeHandle<GhostInstance> m_GhostComponentHandle;
ComponentTypeHandle<PredictedGhost> m_PredictedGhostHandle;
BufferTypeHandle<LinkedEntityGroup> m_LinkedEntityGroupHandle;
EntityTypeHandle m_EntityTypeHandle;
BufferLookup<GhostComponentSerializer.State> m_GhostComponentSerializerStateFromEntity;
BufferLookup<GhostCollectionPrefabSerializer> m_GhostCollectionPrefabSerializerFromEntity;
BufferLookup<GhostCollectionComponentIndex> m_GhostCollectionComponentIndexFromEntity;
//[BurstCompile]
public void OnCreate(ref SystemState state)
{
var builder = new EntityQueryBuilder(Allocator.Temp).WithAll<PredictedGhost, GhostInstance>();
m_PredictionQuery = state.GetEntityQuery(builder);
m_UserSpecifiedComponentData = new NativeList<ComponentType>(8, Allocator.Persistent);
m_SmoothingActions = new NativeParallelHashMap<ComponentType, GhostPredictionSmoothing.SmoothingActionState>(32, Allocator.Persistent);
state.RequireForUpdate<GhostCollection>();
state.RequireForUpdate<SmoothingAction>();
m_GhostComponentHandle = state.GetComponentTypeHandle<GhostInstance>(true);
m_PredictedGhostHandle = state.GetComponentTypeHandle<PredictedGhost>(true);
m_LinkedEntityGroupHandle = state.GetBufferTypeHandle<LinkedEntityGroup>(true);
m_EntityTypeHandle = state.GetEntityTypeHandle();
m_GhostComponentSerializerStateFromEntity = state.GetBufferLookup<GhostComponentSerializer.State>(true);
m_GhostCollectionPrefabSerializerFromEntity = state.GetBufferLookup<GhostCollectionPrefabSerializer>(true);
m_GhostCollectionComponentIndexFromEntity = state.GetBufferLookup<GhostCollectionComponentIndex>(true);
builder = new EntityQueryBuilder(Allocator.Temp).WithAll<SmoothingAction>();
var enableQuery = state.GetEntityQuery(builder);
var atype = new NativeArray<ComponentType>(1, Allocator.Temp);
atype[0] = ComponentType.ReadWrite<GhostPredictionSmoothing>();
var smoothingSingleton = state.EntityManager.CreateEntity(state.EntityManager.CreateArchetype(atype));
FixedString64Bytes singletonName = "GhostPredictionSmoothing-Singleton";
state.EntityManager.SetName(smoothingSingleton, singletonName);
SystemAPI.SetSingleton(new GhostPredictionSmoothing(m_SmoothingActions, m_UserSpecifiedComponentData, enableQuery));
state.World.GetExistingSystemManaged<PredictedSimulationSystemGroup>().AddSystemToPartialTickUpdate(ref state);
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
m_UserSpecifiedComponentData.Dispose();
m_SmoothingActions.Dispose();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var newtorkTime = SystemAPI.GetSingleton<NetworkTime>();
var lastBackupTime = SystemAPI.GetSingleton<GhostSnapshotLastBackupTick>();
if (newtorkTime.ServerTick != lastBackupTime.Value)
return;
if (m_SmoothingActions.IsEmpty)
{
state.EntityManager.DestroyEntity(SystemAPI.GetSingletonEntity<SmoothingAction>());
return;
}
m_GhostComponentHandle.Update(ref state);
m_PredictedGhostHandle.Update(ref state);
m_LinkedEntityGroupHandle.Update(ref state);
m_EntityTypeHandle.Update(ref state);
m_GhostComponentSerializerStateFromEntity.Update(ref state);
m_GhostCollectionPrefabSerializerFromEntity.Update(ref state);
m_GhostCollectionComponentIndexFromEntity.Update(ref state);
var smoothingJob = new PredictionSmoothingJob
{
predictionState = SystemAPI.GetSingleton<GhostPredictionHistoryState>().PredictionState,
ghostType = m_GhostComponentHandle,
predictedGhostType = m_PredictedGhostHandle,
entityType = m_EntityTypeHandle,
GhostCollectionSingleton = SystemAPI.GetSingletonEntity<GhostCollection>(),
GhostComponentCollectionFromEntity = m_GhostComponentSerializerStateFromEntity,
GhostTypeCollectionFromEntity = m_GhostCollectionPrefabSerializerFromEntity,
GhostComponentIndexFromEntity = m_GhostCollectionComponentIndexFromEntity,
childEntityLookup = state.GetEntityStorageInfoLookup(),
linkedEntityGroupType = m_LinkedEntityGroupHandle,
tick = newtorkTime.ServerTick,
smoothingActions = m_SmoothingActions
};
var ghostComponentCollection = state.EntityManager.GetBuffer<GhostCollectionComponentType>(smoothingJob.GhostCollectionSingleton);
DynamicTypeList.PopulateList(ref state, ghostComponentCollection, false, ref smoothingJob.DynamicTypeList);
DynamicTypeList.PopulateListFromArray(ref state, m_UserSpecifiedComponentData.AsArray(), true, ref smoothingJob.UserList);
state.Dependency = smoothingJob.ScheduleParallelByRef(m_PredictionQuery, state.Dependency);
}
[BurstCompile]
struct PredictionSmoothingJob : IJobChunk
{
public DynamicTypeList DynamicTypeList;
public DynamicTypeList UserList;
public NativeParallelHashMap<ulong, System.IntPtr>.ReadOnly predictionState;
[ReadOnly] public ComponentTypeHandle<GhostInstance> ghostType;
[ReadOnly] public ComponentTypeHandle<PredictedGhost> predictedGhostType;
[ReadOnly] public EntityTypeHandle entityType;
public Entity GhostCollectionSingleton;
[ReadOnly] public BufferLookup<GhostComponentSerializer.State> GhostComponentCollectionFromEntity;
[ReadOnly] public BufferLookup<GhostCollectionPrefabSerializer> GhostTypeCollectionFromEntity;
[ReadOnly] public BufferLookup<GhostCollectionComponentIndex> GhostComponentIndexFromEntity;
[ReadOnly] public EntityStorageInfoLookup childEntityLookup;
[ReadOnly] public BufferTypeHandle<LinkedEntityGroup> linkedEntityGroupType;
[ReadOnly] public NativeParallelHashMap<ComponentType, GhostPredictionSmoothing.SmoothingActionState> smoothingActions;
public NetworkTick tick;
const GhostSendType requiredSendMask = GhostSendType.OnlyPredictedClients;
public unsafe void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
// This job is not written to support queries with enableable component types.
Assert.IsFalse(useEnabledMask);
if (!predictionState.TryGetValue(chunk.SequenceNumber, out var state) ||
(*(PredictionBackupState*)state).entityCapacity != chunk.Capacity)
return;
DynamicComponentTypeHandle* ghostChunkComponentTypesPtr = DynamicTypeList.GetData();
int ghostChunkComponentTypesLength = DynamicTypeList.Length;
DynamicComponentTypeHandle* userTypes = UserList.GetData();
int userTypesLength = UserList.Length;
var GhostTypeCollection = GhostTypeCollectionFromEntity[GhostCollectionSingleton];
var GhostComponentIndex = GhostComponentIndexFromEntity[GhostCollectionSingleton];
var GhostComponentCollection = GhostComponentCollectionFromEntity[GhostCollectionSingleton];
var ghostComponents = chunk.GetNativeArray(ref ghostType);
int ghostTypeId = ghostComponents.GetFirstGhostTypeId();
if (ghostTypeId < 0)
return;
if (ghostTypeId >= GhostTypeCollection.Length)
return; // serialization data has not been loaded yet. This can only happen for prespawn objects
var typeData = GhostTypeCollection[ghostTypeId];
Entity* backupEntities = PredictionBackupState.GetEntities(state, (int)(tick.TickIndexForValidTick % PredictionBackupState.PredictionHistorySize));
var entities = chunk.GetNativeArray(entityType);
var PredictedGhosts = chunk.GetNativeArray(ref predictedGhostType);
int numBaseComponents = typeData.NumComponents - typeData.NumChildComponents;
var actions = new NativeList<GhostPredictionSmoothing.SmoothingActionState>(Allocator.Temp);
var childActions = new NativeList<GhostPredictionSmoothing.SmoothingActionState>(Allocator.Temp);
var predictionBackupIndex = (int)(tick.TickIndexForValidTick % PredictionBackupState.PredictionHistorySize);
byte* dataPtr = PredictionBackupState.GetData(state, predictionBackupIndex);
// todo: this loop could be cached on chunk.capacity, because now we are re-calculating it everytime.
for (int comp = 0; comp < typeData.NumComponents; ++comp)
{
int index = typeData.FirstComponent + comp;
int compIdx = GhostComponentIndex[index].ComponentIndex;
int serializerIdx = GhostComponentIndex[index].SerializerIndex;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (compIdx >= ghostChunkComponentTypesLength)
throw new System.InvalidOperationException("Component index out of range");
#endif
if ((GhostComponentIndex[index].SendMask&requiredSendMask) == 0)
continue;
//Buffer does not have any smoothing
if (GhostComponentCollection[serializerIdx].ComponentType.IsBuffer)
{
dataPtr = PredictionBackupState.GetNextData(dataPtr, GhostComponentSerializer.DynamicBufferComponentSnapshotSize, chunk.Capacity);
continue;
}
var compSize = GhostComponentCollection[serializerIdx].ComponentSize;
if (smoothingActions.TryGetValue(GhostComponentCollection[serializerIdx].ComponentType, out var action))
{
action.compIndex = compIdx;
action.compSize = compSize;
action.serializerIndex = serializerIdx;
action.entityIndex = GhostComponentIndex[index].EntityIndex;
action.backupData = dataPtr;
if (comp < numBaseComponents)
actions.Add(action);
else
childActions.Add(action);
}
dataPtr = PredictionBackupState.GetNextData(dataPtr, compSize, chunk.Capacity);
}
foreach (var action in actions)
{
if (chunk.Has(ref ghostChunkComponentTypesPtr[action.compIndex]))
{
for (int ent = 0; ent < entities.Length; ++ent)
{
// If this entity did not predict anything there was no rollback and no need to debug it
if (!PredictedGhosts[ent].ShouldPredict(tick))
continue;
if (entities[ent] != backupEntities[ent])
continue;
var compData = (byte*)chunk.GetDynamicComponentDataArrayReinterpret<byte>(ref ghostChunkComponentTypesPtr[action.compIndex], action.compSize).GetUnsafePtr();
void* usrDataPtr = null;
if (action.userTypeId >= 0 && chunk.Has(ref userTypes[action.userTypeId]))
{
var usrData = (byte*)chunk.GetDynamicComponentDataArrayReinterpret<byte>(ref userTypes[action.userTypeId], action.userTypeSize).GetUnsafeReadOnlyPtr();
usrDataPtr = usrData + action.userTypeSize * ent;
}
action.action.Ptr.Invoke((IntPtr)(compData + action.compSize * ent), (IntPtr)(action.backupData + action.compSize * ent),
(IntPtr)usrDataPtr);
}
}
}
var linkedEntityGroupAccessor = chunk.GetBufferAccessor(ref linkedEntityGroupType);
foreach (var action in childActions)
{
for (int ent = 0, chunkEntityCount = chunk.Count; ent < chunkEntityCount; ++ent)
{
// If this entity did not predict anything there was no rollback and no need to debug it
if (!PredictedGhosts[ent].ShouldPredict(tick))
continue;
if (entities[ent] != backupEntities[ent])
continue;
var linkedEntityGroup = linkedEntityGroupAccessor[ent];
var childEnt = linkedEntityGroup[action.entityIndex].Value;
if (childEntityLookup.TryGetValue(childEnt, out var childChunk) &&
childChunk.Chunk.Has(ref ghostChunkComponentTypesPtr[action.compIndex]))
{
var compData = (byte*)childChunk.Chunk.GetDynamicComponentDataArrayReinterpret<byte>(ref ghostChunkComponentTypesPtr[action.compIndex], action.compSize).GetUnsafePtr();
void* usrDataPtr = null;
if (action.userTypeId >= 0 && chunk.Has(ref userTypes[action.userTypeId]))
{
var usrData = (byte*)chunk.GetDynamicComponentDataArrayReinterpret<byte>(ref userTypes[action.userTypeId], action.userTypeSize).GetUnsafeReadOnlyPtr();
usrDataPtr = usrData + action.userTypeSize * ent;
}
action.action.Ptr.Invoke((IntPtr)(compData + action.compSize * childChunk.IndexInChunk), (IntPtr)(action.backupData + action.compSize * ent), (IntPtr)usrDataPtr);
}
}
}
}
}
}
}
| 0 | 0.933529 | 1 | 0.933529 | game-dev | MEDIA | 0.904901 | game-dev | 0.950854 | 1 | 0.950854 |
Scrawk/CGALDotNetUnity | 1,235 | Assets/Common/Utility/ConsoleRedirect.cs | using System;
using System.IO;
using System.Text;
using UnityEngine;
namespace Common.Unity.Utility
{
/// <summary>
/// Redirects writes to System.Console to Unity3D's Debug.Log.
/// </summary>
/// <author>
/// Jackson Dunstan, http://jacksondunstan.com/articles/2986
/// </author>
public static class ConsoleRedirect
{
private class UnityTextWriter : TextWriter
{
private StringBuilder buffer = new StringBuilder();
public override void Flush()
{
Debug.Log(buffer.ToString());
buffer.Length = 0;
}
public override void Write(string value)
{
buffer.Append(value);
if (value != null)
{
var len = value.Length;
if (len > 0)
{
var lastChar = value[len - 1];
if (lastChar == '\n')
{
Flush();
}
}
}
}
public override void Write(char value)
{
buffer.Append(value);
if (value == '\n')
{
Flush();
}
}
public override void Write(char[] value, int index, int count)
{
Write(new string(value, index, count));
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
public static void Redirect()
{
Console.SetOut(new UnityTextWriter());
}
}
} | 0 | 0.758565 | 1 | 0.758565 | game-dev | MEDIA | 0.301234 | game-dev | 0.8473 | 1 | 0.8473 |
FourGames/FourGames | 1,065 | Resources/Godot/2024/Ticket Quest/ProjectAD/.godot/editor/OldMainMenu.tscn-folding-980861655c813f36fc306d6ef091a91f.cfg | [folding]
node_unfolds=[NodePath("."), PackedStringArray("Layout"), NodePath("Sprite2D"), PackedStringArray("Transform"), NodePath("Label"), PackedStringArray("Layout", "Theme Overrides"), NodePath("VBoxContainer"), PackedStringArray("Layout"), NodePath("VBoxContainer/StartTestWorld"), PackedStringArray("Layout", "Focus", "Theme Overrides"), NodePath("VBoxContainer/StartHubWorld"), PackedStringArray("Layout", "Theme Overrides"), NodePath("VBoxContainer/OptionButton"), PackedStringArray("Layout", "Theme Overrides"), NodePath("VBoxContainer/QuitButton"), PackedStringArray("Layout", "Focus", "Theme Overrides"), NodePath("FpsLabel"), PackedStringArray("Layout")]
resource_unfolds=["res://Scenes/Menus/OldMainMenu.tscn::4", PackedStringArray("Resource"), "res://Scenes/Menus/OldMainMenu.tscn::1", PackedStringArray("Resource"), "res://Scenes/Menus/OldMainMenu.tscn::2", PackedStringArray("Resource"), "res://Scenes/Menus/OldMainMenu.tscn::3", PackedStringArray("Resource"), "res://Scenes/Menus/fps_label.tscn::1", PackedStringArray("Resource")]
nodes_folded=[]
| 0 | 0.886914 | 1 | 0.886914 | game-dev | MEDIA | 0.884067 | game-dev | 0.915926 | 1 | 0.915926 |
TeamWizardry/Wizardry | 2,844 | src/main/java/com/teamwizardry/wizardry/api/lifetimeobject/LifetimeObjectManager.java | package com.teamwizardry.wizardry.api.lifetimeobject;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import java.util.*;
import java.util.function.Consumer;
public final class LifetimeObjectManager<T extends LifetimeObject> {
private static final String NBT_KEY_TICK = "tick";
private static final String NBT_KEY_ENTRIES = "entries";
private static final String NBT_KEY_ENTRY_OBJECT = "object";
private static final String NBT_KEY_ENTRY_TICK = "tick";
private final Adapter<T> adapter;
private final List<Entry> entries = new ArrayList<>();
private final Deque<Entry> adds = new ArrayDeque<>();
private long tick;
public LifetimeObjectManager(final Adapter<T> adapter) {
this.adapter = adapter;
}
public void add(final T object, final long lifespan) {
this.adds.addLast(new Entry(object, lifespan));
}
public void tick(Consumer<Boolean> onChange) {
for (Entry entry; ((entry = this.adds.pollFirst()) != null); ) {
onChange.accept(true);
this.entries.add(entry);
entry.object.start();
}
for (final Iterator<Entry> it = this.entries.iterator(); it.hasNext(); ) {
final Entry entry = it.next();
// Minecraft.getMinecraft().player.sendChatMessage(entry.tick + " / " + this.tick);
if (--entry.tick > 0) {
entry.object.tick();
} else {
entry.object.stop();
it.remove();
onChange.accept(true);
}
}
this.tick++;
}
public NBTTagCompound toNbt() {
final NBTTagCompound compound = new NBTTagCompound();
compound.setLong(NBT_KEY_TICK, this.tick);
final NBTTagList entries = new NBTTagList();
for (final Entry e : this.entries) {
this.adapter.toNbt(e.object, nbt -> {
final NBTTagCompound entry = new NBTTagCompound();
entry.setTag(NBT_KEY_ENTRY_OBJECT, nbt);
entry.setLong(NBT_KEY_ENTRY_TICK, e.tick);
entries.appendTag(entry);
});
}
compound.setTag(NBT_KEY_ENTRIES, entries);
return compound;
}
public void fromNbt(final NBTTagCompound compound) {
this.tick = compound.getLong(NBT_KEY_TICK);
this.entries.clear();
final NBTTagList entries = compound.getTagList(NBT_KEY_ENTRIES, Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < entries.tagCount(); i++) {
final NBTTagCompound entry = entries.getCompoundTagAt(i);
this.adapter.fromNbt(entry.getCompoundTag(NBT_KEY_ENTRY_OBJECT), obj ->
this.entries.add(new Entry(obj, entry.getLong(NBT_KEY_ENTRY_TICK)))
);
}
}
public interface Adapter<T extends LifetimeObject> {
void toNbt(final T object, final Consumer<NBTTagCompound> consumer);
void fromNbt(final NBTTagCompound nbt, final Consumer<T> consumer);
}
private final class Entry {
private final T object;
private long tick;
Entry(final T object, final long tick) {
this.object = object;
this.tick = tick;
}
}
} | 0 | 0.839076 | 1 | 0.839076 | game-dev | MEDIA | 0.95733 | game-dev | 0.816593 | 1 | 0.816593 |
Fluorohydride/ygopro-scripts | 2,979 | c87835759.lua | --創世の竜騎士
function c87835759.initial_effect(c)
--level
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(4)
e1:SetCondition(c87835759.lvcon)
c:RegisterEffect(e1)
--to grave
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(87835759,0))
e2:SetCategory(CATEGORY_TOGRAVE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BATTLE_DESTROYING)
e2:SetCondition(aux.bdogcon)
e2:SetTarget(c87835759.tgtg)
e2:SetOperation(c87835759.tgop)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(87835759,1))
e3:SetCategory(CATEGORY_TOGRAVE+CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,87835759)
e3:SetCost(c87835759.spcost)
e3:SetTarget(c87835759.sptg)
e3:SetOperation(c87835759.spop)
c:RegisterEffect(e3)
end
function c87835759.lvcon(e)
return Duel.GetTurnPlayer()~=e:GetHandlerPlayer()
end
function c87835759.tgfilter(c)
return c:IsRace(RACE_DRAGON) and c:IsLevel(7,8) and c:IsAbleToGrave()
end
function c87835759.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c87835759.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c87835759.tgop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c87835759.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
function c87835759.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,Card.IsAbleToGraveAsCost,1,1,REASON_COST)
end
function c87835759.spfilter(c,e,tp)
return c:IsRace(RACE_DRAGON) and c:IsLevel(7,8) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c87835759.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c87835759.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and e:GetHandler():IsAbleToGrave()
and Duel.IsExistingTarget(c87835759.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c87835759.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,e:GetHandler(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c87835759.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SendtoGrave(c,REASON_EFFECT)~=0 and c:IsLocation(LOCATION_GRAVE) then
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| 0 | 0.920615 | 1 | 0.920615 | game-dev | MEDIA | 0.988285 | game-dev | 0.977171 | 1 | 0.977171 |
NH07HACKS/farlight84-cheat- | 1,066 | ImGui DirectX 11 Kiero Hook/CppSDK/SDK/BP_Express_classes.hpp | #pragma once
/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/
// Package: BP_Express
#include "Basic.hpp"
#include "Solarland_classes.hpp"
namespace SDK
{
// BlueprintGeneratedClass BP_Express.BP_Express_C
// 0x0008 (0x0BF8 - 0x0BF0)
class ABP_Express_C final : public ASolarSummonExpress
{
public:
class UCapsuleComponent* Capsule; // 0x0BF0(0x0008)(BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, HasGetValueTypeHash)
public:
static class UClass* StaticClass()
{
return StaticBPGeneratedClassImpl<"BP_Express_C">();
}
static class ABP_Express_C* GetDefaultObj()
{
return GetDefaultObjImpl<ABP_Express_C>();
}
};
static_assert(alignof(ABP_Express_C) == 0x000008, "Wrong alignment on ABP_Express_C");
static_assert(sizeof(ABP_Express_C) == 0x000BF8, "Wrong size on ABP_Express_C");
static_assert(offsetof(ABP_Express_C, Capsule) == 0x000BF0, "Member 'ABP_Express_C::Capsule' has a wrong offset!");
}
| 0 | 0.564062 | 1 | 0.564062 | game-dev | MEDIA | 0.767901 | game-dev | 0.53408 | 1 | 0.53408 |
spohlenz/tinymce-rails | 1,235 | lib/tinymce/rails/asset_manifest.rb | module TinyMCE
module Rails
class AssetManifest
attr_reader :file
def self.load(manifest_path)
NewPropshaftManifest.try(manifest_path) ||
PropshaftManifest.try(manifest_path) ||
JsonManifest.try(manifest_path, ".sprockets-manifest*.json") ||
JsonManifest.try(manifest_path, "manifest*.json") ||
JsonManifest.try(manifest_path) ||
YamlManifest.try(manifest_path) ||
NullManifest.new
end
def each(pattern)
assets.each_key do |asset|
if asset =~ pattern && !index_asset?(asset)
yield asset
end
end
end
def asset_path(logical_path)
if digested = assets[logical_path]
yield digested, logical_path if block_given?
end
end
def to_s
dump
end
protected
def index_asset?(asset)
asset =~ /\/index[^\/]*\.\w+$/
end
end
require_relative "asset_manifest/json_manifest"
require_relative "asset_manifest/null_manifest"
require_relative "asset_manifest/new_propshaft_manifest"
require_relative "asset_manifest/propshaft_manifest"
require_relative "asset_manifest/yaml_manifest"
end
end
| 0 | 0.579683 | 1 | 0.579683 | game-dev | MEDIA | 0.269142 | game-dev | 0.505477 | 1 | 0.505477 |
una-xiv/umbra | 13,860 | Umbra/src/Toolbar/Widgets/System/WidgetManager.cs |
using Lumina.Misc;
using System.Collections.Immutable;
using Umbra.AuxBar;
namespace Umbra.Widgets.System;
[Service]
internal sealed partial class WidgetManager : IDisposable
{
public event Action<ToolbarWidget>? OnWidgetCreated;
public event Action<ToolbarWidget>? OnWidgetRemoved;
public event Action<ToolbarWidget, string>? OnWidgetRelocated;
private readonly Dictionary<string, Type> _widgetTypes = [];
private readonly Dictionary<string, WidgetInfo> _widgetInfos = [];
private readonly Dictionary<string, ToolbarWidget> _instances = [];
private readonly HashSet<Node> _subscribedQuickAccessNodes = [];
private Toolbar Toolbar { get; }
private IPlayer Player { get; }
private UmbraDelvClipRects ClipRects { get; }
private byte _lastJobId;
private bool _quickAccessEnabled;
public WidgetManager(Toolbar toolbar, IPlayer player, UmbraDelvClipRects clipRects)
{
Toolbar = toolbar;
Player = player;
ClipRects = clipRects;
foreach ((Type type, WidgetInfo info) in WidgetRegistry.RegisteredWidgets) {
if (type.IsSubclassOf(typeof(ToolbarWidget))) {
_widgetTypes[info.Id] = type;
_widgetInfos[info.Id] = info;
}
}
if (!_widgetProfiles.ContainsKey("Default") == false) {
_widgetProfiles["Default"] = WidgetConfigData;
SaveProfileData();
}
ConfigManager.CvarChanged += OnCvarChanged;
LoadProfileData();
LoadState();
}
public void Dispose()
{
ConfigManager.CvarChanged -= OnCvarChanged;
foreach (var node in _subscribedQuickAccessNodes) {
node.OnRightClick -= InvokeInstanceQuickSettings;
}
foreach (var widget in _instances.Values) {
widget.Dispose();
if (widget.Popup is IDisposable disposable) {
disposable.Dispose();
}
}
foreach (var handler in OnWidgetCreated?.GetInvocationList() ?? [])
OnWidgetCreated -= (Action<ToolbarWidget>)handler;
foreach (var handler in OnWidgetRemoved?.GetInvocationList() ?? [])
OnWidgetRemoved -= (Action<ToolbarWidget>)handler;
foreach (var handler in OnWidgetRelocated?.GetInvocationList() ?? [])
OnWidgetRelocated -= (Action<ToolbarWidget, string>)handler;
foreach (var handler in OnPopupOpened?.GetInvocationList() ?? []) OnPopupOpened -= (Action<WidgetPopup>)handler;
foreach (var handler in OnPopupClosed?.GetInvocationList() ?? []) OnPopupClosed -= (Action<WidgetPopup>)handler;
foreach (var handler in ProfileCreated?.GetInvocationList() ?? []) ProfileCreated -= (Action<string>)handler;
foreach (var handler in ProfileRemoved?.GetInvocationList() ?? []) ProfileRemoved -= (Action<string>)handler;
foreach (var handler in ActiveProfileChanged?.GetInvocationList() ?? [])
ActiveProfileChanged -= (Action<string>)handler;
_instances.Clear();
_widgetState.Clear();
_widgetProfiles.Clear();
_widgetTypes.Clear();
_widgetInfos.Clear();
_subscribedQuickAccessNodes.Clear();
_currentPopup = null;
_currentActivator = null;
}
/// <summary>
/// Returns an instance of a widget with the given GUID.
/// </summary>
public ToolbarWidget GetInstance(string guid)
{
return _instances[guid];
}
/// <summary>
/// Returns a list of <see cref="WidgetInfo"/> objects of all registered
/// widgets.
/// </summary>
/// <returns></returns>
public List<WidgetInfo> GetWidgetInfoList()
{
return _widgetInfos.Values.ToList();
}
/// <summary>
/// Returns the <see cref="WidgetInfo"/> object of a widget with the given
/// ID or NULL if no such widget exists.
/// </summary>
public WidgetInfo? GetWidgetInfo(string id)
{
return _widgetInfos.GetValueOrDefault(id);
}
public List<ToolbarWidget> GetWidgetInstances()
{
return _instances.Values.ToList();
}
/// <summary>
/// Creates a widget instance with the given name, location, and
/// configuration values.
/// </summary>
/// <param name="name">Which widget to create.</param>
/// <param name="location">The location of the widget in the toolbar.</param>
/// <param name="sortIndex">The sort index of this instance.</param>
/// <param name="guid">An instance GUID used for user config mapping.</param>
/// <param name="configValues">A dictionary of config values for this instance.</param>
/// <param name="saveState">Whether to save the state of the widgets configuration.</param>
/// <exception cref="InvalidOperationException">If the widget does not exist.</exception>
public void CreateWidget(
string name,
string location,
int? sortIndex = null,
string? guid = null,
Dictionary<string, object>? configValues = null,
bool saveState = true
)
{
CrashLogger.Guard($"Failed to create widget: {name}", $"An error occurred while instantiating the widget {name}. This should never happen. Please report this to the #support channel in Umbra's Discord.", () => {
if (!_widgetTypes.TryGetValue(name, out var type))
throw new InvalidOperationException($"No widget with the name '{name}' is registered.");
if (!_widgetInfos.TryGetValue(name, out var info))
throw new InvalidOperationException($"No widget info for the widget '{name}' is available.");
var panel = Toolbar.GetPanel(location);
if (panel == null) {
if (! location.StartsWith("aux")) {
Logger.Error($"Attempted to create a widget in an invalid location '{location}'.");
return;
}
// Create the aux bar if it doesn't exist yet.
var aux = Framework.Service<AuxBarManager>().CreateBar(location);
panel = Toolbar.GetPanel(aux.Id);
if (panel == null) {
// This should never happen.
Logger.Error($"Attempted to create a widget in an invalid aux bar location '{location}', but the aux bar could not be created.");
return;
}
}
var widget = (ToolbarWidget)Activator.CreateInstance(type, info, guid, configValues)!;
widget.SortIndex = sortIndex ?? panel!.ChildNodes.Count;
widget.Location = location;
widget.Node.Id ??= $"UmbraWidget_{Crc32.Get(widget.Id)}";
widget.Node.Attach("Widget", widget);
widget.Setup();
widget.OpenPopup += OpenPopup;
widget.OpenPopupDelayed += OpenPopupIfAnyIsOpen;
_instances[widget.Id] = widget;
if (EnableQuickSettingAccess && _subscribedQuickAccessNodes.Add(widget.Node)) {
widget.Node.OnRightClick += InvokeInstanceQuickSettings;
}
panel.AppendChild(widget.Node);
SolveSortIndices(widget.Location);
OnWidgetCreated?.Invoke(widget);
SaveWidgetState(widget.Id);
if (saveState) SaveState();
}, false);
}
public void RemoveWidget(string guid, bool saveState = true)
{
if (!_instances.TryGetValue(guid, out var widget)) return;
if (_currentActivator is not null && _currentActivator == widget) {
ClosePopup();
}
if (_subscribedQuickAccessNodes.Remove(widget.Node)) {
widget.Node.OnRightClick -= InvokeInstanceQuickSettings;
}
widget.Node.Remove();
widget.Dispose();
widget.OpenPopup -= OpenPopup;
widget.OpenPopupDelayed -= OpenPopupIfAnyIsOpen;
if (widget.Popup is IDisposable disposable) {
disposable.Dispose();
}
lock (_instances) {
_instances.Remove(guid);
}
lock (_widgetState) {
_widgetState.Remove(guid);
}
int sortIndexStart = widget.SortIndex;
var instances = _instances
.Values
.Where(w => w.Location == widget.Location && w.SortIndex > sortIndexStart)
.ToList();
if (instances.Count > 0) {
foreach (var w in instances) {
w.SortIndex--;
SaveWidgetState(w.Id);
}
}
if (saveState) {
SaveState();
}
OnWidgetRemoved?.Invoke(widget);
}
public void CreateCopyOfWidget(string id)
{
Framework.DalamudFramework.Run(() => {
lock (_widgetState) {
if (!_instances.TryGetValue(id, out var widget)) return;
if (!_widgetState.TryGetValue(id, out var config)) return;
// Generate a new GUID for the copied widget.
string newGuid = Guid.NewGuid().ToString();
// Create a new widget instance with the same configuration as the original.
CreateWidget(widget.Info.Id, widget.Location, widget.SortIndex, newGuid, new(config.Config));
// Since we're copying the widget to the same place, we need to solve the sort indices.
SolveSortIndices(widget.Location);
SaveState();
}
}
);
}
/// <summary>
/// Returns the amount of instances of a widget with the given ID that are
/// currently active on the toolbar.
/// </summary>
public uint GetWidgetInstanceCount(string widgetId)
{
return (uint)_instances.Values.Count(w => w.Info.Id == widgetId);
}
/// <summary>
/// Updates the sort indices of all widgets to ensure there are no gaps.
/// </summary>
/// <param name="location"></param>
private void SolveSortIndices(string location)
{
if (_isLoadingState) return;
List<ToolbarWidget> children = _instances
.Values
.Where(w => w.Node.ParentNode!.Id == location)
.OrderBy(w => w.SortIndex)
.ToList();
for (var i = 0; i < children.Count; i++) {
if (children[i].SortIndex == i) continue;
children[i].SortIndex = i;
SaveWidgetState(children[i].Id);
}
}
[OnTick(interval: 16)]
private void OnUpdateWidgets()
{
byte jobId = Player.JobId;
if (UseJobAssociatedProfiles && jobId != _lastJobId && ActiveProfile != JobToProfileName[jobId]) {
_lastJobId = jobId;
ActivateProfile(JobToProfileName[jobId]);
return;
}
foreach (var widget in _instances.Values.ToImmutableArray()) {
if (widget.Node.ParentNode is null) continue;
string panelId = widget.Node.ParentNode!.Id!;
if (widget.Location != panelId) {
var panel = Toolbar.GetPanel(widget.Location);
if (panel == null) continue;
panel.AppendChild(widget.Node);
SolveSortIndices(widget.Location);
SolveSortIndices(panelId);
SaveWidgetState(widget.Id);
SaveState();
OnWidgetRelocated?.Invoke(widget, panelId);
}
widget.Update();
widget.Node.SortIndex = widget.SortIndex;
}
}
private void ToggleQuickAccessBindings()
{
if (_quickAccessEnabled && !EnableQuickSettingAccess) {
foreach (var instance in _instances.Values) {
if (_subscribedQuickAccessNodes.Remove(instance.Node)) {
instance.Node.OnRightClick -= InvokeInstanceQuickSettings;
}
}
_quickAccessEnabled = false;
return;
}
foreach (var instance in _instances.Values) {
if (_subscribedQuickAccessNodes.Add(instance.Node)) {
instance.Node.OnRightClick += InvokeInstanceQuickSettings;
}
}
_quickAccessEnabled = true;
}
private void InvokeInstanceQuickSettings(Node node)
{
if (node.ParentNode is null) return;
if (!(ImGui.GetIO().KeyCtrl && ImGui.GetIO().KeyShift)) return;
foreach (ToolbarWidget widget in _instances.Values) {
if (widget.Node == node) {
node.CancelEvent = true;
Framework.Service<WidgetInstanceEditor>().OpenEditor(widget);
break;
}
}
}
private void OnCvarChanged(string name)
{
switch (name) {
case "Toolbar.WidgetData":
LoadState();
break;
case "Toolbar.ProfileData":
LoadProfileData();
break;
case "Toolbar.EnableQuickSettingAccess":
ToggleQuickAccessBindings();
break;
}
}
private struct WidgetConfigStruct
{
public string Name { get; init; }
public int SortIndex { get; init; }
public string Location { get; init; }
public Dictionary<string, object> Config { get; init; }
}
}
| 0 | 0.92177 | 1 | 0.92177 | game-dev | MEDIA | 0.424395 | game-dev,desktop-app | 0.942151 | 1 | 0.942151 |
MixedRealityToolkit/MixedRealityToolkit-Unity | 6,207 | org.mixedrealitytoolkit.input/Controllers/ActionBasedControllerWithFallbacks.cs | // Copyright (c) Mixed Reality Toolkit Contributors
// Licensed under the BSD 3-Clause
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;
namespace MixedReality.Toolkit.Input
{
/// <summary>
/// A specialized version of Unity's ActionBasedController that will fallback to other Input System actions for
/// position and rotation data when ActionBasedController's default track state has no position or rotation data.
/// </summary>
/// <remarks>
/// This is useful when the controller has multiple active devices backing it, and some controllers are not being
/// tracked. For example, HoloLens 2 eye gaze might be active but not calibrated, in which case eye gaze tracking
/// state will have no position and no rotation data. In this case, the controller may want to fallback to head pose.
/// </remarks>
[AddComponentMenu("MRTK/Input/XR Controller (Action-based with Fallbacks)")]
public class ActionBasedControllerWithFallbacks : ActionBasedController
{
#region Fallback actions values
[SerializeField, Tooltip("The fallback Input System action to use for Position Tracking for this GameObject when the default tracking state action has no position data. Must be a Vector3Control Control.")]
private InputActionProperty fallbackPositionAction;
/// <summary>
/// The fallback Input System action to use for Position Tracking for this GameObject when the default tracking
/// state action has no position data. Must be a Vector3Control Control.
/// </summary>
public InputActionProperty FallbackPositionAction => fallbackPositionAction;
[SerializeField, Tooltip("The fallback Input System action to use for Rotation Tracking for this GameObject when the default tracking state action has no position data. Must be a QuaternionControl Control.")]
private InputActionProperty fallbackRotationAction;
/// <summary>
/// The fallback Input System action to use for Rotation Tracking for this GameObject when the default tracking
/// state action has no rotation data. Must be a QuaternionControl Control.
/// </summary>
public InputActionProperty FallbackRotationAction => fallbackRotationAction;
[SerializeField, Tooltip("The fallback Input System action to get the Tracking State when updating this GameObject position or rotation. when the default track status action has no position or rotation data. If not specified, this will fallback to the device's tracking state that drives the position or rotation action.Must be a IntegerControl Control.")]
private InputActionProperty fallbackTrackingStateAction;
/// <summary>
/// The fallback Input System action to get the Tracking State when updating this GameObject position or rotation
/// when the default track status action has no position or rotation data. If not specified, this will fallback
/// to the device's tracking state that drives the position or rotation action.Must be a IntegerControl Control.
/// </summary>
public InputActionProperty FallbackTrackingStateAction => fallbackTrackingStateAction;
#endregion Fallback action values
#region ActionBasedController Overrides
/// <inheritdoc />
protected override void UpdateTrackingInput(XRControllerState controllerState)
{
base.UpdateTrackingInput(controllerState);
if (controllerState == null)
{
return;
}
var positionAction = fallbackPositionAction.action;
var hasPositionAction = positionAction != null;
var rotationAction = fallbackRotationAction.action;
var hasRotationAction = rotationAction != null;
var trackingStateAction = fallbackTrackingStateAction.action;
var hasTrackingStateAction = trackingStateAction != null && trackingStateAction.bindings.Count > 0;
// If no position data, use position fallback
if (!controllerState.inputTrackingState.HasFlag(InputTrackingState.Position) && hasPositionAction)
{
InputTrackingState fallbackPositionState = InputTrackingState.None;
if (hasTrackingStateAction)
{
fallbackPositionState = (InputTrackingState)trackingStateAction.ReadValue<int>();
}
else if (positionAction.activeControl?.device is TrackedDevice trackedDevice)
{
fallbackPositionState = (InputTrackingState)trackedDevice.trackingState.ReadValue();
}
if (fallbackPositionState.HasFlag(InputTrackingState.Position))
{
var position = positionAction.ReadValue<Vector3>();
controllerState.position = position;
controllerState.inputTrackingState |= InputTrackingState.Position;
}
}
// If no rotation data, use rotation fallback
if (!controllerState.inputTrackingState.HasFlag(InputTrackingState.Rotation) && hasRotationAction)
{
InputTrackingState fallbackRotationState = InputTrackingState.None;
if (hasTrackingStateAction)
{
fallbackRotationState = (InputTrackingState)trackingStateAction.ReadValue<int>();
}
else if (positionAction.activeControl?.device is TrackedDevice trackedDevice)
{
fallbackRotationState = (InputTrackingState)trackedDevice.trackingState.ReadValue();
}
if (fallbackRotationState.HasFlag(InputTrackingState.Rotation))
{
var rotation = rotationAction.ReadValue<Quaternion>();
controllerState.rotation = rotation;
controllerState.inputTrackingState |= InputTrackingState.Rotation;
}
}
}
#endregion ActionBasedController Overrides
}
}
| 0 | 0.986064 | 1 | 0.986064 | game-dev | MEDIA | 0.922126 | game-dev | 0.911429 | 1 | 0.911429 |
ImLegiitXD/Dream-Advanced | 8,838 | dll/back/1.12/net/minecraft/world/gen/feature/WorldGenBigMushroom.java | package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockHugeMushroom;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class WorldGenBigMushroom extends WorldGenerator
{
/** The mushroom type. 0 for brown, 1 for red. */
private final Block mushroomType;
public WorldGenBigMushroom(Block p_i46449_1_)
{
super(true);
this.mushroomType = p_i46449_1_;
}
public WorldGenBigMushroom()
{
super(false);
this.mushroomType = null;
}
public boolean generate(World worldIn, Random rand, BlockPos position)
{
Block block = this.mushroomType;
if (block == null)
{
block = rand.nextBoolean() ? Blocks.BROWN_MUSHROOM_BLOCK : Blocks.RED_MUSHROOM_BLOCK;
}
int i = rand.nextInt(3) + 4;
if (rand.nextInt(12) == 0)
{
i *= 2;
}
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 < 256)
{
for (int j = position.getY(); j <= position.getY() + 1 + i; ++j)
{
int k = 3;
if (j <= position.getY() + 3)
{
k = 0;
}
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l)
{
for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1)
{
if (j >= 0 && j < 256)
{
Material material = worldIn.getBlockState(blockpos$mutableblockpos.setPos(l, j, i1)).getMaterial();
if (material != Material.AIR && material != Material.LEAVES)
{
flag = false;
}
}
else
{
flag = false;
}
}
}
}
if (!flag)
{
return false;
}
else
{
Block block1 = worldIn.getBlockState(position.down()).getBlock();
if (block1 != Blocks.DIRT && block1 != Blocks.GRASS && block1 != Blocks.MYCELIUM)
{
return false;
}
else
{
int k2 = position.getY() + i;
if (block == Blocks.RED_MUSHROOM_BLOCK)
{
k2 = position.getY() + i - 3;
}
for (int l2 = k2; l2 <= position.getY() + i; ++l2)
{
int j3 = 1;
if (l2 < position.getY() + i)
{
++j3;
}
if (block == Blocks.BROWN_MUSHROOM_BLOCK)
{
j3 = 3;
}
int k3 = position.getX() - j3;
int l3 = position.getX() + j3;
int j1 = position.getZ() - j3;
int k1 = position.getZ() + j3;
for (int l1 = k3; l1 <= l3; ++l1)
{
for (int i2 = j1; i2 <= k1; ++i2)
{
int j2 = 5;
if (l1 == k3)
{
--j2;
}
else if (l1 == l3)
{
++j2;
}
if (i2 == j1)
{
j2 -= 3;
}
else if (i2 == k1)
{
j2 += 3;
}
BlockHugeMushroom.EnumType blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.byMetadata(j2);
if (block == Blocks.BROWN_MUSHROOM_BLOCK || l2 < position.getY() + i)
{
if ((l1 == k3 || l1 == l3) && (i2 == j1 || i2 == k1))
{
continue;
}
if (l1 == position.getX() - (j3 - 1) && i2 == j1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_WEST;
}
if (l1 == k3 && i2 == position.getZ() - (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_WEST;
}
if (l1 == position.getX() + (j3 - 1) && i2 == j1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_EAST;
}
if (l1 == l3 && i2 == position.getZ() - (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.NORTH_EAST;
}
if (l1 == position.getX() - (j3 - 1) && i2 == k1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_WEST;
}
if (l1 == k3 && i2 == position.getZ() + (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_WEST;
}
if (l1 == position.getX() + (j3 - 1) && i2 == k1)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_EAST;
}
if (l1 == l3 && i2 == position.getZ() + (j3 - 1))
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.SOUTH_EAST;
}
}
if (blockhugemushroom$enumtype == BlockHugeMushroom.EnumType.CENTER && l2 < position.getY() + i)
{
blockhugemushroom$enumtype = BlockHugeMushroom.EnumType.ALL_INSIDE;
}
if (position.getY() >= position.getY() + i - 1 || blockhugemushroom$enumtype != BlockHugeMushroom.EnumType.ALL_INSIDE)
{
BlockPos blockpos = new BlockPos(l1, l2, i2);
if (!worldIn.getBlockState(blockpos).isFullBlock())
{
this.setBlockAndNotifyAdequately(worldIn, blockpos, block.getDefaultState().withProperty(BlockHugeMushroom.VARIANT, blockhugemushroom$enumtype));
}
}
}
}
}
for (int i3 = 0; i3 < i; ++i3)
{
IBlockState iblockstate = worldIn.getBlockState(position.up(i3));
if (!iblockstate.isFullBlock())
{
this.setBlockAndNotifyAdequately(worldIn, position.up(i3), block.getDefaultState().withProperty(BlockHugeMushroom.VARIANT, BlockHugeMushroom.EnumType.STEM));
}
}
return true;
}
}
}
else
{
return false;
}
}
}
| 0 | 0.831512 | 1 | 0.831512 | game-dev | MEDIA | 0.865425 | game-dev | 0.973387 | 1 | 0.973387 |
DragonRuby/dragonruby-game-toolkit-contrib | 12,526 | samples/99_genre_fighting/01_special_move_inputs/app/main.rb | def tick args
#tick_instructions args, "Use LEFT and RIGHT arrow keys to move and SPACE to jump."
defaults args
render args
input args
calc args
end
# sets default values and creates empty collections
# initialization only happens in the first frame
def defaults args
fiddle args
Kernel.tick_count = Kernel.tick_count
args.state.bridge_top = 128
args.state.player.x ||= 0 # initializes player's properties
args.state.player.y ||= args.state.bridge_top
args.state.player.w ||= 64
args.state.player.h ||= 64
args.state.player.dy ||= 0
args.state.player.dx ||= 0
args.state.player.r ||= 0
args.state.game_over_at ||= 0
args.state.animation_time ||=0
args.state.timeleft ||=0
args.state.timeright ||=0
args.state.lastpush ||=0
args.state.inputlist ||= ["j","k","l"]
end
# sets enemy, player, hammer values
def fiddle args
args.state.gravity = -0.5
args.state.player_jump_power = 10 # sets player values
args.state.player_jump_power_duration = 5
args.state.player_max_run_speed = 20
args.state.player_speed_slowdown_rate = 0.9
args.state.player_acceleration = 0.9
end
# outputs objects onto the screen
def render args
if (args.state.player.dx < 0.01) && (args.state.player.dx > -0.01)
args.state.player.dx = 0
end
#move list
(Layout.rect_group row: 0, col_from_right: 8, drow: 0.3,
merge: { vertical_alignment_enum: 0, size_enum: -2 },
group: [
{ text: "move: WASD" },
{ text: "jump: Space" },
{ text: "attack forwards: J (while on ground" },
{ text: "attack upwards: K (while on groud)" },
{ text: "attack backwards: J (while on ground and holding A)" },
{ text: "attack downwards: K (while in air)" },
{ text: "dash attack: J, K in quick succession." },
{ text: "shield: hold J, K at the same time." },
{ text: "dash backwards: A, A in quick succession." },
]).into args.outputs.labels
# registered moves
args.outputs.labels << { x: 0.to_layout_col,
y: 0.to_layout_row,
text: "input history",
size_enum: -2,
vertical_alignment_enum: 0 }
(args.state.inputlist.take(5)).map do |s|
{ text: s, size_enum: -2, vertical_alignment_enum: 0 }
end.yield_self do |group|
(Layout.rect_group row: 0.3, col: 0, drow: 0.3, group: group).into args.outputs.labels
end
#sprites
player = [args.state.player.x, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/square/white.png",
args.state.player.r]
playershield = [args.state.player.x - 20, args.state.player.y - 10,
args.state.player.w + 20, args.state.player.h + 20,
"sprites/square/blue.png",
args.state.player.r,
0]
playerjab = [args.state.player.x + 32, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png",
args.state.player.r,
0]
playerupper = [args.state.player.x, args.state.player.y + 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png",
args.state.player.r+90,
0]
if ((Kernel.tick_count - args.state.lastpush) <= 15)
if (args.state.inputlist[0] == "<<")
player = [args.state.player.x, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/square/yellow.png", args.state.player.r]
end
if (args.state.inputlist[0] == "shield")
player = [args.state.player.x, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/square/indigo.png", args.state.player.r]
playershield = [args.state.player.x - 10, args.state.player.y - 10,
args.state.player.w + 20, args.state.player.h + 20,
"sprites/square/blue.png", args.state.player.r, 50]
end
if (args.state.inputlist[0] == "back-attack")
playerjab = [args.state.player.x - 20, args.state.player.y,
args.state.player.w - 10, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r, 255]
end
if (args.state.inputlist[0] == "forward-attack")
playerjab = [args.state.player.x + 32, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r, 255]
end
if (args.state.inputlist[0] == "up-attack")
playerupper = [args.state.player.x, args.state.player.y + 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r + 90, 255]
end
if (args.state.inputlist[0] == "dair")
playerupper = [args.state.player.x, args.state.player.y - 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/indigo.png", args.state.player.r + 90, 255]
end
if (args.state.inputlist[0] == "dash-attack")
playerupper = [args.state.player.x, args.state.player.y + 32,
args.state.player.w, args.state.player.h,
"sprites/isometric/violet.png", args.state.player.r + 90, 255]
playerjab = [args.state.player.x + 32, args.state.player.y,
args.state.player.w, args.state.player.h,
"sprites/isometric/violet.png", args.state.player.r, 255]
end
end
args.outputs.sprites << playerjab
args.outputs.sprites << playerupper
args.outputs.sprites << player
args.outputs.sprites << playershield
args.outputs.solids << 20.map_with_index do |i| # uses 20 squares to form bridge
[i * 64, args.state.bridge_top - 64, 64, 64]
end
end
# Performs calculations to move objects on the screen
def calc args
# Since velocity is the change in position, the change in x increases by dx. Same with y and dy.
args.state.player.x += args.state.player.dx
args.state.player.y += args.state.player.dy
# Since acceleration is the change in velocity, the change in y (dy) increases every frame
args.state.player.dy += args.state.gravity
# player's y position is either current y position or y position of top of
# bridge, whichever has a greater value
# ensures that the player never goes below the bridge
args.state.player.y = args.state.player.y.greater(args.state.bridge_top)
# player's x position is either the current x position or 0, whichever has a greater value
# ensures that the player doesn't go too far left (out of the screen's scope)
args.state.player.x = args.state.player.x.greater(0)
# player is not falling if it is located on the top of the bridge
args.state.player.falling = false if args.state.player.y == args.state.bridge_top
#args.state.player.rect = [args.state.player.x, args.state.player.y, args.state.player.h, args.state.player.w] # sets definition for player
end
# Resets the player by changing its properties back to the values they had at initialization
def reset_player args
args.state.player.x = 0
args.state.player.y = args.state.bridge_top
args.state.player.dy = 0
args.state.player.dx = 0
args.state.enemy.hammers.clear # empties hammer collection
args.state.enemy.hammer_queue.clear # empties hammer_queue
args.state.game_over_at = Kernel.tick_count # game_over_at set to current frame (or passage of time)
end
# Processes input from the user to move the player
def input args
if args.state.inputlist.length > 5
args.state.inputlist.pop
end
should_process_special_move = (args.inputs.keyboard.key_down.j) ||
(args.inputs.keyboard.key_down.k) ||
(args.inputs.keyboard.key_down.a) ||
(args.inputs.keyboard.key_down.d) ||
(args.inputs.controller_one.key_down.y) ||
(args.inputs.controller_one.key_down.x) ||
(args.inputs.controller_one.key_down.left) ||
(args.inputs.controller_one.key_down.right)
if (should_process_special_move)
if (args.inputs.keyboard.key_down.j && args.inputs.keyboard.key_down.k) ||
(args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.y)
args.state.inputlist.unshift("shield")
elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&
(args.state.inputlist[0] == "forward-attack") && ((Kernel.tick_count - args.state.lastpush) <= 15)
args.state.inputlist.unshift("dash-attack")
args.state.player.dx = 20
elsif (args.inputs.keyboard.key_down.j && args.inputs.keyboard.a) ||
(args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.left)
args.state.inputlist.unshift("back-attack")
elsif ( args.inputs.controller_one.key_down.x || args.inputs.keyboard.key_down.j)
args.state.inputlist.unshift("forward-attack")
elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&
(args.state.player.y > 128)
args.state.inputlist.unshift("dair")
elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y)
args.state.inputlist.unshift("up-attack")
elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a) &&
(args.state.inputlist[0] == "<") &&
((Kernel.tick_count - args.state.lastpush) <= 10)
args.state.inputlist.unshift("<<")
args.state.player.dx = -15
elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a)
args.state.inputlist.unshift("<")
args.state.timeleft = Kernel.tick_count
elsif (args.inputs.controller_one.key_down.right || args.inputs.keyboard.key_down.d)
args.state.inputlist.unshift(">")
end
args.state.lastpush = Kernel.tick_count
end
if args.inputs.keyboard.space || args.inputs.controller_one.r2 # if the user presses the space bar
args.state.player.jumped_at ||= Kernel.tick_count # jumped_at is set to current frame
# if the time that has passed since the jump is less than the player's jump duration and
# the player is not falling
if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling
args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump
end
end
# if the space bar is in the "up" state (or not being pressed down)
if args.inputs.keyboard.key_up.space || args.inputs.controller_one.key_up.r2
args.state.player.jumped_at = nil # jumped_at is empty
args.state.player.falling = true # the player is falling
end
if args.inputs.left # if left key is pressed
if args.state.player.dx < -5
args.state.player.dx = args.state.player.dx
else
args.state.player.dx = -5
end
elsif args.inputs.right # if right key is pressed
if args.state.player.dx > 5
args.state.player.dx = args.state.player.dx
else
args.state.player.dx = 5
end
else
args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down
end
if ((args.state.player.dx).abs > 5) #&& ((Kernel.tick_count - args.state.lastpush) <= 10)
args.state.player.dx *= 0.95
end
end
def tick_instructions args, text, y = 715
return if args.state.key_event_occurred
if args.inputs.mouse.click ||
args.inputs.keyboard.directional_vector ||
args.inputs.keyboard.key_down.enter ||
args.inputs.keyboard.key_down.space ||
args.inputs.keyboard.key_down.escape
args.state.key_event_occurred = true
end
args.outputs.debug << [0, y - 50, 1280, 60].solid
args.outputs.debug << [640, y, text, 1, 1, 255, 255, 255].label
args.outputs.debug << [640, y - 25, "(click to dismiss instructions)" , -2, 1, 255, 255, 255].label
end
| 0 | 0.580979 | 1 | 0.580979 | game-dev | MEDIA | 0.909069 | game-dev | 0.873841 | 1 | 0.873841 |
AddstarMC/Minigames | 1,398 | Minigames/src/main/java/au/com/mineauz/minigames/config/Flag.java | package au.com.mineauz.minigames.config;
import au.com.mineauz.minigames.menu.Callback;
import au.com.mineauz.minigames.menu.MenuItem;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.List;
public abstract class Flag<T> {
private T value;
private String name;
private T defaultVal;
public T getFlag() {
return value;
}
public void setFlag(T value) {
this.value = value;
}
public String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
public T getDefaultFlag() {
return defaultVal;
}
protected void setDefaultFlag(T value) {
defaultVal = value;
}
public Callback<T> getCallback() {
return new Callback<>() {
@Override
public T getValue() {
return getFlag();
}
@Override
public void setValue(T value) {
setFlag(value);
}
};
}
public abstract void saveValue(String path, FileConfiguration config);
public abstract void loadValue(String path, FileConfiguration config);
public abstract MenuItem getMenuItem(String name, Material displayItem);
public abstract MenuItem getMenuItem(String name, Material displayItem, List<String> description);
}
| 0 | 0.793277 | 1 | 0.793277 | game-dev | MEDIA | 0.969227 | game-dev | 0.940288 | 1 | 0.940288 |
sideeffects/HoudiniEngineForUnity | 46,806 | Plugins/HoudiniEngineUnity/Scripts/Asset/HEU_GeoNode.cs | /*
* Copyright (c) <2020> Side Effects Software Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. The name of Side Effects Software may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "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 SIDE EFFECTS SOFTWARE 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.
*/
// Uncomment to profile
//#define HEU_PROFILER_ON
#define TERRAIN_SUPPORTED
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Expose internal classes/functions
#if UNITY_EDITOR
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("HoudiniEngineUnityEditor")]
[assembly: InternalsVisibleTo("HoudiniEngineUnityEditorTests")]
[assembly: InternalsVisibleTo("HoudiniEngineUnityPlayModeTests")]
#endif
namespace HoudiniEngineUnity
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Typedefs (copy these from HEU_Common.cs)
using HAPI_NodeId = System.Int32;
using HAPI_PartId = System.Int32;
/// <summary>
/// Represents a Geometry (SOP) node.
/// </summary>
public class HEU_GeoNode : ScriptableObject, IHEU_GeoNode, IHEU_HoudiniAssetSubcomponent, ISerializationCallbackReceiver, IEquivable<HEU_GeoNode>
{
// PUBLIC FIELDS ==========================================================================
/// <inheritdoc />
public HEU_HoudiniAsset ParentAsset
{
get { return (_containerObjectNode != null) ? _containerObjectNode.ParentAsset : null; }
}
/// <inheritdoc />
public HAPI_NodeId GeoID
{
get { return _geoInfo.nodeId; }
}
/// <inheritdoc />
public HAPI_GeoInfo GeoInfo
{
get { return _geoInfo; }
}
/// <inheritdoc />
public string GeoName
{
get { return _geoName; }
}
/// <inheritdoc />
public HAPI_GeoType GeoType
{
get { return _geoInfo.type; }
}
/// <inheritdoc />
public bool Editable
{
get { return _geoInfo.isEditable; }
}
/// <inheritdoc />
public bool Displayable
{
get
{
if (ParentAsset && ParentAsset.UseOutputNodes == true) return true; // Trust that it is displayable if using output nodes
return _geoInfo.isDisplayGeo;
}
}
/// <inheritdoc />
public List<HEU_PartData> Parts
{
get { return _parts; }
}
/// <inheritdoc />
public HEU_ObjectNode ObjectNode
{
get { return _containerObjectNode; }
}
/// <inheritdoc />
public HEU_InputNode InputNode
{
get { return _inputNode; }
}
/// <inheritdoc />
public HEU_Curve GeoCurve
{
get { return _geoCurve; }
}
/// <inheritdoc />
public List<HEU_VolumeCache> VolumeCaches
{
get { return _volumeCaches; }
}
// =========================================================================================
// DATA ------------------------------------------------------------------------------------------------------
[SerializeField] private HAPI_GeoInfo _geoInfo;
[SerializeField] private string _geoName;
[SerializeField] private List<HEU_PartData> _parts;
[SerializeField] private HEU_ObjectNode _containerObjectNode;
[SerializeField] private HEU_InputNode _inputNode;
[SerializeField] private HEU_Curve _geoCurve;
// Deprecated by _volumeCaches. Keeping it for backwards compatibility on saved assets.
[SerializeField] private HEU_VolumeCache _volumeCache;
[SerializeField] private List<HEU_VolumeCache> _volumeCaches;
// PUBLIC FUNCTIONS ===============================================================
public HEU_GeoNode()
{
Reset();
}
// Implement methods
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
// _volumeCaches replaces _volumeCache, and _volumeCache has been deprecated.
// This takes care of moving in the old _volumeCache into _volumeCaches.
if (_volumeCache != null && (_volumeCaches == null || _volumeCaches.Count == 0))
{
_volumeCaches = new List<HEU_VolumeCache>();
_volumeCaches.Add(_volumeCache);
_volumeCache = null;
}
}
/// <inheritdoc />
public HEU_SessionBase GetSession()
{
if (ParentAsset != null)
{
return ParentAsset.GetAssetSession(true);
}
else
{
return HEU_SessionManager.GetOrCreateDefaultSession();
}
}
/// <inheritdoc />
public void Recook()
{
if (ParentAsset != null) ParentAsset.RequestCook();
}
/// <inheritdoc />
public bool IsVisible()
{
return _containerObjectNode.IsVisible();
}
/// <inheritdoc />
public bool IsIntermediate()
{
return (_geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_INTERMEDIATE);
}
/// <inheritdoc />
public bool IsIntermediateOrEditable()
{
return (_geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_INTERMEDIATE ||
(_geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_DEFAULT && _geoInfo.isEditable));
}
/// <inheritdoc />
public bool IsGeoInputType()
{
return _geoInfo.isEditable && _geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_INPUT;
}
/// <inheritdoc />
public bool IsGeoCurveType()
{
return _geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_CURVE;
}
/// <inheritdoc />
public void DestroyAllData(bool bIsRebuild = false)
{
HEU_PartData.DestroyParts(_parts, bIsRebuild);
if (_inputNode != null)
{
HEU_SessionBase session = null;
if (ParentAsset != null)
{
ParentAsset.RemoveInputNode(_inputNode);
session = ParentAsset.GetAssetSession(false);
}
_inputNode.DestroyAllData(session);
HEU_GeneralUtility.DestroyImmediate(_inputNode);
_inputNode = null;
}
if (_geoCurve != null)
{
if (ParentAsset != null)
{
ParentAsset.RemoveCurve(_geoCurve);
}
_geoCurve.DestroyAllData(bIsRebuild);
HEU_GeneralUtility.DestroyImmediate(_geoCurve);
_geoCurve = null;
}
DestroyVolumeCache();
}
/// <inheritdoc />
public void RemoveAndDestroyPart(HEU_PartData part)
{
_parts.Remove(part);
HEU_PartData.DestroyPart(part);
}
/// <inheritdoc />
public void GetOutputGameObjects(List<GameObject> outputObjects)
{
foreach (HEU_PartData part in _parts)
{
part.GetOutputGameObjects(outputObjects);
}
}
/// <inheritdoc />
public void GetOutput(List<HEU_GeneratedOutput> outputs)
{
foreach (HEU_PartData part in _parts)
{
part.GetOutput(outputs);
}
}
/// <inheritdoc />
public HEU_PartData GetHDAPartWithGameObject(GameObject outputGameObject)
{
HEU_PartData foundPart = null;
foreach (HEU_PartData part in _parts)
{
foundPart = part.GetHDAPartWithGameObject(outputGameObject);
if (foundPart != null)
{
return foundPart;
}
}
return null;
}
/// <inheritdoc />
public HEU_PartData GetPartFromPartID(HAPI_NodeId partID)
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
if (_parts[i].PartID == partID)
{
return _parts[i];
}
}
return null;
}
/// <inheritdoc />
public void GetCurves(List<HEU_Curve> curves, bool bEditableOnly)
{
if (_geoCurve != null && (!bEditableOnly || _geoCurve.IsEditable()))
{
curves.Add(_geoCurve);
}
foreach (HEU_PartData part in _parts)
{
HEU_Curve partCurve = part.GetCurve(bEditableOnly);
if (partCurve != null)
{
curves.Add(partCurve);
}
}
}
/// <inheritdoc />
public List<HEU_PartData> GetParts()
{
return _parts;
}
/// <inheritdoc />
public void HideAllGeometry()
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
_parts[i].SetVisiblity(false);
}
}
/// <inheritdoc />
public void DisableAllColliders()
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
_parts[i].SetColliderState(false);
}
}
/// <inheritdoc />
public HEU_VolumeCache GetVolumeCacheByTileIndex(int tileIndex)
{
if (_volumeCaches != null)
{
int numCaches = _volumeCaches.Count;
for (int i = 0; i < numCaches; ++i)
{
if (_volumeCaches[i] != null && _volumeCaches[i].TileIndex == tileIndex)
{
return _volumeCaches[i];
}
}
}
else if (_volumeCache != null)
{
return _volumeCache;
}
return null;
}
// ================================================================================
// LOGIC -----------------------------------------------------------------------------------------------------
internal void Reset()
{
_geoName = "";
_geoInfo = new HAPI_GeoInfo();
_geoInfo.nodeId = -1;
_geoInfo.type = HAPI_GeoType.HAPI_GEOTYPE_DEFAULT;
_parts = new List<HEU_PartData>();
}
internal void Initialize(HEU_SessionBase session, HAPI_GeoInfo geoInfo, HEU_ObjectNode containerObjectNode)
{
_containerObjectNode = containerObjectNode;
_geoInfo = geoInfo;
string realName = HEU_SessionManager.GetString(_geoInfo.nameSH, session);
if (!HEU_PluginSettings.ShortenFolderPaths || realName.Length < 3)
{
_geoName = HEU_SessionManager.GetString(_geoInfo.nameSH, session);
}
else
{
_geoName = realName.Substring(0, 3) + this.GetHashCode();
}
//HEU_Logger.Log(string.Format("GeoNode initialized with ID={0}, name={1}, type={2}", GeoID, GeoName, geoInfo.type));
}
internal bool DoesThisRequirePotentialCook()
{
if ((_geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_INPUT)
|| (_geoInfo.isTemplated && !HEU_PluginSettings.CookTemplatedGeos && !_geoInfo.isEditable)
|| (!_geoInfo.hasGeoChanged)
|| (!_geoInfo.isDisplayGeo && (_geoInfo.type != HAPI_GeoType.HAPI_GEOTYPE_CURVE)))
{
return false;
}
return true;
}
internal void UpdateGeo(HEU_SessionBase session)
{
// Create or recreate parts.
bool bObjectInstancer = _containerObjectNode.IsInstancer();
// Save list of old parts. We'll destroy these after creating new parts.
// The reason for temporarily keeping these is to transfer data (eg. instance overrides, attribute data)
List<HEU_PartData> oldParts = new List<HEU_PartData>(_parts);
_parts.Clear();
if (ParentAsset == null)
{
return;
}
try
{
if (!_geoInfo.isDisplayGeo && !ParentAsset.UseOutputNodes)
{
if (ParentAsset.IgnoreNonDisplayNodes)
{
return;
}
else if (!_geoInfo.isEditable
|| (_geoInfo.type != HAPI_GeoType.HAPI_GEOTYPE_DEFAULT
&& _geoInfo.type != HAPI_GeoType.HAPI_GEOTYPE_INTERMEDIATE
&& _geoInfo.type != HAPI_GeoType.HAPI_GEOTYPE_CURVE))
{
return;
}
}
if (IsGeoCurveType())
{
ProcessGeoCurve(session);
}
else
{
int numParts = _geoInfo.partCount;
//HEU_Logger.Log("Number of parts: " + numParts);
//HEU_Logger.LogFormat("GeoNode type {0}, isTemplated: {1}, isDisplayGeo: {2}, isEditable: {3}", _geoInfo.type, _geoInfo.isTemplated, _geoInfo.isDisplayGeo, _geoInfo.isEditable);
for (int i = 0; i < numParts; ++i)
{
HAPI_PartInfo partInfo = new HAPI_PartInfo();
if (!session.GetPartInfo(GeoID, i, ref partInfo))
{
HEU_Logger.LogErrorFormat("Unable to get PartInfo for geo node {0} and part {1}.", GeoID, i);
continue;
}
string partName = HEU_SessionManager.GetString(partInfo.nameSH, session);
// Find the old part for this new part.
HEU_PartData part = null;
HEU_PartData oldMatchedPart = null;
foreach (HEU_PartData oldPart in oldParts)
{
if (oldPart.PartName.Equals(partName))
{
oldMatchedPart = oldPart;
break;
}
}
if (oldMatchedPart != null)
{
//HEU_Logger.Log("Found matched part: " + oldMatchedPart.name);
// ProcessPart will clear out the object instances, so hence why
// we keep a copy here, then restore after processing the parts.
// Note that at this point we don't know if the the new part is an
// instancer or not (e.g. object, attribute instancer).
List<HEU_ObjectInstanceInfo> sourceObjectInstanceInfos = oldMatchedPart.GetObjectInstanceInfos();
// Clear out old generated data
oldMatchedPart.ClearGeneratedData();
part = oldMatchedPart;
oldParts.Remove(oldMatchedPart);
ProcessPart(session, i, ref partInfo, ref part);
if (sourceObjectInstanceInfos != null && part != null && (bObjectInstancer || part.IsAttribInstancer()))
{
// Set object instances from old part into new. This keeps the user set object inputs around.
part.SetObjectInstanceInfos(sourceObjectInstanceInfos);
}
}
else
{
ProcessPart(session, i, ref partInfo, ref part);
}
}
}
}
finally
{
HEU_PartData.DestroyParts(oldParts);
}
}
/// <summary>
/// Process custom attribute with Unity script name, and attach any scripts found.
/// </summary>
/// <param name="session">Session to use</param>
internal void ProcessUnityScriptAttribute(HEU_SessionBase session)
{
if (_parts == null || _parts.Count == 0)
{
return;
}
foreach (HEU_PartData part in _parts)
{
GameObject outputGO = part.OutputGameObject;
if (outputGO != null)
{
string scriptValue = HEU_GeneralUtility.GetUnityScriptAttributeValue(session, GeoID, part.PartID);
if (!string.IsNullOrEmpty(scriptValue))
{
HEU_GeneralUtility.AttachScriptWithInvokeFunction(scriptValue, outputGO);
}
}
}
}
/// <summary>
/// Process the part at the given index, creating its data (geometry),
/// and adding it to the list of parts.
/// </summary>
/// <param name="session"></param>
/// <param name="partID"></param>
/// <returns>A valid HEU_PartData if it has been successfully processed.</returns>
private void ProcessPart(HEU_SessionBase session, int partID, ref HAPI_PartInfo partInfo, ref HEU_PartData partData)
{
HEU_HoudiniAsset parentAsset = ParentAsset;
if (parentAsset == null)
{
return;
}
bool bResult = true;
//HEU_Logger.LogFormat("Part: name={0}, id={1}, type={2}, instanced={3}, instance count={4}, instance part count={5}", HEU_SessionManager.GetString(partInfo.nameSH, session), partID, partInfo.type, partInfo.isInstanced, partInfo.instanceCount, partInfo.instancedPartCount);
#if HEU_PROFILER_ON
float processPartStartTime = Time.realtimeSinceStartup;
#endif
bool isPartEditable = IsIntermediateOrEditable();
bool isAttribInstancer = false;
if (IsGeoInputType())
{
// Setup for input node to accept inputs
if (_inputNode == null)
{
string partName = HEU_SessionManager.GetString(partInfo.nameSH, session);
_inputNode = HEU_InputNode.CreateSetupInput(GeoID, 0, partName, partName, HEU_InputNode.InputNodeType.NODE, ParentAsset);
if (_inputNode != null)
{
ParentAsset.AddInputNode(_inputNode);
}
}
if (HEU_HAPIUtility.IsSupportedPolygonType(partInfo.type) && partInfo.vertexCount == 0)
{
// No geometry for input asset
if (partData != null)
{
// Clean up existing part
HEU_PartData.DestroyPart(partData);
partData = null;
}
// No need to process further since we don't have geometry
return;
}
}
else
{
// Preliminary check for attribute instancing (mesh type with no verts but has points with instances)
if (HEU_HAPIUtility.IsSupportedPolygonType(partInfo.type) && partInfo.vertexCount == 0 && partInfo.pointCount > 0)
{
if (HEU_GeneralUtility.HasValidInstanceAttribute(session, GeoID, partID, HEU_PluginSettings.UnityInstanceAttr))
{
isAttribInstancer = true;
}
else if (HEU_GeneralUtility.HasValidInstanceAttribute(session, GeoID, partID,
HEU_Defines.HEIGHTFIELD_TREEINSTANCE_PROTOTYPEINDEX))
{
isAttribInstancer = true;
}
}
}
if (partInfo.type == HAPI_PartType.HAPI_PARTTYPE_INVALID)
{
// Clean up invalid parts
if (partData != null)
{
HEU_PartData.DestroyPart(partData);
partData = null;
}
}
else if (partInfo.type < HAPI_PartType.HAPI_PARTTYPE_MAX)
{
// Process the part based on type. Keep or ignore.
// We treat parts of type curve as curves, along with geo nodes that are editable and type curves
if (partInfo.type == HAPI_PartType.HAPI_PARTTYPE_CURVE)
{
if (partData == null)
{
partData = ScriptableObject.CreateInstance<HEU_PartData>();
}
partData.Initialize(session, partID, GeoID, _containerObjectNode.ObjectID, this, ref partInfo,
HEU_PartData.PartOutputType.CURVE, isPartEditable, _containerObjectNode.IsInstancer(), false);
SetupGameObjectAndTransform(partData, parentAsset);
partData.ProcessCurvePart(session, partID);
}
else if (partInfo.type == HAPI_PartType.HAPI_PARTTYPE_VOLUME)
{
// We only process "height" volume parts. Other volume parts are ignored for now.
#if TERRAIN_SUPPORTED
HAPI_VolumeInfo volumeInfo = new HAPI_VolumeInfo();
bResult = session.GetVolumeInfo(GeoID, partID, ref volumeInfo);
if (!bResult)
{
HEU_Logger.LogErrorFormat("Unable to get volume info for geo node {0} and part {1} ", GeoID, partID);
}
else
{
if (Displayable && !IsIntermediateOrEditable())
{
if (partData == null)
{
partData = ScriptableObject.CreateInstance<HEU_PartData>();
}
else
{
// Clear mesh data to handle case where switching from polygonal mesh to volume output.
partData.ClearGeneratedMeshOutput();
}
partData.Initialize(session, partID, GeoID, _containerObjectNode.ObjectID, this, ref partInfo,
HEU_PartData.PartOutputType.VOLUME, isPartEditable, _containerObjectNode.IsInstancer(), false);
SetupGameObjectAndTransform(partData, ParentAsset);
}
}
#else
HEU_Logger.LogWarningFormat("Terrain (heightfield volume) is not yet supported.");
#endif
}
else if (partInfo.type == HAPI_PartType.HAPI_PARTTYPE_INSTANCER || isAttribInstancer)
{
if (partData == null)
{
partData = ScriptableObject.CreateInstance<HEU_PartData>();
}
else
{
partData.ClearGeneratedMeshOutput();
partData.ClearGeneratedVolumeOutput();
}
partData.Initialize(session, partID, GeoID, _containerObjectNode.ObjectID, this, ref partInfo,
HEU_PartData.PartOutputType.INSTANCER, isPartEditable, _containerObjectNode.IsInstancer(), isAttribInstancer);
SetupGameObjectAndTransform(partData, parentAsset);
}
else if (HEU_HAPIUtility.IsSupportedPolygonType(partInfo.type))
{
if (partData == null)
{
partData = ScriptableObject.CreateInstance<HEU_PartData>();
}
else
{
// Clear volume data (case where switching from something other output to mesh)
partData.ClearGeneratedVolumeOutput();
}
partData.Initialize(session, partID, GeoID, _containerObjectNode.ObjectID, this, ref partInfo,
HEU_PartData.PartOutputType.MESH, isPartEditable, _containerObjectNode.IsInstancer(), false);
// This check allows to ignore editable non-display nodes by default, but commented out to allow
// them for now. Users can also ignore them by turning on IgnoreNonDisplayNodes
//if (Displayable || (Editable && ParentAsset.EditableNodesToolsEnabled))
{
SetupGameObjectAndTransform(partData, parentAsset);
}
}
else
{
HEU_Logger.LogWarningFormat("Unsupported part type {0}", partInfo.type);
}
if (partData != null)
{
// Success!
_parts.Add(partData);
// Set unique name for the part
string partName = HEU_PluginSettings.UseFullPathNamesForOutput ? GeneratePartFullName(partData.PartName) : partData.PartName;
partData.SetGameObjectName(partName);
// For intermediate or default-type editable nodes, setup the HEU_AttributeStore
if (isPartEditable)
{
partData.SyncAttributesStore(session, _geoInfo.nodeId, ref partInfo);
}
else
{
// Remove attributes store if it has it
partData.DestroyAttributesStore();
}
}
}
#if HEU_PROFILER_ON
HEU_Logger.LogFormat("PART PROCESS TIME:: NAME={0}, TIME={1}", HEU_SessionManager.GetString(partInfo.nameSH, session), (Time.realtimeSinceStartup - processPartStartTime));
#endif
}
private void SetupGameObjectAndTransform(HEU_PartData partData, HEU_HoudiniAsset parentAsset)
{
// Checking for nulls for undo safety
if (partData == null || parentAsset == null || parentAsset.OwnerGameObject == null || parentAsset.RootGameObject == null)
{
return;
}
// Set a valid gameobject for this part
if (partData.OutputGameObject == null)
{
partData.SetGameObject(HEU_GeneralUtility.CreateNewGameObject());
}
// The parent is either the asset root, OR if this is instanced and not visible, then the HDA data is the parent
// The parent transform is either the asset root (for a display node),
// or the HDA_Data gameobject (for instanced, not visible, intermediate, editable non-display nodes)
Transform partTransform = partData.OutputGameObject.transform;
if (partData.IsPartInstanced()
|| (_containerObjectNode.IsInstanced() && !_containerObjectNode.IsVisible())
|| partData.IsPartCurve()
|| (IsIntermediateOrEditable() && !Displayable))
{
partTransform.parent = parentAsset.OwnerGameObject.transform;
}
else
{
partTransform.parent = parentAsset.RootGameObject.transform;
}
HEU_GeneralUtility.CopyFlags(partTransform.parent.gameObject, partData.OutputGameObject, true);
// Reset to origin
partTransform.localPosition = Vector3.zero;
partTransform.localRotation = Quaternion.identity;
partTransform.localScale = Vector3.one;
// Destroy the children generated from ComposeNChildren
HEU_GeneralUtility.DestroyAutoGeneratedChildren(partData.OutputGameObject);
}
internal void GetPartsByOutputType(List<HEU_PartData> meshParts, List<HEU_PartData> volumeParts)
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
HEU_PartData part = _parts[i];
if (part.IsPartMesh() || part.IsPartCurve())
{
meshParts.Add(part);
}
else if (part.IsPartVolume())
{
volumeParts.Add(part);
}
}
}
/// <summary>
/// Generate the instances of instancer parts.
/// </summary>
internal void GeneratePartInstances(HEU_SessionBase session)
{
List<HEU_PartData> partsToDestroy = new List<HEU_PartData>();
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
if (_parts[i].IsPartInstancer() && !_parts[i].HaveInstancesBeenGenerated())
{
if (!_parts[i].GeneratePartInstances(session))
{
partsToDestroy.Add(_parts[i]);
}
}
}
int numPartsToDestroy = partsToDestroy.Count;
for (int i = 0; i < numPartsToDestroy; ++i)
{
HEU_GeoNode parentNode = partsToDestroy[i].ParentGeoNode;
if (parentNode != null)
{
parentNode.RemoveAndDestroyPart(partsToDestroy[i]);
}
else
{
HEU_PartData.DestroyPart(partsToDestroy[i]);
}
}
partsToDestroy.Clear();
}
internal void GenerateAttributesStore(HEU_SessionBase session)
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
_parts[i].GenerateAttributesStore(session);
}
}
private void ProcessGeoCurve(HEU_SessionBase session)
{
HEU_HoudiniAsset parentAsset = ParentAsset;
if (parentAsset == null)
{
return;
}
string curveName = GenerateGeoCurveName();
curveName = HEU_EditorUtility.GetUniqueNameForSibling(ParentAsset.RootGameObject.transform, curveName);
bool bNewCurve = (_geoCurve == null);
if (bNewCurve)
{
// New geo curve
_geoCurve = HEU_Curve.CreateSetupCurve(session, parentAsset, Editable, curveName, GeoID, 0, true);
}
else
{
_geoCurve.UploadParameterPreset(session, GeoID, parentAsset);
}
SetupGeoCurveGameObjectAndTransform(_geoCurve);
_geoCurve.SetCurveName(curveName);
_geoCurve.SyncFromParameters(session, parentAsset, bNewCurve);
if (bNewCurve)
{
_geoCurve.DownloadAsDefaultPresetData(session);
}
// If geo node has part, generate the mesh using position attribute.
// Note that without any parts we can't generate a mesh so we pass in an invalid part ID
// to at least set default values.
HAPI_PartId partID = _geoInfo.partCount > 0 ? 0 : HEU_Defines.HEU_INVALID_NODE_ID;
_geoCurve.UpdateCurve(session, partID);
_geoCurve.GenerateMesh(_geoCurve.TargetGameObject, session);
bool bIsVisible = IsVisible() && HEU_PluginSettings.Curves_ShowInSceneView;
}
private void SetupGeoCurveGameObjectAndTransform(HEU_Curve curve)
{
if (ParentAsset == null)
{
return;
}
if (curve.TargetGameObject == null)
{
curve.TargetGameObject = HEU_GeneralUtility.CreateNewGameObject();
}
// For geo curve, the parent is the HDA_Data
Transform curveTransform = curve.TargetGameObject.transform;
curveTransform.parent = ParentAsset.OwnerGameObject.transform;
HEU_GeneralUtility.CopyFlags(curveTransform.parent.gameObject, curve.TargetGameObject, true);
// Reset to origin
curveTransform.localPosition = Vector3.zero;
curveTransform.localRotation = Quaternion.identity;
curveTransform.localScale = Vector3.one;
}
/// <summary>
/// Clear object instances so that they can be re-created
/// </summary>
internal void ClearObjectInstances()
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
_parts[i]._objectInstancesGenerated = false;
}
}
internal void SetGeoInfo(HAPI_GeoInfo geoInfo)
{
_geoInfo = geoInfo;
// Also update input node ID in case of this node
// being recreated in new session with a different GeoID
if (_inputNode != null)
{
_inputNode.SetInputNodeID(GeoID);
}
}
/// <summary>
/// Returns the part's full name to set on the gamepboject
/// </summary>
/// <param name="partName"></param>
/// <returns></returns>
internal string GeneratePartFullName(string partName)
{
return _containerObjectNode.ObjectName + "_" + GeoName + "_" + partName;
}
internal string GenerateGeoCurveName()
{
// For a geo curve, just use the geo node name.
// The curve editor presumes this is unique for multiple curves in same asset.
return _geoName;
}
/// <summary>
/// Returns true if any of the geo data has changed and
/// therefore requires regeneration.
/// </summary>
/// <returns>True if changes occurred internal to geo data</returns>
internal bool HasGeoNodeChanged(HEU_SessionBase session)
{
// Note: _geoInfo.hasMaterialChanged has been deprecated so we're not checking that
if (!session.GetGeoInfo(GeoID, ref _geoInfo))
{
return false;
}
else if (_geoInfo.type == HAPI_GeoType.HAPI_GEOTYPE_INPUT)
{
return (_inputNode != null) ? _inputNode.RequiresCook : false;
}
else if (_geoInfo.isTemplated && !HEU_PluginSettings.CookTemplatedGeos && !_geoInfo.isEditable)
{
return false;
}
else if (!_geoInfo.hasGeoChanged)
{
return false;
}
// Commented out to allow non-display geo to be updated
//else if (!_geoInfo.isDisplayGeo && (_geoInfo.type != HAPI_GeoType.HAPI_GEOTYPE_CURVE && !HEU_PluginSettings.CookTemplatedGeos && _geoInfo.isTemplated))
//{
// return false;
//}
return true;
}
/// <summary>
/// Apply the given HAPI transform to all parts of this node.
/// </summary>
/// <param name="hapiTransform">HAPI transform to apply</param>
internal void ApplyHAPITransform(ref HAPI_Transform hapiTransform)
{
foreach (HEU_PartData part in _parts)
{
part.ApplyHAPITransform(ref hapiTransform);
}
}
/// <summary>
/// Get debug info for this geo
/// </summary>
internal void GetDebugInfo(StringBuilder sb)
{
int numParts = _parts != null ? _parts.Count : 0;
sb.AppendFormat("GeoID: {0}, Name: {1}, Type: {2}, Displayable: {3}, Editable: {4}, Parts: {5}, Parent: {6}\n", GeoID, GeoName, GeoType,
Displayable, Editable, numParts, ParentAsset);
if (_parts != null)
{
foreach (HEU_PartData part in _parts)
{
part.GetDebugInfo(sb);
}
}
}
/// <summary>
/// Returns true if this geonode is using the given material.
/// </summary>
/// <param name="materialData">Material data containing the material to check</param>
/// <returns>True if this geonode is using the given material</returns>
internal bool IsUsingMaterial(HEU_MaterialData materialData)
{
foreach (HEU_PartData part in _parts)
{
if (part.IsUsingMaterial(materialData))
{
return true;
}
}
return false;
}
internal void GetClonableParts(List<HEU_PartData> clonableParts)
{
foreach (HEU_PartData part in _parts)
{
part.GetClonableParts(clonableParts);
}
}
internal bool HasAttribInstancer()
{
foreach (HEU_PartData part in _parts)
{
if (part.IsAttribInstancer())
{
return true;
}
}
return false;
}
/// <summary>
/// Set attribute-based modifiers such as tag, layer, and scripts on
/// the part outputs.
/// </summary>
/// <param name="session"></param>
internal void SetAttributeModifiersOnPartOutputs(HEU_SessionBase session)
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
if (_parts[i].OutputGameObject != null)
{
HEU_GeneralUtility.AssignUnityTag(session, GeoID, _parts[i].PartID, _parts[i].OutputGameObject);
HEU_GeneralUtility.AssignUnityLayer(session, GeoID, _parts[i].PartID, _parts[i].OutputGameObject);
HEU_GeneralUtility.MakeStaticIfHasAttribute(session, GeoID, _parts[i].PartID, _parts[i].OutputGameObject);
}
}
}
/// <summary>
/// Calculate the visibility of this geo node and its parts, based on whether the parent is visible.
/// </summary>
/// <param name="bParentVisibility">True if parent is visible</param>
internal void CalculateVisiblity(bool bParentVisibility)
{
if (_geoCurve != null)
{
bool curveVisiblity = bParentVisibility && HEU_PluginSettings.Curves_ShowInSceneView;
_geoCurve.SetCurveGeometryVisibility(curveVisiblity);
}
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
_parts[i].CalculateVisibility(bParentVisibility, Displayable);
}
}
internal void CalculateColliderState()
{
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
_parts[i].CalculateColliderState();
}
}
internal void ProcessVolumeParts(HEU_SessionBase session, List<HEU_PartData> volumeParts, bool bRebuild)
{
if (ParentAsset == null)
{
return;
}
int numVolumeParts = volumeParts.Count;
if (numVolumeParts == 0)
{
DestroyVolumeCache();
}
else if (_volumeCaches == null)
{
_volumeCaches = new List<HEU_VolumeCache>();
}
// First update volume caches. Each volume cache represents a set of terrain layers grouped by tile index.
// Therefore each volume cache represents a potential Unity Terrain (containing layers)
_volumeCaches = HEU_VolumeCache.UpdateVolumeCachesFromParts(session, this, volumeParts, _volumeCaches);
// Heightfield scatter nodes come in as mesh-type parts with attribute instancing.
// So process them here to get all the tree/detail instance scatter information.
int numParts = _parts.Count;
for (int i = 0; i < numParts; ++i)
{
// Find the terrain tile (use primitive attr). Assume 0 tile if not set (i.e. not split into tiles)
int terrainTile = 0;
HEU_TerrainUtility.GetAttributeTile(session, GeoID, _parts[i].PartID, out terrainTile);
// Find the volumecache associated with this part using the terrain tile index
HEU_VolumeCache volumeCache = GetVolumeCacheByTileIndex(terrainTile);
if (volumeCache == null)
{
continue;
}
HEU_VolumeLayer volumeLayer = volumeCache.GetLayer(_parts[i].GetVolumeLayerName());
if (volumeLayer != null && volumeLayer._layerType == HFLayerType.DETAIL)
{
// Clear out outputs since it might have been created when the part was created.
_parts[i].DestroyAllData();
volumeCache.PopulateDetailPrototype(session, GeoID, _parts[i].PartID, volumeLayer);
}
else if (_parts[i].IsAttribInstancer())
{
HAPI_AttributeInfo treeInstAttrInfo = new HAPI_AttributeInfo();
if (HEU_GeneralUtility.GetAttributeInfo(session, GeoID, _parts[i].PartID, HEU_Defines.HEIGHTFIELD_TREEINSTANCE_PROTOTYPEINDEX,
ref treeInstAttrInfo))
{
if (treeInstAttrInfo.exists && treeInstAttrInfo.count > 0)
{
// Clear out outputs since it might have been created when the part was created.
_parts[i].DestroyAllData();
// Mark the instancers as having been created so that the object instancer step skips this.
_parts[i]._objectInstancesGenerated = true;
bool throwWarningIfNoTileAttribute = _volumeCaches.Count > 1;
// Now populate scatter trees based on attributes on this part
// Note: Might do redudant work for each volume and might need refactoring for performance.
foreach (HEU_VolumeCache cache in _volumeCaches)
{
cache.PopulateScatterTrees(session, GeoID, _parts[i].PartID, treeInstAttrInfo.count, throwWarningIfNoTileAttribute);
}
}
}
}
}
// Now generate the terrain for each volume cache
foreach (HEU_VolumeCache cache in _volumeCaches)
{
cache.GenerateTerrainWithAlphamaps(session, ParentAsset, bRebuild);
cache.IsDirty = false;
}
}
internal void DestroyVolumeCache()
{
if (_volumeCaches != null)
{
int numCaches = _volumeCaches.Count;
for (int i = 0; i < numCaches; ++i)
{
if (_volumeCaches[i] != null)
{
if (ParentAsset)
ParentAsset.RemoveVolumeCache(_volumeCaches[i]);
HEU_GeneralUtility.DestroyImmediate(_volumeCaches[i]);
_volumeCaches[i] = null;
}
}
_volumeCaches = null;
}
}
public override string ToString()
{
return (!string.IsNullOrEmpty(_geoName) ? ("GeoNode: " + _geoName) : base.ToString());
}
public bool IsEquivalentTo(HEU_GeoNode other)
{
bool bResult = true;
string header = "HEU_GeoNode";
if (other == null)
{
HEU_Logger.LogError(header + " Not equivalent");
return false;
}
HEU_TestHelpers.AssertTrueLogEquivalent(this._geoInfo.ToTestObject(), other._geoInfo.ToTestObject(), ref bResult, header, "_geoInfo");
//HEU_TestHelpers.AssertTrueLogEquivalent(this._geoName, other._geoName, ref bResult, header, "_geoName");
HEU_TestHelpers.AssertTrueLogEquivalent(this._parts, other._parts, ref bResult, header, "_part");
// SKip _containerObjectNode/parentAsset stuff
HEU_TestHelpers.AssertTrueLogEquivalent(this._geoCurve, other._geoCurve, ref bResult, header, "_geoCurve");
// Skip volumCache
HEU_TestHelpers.AssertTrueLogEquivalent(this._volumeCaches, other._volumeCaches, ref bResult, header, "_volumeCaches");
return bResult;
}
}
} // HoudiniEngineUnity | 0 | 0.921104 | 1 | 0.921104 | game-dev | MEDIA | 0.621835 | game-dev | 0.87704 | 1 | 0.87704 |
gemrb/gemrb | 18,691 | gemrb/GUIScripts/GUIOPT.py | # GemRB - Infinity Engine Emulator
# Copyright (C) 2012 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# GUIOPT.py - scripts to control options windows mostly from the GUIOPT winpack:
# 0 - Main options window (peacock tail)
# 1 - Video options window
# 2 - msg win with 1 button
# 3 - msg win with 2 buttons
# 4 - msg win with 3 buttons
# 5 - Audio options window
# 6 - Gameplay options window
# 8 - Feedback options window
# 9 - Autopause options window
###################################################
import Container
import GameCheck
import GemRB
import GUICommonWindows
import GUISAVE
import GUIOPTControls
import GUIOPTExtra
from GUIDefines import *
from ie_sounds import GEM_SND_VOL_MUSIC, GEM_SND_VOL_AMBIENTS
###################################################
QuitMsgWindow = None
###################################################
def InitOptionsWindow (Window):
"""Open main options window"""
Container.CloseContainerWindow ()
# Return to Game
Button = ReturnButton = Window.GetControl (11)
Button.SetText (10308)
Button.OnPress (Window.Close)
Button.MakeEscape()
# Quit Game
Button = Window.GetControl (10)
Button.SetText (13731)
Button.OnPress (OpenQuitMsgWindow)
# Load Game
Button = Window.GetControl (5)
Button.SetText (13729)
Button.OnPress (LoadGamePress)
# Save Game
Button = Window.GetControl (6)
Button.SetText (13730)
Button.OnPress (OpenSaveMsgWindow)
# Video Options
Button = Window.GetControl (7)
Button.SetText (17162)
Button.OnPress (OpenVideoOptionsWindow)
# Audio Options
Button = Window.GetControl (8)
Button.SetText (17164)
Button.OnPress (OpenAudioOptionsWindow)
# Gameplay Options
Button = Window.GetControl (9)
Button.SetText (17165)
Button.OnPress (OpenGameplayOptionsWindow)
# game version, e.g. v1.1.0000
VersionLabel = Window.GetControl (0x1000000b)
VersionLabel.SetText (GemRB.Version)
if GameCheck.IsIWD2():
# Keyboard shortcuts
KeyboardButton = Window.GetControl (13)
KeyboardButton.SetText (33468)
KeyboardButton.OnPress (OpenHotkeyOptionsWindow)
# Movies
MoviesButton = Window.GetControl (14)
MoviesButton.SetText (15415)
MoviesButton.OnPress (OpenMovieWindow)
# GemRB extras
frame = ReturnButton.GetFrame ()
if GameCheck.IsIWD2 ():
frame = MoviesButton.GetFrame ()
GUIOPTExtra.AddGemRBOptionsButton (Window, frame, 0, 110, "GBTNLRG2")
elif GameCheck.IsBG2 ():
GUIOPTExtra.AddGemRBOptionsButton (Window, frame, 0, -40, "GUBOTC", 1)
elif GameCheck.IsBG2EE ():
GUIOPTExtra.AddGemRBOptionsButton (Window, frame, 0, -50, "GUIOSTCL")
elif GameCheck.IsBG1 ():
GUIOPTExtra.AddGemRBOptionsButton (Window, frame, 0, 55, "BIGBUTT")
elif GameCheck.IsIWD1 ():
GUIOPTExtra.AddGemRBOptionsButton (Window, frame, 0, 50, "STONEOPT", 1)
return
ToggleOptionsWindow = GUICommonWindows.CreateTopWinLoader(2, "GUIOPT", GUICommonWindows.ToggleWindow, InitOptionsWindow, None, True)
OpenOptionsWindow = GUICommonWindows.CreateTopWinLoader(2, "GUIOPT", GUICommonWindows.OpenWindowOnce, InitOptionsWindow, None, True)
def TrySavingConfiguration():
if not GemRB.SaveConfig():
print("ARGH, could not write config to disk!!")
###################################################
# work around radiobutton preselection issues
# after the generation of the controls we have to re-adjust the visible and
# internal state, i.e. adjust button state and dictionary entry
def PreselectRadioGroup (variable, value, buttonIds, window):
for i in buttonIds:
Button = window.GetControl (i)
if (Button.Value == value):
Button.SetState (IE_GUI_BUTTON_SELECTED)
else:
Button.SetState (IE_GUI_BUTTON_ENABLED)
GemRB.SetVar(variable, value)
###################################################
def CloseVideoOptionsWindow ():
GemRB.GetView("SUB_WIN", 0).Close()
TrySavingConfiguration()
def OpenVideoOptionsWindow ():
"""Open video options window"""
Window = GemRB.LoadWindow (6, "GUIOPT")
Window.AddAlias("SUB_WIN", 0)
Window.SetFlags (WF_BORDERLESS, OP_OR)
GUIOPTControls.OptHelpText (33, 18038)
GUIOPTControls.OptDone (CloseVideoOptionsWindow, 21)
GUIOPTControls.OptCancel (CloseVideoOptionsWindow, 32)
if not GameCheck.IsBG2EE ():
GUIOPTControls.OptSlider (17203, 3, 35, 17129, 'Brightness Correction', DisplayHelpBrightness, 4)
GUIOPTControls.OptSlider (17204, 22, 36, 17128, 'Gamma Correction', DisplayHelpContrast)
# Radiobuttons need special care...
Variable = 'BitsPerPixel'
Value = GemRB.GetVar(Variable)
ButtonIds = [5, 6, 7]
if not GameCheck.IsBG2EE ():
GUIOPTControls.OptRadio (DisplayHelpBPP, ButtonIds[0], 37, Variable, 16, None, 17205, 18038)
GUIOPTControls.OptRadio (DisplayHelpBPP, ButtonIds[1], 37, Variable, 24, None, 17205, 18038)
GUIOPTControls.OptRadio (DisplayHelpBPP, ButtonIds[2], 37, Variable, 32, None, 17205, 18038)
PreselectRadioGroup (Variable, Value, ButtonIds, Window)
GUIOPTControls.OptCheckbox (18000, 9, 15 if GameCheck.IsBG2EE () else 38, 17131, 'Full Screen', DisplayHelpFullScreen)
if not GameCheck.IsBG2EE ():
GUIOPTControls.OptCheckbox (20620, 51, 50, 20617, 'Translucent Shadows')
GUIOPTControls.OptCheckbox (15135, 40, 44, 17134, 'SoftMirrorBlt')
GUIOPTControls.OptCheckbox (18006, 41, 46, 17136, 'SoftSrcKeyBlt') # software standard blit
GUIOPTControls.OptCheckbox (18007, 42, 48, 17135, 'SoftBltFast') # software transparent blit
# maybe not present in original iwd, but definitely in how
if GameCheck.IsIWD1 () or GameCheck.IsIWD2 ():
GUIOPTControls.OptCheckbox (15141, 56, 52, 14447, 'TranslucentBlt')
GUIOPTControls.OptCheckbox (18004, 57, 54, 14578, 'StaticAnims')
Window.ShowModal (MODAL_SHADOW_GRAY)
return
def DisplayHelpFullScreen ():
GemRB.GetView ("OPTHELP").SetText (18000)
GemRB.SetFullScreen (GemRB.GetVar("Full Screen"))
def DisplayHelpBPP ():
GemRB.GetView ("OPTHELP").SetText (17205)
def DisplayHelpBrightness ():
GemRB.GetView ("OPTHELP").SetText (17203)
SetGfxCorrection ()
def DisplayHelpContrast ():
GemRB.GetView ("OPTHELP").SetText (17204)
SetGfxCorrection ()
# different games have different slider ranges, but the engine wants:
# gamma: 0-5
# brightness: 0-40
def SetGfxCorrection ():
Brightness = GemRB.GetVar("Brightness Correction")
Gamma = GemRB.GetVar("Gamma Correction")
if GameCheck.IsHOW() or GameCheck.IsIWD2(): # 10/11 ticks
Gamma //= 2
GemRB.SetGamma (Brightness, Gamma)
###################################################
def CloseAudioOptionsWindow ():
GemRB.GetView("SUB_WIN", 0).Close()
TrySavingConfiguration()
def OpenAudioOptionsWindow ():
"""Open audio options window"""
Window = GemRB.LoadWindow (7, "GUIOPT")
Window.AddAlias("SUB_WIN", 0)
Window.SetFlags (WF_BORDERLESS, OP_OR)
GUIOPTControls.OptHelpText (14, 18040)
GUIOPTControls.OptDone (CloseAudioOptionsWindow, 24)
GUIOPTControls.OptCancel (CloseAudioOptionsWindow, 25)
GUIOPTControls.OptButton (OpenCharacterSoundsWindow, 13, 17778)
GUIOPTControls.OptSlider (18008, 1, 16, 16514, 'Volume Ambients', DisplayHelpAmbientVolume, 10)
GUIOPTControls.OptSlider (18009, 2, 17, 16515, 'Volume SFX', None, 10)
GUIOPTControls.OptSlider (18010, 3, 18, 16512, 'Volume Voices', None, 10)
GUIOPTControls.OptSlider (18011, 4, 19, 16511, 'Volume Music', DisplayHelpMusicVolume, 10)
GUIOPTControls.OptSlider (18012, 22, 20, 16546, 'Volume Movie', None, 10)
if not GameCheck.IsBG2EE ():
GUIOPTControls.OptCheckbox (18022, 26, 28, 20689, 'Environmental Audio')
Window.ShowModal (MODAL_SHADOW_GRAY)
return
def DisplayHelpAmbientVolume ():
GemRB.GetView ("OPTHELP").SetText (18008)
GemRB.UpdateVolume (GEM_SND_VOL_AMBIENTS)
def DisplayHelpMusicVolume ():
GemRB.GetView ("OPTHELP").SetText (18011)
GemRB.UpdateVolume (GEM_SND_VOL_MUSIC)
###################################################
def OpenCharacterSoundsWindow ():
"""Open character sounds window"""
Window = GemRB.LoadWindow (12, "GUIOPT")
Window.AddAlias("SUB_WIN", 1)
Window.SetFlags (WF_BORDERLESS, OP_OR)
GUIOPTControls.OptHelpText (16, 18041)
GUIOPTControls.OptDone (Window.Close, 24)
GUIOPTControls.OptCancel (Window.Close, 25)
GUIOPTControls.OptCheckbox (18015, 5, 20, 17138, 'Subtitles')
GUIOPTControls.OptCheckbox (18013, 6, 18, 17139, 'Attack Sounds')
GUIOPTControls.OptCheckbox (18014, 7, 19, 17140, 'Footsteps')
# Radiobuttons need special care...
Variable = 'Command Sounds Frequency'
Value = GemRB.GetVar(Variable)
ButtonIds = [8, 9, 10]
GUIOPTControls.OptRadio (DisplayHelpCommandSounds, ButtonIds[0], 21, Variable, 3)
GUIOPTControls.OptRadio (DisplayHelpCommandSounds, ButtonIds[1], 21, Variable, 2)
GUIOPTControls.OptRadio (DisplayHelpCommandSounds, ButtonIds[2], 21, Variable, 1)
PreselectRadioGroup (Variable, Value, ButtonIds, Window)
Variable = 'Selection Sounds Frequency'
Value = GemRB.GetVar(Variable)
ButtonIds = [58, 59, 60]
GUIOPTControls.OptRadio (DisplayHelpSelectionSounds, ButtonIds[0], 57, Variable, 3)
GUIOPTControls.OptRadio (DisplayHelpSelectionSounds, ButtonIds[1], 57, Variable, 2)
GUIOPTControls.OptRadio (DisplayHelpSelectionSounds, ButtonIds[2], 57, Variable, 1)
PreselectRadioGroup (Variable, Value, ButtonIds, Window)
Window.ShowModal (MODAL_SHADOW_GRAY)
def DisplayHelpCommandSounds ():
GemRB.GetView ("OPTHELP").SetText (18016)
def DisplayHelpSelectionSounds ():
GemRB.GetView ("OPTHELP").SetText (11352)
###################################################
def CloseGameplayOptionsWindow ():
# FIXME: don't need to do anything, since we save stuff immediately
# ergo canceling does not work
GemRB.GetView("SUB_WIN", 0).Close()
TrySavingConfiguration()
def OpenGameplayOptionsWindow ():
"""Open gameplay options window"""
#gameplayoptions
Window = GemRB.LoadWindow (8, "GUIOPT")
Window.AddAlias("SUB_WIN", 0)
Window.SetFlags (WF_BORDERLESS, OP_OR)
GUIOPTControls.OptHelpText (40, 18042)
GUIOPTControls.OptDone (CloseGameplayOptionsWindow, 7)
GUIOPTControls.OptCancel (CloseGameplayOptionsWindow, 20)
GUIOPTControls.OptSlider (18017, 1, 21, 17143, 'Tooltips', DisplayHelpTooltipDelay, 10)
GUIOPTControls.OptSlider (18018, 2, 22, 17144, 'Mouse Scroll Speed', DisplayHelpMouseScrollingSpeed, 5)
GUIOPTControls.OptSlider (18019, 3, 23, 17145, 'Keyboard Scroll Speed', None, 5)
GUIOPTControls.OptSlider (18020, 12, 24, 13911, 'Difficulty Level', None)
if GemRB.GetVar ("Nightmare Mode") == 1:
# lock the slider
Slider = Window.GetControl (12)
Slider.SetDisabled (True)
GUIOPTControls.OptCheckbox (18021, 14, 25, 13697, 'Always Dither')
GUIOPTControls.OptCheckbox (18023, 19, 27, 17182, 'Gore')
GUIOPTControls.OptCheckbox (11797, 42, 44, 11795, 'Infravision')
GUIOPTControls.OptCheckbox (20619, 47, 46, 20618, 'Weather')
if GameCheck.IsBG2OrEE ():
GUIOPTControls.OptCheckbox (2242, 50, 48, 2241, 'Heal Party on Rest')
elif GameCheck.IsIWD2() or GameCheck.IsIWD1():
GUIOPTControls.OptCheckbox (15136, 50, 49, 17378, 'Maximum HP')
GUIOPTControls.OptButton (OpenFeedbackOptionsWindow, 5, 17163)
GUIOPTControls.OptButton (OpenAutopauseOptionsWindow, 6, 17166)
if GameCheck.IsBG2OrEE ():
GUIOPTControls.OptButton (OpenHotkeyOptionsWindow, 51, 816)
Window.ShowModal (MODAL_SHADOW_GRAY)
return
def DisplayHelpTooltipDelay ():
GemRB.GetView ("OPTHELP").SetText (18017)
GemRB.UpdateTooltipDelay()
def DisplayHelpMouseScrollingSpeed ():
GemRB.GetView ("OPTHELP").SetText (18018)
GemRB.SetMouseScrollSpeed (GemRB.GetVar ("Mouse Scroll Speed") )
###################################################
def OpenFeedbackOptionsWindow ():
"""Open feedback options window"""
Window = GemRB.LoadWindow (9, "GUIOPT")
Window.AddAlias("SUB_WIN", 1)
Window.SetFlags (WF_BORDERLESS, OP_OR)
GUIOPTControls.OptHelpText (28, 18043)
GemRB.SetVar ("Circle Feedback", GemRB.GetVar ("GUI Feedback Level") - 1)
GUIOPTControls.OptDone (Window.Close, 26)
GUIOPTControls.OptCancel (Window.Close, 27)
GUIOPTControls.OptSlider (18024, 8, 30, 13688, 'Circle Feedback', DisplayHelpMarkerFeedback)
GUIOPTControls.OptSlider (18025, 9, 31, 17769, 'Locator Feedback Level')
# to hit rolls (extra feedback), combat info, actions, state changes, selection text, miscellaneus
GUIOPTControls.OptCheckbox (18026, 10, 32, 17149, 'Effect Text Level', None, 1)
GUIOPTControls.OptCheckbox (18027, 11, 33, 17150, 'Effect Text Level', None, 2)
GUIOPTControls.OptCheckbox (18028, 12, 34, 17151, 'Effect Text Level', None, 4)
GUIOPTControls.OptCheckbox (18029, 13, 35, 17152, 'Effect Text Level', None, 8)
GUIOPTControls.OptCheckbox (18030, 14, 36, 17181, 'Effect Text Level', None, 16)
GUIOPTControls.OptCheckbox (18031, 15, 37, 17153, 'Effect Text Level', None, 32)
# pst adds bit 64, but it still has its own GUIOPT; let's just ensure it is set
GemRB.SetVar ('Effect Text Level', GemRB.GetVar ('Effect Text Level') | 64)
Window.ShowModal (MODAL_SHADOW_GRAY)
return
def DisplayHelpMarkerFeedback ():
GemRB.GetView ("OPTHELP").SetText (18024)
GemRB.SetVar ("GUI Feedback Level", GemRB.GetVar ("Circle Feedback") + 1)
###################################################
def OpenAutopauseOptionsWindow ():
"""Open autopause options window"""
Window = GemRB.LoadWindow (10, "GUIOPT")
Window.AddAlias("SUB_WIN", 1)
Window.SetFlags (WF_BORDERLESS, OP_OR)
GUIOPTControls.OptHelpText (15, 18044)
GUIOPTControls.OptDone (Window.Close, 11)
GUIOPTControls.OptCancel (Window.Close, 14)
# checkboxes OR the values if they associate to the same variable
GUIOPTControls.OptCheckbox (18032, 1, 17, 17155, 'Auto Pause State', None, 4) # hit
GUIOPTControls.OptCheckbox (18033, 2, 18, 17156, 'Auto Pause State', None, 8) # wounded
GUIOPTControls.OptCheckbox (18034, 3, 19, 17157, 'Auto Pause State', None, 16) # dead
GUIOPTControls.OptCheckbox (18035, 4, 20, 17158, 'Auto Pause State', None, 2) # attacked
GUIOPTControls.OptCheckbox (18036, 5, 21, 17159, 'Auto Pause State', None, 1) # weapon unusable
GUIOPTControls.OptCheckbox (18037, 13, 22, 17160, 'Auto Pause State', None, 32) # target gone
GUIOPTControls.OptCheckbox (10640, 25, 24, 10639, 'Auto Pause State', None, 64) # end of round
if GameCheck.IsIWD2() or GameCheck.IsIWD1():
GUIOPTControls.OptCheckbox (23514, 30, 31, 23516, 'Auto Pause State', None, 128) # enemy sighted
GUIOPTControls.OptCheckbox (18560, 26, 28, 16519, 'Auto Pause State', None, 256) # trap found
GUIOPTControls.OptCheckbox (26311, 36, 37, 26310, 'Auto Pause State', None, 512) # spell cast
GUIOPTControls.OptCheckbox (24888, 33, 34, 10574, 'Auto Pause Center', None, 1)
elif Window.GetControl (26):
GUIOPTControls.OptCheckbox (23514, 26, 27, 23516, 'Auto Pause State', None, 128) # enemy sighted
if GameCheck.IsBG2OrEE ():
GUIOPTControls.OptCheckbox (31872, 31, 33, 31875, 'Auto Pause State', None, 512) # spell cast
GUIOPTControls.OptCheckbox (58171, 34, 30, 57354, 'Auto Pause State', None, 256) # trap found
GUIOPTControls.OptCheckbox (10571, 37, 36, 10574, 'Auto Pause Center', None, 1)
Window.ShowModal (MODAL_SHADOW_GRAY)
return
###################################################
def MoviePlayPress():
movie = MoviesTable.GetRowName (GemRB.GetVar ("MovieIndex"))
GemRB.PlayMovie (movie, 1)
# for iwd2 only, the rest use GUIMOVIE
# TODO: investigate a merger, so it can get removed from GUIOPT
def OpenMovieWindow ():
global TextAreaControl, MoviesTable
Window = GemRB.LoadWindow(2, "GUIMOVIE")
Window.AddAlias("SUB_WIN", 0)
Window.SetFlags (WF_BORDERLESS, OP_OR)
TextAreaControl = Window.GetControl(0)
PlayButton = Window.GetControl(2)
CreditsButton = Window.GetControl(3)
DoneButton = Window.GetControl(4)
MoviesTable = GemRB.LoadTable("MOVIDESC")
opts = [MoviesTable.GetValue (i, 0) for i in range(MoviesTable.GetRowCount ()) if GemRB.GetVar(MoviesTable.GetRowName (i)) == 1]
TextAreaControl.SetOptions (opts, "MovieIndex", 0)
PlayButton.SetText(17318)
CreditsButton.SetText(15591)
DoneButton.SetText(11973)
PlayButton.OnPress (MoviePlayPress)
CreditsButton.OnPress (lambda: GemRB.PlayMovie("CREDITS"))
DoneButton.OnPress (Window.Close)
Window.ShowModal (MODAL_SHADOW_GRAY)
return
###################################################
def OpenSaveMsgWindow ():
GemRB.SetVar("QuitAfterSave",0)
GUISAVE.OpenSaveWindow ()
#save the game without quitting
return
###################################################
def LoadGamePress ():
GemRB.SetNextScript ("GUILOAD")
return
#save game AND quit
def SaveGamePress ():
CloseQuitMsgWindow()
#we need to set a state: quit after save
GemRB.SetVar("QuitAfterSave",1)
GUISAVE.OpenSaveWindow ()
return
def QuitGamePress ():
if GemRB.GetVar("AskAndExit") == 1:
GemRB.Quit()
return
CloseQuitMsgWindow()
GUICommonWindows.CloseTopWindow ()
GemRB.QuitGame ()
GemRB.SetNextScript ("Start")
return
###################################################
def OpenQuitMsgWindow ():
global QuitMsgWindow
if QuitMsgWindow:
return
QuitMsgWindow = Window = GemRB.LoadWindow (5, "GUIOPT")
Window.SetFlags (WF_BORDERLESS, OP_OR)
# Save
Button = Window.GetControl (0)
Button.SetText (15589)
Button.OnPress (SaveGamePress)
if GemRB.GetView("GC") is not None:
Button.SetState (IE_GUI_BUTTON_ENABLED)
else:
Button.SetState (IE_GUI_BUTTON_DISABLED)
# Quit Game
Button = Window.GetControl (1)
Button.SetText (15417)
Button.OnPress (QuitGamePress)
Button.MakeDefault()
# Cancel
Button = Window.GetControl (2)
Button.SetText (GUIOPTControls.STR_OPT_CANCEL)
Button.OnPress (CloseQuitMsgWindow)
Button.MakeEscape()
# Do you wish to save the game ....
Text = Window.GetControl (3)
Text.SetText (16456)
Window.ShowModal (MODAL_SHADOW_GRAY)
return
def CloseQuitMsgWindow ():
global QuitMsgWindow
if QuitMsgWindow:
QuitMsgWindow.Close ()
QuitMsgWindow = None
GemRB.SetVar("AskAndExit", 0)
return
###################################################
def OpenHotkeyOptionsWindow ():
print("TODO: implement OpenHotkeyOptionsWindow!")
# check if pst's guiopt's OpenKeyboardMappingsWindow is reusable
return
def CloseHotkeyOptionsWindow ():
return
###################################################
# End of file GUIOPT.py
| 0 | 0.666714 | 1 | 0.666714 | game-dev | MEDIA | 0.783287 | game-dev,desktop-app | 0.735891 | 1 | 0.735891 |
FriskTheFallenHuman/Prey2006 | 8,563 | neo/game/PlayerIcon.cpp | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#include "Game_local.h"
#include "PlayerIcon.h"
static const char * iconKeys[ ICON_NONE ] = {
"mtr_icon_lag",
"mtr_icon_chat",
"mtr_icon_sameteam" //HUMANHEAD rww
};
/*
===============
idPlayerIcon::idPlayerIcon
===============
*/
idPlayerIcon::idPlayerIcon() {
iconHandle = -1;
iconType = ICON_NONE;
}
/*
===============
idPlayerIcon::~idPlayerIcon
===============
*/
idPlayerIcon::~idPlayerIcon() {
FreeIcon();
}
/*
===============
idPlayerIcon::Draw
===============
*/
void idPlayerIcon::Draw( idActor *player, jointHandle_t joint ) { //HUMANHEAD rww - general actor support
idVec3 origin;
idMat3 axis;
float zOff = 16.0f; //HUMANHEAD rww
if (player->InVehicle()) { //HUMANHEAD rww
zOff = 64.0f;
}
if ( joint == INVALID_JOINT ) {
//HUMANHEAD rww - invalid joint now valid for prox ent
//FreeIcon();
//return;
axis = player->GetAxis();
origin = player->GetOrigin();
zOff += 70.0f;
}
else {
player->GetJointWorldTransform( joint, gameLocal.time, origin, axis );
}
//origin.z += 16.0f;
origin += player->GetAxis()[2]*zOff; //HUMANEAD rww
Draw( player, origin );
}
/*
===============
idPlayerIcon::Draw
===============
*/
void idPlayerIcon::Draw( idActor *player, const idVec3 &origin ) { //HUMANHEAD rww - general actor support
idPlayer *localPlayer = gameLocal.GetLocalPlayer();
if ( !localPlayer || !localPlayer->GetRenderView() ) {
FreeIcon();
return;
}
idMat3 axis = localPlayer->GetRenderView()->viewaxis;
//HUMANHEAD rww - work for general actors
hhPlayer *hhPl = NULL;
bool isLagged = false;
bool isChatting = false;
if (player->IsType(hhPlayer::Type)) {
hhPl = static_cast<hhPlayer *>(player);
}
//we could possibly show these icons for the prox, but i can see it causing issues when the player is out of the
//snapshot and the prox is not, and i don't want to sync those states onto the prox ent as well.
/*
else if (player->IsType(hhSpiritProxy::Type)) {
hhSpiritProxy *prox = static_cast<hhSpiritProxy *>(player);
hhPl = prox->GetPlayer();
}
*/
if (hhPl) {
isLagged = hhPl->isLagged;
isChatting = hhPl->isChatting;
}
//HUMANHEAD END
if ( isLagged ) { //HUMANHEAD rww
// create the icon if necessary, or update if already created
if ( !CreateIcon( player, ICON_LAG, origin, axis ) ) {
UpdateIcon( player, origin, axis );
}
} else if ( isChatting ) { //HUMANHEAD rww
if ( !CreateIcon( player, ICON_CHAT, origin, axis ) ) {
UpdateIcon( player, origin, axis );
}
} else {
FreeIcon();
}
}
/*
===============
idPlayerIcon::FreeIcon
===============
*/
void idPlayerIcon::FreeIcon( void ) {
if ( iconHandle != - 1 ) {
gameRenderWorld->FreeEntityDef( iconHandle );
iconHandle = -1;
}
iconType = ICON_NONE;
}
/*
===============
idPlayerIcon::CreateIcon
===============
*/
bool idPlayerIcon::CreateIcon( idActor *player, playerIconType_t type, const idVec3 &origin, const idMat3 &axis ) { //HUMANHEAD rww - general actor support
assert( type != ICON_NONE );
//HUMANHEAD rww
hhPlayer *hhPl = NULL;
if (player->IsType(hhPlayer::Type)) {
hhPl = static_cast<hhPlayer *>(player);
}
else if (player->IsType(hhSpiritProxy::Type)) {
hhSpiritProxy *prox = static_cast<hhSpiritProxy *>(player);
hhPl = prox->GetPlayer();
}
if (!hhPl) {
return false;
}
//HUMANHEAD END
const char *mtr = hhPl->spawnArgs.GetString( iconKeys[ type ], "_default" );
return CreateIcon( player, type, mtr, origin, axis );
}
/*
===============
idPlayerIcon::CreateIcon
===============
*/
bool idPlayerIcon::CreateIcon( idActor *player, playerIconType_t type, const char *mtr, const idVec3 &origin, const idMat3 &axis ) { //HUMANHEAD rww - general actor support
assert( type != ICON_NONE );
if ( type == iconType ) {
return false;
}
FreeIcon();
memset( &renderEnt, 0, sizeof( renderEnt ) );
renderEnt.origin = origin;
renderEnt.axis = axis;
renderEnt.shaderParms[ SHADERPARM_RED ] = 1.0f;
renderEnt.shaderParms[ SHADERPARM_GREEN ] = 1.0f;
renderEnt.shaderParms[ SHADERPARM_BLUE ] = 1.0f;
renderEnt.shaderParms[ SHADERPARM_ALPHA ] = 1.0f;
renderEnt.shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 16.0f;
renderEnt.shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 16.0f;
renderEnt.hModel = renderModelManager->FindModel( "_sprite" );
renderEnt.callback = NULL;
renderEnt.numJoints = 0;
renderEnt.joints = NULL;
renderEnt.customSkin = 0;
renderEnt.noShadow = true;
renderEnt.noSelfShadow = true;
renderEnt.customShader = declManager->FindMaterial( mtr );
renderEnt.referenceShader = 0;
renderEnt.bounds = renderEnt.hModel->Bounds( &renderEnt );
iconHandle = gameRenderWorld->AddEntityDef( &renderEnt );
iconType = type;
return true;
}
/*
===============
idPlayerIcon::UpdateIcon
===============
*/
void idPlayerIcon::UpdateIcon( idActor *player, const idVec3 &origin, const idMat3 &axis ) { //HUMANHEAD rww - general actor support
assert( iconHandle >= 0 );
renderEnt.origin = origin;
renderEnt.axis = axis;
gameRenderWorld->UpdateEntityDef( iconHandle, &renderEnt );
}
//HUMANHEAD rww
/*
===============
hhPlayerTeamIcon::Draw
for some reason i have to override this too or the compiler directs joint calls
to the idVec3 version and uses the int as a mask. which is dumb.
===============
*/
void hhPlayerTeamIcon::Draw( idActor *player, jointHandle_t joint ) {
idVec3 origin;
idMat3 axis;
float zOff = 32.0f;
if (player->InVehicle()) {
zOff = 80.0f;
}
if ( joint == INVALID_JOINT ) {
//HUMANHEAD rww - invalid joint now valid for prox ent
//FreeIcon();
//return;
axis = player->GetAxis();
origin = player->GetOrigin();
zOff += 70.0f;
}
else {
player->GetJointWorldTransform( joint, gameLocal.time, origin, axis );
}
origin += player->GetAxis()[2]*zOff;
Draw( player, origin );
}
/*
===============
hhPlayerTeamIcon::Draw
===============
*/
void hhPlayerTeamIcon::Draw( idActor *player, const idVec3 &origin ) {
idPlayer *localPlayer = gameLocal.GetLocalPlayer();
if ( !localPlayer || !localPlayer->GetRenderView() || localPlayer->spectating ) { //also don't draw team icons for spectators
FreeIcon();
return;
}
hhPlayer *hhPl = NULL;
int plTeam = 0;
if (player->IsType(hhPlayer::Type)) {
hhPl = static_cast<hhPlayer *>(player);
}
else if (player->IsType(hhSpiritProxy::Type)) {
hhSpiritProxy *prox = static_cast<hhSpiritProxy *>(player);
hhPl = prox->GetPlayer();
}
if (hhPl) {
plTeam = hhPl->team;
}
if ( gameLocal.gameType == GAME_TDM && plTeam == localPlayer->team ) {
idMat3 axis = localPlayer->GetRenderView()->viewaxis;
// create the icon if necessary, or update if already created
CreateIcon( player, ICON_SAMETEAM, origin, axis );
if (player->InVehicle()) {
renderEnt.shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 48.0f; //32
renderEnt.shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 48.0f; //32
}
else {
renderEnt.shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 32.0f; //16
renderEnt.shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 32.0f; //16
}
UpdateIcon( player, origin, axis );
}
else {
FreeIcon();
}
}
//HUMANHEAD END
| 0 | 0.926038 | 1 | 0.926038 | game-dev | MEDIA | 0.972697 | game-dev | 0.929544 | 1 | 0.929544 |
kripken/ammo.js | 13,873 | bullet/src/BulletDynamics/ConstraintSolver/btTypedConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2010 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_TYPED_CONSTRAINT_H
#define BT_TYPED_CONSTRAINT_H
#include "LinearMath/btScalar.h"
#include "btSolverConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#ifdef BT_USE_DOUBLE_PRECISION
#define btTypedConstraintData2 btTypedConstraintDoubleData
#define btTypedConstraintDataName "btTypedConstraintDoubleData"
#else
#define btTypedConstraintData2 btTypedConstraintFloatData
#define btTypedConstraintDataName "btTypedConstraintFloatData"
#endif //BT_USE_DOUBLE_PRECISION
class btSerializer;
//Don't change any of the existing enum values, so add enum types at the end for serialization compatibility
enum btTypedConstraintType
{
POINT2POINT_CONSTRAINT_TYPE=3,
HINGE_CONSTRAINT_TYPE,
CONETWIST_CONSTRAINT_TYPE,
D6_CONSTRAINT_TYPE,
SLIDER_CONSTRAINT_TYPE,
CONTACT_CONSTRAINT_TYPE,
D6_SPRING_CONSTRAINT_TYPE,
GEAR_CONSTRAINT_TYPE,
FIXED_CONSTRAINT_TYPE,
MAX_CONSTRAINT_TYPE
};
enum btConstraintParams
{
BT_CONSTRAINT_ERP=1,
BT_CONSTRAINT_STOP_ERP,
BT_CONSTRAINT_CFM,
BT_CONSTRAINT_STOP_CFM
};
#if 1
#define btAssertConstrParams(_par) btAssert(_par)
#else
#define btAssertConstrParams(_par)
#endif
ATTRIBUTE_ALIGNED16(struct) btJointFeedback
{
btVector3 m_appliedForceBodyA;
btVector3 m_appliedTorqueBodyA;
btVector3 m_appliedForceBodyB;
btVector3 m_appliedTorqueBodyB;
};
///TypedConstraint is the baseclass for Bullet constraints and vehicles
ATTRIBUTE_ALIGNED16(class) btTypedConstraint : public btTypedObject
{
int m_userConstraintType;
union
{
int m_userConstraintId;
void* m_userConstraintPtr;
};
btScalar m_breakingImpulseThreshold;
bool m_isEnabled;
bool m_needsFeedback;
int m_overrideNumSolverIterations;
btTypedConstraint& operator=(btTypedConstraint& other)
{
btAssert(0);
(void) other;
return *this;
}
protected:
btRigidBody& m_rbA;
btRigidBody& m_rbB;
btScalar m_appliedImpulse;
btScalar m_dbgDrawSize;
btJointFeedback* m_jointFeedback;
///internal method used by the constraint solver, don't use them directly
btScalar getMotorFactor(btScalar pos, btScalar lowLim, btScalar uppLim, btScalar vel, btScalar timeFact);
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
virtual ~btTypedConstraint() {};
btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA);
btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA,btRigidBody& rbB);
struct btConstraintInfo1 {
int m_numConstraintRows,nub;
};
static btRigidBody& getFixedBody();
struct btConstraintInfo2 {
// integrator parameters: frames per second (1/stepsize), default error
// reduction parameter (0..1).
btScalar fps,erp;
// for the first and second body, pointers to two (linear and angular)
// n*3 jacobian sub matrices, stored by rows. these matrices will have
// been initialized to 0 on entry. if the second body is zero then the
// J2xx pointers may be 0.
btScalar *m_J1linearAxis,*m_J1angularAxis,*m_J2linearAxis,*m_J2angularAxis;
// elements to jump from one row to the next in J's
int rowskip;
// right hand sides of the equation J*v = c + cfm * lambda. cfm is the
// "constraint force mixing" vector. c is set to zero on entry, cfm is
// set to a constant value (typically very small or zero) value on entry.
btScalar *m_constraintError,*cfm;
// lo and hi limits for variables (set to -/+ infinity on entry).
btScalar *m_lowerLimit,*m_upperLimit;
// findex vector for variables. see the LCP solver interface for a
// description of what this does. this is set to -1 on entry.
// note that the returned indexes are relative to the first index of
// the constraint.
int *findex;
// number of solver iterations
int m_numIterations;
//damping of the velocity
btScalar m_damping;
};
int getOverrideNumSolverIterations() const
{
return m_overrideNumSolverIterations;
}
///override the number of constraint solver iterations used to solve this constraint
///-1 will use the default number of iterations, as specified in SolverInfo.m_numIterations
void setOverrideNumSolverIterations(int overideNumIterations)
{
m_overrideNumSolverIterations = overideNumIterations;
}
///internal method used by the constraint solver, don't use them directly
virtual void buildJacobian() {};
///internal method used by the constraint solver, don't use them directly
virtual void setupSolverConstraint(btConstraintArray& ca, int solverBodyA,int solverBodyB, btScalar timeStep)
{
(void)ca;
(void)solverBodyA;
(void)solverBodyB;
(void)timeStep;
}
///internal method used by the constraint solver, don't use them directly
virtual void getInfo1 (btConstraintInfo1* info)=0;
///internal method used by the constraint solver, don't use them directly
virtual void getInfo2 (btConstraintInfo2* info)=0;
///internal method used by the constraint solver, don't use them directly
void internalSetAppliedImpulse(btScalar appliedImpulse)
{
m_appliedImpulse = appliedImpulse;
}
///internal method used by the constraint solver, don't use them directly
btScalar internalGetAppliedImpulse()
{
return m_appliedImpulse;
}
btScalar getBreakingImpulseThreshold() const
{
return m_breakingImpulseThreshold;
}
void setBreakingImpulseThreshold(btScalar threshold)
{
m_breakingImpulseThreshold = threshold;
}
bool isEnabled() const
{
return m_isEnabled;
}
void setEnabled(bool enabled)
{
m_isEnabled=enabled;
}
///internal method used by the constraint solver, don't use them directly
virtual void solveConstraintObsolete(btSolverBody& /*bodyA*/,btSolverBody& /*bodyB*/,btScalar /*timeStep*/) {};
const btRigidBody& getRigidBodyA() const
{
return m_rbA;
}
const btRigidBody& getRigidBodyB() const
{
return m_rbB;
}
btRigidBody& getRigidBodyA()
{
return m_rbA;
}
btRigidBody& getRigidBodyB()
{
return m_rbB;
}
int getUserConstraintType() const
{
return m_userConstraintType ;
}
void setUserConstraintType(int userConstraintType)
{
m_userConstraintType = userConstraintType;
};
void setUserConstraintId(int uid)
{
m_userConstraintId = uid;
}
int getUserConstraintId() const
{
return m_userConstraintId;
}
void setUserConstraintPtr(void* ptr)
{
m_userConstraintPtr = ptr;
}
void* getUserConstraintPtr()
{
return m_userConstraintPtr;
}
void setJointFeedback(btJointFeedback* jointFeedback)
{
m_jointFeedback = jointFeedback;
}
const btJointFeedback* getJointFeedback() const
{
return m_jointFeedback;
}
btJointFeedback* getJointFeedback()
{
return m_jointFeedback;
}
int getUid() const
{
return m_userConstraintId;
}
bool needsFeedback() const
{
return m_needsFeedback;
}
///enableFeedback will allow to read the applied linear and angular impulse
///use getAppliedImpulse, getAppliedLinearImpulse and getAppliedAngularImpulse to read feedback information
void enableFeedback(bool needsFeedback)
{
m_needsFeedback = needsFeedback;
}
///getAppliedImpulse is an estimated total applied impulse.
///This feedback could be used to determine breaking constraints or playing sounds.
btScalar getAppliedImpulse() const
{
btAssert(m_needsFeedback);
return m_appliedImpulse;
}
btTypedConstraintType getConstraintType () const
{
return btTypedConstraintType(m_objectType);
}
void setDbgDrawSize(btScalar dbgDrawSize)
{
m_dbgDrawSize = dbgDrawSize;
}
btScalar getDbgDrawSize()
{
return m_dbgDrawSize;
}
///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5).
///If no axis is provided, it uses the default axis for this constraint.
virtual void setParam(int num, btScalar value, int axis = -1) = 0;
///return the local value of parameter
virtual btScalar getParam(int num, int axis = -1) const = 0;
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;
};
// returns angle in range [-SIMD_2_PI, SIMD_2_PI], closest to one of the limits
// all arguments should be normalized angles (i.e. in range [-SIMD_PI, SIMD_PI])
SIMD_FORCE_INLINE btScalar btAdjustAngleToLimits(btScalar angleInRadians, btScalar angleLowerLimitInRadians, btScalar angleUpperLimitInRadians)
{
if(angleLowerLimitInRadians >= angleUpperLimitInRadians)
{
return angleInRadians;
}
else if(angleInRadians < angleLowerLimitInRadians)
{
btScalar diffLo = btFabs(btNormalizeAngle(angleLowerLimitInRadians - angleInRadians));
btScalar diffHi = btFabs(btNormalizeAngle(angleUpperLimitInRadians - angleInRadians));
return (diffLo < diffHi) ? angleInRadians : (angleInRadians + SIMD_2_PI);
}
else if(angleInRadians > angleUpperLimitInRadians)
{
btScalar diffHi = btFabs(btNormalizeAngle(angleInRadians - angleUpperLimitInRadians));
btScalar diffLo = btFabs(btNormalizeAngle(angleInRadians - angleLowerLimitInRadians));
return (diffLo < diffHi) ? (angleInRadians - SIMD_2_PI) : angleInRadians;
}
else
{
return angleInRadians;
}
}
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btTypedConstraintFloatData
{
btRigidBodyFloatData *m_rbA;
btRigidBodyFloatData *m_rbB;
char *m_name;
int m_objectType;
int m_userConstraintType;
int m_userConstraintId;
int m_needsFeedback;
float m_appliedImpulse;
float m_dbgDrawSize;
int m_disableCollisionsBetweenLinkedBodies;
int m_overrideNumSolverIterations;
float m_breakingImpulseThreshold;
int m_isEnabled;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
#define BT_BACKWARDS_COMPATIBLE_SERIALIZATION
#ifdef BT_BACKWARDS_COMPATIBLE_SERIALIZATION
///this structure is not used, except for loading pre-2.82 .bullet files
struct btTypedConstraintData
{
btRigidBodyData *m_rbA;
btRigidBodyData *m_rbB;
char *m_name;
int m_objectType;
int m_userConstraintType;
int m_userConstraintId;
int m_needsFeedback;
float m_appliedImpulse;
float m_dbgDrawSize;
int m_disableCollisionsBetweenLinkedBodies;
int m_overrideNumSolverIterations;
float m_breakingImpulseThreshold;
int m_isEnabled;
};
#endif //BACKWARDS_COMPATIBLE
struct btTypedConstraintDoubleData
{
btRigidBodyDoubleData *m_rbA;
btRigidBodyDoubleData *m_rbB;
char *m_name;
int m_objectType;
int m_userConstraintType;
int m_userConstraintId;
int m_needsFeedback;
double m_appliedImpulse;
double m_dbgDrawSize;
int m_disableCollisionsBetweenLinkedBodies;
int m_overrideNumSolverIterations;
double m_breakingImpulseThreshold;
int m_isEnabled;
char padding[4];
};
SIMD_FORCE_INLINE int btTypedConstraint::calculateSerializeBufferSize() const
{
return sizeof(btTypedConstraintData2);
}
class btAngularLimit
{
private:
btScalar
m_center,
m_halfRange,
m_softness,
m_biasFactor,
m_relaxationFactor,
m_correction,
m_sign;
bool
m_solveLimit;
public:
/// Default constructor initializes limit as inactive, allowing free constraint movement
btAngularLimit()
:m_center(0.0f),
m_halfRange(-1.0f),
m_softness(0.9f),
m_biasFactor(0.3f),
m_relaxationFactor(1.0f),
m_correction(0.0f),
m_sign(0.0f),
m_solveLimit(false)
{}
/// Sets all limit's parameters.
/// When low > high limit becomes inactive.
/// When high - low > 2PI limit is ineffective too becouse no angle can exceed the limit
void set(btScalar low, btScalar high, btScalar _softness = 0.9f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f);
/// Checks conastaint angle against limit. If limit is active and the angle violates the limit
/// correction is calculated.
void test(const btScalar angle);
/// Returns limit's softness
inline btScalar getSoftness() const
{
return m_softness;
}
/// Returns limit's bias factor
inline btScalar getBiasFactor() const
{
return m_biasFactor;
}
/// Returns limit's relaxation factor
inline btScalar getRelaxationFactor() const
{
return m_relaxationFactor;
}
/// Returns correction value evaluated when test() was invoked
inline btScalar getCorrection() const
{
return m_correction;
}
/// Returns sign value evaluated when test() was invoked
inline btScalar getSign() const
{
return m_sign;
}
/// Gives half of the distance between min and max limit angle
inline btScalar getHalfRange() const
{
return m_halfRange;
}
/// Returns true when the last test() invocation recognized limit violation
inline bool isLimit() const
{
return m_solveLimit;
}
/// Checks given angle against limit. If limit is active and angle doesn't fit it, the angle
/// returned is modified so it equals to the limit closest to given angle.
void fit(btScalar& angle) const;
/// Returns correction value multiplied by sign value
btScalar getError() const;
btScalar getLow() const;
btScalar getHigh() const;
};
#endif //BT_TYPED_CONSTRAINT_H
| 0 | 0.878561 | 1 | 0.878561 | game-dev | MEDIA | 0.969471 | game-dev | 0.880709 | 1 | 0.880709 |
PulseBeat02/MurderRun | 4,432 | src/main/java/me/brandonli/murderrun/game/ability/AbilityActionHandler.java | /*
* This file is part of Murder Run, a spin-off game-mode of Dead by Daylight
* Copyright (C) Brandon Li <https://brandonli.me/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package me.brandonli.murderrun.game.ability;
import static java.util.Objects.requireNonNull;
import java.util.Collection;
import java.util.Map;
import me.brandonli.murderrun.MurderRun;
import me.brandonli.murderrun.game.Game;
import me.brandonli.murderrun.game.player.GamePlayer;
import me.brandonli.murderrun.game.player.GamePlayerManager;
import me.brandonli.murderrun.utils.PDCUtils;
import me.brandonli.murderrun.utils.immutable.Keys;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.PluginManager;
public final class AbilityActionHandler implements Listener {
private final AbilityManager manager;
private final Map<String, Ability> abilities;
public AbilityActionHandler(final AbilityManager manager) {
final AbilityLoadingMechanism mechanism = manager.getMechanism();
final MurderRun plugin = manager.getPlugin();
this.manager = manager;
this.abilities = mechanism.getGameAbilities();
}
public void start() {
final Server server = Bukkit.getServer();
final PluginManager pluginManager = server.getPluginManager();
final MurderRun plugin = this.manager.getPlugin();
pluginManager.registerEvents(this, plugin);
final Collection<Ability> abilityList = this.abilities.values();
for (final Ability ability : abilityList) {
ability.start();
}
}
public void shutdown() {
HandlerList.unregisterAll(this);
final Collection<Ability> abilityList = this.abilities.values();
for (final Ability ability : abilityList) {
ability.shutdown();
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerFish(final PlayerFishEvent event) {
final PlayerFishEvent.State state = event.getState();
if (state != PlayerFishEvent.State.FISHING) {
return;
}
final Player player = event.getPlayer();
final Game game = this.manager.getGame();
final GamePlayerManager manager = game.getPlayerManager();
if (!manager.checkPlayerExists(player)) {
return;
}
final PlayerInventory inventory = player.getInventory();
final EquipmentSlot hand = requireNonNull(event.getHand());
final ItemStack rod = requireNonNull(inventory.getItem(hand));
if (!PDCUtils.isAbility(rod)) {
return;
}
final GamePlayer gamePlayer = manager.getGamePlayer(player);
final int cooldown = gamePlayer.getCooldown(rod);
if (cooldown > 0) {
event.setCancelled(true);
return;
}
gamePlayer.setCooldown(rod, 0);
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerThrow(final PlayerDropItemEvent event) {
final Player player = event.getPlayer();
final Game game = this.manager.getGame();
final GamePlayerManager manager = game.getPlayerManager();
if (!manager.checkPlayerExists(player)) {
return;
}
final Item item = event.getItemDrop();
final ItemStack stack = item.getItemStack();
final String data = PDCUtils.getPersistentDataAttribute(stack, Keys.ABILITY_KEY_NAME, PersistentDataType.STRING);
if (data == null) {
return;
}
event.setCancelled(true);
}
}
| 0 | 0.950161 | 1 | 0.950161 | game-dev | MEDIA | 0.766661 | game-dev | 0.992444 | 1 | 0.992444 |
unclebob/spacewar | 12,369 | src/spacewar/ui/tactical_scan.cljc | (ns spacewar.ui.tactical-scan
(:require [quil.core :as q #?@(:cljs [:include-macros true])]
[spacewar.util :as util]
[spacewar.ui.config :as uic]
[spacewar.ui.icons :as icons]
[spacewar.game-logic.config :as glc]
[spacewar.ui.protocols :as p]
[spacewar.geometry :as geo]
[spacewar.vector :as vector]))
(defn- background-color [{:keys [update-time ship game-over-timer]}]
(let [{:keys [shields antimatter
life-support-damage
hull-damage warp-damage
impulse-damage sensor-damage
weapons-damage]} ship
max-damage (max life-support-damage
hull-damage
warp-damage
impulse-damage
sensor-damage
weapons-damage)]
(cond (pos? game-over-timer) uic/black
(< (mod update-time 1000) 500) uic/black
(> max-damage 0) uic/dark-red
(< (/ antimatter glc/ship-antimatter) 0.1) uic/dark-red
(< (/ shields glc/ship-shields) 0.6) uic/dark-yellow
:else uic/black)))
(defn- draw-background [state]
(let [{:keys [w h]} state]
(apply q/fill (background-color (:world state)))
(q/rect-mode :corner)
(q/rect 0 0 w h)))
(defn- in-range [x y ship]
(< (geo/distance [x y] [(:x ship) (:y ship)]) (/ glc/tactical-range 2)))
(defn- click->pos [tactical-scan click]
(let [{:keys [x y w h world]} tactical-scan
ship (:ship world)
center (vector/add [(/ w 2) (/ h 2)] [x y])
scale (/ glc/tactical-range w)
click-delta (vector/subtract click center)
tactical-click-delta (vector/scale scale click-delta)]
(vector/add tactical-click-delta [(:x ship) (:y ship)])))
(defn- click->bearing [tactical-scan click]
(let [tactical-loc (click->pos tactical-scan click)
ship (-> tactical-scan :world :ship)
ship-loc [(:x ship) (:y ship)]
bearing (geo/angle-degrees ship-loc tactical-loc)
] bearing))
(defn- present-objects [state objects]
(if (empty? objects)
[]
(let [{:keys [w world]} state
ship (:ship world)
scale (/ w glc/tactical-range)
presentables (->> objects
(filter #(in-range (:x %) (:y %) ship))
(map #(assoc % :x (- (:x %) (:x ship))
:y (- (:y %) (:y ship))))
(map #(assoc % :x (* (:x %) scale)
:y (* (:y %) scale))))]
presentables)))
(defn- draw-objects-in [state objects draw]
(let [{:keys [w h]} state
presentable-objects (present-objects state objects)]
(doseq [{:keys [x y] :as object} presentable-objects]
(q/with-translation
[(+ x (/ w 2)) (+ y (/ h 2))]
(draw object)))))
(defn- draw-objects [state key draw]
(draw-objects-in state (-> state :world key) draw))
(defn- draw-bases [state]
(draw-objects state :bases icons/draw-base-icon))
(defn- draw-transports [state]
(draw-objects state :transports icons/draw-transport-icon))
(defn- draw-stars [state]
(q/no-stroke)
(q/ellipse-mode :center)
(draw-objects state :stars icons/draw-star-icon))
(defn- draw-klingon-and-shield [klingon]
(icons/draw-klingon-shields (:shields klingon))
(icons/draw-klingon-icon klingon)
(icons/draw-klingon-counts klingon))
(defn- draw-klingons [state]
(draw-objects state :klingons draw-klingon-and-shield))
(defn- draw-romulans [state]
(draw-objects state :romulans icons/draw-romulan))
(defn target-arc [ship]
(let [{:keys [selected-weapon
target-bearing
weapon-spread-setting]} ship
range (condp = selected-weapon
:phaser uic/phaser-target
:torpedo uic/torpedo-target
:kinetic uic/kinetic-target
0)
half-spread (max 3 (/ weapon-spread-setting 2))]
[range
(- target-bearing half-spread)
(+ target-bearing half-spread)]))
(defn- draw-ship [state]
(let [{:keys [w h]} state
ship (->> state :world :ship)
heading (or (:heading ship) 0)
velocity (or (:velocity ship) [0 0])
[vx vy] (vector/scale uic/velocity-vector-scale velocity)
radians (q/radians heading)
[tgt-radius start stop] (target-arc ship)
start (q/radians start)
stop (q/radians stop)
draw-arc (not= (:selected-weapon ship) :none)]
(q/with-translation
[(/ w 2) (/ h 2)]
(when draw-arc
(q/no-stroke)
(q/fill 255 255 255 50)
(q/ellipse-mode :center)
(q/arc 0 0 tgt-radius tgt-radius start stop #?(:clj :pie)))
(icons/draw-ship-icon [vx vy] radians ship)
)))
(defn- draw-torpedo-segment []
(let [angle (rand 360)
color (repeatedly 3 #(+ 128 (rand 127)))
length (+ 5 (rand 5))
radians (geo/->radians angle)
[tx ty] (vector/from-angular length radians)]
(apply q/stroke color)
(q/line 0 0 tx ty)))
(defn- draw-torpedo [color shot]
(q/stroke-weight 1)
(doseq [_ (range 3)]
(draw-torpedo-segment))
(apply q/fill (if (:corbomite shot) uic/red color))
(q/ellipse-mode :center)
(q/ellipse 0 0 4 4))
(defn- draw-torpedo-shots [{:keys [world] :as state}]
(let [shots (:shots world)]
(draw-objects-in state
(filter #(= :torpedo (:type %)) shots)
(partial draw-torpedo uic/white))))
(defn- draw-klingon-torpedo-shots [state]
(draw-objects-in state
(filter #(= :klingon-torpedo (:type %)) (:shots (:world state)))
(partial draw-torpedo uic/green)))
(defn- draw-romulan-blast-shots [state]
(draw-objects-in state
(filter #(= :romulan-blast (:type %)) (:shots (:world state)))
(partial icons/draw-romulan-shot (/ (:w state) glc/tactical-range))))
(defn- draw-kinetic-shot [color shot]
(let [corbomite (:corbomite shot)
color (if corbomite uic/red color)
radius (if corbomite 5 3)]
(q/ellipse-mode :center)
(q/no-stroke)
(apply q/fill color)
(q/ellipse 0 0 radius radius)))
(defn- draw-kinetic-shots [state]
(draw-objects-in state
(filter #(= :kinetic (:type %)) (:shots (:world state)))
(partial draw-kinetic-shot uic/kinetic-color)))
(defn- draw-klingon-kinetic-shots [state]
(draw-objects-in state
(filter #(= :klingon-kinetic (:type %)) (:shots (:world state)))
(partial draw-kinetic-shot uic/klingon-kinetic-color)))
(defn- phaser-intensity [range]
(let [intensity (* 255 (- 1 (/ range glc/phaser-range)))]
[intensity intensity intensity]))
(defn- phaser-color [shot]
(phaser-intensity (:range shot)))
(defn- klingon-phaser-color [_]
uic/green)
(defn- draw-phaser-shot [color-function shot]
(let [{:keys [bearing]} shot
radians (geo/->radians bearing)
[sx sy] (vector/from-angular uic/phaser-length radians)
beam-color (if (:corbomite shot) uic/red (color-function shot))]
(apply q/stroke beam-color)
(q/stroke-weight 6)
(q/line 0 0 sx sy)))
(defn- draw-phaser-shots [state]
(draw-objects-in state
(filter #(= :phaser (:type %)) (:shots (:world state)))
(partial draw-phaser-shot phaser-color)))
(defn- draw-klingon-phaser-shots [state]
(draw-objects-in state
(filter #(= :klingon-phaser (:type %)) (:shots (:world state)))
(partial draw-phaser-shot klingon-phaser-color)))
(defn explosion-radius [age profile]
(loop [profile profile radius 0 last-time 0]
(let [{:keys [velocity until]} (first profile)]
(cond (empty? profile)
nil
(> age until)
(recur (rest profile)
(+ radius (* (- until last-time) velocity))
until)
:else
(+ radius (* velocity (- age last-time)))))))
(defn age-color [age profile]
(loop [profile profile last-age 0 last-color [0 0 0]]
(if (empty? profile)
last-color
(if (<= age (:until (first profile)))
(let [profile-entry (first profile)
{:keys [until colors]} profile-entry
[c1 c2] colors
diff (util/color-diff c2 c1)
span (- until last-age)
increment (util/color-scale diff (/ (- age last-age) span))]
(util/color-add increment c1))
(let [profile-entry (first profile)
{:keys [until colors]} profile-entry]
(recur (rest profile) until (last colors)))))))
(defn draw-fragment [fragment age fragment-color]
(let [{:keys [velocity direction]} fragment
radians (geo/->radians direction)
velocity-vector (vector/from-angular velocity radians)
[hx hy] (vector/scale age velocity-vector)
[tx ty] (vector/scale (* age 0.9) velocity-vector)
]
(q/stroke-weight 1)
(apply q/stroke fragment-color)
(q/line hx hy tx ty)))
(defn draw-explosion [state explosion]
(let [{:keys [age type]} explosion
{:keys [explosion-profile
explosion-color-profile
fragment-color-profile]} (type uic/explosion-profiles)]
(let [fragments (present-objects state (:fragments explosion))
radius (explosion-radius age explosion-profile)
explosion-color (age-color age explosion-color-profile)
fragment-color (age-color age fragment-color-profile)
ex (- (rand 6) 3)
ey (- (rand 6) 3)]
(apply q/fill explosion-color)
(q/ellipse-mode :center)
(q/no-stroke)
(q/ellipse ex ey radius radius)
(doseq [fragment fragments]
(draw-fragment fragment age fragment-color)))))
(defn- draw-explosions [state]
(draw-objects state :explosions (partial draw-explosion state)))
(defn- draw-clouds [state]
(draw-objects state :clouds icons/draw-cloud-icon))
(defn- draw-shots [state]
(draw-phaser-shots state)
(draw-torpedo-shots state)
(draw-kinetic-shots state)
(draw-klingon-kinetic-shots state)
(draw-klingon-phaser-shots state)
(draw-klingon-torpedo-shots state)
(draw-romulan-blast-shots state))
(deftype tactical-scan [state]
p/Drawable
(draw [_]
(let [{:keys [x y]} state]
(q/with-translation
[x y]
(draw-background state)
(draw-stars state)
(draw-shots state)
(draw-klingons state)
(when (zero? (-> state :world :game-over-timer))
(draw-ship state))
(draw-bases state)
(draw-transports state)
(draw-explosions state)
(draw-clouds state)
(draw-romulans state)
)))
(setup [_]
(tactical-scan. state))
(update-state [_ world]
(let [{:keys [x y w h]} state
last-left-down (:left-down state)
mx (q/mouse-x)
my (q/mouse-y)
mouse-in (geo/inside-rect [x y w h] [mx my])
left-down (and mouse-in (q/mouse-pressed?) (= :left (q/mouse-button)))
state (assoc state :mouse-in mouse-in :left-down left-down)
left-up (and (not left-down) last-left-down mouse-in)
pressed? (q/key-pressed?)
the-key (q/key-as-keyword)
key (and pressed? the-key)
event (if left-up
(condp = key
:p {:event :debug-position-ship :pos (click->pos state [mx my])}
:c {:event :debug-dilithium-cloud :pos (click->pos state [mx my])}
:e {:event :debug-explosion :pos (click->pos state [mx my])}
:r {:event :debug-resupply-ship}
:k {:event :debug-add-klingon :pos (click->pos state [mx my])}
:K {:event :debug-add-kamikazee-klingon :pos (click->pos state [mx my])}
:R {:event :debug-add-romulan :pos (click->pos state [mx my])}
:P {:event :debug-add-pulsar :pos (click->pos state [mx my])}
:f {:event :debug-klingon-stats}
{:event :weapon-direction :angle (click->bearing state [mx my])})
nil)]
(p/pack-update (tactical-scan. (assoc state :world world)) event)))
) | 0 | 0.825883 | 1 | 0.825883 | game-dev | MEDIA | 0.860728 | game-dev | 0.896878 | 1 | 0.896878 |
flashhawk/spp.js | 2,040 | examples/fruitNinja/js/src/Module_bomb.js | (function() {
// throw bomb
var bombSmokeUpdate = function() {
this.scale -= 0.03;
if (this.scale < 0)
{
this.scale = 0;
this.life = 0;
}
};
var bombUpdate = function() {
var smoke = particleSystem.createParticle(SPP.SpriteImage);
var r = 1.414 * assetsManager.bomb.width * 0.5 - 5;
var px = this.position.x + r
* Math.cos(this.rotation - SPP.MathUtils.toRadian(135));
var py = this.position.y + r
* Math.sin(this.rotation - SPP.MathUtils.toRadian(135));
smoke.init(px, py, Infinity, assetsManager.star, topContext);
smoke.onUpdate = bombSmokeUpdate;
smoke.scale = 0.8;
smoke.damp.reset(0, 0);
smoke.velocity.reset(0, -(1 + Math.random() * 1));
smoke.velocity.rotate(360 * Math.random());
smoke.addForce("g", gravity);
};
// bomb explode
var explodeSmokeUpdate = function() {
this.scale -= 0.02;
if (this.scale < 0)
{
this.scale = 0;
this.life = 0;
}
};
var bombExplode = function(target) {
for ( var i = 0; i < 150; i++)
{
var smoke = particleSystem.createParticle(SPP.SpriteImage);
smoke.init(target.position.x, target.position.y, Infinity,
assetsManager.star, topContext);
smoke.onUpdate = explodeSmokeUpdate;
smoke.scale = 2;
smoke.damp.reset(0, 0);
smoke.velocity.reset(0, -(3 + Math.random() * 7));
smoke.velocity.rotate(360 * Math.random());
smoke.addForce("g", gravity);
}
createjs.Sound.play("bombExplode");
};
throwBomb = function() {
var p = bombSystem.createParticle(FruitGame.Fruit);
p.init(gameWidth * 0.5 + (1 - Math.random() * 2) * 300, gameHeight
+ assetsManager.bomb.height, Infinity, assetsManager.bomb,
assetsManager.shadow, middleContext);
p.velocity.reset(0, -(10 + Math.random() * 3));
p.velocity.rotate(8 - Math.random() * 16);
p.damp.reset(0, 0);
p.addForce("g", gravity);
p.onUpdate = bombUpdate;
p.bottomY = gameHeight + assetsManager.bomb.height;
};
// cut bomb
cutBomb = function(target) {
bombExplode(target);
target.life = 0;
gameOver();
};
}()); | 0 | 0.685915 | 1 | 0.685915 | game-dev | MEDIA | 0.851191 | game-dev | 0.82063 | 1 | 0.82063 |
bisterix-studio/parley | 1,200 | addons/parley/components/node/node_editor.gd | # Copyright 2024-2025 the Bisterix Studio authors. All rights reserved. MIT license.
@tool
class_name ParleyBaseNodeEditor extends VBoxContainer
@export var id: String = "": set = _on_id_changed
@export var type: ParleyDialogueSequenceAst.Type = ParleyDialogueSequenceAst.Type.UNKNOWN: set = _on_type_changed
@onready var title_label: Label = %TitleLabel
@onready var title_panel: PanelContainer = %TitlePanelContainer
signal delete_node_button_pressed(id: String)
func _ready() -> void:
set_title()
func _on_id_changed(new_id: String) -> void:
if id != new_id: id = new_id
set_title()
func _on_type_changed(new_type: ParleyDialogueSequenceAst.Type) -> void:
if type != new_type: type = new_type
set_title()
func set_title(title: String = "", colour: Variant = null) -> void:
if title_label:
title_label.text = "%s [ID: %s]" % [title if title else ParleyDialogueSequenceAst.get_type_name(type), id.replace(ParleyNodeAst.id_prefix, '')]
if title_panel:
title_panel.get_theme_stylebox('panel').set('bg_color', colour if colour is Color else ParleyDialogueSequenceAst.get_type_colour(type))
func _on_delete_node_button_pressed() -> void:
delete_node_button_pressed.emit(id)
| 0 | 0.917149 | 1 | 0.917149 | game-dev | MEDIA | 0.498324 | game-dev,desktop-app | 0.873108 | 1 | 0.873108 |
stubma/cocos2dx-classical | 3,254 | cocos2dx/platform/android/CCApplication.cpp | #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "jni/JniHelper.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include "CCApplication.h"
#include "CCDirector.h"
#include "CCEGLView.h"
#include <android/log.h>
#include <jni.h>
#include <cstring>
#define LOG_TAG "CCApplication_android Debug"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
NS_CC_BEGIN
// sharedApplication pointer
CCApplication * CCApplication::sm_pSharedApplication = 0;
CCApplication::CCApplication()
{
CCAssert(! sm_pSharedApplication, "");
sm_pSharedApplication = this;
}
CCApplication::~CCApplication()
{
CCAssert(this == sm_pSharedApplication, "");
sm_pSharedApplication = NULL;
}
int CCApplication::run()
{
// Initialize instance and cocos2d.
if (! applicationDidFinishLaunching())
{
return 0;
}
return -1;
}
void CCApplication::setAnimationInterval(double interval)
{
JniMethodInfo methodInfo;
if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxRenderer", "setAnimationInterval",
"(D)V"))
{
CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__);
}
else
{
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, interval);
}
// release
methodInfo.env->DeleteLocalRef(methodInfo.classID);
}
//////////////////////////////////////////////////////////////////////////
// static member function
//////////////////////////////////////////////////////////////////////////
CCApplication* CCApplication::sharedApplication()
{
CCAssert(sm_pSharedApplication, "");
return sm_pSharedApplication;
}
ccLanguageType CCApplication::getCurrentLanguage()
{
std::string languageName = getCurrentLanguageJNI();
const char* pLanguageName = languageName.c_str();
ccLanguageType ret = kLanguageEnglish;
if (0 == strcmp("zh", pLanguageName))
{
ret = kLanguageChinese;
}
else if (0 == strcmp("en", pLanguageName))
{
ret = kLanguageEnglish;
}
else if (0 == strcmp("fr", pLanguageName))
{
ret = kLanguageFrench;
}
else if (0 == strcmp("it", pLanguageName))
{
ret = kLanguageItalian;
}
else if (0 == strcmp("de", pLanguageName))
{
ret = kLanguageGerman;
}
else if (0 == strcmp("es", pLanguageName))
{
ret = kLanguageSpanish;
}
else if (0 == strcmp("nl", pLanguageName))
{
ret = kLanguageDutch;
}
else if (0 == strcmp("ru", pLanguageName))
{
ret = kLanguageRussian;
}
else if (0 == strcmp("ko", pLanguageName))
{
ret = kLanguageKorean;
}
else if (0 == strcmp("ja", pLanguageName))
{
ret = kLanguageJapanese;
}
else if (0 == strcmp("hu", pLanguageName))
{
ret = kLanguageHungarian;
}
else if (0 == strcmp("pt", pLanguageName))
{
ret = kLanguagePortuguese;
}
else if (0 == strcmp("ar", pLanguageName))
{
ret = kLanguageArabic;
}
return ret;
}
TargetPlatform CCApplication::getTargetPlatform()
{
return kTargetAndroid;
}
NS_CC_END
#endif // #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID | 0 | 0.757947 | 1 | 0.757947 | game-dev | MEDIA | 0.799587 | game-dev | 0.643504 | 1 | 0.643504 |
Ladysnake/Requiem | 4,336 | src/main/java/ladysnake/requiem/common/item/dispensing/FilledVesselItemDispenserBehavior.java | /*
* Requiem
* Copyright (C) 2017-2023 Ladysnake
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses>.
*
* Linking this mod statically or dynamically with other
* modules is making a combined work based on this mod.
* Thus, the terms and conditions of the GNU General Public License cover the whole combination.
*
* In addition, as a special exception, the copyright holders of
* this mod give you permission to combine this mod
* with free software programs or libraries that are released under the GNU LGPL
* and with code included in the standard release of Minecraft under All Rights Reserved (or
* modified versions of such code, with unchanged license).
* You may copy and distribute such a system following the terms of the GNU GPL for this mod
* and the licenses of the other code concerned.
*
* Note that people who make modified versions of this mod are not obligated to grant
* this special exception for their modified versions; it is their choice whether to do so.
* The GNU General Public License gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version which carries forward this exception.
*/
package ladysnake.requiem.common.item.dispensing;
import ladysnake.requiem.common.entity.ReleasedSoulEntity;
import ladysnake.requiem.common.entity.RequiemEntities;
import ladysnake.requiem.common.item.FilledSoulVesselItem;
import net.minecraft.block.DispenserBlock;
import net.minecraft.block.dispenser.DispenserBehavior;
import net.minecraft.block.dispenser.ItemDispenserBehavior;
import net.minecraft.block.entity.DispenserBlockEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPointer;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID;
public class FilledVesselItemDispenserBehavior implements DispenserBehavior {
private final ItemDispenserBehavior fallbackBehavior = new ItemDispenserBehavior();
public FilledVesselItemDispenserBehavior() {
}
public ItemStack tryPutStack(BlockPointer pointer, ItemStack inputStack, ItemStack outputStack) {
inputStack.decrement(1);
if (inputStack.isEmpty()) {
return outputStack.copy();
} else {
if (pointer.<DispenserBlockEntity>getBlockEntity().addToFirstFreeSlot(outputStack.copy()) < 0) {
fallbackBehavior.dispense(pointer, outputStack.copy());
}
return inputStack;
}
}
@Override
public ItemStack dispense(BlockPointer pointer, ItemStack stack) {
Direction direction = pointer.getBlockState().get(DispenserBlock.FACING);
Vec3d targetPos = Vec3d.ofCenter(pointer.getPos().offset(direction));
@Nullable UUID ownerRecord = Optional.ofNullable(stack.getSubNbt(FilledSoulVesselItem.SOUL_FRAGMENT_NBT))
.filter(data -> data.containsUuid("uuid"))
.map(data -> data.getUuid("uuid"))
.orElse(null);
ReleasedSoulEntity releasedSoul = new ReleasedSoulEntity(RequiemEntities.RELEASED_SOUL, pointer.getWorld(), ownerRecord);
releasedSoul.setPosition(targetPos.getX(), targetPos.getY(), targetPos.getZ());
releasedSoul.setVelocity(new Vec3d(direction.getUnitVector()).multiply(0.15f));
releasedSoul.setYaw(pointer.getWorld().random.nextFloat());
releasedSoul.setPitch(pointer.getWorld().random.nextFloat());
pointer.getWorld().spawnEntity(releasedSoul);
ItemStack result = ((FilledSoulVesselItem) stack.getItem()).getEmptiedStack();
return this.tryPutStack(pointer, stack, result);
}
}
| 0 | 0.76761 | 1 | 0.76761 | game-dev | MEDIA | 0.965741 | game-dev | 0.921443 | 1 | 0.921443 |
karellodewijk/canvas-webgl | 10,497 | CanvasMark/scripts/arena_effects.js | /**
* Particle emitter effect actor class.
*
* A simple particle emitter, that does not recycle particles, but sets itself as expired() once
* all child particles have expired.
*
* Requires a function known as the emitter that is called per particle generated.
*
* @namespace Arena
* @class Arena.Particles
*/
(function()
{
/**
* Constructor
*
* @param p {Vector} Emitter position
* @param v {Vector} Emitter velocity
* @param count {Integer} Number of particles
* @param fnEmitter {Function} Emitter function to call per particle generated
*/
Arena.Particles = function(p, v, count, fnEmitter)
{
Arena.Particles.superclass.constructor.call(this, p, v);
// generate particles based on the supplied emitter function
this.particles = new Array(count);
for (var i=0; i<count; i++)
{
this.particles[i] = fnEmitter.call(this, i);
}
return this;
};
extend(Arena.Particles, Game.Actor,
{
particles: null,
/**
* Particle effect rendering method
*
* @param ctx {object} Canvas rendering context
*/
onRender: function onRender(ctx, world)
{
ctx.save();
ctx.shadowBlur = 0;
ctx.globalCompositeOperation = "lighter";
for (var i=0, particle, viewposition; i<this.particles.length; i++)
{
particle = this.particles[i];
// update particle and test for lifespan
if (particle.update())
{
viewposition = Game.worldToScreen(particle.position, world, particle.size);
if (viewposition)
{
ctx.save();
ctx.translate(viewposition.x, viewposition.y);
ctx.scale(world.scale, world.scale);
particle.render(ctx);
ctx.restore();
}
}
else
{
// particle no longer alive, remove from list
this.particles.splice(i, 1);
}
}
ctx.restore();
},
expired: function expired()
{
return (this.particles.length === 0);
}
});
})();
/**
* Default Arena Particle structure.
* Currently supports three particle types; dot, line and smudge.
*/
function ArenaParticle(position, vector, size, type, lifespan, fadelength, colour)
{
this.position = position;
this.vector = vector;
this.size = size;
this.type = type;
this.lifespan = lifespan;
this.fadelength = fadelength;
this.colour = colour ? colour : "rgb(255,125,50)"; // default colour if none set
// randomize rotation speed and angle for line particle
if (type === 1)
{
this.rotate = Rnd() * TWOPI;
this.rotationv = Rnd() - 0.5;
}
this.update = function()
{
this.position.add(this.vector);
return (--this.lifespan !== 0);
};
this.render = function(ctx)
{
// NOTE: the try/catch here is to handle where FireFox gets
// upset when rendering images outside the canvas area
try
{
ctx.globalAlpha = (this.lifespan < this.fadelength ? ((1 / this.fadelength) * this.lifespan) : 1);
switch (this.type)
{
case 0: // point (prerendered image)
// prerendered images for each enemy colour with health > 1
// lookup based on particle colour e.g. points_rgb(x,y,z)
ctx.drawImage(
GameHandler.prerenderer.images["points_" + this.colour][this.size], 0, 0);
break;
case 1: // line
var s = this.size;
ctx.rotate(this.rotate);
this.rotate += this.rotationv;
// specific line colour - for enemy explosion pieces
ctx.strokeStyle = this.colour;
ctx.lineWidth = 2.0;
ctx.beginPath();
ctx.moveTo(-s, -s);
ctx.lineTo(s, s);
ctx.closePath();
ctx.stroke();
break;
case 2: // smudge (prerendered image)
ctx.drawImage(GameHandler.prerenderer.images["smudges"][this.size - 4], 0, 0);
break;
}
}
catch (error)
{
if (console !== undefined) console.log(error.message);
}
};
}
/**
* Enemy explosion - Particle effect actor class.
*
* @namespace Arena
* @class Arena.EnemyExplosion
*/
(function()
{
/**
* Constructor
*/
Arena.EnemyExplosion = function(p, v, enemy)
{
Arena.EnemyExplosion.superclass.constructor.call(this, p, v, 16, function()
{
// randomise start position slightly
var pos = p.clone();
pos.x += randomInt(-5, 5);
pos.y += randomInt(-5, 5);
// randomise radial direction vector - speed and angle, then add parent vector
switch (randomInt(0, 2))
{
case 0:
var t = new Vector(0, randomInt(20, 25));
t.rotate(Rnd() * TWOPI);
t.add(v);
return new ArenaParticle(
pos, t, ~~(Rnd() * 4), 0, 20, 15);
case 1:
var t = new Vector(0, randomInt(5, 10));
t.rotate(Rnd() * TWOPI);
t.add(v);
// create line particle - size based on enemy type
return new ArenaParticle(
pos, t, (enemy.type !== 3 ? Rnd() * 5 + 5 : Rnd() * 10 + 10), 1, 20, 15, enemy.colorRGB);
case 2:
var t = new Vector(0, randomInt(2, 4));
t.rotate(Rnd() * TWOPI);
t.add(v);
return new ArenaParticle(
pos, t, ~~(Rnd() * 4 + 4), 2, 20, 15);
}
});
return this;
};
extend(Arena.EnemyExplosion, Arena.Particles);
})();
/**
* Enemy impact effect - Particle effect actor class.
* Used when an enemy is hit by player bullet but not destroyed.
*
* @namespace Arena
* @class Arena.EnemyImpact
*/
(function()
{
/**
* Constructor
*/
Arena.EnemyImpact = function(p, v, enemy)
{
Arena.EnemyImpact.superclass.constructor.call(this, p, v, 5, function()
{
// slightly randomise vector angle - then add parent vector
var t = new Vector(0, Rnd() < 0.5 ? randomInt(-5, -10) : randomInt(5, 10));
t.rotate(Rnd() * PIO2 - PIO4);
t.add(v);
return new ArenaParticle(
p.clone(), t, ~~(Rnd() * 4), 0, 15, 10, enemy.colorRGB);
});
return this;
};
extend(Arena.EnemyImpact, Arena.Particles);
})();
/**
* Bullet impact effect - Particle effect actor class.
* Used when an bullet hits an object and is destroyed.
*
* @namespace Arena
* @class Arena.BulletImpactEffect
*/
(function()
{
/**
* Constructor
*/
Arena.BulletImpactEffect = function(p, v, enemy)
{
Arena.BulletImpactEffect.superclass.constructor.call(this, p, v, 3, function()
{
return new ArenaParticle(
p.clone(), v.nrotate(Rnd()*PIO8), ~~(Rnd() * 4), 0, 15, 10);
});
return this;
};
extend(Arena.BulletImpactEffect, Arena.Particles);
})();
/**
* Player explosion - Particle effect actor class.
*
* @namespace Arena
* @class Arena.PlayerExplosion
*/
(function()
{
/**
* Constructor
*/
Arena.PlayerExplosion = function(p, v)
{
Arena.PlayerExplosion.superclass.constructor.call(this, p, v, 20, function()
{
// randomise start position slightly
var pos = p.clone();
pos.x += randomInt(-5, 5);
pos.y += randomInt(-5, 5);
// randomise radial direction vector - speed and angle, then add parent vector
switch (randomInt(1,2))
{
case 1:
var t = new Vector(0, randomInt(5, 8));
t.rotate(Rnd() * TWOPI);
t.add(v);
return new ArenaParticle(
pos, t, Rnd() * 5 + 5, 1, 25, 15, "white");
case 2:
var t = new Vector(0, randomInt(5, 10));
t.rotate(Rnd() * TWOPI);
t.add(v);
return new ArenaParticle(
pos, t, ~~(Rnd() * 4 + 4), 2, 25, 15);
}
});
return this;
};
extend(Arena.PlayerExplosion, Arena.Particles);
})();
/**
* Text indicator effect actor class.
*
* @namespace Arena
* @class Arena.TextIndicator
*/
(function()
{
Arena.TextIndicator = function(p, v, msg, textSize, colour, fadeLength)
{
this.fadeLength = (fadeLength ? fadeLength : this.DEFAULT_FADE_LENGTH);
Arena.TextIndicator.superclass.constructor.call(this, p, v, this.fadeLength);
this.msg = msg;
if (textSize)
{
this.textSize = textSize;
}
if (colour)
{
this.colour = colour;
}
return this;
};
extend(Arena.TextIndicator, Game.EffectActor,
{
DEFAULT_FADE_LENGTH: 16,
fadeLength: 0,
textSize: 22,
msg: null,
colour: "rgb(255,255,255)",
/**
* Text indicator effect rendering method
*
* @param ctx {object} Canvas rendering context
*/
onRender: function onRender(ctx, world)
{
ctx.save();
if (this.worldToScreen(ctx, world, 128))
{
var alpha = (1.0 / this.fadeLength) * this.lifespan;
ctx.globalAlpha = alpha;
ctx.shadowBlur = 0;
Game.fillText(ctx, this.msg, this.textSize + "pt Courier New", 0, 0, this.colour);
}
ctx.restore();
}
});
})();
/**
* Score indicator effect actor class.
*
* @namespace Arena
* @class Arena.ScoreIndicator
*/
(function()
{
Arena.ScoreIndicator = function(p, v, score, textSize, prefix, colour, fadeLength)
{
var msg = score.toString();
if (prefix)
{
msg = prefix + ' ' + msg;
}
Arena.ScoreIndicator.superclass.constructor.call(this, p, v, msg, textSize, colour, fadeLength);
return this;
};
extend(Arena.ScoreIndicator, Arena.TextIndicator,
{
});
})();
| 0 | 0.832732 | 1 | 0.832732 | game-dev | MEDIA | 0.897452 | game-dev | 0.849863 | 1 | 0.849863 |
TurningWheel/Barony | 29,520 | src/actmagictrap.cpp | /*-------------------------------------------------------------------------------
BARONY
File: actmagictrap.cpp
Desc: implements magic trap code
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#include "main.hpp"
#include "game.hpp"
#include "stat.hpp"
#include "entity.hpp"
#include "engine/audio/sound.hpp"
#include "items.hpp"
#include "net.hpp"
#include "monster.hpp"
#include "collision.hpp"
#include "player.hpp"
#include "magic/magic.hpp"
#include "prng.hpp"
#include "mod_tools.hpp"
/*-------------------------------------------------------------------------------
act*
The following function describes an entity behavior. The function
takes a pointer to the entity that uses it as an argument.
-------------------------------------------------------------------------------*/
void actMagicTrapCeiling(Entity* my)
{
if ( !my )
{
return;
}
my->actMagicTrapCeiling();
}
void Entity::actMagicTrapCeiling()
{
#ifdef USE_FMOD
if ( spellTrapAmbience == 0 )
{
spellTrapAmbience--;
stopEntitySound();
entity_sound = playSoundEntityLocal(this, 149, 16);
}
if ( entity_sound )
{
bool playing = false;
entity_sound->isPlaying(&playing);
if ( !playing )
{
entity_sound = nullptr;
}
}
#else
spellTrapAmbience--;
if ( spellTrapAmbience <= 0 )
{
spellTrapAmbience = TICKS_PER_SECOND * 30;
playSoundEntityLocal(this, 149, 16);
}
#endif
if ( multiplayer == CLIENT )
{
return;
}
if ( circuit_status != CIRCUIT_ON )
{
spellTrapReset = 0;
spellTrapCounter = spellTrapRefireRate; //shoost instantly!
return;
}
if ( !spellTrapInit )
{
spellTrapInit = 1;
auto& rng = entity_rng ? *entity_rng : local_rng;
if ( spellTrapType == -1 )
{
switch ( rng.rand() % 8 )
{
case 0:
spellTrapType = SPELL_FORCEBOLT;
break;
case 1:
spellTrapType = SPELL_MAGICMISSILE;
break;
case 2:
spellTrapType = SPELL_COLD;
break;
case 3:
spellTrapType = SPELL_FIREBALL;
break;
case 4:
spellTrapType = SPELL_LIGHTNING;
break;
case 5:
spellTrapType = SPELL_SLEEP;
spellTrapRefireRate = 275; // stop getting stuck forever!
break;
case 6:
spellTrapType = SPELL_CONFUSE;
break;
case 7:
spellTrapType = SPELL_SLOW;
break;
default:
spellTrapType = SPELL_MAGICMISSILE;
break;
}
}
}
++spellTrapCounter;
node_t* node = children.first;
Entity* ceilingModel = (Entity*)(node->element);
int triggerSprite = 0;
switch ( spellTrapType )
{
case SPELL_FORCEBOLT:
case SPELL_MAGICMISSILE:
case SPELL_CONFUSE:
triggerSprite = 173;
break;
case SPELL_FIREBALL:
triggerSprite = 168;
break;
case SPELL_LIGHTNING:
triggerSprite = 170;
break;
case SPELL_COLD:
case SPELL_SLEEP:
triggerSprite = 172;
break;
case SPELL_SLOW:
default:
triggerSprite = 171;
break;
}
if ( spellTrapCounter > spellTrapRefireRate )
{
spellTrapCounter = 0; // reset timer.
if ( spellTrapReset == 0 )
{
// once off magic particles. reset once power is cut.
spawnMagicEffectParticles(x, y, z, triggerSprite);
playSoundEntity(this, 252, 128);
spellTrapReset = 1;
/*spellTrapCounter = spellTrapRefireRate - 5; // delay?
return;*/
}
Entity* entity = castSpell(getUID(), getSpellFromID(spellTrapType), false, true);
if ( ceilingModel && entity )
{
entity->x = x;
entity->y = y;
entity->z = ceilingModel->z - 2;
double missile_speed = 4 * ((double)(((spellElement_t*)(getSpellFromID(spellTrapType)->elements.first->element))->mana) / ((spellElement_t*)(getSpellFromID(spellTrapType)->elements.first->element))->overload_multiplier);
entity->vel_x = 0.0;
entity->vel_y = 0.0;
entity->vel_z = 0.5 * (missile_speed);
entity->pitch = PI / 2;
entity->actmagicIsVertical = MAGIC_ISVERTICAL_Z;
}
}
}
/*-------------------------------------------------------------------------------
act*
The following function describes an entity behavior. The function
takes a pointer to the entity that uses it as an argument.
-------------------------------------------------------------------------------*/
#define MAGICTRAP_INIT my->skill[0]
#define MAGICTRAP_SPELL my->skill[1]
#define MAGICTRAP_DIRECTION my->skill[3]
void actMagicTrap(Entity* my)
{
if ( !MAGICTRAP_INIT )
{
MAGICTRAP_INIT = 1;
auto& rng = my->entity_rng ? *my->entity_rng : local_rng;
switch ( rng.rand() % 8 )
{
case 0:
MAGICTRAP_SPELL = SPELL_FORCEBOLT;
break;
case 1:
MAGICTRAP_SPELL = SPELL_MAGICMISSILE;
break;
case 2:
MAGICTRAP_SPELL = SPELL_COLD;
break;
case 3:
MAGICTRAP_SPELL = SPELL_FIREBALL;
break;
case 4:
MAGICTRAP_SPELL = SPELL_LIGHTNING;
break;
case 5:
MAGICTRAP_SPELL = SPELL_SLEEP;
break;
case 6:
MAGICTRAP_SPELL = SPELL_CONFUSE;
break;
case 7:
MAGICTRAP_SPELL = SPELL_SLOW;
break;
default:
MAGICTRAP_SPELL = SPELL_MAGICMISSILE;
break;
}
my->light = addLight(my->x / 16, my->y / 16, "magictrap");
}
// eliminate traps that have been destroyed.
// check wall inside me.
int checkx = static_cast<int>(my->x) >> 4;
int checky = static_cast<int>(my->y) >> 4;
if ( !map.tiles[OBSTACLELAYER + checky * MAPLAYERS + checkx * MAPLAYERS * map.height] ) // wall
{
my->removeLightField();
list_RemoveNode(my->mynode);
return;
}
if ( multiplayer == CLIENT )
{
return;
}
if ( my->ticks % TICKS_PER_SECOND == 0 )
{
int oldir = 0;
int x = 0, y = 0;
switch ( MAGICTRAP_DIRECTION )
{
case 0:
x = 12;
y = 0;
oldir = MAGICTRAP_DIRECTION;
MAGICTRAP_DIRECTION++;
break;
case 1:
x = 0;
y = 12;
oldir = MAGICTRAP_DIRECTION;
MAGICTRAP_DIRECTION++;
break;
case 2:
x = -12;
y = 0;
oldir = MAGICTRAP_DIRECTION;
MAGICTRAP_DIRECTION++;
break;
case 3:
x = 0;
y = -12;
oldir = MAGICTRAP_DIRECTION;
MAGICTRAP_DIRECTION = 0;
break;
}
int u = std::min<int>(std::max<int>(0.0, (my->x + x) / 16), map.width - 1);
int v = std::min<int>(std::max<int>(0.0, (my->y + y) / 16), map.height - 1);
if ( !map.tiles[OBSTACLELAYER + v * MAPLAYERS + u * MAPLAYERS * map.height] )
{
Entity* entity = castSpell(my->getUID(), getSpellFromID(MAGICTRAP_SPELL), false, true);
entity->x = my->x + x;
entity->y = my->y + y;
entity->z = my->z;
entity->yaw = oldir * (PI / 2.f);
double missile_speed = 4 * ((double)(((spellElement_t*)(getSpellFromID(MAGICTRAP_SPELL)->elements.first->element))->mana) / ((spellElement_t*)(getSpellFromID(MAGICTRAP_SPELL)->elements.first->element))->overload_multiplier);
entity->vel_x = cos(entity->yaw) * (missile_speed);
entity->vel_y = sin(entity->yaw) * (missile_speed);
}
}
}
void actTeleportShrine(Entity* my)
{
if ( !my )
{
return;
}
my->actTeleportShrine();
}
void Entity::actTeleportShrine()
{
if ( this->ticks == 1 )
{
this->createWorldUITooltip();
}
this->removeLightField();
if ( shrineActivateDelay == 0 )
{
this->light = addLight(this->x / 16, this->y / 16, "teleport_shrine");
spawnAmbientParticles(80, 576, 10 + local_rng.rand() % 40, 1.0, false);
}
#ifdef USE_FMOD
if ( shrineAmbience == 0 )
{
shrineAmbience--;
stopEntitySound();
entity_sound = playSoundEntityLocal(this, 149, 16);
}
if ( entity_sound )
{
bool playing = false;
entity_sound->isPlaying(&playing);
if ( !playing )
{
entity_sound = nullptr;
}
}
#else
shrineAmbience--;
if ( shrineAmbience <= 0 )
{
shrineAmbience = TICKS_PER_SECOND * 30;
playSoundEntityLocal(this, 149, 16);
}
#endif
if ( multiplayer == CLIENT )
{
return;
}
if ( !shrineInit )
{
shrineInit = 1;
shrineSpellEffect = SPELL_TELEPORTATION;
}
if ( shrineActivateDelay > 0 )
{
--shrineActivateDelay;
if ( shrineActivateDelay == 0 )
{
serverUpdateEntitySkill(this, 7);
}
}
// using
if ( this->isInteractWithMonster() )
{
Entity* monsterInteracting = uidToEntity(this->interactedByMonster);
if ( monsterInteracting )
{
if ( shrineActivateDelay == 0 )
{
std::vector<std::pair<Entity*, std::pair<int, int>>> allShrines;
for ( node_t* node = map.entities->first; node; node = node->next )
{
Entity* entity = (Entity*)node->element;
if ( !entity ) { continue; }
if ( entity->behavior == &::actTeleportShrine )
{
allShrines.push_back(std::make_pair(entity, std::make_pair((int)(entity->x / 16), (int)(entity->y / 16))));
}
}
Entity* selectedShrine = nullptr;
for ( size_t s = 0; s < allShrines.size(); ++s )
{
if ( allShrines[s].first == this )
{
// find next one in list
if ( (s + 1) >= allShrines.size() )
{
selectedShrine = allShrines[0].first;
}
else
{
selectedShrine = allShrines[s + 1].first;
}
break;
}
}
if ( selectedShrine )
{
playSoundEntity(this, 252, 128);
//messagePlayer(i, MESSAGE_INTERACTION, Language::get(4301));
if ( auto leader = monsterInteracting->monsterAllyGetPlayerLeader() )
{
Compendium_t::Events_t::eventUpdateWorld(leader->skill[2], Compendium_t::CPDM_OBELISK_FOLLOWER_USES, "obelisk", 1);
}
Entity* spellTimer = createParticleTimer(this, 200, 625);
spellTimer->particleTimerPreDelay = 0; // wait x ticks before animation.
spellTimer->particleTimerEndAction = PARTICLE_EFFECT_SHRINE_TELEPORT; // teleport behavior of timer.
spellTimer->particleTimerEndSprite = 625; // sprite to use for end of timer function.
spellTimer->particleTimerCountdownAction = 1;
spellTimer->particleTimerCountdownSprite = 625;
spellTimer->particleTimerTarget = static_cast<Sint32>(selectedShrine->getUID()); // get the target to teleport around.
spellTimer->particleTimerVariable1 = 1; // distance of teleport in tiles
spellTimer->particleTimerVariable2 = monsterInteracting->getUID(); // which player to teleport
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(this, PARTICLE_EFFECT_SHRINE_TELEPORT, 625);
}
shrineActivateDelay = 250;
serverUpdateEntitySkill(this, 7);
}
}
this->clearMonsterInteract();
return;
}
this->clearMonsterInteract();
}
for ( int i = 0; i < MAXPLAYERS; i++ )
{
if ( selectedEntity[i] == this || client_selected[i] == this )
{
if ( inrange[i] && Player::getPlayerInteractEntity(i) )
{
if ( shrineActivateDelay > 0 )
{
messagePlayer(i, MESSAGE_INTERACTION, Language::get(4300));
break;
}
std::vector<std::pair<Entity*, std::pair<int, int>>> allShrines;
for ( node_t* node = map.entities->first; node; node = node->next )
{
Entity* entity = (Entity*)node->element;
if ( !entity ) { continue; }
if ( entity->behavior == &::actTeleportShrine )
{
allShrines.push_back(std::make_pair(entity, std::make_pair((int)(entity->x / 16), (int)(entity->y / 16))));
}
}
Entity* selectedShrine = nullptr;
for ( size_t s = 0; s < allShrines.size(); ++s )
{
if ( allShrines[s].first == this )
{
// find next one in list
if ( (s + 1) >= allShrines.size() )
{
selectedShrine = allShrines[0].first;
}
else
{
selectedShrine = allShrines[s + 1].first;
}
break;
}
}
if ( selectedShrine )
{
playSoundEntity(this, 252, 128);
messagePlayer(i, MESSAGE_INTERACTION, Language::get(4301));
Compendium_t::Events_t::eventUpdateWorld(i, Compendium_t::CPDM_OBELISK_USES, "obelisk", 1);
Entity* spellTimer = createParticleTimer(this, 200, 625);
spellTimer->particleTimerPreDelay = 0; // wait x ticks before animation.
spellTimer->particleTimerEndAction = PARTICLE_EFFECT_SHRINE_TELEPORT; // teleport behavior of timer.
spellTimer->particleTimerEndSprite = 625; // sprite to use for end of timer function.
spellTimer->particleTimerCountdownAction = 1;
spellTimer->particleTimerCountdownSprite = 625;
spellTimer->particleTimerTarget = static_cast<Sint32>(selectedShrine->getUID()); // get the target to teleport around.
spellTimer->particleTimerVariable1 = 1; // distance of teleport in tiles
spellTimer->particleTimerVariable2 = Player::getPlayerInteractEntity(i)->getUID(); // which player to teleport
if ( multiplayer == SERVER )
{
serverSpawnMiscParticles(this, PARTICLE_EFFECT_SHRINE_TELEPORT, 625);
}
shrineActivateDelay = 250;
serverUpdateEntitySkill(this, 7);
}
break;
}
}
}
}
void actDaedalusShrine(Entity* my)
{
if ( !my )
{
return;
}
my->actDaedalusShrine();
}
#define SHRINE_DAEDALUS_EXIT_UID my->skill[13]
#define SHRINE_TURN_DIR my->skill[14]
#define SHRINE_LAST_TOUCHED my->skill[15]
#define SHRINE_START_DIR my->fskill[0]
#define SHRINE_TARGET_DIR my->fskill[1]
void daedalusShrineInteract(Entity* my, Entity* touched)
{
if ( !my ) { return; }
if ( multiplayer == SERVER )
{
for ( int i = 1; i < MAXPLAYERS; ++i )
{
if ( !client_disconnected[i] )
{
strcpy((char*)net_packet->data, "DAED");
SDLNet_Write32(static_cast<Uint32>(my->getUID()), &net_packet->data[4]);
net_packet->address.host = net_clients[i - 1].host;
net_packet->address.port = net_clients[i - 1].port;
net_packet->len = 8;
sendPacketSafe(net_sock, -1, net_packet, i - 1);
}
}
}
if ( my->shrineDaedalusState == 0 ) // default
{
if ( multiplayer != CLIENT )
{
SHRINE_LAST_TOUCHED = touched ? touched->getUID() : 0;
}
Entity* exitEntity = nullptr;
for ( node_t* node = map.entities->first; node; node = node->next )
{
Entity* entity = (Entity*)node->element;
if ( !entity ) { continue; }
if ( (entity->behavior == &actLadder && strcmp(map.name, "Hell")) || (entity->behavior == &actPortal && !strcmp(map.name, "Hell")) )
{
if ( entity->behavior == &actLadder && entity->skill[3] != 1 )
{
exitEntity = entity;
break;
}
if ( entity->behavior == &actPortal && entity->portalNotSecret == 1 )
{
exitEntity = entity;
break;
}
}
}
if ( exitEntity )
{
real_t tangent = atan2(exitEntity->y - my->y, exitEntity->x - my->x);
while ( tangent >= 2 * PI )
{
tangent -= 2 * PI;
}
while ( tangent < 0 )
{
tangent += 2 * PI;
}
while ( my->yaw >= 2 * PI )
{
my->yaw -= 2 * PI;
}
while ( my->yaw < 0 )
{
my->yaw += 2 * PI;
}
SHRINE_TARGET_DIR = tangent;
SHRINE_DAEDALUS_EXIT_UID = exitEntity->getUID();
SHRINE_START_DIR = my->yaw;
playSoundEntityLocal(my, 248, 128);
my->shrineDaedalusState = 1;
}
}
else if ( my->shrineDaedalusState == 2 )
{
shrineDaedalusRevealMap(*my);
if ( multiplayer != CLIENT )
{
SHRINE_LAST_TOUCHED = touched ? touched->getUID() : 0;
spawnMagicEffectParticles(my->x, my->y, my->z, 174);
if ( my->ticks >= (getMinotaurTimeToArrive() - TICKS_PER_SECOND * 30) && my->ticks <= getMinotaurTimeToArrive() )
{
if ( touched && touched->getStats() )
{
Stat* myStats = touched->getStats();
if ( myStats->EFFECTS[EFF_SLOW] )
{
touched->setEffect(EFF_SLOW, false, 0, true);
}
if ( touched->setEffect(EFF_FAST, true, std::max(TICKS_PER_SECOND * 15, myStats->EFFECTS_TIMERS[EFF_FAST]), true) )
{
playSoundEntity(touched, 178, 128);
spawnMagicEffectParticles(touched->x, touched->y, touched->z, 174);
if ( touched->behavior == &actPlayer )
{
messagePlayerColor(touched->skill[2], MESSAGE_STATUS, makeColorRGB(0, 255, 0), Language::get(768));
steamAchievementClient(touched->skill[2], "BARONY_ACH_BULL_RUSH");
Compendium_t::Events_t::eventUpdateWorld(touched->skill[2], Compendium_t::CPDM_DAED_SPEED_BUFFS, "daedalus", 1);
}
}
}
for ( int i = 0; i < MAXPLAYERS; ++i )
{
messagePlayerColor(i, MESSAGE_INTERACTION, makeColorRGB(255, 0, 255), Language::get(6285));
}
}
else
{
for ( int i = 0; i < MAXPLAYERS; ++i )
{
messagePlayerColor(i, MESSAGE_INTERACTION, makeColorRGB(255, 0, 255), Language::get(6267));
}
}
}
}
}
void Entity::actDaedalusShrine()
{
if ( this->ticks == 1 )
{
this->createWorldUITooltip();
}
this->removeLightField();
if ( shrineActivateDelay == 0 )
{
this->light = addLight(this->x / 16, this->y / 16, "teleport_shrine");
spawnAmbientParticles(80, 576, 10 + local_rng.rand() % 40, 1.0, false);
}
#ifdef USE_FMOD
if ( shrineAmbience == 0 )
{
shrineAmbience--;
stopEntitySound();
entity_sound = playSoundEntityLocal(this, 149, 16);
}
if ( entity_sound )
{
bool playing = false;
entity_sound->isPlaying(&playing);
if ( !playing )
{
entity_sound = nullptr;
}
}
#else
shrineAmbience--;
if ( shrineAmbience <= 0 )
{
shrineAmbience = TICKS_PER_SECOND * 30;
playSoundEntityLocal(this, 149, 16);
}
#endif
if ( !shrineInit )
{
shrineInit = 1;
shrineSpellEffect = SPELL_SPEED;
}
if ( shrineActivateDelay > 0 )
{
--shrineActivateDelay;
if ( shrineActivateDelay == 0 )
{
if ( multiplayer != CLIENT )
{
serverUpdateEntitySkill(this, 7);
}
}
}
if ( shrineDaedalusState == 1 )
{
// point to exit
int dir = 0;
real_t startDir = fskill[0];
real_t targetDir = fskill[1];
int diff = static_cast<int>((startDir - targetDir) * 180.0 / PI) % 360;
if ( diff < 0 )
{
diff += 360;
}
if ( diff < 180 )
{
dir = 1;
}
real_t speed = dir == 1 ? -2.f : 2.f;
real_t scale = 1.0;
{
if ( diff > 180 )
{
diff -= 360;
}
scale = std::max(0.05, (abs(diff) / 180.0)) / (real_t)TICKS_PER_SECOND;
speed *= scale;
}
if ( limbAnimateToLimit(this, ANIMATE_YAW, speed, targetDir, false, 0.0) )
{
shrineDaedalusState = 2;
shrineDaedalusRevealMap(*this);
if ( multiplayer != CLIENT )
{
spawnMagicEffectParticles(x, y, z, 174);
Entity* touched = nullptr;
if ( skill[15] != 0 )
{
touched = uidToEntity(skill[15]);
}
if ( this->ticks >= (getMinotaurTimeToArrive() - TICKS_PER_SECOND * 30) && this->ticks <= getMinotaurTimeToArrive() )
{
if ( touched && touched->getStats() )
{
Stat* myStats = touched->getStats();
if ( myStats->EFFECTS[EFF_SLOW] )
{
touched->setEffect(EFF_SLOW, false, 0, true);
}
if ( touched->setEffect(EFF_FAST, true, std::max(TICKS_PER_SECOND * 15, myStats->EFFECTS_TIMERS[EFF_FAST]), true) )
{
playSoundEntity(touched, 178, 128);
spawnMagicEffectParticles(touched->x, touched->y, touched->z, 174);
if ( touched->behavior == &actPlayer )
{
messagePlayerColor(touched->skill[2], MESSAGE_STATUS, makeColorRGB(0, 255, 0), Language::get(768));
steamAchievementClient(touched->skill[2], "BARONY_ACH_BULL_RUSH");
Compendium_t::Events_t::eventUpdateWorld(touched->skill[2], Compendium_t::CPDM_DAED_SPEED_BUFFS, "daedalus", 1);
}
}
}
for ( int i = 0; i < MAXPLAYERS; ++i )
{
messagePlayerColor(i, MESSAGE_INTERACTION, makeColorRGB(255, 0, 255), Language::get(6285));
}
}
else
{
for ( int i = 0; i < MAXPLAYERS; ++i )
{
messagePlayerColor(i, MESSAGE_INTERACTION, makeColorRGB(255, 0, 255), Language::get(6267));
}
}
}
}
}
if ( multiplayer == CLIENT )
{
return;
}
// using
//if ( this->isInteractWithMonster() )
//{
// Entity* monsterInteracting = uidToEntity(this->interactedByMonster);
// if ( monsterInteracting )
// {
// if ( shrineActivateDelay == 0 )
// {
// std::vector<std::pair<Entity*, std::pair<int, int>>> allShrines;
// for ( node_t* node = map.entities->first; node; node = node->next )
// {
// Entity* entity = (Entity*)node->element;
// if ( !entity ) { continue; }
// if ( entity->behavior == &::actTeleportShrine )
// {
// allShrines.push_back(std::make_pair(entity, std::make_pair((int)(entity->x / 16), (int)(entity->y / 16))));
// }
// }
// Entity* selectedShrine = nullptr;
// for ( size_t s = 0; s < allShrines.size(); ++s )
// {
// if ( allShrines[s].first == this )
// {
// // find next one in list
// if ( (s + 1) >= allShrines.size() )
// {
// selectedShrine = allShrines[0].first;
// }
// else
// {
// selectedShrine = allShrines[s + 1].first;
// }
// break;
// }
// }
// if ( selectedShrine )
// {
// playSoundEntity(this, 252, 128);
// //messagePlayer(i, MESSAGE_INTERACTION, Language::get(4301));
// if ( auto leader = monsterInteracting->monsterAllyGetPlayerLeader() )
// {
// Compendium_t::Events_t::eventUpdateWorld(leader->skill[2], Compendium_t::CPDM_OBELISK_FOLLOWER_USES, "obelisk", 1);
// }
// Entity* spellTimer = createParticleTimer(this, 200, 625);
// spellTimer->particleTimerPreDelay = 0; // wait x ticks before animation.
// spellTimer->particleTimerEndAction = PARTICLE_EFFECT_SHRINE_TELEPORT; // teleport behavior of timer.
// spellTimer->particleTimerEndSprite = 625; // sprite to use for end of timer function.
// spellTimer->particleTimerCountdownAction = 1;
// spellTimer->particleTimerCountdownSprite = 625;
// spellTimer->particleTimerTarget = static_cast<Sint32>(selectedShrine->getUID()); // get the target to teleport around.
// spellTimer->particleTimerVariable1 = 1; // distance of teleport in tiles
// spellTimer->particleTimerVariable2 = monsterInteracting->getUID(); // which player to teleport
// if ( multiplayer == SERVER )
// {
// serverSpawnMiscParticles(this, PARTICLE_EFFECT_SHRINE_TELEPORT, 625);
// }
// shrineActivateDelay = 250;
// serverUpdateEntitySkill(this, 7);
// }
// }
// this->clearMonsterInteract();
// return;
// }
// this->clearMonsterInteract();
//}
for ( int i = 0; i < MAXPLAYERS; i++ )
{
if ( selectedEntity[i] == this || client_selected[i] == this )
{
if ( inrange[i] && Player::getPlayerInteractEntity(i) )
{
if ( shrineActivateDelay > 0 )
{
messagePlayer(i, MESSAGE_INTERACTION, Language::get(4300));
break;
}
daedalusShrineInteract(this, Player::getPlayerInteractEntity(i));
Compendium_t::Events_t::eventUpdateWorld(i, Compendium_t::CPDM_DAED_USES, "daedalus", 1);
shrineActivateDelay = TICKS_PER_SECOND * 5;
serverUpdateEntitySkill(this, 7);
break;
}
}
}
}
void actAssistShrine(Entity* my)
{
if ( !my )
{
return;
}
my->actAssistShrine();
}
void Entity::actAssistShrine()
{
if ( this->ticks == 1 )
{
this->createWorldUITooltip();
}
this->removeLightField();
#ifdef USE_FMOD
if ( shrineAmbience == 0 )
{
shrineAmbience--;
stopEntitySound();
entity_sound = playSoundEntityLocal(this, 149, 16);
}
if ( entity_sound )
{
bool playing = false;
entity_sound->isPlaying(&playing);
if ( !playing )
{
entity_sound = nullptr;
}
}
#else
shrineAmbience--;
if ( shrineAmbience <= 0 )
{
shrineAmbience = TICKS_PER_SECOND * 30;
playSoundEntityLocal(this, 149, 16);
}
#endif
if ( !shrineInit )
{
shrineInit = 1;
}
Sint32& shrineInteracting = this->skill[0];
Uint32 numFlames = 0;
Uint32 redFlames = 0;
Entity* interacting = uidToEntity(shrineInteracting);
if ( interacting && interacting->behavior == &actPlayer )
{
redFlames |= (1 << interacting->skill[2]);
numFlames |= (1 << interacting->skill[2]);
}
for ( int i = 0; i < MAXPLAYERS; ++i )
{
if ( !client_disconnected[i] )
{
if ( stats[i]->MISC_FLAGS[STAT_FLAG_ASSISTANCE_PLAYER_PTS] > 0 )
{
numFlames |= (1 << i);
}
}
}
static ConsoleVariable<float> cvar_assist_flame_x1("/assist_flame_x1", 0.5);
static ConsoleVariable<float> cvar_assist_flame_y1("/assist_flame_y1", -3.f);
static ConsoleVariable<float> cvar_assist_flame_x2("/assist_flame_x2", -1.f);
static ConsoleVariable<float> cvar_assist_flame_y2("/assist_flame_y2", -1.f);
static ConsoleVariable<float> cvar_assist_flame_x3("/assist_flame_x3", -1.f);
static ConsoleVariable<float> cvar_assist_flame_y3("/assist_flame_y3", -3.5);
static ConsoleVariable<float> cvar_assist_flame_x4("/assist_flame_x4", 0.5);
static ConsoleVariable<float> cvar_assist_flame_y4("/assist_flame_y4", -1.f);
static ConsoleVariable<float> cvar_assist_flame_z1("/assist_flame_z1", 6.5);
static ConsoleVariable<float> cvar_assist_flame_z2("/assist_flame_z2", 9.f);
static ConsoleVariable<float> cvar_assist_flame_z3("/assist_flame_z3", 6.5);
static ConsoleVariable<float> cvar_assist_flame_z4("/assist_flame_z4", 10.f);
const int spriteCandle = 202;
const int spriteCandleBlue = 203;
if ( numFlames > 0 && ( flickerLights || this->ticks % TICKS_PER_SECOND == 1 ) )
{
Entity* entity = nullptr;
if ( numFlames & (1 << 3) )
{
if ( entity = spawnFlame(this, redFlames & (1 << 3) ? spriteCandle : spriteCandleBlue) )
{
entity->x += *cvar_assist_flame_x4 * cos(this->yaw);
entity->y += *cvar_assist_flame_x4 * sin(this->yaw);
entity->x += *cvar_assist_flame_y4 * cos(this->yaw + PI / 2);
entity->y += *cvar_assist_flame_y4 * sin(this->yaw + PI / 2);
entity->z -= *cvar_assist_flame_z4;
entity->flags[GENIUS] = false;
entity->setUID(-3);
}
}
if ( numFlames & (1 << 2) )
{
if ( entity = spawnFlame(this, redFlames & (1 << 2) ? spriteCandle : spriteCandleBlue) )
{
entity->x += *cvar_assist_flame_x3 * cos(this->yaw);
entity->y += *cvar_assist_flame_x3 * sin(this->yaw);
entity->x += *cvar_assist_flame_y3 * cos(this->yaw + PI / 2);
entity->y += *cvar_assist_flame_y3 * sin(this->yaw + PI / 2);
entity->z -= *cvar_assist_flame_z3;
entity->flags[GENIUS] = false;
entity->setUID(-3);
}
}
if ( numFlames & (1 << 1) )
{
if ( entity = spawnFlame(this, redFlames & (1 << 1) ? spriteCandle : spriteCandleBlue) )
{
entity->x += *cvar_assist_flame_x2 * cos(this->yaw);
entity->y += *cvar_assist_flame_x2 * sin(this->yaw);
entity->x += *cvar_assist_flame_y2 * cos(this->yaw + PI / 2);
entity->y += *cvar_assist_flame_y2 * sin(this->yaw + PI / 2);
entity->z -= *cvar_assist_flame_z2;
entity->flags[GENIUS] = false;
entity->setUID(-3);
}
}
if ( numFlames & (1 << 0) )
{
if ( entity = spawnFlame(this, redFlames & (1 << 0) ? spriteCandle : spriteCandleBlue) )
{
entity->x += *cvar_assist_flame_x1 * cos(this->yaw);
entity->y += *cvar_assist_flame_x1 * sin(this->yaw);
entity->x += *cvar_assist_flame_y1 * cos(this->yaw + PI / 2);
entity->y += *cvar_assist_flame_y1 * sin(this->yaw + PI / 2);
entity->z -= *cvar_assist_flame_z1;
entity->flags[GENIUS] = false;
entity->setUID(-3);
}
}
if ( redFlames )
{
this->light = addLight(this->x / 16, this->y / 16, "assist_shrine_red");
}
else
{
std::string lightname = "assist_shrine_flame";
int flames = 0;
for ( int i = 0; i < MAXPLAYERS; ++i )
{
if ( numFlames & (1 << i) )
{
++flames;
}
}
lightname += std::to_string(std::min(MAXPLAYERS, flames));
this->light = addLight(this->x / 16, this->y / 16, lightname.c_str());
}
}
else
{
this->light = addLight(this->x / 16, this->y / 16, "assist_shrine");
}
if ( multiplayer == CLIENT )
{
return;
}
if ( shrineInteracting > 0 )
{
if ( !interacting || (entityDist(interacting, this) > TOUCHRANGE) )
{
int playernum = -1;
if ( !interacting )
{
for ( int i = 0; i < MAXPLAYERS; ++i )
{
if ( achievementObserver.playerUids[i] == shrineInteracting )
{
playernum = i;
break;
}
}
}
else if ( interacting->behavior == &actPlayer )
{
playernum = interacting->skill[2];
}
shrineInteracting = 0;
serverUpdateEntitySkill(this, 0);
if ( multiplayer == SERVER && playernum > 0 )
{
strcpy((char*)net_packet->data, "ASCL");
net_packet->data[4] = playernum;
SDLNet_Write32(this->getUID(), &net_packet->data[5]);
net_packet->address.host = net_clients[playernum - 1].host;
net_packet->address.port = net_clients[playernum - 1].port;
net_packet->len = 9;
sendPacketSafe(net_sock, -1, net_packet, playernum - 1);
}
else if ( multiplayer == SINGLE || playernum == 0 )
{
GenericGUI[playernum].assistShrineGUI.closeAssistShrine();
}
}
}
// using
for ( int i = 0; i < MAXPLAYERS; i++ )
{
if ( selectedEntity[i] == this || client_selected[i] == this )
{
if ( inrange[i] && players[i]->entity )
{
if ( shrineInteracting != 0 )
{
if ( Entity* interacting = uidToEntity(shrineInteracting) )
{
if ( interacting != players[i]->entity )
{
messagePlayer(i, MESSAGE_INTERACTION, Language::get(6351));
}
}
}
else
{
shrineInteracting = players[i]->entity->getUID();
if ( multiplayer == SERVER )
{
serverUpdateEntitySkill(this, 0);
}
if ( players[i]->isLocalPlayer() )
{
GenericGUI[i].openGUI(GUI_TYPE_ASSIST, this);
}
else if ( multiplayer == SERVER && i > 0 )
{
strcpy((char*)net_packet->data, "ASSO");
SDLNet_Write32(this->getUID(), &net_packet->data[4]);
net_packet->address.host = net_clients[i - 1].host;
net_packet->address.port = net_clients[i - 1].port;
net_packet->len = 8;
sendPacketSafe(net_sock, -1, net_packet, i - 1);
}
}
break;
}
}
}
} | 0 | 0.954641 | 1 | 0.954641 | game-dev | MEDIA | 0.94695 | game-dev | 0.994747 | 1 | 0.994747 |
defparam/higan-verilog | 1,330 | higan/target-tomoko/program/state.cpp | auto Program::stateName(uint slot, bool managed) -> string {
return {
mediumPaths(1), "higan/states/",
managed ? "managed/" : "quick/",
"slot-", slot, ".bst"
};
}
auto Program::loadState(uint slot, bool managed) -> bool {
if(!emulator) return false;
string type = managed ? "managed" : "quick";
auto location = stateName(slot, managed);
auto memory = file::read(location);
if(memory.size() == 0) return showMessage({"Slot ", slot, " ", type, " state does not exist"}), false;
serializer s(memory.data(), memory.size());
if(emulator->unserialize(s) == false) return showMessage({"Slot ", slot, " ", type, " state incompatible"}), false;
return showMessage({"Loaded ", type, " state from slot ", slot}), true;
}
auto Program::saveState(uint slot, bool managed) -> bool {
if(!emulator) return false;
string type = managed ? "managed" : "quick";
auto location = stateName(slot, managed);
serializer s = emulator->serialize();
if(s.size() == 0) return showMessage({"Failed to save ", type, " state to slot ", slot}), false;
directory::create(Location::path(location));
if(file::write(location, s.data(), s.size()) == false) {
return showMessage({"Unable to write ", type, " state to slot ", slot}), false;
}
return showMessage({"Saved ", type, " state to slot ", slot}), true;
}
| 0 | 0.768969 | 1 | 0.768969 | game-dev | MEDIA | 0.561239 | game-dev,desktop-app | 0.724796 | 1 | 0.724796 |
Open-RSC/Core-Framework | 2,131 | server/plugins/com/openrsc/server/plugins/authentic/npcs/alkharid/ZekeScimitars.java | package com.openrsc.server.plugins.authentic.npcs.alkharid;
import com.openrsc.server.constants.ItemId;
import com.openrsc.server.constants.NpcId;
import com.openrsc.server.constants.Quests;
import com.openrsc.server.model.Shop;
import com.openrsc.server.model.container.Item;
import com.openrsc.server.model.entity.npc.Npc;
import com.openrsc.server.model.entity.player.Player;
import com.openrsc.server.model.world.World;
import com.openrsc.server.net.rsc.ActionSender;
import com.openrsc.server.plugins.AbstractShop;
import static com.openrsc.server.plugins.Functions.*;
public final class ZekeScimitars extends AbstractShop {
private final Shop shop = new Shop(false, 25000, 100, 55, 2,
new Item(ItemId.BRONZE_SCIMITAR.id(), 5),
new Item(ItemId.IRON_SCIMITAR.id(), 3),
new Item(ItemId.STEEL_SCIMITAR.id(), 2),
new Item(ItemId.MITHRIL_SCIMITAR.id(), 1)
);
@Override
public boolean blockTalkNpc(final Player player, final Npc n) {
return n.getID() == NpcId.ZEKE.id();
}
@Override
public Shop[] getShops(World world) {
return new Shop[]{shop};
}
@Override
public boolean isMembers() {
return false;
}
@Override
public Shop getShop() {
return shop;
}
@Override
public void onTalkNpc(final Player player, final Npc n) {
final String[] options;
npcsay(player, n, player.getText("ZekeAThousandGreetings"));
if (player.getQuestStage(Quests.FAMILY_CREST) <= 2 || player.getQuestStage(Quests.FAMILY_CREST) >= 5) {
options = new String[]{
"Do you want to trade?",
"Nice cloak"
};
} else {
options = new String[]{
"Do you want to trade?",
"Nice cloak",
"I'm in search of a man named adam fitzharmon"
};
}
int option = multi(player, n, options);
if (option == 0) {
npcsay(player, n, "Yes, certainly", "I deal in scimitars");
player.setAccessingShop(shop);
ActionSender.showShop(player, shop);
} else if (option == 1) {
npcsay(player, n, "Thank you");
} else if (option == 2) {
npcsay(player, n, "I haven't seen him",
"I'm sure if he's been to Al Kharid recently",
"Someone around here will have seen him though");
}
}
}
| 0 | 0.891967 | 1 | 0.891967 | game-dev | MEDIA | 0.945482 | game-dev | 0.898572 | 1 | 0.898572 |
EphemeralSpace/ephemeral-space | 3,740 | Content.Shared/Implants/Components/ImplanterComponent.cs | using Content.Shared.Containers.ItemSlots;
using Content.Shared.Damage;
using Content.Shared.Whitelist;
using Robust.Shared.GameStates;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
namespace Content.Shared.Implants.Components;
/// <summary>
/// Implanters are used to implant or extract implants from an entity.
/// Some can be single use (implant only) or some can draw out an implant
/// </summary>
//TODO: Rework drawing to work with implant cases when surgery is in
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState(true)]
public sealed partial class ImplanterComponent : Component
{
public const string ImplanterSlotId = "implanter_slot";
public const string ImplantSlotId = "implant";
/// <summary>
/// Whitelist to check entities against before implanting.
/// Implants get their own whitelist which is checked afterwards.
/// </summary>
[DataField, AutoNetworkedField]
public EntityWhitelist? Whitelist;
/// <summary>
/// Blacklist to check entities against before implanting.
/// </summary>
[DataField, AutoNetworkedField]
public EntityWhitelist? Blacklist;
/// <summary>
/// Used for implanters that start with specific implants
/// </summary>
[DataField]
public EntProtoId? Implant;
/// <summary>
/// The time it takes to implant someone else
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField]
public float ImplantTime = 5f;
//TODO: Remove when surgery is a thing
/// <summary>
/// The time it takes to extract an implant from someone
/// It's excessively long to deter from implant checking any antag
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField]
public float DrawTime = 25f;
/// <summary>
/// Good for single-use injectors
/// </summary>
[DataField, AutoNetworkedField]
public bool ImplantOnly;
/// <summary>
/// The current mode of the implanter
/// Mode is changed automatically depending if it implants or draws
/// </summary>
[DataField, AutoNetworkedField]
public ImplanterToggleMode CurrentMode;
/// <summary>
/// The name and description of the implant to show on the implanter
/// </summary>
[DataField]
public (string, string) ImplantData;
/// <summary>
/// Determines if the same type of implant can be implanted into an entity multiple times.
/// </summary>
[DataField]
public bool AllowMultipleImplants = false;
/// <summary>
/// The <see cref="ItemSlot"/> for this implanter
/// </summary>
[DataField(required: true)]
public ItemSlot ImplanterSlot = new();
/// <summary>
/// If true, the implanter may be used to remove all kinds of (deimplantable) implants without selecting any.
/// </summary>
[DataField]
public bool AllowDeimplantAll = false;
/// <summary>
/// The subdermal implants that may be removed via this implanter
/// </summary>
[DataField]
public List<EntProtoId> DeimplantWhitelist = new();
/// <summary>
/// The subdermal implants that may be removed via this implanter
/// </summary>
[DataField]
public DamageSpecifier DeimplantFailureDamage = new();
/// <summary>
/// Chosen implant to remove, if necessary.
/// </summary>
[AutoNetworkedField]
public EntProtoId? DeimplantChosen = null;
public bool UiUpdateNeeded;
}
[Serializable, NetSerializable]
public enum ImplanterToggleMode : byte
{
Inject,
Draw
}
[Serializable, NetSerializable]
public enum ImplanterVisuals : byte
{
Full
}
[Serializable, NetSerializable]
public enum ImplanterImplantOnlyVisuals : byte
{
ImplantOnly
}
| 0 | 0.661755 | 1 | 0.661755 | game-dev | MEDIA | 0.497014 | game-dev | 0.507497 | 1 | 0.507497 |
aclements/sv6 | 1,622 | metis/lib/bsearch.c | #include "bsearch.h"
#define ELEM(idx) (base + size * (idx))
int
bsearch_lar(const void *key, const void *base, int nelems, size_t size,
bsearch_cmp_t keycmp)
{
if (!nelems)
return 0;
int res = keycmp(key, ELEM(nelems - 1));
if (res >= 0)
return nelems;
if (nelems == 1)
return 0;
if (nelems == 2) {
if (keycmp(key, ELEM(0)) < 0)
return 0;
return 1;
}
int left = 0;
int right = nelems - 2;
int mid;
while (left < right) {
mid = (left + right) / 2;
res = keycmp(key, ELEM(mid));
if (res >= 0)
left = mid + 1;
else if (res < 0)
right = mid - 1;
}
res = keycmp(key, ELEM(left));
if (res >= 0)
return left + 1;
return left;
}
int
bsearch_eq(const void *key, const void *base, int nelems, size_t size,
bsearch_cmp_t keycmp, int *bfound)
{
if (!nelems) {
*bfound = 0;
return 0;
}
int res = keycmp(key, ELEM(nelems - 1));
*bfound = 0;
if (!res) {
*bfound = 1;
return nelems - 1;
}
if (res > 0)
return nelems;
if (nelems == 1)
return 0;
if (nelems == 2) {
int res = keycmp(key, ELEM(0));
if (res == 0) {
*bfound = 1;
return 0;
}
if (res < 0)
return 0;
return 1;
}
int left = 0;
int right = nelems - 2;
int mid;
while (left < right) {
mid = (left + right) / 2;
res = keycmp(key, ELEM(mid));
if (!res) {
*bfound = 1;
return mid;
} else if (res < 0)
right = mid - 1;
else
left = mid + 1;
}
res = keycmp(key, ELEM(left));
if (!res) {
*bfound = 1;
return left;
}
if (res > 0)
return left + 1;
return left;
}
| 0 | 0.941024 | 1 | 0.941024 | game-dev | MEDIA | 0.433103 | game-dev | 0.980736 | 1 | 0.980736 |
xfw5/Fear-SDK-1.08 | 61,637 | Game/ObjectDLL/PlayerInventory.cpp |
// ----------------------------------------------------------------------- //
//
// MODULE : PlayerInventory.cpp
//
// PURPOSE : Provides a layer to manage the player's limited weapon capacity
//
// CREATED : 11/21/03
//
// (c) 2003 Monolith Productions, Inc. All Rights Reserved
// ----------------------------------------------------------------------- //
#include "Stdafx.h"
#include "PlayerInventory.h"
#include "PickupItem.h"
#include "PlayerObj.h"
#include "ObjectMsgs.h"
#include "WeaponItems.h"
#include "AmmoBox.h"
#include "WeaponDB.h"
#include "ServerMissionMgr.h"
#include "Weapon.h"
#include "Spawner.h"
#include "SkillDefs.h"
#include <vector>
#include "GameModeMgr.h"
#include "ServerDB.h"
#include "SlowMoDB.h"
#include "NavMarker.h"
#include "NavMarkerTypeDB.h"
static VarTrack s_vtWeaponDropImpulse;
static VarTrack s_vtWeaponDropVel;
static VarTrack s_vtWeaponDropLockout;
CPlayerInventory::CPlayerInventory() :
m_pPlayer(NULL),
m_pArsenal(NULL),
m_hUnarmed(NULL),
m_nWeaponCapacity(0),
m_fSlowMoCharge(0.0f),
m_fSlowMoMaxCharge(0.0f),
m_bSlowMoPlayerControlled(false),
m_fSlowMoRechargeRate(0.0f),
m_hSlowMoRecord( NULL ),
m_hSlowMoGearObject( NULL ),
m_hSlowMoGearRecord( NULL ),
m_bUpdateCharge( true ),
m_hSlowMoNavMarker( NULL ),
m_hEnemySlowMoNavMarker( NULL ),
m_hFlagNavMarker( NULL )
{
}
CPlayerInventory::~CPlayerInventory()
{
RemoveSlowMoNavMarker( );
//remove any old nav marker
if( m_hFlagNavMarker )
{
g_pLTServer->RemoveObject( m_hFlagNavMarker );
m_hFlagNavMarker = NULL;
}
// Respawn the slowmo gearitem if we cached one...
if( m_hSlowMoGearObject )
{
g_pCmdMgr->QueueMessage( NULL, m_hSlowMoGearObject, "RESPAWN" );
m_hSlowMoGearObject = NULL;
}
}
void CPlayerInventory::Init(CPlayerObj* pPlayer)
{
LTASSERT(pPlayer,"Player inventory initialized without a player.");
m_pPlayer = pPlayer;
if (pPlayer)
m_pArsenal = pPlayer->GetArsenal();
//set up our gear array
uint8 nNumGear = g_pWeaponDB->GetNumGear();
m_vecGearCount.clear();
m_vecGearCount.insert(m_vecGearCount.begin(),nNumGear,0);
m_vecPriorities.clear();
m_vecPriorities.reserve(g_pWeaponDB->GetNumDefaultWeaponPriorities());
for (uint8 nWpn = 0; nWpn < g_pWeaponDB->GetNumDefaultWeaponPriorities(); ++nWpn)
{
HWEAPON hWpn = g_pWeaponDB->GetWeaponFromDefaultPriority(nWpn);
m_vecPriorities.push_back(hWpn);
}
if( IsMultiplayerGameServer( ))
{
m_hSlowMoRecord = g_pServerDB->GetPlayerRecordLink( SrvDB_rMPSlowMo );
}
else
{
m_hSlowMoRecord = g_pServerDB->GetPlayerRecordLink(SrvDB_rSlowMo);
}
m_fSlowMoCharge = 0.0f;
m_fSlowMoMaxCharge = GETCATRECORDATTRIB( SlowMo, m_hSlowMoRecord, Period );
m_bSlowMoPlayerControlled = false;
m_fSlowMoRechargeRate = GETCATRECORDATTRIB( SlowMo, m_hSlowMoRecord, RechargeRate );
m_bUpdateCharge = true;
SendSlowMoValuesToClient( );
if(!s_vtWeaponDropImpulse.IsInitted())
s_vtWeaponDropImpulse.Init(g_pLTServer, "WeaponDropImpulse", NULL, g_pServerDB->GetPlayerFloat("WeaponDropImpulse"));
if(!s_vtWeaponDropVel.IsInitted())
s_vtWeaponDropVel.Init(g_pLTServer, "WeaponDropVelocity", NULL, g_pServerDB->GetPlayerFloat("WeaponDropVelocity"));
if(!s_vtWeaponDropLockout.IsInitted())
s_vtWeaponDropLockout.Init(g_pLTServer, "WeaponDropLockoutTime", NULL, g_pServerDB->GetPlayerFloat("WeaponDropLockoutTime"));
}
void CPlayerInventory::Reset()
{
m_hUnarmed = NULL;
ClearWeaponSlots();
m_pArsenal->Reset();
SendSlowMoValuesToClient( );
}
void CPlayerInventory::Update()
{
if (g_pGameServerShell->IsInSlowMo() && IsSlowMoPlayerControlled() && m_bUpdateCharge )
{
float fDischarge = GameTimeTimer::Instance().GetTimerElapsedS();
m_fSlowMoCharge = LTMAX(0.0f,m_fSlowMoCharge - fDischarge);
}
else
{
float fRecharge = GameTimeTimer::Instance().GetTimerElapsedS() * m_fSlowMoRechargeRate;
m_fSlowMoCharge = LTMIN(m_fSlowMoMaxCharge,m_fSlowMoCharge + fRecharge);
}
}
void CPlayerInventory::RemoveWeapons()
{
m_hUnarmed = NULL;
ClearWeaponSlots();
m_pArsenal->RemoveAllActiveWeapons( );
}
void CPlayerInventory::SetCapacity(uint8 nCap)
{
//TODO: deal with setting weapon cpacity to less than current number held
LTASSERT(nCap >= m_vecWeapons.size(),"Inventory Capacity set to less than current weapon count.");
if (nCap < m_vecWeapons.size())
return;
if (nCap > m_nWeaponCapacity)
{
m_nWeaponCapacity = nCap;
m_vecWeapons.resize(m_nWeaponCapacity,(HWEAPON)NULL);
}
SendWeaponCapacityToClient( );
}
void CPlayerInventory::SendWeaponCapacityToClient( )
{
//notify client
HCLIENT hClient = m_pPlayer->GetClient();
if (hClient)
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_INFOCHANGE);
cMsg.Writeuint8(IC_WEAPONCAP_ID);
cMsg.Writeuint8(m_nWeaponCapacity);
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
}
}
void CPlayerInventory::OnObtainClient( )
{
SendWeaponCapacityToClient( );
SendSlowMoValuesToClient( );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandlePickupMsg
//
// PURPOSE: Handle messages from pickup items
//
// ----------------------------------------------------------------------- //
uint32 CPlayerInventory::HandlePickupMsg(HOBJECT hSender, ILTMessage_Read *pMsg)
{
bool bPickedUp = false;
pMsg->SeekTo(0);
uint32 messageID = pMsg->Readuint32();
switch(messageID)
{
case MID_ADDWEAPON:
{
bPickedUp = PickupWeapon( hSender, pMsg );
}
break;
case MID_AMMOBOX:
{
bPickedUp = PickupAmmoBox( hSender, pMsg );
}
break;
case MID_ADDMOD:
{
bPickedUp = PickupMod( hSender, pMsg );
}
break;
case MID_ADDGEAR:
{
bPickedUp = PickupGear( hSender, pMsg );
}
break;
default : break;
}
if (!bPickedUp)
{
CAutoMessage cMsg;
cMsg.Writeuint32(MID_PICKEDUP);
cMsg.Writebool( false );
cMsg.Writebool( false );
g_pLTServer->SendToObject(cMsg.Read(), m_pPlayer->m_hObject, hSender, MESSAGE_GUARANTEED);
return 0;
}
return 1;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::PickupWeapon
//
// PURPOSE: Try to pickup a weapon item
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::PickupWeapon( HOBJECT hSender, ILTMessage_Read *pMsg )
{
HWEAPON hWeapon = pMsg->ReadDatabaseRecord( g_pLTDatabase, g_pWeaponDB->GetWeaponsCategory() );
HAMMO hAmmo = pMsg->ReadDatabaseRecord( g_pLTDatabase, g_pWeaponDB->GetAmmoCategory() );
int nAmmo = pMsg->Readint32();
bool bWillRespawn = pMsg->Readbool();
uint32 nHealth = pMsg->Readuint32();
bool bWasPlaced = pMsg->Readbool();
HOBJECT hDroppedBy = pMsg->ReadObject();
if( !hWeapon || !hAmmo )
return false;
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
HAMMODATA hAmmoData = g_pWeaponDB->GetAmmoData( hAmmo, !USE_AI_DATA );
bool bPickedUp = false;
bool bTakesInventorySlot = g_pWeaponDB->GetBool(hWpnData,WDB_WEAPON_bTakesInventorySlot);
bool bIsAmmo = g_pWeaponDB->GetBool(hWpnData,WDB_WEAPON_bIsAmmo);
bool bHasWeapon = HaveWeapon(hWeapon);
bool bWeaponsStay = IsMultiplayerGameServer( ) && GameModeMgr::Instance( ).m_grbWeaponsStay;
if (hDroppedBy == m_pPlayer->m_hObject)
{
PickupItem *pPickupItem = dynamic_cast<PickupItem*>(g_pLTServer->HandleToObject( hSender ));
if (pPickupItem)
{
double fElapsedTime = SimulationTimer::Instance().GetTimerAccumulatedS() - pPickupItem->DropTime();
if (fElapsedTime < s_vtWeaponDropLockout.GetFloat())
{
return false;
}
}
}
// In multiplayer the weapon should already have the correct amount...
// If it was dropped by this player, the amount will also be set correctly already
if( !IsMultiplayerGameServer( ) && (hDroppedBy != m_pPlayer->m_hObject))
{
// In singleplayer use the initial amount if they do not have the weapon already and the weapon was placed
// or dropped by someone else
if (!bHasWeapon)
{
nAmmo = g_pWeaponDB->GetInt32( hAmmoData, WDB_AMMO_nPickupInitialAmount );
}
else if (!bWasPlaced)
{
// use supplemental ammo amount if the player already has the weapon and the weapon was dropped (i.e. not placed by LD)
nAmmo = g_pWeaponDB->GetInt32( hAmmoData, WDB_AMMO_nPickupSupplementalAmount );
}
}
// Does this weapon support dual weapons...
HWEAPON hDualWeapon = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rDualWeapon );
if( hDualWeapon )
{
bool bHasDualVersion = HaveWeapon(hDualWeapon);
if( bHasWeapon )
{
if( bHasDualVersion )
{
LTERROR( "Dual can only be aquired from picking up two single weaopns" );
return false;
}
// Keep the current ammo amount...
nAmmo += m_pArsenal->GetAmmoCount( hAmmo );
// Remove single version of the weapon...
// NOTE: This will free a weapon slot so there is room to acquire the new dual version below.
RemoveWeapon( hWeapon, false );
// Acquire the dual weapon...
hWeapon = hDualWeapon;
bHasWeapon = false;
}
else if( bHasDualVersion )
{
// If we don't have the weapon, but we do have it's dual version, just add the ammo
hWeapon = hDualWeapon;
bHasWeapon = true;
}
}
if (bHasWeapon && bWeaponsStay && bWillRespawn)
return false;
//if we have too many weapons, or it doesn't take a slot
uint8 nSlot = GetWeaponSlot(hWeapon);
if (nSlot == WDB_INVALID_WEAPON_INDEX)
nSlot = FindFirstEmptySlot();
if ( bHasWeapon || nSlot != WDB_INVALID_WEAPON_INDEX || !bTakesInventorySlot)
{
bPickedUp = m_pArsenal->AddWeapon( hSender, hWeapon, hAmmo, nAmmo, nHealth, nSlot );
//if this is a newly acquired weapon...
if (bPickedUp && bTakesInventorySlot && !bHasWeapon)
{
m_vecWeapons[nSlot] = hWeapon;
}
}
if( bPickedUp)
{
// Tell weapon powerup it was picked up...
CAutoMessage cMsg;
cMsg.Writeuint32(MID_PICKEDUP);
cMsg.Writebool( true );
cMsg.Writebool( bWeaponsStay && bWillRespawn && !bIsAmmo );
g_pLTServer->SendToObject(cMsg.Read(), m_pPlayer->m_hObject, hSender, MESSAGE_GUARANTEED);
// Tell the client whether this weapon is weak (eg: hud indicator)
uint32 nWarnHealth = g_pWeaponDB->GetInt32(hWpnData, WDB_WEAPON_nWarnHealth);
if( nWarnHealth > 0 )
{
HCLIENT hClient = m_pPlayer->GetClient();
if( hClient )
{
CAutoMessage cMsg;
cMsg.Writeuint8( MID_WEAPON_BREAK_WARN );
cMsg.WriteDatabaseRecord( g_pLTDatabase, hWeapon );
cMsg.Writebool(nHealth <= nWarnHealth);
g_pLTServer->SendToClient( cMsg.Read(), hClient, MESSAGE_GUARANTEED );
}
}
//see if there's another weapon we're supposed to get at the same time...
HWEAPON hLinkedWeapon = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rLinkedWeapon );
if( hLinkedWeapon && !m_pArsenal->HasWeapon(hLinkedWeapon) )
{
AcquireWeapon(hLinkedWeapon,NULL,-1,true);
}
}
return bPickedUp;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::PickupAmmoBox
//
// PURPOSE: Collect ammo from a box
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::PickupAmmoBox( HOBJECT hSender, ILTMessage_Read *pMsg )
{
uint8 nAmmoIdsLeft = 0;
uint8 nNumUniqueAmmo = pMsg->Readuint8();
HAMMO hAmmo[AB_MAX_TYPES];
int32 nAmmo[AB_MAX_TYPES];
int32 nTaken[AB_MAX_TYPES];
bool bTookAmmo = false;
uint8 i;
for( i = 0; i < nNumUniqueAmmo; ++i )
{
hAmmo[i] = pMsg->ReadDatabaseRecord( g_pLTDatabase, g_pWeaponDB->GetAmmoCategory() );
nAmmo[i] = pMsg->Readuint32();
nTaken[i] = 0;
if( hAmmo[i] )
{
//verify that we have a weapon that uses this ammo
if (m_pArsenal->CanUseAmmo(hAmmo[i]))
{
nTaken[i] = m_pArsenal->AddAmmo( hAmmo[i], nAmmo[i] );
HAMMODATA hAmmoData = g_pWeaponDB->GetAmmoData(hAmmo[i],false);
if( g_pWeaponDB->GetInt32( hAmmoData, WDB_AMMO_nSelectionAmount ) >= 1000 )
nTaken[i] = nAmmo[i];
}
if( nTaken[i] > 0 )
{
bTookAmmo = true;
}
if( nTaken[i] < nAmmo[i] )
{
++nAmmoIdsLeft;
}
nAmmo[i] -= nTaken[i];
}
}
if( nAmmoIdsLeft )
{
// Tell powerup what is left in the box...If we actually
// took something...
if( bTookAmmo )
{
CAutoMessage cMsg;
cMsg.Writeuint32(MID_AMMOBOX);
cMsg.Writeuint8(nNumUniqueAmmo);
for( i = 0; i < nNumUniqueAmmo; ++i )
{
cMsg.WriteDatabaseRecord( g_pLTDatabase, hAmmo[i] );
cMsg.Writeint32( nAmmo[i] );
}
g_pLTServer->SendToObject( cMsg.Read(), m_pPlayer->m_hObject, hSender, MESSAGE_GUARANTEED );
}
}
else
{
// Tell ammo powerup it was picked up...
CAutoMessage cMsg;
cMsg.Writeuint32(MID_PICKEDUP);
cMsg.Writebool( true );
cMsg.Writebool( false );
g_pLTServer->SendToObject(cMsg.Read(), m_pPlayer->m_hObject, hSender, MESSAGE_GUARANTEED);
}
// Send the appropriate message to the client...
if( !m_pPlayer )
return false;
HCLIENT hClient = m_pPlayer->GetClient();
if( hClient )
{
for( i = 0; i < nNumUniqueAmmo; ++i )
{
if( hAmmo[i] )
{
if( !AddIsAmmoWeapon( hAmmo[i], nTaken[i] ))
{
// Normal method of picking up ammo...
if (nTaken[i])
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_INFOCHANGE);
cMsg.Writeuint8(IC_WEAPON_PICKUP_ID);
cMsg.WriteDatabaseRecord( g_pLTDatabase, NULL );
cMsg.WriteDatabaseRecord( g_pLTDatabase, hAmmo[i] );
cMsg.Writeuint32(m_pArsenal->GetAmmoCount( hAmmo[i] ));
cMsg.Writeuint8( WDB_INVALID_WEAPON_INDEX );
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
}
}
}
}
}
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AddIsAmmoWeapon
//
// PURPOSE: Add an IsAmmo type weapon if necessary...
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AddIsAmmoWeapon(HAMMO hAmmo, uint32 nTaken )
{
if( !hAmmo )
return false;
// If this ammo type is used by an IsAmmo weapon give us the weapon
HWEAPON hWeapon = g_pWeaponDB->GetWeaponFromAmmo( hAmmo, !USE_AI_DATA );
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
if( hWeapon && g_pWeaponDB->GetBool( hWpnData, WDB_WEAPON_bIsAmmo ))
{
bool bAcquired = !m_pArsenal->HasWeapon(hWeapon);
if (bAcquired)
{
m_pArsenal->ObtainWeapon(hWeapon, hAmmo, nTaken, true );
//see if there's another weapon we're supposed to get at the same time...
HWEAPON hLinkedWeapon = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rLinkedWeapon );
if( hLinkedWeapon && !m_pArsenal->HasWeapon(hLinkedWeapon) )
{
AcquireWeapon(hLinkedWeapon, NULL, -1, true);
}
//notify client
HCLIENT hClient = m_pPlayer->GetClient();
if (hClient)
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_INFOCHANGE);
cMsg.Writeuint8(IC_WEAPON_PICKUP_ID);
cMsg.WriteDatabaseRecord( g_pLTDatabase, hWeapon );
cMsg.WriteDatabaseRecord( g_pLTDatabase, hAmmo );
cMsg.Writeuint32(m_pArsenal->GetAmmoCount( hAmmo ));
cMsg.Writeuint8(GetWeaponSlot(hWeapon));
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
}
}
return bAcquired;
}
return false;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::PickupMod
//
// PURPOSE: Try to pickup a weapon mod
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::PickupMod( HOBJECT hSender, ILTMessage_Read *pMsg )
{
bool bRet = false;
HMOD hMod = pMsg->ReadDatabaseRecord( g_pLTDatabase, g_pWeaponDB->GetModsCategory() );
if( hMod )
{
HWEAPON hWeapon = g_pWeaponDB->GetWeaponFromMod( hMod, !USE_AI_DATA );
bool bPickedUp = false;
if (m_pArsenal->HasWeapon(hWeapon))
{
// Check to see if we already have the mod...
if( !m_pArsenal->HasMod(hWeapon, hMod ))
{
m_pArsenal->ObtainMod( hWeapon, hMod );
bPickedUp = true;
}
bRet = true;
}
if (bPickedUp)
{
// Tell mod powerup if it was picked up...
CAutoMessage cMsg;
cMsg.Writeuint32(MID_PICKEDUP);
cMsg.Writebool(true);
cMsg.Writebool( false );
g_pLTServer->SendToObject(cMsg.Read(), m_pPlayer->m_hObject, hSender, MESSAGE_GUARANTEED);
}
}
return bRet;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleCheatWeapon
//
// PURPOSE: Do the single weapon cheat for the player
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::HandleCheatWeapon( HWEAPON hWeapon )
{
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
bool bTakesSlot = g_pWeaponDB->GetBool(hWpnData,WDB_WEAPON_bTakesInventorySlot);
bool bHas = HaveWeapon(hWeapon);
//if the weapon takes a slot and we don't have one...
uint8 nSlot = FindFirstEmptySlot();
if (bTakesSlot && !bHas && nSlot != WDB_INVALID_WEAPON_INDEX )
{
//pick a weapon to drop
HWEAPON hWeaponToDrop = m_pArsenal->GetCurWeaponRecord();
//we can't drop our fists...
if (hWeaponToDrop == m_hUnarmed)
{
hWeaponToDrop = GetLowestPriorityWeapon();
}
LTVector vPos;
LTRotation rRot;
g_pLTServer->GetObjectPos(m_pPlayer->m_hObject,&vPos);
g_pLTServer->GetObjectRotation(m_pPlayer->m_hObject,&rRot);
rRot.Rotate(rRot.Up( ),GetRandom(-1.0f,1.0f));
vPos += (rRot.Up() * 50.0f);
DropWeapon( hWeaponToDrop, vPos, rRot, m_pPlayer->GetLastVelocity() );
}
return AcquireWeapon(hWeapon,NULL,10000,true);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleCheatFullWeapon
//
// PURPOSE: Do the full weapon cheat for the player
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::HandleCheatFullWeapon()
{
uint8 nNumWeapons = g_pWeaponDB->GetNumPlayerWeapons();
SetCapacity(nNumWeapons);
for( uint8 nWeapon = 0; nWeapon < nNumWeapons; ++nWeapon )
{
HWEAPON hWeapon = g_pWeaponDB->GetPlayerWeapon( nWeapon );
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
HWEAPON hDualWeapon = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rDualWeapon );
if( hDualWeapon )
{
//if there's a dual version, skip the single version weapon
continue;
}
AcquireWeapon(hWeapon,NULL,10000,true);
}
HandleCheatFullAmmo();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleCheatFullAmmo
//
// PURPOSE: Do the full ammo cheat for the player
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::HandleCheatFullAmmo()
{
uint8 nNumAmmoTypes = g_pWeaponDB->GetNumAmmo();
for( uint8 nAmmo = 0; nAmmo < nNumAmmoTypes; ++nAmmo )
{
HAMMO hAmmo = g_pWeaponDB->GetAmmoRecord( nAmmo );
AcquireAmmo( hAmmo );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleCheatFullMods
//
// PURPOSE: Do the full mod cheat for the player
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::HandleCheatFullMods()
{
uint8 nNumWeapons = g_pWeaponDB->GetNumWeapons();
for( uint8 nWeapon = 0 ; nWeapon < nNumWeapons ; ++nWeapon )
{
HWEAPON hWeapon = g_pWeaponDB->GetWeaponRecord( nWeapon );
if( hWeapon )
{
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
uint8 nNumMods = ( uint8 )LTMIN( g_pWeaponDB->GetNumValues( hWpnData, WDB_WEAPON_rModName ), 255 );
for( uint8 nMod = 0; nMod < nNumMods; ++nMod )
{
HMOD hMod = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rModName, nMod );
if( hMod )
{
m_pArsenal->ObtainMod( hWeapon, hMod, true );
}
}
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleCheatFullGear
//
// PURPOSE: Do the full gear cheat for the player
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::HandleCheatFullGear()
{
uint8 nNumGear = g_pWeaponDB->GetNumGear();
for( uint8 nGear = 0 ; nGear < nNumGear ; ++nGear )
{
HGEAR hGear = g_pWeaponDB->GetGearRecord( nGear );
if( hGear )
{
AcquireGear(hGear);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AcquireDefaultWeapon
//
// PURPOSE: Obtain the default weapon for the player
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AcquireDefaultWeapon(HWEAPON hWeapon)
{
if( !hWeapon || !g_pWeaponDB->IsPlayerWeapon( hWeapon ))
return false;
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
HAMMO hAmmo = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rAmmoName ) ;
if( !hAmmo )
return false;
HAMMODATA hAmmoData = g_pWeaponDB->GetAmmoData(hAmmo,false);
uint32 nAmount = g_pWeaponDB->GetInt32( hAmmoData, WDB_AMMO_nSelectionAmount );
if( hWeapon == g_pWeaponDB->GetUnarmedRecord() )
{
m_hUnarmed = hWeapon;
}
return AcquireWeapon(hWeapon,hAmmo,nAmount,true);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AcquireWeapon
//
// PURPOSE: Obtain the specified weapon for the player
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AcquireWeapon(HWEAPON hWeapon, HAMMO hAmmo /* = NULL */, int32 nAmmo /* = -1 */, bool bNotifyClient /* = false */)
{
if( !hWeapon || !g_pWeaponDB->IsPlayerWeapon( hWeapon ))
{
LTERROR( "Invalid weapon for player." );
return false;
}
// DebugCPrint(0,"CPlayerInventory::AcquireWeapon - %s",g_pWeaponDB->GetRecordName(hWeapon));
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
//no ammo specified, try the default
if (!hAmmo)
hAmmo = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rAmmoName ) ;
//still no ammo? abort
if( !hAmmo )
{
LTERROR( "Invalid ammo." );
return false;
}
bool bAcquired = false;
bool bTakesSlot = g_pWeaponDB->GetBool(hWpnData,WDB_WEAPON_bTakesInventorySlot);
bool bHas = HaveWeapon(hWeapon);
//if we have a free slot, or we don't need one for this weapon...
uint8 nSlot = FindFirstEmptySlot();
if (nSlot != WDB_INVALID_WEAPON_INDEX || !bTakesSlot)
{
bAcquired = true;
//if this is a newly acquired weapon...
if (bTakesSlot && !bHas)
m_vecWeapons[nSlot] = hWeapon;
m_pArsenal->ObtainWeapon(hWeapon, hAmmo, nAmmo, bNotifyClient );
//see if there's another weapon we're supposed to get at the same time...
HWEAPON hLinkedWeapon = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rLinkedWeapon );
if( hLinkedWeapon && !m_pArsenal->HasWeapon(hLinkedWeapon) )
{
AcquireWeapon(hLinkedWeapon, NULL, -1, bNotifyClient);
}
}
return bAcquired;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AcquireMod
//
// PURPOSE: Give the player the specified mod, fail if weapon not owned
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AcquireMod( HMOD hMod , bool bDisplayMsg/* = true*/)
{
bool bRet = false;
if( hMod )
{
HWEAPON hWeapon = g_pWeaponDB->GetWeaponFromMod( hMod, !USE_AI_DATA );
if( hWeapon )
{
bool bHas = HaveWeapon(hWeapon);
if (bHas)
{
m_pArsenal->ObtainMod( hWeapon, hMod, true, bDisplayMsg );
bRet = true;
}
}
}
return bRet;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AcquireAmmo
//
// PURPOSE: Do the specific ammo cheat for the player
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AcquireAmmo( HAMMO hAmmo )
{
//verify that we have a weapon that uses this ammo
if( hAmmo && m_pArsenal->CanUseAmmo(hAmmo) )
{
m_pArsenal->SetAmmo( hAmmo );
return true;
}
return false;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AcquireGear
//
// PURPOSE: Give the player the specified Gear
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AcquireGear(HGEAR hGear, uint8 nNum /* = -1 */)
{
bool bAdded = false;
if( hGear )
{
uint32 nIndex = g_pWeaponDB->GetRecordIndex(hGear);
LTASSERT(nIndex < m_vecGearCount.size(),"Invalid gear index.");
if (nIndex >= m_vecGearCount.size())
return false;
//check to see if we can carry more of this type of item
// if the limit is 0, then there is no limit
uint8 nMax = g_pWeaponDB->GetInt32(hGear,WDB_GEAR_nMaxAmount);
uint8 nAmount = ( nMax - m_vecGearCount[nIndex] );
//figure out how many to get...
nAmount = LTMIN(nNum,nAmount);
m_vecGearCount[nIndex] += nAmount;
//automatically activate items that are not counted
if (nMax == 0)
{
bAdded = UseGear(hGear,false);
}
else
{
bAdded = (nAmount > 0);
}
if (bAdded)
{
HCLIENT hClient = m_pPlayer->GetClient();
if (hClient)
{
CAutoMessage cMsg;
cMsg.Writeuint8( MID_SFX_MESSAGE );
cMsg.Writeuint8( SFX_CHARACTER_ID );
cMsg.WriteObject( m_pPlayer->m_hObject );
cMsg.WriteBits(CFX_USE_GEAR, FNumBitsExclusive<CFX_COUNT>::k_nValue );
cMsg.WriteDatabaseRecord( g_pLTDatabase, hGear );
cMsg.Writeuint8(kGearAdd);
cMsg.Writeuint8( nAmount );
g_pLTServer->SendToClient( cMsg.Read( ), NULL, MESSAGE_GUARANTEED );
}
}
}
return bAdded;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::DropWeapon
//
// PURPOSE: Remove the specified weapon from the players inventory and spawn a pickup item
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::DropWeapon(HWEAPON hWeapon, LTVector const& vPos, LTRotation const& rRot, LTVector const& vVel, bool bChangeToUnarmed /* = true */)
{
if (!hWeapon || !m_pArsenal->IsValidWeaponRecord(hWeapon) || hWeapon == m_hUnarmed)
return;
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
bool bTakesSlot = g_pWeaponDB->GetBool(hWpnData,WDB_WEAPON_bTakesInventorySlot);
bool bHas = HaveWeapon(hWeapon);
//if we don't have it... bail out early
if (!bHas)
return;
CWeapon* pWeapon = m_pArsenal->GetWeapon(hWeapon);
if( !pWeapon )
return;
HAMMO hAmmo = pWeapon->GetAmmoRecord();
int32 nAmount = pWeapon->GetAmmoInClip( );
if( !g_pWeaponDB->GetBool( hWpnData, WDB_WEAPON_bWhenDroppedGiveAmmoInClip ))
{
// Keep the total amount of ammo with the weapon...
nAmount = m_pArsenal->GetAmmoCount( hAmmo );
}
//if we didn't remove the weapon, fail out...
if (!RemoveWeapon( hWeapon, bChangeToUnarmed ))
return;
//if this is a ammo weapon, and we're out of ammo for it, do not spawn a pickup item...
if (nAmount == 0 && g_pWeaponDB->GetBool( hWpnData, WDB_WEAPON_bIsAmmo ))
return;
float fLifetime = -1.0f;
if (IsMultiplayerGameServer())
{
HRECORD hGlobalRec = g_pWeaponDB->GetGlobalRecord();
fLifetime = float(g_pWeaponDB->GetInt32(hGlobalRec,WDB_GLOBAL_tDroppedWeaponLifeTime)) / 1000.0f;
}
//otherwise spawn the item...
uint8 nNumSpawns = 1;
HWEAPON hSingleWeapon = g_pWeaponDB->GetRecordLink( hWpnData, WDB_WEAPON_rSingleWeapon );
if( hSingleWeapon )
{
// Dropping a Dual weapon so two single weapons need to be respawned...
hWeapon = hSingleWeapon;
nNumSpawns = 2;
nAmount /= 2;
}
// [BJL 11/04/04] - Optionally disable movement to the floor based on
// the weapon properties.
bool bMoveToFloor = g_pWeaponDB->GetBool( hWpnData, WDB_WEAPON_bDroppedMoveToFloor );
char szSpawn[1024] = "";
LTSNPrintF( szSpawn, ARRAY_LEN(szSpawn), "WeaponItem Gravity 0;MoveToFloor %d;AmmoAmount %d;WeaponType (%s);AmmoType (%s);MPRespawn 0; DMTouchPickup 1;LifeTime %0.2f;Health %d;Placed 0",
bMoveToFloor, nAmount, g_pWeaponDB->GetRecordName( hWeapon ), g_pWeaponDB->GetRecordName( hAmmo ), fLifetime, pWeapon->GetHealth());
LTVector vSpawnPos = vPos;
uint8 nSpawn = 0;
while( nNumSpawns > 0 )
{
BaseClass* pObj = SpawnObject(szSpawn, vSpawnPos, rRot);
if (!pObj)
{
LTASSERT_PARAM1(0, "CPlayerInventory::DropWeapon : Failed to Spawn: %s", szSpawn);
return;
}
WeaponItem* pWeaponItem = dynamic_cast< WeaponItem* >( pObj );
if ( pWeaponItem )
{
LTVector vToss;
//toss the first to the right, and the second to the left
if (nSpawn == 0)
{
vToss = rRot.Right();
}
else
{
vToss = -rRot.Right();
}
LTVector vImpulse = rRot.Forward() + rRot.Up() + vToss;
vImpulse *= s_vtWeaponDropImpulse.GetFloat();
if (m_pPlayer->GetDestructible()->IsDead() && m_pPlayer->GetDestructible()->GetDeathType() == DT_EXPLODE)
{
vImpulse += m_pPlayer->GetDestructible()->GetDeathDir() * m_pPlayer->GetDestructible()->GetDeathImpulseForce();
}
vToss *= 0.5f;
LTVector vAdjVel = vVel + ( (rRot.Forward() + vToss) * s_vtWeaponDropVel.GetFloat());
LTVector vAng( GetRandom(-10.0f,10.0f),GetRandom(-10.0f,10.0f),GetRandom(-20.0f,20.0f));
pWeaponItem->DropItem( vImpulse, vAdjVel, vAng, m_pPlayer->m_hObject );
//in the case of dropping an empty weapon, we need to force the ammo count to 0
if (nAmount == 0)
{
pWeaponItem->SetAmmoAmount(0);
}
}
// Randomize the position for the next spawn...
LTVector vDiff = GetRandom( -50.0f, 0.0f ) * rRot.Right() + GetRandom( 0.0f, 50.0f ) * rRot.Forward();
vSpawnPos = (vPos + vDiff);
--nNumSpawns;
++nSpawn;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::DropAllWeapons
//
// PURPOSE: Drop and spawn all carried weapons
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::DropAllWeapons()
{
LTVector vPlayerPos, vUp, vVel;
LTRotation rPlayerRot;
g_pLTServer->GetObjectPos(m_pPlayer->m_hObject,&vPlayerPos);
g_pLTServer->GetObjectRotation(m_pPlayer->m_hObject,&rPlayerRot);
vUp = rPlayerRot.Up();
uint8 nNumWeapons = g_pWeaponDB->GetNumPlayerWeapons();
for( uint8 nWeapon = 0; nWeapon < nNumWeapons; ++nWeapon )
{
HWEAPON hWeapon = g_pWeaponDB->GetPlayerWeapon( nWeapon );
LTRotation rRot = rPlayerRot;
rRot.Rotate(vUp,GetRandom(-1.0f,1.0f));
LTVector vPos = vPlayerPos + (vUp * 50.0f);
DropWeapon(hWeapon, vPos, rRot, m_pPlayer->GetLastVelocity() );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::RemoveWeapon
//
// PURPOSE: Remove the specified weapon from the players inventory
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::RemoveWeapon( HWEAPON hWeapon, bool bChangeToUnarmed /*=true*/)
{
if( !hWeapon || !g_pWeaponDB->IsPlayerWeapon( hWeapon ))
return false;
HWEAPONDATA hWpnData = g_pWeaponDB->GetWeaponData(hWeapon, !USE_AI_DATA);
// if the weapon takes a slot, clear it...
if (g_pWeaponDB->GetBool(hWpnData,WDB_WEAPON_bTakesInventorySlot))
{
//we don't actually have it...
uint8 nSlot = GetWeaponSlot(hWeapon);
if (nSlot == WDB_INVALID_WEAPON_INDEX)
return false;
m_vecWeapons[nSlot] = (HWEAPON)NULL;
}
if( (m_pArsenal->GetCurWeaponRecord() == hWeapon) && bChangeToUnarmed )
m_pPlayer->ChangeWeapon( m_hUnarmed, true, NULL, false, false );
m_pArsenal->RemoveWeapon(hWeapon);
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::WeaponSwap
//
// PURPOSE: drop our current weapon, and pickup one on the ground
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::WeaponSwap( HOBJECT hTarget, const LTRigidTransform& tPickup )
{
//can't drop fists
HWEAPON hWeapon = m_pArsenal->GetCurWeaponRecord();
if (hWeapon == m_hUnarmed)
hWeapon = GetLowestPriorityWeapon();
if (!hWeapon)
return false;
WeaponItem *pWpnItem = dynamic_cast<WeaponItem*>(g_pLTServer->HandleToObject( hTarget ));
if (!pWpnItem)
return false;
HWEAPONDATA hTgtWpnData = g_pWeaponDB->GetWeaponData( pWpnItem->GetWeaponRecord( ), !USE_AI_DATA );
if (!g_pWeaponDB->GetBool(hTgtWpnData,WDB_WEAPON_bTakesInventorySlot))
{
//not an weapon that takes a slot we shouldn't swap, we should just get it
return false;
}
// Drop the weapon in hand but don't switch to the unarmed weapon...
DropWeapon( hWeapon, tPickup.m_vPos, tPickup.m_rRot, LTVector::GetIdentity(), false );
//touch the item on the ground so that we pick it up
pWpnItem->ObjectTouch(m_pPlayer->m_hObject);
// Force a change to the weapon since we dropped the on in hand...
m_pPlayer->ChangeWeapon( pWpnItem->GetWeaponRecord( ), true, NULL, true, true );
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::SwapWeapon
//
// PURPOSE: Replaces one weapon with another one...
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::SwapWeapon( HWEAPON hFromWeapon, HWEAPON hToWeapon, bool bNotifyClient )
{
// Both weapons must be usable by the player...
if( !hFromWeapon || !g_pWeaponDB->IsPlayerWeapon( hFromWeapon ) ||
!hToWeapon || !g_pWeaponDB->IsPlayerWeapon( hToWeapon ) )
{
return false;
}
// Get at the weapon data...
HWEAPONDATA hFromWeaponData = g_pWeaponDB->GetWeaponData( hFromWeapon, false );
HWEAPONDATA hToWeaponData = g_pWeaponDB->GetWeaponData( hToWeapon, false );
// Only weapons that take up slots will be valid for swapping...
if( !g_pWeaponDB->GetBool( hFromWeaponData, WDB_WEAPON_bTakesInventorySlot ) ||
!g_pWeaponDB->GetBool( hToWeaponData, WDB_WEAPON_bTakesInventorySlot ) )
{
return false;
}
// Get at the ammo for the new weapon
HAMMO hToAmmo = g_pWeaponDB->GetRecordLink( hToWeaponData, WDB_WEAPON_rAmmoName );
if( !hToAmmo )
{
// Must have a valid ammo...
return false;
}
// If our from weapon is taking up a slot... clear that slot out
uint8 nWeaponSlot = GetWeaponSlot( hFromWeapon );
if( nWeaponSlot == WDB_INVALID_WEAPON_INDEX )
{
// We didn't actually have the old weapon... so just bail!
return false;
}
// Change it to the new weapon...
m_vecWeapons[ nWeaponSlot ] = hToWeapon;
if ( m_pArsenal->GetCurWeapon() )
{
m_pArsenal->GetCurWeapon()->Drop();
}
// Obtain the new weapon, and ditch the old one...
m_pArsenal->DeselectCurWeapon();
//!!ARL: Removing the weapon makes it disappear immediately (which looks bad).
// We should probably still get rid of it when the complimentary weapon
// is dropped or something. But since there's no way to switch to it
// in the Dark, we won't worry about it for now.
// m_pArsenal->RemoveWeapon( hFromWeapon );
m_pArsenal->ObtainWeapon( hToWeapon, hToAmmo, -1, bNotifyClient );
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleWeaponBroke
//
// PURPOSE: Replaces current weapon with a broken version
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::HandleWeaponBroke( HWEAPON hBrokenWeapon, HWEAPON hReplacementWeapon )
{
// new weapon must be usable by the player...
if( !hReplacementWeapon || !g_pWeaponDB->IsPlayerWeapon( hReplacementWeapon ) )
{
return false;
}
// Get at the weapon data...
HWEAPONDATA hReplacementWeaponData = g_pWeaponDB->GetWeaponData( hReplacementWeapon, false );
// Get at the ammo for the new weapon
HAMMO hReplacementAmmo = g_pWeaponDB->GetRecordLink( hReplacementWeaponData, WDB_WEAPON_rAmmoName );
if( !hReplacementAmmo )
{
// Must have a valid ammo...
return false;
}
// If our from weapon is taking up a slot... clear that slot out
uint8 nWeaponSlot = GetWeaponSlot( hBrokenWeapon );
if( nWeaponSlot == WDB_INVALID_WEAPON_INDEX )
{
// We didn't actually have the old weapon... so just bail!
return false;
}
// Change it to the new weapon...
m_vecWeapons[ nWeaponSlot ] = hReplacementWeapon;
// remove broken weapon from arsenal
m_pArsenal->RemoveWeapon( hBrokenWeapon );
// add a replacement weapon - don't play any weapon change anims
m_pArsenal->ObtainWeapon(hReplacementWeapon, hReplacementAmmo, -1, true, -1, true);
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::GetLowestPriorityWeapon
//
// PURPOSE: find the weapon we least care about
//
// ----------------------------------------------------------------------- //
HWEAPON CPlayerInventory::GetLowestPriorityWeapon()
{
for( uint8 nWeapon = 0; nWeapon < m_vecPriorities.size(); ++nWeapon )
{
HWEAPON hWeapon = m_vecPriorities[nWeapon];
//skip our fists...
if( hWeapon != m_hUnarmed && HaveWeapon(hWeapon) )
{
return hWeapon;
}
}
return NULL;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::PickupGear
//
// PURPOSE: Try to pickup a gear item
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::PickupGear(HOBJECT hSender, ILTMessage_Read *pMsg)
{
if (!m_pPlayer || !m_pPlayer->IsAlive()) return false;
HGEAR hGear = pMsg->ReadDatabaseRecord(g_pLTDatabase, g_pWeaponDB->GetGearCategory() );
if (!hGear)
return false;
uint32 nIndex = g_pWeaponDB->GetRecordIndex(hGear);
LTASSERT(nIndex < m_vecGearCount.size(),"Invalid gear index.");
if (nIndex >= m_vecGearCount.size())
return false;
/* hacked out stealth support
// This may change after the new item is added...
float fOldStealth = GetStealthModifier();
*/
//check to see if we can carry more of this type of item
// if the limit is 0, then there is no limit
uint16 nMax = g_pWeaponDB->GetInt32(hGear,WDB_GEAR_nMaxAmount);
if (nMax && m_vecGearCount[nIndex] >= nMax)
return false;
bool bAdded = true;
if (nMax == 0)
{
bAdded = UseGear(hGear,false);
}
else
{
//if we're counting pickups, and we added this one increment our count
++m_vecGearCount[nIndex];
// Update SlowMo recharge rates if the gear item is supposed to recharge it...
if( g_pWeaponDB->GetFloat( hGear, WDB_GEAR_fSlowMoTime ) > 0.0f )
{
m_fSlowMoRechargeRate = g_pWeaponDB->GetFloat( hGear, WDB_GEAR_fSlowMoTime );
PickupItem *pPickupItem = dynamic_cast<PickupItem*>(g_pLTServer->HandleToObject( hSender ));
if( pPickupItem )
{
// Cache the original slow-mo gear object...
m_hSlowMoGearObject = pPickupItem->GetOriginalPickupObject( );
pPickupItem->SetOriginalPickupObject( NULL );
if( !m_hSlowMoGearObject )
m_hSlowMoGearObject = hSender;
}
NavMarkerCreator nmc;
//see what kind of marker we're supposed to use
nmc.m_hType = g_pNavMarkerTypeDB->GetRecord( "SlowMo_Enemy" );
//create the marker, if a type was specified
if (nmc.m_hType && GameModeMgr::Instance( ).m_grbSlowMoNavMarker)
{
if( GameModeMgr::Instance( ).m_grbUseTeams )
{
nmc.m_nTeamId = 1 - m_pPlayer->GetTeamID();
}
else
{
nmc.m_nTeamId = 255;
}
nmc.m_hTarget = m_pPlayer->m_hObject;
g_pLTServer->GetObjectPos( m_pPlayer->m_hObject, &nmc.m_vPos );
NavMarker* pNM = nmc.SpawnMarker();
if (pNM)
{
//keep track incase we need to remove it later
m_hEnemySlowMoNavMarker = pNM->m_hObject;
}
}
if( GameModeMgr::Instance( ).m_grbUseTeams )
{
//see what kind of marker we're supposed to use for my friends
nmc.m_hType = g_pNavMarkerTypeDB->GetRecord( "SlowMo_Team" );
//create the marker, if a type was specified
if (nmc.m_hType)
{
nmc.m_nTeamId = m_pPlayer->GetTeamID();
nmc.m_hTarget = m_pPlayer->m_hObject;
g_pLTServer->GetObjectPos( m_pPlayer->m_hObject, &nmc.m_vPos );
NavMarker* pNM = nmc.SpawnMarker();
if (pNM)
{
//keep track in case we need to remove it later
m_hSlowMoNavMarker = pNM->m_hObject;
}
}
}
m_pPlayer->SetHasSlowMoRecharge(true);
m_hSlowMoGearRecord = hGear;
SendSlowMoValuesToClient( );
}
}
/* hacked out stealth support
// If our stealth modifier has changed, notify the clients...
if (fOldStealth != GetStealthModifier())
{
if (IsCharacter(m_hObject))
{
CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject(m_hObject);
if (pChar)
{
pChar->SendStealthToClients();
}
}
}
*/
if (bAdded)
{
CAutoMessage cMsg;
cMsg.Writeuint32(MID_PICKEDUP);
cMsg.Writebool( true );
cMsg.Writebool( false ); // bWeaponsStay
g_pLTServer->SendToObject(cMsg.Read(), m_pPlayer->m_hObject, hSender, MESSAGE_GUARANTEED);
}
return bAdded;
}
uint16 CPlayerInventory::GetGearCount(HGEAR hGear) const
{
if (!hGear)
return 0;
uint32 nIndex = g_pWeaponDB->GetRecordIndex(hGear);
LTASSERT(nIndex < m_vecGearCount.size(),"Invalid gear index.");
if (nIndex >= m_vecGearCount.size())
return 0;
return m_vecGearCount[nIndex];
}
bool CPlayerInventory::UseGear(HGEAR hGear, bool bNotifyClient /* = true */)
{
if (!m_pPlayer->IsAlive())
return false;
if (!hGear)
return false;
if( !m_pPlayer->IsAlive() )
return false;
uint32 nIndex = g_pWeaponDB->GetRecordIndex(hGear);
uint8 nMax = g_pWeaponDB->GetInt32(hGear,WDB_GEAR_nMaxAmount);
LTASSERT(nIndex < m_vecGearCount.size(),"Invalid gear index.");
if (nIndex >= m_vecGearCount.size() || //valid index
(nMax > 0 && m_vecGearCount[nIndex] == 0)) //is uncounted type, or has at least one
return false;
bool bUsed = false;
float fRepair = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fArmor);
if (fRepair > 0.0f)
{
fRepair *= GetSkillValue(eArmorPickup);
bUsed = m_pPlayer->GetDestructible()->Repair(fRepair);
if (bUsed)
{
m_pPlayer->UpdateSurfaceFlags();
}
}
float fHealth = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fHealth);
if (fHealth > 0.0f)
{
fHealth *= GetSkillValue(eHealthPickup);
bUsed = m_pPlayer->GetDestructible()->Heal(fHealth);
}
float fSlowMoMax = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fSlowMoMaxBonus);
if (fSlowMoMax > 0.0f)
{
m_fSlowMoMaxCharge += fSlowMoMax;
bUsed = true;
}
float fSlowMo = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fSlowMoTime);
if (fSlowMo > 0.0f)
{
bUsed = (m_fSlowMoCharge < m_fSlowMoMaxCharge);
m_fSlowMoCharge = LTMIN(m_fSlowMoMaxCharge,m_fSlowMoCharge+fSlowMo);
}
float fMaxBonus = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fHealthMax);
float fCurrentMax = m_pPlayer->GetDestructible()->GetMaxHitPoints();
float fAbsoluteMax = (float)g_pServerDB->GetMaxPlayerHealth();
if (fMaxBonus > 0.0f && m_pPlayer->GetClient( ) && fCurrentMax < fAbsoluteMax)
{
fMaxBonus *= GetSkillValue(eHealthPickup);
float fMax = fCurrentMax + fMaxBonus;
fMax = LTMIN( fAbsoluteMax, fMax);
m_pPlayer->GetDestructible()->SetMaxHitPoints(fMax);
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_INFOCHANGE);
cMsg.Writeuint8(IC_MAX_HEALTH_ID);
cMsg.Writeuint8(0);
cMsg.Writeuint8(0);
cMsg.Writefloat(fMax);
g_pLTServer->SendToClient(cMsg.Read( ), m_pPlayer->GetClient( ), MESSAGE_GUARANTEED);
m_pPlayer->GetDestructible()->Heal(fMax);
bUsed = true;
}
fMaxBonus = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fArmorMax);
fCurrentMax = m_pPlayer->GetDestructible()->GetMaxArmorPoints();
fAbsoluteMax = (float)g_pServerDB->GetMaxPlayerArmor();
if (fMaxBonus > 0.0f && m_pPlayer->GetClient( ) && fCurrentMax < fAbsoluteMax)
{
fMaxBonus *= GetSkillValue(eArmorPickup);
float fMax = fCurrentMax + fMaxBonus;
fMax = LTMIN( fAbsoluteMax, fMax);
m_pPlayer->GetDestructible()->SetMaxArmorPoints(fMax);
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_INFOCHANGE);
cMsg.Writeuint8(IC_MAX_ARMOR_ID);
cMsg.Writeuint8(0);
cMsg.Writeuint8(0);
cMsg.Writefloat(fMax);
g_pLTServer->SendToClient(cMsg.Read( ), m_pPlayer->GetClient( ), MESSAGE_GUARANTEED);
m_pPlayer->GetDestructible()->Repair(fMax);
bUsed = true;
}
if (bUsed)
{
if (fSlowMo > 0.0f || fSlowMoMax > 0.0f)
{
SendSlowMoValuesToClient( );
}
//this might be 0 for uncounted items
if (m_vecGearCount[nIndex] > 0)
--m_vecGearCount[nIndex];
HCLIENT hClient = m_pPlayer->GetClient();
if (hClient && bNotifyClient)
{
CAutoMessage cMsg;
cMsg.Writeuint8( MID_SFX_MESSAGE );
cMsg.Writeuint8( SFX_CHARACTER_ID );
cMsg.WriteObject( m_pPlayer->m_hObject );
cMsg.WriteBits(CFX_USE_GEAR, FNumBitsExclusive<CFX_COUNT>::k_nValue );
cMsg.WriteDatabaseRecord( g_pLTDatabase, hGear );
cMsg.Writeuint8(kGearUse);
cMsg.Writeuint8( 1 );
g_pLTServer->SendToClient( cMsg.Read( ), NULL, MESSAGE_GUARANTEED );
}
}
return bUsed;
}
bool CPlayerInventory::RemoveGear(HGEAR hGear, uint8 nAmount /* = 1 */)
{
if (!hGear)
return false;
uint32 nIndex = g_pWeaponDB->GetRecordIndex(hGear);
LTASSERT(nIndex < m_vecGearCount.size(),"Invalid gear index.");
if (nIndex >= m_vecGearCount.size() || m_vecGearCount[nIndex] == 0)
return false;
if (nAmount > m_vecGearCount[nIndex])
{
nAmount = m_vecGearCount[nIndex];
}
m_vecGearCount[nIndex] -= nAmount;
HCLIENT hClient = m_pPlayer->GetClient();
if (hClient)
{
CAutoMessage cMsg;
cMsg.Writeuint8( MID_SFX_MESSAGE );
cMsg.Writeuint8( SFX_CHARACTER_ID );
cMsg.WriteObject( m_pPlayer->m_hObject );
cMsg.WriteBits(CFX_USE_GEAR, FNumBitsExclusive<CFX_COUNT>::k_nValue );
cMsg.WriteDatabaseRecord( g_pLTDatabase, hGear );
cMsg.Writeuint8(kGearRemove);
cMsg.Writeuint8( nAmount );
g_pLTServer->SendToClient( cMsg.Read( ), NULL, MESSAGE_GUARANTEED );
}
return true;
}
void CPlayerInventory::RemoveAllGear()
{
GearArray::iterator itr = m_vecGearCount.begin();
while (itr != m_vecGearCount.end())
{
(*itr) = 0;
++itr;
}
}
float CPlayerInventory::GetGearProtection(DamageType DT) const
{
float fProtection = 0.0f;
// See if we have protection from this kind of damage...
for (uint8 nGearId=0; nGearId < g_pWeaponDB->GetNumGear(); nGearId++)
{
//if we have this gear type...
if (m_vecGearCount[nGearId] > 0)
{
HGEAR hGear = g_pWeaponDB->GetGearRecord(nGearId);
//does it protect against this damage type?
if (StringToDamageType(g_pWeaponDB->GetString(hGear,WDB_GEAR_sProtectionType)) == DT)
{
fProtection += g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fProtection);
//fully protected stop looking
if (fProtection >= 1.0f)
{
return 1.0f;
}
}
}
}
return fProtection;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::GetStealthModifier
//
// PURPOSE: Returns footstep sound volume multiplier for the current gear
// and skills
//
// ----------------------------------------------------------------------- //
float CPlayerInventory::GetStealthModifier()
{
float fMult = 1.0f;
for (uint8 nGearId=0; nGearId < g_pWeaponDB->GetNumGear(); nGearId++)
{
HGEAR hGear = g_pWeaponDB->GetGearRecord(nGearId);
if (hGear && GetGearCount(hGear) > 0)
{
float fStealth = g_pWeaponDB->GetFloat(hGear,WDB_GEAR_fStealth);
fMult *= (1.0f - fStealth);
}
}
fMult *= GetSkillValue(eStealthRadius);
return fMult;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HasAirSupply
//
// PURPOSE: Determine whether player can survive underwater
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::HasAirSupply()
{
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandleGearMsg
//
// PURPOSE: handle gear message from client
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::HandleGearMsg(ILTMessage_Read *pMsg)
{
HGEAR hGear = pMsg->ReadDatabaseRecord( g_pLTDatabase, g_pWeaponDB->GetGearCategory() );
GearMsgType eMsgType = static_cast<GearMsgType>(pMsg->Readuint8());
switch(eMsgType)
{
case kGearUse:
UseGear(hGear);
break;
case kGearAdd:
case kGearRemove:
default:
break;
//unhandled messages
};
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HandlePriorityMsg
//
// PURPOSE: handle weapon priority message from client
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::HandlePriorityMsg(ILTMessage_Read *pMsg)
{
m_vecPriorities.clear();
uint8 nNum = pMsg->Readuint8();
m_vecPriorities.reserve(nNum);
for (uint8 n = 0; n < nNum; ++n)
{
HWEAPON hWeapon = pMsg->ReadDatabaseRecord( g_pLTDatabase, g_pWeaponDB->GetWeaponsCategory() );
m_vecPriorities.push_back(hWeapon);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::Save
//
// PURPOSE: Save the object
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::Save(ILTMessage_Write *pMsg)
{
if (!pMsg) return;
SAVE_BYTE( m_nWeaponCapacity );
//save set of weapons we are carrying
WeaponArray::iterator iter = m_vecWeapons.begin();
while (iter != m_vecWeapons.end())
{
SAVE_HRECORD( (*iter));
++iter;
};
//save vector tracking gear items that have been picked up
SAVE_BYTE(g_pWeaponDB->GetNumGear());
for( uint8 nGear = 0; nGear < g_pWeaponDB->GetNumGear(); ++nGear )
{
// Save the name of the gear record so the correct index can be properly resolved when loading...
// This will help minimize the possibility of thrashing saved games in future updates...
HGEAR hGear = g_pLTDatabase->GetRecordByIndex( g_pWeaponDB->GetGearCategory( ), nGear );
const char *pszGearName = g_pWeaponDB->GetRecordName( hGear );
SAVE_CHARSTRING( pszGearName );
SAVE_BYTE( m_vecGearCount[nGear] );
}
SAVE_HRECORD( m_hSlowMoRecord );
SAVE_FLOAT(m_fSlowMoCharge);
SAVE_bool(m_bSlowMoPlayerControlled);
SAVE_FLOAT(m_fSlowMoMaxCharge);
SAVE_FLOAT(m_fSlowMoRechargeRate);
SAVE_bool( m_bUpdateCharge );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::Load
//
// PURPOSE: Load the object
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::Load(ILTMessage_Read *pMsg)
{
if (!pMsg) return;
LOAD_BYTE( m_nWeaponCapacity );
m_vecWeapons.clear();
m_vecWeapons.resize(m_nWeaponCapacity,(HWEAPON)NULL);
for (uint8 i = 0; i < m_nWeaponCapacity; ++i)
{
HWEAPON hWeapon;
LOAD_HRECORD(hWeapon, g_pWeaponDB->GetWeaponsCategory() );
m_vecWeapons[i] = hWeapon;
}
uint8 numGearSaved;
LOAD_BYTE(numGearSaved);
//set up our gear array
uint8 nNumGear = g_pWeaponDB->GetNumGear();
m_vecGearCount.clear();
m_vecGearCount.insert(m_vecGearCount.begin(),nNumGear,0);
LTASSERT(numGearSaved == nNumGear,"Number of gear in saved game doesn't match current DB.");
char szGearName[256] = {0};
for( uint8 nGear = 0; nGear < numGearSaved; ++nGear)
{
// Resolve the record name to the proper index...
LOAD_CHARSTRING( szGearName, LTARRAYSIZE( szGearName ));
HGEAR hGear = g_pWeaponDB->GetGearRecord( szGearName );
uint32 nGearIndex = g_pWeaponDB->GetRecordIndex( hGear );
uint8 nCount;
LOAD_BYTE(nCount);
m_vecGearCount[nGearIndex] = nCount;
}
m_hUnarmed = g_pWeaponDB->GetUnarmedRecord();
LOAD_HRECORD( m_hSlowMoRecord, DATABASE_CATEGORY( SlowMo ).GetCategory( ));
LOAD_FLOAT(m_fSlowMoCharge);
LOAD_bool(m_bSlowMoPlayerControlled);
LOAD_FLOAT(m_fSlowMoMaxCharge);
LOAD_FLOAT(m_fSlowMoRechargeRate);
LOAD_bool( m_bUpdateCharge );
SendSlowMoValuesToClient( );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::IsPreferredWeapon( )
//
// PURPOSE: Checks if WeaponA is preferred to WeaponB.
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::IsPreferredWeapon( HWEAPON hWeaponA, HWEAPON hWeaponB ) const
{
if (hWeaponA == hWeaponB)
return false;
const char *szA = g_pWeaponDB->GetRecordName(hWeaponA);
const char *szB = g_pWeaponDB->GetRecordName(hWeaponB);
//using indices rather than iterators because this needs to be a const function
for (uint32 n = m_vecPriorities.size()-1; n < m_vecPriorities.size(); --n)
{
//found A first, its the preferred one...
if (hWeaponA == m_vecPriorities[n])
{
return true;
}
//found B first, so A is not preferred...
if (hWeaponB == m_vecPriorities[n])
{
return false;
}
}
//didn't find either one, no preference...
return false;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::HaveWeapon( )
//
// PURPOSE: Do we have the specified?
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::HaveWeapon( HWEAPON hWpn )
{
return (GetWeaponSlot(hWpn) != WDB_INVALID_WEAPON_INDEX);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::GetWeaponSlot( )
//
// PURPOSE: Find the specified weapon...
//
// ----------------------------------------------------------------------- //
uint8 CPlayerInventory::GetWeaponSlot( HWEAPON hWpn )
{
uint8 n = 0;
while (n < m_nWeaponCapacity && hWpn != m_vecWeapons[n])
{
n++;
}
if (n >= m_nWeaponCapacity )
{
return WDB_INVALID_WEAPON_INDEX;
}
else
{
return n;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::FindFirstEmptySlot( )
//
// PURPOSE: Find the first open slot
//
// ----------------------------------------------------------------------- //
uint8 CPlayerInventory::FindFirstEmptySlot( )
{
uint8 n = 0;
while (n < m_nWeaponCapacity && (NULL != m_vecWeapons[n]))
{
n++;
}
if (n >= m_nWeaponCapacity )
{
return WDB_INVALID_WEAPON_INDEX;
}
else
{
return n;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::ClearWeaponSlots( )
//
// PURPOSE: Clear out our slots
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::ClearWeaponSlots()
{
if (m_nWeaponCapacity != m_vecWeapons.size())
{
m_vecWeapons.clear();
SetCapacity(m_nWeaponCapacity);
return;
}
for (uint8 n =0;n < m_nWeaponCapacity;++n )
{
m_vecWeapons[n] = NULL;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::GetWeaponInSlot( )
//
// PURPOSE: Get the weapon in the specified slot...
//
// ----------------------------------------------------------------------- //
HWEAPON CPlayerInventory::GetWeaponInSlot( uint8 nSlot )
{
if (nSlot < m_vecWeapons.size())
return m_vecWeapons[nSlot];
return NULL;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AddHealth
//
// PURPOSE: Add the specified ammount of health to the player...
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AddHealth( uint32 nAmmount )
{
return m_pPlayer->GetDestructible( )->Heal( (float)nAmmount );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AddArmor
//
// PURPOSE: Add the specified amount of armor to the player...
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AddArmor( uint32 nAmmount )
{
return m_pPlayer->GetDestructible( )->Repair( (float)nAmmount );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AddAmmo
//
// PURPOSE: Add the specified amount of ammo of the specified ammo type to the player...
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AddAmmo( HAMMO hAmmo, uint32 nAmmount )
{
if (!m_pArsenal->CanUseAmmo(hAmmo))
return false;
return (m_pArsenal->AddAmmo( hAmmo, nAmmount ) > 0);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::AddSlowMo
//
// PURPOSE: Add the specified amount of slow-mo to the total slow-mo charge for the player...
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::AddSlowMo( uint32 nAmount )
{
if (!nAmount) return false;
// Don't give more than the max limit...
if( m_fSlowMoCharge >= m_fSlowMoMaxCharge )
return false;
// Add in the extra amount...
float fAmount = nAmount / 1000.0f;
m_fSlowMoCharge = LTMIN( m_fSlowMoCharge + fAmount, m_fSlowMoMaxCharge );
// Let the client know of the changed value...
SendSlowMoValuesToClient( );
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::IsSlowMoPlayerControlled
//
// PURPOSE: Is the player controlling a slow mo
//
// ----------------------------------------------------------------------- //
bool CPlayerInventory::IsSlowMoPlayerControlled() const
{
return (m_bSlowMoPlayerControlled);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::SetSlowMoPlayerControl
//
// PURPOSE: set/clear the player controlled slow mor flag
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::SetSlowMoPlayerControl(bool bPlayer )
{
m_bSlowMoPlayerControlled = bPlayer;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::SendSlowMoValues
//
// PURPOSE: notify client of current values
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::SendSlowMoValuesToClient( )
{
HCLIENT hClient = m_pPlayer->GetClient( );
if( hClient )
{
CAutoMessage cMsg;
cMsg.Writeuint8( MID_SLOWMO );
// Leave slowmo.
cMsg.Writeuint8( kSlowMoInit );
cMsg.Writefloat( m_fSlowMoCharge );
cMsg.Writefloat( m_fSlowMoMaxCharge );
cMsg.Writefloat( GETCATRECORDATTRIB( SlowMo, m_hSlowMoRecord, MinimumPeriod ) );
cMsg.Writefloat( m_fSlowMoRechargeRate );
g_pLTServer->SendToClient( cMsg.Read(), hClient, MESSAGE_GUARANTEED );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::TransferPersistentInventory
//
// PURPOSE: Transfer all persistent inventory items from specified inventory to this one...
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::TransferPersistentInventory( const CPlayerInventory *pFromInventory )
{
if( !pFromInventory )
return;
if( GameModeMgr::Instance( ).m_grbSlowMoPersistsAcrossDeath )
m_fSlowMoCharge = pFromInventory->m_fSlowMoCharge;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::ExitSlowMo
//
// PURPOSE: Handle special functionality when a player exits slow-mo...
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::ExitSlowMo( )
{
m_bSlowMoPlayerControlled = false;
if( GameModeMgr::Instance( ).m_grbSlowMoRespawnAfterUse )
{
// Respawn the slowmo gearitem if we cached one...
if( m_hSlowMoGearObject )
{
g_pCmdMgr->QueueMessage( m_pPlayer->m_hObject, m_hSlowMoGearObject, "RESPAWN" );
}
m_hSlowMoGearObject = NULL;
RemoveGear( m_hSlowMoGearRecord );
RemoveSlowMoNavMarker();
m_hSlowMoGearRecord = NULL;
// Reset slow-mo values...
m_fSlowMoCharge = 0.0f;
m_fSlowMoRechargeRate = GETCATRECORDATTRIB( SlowMo, m_hSlowMoRecord, RechargeRate );
m_bUpdateCharge = true;
SendSlowMoValuesToClient( );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::RemoveSlowMoNavMarker
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::RemoveSlowMoNavMarker( )
{
if( m_hSlowMoNavMarker )
{
g_pLTServer->RemoveObject( m_hSlowMoNavMarker );
m_hSlowMoNavMarker = NULL;
}
if( m_hEnemySlowMoNavMarker )
{
g_pLTServer->RemoveObject( m_hEnemySlowMoNavMarker );
m_hEnemySlowMoNavMarker = NULL;
}
m_pPlayer->SetHasSlowMoRecharge(false);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CPlayerInventory::SetCTFFlag
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CPlayerInventory::SetCTFFlag( HOBJECT hCTFFlag )
{
m_hCTFFlag = hCTFFlag;
if (m_hCTFFlag)
{
//remove any old marker
if( m_hFlagNavMarker )
{
g_pLTServer->RemoveObject( m_hFlagNavMarker );
m_hFlagNavMarker = NULL;
}
NavMarkerCreator nmc;
//see what kind of marker we're supposed to use
nmc.m_hType = g_pNavMarkerTypeDB->GetRecord( "Flag_Team" );
//create the marker, if a type was specified
if (nmc.m_hType)
{
nmc.m_nTeamId = m_pPlayer->GetTeamID();
nmc.m_hTarget = m_pPlayer->m_hObject;
g_pLTServer->GetObjectPos( m_pPlayer->m_hObject, &nmc.m_vPos );
NavMarker* pNM = nmc.SpawnMarker();
if (pNM)
{
//keep track in case we need to remove it later
m_hFlagNavMarker = pNM->m_hObject;
}
}
}
else
{
if( m_hFlagNavMarker )
{
g_pLTServer->RemoveObject( m_hFlagNavMarker );
m_hFlagNavMarker = NULL;
}
}
}
// EOF
| 0 | 0.958103 | 1 | 0.958103 | game-dev | MEDIA | 0.981276 | game-dev | 0.841221 | 1 | 0.841221 |
penguinsword/foundation | 3,051 | Runtime/Common/Pattern/EventBus/Core/SubscriberBusWrapper.cs | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Pancake.EventBus
{
internal sealed class SubscriberBusWrapper : IDisposable, ISubscriberWrapper
{
internal static Stack<SubscriberBusWrapper> s_WrappersPool = new Stack<SubscriberBusWrapper>(512);
private ISubscriberName m_Name;
private ISubscriberPriority m_Priority;
internal bool IsActive;
public IEventBus Bus;
public string Name => m_Name.Name;
public ISubscriber Target => Bus;
public int Order => m_Priority.Priority;
public int Index { get; private set; }
// =======================================================================
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Invoke<TEvent, TInvoker>(in TEvent e, in TInvoker invoker) where TInvoker : IEventInvoker
{
#if DEBUG
Bus.Send(in e, in invoker);
#else
try
{
Bus.Send(in e, in invoker);
}
catch (Exception exception)
{
UnityEngine.Debug.LogError($"{this}; Exception: {exception}");
}
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public SubscriberBusWrapper(in IEventBus bus, int index)
{
Setup(bus, index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Setup(in IEventBus bus, int index)
{
Index = index;
IsActive = true;
Bus = bus;
m_Name = bus as ISubscriberName ?? Extensions.s_DefaultSubscriberName;
m_Priority = bus as ISubscriberPriority ?? Extensions.s_DefaultSubscriberPriority;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
return Bus == ((SubscriberBusWrapper)obj).Bus;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return Bus.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
IsActive = false;
Bus = null;
m_Name = null;
m_Priority = null;
s_WrappersPool.Push(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static SubscriberBusWrapper Create(in IEventBus bus, int index)
{
if (s_WrappersPool.Count > 0)
{
var wrapper = s_WrappersPool.Pop();
wrapper.Setup(in bus, index);
return wrapper;
}
else
return new SubscriberBusWrapper(in bus, index);
}
public override string ToString()
{
return $"Bus: <Name> {Name}, <Type> {Bus.GetType()}";
}
}
} | 1 | 0.746542 | 1 | 0.746542 | game-dev | MEDIA | 0.229959 | game-dev | 0.84484 | 1 | 0.84484 |
bakkesmodorg/BakkesModSDK | 2,835 | include/bakkesmod/wrappers/GameObject/BallHauntedWrapper.h | #pragma once
#include "BallWrapper.h"
class GoalWrapper;
class CarWrapper;
class BAKKESMOD_PLUGIN_IMPORT BallHauntedWrapper : public BallWrapper {
public:
CONSTRUCTORS(BallHauntedWrapper)
//BEGIN SELF IMPLEMENTED
//END SELF IMPLEMENTED
//AUTO-GENERATED FROM FIELDS
float GetTrappedHoverHeight();
void SetTrappedHoverHeight(float TrappedHoverHeight);
float GetHorizontalSpeed();
void SetHorizontalSpeed(float HorizontalSpeed);
float GetVerticalSpeed();
void SetVerticalSpeed(float VerticalSpeed);
float GetArrivalDistance();
void SetArrivalDistance(float ArrivalDistance);
float GetTrappedHorizontalSpeed();
void SetTrappedHorizontalSpeed(float TrappedHorizontalSpeed);
float GetTrappedVerticalSpeed();
void SetTrappedVerticalSpeed(float TrappedVerticalSpeed);
float GetTrappedCaptureTime();
void SetTrappedCaptureTime(float TrappedCaptureTime);
float GetHitPhysicsDuration();
void SetHitPhysicsDuration(float HitPhysicsDuration);
unsigned char GetReplicatedBeamBrokenValue();
void SetReplicatedBeamBrokenValue(unsigned char ReplicatedBeamBrokenValue);
unsigned char GetLastTeamTouch();
void SetLastTeamTouch(unsigned char LastTeamTouch);
unsigned char GetDeactivatedGoalIndex();
void SetDeactivatedGoalIndex(unsigned char DeactivatedGoalIndex);
unsigned char GetTotalActiveBeams();
void SetTotalActiveBeams(unsigned char TotalActiveBeams);
Vector GetSeekTarget();
void SetSeekTarget(Vector SeekTarget);
float GetNextNeutralTime();
void SetNextNeutralTime(float NextNeutralTime);
unsigned int GetbHitPhysicsActive();
void SetbHitPhysicsActive(unsigned int bHitPhysicsActive);
unsigned int GetbIsBallBeamed();
void SetbIsBallBeamed(unsigned int bIsBallBeamed);
unsigned int GetbIsTrapped();
void SetbIsTrapped(unsigned int bIsTrapped);
float GetCurrentCaptureTime();
void SetCurrentCaptureTime(float CurrentCaptureTime);
float GetCaptureTimePercentage();
void SetCaptureTimePercentage(float CaptureTimePercentage);
float GetCaptureTimeAtExit();
void SetCaptureTimeAtExit(float CaptureTimeAtExit);
GoalWrapper GetActiveGoal();
void SetActiveGoal(GoalWrapper ActiveGoal);
//END AUTO-GENERATED FROM FIELDS
//AUTO-GENERATED FROM METHODS
Vector GetBallDestination();
float GetVerticalVelocity(Vector& Destination);
Vector GetDesiredVelocity();
void AddHauntedForces();
void ScoreTrapGoal();
void SetLastTeamTouch2(unsigned char InLastTeamTouch);
void SetBallIsTrapped(unsigned int bValue, GoalWrapper Goal);
void SetBallHitData(CarWrapper HitCar, Vector& HitLocation, Vector& HitNormal, unsigned char HitType);
void TryBreakBeam(CarWrapper HitCar);
void OnCarTouch(CarWrapper HitCar, unsigned char HitType);
void ActivateHitPhysics();
void SetBallPhased(unsigned int bValue, unsigned int TeamIndex);
void SetBallTarget();
//END AUTO-GENERATED FROM METHODS
private:
PIMPL
}; | 1 | 0.648721 | 1 | 0.648721 | game-dev | MEDIA | 0.948275 | game-dev | 0.504623 | 1 | 0.504623 |
MohistMC/Youer | 2,661 | src/main/java/org/bukkit/material/TrapDoor.java | package org.bukkit.material;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
/**
* Represents a trap door
*
* @deprecated all usage of MaterialData is deprecated and subject to removal.
* Use {@link org.bukkit.block.data.BlockData}.
*/
@Deprecated
public class TrapDoor extends SimpleAttachableMaterialData implements Openable {
public TrapDoor() {
super(Material.LEGACY_TRAP_DOOR);
}
public TrapDoor(final Material type) {
super(type);
}
/**
* @param type the type
* @param data the raw data value
* @deprecated Magic value
*/
@Deprecated
public TrapDoor(final Material type, final byte data) {
super(type, data);
}
@Override
public boolean isOpen() {
return ((getData() & 0x4) == 0x4);
}
@Override
public void setOpen(boolean isOpen) {
byte data = getData();
if (isOpen) {
data |= 0x4;
} else {
data &= ~0x4;
}
setData(data);
}
/**
* Test if trapdoor is inverted
*
* @return true if inverted (top half), false if normal (bottom half)
*/
public boolean isInverted() {
return ((getData() & 0x8) != 0);
}
/**
* Set trapdoor inverted state
*
* @param inv - true if inverted (top half), false if normal (bottom half)
*/
public void setInverted(boolean inv) {
int dat = getData() & 0x7;
if (inv) {
dat |= 0x8;
}
setData((byte) dat);
}
@Override
public BlockFace getAttachedFace() {
byte data = (byte) (getData() & 0x3);
switch (data) {
case 0x0:
return BlockFace.SOUTH;
case 0x1:
return BlockFace.NORTH;
case 0x2:
return BlockFace.EAST;
case 0x3:
return BlockFace.WEST;
}
return null;
}
@Override
public void setFacingDirection(BlockFace face) {
byte data = (byte) (getData() & 0xC);
switch (face) {
case SOUTH:
data |= 0x1;
break;
case WEST:
data |= 0x2;
break;
case EAST:
data |= 0x3;
break;
}
setData(data);
}
@Override
public String toString() {
return (isOpen() ? "OPEN " : "CLOSED ") + super.toString() + " with hinges set " + getAttachedFace() + (isInverted() ? " inverted" : "");
}
@Override
public TrapDoor clone() {
return (TrapDoor) super.clone();
}
}
| 1 | 0.848807 | 1 | 0.848807 | game-dev | MEDIA | 0.648876 | game-dev | 0.665905 | 1 | 0.665905 |
gflze/CSGO-ZE-Configs | 2,231 | stripper/ze_tibia_v4_2.cfg | ;Filter ZM mode nuke to the correct team
modify:
{
match:
{
"classname" "trigger_hurt"
"targetname" "Nuke_hurt_ZM"
}
replace:
{
"filtername" "zombie"
}
}
;Apparently this is somehow setting zombie HP in the live server. No idea why, as it is filtered to ct and works fine offline...
modify:
{
match:
{
"OnStartTouch" "!activatorAddOutputhealth 9999999990-1"
}
delete:
{
"OnStartTouch" "!activatorAddOutputhealth 9999999990-1"
}
insert:
{
"OnStartTouch" "!activator,AddContext,no_nuke:1,0,-1"
}
}
add:
{
"classname" "filter_activator_context"
"targetname" "filter_no_nuke"
"origin" "-184 -1368 56"
"Negated" "1"
"ResponseContext" "no_nuke"
}
modify:
{
match:
{
"classname" "trigger_hurt"
"targetname" "Nuke_hurt"
}
insert:
{
"filtername" "filter_no_nuke"
}
}
modify:
{
match:
{
"classname" "logic_auto"
}
insert:
{
"OnMapSpawn" "playerClearContext0-1"
}
}
; __ __ ____ _____ _____ ________ __
; | \/ |/ __ \| __ \_ _| ____\ \ / /
; | \ / | | | | | | || | | |__ \ \_/ /
; | |\/| | | | | | | || | | __| \ /
; | | | | |__| | |__| || |_| | | |
; |_| |_|\____/|_____/_____|_| |_| by Małgo
;---------------------------------------------------------------
;STRIPPER CFG BY MAŁGO https://steamcommunity.com/profiles/76561197992553990/
;---------------------------------------------------------------
;---------------------------------------
;Fix too fast enable bridge stage 2
;---------------------------------------
modify:
{
match:
{
"targetname" "LVL2Relay"
"classname" "logic_relay"
}
delete:
{
"OnTrigger" "BridgeTriggerEnable21.011"
}
}
;---------------------------------------
;fix broken dragon zombie attack
;---------------------------------------
modify:
{
match:
{
"targetname" "Cave3CopperS_Dragon_Boss_attack_case"
"classname" "logic_case"
}
insert:
{
"OnCase07" "Cave3_CopperS_Floor_002FireUser10-1"
}
}
;---------------------------------------
;Delete shit trigger on stage 2 (big boy)
;---------------------------------------
modify:
{
match:
{
"targetname" "Bear_Func"
"classname" "func_breakable"
}
delete:
{
"OnBreak" "Lvl2LoseTriggerZMEnable24-1"
}
} | 1 | 0.918013 | 1 | 0.918013 | game-dev | MEDIA | 0.659203 | game-dev | 0.634403 | 1 | 0.634403 |
NYU-NEWS/janus | 1,842 | src/deptran/marshallable.h | #pragma once
#include "__dep__.h"
namespace janus {
class Marshallable {
public:
int32_t kind_{0};
// int32_t __debug_{10};
Marshallable() = delete;
explicit Marshallable(int32_t k): kind_(k) {};
virtual ~Marshallable() {
// if (__debug_ != 10) {
// verify(0);
// }
// __debug_ = 30;
// Log_debug("destruct marshallable.");
};
virtual Marshal& ToMarshal(Marshal& m) const;
virtual Marshal& FromMarshal(Marshal& m);
};
class MarshallDeputy {
public:
typedef unordered_map<int32_t, function<Marshallable*()>> MarContainer;
static MarContainer& Initializers();
static int RegInitializer(int32_t, function<Marshallable*()>);
static function<Marshallable*()> GetInitializer(int32_t);
public:
shared_ptr<Marshallable> sp_data_{nullptr};
int32_t kind_{0};
enum Kind {
UNKNOWN=0,
EMPTY_GRAPH=1,
RCC_GRAPH=2,
CONTAINER_CMD=3,
CMD_TPC_PREPARE=4,
CMD_TPC_COMMIT=5,
CMD_VEC_PIECE=6
};
/**
* This should be called by the rpc layer.
*/
MarshallDeputy() : kind_(UNKNOWN){}
/**
* This should be called by inherited class as instructor.
* @param kind
*/
explicit MarshallDeputy(shared_ptr<Marshallable> m): sp_data_(std::move(m)) {
kind_ = sp_data_->kind_;
}
Marshal& CreateActualObjectFrom(Marshal& m);
void SetMarshallable(shared_ptr<Marshallable> m) {
verify(sp_data_ == nullptr);
sp_data_ = m;
kind_ = m->kind_;
}
~MarshallDeputy() = default;
};
inline Marshal& operator>>(Marshal& m, MarshallDeputy& rhs) {
m >> rhs.kind_;
rhs.CreateActualObjectFrom(m);
return m;
}
inline Marshal& operator<<(Marshal& m, const MarshallDeputy& rhs) {
verify(rhs.kind_ != MarshallDeputy::UNKNOWN);
m << rhs.kind_;
verify(rhs.sp_data_); // must be non-empty
rhs.sp_data_->ToMarshal(m);
return m;
}
} // namespace janus;
| 1 | 0.845128 | 1 | 0.845128 | game-dev | MEDIA | 0.290534 | game-dev | 0.580357 | 1 | 0.580357 |
ldtteam/minecolonies | 11,654 | src/main/java/com/minecolonies/api/util/ChunkLoadStorage.java | package com.minecolonies.api.util;
import com.minecolonies.api.colony.IColonyTagCapability;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.chunk.LevelChunk;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.minecolonies.api.util.constant.ColonyManagerConstants.NO_COLONY_ID;
import static com.minecolonies.api.util.constant.NbtTagConstants.*;
/**
* The chunkload storage used to load chunks with colony information.
*/
public class ChunkLoadStorage
{
/**
* NBT tag for claims to add
*/
public static final String TAG_CLAIM_LIST = "claimsToAdd";
/**
* NBT tag for colonies to add.
*/
private static final String TAG_COLONIES_TO_ADD = "coloniesToAdd";
/**
* NBT tag for colonies to remove.
*/
private static final String TAG_COLONIES_TO_REMOVE = "coloniesToRemove";
/**
* The max amount of claim caches we stack
*/
private static final int MAX_CHUNK_CLAIMS = 20;
/**
* The colony id.
*/
private final List<Short> owningChanges = new ArrayList<>();
/**
* The list of colonies to be added to this loc.
*/
private final List<Short> coloniesToRemove = new ArrayList<>();
/**
* The list of colonies to be removed from this loc.
*/
private final List<Short> coloniesToAdd = new ArrayList<>();
/**
* XZ pos as long.
*/
private final long xz;
/**
* The dimension of the chunk.
*/
private final ResourceLocation dimension;
/**
* The building claiming this.
*/
private final List<Tuple<Short, BlockPos>> claimingBuilding = new ArrayList<>();
/**
* The building unclaiming this.
*/
private final List<Tuple<Short, BlockPos>> unClaimingBuilding = new ArrayList<>();
/**
* Intitialize a ChunLoadStorage from nbt.
*
* @param compound the compound to use.
*/
public ChunkLoadStorage(final CompoundTag compound)
{
if (compound.contains(TAG_ID))
{
this.owningChanges.add(compound.getShort(TAG_ID));
}
this.xz = compound.getLong(TAG_POS);
this.dimension = new ResourceLocation(compound.getString(TAG_DIMENSION));
owningChanges.addAll(NBTUtils.streamCompound(compound.getList(TAG_CLAIM_LIST, Tag.TAG_COMPOUND))
.map(tempCompound -> tempCompound.getShort(TAG_COLONY_ID)).collect(Collectors.toList()));
coloniesToAdd.addAll(NBTUtils.streamCompound(compound.getList(TAG_COLONIES_TO_ADD, Tag.TAG_COMPOUND))
.map(tempCompound -> tempCompound.getShort(TAG_COLONY_ID)).collect(Collectors.toList()));
coloniesToRemove.addAll(NBTUtils.streamCompound(compound.getList(TAG_COLONIES_TO_REMOVE, Tag.TAG_COMPOUND))
.map(tempCompound -> tempCompound.getShort(TAG_COLONY_ID)).collect(Collectors.toList()));
claimingBuilding.addAll(NBTUtils.streamCompound(compound.getList(TAG_BUILDINGS_CLAIM, Tag.TAG_COMPOUND))
.map(ChunkLoadStorage::readTupleFromNbt).collect(Collectors.toList()));
unClaimingBuilding.addAll(NBTUtils.streamCompound(compound.getList(TAG_BUILDINGS_UNCLAIM, Tag.TAG_COMPOUND))
.map(ChunkLoadStorage::readTupleFromNbt).collect(Collectors.toList()));
}
/**
* Create a new chunkload storage.
*
* @param colonyId the id of the colony.
* @param xz the chunk xz.
* @param add the operation type.
* @param dimension the dimension.
* @param forceOwnership if the colony should own the chunk.
*/
public ChunkLoadStorage(final int colonyId, final long xz, final boolean add, final ResourceLocation dimension, final boolean forceOwnership)
{
this.owningChanges.add((short) (forceOwnership && add ? colonyId : NO_COLONY_ID));
this.xz = xz;
this.dimension = dimension;
if (add)
{
coloniesToAdd.add((short) colonyId);
}
else
{
coloniesToRemove.add((short) colonyId);
}
}
/**
* Create a new chunkload storage.
*
* @param colonyId the id of the colony.
* @param xz the chunk xz.
* @param dimension the dimension.
* @param building the building claiming this chunk.
*/
public ChunkLoadStorage(final int colonyId, final long xz, final ResourceLocation dimension, final BlockPos building, final boolean add)
{
this.xz = xz;
this.dimension = dimension;
if (add)
{
claimingBuilding.add(new Tuple<>((short) colonyId, building));
}
else
{
unClaimingBuilding.add(new Tuple<>((short) colonyId, building));
}
}
/**
* Write the ChunkLoadStorage to NBT.
*
* @return the compound.
*/
public CompoundTag toNBT()
{
final CompoundTag compound = new CompoundTag();
compound.putLong(TAG_POS, xz);
compound.putString(TAG_DIMENSION, dimension.toString());
compound.put(TAG_CLAIM_LIST, owningChanges.stream().map(ChunkLoadStorage::getCompoundOfColonyId).collect(NBTUtils.toListNBT()));
compound.put(TAG_COLONIES_TO_ADD, coloniesToAdd.stream().map(ChunkLoadStorage::getCompoundOfColonyId).collect(NBTUtils.toListNBT()));
compound.put(TAG_COLONIES_TO_REMOVE, coloniesToRemove.stream().map(ChunkLoadStorage::getCompoundOfColonyId).collect(NBTUtils.toListNBT()));
compound.put(TAG_BUILDINGS, claimingBuilding.stream().map(ChunkLoadStorage::writeTupleToNBT).collect(NBTUtils.toListNBT()));
compound.put(TAG_BUILDINGS, unClaimingBuilding.stream().map(ChunkLoadStorage::writeTupleToNBT).collect(NBTUtils.toListNBT()));
return compound;
}
private static CompoundTag getCompoundOfColonyId(final int id)
{
final CompoundTag compound = new CompoundTag();
compound.putInt(TAG_COLONY_ID, id);
return compound;
}
/**
* Getter for the dimension.
*
* @return the dimension id.
*/
public ResourceLocation getDimension()
{
return dimension;
}
/**
* Get the x long.
*
* @return the long representing two integers.
*/
public long getXz()
{
return xz;
}
@Override
public boolean equals(final Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
final ChunkLoadStorage storage = (ChunkLoadStorage) o;
return xz == storage.xz &&
dimension == storage.dimension &&
Objects.equals(owningChanges, storage.owningChanges) &&
Objects.equals(coloniesToRemove, storage.coloniesToRemove) &&
Objects.equals(coloniesToAdd, storage.coloniesToAdd) &&
Objects.equals(claimingBuilding, storage.claimingBuilding) &&
Objects.equals(unClaimingBuilding, storage.unClaimingBuilding);
}
@Override
public int hashCode()
{
return Objects.hash(owningChanges, coloniesToRemove, coloniesToAdd, xz, dimension, claimingBuilding, unClaimingBuilding);
}
/**
* Apply this ChunkLoadStorage to a capability.
*
* @param chunk the chunk to apply it to.
* @param cap the capability to apply it to.
*/
public void applyToCap(final IColonyTagCapability cap, final LevelChunk chunk)
{
if (this.claimingBuilding.isEmpty() && unClaimingBuilding.isEmpty())
{
final int amountOfOperations = Math.max(Math.max(owningChanges.size(), coloniesToAdd.size()), coloniesToRemove.size());
for (int i = 0; i < amountOfOperations; i++)
{
if (i < owningChanges.size())
{
final int claimID = owningChanges.get(i);
if (claimID > NO_COLONY_ID)
{
cap.setOwningColony(claimID, chunk);
}
}
if (i < coloniesToAdd.size() && coloniesToAdd.get(i) > NO_COLONY_ID)
{
cap.addColony(coloniesToAdd.get(i), chunk);
}
if (i < coloniesToRemove.size() && coloniesToRemove.get(i) > NO_COLONY_ID)
{
cap.removeColony(coloniesToRemove.get(i), chunk);
}
}
}
else
{
for (final Tuple<Short, BlockPos> tuple : unClaimingBuilding)
{
cap.removeBuildingClaim(tuple.getA(), tuple.getB(), chunk);
}
for (final Tuple<Short, BlockPos> tuple : claimingBuilding)
{
cap.addBuildingClaim(tuple.getA(), tuple.getB(), chunk);
}
}
chunk.setUnsaved(true);
}
/**
* Check if the chunkloadstorage is empty.
*
* @return true if so.
*/
public boolean isEmpty()
{
return coloniesToAdd.isEmpty() && coloniesToRemove.isEmpty();
}
/**
* Merge the two Chunkstorages into one. The newer one is considered to be the "more up to date" version.
*
* @param newStorage the new version to add.
*/
public void merge(final ChunkLoadStorage newStorage)
{
if (this.claimingBuilding.isEmpty() && unClaimingBuilding.isEmpty())
{
owningChanges.addAll(newStorage.owningChanges);
coloniesToAdd.addAll(newStorage.coloniesToAdd);
coloniesToRemove.addAll(newStorage.coloniesToRemove);
if (coloniesToAdd.size() > MAX_CHUNK_CLAIMS)
{
owningChanges.clear();
coloniesToAdd.clear();
coloniesToRemove.clear();
}
}
else
{
this.claimingBuilding.removeIf(newStorage.unClaimingBuilding::contains);
this.unClaimingBuilding.removeIf(newStorage.claimingBuilding::contains);
for (final Tuple<Short, BlockPos> tuple : newStorage.unClaimingBuilding)
{
if (!this.unClaimingBuilding.contains(tuple))
{
this.unClaimingBuilding.add(tuple);
}
}
for (final Tuple<Short, BlockPos> tuple : newStorage.claimingBuilding)
{
if (!this.claimingBuilding.contains(tuple))
{
this.claimingBuilding.add(tuple);
}
}
}
}
/**
* Write the tuple to NBT.
*
* @param tuple the tuple to write.
* @return the resulting compound.
*/
private static CompoundTag writeTupleToNBT(final Tuple<Short, BlockPos> tuple)
{
final CompoundTag compound = new CompoundTag();
compound.putShort(TAG_COLONY_ID, tuple.getA());
BlockPosUtil.write(compound, TAG_BUILDING, tuple.getB());
return compound;
}
/**
* Read the tuple from NBT.
*
* @param compound the compound to extract it from.
* @return the tuple.
*/
private static Tuple<Short, BlockPos> readTupleFromNbt(final CompoundTag compound)
{
return new Tuple<>(compound.getShort(TAG_COLONY_ID), BlockPosUtil.read(compound, TAG_BUILDING));
}
}
| 1 | 0.880131 | 1 | 0.880131 | game-dev | MEDIA | 0.917234 | game-dev | 0.926987 | 1 | 0.926987 |
psiroki/gzdoomxxh | 38,965 | src/menu/doommenu.cpp | /*
** menu.cpp
** Menu base class and global interface
**
**---------------------------------------------------------------------------
** Copyright 2010 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
**---------------------------------------------------------------------------
**
*/
#include "c_dispatch.h"
#include "d_gui.h"
#include "c_buttons.h"
#include "c_console.h"
#include "c_bind.h"
#include "d_eventbase.h"
#include "g_input.h"
#include "configfile.h"
#include "gstrings.h"
#include "menu.h"
#include "vm.h"
#include "v_video.h"
#include "i_system.h"
#include "types.h"
#include "texturemanager.h"
#include "v_draw.h"
#include "vm.h"
#include "gamestate.h"
#include "i_interface.h"
#include "gi.h"
#include "g_game.h"
#include "g_level.h"
#include "d_event.h"
#include "p_tick.h"
#include "st_start.h"
#include "d_main.h"
#include "i_system.h"
#include "doommenu.h"
#include "r_utility.h"
#include "gameconfigfile.h"
#include "d_player.h"
#include "teaminfo.h"
#include "hwrenderer/scene/hw_drawinfo.h"
EXTERN_CVAR(Int, cl_gfxlocalization)
EXTERN_CVAR(Bool, m_quickexit)
EXTERN_CVAR(Bool, saveloadconfirmation) // [mxd]
EXTERN_CVAR(Bool, quicksaverotation)
EXTERN_CVAR(Bool, show_messages)
CVAR(Bool, m_simpleoptions, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
typedef void(*hfunc)();
DMenu* CreateMessageBoxMenu(DMenu* parent, const char* message, int messagemode, bool playsound, FName action = NAME_None, hfunc handler = nullptr);
bool OkForLocalization(FTextureID texnum, const char* substitute);
void I_WaitVBL(int count);
FNewGameStartup NewGameStartupInfo;
bool M_SetSpecialMenu(FName& menu, int param)
{
// some menus need some special treatment
switch (menu.GetIndex())
{
case NAME_Mainmenu:
if (gameinfo.gametype & GAME_DoomStrifeChex) // Raven's games always used text based menus
{
if (gameinfo.forcetextinmenus) // If text is forced, this overrides any check.
{
menu = NAME_MainmenuTextOnly;
}
else if (cl_gfxlocalization != 0 && !gameinfo.forcenogfxsubstitution)
{
// For these games we must check up-front if they get localized because in that case another template must be used.
DMenuDescriptor **desc = MenuDescriptors.CheckKey(NAME_Mainmenu);
if (desc != nullptr)
{
if ((*desc)->IsKindOf(RUNTIME_CLASS(DListMenuDescriptor)))
{
DListMenuDescriptor *ld = static_cast<DListMenuDescriptor*>(*desc);
if (ld->mFromEngine)
{
// This assumes that replacing one graphic will replace all of them.
// So this only checks the "New game" entry for localization capability.
FTextureID texid = TexMan.CheckForTexture("M_NGAME", ETextureType::MiscPatch);
if (!OkForLocalization(texid, "$MNU_NEWGAME"))
{
menu = NAME_MainmenuTextOnly;
}
}
}
}
}
}
break;
case NAME_Episodemenu:
// sent from the player class menu
NewGameStartupInfo.Skill = -1;
NewGameStartupInfo.Episode = -1;
NewGameStartupInfo.PlayerClass =
param == -1000? nullptr :
param == -1? "Random" : GetPrintableDisplayName(PlayerClasses[param].Type).GetChars();
M_StartupEpisodeMenu(&NewGameStartupInfo); // needs player class name from class menu (later)
break;
case NAME_Skillmenu:
// sent from the episode menu
if ((gameinfo.flags & GI_SHAREWARE) && param > 0)
{
// Only Doom and Heretic have multi-episode shareware versions.
M_StartMessage(GStrings("SWSTRING"), 1);
return false;
}
NewGameStartupInfo.Episode = param;
M_StartupSkillMenu(&NewGameStartupInfo); // needs player class name from class menu (later)
break;
case NAME_StartgameConfirm:
{
// sent from the skill menu for a skill that needs to be confirmed
NewGameStartupInfo.Skill = param;
const char *msg = AllSkills[param].MustConfirmText;
if (*msg==0) msg = GStrings("NIGHTMARE");
M_StartMessage (msg, 0, NAME_StartgameConfirmed);
return false;
}
case NAME_Startgame:
// sent either from skill menu or confirmation screen. Skill gets only set if sent from skill menu
// Now we can finally start the game. Ugh...
NewGameStartupInfo.Skill = param;
[[fallthrough]];
case NAME_StartgameConfirmed:
G_DeferedInitNew (&NewGameStartupInfo);
if (gamestate == GS_FULLCONSOLE)
{
gamestate = GS_HIDECONSOLE;
gameaction = ga_newgame;
}
M_ClearMenus ();
return false;
case NAME_Savegamemenu:
if (!usergame || (players[consoleplayer].health <= 0 && !multiplayer) || gamestate != GS_LEVEL)
{
// cannot save outside the game.
M_StartMessage (GStrings("SAVEDEAD"), 1);
return false;
}
break;
case NAME_Quitmenu:
// The separate menu class no longer exists but the name still needs support for existing mods.
C_DoCommand("menu_quit");
return false;
case NAME_EndGameMenu:
// The separate menu class no longer exists but the name still needs support for existing mods.
void ActivateEndGameMenu();
ActivateEndGameMenu();
return false;
case NAME_Playermenu:
menu = NAME_NewPlayerMenu; // redirect the old player menu to the new one.
break;
case NAME_Optionsmenu:
if (m_simpleoptions) menu = NAME_OptionsmenuSimple;
break;
case NAME_OptionsmenuFull:
menu = NAME_Optionsmenu;
break;
}
DMenuDescriptor** desc = MenuDescriptors.CheckKey(menu);
if (desc != nullptr)
{
if ((*desc)->mNetgameMessage.IsNotEmpty() && netgame && !demoplayback)
{
M_StartMessage((*desc)->mNetgameMessage, 1);
return false;
}
}
// End of special checks
return true;
}
//=============================================================================
//
//
//
//=============================================================================
void M_StartControlPanel(bool makeSound, bool scaleoverride)
{
if (hud_toggled)
D_ToggleHud();
// intro might call this repeatedly
if (CurrentMenu != nullptr)
return;
P_CheckTickerPaused();
if (makeSound)
{
S_Sound(CHAN_VOICE, CHANF_UI, "menu/activate", snd_menuvolume, ATTN_NONE);
}
M_DoStartControlPanel(scaleoverride);
}
//==========================================================================
//
// M_Dim
//
// Applies a colored overlay to the entire screen, with the opacity
// determined by the dimamount cvar.
//
//==========================================================================
CUSTOM_CVAR(Float, dimamount, -1.f, CVAR_ARCHIVE)
{
if (self < 0.f && self != -1.f)
{
self = -1.f;
}
else if (self > 1.f)
{
self = 1.f;
}
}
CVAR(Color, dimcolor, 0xffd700, CVAR_ARCHIVE)
void System_M_Dim()
{
PalEntry dimmer;
float amount;
if (dimamount >= 0)
{
dimmer = PalEntry(dimcolor);
amount = dimamount;
}
else
{
dimmer = gameinfo.dimcolor;
amount = gameinfo.dimamount;
}
Dim(twod, dimmer, amount, 0, 0, twod->GetWidth(), twod->GetHeight());
}
//=============================================================================
//
//
//
//=============================================================================
CCMD (menu_quit)
{ // F10
if (m_quickexit)
{
CleanSWDrawer();
ST_Endoom();
}
M_StartControlPanel (true);
const size_t messageindex = static_cast<size_t>(gametic) % gameinfo.quitmessages.Size();
FString EndString;
const char *msg = gameinfo.quitmessages[messageindex];
if (msg[0] == '$')
{
if (msg[1] == '*')
{
EndString = GStrings(msg + 2);
}
else
{
EndString.Format("%s\n\n%s", GStrings(msg + 1), GStrings("DOSY"));
}
}
else EndString = gameinfo.quitmessages[messageindex];
DMenu *newmenu = CreateMessageBoxMenu(CurrentMenu, EndString, 0, false, NAME_None, []()
{
if (!netgame)
{
if (gameinfo.quitSound.IsNotEmpty())
{
S_Sound(CHAN_VOICE, CHANF_UI, gameinfo.quitSound, snd_menuvolume, ATTN_NONE);
I_WaitVBL(105);
}
}
CleanSWDrawer();
ST_Endoom();
});
M_ActivateMenu(newmenu);
}
//=============================================================================
//
//
//
//=============================================================================
void ActivateEndGameMenu()
{
FString tempstring = GStrings(netgame ? "NETEND" : "ENDGAME");
DMenu *newmenu = CreateMessageBoxMenu(CurrentMenu, tempstring, 0, false, NAME_None, []()
{
M_ClearMenus();
if (!netgame)
{
if (demorecording)
G_CheckDemoStatus();
D_StartTitle();
}
});
M_ActivateMenu(newmenu);
}
CCMD (menu_endgame)
{ // F7
if (!usergame)
{
S_Sound (CHAN_VOICE, CHANF_UI, "menu/invalid", snd_menuvolume, ATTN_NONE);
return;
}
//M_StartControlPanel (true);
S_Sound (CHAN_VOICE, CHANF_UI, "menu/activate", snd_menuvolume, ATTN_NONE);
ActivateEndGameMenu();
}
//=============================================================================
//
//
//
//=============================================================================
CCMD (quicksave)
{ // F6
if (!usergame || (players[consoleplayer].health <= 0 && !multiplayer))
{
S_Sound (CHAN_VOICE, CHANF_UI, "menu/invalid", snd_menuvolume, ATTN_NONE);
return;
}
if (gamestate != GS_LEVEL)
return;
// If the quick save rotation is enabled, it handles the save slot.
if (quicksaverotation)
{
G_DoQuickSave();
return;
}
if (savegameManager.quickSaveSlot == NULL || savegameManager.quickSaveSlot == (FSaveGameNode*)1)
{
S_Sound(CHAN_VOICE, CHANF_UI, "menu/activate", snd_menuvolume, ATTN_NONE);
M_StartControlPanel(false);
M_SetMenu(NAME_Savegamemenu);
return;
}
// [mxd]. Just save the game, no questions asked.
if (!saveloadconfirmation)
{
G_SaveGame(savegameManager.quickSaveSlot->Filename.GetChars(), savegameManager.quickSaveSlot->SaveTitle.GetChars());
return;
}
S_Sound(CHAN_VOICE, CHANF_UI, "menu/activate", snd_menuvolume, ATTN_NONE);
FString tempstring = GStrings("QSPROMPT");
tempstring.Substitute("%s", savegameManager.quickSaveSlot->SaveTitle.GetChars());
DMenu *newmenu = CreateMessageBoxMenu(CurrentMenu, tempstring, 0, false, NAME_None, []()
{
G_SaveGame(savegameManager.quickSaveSlot->Filename.GetChars(), savegameManager.quickSaveSlot->SaveTitle.GetChars());
S_Sound(CHAN_VOICE, CHANF_UI, "menu/dismiss", snd_menuvolume, ATTN_NONE);
M_ClearMenus();
});
M_ActivateMenu(newmenu);
}
//=============================================================================
//
//
//
//=============================================================================
CCMD (quickload)
{ // F9
if (netgame)
{
M_StartControlPanel(true);
M_StartMessage (GStrings("QLOADNET"), 1);
return;
}
if (savegameManager.quickSaveSlot == NULL || savegameManager.quickSaveSlot == (FSaveGameNode*)1)
{
M_StartControlPanel(true);
// signal that whatever gets loaded should be the new quicksave
savegameManager.quickSaveSlot = (FSaveGameNode *)1;
M_SetMenu(NAME_Loadgamemenu);
return;
}
// [mxd]. Just load the game, no questions asked.
if (!saveloadconfirmation)
{
G_LoadGame(savegameManager.quickSaveSlot->Filename.GetChars());
return;
}
FString tempstring = GStrings("QLPROMPT");
tempstring.Substitute("%s", savegameManager.quickSaveSlot->SaveTitle.GetChars());
M_StartControlPanel(true);
DMenu *newmenu = CreateMessageBoxMenu(CurrentMenu, tempstring, 0, false, NAME_None, []()
{
G_LoadGame(savegameManager.quickSaveSlot->Filename.GetChars());
S_Sound(CHAN_VOICE, CHANF_UI, "menu/dismiss", snd_menuvolume, ATTN_NONE);
M_ClearMenus();
});
M_ActivateMenu(newmenu);
}
//
// Toggle messages on/off
//
CCMD (togglemessages)
{
if (show_messages)
{
Printf(TEXTCOLOR_RED "%s\n", GStrings("MSGOFF"));
show_messages = false;
}
else
{
show_messages = true;
Printf(TEXTCOLOR_RED "%s\n", GStrings("MSGON"));
}
}
EXTERN_CVAR (Int, screenblocks)
CCMD (sizedown)
{
screenblocks = screenblocks - 1;
S_Sound (CHAN_VOICE, CHANF_UI, "menu/change", snd_menuvolume, ATTN_NONE);
}
CCMD (sizeup)
{
screenblocks = screenblocks + 1;
S_Sound (CHAN_VOICE, CHANF_UI, "menu/change", snd_menuvolume, ATTN_NONE);
}
CCMD(reset2defaults)
{
C_SetDefaultBindings ();
C_SetCVarsToDefaults ();
R_SetViewSize (screenblocks);
}
CCMD(reset2saved)
{
GameConfig->DoGlobalSetup ();
GameConfig->DoGameSetup (gameinfo.ConfigName);
GameConfig->DoModSetup (gameinfo.ConfigName);
R_SetViewSize (screenblocks);
}
CCMD(resetb2defaults)
{
C_SetDefaultBindings ();
}
//=============================================================================
//
// Creates the episode menu
// Falls back on an option menu if there's not enough screen space to show all episodes
//
//=============================================================================
void M_StartupEpisodeMenu(FNewGameStartup *gs)
{
// Build episode menu
bool success = false;
bool isOld = false;
DMenuDescriptor **desc = MenuDescriptors.CheckKey(NAME_Episodemenu);
if (desc != nullptr)
{
if ((*desc)->IsKindOf(RUNTIME_CLASS(DListMenuDescriptor)))
{
DListMenuDescriptor *ld = static_cast<DListMenuDescriptor*>(*desc);
// Delete previous contents
for(unsigned i=0; i<ld->mItems.Size(); i++)
{
FName n = ld->mItems[i]->mAction;
if (n == NAME_Skillmenu)
{
isOld = true;
ld->mItems.Resize(i);
break;
}
}
int posx = (int)ld->mXpos;
int posy = (int)ld->mYpos;
int topy = posy;
// Get lowest y coordinate of any static item in the menu
for(unsigned i = 0; i < ld->mItems.Size(); i++)
{
int y = (int)ld->mItems[i]->GetY();
if (y < topy) topy = y;
}
int spacing = ld->mLinespacing;
for (unsigned i = 0; i < AllEpisodes.Size(); i++)
{
if (AllEpisodes[i].mPicName.IsNotEmpty())
{
FTextureID tex = GetMenuTexture(AllEpisodes[i].mPicName);
if (AllEpisodes[i].mEpisodeName.IsEmpty() || OkForLocalization(tex, AllEpisodes[i].mEpisodeName))
continue;
}
if ((gameinfo.gametype & GAME_DoomStrifeChex) && spacing == 16) spacing = 18;
break;
}
// center the menu on the screen if the top space is larger than the bottom space
int totalheight = posy + AllEpisodes.Size() * spacing - topy;
if (totalheight < 190 || AllEpisodes.Size() == 1)
{
int newtop = (200 - totalheight) / 2;
int topdelta = newtop - topy;
if (topdelta < 0)
{
for(unsigned i = 0; i < ld->mItems.Size(); i++)
{
ld->mItems[i]->OffsetPositionY(topdelta);
}
posy += topdelta;
ld->mYpos += topdelta;
}
if (!isOld) ld->mSelectedItem = ld->mItems.Size();
for (unsigned i = 0; i < AllEpisodes.Size(); i++)
{
DMenuItemBase *it = nullptr;
if (AllEpisodes[i].mPicName.IsNotEmpty())
{
FTextureID tex = GetMenuTexture(AllEpisodes[i].mPicName);
if (AllEpisodes[i].mEpisodeName.IsEmpty() || OkForLocalization(tex, AllEpisodes[i].mEpisodeName))
continue; // We do not measure patch based entries. They are assumed to fit
}
const char *c = AllEpisodes[i].mEpisodeName;
if (*c == '$') c = GStrings(c + 1);
int textwidth = ld->mFont->StringWidth(c);
int textright = posx + textwidth;
if (posx + textright > 320) posx = std::max(0, 320 - textright);
}
for(unsigned i = 0; i < AllEpisodes.Size(); i++)
{
DMenuItemBase *it = nullptr;
if (AllEpisodes[i].mPicName.IsNotEmpty())
{
FTextureID tex = GetMenuTexture(AllEpisodes[i].mPicName);
if (AllEpisodes[i].mEpisodeName.IsEmpty() || OkForLocalization(tex, AllEpisodes[i].mEpisodeName))
it = CreateListMenuItemPatch(posx, posy, spacing, AllEpisodes[i].mShortcut, tex, NAME_Skillmenu, i);
}
if (it == nullptr)
{
it = CreateListMenuItemText(posx, posy, spacing, AllEpisodes[i].mShortcut,
AllEpisodes[i].mEpisodeName, ld->mFont, ld->mFontColor, ld->mFontColor2, NAME_Skillmenu, i);
}
ld->mItems.Push(it);
posy += spacing;
}
if (AllEpisodes.Size() == 1)
{
ld->mAutoselect = ld->mSelectedItem;
}
success = true;
for (auto &p : ld->mItems)
{
GC::WriteBarrier(*desc, p);
}
}
}
else return; // do not recreate the option menu variant, because it is always text based.
}
if (!success)
{
// Couldn't create the episode menu, either because there's too many episodes or some error occured
// Create an option menu for episode selection instead.
DOptionMenuDescriptor *od = Create<DOptionMenuDescriptor>();
MenuDescriptors[NAME_Episodemenu] = od;
od->mMenuName = NAME_Episodemenu;
od->mFont = gameinfo.gametype == GAME_Doom ? BigUpper : BigFont;
od->mTitle = "$MNU_EPISODE";
od->mSelectedItem = 0;
od->mScrollPos = 0;
od->mClass = nullptr;
od->mPosition = -15;
od->mScrollTop = 0;
od->mIndent = 160;
od->mDontDim = false;
GC::WriteBarrier(od);
for(unsigned i = 0; i < AllEpisodes.Size(); i++)
{
auto it = CreateOptionMenuItemSubmenu(AllEpisodes[i].mEpisodeName, "Skillmenu", i);
od->mItems.Push(it);
GC::WriteBarrier(od, it);
}
}
}
//=============================================================================
//
//
//
//=============================================================================
static void BuildPlayerclassMenu()
{
bool success = false;
// Build player class menu
DMenuDescriptor **desc = MenuDescriptors.CheckKey(NAME_Playerclassmenu);
if (desc != nullptr)
{
if ((*desc)->IsKindOf(RUNTIME_CLASS(DListMenuDescriptor)))
{
DListMenuDescriptor *ld = static_cast<DListMenuDescriptor*>(*desc);
// add player display
ld->mSelectedItem = ld->mItems.Size();
int posy = (int)ld->mYpos;
int topy = posy;
// Get lowest y coordinate of any static item in the menu
for(unsigned i = 0; i < ld->mItems.Size(); i++)
{
int y = (int)ld->mItems[i]->GetY();
if (y < topy) topy = y;
}
// Count the number of items this menu will show
int numclassitems = 0;
for (unsigned i = 0; i < PlayerClasses.Size (); i++)
{
if (!(PlayerClasses[i].Flags & PCF_NOMENU))
{
const char *pname = GetPrintableDisplayName(PlayerClasses[i].Type);
if (pname != nullptr)
{
numclassitems++;
}
}
}
// center the menu on the screen if the top space is larger than the bottom space
int totalheight = posy + (numclassitems+1) * ld->mLinespacing - topy;
if (numclassitems <= 1)
{
// create a dummy item that auto-chooses the default class.
auto it = CreateListMenuItemText(0, 0, 0, 'p', "player",
ld->mFont,ld->mFontColor, ld->mFontColor2, NAME_Episodemenu, -1000);
ld->mAutoselect = ld->mItems.Push(it);
success = true;
}
else if (totalheight <= 190)
{
int newtop = (200 - totalheight + topy) / 2;
int topdelta = newtop - topy;
if (topdelta < 0)
{
for(unsigned i = 0; i < ld->mItems.Size(); i++)
{
ld->mItems[i]->OffsetPositionY(topdelta);
}
posy -= topdelta;
}
int n = 0;
for (unsigned i = 0; i < PlayerClasses.Size (); i++)
{
if (!(PlayerClasses[i].Flags & PCF_NOMENU))
{
const char *pname = GetPrintableDisplayName(PlayerClasses[i].Type);
if (pname != nullptr)
{
auto it = CreateListMenuItemText(ld->mXpos, ld->mYpos, ld->mLinespacing, *pname,
pname, ld->mFont,ld->mFontColor,ld->mFontColor2, NAME_Episodemenu, i);
ld->mItems.Push(it);
ld->mYpos += ld->mLinespacing;
n++;
}
}
}
if (n > 1 && !gameinfo.norandomplayerclass)
{
auto it = CreateListMenuItemText(ld->mXpos, ld->mYpos, ld->mLinespacing, 'r',
"$MNU_RANDOM", ld->mFont,ld->mFontColor,ld->mFontColor2, NAME_Episodemenu, -1);
ld->mItems.Push(it);
}
if (n == 0)
{
const char *pname = GetPrintableDisplayName(PlayerClasses[0].Type);
if (pname != nullptr)
{
auto it = CreateListMenuItemText(ld->mXpos, ld->mYpos, ld->mLinespacing, *pname,
pname, ld->mFont,ld->mFontColor,ld->mFontColor2, NAME_Episodemenu, 0);
ld->mItems.Push(it);
}
}
success = true;
for (auto &p : ld->mItems)
{
GC::WriteBarrier(ld, p);
}
}
}
}
if (!success)
{
// Couldn't create the playerclass menu, either because there's too many episodes or some error occured
// Create an option menu for class selection instead.
DOptionMenuDescriptor *od = Create<DOptionMenuDescriptor>();
MenuDescriptors[NAME_Playerclassmenu] = od;
od->mMenuName = NAME_Playerclassmenu;
od->mFont = gameinfo.gametype == GAME_Doom ? BigUpper : BigFont;
od->mTitle = "$MNU_CHOOSECLASS";
od->mSelectedItem = 0;
od->mScrollPos = 0;
od->mClass = nullptr;
od->mPosition = -15;
od->mScrollTop = 0;
od->mIndent = 160;
od->mDontDim = false;
od->mNetgameMessage = "$NEWGAME";
GC::WriteBarrier(od);
for (unsigned i = 0; i < PlayerClasses.Size (); i++)
{
if (!(PlayerClasses[i].Flags & PCF_NOMENU))
{
const char *pname = GetPrintableDisplayName(PlayerClasses[i].Type);
if (pname != nullptr)
{
auto it = CreateOptionMenuItemSubmenu(pname, "Episodemenu", i);
od->mItems.Push(it);
GC::WriteBarrier(od, it);
}
}
}
auto it = CreateOptionMenuItemSubmenu("Random", "Episodemenu", -1);
od->mItems.Push(it);
GC::WriteBarrier(od, it);
}
}
//=============================================================================
//
// Reads any XHAIRS lumps for the names of crosshairs and
// adds them to the display options menu.
//
//=============================================================================
static void InitCrosshairsList()
{
int lastlump, lump;
lastlump = 0;
FOptionValues **opt = OptionValues.CheckKey(NAME_Crosshairs);
if (opt == nullptr)
{
return; // no crosshair value list present. No need to go on.
}
FOptionValues::Pair *pair = &(*opt)->mValues[(*opt)->mValues.Reserve(1)];
pair->Value = 0;
pair->Text = "None";
while ((lump = fileSystem.FindLump("XHAIRS", &lastlump)) != -1)
{
FScanner sc(lump);
while (sc.GetNumber())
{
FOptionValues::Pair value;
value.Value = sc.Number;
sc.MustGetString();
value.Text = sc.String;
if (value.Value != 0)
{ // Check if it already exists. If not, add it.
unsigned int i;
for (i = 1; i < (*opt)->mValues.Size(); ++i)
{
if ((*opt)->mValues[i].Value == value.Value)
{
break;
}
}
if (i < (*opt)->mValues.Size())
{
(*opt)->mValues[i].Text = value.Text;
}
else
{
(*opt)->mValues.Push(value);
}
}
}
}
}
//=============================================================================
//
// With the current workings of the menu system this cannot be done any longer
// from within the respective CCMDs.
//
//=============================================================================
static void InitKeySections()
{
DMenuDescriptor **desc = MenuDescriptors.CheckKey(NAME_CustomizeControls);
if (desc != nullptr)
{
if ((*desc)->IsKindOf(RUNTIME_CLASS(DOptionMenuDescriptor)))
{
DOptionMenuDescriptor *menu = static_cast<DOptionMenuDescriptor*>(*desc);
for (unsigned i = 0; i < KeySections.Size(); i++)
{
FKeySection *sect = &KeySections[i];
DMenuItemBase *item = CreateOptionMenuItemStaticText(" ");
menu->mItems.Push(item);
item = CreateOptionMenuItemStaticText(sect->mTitle, 1);
menu->mItems.Push(item);
for (unsigned j = 0; j < sect->mActions.Size(); j++)
{
FKeyAction *act = §->mActions[j];
item = CreateOptionMenuItemControl(act->mTitle, act->mAction, &Bindings);
menu->mItems.Push(item);
}
}
for (auto &p : menu->mItems)
{
GC::WriteBarrier(*desc, p);
}
}
}
}
//=============================================================================
//
// Special menus will be created once all engine data is loaded
//
//=============================================================================
void M_CreateGameMenus()
{
BuildPlayerclassMenu();
InitCrosshairsList();
InitKeySections();
auto opt = OptionValues.CheckKey(NAME_PlayerTeam);
if (opt != nullptr)
{
auto op = *opt;
op->mValues.Resize(Teams.Size() + 1);
op->mValues[0].Value = 0;
op->mValues[0].Text = "$OPTVAL_NONE";
for (unsigned i = 0; i < Teams.Size(); i++)
{
op->mValues[i+1].Value = i+1;
op->mValues[i+1].Text = Teams[i].GetName();
}
}
opt = OptionValues.CheckKey(NAME_PlayerClass);
if (opt != nullptr)
{
auto op = *opt;
int o = 0;
if (!gameinfo.norandomplayerclass && PlayerClasses.Size() > 1)
{
op->mValues.Resize(PlayerClasses.Size()+1);
op->mValues[0].Value = -1;
op->mValues[0].Text = "$MNU_RANDOM";
o = 1;
}
else op->mValues.Resize(PlayerClasses.Size());
for (unsigned i = 0; i < PlayerClasses.Size(); i++)
{
op->mValues[i+o].Value = i;
op->mValues[i+o].Text = GetPrintableDisplayName(PlayerClasses[i].Type);
}
}
}
DEFINE_ACTION_FUNCTION(DNewPlayerMenu, UpdateColorsets)
{
PARAM_PROLOGUE;
PARAM_POINTER(playerClass, FPlayerClass);
TArray<int> PlayerColorSets;
EnumColorSets(playerClass->Type, &PlayerColorSets);
auto opt = OptionValues.CheckKey(NAME_PlayerColors);
if (opt != nullptr)
{
auto op = *opt;
op->mValues.Resize(PlayerColorSets.Size() + 1);
op->mValues[0].Value = -1;
op->mValues[0].Text = "$OPTVAL_CUSTOM";
for (unsigned i = 0; i < PlayerColorSets.Size(); i++)
{
auto cset = GetColorSet(playerClass->Type, PlayerColorSets[i]);
op->mValues[i + 1].Value = PlayerColorSets[i];
op->mValues[i + 1].Text = cset? cset->Name.GetChars() : "?"; // The null case should never happen here.
}
}
return 0;
}
DEFINE_ACTION_FUNCTION(DNewPlayerMenu, UpdateSkinOptions)
{
PARAM_PROLOGUE;
PARAM_POINTER(playerClass, FPlayerClass);
auto opt = OptionValues.CheckKey(NAME_PlayerSkin);
if (opt != nullptr)
{
auto op = *opt;
if ((GetDefaultByType(playerClass->Type)->flags4 & MF4_NOSKIN) || players[consoleplayer].userinfo.GetPlayerClassNum() == -1)
{
op->mValues.Resize(1);
op->mValues[0].Value = -1;
op->mValues[0].Text = "$OPTVAL_DEFAULT";
}
else
{
op->mValues.Clear();
for (unsigned i = 0; i < Skins.Size(); i++)
{
op->mValues.Reserve(1);
op->mValues.Last().Value = i;
op->mValues.Last().Text = Skins[i].Name;
}
}
}
return 0;
}
//=============================================================================
//
// The skill menu must be refeshed each time it starts up
//
//=============================================================================
extern int restart;
void M_StartupSkillMenu(FNewGameStartup *gs)
{
static int done = -1;
bool success = false;
TArray<FSkillInfo*> MenuSkills;
TArray<int> SkillIndices;
if (MenuSkills.Size() == 0)
{
for (unsigned ind = 0; ind < AllSkills.Size(); ind++)
{
if (!AllSkills[ind].NoMenu)
{
MenuSkills.Push(&AllSkills[ind]);
SkillIndices.Push(ind);
}
}
}
if (MenuSkills.Size() == 0) I_Error("No valid skills for menu found. At least one must be defined.");
int defskill = DefaultSkill;
if ((unsigned int)defskill >= MenuSkills.Size())
{
defskill = SkillIndices[(MenuSkills.Size() - 1) / 2];
}
if (AllSkills[defskill].NoMenu)
{
for (defskill = 0; defskill < (int)AllSkills.Size(); defskill++)
{
if (!AllSkills[defskill].NoMenu) break;
}
}
int defindex = 0;
for (unsigned i = 0; i < MenuSkills.Size(); i++)
{
if (MenuSkills[i] == &AllSkills[defskill])
{
defindex = i;
break;
}
}
DMenuDescriptor **desc = MenuDescriptors.CheckKey(NAME_Skillmenu);
if (desc != nullptr)
{
if ((*desc)->IsKindOf(RUNTIME_CLASS(DListMenuDescriptor)))
{
DListMenuDescriptor *ld = static_cast<DListMenuDescriptor*>(*desc);
int posx = (int)ld->mXpos;
int y = (int)ld->mYpos;
// Delete previous contents
for(unsigned i=0; i<ld->mItems.Size(); i++)
{
FName n = ld->mItems[i]->mAction;
if (n == NAME_Startgame || n == NAME_StartgameConfirm)
{
ld->mItems.Resize(i);
break;
}
}
int spacing = ld->mLinespacing;
//if (done != restart)
{
//done = restart;
ld->mSelectedItem = ld->mItems.Size() + defindex;
int posy = y;
int topy = posy;
// Get lowest y coordinate of any static item in the menu
for(unsigned i = 0; i < ld->mItems.Size(); i++)
{
int y = (int)ld->mItems[i]->GetY();
if (y < topy) topy = y;
}
for (unsigned i = 0; i < MenuSkills.Size(); i++)
{
if (MenuSkills[i]->PicName.IsNotEmpty())
{
FTextureID tex = GetMenuTexture(MenuSkills[i]->PicName);
if (MenuSkills[i]->MenuName.IsEmpty() || OkForLocalization(tex, MenuSkills[i]->MenuName))
continue;
}
if ((gameinfo.gametype & GAME_DoomStrifeChex) && spacing == 16) spacing = 18;
break;
}
// center the menu on the screen if the top space is larger than the bottom space
int totalheight = posy + MenuSkills.Size() * spacing - topy;
if (totalheight < 190 || MenuSkills.Size() == 1)
{
int newtop = (200 - totalheight) / 2;
int topdelta = newtop - topy;
if (topdelta < 0)
{
for(unsigned i = 0; i < ld->mItems.Size(); i++)
{
ld->mItems[i]->OffsetPositionY(topdelta);
}
ld->mYpos = y = posy + topdelta;
}
}
else
{
// too large
desc = nullptr;
done = false;
goto fail;
}
}
for (unsigned int i = 0; i < MenuSkills.Size(); i++)
{
FSkillInfo &skill = *MenuSkills[i];
DMenuItemBase *li = nullptr;
FString *pItemText = nullptr;
if (gs->PlayerClass != nullptr)
{
pItemText = skill.MenuNamesForPlayerClass.CheckKey(gs->PlayerClass);
}
if (skill.PicName.Len() != 0 && pItemText == nullptr)
{
FTextureID tex = GetMenuTexture(skill.PicName);
if (skill.MenuName.IsEmpty() || OkForLocalization(tex, skill.MenuName))
continue;
}
const char *c = pItemText ? pItemText->GetChars() : skill.MenuName.GetChars();
if (*c == '$') c = GStrings(c + 1);
int textwidth = ld->mFont->StringWidth(c);
int textright = posx + textwidth;
if (posx + textright > 320) posx = std::max(0, 320 - textright);
}
unsigned firstitem = ld->mItems.Size();
for(unsigned int i = 0; i < MenuSkills.Size(); i++)
{
FSkillInfo &skill = *MenuSkills[i];
DMenuItemBase *li = nullptr;
// Using a different name for skills that must be confirmed makes handling this easier.
FName action = (skill.MustConfirm && !AllEpisodes[gs->Episode].mNoSkill) ?
NAME_StartgameConfirm : NAME_Startgame;
FString *pItemText = nullptr;
if (gs->PlayerClass != nullptr)
{
pItemText = skill.MenuNamesForPlayerClass.CheckKey(gs->PlayerClass);
}
EColorRange color = (EColorRange)skill.GetTextColor();
if (color == CR_UNTRANSLATED) color = ld->mFontColor;
if (skill.PicName.Len() != 0 && pItemText == nullptr)
{
FTextureID tex = GetMenuTexture(skill.PicName);
if (skill.MenuName.IsEmpty() || OkForLocalization(tex, skill.MenuName))
li = CreateListMenuItemPatch(posx, y, spacing, skill.Shortcut, tex, action, SkillIndices[i]);
}
if (li == nullptr)
{
li = CreateListMenuItemText(posx, y, spacing, skill.Shortcut,
pItemText? *pItemText : skill.MenuName, ld->mFont, color,ld->mFontColor2, action, SkillIndices[i]);
}
ld->mItems.Push(li);
GC::WriteBarrier(*desc, li);
y += spacing;
}
if (AllEpisodes[gs->Episode].mNoSkill || MenuSkills.Size() == 1)
{
ld->mAutoselect = firstitem + defindex;
}
else
{
ld->mAutoselect = -1;
}
success = true;
}
}
if (success) return;
fail:
// Option menu fallback for overlong skill lists
DOptionMenuDescriptor *od;
if (desc == nullptr)
{
od = Create<DOptionMenuDescriptor>();
MenuDescriptors[NAME_Skillmenu] = od;
od->mMenuName = NAME_Skillmenu;
od->mFont = gameinfo.gametype == GAME_Doom ? BigUpper : BigFont;
od->mTitle = "$MNU_CHOOSESKILL";
od->mSelectedItem = defindex;
od->mScrollPos = 0;
od->mClass = nullptr;
od->mPosition = -15;
od->mScrollTop = 0;
od->mIndent = 160;
od->mDontDim = false;
GC::WriteBarrier(od);
}
else
{
od = static_cast<DOptionMenuDescriptor*>(*desc);
od->mItems.Clear();
}
for(unsigned int i = 0; i < MenuSkills.Size(); i++)
{
FSkillInfo &skill = *MenuSkills[i];
DMenuItemBase *li;
// Using a different name for skills that must be confirmed makes handling this easier.
const char *action = (skill.MustConfirm && !AllEpisodes[gs->Episode].mNoSkill) ?
"StartgameConfirm" : "Startgame";
FString *pItemText = nullptr;
if (gs->PlayerClass != nullptr)
{
pItemText = skill.MenuNamesForPlayerClass.CheckKey(gs->PlayerClass);
}
li = CreateOptionMenuItemSubmenu(pItemText? *pItemText : skill.MenuName, action, SkillIndices[i]);
od->mItems.Push(li);
GC::WriteBarrier(od, li);
if (!done)
{
done = true;
od->mSelectedItem = defindex;
}
}
}
//==========================================================================
//
// Defines how graphics substitution is handled.
// 0: Never replace a text-containing graphic with a font-based text.
// 1: Always replace, regardless of any missing information. Useful for testing the substitution without providing full data.
// 2: Only replace for non-default texts, i.e. if some language redefines the string's content, use it instead of the graphic. Never replace a localized graphic.
// 3: Only replace if the string is not the default and the graphic comes from the IWAD. Never replace a localized graphic.
// 4: Like 1, but lets localized graphics pass.
//
// The default is 3, which only replaces known content with non-default texts.
//
//==========================================================================
CUSTOM_CVAR(Int, cl_gfxlocalization, 3, CVAR_ARCHIVE)
{
if (self < 0 || self > 4) self = 0;
}
bool OkForLocalization(FTextureID texnum, const char* substitute)
{
if (!texnum.isValid()) return false;
// First the unconditional settings, 0='never' and 1='always'.
if (cl_gfxlocalization == 1 || gameinfo.forcetextinmenus) return false;
if (cl_gfxlocalization == 0 || gameinfo.forcenogfxsubstitution) return true;
return TexMan.OkForLocalization(texnum, substitute, cl_gfxlocalization);
}
bool CheckSkipGameOptionBlock(const char *str)
{
bool filter = false;
if (!stricmp(str, "ReadThis")) filter |= gameinfo.drawreadthis;
else if (!stricmp(str, "Swapmenu")) filter |= gameinfo.swapmenu;
return filter;
}
void SetDefaultMenuColors()
{
OptionSettings.mTitleColor = V_FindFontColor(gameinfo.mTitleColor);
OptionSettings.mFontColor = V_FindFontColor(gameinfo.mFontColor);
OptionSettings.mFontColorValue = V_FindFontColor(gameinfo.mFontColorValue);
OptionSettings.mFontColorMore = V_FindFontColor(gameinfo.mFontColorMore);
OptionSettings.mFontColorHeader = V_FindFontColor(gameinfo.mFontColorHeader);
OptionSettings.mFontColorHighlight = V_FindFontColor(gameinfo.mFontColorHighlight);
OptionSettings.mFontColorSelection = V_FindFontColor(gameinfo.mFontColorSelection);
auto cls = PClass::FindClass("DoomMenuDelegate");
menuDelegate = cls->CreateNew();
}
CCMD (menu_main)
{
if (gamestate == GS_FULLCONSOLE) gamestate = GS_MENUSCREEN;
M_StartControlPanel(true);
M_SetMenu(NAME_Mainmenu, -1);
}
CCMD (menu_load)
{ // F3
M_StartControlPanel (true);
M_SetMenu(NAME_Loadgamemenu, -1);
}
CCMD (menu_save)
{ // F2
M_StartControlPanel (true);
M_SetMenu(NAME_Savegamemenu, -1);
}
CCMD (menu_help)
{ // F1
M_StartControlPanel (true);
M_SetMenu(NAME_Readthismenu, -1);
}
CCMD (menu_game)
{
M_StartControlPanel (true);
M_SetMenu(NAME_Playerclassmenu, -1); // The playerclass menu is the first in the 'start game' chain
}
CCMD (menu_options)
{
M_StartControlPanel (true);
M_SetMenu(NAME_Optionsmenu, -1);
}
CCMD (menu_player)
{
M_StartControlPanel (true);
M_SetMenu(NAME_Playermenu, -1);
}
CCMD (menu_messages)
{
M_StartControlPanel (true);
M_SetMenu(NAME_MessageOptions, -1);
}
CCMD (menu_automap)
{
M_StartControlPanel (true);
M_SetMenu(NAME_AutomapOptions, -1);
}
CCMD (menu_scoreboard)
{
M_StartControlPanel (true);
M_SetMenu(NAME_ScoreboardOptions, -1);
}
CCMD (menu_mapcolors)
{
M_StartControlPanel (true);
M_SetMenu(NAME_MapColorMenu, -1);
}
CCMD (menu_keys)
{
M_StartControlPanel (true);
M_SetMenu(NAME_CustomizeControls, -1);
}
CCMD (menu_gameplay)
{
M_StartControlPanel (true);
M_SetMenu(NAME_GameplayOptions, -1);
}
CCMD (menu_compatibility)
{
M_StartControlPanel (true);
M_SetMenu(NAME_CompatibilityOptions, -1);
}
CCMD (menu_mouse)
{
M_StartControlPanel (true);
M_SetMenu(NAME_MouseOptions, -1);
}
CCMD (menu_joystick)
{
M_StartControlPanel (true);
M_SetMenu(NAME_JoystickOptions, -1);
}
CCMD (menu_sound)
{
M_StartControlPanel (true);
M_SetMenu(NAME_SoundOptions, -1);
}
CCMD (menu_advsound)
{
M_StartControlPanel (true);
M_SetMenu(NAME_AdvSoundOptions, -1);
}
CCMD (menu_modreplayer)
{
M_StartControlPanel(true);
M_SetMenu(NAME_ModReplayerOptions, -1);
}
CCMD (menu_display)
{
M_StartControlPanel (true);
M_SetMenu(NAME_VideoOptions, -1);
}
CCMD (menu_video)
{
M_StartControlPanel (true);
M_SetMenu(NAME_VideoModeMenu, -1);
}
#ifdef _WIN32
EXTERN_CVAR(Bool, vr_enable_quadbuffered)
#endif
void UpdateVRModes(bool considerQuadBuffered)
{
FOptionValues** pVRModes = OptionValues.CheckKey("VRMode");
if (pVRModes == nullptr) return;
TArray<FOptionValues::Pair>& vals = (*pVRModes)->mValues;
TArray<FOptionValues::Pair> filteredValues;
int cnt = vals.Size();
for (int i = 0; i < cnt; ++i) {
auto const& mode = vals[i];
if (mode.Value == 7) { // Quad-buffered stereo
#ifdef _WIN32
if (!vr_enable_quadbuffered) continue;
#else
continue; // Remove quad-buffered option on Mac and Linux
#endif
if (!considerQuadBuffered) continue; // Probably no compatible screen mode was found
}
filteredValues.Push(mode);
}
vals = filteredValues;
}
| 1 | 0.950451 | 1 | 0.950451 | game-dev | MEDIA | 0.97491 | game-dev | 0.920507 | 1 | 0.920507 |
ColumbusUtrigas/ColumbusEngine | 22,812 | Lib/compressonator/applications/_plugins/common/pluginmanager.cpp | //=====================================================================
// Copyright 2016-2024 (c), Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND 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.
//
/// \file PluginManager.cpp
/// \version 3.1
/// \brief Declares the interface to the Compressonator SDK
//=====================================================================
#include "pluginmanager.h"
// Windows Header Files:
#ifdef _WIN32
#include <windows.h>
#define USE_NewLoader
#endif
#include <string>
#ifdef USE_NewLoader
#pragma warning(disable : 4091) //'fopen': This function or variable may be unsafe.
#include "imagehlp.h"
#pragma comment(lib, "imagehlp.lib")
bool GetDLLFileExports(LPCSTR szFileName, std::vector<std::string>& names)
{
//printf("%s\n",__FUNCTION__);
_LOADED_IMAGE LoadedImage;
if (!MapAndLoad(szFileName, NULL, &LoadedImage, TRUE, TRUE))
return false;
_IMAGE_EXPORT_DIRECTORY* ImageExportDirectory;
ULONG DataSize;
ImageExportDirectory = (_IMAGE_EXPORT_DIRECTORY*)ImageDirectoryEntryToData(LoadedImage.MappedAddress, false, IMAGE_DIRECTORY_ENTRY_EXPORT, &DataSize);
if (ImageExportDirectory != NULL)
{
DWORD* dExportNameAddress(0);
char* FileExportName;
dExportNameAddress = (DWORD*)ImageRvaToVa(LoadedImage.FileHeader, LoadedImage.MappedAddress, ImageExportDirectory->AddressOfNames, NULL);
if (!dExportNameAddress)
{
UnMapAndLoad(&LoadedImage);
return false;
}
for (size_t i = 0; i < ImageExportDirectory->NumberOfNames; i++)
{
FileExportName = (char*)ImageRvaToVa(LoadedImage.FileHeader, LoadedImage.MappedAddress, dExportNameAddress[i], NULL);
if (FileExportName)
names.push_back(FileExportName);
}
}
UnMapAndLoad(&LoadedImage);
// This code that does not use MapAndLoad() and is much lower level
// unsigned int nNoOfExports;
//
// HANDLE hFile;
// HANDLE hFileMapping;
// LPVOID lpFileBase;
// PIMAGE_DOS_HEADER pImg_DOS_Header;
// PIMAGE_NT_HEADERS pImg_NT_Header;
// PIMAGE_EXPORT_DIRECTORY pImg_Export_Dir;
//
// hFile = CreateFileA(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// if (hFile == INVALID_HANDLE_VALUE)
// return false;
//
// hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
// if (hFileMapping == 0)
// {
// CloseHandle(hFile);
// return false;
// }
//
// lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
// if (lpFileBase == 0)
// {
// CloseHandle(hFileMapping);
// CloseHandle(hFile);
// return false;
// }
//
// pImg_DOS_Header = (PIMAGE_DOS_HEADER)lpFileBase;
//
// pImg_NT_Header = (PIMAGE_NT_HEADERS)((BYTE*)pImg_DOS_Header + pImg_DOS_Header->e_lfanew);
//
// if (IsBadReadPtr(pImg_NT_Header, sizeof(IMAGE_NT_HEADERS)) || pImg_NT_Header->Signature != IMAGE_NT_SIGNATURE)
// {
// UnmapViewOfFile(lpFileBase);
// CloseHandle(hFileMapping);
// CloseHandle(hFile);
// return false;
// }
//
// pImg_Export_Dir = (PIMAGE_EXPORT_DIRECTORY)pImg_NT_Header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
// if (!pImg_Export_Dir)
// {
// UnmapViewOfFile(lpFileBase);
// CloseHandle(hFileMapping);
// CloseHandle(hFile);
// return false;
// }
//
// pImg_Export_Dir = (PIMAGE_EXPORT_DIRECTORY)ImageRvaToVa(pImg_NT_Header, pImg_DOS_Header, (DWORD)pImg_Export_Dir, 0);
//
// DWORD **ppdwNames = (DWORD **)pImg_Export_Dir->AddressOfNames;
//
// ppdwNames = (PDWORD*)ImageRvaToVa(pImg_NT_Header, pImg_DOS_Header, (DWORD)ppdwNames, 0);
// if (!ppdwNames)
// {
// UnmapViewOfFile(lpFileBase);
// CloseHandle(hFileMapping);
// CloseHandle(hFile);
// return false;
// }
//
// nNoOfExports = pImg_Export_Dir->NumberOfNames;
//
// Bug here skips alternate names : error is in incr address of ppdwNames
// for (unsigned i = 0; i < nNoOfExports; i++)
// {
// char *szFunc = (PSTR)ImageRvaToVa(pImg_NT_Header, pImg_DOS_Header, (DWORD)*ppdwNames, 0);
// if (szFunc)
// names.push_back(szFunc);
// ppdwNames++;
// }
//
// UnmapViewOfFile(lpFileBase);
// CloseHandle(hFileMapping);
// CloseHandle(hFile);
return true;
};
#endif
PluginManager::PluginManager()
{
//printf("%s\n", __FUNCTION__);
m_pluginlistset = false;
}
PluginManager::~PluginManager()
{
//printf("%s\n", __FUNCTION__);
clearPluginList();
}
void PluginManager::registerStaticPlugin(char* pluginType, char* pluginName, void* makePlugin)
{
//printf("%s\n", __FUNCTION__);
PluginDetails* curPlugin = new PluginDetails();
curPlugin->funcHandle = reinterpret_cast<PLUGIN_FACTORYFUNC>(makePlugin);
curPlugin->isStatic = true;
curPlugin->setType(pluginType);
curPlugin->setName(pluginName);
pluginRegister.push_back(curPlugin);
}
void PluginManager::registerStaticPlugin(char* pluginType, char* pluginName, char* uuid, void* makePlugin)
{
PluginDetails* curPlugin = new PluginDetails();
curPlugin->funcHandle = reinterpret_cast<PLUGIN_FACTORYFUNC>(makePlugin);
curPlugin->isStatic = true;
curPlugin->setType(pluginType);
curPlugin->setName(pluginName);
curPlugin->setUUID(uuid);
pluginRegister.push_back(curPlugin);
}
void PluginManager::getPluginDetails(PluginDetails* curPlugin)
{
//printf("%s\n", __FUNCTION__);
#ifdef _WIN32
HINSTANCE dllHandle;
dllHandle = LoadLibraryA(curPlugin->getFileName());
if (dllHandle != NULL)
{
PLUGIN_TEXTFUNC textFunc;
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginType"));
if (textFunc)
curPlugin->setType(textFunc());
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginName"));
if (textFunc)
curPlugin->setName(textFunc());
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginUUID"));
if (textFunc)
curPlugin->setUUID(textFunc());
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginCategory"));
if (textFunc)
curPlugin->setCategory(textFunc());
PLUGIN_ULONGFUNC ulongFunc;
ulongFunc = reinterpret_cast<PLUGIN_ULONGFUNC>(GetProcAddress(dllHandle, "getPluginOptions"));
if (ulongFunc)
curPlugin->setOptions(ulongFunc());
else
curPlugin->setOptions(0);
curPlugin->isRegistered = true;
FreeLibrary(dllHandle);
}
#endif
}
void PluginManager::clearPluginList()
{
//printf("%s\n", __FUNCTION__);
for (unsigned int i = 0; i < pluginRegister.size(); i++)
{
delete pluginRegister.at(i);
pluginRegister.at(i) = NULL;
}
pluginRegister.clear();
}
bool PluginManager::fileExists(const std::string& abs_filename)
{
bool ret = false;
FILE* fp;
#ifdef _WIN32
errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb");
if (err != 0)
return false;
#else
fp = fopen(abs_filename.c_str(), "rb");
#endif
if (fp)
{
ret = true;
fclose(fp);
}
return ret;
}
void PluginManager::getPluginList(char* SubFolderName, bool append)
{
//printf("%s\n", __FUNCTION__);
// Check for prior setting, if set clear for new one
if (m_pluginlistset)
{
if (!append)
clearPluginList();
else
return;
}
else
m_pluginlistset = true;
#ifdef _WIN32
WIN32_FIND_DATAA fd;
char fname[MAX_PATH];
//----------------------------------
// Load plugin List for processing
// Use an Enviornment var, search through systems path
// or use default app running folder.
//----------------------------------
char dirPath[MAX_PATH];
// v2.1 change - to check if path exists in PATH or AMDCOMPRESS_PLUGINS is set
// else use current exe directory
char* pPath;
size_t len;
#ifdef _WIN32
_dupenv_s(&pPath, &len, "AMDCOMPRESS_PLUGINS");
#else
pPath = getenv("AMDCOMPRESS_PLUGINS") + '\0';
len = strlen(pPath);
#endif
if (len > 0)
{
snprintf(dirPath, 260, "%s", pPath + '\0');
}
else
{
bool pathFound = false;
//Get the exe directory
DWORD pathsize;
HMODULE hModule = GetModuleHandleA(NULL);
pathsize = GetModuleFileNameA(hModule, dirPath, MAX_PATH);
if (pathsize > 0)
{
char* appName = (strrchr(dirPath, '\\') + 1);
int pathLen = (int)strlen(dirPath);
int appNameLen = (int)strlen(appName);
// Null terminate the dirPath so that FileName is removed
pathLen = pathLen - appNameLen;
dirPath[pathLen] = 0;
if (dirPath[pathLen - 1] == '/' || dirPath[pathLen - 1] == '\\')
{
pathLen--;
dirPath[pathLen] = 0;
}
strcat_s(dirPath, SubFolderName);
snprintf(fname, 260, "%s\\*.dll", dirPath);
HANDLE hFind = FindFirstFileA(fname, &fd);
if (hFind != INVALID_HANDLE_VALUE)
{
pathFound = true;
}
FindClose(hFind);
}
if (!pathFound)
{
#ifdef _WIN32
_dupenv_s(&pPath, &len, "PATH");
#else
pPath = getenv("PATH");
len = strlen(pPath);
#endif
if (len > 0)
{
std::string s = pPath;
char delimiter = ';';
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos)
{
token = s.substr(0, pos);
snprintf(dirPath, 260, "%s\\compressonatorCLI.exe", token.c_str());
if (fileExists(dirPath))
{
snprintf(dirPath, 260, "%s", token.c_str());
strcat_s(dirPath, SubFolderName);
pathFound = true;
break;
}
s.erase(0, pos + sizeof(delimiter));
}
}
}
}
#ifdef _WIN32
strcpy_s(fname, dirPath);
#else
strcpy(fname, dirPath);
#endif
len = strlen(fname);
if (fname[len - 1] == '/' || fname[len - 1] == '\\')
strcat_s(fname, "*.dll");
else
strcat_s(fname, "\\*.dll");
HANDLE hFind = FindFirstFileA(fname, &fd);
if (hFind == INVALID_HANDLE_VALUE)
{
FindClose(hFind);
return;
}
do
{
HINSTANCE dllHandle = NULL;
std::vector<std::string> names;
try
{
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
snprintf(fname, MAX_PATH, "%s\\%s", dirPath, fd.cFileName);
#ifdef USE_NewLoader
//printf("GetDLL File exports %s\n", fd.cFileName);
// Valid only for Windows need one for Linux
names.clear();
GetDLLFileExports(fname, names);
if ((names.size() >= 3) && (names.size() <= 50))
{
bool bmakePlugin = false;
bool bgetPluginType = false;
bool bgetPluginName = false;
for (std::vector<std::string>::const_iterator str = names.begin(); str != names.end(); ++str)
{
if (*str == "makePlugin")
bmakePlugin = true;
else if (*str == "getPluginType")
bgetPluginType = true;
else if (*str == "getPluginName")
bgetPluginName = true;
}
if (bmakePlugin && bgetPluginType && bgetPluginName)
{
// we have a vaild plugin to register to use when needed save it!
PluginDetails* curPlugin = new PluginDetails();
curPlugin->setFileName(fname);
pluginRegister.push_back(curPlugin);
}
}
#else
dllHandle = LoadLibraryA(fname);
if (dllHandle != NULL)
{
// Is this DLL a plugin for us if so keep its type and name details
PLUGIN_FACTORYFUNC funcHandle;
funcHandle = reinterpret_cast<PLUGIN_FACTORYFUNC>(GetProcAddress(dllHandle, "makePlugin"));
if (funcHandle != NULL)
{
PluginDetails* curPlugin = new PluginDetails();
//printf("new: %s\n", fname);
curPlugin->setFileName(fname);
PLUGIN_TEXTFUNC textFunc;
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginType"));
if (textFunc)
curPlugin->setType(textFunc());
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginName"));
if (textFunc)
curPlugin->setName(textFunc());
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginUUID"));
if (textFunc)
curPlugin->setUUID(textFunc());
textFunc = reinterpret_cast<PLUGIN_TEXTFUNC>(GetProcAddress(dllHandle, "getPluginCategory"));
if (textFunc)
curPlugin->setCategory(textFunc());
curPlugin->isRegistered = true;
pluginRegister.push_back(curPlugin);
}
FreeLibrary(dllHandle);
}
#endif
}
}
catch (...)
{
if (dllHandle != NULL)
FreeLibrary(dllHandle);
}
} while (FindNextFileA(hFind, &fd));
FindClose(hFind);
#endif
}
void* PluginManager::makeNewPluginInstance(int index)
{
if (!pluginRegister.at(index)->isRegistered)
getPluginDetails(pluginRegister.at(index));
return pluginRegister.at(index)->makeNewInstance();
}
int PluginManager::getNumPlugins()
{
return static_cast<int>(pluginRegister.size());
}
char* PluginManager::getPluginName(int index)
{
if (!pluginRegister.at(index)->isRegistered)
getPluginDetails(pluginRegister.at(index));
return pluginRegister.at(index)->getName();
}
char* PluginManager::getPluginUUID(int index)
{
if (!pluginRegister.at(index)->isRegistered)
getPluginDetails(pluginRegister.at(index));
return pluginRegister.at(index)->getUUID();
}
char* PluginManager::getPluginCategory(int index)
{
if (!pluginRegister.at(index)->isRegistered)
getPluginDetails(pluginRegister.at(index));
return pluginRegister.at(index)->getCategory();
}
char* PluginManager::getPluginType(int index)
{
if (!pluginRegister.at(index)->isRegistered)
getPluginDetails(pluginRegister.at(index));
return pluginRegister.at(index)->getType();
}
unsigned long PluginManager::getPluginOption(int index)
{
if (!pluginRegister.at(index)->isRegistered)
getPluginDetails(pluginRegister.at(index));
return pluginRegister.at(index)->getOptions();
}
void* PluginManager::GetPlugin(char* type, const char* name)
{
if (!m_pluginlistset)
{
getPluginList(DEFAULT_PLUGINLIST_DIR);
}
unsigned int numPlugins = getNumPlugins();
for (unsigned int i = 0; i < numPlugins; i++)
{
PluginDetails* pPlugin = pluginRegister.at(i);
if (!pPlugin->isRegistered)
getPluginDetails(pPlugin);
//printf("%2d getPlugin(Type %s name %s) == [%s,%s] \n", i, getPluginType(i), getPluginName(i), type, name);
if ((strcmp(getPluginType(i), type) == 0) && (strcmp(getPluginName(i), name) == 0))
{
return ((void*)makeNewPluginInstance(i));
}
}
return (NULL);
}
bool PluginManager::RemovePlugin(char* type, char* name)
{
if (!m_pluginlistset)
{
getPluginList(DEFAULT_PLUGINLIST_DIR);
}
int numPlugins = getNumPlugins();
for (int i = 0; i < numPlugins; i++)
{
if (!pluginRegister.at(i)->isRegistered)
getPluginDetails(pluginRegister.at(i));
if ((strcmp(getPluginType(i), type) == 0) && (strcmp(getPluginName(i), name) == 0))
{
delete pluginRegister.at(i);
return true;
}
}
return (false);
}
void* PluginManager::GetPlugin(char* uuid)
{
if (!m_pluginlistset)
{
getPluginList(DEFAULT_PLUGINLIST_DIR);
}
int numPlugins = getNumPlugins();
for (int i = 0; i < numPlugins; i++)
{
if (!pluginRegister.at(i)->isRegistered)
getPluginDetails(pluginRegister.at(i));
if (strcmp(getPluginUUID(i), uuid) == 0)
{
return ((void*)makeNewPluginInstance(i));
}
}
return (NULL);
}
bool PluginManager::PluginSupported(char* type, char* name)
{
if (!type)
return false;
if (!name)
return false;
if (!m_pluginlistset)
{
getPluginList(DEFAULT_PLUGINLIST_DIR);
}
int numPlugins = getNumPlugins();
for (int i = 0; i < numPlugins; i++)
{
if (!pluginRegister.at(i)->isRegistered)
getPluginDetails(pluginRegister.at(i));
//PrintInfo("Type : %s Name : %s\n",pluginManager.getPluginType(i),pluginManager.getPluginName(i));
if ((strcmp(getPluginType(i), type) == 0) && (strcmp(getPluginName(i), name) == 0))
{
return (true);
}
}
return (false);
}
void PluginManager::getPluginListTypeNames(char* pluginType, std::vector<std::string>& TypeNames)
{
TypeNames.clear();
PluginDetails* plugin;
char* pName;
char* pType;
for (unsigned int i = 0; i < pluginRegister.size(); i++)
{
plugin = pluginRegister.at(i);
pType = plugin->getType();
if (strlen(pType) == 0)
{
getPluginDetails(plugin);
pName = plugin->getName();
pType = plugin->getType();
}
else
pName = plugin->getName();
if (strlen(pType) > 0)
{
if (strcmp(pluginType, pType) == 0)
{
TypeNames.push_back(pName);
}
}
}
}
void PluginManager::getPluginListOptionNames(char* pluginType, unsigned long options, std::vector<std::string>& TypeNames)
{
PluginDetails* plugin;
char* pName;
char* pType;
unsigned long uOptions;
for (unsigned int i = 0; i < pluginRegister.size(); i++)
{
plugin = pluginRegister.at(i);
pType = plugin->getType();
if (strlen(pType) == 0)
{
getPluginDetails(plugin);
pName = plugin->getName();
pType = plugin->getType();
uOptions = plugin->getOptions();
}
else
{
pName = plugin->getName();
uOptions = plugin->getOptions();
}
if (strlen(pType) > 0)
{
unsigned long selectedoption = uOptions & options;
if ((strcmp(pluginType, pType) == 0) && (selectedoption > 0))
{
TypeNames.push_back(pName);
}
}
}
}
//----------------------------------------------
PluginDetails::~PluginDetails()
{
#ifdef _WIN32
if (dllHandle)
FreeLibrary(dllHandle);
#endif
clearMembers();
}
void PluginDetails::setFileName(char* nm)
{
#ifdef _WIN32
strcpy_s(filename, MAX_PLUGIN_FILENAME_STR, nm);
#else
strcpy(filename, nm);
#endif
}
void PluginDetails::setName(char* nm)
{
#ifdef _WIN32
strcpy_s(pluginName, MAX_PLUGIN_NAME_STR, nm);
#else
strcpy(pluginName, nm);
#endif
}
void PluginDetails::setUUID(char* nm)
{
#ifdef _WIN32
strcpy_s(pluginUUID, MAX_PLUGIN_UUID_STR, nm);
#else
strcpy(pluginUUID, nm);
#endif
}
void PluginDetails::setOptions(unsigned long uoptions)
{
pluginOptions = uoptions;
}
void PluginDetails::setType(char* nm)
{
#ifdef _WIN32
strcpy_s(pluginType, MAX_PLUGIN_TYPE_STR, nm);
#else
strcpy(pluginType, nm);
#endif
}
void PluginDetails::setCategory(char* nm)
{
#ifdef _WIN32
strcpy_s(pluginCategory, MAX_PLUGIN_CATEGORY_STR, nm);
#else
strcpy(pluginCategory, nm);
#endif
}
void* PluginDetails::makeNewInstance()
{
if (isStatic)
{
return funcHandle();
}
else
{
#ifdef _WIN32
if (!dllHandle)
dllHandle = LoadLibraryA(filename);
if (dllHandle != NULL)
{
funcHandle = reinterpret_cast<PLUGIN_FACTORYFUNC>(GetProcAddress(dllHandle, "makePlugin"));
if (funcHandle != NULL)
{
return funcHandle();
}
}
#endif
}
return NULL;
}
| 1 | 0.963484 | 1 | 0.963484 | game-dev | MEDIA | 0.316707 | game-dev | 0.954866 | 1 | 0.954866 |
auroramod/iw7-mod | 4,546 | data/cdata/custom_scripts/mp/ranked.gsc | main()
{
if (!getdvarint("xblive_privatematch"))
{
level.onlinegame = 1;
level.rankedmatch = 1;
setdvar("systemlink", 0);
setdvar("onlinegame", 1);
replacefunc(scripts\mp\utility::rankingenabled, ::rankingenabled);
}
replacefunc(scripts\mp\menus::addtoteam, ::addtoteam_stub);
replacefunc(scripts\mp\menus::watchforteamchange, ::watchforteamchange_stub);
// Bypass check for sessionteam
replacefunc(scripts\mp\playerlogic::connect_validateplayerteam, ::connect_validateplayerteam_stub);
}
rankingenabled()
{
return !(!isplayer( self ) || isai( self ));
}
addtoteam_stub( team, firstConnect, changeTeamsWithoutRespawning )
{
if ( isdefined( self.team ) )
{
scripts\mp\playerlogic::removefromteamcount();
if ( isdefined( changeTeamsWithoutRespawning ) && changeTeamsWithoutRespawning )
scripts\mp\playerlogic::decrementalivecount( self.team );
}
if ( isdefined( self.pers["team"] ) && self.pers["team"] != "" && self.pers["team"] != "spectator" )
self.pers["last_team"] = self.pers["team"];
self.pers["team"] = team;
self.team = team;
// bypass session team is readonly in ranked matches if "teambased" is set on the playlist
if ( level.teambased )
self.sessionteam = team;
else if ( team == "spectator" )
self.sessionteam = "spectator";
else
self.sessionteam = "none";
if ( game["state"] != "postgame" )
{
scripts\mp\playerlogic::addtoteamcount();
if ( isdefined( changeTeamsWithoutRespawning ) && changeTeamsWithoutRespawning )
scripts\mp\playerlogic::incrementalivecount( self.team );
}
if ( isgamebattlematch() )
setmatchdata( "players", self.clientid, "team", team );
scripts\mp\utility::updateobjectivetext();
if ( isdefined( firstConnect ) && firstConnect )
waittillframeend;
scripts\mp\utility::updatemainmenu();
if ( team == "spectator" )
{
self notify( "joined_spectators" );
level notify( "joined_team", self );
}
else
{
self notify( "joined_team" );
level notify( "joined_team", self );
}
}
watchforteamchange_stub()
{
self endon( "disconnect" );
level endon( "game_ended" );
//------------------
// 0 = axis
// 1 = allies
// 2 = auto
// 3 = spectate
//------------------
for (;;)
{
self waittill( "luinotifyserver", channel, teamSelected );
if ( channel != "team_select" )
continue;
var_2 = 0;
if ( teamSelected >= 3 )
var_2 = 1;
if ( var_2 )
{
self setclientomnvar( "ui_spectator_selected", 1 );
self setclientomnvar( "ui_loadout_selected", -1 );
self.spectating_actively = 1;
}
else
{
self setclientomnvar( "ui_spectator_selected", -1 );
self.spectating_actively = 0;
}
var_3 = self ismlgspectator();
var_4 = !var_3 && isdefined( self.team ) && self.team == "spectator";
var_5 = var_3 && teamSelected == 3 || var_4 && teamSelected == 4;
if ( teamSelected == 4 )
{
teamSelected = 3;
self setmlgspectator( 1 );
}
else
self setmlgspectator( 0 );
self setclientomnvar( "ui_team_selected", teamSelected );
if ( teamSelected == 0 )
teamSelected = "axis";
else if ( teamSelected == 1 )
teamSelected = "allies";
else if ( teamSelected == 2 )
teamSelected = "random";
else
teamSelected = "spectator";
if ( !var_5 && isdefined( self.pers["team"] ) && teamSelected == self.pers["team"] )
continue;
self setclientomnvar( "ui_loadout_selected", -1 );
thread scripts\mp\menus::logteamselection( teamSelected );
if ( teamSelected == "axis" )
{
thread scripts\mp\menus::setteam( "axis" );
continue;
}
if ( teamSelected == "allies" )
{
thread scripts\mp\menus::setteam( "allies" );
continue;
}
if ( teamSelected == "random" )
{
thread scripts\mp\menus::autoassign();
continue;
}
if ( teamSelected == "spectator" )
thread scripts\mp\menus::setspectator( var_5 );
}
}
connect_validateplayerteam_stub()
{
if ( !isdefined( self ) )
return;
} | 1 | 0.800215 | 1 | 0.800215 | game-dev | MEDIA | 0.928683 | game-dev,testing-qa | 0.87175 | 1 | 0.87175 |
KaboomB52/KewlSpigot | 1,770 | kewlspigot-server/src/main/java/net/minecraft/server/NBTTagIntArray.java | package net.minecraft.server;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
public class NBTTagIntArray extends NBTBase {
private int[] data;
NBTTagIntArray() {}
public NBTTagIntArray(int[] aint) {
this.data = aint;
}
void write(DataOutput dataoutput) throws IOException {
dataoutput.writeInt(this.data.length);
for (int i = 0; i < this.data.length; ++i) {
dataoutput.writeInt(this.data[i]);
}
}
void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException {
nbtreadlimiter.a(192L);
int j = datainput.readInt();
com.google.common.base.Preconditions.checkArgument( j < 1 << 24);
nbtreadlimiter.a((long) (32 * j));
this.data = new int[j];
for (int k = 0; k < j; ++k) {
this.data[k] = datainput.readInt();
}
}
public byte getTypeId() {
return (byte) 11;
}
public String toString() {
String s = "[";
int[] aint = this.data;
int i = aint.length;
for (int j = 0; j < i; ++j) {
int k = aint[j];
s = s + k + ",";
}
return s + "]";
}
public NBTBase clone() {
int[] aint = new int[this.data.length];
System.arraycopy(this.data, 0, aint, 0, this.data.length);
return new NBTTagIntArray(aint);
}
public boolean equals(Object object) {
return super.equals(object) ? Arrays.equals(this.data, ((NBTTagIntArray) object).data) : false;
}
public int hashCode() {
return super.hashCode() ^ Arrays.hashCode(this.data);
}
public int[] c() {
return this.data;
}
}
| 1 | 0.655888 | 1 | 0.655888 | game-dev | MEDIA | 0.215882 | game-dev | 0.697109 | 1 | 0.697109 |
chrisboyle/sgtpuzzles | 20,393 | app/src/main/jni/divvy.c | /*
* Library code to divide up a rectangle into a number of equally
* sized ominoes, in a random fashion.
*
* Could use this for generating solved grids of
* http://www.nikoli.co.jp/ja/puzzles/block_puzzle/
* or for generating the playfield for Jigsaw Sudoku.
*/
/*
* This code is restricted to simply connected solutions: that is,
* no single polyomino may completely surround another (not even
* with a corner visible to the outside world, in the sense that a
* 7-omino can `surround' a single square).
*
* It's tempting to think that this is a natural consequence of
* all the ominoes being the same size - after all, a division of
* anything into 7-ominoes must necessarily have all of them
* simply connected, because if one was not then the 1-square
* space in the middle could not be part of any 7-omino - but in
* fact, for sufficiently large k, it is perfectly possible for a
* k-omino to completely surround another k-omino. A simple
* example is this one with two 25-ominoes:
*
* +--+--+--+--+--+--+--+
* | |
* + +--+--+--+--+--+ +
* | | | |
* + + + +
* | | | |
* + + + +--+
* | | | |
* + + + +--+
* | | | |
* + + + +
* | | | |
* + +--+--+--+--+--+ +
* | |
* +--+--+--+--+--+--+--+
*
* I claim the smallest k which can manage this is 23. More
* formally:
*
* If a k-omino P is completely surrounded by another k-omino Q,
* such that every edge of P borders on Q, then k >= 23.
*
* Proof:
*
* It's relatively simple to find the largest _rectangle_ a
* k-omino can enclose. So I'll construct my proof in two parts:
* firstly, show that no 22-omino or smaller can enclose a
* rectangle as large as itself, and secondly, show that no
* polyomino can enclose a larger non-rectangle than a rectangle.
*
* The first of those claims:
*
* To surround an m x n rectangle, a polyomino must have 2m
* squares along the two m-sides of the rectangle, 2n squares
* along the two n-sides, and must fill in at least three of the
* corners in order to be connected. Thus, 2(m+n)+3 <= k. We wish
* to find the largest value of mn subject to that constraint, and
* it's clear that this is achieved when m and n are as close to
* equal as possible. (If they aren't, WLOG suppose m < n; then
* (m+1)(n-1) = mn + n - m - 1 >= mn, with equality only when
* m=n-1.)
*
* So the area of the largest rectangle which can be enclosed by a
* k-omino is given by floor(k'/2) * ceil(k'/2), where k' =
* (k-3)/2. This is a monotonic function in k, so there will be a
* unique point at which it goes from being smaller than k to
* being larger than k. That point is between 22 (maximum area 20)
* and 23 (maximum area 25).
*
* The second claim:
*
* Suppose we have an inner polyomino P surrounded by an outer
* polyomino Q. I seek to show that if P is non-rectangular, then
* P is also non-maximal, in the sense that we can transform P and
* Q into a new pair of polyominoes in which P is larger and Q is
* at most the same size.
*
* Consider walking along the boundary of P in a clockwise
* direction. (We may assume, of course, that there is only _one_
* boundary of P, i.e. P has no hole in the middle. If it does
* have a hole in the middle, it's _trivially_ non-maximal because
* we can just fill the hole in!) Our walk will take us along many
* edges between squares; sometimes we might turn left, and
* certainly sometimes we will turn right. Always there will be a
* square of P on our right, and a square of Q on our left.
*
* The net angle through which we turn during the entire walk must
* add up to 360 degrees rightwards. So if there are no left
* turns, then we must turn right exactly four times, meaning we
* have described a rectangle. Hence, if P is _not_ rectangular,
* then there must have been a left turn at some point. A left
* turn must mean we walk along two edges of the same square of Q.
*
* Thus, there is some square X in Q which is adjacent to two
* diagonally separated squares in P. Let us call those two
* squares N and E; let us refer to the other two neighbours of X
* as S and W; let us refer to the other mutual neighbour of S and
* W as D; and let us refer to the other mutual neighbour of S and
* E as Y. In other words, we have named seven squares, arranged
* thus:
*
* N
* W X E
* D S Y
*
* where N and E are in P, and X is in Q.
*
* Clearly at least one of W and S must be in Q (because otherwise
* X would not be connected to any other square in Q, and would
* hence have to be the whole of Q; and evidently if Q were a
* 1-omino it could not enclose _anything_). So we divide into
* cases:
*
* If both W and S are in Q, then we take X out of Q and put it in
* P, which does not expose any edge of P. If this disconnects Q,
* then we can reconnect it by adding D to Q.
*
* If only one of W and S is in Q, then wlog let it be W. If S is
* in _P_, then we have a particularly easy case: we can simply
* take X out of Q and add it to P, and this cannot disconnect X
* since X was a leaf square of Q.
*
* Our remaining case is that W is in Q and S is in neither P nor
* Q. Again we take X out of Q and put it in P; we also add S to
* Q. This ensures we do not expose an edge of P, but we must now
* prove that S is adjacent to some other existing square of Q so
* that we haven't disconnected Q by adding it.
*
* To do this, we recall that we walked along the edge XE, and
* then turned left to walk along XN. So just before doing all
* that, we must have reached the corner XSE, and we must have
* done it by walking along one of the three edges meeting at that
* corner which are _not_ XE. It can't have been SY, since S would
* then have been on our left and it isn't in Q; and it can't have
* been XS, since S would then have been on our right and it isn't
* in P. So it must have been YE, in which case Y was on our left,
* and hence is in Q.
*
* So in all cases we have shown that we can take X out of Q and
* add it to P, and add at most one square to Q to restore the
* containment and connectedness properties. Hence, we can keep
* doing this until we run out of left turns and P becomes
* rectangular. []
*
* ------------
*
* Anyway, that entire proof was a bit of a sidetrack. The point
* is, although constructions of this type are possible for
* sufficiently large k, divvy_rectangle() will never generate
* them. This could be considered a weakness for some purposes, in
* the sense that we can't generate all possible divisions.
* However, there are many divisions which we are highly unlikely
* to generate anyway, so in practice it probably isn't _too_ bad.
*
* If I wanted to fix this issue, I would have to make the rules
* more complicated for determining when a square can safely be
* _removed_ from a polyomino. Adding one becomes easier (a square
* may be added to a polyomino iff it is 4-adjacent to any square
* currently part of the polyomino, and the current test for loop
* formation may be dispensed with), but to determine which
* squares may be removed we must now resort to analysis of the
* overall structure of the polyomino rather than the simple local
* properties we can currently get away with measuring.
*/
/*
* Possible improvements which might cut the fail rate:
*
* - instead of picking one omino to extend in an iteration, try
* them all in succession (in a randomised order)
*
* - (for real rigour) instead of bfsing over ominoes, bfs over
* the space of possible _removed squares_. That way we aren't
* limited to randomly choosing a single square to remove from
* an omino and failing if that particular square doesn't
* happen to work.
*
* However, I don't currently think it's necessary to do either of
* these, because the failure rate is already low enough to be
* easily tolerable, under all circumstances I've been able to
* think of.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include "puzzles.h"
/*
* Subroutine which implements a function used in computing both
* whether a square can safely be added to an omino, and whether
* it can safely be removed.
*
* We enumerate the eight squares 8-adjacent to this one, in
* cyclic order. We go round that loop and count the number of
* times we find a square owned by the target omino next to one
* not owned by it. We then return success iff that count is 2.
*
* When adding a square to an omino, this is precisely the
* criterion which tells us that adding the square won't leave a
* hole in the middle of the omino. (If it did, then things get
* more complicated; see above.)
*
* When removing a square from an omino, the _same_ criterion
* tells us that removing the square won't disconnect the omino.
* (This only works _because_ we've ensured the omino is simply
* connected.)
*/
static bool addremcommon(int w, int h, int x, int y, int *own, int val)
{
int neighbours[8];
int dir, count;
for (dir = 0; dir < 8; dir++) {
int dx = ((dir & 3) == 2 ? 0 : dir > 2 && dir < 6 ? +1 : -1);
int dy = ((dir & 3) == 0 ? 0 : dir < 4 ? -1 : +1);
int sx = x+dx, sy = y+dy;
if (sx < 0 || sx >= w || sy < 0 || sy >= h)
neighbours[dir] = -1; /* outside the grid */
else
neighbours[dir] = own[sy*w+sx];
}
/*
* To begin with, check 4-adjacency.
*/
if (neighbours[0] != val && neighbours[2] != val &&
neighbours[4] != val && neighbours[6] != val)
return false;
count = 0;
for (dir = 0; dir < 8; dir++) {
int next = (dir + 1) & 7;
bool gotthis = (neighbours[dir] == val);
bool gotnext = (neighbours[next] == val);
if (gotthis != gotnext)
count++;
}
return (count == 2);
}
/*
* w and h are the dimensions of the rectangle.
*
* k is the size of the required ominoes. (So k must divide w*h,
* of course.)
*
* The returned result is a w*h-sized dsf.
*
* In both of the above suggested use cases, the user would
* probably want w==h==k, but that isn't a requirement.
*/
DSF *divvy_rectangle_attempt(int w, int h, int k, random_state *rs)
{
int *order, *queue, *tmp, *own, *sizes, *addable;
DSF *retdsf, *tmpdsf;
bool *removable;
int wh = w*h;
int i, j, n, x, y, qhead, qtail;
n = wh / k;
assert(wh == k*n);
order = snewn(wh, int);
tmp = snewn(wh, int);
own = snewn(wh, int);
sizes = snewn(n, int);
queue = snewn(n, int);
addable = snewn(wh*4, int);
removable = snewn(wh, bool);
retdsf = tmpdsf = NULL;
/*
* Permute the grid squares into a random order, which will be
* used for iterating over the grid whenever we need to search
* for something. This prevents directional bias and arranges
* for the answer to be non-deterministic.
*/
for (i = 0; i < wh; i++)
order[i] = i;
shuffle(order, wh, sizeof(*order), rs);
/*
* Begin by choosing a starting square at random for each
* omino.
*/
for (i = 0; i < wh; i++) {
own[i] = -1;
}
for (i = 0; i < n; i++) {
own[order[i]] = i;
sizes[i] = 1;
}
/*
* Now repeatedly pick a random omino which isn't already at
* the target size, and find a way to expand it by one. This
* may involve stealing a square from another omino, in which
* case we then re-expand that omino, forming a chain of
* square-stealing which terminates in an as yet unclaimed
* square. Hence every successful iteration around this loop
* causes the number of unclaimed squares to drop by one, and
* so the process is bounded in duration.
*/
while (1) {
#ifdef DIVVY_DIAGNOSTICS
{
int x, y;
printf("Top of loop. Current grid:\n");
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++)
printf("%3d", own[y*w+x]);
printf("\n");
}
}
#endif
/*
* Go over the grid and figure out which squares can
* safely be added to, or removed from, each omino. We
* don't take account of other ominoes in this process, so
* we will often end up knowing that a square can be
* poached from one omino by another.
*
* For each square, there may be up to four ominoes to
* which it can be added (those to which it is
* 4-adjacent).
*/
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
int yx = y*w+x;
int curr = own[yx];
int dir;
if (curr < 0) {
removable[yx] = false; /* can't remove if not owned! */
} else if (sizes[curr] == 1) {
removable[yx] = true; /* can always remove a singleton */
} else {
/*
* See if this square can be removed from its
* omino without disconnecting it.
*/
removable[yx] = addremcommon(w, h, x, y, own, curr);
}
for (dir = 0; dir < 4; dir++) {
int dx = (dir == 0 ? -1 : dir == 1 ? +1 : 0);
int dy = (dir == 2 ? -1 : dir == 3 ? +1 : 0);
int sx = x + dx, sy = y + dy;
int syx = sy*w+sx;
addable[yx*4+dir] = -1;
if (sx < 0 || sx >= w || sy < 0 || sy >= h)
continue; /* no omino here! */
if (own[syx] < 0)
continue; /* also no omino here */
if (own[syx] == own[yx])
continue; /* we already got one */
if (!addremcommon(w, h, x, y, own, own[syx]))
continue; /* would non-simply connect the omino */
addable[yx*4+dir] = own[syx];
}
}
}
for (i = j = 0; i < n; i++)
if (sizes[i] < k)
tmp[j++] = i;
if (j == 0)
break; /* all ominoes are complete! */
j = tmp[random_upto(rs, j)];
#ifdef DIVVY_DIAGNOSTICS
printf("Trying to extend %d\n", j);
#endif
/*
* So we're trying to expand omino j. We breadth-first
* search out from j across the space of ominoes.
*
* For bfs purposes, we use two elements of tmp per omino:
* tmp[2*i+0] tells us which omino we got to i from, and
* tmp[2*i+1] numbers the grid square that omino stole
* from us.
*
* This requires that wh (the size of tmp) is at least 2n,
* i.e. k is at least 2. There would have been nothing to
* stop a user calling this function with k=1, but if they
* did then we wouldn't have got to _here_ in the code -
* we would have noticed above that all ominoes were
* already at their target sizes, and terminated :-)
*/
assert(wh >= 2*n);
for (i = 0; i < n; i++)
tmp[2*i] = tmp[2*i+1] = -1;
qhead = qtail = 0;
queue[qtail++] = j;
tmp[2*j] = tmp[2*j+1] = -2; /* special value: `starting point' */
while (qhead < qtail) {
int tmpsq;
j = queue[qhead];
/*
* We wish to expand omino j. However, we might have
* got here by omino j having a square stolen from it,
* so first of all we must temporarily mark that
* square as not belonging to j, so that our adjacency
* calculations don't assume j _does_ belong to us.
*/
tmpsq = tmp[2*j+1];
if (tmpsq >= 0) {
assert(own[tmpsq] == j);
own[tmpsq] = -3;
}
/*
* OK. Now begin by seeing if we can find any
* unclaimed square into which we can expand omino j.
* If we find one, the entire bfs terminates.
*/
for (i = 0; i < wh; i++) {
int dir;
if (own[order[i]] != -1)
continue; /* this square is claimed */
/*
* Special case: if our current omino was size 1
* and then had a square stolen from it, it's now
* size zero, which means it's valid to `expand'
* it into _any_ unclaimed square.
*/
if (sizes[j] == 1 && tmpsq >= 0)
break; /* got one */
/*
* Failing that, we must do the full test for
* addability.
*/
for (dir = 0; dir < 4; dir++)
if (addable[order[i]*4+dir] == j) {
/*
* We know this square is addable to this
* omino with the grid in the state it had
* at the top of the loop. However, we
* must now check that it's _still_
* addable to this omino when the omino is
* missing a square. To do this it's only
* necessary to re-check addremcommon.
*/
if (!addremcommon(w, h, order[i]%w, order[i]/w,
own, j))
continue;
break;
}
if (dir == 4)
continue; /* we can't add this square to j */
break; /* got one! */
}
if (i < wh) {
i = order[i];
/*
* Restore the temporarily removed square _before_
* we start shifting ownerships about.
*/
if (tmpsq >= 0)
own[tmpsq] = j;
/*
* We are done. We can add square i to omino j,
* and then backtrack along the trail in tmp
* moving squares between ominoes, ending up
* expanding our starting omino by one.
*/
#ifdef DIVVY_DIAGNOSTICS
printf("(%d,%d)", i%w, i/w);
#endif
while (1) {
own[i] = j;
#ifdef DIVVY_DIAGNOSTICS
printf(" -> %d", j);
#endif
if (tmp[2*j] == -2)
break;
i = tmp[2*j+1];
j = tmp[2*j];
#ifdef DIVVY_DIAGNOSTICS
printf("; (%d,%d)", i%w, i/w);
#endif
}
#ifdef DIVVY_DIAGNOSTICS
printf("\n");
#endif
/*
* Increment the size of the starting omino.
*/
sizes[j]++;
/*
* Terminate the bfs loop.
*/
break;
}
/*
* If we get here, we haven't been able to expand
* omino j into an unclaimed square. So now we begin
* to investigate expanding it into squares which are
* claimed by ominoes the bfs has not yet visited.
*/
for (i = 0; i < wh; i++) {
int dir, nj;
nj = own[order[i]];
if (nj < 0 || tmp[2*nj] != -1)
continue; /* unclaimed, or owned by wrong omino */
if (!removable[order[i]])
continue; /* its omino won't let it go */
for (dir = 0; dir < 4; dir++)
if (addable[order[i]*4+dir] == j) {
/*
* As above, re-check addremcommon.
*/
if (!addremcommon(w, h, order[i]%w, order[i]/w,
own, j))
continue;
/*
* We have found a square we can use to
* expand omino j, at the expense of the
* as-yet unvisited omino nj. So add this
* to the bfs queue.
*/
assert(qtail < n);
queue[qtail++] = nj;
tmp[2*nj] = j;
tmp[2*nj+1] = order[i];
/*
* Now terminate the loop over dir, to
* ensure we don't accidentally add the
* same omino twice to the queue.
*/
break;
}
}
/*
* Restore the temporarily removed square.
*/
if (tmpsq >= 0)
own[tmpsq] = j;
/*
* Advance the queue head.
*/
qhead++;
}
if (qhead == qtail) {
/*
* We have finished the bfs and not found any way to
* expand omino j. Panic, and return failure.
*
* FIXME: or should we loop over all ominoes before we
* give up?
*/
#ifdef DIVVY_DIAGNOSTICS
printf("FAIL!\n");
#endif
retdsf = NULL;
goto cleanup;
}
}
#ifdef DIVVY_DIAGNOSTICS
{
int x, y;
printf("SUCCESS! Final grid:\n");
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++)
printf("%3d", own[y*w+x]);
printf("\n");
}
}
#endif
/*
* Construct the output dsf.
*/
for (i = 0; i < wh; i++) {
assert(own[i] >= 0 && own[i] < n);
tmp[own[i]] = i;
}
retdsf = dsf_new(wh);
for (i = 0; i < wh; i++) {
dsf_merge(retdsf, i, tmp[own[i]]);
}
/*
* Construct the output dsf a different way, to verify that
* the ominoes really are k-ominoes and we haven't
* accidentally split one into two disconnected pieces.
*/
tmpdsf = dsf_new(wh);
for (y = 0; y < h; y++)
for (x = 0; x+1 < w; x++)
if (own[y*w+x] == own[y*w+(x+1)])
dsf_merge(tmpdsf, y*w+x, y*w+(x+1));
for (x = 0; x < w; x++)
for (y = 0; y+1 < h; y++)
if (own[y*w+x] == own[(y+1)*w+x])
dsf_merge(tmpdsf, y*w+x, (y+1)*w+x);
for (i = 0; i < wh; i++) {
j = dsf_canonify(retdsf, i);
assert(dsf_equivalent(tmpdsf, j, i));
}
cleanup:
/*
* Free our temporary working space.
*/
sfree(order);
sfree(tmp);
dsf_free(tmpdsf);
sfree(own);
sfree(sizes);
sfree(queue);
sfree(addable);
sfree(removable);
/*
* And we're done.
*/
return retdsf;
}
DSF *divvy_rectangle(int w, int h, int k, random_state *rs)
{
DSF *ret;
do {
ret = divvy_rectangle_attempt(w, h, k, rs);
} while (!ret);
return ret;
}
| 1 | 0.948229 | 1 | 0.948229 | game-dev | MEDIA | 0.459617 | game-dev | 0.531279 | 1 | 0.531279 |
Eaglercraft-Archive/EaglercraftX-1.8-workspace | 22,423 | src/game/java/net/minecraft/world/storage/WorldInfo.java | package net.minecraft.world.storage;
import java.util.concurrent.Callable;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.BlockPos;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameRules;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.lax1dude.eaglercraft.v1_8.HString;
/**+
* This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code.
*
* Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!"
* Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team
*
* EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
public class WorldInfo {
public static final EnumDifficulty DEFAULT_DIFFICULTY = EnumDifficulty.NORMAL;
private long randomSeed;
private WorldType terrainType = WorldType.DEFAULT;
private String generatorOptions = "";
private int spawnX;
private int spawnY;
private int spawnZ;
private long totalTime;
private long worldTime;
private long lastTimePlayed;
private long sizeOnDisk;
private NBTTagCompound playerTag;
private int dimension;
private String levelName;
private int saveVersion;
private int cleanWeatherTime;
private boolean raining;
private int rainTime;
private boolean thundering;
private int thunderTime;
private WorldSettings.GameType theGameType;
private boolean mapFeaturesEnabled;
private boolean hardcore;
private boolean allowCommands;
private boolean initialized;
private EnumDifficulty difficulty;
private boolean difficultyLocked;
private double borderCenterX = 0.0D;
private double borderCenterZ = 0.0D;
private double borderSize = 6.0E7D;
private long borderSizeLerpTime = 0L;
private double borderSizeLerpTarget = 0.0D;
private double borderSafeZone = 5.0D;
private double borderDamagePerBlock = 0.2D;
private int borderWarningDistance = 5;
private int borderWarningTime = 15;
private GameRules theGameRules = new GameRules();
public static final int eaglerVersionCurrent = 1;
private int eaglerVersion = eaglerVersionCurrent;
protected WorldInfo() {
}
public WorldInfo(NBTTagCompound nbt) {
this.randomSeed = nbt.getLong("RandomSeed");
if (nbt.hasKey("generatorName", 8)) {
String s = nbt.getString("generatorName");
this.terrainType = WorldType.parseWorldType(s);
if (this.terrainType == null) {
this.terrainType = WorldType.DEFAULT;
} else if (this.terrainType.isVersioned()) {
int i = 0;
if (nbt.hasKey("generatorVersion", 99)) {
i = nbt.getInteger("generatorVersion");
}
this.terrainType = this.terrainType.getWorldTypeForGeneratorVersion(i);
}
if (nbt.hasKey("generatorOptions", 8)) {
this.generatorOptions = nbt.getString("generatorOptions");
}
}
this.theGameType = WorldSettings.GameType.getByID(nbt.getInteger("GameType"));
if (nbt.hasKey("MapFeatures", 99)) {
this.mapFeaturesEnabled = nbt.getBoolean("MapFeatures");
} else {
this.mapFeaturesEnabled = true;
}
this.spawnX = nbt.getInteger("SpawnX");
this.spawnY = nbt.getInteger("SpawnY");
this.spawnZ = nbt.getInteger("SpawnZ");
this.totalTime = nbt.getLong("Time");
if (nbt.hasKey("DayTime", 99)) {
this.worldTime = nbt.getLong("DayTime");
} else {
this.worldTime = this.totalTime;
}
this.lastTimePlayed = nbt.getLong("LastPlayed");
this.sizeOnDisk = nbt.getLong("SizeOnDisk");
this.levelName = nbt.getString("LevelName");
this.saveVersion = nbt.getInteger("version");
this.cleanWeatherTime = nbt.getInteger("clearWeatherTime");
this.rainTime = nbt.getInteger("rainTime");
this.raining = nbt.getBoolean("raining");
this.thunderTime = nbt.getInteger("thunderTime");
this.thundering = nbt.getBoolean("thundering");
this.hardcore = nbt.getBoolean("hardcore");
if (nbt.hasKey("initialized", 99)) {
this.initialized = nbt.getBoolean("initialized");
} else {
this.initialized = true;
}
if (nbt.hasKey("allowCommands", 99)) {
this.allowCommands = nbt.getBoolean("allowCommands");
} else {
this.allowCommands = this.theGameType == WorldSettings.GameType.CREATIVE;
}
if (nbt.hasKey("Player", 10)) {
this.playerTag = nbt.getCompoundTag("Player");
this.dimension = this.playerTag.getInteger("Dimension");
}
if (nbt.hasKey("GameRules", 10)) {
this.theGameRules.readFromNBT(nbt.getCompoundTag("GameRules"));
}
if (nbt.hasKey("Difficulty", 99)) {
this.difficulty = EnumDifficulty.getDifficultyEnum(nbt.getByte("Difficulty"));
}
if (nbt.hasKey("DifficultyLocked", 1)) {
this.difficultyLocked = nbt.getBoolean("DifficultyLocked");
}
if (nbt.hasKey("BorderCenterX", 99)) {
this.borderCenterX = nbt.getDouble("BorderCenterX");
}
if (nbt.hasKey("BorderCenterZ", 99)) {
this.borderCenterZ = nbt.getDouble("BorderCenterZ");
}
if (nbt.hasKey("BorderSize", 99)) {
this.borderSize = nbt.getDouble("BorderSize");
}
if (nbt.hasKey("BorderSizeLerpTime", 99)) {
this.borderSizeLerpTime = nbt.getLong("BorderSizeLerpTime");
}
if (nbt.hasKey("BorderSizeLerpTarget", 99)) {
this.borderSizeLerpTarget = nbt.getDouble("BorderSizeLerpTarget");
}
if (nbt.hasKey("BorderSafeZone", 99)) {
this.borderSafeZone = nbt.getDouble("BorderSafeZone");
}
if (nbt.hasKey("BorderDamagePerBlock", 99)) {
this.borderDamagePerBlock = nbt.getDouble("BorderDamagePerBlock");
}
if (nbt.hasKey("BorderWarningBlocks", 99)) {
this.borderWarningDistance = nbt.getInteger("BorderWarningBlocks");
}
if (nbt.hasKey("BorderWarningTime", 99)) {
this.borderWarningTime = nbt.getInteger("BorderWarningTime");
}
this.eaglerVersion = nbt.getInteger("eaglerVersionSerial");
}
public WorldInfo(WorldSettings settings, String name) {
this.populateFromWorldSettings(settings);
this.levelName = name;
this.difficulty = DEFAULT_DIFFICULTY;
this.initialized = false;
}
public void populateFromWorldSettings(WorldSettings settings) {
this.randomSeed = settings.getSeed();
this.theGameType = settings.getGameType();
this.mapFeaturesEnabled = settings.isMapFeaturesEnabled();
this.hardcore = settings.getHardcoreEnabled();
this.terrainType = settings.getTerrainType();
this.generatorOptions = settings.getWorldName();
this.allowCommands = settings.areCommandsAllowed();
}
public WorldInfo(WorldInfo worldInformation) {
this.randomSeed = worldInformation.randomSeed;
this.terrainType = worldInformation.terrainType;
this.generatorOptions = worldInformation.generatorOptions;
this.theGameType = worldInformation.theGameType;
this.mapFeaturesEnabled = worldInformation.mapFeaturesEnabled;
this.spawnX = worldInformation.spawnX;
this.spawnY = worldInformation.spawnY;
this.spawnZ = worldInformation.spawnZ;
this.totalTime = worldInformation.totalTime;
this.worldTime = worldInformation.worldTime;
this.lastTimePlayed = worldInformation.lastTimePlayed;
this.sizeOnDisk = worldInformation.sizeOnDisk;
this.playerTag = worldInformation.playerTag;
this.dimension = worldInformation.dimension;
this.levelName = worldInformation.levelName;
this.saveVersion = worldInformation.saveVersion;
this.rainTime = worldInformation.rainTime;
this.raining = worldInformation.raining;
this.thunderTime = worldInformation.thunderTime;
this.thundering = worldInformation.thundering;
this.hardcore = worldInformation.hardcore;
this.allowCommands = worldInformation.allowCommands;
this.initialized = worldInformation.initialized;
this.theGameRules = worldInformation.theGameRules;
this.difficulty = worldInformation.difficulty;
this.difficultyLocked = worldInformation.difficultyLocked;
this.borderCenterX = worldInformation.borderCenterX;
this.borderCenterZ = worldInformation.borderCenterZ;
this.borderSize = worldInformation.borderSize;
this.borderSizeLerpTime = worldInformation.borderSizeLerpTime;
this.borderSizeLerpTarget = worldInformation.borderSizeLerpTarget;
this.borderSafeZone = worldInformation.borderSafeZone;
this.borderDamagePerBlock = worldInformation.borderDamagePerBlock;
this.borderWarningTime = worldInformation.borderWarningTime;
this.borderWarningDistance = worldInformation.borderWarningDistance;
}
/**+
* Gets the NBTTagCompound for the worldInfo
*/
public NBTTagCompound getNBTTagCompound() {
NBTTagCompound nbttagcompound = new NBTTagCompound();
this.updateTagCompound(nbttagcompound, this.playerTag);
return nbttagcompound;
}
/**+
* Creates a new NBTTagCompound for the world, with the given
* NBTTag as the "Player"
*/
public NBTTagCompound cloneNBTCompound(NBTTagCompound nbttagcompound) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
this.updateTagCompound(nbttagcompound1, nbttagcompound);
return nbttagcompound1;
}
private void updateTagCompound(NBTTagCompound nbt, NBTTagCompound playerNbt) {
nbt.setLong("RandomSeed", this.randomSeed);
nbt.setString("generatorName", this.terrainType.getWorldTypeName());
nbt.setInteger("generatorVersion", this.terrainType.getGeneratorVersion());
nbt.setString("generatorOptions", this.generatorOptions);
nbt.setInteger("GameType", this.theGameType.getID());
nbt.setBoolean("MapFeatures", this.mapFeaturesEnabled);
nbt.setInteger("SpawnX", this.spawnX);
nbt.setInteger("SpawnY", this.spawnY);
nbt.setInteger("SpawnZ", this.spawnZ);
nbt.setLong("Time", this.totalTime);
nbt.setLong("DayTime", this.worldTime);
nbt.setLong("SizeOnDisk", this.sizeOnDisk);
nbt.setLong("LastPlayed", System.currentTimeMillis());
nbt.setString("LevelName", this.levelName);
nbt.setInteger("version", this.saveVersion);
nbt.setInteger("clearWeatherTime", this.cleanWeatherTime);
nbt.setInteger("rainTime", this.rainTime);
nbt.setBoolean("raining", this.raining);
nbt.setInteger("thunderTime", this.thunderTime);
nbt.setBoolean("thundering", this.thundering);
nbt.setBoolean("hardcore", this.hardcore);
nbt.setBoolean("allowCommands", this.allowCommands);
nbt.setBoolean("initialized", this.initialized);
nbt.setDouble("BorderCenterX", this.borderCenterX);
nbt.setDouble("BorderCenterZ", this.borderCenterZ);
nbt.setDouble("BorderSize", this.borderSize);
nbt.setLong("BorderSizeLerpTime", this.borderSizeLerpTime);
nbt.setDouble("BorderSafeZone", this.borderSafeZone);
nbt.setDouble("BorderDamagePerBlock", this.borderDamagePerBlock);
nbt.setDouble("BorderSizeLerpTarget", this.borderSizeLerpTarget);
nbt.setDouble("BorderWarningBlocks", (double) this.borderWarningDistance);
nbt.setDouble("BorderWarningTime", (double) this.borderWarningTime);
nbt.setInteger("eaglerVersionSerial", this.eaglerVersion);
if (this.difficulty != null) {
nbt.setByte("Difficulty", (byte) this.difficulty.getDifficultyId());
}
nbt.setBoolean("DifficultyLocked", this.difficultyLocked);
nbt.setTag("GameRules", this.theGameRules.writeToNBT());
if (playerNbt != null) {
nbt.setTag("Player", playerNbt);
}
}
/**+
* Returns the seed of current world.
*/
public long getSeed() {
return this.randomSeed;
}
/**+
* Returns the x spawn position
*/
public int getSpawnX() {
return this.spawnX;
}
/**+
* Return the Y axis spawning point of the player.
*/
public int getSpawnY() {
return this.spawnY;
}
/**+
* Returns the z spawn position
*/
public int getSpawnZ() {
return this.spawnZ;
}
public long getWorldTotalTime() {
return this.totalTime;
}
/**+
* Get current world time
*/
public long getWorldTime() {
return this.worldTime;
}
public long getSizeOnDisk() {
return this.sizeOnDisk;
}
/**+
* Returns the player's NBTTagCompound to be loaded
*/
public NBTTagCompound getPlayerNBTTagCompound() {
return this.playerTag;
}
/**+
* Set the x spawn position to the passed in value
*/
public void setSpawnX(int i) {
this.spawnX = i;
}
/**+
* Sets the y spawn position
*/
public void setSpawnY(int i) {
this.spawnY = i;
}
/**+
* Set the z spawn position to the passed in value
*/
public void setSpawnZ(int i) {
this.spawnZ = i;
}
public void setWorldTotalTime(long i) {
this.totalTime = i;
}
/**+
* Set current world time
*/
public void setWorldTime(long i) {
this.worldTime = i;
}
public void setSpawn(BlockPos blockpos) {
this.spawnX = blockpos.getX();
this.spawnY = blockpos.getY();
this.spawnZ = blockpos.getZ();
}
/**+
* Get current world name
*/
public String getWorldName() {
return this.levelName;
}
public void setWorldName(String s) {
this.levelName = s;
}
/**+
* Returns the save version of this world
*/
public int getSaveVersion() {
return this.saveVersion;
}
/**+
* Sets the save version of the world
*/
public void setSaveVersion(int i) {
this.saveVersion = i;
}
/**+
* Return the last time the player was in this world.
*/
public long getLastTimePlayed() {
return this.lastTimePlayed;
}
public int getCleanWeatherTime() {
return this.cleanWeatherTime;
}
public void setCleanWeatherTime(int cleanWeatherTimeIn) {
this.cleanWeatherTime = cleanWeatherTimeIn;
}
/**+
* Returns true if it is thundering, false otherwise.
*/
public boolean isThundering() {
return this.thundering;
}
/**+
* Sets whether it is thundering or not.
*/
public void setThundering(boolean flag) {
this.thundering = flag;
}
/**+
* Returns the number of ticks until next thunderbolt.
*/
public int getThunderTime() {
return this.thunderTime;
}
/**+
* Defines the number of ticks until next thunderbolt.
*/
public void setThunderTime(int i) {
this.thunderTime = i;
}
/**+
* Returns true if it is raining, false otherwise.
*/
public boolean isRaining() {
return this.raining;
}
/**+
* Sets whether it is raining or not.
*/
public void setRaining(boolean flag) {
this.raining = flag;
}
/**+
* Return the number of ticks until rain.
*/
public int getRainTime() {
return this.rainTime;
}
/**+
* Sets the number of ticks until rain.
*/
public void setRainTime(int i) {
this.rainTime = i;
}
/**+
* Gets the GameType.
*/
public WorldSettings.GameType getGameType() {
return this.theGameType;
}
/**+
* Get whether the map features (e.g. strongholds) generation is
* enabled or disabled.
*/
public boolean isMapFeaturesEnabled() {
return this.mapFeaturesEnabled;
}
public void setMapFeaturesEnabled(boolean enabled) {
this.mapFeaturesEnabled = enabled;
}
/**+
* Sets the GameType.
*/
public void setGameType(WorldSettings.GameType type) {
this.theGameType = type;
}
/**+
* Returns true if hardcore mode is enabled, otherwise false
*/
public boolean isHardcoreModeEnabled() {
return this.hardcore;
}
public void setHardcore(boolean hardcoreIn) {
this.hardcore = hardcoreIn;
}
public WorldType getTerrainType() {
return this.terrainType;
}
public void setTerrainType(WorldType worldtype) {
this.terrainType = worldtype;
}
public String getGeneratorOptions() {
return this.generatorOptions;
}
/**+
* Returns true if commands are allowed on this World.
*/
public boolean areCommandsAllowed() {
return this.allowCommands;
}
public void setAllowCommands(boolean flag) {
this.allowCommands = flag;
}
/**+
* Returns true if the World is initialized.
*/
public boolean isInitialized() {
return this.initialized;
}
/**+
* Sets the initialization status of the World.
*/
public void setServerInitialized(boolean flag) {
this.initialized = flag;
}
/**+
* Gets the GameRules class Instance.
*/
public GameRules getGameRulesInstance() {
return this.theGameRules;
}
/**+
* Returns the border center X position
*/
public double getBorderCenterX() {
return this.borderCenterX;
}
/**+
* Returns the border center Z position
*/
public double getBorderCenterZ() {
return this.borderCenterZ;
}
public double getBorderSize() {
return this.borderSize;
}
/**+
* Sets the border size
*/
public void setBorderSize(double size) {
this.borderSize = size;
}
/**+
* Returns the border lerp time
*/
public long getBorderLerpTime() {
return this.borderSizeLerpTime;
}
/**+
* Sets the border lerp time
*/
public void setBorderLerpTime(long time) {
this.borderSizeLerpTime = time;
}
/**+
* Returns the border lerp target
*/
public double getBorderLerpTarget() {
return this.borderSizeLerpTarget;
}
/**+
* Sets the border lerp target
*/
public void setBorderLerpTarget(double lerpSize) {
this.borderSizeLerpTarget = lerpSize;
}
/**+
* Returns the border center Z position
*/
public void getBorderCenterZ(double posZ) {
this.borderCenterZ = posZ;
}
/**+
* Returns the border center X position
*/
public void getBorderCenterX(double posX) {
this.borderCenterX = posX;
}
/**+
* Returns the border safe zone
*/
public double getBorderSafeZone() {
return this.borderSafeZone;
}
/**+
* Sets the border safe zone
*/
public void setBorderSafeZone(double amount) {
this.borderSafeZone = amount;
}
/**+
* Returns the border damage per block
*/
public double getBorderDamagePerBlock() {
return this.borderDamagePerBlock;
}
/**+
* Sets the border damage per block
*/
public void setBorderDamagePerBlock(double damage) {
this.borderDamagePerBlock = damage;
}
/**+
* Returns the border warning distance
*/
public int getBorderWarningDistance() {
return this.borderWarningDistance;
}
/**+
* Returns the border warning time
*/
public int getBorderWarningTime() {
return this.borderWarningTime;
}
/**+
* Sets the border warning distance
*/
public void setBorderWarningDistance(int amountOfBlocks) {
this.borderWarningDistance = amountOfBlocks;
}
/**+
* Sets the border warning time
*/
public void setBorderWarningTime(int ticks) {
this.borderWarningTime = ticks;
}
public EnumDifficulty getDifficulty() {
return this.difficulty;
}
public void setDifficulty(EnumDifficulty enumdifficulty) {
this.difficulty = enumdifficulty;
}
public boolean isDifficultyLocked() {
return this.difficultyLocked;
}
public void setDifficultyLocked(boolean flag) {
this.difficultyLocked = flag;
}
public int getEaglerVersion() {
return this.eaglerVersion;
}
public boolean isOldEaglercraftRandom() {
return this.eaglerVersion == 0;
}
public static void initEaglerVersion(NBTTagCompound compound) {
if (!compound.hasKey("eaglerVersionSerial", 99)) {
compound.setInteger("eaglerVersionSerial", eaglerVersionCurrent);
}
}
/**+
* Adds this WorldInfo instance to the crash report.
*/
public void addToCrashReport(CrashReportCategory category) {
category.addCrashSectionCallable("Level seed", new Callable<String>() {
public String call() throws Exception {
return String.valueOf(WorldInfo.this.getSeed());
}
});
category.addCrashSectionCallable("Level generator", new Callable<String>() {
public String call() throws Exception {
return HString.format("ID %02d - %s, ver %d. Features enabled: %b",
new Object[] { Integer.valueOf(WorldInfo.this.terrainType.getWorldTypeID()),
WorldInfo.this.terrainType.getWorldTypeName(),
Integer.valueOf(WorldInfo.this.terrainType.getGeneratorVersion()),
Boolean.valueOf(WorldInfo.this.mapFeaturesEnabled) });
}
});
category.addCrashSectionCallable("Level generator options", new Callable<String>() {
public String call() throws Exception {
return WorldInfo.this.generatorOptions;
}
});
category.addCrashSectionCallable("Level spawn location", new Callable<String>() {
public String call() throws Exception {
return CrashReportCategory.getCoordinateInfo((double) WorldInfo.this.spawnX,
(double) WorldInfo.this.spawnY, (double) WorldInfo.this.spawnZ);
}
});
category.addCrashSectionCallable("Level time", new Callable<String>() {
public String call() throws Exception {
return HString.format("%d game time, %d day time", new Object[] {
Long.valueOf(WorldInfo.this.totalTime), Long.valueOf(WorldInfo.this.worldTime) });
}
});
category.addCrashSectionCallable("Level dimension", new Callable<String>() {
public String call() throws Exception {
return String.valueOf(WorldInfo.this.dimension);
}
});
category.addCrashSectionCallable("Level storage version", new Callable<String>() {
public String call() throws Exception {
String s = "Unknown?";
try {
switch (WorldInfo.this.saveVersion) {
case 19132:
s = "McRegion";
break;
case 19133:
s = "Anvil";
}
} catch (Throwable var3) {
;
}
return HString.format("0x%05X - %s", new Object[] { Integer.valueOf(WorldInfo.this.saveVersion), s });
}
});
category.addCrashSectionCallable("Level weather", new Callable<String>() {
public String call() throws Exception {
return HString.format("Rain time: %d (now: %b), thunder time: %d (now: %b)",
new Object[] { Integer.valueOf(WorldInfo.this.rainTime),
Boolean.valueOf(WorldInfo.this.raining), Integer.valueOf(WorldInfo.this.thunderTime),
Boolean.valueOf(WorldInfo.this.thundering) });
}
});
category.addCrashSectionCallable("Level game mode", new Callable<String>() {
public String call() throws Exception {
return HString.format("Game mode: %s (ID %d). Hardcore: %b. Cheats: %b", new Object[] {
WorldInfo.this.theGameType.getName(), Integer.valueOf(WorldInfo.this.theGameType.getID()),
Boolean.valueOf(WorldInfo.this.hardcore), Boolean.valueOf(WorldInfo.this.allowCommands) });
}
});
}
} | 1 | 0.902598 | 1 | 0.902598 | game-dev | MEDIA | 0.965335 | game-dev | 0.903912 | 1 | 0.903912 |
qcdong2016/QCEditor | 9,745 | cocos2d/external/bullet/include/bullet/BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h | /*! \file btGImpactShape.h
\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_GIMPACT_BVH_CONCAVE_COLLISION_ALGORITHM_H
#define BT_GIMPACT_BVH_CONCAVE_COLLISION_ALGORITHM_H
#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btGImpactShape.h"
#include "BulletCollision/CollisionShapes/btStaticPlaneShape.h"
#include "BulletCollision/CollisionShapes/btCompoundShape.h"
#include "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h"
#include "LinearMath/btIDebugDraw.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
//! Collision Algorithm for GImpact Shapes
/*!
For register this algorithm in Bullet, proceed as following:
\code
btCollisionDispatcher * dispatcher = static_cast<btCollisionDispatcher *>(m_dynamicsWorld ->getDispatcher());
btGImpactCollisionAlgorithm::registerAlgorithm(dispatcher);
\endcode
*/
class btGImpactCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
protected:
btCollisionAlgorithm * m_convex_algorithm;
btPersistentManifold * m_manifoldPtr;
btManifoldResult* m_resultOut;
const btDispatcherInfo * m_dispatchInfo;
int m_triface0;
int m_part0;
int m_triface1;
int m_part1;
//! Creates a new contact point
SIMD_FORCE_INLINE btPersistentManifold* newContactManifold(const btCollisionObject* body0,const btCollisionObject* body1)
{
m_manifoldPtr = m_dispatcher->getNewManifold(body0,body1);
return m_manifoldPtr;
}
SIMD_FORCE_INLINE void destroyConvexAlgorithm()
{
if(m_convex_algorithm)
{
m_convex_algorithm->~btCollisionAlgorithm();
m_dispatcher->freeCollisionAlgorithm( m_convex_algorithm);
m_convex_algorithm = NULL;
}
}
SIMD_FORCE_INLINE void destroyContactManifolds()
{
if(m_manifoldPtr == NULL) return;
m_dispatcher->releaseManifold(m_manifoldPtr);
m_manifoldPtr = NULL;
}
SIMD_FORCE_INLINE void clearCache()
{
destroyContactManifolds();
destroyConvexAlgorithm();
m_triface0 = -1;
m_part0 = -1;
m_triface1 = -1;
m_part1 = -1;
}
SIMD_FORCE_INLINE btPersistentManifold* getLastManifold()
{
return m_manifoldPtr;
}
// Call before process collision
SIMD_FORCE_INLINE void checkManifold(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
if(getLastManifold() == 0)
{
newContactManifold(body0Wrap->getCollisionObject(),body1Wrap->getCollisionObject());
}
m_resultOut->setPersistentManifold(getLastManifold());
}
// Call before process collision
SIMD_FORCE_INLINE btCollisionAlgorithm * newAlgorithm(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
checkManifold(body0Wrap,body1Wrap);
btCollisionAlgorithm * convex_algorithm = m_dispatcher->findAlgorithm(
body0Wrap,body1Wrap,getLastManifold());
return convex_algorithm ;
}
// Call before process collision
SIMD_FORCE_INLINE void checkConvexAlgorithm(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
if(m_convex_algorithm) return;
m_convex_algorithm = newAlgorithm(body0Wrap,body1Wrap);
}
void addContactPoint(const btCollisionObjectWrapper * body0Wrap,
const btCollisionObjectWrapper * body1Wrap,
const btVector3 & point,
const btVector3 & normal,
btScalar distance);
//! Collision routines
//!@{
void collide_gjk_triangles(const btCollisionObjectWrapper* body0Wrap,
const btCollisionObjectWrapper* body1Wrap,
const btGImpactMeshShapePart * shape0,
const btGImpactMeshShapePart * shape1,
const int * pairs, int pair_count);
void collide_sat_triangles(const btCollisionObjectWrapper* body0Wrap,
const btCollisionObjectWrapper* body1Wrap,
const btGImpactMeshShapePart * shape0,
const btGImpactMeshShapePart * shape1,
const int * pairs, int pair_count);
void shape_vs_shape_collision(
const btCollisionObjectWrapper* body0,
const btCollisionObjectWrapper* body1,
const btCollisionShape * shape0,
const btCollisionShape * shape1);
void convex_vs_convex_collision(const btCollisionObjectWrapper* body0Wrap,
const btCollisionObjectWrapper* body1Wrap,
const btCollisionShape* shape0,
const btCollisionShape* shape1);
void gimpact_vs_gimpact_find_pairs(
const btTransform & trans0,
const btTransform & trans1,
const btGImpactShapeInterface * shape0,
const btGImpactShapeInterface * shape1,btPairSet & pairset);
void gimpact_vs_shape_find_pairs(
const btTransform & trans0,
const btTransform & trans1,
const btGImpactShapeInterface * shape0,
const btCollisionShape * shape1,
btAlignedObjectArray<int> & collided_primitives);
void gimpacttrimeshpart_vs_plane_collision(
const btCollisionObjectWrapper * body0Wrap,
const btCollisionObjectWrapper * body1Wrap,
const btGImpactMeshShapePart * shape0,
const btStaticPlaneShape * shape1,bool swapped);
public:
btGImpactCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap);
virtual ~btGImpactCollisionAlgorithm();
virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);
virtual void getAllContactManifolds(btManifoldArray& manifoldArray)
{
if (m_manifoldPtr)
manifoldArray.push_back(m_manifoldPtr);
}
btManifoldResult* internalGetResultOut()
{
return m_resultOut;
}
struct CreateFunc :public btCollisionAlgorithmCreateFunc
{
virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
{
void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btGImpactCollisionAlgorithm));
return new(mem) btGImpactCollisionAlgorithm(ci,body0Wrap,body1Wrap);
}
};
//! Use this function for register the algorithm externally
static void registerAlgorithm(btCollisionDispatcher * dispatcher);
#ifdef TRI_COLLISION_PROFILING
//! Gets the average time in miliseconds of tree collisions
static float getAverageTreeCollisionTime();
//! Gets the average time in miliseconds of triangle collisions
static float getAverageTriangleCollisionTime();
#endif //TRI_COLLISION_PROFILING
//! Collides two gimpact shapes
/*!
\pre shape0 and shape1 couldn't be btGImpactMeshShape objects
*/
void gimpact_vs_gimpact(const btCollisionObjectWrapper* body0Wrap,
const btCollisionObjectWrapper * body1Wrap,
const btGImpactShapeInterface * shape0,
const btGImpactShapeInterface * shape1);
void gimpact_vs_shape(const btCollisionObjectWrapper* body0Wrap,
const btCollisionObjectWrapper* body1Wrap,
const btGImpactShapeInterface * shape0,
const btCollisionShape * shape1,bool swapped);
void gimpact_vs_compoundshape(const btCollisionObjectWrapper * body0Wrap,
const btCollisionObjectWrapper * body1Wrap,
const btGImpactShapeInterface * shape0,
const btCompoundShape * shape1,bool swapped);
void gimpact_vs_concave(
const btCollisionObjectWrapper * body0Wrap,
const btCollisionObjectWrapper * body1Wrap,
const btGImpactShapeInterface * shape0,
const btConcaveShape * shape1,bool swapped);
/// Accessor/Mutator pairs for Part and triangleID
void setFace0(int value)
{
m_triface0 = value;
}
int getFace0()
{
return m_triface0;
}
void setFace1(int value)
{
m_triface1 = value;
}
int getFace1()
{
return m_triface1;
}
void setPart0(int value)
{
m_part0 = value;
}
int getPart0()
{
return m_part0;
}
void setPart1(int value)
{
m_part1 = value;
}
int getPart1()
{
return m_part1;
}
};
//algorithm details
//#define BULLET_TRIANGLE_COLLISION 1
#define GIMPACT_VS_PLANE_COLLISION 1
#endif //BT_GIMPACT_BVH_CONCAVE_COLLISION_ALGORITHM_H
| 1 | 0.958612 | 1 | 0.958612 | game-dev | MEDIA | 0.978939 | game-dev | 0.872635 | 1 | 0.872635 |
magefree/mage | 3,407 | Mage.Sets/src/mage/cards/z/ZamWesell.java | package mage.cards.z;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldAbility;
import mage.abilities.condition.FixedCondition;
import mage.abilities.condition.common.AttachedCondition;
import mage.abilities.effects.ContinuousEffect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.*;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.players.Player;
import mage.target.TargetCard;
import mage.target.TargetPlayer;
import mage.target.common.*;
import mage.target.targetpointer.FixedTarget;
/**
*
* @author Styxo, Merlingilb
*/
public final class ZamWesell extends CardImpl {
public ZamWesell(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{U}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.SHAPESHIFTER, SubType.HUNTER);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// When you cast Zam Wesell, target opponent reveals their hand. You may choose a creature card from it and have Zam Wesell enter the battlefield as a copy of that creature card.
Ability ability = new EntersBattlefieldAbility(new ZamWesselEffect(), new FixedCondition(true), "When you cast {this}, target opponent reveals his or her hand. You may choose a creature card from it and have {this} enter the battlefield as a copy of that creature card.", "");
this.addAbility(ability);
}
private ZamWesell(final ZamWesell card) {
super(card);
}
@Override
public ZamWesell copy() {
return new ZamWesell(this);
}
}
class ZamWesselEffect extends OneShotEffect {
ZamWesselEffect() {
super(Outcome.Benefit);
this.staticText = "";
}
private ZamWesselEffect(final ZamWesselEffect effect) {
super(effect);
}
@Override
public ZamWesselEffect copy() {
return new ZamWesselEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player you = game.getPlayer(source.getControllerId());
TargetPlayer targetOpponent = new TargetOpponent();
if (you.chooseTarget(Outcome.Benefit, targetOpponent, source, game)) {
Player targetPlayer = game.getPlayer(targetOpponent.getFirstTarget());
if (targetPlayer != null && you != null) {
if (!targetPlayer.getHand().isEmpty()) {
TargetCard target = new TargetCard(0, 1, Zone.HAND, StaticFilters.FILTER_CARD_CREATURE);
if (you.choose(Outcome.Benefit, targetPlayer.getHand(), target, source, game)) {
Card card = game.getCard(target.getFirstTarget());
if (card != null) {
ContinuousEffect copyEffect = new CopyEffect(Duration.EndOfGame, card.getMainCard(), source.getSourceId());
copyEffect.setTargetPointer(new FixedTarget(source.getSourceId(), game));
game.addEffect(copyEffect, source);
return true;
}
}
}
}
}
return false;
}
}
| 1 | 0.956542 | 1 | 0.956542 | game-dev | MEDIA | 0.988463 | game-dev | 0.983982 | 1 | 0.983982 |
acristescu/OnlineGo | 5,181 | app/src/main/cpp/Goban.h | #pragma once
#include "Color.h"
#include "Point.h"
#include "Vec.h"
#include "Grid.h"
#ifdef USE_THREADS
# include <random>
#endif
class Goban {
public:
enum Result {
OK = 0,
ILLEGAL = 1,
};
public:
int width;
int height;
Grid board;
int do_ko_check;
Point possible_ko;
Grid global_visited;
int last_visited_counter;
#ifdef USE_THREADS
std::mt19937 rand;
#endif
Goban(int width, int height);
Goban(const Goban &other);
void setBoardSize(int width, int height);
Grid estimate(Color player_to_move, int trials, float tolerance, bool debug) const;
Point generateMove(Color player, int trials, float tolerance);
inline int at(const Point &p) const { return board[p]; }
inline int& at(const Point &p) { return board[p]; }
inline int operator[](const Point &p) const { return board[p]; }
inline int& operator[](const Point &p) { return board[p]; }
void setSize(int width, int height);
void clearBoard();
void play_out_position(Color player_to_move, const Grid &life_map, const Grid &seki);
Result place_and_remove(Point move, Color player, Vec &possible_moves);
/* Looks for probable seki situations and returns them as a binary grid */
Grid scanForSeki(int num_iterations, float tolerance, const Grid &rollout_pass) const;
/** Returns a list of false eyes detected */
Vec getFalseEyes() const;
/** Fills false eyes, removing stones if appropriate */
void fillFalseEyes(const Vec &false_eyes);
void fillFalseEyes() { fillFalseEyes(getFalseEyes()); }
/**
* Play num_iterations random matches. Don't play in places identifies
* by life_map, assuming those spots are definitely alive and non
* invadable. Note this is a heavy bias on not assuming territory is
* invadable, which for our purposes is fine. Such things would be
* horrible for a bot, but we're just trying to mark the board up how
* the players, who may be weak or strong, view the board.
*/
Grid rollout(int num_iterations, Color player_to_move, bool pullup_life_based_on_neigboring_territory = true, const Grid &life_map = Grid(), const Grid &bias = Grid(), const Grid &seki = Grid()) const;
/**
* We bias positions on the board based on who they currently belong
* to. The goal with the bias is to help prevent unexpected removals of
* tricky-but-still-alive stones while still not hindering the removal
* of obviously dead bad invasions or obviously dead groups.
*/
Grid computeBias(int num_iterations, float tolerance);
/**
* Bias against some probably very dead stone groups, namely groups with
* no eyes that are surrounded by area that is almost definitely the opponents
*/
Grid biasLikelyDead(int num_iterations, float tolerance, const Grid &liberty_map) const;
Grid biasLibertyMap(int num_iterations, float tolerance, const Grid &liberty_map) const;
/**
* Marks each location with the positive or negative size of the
* territory (negative for white, postive for black), or zero if the
* location is not territory. */
Grid computeTerritory();
/** Uniquely labels strings of groups on the board. */
Grid computeGroupMap() const;
/**
* Computes the liberties for any groups on the boards. For empty
* spaces, computes the number of blank minus number of white stones
* touching the group. The value is always negative for white and positive for black.
*/
Grid computeLiberties(const Grid &group_map) const;
/**
* Flags spaces that are part of a string of like colored stone strings
* and territory * so long as the stone strings have a combined two or
* more territory
*/
Grid computeStrongLife(const Grid &groups, const Grid &territory, const Grid &liberties) const;
/**
* Returns a list of stones that are probably dead as determined by
* looking at the results of a rollout pass compared to our initial
* board state
*/
Vec getDead(int num_iterations, float tolerance, const Grid &rollout_pass) const;
private:
Grid _estimate(Color player_to_move, int trials, float tolerance, bool debug);
bool has_liberties(const Point &pt);
int remove_group(Point move, Vec &possible_moves);
bool is_eye(Point move, Color player) const;
bool would_self_atari(Point move, Color player) const;
bool is_safe_horseshoe(Point move, Color player) const; // u shape but not eye, without opponents in enough corners to be dangerous
bool is_territory(Point pt, Color player) ;
void fill_territory(Point pt, Color player);
#if 0
void synchronize_tracking_counters(Grid &track, Goban &visited, Point &p);
#endif
}; | 1 | 0.980742 | 1 | 0.980742 | game-dev | MEDIA | 0.920663 | game-dev | 0.791086 | 1 | 0.791086 |
SenseNet/sensenet | 1,762 | src/Search/Indexing/IndexingActivityStatus.cs | using System.Linq;
namespace SenseNet.Search.Indexing
{
/// <summary>
/// Represents an indexing state
/// </summary>
public class IndexingActivityStatus
{
/// <summary>
/// Shortcut for empty indexing state.
/// </summary>
public static IndexingActivityStatus Startup => new IndexingActivityStatus { Gaps = new int[0], LastActivityId = 0 };
/// <summary>
/// Gets or sets the last written activity id.
/// </summary>
public int LastActivityId { get; set; }
/// <summary>
/// Gets or sets an array of the missing activity ids that are less than the LastActivityId.
/// </summary>
public int[] Gaps { get; set; } = new int[0];
/// <summary>
/// Returns with the string representation of this instance.
/// </summary>
public override string ToString()
{
return $"{LastActivityId}({GapsToString(Gaps, 50, 10)})";
}
/// <summary>
/// Returns with the string representation of the given gaps.
/// The string length can be limited with two parameter.
/// If the gaps length is greater than {maxCount} + {growth},
/// only the {maxCount} items will be converted. For example:
/// "14, 16, 21,... and 20 additional items".
/// </summary>
public static string GapsToString(int[] gaps, int maxCount, int growth)
{
if (gaps.Length < maxCount + growth)
maxCount = gaps.Length;
return (gaps.Length > maxCount)
? $"{string.Join(",", gaps.Take(maxCount))},... and {gaps.Length - maxCount} additional items"
: string.Join(",", gaps);
}
}
}
| 1 | 0.875827 | 1 | 0.875827 | game-dev | MEDIA | 0.502211 | game-dev | 0.943487 | 1 | 0.943487 |
Silverlan/pragma | 1,948 | core/shared/src/lua/ldefinitions.cpp | // SPDX-FileCopyrightText: (c) 2019 Silverlan <opensource@pragma-engine.com>
// SPDX-License-Identifier: MIT
#include "stdafx_shared.h"
#include "pragma/engine.h"
#include "pragma/lua/ldefinitions.h"
#include "pragma/lua/baseluaobj.h"
#include <pragma/lua/lua_error_handling.hpp>
#include <scripting/lua/lua.hpp>
#include <stack>
#include <sharedutils/util_file.h>
// import pragma.scripting.lua;
extern DLLNETWORK Engine *engine;
static void Lua::TypeError(const luabind::object &o, Type type)
{
// TODO
auto *l = o.interpreter();
o.push(l);
auto *typeName = Lua::GetTypeString(l, -1);
Lua::Pop(l, 1);
Lua::PushString(l, typeName);
lua_error(o.interpreter());
}
Lua::Type Lua::GetType(const luabind::object &o) { return static_cast<Type>(luabind::type(o)); }
void Lua::CheckType(const luabind::object &o, Type type)
{
if(GetType(o) == type)
return;
TypeError(o, type);
}
void Lua::PushObject(lua_State *l, BaseLuaObj *o) { o->GetLuaObject()->push(l); }
Lua::StatusCode Lua::Execute(lua_State *l, const std::function<Lua::StatusCode(int (*traceback)(lua_State *))> &target)
{
auto r = target(Lua::HandleTracebackError);
Lua::HandleSyntaxError(l, r);
return r;
}
void Lua::Execute(lua_State *, const std::function<void(int (*traceback)(lua_State *), void (*syntaxHandle)(lua_State *, Lua::StatusCode))> &target) { target(Lua::HandleTracebackError, Lua::HandleSyntaxError); }
void Lua::HandleLuaError(lua_State *l)
{
if(!Lua::IsString(l, -1))
return;
std::string msg = Lua::ToString(l, -1);
msg = pragma::scripting::lua::format_error_message(l, msg, Lua::StatusCode::ErrorRun);
pragma::scripting::lua::submit_error(l, msg);
}
void Lua::HandleLuaError(lua_State *l, Lua::StatusCode s)
{
Lua::HandleTracebackError(l);
Lua::HandleSyntaxError(l, s);
}
std::string Lua::GetErrorMessagePrefix(lua_State *l)
{
auto *state = engine->GetNetworkState(l);
if(state != nullptr)
return state->GetMessagePrefix();
return "";
}
| 1 | 0.738996 | 1 | 0.738996 | game-dev | MEDIA | 0.622717 | game-dev | 0.621053 | 1 | 0.621053 |
RavEngine/RavEngine | 4,776 | deps/physx/physx/include/vehicle2/wheel/PxVehicleWheelComponents.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#pragma once
#include "vehicle2/PxVehicleParams.h"
#include "vehicle2/PxVehicleComponent.h"
#include "vehicle2/commands/PxVehicleCommandHelpers.h"
#include "vehicle2/tire/PxVehicleTireStates.h"
#include "PxVehicleWheelFunctions.h"
#include "PxVehicleWheelHelpers.h"
#include "common/PxProfileZone.h"
#if !PX_DOXYGEN
namespace physx
{
namespace vehicle2
{
#endif
class PxVehicleWheelComponent : public PxVehicleComponent
{
public:
PxVehicleWheelComponent() : PxVehicleComponent() {}
virtual ~PxVehicleWheelComponent() {}
virtual void getDataForWheelComponent(
const PxVehicleAxleDescription*& axleDescription,
PxVehicleArrayData<const PxReal>& steerResponseStates,
PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams,
PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams,
PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates,
PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates,
PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates,
PxVehicleArrayData<const PxVehicleTireSpeedState>& tireSpeedStates,
PxVehicleArrayData<PxVehicleWheelRigidBody1dState>& wheelRigidBody1dStates,
PxVehicleArrayData<PxVehicleWheelLocalPose>& wheelLocalPoses) = 0;
virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context)
{
PX_PROFILE_ZONE("PxVehicleWheelComponent::update", 0);
const PxVehicleAxleDescription* axleDescription;
PxVehicleArrayData<const PxReal> steerResponseStates;
PxVehicleArrayData<const PxVehicleWheelParams> wheelParams;
PxVehicleArrayData<const PxVehicleSuspensionParams> suspensionParams;
PxVehicleArrayData<const PxVehicleWheelActuationState> actuationStates;
PxVehicleArrayData<const PxVehicleSuspensionState> suspensionStates;
PxVehicleArrayData<const PxVehicleSuspensionComplianceState> suspensionComplianceStates;
PxVehicleArrayData<const PxVehicleTireSpeedState> tireSpeedStates;
PxVehicleArrayData<PxVehicleWheelRigidBody1dState> wheelRigidBody1dStates;
PxVehicleArrayData<PxVehicleWheelLocalPose> wheelLocalPoses;
getDataForWheelComponent(axleDescription, steerResponseStates,
wheelParams, suspensionParams, actuationStates, suspensionStates,
suspensionComplianceStates, tireSpeedStates, wheelRigidBody1dStates,
wheelLocalPoses);
for (PxU32 i = 0; i < axleDescription->nbWheels; i++)
{
const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i];
PxVehicleWheelRotationAngleUpdate(
wheelParams[wheelId],
actuationStates[wheelId], suspensionStates[wheelId],
tireSpeedStates[wheelId],
context.thresholdForwardSpeedForWheelAngleIntegration, dt,
wheelRigidBody1dStates[wheelId]);
wheelLocalPoses[wheelId].localPose = PxVehicleComputeWheelLocalPose(context.frame,
suspensionParams[wheelId],
suspensionStates[wheelId],
suspensionComplianceStates[wheelId],
steerResponseStates[wheelId],
wheelRigidBody1dStates[wheelId]);
}
return true;
}
};
#if !PX_DOXYGEN
} // namespace vehicle2
} // namespace physx
#endif
| 1 | 0.639968 | 1 | 0.639968 | game-dev | MEDIA | 0.722005 | game-dev | 0.704045 | 1 | 0.704045 |
fortressforever/fortressforever | 25,750 | dlls/hl2_dll/npc_zombine.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Combine Zombie... Zombie Combine... its like a... Zombine... get it?
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "ai_basenpc.h"
#include "ai_default.h"
#include "ai_schedule.h"
#include "ai_hull.h"
#include "ai_motor.h"
#include "ai_memory.h"
#include "ai_route.h"
#include "ai_squad.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "entitylist.h"
#include "ai_task.h"
#include "activitylist.h"
#include "engine/IEngineSound.h"
#include "npc_BaseZombie.h"
#include "movevars_shared.h"
#include "IEffects.h"
#include "props.h"
#include "physics_npc_solver.h"
#include "hl2_player.h"
#include "hl2_gamerules.h"
#include "basecombatweapon.h"
#include "basegrenade_shared.h"
#include "grenade_frag.h"
#include "ai_interactions.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
enum
{
SQUAD_SLOT_ZOMBINE_SPRINT1 = LAST_SHARED_SQUADSLOT,
SQUAD_SLOT_ZOMBINE_SPRINT2,
};
#define MIN_SPRINT_TIME 3.5f
#define MAX_SPRINT_TIME 5.5f
#define MIN_SPRINT_DISTANCE 64.0f
#define MAX_SPRINT_DISTANCE 1024.0f
#define SPRINT_CHANCE_VALUE 10
#define SPRINT_CHANCE_VALUE_DARKNESS 50
#define GRENADE_PULL_MAX_DISTANCE 256.0f
#define ZOMBINE_MAX_GRENADES 1
int ACT_ZOMBINE_GRENADE_PULL;
int ACT_ZOMBINE_GRENADE_WALK;
int ACT_ZOMBINE_GRENADE_RUN;
int ACT_ZOMBINE_GRENADE_IDLE;
int ACT_ZOMBINE_ATTACK_FAST;
int ACT_ZOMBINE_GRENADE_FLINCH_BACK;
int ACT_ZOMBINE_GRENADE_FLINCH_FRONT;
int ACT_ZOMBINE_GRENADE_FLINCH_WEST;
int ACT_ZOMBINE_GRENADE_FLINCH_EAST;
int AE_ZOMBINE_PULLPIN;
extern bool IsAlyxInDarknessMode();
ConVar sk_zombie_soldier_health( "sk_zombie_soldier_health","0");
float g_flZombineGrenadeTimes = 0;
class CNPC_Zombine : public CAI_BlendingHost<CNPC_BaseZombie>, public CDefaultPlayerPickupVPhysics
{
DECLARE_DATADESC();
DECLARE_CLASS( CNPC_Zombine, CAI_BlendingHost<CNPC_BaseZombie> );
public:
void Spawn( void );
void Precache( void );
void SetZombieModel( void );
virtual void PrescheduleThink( void );
virtual int SelectSchedule( void );
virtual void BuildScheduleTestBits( void );
virtual void HandleAnimEvent( animevent_t *pEvent );
virtual const char *GetLegsModel( void );
virtual const char *GetTorsoModel( void );
virtual const char *GetHeadcrabClassname( void );
virtual const char *GetHeadcrabModel( void );
virtual void PainSound( const CTakeDamageInfo &info );
virtual void DeathSound( const CTakeDamageInfo &info );
virtual void AlertSound( void );
virtual void IdleSound( void );
virtual void AttackSound( void );
virtual void AttackHitSound( void );
virtual void AttackMissSound( void );
virtual void FootstepSound( bool fRightFoot );
virtual void FootscuffSound( bool fRightFoot );
virtual void MoanSound( envelopePoint_t *pEnvelope, int iEnvelopeSize );
virtual void Event_Killed( const CTakeDamageInfo &info );
virtual void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr );
virtual void RunTask( const Task_t *pTask );
virtual int MeleeAttack1Conditions ( float flDot, float flDist );
virtual bool ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold );
virtual void OnScheduleChange ( void );
virtual bool CanRunAScriptedNPCInteraction( bool bForced );
void GatherGrenadeConditions( void );
virtual Activity NPC_TranslateActivity( Activity baseAct );
const char *GetMoanSound( int nSound );
bool AllowedToSprint( void );
void Sprint( bool bMadSprint = false );
void StopSprint( void );
void DropGrenade( Vector vDir );
bool IsSprinting( void ) { return m_flSprintTime > gpGlobals->curtime; }
bool HasGrenade( void ) { return m_hGrenade != NULL; }
int TranslateSchedule( int scheduleType );
void InputStartSprint ( inputdata_t &inputdata );
void InputPullGrenade ( inputdata_t &inputdata );
virtual CBaseEntity *OnFailedPhysGunPickup ( Vector vPhysgunPos );
//Called when we want to let go of a grenade and let the physcannon pick it up.
void ReleaseGrenade( Vector vPhysgunPos );
virtual bool HandleInteraction( int interactionType, void *data, CBaseCombatCharacter *sourceEnt );
enum
{
COND_ZOMBINE_GRENADE = LAST_BASE_ZOMBIE_CONDITION,
};
enum
{
SCHED_ZOMBINE_PULL_GRENADE = LAST_BASE_ZOMBIE_SCHEDULE,
};
public:
DEFINE_CUSTOM_AI;
private:
float m_flSprintTime;
float m_flSprintRestTime;
float m_flSuperFastAttackTime;
float m_flGrenadePullTime;
int m_iGrenadeCount;
EHANDLE m_hGrenade;
protected:
static const char *pMoanSounds[];
};
LINK_ENTITY_TO_CLASS( npc_zombine, CNPC_Zombine );
BEGIN_DATADESC( CNPC_Zombine )
DEFINE_FIELD( m_flSprintTime, FIELD_TIME ),
DEFINE_FIELD( m_flSprintRestTime, FIELD_TIME ),
DEFINE_FIELD( m_flSuperFastAttackTime, FIELD_TIME ),
DEFINE_FIELD( m_hGrenade, FIELD_EHANDLE ),
DEFINE_FIELD( m_flGrenadePullTime, FIELD_TIME ),
DEFINE_FIELD( m_iGrenadeCount, FIELD_INTEGER ),
DEFINE_INPUTFUNC( FIELD_VOID, "StartSprint", InputStartSprint ),
DEFINE_INPUTFUNC( FIELD_VOID, "PullGrenade", InputPullGrenade ),
END_DATADESC()
//---------------------------------------------------------
//---------------------------------------------------------
const char *CNPC_Zombine::pMoanSounds[] =
{
"ATV_engine_null",
};
void CNPC_Zombine::Spawn( void )
{
Precache();
m_fIsTorso = false;
m_fIsHeadless = false;
SetBloodColor( BLOOD_COLOR_GREEN );
m_iHealth = sk_zombie_soldier_health.GetFloat();
SetMaxHealth( m_iHealth );
m_flFieldOfView = 0.2;
CapabilitiesClear();
BaseClass::Spawn();
m_flSprintTime = 0.0f;
m_flSprintRestTime = 0.0f;
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 1.0, 4.0 );
g_flZombineGrenadeTimes = gpGlobals->curtime;
m_flGrenadePullTime = gpGlobals->curtime;
m_iGrenadeCount = ZOMBINE_MAX_GRENADES;
}
void CNPC_Zombine::Precache( void )
{
BaseClass::Precache();
PrecacheModel( "models/zombie/zombie_soldier.mdl" );
PrecacheModel( "models/zombie/classic_legs.mdl" );
PrecacheModel( "models/zombie/classic_torso.mdl" );
PrecacheScriptSound( "Zombie.FootstepRight" );
PrecacheScriptSound( "Zombie.FootstepLeft" );
PrecacheScriptSound( "Zombine.ScuffRight" );
PrecacheScriptSound( "Zombine.ScuffLeft" );
PrecacheScriptSound( "Zombie.AttackHit" );
PrecacheScriptSound( "Zombie.AttackMiss" );
PrecacheScriptSound( "Zombine.Pain" );
PrecacheScriptSound( "Zombine.Die" );
PrecacheScriptSound( "Zombine.Alert" );
PrecacheScriptSound( "Zombine.Idle" );
PrecacheScriptSound( "Zombine.ReadyGrenade" );
PrecacheScriptSound( "ATV_engine_null" );
PrecacheScriptSound( "Zombine.Charge" );
PrecacheScriptSound( "Zombie.Attack" );
}
void CNPC_Zombine::SetZombieModel( void )
{
SetModel( "models/zombie/zombie_soldier.mdl" );
SetHullType( HULL_HUMAN );
SetBodygroup( ZOMBIE_BODYGROUP_HEADCRAB, !m_fIsHeadless );
SetHullSizeNormal( true );
SetDefaultEyeOffset();
SetActivity( ACT_IDLE );
}
void CNPC_Zombine::PrescheduleThink( void )
{
GatherGrenadeConditions();
if( gpGlobals->curtime > m_flNextMoanSound )
{
if( CanPlayMoanSound() )
{
// Classic guy idles instead of moans.
IdleSound();
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 10.0, 15.0 );
}
else
{
m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 2.5, 5.0 );
}
}
if ( HasGrenade () )
{
CSoundEnt::InsertSound ( SOUND_DANGER, GetAbsOrigin() + GetSmoothedVelocity() * 0.5f , 256, 0.1, this, SOUNDENT_CHANNEL_ZOMBINE_GRENADE );
if( IsSprinting() && GetEnemy() && GetEnemy()->Classify() == CLASS_PLAYER_ALLY_VITAL && HasCondition( COND_SEE_ENEMY ) )
{
if( GetAbsOrigin().DistToSqr(GetEnemy()->GetAbsOrigin()) < Square( 144 ) )
{
StopSprint();
}
}
}
BaseClass::PrescheduleThink();
}
void CNPC_Zombine::OnScheduleChange( void )
{
if ( HasCondition( COND_CAN_MELEE_ATTACK1 ) && IsSprinting() == true )
{
m_flSuperFastAttackTime = gpGlobals->curtime + 1.0f;
}
BaseClass::OnScheduleChange();
}
bool CNPC_Zombine::CanRunAScriptedNPCInteraction( bool bForced )
{
if ( HasGrenade() == true )
return false;
return BaseClass::CanRunAScriptedNPCInteraction( bForced );
}
int CNPC_Zombine::SelectSchedule( void )
{
if ( GetHealth() <= 0 )
return BaseClass::SelectSchedule();
if ( HasCondition( COND_ZOMBINE_GRENADE ) )
{
ClearCondition( COND_ZOMBINE_GRENADE );
return SCHED_ZOMBINE_PULL_GRENADE;
}
return BaseClass::SelectSchedule();
}
void CNPC_Zombine::BuildScheduleTestBits( void )
{
BaseClass::BuildScheduleTestBits();
SetCustomInterruptCondition( COND_ZOMBINE_GRENADE );
}
Activity CNPC_Zombine::NPC_TranslateActivity( Activity baseAct )
{
if ( baseAct == ACT_MELEE_ATTACK1 )
{
if ( m_flSuperFastAttackTime > gpGlobals->curtime || HasGrenade() )
{
return (Activity)ACT_ZOMBINE_ATTACK_FAST;
}
}
if ( baseAct == ACT_IDLE )
{
if ( HasGrenade() )
{
return (Activity)ACT_ZOMBINE_GRENADE_IDLE;
}
}
return BaseClass::NPC_TranslateActivity( baseAct );
}
int CNPC_Zombine::MeleeAttack1Conditions ( float flDot, float flDist )
{
int iBase = BaseClass::MeleeAttack1Conditions( flDot, flDist );
if( HasGrenade() )
{
//Adrian: stop spriting if we get close enough to melee and we have a grenade
//this gives NPCs time to move away from you (before it was almost impossible cause of the high sprint speed)
if ( iBase == COND_CAN_MELEE_ATTACK1 )
{
StopSprint();
}
}
return iBase;
}
void CNPC_Zombine::GatherGrenadeConditions( void )
{
if ( m_iGrenadeCount <= 0 )
return;
if ( g_flZombineGrenadeTimes > gpGlobals->curtime )
return;
if ( m_flGrenadePullTime > gpGlobals->curtime )
return;
if ( m_flSuperFastAttackTime >= gpGlobals->curtime )
return;
if ( HasGrenade() )
return;
if ( GetEnemy() == NULL )
return;
if ( FVisible( GetEnemy() ) == false )
return;
if ( IsSprinting() )
return;
if ( IsOnFire() )
return;
if ( IsRunningDynamicInteraction() == true )
return;
if ( m_ActBusyBehavior.IsActive() )
return;
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if ( pPlayer && pPlayer->FVisible( this ) )
{
float flLengthToPlayer = (pPlayer->GetAbsOrigin() - GetAbsOrigin()).Length();
float flLengthToEnemy = flLengthToPlayer;
if ( pPlayer != GetEnemy() )
{
flLengthToEnemy = ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin()).Length();
}
if ( flLengthToPlayer <= GRENADE_PULL_MAX_DISTANCE && flLengthToEnemy <= GRENADE_PULL_MAX_DISTANCE )
{
float flPullChance = 1.0f - ( flLengthToEnemy / GRENADE_PULL_MAX_DISTANCE );
m_flGrenadePullTime = gpGlobals->curtime + 0.5f;
if ( flPullChance >= random->RandomFloat( 0.0f, 1.0f ) )
{
g_flZombineGrenadeTimes = gpGlobals->curtime + 10.0f;
SetCondition( COND_ZOMBINE_GRENADE );
}
}
}
}
int CNPC_Zombine::TranslateSchedule( int scheduleType )
{
return BaseClass::TranslateSchedule( scheduleType );
}
void CNPC_Zombine::DropGrenade( Vector vDir )
{
if ( m_hGrenade == NULL )
return;
m_hGrenade->SetParent( NULL );
m_hGrenade->SetOwnerEntity( NULL );
Vector vGunPos;
QAngle angles;
GetAttachment( "grenade_attachment", vGunPos, angles );
IPhysicsObject *pPhysObj = m_hGrenade->VPhysicsGetObject();
if ( pPhysObj == NULL )
{
m_hGrenade->SetMoveType( MOVETYPE_VPHYSICS );
m_hGrenade->SetSolid( SOLID_VPHYSICS );
m_hGrenade->SetCollisionGroup( COLLISION_GROUP_WEAPON );
m_hGrenade->CreateVPhysics();
}
if ( pPhysObj )
{
pPhysObj->Wake();
pPhysObj->SetPosition( vGunPos, angles, true );
pPhysObj->ApplyForceCenter( vDir * 0.2f );
pPhysObj->RecheckCollisionFilter();
}
m_hGrenade = NULL;
}
void CNPC_Zombine::Event_Killed( const CTakeDamageInfo &info )
{
BaseClass::Event_Killed( info );
if ( HasGrenade() )
{
DropGrenade( vec3_origin );
}
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CNPC_Zombine::HandleInteraction( int interactionType, void *data, CBaseCombatCharacter *sourceEnt )
{
if ( interactionType == g_interactionBarnacleVictimGrab )
{
if ( HasGrenade() )
{
DropGrenade( vec3_origin );
}
}
return BaseClass::HandleInteraction( interactionType, data, sourceEnt );
}
void CNPC_Zombine::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr )
{
BaseClass::TraceAttack( info, vecDir, ptr );
//Only knock grenades off their hands if it's a player doing the damage.
if ( info.GetAttacker() && info.GetAttacker()->IsNPC() )
return;
if ( info.GetDamageType() & ( DMG_BULLET | DMG_CLUB ) )
{
if ( ptr->hitgroup == HITGROUP_LEFTARM )
{
if ( HasGrenade() )
{
DropGrenade( info.GetDamageForce() );
StopSprint();
}
}
}
}
void CNPC_Zombine::HandleAnimEvent( animevent_t *pEvent )
{
if ( pEvent->event == AE_ZOMBINE_PULLPIN )
{
Vector vecStart;
QAngle angles;
GetAttachment( "grenade_attachment", vecStart, angles );
CBaseGrenade *pGrenade = Fraggrenade_Create( vecStart, vec3_angle, vec3_origin, AngularImpulse( 0, 0, 0 ), this, 3.5f, true );
if ( pGrenade )
{
// Move physobject to shadow
IPhysicsObject *pPhysicsObject = pGrenade->VPhysicsGetObject();
if ( pPhysicsObject )
{
pGrenade->VPhysicsDestroyObject();
int iAttachment = LookupAttachment( "grenade_attachment");
pGrenade->SetMoveType( MOVETYPE_NONE );
pGrenade->SetSolid( SOLID_NONE );
pGrenade->SetCollisionGroup( COLLISION_GROUP_DEBRIS );
pGrenade->SetAbsOrigin( vecStart );
pGrenade->SetAbsAngles( angles );
pGrenade->SetParent( this, iAttachment );
pGrenade->SetDamage( 200.0f );
m_hGrenade = pGrenade;
EmitSound( "Zombine.ReadyGrenade" );
// Tell player allies nearby to regard me!
CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs();
CAI_BaseNPC *pNPC;
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
pNPC = ppAIs[i];
if( pNPC->Classify() == CLASS_PLAYER_ALLY || pNPC->Classify() == CLASS_PLAYER_ALLY_VITAL && pNPC->FVisible(this) )
{
int priority;
Disposition_t disposition;
priority = pNPC->IRelationPriority(this);
disposition = pNPC->IRelationType(this);
pNPC->AddEntityRelationship( this, disposition, priority + 1 );
}
}
}
m_iGrenadeCount--;
}
return;
}
if ( pEvent->event == AE_NPC_ATTACK_BROADCAST )
{
if ( HasGrenade() )
return;
}
BaseClass::HandleAnimEvent( pEvent );
}
bool CNPC_Zombine::AllowedToSprint( void )
{
if ( IsOnFire() )
return false;
//If you're sprinting then there's no reason to sprint again.
if ( IsSprinting() )
return false;
int iChance = SPRINT_CHANCE_VALUE;
CHL2_Player *pPlayer = dynamic_cast <CHL2_Player*> ( AI_GetSinglePlayer() );
if ( pPlayer )
{
if ( HL2GameRules()->IsAlyxInDarknessMode() && pPlayer->FlashlightIsOn() == false )
{
iChance = SPRINT_CHANCE_VALUE_DARKNESS;
}
//Bigger chance of this happening if the player is not looking at the zombie
if ( pPlayer->FInViewCone( this ) == false )
{
iChance *= 2;
}
}
if ( HasGrenade() )
{
iChance *= 4;
}
//Below 25% health they'll always sprint
if ( ( GetHealth() > GetMaxHealth() * 0.5f ) )
{
if ( IsStrategySlotRangeOccupied( SQUAD_SLOT_ZOMBINE_SPRINT1, SQUAD_SLOT_ZOMBINE_SPRINT2 ) == true )
return false;
if ( random->RandomInt( 0, 100 ) > iChance )
return false;
if ( m_flSprintRestTime > gpGlobals->curtime )
return false;
}
float flLength = ( GetEnemy()->WorldSpaceCenter() - WorldSpaceCenter() ).Length();
if ( flLength > MAX_SPRINT_DISTANCE )
return false;
return true;
}
void CNPC_Zombine::StopSprint( void )
{
GetNavigator()->SetMovementActivity( ACT_WALK );
m_flSprintTime = gpGlobals->curtime;
m_flSprintRestTime = m_flSprintTime + random->RandomFloat( 2.5f, 5.0f );
}
void CNPC_Zombine::Sprint( bool bMadSprint )
{
if ( IsSprinting() )
return;
OccupyStrategySlotRange( SQUAD_SLOT_ZOMBINE_SPRINT1, SQUAD_SLOT_ZOMBINE_SPRINT2 );
GetNavigator()->SetMovementActivity( ACT_RUN );
float flSprintTime = random->RandomFloat( MIN_SPRINT_TIME, MAX_SPRINT_TIME );
//If holding a grenade then sprint until it blows up.
if ( HasGrenade() || bMadSprint == true )
{
flSprintTime = 9999;
}
m_flSprintTime = gpGlobals->curtime + flSprintTime;
//Don't sprint for this long after I'm done with this sprint run.
m_flSprintRestTime = m_flSprintTime + random->RandomFloat( 2.5f, 5.0f );
EmitSound( "Zombine.Charge" );
}
void CNPC_Zombine::RunTask( const Task_t *pTask )
{
switch ( pTask->iTask )
{
case TASK_WAIT_FOR_MOVEMENT_STEP:
case TASK_WAIT_FOR_MOVEMENT:
{
BaseClass::RunTask( pTask );
if ( IsOnFire() && IsSprinting() )
{
StopSprint();
}
//Only do this if I have an enemy
if ( GetEnemy() )
{
if ( AllowedToSprint() == true )
{
Sprint( ( GetHealth() <= GetMaxHealth() * 0.5f ) );
return;
}
if ( HasGrenade() )
{
if ( IsSprinting() )
{
GetNavigator()->SetMovementActivity( (Activity)ACT_ZOMBINE_GRENADE_RUN );
}
else
{
GetNavigator()->SetMovementActivity( (Activity)ACT_ZOMBINE_GRENADE_WALK );
}
return;
}
if ( GetNavigator()->GetMovementActivity() != ACT_WALK )
{
if ( IsSprinting() == false )
{
GetNavigator()->SetMovementActivity( ACT_WALK );
}
}
}
else
{
GetNavigator()->SetMovementActivity( ACT_WALK );
}
break;
}
default:
{
BaseClass::RunTask( pTask );
break;
}
}
}
void CNPC_Zombine::InputStartSprint ( inputdata_t &inputdata )
{
Sprint();
}
void CNPC_Zombine::InputPullGrenade ( inputdata_t &inputdata )
{
g_flZombineGrenadeTimes = gpGlobals->curtime + 5.0f;
SetCondition( COND_ZOMBINE_GRENADE );
}
//-----------------------------------------------------------------------------
// Purpose: Returns a moan sound for this class of zombie.
//-----------------------------------------------------------------------------
const char *CNPC_Zombine::GetMoanSound( int nSound )
{
return pMoanSounds[ nSound % ARRAYSIZE( pMoanSounds ) ];
}
//-----------------------------------------------------------------------------
// Purpose: Sound of a footstep
//-----------------------------------------------------------------------------
void CNPC_Zombine::FootstepSound( bool fRightFoot )
{
if( fRightFoot )
{
EmitSound( "Zombie.FootstepRight" );
}
else
{
EmitSound( "Zombie.FootstepLeft" );
}
}
//-----------------------------------------------------------------------------
// Purpose: Overloaded so that explosions don't split the zombine in twain.
//-----------------------------------------------------------------------------
bool CNPC_Zombine::ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold )
{
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Sound of a foot sliding/scraping
//-----------------------------------------------------------------------------
void CNPC_Zombine::FootscuffSound( bool fRightFoot )
{
if( fRightFoot )
{
EmitSound( "Zombine.ScuffRight" );
}
else
{
EmitSound( "Zombine.ScuffLeft" );
}
}
//-----------------------------------------------------------------------------
// Purpose: Play a random attack hit sound
//-----------------------------------------------------------------------------
void CNPC_Zombine::AttackHitSound( void )
{
EmitSound( "Zombie.AttackHit" );
}
//-----------------------------------------------------------------------------
// Purpose: Play a random attack miss sound
//-----------------------------------------------------------------------------
void CNPC_Zombine::AttackMissSound( void )
{
// Play a random attack miss sound
EmitSound( "Zombie.AttackMiss" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Zombine::PainSound( const CTakeDamageInfo &info )
{
// We're constantly taking damage when we are on fire. Don't make all those noises!
if ( IsOnFire() )
{
return;
}
EmitSound( "Zombine.Pain" );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Zombine::DeathSound( const CTakeDamageInfo &info )
{
EmitSound( "Zombine.Die" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Zombine::AlertSound( void )
{
EmitSound( "Zombine.Alert" );
// Don't let a moan sound cut off the alert sound.
m_flNextMoanSound += random->RandomFloat( 2.0, 4.0 );
}
//-----------------------------------------------------------------------------
// Purpose: Play a random idle sound.
//-----------------------------------------------------------------------------
void CNPC_Zombine::IdleSound( void )
{
if( GetState() == NPC_STATE_IDLE && random->RandomFloat( 0, 1 ) == 0 )
{
// Moan infrequently in IDLE state.
return;
}
if( IsSlumped() )
{
// Sleeping zombies are quiet.
return;
}
EmitSound( "Zombine.Idle" );
MakeAISpookySound( 360.0f );
}
//-----------------------------------------------------------------------------
// Purpose: Play a random attack sound.
//-----------------------------------------------------------------------------
void CNPC_Zombine::AttackSound( void )
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const char *CNPC_Zombine::GetHeadcrabModel( void )
{
return "models/headcrabclassic.mdl";
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CNPC_Zombine::GetLegsModel( void )
{
return "models/zombie/classic_legs.mdl";
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const char *CNPC_Zombine::GetTorsoModel( void )
{
return "models/zombie/classic_torso.mdl";
}
//---------------------------------------------------------
// Classic zombie only uses moan sound if on fire.
//---------------------------------------------------------
void CNPC_Zombine::MoanSound( envelopePoint_t *pEnvelope, int iEnvelopeSize )
{
if( IsOnFire() )
{
BaseClass::MoanSound( pEnvelope, iEnvelopeSize );
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns the classname (ie "npc_headcrab") to spawn when our headcrab bails.
//-----------------------------------------------------------------------------
const char *CNPC_Zombine::GetHeadcrabClassname( void )
{
return "npc_headcrab";
}
void CNPC_Zombine::ReleaseGrenade( Vector vPhysgunPos )
{
if ( HasGrenade() == false )
return;
Vector vDir = vPhysgunPos - m_hGrenade->GetAbsOrigin();
VectorNormalize( vDir );
Activity aActivity;
Vector vForward, vRight;
GetVectors( &vForward, &vRight, NULL );
float flDotForward = DotProduct( vForward, vDir );
float flDotRight = DotProduct( vRight, vDir );
bool bNegativeForward = false;
bool bNegativeRight = false;
if ( flDotForward < 0.0f )
{
bNegativeForward = true;
flDotForward = flDotForward * -1;
}
if ( flDotRight < 0.0f )
{
bNegativeRight = true;
flDotRight = flDotRight * -1;
}
if ( flDotRight > flDotForward )
{
if ( bNegativeRight == true )
aActivity = (Activity)ACT_ZOMBINE_GRENADE_FLINCH_WEST;
else
aActivity = (Activity)ACT_ZOMBINE_GRENADE_FLINCH_EAST;
}
else
{
if ( bNegativeForward == true )
aActivity = (Activity)ACT_ZOMBINE_GRENADE_FLINCH_BACK;
else
aActivity = (Activity)ACT_ZOMBINE_GRENADE_FLINCH_FRONT;
}
AddGesture( aActivity );
DropGrenade( vec3_origin );
if ( IsSprinting() )
{
StopSprint();
}
else
{
Sprint();
}
}
CBaseEntity *CNPC_Zombine::OnFailedPhysGunPickup( Vector vPhysgunPos )
{
CBaseEntity *pGrenade = m_hGrenade;
ReleaseGrenade( vPhysgunPos );
return pGrenade;
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( npc_zombine, CNPC_Zombine )
//Squad slots
DECLARE_SQUADSLOT( SQUAD_SLOT_ZOMBINE_SPRINT1 )
DECLARE_SQUADSLOT( SQUAD_SLOT_ZOMBINE_SPRINT2 )
DECLARE_CONDITION( COND_ZOMBINE_GRENADE )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_PULL )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_WALK )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_RUN )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_IDLE )
DECLARE_ACTIVITY( ACT_ZOMBINE_ATTACK_FAST )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_FLINCH_BACK )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_FLINCH_FRONT )
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_FLINCH_WEST)
DECLARE_ACTIVITY( ACT_ZOMBINE_GRENADE_FLINCH_EAST )
DECLARE_ANIMEVENT( AE_ZOMBINE_PULLPIN )
DEFINE_SCHEDULE
(
SCHED_ZOMBINE_PULL_GRENADE,
" Tasks"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_ZOMBINE_GRENADE_PULL"
" Interrupts"
)
AI_END_CUSTOM_NPC()
| 1 | 0.987018 | 1 | 0.987018 | game-dev | MEDIA | 0.982411 | game-dev | 0.791725 | 1 | 0.791725 |
dreamanlan/CSharpGameFramework | 2,779 | Unity3d/Assets/Scripts/StoryScript/StoryObject.cs | using UnityEngine;
using System.Collections;
public class StoryObject : MonoBehaviour
{
public void SetLightVisible(int visible)
{
Light[] lights = gameObject.GetComponentsInChildren<Light>();
for (int i = 0; i < lights.Length; ++i) {
Light light = lights[i];
if(visible==0){
light.enabled = false;
} else {
light.enabled = true;
}
}
}
public void SetVisible(int visible)
{
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
for (int i = 0; i < renderers.Length; ++i) {
if (visible == 0) {
renderers[i].enabled = false;
} else {
renderers[i].enabled = true;
}
}
}
public void SetChildActive(object[] args)
{
if (args.Length < 2) return;
string child = (string)args[0];
int visible = (int)args[1];
var t = transform.Find(child);
if (null != t) {
t.gameObject.SetActive(visible != 0);
}
}
public void PlayAnimation(object[] args)
{
if (args.Length < 2) return;
string animName = (string)args[0];
float speed = (float)args[1];
Animator[] animators = gameObject.GetComponentsInChildren<Animator>();
if (null != animators) {
for (int i = 0; i < animators.Length; ++i) {
var animator = animators[i];
animator.Play(animName, -1, 0);
animator.speed = speed;
}
}
}
public void PlayParticle()
{
ParticleSystem[] pss = gameObject.GetComponentsInChildren<ParticleSystem>();
for (int i = 0; i < pss.Length; i++) {
pss[i].Play();
}
}
public void StopParticle()
{
ParticleSystem[] pss = gameObject.GetComponentsInChildren<ParticleSystem>();
for (int i = 0; i < pss.Length; i++) {
pss[i].Stop();
}
}
public void EnableObstacle(int arg)
{
bool enable = (int)arg != 0 ? true : false;
var obs = gameObject.GetComponentInChildren<UnityEngine.AI.NavMeshObstacle>();
if (null != obs) {
obs.enabled = enable;
}
}
public void PlaySound(int index)
{
AudioSource[] audios = gameObject.GetComponentsInChildren<AudioSource>();
if (null != audios && index >= 0 && index < audios.Length) {
audios[index].Play();
}
}
public void StopSound(int index)
{
AudioSource[] audios = gameObject.GetComponentsInChildren<AudioSource>();
if (null != audios && index >= 0 && index < audios.Length) {
audios[index].Stop();
}
}
}
| 1 | 0.659379 | 1 | 0.659379 | game-dev | MEDIA | 0.840193 | game-dev | 0.923458 | 1 | 0.923458 |
magefree/mage | 1,658 | Mage.Sets/src/mage/cards/w/WildPackSquad.java | package mage.cards.w;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.FirstStrikeAbility;
import mage.abilities.keyword.VigilanceAbility;
import mage.abilities.triggers.BeginningOfCombatTriggeredAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.target.common.TargetCreaturePermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class WildPackSquad extends CardImpl {
public WildPackSquad(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.MERCENARY);
this.power = new MageInt(2);
this.toughness = new MageInt(3);
// At the beginning of combat on your turn, up to one target creature gains first strike and vigilance until end of turn.
Ability ability = new BeginningOfCombatTriggeredAbility(new GainAbilityTargetEffect(FirstStrikeAbility.getInstance())
.setText("up to one target creature gains first strike"));
ability.addEffect(new GainAbilityTargetEffect(VigilanceAbility.getInstance())
.setText("and vigilance until end of turn"));
ability.addTarget(new TargetCreaturePermanent(0, 1));
this.addAbility(ability);
}
private WildPackSquad(final WildPackSquad card) {
super(card);
}
@Override
public WildPackSquad copy() {
return new WildPackSquad(this);
}
}
| 1 | 0.89307 | 1 | 0.89307 | game-dev | MEDIA | 0.982033 | game-dev | 0.980763 | 1 | 0.980763 |
stride3d/stride-community-toolkit | 2,129 | examples/code-only/Example10_StrideUI_DragAndDrop/Program.cs | using Example10_StrideUI_DragAndDrop;
using Stride.CommunityToolkit.Bepu;
using Stride.CommunityToolkit.Engine;
using Stride.CommunityToolkit.Renderers;
using Stride.CommunityToolkit.Rendering.ProceduralModels;
using Stride.CommunityToolkit.Skyboxes;
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Games;
using Stride.Graphics;
UIManager? _uiManager = null;
PrimitiveGenerator? _shapeGenerator = null;
const int ShapeCount = 100;
const int RemovalThresholdY = -30;
const string TotalCubes = "Total Shapes: ";
using var game = new Game();
game.Run(start: Start, update: Update);
void Start(Scene scene)
{
// Setup the base 3D scene with default lighting, camera, etc.
game.SetupBase3DScene();
// Add debugging aids: entity names, positions
game.AddEntityDebugSceneRenderer(new()
{
EnableBackground = true
});
game.AddSkybox();
game.AddProfiler();
_shapeGenerator = new PrimitiveGenerator(game, scene);
var font = game.Content.Load<SpriteFont>("StrideDefaultFont");
// Create and display the UI components on screen
CreateAndAddUI(scene, font);
// Add an example 3D capsule entity to the scene for visual reference
AddExampleShape(scene);
}
void Update(Scene scene, GameTime time)
{
foreach (var entity in scene.Entities)
{
if (entity.Transform.Position.Y < RemovalThresholdY)
{
entity.Scene = null;
_shapeGenerator?.SubtractTotalCubes(1);
_uiManager?.UpdateTextBlock($"{TotalCubes} {_shapeGenerator?.TotalShapes ?? 0}");
}
}
}
void CreateAndAddUI(Scene scene, SpriteFont font)
{
_uiManager = new UIManager(font, GenerateRandomSpheres);
_uiManager.Entity.Scene = scene;
}
void AddExampleShape(Scene scene)
{
var entity = game.Create3DPrimitive(PrimitiveModelType.Capsule);
entity.Transform.Position = new Vector3(0, 8, 0);
entity.Scene = scene;
}
void GenerateRandomSpheres()
{
var totalShapes = _shapeGenerator?.Generate(ShapeCount, PrimitiveModelType.Sphere);
_uiManager?.UpdateTextBlock($"{TotalCubes} {totalShapes ?? 0}");
} | 1 | 0.777989 | 1 | 0.777989 | game-dev | MEDIA | 0.881493 | game-dev | 0.963849 | 1 | 0.963849 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.