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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MonsterDruide1/OdysseyDecomp | 8,974 | lib/al/Library/LiveActor/ActorResourceFunction.cpp | #include "Library/LiveActor/ActorResourceFunction.h"
#include <prim/seadSafeString.h>
#include "Library/Base/StringUtil.h"
#include "Library/LiveActor/ActorInitInfo.h"
#include "Library/LiveActor/ActorInitUtil.h"
#include "Library/LiveActor/LiveActor.h"
#include "Library/Model/ModelKeeper.h"
#include "Library/Resource/ActorResource.h"
#include "Library/Resource/Resource.h"
#include "Library/Resource/ResourceFunction.h"
#include "Library/Yaml/ByamlIter.h"
#include "Library/Yaml/ParameterObj.h"
namespace al {
bool isExistModelResource(const LiveActor* actor) {
return actor->getModelKeeper() != nullptr;
}
bool isExistAnimResource(const LiveActor* actor) {
return tryGetAnimResource(actor) != nullptr;
}
Resource* tryGetAnimResource(const LiveActor* actor) {
return actor->getModelKeeper()->getAnimResource();
}
bool isExistModelResourceYaml(const LiveActor* actor, const char* name, const char* suffix) {
return isExistResourceYaml(getModelResource(actor), name, suffix);
}
Resource* getModelResource(const LiveActor* actor) {
return actor->getModelKeeper()->getModelResource();
}
bool isExistAnimResourceYaml(const LiveActor* actor, const char* name, const char* suffix) {
return isExistResourceYaml(getAnimResource(actor), name, suffix);
}
Resource* getAnimResource(const LiveActor* actor) {
return actor->getModelKeeper()->getAnimResource();
}
bool isExistModelOrAnimResourceYaml(const LiveActor* actor, const char* name, const char* suffix) {
if (isExistModelResourceYaml(actor, name, suffix))
return true;
return tryGetAnimResource(actor) && isExistResourceYaml(getAnimResource(actor), name, suffix);
}
const u8* getModelResourceYaml(const LiveActor* actor, const char* name, const char* suffix) {
return findResourceYaml(getModelResource(actor), name, suffix);
}
const u8* getAnimResourceYaml(const LiveActor* actor, const char* name, const char* suffix) {
return findResourceYaml(getAnimResource(actor), name, suffix);
}
const u8* getModelOrAnimResourceYaml(const LiveActor* actor, const char* name, const char* suffix) {
if (isExistModelResourceYaml(actor, name, suffix))
return getModelResourceYaml(actor, name, suffix);
else
return getAnimResourceYaml(actor, name, suffix);
}
const u8* getMapPartsResourceYaml(const ActorInitInfo& initInfo, const char* name) {
sead::FixedSafeString<256> modelName, path;
makeMapPartsModelName(&modelName, &path, *initInfo.placementInfo);
return findOrCreateResource(path, nullptr)->getByml(name);
}
const u8* tryGetMapPartsResourceYaml(const ActorInitInfo& initInfo, const char* name) {
sead::FixedSafeString<256> modelName, path;
makeMapPartsModelName(&modelName, &path, *initInfo.placementInfo);
return findOrCreateResource(path, nullptr)->tryGetByml(name);
}
bool tryMakeInitFileName(sead::BufferedSafeString* fileName, const Resource* resource,
const char* suffixIterKey, const char* suffixIterSuffix,
const char* suffixIterName) {
const char* suffix = nullptr;
ByamlIter iter;
bool tryResult = tryGetSuffixIter(&iter, resource, suffixIterName, suffixIterSuffix);
if (tryResult) {
if (!iter.isExistKey(suffixIterKey))
return false;
iter.tryGetStringByKey(&suffix, suffixIterKey);
}
createFileNameBySuffix(fileName, suffixIterKey, suffix);
return true;
}
bool tryGetSuffixIter(ByamlIter* iter, const Resource* resource, const char* name,
const char* suffix) {
if (!suffix)
return false;
StringTmp<128> fileNameBySuffix;
createFileNameBySuffix(&fileNameBySuffix, name, suffix);
const u8* resBymlData = resource->tryGetByml(fileNameBySuffix);
if (!resBymlData)
return false;
*iter = {resBymlData};
return true;
}
bool tryGetInitFileIterAndName(ByamlIter* iter, sead::BufferedSafeString* fileName,
const Resource* resource, const char* suffixIterKey,
const char* suffixIterSuffix, const char* suffixIterName) {
StringTmp<128> tmpFileName;
if (!tryMakeInitFileName(&tmpFileName, resource, suffixIterKey, suffixIterSuffix,
suffixIterName))
return false;
const u8* resBymlData = resource->tryGetByml(tmpFileName.cstr());
if (!resBymlData)
return false;
if (iter)
*iter = {resBymlData};
if (fileName)
fileName->format(tmpFileName.cstr());
return true;
}
bool tryGetActorInitFileIterAndName(ByamlIter* iter, sead::BufferedSafeString* fileName,
const Resource* resource, const char* suffixIterKey,
const char* suffixIterSuffix) {
return tryGetInitFileIterAndName(iter, fileName, resource, suffixIterKey, suffixIterSuffix,
"InitActor");
}
bool tryGetActorInitFileIter(ByamlIter* iter, const Resource* resource, const char* suffixIterKey,
const char* suffixIterSuffix) {
return tryGetActorInitFileIterAndName(iter, nullptr, resource, suffixIterKey, suffixIterSuffix);
}
bool tryGetActorInitFileIterAndName(ByamlIter* iter, sead::BufferedSafeString* fileName,
const LiveActor* actor, const char* suffixIterKey,
const char* suffixIterSuffix) {
return tryGetInitFileIterAndName(iter, fileName, getModelResource(actor), suffixIterKey,
suffixIterSuffix, "InitActor");
}
bool tryGetActorInitFileIter(ByamlIter* iter, const LiveActor* actor, const char* suffixIterKey,
const char* suffixIterSuffix) {
return tryGetActorInitFileIterAndName(iter, nullptr, actor, suffixIterKey, suffixIterSuffix);
}
bool tryGetActorInitFileName(sead::BufferedSafeString* fileName, const Resource* resource,
const char* suffixIterKey, const char* suffixIterSuffix) {
return tryMakeInitFileName(fileName, resource, suffixIterKey, suffixIterSuffix, "InitActor");
}
bool tryGetActorInitFileName(sead::BufferedSafeString* fileName, const ActorResource* actorRes,
const char* suffixIterKey, const char* suffixIterSuffix) {
return tryGetActorInitFileName(fileName, actorRes->getModelRes(), suffixIterKey,
suffixIterSuffix);
}
bool tryGetActorInitFileName(sead::BufferedSafeString* fileName, const LiveActor* actor,
const char* suffixIterKey, const char* suffixIterSuffix) {
return tryGetActorInitFileName(fileName, getModelResource(actor), suffixIterKey,
suffixIterSuffix);
}
bool tryGetActorInitFileSuffixName(sead::BufferedSafeString* fileName, const Resource* resource,
const char* suffixIterKey, const char* suffixIterSuffix) {
const char* suffix = nullptr;
ByamlIter iter;
bool tryResult = tryGetSuffixIter(&iter, resource, "InitActor", suffixIterSuffix);
if (tryResult) {
if (!iter.isExistKey(suffixIterKey))
return false;
iter.tryGetStringByKey(&suffix, suffixIterKey);
}
if (fileName)
fileName->copy(suffix == nullptr ? "" : suffix);
return true;
}
bool tryGetActorInitFileSuffixName(sead::BufferedSafeString* fileName, const LiveActor* actor,
const char* suffixIterKey, const char* suffixIterSuffix) {
return tryGetActorInitFileSuffixName(fileName, getModelResource(actor), suffixIterKey,
suffixIterSuffix);
}
const char* tryGetActorInitFileSuffixName(const LiveActor* actor, const char* suffixIterKey,
const char* suffixIterSuffix) {
return tryGetActorInitFileSuffixName(getModelResource(actor), suffixIterKey, suffixIterSuffix);
}
const char* tryGetActorInitFileSuffixName(const Resource* resource, const char* suffixIterKey,
const char* suffixIterSuffix) {
const char* suffix = nullptr;
ByamlIter iter;
bool tryResult = tryGetSuffixIter(&iter, resource, "InitActor", suffixIterSuffix);
if (tryResult) {
if (!iter.isExistKey(suffixIterKey))
return nullptr;
iter.tryGetStringByKey(&suffix, suffixIterKey);
}
return suffix;
}
void initParameterIoAsActorInfo(ParameterIo* parameterIo, const LiveActor* actor,
const char* suffixIterKey, const char* suffixIterSuffix) {}
void initParameterIoAndLoad(ParameterIo* parameterIo, const LiveActor* actor,
const char* suffixIterKey, const char* suffixIterSuffix) {
ByamlIter iter;
tryGetActorInitFileIter(&iter, actor, suffixIterKey, suffixIterSuffix);
parameterIo->tryGetParam(iter);
}
} // namespace al
| 0 | 0.509707 | 1 | 0.509707 | game-dev | MEDIA | 0.624795 | game-dev | 0.603798 | 1 | 0.603798 |
Max-Coin/maxcoin | 1,149 | src/cryptopp/hex.cpp | // hex.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "hex.h"
NAMESPACE_BEGIN(CryptoPP)
static const byte s_vecUpper[] = "0123456789ABCDEF";
static const byte s_vecLower[] = "0123456789abcdef";
void HexEncoder::IsolatedInitialize(const NameValuePairs ¶meters)
{
bool uppercase = parameters.GetValueWithDefault(Name::Uppercase(), true);
m_filter->Initialize(CombinedNameValuePairs(
parameters,
MakeParameters(Name::EncodingLookupArray(), uppercase ? &s_vecUpper[0] : &s_vecLower[0], false)(Name::Log2Base(), 4, true)));
}
void HexDecoder::IsolatedInitialize(const NameValuePairs ¶meters)
{
BaseN_Decoder::IsolatedInitialize(CombinedNameValuePairs(
parameters,
MakeParameters(Name::DecodingLookupArray(), GetDefaultDecodingLookupArray(), false)(Name::Log2Base(), 4, true)));
}
const int *HexDecoder::GetDefaultDecodingLookupArray()
{
static volatile bool s_initialized = false;
static int s_array[256];
if (!s_initialized)
{
InitializeDecodingLookupArray(s_array, s_vecUpper, 16, true);
s_initialized = true;
}
return s_array;
}
NAMESPACE_END
#endif
| 0 | 0.832132 | 1 | 0.832132 | game-dev | MEDIA | 0.297426 | game-dev | 0.56045 | 1 | 0.56045 |
jaames/playnote-studio | 8,065 | Source/sceneManager.lua | sceneManager = {}
local registeredScenes = {}
local activeScene = nil
local isSceneTransitionActive = false
local transitionDrawFn = nil
local sceneHistory = {}
local transitionHistory = {}
local systemMenu = playdate.getSystemMenu()
local systemMenuItems = {}
local isScreenEffectActive = false
local screenEffectMoveX = 0
local screenEffectMoveY = 0
spritelib.setAlwaysRedraw(false)
spritelib.setBackgroundDrawingCallback(function (x, y, w, h)
sceneManager:drawBg(x, y, w, h)
end)
sounds:prepareSfxGroup('screen', {
'navigationForward',
'navigationBackward',
'navigationNotAllowed',
})
sceneManager.blockEffects = false
function sceneManager:register(scenes)
for name, SceneClass in pairs(scenes) do
self:registerScene(name, SceneClass)
end
end
function sceneManager:registerScene(id, SceneClass)
local sceneInst = SceneClass()
registeredScenes[id] = sceneInst
sceneInst.id = id
-- B button should return to the previous screen, globally
if sceneInst.inputHandlers.BButtonDown == nil then
sceneInst.inputHandlers.BButtonDown = function ()
sceneManager:pop()
end
end
end
function sceneManager:push(id, transitionFn, backTransitionFn, ...)
if not isSceneTransitionActive then
local nextScene = registeredScenes[id]
self:_switchScene(nextScene, transitionFn, ...)
if #sceneHistory > 0 then
sounds:playSfx('navigationForward')
end
table.insert(sceneHistory, nextScene)
table.insert(transitionHistory, backTransitionFn or transitionFn)
end
end
function sceneManager:pop()
if not isSceneTransitionActive and #sceneHistory > 1 then
table.remove(sceneHistory)
table.remove(transitionHistory)
local lastScene = sceneHistory[#sceneHistory]
local lastTransition = transitionHistory[#transitionHistory]
self:_switchScene(lastScene, lastTransition)
sounds:playSfx('navigationBackward')
else
self:shakeX()
sounds:playSfx('navigationNotAllowed')
end
end
function sceneManager:_switchScene(nextScene, transitionFn, ...)
isSceneTransitionActive = true
local prevScene = activeScene
self:_sceneBeforeLeave(prevScene)
self:_sceneBeforeEnter(nextScene, ...)
transitionDrawFn = transitionFn(prevScene, nextScene, function()
self:_sceneAfterLeave(prevScene)
self:_sceneAfterEnter(nextScene)
isSceneTransitionActive = false
end)
end
function sceneManager:_sceneBeforeEnter(scene, ...)
-- add sprites for the current scene
if not scene.areSpritesSetup then
scene.areSpritesSetup = true
local sprites = scene:setupSprites()
for i = 1, #sprites do
scene:addSprite(sprites[i])
end
end
systemMenuItems = scene:setupMenuItems(systemMenu)
scene:_addToDisplayList()
scene:beforeEnter(...)
scene:emitHook('enter:before')
end
function sceneManager:_screenEnter(scene)
activeScene = scene
scene.active = true
scene:setSpritesVisible(true)
scene:forceDrawOffset()
scene:enter()
scene:emitHook('enter')
end
function sceneManager:_sceneAfterEnter(scene)
playdate.inputHandlers.push(scene.inputHandlers, true)
scene:afterEnter()
scene:emitHook('enter:after')
end
function sceneManager:_sceneBeforeLeave(scene)
if scene then
playdate.inputHandlers.pop()
scene:beforeLeave()
if systemMenuItems then
for _, item in pairs(systemMenuItems) do
systemMenu:removeMenuItem(item)
end
end
scene:emitHook('leave:before')
end
end
function sceneManager:_screenLeave(scene)
if scene then
scene.active = false
scene:setSpritesVisible(false)
scene:leave()
scene:emitHook('leave')
end
end
function sceneManager:_sceneAfterLeave(scene)
if scene then
scene:_removeFromDisplayList()
scene:afterLeave()
scene:emitHook('leave:after')
end
end
function sceneManager:reloadCurrent(transitionFn, callbackFn)
isSceneTransitionActive = true
self:_sceneAfterLeave(activeScene)
self:_sceneBeforeEnter(activeScene)
transitionDrawFn = transitionFn(activeScene, activeScene, function()
isSceneTransitionActive = false
callbackFn()
end)
end
function sceneManager:shakeX()
if isScreenEffectActive or self.blockEffects then return end
local timer = playdate.timer.new(200, 0, 1)
isScreenEffectActive = true
screenEffectMoveX = 0
screenEffectMoveY = 0
spritelib.setAlwaysRedraw(true)
timer.updateCallback = function (t)
screenEffectMoveX = (playdate.graphics.perlin(t.value, 0, 0, 0) - 0.5) * 60
end
timer.timerEndedCallback = function ()
screenEffectMoveX = 0
utils:nextTick(function ()
isScreenEffectActive = false
spritelib.setAlwaysRedraw(false)
end)
end
end
function sceneManager:doBounce(updateCallback)
if isScreenEffectActive or self.blockEffects then return end
local timer = playdate.timer.new(80, 0, 1, playdate.easingFunctions.inOutSine)
timer.reverses = true
isScreenEffectActive = true
screenEffectMoveX = 0
screenEffectMoveY = 0
spritelib.setAlwaysRedraw(true)
timer.updateCallback = function (t)
updateCallback(t.value)
end
timer.timerEndedCallback = function (t)
screenEffectMoveX = 0
screenEffectMoveY = 0
utils:nextTick(function ()
isScreenEffectActive = false
spritelib.setAlwaysRedraw(false)
end)
end
end
function sceneManager:bounceLeft()
self:doBounce(function (value) screenEffectMoveX = value * 5 end)
end
function sceneManager:bounceRight()
self:doBounce(function (value) screenEffectMoveX = value * -5 end)
end
function sceneManager:bounceUp()
self:doBounce(function (value) screenEffectMoveY = value * 5 end)
end
function sceneManager:bounceDown()
self:doBounce(function (value) screenEffectMoveY = value * -5 end)
end
function sceneManager:drawBg(x, y, w, h)
if activeScene then
activeScene:drawBg(x, y, w, h)
end
end
function sceneManager:update()
if isSceneTransitionActive then
transitionDrawFn()
else
if isScreenEffectActive then
gfx.setDrawOffset(activeScene.drawOffsetX + screenEffectMoveX, activeScene.drawOffsetY + screenEffectMoveY)
end
activeScene:update()
end
end
function sceneManager:_makeTransition(duration, initialState, transitionFn)
return function(a, b, completedCallback)
local timer = playdate.timer.new(duration, 0, 1)
local value = 0
local state = {}
local function drawFn()
transitionFn(value, a, b, state)
end
if type(initialState) == 'function' then
state = initialState(drawFn)
elseif type(initialState) == 'table' then
state = table.deepcopy(initialState)
end
timer.updateCallback = function ()
value = timer.value
if a then a:updateTransitionOut(value, b) end
b:updateTransitionIn(value, a)
end
timer.timerEndedCallback = function ()
value = 1
if a then a:updateTransitionOut(value, b) end
b:updateTransitionIn(value, a)
-- sometimes (depends on easing and frame timing) transition values don't reach 1 before isTransitionActive is set to false,
-- calling drawFn once more seems to fix this
drawFn()
completedCallback()
end
return drawFn
end
end
function sceneManager:_makeInOutTransition(duration, setup, inFn, outFn)
return self:_makeTransition(duration, setup, function (t, a, b, state)
if t < 0.5 then
inFn(t * 2, a, b, state)
else
outFn((t - 0.5) * 2, a, b, state)
end
end)
end
sceneManager.kTransitionNone = sceneManager:_makeTransition(0, nil, function () end)
sceneManager.kTransitionStartup = sceneManager:_makeTransition(650, nil,
function (t, a, b, state)
if not b.active then
sceneManager:_screenEnter(b)
end
overlay:setWhiteFade((0.8 - t))
end
)
sceneManager.kTransitionFade = sceneManager:_makeInOutTransition(420, {nextIn = false},
function (t, a, b, state)
overlay:setWhiteFade(t)
end,
function (t, a, b, state)
if not state.nextIn then
sceneManager:_screenLeave(a)
sceneManager:_screenEnter(b)
state.nextIn = true
end
overlay:setWhiteFade(1 - t)
end
) | 0 | 0.822662 | 1 | 0.822662 | game-dev | MEDIA | 0.978452 | game-dev | 0.946067 | 1 | 0.946067 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 4,865 | Library/PackageCache/com.unity.timeline@1.6.5/Editor/Window/TimelineWindow_PlayRange.cs | using System.Linq;
using UnityEngine;
namespace UnityEditor.Timeline
{
partial class TimelineWindow
{
TimeAreaItem m_PlayRangeEnd;
TimeAreaItem m_PlayRangeStart;
void PlayRangeGUI(TimelineItemArea area)
{
if (!currentMode.ShouldShowPlayRange(state) || treeView == null)
return;
if (state.masterSequence.asset != null && !state.masterSequence.asset.GetRootTracks().Any())
return;
// left Time Cursor
if (m_PlayRangeStart == null || m_PlayRangeStart.style != styles.playTimeRangeStart)
{
m_PlayRangeStart = new TimeAreaItem(styles.playTimeRangeStart, OnTrackHeadMinSelectDrag);
Vector2 offset = new Vector2(-2.0f, 0);
m_PlayRangeStart.boundOffset = offset;
}
// right Time Cursor
if (m_PlayRangeEnd == null || m_PlayRangeEnd.style != styles.playTimeRangeEnd)
{
m_PlayRangeEnd = new TimeAreaItem(styles.playTimeRangeEnd, OnTrackHeadMaxSelectDrag);
Vector2 offset = new Vector2(2.0f, 0);
m_PlayRangeEnd.boundOffset = offset;
}
if (area == TimelineItemArea.Header)
DrawPlayRange(true, false);
else if (area == TimelineItemArea.Lines)
DrawPlayRange(false, true);
}
void DrawPlayRange(bool drawHeads, bool drawLines)
{
Rect timeCursorRect = state.timeAreaRect;
timeCursorRect.height = clientArea.height;
m_PlayRangeEnd.HandleManipulatorsEvents(state);
m_PlayRangeStart.HandleManipulatorsEvents(state);
// The first time a user enable the play range, we put the play range 75% around the current time...
if (state.playRange == TimelineAssetViewModel.NoPlayRangeSet)
{
float minimumPlayRangeTime = 0.01f;
float t0 = Mathf.Max(0.0f, state.PixelToTime(state.timeAreaRect.xMin));
float t1 = Mathf.Min((float)state.masterSequence.duration, state.PixelToTime(state.timeAreaRect.xMax));
if (Mathf.Abs(t1 - t0) <= minimumPlayRangeTime)
{
state.playRange = new Vector2(t0, t1);
return;
}
float deltaT = (t1 - t0) * 0.25f / 2.0f;
t0 += deltaT;
t1 -= deltaT;
if (t1 < t0)
{
float temp = t0;
t0 = t1;
t1 = temp;
}
if (Mathf.Abs(t1 - t0) < minimumPlayRangeTime)
{
if (t0 - minimumPlayRangeTime > 0.0f)
t0 -= minimumPlayRangeTime;
else if (t1 + minimumPlayRangeTime < state.masterSequence.duration)
t1 += minimumPlayRangeTime;
}
state.playRange = new Vector2(t0, t1);
}
// Draw the head or the lines according to the parameters..
m_PlayRangeStart.drawHead = drawHeads;
m_PlayRangeStart.drawLine = drawLines;
m_PlayRangeEnd.drawHead = drawHeads;
m_PlayRangeEnd.drawLine = drawLines;
var playRangeTime = state.playRange;
m_PlayRangeStart.Draw(sequenceContentRect, state, playRangeTime.x);
m_PlayRangeEnd.Draw(sequenceContentRect, state, playRangeTime.y);
// Draw Time Range Box from Start to End...
if (state.playRangeEnabled && m_PlayHead != null)
{
Rect rect =
Rect.MinMaxRect(
Mathf.Clamp(state.TimeToPixel(playRangeTime.x), state.timeAreaRect.xMin, state.timeAreaRect.xMax),
m_PlayHead.bounds.yMax,
Mathf.Clamp(state.TimeToPixel(playRangeTime.y), state.timeAreaRect.xMin, state.timeAreaRect.xMax),
sequenceContentRect.height + state.timeAreaRect.height + timeCursorRect.y
);
EditorGUI.DrawRect(rect, DirectorStyles.Instance.customSkin.colorRange);
rect.height = 3f;
EditorGUI.DrawRect(rect, Color.white);
}
}
void OnTrackHeadMinSelectDrag(double newTime)
{
Vector2 range = state.playRange;
range.x = (float)newTime;
state.playRange = range;
m_PlayRangeStart.showTooltip = true;
}
void OnTrackHeadMaxSelectDrag(double newTime)
{
Vector2 range = state.playRange;
range.y = (float)newTime;
state.playRange = range;
m_PlayRangeEnd.showTooltip = true;
}
}
}
| 0 | 0.836943 | 1 | 0.836943 | game-dev | MEDIA | 0.746512 | game-dev | 0.979503 | 1 | 0.979503 |
Povstalec/StargateJourney | 5,102 | src/main/java/net/povstalec/sgjourney/common/items/blocks/CartoucheBlockItem.java | package net.povstalec.sgjourney.common.items.blocks;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.povstalec.sgjourney.common.block_entities.CartoucheEntity;
import net.povstalec.sgjourney.common.block_entities.StructureGenEntity;
import net.povstalec.sgjourney.common.block_entities.transporter.AbstractTransporterEntity;
import net.povstalec.sgjourney.common.blockstates.Orientation;
public class CartoucheBlockItem extends BlockItem
{
public CartoucheBlockItem(Block block, Properties properties)
{
super(block, properties);
}
@Override
protected boolean canPlace(BlockPlaceContext context, BlockState state)
{
BlockPos blockpos = context.getClickedPos();
Level level = context.getLevel();
Player player = context.getPlayer();
CollisionContext collisioncontext = player == null ? CollisionContext.empty() : CollisionContext.of(player);
Orientation orientation = Orientation.getOrientationFromXRot(context.getPlayer());
Direction direction = context.getHorizontalDirection().getOpposite();
int maxBuildHeight = level.getMaxBuildHeight();
if(orientation != Orientation.REGULAR)
maxBuildHeight -= 1;
if(blockpos.getY() > maxBuildHeight || !level.getBlockState(blockpos.relative(Orientation.getMultiDirection(direction, Direction.UP, orientation))).canBeReplaced(context))
{
player.displayClientMessage(Component.translatable("block.sgjourney.cartouche.not_enough_space"), true);
return false;
}
return (!this.mustSurvive() || state.canSurvive(context.getLevel(), context.getClickedPos())) && context.getLevel().isUnobstructed(state, context.getClickedPos(), collisioncontext);
}
@Override
protected boolean updateCustomBlockEntityTag(BlockPos pos, Level level, @Nullable Player player, ItemStack stack, BlockState state)
{
return updateCustomBlockEntityTag(level, player, pos, stack);
}
public static boolean updateCustomBlockEntityTag(Level level, @Nullable Player player, BlockPos pos, ItemStack stack)
{
MinecraftServer minecraftserver = level.getServer();
if(minecraftserver == null)
return false;
if(stack.has(DataComponents.BLOCK_ENTITY_DATA))
{
CompoundTag compoundtag = stack.get(DataComponents.BLOCK_ENTITY_DATA).getUnsafe();
BlockEntity blockentity = level.getBlockEntity(pos);
if(blockentity != null)
{
if(!level.isClientSide && blockentity.onlyOpCanSetNbt() && (player == null || !player.canUseGameMasterBlocks()))
return false;
CompoundTag compoundtag1 = blockentity.saveWithoutMetadata(minecraftserver.registryAccess());
CompoundTag compoundtag2 = compoundtag1.copy();
compoundtag1.merge(compoundtag);
if(!compoundtag1.equals(compoundtag2))
{
blockentity.loadCustomOnly(compoundtag1, minecraftserver.registryAccess());
blockentity.setChanged();
return setupBlockEntity(level, blockentity, compoundtag);
}
}
}
else
return setupBlockEntity(level, level.getBlockEntity(pos), new CompoundTag());
return false;
}
private static boolean setupBlockEntity(Level level, BlockEntity baseEntity, CompoundTag info)
{
if(baseEntity instanceof CartoucheEntity cartouche)
{
StructureGenEntity.Step generationStep;
if(info.contains(AbstractTransporterEntity.GENERATION_STEP, CompoundTag.TAG_BYTE))
generationStep = StructureGenEntity.Step.fromByte(info.getByte(AbstractTransporterEntity.GENERATION_STEP));
else
generationStep = StructureGenEntity.Step.GENERATED;
if(generationStep == StructureGenEntity.Step.GENERATED)
{
if(info.contains(CartoucheEntity.DIMENSION, CompoundTag.TAG_STRING) && !info.contains(CartoucheEntity.ADDRESS))
cartouche.setDimension(ResourceLocation.tryParse(info.getString(CartoucheEntity.DIMENSION)));
else
cartouche.setDimensionFromLevel(level);
cartouche.setAddressFromDimension();
if(info.contains(CartoucheEntity.SYMBOLS, CompoundTag.TAG_STRING))
cartouche.setSymbols(ResourceLocation.tryParse(info.getString(CartoucheEntity.SYMBOLS)));
else
cartouche.setSymbolsFromLevel(level);
}
return true;
}
return false;
}
}
| 0 | 0.91171 | 1 | 0.91171 | game-dev | MEDIA | 0.997912 | game-dev | 0.936311 | 1 | 0.936311 |
runuo/runuo | 1,656 | Scripts/Engines/CannedEvil/ChampionPlatform.cs | using System;
using System.Collections;
using Server;
using Server.Items;
namespace Server.Engines.CannedEvil
{
public class ChampionPlatform : BaseAddon
{
private ChampionSpawn m_Spawn;
public ChampionPlatform( ChampionSpawn spawn )
{
m_Spawn = spawn;
for ( int x = -2; x <= 2; ++x )
for ( int y = -2; y <= 2; ++y )
AddComponent( 0x750, x, y, -5 );
for ( int x = -1; x <= 1; ++x )
for ( int y = -1; y <= 1; ++y )
AddComponent( 0x750, x, y, 0 );
for ( int i = -1; i <= 1; ++i )
{
AddComponent( 0x751, i, 2, 0 );
AddComponent( 0x752, 2, i, 0 );
AddComponent( 0x753, i, -2, 0 );
AddComponent( 0x754, -2, i, 0 );
}
AddComponent( 0x759, -2, -2, 0 );
AddComponent( 0x75A, 2, 2, 0 );
AddComponent( 0x75B, -2, 2, 0 );
AddComponent( 0x75C, 2, -2, 0 );
}
public void AddComponent( int id, int x, int y, int z )
{
AddonComponent ac = new AddonComponent( id );
ac.Hue = 0x497;
AddComponent( ac, x, y, z );
}
public override void OnAfterDelete()
{
base.OnAfterDelete();
if ( m_Spawn != null )
m_Spawn.Delete();
}
public ChampionPlatform( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( m_Spawn );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_Spawn = reader.ReadItem() as ChampionSpawn;
if ( m_Spawn == null )
Delete();
break;
}
}
}
}
} | 0 | 0.842661 | 1 | 0.842661 | game-dev | MEDIA | 0.896651 | game-dev | 0.737659 | 1 | 0.737659 |
KCL-Planning/VAL | 6,390 | libraries/VAL/include/RepairAdvice.h | // Copyright 2019 - University of Strathclyde, King's College London and Schlumberger Ltd
// This source code is licensed under the BSD license found in the LICENSE file in the root directory of this source tree.
#ifndef __REPAIRADVICE
#define __REPAIRADVICE
#include "Action.h"
#include "State.h"
#include <memory>
using std::auto_ptr;
namespace VAL {
class UnsatCondition {
protected:
mutable State state;
private:
// Don't want these to be allowed.
UnsatCondition(const UnsatCondition &us);
UnsatCondition &operator=(const UnsatCondition &us);
public:
const AdviceProposition *ap;
UnsatCondition(const State &st, const AdviceProposition *a)
: state(st), ap(a){};
virtual ~UnsatCondition() { delete ap; };
virtual void display() const {};
virtual void advice() const {};
virtual const Action *getAct() const { return 0; };
virtual double getTime() const { return 0; };
virtual State &getState() const { return state; };
virtual double howLong() const { return 0.0; };
virtual string getDisplayString() const { return "!"; };
virtual string getAdviceString() const;
};
struct UnsatPrecondition : public UnsatCondition {
double time;
const Action *action;
UnsatPrecondition(double t, const Action *a, const State *s)
: UnsatCondition(*s, a->getPrecondition()->getAdviceProp(s)),
time(t),
action(a){};
~UnsatPrecondition(){};
void display() const;
void advice() const;
const Action *getAct() const { return action; };
double getTime() const { return time; };
string getDisplayString() const;
};
struct UnsatDurationCondition : public UnsatCondition {
double time;
const Action *action;
double error; // how far out was the duration?
UnsatDurationCondition(double t, const Action *a, const State *s, double e)
: UnsatCondition(*s, 0), time(t), action(a), error(e){};
~UnsatDurationCondition(){};
void display() const;
string getDisplayString() const;
void advice() const;
};
struct MutexViolation : public UnsatCondition {
double time;
const Action *action1;
const Action *action2;
// string reason; //reason for the mutex condition
MutexViolation(double t, const Action *a1, const Action *a2, const State *s)
: UnsatCondition(*s, 0), time(t), action1(a1), action2(a2){};
~MutexViolation(){};
void display() const;
string getDisplayString() const;
void advice() const;
};
struct UnsatGoal : public UnsatCondition {
const Proposition *pre;
UnsatGoal(const Proposition *p, const State *s)
: UnsatCondition(*s, p->getAdviceProp(s)), pre(p){};
~UnsatGoal() { pre->destroy(); };
void display() const;
string getDisplayString() const;
void advice() const;
};
struct UnsatInvariant : public UnsatCondition {
double startTime;
double endTime;
Intervals satisfiedOn;
const Action *action; // invariant Action, precondition is unsatisfied
// condition
bool rootError;
UnsatInvariant(double st, double e, const Intervals &ints, const Action *a,
const State *s, bool re)
: UnsatCondition(*s, a->getPrecondition()->getAdviceProp(s)),
startTime(st),
endTime(e),
satisfiedOn(ints),
action(a),
rootError(re){};
~UnsatInvariant(){};
void display() const;
void advice() const;
const Action *getAct() const { return action; };
double getTime() const { return startTime; };
double getEnd() const { return endTime; };
bool isRootError() const { return rootError; };
const Intervals &getInts() const { return satisfiedOn; };
double howLong() const { return endTime - startTime; };
string getDisplayString() const;
};
struct UnsatConditionFactory {
virtual ~UnsatConditionFactory(){};
virtual UnsatPrecondition *buildUnsatPrecondition(double t, const Action *a,
const State *s) {
return new UnsatPrecondition(t, a, s);
};
virtual UnsatDurationCondition *buildUnsatDurationCondition(double t,
const Action *a,
const State *s,
double e) {
return new UnsatDurationCondition(t, a, s, e);
};
virtual MutexViolation *buildMutexViolation(double t, const Action *a1,
const Action *a2,
const State *s) {
return new MutexViolation(t, a1, a2, s);
};
virtual UnsatGoal *buildUnsatGoal(const Proposition *p, const State *s) {
return new UnsatGoal(p, s);
};
virtual UnsatInvariant *buildUnsatInvariant(double st, double e,
const Intervals &ints,
const Action *a, const State *s,
bool re) {
return new UnsatInvariant(st, e, ints, a, s, re);
};
};
class ErrorLog {
private:
static std::unique_ptr< UnsatConditionFactory > fac;
vector< const UnsatCondition * > conditions;
public:
template < typename Fac >
static void replace() {
fac = std::make_unique<Fac>();
};
template < typename Fac >
static void replace(std::unique_ptr<Fac> f) {
fac = std::move(f);
};
ErrorLog(){};
~ErrorLog();
void addPrecondition(double t, const Action *a, const State *s);
void addUnsatDurationCondition(double t, const Action *a, const State *s,
double e);
void addMutexViolation(double t, const Action *a1, const Action *a2,
const State *s);
void addUnsatInvariant(double st, double e, Intervals ints, const Action *a,
const State *s, bool rootError = false);
void addGoal(const Proposition *p, const State *s);
vector< const UnsatCondition * > &getConditions() { return conditions; };
// vector<const UnsatCondition *> getConditions() const {return
// conditions;};
void displayReport() const;
};
}; // namespace VAL
#endif
| 0 | 0.66688 | 1 | 0.66688 | game-dev | MEDIA | 0.371404 | game-dev | 0.705104 | 1 | 0.705104 |
barncastle/AIO-Sandbox | 8,129 | Plugins/Beta_3694/Handlers/CharHandler.cs | using System;
using System.Linq;
using Common.Commands;
using Common.Constants;
using Common.Extensions;
using Common.Interfaces;
using Common.Interfaces.Handlers;
using Common.Structs;
namespace Beta_3694.Handlers
{
public class CharHandler : ICharHandler
{
public void HandleCharCreate(ref IPacketReader packet, ref IWorldManager manager)
{
string name = packet.ReadString();
Character cha = new Character()
{
Name = name.ToUpperFirst(),
Race = packet.ReadByte(),
Class = packet.ReadByte(),
Gender = packet.ReadByte(),
Skin = packet.ReadByte(),
Face = packet.ReadByte(),
HairStyle = packet.ReadByte(),
HairColor = packet.ReadByte(),
FacialHair = packet.ReadByte()
};
var result = manager.Account.Characters.Where(x => x.Build == Sandbox.Instance.Build);
PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_CHAR_CREATE], "SMSG_CHAR_CREATE");
if (result.Any(x => x.Name.Equals(cha.Name, StringComparison.CurrentCultureIgnoreCase)))
{
writer.WriteUInt8(0x2B); // Duplicate name
manager.Send(writer);
return;
}
cha.Guid = (ulong)(manager.Account.Characters.Count + 1);
cha.Location = new Location(-8949.95f, -132.493f, 83.5312f, 0, 0);
cha.RestedState = (byte)new Random().Next(1, 3);
cha.SetDefaultValues();
manager.Account.Characters.Add(cha);
manager.Account.Save();
// Success
writer.WriteUInt8(0x28);
manager.Send(writer);
}
public void HandleCharDelete(ref IPacketReader packet, ref IWorldManager manager)
{
ulong guid = packet.ReadUInt64();
var character = manager.Account.GetCharacter(guid, Sandbox.Instance.Build);
PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_CHAR_DELETE], "SMSG_CHAR_DELETE");
writer.WriteUInt8(0x2C);
manager.Send(writer);
if (character != null)
{
manager.Account.Characters.Remove(character);
manager.Account.Save();
}
}
public void HandleCharEnum(ref IPacketReader packet, ref IWorldManager manager)
{
var account = manager.Account;
var result = account.Characters.Where(x => x.Build == Sandbox.Instance.Build);
PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_CHAR_ENUM], "SMSG_CHAR_ENUM");
writer.WriteUInt8((byte)result.Count());
foreach (Character c in result)
{
writer.WriteUInt64(c.Guid);
writer.WriteString(c.Name);
writer.WriteUInt8(c.Race);
writer.WriteUInt8(c.Class);
writer.WriteUInt8(c.Gender);
writer.WriteUInt8(c.Skin);
writer.WriteUInt8(c.Face);
writer.WriteUInt8(c.HairStyle);
writer.WriteUInt8(c.HairColor);
writer.WriteUInt8(c.FacialHair);
writer.WriteUInt8((byte)c.Level);
writer.WriteUInt32(c.Zone);
writer.WriteUInt32(c.Location.Map);
writer.WriteFloat(c.Location.X);
writer.WriteFloat(c.Location.Y);
writer.WriteFloat(c.Location.Z);
writer.WriteUInt32(0);
writer.WriteUInt32(0);
writer.WriteUInt8(c.RestedState);
writer.WriteUInt32(0);
writer.WriteUInt32(0);
writer.WriteUInt32(0);
// Items
for (int j = 0; j < 0x14; j++)
{
writer.WriteUInt32(0); // DisplayId
writer.WriteUInt8(0); // InventoryType
}
}
manager.Send(writer);
}
public void HandleMessageChat(ref IPacketReader packet, ref IWorldManager manager)
{
var character = manager.Account.ActiveCharacter;
PacketWriter writer = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_MESSAGECHAT], "SMSG_MESSAGECHAT");
writer.WriteUInt8((byte)packet.ReadInt32()); // System Message
packet.ReadUInt32();
writer.WriteUInt32(0); // Language: General
writer.WriteUInt64(character.Guid);
string message = packet.ReadString();
writer.WriteString(message);
writer.WriteUInt8(0);
if (!CommandManager.InvokeHandler(message, manager))
manager.Send(writer);
}
public void HandleMovementStatus(ref IPacketReader packet, ref IWorldManager manager)
{
if (manager.Account.ActiveCharacter.IsTeleporting)
return;
long pos = packet.Position;
uint Flags = packet.ReadUInt32();
packet.ReadUInt32();
manager.Account.ActiveCharacter.Location.Update(packet, true);
}
public void HandleNameCache(ref IPacketReader packet, ref IWorldManager manager)
{
ulong guid = packet.ReadUInt64();
var character = manager.Account.GetCharacter(guid, Sandbox.Instance.Build);
PacketWriter nameCache = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_NAME_QUERY_RESPONSE], "SMSG_NAME_QUERY_RESPONSE");
nameCache.WriteUInt64(guid);
nameCache.WriteString(character.Name);
nameCache.WriteUInt32(character.Race);
nameCache.WriteUInt32(character.Gender);
nameCache.WriteUInt32(character.Class);
manager.Send(nameCache);
}
public void HandleStandState(ref IPacketReader packet, ref IWorldManager manager)
{
manager.Account.ActiveCharacter.StandState = (StandState)packet.ReadUInt32();
manager.Send(manager.Account.ActiveCharacter.BuildUpdate());
}
public void HandleTextEmote(ref IPacketReader packet, ref IWorldManager manager)
{
uint emote = packet.ReadUInt32();
ulong guid = packet.ReadUInt64();
uint emoteId = Emotes.Get((TextEmotes)emote);
Character character = (Character)manager.Account.ActiveCharacter;
PacketWriter pw = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_TEXT_EMOTE], "SMSG_TEXT_EMOTE");
pw.Write(character.Guid);
pw.Write(emote);
if (guid == character.Guid)
pw.WriteString(character.Name);
else
pw.WriteUInt8(0);
manager.Send(pw);
switch ((TextEmotes)emote)
{
case TextEmotes.EMOTE_SIT:
character.StandState = StandState.SITTING;
manager.Send(character.BuildUpdate());
return;
case TextEmotes.EMOTE_STAND:
character.StandState = StandState.STANDING;
manager.Send(character.BuildUpdate());
return;
case TextEmotes.EMOTE_SLEEP:
character.StandState = StandState.SLEEPING;
manager.Send(character.BuildUpdate());
return;
case TextEmotes.EMOTE_KNEEL:
character.StandState = StandState.KNEEL;
manager.Send(character.BuildUpdate());
return;
}
if (emoteId > 0)
{
pw = new PacketWriter(Sandbox.Instance.Opcodes[global::Opcodes.SMSG_EMOTE], "SMSG_EMOTE");
pw.WriteUInt32(emoteId);
pw.WriteUInt64(character.Guid);
manager.Send(pw);
}
}
}
}
| 0 | 0.850003 | 1 | 0.850003 | game-dev | MEDIA | 0.628507 | game-dev,networking | 0.862285 | 1 | 0.862285 |
The-Legion-Preservation-Project/LegionCore-7.3.5 | 41,451 | src/server/scripts/Legion/TheEmeraldNightmare/boss_dragons_of_nightmare.cpp | /*
To-Do: нужны еще снифы для фраз/варнингов. Не хватает парочки
*/
#include "the_emerald_nightmare.h"
#include "CreatureGroups.h"
enum Says
{
SAY_AGGRO = 0,
SAY_CALL = 1,
SAY_DEATH = 3,
};
enum Spells
{
SPELL_EMPTY_ENERGY = 205283, //224200, 203909, 204719?
SPELL_ENERGIZE_UP = 205284,
SPELL_REMOVE_MARK_TAERAR = 224627,
SPELL_REMOVE_MARK_LETHON = 224626,
SPELL_REMOVE_MARK_EMERISS = 224625,
SPELL_NIGHTMARE_BOND = 203966, //Share damage. 203969
SPELL_CORRUPTED_BREATH = 203028,
SPELL_TAIL_LASH = 204119,
SPELL_ENERGIZE_DRAGONS = 205281,
SPELL_SLUMBERING_NIGHTMARE = 203110,
//Ysondre - 102679
SPELL_MARK_OF_YSONDRE = 203083,
SPELL_ENERGIZE_YSONDRE = 205282,
SPELL_NIGHTMARE_BLAST = 203147,
SPELL_CALL_DEFILED_SPIRIT = 207573,
//Taerar - 102681
SPELL_MARK_OF_TAERAR = 203085,
SPELL_SHADES_OF_TAERAR = 204100,
SPELL_SEEPING_FOG = 205331,
SPELL_BELLOWING_ROAR_AURA = 205172, //Heroic+
SPELL_BELLOWING_ROAR = 204078,
//Lethon - 102682
SPELL_MARK_OF_LETHON = 203086,
SPELL_SIPHON_SPIRIT = 203888,
SPELL_SIPHON_SPIRIT_SUM = 203837,
SPELL_DARK_OFFERING_LETHON = 203896,
SPELL_DARK_OFFERING_YSONDRE = 203897,
SPELL_GLOOM_AURA = 206758,
SPELL_SHADOW_BURST = 204030, //Heroic+
//Emeriss - 102683
SPELL_MARK_OF_EMERISS = 203084,
SPELL_NIGHTMARE_ENERGY = 224200,
SPELL_GROUNDED = 204719,
SPELL_VOLATILE_INFECTION = 203787,
SPELL_ESSENCE_OF_CORRUPTION = 205298,
//Nightmare Bloom - 102804
SPELL_NIGHTMARE_BLOOM_VISUAL = 203672,
SPELL_NIGHTMARE_BLOOM_DUMMY = 205945,
SPELL_NIGHTMARE_BLOOM_DUMMY_2 = 207681,
SPELL_NIGHTMARE_BLOOM_DUMMY_3 = 220938,
SPELL_NIGHTMARE_BLOOM_DUMMY_4 = 211497,
SPELL_NIGHTMARE_BLOOM_AT = 203687,
SPELL_NIGHTMARE_BLOOM_PERIODIC = 205278,
//Defiled Druid Spirit - 103080
SPELL_DEFILED_SPIRIT_ROOT = 203768,
SPELL_DEFILED_ERUPTION = 203771,
//Essence of Corruption - 103691
SPELL_CORRUPTION = 205300,
//Shade of Taerar - 103145
SPELL_NIGHTMARE_VISAGE = 204084,
SPELL_CORRUPTED_BREATH_2 = 204767,
SPELL_TAIL_LASH_2 = 204768,
//Dread Horror - 103044
SPELL_WASTING_DREAD_AT = 204729, //Heroic
SPELL_UNRELENTING = 221419, //Mythic. Нужна инфа с офа, как часто использует эту способность. Пока что раз в 10 секунд.
//Corrupted Mushroom
SPELL_CORRUPTED_BURST_4 = 203817,
SPELL_CORRUPTED_BURST_7 = 203827,
SPELL_CORRUPTED_BURST_10 = 203828,
};
enum eEvents
{
EVENT_CORRUPTED_BREATH = 1,
//Ysondre
EVENT_SWITCH_DRAGONS = 2,
EVENT_NIGHTMARE_BLAST = 3,
EVENT_CALL_DEFILED_SPIRIT = 4,
//Taerar
EVENT_SHADES_OF_TAERAR = 5,
EVENT_SEEPING_FOG = 6,
//Emeriss
EVENT_VOLATILE_INFECTION = 7,
EVENT_ESSENCE_OF_CORRUPTION = 8,
//Lethon
EVENT_SIPHON_SPIRIT = 9,
EVENT_SHADOW_BURST = 10, //Heroic+
//Mythic
EVENT_TAIL_LASH = 11,
};
Position const dragonPos[5] =
{
{617.51f, -12807.0f, 4.84f, 3.39f},
{674.78f, -12875.5f, 42.21f, 2.91f},
{623.48f, -12845.71f, 4.13f, 2.47f},
//Mythic
{681.84f, -12869.25f, 43.62f, 2.74f},
{662.45f, -12893.78f, 43.62f, 2.31f}
};
//102679
struct boss_dragon_ysondre : public BossAI
{
boss_dragon_ysondre(Creature* creature) : BossAI(creature, DATA_DRAGON_NIGHTMARE)
{
group_member = sFormationMgr->CreateCustomFormation(me);
helpersList = {NPC_TAERAR, NPC_LETHON, NPC_EMERISS};
Trinity::Containers::RandomResizeList(helpersList, IsMythicRaid() ? 3 : 2);
}
std::vector<uint32> helpersList;
FormationInfo* group_member;
uint8 eventPhaseHP;
bool introDone = false;
void Reset() override
{
_Reset();
DoCast(me, SPELL_EMPTY_ENERGY, true);
eventPhaseHP = 71;
me->GetMotionMaster()->MoveIdle();
me->NearTeleportTo(me->GetHomePosition());
if (auto dragon = me->SummonCreature(helpersList[0], dragonPos[0]))
if (CreatureGroup* f = me->GetFormation())
f->AddMember(dragon, group_member);
if (IsMythicRaid())
{
for (uint8 i = 0; i < 2; ++i)
if (auto dragon = me->SummonCreature(helpersList[1 + i], dragonPos[3 + i]))
{
dragon->SetReactState(REACT_PASSIVE);
dragon->AI()->SetFlyMode(true);
dragon->SetVisible(false);
}
}
else
{
if (auto dragon = me->SummonCreature(helpersList[1], dragonPos[1]))
{
dragon->SetReactState(REACT_PASSIVE);
dragon->AI()->SetFlyMode(true);
dragon->SetVisible(false);
}
}
DespawnTrash();
}
void EnterCombat(Unit* who) override
{
_EnterCombat();
Talk(SAY_AGGRO);
DoCast(me, SPELL_ENERGIZE_YSONDRE, true);
DoCast(me, SPELL_MARK_OF_YSONDRE, true);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 16000);
events.RescheduleEvent(EVENT_SWITCH_DRAGONS, 1000);
events.RescheduleEvent(EVENT_NIGHTMARE_BLAST, 40000);
if (IsMythicRaid())
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
DoActionSummon(helpersList[0], ACTION_3);
}
void MoveInLineOfSight(Unit* who) override
{
if (!who->IsPlayer())
return;
if (!introDone && me->IsWithinDistInMap(who, 150.0f))
{
introDone = true;
who->CreateConversation(3608);
}
BossAI::MoveInLineOfSight(who);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
DespawnTrash();
Talk(SAY_DEATH);
}
void DespawnTrash()
{
std::list<Creature*> creList;
GetCreatureListWithEntryInGrid(creList, me, NPC_NIGHTMARE_BLOOM, 120.0f);
GetCreatureListWithEntryInGrid(creList, me, NPC_ESSENCE_OF_CORRUPTION, 120.0f);
GetCreatureListWithEntryInGrid(creList, me, NPC_SHADE_OF_TAERAR, 120.0f);
GetCreatureListWithEntryInGrid(creList, me, NPC_SEEPING_FOG, 120.0f);
GetCreatureListWithEntryInGrid(creList, me, NPC_SPIRIT_SHADE, 120.0f);
GetCreatureListWithEntryInGrid(creList, me, NPC_DREAD_HORROR, 120.0f);
for (auto const& trash : creList)
{
if (trash && trash->IsInWorld())
trash->DespawnOrUnsummon();
}
}
void DoAction(int32 const action, Creature* caller) override
{
switch (action)
{
case ACTION_1:
if (auto f = me->GetFormation())
f->AddMember(caller, group_member);
break;
case ACTION_2:
if (auto f = me->GetFormation())
f->RemoveMember(caller);
break;
case ACTION_4: //Special Attack
events.RescheduleEvent(EVENT_CALL_DEFILED_SPIRIT, 100);
break;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (CheckHomeDistToEvade(diff, 100.0f, 576.33f, -12813.32f, 6.17f))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CORRUPTED_BREATH:
DoCastVictim(SPELL_CORRUPTED_BREATH);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 32000);
break;
case EVENT_SWITCH_DRAGONS:
if (me->HealthBelowPct(eventPhaseHP))
{
if (eventPhaseHP > 41)
{
eventPhaseHP = 41;
EntryCheckPredicate pred0(helpersList[0]);
summons.DoAction(ACTION_1, pred0);
EntryCheckPredicate pred1(helpersList[1]);
summons.DoAction(ACTION_2, pred1);
}
else
{
eventPhaseHP = 0;
if (IsMythicRaid())
{
EntryCheckPredicate pred0(helpersList[1]);
summons.DoAction(ACTION_1, pred0);
EntryCheckPredicate pred1(helpersList[2]);
summons.DoAction(ACTION_2, pred1);
}
else
{
EntryCheckPredicate pred0(helpersList[0]);
summons.DoAction(ACTION_2, pred0);
EntryCheckPredicate pred1(helpersList[1]);
summons.DoAction(ACTION_1, pred1);
}
break;
}
}
events.RescheduleEvent(EVENT_SWITCH_DRAGONS, 1000);
break;
case EVENT_NIGHTMARE_BLAST:
DoCast(SPELL_NIGHTMARE_BLAST);
events.RescheduleEvent(EVENT_NIGHTMARE_BLAST, 15000);
break;
case EVENT_CALL_DEFILED_SPIRIT:
Talk(SAY_CALL);
DoCast(SPELL_CALL_DEFILED_SPIRIT);
break;
case EVENT_TAIL_LASH:
DoCast(SPELL_TAIL_LASH);
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
break;
}
}
DoMeleeAttackIfReady();
}
};
//102681
struct boss_dragon_taerar : public ScriptedAI
{
boss_dragon_taerar(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
me->SetSpeed(MOVE_FLIGHT, 2.0f);
}
InstanceScript* instance;
EventMap events;
void Reset() override
{
me->SetMaxPower(POWER_ENERGY, 100);
DoCast(me, SPELL_EMPTY_ENERGY, true);
}
void EnterCombat(Unit* who) override
{
DoCast(me, SPELL_ENERGIZE_UP, true);
Talk(SAY_AGGRO);
DoZoneInCombat(me, 150.0f);
}
void DefaultEvents()
{
instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me);
me->RemoveAurasDueToSpell(SPELL_BELLOWING_ROAR_AURA);
DoCast(me, SPELL_MARK_OF_TAERAR, true);
DoCast(me, SPELL_ENERGIZE_DRAGONS, true);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 16000);
events.RescheduleEvent(EVENT_SEEPING_FOG, 26000);
if (IsMythicRaid())
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
}
void JustDied(Unit* /*killer*/) override {}
void DoAction(int32 const action) override
{
switch (action)
{
case ACTION_1:
if (auto owner = me->GetAnyOwner())
owner->GetAI()->DoAction(ACTION_2, me); //Leave group
events.Reset();
me->StopAttack();
SetFlyMode(true);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->RemoveAurasDueToSpell(SPELL_MARK_OF_TAERAR);
me->RemoveAurasDueToSpell(SPELL_ENERGIZE_DRAGONS);
me->GetMotionMaster()->MovePoint(1, dragonPos[1].GetPosition(), false);
instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me);
break;
case ACTION_2:
me->SetVisible(true);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->GetMotionMaster()->MovePoint(2, dragonPos[2].GetPosition(), false);
//No break!
case ACTION_3:
DefaultEvents();
break;
case ACTION_4: //Special Attack
events.RescheduleEvent(EVENT_SHADES_OF_TAERAR, 100);
break;
}
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetFacingTo(2.47f);
if (IsHeroicPlusRaid())
DoCast(me, SPELL_BELLOWING_ROAR_AURA, true);
}
else if (id == 2)
{
SetFlyMode(false);
me->SetReactState(REACT_AGGRESSIVE);
DoZoneInCombat(me, 150.0f);
if (auto owner = me->GetAnyOwner())
{
me->SetHealth(owner->GetHealth());
owner->GetAI()->DoAction(ACTION_1, me); //Invite group
}
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (me->GetReactState() == REACT_AGGRESSIVE && CheckHomeDistToEvade(diff, 100.0f, 576.33f, -12813.32f, 6.17f))
{
if (auto owner = me->GetAnyOwner())
if (auto summoner = owner->ToCreature())
if (summoner->isInCombat())
summoner->AI()->EnterEvadeMode();
return;
}
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CORRUPTED_BREATH:
DoCastVictim(SPELL_CORRUPTED_BREATH);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 32000);
break;
case EVENT_SHADES_OF_TAERAR:
DoCast(SPELL_SHADES_OF_TAERAR);
Talk(1);
break;
case EVENT_SEEPING_FOG:
DoCast(me, SPELL_SEEPING_FOG, true);
events.RescheduleEvent(EVENT_SEEPING_FOG, 16000);
break;
case EVENT_TAIL_LASH:
DoCast(SPELL_TAIL_LASH);
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
break;
}
}
DoMeleeAttackIfReady();
}
};
//102682
struct boss_dragon_lethon : public ScriptedAI
{
boss_dragon_lethon(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
me->SetSpeed(MOVE_FLIGHT, 2.0f);
}
InstanceScript* instance;
EventMap events;
void Reset() override
{
me->SetMaxPower(POWER_ENERGY, 100);
DoCast(me, SPELL_EMPTY_ENERGY, true);
}
void EnterCombat(Unit* who) override
{
DoCast(me, SPELL_ENERGIZE_UP, true);
Talk(SAY_AGGRO);
DoZoneInCombat(me, 150.0f);
}
void DefaultEvents()
{
instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me);
DoCast(me, SPELL_MARK_OF_LETHON, true);
DoCast(me, SPELL_ENERGIZE_DRAGONS, true);
DoCast(me, SPELL_GLOOM_AURA, true);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 16000);
events.CancelEvent(EVENT_SHADOW_BURST);
if (IsMythicRaid())
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
}
void JustDied(Unit* /*killer*/) override {}
void DoAction(int32 const action) override
{
switch (action)
{
case ACTION_1:
if (auto owner = me->GetAnyOwner())
if (auto summoner = owner->ToCreature())
summoner->AI()->DoAction(ACTION_2, me); //Leave group
events.Reset();
me->StopAttack();
SetFlyMode(true);
me->RemoveAurasDueToSpell(SPELL_MARK_OF_LETHON);
me->RemoveAurasDueToSpell(SPELL_ENERGIZE_DRAGONS);
me->RemoveAurasDueToSpell(SPELL_GLOOM_AURA);
me->GetMotionMaster()->MovePoint(1, dragonPos[1].GetPosition(), false);
instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me);
break;
case ACTION_2:
me->SetVisible(true);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->GetMotionMaster()->MovePoint(2, dragonPos[2].GetPosition(), false);
//No break!
case ACTION_3:
DefaultEvents();
break;
case ACTION_4: //Special Attack
events.RescheduleEvent(EVENT_SIPHON_SPIRIT, 100);
break;
}
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetFacingTo(2.47f);
if (IsHeroicPlusRaid())
events.RescheduleEvent(EVENT_SHADOW_BURST, 15000);
}
else if (id == 2)
{
SetFlyMode(false);
me->SetReactState(REACT_AGGRESSIVE);
DoZoneInCombat(me, 150.0f);
if (auto owner = me->GetAnyOwner())
{
me->SetHealth(owner->GetHealth());
owner->GetAI()->DoAction(ACTION_1, me); //Invite group
}
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->GetReactState() == REACT_AGGRESSIVE && CheckHomeDistToEvade(diff, 100.0f, 576.33f, -12813.32f, 6.17f))
{
if (auto owner = me->GetAnyOwner()->ToCreature())
if (owner && owner->isInCombat())
owner->AI()->EnterEvadeMode();
return;
}
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CORRUPTED_BREATH:
DoCastVictim(SPELL_CORRUPTED_BREATH);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 32000);
break;
case EVENT_SIPHON_SPIRIT:
DoCast(SPELL_SIPHON_SPIRIT);
Talk(1);
Talk(2);
break;
case EVENT_SHADOW_BURST:
DoCast(me, SPELL_SHADOW_BURST, true);
events.RescheduleEvent(EVENT_SHADOW_BURST, 15000);
break;
case EVENT_TAIL_LASH:
DoCast(SPELL_TAIL_LASH);
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
break;
}
}
DoMeleeAttackIfReady();
}
};
//102683
struct boss_dragon_emeriss : public ScriptedAI
{
boss_dragon_emeriss(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
me->SetSpeed(MOVE_FLIGHT, 2.0f);
}
InstanceScript* instance;
EventMap events;
void Reset() override
{
me->SetMaxPower(POWER_ENERGY, 100);
DoCast(me, SPELL_EMPTY_ENERGY, true);
DoCast(me, SPELL_NIGHTMARE_ENERGY, true);
}
void EnterCombat(Unit* who) override
{
DoCast(me, SPELL_ENERGIZE_UP, true);
Talk(SAY_AGGRO);
DoZoneInCombat(me, 150.0f);
}
void DefaultEvents()
{
instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me);
DoCast(me, SPELL_MARK_OF_EMERISS, true);
DoCast(me, SPELL_ENERGIZE_DRAGONS, true);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 16000);
events.RescheduleEvent(EVENT_ESSENCE_OF_CORRUPTION, 30000);
if (IsMythicRaid())
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
}
void JustDied(Unit* /*killer*/) override {}
void DoAction(int32 const action) override
{
switch (action)
{
case ACTION_1:
if (auto owner = me->GetAnyOwner())
owner->GetAI()->DoAction(ACTION_2, me); //Leave group
events.Reset();
me->StopAttack();
SetFlyMode(true);
me->RemoveAurasDueToSpell(SPELL_MARK_OF_EMERISS);
me->RemoveAurasDueToSpell(SPELL_ENERGIZE_DRAGONS);
me->GetMotionMaster()->MovePoint(1, dragonPos[1].GetPosition(), false);
instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me);
break;
case ACTION_2:
me->SetVisible(true);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->GetMotionMaster()->MovePoint(2, dragonPos[2].GetPosition(), false);
//No break!
case ACTION_3:
DefaultEvents();
break;
case ACTION_4: //Special Attack
events.RescheduleEvent(EVENT_VOLATILE_INFECTION, 100);
break;
}
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_ATTACKABLE_1);
me->SetFacingTo(2.47f);
}
else if (id == 2)
{
SetFlyMode(false);
me->SetReactState(REACT_AGGRESSIVE);
DoZoneInCombat(me, 150.0f);
if (auto owner = me->GetAnyOwner())
{
me->SetHealth(owner->GetHealth());
owner->GetAI()->DoAction(ACTION_1, me); //Invite group
}
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->GetReactState() == REACT_AGGRESSIVE && CheckHomeDistToEvade(diff, 100.0f, 576.33f, -12813.32f, 6.17f))
{
if (auto owner = me->GetAnyOwner())
if (auto summoner = owner->ToCreature())
if (summoner->isInCombat())
summoner->AI()->EnterEvadeMode();
return;
}
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CORRUPTED_BREATH:
DoCastVictim(SPELL_CORRUPTED_BREATH);
events.RescheduleEvent(EVENT_CORRUPTED_BREATH, 32000);
break;
case EVENT_VOLATILE_INFECTION:
DoCast(me, SPELL_VOLATILE_INFECTION, true);
break;
case EVENT_ESSENCE_OF_CORRUPTION:
DoCast(me, SPELL_ESSENCE_OF_CORRUPTION, true);
events.RescheduleEvent(EVENT_ESSENCE_OF_CORRUPTION, 30000);
break;
case EVENT_TAIL_LASH:
DoCast(SPELL_TAIL_LASH);
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
break;
}
}
DoMeleeAttackIfReady();
}
};
//102804
struct npc_ysondre_nightmare_bloom : public ScriptedAI
{
npc_ysondre_nightmare_bloom(Creature* creature) : ScriptedAI(creature)
{
me->SetReactState(REACT_PASSIVE);
}
uint32 despawnTimer = 0;
void Reset() override {}
void IsSummonedBy(Unit* summoner) override
{
DoCast(me, SPELL_NIGHTMARE_BLOOM_VISUAL, true);
DoCast(me, SPELL_NIGHTMARE_BLOOM_DUMMY, true);
DoCast(me, SPELL_NIGHTMARE_BLOOM_AT, true);
DoCast(me, SPELL_NIGHTMARE_BLOOM_PERIODIC, true);
uint8 playerCount = me->GetMap()->GetPlayersCountExceptGMs();
if (IsMythicRaid())
despawnTimer = 30000;
else if (playerCount < 20)
despawnTimer = 20000;
else if (playerCount >= 20 && playerCount <= 30)
despawnTimer = 40000;
}
void UpdateAI(uint32 diff) override
{
if (despawnTimer)
{
if (despawnTimer <= diff)
{
despawnTimer = 0;
me->DespawnOrUnsummon(100);
}
else
despawnTimer -= diff;
}
}
};
//103080
struct npc_ysondre_defiled_druid_spirit : public ScriptedAI
{
npc_ysondre_defiled_druid_spirit(Creature* creature) : ScriptedAI(creature)
{
me->SetReactState(REACT_PASSIVE);
}
uint16 explodeTimer = 0;
void Reset() override {}
void IsSummonedBy(Unit* summoner) override
{
explodeTimer = 500;
DoCast(me, SPELL_DEFILED_SPIRIT_ROOT, true);
}
void UpdateAI(uint32 diff) override
{
if (explodeTimer)
{
if (explodeTimer <= diff)
{
explodeTimer = 0;
me->DespawnOrUnsummon(8000);
DoCast(SPELL_DEFILED_ERUPTION);
}
else
explodeTimer -= diff;
}
}
};
//103145
struct npc_ysondre_shade_of_taerar : public ScriptedAI
{
npc_ysondre_shade_of_taerar(Creature* creature) : ScriptedAI(creature) {}
EventMap events;
void Reset() override {}
void IsSummonedBy(Unit* summoner) override
{
DoCast(me, SPELL_NIGHTMARE_VISAGE, true); //Scale
DoZoneInCombat(me, 150.0f);
events.RescheduleEvent(EVENT_1, 5000);
if (IsMythicRaid())
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_1:
DoCastVictim(SPELL_CORRUPTED_BREATH_2);
events.RescheduleEvent(EVENT_1, 30000);
break;
case EVENT_TAIL_LASH:
DoCast(SPELL_TAIL_LASH_2);
events.RescheduleEvent(EVENT_TAIL_LASH, 5000);
break;
}
}
DoMeleeAttackIfReady();
}
};
//103100
struct npc_ysondre_spirit_shade : public ScriptedAI
{
npc_ysondre_spirit_shade(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
me->SetSpeed(MOVE_RUN, 0.5f);
me->SetReactState(REACT_PASSIVE);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_FEAR, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_ROOT, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_HORROR, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_SAPPED, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_CHARM, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_DISORIENTED, true);
me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CONFUSE, true);
}
InstanceScript* instance;
bool despawn = false;
uint16 moveTimer = 0;
uint16 checkBossStateTimer = 0;
void Reset() override {}
void IsSummonedBy(Unit* summoner) override
{
moveTimer = 500;
checkBossStateTimer = 1000;
summoner->CastSpell(me, 203840, true); //Clone Player
DoCast(me, 203950, true); //Mod Scale
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
if (auto lethon = instance->instance->GetCreature(instance->GetGuidData(NPC_LETHON)))
{
if (me->GetDistance(lethon) < 5.0f)
{
if (!despawn)
{
despawn = true;
moveTimer = 0;
me->CastSpell(me, SPELL_DARK_OFFERING_LETHON, true);
me->CastSpell(me, SPELL_DARK_OFFERING_YSONDRE, true);
me->GetMotionMaster()->Clear();
me->DespawnOrUnsummon(1000);
}
}
}
}
}
void UpdateAI(uint32 diff) override
{
if (checkBossStateTimer)
{
if (checkBossStateTimer <= diff)
{
checkBossStateTimer = 1000;
if (instance->GetBossState(DATA_DRAGON_NIGHTMARE) != IN_PROGRESS)
{
me->DespawnOrUnsummon();
return;
}
if (auto lethon = instance->instance->GetCreature(instance->GetGuidData(NPC_LETHON)))
{
if (lethon->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_1))
{
me->DespawnOrUnsummon();
return;
}
}
}
else
checkBossStateTimer -= diff;
}
if (moveTimer)
{
if (moveTimer <= diff)
{
moveTimer = 2000;
if (!me->HasUnitState(UNIT_STATE_STUNNED))
{
if (auto lethon = instance->instance->GetCreature(instance->GetGuidData(NPC_LETHON)))
me->GetMotionMaster()->MovePoint(1, lethon->GetPosition());
}
}
else
moveTimer -= diff;
}
}
};
//103044
struct npc_ysondre_dread_horror : public ScriptedAI
{
npc_ysondre_dread_horror(Creature* creature) : ScriptedAI(creature) {}
uint16 unrelentingTimer = 0;
void Reset() override {}
void IsSummonedBy(Unit* summoner) override
{
if (IsHeroicPlusRaid())
{
DoCast(me, SPELL_WASTING_DREAD_AT, true);
if (IsMythicRaid())
unrelentingTimer = 10000;
}
DoZoneInCombat(me, 100.0f);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (unrelentingTimer)
{
if (unrelentingTimer <= diff)
{
unrelentingTimer = 10000;
DoCast(me, SPELL_UNRELENTING, true);
}
else
unrelentingTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
//103095, 103096, 103097
struct npc_ysondre_corrupted_mushroom : public ScriptedAI
{
npc_ysondre_corrupted_mushroom(Creature* creature) : ScriptedAI(creature)
{
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC);
}
EventMap events;
void Reset() override {}
void IsSummonedBy(Unit* summoner) override
{
switch (me->GetEntry())
{
case NPC_CORRUPTED_MUSHROOM_SMALL:
events.RescheduleEvent(EVENT_1, 500);
break;
case NPC_CORRUPTED_MUSHROOM_MEDIUM:
events.RescheduleEvent(EVENT_2, 500);
break;
case NPC_CORRUPTED_MUSHROOM_BIG:
events.RescheduleEvent(EVENT_3, 500);
break;
}
events.RescheduleEvent(EVENT_4, 5000);
}
void UpdateAI(uint32 diff) override
{
events.Update(diff);
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_1:
DoCast(me, SPELL_CORRUPTED_BURST_4, false);
break;
case EVENT_2:
DoCast(me, SPELL_CORRUPTED_BURST_7, false);
break;
case EVENT_3:
DoCast(me, SPELL_CORRUPTED_BURST_10, false);
break;
case EVENT_4:
me->DespawnOrUnsummon(100);
break;
}
}
}
};
//111852
struct npc_en_rothos : public ScriptedAI
{
npc_en_rothos(Creature* creature) : ScriptedAI(creature)
{
SetFlyMode(true);
}
EventMap events;
void DespawnTrash()
{
std::list<Creature*> creatureList;
me->GetCreatureListWithEntryInGrid(creatureList, 113214, 100.0f);
for (auto trash : creatureList)
trash->DespawnOrUnsummon();
}
void Reset() override
{
events.Reset();
}
void JustDied(Unit* /*killer*/) override
{
DespawnTrash();
}
void EnterEvadeMode() override
{
SetFlyMode(true);
ScriptedAI::EnterEvadeMode();
me->NearTeleportTo(me->GetHomePosition());
DespawnTrash();
}
void EnterCombat(Unit* /*who*/) override
{
SetFlyMode(false);
me->StopAttack(true);
me->SetReactState(REACT_AGGRESSIVE, 2000);
events.RescheduleEvent(EVENT_1, 8000);
events.RescheduleEvent(EVENT_2, 12000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_1:
DoCastVictim(223697);
events.RescheduleEvent(EVENT_1, 15000);
break;
case EVENT_2:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, 223735);
events.RescheduleEvent(EVENT_2, 12000);
break;
}
}
DoMeleeAttackIfReady();
}
};
//205281, 205282
class spell_ysondre_periodic_energize : public AuraScript
{
PrepareAuraScript(spell_ysondre_periodic_energize);
bool fullPower = false;
void OnTick(AuraEffect const* aurEff)
{
auto caster = GetCaster()->ToCreature();
if (!caster || !caster->isInCombat())
return;
uint8 powerCount = caster->GetPower(POWER_ENERGY);
if (powerCount < 100)
{
caster->SetPower(POWER_ENERGY, powerCount + 2);
if (fullPower)
fullPower = false;
}
else
{
if (!fullPower)
{
fullPower = true;
if (GetCaster()->GetEntry() == NPC_YSONDRE)
caster->AI()->DoAction(ACTION_4, nullptr);
else
caster->AI()->DoAction(ACTION_4);
}
}
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_ysondre_periodic_energize::OnTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
//203102,203121,203124,203125
class spell_ysondre_marks : public AuraScript
{
PrepareAuraScript(spell_ysondre_marks);
void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/)
{
if (!GetTarget())
return;
if (auto aura = aurEff->GetBase())
if (aura->GetStackAmount() == 10)
GetTarget()->CastSpell(GetTarget(), SPELL_SLUMBERING_NIGHTMARE, true);
}
void Register() override
{
OnEffectApply += AuraEffectApplyFn(spell_ysondre_marks::OnApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAPPLY);
}
};
//203110
class spell_ysondre_slumbering_nightmare : public AuraScript
{
PrepareAuraScript(spell_ysondre_slumbering_nightmare);
void CalculateMaxDuration(int32& duration)
{
if (!GetCaster())
return;
if (GetCaster()->GetMap()->GetDifficultyID() == DIFFICULTY_LFR_RAID)
duration = 10000;
else
duration = 30000;
}
void Register() override
{
DoCalcMaxDuration += AuraCalcMaxDurationFn(spell_ysondre_slumbering_nightmare::CalculateMaxDuration);
}
};
//203686
class spell_ysondre_nightmare_bloom : public SpellScript
{
PrepareSpellScript(spell_ysondre_nightmare_bloom);
void FilterTargets(std::list<WorldObject*>& targets)
{
if (GetCaster() && targets.empty())
if (auto owner = GetCaster()->GetAnyOwner())
GetCaster()->CastSpell(GetCaster(), 203667, true, 0, 0, owner->GetGUID());
}
void HandleOnHit()
{
if (GetCaster() && GetHitUnit())
GetCaster()->CastSpell(GetHitUnit(), 203690, true);
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ysondre_nightmare_bloom::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnHit += SpellHitFn(spell_ysondre_nightmare_bloom::HandleOnHit);
}
};
//204044
class spell_ysondre_shadow_burst_filter : public SpellScript
{
PrepareSpellScript(spell_ysondre_shadow_burst_filter);
void FilterTargets(std::list<WorldObject*>& targets)
{
if (GetCaster())
targets.sort(Trinity::UnitSortDistance(true, GetCaster()));
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ysondre_shadow_burst_filter::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ysondre_shadow_burst_filter::FilterTargets, EFFECT_1, TARGET_UNIT_SRC_AREA_ALLY);
}
};
//204040
class spell_ysondre_shadow_burst : public AuraScript
{
PrepareAuraScript(spell_ysondre_shadow_burst);
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (!GetCaster() || !GetTarget() || GetTargetApplication()->GetRemoveMode() != AURA_REMOVE_BY_EXPIRE)
return;
GetTarget()->CastSpell(GetTarget(), 204044, true, 0, 0, GetCaster()->GetGUID());
}
void Register() override
{
OnEffectRemove += AuraEffectRemoveFn(spell_ysondre_shadow_burst::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
//205172
class spell_ysondre_bellowing_roar : public AuraScript
{
PrepareAuraScript(spell_ysondre_bellowing_roar)
void OnPeriodic(AuraEffect const* aurEff)
{
if (!GetCaster())
return;
//GetCaster()->AI()->Talk();
GetCaster()->CastSpell(GetCaster(), SPELL_BELLOWING_ROAR);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_ysondre_bellowing_roar::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
//203888
class spell_ysondre_siphon_spirit_filter : public SpellScript
{
PrepareSpellScript(spell_ysondre_siphon_spirit_filter);
void FilterTargets(std::list<WorldObject*>& targets)
{
if (!GetCaster())
return;
targets.sort(Trinity::UnitSortDistance(false, GetCaster()));
if (GetCaster()->GetMap()->IsMythicRaid())
{
if (targets.size() > 6)
targets.resize(6);
}
else
{
uint32 playerCount = GetCaster()->GetMap()->GetPlayersCountExceptGMs() / 5 + 1;
if (targets.size() > playerCount)
targets.resize(playerCount);
}
for (auto object : targets)
{
if (auto target = object->ToUnit())
target->CastSpell(target, SPELL_SIPHON_SPIRIT_SUM, true);
}
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ysondre_siphon_spirit_filter::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
}
};
void AddSC_boss_dragons_of_nightmare()
{
RegisterCreatureAI(boss_dragon_ysondre);
RegisterCreatureAI(boss_dragon_taerar);
RegisterCreatureAI(boss_dragon_lethon);
RegisterCreatureAI(boss_dragon_emeriss);
RegisterCreatureAI(npc_ysondre_nightmare_bloom);
RegisterCreatureAI(npc_ysondre_defiled_druid_spirit);
RegisterCreatureAI(npc_ysondre_shade_of_taerar);
RegisterCreatureAI(npc_ysondre_spirit_shade);
RegisterCreatureAI(npc_ysondre_dread_horror);
RegisterCreatureAI(npc_ysondre_corrupted_mushroom);
RegisterCreatureAI(npc_en_rothos);
RegisterSpellScript(spell_ysondre_shadow_burst_filter);
RegisterAuraScript(spell_ysondre_shadow_burst);
RegisterAuraScript(spell_ysondre_periodic_energize);
RegisterAuraScript(spell_ysondre_marks);
RegisterAuraScript(spell_ysondre_slumbering_nightmare);
RegisterSpellScript(spell_ysondre_nightmare_bloom);
RegisterAuraScript(spell_ysondre_bellowing_roar);
RegisterSpellScript(spell_ysondre_siphon_spirit_filter);
}
| 0 | 0.991141 | 1 | 0.991141 | game-dev | MEDIA | 0.965546 | game-dev | 0.981608 | 1 | 0.981608 |
SourceEngine-CommunityEdition/source | 25,298 | public/jigglebones.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "tier1/convar.h"
#include "jigglebones.h"
#ifdef CLIENT_DLL
#include "engine/ivdebugoverlay.h"
#include "cdll_client_int.h"
#endif // CLIENT_DLL
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef CLIENT_DLL
//-----------------------------------------------------------------------------
ConVar cl_jiggle_bone_debug( "cl_jiggle_bone_debug", "0", FCVAR_CHEAT, "Display physics-based 'jiggle bone' debugging information" );
ConVar cl_jiggle_bone_debug_yaw_constraints( "cl_jiggle_bone_debug_yaw_constraints", "0", FCVAR_CHEAT, "Display physics-based 'jiggle bone' debugging information" );
ConVar cl_jiggle_bone_debug_pitch_constraints( "cl_jiggle_bone_debug_pitch_constraints", "0", FCVAR_CHEAT, "Display physics-based 'jiggle bone' debugging information" );
#endif // CLIENT_DLL
ConVar cl_jiggle_bone_framerate_cutoff( "cl_jiggle_bone_framerate_cutoff", "20", 0, "Skip jiggle bone simulation if framerate drops below this value (frames/second)" );
//-----------------------------------------------------------------------------
JiggleData * CJiggleBones::GetJiggleData( int bone, float currenttime, const Vector &initBasePos, const Vector &initTipPos )
{
FOR_EACH_LL( m_jiggleBoneState, it )
{
if ( m_jiggleBoneState[it].bone == bone )
{
return &m_jiggleBoneState[it];
}
}
JiggleData data;
data.Init( bone, currenttime, initBasePos, initTipPos );
// Start out using jiggle bones for at least 16 frames.
data.useGoalMatrixCount = 0;
data.useJiggleBoneCount = 16;
int idx = m_jiggleBoneState.AddToHead( data );
if ( idx == m_jiggleBoneState.InvalidIndex() )
return NULL;
return &m_jiggleBoneState[idx];
}
//-----------------------------------------------------------------------------
/**
* Do spring physics calculations and update "jiggle bone" matrix
* (Michael Booth, Turtle Rock Studios)
*/
void CJiggleBones::BuildJiggleTransformations( int boneIndex, float currenttime, const mstudiojigglebone_t *jiggleInfo, const matrix3x4_t &goalMX, matrix3x4_t &boneMX )
{
Vector goalBasePosition;
MatrixPosition( goalMX, goalBasePosition );
Vector goalForward, goalUp, goalLeft;
MatrixGetColumn( goalMX, 0, goalLeft );
MatrixGetColumn( goalMX, 1, goalUp );
MatrixGetColumn( goalMX, 2, goalForward );
// compute goal tip position
Vector goalTip = goalBasePosition + jiggleInfo->length * goalForward;
JiggleData *data = GetJiggleData( boneIndex, currenttime, goalBasePosition, goalTip );
if ( !data )
{
return;
}
// if frames have been skipped since our last update, we were likely
// disabled and re-enabled, so re-init
#if defined(CLIENT_DLL) || defined(GAME_DLL)
float timeTolerance = 1.2f * gpGlobals->frametime;
#else
float timeTolerance = 0.5f;
#endif
if ( currenttime - data->lastUpdate > timeTolerance )
{
data->Init( boneIndex, currenttime, goalBasePosition, goalTip );
}
if ( data->lastLeft.IsZero() )
{
data->lastLeft = goalLeft;
}
// limit maximum deltaT to avoid simulation blowups
// if framerate is too low, skip jigglebones altogether, since movement will be too
// large between frames to simulate with a simple Euler integration
float deltaT = currenttime - data->lastUpdate;
const float thousandHZ = 0.001f;
bool bMaxDeltaT = deltaT < thousandHZ;
bool bUseGoalMatrix = cl_jiggle_bone_framerate_cutoff.GetFloat() <= 0.0f || deltaT > ( 1.0f / cl_jiggle_bone_framerate_cutoff.GetFloat() );
if ( bUseGoalMatrix )
{
// We hit the jiggle bone framerate cutoff. Reset the useGoalMatrixCount so we
// use the goal matrix at least 32 frames and don't flash back and forth.
data->useGoalMatrixCount = 32;
}
else if ( data->useGoalMatrixCount > 0 )
{
// Below the cutoff, but still need to use the goal matrix a few more times.
bUseGoalMatrix = true;
data->useGoalMatrixCount--;
}
else
{
// Use real jiggle bones. Woot!
data->useJiggleBoneCount = 32;
}
if ( data->useJiggleBoneCount > 0 )
{
// Make sure we draw at least runs of 32 frames with real jiggle bones.
data->useJiggleBoneCount--;
data->useGoalMatrixCount = 0;
bUseGoalMatrix = false;
}
if ( bMaxDeltaT )
{
deltaT = thousandHZ;
}
else if ( bUseGoalMatrix )
{
// disable jigglebone - just use goal matrix
boneMX = goalMX;
return;
}
// we want lastUpdate here, so if jigglebones were skipped they get reinitialized if they turn back on
data->lastUpdate = currenttime;
//
// Bone tip flex
//
if ( jiggleInfo->flags & ( JIGGLE_IS_FLEXIBLE | JIGGLE_IS_RIGID ) )
{
// apply gravity in global space
data->tipAccel.z -= jiggleInfo->tipMass;
if ( jiggleInfo->flags & JIGGLE_IS_FLEXIBLE )
{
// decompose into local coordinates
Vector error = goalTip - data->tipPos;
Vector localError;
localError.x = DotProduct( goalLeft, error );
localError.y = DotProduct( goalUp, error );
localError.z = DotProduct( goalForward, error );
Vector localVel;
localVel.x = DotProduct( goalLeft, data->tipVel );
localVel.y = DotProduct( goalUp, data->tipVel );
// yaw spring
float yawAccel = jiggleInfo->yawStiffness * localError.x - jiggleInfo->yawDamping * localVel.x;
// pitch spring
float pitchAccel = jiggleInfo->pitchStiffness * localError.y - jiggleInfo->pitchDamping * localVel.y;
if ( jiggleInfo->flags & JIGGLE_HAS_LENGTH_CONSTRAINT )
{
// drive tip towards goal tip position
data->tipAccel += yawAccel * goalLeft + pitchAccel * goalUp;
}
else
{
// allow flex along length of spring
localVel.z = DotProduct( goalForward, data->tipVel );
// along spring
float alongAccel = jiggleInfo->alongStiffness * localError.z - jiggleInfo->alongDamping * localVel.z;
// drive tip towards goal tip position
data->tipAccel += yawAccel * goalLeft + pitchAccel * goalUp + alongAccel * goalForward;
}
}
// simple euler integration
data->tipVel += data->tipAccel * deltaT;
data->tipPos += data->tipVel * deltaT;
// clear this timestep's accumulated accelerations
data->tipAccel = vec3_origin;
//
// Apply optional constraints
//
if ( jiggleInfo->flags & ( JIGGLE_HAS_YAW_CONSTRAINT | JIGGLE_HAS_PITCH_CONSTRAINT ) )
{
// find components of spring vector in local coordinate system
Vector along = data->tipPos - goalBasePosition;
Vector localAlong;
localAlong.x = DotProduct( goalLeft, along );
localAlong.y = DotProduct( goalUp, along );
localAlong.z = DotProduct( goalForward, along );
Vector localVel;
localVel.x = DotProduct( goalLeft, data->tipVel );
localVel.y = DotProduct( goalUp, data->tipVel );
localVel.z = DotProduct( goalForward, data->tipVel );
if ( jiggleInfo->flags & JIGGLE_HAS_YAW_CONSTRAINT )
{
// enforce yaw constraints in local XZ plane
float yawError = atan2( localAlong.x, localAlong.z );
bool isAtLimit = false;
float yaw = 0.0f;
if ( yawError < jiggleInfo->minYaw )
{
// at angular limit
isAtLimit = true;
yaw = jiggleInfo->minYaw;
}
else if ( yawError > jiggleInfo->maxYaw )
{
// at angular limit
isAtLimit = true;
yaw = jiggleInfo->maxYaw;
}
if ( isAtLimit )
{
float sy, cy;
SinCos( yaw, &sy, &cy );
// yaw matrix
matrix3x4_t yawMatrix;
yawMatrix[0][0] = cy;
yawMatrix[1][0] = 0;
yawMatrix[2][0] = -sy;
yawMatrix[0][1] = 0;
yawMatrix[1][1] = 1.0f;
yawMatrix[2][1] = 0;
yawMatrix[0][2] = sy;
yawMatrix[1][2] = 0;
yawMatrix[2][2] = cy;
yawMatrix[0][3] = 0;
yawMatrix[1][3] = 0;
yawMatrix[2][3] = 0;
// global coordinates of limit
matrix3x4_t limitMatrix;
ConcatTransforms( goalMX, yawMatrix, limitMatrix );
Vector limitLeft( limitMatrix.m_flMatVal[0][0],
limitMatrix.m_flMatVal[1][0],
limitMatrix.m_flMatVal[2][0] );
Vector limitUp( limitMatrix.m_flMatVal[0][1],
limitMatrix.m_flMatVal[1][1],
limitMatrix.m_flMatVal[2][1] );
Vector limitForward( limitMatrix.m_flMatVal[0][2],
limitMatrix.m_flMatVal[1][2],
limitMatrix.m_flMatVal[2][2] );
#ifdef CLIENT_DLL
if ( cl_jiggle_bone_debug_yaw_constraints.GetBool() )
{
float dT = 0.01f;
const float axisSize = 10.0f;
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * limitLeft, 0, 255, 255, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * limitUp, 255, 255, 0, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * limitForward, 255, 0, 255, true, dT );
}
}
#endif // CLIENT_DLL
Vector limitAlong( DotProduct( limitLeft, along ),
DotProduct( limitUp, along ),
DotProduct( limitForward, along ) );
// clip to limit plane
data->tipPos = goalBasePosition + limitAlong.y * limitUp + limitAlong.z * limitForward;
// removed friction and velocity clipping against constraint - was causing simulation blowups (MSB 12/9/2010)
data->tipVel.Zero();
// update along vectors for use by pitch constraint
along = data->tipPos - goalBasePosition;
localAlong.x = DotProduct( goalLeft, along );
localAlong.y = DotProduct( goalUp, along );
localAlong.z = DotProduct( goalForward, along );
localVel.x = DotProduct( goalLeft, data->tipVel );
localVel.y = DotProduct( goalUp, data->tipVel );
localVel.z = DotProduct( goalForward, data->tipVel );
}
}
if ( jiggleInfo->flags & JIGGLE_HAS_PITCH_CONSTRAINT )
{
// enforce pitch constraints in local YZ plane
float pitchError = atan2( localAlong.y, localAlong.z );
bool isAtLimit = false;
float pitch = 0.0f;
if ( pitchError < jiggleInfo->minPitch )
{
// at angular limit
isAtLimit = true;
pitch = jiggleInfo->minPitch;
}
else if ( pitchError > jiggleInfo->maxPitch )
{
// at angular limit
isAtLimit = true;
pitch = jiggleInfo->maxPitch;
}
if ( isAtLimit )
{
float sp, cp;
SinCos( pitch, &sp, &cp );
// pitch matrix
matrix3x4_t pitchMatrix;
pitchMatrix[0][0] = 1.0f;
pitchMatrix[1][0] = 0;
pitchMatrix[2][0] = 0;
pitchMatrix[0][1] = 0;
pitchMatrix[1][1] = cp;
pitchMatrix[2][1] = -sp;
pitchMatrix[0][2] = 0;
pitchMatrix[1][2] = sp;
pitchMatrix[2][2] = cp;
pitchMatrix[0][3] = 0;
pitchMatrix[1][3] = 0;
pitchMatrix[2][3] = 0;
// global coordinates of limit
matrix3x4_t limitMatrix;
ConcatTransforms( goalMX, pitchMatrix, limitMatrix );
Vector limitLeft( limitMatrix.m_flMatVal[0][0],
limitMatrix.m_flMatVal[1][0],
limitMatrix.m_flMatVal[2][0] );
Vector limitUp( limitMatrix.m_flMatVal[0][1],
limitMatrix.m_flMatVal[1][1],
limitMatrix.m_flMatVal[2][1] );
Vector limitForward( limitMatrix.m_flMatVal[0][2],
limitMatrix.m_flMatVal[1][2],
limitMatrix.m_flMatVal[2][2] );
#ifdef CLIENT_DLL
if (cl_jiggle_bone_debug_pitch_constraints.GetBool())
{
float dT = 0.01f;
const float axisSize = 10.0f;
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * limitLeft, 0, 255, 255, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * limitUp, 255, 255, 0, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * limitForward, 255, 0, 255, true, dT );
}
}
#endif // CLIENT_DLL
Vector limitAlong( DotProduct( limitLeft, along ),
DotProduct( limitUp, along ),
DotProduct( limitForward, along ) );
// clip to limit plane
data->tipPos = goalBasePosition + limitAlong.x * limitLeft + limitAlong.z * limitForward;
// removed friction and velocity clipping against constraint - was causing simulation blowups (MSB 12/9/2010)
data->tipVel.Zero();
}
}
}
// needed for matrix assembly below
Vector forward = data->tipPos - goalBasePosition;
forward.NormalizeInPlace();
if ( jiggleInfo->flags & JIGGLE_HAS_ANGLE_CONSTRAINT )
{
// enforce max angular error
Vector error = goalTip - data->tipPos;
float dot = DotProduct( forward, goalForward );
float angleBetween = acos( dot );
if ( dot < 0.0f )
{
angleBetween = 2.0f * M_PI - angleBetween;
}
if ( angleBetween > jiggleInfo->angleLimit )
{
// at angular limit
float maxBetween = jiggleInfo->length * sin( jiggleInfo->angleLimit );
Vector delta = goalTip - data->tipPos;
delta.NormalizeInPlace();
data->tipPos = goalTip - maxBetween * delta;
forward = data->tipPos - goalBasePosition;
forward.NormalizeInPlace();
}
}
if ( jiggleInfo->flags & JIGGLE_HAS_LENGTH_CONSTRAINT )
{
// enforce spring length
data->tipPos = goalBasePosition + jiggleInfo->length * forward;
// zero velocity along forward bone axis
data->tipVel -= DotProduct( data->tipVel, forward ) * forward;
}
//
// Build bone matrix to align along current tip direction
//
Vector left = CrossProduct( goalUp, forward );
left.NormalizeInPlace();
if ( DotProduct( left, data->lastLeft ) < 0.0f )
{
// The bone has rotated so far its on the other side of the up vector
// resulting in the cross product result flipping 180 degrees around the up
// vector. Flip it back.
left = -left;
}
data->lastLeft = left;
#ifdef CLIENT_DLL
if ( cl_jiggle_bone_debug.GetBool() )
{
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + 10.0f * data->lastLeft, 255, 0, 255, true, 0.01f );
}
}
#endif
Vector up = CrossProduct( forward, left );
boneMX[0][0] = left.x;
boneMX[1][0] = left.y;
boneMX[2][0] = left.z;
boneMX[0][1] = up.x;
boneMX[1][1] = up.y;
boneMX[2][1] = up.z;
boneMX[0][2] = forward.x;
boneMX[1][2] = forward.y;
boneMX[2][2] = forward.z;
boneMX[0][3] = goalBasePosition.x;
boneMX[1][3] = goalBasePosition.y;
boneMX[2][3] = goalBasePosition.z;
}
//
// Bone base flex
//
if ( jiggleInfo->flags & JIGGLE_HAS_BASE_SPRING )
{
// gravity
data->baseAccel.z -= jiggleInfo->baseMass;
// simple spring
Vector error = goalBasePosition - data->basePos;
data->baseAccel += jiggleInfo->baseStiffness * error - jiggleInfo->baseDamping * data->baseVel;
data->baseVel += data->baseAccel * deltaT;
data->basePos += data->baseVel * deltaT;
// clear this timestep's accumulated accelerations
data->baseAccel = vec3_origin;
// constrain to limits
error = data->basePos - goalBasePosition;
Vector localError;
localError.x = DotProduct( goalLeft, error );
localError.y = DotProduct( goalUp, error );
localError.z = DotProduct( goalForward, error );
Vector localVel;
localVel.x = DotProduct( goalLeft, data->baseVel );
localVel.y = DotProduct( goalUp, data->baseVel );
localVel.z = DotProduct( goalForward, data->baseVel );
// horizontal constraint
if ( localError.x < jiggleInfo->baseMinLeft )
{
localError.x = jiggleInfo->baseMinLeft;
// friction
data->baseAccel -= jiggleInfo->baseLeftFriction * (localVel.y * goalUp + localVel.z * goalForward);
}
else if ( localError.x > jiggleInfo->baseMaxLeft )
{
localError.x = jiggleInfo->baseMaxLeft;
// friction
data->baseAccel -= jiggleInfo->baseLeftFriction * (localVel.y * goalUp + localVel.z * goalForward);
}
if ( localError.y < jiggleInfo->baseMinUp )
{
localError.y = jiggleInfo->baseMinUp;
// friction
data->baseAccel -= jiggleInfo->baseUpFriction * (localVel.x * goalLeft + localVel.z * goalForward);
}
else if ( localError.y > jiggleInfo->baseMaxUp )
{
localError.y = jiggleInfo->baseMaxUp;
// friction
data->baseAccel -= jiggleInfo->baseUpFriction * (localVel.x * goalLeft + localVel.z * goalForward);
}
if ( localError.z < jiggleInfo->baseMinForward )
{
localError.z = jiggleInfo->baseMinForward;
// friction
data->baseAccel -= jiggleInfo->baseForwardFriction * (localVel.x * goalLeft + localVel.y * goalUp);
}
else if ( localError.z > jiggleInfo->baseMaxForward )
{
localError.z = jiggleInfo->baseMaxForward;
// friction
data->baseAccel -= jiggleInfo->baseForwardFriction * (localVel.x * goalLeft + localVel.y * goalUp);
}
data->basePos = goalBasePosition + localError.x * goalLeft + localError.y * goalUp + localError.z * goalForward;
// fix up velocity
data->baseVel = (data->basePos - data->baseLastPos) / deltaT;
data->baseLastPos = data->basePos;
if ( !( jiggleInfo->flags & ( JIGGLE_IS_FLEXIBLE | JIGGLE_IS_RIGID ) ) )
{
// no tip flex - use bone's goal orientation
boneMX = goalMX;
}
// update bone position
MatrixSetColumn( data->basePos, 3, boneMX );
}
else if ( jiggleInfo->flags & JIGGLE_IS_BOING )
{
// estimate velocity
Vector vel = goalBasePosition - data->lastBoingPos;
#ifdef CLIENT_DLL
if ( cl_jiggle_bone_debug.GetBool() )
{
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( data->lastBoingPos, goalBasePosition, 0, 128, ( gpGlobals->framecount & 0x1 ) ? 0 : 200, true, 999.9f );
}
}
#endif
data->lastBoingPos = goalBasePosition;
float speed = vel.NormalizeInPlace();
if ( speed < 0.00001f )
{
vel = Vector( 0, 0, 1.0f );
speed = 0.0f;
}
else
{
speed /= deltaT;
}
data->boingTime += deltaT;
// if velocity changed a lot, we impacted and should *boing*
const float minSpeed = 5.0f; // 15.0f;
const float minReBoingTime = 0.5f;
if ( ( speed > minSpeed || data->boingSpeed > minSpeed ) && data->boingTime > minReBoingTime )
{
if ( fabs( data->boingSpeed - speed ) > jiggleInfo->boingImpactSpeed || DotProduct( vel, data->boingVelDir ) < jiggleInfo->boingImpactAngle )
{
data->boingTime = 0.0f;
data->boingDir = -vel;
#ifdef CLIENT_DLL
if ( cl_jiggle_bone_debug.GetBool() )
{
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + 5.0f * data->boingDir, 255, 255, 0, true, 999.9f );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + Vector( 0.1, 0, 0 ), 128, 128, 0, true, 999.9f );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + Vector( 0, 0.1, 0 ), 128, 128, 0, true, 999.9f );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + Vector( 0, 0, 0.1 ), 128, 128, 0, true, 999.9f );
}
}
#endif
}
}
data->boingVelDir = vel;
data->boingSpeed = speed;
float damping = 1.0f - ( jiggleInfo->boingDampingRate * data->boingTime );
if ( damping < 0.01f )
{
// boing has entirely damped out
boneMX = goalMX;
}
else
{
damping *= damping;
damping *= damping;
float flex = jiggleInfo->boingAmplitude * cos( jiggleInfo->boingFrequency * data->boingTime ) * damping;
float squash = 1.0f + flex;
float stretch = 1.0f - flex;
boneMX[0][0] = goalLeft.x;
boneMX[1][0] = goalLeft.y;
boneMX[2][0] = goalLeft.z;
boneMX[0][1] = goalUp.x;
boneMX[1][1] = goalUp.y;
boneMX[2][1] = goalUp.z;
boneMX[0][2] = goalForward.x;
boneMX[1][2] = goalForward.y;
boneMX[2][2] = goalForward.z;
boneMX[0][3] = 0.0f;
boneMX[1][3] = 0.0f;
boneMX[2][3] = 0.0f;
// build transform into "boing space", where Z is along primary boing axis
Vector boingSide;
if ( fabs( data->boingDir.x ) < 0.9f )
{
boingSide = CrossProduct( data->boingDir, Vector( 1.0f, 0, 0 ) );
}
else
{
boingSide = CrossProduct( data->boingDir, Vector( 0, 0, 1.0f ) );
}
boingSide.NormalizeInPlace();
Vector boingOtherSide = CrossProduct( data->boingDir, boingSide );
matrix3x4_t xfrmToBoingCoordsMX;
xfrmToBoingCoordsMX[0][0] = boingSide.x;
xfrmToBoingCoordsMX[0][1] = boingSide.y;
xfrmToBoingCoordsMX[0][2] = boingSide.z;
xfrmToBoingCoordsMX[1][0] = boingOtherSide.x;
xfrmToBoingCoordsMX[1][1] = boingOtherSide.y;
xfrmToBoingCoordsMX[1][2] = boingOtherSide.z;
xfrmToBoingCoordsMX[2][0] = data->boingDir.x;
xfrmToBoingCoordsMX[2][1] = data->boingDir.y;
xfrmToBoingCoordsMX[2][2] = data->boingDir.z;
xfrmToBoingCoordsMX[0][3] = 0.0f;
xfrmToBoingCoordsMX[1][3] = 0.0f;
xfrmToBoingCoordsMX[2][3] = 0.0f;
// build squash and stretch transform in "boing space"
matrix3x4_t boingMX;
boingMX[0][0] = squash;
boingMX[1][0] = 0.0f;
boingMX[2][0] = 0.0f;
boingMX[0][1] = 0.0f;
boingMX[1][1] = squash;
boingMX[2][1] = 0.0f;
boingMX[0][2] = 0.0f;
boingMX[1][2] = 0.0f;
boingMX[2][2] = stretch;
boingMX[0][3] = 0.0f;
boingMX[1][3] = 0.0f;
boingMX[2][3] = 0.0f;
// transform back from boing space (inverse is transpose since orthogonal)
matrix3x4_t xfrmFromBoingCoordsMX;
xfrmFromBoingCoordsMX[0][0] = xfrmToBoingCoordsMX[0][0];
xfrmFromBoingCoordsMX[1][0] = xfrmToBoingCoordsMX[0][1];
xfrmFromBoingCoordsMX[2][0] = xfrmToBoingCoordsMX[0][2];
xfrmFromBoingCoordsMX[0][1] = xfrmToBoingCoordsMX[1][0];
xfrmFromBoingCoordsMX[1][1] = xfrmToBoingCoordsMX[1][1];
xfrmFromBoingCoordsMX[2][1] = xfrmToBoingCoordsMX[1][2];
xfrmFromBoingCoordsMX[0][2] = xfrmToBoingCoordsMX[2][0];
xfrmFromBoingCoordsMX[1][2] = xfrmToBoingCoordsMX[2][1];
xfrmFromBoingCoordsMX[2][2] = xfrmToBoingCoordsMX[2][2];
xfrmFromBoingCoordsMX[0][3] = 0.0f;
xfrmFromBoingCoordsMX[1][3] = 0.0f;
xfrmFromBoingCoordsMX[2][3] = 0.0f;
// put it all together
matrix3x4_t xfrmMX;
MatrixMultiply( xfrmToBoingCoordsMX, boingMX, xfrmMX );
MatrixMultiply( xfrmMX, xfrmFromBoingCoordsMX, xfrmMX );
MatrixMultiply( boneMX, xfrmMX, boneMX );
#ifdef CLIENT_DLL
if ( cl_jiggle_bone_debug.GetBool() )
{
float dT = 0.01f;
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + 50.0f * data->boingDir, 255, 255, 0, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + 50.0f * boingSide, 255, 0, 255, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + 50.0f * boingOtherSide, 0, 255, 255, true, dT );
}
}
#endif
boneMX[0][3] = goalBasePosition.x;
boneMX[1][3] = goalBasePosition.y;
boneMX[2][3] = goalBasePosition.z;
}
}
else if ( !( jiggleInfo->flags & ( JIGGLE_IS_FLEXIBLE | JIGGLE_IS_RIGID ) ) )
{
// no flex at all - just use goal matrix
boneMX = goalMX;
}
#ifdef CLIENT_DLL
// debug display for client only so server doesn't try to also draw it
if ( cl_jiggle_bone_debug.GetBool() )
{
float dT = 0.01f;
const float axisSize = 5.0f;
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * goalLeft, 255, 0, 0, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * goalUp, 0, 255, 0, true, dT );
debugoverlay->AddLineOverlay( goalBasePosition, goalBasePosition + axisSize * goalForward, 0, 0, 255, true, dT );
}
if ( cl_jiggle_bone_debug.GetInt() > 1 )
{
DevMsg( "Jiggle bone #%d, basePos( %3.2f, %3.2f, %3.2f ), tipPos( %3.2f, %3.2f, %3.2f ), left( %3.2f, %3.2f, %3.2f ), up( %3.2f, %3.2f, %3.2f ), forward( %3.2f, %3.2f, %3.2f )\n",
data->bone,
goalBasePosition.x, goalBasePosition.y, goalBasePosition.z,
data->tipPos.x, data->tipPos.y, data->tipPos.z,
goalLeft.x, goalLeft.y, goalLeft.z,
goalUp.x, goalUp.y, goalUp.z,
goalForward.x, goalForward.y, goalForward.z );
}
const float sz = 1.0f;
if ( jiggleInfo->flags & ( JIGGLE_IS_FLEXIBLE | JIGGLE_IS_RIGID ) )
{
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( goalBasePosition,
data->tipPos, 255, 255, 0, true, dT );
debugoverlay->AddLineOverlay( data->tipPos + Vector( -sz, 0, 0 ),
data->tipPos + Vector( sz, 0, 0 ), 0, 255, 255, true, dT );
debugoverlay->AddLineOverlay( data->tipPos + Vector( 0, -sz, 0 ),
data->tipPos + Vector( 0, sz, 0 ), 0, 255, 255, true, dT );
debugoverlay->AddLineOverlay( data->tipPos + Vector( 0, 0, -sz ),
data->tipPos + Vector( 0, 0, sz ), 0, 255, 255, true, dT );
}
}
if ( jiggleInfo->flags & JIGGLE_HAS_BASE_SPRING )
{
if ( debugoverlay )
{
debugoverlay->AddLineOverlay( data->basePos + Vector( -sz, 0, 0 ),
data->basePos + Vector( sz, 0, 0 ), 255, 0, 255, true, dT );
debugoverlay->AddLineOverlay( data->basePos + Vector( 0, -sz, 0 ),
data->basePos + Vector( 0, sz, 0 ), 255, 0, 255, true, dT );
debugoverlay->AddLineOverlay( data->basePos + Vector( 0, 0, -sz ),
data->basePos + Vector( 0, 0, sz ), 255, 0, 255, true, dT );
}
}
if ( jiggleInfo->flags & JIGGLE_IS_BOING )
{
if ( cl_jiggle_bone_debug.GetInt() > 2 )
{
DevMsg( " boingSpeed = %3.2f, boingVelDir( %3.2f, %3.2f, %3.2f )\n", data->boingVelDir.Length() / deltaT, data->boingVelDir.x, data->boingVelDir.y, data->boingVelDir.z );
}
}
}
#endif // CLIENT_DLL
}
| 0 | 0.892857 | 1 | 0.892857 | game-dev | MEDIA | 0.876204 | game-dev | 0.965094 | 1 | 0.965094 |
WayofTime/BloodMagic | 2,461 | src/main/java/wayoftime/bloodmagic/common/item/ItemThrowingDagger.java | package wayoftime.bloodmagic.common.item;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import wayoftime.bloodmagic.BloodMagic;
import wayoftime.bloodmagic.entity.projectile.AbstractEntityThrowingDagger;
import wayoftime.bloodmagic.entity.projectile.EntityThrowingDagger;
import java.util.List;
public class ItemThrowingDagger extends Item
{
public ItemThrowingDagger()
{
super(new Item.Properties().stacksTo(64));
}
@Override
public InteractionResultHolder<ItemStack> use(Level worldIn, Player playerIn, InteractionHand hand)
{
ItemStack stack = playerIn.getItemInHand(hand);
if (!playerIn.isCreative())
{
stack.shrink(1);
}
playerIn.getCooldowns().addCooldown(this, 50);
worldIn.playSound((Player) null, playerIn.getX(), playerIn.getY(), playerIn.getZ(), SoundEvents.SNOWBALL_THROW, SoundSource.NEUTRAL, 0.5F, 0.4F / (worldIn.random.nextFloat() * 0.4F + 0.8F));
if (!worldIn.isClientSide)
{
ItemStack copyStack = stack.copy();
copyStack.setCount(1);
AbstractEntityThrowingDagger dagger = getDagger(copyStack, worldIn, playerIn);
worldIn.addFreshEntity(dagger);
}
return new InteractionResultHolder<>(InteractionResult.SUCCESS, stack);
}
public AbstractEntityThrowingDagger getDagger(ItemStack stack, Level world, Player player)
{
AbstractEntityThrowingDagger dagger = new EntityThrowingDagger(stack, world, player);
dagger.shootFromRotation(player, player.getXRot(), player.getYRot(), 0.0F, 3F, 0.5F);
dagger.setDamage(10);
// dagger.setEffectsFromItem(stack);
return dagger;
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, Level world, List<Component> tooltip, TooltipFlag flag)
{
tooltip.add(Component.translatable("tooltip.bloodmagic.throwing_dagger.desc").withStyle(ChatFormatting.ITALIC).withStyle(ChatFormatting.GRAY));
super.appendHoverText(stack, world, tooltip, flag);
}
}
| 0 | 0.783547 | 1 | 0.783547 | game-dev | MEDIA | 0.994626 | game-dev | 0.891405 | 1 | 0.891405 |
indianakernick/Simpleton-Engine | 4,433 | Simpleton/Time/simple anim.hpp | //
// simple anim.hpp
// Simpleton Engine
//
// Created by Indi Kernick on 6/8/17.
// Copyright © 2017 Indi Kernick. All rights reserved.
//
#ifndef engine_time_simple_anim_hpp
#define engine_time_simple_anim_hpp
#include "../Math/int float.hpp"
namespace Time {
template <typename Duration>
class SimpleAnim {
public:
static_assert(std::is_arithmetic<Duration>::value);
SimpleAnim() = default;
explicit SimpleAnim(const Duration duration)
: duration(duration) {}
///Progress the animation forward
void advance(const Duration delta) {
progress += delta;
}
///Progress the animation backward
void advanceRev(const Duration delta) {
progress -= delta;
}
///Has the playhead passed the end?
bool overflow() const {
return progress > duration;
}
///Has the playhead passed the beginning?
bool underflow() const {
return progress < Duration(0);
}
///How far past the end is the playhead
Duration overflowTime() const {
return progress - duration;
}
///How far past the beginning is the playhead
Duration underflowTime() const {
return -progress;
}
///Is the playhead at the beginning?
bool atBegin() const {
return progress == Duration(0);
}
///Is the playhead at the end?
bool atEnd() const {
return progress == duration;
}
///Stop playing when progess passes the end
bool stopOnEnd() {
if (progress > duration) {
progress = duration;
return true;
} else {
return false;
}
}
///Stop playing when progress passes the beginning
bool stopOnBegin() {
if (progress < Duration(0)) {
progress = Duration(0);
return true;
} else {
return false;
}
}
///Move the playhead to the beginning when the playhead passes the end
void repeatOnOverflow() {
if (duration == Duration(0)) {
progress = Duration(0);
} else {
progress = Math::mod(progress, duration);
}
}
///Move the playhead to the end when the playhead passes the beginning
void repeatOnUnderflow() {
if (duration == Duration(0)) {
progress = Duration(0);
} else {
progress = duration - Math::mod(duration - progress, duration);
}
}
///Returns true if the animation should be played in reverse
bool reverseOnOverflow() {
if (progress > duration) {
progress = duration + duration - progress;
return true;
} else {
return false;
}
}
///Returns true if the animation should be played forward
bool forwardOnUnderflow() {
if (progress < Duration(0)) {
progress = -progress;
return true;
} else {
return false;
}
}
///Move the playhead to the beginning
void toBegin() {
progress = Duration(0);
}
///Move the playhead to the end
void toEnd() {
progress = duration;
}
///Change the duration
void setDuration(const Duration newDuration) {
duration = newDuration;
}
///Get the duration
Duration getDuration() const {
return duration;
}
///Get the progress of the animation as a float in range 0.0-1.0
template <typename Float>
std::enable_if_t<
std::is_floating_point<Float>::value,
Float
>
getProgress() const {
if (duration == Duration(0)) {
if (progress == Duration(0)) {
return Float(0);
} else {
return Math::infinity<Float>();
}
} else {
return static_cast<Float>(progress) / static_cast<Float>(duration);
}
}
///Set the progress of the animation as a float in range 0.0-1.0
template <typename Float>
std::enable_if_t<
std::is_floating_point<Float>::value,
Float
>
setProgress(const Float prog) {
progress = prog * duration;
}
///Get the progress of the animation as a duration from the beginning
Duration getProgressTime() const {
return progress;
}
///Set the progress of the animation as a duration from the beginning
void setProgressTime(const Duration newProgress) {
progress = newProgress;
}
private:
Duration duration = Duration(0);
Duration progress = Duration(0);
};
}
#endif
| 0 | 0.924379 | 1 | 0.924379 | game-dev | MEDIA | 0.306553 | game-dev | 0.869414 | 1 | 0.869414 |
PixelGuys/Cubyz | 5,067 | src/server/terrain/noise/CachedFractalNoise3D.zig | const std = @import("std");
const main = @import("main");
const Array3D = main.utils.Array3D;
const ChunkPosition = main.chunk.ChunkPosition;
const CachedFractalNoise3D = @This();
pos: ChunkPosition,
cache: Array3D(f32),
voxelShift: u5,
scale: u31,
worldSeed: u64,
pub fn init(wx: i32, wy: i32, wz: i32, voxelSize: u31, size: u31, worldSeed: u64, scale: u31) CachedFractalNoise3D {
const maxSize = size/voxelSize;
const cacheWidth = maxSize + 1;
var self = CachedFractalNoise3D{
.pos = .{
.wx = wx,
.wy = wy,
.wz = wz,
.voxelSize = voxelSize,
},
.voxelShift = @ctz(voxelSize),
.cache = Array3D(f32).init(main.globalAllocator, cacheWidth, cacheWidth, cacheWidth),
.scale = scale,
.worldSeed = worldSeed,
};
// Init the corners:
@memset(self.cache.mem, 0);
const reducedScale = scale/voxelSize;
var x: u31 = 0;
while(x <= maxSize) : (x += reducedScale) {
var y: u31 = 0;
while(y <= maxSize) : (y += reducedScale) {
var z: u31 = 0;
while(z <= maxSize) : (z += reducedScale) {
self.cache.ptr(x, y, z).* = (@as(f32, @floatFromInt(reducedScale + 1 + scale))*self.getGridValue(x, y, z))*@as(f32, @floatFromInt(voxelSize));
} // ↑ sacrifice some resolution to reserve the value 0, for determining if the value was initialized. This prevents an expensive array initialization.
}
}
return self;
}
pub fn deinit(self: CachedFractalNoise3D) void {
self.cache.deinit(main.globalAllocator);
}
pub fn getRandomValue(self: CachedFractalNoise3D, wx: i32, wy: i32, wz: i32) f32 {
var seed: u64 = main.random.initSeed3D(self.worldSeed, .{wx, wy, wz});
return main.random.nextFloat(&seed) - 0.5;
}
fn getGridValue(self: CachedFractalNoise3D, relX: u31, relY: u31, relZ: u31) f32 {
return self.getRandomValue(self.pos.wx +% relX*%self.pos.voxelSize, self.pos.wy +% relY*%self.pos.voxelSize, self.pos.wz +% relZ*%self.pos.voxelSize);
}
fn generateRegion(self: CachedFractalNoise3D, _x: u31, _y: u31, _z: u31, voxelSize: u31) void {
const x = _x & ~@as(u31, voxelSize - 1);
const y = _y & ~@as(u31, voxelSize - 1);
const z = _z & ~@as(u31, voxelSize - 1);
// Make sure that all higher points are generated:
_ = self._getValue(x | voxelSize, y | voxelSize, z | voxelSize);
const xMid = x + @divExact(voxelSize, 2);
const yMid = y + @divExact(voxelSize, 2);
const zMid = z + @divExact(voxelSize, 2);
const randomFactor: f32 = @floatFromInt(voxelSize*self.pos.voxelSize);
const cache = self.cache;
var a: u31 = 0;
while(a <= voxelSize) : (a += voxelSize) { // 2 coordinates on the grid.
var b: u31 = 0;
while(b <= voxelSize) : (b += voxelSize) {
// x-y
cache.ptr(x + a, y + b, zMid).* = (cache.get(x + a, y + b, z) + cache.get(x + a, y + b, z + voxelSize))/2;
cache.ptr(x + a, y + b, zMid).* += randomFactor*self.getGridValue(x + a, y + b, zMid);
// x-z
cache.ptr(x + a, yMid, z + b).* = (cache.get(x + a, y, z + b) + cache.get(x + a, y + voxelSize, z + b))/2;
cache.ptr(x + a, yMid, z + b).* += randomFactor*self.getGridValue(x + a, yMid, z + b);
// x-z
cache.ptr(xMid, y + a, z + b).* = (cache.get(x, y + a, z + b) + cache.get(x + voxelSize, y + a, z + b))/2;
cache.ptr(xMid, y + a, z + b).* += randomFactor*self.getGridValue(xMid, y + a, z + b);
}
}
a = 0;
while(a <= voxelSize) : (a += voxelSize) { // 1 coordinate on the grid.
// x
cache.ptr(x + a, yMid, zMid).* = (cache.get(x + a, yMid, z) + cache.get(x + a, yMid, z + voxelSize) + cache.get(x + a, y, zMid) + cache.get(x + a, y + voxelSize, zMid))/4 + randomFactor*self.getGridValue(x + a, yMid, zMid);
// y
cache.ptr(xMid, y + a, zMid).* = (cache.get(xMid, y + a, z) + cache.get(xMid, y + a, z + voxelSize) + cache.get(x, y + a, zMid) + cache.get(x + voxelSize, y + a, zMid))/4 + randomFactor*self.getGridValue(xMid, y + a, zMid);
// z
cache.ptr(xMid, yMid, z + a).* = (cache.get(xMid, y, z + a) + cache.get(xMid, y + voxelSize, z + a) + cache.get(x, yMid, z + a) + cache.get(x + voxelSize, yMid, z + a))/4 + randomFactor*self.getGridValue(xMid, yMid, z + a);
}
// Center point:
cache.ptr(xMid, yMid, zMid).* = (cache.get(xMid, yMid, z) + cache.get(xMid, yMid, z + voxelSize) + cache.get(xMid, y, zMid) + cache.get(xMid, y + voxelSize, zMid) + cache.get(x, yMid, zMid) + cache.get(x + voxelSize, yMid, zMid))/6 + randomFactor*self.getGridValue(xMid, yMid, zMid);
}
fn _getValue(self: CachedFractalNoise3D, x: u31, y: u31, z: u31) f32 {
const value = self.cache.get(x, y, z);
if(value != 0) return value;
// Need to actually generate stuff now.
const minShift = @min(@ctz(x), @ctz(y), @ctz(z));
self.generateRegion(x, y, z, @as(u31, 2) << @intCast(minShift));
return self.cache.get(x, y, z);
}
pub fn getValue(self: CachedFractalNoise3D, wx: i32, wy: i32, wz: i32) f32 {
const x: u31 = @intCast((wx -% self.pos.wx) >> self.voxelShift);
const y: u31 = @intCast((wy -% self.pos.wy) >> self.voxelShift);
const z: u31 = @intCast((wz -% self.pos.wz) >> self.voxelShift);
return self._getValue(x, y, z) - @as(f32, @floatFromInt(self.scale));
}
| 0 | 0.780288 | 1 | 0.780288 | game-dev | MEDIA | 0.275454 | game-dev | 0.814061 | 1 | 0.814061 |
Source-Python-Dev-Team/Source.Python | 10,914 | src/patches/l4d2/game/shared/predictioncopy.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PREDICTIONCOPY_H
#define PREDICTIONCOPY_H
#ifdef _WIN32
#pragma once
#endif
#include <memory.h>
#include "datamap.h"
#include "ehandle.h"
#include "tier1/utlstring.h"
#if defined( CLIENT_DLL )
class C_BaseEntity;
typedef CHandle<C_BaseEntity> EHANDLE;
#if defined( _DEBUG )
// #define COPY_CHECK_STRESSTEST
class IGameSystem;
IGameSystem* GetPredictionCopyTester( void );
#endif
#else
class CBaseEntity;
typedef CHandle<CBaseEntity> EHANDLE;
#endif
#define PATCH_PC_REDEFINITIONS
#if 0
enum
{
PC_EVERYTHING = 0,
PC_NON_NETWORKED_ONLY,
PC_NETWORKED_ONLY,
};
#endif
#define PC_DATA_PACKED true
#define PC_DATA_NORMAL false
typedef void ( *FN_FIELD_COMPARE )( const char *classname, const char *fieldname, const char *fieldtype,
bool networked, bool noterrorchecked, bool differs, bool withintolerance, const char *value );
class CPredictionCopy
{
public:
typedef enum
{
DIFFERS = 0,
IDENTICAL,
WITHINTOLERANCE,
} difftype_t;
CPredictionCopy( int type, void *dest, bool dest_packed, void const *src, bool src_packed,
bool counterrors = false, bool reporterrors = false, bool performcopy = true,
bool describefields = false, FN_FIELD_COMPARE func = NULL );
void CopyShort( difftype_t dt, short *outvalue, const short *invalue, int count );
void CopyInt( difftype_t dt, int *outvalue, const int *invalue, int count ); // Copy an int
void CopyBool( difftype_t dt, bool *outvalue, const bool *invalue, int count ); // Copy a bool
void CopyFloat( difftype_t dt, float *outvalue, const float *invalue, int count ); // Copy a float
void CopyString( difftype_t dt, char *outstring, const char *instring ); // Copy a null-terminated string
void CopyVector( difftype_t dt, Vector& outValue, const Vector &inValue ); // Copy a vector
void CopyVector( difftype_t dt, Vector* outValue, const Vector *inValue, int count ); // Copy a vector array
void CopyQuaternion( difftype_t dt, Quaternion& outValue, const Quaternion &inValue ); // Copy a quaternion
void CopyQuaternion( difftype_t dt, Quaternion* outValue, const Quaternion *inValue, int count ); // Copy a quaternion array
void CopyEHandle( difftype_t dt, EHANDLE *outvalue, EHANDLE const *invalue, int count );
void FORCEINLINE CopyData( difftype_t dt, int size, char *outdata, const char *indata ) // Copy a binary data block
{
if ( !m_bPerformCopy )
return;
if ( dt == IDENTICAL )
return;
memcpy( outdata, indata, size );
}
int TransferData( const char *operation, int entindex, datamap_t *dmap );
private:
void TransferData_R( int chaincount, datamap_t *dmap );
void DetermineWatchField( const char *operation, int entindex, datamap_t *dmap );
void DumpWatchField( typedescription_t *field );
void WatchMsg( const char *fmt, ... );
difftype_t CompareShort( short *outvalue, const short *invalue, int count );
difftype_t CompareInt( int *outvalue, const int *invalue, int count ); // Compare an int
difftype_t CompareBool( bool *outvalue, const bool *invalue, int count ); // Compare a bool
difftype_t CompareFloat( float *outvalue, const float *invalue, int count ); // Compare a float
difftype_t CompareData( int size, char *outdata, const char *indata ); // Compare a binary data block
difftype_t CompareString( char *outstring, const char *instring ); // Compare a null-terminated string
difftype_t CompareVector( Vector& outValue, const Vector &inValue ); // Compare a vector
difftype_t CompareVector( Vector* outValue, const Vector *inValue, int count ); // Compare a vector array
difftype_t CompareQuaternion( Quaternion& outValue, const Quaternion &inValue ); // Compare a Quaternion
difftype_t CompareQuaternion( Quaternion* outValue, const Quaternion *inValue, int count ); // Compare a Quaternion array
difftype_t CompareEHandle( EHANDLE *outvalue, EHANDLE const *invalue, int count );
void DescribeShort( difftype_t dt, short *outvalue, const short *invalue, int count );
void DescribeInt( difftype_t dt, int *outvalue, const int *invalue, int count ); // Compare an int
void DescribeBool( difftype_t dt, bool *outvalue, const bool *invalue, int count ); // Compare a bool
void DescribeFloat( difftype_t dt, float *outvalue, const float *invalue, int count ); // Compare a float
void DescribeData( difftype_t dt, int size, char *outdata, const char *indata ); // Compare a binary data block
void DescribeString( difftype_t dt, char *outstring, const char *instring ); // Compare a null-terminated string
void DescribeVector( difftype_t dt, Vector& outValue, const Vector &inValue ); // Compare a vector
void DescribeVector( difftype_t dt, Vector* outValue, const Vector *inValue, int count ); // Compare a vector array
void DescribeQuaternion( difftype_t dt, Quaternion& outValue, const Quaternion &inValue ); // Compare a Quaternion
void DescribeQuaternion( difftype_t dt, Quaternion* outValue, const Quaternion *inValue, int count ); // Compare a Quaternion array
void DescribeEHandle( difftype_t dt, EHANDLE *outvalue, EHANDLE const *invalue, int count );
void WatchShort( difftype_t dt, short *outvalue, const short *invalue, int count );
void WatchInt( difftype_t dt, int *outvalue, const int *invalue, int count ); // Compare an int
void WatchBool( difftype_t dt, bool *outvalue, const bool *invalue, int count ); // Compare a bool
void WatchFloat( difftype_t dt, float *outvalue, const float *invalue, int count ); // Compare a float
void WatchData( difftype_t dt, int size, char *outdata, const char *indata ); // Compare a binary data block
void WatchString( difftype_t dt, char *outstring, const char *instring ); // Compare a null-terminated string
void WatchVector( difftype_t dt, Vector& outValue, const Vector &inValue ); // Compare a vector
void WatchVector( difftype_t dt, Vector* outValue, const Vector *inValue, int count ); // Compare a vector array
void WatchQuaternion( difftype_t dt, Quaternion& outValue, const Quaternion &inValue ); // Compare a Quaternion
void WatchQuaternion( difftype_t dt, Quaternion* outValue, const Quaternion *inValue, int count ); // Compare a Quaternion array
void WatchEHandle( difftype_t dt, EHANDLE *outvalue, EHANDLE const *invalue, int count );
// Report function
void ReportFieldsDiffer( const char *fmt, ... );
void DescribeFields( difftype_t dt, const char *fmt, ... );
bool CanCheck( void );
void CopyFields( int chaincount, datamap_t *pMap, typedescription_t *pFields, int fieldCount );
private:
int m_nType;
void *m_pDest;
void const *m_pSrc;
int m_nDestOffsetIndex;
int m_nSrcOffsetIndex;
bool m_bErrorCheck;
bool m_bReportErrors;
bool m_bDescribeFields;
typedescription_t *m_pCurrentField;
char const *m_pCurrentClassName;
datamap_t *m_pCurrentMap;
bool m_bShouldReport;
bool m_bShouldDescribe;
int m_nErrorCount;
bool m_bPerformCopy;
FN_FIELD_COMPARE m_FieldCompareFunc;
typedescription_t *m_pWatchField;
char const *m_pOperation;
};
typedef void (*FN_FIELD_DESCRIPTION)( const char *classname, const char *fieldname, const char *fieldtype,
bool networked, const char *value );
//-----------------------------------------------------------------------------
// Purpose: Simply dumps all data fields in object
//-----------------------------------------------------------------------------
class CPredictionDescribeData
{
public:
CPredictionDescribeData( void const *src, bool src_packed, FN_FIELD_DESCRIPTION func = 0 );
void DescribeShort( const short *invalue, int count );
void DescribeInt( const int *invalue, int count );
void DescribeBool( const bool *invalue, int count );
void DescribeFloat( const float *invalue, int count );
void DescribeData( int size, const char *indata );
void DescribeString( const char *instring );
void DescribeVector( const Vector &inValue );
void DescribeVector( const Vector *inValue, int count );
void DescribeQuaternion( const Quaternion &inValue );
void DescribeQuaternion( const Quaternion *inValue, int count );
void DescribeEHandle( EHANDLE const *invalue, int count );
void DumpDescription( datamap_t *pMap );
private:
void DescribeFields_R( int chain_count, datamap_t *pMap, typedescription_t *pFields, int fieldCount );
void const *m_pSrc;
int m_nSrcOffsetIndex;
void Describe( const char *fmt, ... );
typedescription_t *m_pCurrentField;
char const *m_pCurrentClassName;
datamap_t *m_pCurrentMap;
bool m_bShouldReport;
FN_FIELD_DESCRIPTION m_FieldDescFunc;
};
#if defined( CLIENT_DLL )
class CValueChangeTracker
{
public:
CValueChangeTracker();
void Reset();
void StartTrack( char const *pchContext );
void EndTrack();
bool IsActive() const;
void SetupTracking( C_BaseEntity *ent, char const *pchFieldName );
void ClearTracking();
void Spew();
C_BaseEntity *GetEntity();
private:
enum
{
eChangeTrackerBufSize = 128,
};
// Returns field size
void GetValue( char *buf, size_t bufsize );
bool m_bActive : 1;
bool m_bTracking : 1;
EHANDLE m_hEntityToTrack;
CUtlVector< typedescription_t * > m_FieldStack;
CUtlString m_strFieldName;
CUtlString m_strContext;
// First 128 bytes of data is all we will consider
char m_OrigValueBuf[ eChangeTrackerBufSize ];
CUtlVector< CUtlString > m_History;
};
extern CValueChangeTracker *g_pChangeTracker;
class CValueChangeTrackerScope
{
public:
CValueChangeTrackerScope( char const *pchContext )
{
m_bCallEndTrack = true;
g_pChangeTracker->StartTrack( pchContext );
}
// Only calls Start/End if passed in entity matches entity to track
CValueChangeTrackerScope( C_BaseEntity *pEntity, char const *pchContext )
{
m_bCallEndTrack = g_pChangeTracker->GetEntity() == pEntity;
if ( m_bCallEndTrack )
{
g_pChangeTracker->StartTrack( pchContext );
}
}
~CValueChangeTrackerScope()
{
if ( m_bCallEndTrack )
{
g_pChangeTracker->EndTrack();
}
}
private:
bool m_bCallEndTrack;
};
#if defined( _DEBUG )
#define PREDICTION_TRACKVALUECHANGESCOPE( context ) CValueChangeTrackerScope scope( context );
#define PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( entity, context ) CValueChangeTrackerScope scope( entity, context );
#define PREDICTION_STARTTRACKVALUE( context ) g_pChangeTracker->StartTrack( context );
#define PREDICTION_ENDTRACKVALUE() g_pChangeTracker->EndTrack();
#define PREDICTION_SPEWVALUECHANGES() g_pChangeTracker->Spew();
#else
#define PREDICTION_TRACKVALUECHANGESCOPE( context )
#define PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( entity, context )
#define PREDICTION_STARTTRACKVALUE( context )
#define PREDICTION_ENDTRACKVALUE()
#define PREDICTION_SPEWVALUECHANGES()
#endif
#endif // !CLIENT_DLL
#endif // PREDICTIONCOPY_H
| 0 | 0.920399 | 1 | 0.920399 | game-dev | MEDIA | 0.436939 | game-dev | 0.638797 | 1 | 0.638797 |
iPortalTeam/ImmersivePortalsMod | 3,965 | src/main/java/qouteall/imm_ptl/core/mixin/client/interaction/MixinMinecraft_B.java | package qouteall.imm_ptl.core.mixin.client.interaction;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.world.phys.HitResult;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import qouteall.imm_ptl.core.ClientWorldLoader;
import qouteall.imm_ptl.core.block_manipulation.BlockManipulationClient;
@Mixin(Minecraft.class)
public abstract class MixinMinecraft_B {
@Shadow
protected abstract void pickBlock();
@Shadow
public ClientLevel level;
@Shadow
public HitResult hitResult;
@Shadow
protected int missTime;
@Shadow
protected abstract boolean startAttack();
@Shadow
protected abstract void continueAttack(boolean leftClick);
@Shadow
protected abstract void startUseItem();
@WrapOperation(
method = "handleKeybinds",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/Minecraft;startAttack()Z"
)
)
private boolean wrapStartAttack(Minecraft instance, Operation<Boolean> original) {
ClientLevel remoteWorld = BlockManipulationClient.getRemotePointedWorld();
if (BlockManipulationClient.isPointingToPortal()) {
BlockManipulationClient.withSwitchedContext(
() -> original.call(instance),
false
);
return false;
}
else {
return original.call(instance);
}
}
@WrapOperation(
method = "handleKeybinds",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/Minecraft;continueAttack(Z)V"
)
)
private void wrapContinueAttack(Minecraft instance, boolean leftClick, Operation<Void> original) {
if (BlockManipulationClient.isPointingToPortal()) {
BlockManipulationClient.withSwitchedContext(
() -> {
original.call(instance, leftClick);
return null;
},
false
);
}
else {
original.call(instance, leftClick);
}
}
@WrapOperation(
method = "handleKeybinds",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/Minecraft;startUseItem()V"
)
)
private void wrapStartUseItem(Minecraft instance, Operation<Void> original) {
if (BlockManipulationClient.isPointingToPortal()) {
BlockManipulationClient.withSwitchedContext(
() -> {
original.call(instance);
return null;
},
true
);
}
else {
original.call(instance);
}
}
@WrapOperation(
method = "handleKeybinds",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/Minecraft;pickBlock()V"
)
)
private void wrapPickBlock(Minecraft instance, Operation<Void> original) {
if (BlockManipulationClient.isPointingToPortal()) {
ClientLevel remoteWorld = ClientWorldLoader.getWorld(BlockManipulationClient.remotePointedDim);
ClientLevel oldWorld = this.level;
HitResult oldTarget = this.hitResult;
level = remoteWorld;
hitResult = BlockManipulationClient.remoteHitResult;
try {
original.call(instance);
}
finally {
level = oldWorld;
hitResult = oldTarget;
}
}
else {
original.call(instance);
}
}
}
| 0 | 0.941654 | 1 | 0.941654 | game-dev | MEDIA | 0.984379 | game-dev | 0.89672 | 1 | 0.89672 |
dcs-liberation/dcs_liberation | 19,859 | game/theater/start_generator.py | from __future__ import annotations
import logging
import random
from dataclasses import dataclass, fields
from datetime import datetime, time
from pathlib import Path
from typing import List
import dcs.statics
import yaml
from game import Game
from game.factions.faction import Faction
from game.naming import namegen
from game.scenery_group import SceneryGroup
from game.theater import PointWithHeading, PresetLocation
from game.theater.theatergroundobject import (
BuildingGroundObject,
IadsBuildingGroundObject,
)
from game.utils import Heading, escape_string_for_lua
from game.version import VERSION
from . import (
ConflictTheater,
ControlPoint,
ControlPointType,
Fob,
OffMapSpawn,
)
from .theatergroup import IadsGroundGroup, IadsRole, SceneryUnit, TheaterGroup
from ..armedforces.armedforces import ArmedForces
from ..armedforces.forcegroup import ForceGroup
from ..campaignloader.campaignairwingconfig import CampaignAirWingConfig
from ..data.groups import GroupTask
from ..persistence.paths import liberation_user_dir
from ..plugins import LuaPluginManager
from ..profiling import logged_duration
from ..settings import Settings
@dataclass(frozen=True)
class GeneratorSettings:
start_date: datetime
start_time: time | None
player_budget: int
enemy_budget: int
inverted: bool
advanced_iads: bool
no_carrier: bool
no_lha: bool
no_player_navy: bool
no_enemy_navy: bool
@dataclass
class ModSettings:
a4_skyhawk: bool = False
f22_raptor: bool = False
f104_starfighter: bool = False
f4_phantom: bool = False
hercules: bool = False
uh_60l: bool = False
jas39_gripen: bool = False
su57_felon: bool = False
frenchpack: bool = False
high_digit_sams: bool = False
ov10a_bronco: bool = False
fa18efg: bool = False
def save_player_settings(self) -> None:
"""Saves the player's global settings to the user directory."""
settings: dict[str, dict[str, bool]] = {}
for field in fields(self):
settings[field.name] = self.__dict__[field.name]
with self._player_settings_file.open("w", encoding="utf-8") as settings_file:
yaml.dump(settings, settings_file, sort_keys=False, explicit_start=True)
def merge_player_settings(self) -> None:
"""Updates with the player's global settings."""
settings_path = self._player_settings_file
if not settings_path.exists():
return
with settings_path.open(encoding="utf-8") as settings_file:
data = yaml.safe_load(settings_file)
for mod_name, enabled in data.items():
if mod_name not in self.__dict__:
logging.warning(
"Unexpected mod key found in %s: %s. Ignoring.",
settings_path,
mod_name,
)
continue
self.__dict__[mod_name] = enabled
@property
def _player_settings_file(self) -> Path:
"""Returns the path to the player's global settings file."""
return liberation_user_dir() / "mods.yaml"
class GameGenerator:
def __init__(
self,
player: Faction,
enemy: Faction,
theater: ConflictTheater,
air_wing_config: CampaignAirWingConfig,
settings: Settings,
generator_settings: GeneratorSettings,
mod_settings: ModSettings,
lua_plugin_manager: LuaPluginManager,
) -> None:
self.player = player
self.enemy = enemy
self.theater = theater
self.air_wing_config = air_wing_config
self.settings = settings
self.generator_settings = generator_settings
self.player.apply_mod_settings(mod_settings)
self.enemy.apply_mod_settings(mod_settings)
self.lua_plugin_manager = lua_plugin_manager
def generate(self) -> Game:
with logged_duration("TGO population"):
# Reset name generator
namegen.reset()
self.prepare_theater()
game = Game(
player_faction=self.player,
enemy_faction=self.enemy,
theater=self.theater,
air_wing_config=self.air_wing_config,
start_date=self.generator_settings.start_date,
start_time=self.generator_settings.start_time,
settings=self.settings,
lua_plugin_manager=self.lua_plugin_manager,
player_budget=self.generator_settings.player_budget,
enemy_budget=self.generator_settings.enemy_budget,
)
GroundObjectGenerator(game, self.generator_settings).generate()
game.settings.version = VERSION
return game
def should_remove_carrier(self, player: bool) -> bool:
faction = self.player if player else self.enemy
return self.generator_settings.no_carrier or not faction.carrier_names
def should_remove_lha(self, player: bool) -> bool:
faction = self.player if player else self.enemy
return self.generator_settings.no_lha or not faction.helicopter_carrier_names
def prepare_theater(self) -> None:
to_remove: List[ControlPoint] = []
# Remove carrier and lha, invert situation if needed
for cp in self.theater.controlpoints:
if self.generator_settings.inverted:
cp.starts_blue = cp.captured_invert
if cp.is_carrier and self.should_remove_carrier(cp.starts_blue):
to_remove.append(cp)
elif cp.is_lha and self.should_remove_lha(cp.starts_blue):
to_remove.append(cp)
# do remove
for cp in to_remove:
self.theater.controlpoints.remove(cp)
class ControlPointGroundObjectGenerator:
def __init__(
self,
game: Game,
generator_settings: GeneratorSettings,
control_point: ControlPoint,
) -> None:
self.game = game
self.generator_settings = generator_settings
self.control_point = control_point
@property
def faction_name(self) -> str:
return self.faction.name
@property
def faction(self) -> Faction:
return self.game.coalition_for(self.control_point.captured).faction
@property
def armed_forces(self) -> ArmedForces:
return self.game.coalition_for(self.control_point.captured).armed_forces
def generate(self) -> bool:
self.control_point.connected_objectives = []
self.generate_navy()
return True
def generate_ground_object_from_group(
self, unit_group: ForceGroup, location: PresetLocation
) -> None:
ground_object = unit_group.generate(
namegen.random_objective_name(),
location,
self.control_point,
self.game,
)
self.control_point.connected_objectives.append(ground_object)
def generate_navy(self) -> None:
skip_player_navy = self.generator_settings.no_player_navy
if self.control_point.captured and skip_player_navy:
return
skip_enemy_navy = self.generator_settings.no_enemy_navy
if not self.control_point.captured and skip_enemy_navy:
return
for position in self.control_point.preset_locations.ships:
unit_group = self.armed_forces.random_group_for_task(GroupTask.NAVY)
if not unit_group:
logging.warning(f"{self.faction_name} has no ForceGroup for Navy")
return
self.generate_ground_object_from_group(unit_group, position)
class NoOpGroundObjectGenerator(ControlPointGroundObjectGenerator):
def generate(self) -> bool:
return True
class GenericCarrierGroundObjectGenerator(ControlPointGroundObjectGenerator):
def update_carrier_name(self, carrier_name: str) -> None:
# Set Control Point name
self.control_point.name = carrier_name
# Set UnitName. First unit of the TGO is always the carrier
carrier = next(self.control_point.ground_objects[-1].units)
carrier.name = carrier_name
class CarrierGroundObjectGenerator(GenericCarrierGroundObjectGenerator):
def generate(self) -> bool:
if not super().generate():
return False
carrier_names = self.faction.carrier_names
if not carrier_names:
logging.info(
f"Skipping generation of {self.control_point.name} because "
f"{self.faction_name} has no carriers"
)
return False
unit_group = self.armed_forces.random_group_for_task(GroupTask.AIRCRAFT_CARRIER)
if not unit_group:
logging.error(f"{self.faction_name} has no access to AircraftCarrier")
return False
self.generate_ground_object_from_group(
unit_group,
PresetLocation(
self.control_point.name,
self.control_point.position,
self.control_point.heading,
),
)
self.update_carrier_name(random.choice(carrier_names))
return True
class LhaGroundObjectGenerator(GenericCarrierGroundObjectGenerator):
def generate(self) -> bool:
if not super().generate():
return False
lha_names = self.faction.helicopter_carrier_names
if not lha_names:
logging.info(
f"Skipping generation of {self.control_point.name} because "
f"{self.faction_name} has no LHAs"
)
return False
unit_group = self.armed_forces.random_group_for_task(
GroupTask.HELICOPTER_CARRIER
)
if not unit_group:
logging.error(f"{self.faction_name} has no access to HelicopterCarrier")
return False
self.generate_ground_object_from_group(
unit_group,
PresetLocation(
self.control_point.name,
self.control_point.position,
self.control_point.heading,
),
)
self.update_carrier_name(random.choice(lha_names))
return True
class AirbaseGroundObjectGenerator(ControlPointGroundObjectGenerator):
def __init__(
self,
game: Game,
generator_settings: GeneratorSettings,
control_point: ControlPoint,
) -> None:
super().__init__(game, generator_settings, control_point)
def generate(self) -> bool:
if not super().generate():
return False
self.generate_ground_points()
return True
def generate_ground_points(self) -> None:
"""Generate ground objects and AA sites for the control point."""
self.generate_armor_groups()
self.generate_iads()
self.generate_scenery_sites()
self.generate_strike_targets()
self.generate_offshore_strike_targets()
self.generate_factories()
self.generate_ammunition_depots()
self.generate_missile_sites()
self.generate_coastal_sites()
def generate_armor_groups(self) -> None:
for position in self.control_point.preset_locations.armor_groups:
unit_group = self.armed_forces.random_group_for_task(GroupTask.BASE_DEFENSE)
if not unit_group:
logging.error(f"{self.faction_name} has no ForceGroup for Armor")
return
self.generate_ground_object_from_group(unit_group, position)
def generate_aa(self) -> None:
presets = self.control_point.preset_locations
aa_tasking = [GroupTask.AAA]
for position in presets.aaa:
self.generate_aa_at(position, aa_tasking)
aa_tasking.insert(0, GroupTask.SHORAD)
for position in presets.short_range_sams:
self.generate_aa_at(position, aa_tasking)
aa_tasking.insert(0, GroupTask.MERAD)
for position in presets.medium_range_sams:
self.generate_aa_at(position, aa_tasking)
aa_tasking.insert(0, GroupTask.LORAD)
for position in presets.long_range_sams:
self.generate_aa_at(position, aa_tasking)
def generate_ewrs(self) -> None:
for position in self.control_point.preset_locations.ewrs:
unit_group = self.armed_forces.random_group_for_task(
GroupTask.EARLY_WARNING_RADAR
)
if not unit_group:
logging.error(f"{self.faction_name} has no ForceGroup for EWR")
return
self.generate_ground_object_from_group(unit_group, position)
def generate_building_at(
self,
group_task: GroupTask,
location: PresetLocation,
) -> None:
# GroupTask is the type of the building to be generated
unit_group = self.armed_forces.random_group_for_task(group_task)
if not unit_group:
raise RuntimeError(
f"{self.faction_name} has no access to Building {group_task.description}"
)
self.generate_ground_object_from_group(unit_group, location)
def generate_ammunition_depots(self) -> None:
for position in self.control_point.preset_locations.ammunition_depots:
self.generate_building_at(GroupTask.AMMO, position)
def generate_factories(self) -> None:
for position in self.control_point.preset_locations.factories:
self.generate_building_at(GroupTask.FACTORY, position)
def generate_aa_at(self, location: PresetLocation, tasks: list[GroupTask]) -> None:
for task in tasks:
unit_group = self.armed_forces.random_group_for_task(task)
if unit_group:
# Only take next (smaller) aa_range when no template available for the
# most requested range. Otherwise break the loop and continue
self.generate_ground_object_from_group(unit_group, location)
return
logging.error(
f"{self.faction_name} has no access to SAM {', '.join([task.description for task in tasks])}"
)
def generate_iads(self) -> None:
# AntiAir
self.generate_aa()
# EWR
self.generate_ewrs()
# IADS Buildings
for iads_element in self.control_point.preset_locations.iads_command_center:
self.generate_building_at(GroupTask.COMMAND_CENTER, iads_element)
for iads_element in self.control_point.preset_locations.iads_connection_node:
self.generate_building_at(GroupTask.COMMS, iads_element)
for iads_element in self.control_point.preset_locations.iads_power_source:
self.generate_building_at(GroupTask.POWER, iads_element)
def generate_scenery_sites(self) -> None:
presets = self.control_point.preset_locations
for scenery_group in presets.scenery:
self.generate_tgo_for_scenery(scenery_group)
def generate_tgo_for_scenery(self, scenery: SceneryGroup) -> None:
# Special Handling for scenery Objects based on trigger zones
iads_role = IadsRole.for_category(scenery.category)
tgo_type = (
IadsBuildingGroundObject if iads_role.participate else BuildingGroundObject
)
g = tgo_type(
namegen.random_objective_name(),
scenery.category,
PresetLocation(scenery.name, scenery.centroid),
self.control_point,
)
ground_group = TheaterGroup(
self.game.next_group_id(),
scenery.name,
PointWithHeading.from_point(scenery.centroid, Heading.from_degrees(0)),
[],
g,
)
if iads_role.participate:
ground_group = IadsGroundGroup.from_group(ground_group)
ground_group.iads_role = iads_role
g.groups.append(ground_group)
# Each nested trigger zone is a target/building/unit for an objective.
for zone in scenery.target_zones:
zone.name = escape_string_for_lua(zone.name)
scenery_unit = SceneryUnit(
zone.id,
zone.name,
dcs.statics.Fortification.White_Flag,
PointWithHeading.from_point(zone.position, Heading.from_degrees(0)),
g,
)
scenery_unit.zone = zone
ground_group.units.append(scenery_unit)
self.control_point.connected_objectives.append(g)
def generate_missile_sites(self) -> None:
for position in self.control_point.preset_locations.missile_sites:
unit_group = self.armed_forces.random_group_for_task(GroupTask.MISSILE)
if not unit_group:
logging.warning(f"{self.faction_name} has no ForceGroup for Missile")
return
self.generate_ground_object_from_group(unit_group, position)
def generate_coastal_sites(self) -> None:
for position in self.control_point.preset_locations.coastal_defenses:
unit_group = self.armed_forces.random_group_for_task(GroupTask.COASTAL)
if not unit_group:
logging.warning(f"{self.faction_name} has no ForceGroup for Coastal")
return
self.generate_ground_object_from_group(unit_group, position)
def generate_strike_targets(self) -> None:
for position in self.control_point.preset_locations.strike_locations:
self.generate_building_at(GroupTask.STRIKE_TARGET, position)
def generate_offshore_strike_targets(self) -> None:
for position in self.control_point.preset_locations.offshore_strike_locations:
self.generate_building_at(GroupTask.OIL, position)
class FobGroundObjectGenerator(AirbaseGroundObjectGenerator):
def generate(self) -> bool:
if super(FobGroundObjectGenerator, self).generate():
self.generate_fob()
return True
return False
def generate_fob(self) -> None:
self.generate_building_at(
GroupTask.FOB,
PresetLocation(
self.control_point.name,
self.control_point.position,
self.control_point.heading,
),
)
class GroundObjectGenerator:
def __init__(self, game: Game, generator_settings: GeneratorSettings) -> None:
self.game = game
self.generator_settings = generator_settings
def generate(self) -> None:
# Copied so we can remove items from the original list without breaking
# the iterator.
control_points = list(self.game.theater.controlpoints)
for control_point in control_points:
if not self.generate_for_control_point(control_point):
self.game.theater.controlpoints.remove(control_point)
def generate_for_control_point(self, control_point: ControlPoint) -> bool:
generator: ControlPointGroundObjectGenerator
if control_point.cptype == ControlPointType.AIRCRAFT_CARRIER_GROUP:
generator = CarrierGroundObjectGenerator(
self.game, self.generator_settings, control_point
)
elif control_point.cptype == ControlPointType.LHA_GROUP:
generator = LhaGroundObjectGenerator(
self.game, self.generator_settings, control_point
)
elif isinstance(control_point, OffMapSpawn):
generator = NoOpGroundObjectGenerator(
self.game, self.generator_settings, control_point
)
elif isinstance(control_point, Fob):
generator = FobGroundObjectGenerator(
self.game, self.generator_settings, control_point
)
else:
generator = AirbaseGroundObjectGenerator(
self.game, self.generator_settings, control_point
)
return generator.generate()
| 0 | 0.849306 | 1 | 0.849306 | game-dev | MEDIA | 0.473325 | game-dev | 0.985993 | 1 | 0.985993 |
EIRTeam/Project-Heartbeat | 9,340 | menus/BackgroundMusicPlayer.gd | extends Node
class_name HBBackgroundMusicPlayer
signal stream_time_changed
signal song_started(song)
var song_idx = 0
class SongPlayer:
extends Node
const FADE_IN_VOLUME = -70
var audio_playback: ShinobuSoundPlayer
var voice_audio_playback: ShinobuSoundPlayer
var song: HBSong
signal song_assets_loaded(assets)
signal song_ended()
signal stream_time_changed(time)
var target_volume := 0.0
var volume_offset := 0.0
var has_audio_normalization_data = false
var song_idx = 0
var voice_remap: ShinobuChannelRemapEffect
var audio_remap: ShinobuChannelRemapEffect
var has_assets := false
func _get_song_user_volume(song: HBSong, variant := -1, loudness_offset := 0.0) -> float:
var volume_offset := loudness_offset
var base_volume := song.get_volume_db()
var out_volume := 0.0
if song.id in UserSettings.user_settings.per_song_settings:
var user_song_settings = UserSettings.user_settings.per_song_settings[song.id] as HBPerSongSettings
if variant != -1:
volume_offset = song.get_variant_data(variant).get_volume()
out_volume = db_to_linear(base_volume + volume_offset) * user_song_settings.volume
else:
out_volume = db_to_linear(base_volume + volume_offset)
return out_volume
func load_song_assets():
if not song.has_audio() or not song.is_cached():
return ERR_FILE_NOT_FOUND
var assets_to_load: Array[SongAssetLoader.ASSET_TYPES] = [
SongAssetLoader.ASSET_TYPES.AUDIO,
SongAssetLoader.ASSET_TYPES.VOICE,
SongAssetLoader.ASSET_TYPES.PREVIEW,
SongAssetLoader.ASSET_TYPES.BACKGROUND
]
if not song.has_audio_loudness and not SongDataCache.is_song_audio_loudness_cached(song):
assets_to_load.append(SongAssetLoader.ASSET_TYPES.AUDIO_LOUDNESS)
var token := SongAssetLoader.request_asset_load(song, assets_to_load)
token.assets_loaded.connect(_on_song_assets_loaded)
emit_signal("stream_time_changed", song.preview_start / 1000.0)
return OK
func _init(_song: HBSong, _song_idx: int):
song = _song
song_idx = _song_idx
func _ready():
set_process(false)
func pause():
audio_playback.stop()
if voice_audio_playback:
voice_audio_playback.stop()
func resume():
audio_playback.start()
if voice_audio_playback:
voice_audio_playback.start()
func _process(_delta):
if audio_playback:
emit_signal("stream_time_changed", audio_playback.get_playback_position_msec() / 1000.0)
var end_time = audio_playback.get_length_msec()
if song.preview_end != -1:
end_time = song.preview_end
if audio_playback.get_playback_position_msec() >= end_time or audio_playback.is_at_stream_end():
fade_out()
emit_signal("song_ended")
func get_song_audio_name():
return "%s_%d" % [str(song.id), song_idx]
func get_song_voice_audio_name():
return "voice_%s_%d" % [str(song.id), song_idx]
func _on_song_assets_loaded(token: SongAssetLoader.AssetLoadToken):
has_assets = true
var audio: SongAssetLoader.SongAudioData = token.get_asset(SongAssetLoader.ASSET_TYPES.AUDIO)
var voice: SongAssetLoader.SongAudioData = token.get_asset(SongAssetLoader.ASSET_TYPES.VOICE)
var audio_loudness: SongAssetLoader.AudioNormalizationInfo = token.get_asset(SongAssetLoader.ASSET_TYPES.AUDIO_LOUDNESS)
if audio and audio.shinobu:
if song.has_audio_loudness or SongDataCache.is_song_audio_loudness_cached(song):
var song_loudness = 0.0
has_audio_normalization_data = true
if SongDataCache.is_song_audio_loudness_cached(song):
song_loudness = SongDataCache.audio_normalization_cache[song.id].loudness
else:
song_loudness = song.audio_loudness
volume_offset = HBAudioNormalizer.get_offset_from_loudness(song_loudness)
elif audio_loudness:
volume_offset = HBAudioNormalizer.get_offset_from_loudness(audio_loudness.loudness)
target_volume = _get_song_user_volume(song, -1, volume_offset)
var song_audio_name = get_song_audio_name()
var sound_source := audio.shinobu
audio_playback = sound_source.instantiate(HBGame.menu_music_group, song.uses_dsc_style_channels())
var use_source_channel_count := song.uses_dsc_style_channels() and audio_playback.get_channel_count() >= 4
if song.uses_dsc_style_channels() and not use_source_channel_count:
audio_playback.queue_free()
audio_playback = sound_source.instantiate(HBGame.menu_music_group)
add_child(audio_playback)
audio_playback.seek(song.preview_start)
# Scheduling starts prevents crackles
audio_playback.schedule_start_time(Shinobu.get_dsp_time())
#audio_playback.connect_sound_to_effect(HBGame.spectrum_analyzer)
if voice and voice.shinobu:
var song_voice_audio_name = get_song_voice_audio_name()
var voice_source := voice.shinobu
voice_audio_playback = voice_source.instantiate(HBGame.menu_music_group, use_source_channel_count)
voice_audio_playback.seek(song.preview_start)
voice_audio_playback.schedule_start_time(Shinobu.get_dsp_time())
voice_audio_playback.start()
add_child(voice_audio_playback)
if song.uses_dsc_style_channels() and audio_playback.get_channel_count() >= 4:
if voice_audio_playback:
voice_remap = Shinobu.instantiate_channel_remap(voice_audio_playback.get_channel_count(), 2)
voice_remap.set_weight(2, 0, 1.0)
voice_remap.set_weight(3, 1, 1.0)
voice_remap.connect_to_group(HBGame.menu_music_group)
voice_audio_playback.connect_sound_to_effect(voice_remap)
audio_remap = Shinobu.instantiate_channel_remap(audio_playback.get_channel_count(), 2)
audio_remap.set_weight(0, 0, 1.0)
audio_remap.set_weight(1, 1, 1.0)
audio_remap.connect_to_group(HBGame.menu_music_group)
audio_playback.connect_sound_to_effect(audio_remap)
if audio_playback:
# WARNING: DO NOT SET THE VOLUME FOR THE BACKGORUND MUSIC PLAYER's AUDIO PLAYBACK NODES
# OR YOU WILL BE KILLED, AUDIO FADING IS INDEPENDENT FROM VOLUME SO IF YOU DO THAT IT WILL GET
# EXPONENTIALLY BOOSTED, KEEP IT AT 1.0 PLEASE
audio_playback.fade(500, 0.0, target_volume)
audio_playback.start()
if voice_audio_playback:
voice_audio_playback.fade(500, 0.0, target_volume)
voice_audio_playback.start()
emit_signal("song_assets_loaded")
set_process(true)
func notify_song_volume_settings_changed():
# We are fading out already, do nothing..
if not is_processing():
return
target_volume = _get_song_user_volume(song, -1, volume_offset)
if voice_audio_playback:
voice_audio_playback.fade(200, -1.0, target_volume)
if audio_playback:
audio_playback.fade(200, -1.0, target_volume)
func fade_out():
set_process(false) # nothing else should fire while fading out...
if audio_playback:
audio_playback.fade(500, target_volume, 0.0)
if voice_audio_playback:
voice_audio_playback.fade(500, target_volume, 0.0)
var timer := get_tree().create_timer(0.5, false)
timer.timeout.connect(self.queue_free)
var current_song_player: SongPlayer
func play_song(song: HBSong):
# if not song.has_audio_loudness and not SongDataCache.is_song_audio_loudness_cached(song):
# return
if current_song_player:
if song == current_song_player.song:
return
var song_player = SongPlayer.new(song, song_idx)
song_idx += 1
add_child(song_player)
song_player.connect("song_assets_loaded", Callable(self, "_on_song_assets_loaded"))
song_player.connect("stream_time_changed", Callable(self, "_on_stream_time_changed"))
song_player.connect("song_ended", Callable(self, "_on_song_ended"))
if song_player.load_song_assets() == OK:
if current_song_player:
current_song_player.disconnect("song_assets_loaded", Callable(self, "_on_song_assets_loaded"))
current_song_player.disconnect("stream_time_changed", Callable(self, "_on_stream_time_changed"))
if not current_song_player.has_assets:
current_song_player.queue_free()
else:
current_song_player.fade_out()
current_song_player = song_player
else:
song_player.queue_free()
func _on_stream_time_changed(time: float):
emit_signal("stream_time_changed", time)
func _on_song_ended():
play_random_song()
func _on_song_assets_loaded():
emit_signal("song_started")
func _input(event: InputEvent) -> void:
if event is InputEventKey and event.is_pressed() and not event.is_echo():
if event.keycode == KEY_F9:
play_random_song()
func play_random_song():
if SongLoader.songs.size() == 0:
return
randomize()
var found_song: HBSong
var attempts := 0
const MAX_ATTEMPTS := 40
while not found_song and attempts < MAX_ATTEMPTS:
var song := SongLoader.songs.values()[randi() % SongLoader.songs.size()] as HBSong
var is_current_song = false
if current_song_player:
is_current_song = current_song_player.song == song
if song.has_audio() and song.is_cached() and \
(song.has_audio_loudness or SongDataCache.is_song_audio_loudness_cached(song)) and \
not is_current_song:
found_song = song
attempts += 1
if found_song:
play_song(found_song)
func pause():
current_song_player.pause()
func resume():
current_song_player.resume()
func notify_song_volume_settings_changed(song: HBSong):
if current_song_player.song == song:
current_song_player.notify_song_volume_settings_changed()
func get_current_song_length() -> float:
if current_song_player.audio_playback:
return current_song_player.audio_playback.get_length_msec() * 0.001
return -1.0
| 0 | 0.588232 | 1 | 0.588232 | game-dev | MEDIA | 0.630409 | game-dev,audio-video-media | 0.98922 | 1 | 0.98922 |
bibendovsky/bstone | 1,615 | src/bstone/src/bstone_saved_game.h | /*
BStone: Unofficial source port of Blake Stone: Aliens of Gold and Blake Stone: Planet Strike
Copyright (c) 2024 Boris I. Bendovsky (bibendovsky@hotmail.com) and Contributors
SPDX-License-Identifier: MIT
*/
// Saved game stuff.
#ifndef BSTONE_SAVED_GAME_INCLUDED
#define BSTONE_SAVED_GAME_INCLUDED
#include <cstddef>
#include <cstdint>
#include "bstone_memory_stream.h"
#include "bstone_stream.h"
#include "bstone_four_cc.h"
namespace bstone {
constexpr auto sg_version = 11;
struct SgKnownFourCc
{
static constexpr FourCc vers() { return FourCc{'V', 'E', 'R', 'S'}; }
static constexpr FourCc desc() { return FourCc{'D', 'E', 'S', 'C'}; }
static constexpr FourCc head() { return FourCc{'H', 'E', 'A', 'D'}; }
static constexpr FourCc lvxx() { return FourCc{'L', 'V', 'X', 'X'}; }
};
struct SgChunkHeader
{
public:
std::uint32_t id;
std::int32_t size;
public:
void serialize(Stream& stream) const;
void deserialize(Stream& stream);
};
static_assert(
sizeof(SgChunkHeader) == 8 &&
offsetof(SgChunkHeader, id) == 0 &&
offsetof(SgChunkHeader, size) == 4,
"Invalid SgChunkHeader type.");
constexpr auto sg_chunk_header_size = static_cast<int>(sizeof(SgChunkHeader));
FourCc sg_make_numbered_four_cc(char ch_0, char ch_1, int number);
FourCc sg_make_level_four_cc(int number);
FourCc sg_make_overlay_four_cc(int number);
// Returns a position of chunk's data nn success or zero otherwise.
int sg_find_chunk(bstone::FourCc four_cc, bstone::Stream& stream);
void sg_delete_chunk(bstone::FourCc four_cc, bstone::MemoryStream& stream);
} // namespace bstone
#endif // BSTONE_SAVED_GAME_INCLUDED
| 0 | 0.902462 | 1 | 0.902462 | game-dev | MEDIA | 0.521662 | game-dev | 0.946604 | 1 | 0.946604 |
AssetRipper/AssetRipper | 4,135 | Source/AssetRipper.AssemblyDumper/Passes/Pass201_GuidConversionOperators.cs | using AssetRipper.AssemblyDumper.Methods;
namespace AssetRipper.AssemblyDumper.Passes;
public static class Pass201_GuidConversionOperators
{
const MethodAttributes ConversionAttributes = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
public static void DoPass()
{
foreach (TypeDefinition type in SharedState.Instance.SubclassGroups["GUID"].Types)
{
AddImplicitConversion(type);
AddExplicitConversion(type);
}
}
private static void AddImplicitConversion(TypeDefinition guidType)
{
ITypeDefOrRef commonGuidType = SharedState.Instance.Importer.ImportType<UnityGuid>();
IMethodDefOrRef constructor = SharedState.Instance.Importer.ImportConstructor<UnityGuid>(4);
FieldDefinition data0 = guidType.Fields.Single(field => field.Name == "m_Data_0_");
FieldDefinition data1 = guidType.Fields.Single(field => field.Name == "m_Data_1_");
FieldDefinition data2 = guidType.Fields.Single(field => field.Name == "m_Data_2_");
FieldDefinition data3 = guidType.Fields.Single(field => field.Name == "m_Data_3_");
MethodDefinition implicitMethod = guidType.AddMethod("op_Implicit", ConversionAttributes, commonGuidType.ToTypeSignature());
implicitMethod.AddParameter(guidType.ToTypeSignature(), "value");
implicitMethod.CilMethodBody!.InitializeLocals = true;
CilInstructionCollection instructions = implicitMethod.CilMethodBody.Instructions;
instructions.Add(CilOpCodes.Ldarg_0);
instructions.Add(CilOpCodes.Ldfld, data0);
instructions.Add(CilOpCodes.Ldarg_0);
instructions.Add(CilOpCodes.Ldfld, data1);
instructions.Add(CilOpCodes.Ldarg_0);
instructions.Add(CilOpCodes.Ldfld, data2);
instructions.Add(CilOpCodes.Ldarg_0);
instructions.Add(CilOpCodes.Ldfld, data3);
instructions.Add(CilOpCodes.Newobj, constructor);
instructions.Add(CilOpCodes.Ret);
}
private static void AddExplicitConversion(TypeDefinition guidType)
{
ITypeDefOrRef commonGuidType = SharedState.Instance.Importer.ImportType<UnityGuid>();
IMethodDefOrRef constructor = guidType.Methods.Single(m => m.IsConstructor && m.Parameters.Count == 0 && !m.IsStatic);
FieldDefinition data0 = guidType.Fields.Single(field => field.Name == "m_Data_0_");
FieldDefinition data1 = guidType.Fields.Single(field => field.Name == "m_Data_1_");
FieldDefinition data2 = guidType.Fields.Single(field => field.Name == "m_Data_2_");
FieldDefinition data3 = guidType.Fields.Single(field => field.Name == "m_Data_3_");
IMethodDefOrRef getData0 = SharedState.Instance.Importer.ImportMethod<UnityGuid>(m => m.Name == $"get_{nameof(UnityGuid.Data0)}");
IMethodDefOrRef getData1 = SharedState.Instance.Importer.ImportMethod<UnityGuid>(m => m.Name == $"get_{nameof(UnityGuid.Data1)}");
IMethodDefOrRef getData2 = SharedState.Instance.Importer.ImportMethod<UnityGuid>(m => m.Name == $"get_{nameof(UnityGuid.Data2)}");
IMethodDefOrRef getData3 = SharedState.Instance.Importer.ImportMethod<UnityGuid>(m => m.Name == $"get_{nameof(UnityGuid.Data3)}");
MethodDefinition explicitMethod = guidType.AddMethod("op_Explicit", ConversionAttributes, guidType.ToTypeSignature());
Parameter parameter = explicitMethod.AddParameter(commonGuidType.ToTypeSignature(), "value");
CilInstructionCollection instructions = explicitMethod.CilMethodBody!.Instructions;
instructions.Add(CilOpCodes.Newobj, constructor);
instructions.Add(CilOpCodes.Dup);
instructions.Add(CilOpCodes.Ldarga, parameter);
instructions.Add(CilOpCodes.Call, getData0);
instructions.Add(CilOpCodes.Stfld, data0);
instructions.Add(CilOpCodes.Dup);
instructions.Add(CilOpCodes.Ldarga, parameter);
instructions.Add(CilOpCodes.Call, getData1);
instructions.Add(CilOpCodes.Stfld, data1);
instructions.Add(CilOpCodes.Dup);
instructions.Add(CilOpCodes.Ldarga, parameter);
instructions.Add(CilOpCodes.Call, getData2);
instructions.Add(CilOpCodes.Stfld, data2);
instructions.Add(CilOpCodes.Dup);
instructions.Add(CilOpCodes.Ldarga, parameter);
instructions.Add(CilOpCodes.Call, getData3);
instructions.Add(CilOpCodes.Stfld, data3);
instructions.Add(CilOpCodes.Ret);
}
}
| 0 | 0.917997 | 1 | 0.917997 | game-dev | MEDIA | 0.32095 | game-dev | 0.899696 | 1 | 0.899696 |
TaiyitistMC/Taiyitist | 2,599 | modules/taiyitist-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java | package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Guardian;
import org.bukkit.entity.LivingEntity;
public class CraftGuardian extends CraftMonster implements Guardian {
private static final int MINIMUM_ATTACK_TICKS = -10;
public CraftGuardian(CraftServer server, net.minecraft.world.entity.monster.Guardian entity) {
super(server, entity);
}
@Override
public net.minecraft.world.entity.monster.Guardian getHandle() {
return (net.minecraft.world.entity.monster.Guardian) super.getHandle();
}
@Override
public String toString() {
return "CraftGuardian";
}
@Override
public void setTarget(LivingEntity target) {
super.setTarget(target);
// clean up laser target, when target is removed
if (target == null) {
this.getHandle().setActiveAttackTarget(0);
}
}
@Override
public boolean setLaser(boolean activated) {
if (activated) {
LivingEntity target = this.getTarget();
if (target == null) {
return false;
}
this.getHandle().setActiveAttackTarget(target.getEntityId());
} else {
this.getHandle().setActiveAttackTarget(0);
}
return true;
}
@Override
public boolean hasLaser() {
return this.getHandle().hasActiveAttackTarget();
}
@Override
public int getLaserDuration() {
return this.getHandle().getAttackDuration();
}
@Override
public void setLaserTicks(int ticks) {
Preconditions.checkArgument(ticks >= CraftGuardian.MINIMUM_ATTACK_TICKS, "ticks must be >= %s. Given %s", CraftGuardian.MINIMUM_ATTACK_TICKS, ticks);
net.minecraft.world.entity.monster.Guardian.GuardianAttackGoal goal = this.getHandle().bridge$guardianAttackGoal();
if (goal != null) {
goal.attackTime = ticks;
}
}
@Override
public int getLaserTicks() {
net.minecraft.world.entity.monster.Guardian.GuardianAttackGoal goal = this.getHandle().bridge$guardianAttackGoal();
return (goal != null) ? goal.attackTime : CraftGuardian.MINIMUM_ATTACK_TICKS;
}
@Override
public boolean isElder() {
return false;
}
@Override
public void setElder(boolean shouldBeElder) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public boolean isMoving() {
return this.getHandle().isMoving();
}
}
| 0 | 0.867413 | 1 | 0.867413 | game-dev | MEDIA | 0.971135 | game-dev | 0.935386 | 1 | 0.935386 |
vayerx/shadowgrounds | 7,657 | game/physics/PhysicsContactEffectManager.cpp | #include "precompiled.h"
#include "PhysicsContactEffectManager.h"
#include "AbstractPhysicsObject.h"
#include "../Game.h"
#include "../GameUI.h"
#include "../ui/VisualEffectManager.h"
#include "../ui/VisualEffect.h"
#include "../../util/SoundMaterialParser.h"
#include "../../util/Debug_MemoryManager.h"
namespace game
{
class PhysicsContactEffectManagerImpl {
public:
PhysicsContactEffectManagerImpl()
{
soundmp = new util::SoundMaterialParser();
};
~PhysicsContactEffectManagerImpl()
{
//deleteAllEffects();
delete soundmp;
};
/*
void deleteAllEffects()
{
while (!effectsRunning.isEmpty())
{
VisualEffect *vef = (VisualEffect *)effectsRunning.popLast();
if (game->gameUI->getVisualEffectManager() != NULL)
{
game->gameUI->getVisualEffectManager()->deleteVisualEffect(vef);
vef->freeReference();
}
}
}
void updateEffects()
{
// HACK: for now, just delete the effects every second or so?
if ((game->gameTimer & 63) == 0)
{
deleteAllEffects();
}
// FIXME: real implementation!!!
}
*/
util::SoundMaterialParser *soundmp;
Game *game;
//LinkedList effectsRunning;
};
PhysicsContactEffectManager::PhysicsContactEffectManager(Game *game)
{
impl = new PhysicsContactEffectManagerImpl();
impl->game = game;
}
PhysicsContactEffectManager::~PhysicsContactEffectManager()
{
delete impl;
}
void PhysicsContactEffectManager::reloadConfiguration()
{
delete impl->soundmp;
impl->soundmp = new util::SoundMaterialParser();
}
/*
void PhysicsContactEffectManager::deleteAllEffects()
{
impl->deleteAllEffects();
}
void PhysicsContactEffectManager::updateEffects()
{
impl->updateEffects();
}
*/
void PhysicsContactEffectManager::physicsContact(const PhysicsContact &contact)
{
// WARNING: unsafe IGamePhysicsObject -> AbstractPhysicsObject casts!
AbstractPhysicsObject *o1 = (AbstractPhysicsObject *)contact.obj1;
AbstractPhysicsObject *o2 = (AbstractPhysicsObject *)contact.obj2;
//assert(o1 != NULL);
//assert(o2 != NULL);
assert(contact.physicsObject1);
assert(contact.physicsObject2);
#ifdef PHYSICS_PHYSX
int sm1 = contact.physicsObject1->getIntData();
int sm2 = contact.physicsObject2->getIntData();
if (sm1 == SOUNDMATERIALPARSER_NO_SOUND_INDEX || sm2 == SOUNDMATERIALPARSER_NO_SOUND_INDEX)
return;
#else
if (o1->getSoundMaterial() == SOUNDMATERIALPARSER_NO_SOUND_INDEX
|| o2->getSoundMaterial() == SOUNDMATERIALPARSER_NO_SOUND_INDEX)
return;
#endif
const util::SoundMaterialParser::SoundMaterialList &smlist = impl->soundmp->getSoundMaterials();
for (int i = 0; i < 2; i++) {
AbstractPhysicsObject *o = o1;
if (i == 1)
o = o2;
#ifdef PHYSICS_PHYSX
int smindex = sm1;
if (i == 1)
smindex = sm2;
assert( smindex >= 0 && smindex < (int)smlist.size() );
#else
int smindex = o->getSoundMaterial();
#endif
bool makeEffect = false;
VC3 effectpos;
if (o) {
if (contact.contactForceLen >= smlist[smindex].requiredEffectForce) {
effectpos = contact.contactPosition;
VC3 accel = o->getAcceleration();
VC3 angaccel = o->getAngularAcceleration();
if (accel.GetSquareLength() >= smlist[smindex].requiredEffectAcceleration
* smlist[smindex].requiredEffectAcceleration
|| angaccel.GetSquareLength() >= smlist[smindex].requiredEffectAngularAcceleration
* smlist[smindex].requiredEffectAngularAcceleration)
makeEffect = true;
}
} else {
if (contact.contactForceLen >= smlist[smindex].requiredEffectForce) {
makeEffect = true;
effectpos = contact.contactPosition;
}
}
if (makeEffect)
if (o) {
if ( impl->game->gameTimer < o->getLastEffectTick()
+ (smlist[smindex].effectMaxRate / GAME_TICK_MSEC) )
makeEffect = false;
else
o->setLastEffectTick(impl->game->gameTimer);
}
if (makeEffect) {
std::vector<std::string> effectlist = smlist[smindex].effects;
if (effectlist.size() > 0) {
float effectFactor = 1.0f;
if (smlist[smindex].requiredEffectForce > 0.0f) {
// 0% - 100% effect factor (100% required force - 200% required force)
effectFactor = (contact.contactForceLen / smlist[smindex].requiredEffectForce) - 1.0f;
if (effectFactor > 1.0f)
effectFactor = 1.0f;
assert(effectFactor >= 0.0f);
assert(effectFactor <= 1.0f);
}
int effnum = (int)( effectFactor * (effectlist.size() - 1) );
if (effnum < 0) effnum = 0;
if ( effnum >= (int)effectlist.size() ) effnum = (int)effectlist.size() - 1;
const char *effname = effectlist[effnum].c_str();
ui::VisualEffectManager *vefman = impl->game->gameUI->getVisualEffectManager();
if (vefman != NULL) {
assert(effname != NULL);
// TODO: optimize this!!!
int visualEffId = vefman->getVisualEffectIdByName(effname);
if (visualEffId != -1) {
// TODO: proper lifetime
int lifetime = GAME_TICKS_PER_SECOND / 2;
VisualEffect *vef = vefman->createNewManagedVisualEffect(visualEffId, lifetime, NULL, NULL,
effectpos, effectpos, VC3(0,
0,
0),
VC3(0, 0, 0), impl->game);
if (vef == NULL) {
Logger::getInstance()->error(
"PhysicsContactEffectManager::physicsContact - Failed to create visual effect.");
Logger::getInstance()->debug(effname);
}
} else {
Logger::getInstance()->error(
"PhysicsContactEffectManager::physicsContact - Given visual effect name not found.");
Logger::getInstance()->debug(effname);
}
}
}
}
}
}
}
| 0 | 0.782963 | 1 | 0.782963 | game-dev | MEDIA | 0.887387 | game-dev | 0.962624 | 1 | 0.962624 |
modernuo/ModernUO | 3,956 | Projects/UOContent/Items/TreasureChests/TreasureChestLevel4.cs | using System;
using ModernUO.Serialization;
namespace Server.Items;
[SerializationGenerator(0, false)]
public partial class TreasureChestLevel4 : LockableContainer
{
[Constructible]
public TreasureChestLevel4() : base(0xE41)
{
SetChestAppearance();
Movable = false;
TrapType = TrapType.ExplosionTrap;
TrapPower = 4 * Utility.Random(10, 25);
Locked = true;
RequiredSkill = 92;
LockLevel = RequiredSkill - Utility.Random(1, 10);
MaxLockLevel = RequiredSkill + Utility.Random(1, 10);
// According to OSI, loot in level 4 chest is:
// Gold 500 - 900
// Reagents
// Scrolls
// Blank scrolls
// Potions
// Gems
// Magic Wand
// Magic weapon
// Magic armour
// Magic clothing (not implemented)
// Magic jewelry (not implemented)
// Crystal ball (not implemented)
// Gold
DropItem(new Gold(Utility.Random(200, 400)));
// Reagents
for (var i = Utility.Random(4); i > 0; i--)
{
var reagents = Loot.RandomReagent();
reagents.Amount = 12;
DropItem(reagents);
}
// Scrolls
for (var i = Utility.Random(4); i > 0; i--)
{
var scroll = Loot.RandomScroll(0, 47, SpellbookType.Regular);
scroll.Amount = 16;
DropItem(scroll);
}
// Drop blank scrolls
DropItem(new BlankScroll(Utility.Random(1, 4)));
// Potions
for (var i = Utility.Random(4); i > 0; i--)
{
DropItem(Loot.RandomPotion());
}
// Gems
for (var i = Utility.Random(4); i > 0; i--)
{
var gems = Loot.RandomGem();
gems.Amount = 12;
DropItem(gems);
}
// Magic Wand
for (var i = Utility.Random(4); i > 0; i--)
{
DropItem(Loot.RandomWand());
}
// Equipment
for (var i = Utility.Random(4); i > 0; i--)
{
var item = Loot.RandomArmorOrShieldOrWeapon();
if (item is BaseWeapon weapon)
{
weapon.DamageLevel = (WeaponDamageLevel)Utility.Random(4);
weapon.AccuracyLevel = (WeaponAccuracyLevel)Utility.Random(4);
weapon.DurabilityLevel = (WeaponDurabilityLevel)Utility.Random(4);
weapon.Quality = WeaponQuality.Regular;
}
else if (item is BaseArmor armor)
{
armor.ProtectionLevel = (ArmorProtectionLevel)Utility.Random(4);
armor.Durability = (ArmorDurabilityLevel)Utility.Random(4);
armor.Quality = ArmorQuality.Regular;
}
DropItem(item);
}
// Clothing
for (var i = Utility.Random(3); i > 0; i--)
{
DropItem(Loot.RandomClothing());
}
// Jewelry
for (var i = Utility.Random(3); i > 0; i--)
{
DropItem(Loot.RandomJewelry());
}
// Crystal ball (not implemented)
}
public override bool Decays => true;
public override bool IsDecoContainer => false;
public override TimeSpan DecayTime => TimeSpan.FromMinutes(Utility.Random(15, 60));
public override int DefaultGumpID => 0x42;
public override int DefaultDropSound => 0x42;
public override Rectangle2D Bounds => new(18, 105, 144, 73);
private static readonly (int, int)[] _chestAppearances =
{
// Wooden Chest
(0xe42, 0x49),
(0xe43, 0x49),
// Metal Chest
(0x9ab, 0x4A),
(0xe7c, 0x4A),
// Metal Golden Chest
(0xe40, 0x42),
(0xe41, 0x42),
// Keg
(0xe7f, 0x3e),
};
private void SetChestAppearance()
{
(ItemID, GumpID) = _chestAppearances.RandomElement();
}
}
| 0 | 0.856422 | 1 | 0.856422 | game-dev | MEDIA | 0.982907 | game-dev | 0.971545 | 1 | 0.971545 |
Jire/tarnish | 3,549 | game-server/src/main/java/com/osroyale/content/skill/impl/smithing/Smithing.java | package com.osroyale.content.skill.impl.smithing;
import com.osroyale.game.world.entity.mob.player.Player;
import com.osroyale.content.event.impl.ClickButtonInteractionEvent;
import com.osroyale.content.event.impl.ItemContainerInteractionEvent;
import com.osroyale.content.event.impl.ItemOnObjectInteractionEvent;
import com.osroyale.content.event.impl.ObjectInteractionEvent;
import com.osroyale.game.world.entity.skill.Skill;
import com.osroyale.game.world.items.Item;
import com.osroyale.net.packet.out.SendInputAmount;
import com.osroyale.net.packet.out.SendMessage;
/**
* @author <a href="http://www.rune-server.org/members/stand+up/">Stand Up</a>
* @since 11-2-2017.
*/
public final class Smithing extends Skill {
public Smithing(int level, double experience) {
super(Skill.SMITHING, level, experience);
}
@Override
public boolean itemContainerAction(Player player, ItemContainerInteractionEvent event) {
switch(event.id) {
case 1:
return SmithingArmour.forge(player, event.interfaceId, event.removeSlot, 1);
case 2:
return SmithingArmour.forge(player, event.interfaceId, event.removeSlot, 5);
case 3:
return SmithingArmour.forge(player, event.interfaceId, event.removeSlot, 10);
case 4:
return SmithingArmour.forge(player, event.interfaceId, event.removeSlot, Integer.MAX_VALUE);
case 5:
switch(event.interfaceId) {
case 1119:
case 1120:
case 1121:
case 1122:
case 1123:
player.send(new SendInputAmount("Enter amount", 2, input -> SmithingArmour.forge(player, event.interfaceId, event.removeSlot, Integer.parseInt(input))));
return true;
}
return false;
default:
return false;
}
}
@Override
public boolean clickButton(Player player, ClickButtonInteractionEvent event) {
switch(event.getType()) {
case CLICK_BUTTON:
return Smelting.smelt(player, event.getButton());
default:
return false;
}
}
@Override
public boolean useItem(Player player, ItemOnObjectInteractionEvent event) {
switch(event.getType()) {
case ITEM_ON_OBJECT:
return SmithingArmour.openInterface(player, event.getItem(), event.getObject());
default:
return false;
}
}
@Override
protected boolean clickObject(Player player, ObjectInteractionEvent event) {
if (event.getObject().getId() == 2097) {
Item foundBar = null;
for (int bar : Smelting.SMELT_BARS) {
if (player.inventory.contains(bar)) {
foundBar = new Item(bar);
break;
}
}
if (foundBar != null) {
SmithingArmour.openInterface(player, foundBar, event.getObject());
} else {
player.send(new SendMessage("You have no bar which you have the required Smithing level to use."));
}
return true;
}
switch(event.getType()) {
case FIRST_CLICK_OBJECT:
case SECOND_CLICK_OBJECT:
return Smelting.openInterface(player, event.getObject());
default:
return false;
}
}
}
| 0 | 0.946588 | 1 | 0.946588 | game-dev | MEDIA | 0.968425 | game-dev | 0.81992 | 1 | 0.81992 |
defeatedcrow/HeatAndClimateMod | 2,335 | src/main/java/defeatedcrow/hac/magic/material/entity/ArrowGreen.java | package defeatedcrow.hac.magic.material.entity;
import javax.annotation.Nullable;
import defeatedcrow.hac.core.material.entity.ChairEntity;
import defeatedcrow.hac.magic.material.MagicInit;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.Vec3;
public class ArrowGreen extends AbstractArrow {
private boolean dealtDamage;
private int maxAge = 1200;
public ArrowGreen(EntityType<? extends ArrowGreen> type, Level level) {
super(type, level);
}
public ArrowGreen(Level level, LivingEntity shooter) {
super(MagicInit.ARROW_GREEN_ENTITY.get(), shooter, level);
}
public ArrowGreen(Level level, double x, double y, double z) {
super(MagicInit.ARROW_GREEN_ENTITY.get(), x, y, z, level);
}
public void setMaxAge(int a) {
maxAge = a;
}
@Override
@Nullable
protected EntityHitResult findHitEntity(Vec3 vec, Vec3 vec2) {
return this.dealtDamage ? null : super.findHitEntity(vec, vec2);
}
@Override
protected void onHitEntity(EntityHitResult res) {
Entity entity = res.getEntity();
Entity owner = this.getOwner();
if (entity instanceof LivingEntity) {
LivingEntity liv = (LivingEntity) entity;
this.dealtDamage = true;
if (liv != null && !level.isClientSide) {
if (liv.getVehicle() != null) {
liv.removeVehicle();
}
ChairEntity bind = MagicInit.BIND_PLANT_ENTITY.get().create(level);
bind.setPos(liv.position());
bind.setDeltaMovement(0D, 0D, 0D);
bind.setMaxAge(maxAge);
if (owner instanceof Player player) {
bind.setOwner(player.getUUID());
}
liv.startRiding(bind);
level.addFreshEntity(bind);
}
this.playSound(this.getHitGroundSoundEvent(), 1.0F, 1.2F / (this.random.nextFloat() * 0.2F + 0.9F));
if (this.getPierceLevel() <= 0) {
this.discard();
return;
}
}
super.onHitEntity(res);
}
@Override
protected ItemStack getPickupItem() {
return new ItemStack(MagicInit.ARROW_GREEN.get());
}
@Override
public byte getPierceLevel() {
return 5;
}
}
| 0 | 0.842709 | 1 | 0.842709 | game-dev | MEDIA | 0.976152 | game-dev | 0.972649 | 1 | 0.972649 |
Fluorohydride/ygopro-scripts | 2,872 | c71703785.lua | --守護神官マハード
function c71703785.initial_effect(c)
aux.AddCodeList(c,46986414)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(71703785,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_DRAW)
e1:SetCost(c71703785.spcost)
e1:SetTarget(c71703785.sptg1)
e1:SetOperation(c71703785.spop1)
c:RegisterEffect(e1)
--atkup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_SET_ATTACK_FINAL)
e2:SetCondition(c71703785.atkcon)
e2:SetValue(c71703785.atkval)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(71703785,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_DESTROYED)
e3:SetCondition(c71703785.spcon2)
e3:SetTarget(c71703785.sptg2)
e3:SetOperation(c71703785.spop2)
c:RegisterEffect(e3)
end
function c71703785.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not e:GetHandler():IsPublic() end
end
function c71703785.sptg1(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c71703785.spop1(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
function c71703785.atkcon(e)
local ph=Duel.GetCurrentPhase()
local bc=e:GetHandler():GetBattleTarget()
return (ph==PHASE_DAMAGE or ph==PHASE_DAMAGE_CAL) and bc and bc:IsAttribute(ATTRIBUTE_DARK)
end
function c71703785.atkval(e,c)
return e:GetHandler():GetAttack()*2
end
function c71703785.spcon2(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT+REASON_BATTLE)~=0
end
function c71703785.spfilter(c,e,tp)
return c:IsCode(46986414) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c71703785.sptg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c71703785.spfilter,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE)
end
function c71703785.spop2(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c71703785.spfilter),tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| 0 | 0.944495 | 1 | 0.944495 | game-dev | MEDIA | 0.982273 | game-dev | 0.966655 | 1 | 0.966655 |
sebas77/Svelto.MiniExamples | 4,417 | Example1-Stride-DoofusesMustEat/DOOFUSES_STRIDE/Svelto/com.sebaslab.svelto.ecs/Extensions/Unity/DOTS/UECS/SveltoOnDOTSEntitiesSubmissionGroup.cs | #if UNITY_ECS
#if !UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP_RUNTIME_WORLD && !UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP
#error SveltoOnDOTS required the user to take over the DOTS world control and explicitly create it. UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP must be defined
#endif
using System;
using Svelto.Common;
using Svelto.DataStructures;
using Svelto.ECS.Schedulers;
using Unity.Entities;
using Unity.Jobs;
namespace Svelto.ECS.SveltoOnDOTS
{
/// <summary>
/// SveltoDOTS ECSEntitiesSubmissionGroup extends the _submissionScheduler responsibility to integrate the
/// submission of Svelto entities with the submission of DOTS ECS entities using DOTSOperationsForSvelto.
/// As there is just one submissionScheduler per enginesRoot, there should be only one SveltoDOTS
/// ECSEntitiesSubmissionGroup.
/// initialise DOTS ECS/Svelto systems/engines that handles DOTS ECS entities structural changes.
/// Flow:
/// Complete all the jobs used as input dependencies (this is a sync point)
/// Svelto entities are submitted
/// Svelto Add and remove callback are called
/// ISveltoOnDOTSStructuralEngine can use DOTSOperationsForSvelto in their add/remove/moove callbacks
/// </summary>
[DisableAutoCreation]
public sealed partial class SveltoOnDOTSEntitiesSubmissionGroup: SystemBase, IQueryingEntitiesEngine, ISveltoOnDOTSSubmission
{
public SveltoOnDOTSEntitiesSubmissionGroup(EntitiesSubmissionScheduler submissionScheduler)
{
_submissionScheduler = submissionScheduler;
_structuralEngines = new FasterList<ISveltoOnDOTSStructuralEngine>();
}
public EntitiesDB entitiesDB { get; set; }
public void Ready() { }
public void SubmitEntities(JobHandle jobHandle)
{
if (_submissionScheduler.paused == true || World.EntityManager == default)
return;
using (var profiler = new PlatformProfiler("SveltoDOTSEntitiesSubmissionGroup"))
{
using (profiler.Sample("Complete All Pending Jobs"))
{
jobHandle.Complete(); //sync-point
#if UNITY_ECS_100
EntityManager.CompleteAllTrackedJobs();
#else
EntityManager.CompleteAllJobs();
#endif
}
//Submit Svelto Entities, calls Add/Remove/MoveTo that can be used by the DOTS ECSSubmissionEngines
_submissionScheduler.SubmitEntities();
foreach (var engine in _structuralEngines)
engine.OnPostSubmission();
_dotsOperationsForSvelto.Complete();
}
}
public void Add(ISveltoOnDOTSStructuralEngine engine)
{
_structuralEngines.Add(engine);
if (_isReady == true)
{
engine.DOTSOperations = _dotsOperationsForSvelto;
engine.OnOperationsReady();
}
}
protected override void OnCreate()
{
unsafe
{
_jobHandle = (JobHandle*) MemoryUtilities.NativeAlloc((uint)MemoryUtilities.SizeOf<JobHandle>(), Allocator.Persistent);
_dotsOperationsForSvelto = new DOTSOperationsForSvelto(World.EntityManager, _jobHandle);
_isReady = true;
//initialise engines field while world was null
foreach (var engine in _structuralEngines)
{
engine.DOTSOperations = _dotsOperationsForSvelto;
engine.OnOperationsReady();
}
}
}
protected override void OnDestroy()
{
unsafe
{
base.OnDestroy();
MemoryUtilities.NativeFree((IntPtr)_jobHandle, Allocator.Persistent);
}
}
protected override void OnUpdate()
{
throw new NotSupportedException("if this is called something broke the original design");
}
readonly FasterList<ISveltoOnDOTSStructuralEngine> _structuralEngines;
readonly EntitiesSubmissionScheduler _submissionScheduler;
DOTSOperationsForSvelto _dotsOperationsForSvelto;
bool _isReady;
unsafe JobHandle* _jobHandle;
}
}
#endif | 0 | 0.880844 | 1 | 0.880844 | game-dev | MEDIA | 0.927654 | game-dev | 0.88825 | 1 | 0.88825 |
openkraken/kraken | 3,096 | kraken/lib/src/dom/event_target.dart | /*
* Copyright (C) 2019-present The Kraken authors. All rights reserved.
*/
import 'package:flutter/foundation.dart';
import 'package:kraken/dom.dart';
import 'package:kraken/foundation.dart';
import 'package:kraken/module.dart';
typedef EventHandler = void Function(Event event);
abstract class EventTarget extends BindingObject {
EventTarget(BindingContext? context) : super(context);
bool _disposed = false;
bool get disposed => _disposed;
@protected
final Map<String, List<EventHandler>> _eventHandlers = {};
Map<String, List<EventHandler>> getEventHandlers() => _eventHandlers;
@protected
bool hasEventListener(String type) => _eventHandlers.containsKey(type);
@mustCallSuper
void addEventListener(String eventType, EventHandler eventHandler) {
if (_disposed) return;
List<EventHandler>? existHandler = _eventHandlers[eventType];
if (existHandler == null) {
_eventHandlers[eventType] = existHandler = [];
}
existHandler.add(eventHandler);
}
@mustCallSuper
void removeEventListener(String eventType, EventHandler eventHandler) {
if (_disposed) return;
List<EventHandler>? currentHandlers = _eventHandlers[eventType];
if (currentHandlers != null) {
currentHandlers.remove(eventHandler);
if (currentHandlers.isEmpty) {
_eventHandlers.remove(eventType);
}
}
}
@mustCallSuper
void dispatchEvent(Event event) {
if (_disposed) return;
event.target = this;
_dispatchEventInDOM(event);
}
// Refs: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/dom/EventDispatcher.cpp#L85
void _dispatchEventInDOM(Event event) {
// TODO: Invoke capturing event listeners in the reverse order.
String eventType = event.type;
List<EventHandler>? existHandler = _eventHandlers[eventType];
if (existHandler != null) {
// Modify currentTarget before the handler call, otherwise currentTarget may be modified by the previous handler.
event.currentTarget = this;
// To avoid concurrent exception while prev handler modify the original handler list, causing list iteration
// with error, copy the handlers here.
for (EventHandler handler in [...existHandler]) {
handler(event);
}
event.currentTarget = null;
}
// Invoke bubbling event listeners.
if (event.bubbles && !event.propagationStopped) {
parentEventTarget?._dispatchEventInDOM(event);
}
}
@override
@mustCallSuper
void dispose() {
if (kProfileMode) {
PerformanceTiming.instance().mark(PERF_DISPOSE_EVENT_TARGET_START, uniqueId: hashCode);
}
_disposed = true;
_eventHandlers.clear();
super.dispose();
if (kProfileMode) {
PerformanceTiming.instance().mark(PERF_DISPOSE_EVENT_TARGET_END, uniqueId: hashCode);
}
}
EventTarget? get parentEventTarget;
List<EventTarget> get eventPath {
List<EventTarget> path = [];
EventTarget? current = this;
while (current != null) {
path.add(current);
current = current.parentEventTarget;
}
return path;
}
}
| 0 | 0.933879 | 1 | 0.933879 | game-dev | MEDIA | 0.360729 | game-dev | 0.933903 | 1 | 0.933903 |
SelinaDev/Godot-Roguelike-Tutorial | 2,078 | part_11/src/Entities/Actors/Components/fighter_component.gd | class_name FighterComponent
extends Component
signal hp_changed(hp, max_hp)
var max_hp: int
var hp: int:
set(value):
hp = clampi(value, 0, max_hp)
hp_changed.emit(hp, max_hp)
if hp <= 0:
var die_silently := false
if not is_inside_tree():
die_silently = true
await ready
die(not die_silently)
var defense: int
var power: int
var death_texture: Texture
var death_color: Color
func _init(definition: FighterComponentDefinition) -> void:
max_hp = definition.max_hp
hp = definition.max_hp
defense = definition.defense
power = definition.power
death_texture = definition.death_texture
death_color = definition.death_color
func heal(amount: int) -> int:
if hp == max_hp:
return 0
var new_hp_value: int = hp + amount
if new_hp_value > max_hp:
new_hp_value = max_hp
var amount_recovered: int = new_hp_value - hp
hp = new_hp_value
return amount_recovered
func take_damage(amount: int) -> void:
hp -= amount
func die(trigger_side_effects := true) -> void:
var death_message: String
var death_message_color: Color
if get_map_data().player == entity:
death_message = "You died!"
death_message_color = GameColors.PLAYER_DIE
SignalBus.player_died.emit()
else:
death_message = "%s is dead!" % entity.get_entity_name()
death_message_color = GameColors.ENEMY_DIE
if trigger_side_effects:
MessageLog.send_message(death_message, death_message_color)
get_map_data().player.level_component.add_xp(entity.level_component.xp_given)
entity.texture = death_texture
entity.modulate = death_color
entity.ai_component.queue_free()
entity.ai_component = null
entity.entity_name = "Remains of %s" % entity.entity_name
entity.blocks_movement = false
entity.type = Entity.EntityType.CORPSE
get_map_data().unregister_blocking_entity(entity)
func get_save_data() -> Dictionary:
return {
"max_hp": max_hp,
"hp": hp,
"power": power,
"defense": defense
}
func restore(save_data: Dictionary) -> void:
max_hp = save_data["max_hp"]
hp = save_data["hp"]
power = save_data["power"]
defense = save_data["defense"]
| 0 | 0.804828 | 1 | 0.804828 | game-dev | MEDIA | 0.888846 | game-dev | 0.676329 | 1 | 0.676329 |
PurplesInc/AetherSpigot | 5,789 | AetherSpigot-API/src/main/java/org/bukkit/material/Vine.java | package org.bukkit.material;
import java.util.Arrays;
import java.util.EnumSet;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
/**
* Represents a vine
*/
public class Vine extends MaterialData {
private static final int VINE_NORTH = 0x4;
private static final int VINE_EAST = 0x8;
private static final int VINE_WEST = 0x2;
private static final int VINE_SOUTH = 0x1;
EnumSet<BlockFace> possibleFaces = EnumSet.of(BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST);
public Vine() {
super(Material.VINE);
}
/**
* @param type the raw type id
* @param data the raw data value
* @deprecated Magic value
*/
@Deprecated
public Vine(int type, byte data){
super(type, data);
}
/**
* @param data the raw data value
* @deprecated Magic value
*/
@Deprecated
public Vine(byte data) {
super(Material.VINE, data);
}
public Vine(BlockFace... faces) {
this(EnumSet.copyOf(Arrays.asList(faces)));
}
public Vine(EnumSet<BlockFace> faces) {
this((byte) 0);
faces.retainAll(possibleFaces);
byte data = 0;
if (faces.contains(BlockFace.WEST)) {
data |= VINE_WEST;
}
if (faces.contains(BlockFace.NORTH)) {
data |= VINE_NORTH;
}
if (faces.contains(BlockFace.SOUTH)) {
data |= VINE_SOUTH;
}
if (faces.contains(BlockFace.EAST)) {
data |= VINE_EAST;
}
setData(data);
}
/**
* Check if the vine is attached to the specified face of an adjacent
* block. You can check two faces at once by passing e.g. {@link
* BlockFace#NORTH_EAST}.
*
* @param face The face to check.
* @return Whether it is attached to that face.
*/
public boolean isOnFace(BlockFace face) {
switch (face) {
case WEST:
return (getData() & VINE_WEST) == VINE_WEST;
case NORTH:
return (getData() & VINE_NORTH) == VINE_NORTH;
case SOUTH:
return (getData() & VINE_SOUTH) == VINE_SOUTH;
case EAST:
return (getData() & VINE_EAST) == VINE_EAST;
case NORTH_EAST:
return isOnFace(BlockFace.EAST) && isOnFace(BlockFace.NORTH);
case NORTH_WEST:
return isOnFace(BlockFace.WEST) && isOnFace(BlockFace.NORTH);
case SOUTH_EAST:
return isOnFace(BlockFace.EAST) && isOnFace(BlockFace.SOUTH);
case SOUTH_WEST:
return isOnFace(BlockFace.WEST) && isOnFace(BlockFace.SOUTH);
case UP: // It's impossible to be accurate with this since it's contextual
return true;
default:
return false;
}
}
/**
* Attach the vine to the specified face of an adjacent block.
*
* @param face The face to attach.
*/
public void putOnFace(BlockFace face) {
switch(face) {
case WEST:
setData((byte) (getData() | VINE_WEST));
break;
case NORTH:
setData((byte) (getData() | VINE_NORTH));
break;
case SOUTH:
setData((byte) (getData() | VINE_SOUTH));
break;
case EAST:
setData((byte) (getData() | VINE_EAST));
break;
case NORTH_WEST:
putOnFace(BlockFace.WEST);
putOnFace(BlockFace.NORTH);
break;
case SOUTH_WEST:
putOnFace(BlockFace.WEST);
putOnFace(BlockFace.SOUTH);
break;
case NORTH_EAST:
putOnFace(BlockFace.EAST);
putOnFace(BlockFace.NORTH);
break;
case SOUTH_EAST:
putOnFace(BlockFace.EAST);
putOnFace(BlockFace.SOUTH);
break;
case UP:
break;
default:
throw new IllegalArgumentException("Vines can't go on face " + face.toString());
}
}
/**
* Detach the vine from the specified face of an adjacent block.
*
* @param face The face to detach.
*/
public void removeFromFace(BlockFace face) {
switch(face) {
case WEST:
setData((byte) (getData() & ~VINE_WEST));
break;
case NORTH:
setData((byte) (getData() & ~VINE_NORTH));
break;
case SOUTH:
setData((byte) (getData() & ~VINE_SOUTH));
break;
case EAST:
setData((byte) (getData() & ~VINE_EAST));
break;
case NORTH_WEST:
removeFromFace(BlockFace.WEST);
removeFromFace(BlockFace.NORTH);
break;
case SOUTH_WEST:
removeFromFace(BlockFace.WEST);
removeFromFace(BlockFace.SOUTH);
break;
case NORTH_EAST:
removeFromFace(BlockFace.EAST);
removeFromFace(BlockFace.NORTH);
break;
case SOUTH_EAST:
removeFromFace(BlockFace.EAST);
removeFromFace(BlockFace.SOUTH);
break;
case UP:
break;
default:
throw new IllegalArgumentException("Vines can't go on face " + face.toString());
}
}
@Override
public String toString() {
return "VINE";
}
@Override
public Vine clone() {
return (Vine) super.clone();
}
}
| 0 | 0.755828 | 1 | 0.755828 | game-dev | MEDIA | 0.782886 | game-dev | 0.813008 | 1 | 0.813008 |
ImLegiitXD/Dream-Advanced | 5,890 | dll/back/1.8.9/net/minecraft/entity/item/EntityPainting.java | package net.minecraft.entity.item;
import com.google.common.collect.Lists;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityHanging;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class EntityPainting extends EntityHanging
{
public EntityPainting.EnumArt art;
public EntityPainting(World worldIn)
{
super(worldIn);
}
public EntityPainting(World worldIn, BlockPos pos, EnumFacing facing)
{
super(worldIn, pos);
List<EntityPainting.EnumArt> list = Lists.<EntityPainting.EnumArt>newArrayList();
for (EntityPainting.EnumArt entitypainting$enumart : EntityPainting.EnumArt.values())
{
this.art = entitypainting$enumart;
this.updateFacingWithBoundingBox(facing);
if (this.onValidSurface())
{
list.add(entitypainting$enumart);
}
}
if (!list.isEmpty())
{
this.art = (EntityPainting.EnumArt)list.get(this.rand.nextInt(list.size()));
}
this.updateFacingWithBoundingBox(facing);
}
public EntityPainting(World worldIn, BlockPos pos, EnumFacing facing, String title)
{
this(worldIn, pos, facing);
for (EntityPainting.EnumArt entitypainting$enumart : EntityPainting.EnumArt.values())
{
if (entitypainting$enumart.title.equals(title))
{
this.art = entitypainting$enumart;
break;
}
}
this.updateFacingWithBoundingBox(facing);
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound tagCompound)
{
tagCompound.setString("Motive", this.art.title);
super.writeEntityToNBT(tagCompound);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound tagCompund)
{
String s = tagCompund.getString("Motive");
for (EntityPainting.EnumArt entitypainting$enumart : EntityPainting.EnumArt.values())
{
if (entitypainting$enumart.title.equals(s))
{
this.art = entitypainting$enumart;
}
}
if (this.art == null)
{
this.art = EntityPainting.EnumArt.KEBAB;
}
super.readEntityFromNBT(tagCompund);
}
public int getWidthPixels()
{
return this.art.sizeX;
}
public int getHeightPixels()
{
return this.art.sizeY;
}
/**
* Called when this entity is broken. Entity parameter may be null.
*/
public void onBroken(Entity brokenEntity)
{
if (this.worldObj.getGameRules().getBoolean("doEntityDrops"))
{
if (brokenEntity instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)brokenEntity;
if (entityplayer.capabilities.isCreativeMode)
{
return;
}
}
this.entityDropItem(new ItemStack(Items.painting), 0.0F);
}
}
/**
* Sets the location and Yaw/Pitch of an entity in the world
*/
public void setLocationAndAngles(double x, double y, double z, float yaw, float pitch)
{
BlockPos blockpos = this.hangingPosition.add(x - this.posX, y - this.posY, z - this.posZ);
this.setPosition((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ());
}
public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_)
{
BlockPos blockpos = this.hangingPosition.add(x - this.posX, y - this.posY, z - this.posZ);
this.setPosition((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ());
}
public static enum EnumArt
{
KEBAB("Kebab", 16, 16, 0, 0),
AZTEC("Aztec", 16, 16, 16, 0),
ALBAN("Alban", 16, 16, 32, 0),
AZTEC_2("Aztec2", 16, 16, 48, 0),
BOMB("Bomb", 16, 16, 64, 0),
PLANT("Plant", 16, 16, 80, 0),
WASTELAND("Wasteland", 16, 16, 96, 0),
POOL("Pool", 32, 16, 0, 32),
COURBET("Courbet", 32, 16, 32, 32),
SEA("Sea", 32, 16, 64, 32),
SUNSET("Sunset", 32, 16, 96, 32),
CREEBET("Creebet", 32, 16, 128, 32),
WANDERER("Wanderer", 16, 32, 0, 64),
GRAHAM("Graham", 16, 32, 16, 64),
MATCH("Match", 32, 32, 0, 128),
BUST("Bust", 32, 32, 32, 128),
STAGE("Stage", 32, 32, 64, 128),
VOID("Void", 32, 32, 96, 128),
SKULL_AND_ROSES("SkullAndRoses", 32, 32, 128, 128),
WITHER("Wither", 32, 32, 160, 128),
FIGHTERS("Fighters", 64, 32, 0, 96),
POINTER("Pointer", 64, 64, 0, 192),
PIGSCENE("Pigscene", 64, 64, 64, 192),
BURNING_SKULL("BurningSkull", 64, 64, 128, 192),
SKELETON("Skeleton", 64, 48, 192, 64),
DONKEY_KONG("DonkeyKong", 64, 48, 192, 112);
public static final int field_180001_A = "SkullAndRoses".length();
public final String title;
public final int sizeX;
public final int sizeY;
public final int offsetX;
public final int offsetY;
private EnumArt(String titleIn, int width, int height, int textureU, int textureV)
{
this.title = titleIn;
this.sizeX = width;
this.sizeY = height;
this.offsetX = textureU;
this.offsetY = textureV;
}
}
}
| 0 | 0.786645 | 1 | 0.786645 | game-dev | MEDIA | 0.968835 | game-dev | 0.792416 | 1 | 0.792416 |
martindevans/Myriad.ECS | 2,156 | Myriad.ECS.Tests/Queries/CursorQuery.cs | using Myriad.ECS.Command;
using Myriad.ECS.Queries;
using Myriad.ECS.Worlds;
using Myriad.ECS.Worlds.Archetypes;
namespace Myriad.ECS.Tests.Queries;
[TestClass]
public class CursorQuery
{
[TestMethod]
public void BasicCursor()
{
var w = new WorldBuilder().Build();
// Create 3 chunks worth of entities,
var c = new CommandBuffer(w);
for (var i = 0; i < Archetype.CHUNK_SIZE * 3; i++)
c.Create().Set(new ComponentInt32());
// Plus some other unrelated entities
for (var i = 0; i < Archetype.CHUNK_SIZE; i++)
c.Create().Set(new Component0());
c.Playback().Dispose();
// Create a cursor with budget to process one chunk
var cursor = new Cursor
{
EntityBudget = Archetype.CHUNK_SIZE,
};
// Execute query with cursor
QueryDescription? q = null;
var inc = new Increment();
Assert.AreEqual(Archetype.CHUNK_SIZE, w.Execute<Increment, ComponentInt32>(ref inc, ref q, cursor));
// Check that exactly 1 chunk of entities has been processed
var incremented = 0;
foreach (var (_, ci32) in w.Query<ComponentInt32>())
if (ci32.Ref.Value > 0)
incremented++;
Assert.AreEqual(Archetype.CHUNK_SIZE, incremented);
// Now run it twice more, each time processing entities
Assert.AreEqual(Archetype.CHUNK_SIZE, w.Execute<Increment, ComponentInt32>(ref inc, ref q, cursor));
Assert.AreEqual(Archetype.CHUNK_SIZE, w.Execute<Increment, ComponentInt32>(ref inc, ref q, cursor));
// This final time should process none, because the query has reached the end
Assert.AreEqual(0, w.Execute<Increment, ComponentInt32>(ref inc, ref q, cursor));
// Check that all entities have been processed exactly once
foreach (var (_, ci32) in w.Query<ComponentInt32>())
Assert.AreEqual(1, ci32.Ref.Value);
}
private struct Increment
: IQuery<ComponentInt32>
{
public void Execute(Entity e, ref ComponentInt32 t0)
{
t0.Value++;
}
}
} | 0 | 0.760138 | 1 | 0.760138 | game-dev | MEDIA | 0.800714 | game-dev | 0.673749 | 1 | 0.673749 |
cmangos/playerbots | 18,841 | playerbot/strategy/shaman/ShamanTriggers.h | #pragma once
#include "playerbot/strategy/triggers/GenericTriggers.h"
namespace ai
{
class ShamanWeaponTrigger : public BuffTrigger
{
public:
ShamanWeaponTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "rockbiter weapon") {}
virtual bool IsActive();
private:
static std::list<std::string> spells;
};
class ReadyToRemoveTotemsTrigger : public Trigger
{
public:
ReadyToRemoveTotemsTrigger(PlayerbotAI* ai) : Trigger(ai, "ready to remove totems", 5) {}
virtual bool IsActive()
{
// Avoid removing any of the big cooldown totems.
return AI_VALUE(bool, "have any totem")
&& !AI_VALUE2(bool, "has totem", "mana tide totem")
&& !AI_VALUE2(bool, "has totem", "earth elemental totem")
&& !AI_VALUE2(bool, "has totem", "fire elemental totem");
}
};
class TotemsAreNotSummonedTrigger : public Trigger
{
public:
TotemsAreNotSummonedTrigger(PlayerbotAI* ai) : Trigger(ai, "no totems summoned", 5) {}
virtual bool IsActive()
{
return !AI_VALUE(bool, "have any totem");
}
};
class TotemTrigger : public Trigger
{
public:
TotemTrigger(PlayerbotAI* ai, std::string spell, int attackerCount = 0) : Trigger(ai, spell), attackerCount(attackerCount) {}
virtual bool IsActive()
{
return AI_VALUE(uint8, "attackers count") >= attackerCount && !AI_VALUE2(bool, "has totem", name);
}
protected:
int attackerCount;
};
class FireTotemTrigger : public Trigger
{
public:
FireTotemTrigger(PlayerbotAI* ai, bool inMovement = true) : Trigger(ai, "trigger spec appropriate fire totem", 5), inMovement(inMovement) {}
virtual bool IsActive()
{
if (!inMovement && bot->IsMoving() && bot->GetMotionMaster() && bot->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE)
{
return false;
}
if (ai->HasStrategy("totem fire nova", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "fire nova totem");
}
else if (ai->HasStrategy("totem fire flametongue", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "flametongue totem");
}
else if (ai->HasStrategy("totem fire resistance", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "frost resistance totem");
}
else if (ai->HasStrategy("totem fire magma", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "magma totem");
}
else if (ai->HasStrategy("totem fire searing", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "searing totem");
}
else
{
return !AI_VALUE2(bool, "has totem", "searing totem") &&
!AI_VALUE2(bool, "has totem", "magma totem") &&
!AI_VALUE2(bool, "has totem", "frost resistance totem") &&
!AI_VALUE2(bool, "has totem", "flametongue totem") &&
!AI_VALUE2(bool, "has totem", "totem of wrath") &&
!AI_VALUE2(bool, "has totem", "fire elemental totem");
}
}
private:
bool inMovement;
};
class FireTotemAoeTrigger : public Trigger
{
public:
FireTotemAoeTrigger(PlayerbotAI* ai) : Trigger(ai, "trigger spec appropriate fire totem aoe", 2) {}
virtual bool IsActive()
{
return AI_VALUE(uint8, "attackers count") >= 3 &&
!AI_VALUE2(bool, "has totem", "searing totem") &&
!AI_VALUE2(bool, "has totem", "magma totem") &&
!AI_VALUE2(bool, "has totem", "frost resistance totem") &&
!AI_VALUE2(bool, "has totem", "flametongue totem") &&
!AI_VALUE2(bool, "has totem", "totem of wrath") &&
!AI_VALUE2(bool, "has totem", "fire elemental totem");
}
};
class EarthTotemTrigger : public Trigger
{
public:
EarthTotemTrigger(PlayerbotAI* ai, bool inMovement = true) : Trigger(ai, "trigger spec appropriate earth totem", 5), inMovement(inMovement) {}
virtual bool IsActive()
{
if (!inMovement && bot->IsMoving() && bot->GetMotionMaster() && bot->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE)
{
return false;
}
if (ai->HasStrategy("totem earth stoneclaw", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "stoneclaw totem");
}
else if (ai->HasStrategy("totem earth stoneskin", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "stoneskin totem");
}
else if (ai->HasStrategy("totem earth earthbind", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "earthbind totem");
}
else if (ai->HasStrategy("totem earth strength", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "strength of earth totem");
}
else if (ai->HasStrategy("totem earth tremor", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "tremor totem");
}
else
{
return !AI_VALUE2(bool, "has totem", "earthbind totem") &&
!AI_VALUE2(bool, "has totem", "stoneskin totem") &&
!AI_VALUE2(bool, "has totem", "stoneclaw totem") &&
!AI_VALUE2(bool, "has totem", "strength of earth totem") &&
!AI_VALUE2(bool, "has totem", "tremor totem") &&
!AI_VALUE2(bool, "has totem", "earth elemental totem");
}
}
private:
bool inMovement;
};
class AirTotemTrigger : public Trigger
{
public:
AirTotemTrigger(PlayerbotAI* ai, bool inMovement = true) : Trigger(ai, "trigger spec appropriate air totem", 5), inMovement(inMovement) {}
virtual bool IsActive()
{
if (!inMovement && bot->IsMoving() && bot->GetMotionMaster() && bot->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE)
{
return false;
}
if (ai->HasStrategy("totem air grace", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "grace of air totem");
}
else if (ai->HasStrategy("totem air grounding", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "grounding totem");
}
else if (ai->HasStrategy("totem air resistance", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "nature resistance totem");
}
else if (ai->HasStrategy("totem air tranquil", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "tranquil air totem");
}
else if (ai->HasStrategy("totem air windfury", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "windfury totem");
}
else if (ai->HasStrategy("totem air windwall", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "windwall totem");
}
else if (ai->HasStrategy("totem air wrath", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "wrath of air totem");
}
else
{
return !AI_VALUE2(bool, "has totem", "grace of air totem") &&
!AI_VALUE2(bool, "has totem", "windwall totem") &&
!AI_VALUE2(bool, "has totem", "tranquil air totem") &&
!AI_VALUE2(bool, "has totem", "windfury totem") &&
!AI_VALUE2(bool, "has totem", "grounding totem") &&
!AI_VALUE2(bool, "has totem", "sentry totem") &&
!AI_VALUE2(bool, "has totem", "nature resistance totem") &&
!AI_VALUE2(bool, "has totem", "wrath of air totem");
}
}
private:
bool inMovement;
};
class WaterTotemTrigger : public Trigger
{
public:
WaterTotemTrigger(PlayerbotAI* ai, bool inMovement = true) : Trigger(ai, "trigger spec appropriate water totem", 5), inMovement(inMovement) {}
virtual bool IsActive()
{
if (!inMovement && bot->IsMoving() && bot->GetMotionMaster() && bot->GetMotionMaster()->GetCurrentMovementGeneratorType() != IDLE_MOTION_TYPE)
{
return false;
}
if (ai->HasStrategy("totem water cleansing", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "disease cleansing totem");
}
else if (ai->HasStrategy("totem water resistance", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "fire resistance totem");
}
else if (ai->HasStrategy("totem water healing", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "healing stream totem");
}
else if (ai->HasStrategy("totem water mana", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "mana spring totem");
}
else if (ai->HasStrategy("totem water poison", BotState::BOT_STATE_COMBAT))
{
return !AI_VALUE2(bool, "has totem", "poison cleansing totem");
}
else
{
return !AI_VALUE2(bool, "has totem", "healing stream totem") &&
!AI_VALUE2(bool, "has totem", "mana spring totem") &&
!AI_VALUE2(bool, "has totem", "poison cleansing totem") &&
!AI_VALUE2(bool, "has totem", "disease cleansing totem") &&
!AI_VALUE2(bool, "has totem", "mana tide totem") &&
!AI_VALUE2(bool, "has totem", "fire resistance totem");
}
}
private:
bool inMovement;
};
class WindShearInterruptSpellTrigger : public InterruptSpellTrigger
{
public:
WindShearInterruptSpellTrigger(PlayerbotAI* ai) : InterruptSpellTrigger(ai, "wind shear") {}
};
class WaterShieldTrigger : public BuffTrigger
{
public:
WaterShieldTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "water shield") {}
};
class LightningShieldTrigger : public BuffTrigger
{
public:
LightningShieldTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "lightning shield") {}
};
class PurgeTrigger : public TargetAuraDispelTrigger
{
public:
PurgeTrigger(PlayerbotAI* ai) : TargetAuraDispelTrigger(ai, "purge", DISPEL_MAGIC, 3) {}
virtual bool IsActive()
{
Unit* target = AI_VALUE(Unit*, "current target");
if (!target)
return false;
if (sServerFacade.IsFriendlyTo(bot, target))
return false;
for (uint32 type = SPELL_AURA_NONE; type < TOTAL_AURAS; ++type)
{
Unit::AuraList const& auras = target->GetAurasByType((AuraType)type);
for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
const Aura* aura = *itr;
const SpellEntry* entry = aura->GetSpellProto();
uint32 spellId = entry->Id;
if (!IsPositiveSpell(spellId))
continue;
std::vector<uint32> ignoreSpells;
ignoreSpells.push_back(17627);
ignoreSpells.push_back(24382);
ignoreSpells.push_back(22888);
ignoreSpells.push_back(24425);
ignoreSpells.push_back(16609);
ignoreSpells.push_back(22818);
ignoreSpells.push_back(22820);
ignoreSpells.push_back(15366);
ignoreSpells.push_back(15852);
ignoreSpells.push_back(22817);
ignoreSpells.push_back(17538);
ignoreSpells.push_back(11405);
ignoreSpells.push_back(7396);
ignoreSpells.push_back(17539);
if (find(ignoreSpells.begin(), ignoreSpells.end(), spellId) != ignoreSpells.end())
continue;
/*if (sPlayerbotAIConfig.dispelAuraDuration && aura->GetAuraDuration() && aura->GetAuraDuration() < (int32)sPlayerbotAIConfig.dispelAuraDuration)
return false;*/
if (ai->canDispel(entry, DISPEL_MAGIC))
return true;
}
}
return false;
}
};
class WaterWalkingTrigger : public BuffTrigger
{
public:
WaterWalkingTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "water walking", 7) {}
virtual bool IsActive()
{
return BuffTrigger::IsActive() && AI_VALUE2(bool, "swimming", "self target");
}
};
class WaterBreathingTrigger : public BuffTrigger
{
public:
WaterBreathingTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "water breathing", 5) {}
virtual bool IsActive()
{
return BuffTrigger::IsActive() && AI_VALUE2(bool, "swimming", "self target");
}
};
class WaterWalkingOnPartyTrigger : public BuffOnPartyTrigger
{
public:
WaterWalkingOnPartyTrigger(PlayerbotAI* ai) : BuffOnPartyTrigger(ai, "water walking on party", 7) {}
virtual bool IsActive()
{
return BuffOnPartyTrigger::IsActive() && AI_VALUE2(bool, "swimming", "self target");
}
};
class WaterBreathingOnPartyTrigger : public BuffOnPartyTrigger
{
public:
WaterBreathingOnPartyTrigger(PlayerbotAI* ai) : BuffOnPartyTrigger(ai, "water breathing on party", 2) {}
virtual bool IsActive()
{
return BuffOnPartyTrigger::IsActive() && AI_VALUE2(bool, "swimming", "self target");
}
};
class CleanseSpiritPoisonTrigger : public NeedCureTrigger
{
public:
CleanseSpiritPoisonTrigger(PlayerbotAI* ai) : NeedCureTrigger(ai, "cleanse spirit", DISPEL_POISON) {}
};
class PartyMemberCleanseSpiritPoisonTrigger : public PartyMemberNeedCureTrigger
{
public:
PartyMemberCleanseSpiritPoisonTrigger(PlayerbotAI* ai) : PartyMemberNeedCureTrigger(ai, "cleanse spirit", DISPEL_POISON) {}
};
class CleanseSpiritCurseTrigger : public NeedCureTrigger
{
public:
CleanseSpiritCurseTrigger(PlayerbotAI* ai) : NeedCureTrigger(ai, "cleanse spirit", DISPEL_CURSE) {}
};
class PartyMemberCleanseSpiritCurseTrigger : public PartyMemberNeedCureTrigger
{
public:
PartyMemberCleanseSpiritCurseTrigger(PlayerbotAI* ai) : PartyMemberNeedCureTrigger(ai, "cleanse spirit", DISPEL_CURSE) {}
};
class CleanseSpiritDiseaseTrigger : public NeedCureTrigger
{
public:
CleanseSpiritDiseaseTrigger(PlayerbotAI* ai) : NeedCureTrigger(ai, "cleanse spirit", DISPEL_DISEASE) {}
};
class PartyMemberCleanseSpiritDiseaseTrigger : public PartyMemberNeedCureTrigger
{
public:
PartyMemberCleanseSpiritDiseaseTrigger(PlayerbotAI* ai) : PartyMemberNeedCureTrigger(ai, "cleanse spirit", DISPEL_DISEASE) {}
};
class ShockTrigger : public DebuffTrigger
{
public:
ShockTrigger(PlayerbotAI* ai) : DebuffTrigger(ai, "earth shock") {}
virtual bool IsActive();
};
class FrostShockSnareTrigger : public SnareTargetTrigger
{
public:
FrostShockSnareTrigger(PlayerbotAI* ai) : SnareTargetTrigger(ai, "frost shock") {}
};
class HeroismTrigger : public BoostTrigger
{
public:
HeroismTrigger(PlayerbotAI* ai) : BoostTrigger(ai, "heroism") {}
};
class BloodlustTrigger : public BoostTrigger
{
public:
BloodlustTrigger(PlayerbotAI* ai) : BoostTrigger(ai, "bloodlust") {}
};
class MaelstromWeaponTrigger : public HasAuraTrigger
{
public:
MaelstromWeaponTrigger(PlayerbotAI* ai) : HasAuraTrigger(ai, "maelstrom weapon") {}
};
class WindShearInterruptEnemyHealerSpellTrigger : public InterruptEnemyHealerTrigger
{
public:
WindShearInterruptEnemyHealerSpellTrigger(PlayerbotAI* ai) : InterruptEnemyHealerTrigger(ai, "wind shear") {}
};
class CurePoisonTrigger : public NeedCureTrigger
{
public:
CurePoisonTrigger(PlayerbotAI* ai) : NeedCureTrigger(ai, "cure poison", DISPEL_POISON) {}
};
class PartyMemberCurePoisonTrigger : public PartyMemberNeedCureTrigger
{
public:
PartyMemberCurePoisonTrigger(PlayerbotAI* ai) : PartyMemberNeedCureTrigger(ai, "cure poison", DISPEL_POISON) {}
};
class CureDiseaseTrigger : public NeedCureTrigger
{
public:
CureDiseaseTrigger(PlayerbotAI* ai) : NeedCureTrigger(ai, "cure disease", DISPEL_DISEASE) {}
};
class PartyMemberCureDiseaseTrigger : public PartyMemberNeedCureTrigger
{
public:
PartyMemberCureDiseaseTrigger(PlayerbotAI* ai) : PartyMemberNeedCureTrigger(ai, "cure disease", DISPEL_DISEASE) {}
};
class PartyTankEarthShieldTrigger : public BuffOnTankTrigger
{
public:
PartyTankEarthShieldTrigger(PlayerbotAI* ai) : BuffOnTankTrigger(ai, "earth shield") {}
virtual bool IsActive()
{
Group* group = bot->GetGroup();
if (group)
{
for (GroupReference* ref = group->GetFirstMember(); ref; ref = ref->next())
{
if (ai->HasAura("earth shield", ref->getSource(), false, true))
return false;
}
}
return BuffOnTankTrigger::IsActive();
}
};
CAN_CAST_TRIGGER(ChainLightningTrigger, "chain lightning");
CAN_CAST_TRIGGER(StormstrikeTrigger, "stormstrike");
}
| 0 | 0.883697 | 1 | 0.883697 | game-dev | MEDIA | 0.945915 | game-dev | 0.627109 | 1 | 0.627109 |
v3921358/MapleRoot | 7,467 | MapleRoot/scripts/event/HenesysPQ.js | /*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2016 - 2019 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author: Ronan
* @event: Henesys PQ
*/
var isPq = true;
var minPlayers = 3, maxPlayers = 6;
var minLevel = 10, maxLevel = 255;
var entryMap = 910010000;
var exitMap = 910010300;
var recruitMap = 100000200;
var clearMap = 910010100;
var minMapId = 910010000;
var maxMapId = 910010400;
var eventTime = 10; // 10 minutes
const maxLobbies = 1;
function init() {
setEventRequirements();
}
function getMaxLobbies() {
return maxLobbies;
}
function setEventRequirements() {
var reqStr = "";
reqStr += "\r\n Number of players: ";
if (maxPlayers - minPlayers >= 1) {
reqStr += minPlayers + " ~ " + maxPlayers;
} else {
reqStr += minPlayers;
}
reqStr += "\r\n Level range: ";
if (maxLevel - minLevel >= 1) {
reqStr += minLevel + " ~ " + maxLevel;
} else {
reqStr += minLevel;
}
reqStr += "\r\n Time limit: ";
reqStr += eventTime + " minutes";
em.setProperty("party", reqStr);
}
function setEventExclusives(eim) {
var itemSet = [4001095, 4001096, 4001097, 4001098, 4001099, 4001100, 4001101];
eim.setExclusiveItems(itemSet);
}
function setEventRewards(eim) {
var itemSet, itemQty, evLevel, expStages;
evLevel = 1; //Rewards at clear PQ
itemSet = [4001158];
itemQty = [1];
eim.setEventRewards(evLevel, itemSet, itemQty);
expStages = [1600]; //bonus exp given on CLEAR stage signal
eim.setEventClearStageExp(expStages);
}
function getEligibleParty(party) { //selects, from the given party, the team that is allowed to attempt this event
var eligible = [];
var hasLeader = false;
if (party.size() > 0) {
var partyList = party.toArray();
for (var i = 0; i < party.size(); i++) {
var ch = partyList[i];
if (ch.getMapId() == recruitMap && ch.getLevel() >= minLevel && ch.getLevel() <= maxLevel) {
if (ch.isLeader()) {
hasLeader = true;
}
eligible.push(ch);
}
}
}
if (!(hasLeader && eligible.length >= minPlayers && eligible.length <= maxPlayers)) {
eligible = [];
}
return Java.to(eligible, Java.type('net.server.world.PartyCharacter[]'));
}
function setup(level, lobbyid) {
var eim = em.newInstance("Henesys" + lobbyid);
eim.setProperty("level", level);
eim.setProperty("stage", "0");
eim.setProperty("bunnyCake", "0");
eim.setProperty("bunnyDamaged", "0");
eim.getInstanceMap(910010000).resetPQ(level);
eim.getInstanceMap(910010000).allowSummonState(false);
eim.getInstanceMap(910010200).resetPQ(level);
respawnStages(eim);
eim.startEventTimer(eventTime * 60000);
setEventRewards(eim);
setEventExclusives(eim);
return eim;
}
function afterSetup(eim) {}
function respawnStages(eim) {
eim.getInstanceMap(910010000).instanceMapRespawn();
eim.getInstanceMap(910010200).instanceMapRespawn();
eim.schedule("respawnStages", 15 * 1000);
}
function playerEntry(eim, player) {
var map = eim.getMapInstance(entryMap);
player.changeMap(map, map.getPortal(0));
}
function scheduledTimeout(eim) {
if (eim.getProperty("1stageclear") != null) {
var curStage = 910010200, toStage = 910010400;
eim.warpEventTeam(curStage, toStage);
} else {
end(eim);
}
}
function bunnyDefeated(eim) {
eim.dropMessage(5, "Due to your failure to protect the Moon Bunny, you have been transported to the Exile Map.");
end(eim);
}
function playerUnregistered(eim, player) {}
function playerExit(eim, player) {
eim.unregisterPlayer(player);
player.changeMap(exitMap, 0);
}
function playerLeft(eim, player) {
if (!eim.isEventCleared()) {
playerExit(eim, player);
}
}
function changedMap(eim, player, mapid) {
if (mapid < minMapId || mapid > maxMapId || mapid == 910010300) {
if (eim.isEventTeamLackingNow(true, minPlayers, player)) {
eim.unregisterPlayer(player);
end(eim);
} else {
eim.unregisterPlayer(player);
}
}
}
function changedLeader(eim, leader) {
var mapid = leader.getMapId();
if (!eim.isEventCleared() && (mapid < minMapId || mapid > maxMapId)) {
end(eim);
}
}
function playerDead(eim, player) {}
function playerRevive(eim, player) { // player presses ok on the death pop up.
if (eim.isEventTeamLackingNow(true, minPlayers, player)) {
eim.unregisterPlayer(player);
end(eim);
} else {
eim.unregisterPlayer(player);
}
}
function playerDisconnected(eim, player) {
if (eim.isEventTeamLackingNow(true, minPlayers, player)) {
eim.unregisterPlayer(player);
end(eim);
} else {
eim.unregisterPlayer(player);
}
}
function leftParty(eim, player) {
if (eim.isEventTeamLackingNow(false, minPlayers, player)) {
end(eim);
} else {
playerLeft(eim, player);
}
}
function disbandParty(eim) {
if (!eim.isEventCleared()) {
end(eim);
}
}
function monsterValue(eim, mobId) {
return 1;
}
function end(eim) {
var party = eim.getPlayers();
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i));
}
eim.dispose();
}
function giveRandomEventReward(eim, player) {
eim.giveEventReward(player);
}
function clearPQ(eim) {
eim.stopEventTimer();
eim.setEventCleared();
eim.warpEventTeam(910010100);
}
function monsterKilled(mob, eim) {}
function friendlyKilled(mob, eim) {
if (mob.getId() == 9300061) {
eim.schedule("bunnyDefeated", 5 * 1000);
}
}
function friendlyItemDrop(eim, mob) {
if (mob.getId() == 9300061) {
var cakes = eim.getIntProperty("bunnyCake") + 1;
eim.setIntProperty("bunnyCake", cakes);
const PacketCreator = Java.type('tools.PacketCreator');
mob.getMap().broadcastMessage(PacketCreator.serverNotice(6, "The Moon Bunny made rice cake number " + cakes + "."));
}
}
function friendlyDamaged(eim, mob) {
if (mob.getId() == 9300061) {
var bunnyDamage = eim.getIntProperty("bunnyDamaged") + 1;
if (bunnyDamage > 5) {
const PacketCreator = Java.type('tools.PacketCreator');
broadcastMessage(PacketCreator.serverNotice(6, "The Moon Bunny is feeling sick. Please protect it so it can make delicious rice cakes."));
eim.setIntProperty("bunnyDamaged", 0);
}
}
}
function allMonstersDead(eim) {}
function cancelSchedule() {}
function dispose(eim) {}
| 0 | 0.84899 | 1 | 0.84899 | game-dev | MEDIA | 0.952062 | game-dev | 0.940113 | 1 | 0.940113 |
msgpack/msgpack-cli | 3,757 | src/MsgPack/Serialization/ReflectionSerializers/ReflectionEnumMessagePackSerializer`1.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014-2016 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Globalization;
#if FEATURE_TAP
using System.Threading;
using System.Threading.Tasks;
#endif // FEATURE_TAP
namespace MsgPack.Serialization.ReflectionSerializers
{
/// <summary>
/// Implements reflection-based enum serializer for restricted platforms.
/// </summary>
#if !UNITY
[Preserve( AllMembers = true )]
internal class ReflectionEnumMessagePackSerializer<T> : EnumMessagePackSerializer<T>
where T : struct
#else
internal class ReflectionEnumMessagePackSerializer : UnityEnumMessagePackSerializer
#endif // !UNITY
{
#if !UNITY
public ReflectionEnumMessagePackSerializer( SerializationContext context )
: base(
context,
EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(
context,
typeof( T ),
EnumMemberSerializationMethod.Default
)
) { }
#else
public ReflectionEnumMessagePackSerializer( SerializationContext context, Type targetType )
: base(
context,
targetType,
EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(
context,
targetType,
EnumMemberSerializationMethod.Default
)
) { }
#endif // !UNITY
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
#if !UNITY
protected internal override void PackUnderlyingValueTo( Packer packer, T enumValue )
#else
protected internal override void PackUnderlyingValueTo( Packer packer, object enumValue )
#endif // !UNITY
{
packer.Pack( UInt64.Parse( ( ( IFormattable ) enumValue ).ToString( "D", CultureInfo.InvariantCulture ), CultureInfo.InvariantCulture ) );
}
#if FEATURE_TAP
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override Task PackUnderlyingValueToAsync( Packer packer, T enumValue, CancellationToken cancellationToken )
{
return packer.PackAsync( UInt64.Parse( ( ( IFormattable )enumValue ).ToString( "D", CultureInfo.InvariantCulture ), CultureInfo.InvariantCulture ), cancellationToken );
}
#endif // FEATURE_TAP
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
#if !UNITY
protected internal override T UnpackFromUnderlyingValue( MessagePackObject messagePackObject )
{
return ( T )Enum.Parse( typeof( T ), messagePackObject.ToString(), false );
}
#else
protected internal override object UnpackFromUnderlyingValue( MessagePackObject messagePackObject )
{
return Enum.Parse( this.TargetType, messagePackObject.ToString(), false );
}
#endif // !UNITY
}
}
| 0 | 0.827835 | 1 | 0.827835 | game-dev | MEDIA | 0.321112 | game-dev | 0.840332 | 1 | 0.840332 |
lordmilko/ClrDebug | 4,224 | ClrDebug/Extensions/DiaStringMarshaller.cs | using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
#if GENERATED_MARSHALLING
using System.Runtime.InteropServices.Marshalling;
#endif
using static ClrDebug.Extensions;
namespace ClrDebug
{
#if !GENERATED_MARSHALLING
class DiaStringMarshaller : ICustomMarshaler
{
[ThreadStatic]
private object current;
public static ICustomMarshaler GetInstance(string pstrCookie) => new DiaStringMarshaller();
public void CleanUpManagedData(object ManagedObj)
{
}
public void CleanUpNativeData(IntPtr pNativeData)
{
if (current == null)
DiaFreeString(pNativeData);
else
{
if (current is string[] a)
{
for (var i = 0; i < a.Length; i++)
{
var ptr = Marshal.ReadIntPtr(pNativeData + (i * IntPtr.Size));
DiaFreeString(ptr);
}
current = null;
Marshal.FreeHGlobal(pNativeData);
}
else
throw new NotImplementedException($"Don't know how to cleanup a value of type {current.GetType().Name}");
}
}
public int GetNativeDataSize() => throw new NotImplementedException();
public unsafe IntPtr MarshalManagedToNative(object ManagedObj)
{
if (ManagedObj == null)
return IntPtr.Zero;
Debug.Assert(current == null);
if (ManagedObj is string[] a)
{
current = a;
return Marshal.AllocHGlobal(a.Length * IntPtr.Size);
}
if (ManagedObj is string s)
{
//We allocate the string, and then DbgHelp is responsible for freeing it, e.g. dbghelp!diaFillSymbolInfo calls dbghelp!DiaFreeString -> LocalFree
if (DiaStringsUseComHeap)
return Marshal.StringToBSTR(s);
//We can't just do Marshal.StringToHGlobalUni; we need to create a fake BSTR with a length in front of it and hand out a pointer to the area
//after the length, so that when dbghelp!DiaFreeString rewinds the pointer, it gets the true allocation address
var charBytes = s.Length * 2 + 2; //+2 for the null terminator
var buffer = Marshal.AllocHGlobal(charBytes + 4); //Each character is 2 bytes + 4 bytes at the start for the length + 2 bytes for the null terminator
IntPtr str = buffer + 4;
char* dest = (char*) str;
for (var i = 0; i < s.Length; i++)
dest[i] = s[i];
dest[s.Length] = '\0';
*((int*) buffer) = charBytes;
return str;
}
throw new NotImplementedException($"Don't know how to marshal a value of type {ManagedObj.GetType().Name}");
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
if (current != null)
{
if (current is string[] a)
{
for (var i = 0; i < a.Length; i++)
a[i] = DiaStringToManaged(Marshal.ReadIntPtr(pNativeData + (i * IntPtr.Size)));
return a;
}
else
throw new NotImplementedException($"Don't know how to marshal a value of type {current.GetType().Name}");
}
else
return DiaStringToManaged(pNativeData);
}
}
#else
[CustomMarshaller(typeof(string), MarshalMode.Default, typeof(DiaStringMarshaller))]
public static unsafe class DiaStringMarshaller
{
public static void* ConvertToUnmanaged(string managed)
{
if (managed == null)
return (void*) IntPtr.Zero;
throw new NotImplementedException();
}
public static string ConvertToManaged(void* unmanaged) => DiaStringToManaged((IntPtr) unmanaged);
public static void Free(void* unmanaged) => DiaFreeString((IntPtr) unmanaged);
}
#endif
}
| 0 | 0.897614 | 1 | 0.897614 | game-dev | MEDIA | 0.598179 | game-dev | 0.90154 | 1 | 0.90154 |
revolucas/CoC-Xray | 45,598 | src/xrEngine/x_ray.cpp | //-----------------------------------------------------------------------------
// File: x_ray.cpp
//
// Programmers:
// Oles - Oles Shishkovtsov
// AlexMX - Alexander Maksimchuk
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "igame_level.h"
#include "igame_persistent.h"
#include "dedicated_server_only.h"
#include "no_single.h"
#include "../xrNetServer/NET_AuthCheck.h"
#include "xr_input.h"
#include "xr_ioconsole.h"
#include "x_ray.h"
#include "std_classes.h"
#include "GameFont.h"
#include "resource.h"
#include "LightAnimLibrary.h"
#include "../xrcdb/ispatial.h"
#include "Text_Console.h"
#include <process.h>
#include <locale.h>
#include "xrSash.h"
//#include "securom_api.h"
//---------------------------------------------------------------------
ENGINE_API CInifile* pGameIni = NULL;
BOOL g_bIntroFinished = FALSE;
extern void Intro(void* fn);
extern void Intro_DSHOW(void* fn);
extern int PASCAL IntroDSHOW_wnd(HINSTANCE hInstC, HINSTANCE hInstP, LPSTR lpCmdLine, int nCmdShow);
//int max_load_stage = 0;
// computing build id
XRCORE_API LPCSTR build_date;
XRCORE_API u32 build_id;
#ifdef MASTER_GOLD
# define NO_MULTI_INSTANCES
#endif // #ifdef MASTER_GOLD
static LPSTR month_id[12] =
{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static int days_in_month[12] =
{
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static int start_day = 31; // 31
static int start_month = 1; // January
static int start_year = 1999; // 1999
// binary hash, mainly for copy-protection
#ifndef DEDICATED_SERVER
#include <ctype.h>
#define DEFAULT_MODULE_HASH "3CAABCFCFF6F3A810019C6A72180F166"
static char szEngineHash[33] = DEFAULT_MODULE_HASH;
PROTECT_API char* ComputeModuleHash(char* pszHash)
{
/*
//SECUROM_MARKER_HIGH_SECURITY_ON(3)
char szModuleFileName[MAX_PATH];
HANDLE hModuleHandle = NULL, hFileMapping = NULL;
LPVOID lpvMapping = NULL;
MEMORY_BASIC_INFORMATION MemoryBasicInformation;
if (!GetModuleFileName(NULL, szModuleFileName, MAX_PATH))
return pszHash;
hModuleHandle = CreateFile(szModuleFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hModuleHandle == INVALID_HANDLE_VALUE)
return pszHash;
hFileMapping = CreateFileMapping(hModuleHandle, NULL, PAGE_READONLY, 0, 0, NULL);
if (hFileMapping == NULL)
{
CloseHandle(hModuleHandle);
return pszHash;
}
lpvMapping = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
if (lpvMapping == NULL)
{
CloseHandle(hFileMapping);
CloseHandle(hModuleHandle);
return pszHash;
}
ZeroMemory(&MemoryBasicInformation, sizeof(MEMORY_BASIC_INFORMATION));
VirtualQuery(lpvMapping, &MemoryBasicInformation, sizeof(MEMORY_BASIC_INFORMATION));
if (MemoryBasicInformation.RegionSize)
{
char szHash[33];
MD5Digest((unsigned char*)lpvMapping, (unsigned int)MemoryBasicInformation.RegionSize, szHash);
MD5Digest((unsigned char*)szHash, 32, pszHash);
for (int i = 0; i < 32; ++i)
pszHash[i] = (char)toupper(pszHash[i]);
}
UnmapViewOfFile(lpvMapping);
CloseHandle(hFileMapping);
CloseHandle(hModuleHandle);
//SECUROM_MARKER_HIGH_SECURITY_OFF(3)
*/
return pszHash;
}
#endif // DEDICATED_SERVER
void compute_build_id()
{
build_date = __DATE__;
int days;
int months = 0;
int years;
string16 month;
string256 buffer;
xr_strcpy(buffer, __DATE__);
sscanf(buffer, "%s %d %d\0", month, &days, &years);
for (int i = 0; i < 12; i++)
{
if (_stricmp(month_id[i], month))
continue;
months = i;
break;
}
build_id = (years - start_year) * 365 + days - start_day;
for (int i = 0; i < months; ++i)
build_id += days_in_month[i];
for (int i = 0; i < start_month - 1; ++i)
build_id -= days_in_month[i];
}
//---------------------------------------------------------------------
// 2446363
// umbt@ukr.net
//////////////////////////////////////////////////////////////////////////
struct _SoundProcessor : public pureFrame
{
virtual void _BCL OnFrame()
{
//Msg ("------------- sound: %d [%3.2f,%3.2f,%3.2f]",u32(Device.dwFrame),VPUSH(Device.vCameraPosition));
Device.Statistic->Sound.Begin();
::Sound->update(Device.vCameraPosition, Device.vCameraDirection, Device.vCameraTop);
Device.Statistic->Sound.End();
}
} SoundProcessor;
//////////////////////////////////////////////////////////////////////////
// global variables
ENGINE_API CApplication* pApp = NULL;
static HWND logoWindow = NULL;
int doLauncher();
void doBenchmark(LPCSTR name);
ENGINE_API bool g_bBenchmark = false;
string512 g_sBenchmarkName;
ENGINE_API string512 g_sLaunchOnExit_params;
ENGINE_API string512 g_sLaunchOnExit_app;
ENGINE_API string_path g_sLaunchWorkingFolder;
// -------------------------------------------
// startup point
void InitEngine()
{
Engine.Initialize();
while (!g_bIntroFinished) Sleep(100);
Device.Initialize();
}
struct path_excluder_predicate
{
explicit path_excluder_predicate(xr_auth_strings_t const* ignore) :
m_ignore(ignore)
{
}
bool xr_stdcall is_allow_include(LPCSTR path)
{
if (!m_ignore)
return true;
return allow_to_include_path(*m_ignore, path);
}
xr_auth_strings_t const* m_ignore;
};
PROTECT_API void InitSettings()
{
#ifndef DEDICATED_SERVER
Msg("EH: %s\n", ComputeModuleHash(szEngineHash));
#endif // DEDICATED_SERVER
string_path fname;
FS.update_path(fname, "$game_config$", "system.ltx");
#ifdef DEBUG
Msg("Updated path to system.ltx is %s", fname);
#endif // #ifdef DEBUG
pSettings = xr_new<CInifile>(fname, TRUE);
CHECK_OR_EXIT(0 != pSettings->section_count(), make_string("Cannot find file %s.\nReinstalling application may fix this problem.", fname));
xr_auth_strings_t tmp_ignore_pathes;
xr_auth_strings_t tmp_check_pathes;
fill_auth_check_params(tmp_ignore_pathes, tmp_check_pathes);
path_excluder_predicate tmp_excluder(&tmp_ignore_pathes);
CInifile::allow_include_func_t tmp_functor;
tmp_functor.bind(&tmp_excluder, &path_excluder_predicate::is_allow_include);
pSettingsAuth = xr_new<CInifile>(
fname,
TRUE,
TRUE,
FALSE,
0,
tmp_functor
);
FS.update_path(fname, "$game_config$", "game.ltx");
pGameIni = xr_new<CInifile>(fname, TRUE);
CHECK_OR_EXIT(0 != pGameIni->section_count(), make_string("Cannot find file %s.\nReinstalling application may fix this problem.", fname));
}
PROTECT_API void InitConsole()
{
////SECUROM_MARKER_SECURITY_ON(5)
#ifdef DEDICATED_SERVER
{
Console = xr_new<CTextConsole>();
}
#else
// else
{
Console = xr_new<CConsole>();
}
#endif
Console->Initialize();
xr_strcpy(Console->ConfigFile, "user.ltx");
if (strstr(Core.Params, "-ltx "))
{
string64 c_name;
sscanf(strstr(Core.Params, "-ltx ") + 5, "%[^ ] ", c_name);
xr_strcpy(Console->ConfigFile, c_name);
}
////SECUROM_MARKER_SECURITY_OFF(5)
}
PROTECT_API void InitInput()
{
BOOL bCaptureInput = !strstr(Core.Params, "-i");
pInput = xr_new<CInput>(bCaptureInput);
}
void destroyInput()
{
xr_delete(pInput);
}
PROTECT_API void InitSound1()
{
CSound_manager_interface::_create(0);
}
PROTECT_API void InitSound2()
{
CSound_manager_interface::_create(1);
}
void destroySound()
{
CSound_manager_interface::_destroy();
}
void destroySettings()
{
CInifile** s = (CInifile**)(&pSettings);
xr_delete(*s);
xr_delete(pGameIni);
}
void destroyConsole()
{
Console->Execute("cfg_save");
Console->Destroy();
xr_delete(Console);
}
void destroyEngine()
{
Device.Destroy();
Engine.Destroy();
}
void execUserScript()
{
Console->Execute("default_controls");
Console->ExecuteScript(Console->ConfigFile);
}
void slowdownthread(void*)
{
// Sleep (30*1000);
for (;;)
{
if (Device.Statistic->fFPS < 30) Sleep(1);
if (Device.mt_bMustExit) return;
if (0 == pSettings) return;
if (0 == Console) return;
if (0 == pInput) return;
if (0 == pApp) return;
}
}
void CheckPrivilegySlowdown()
{
#ifdef DEBUG
if (strstr(Core.Params, "-slowdown"))
{
thread_spawn(slowdownthread, "slowdown", 0, 0);
}
if (strstr(Core.Params, "-slowdown2x"))
{
thread_spawn(slowdownthread, "slowdown", 0, 0);
thread_spawn(slowdownthread, "slowdown", 0, 0);
}
#endif // DEBUG
}
void Startup()
{
InitSound1();
execUserScript();
InitSound2();
// ...command line for auto start
{
LPCSTR pStartup = strstr(Core.Params, "-start ");
if (pStartup) Console->Execute(pStartup + 1);
}
{
LPCSTR pStartup = strstr(Core.Params, "-load ");
if (pStartup) Console->Execute(pStartup + 1);
}
// Initialize APP
//#ifndef DEDICATED_SERVER
ShowWindow(Device.m_hWnd, SW_SHOWNORMAL);
Device.Create();
//#endif
LALib.OnCreate();
pApp = xr_new<CApplication>();
g_pGamePersistent = (IGame_Persistent*)NEW_INSTANCE(CLSID_GAME_PERSISTANT);
g_SpatialSpace = xr_new<ISpatial_DB>();
g_SpatialSpacePhysic = xr_new<ISpatial_DB>();
// Destroy LOGO
DestroyWindow(logoWindow);
logoWindow = NULL;
// Main cycle
Memory.mem_usage();
Device.Run();
// Destroy APP
xr_delete(g_SpatialSpacePhysic);
xr_delete(g_SpatialSpace);
DEL_INSTANCE(g_pGamePersistent);
xr_delete(pApp);
Engine.Event.Dump();
// Destroying
//. destroySound();
destroyInput();
if (!g_bBenchmark && !g_SASH.IsRunning())
destroySettings();
LALib.OnDestroy();
if (!g_bBenchmark && !g_SASH.IsRunning())
destroyConsole();
else
Console->Destroy();
destroySound();
destroyEngine();
}
static BOOL CALLBACK logDlgProc(HWND hw, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case WM_DESTROY:
break;
case WM_CLOSE:
DestroyWindow(hw);
break;
case WM_COMMAND:
if (LOWORD(wp) == IDCANCEL)
DestroyWindow(hw);
break;
default:
return FALSE;
}
return TRUE;
}
/*
void test_rtc ()
{
CStatTimer tMc,tM,tC,tD;
u32 bytes=0;
tMc.FrameStart ();
tM.FrameStart ();
tC.FrameStart ();
tD.FrameStart ();
::Random.seed (0x12071980);
for (u32 test=0; test<10000; test++)
{
u32 in_size = ::Random.randI(1024,256*1024);
u32 out_size_max = rtc_csize (in_size);
u8* p_in = xr_alloc<u8> (in_size);
u8* p_in_tst = xr_alloc<u8> (in_size);
u8* p_out = xr_alloc<u8> (out_size_max);
for (u32 git=0; git<in_size; git++) p_in[git] = (u8)::Random.randI (8); // garbage
bytes += in_size;
tMc.Begin ();
memcpy (p_in_tst,p_in,in_size);
tMc.End ();
tM.Begin ();
CopyMemory(p_in_tst,p_in,in_size);
tM.End ();
tC.Begin ();
u32 out_size = rtc_compress (p_out,out_size_max,p_in,in_size);
tC.End ();
tD.Begin ();
u32 in_size_tst = rtc_decompress(p_in_tst,in_size,p_out,out_size);
tD.End ();
// sanity check
R_ASSERT (in_size == in_size_tst);
for (u32 tit=0; tit<in_size; tit++) R_ASSERT(p_in[tit] == p_in_tst[tit]); // garbage
xr_free (p_out);
xr_free (p_in_tst);
xr_free (p_in);
}
tMc.FrameEnd (); float rMc = 1000.f*(float(bytes)/tMc.result)/(1024.f*1024.f);
tM.FrameEnd (); float rM = 1000.f*(float(bytes)/tM.result)/(1024.f*1024.f);
tC.FrameEnd (); float rC = 1000.f*(float(bytes)/tC.result)/(1024.f*1024.f);
tD.FrameEnd (); float rD = 1000.f*(float(bytes)/tD.result)/(1024.f*1024.f);
Msg ("* memcpy: %5.2f M/s (%3.1f%%)",rMc,100.f*rMc/rMc);
Msg ("* mm-memcpy: %5.2f M/s (%3.1f%%)",rM,100.f*rM/rMc);
Msg ("* compression: %5.2f M/s (%3.1f%%)",rC,100.f*rC/rMc);
Msg ("* decompression: %5.2f M/s (%3.1f%%)",rD,100.f*rD/rMc);
}
*/
extern void testbed(void);
// video
/*
static HINSTANCE g_hInstance ;
static HINSTANCE g_hPrevInstance ;
static int g_nCmdShow ;
void __cdecl intro_dshow_x (void*)
{
IntroDSHOW_wnd (g_hInstance,g_hPrevInstance,"GameData\\Stalker_Intro.avi",g_nCmdShow);
g_bIntroFinished = TRUE ;
}
*/
#define dwStickyKeysStructSize sizeof( STICKYKEYS )
#define dwFilterKeysStructSize sizeof( FILTERKEYS )
#define dwToggleKeysStructSize sizeof( TOGGLEKEYS )
struct damn_keys_filter
{
BOOL bScreenSaverState;
// Sticky & Filter & Toggle keys
STICKYKEYS StickyKeysStruct;
FILTERKEYS FilterKeysStruct;
TOGGLEKEYS ToggleKeysStruct;
DWORD dwStickyKeysFlags;
DWORD dwFilterKeysFlags;
DWORD dwToggleKeysFlags;
damn_keys_filter()
{
// Screen saver stuff
bScreenSaverState = FALSE;
// Saveing current state
SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, (PVOID)&bScreenSaverState, 0);
if (bScreenSaverState)
// Disable screensaver
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, NULL, 0);
dwStickyKeysFlags = 0;
dwFilterKeysFlags = 0;
dwToggleKeysFlags = 0;
ZeroMemory(&StickyKeysStruct, dwStickyKeysStructSize);
ZeroMemory(&FilterKeysStruct, dwFilterKeysStructSize);
ZeroMemory(&ToggleKeysStruct, dwToggleKeysStructSize);
StickyKeysStruct.cbSize = dwStickyKeysStructSize;
FilterKeysStruct.cbSize = dwFilterKeysStructSize;
ToggleKeysStruct.cbSize = dwToggleKeysStructSize;
// Saving current state
SystemParametersInfo(SPI_GETSTICKYKEYS, dwStickyKeysStructSize, (PVOID)&StickyKeysStruct, 0);
SystemParametersInfo(SPI_GETFILTERKEYS, dwFilterKeysStructSize, (PVOID)&FilterKeysStruct, 0);
SystemParametersInfo(SPI_GETTOGGLEKEYS, dwToggleKeysStructSize, (PVOID)&ToggleKeysStruct, 0);
if (StickyKeysStruct.dwFlags & SKF_AVAILABLE)
{
// Disable StickyKeys feature
dwStickyKeysFlags = StickyKeysStruct.dwFlags;
StickyKeysStruct.dwFlags = 0;
SystemParametersInfo(SPI_SETSTICKYKEYS, dwStickyKeysStructSize, (PVOID)&StickyKeysStruct, 0);
}
if (FilterKeysStruct.dwFlags & FKF_AVAILABLE)
{
// Disable FilterKeys feature
dwFilterKeysFlags = FilterKeysStruct.dwFlags;
FilterKeysStruct.dwFlags = 0;
SystemParametersInfo(SPI_SETFILTERKEYS, dwFilterKeysStructSize, (PVOID)&FilterKeysStruct, 0);
}
if (ToggleKeysStruct.dwFlags & TKF_AVAILABLE)
{
// Disable FilterKeys feature
dwToggleKeysFlags = ToggleKeysStruct.dwFlags;
ToggleKeysStruct.dwFlags = 0;
SystemParametersInfo(SPI_SETTOGGLEKEYS, dwToggleKeysStructSize, (PVOID)&ToggleKeysStruct, 0);
}
}
~damn_keys_filter()
{
if (bScreenSaverState)
// Restoring screen saver
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, TRUE, NULL, 0);
if (dwStickyKeysFlags)
{
// Restore StickyKeys feature
StickyKeysStruct.dwFlags = dwStickyKeysFlags;
SystemParametersInfo(SPI_SETSTICKYKEYS, dwStickyKeysStructSize, (PVOID)&StickyKeysStruct, 0);
}
if (dwFilterKeysFlags)
{
// Restore FilterKeys feature
FilterKeysStruct.dwFlags = dwFilterKeysFlags;
SystemParametersInfo(SPI_SETFILTERKEYS, dwFilterKeysStructSize, (PVOID)&FilterKeysStruct, 0);
}
if (dwToggleKeysFlags)
{
// Restore FilterKeys feature
ToggleKeysStruct.dwFlags = dwToggleKeysFlags;
SystemParametersInfo(SPI_SETTOGGLEKEYS, dwToggleKeysStructSize, (PVOID)&ToggleKeysStruct, 0);
}
}
};
#undef dwStickyKeysStructSize
#undef dwFilterKeysStructSize
#undef dwToggleKeysStructSize
// THQ
BOOL IsOutOfVirtualMemory()
{
#define VIRT_ERROR_SIZE 256
#define VIRT_MESSAGE_SIZE 512
//SECUROM_MARKER_HIGH_SECURITY_ON(1)
MEMORYSTATUSEX statex;
DWORD dwPageFileInMB = 0;
DWORD dwPhysMemInMB = 0;
HINSTANCE hApp = 0;
char pszError[VIRT_ERROR_SIZE];
char pszMessage[VIRT_MESSAGE_SIZE];
ZeroMemory(&statex, sizeof(MEMORYSTATUSEX));
statex.dwLength = sizeof(MEMORYSTATUSEX);
if (!GlobalMemoryStatusEx(&statex))
return 0;
dwPageFileInMB = (DWORD)(statex.ullTotalPageFile / (1024 * 1024));
dwPhysMemInMB = (DWORD)(statex.ullTotalPhys / (1024 * 1024));
//
if ((dwPhysMemInMB > 500) && ((dwPageFileInMB + dwPhysMemInMB) > 2500))
return 0;
hApp = GetModuleHandle(NULL);
if (!LoadString(hApp, RC_VIRT_MEM_ERROR, pszError, VIRT_ERROR_SIZE))
return 0;
if (!LoadString(hApp, RC_VIRT_MEM_TEXT, pszMessage, VIRT_MESSAGE_SIZE))
return 0;
MessageBox(NULL, pszMessage, pszError, MB_OK | MB_ICONHAND);
//SECUROM_MARKER_HIGH_SECURITY_OFF(1)
return 1;
}
#include "xr_ioc_cmd.h"
//typedef void DUMMY_STUFF (const void*,const u32&,void*);
//XRCORE_API DUMMY_STUFF *g_temporary_stuff;
//#define TRIVIAL_ENCRYPTOR_DECODER
//#include "trivial_encryptor.h"
//#define RUSSIAN_BUILD
#if 0
void foo()
{
typedef std::map<int, int> TEST_MAP;
TEST_MAP temp;
temp.insert(std::make_pair(0, 0));
TEST_MAP::const_iterator I = temp.upper_bound(2);
if (I == temp.end())
OutputDebugString("end() returned\r\n");
else
OutputDebugString("last element returned\r\n");
typedef void* pvoid;
LPCSTR path = "d:\\network\\stalker_net2";
FILE* f = fopen(path, "rb");
int file_handle = _fileno(f);
u32 buffer_size = _filelength(file_handle);
pvoid buffer = xr_malloc(buffer_size);
size_t result = fread(buffer, buffer_size, 1, f);
R_ASSERT3(!buffer_size || (result && (buffer_size >= result)), "Cannot read from file", path);
fclose(f);
u32 compressed_buffer_size = rtc_csize(buffer_size);
pvoid compressed_buffer = xr_malloc(compressed_buffer_size);
u32 compressed_size = rtc_compress(compressed_buffer, compressed_buffer_size, buffer, buffer_size);
LPCSTR compressed_path = "d:\\network\\stalker_net2.rtc";
FILE* f1 = fopen(compressed_path, "wb");
fwrite(compressed_buffer, compressed_size, 1, f1);
fclose(f1);
}
#endif // 0
ENGINE_API bool g_dedicated_server = false;
#ifndef DEDICATED_SERVER
#endif // DEDICATED_SERVER
int APIENTRY WinMain_impl(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
char* lpCmdLine,
int nCmdShow)
{
#ifdef DEDICATED_SERVER
Debug._initialize(true);
#else // DEDICATED_SERVER
Debug._initialize(false);
#endif // DEDICATED_SERVER
if (!IsDebuggerPresent())
{
HMODULE const kernel32 = LoadLibrary("kernel32.dll");
R_ASSERT(kernel32);
typedef BOOL(__stdcall*HeapSetInformation_type) (HANDLE, HEAP_INFORMATION_CLASS, PVOID, SIZE_T);
HeapSetInformation_type const heap_set_information =
(HeapSetInformation_type)GetProcAddress(kernel32, "HeapSetInformation");
if (heap_set_information)
{
ULONG HeapFragValue = 2;
#ifdef DEBUG
BOOL const result =
#endif // #ifdef DEBUG
heap_set_information(
GetProcessHeap(),
HeapCompatibilityInformation,
&HeapFragValue,
sizeof(HeapFragValue)
);
#ifdef DEBUG
VERIFY2(result, "can't set process heap low fragmentation");
#endif
}
}
// foo();
#ifndef DEDICATED_SERVER
// Check for virtual memory
if ((strstr(lpCmdLine, "--skipmemcheck") == NULL) && IsOutOfVirtualMemory())
return 0;
// Check for another instance
#ifdef NO_MULTI_INSTANCES
#define STALKER_PRESENCE_MUTEX "Local\\STALKER-COP"
HANDLE hCheckPresenceMutex = INVALID_HANDLE_VALUE;
hCheckPresenceMutex = OpenMutex(READ_CONTROL, FALSE, STALKER_PRESENCE_MUTEX);
if (hCheckPresenceMutex == NULL)
{
// New mutex
hCheckPresenceMutex = CreateMutex(NULL, FALSE, STALKER_PRESENCE_MUTEX);
if (hCheckPresenceMutex == NULL)
// Shit happens
return 2;
}
else
{
// Already running
CloseHandle(hCheckPresenceMutex);
return 1;
}
#endif
#else // DEDICATED_SERVER
g_dedicated_server = true;
#endif // DEDICATED_SERVER
SetThreadAffinityMask(GetCurrentThread(), 1);
// Title window
logoWindow = CreateDialog(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_STARTUP), 0, logDlgProc);
HWND logoPicture = GetDlgItem(logoWindow, IDC_STATIC_LOGO);
RECT logoRect;
GetWindowRect(logoPicture, &logoRect);
SetWindowPos(
logoWindow,
#ifndef DEBUG
HWND_TOPMOST,
#else
HWND_NOTOPMOST,
#endif // NDEBUG
0,
0,
logoRect.right - logoRect.left,
logoRect.bottom - logoRect.top,
SWP_NOMOVE | SWP_SHOWWINDOW// | SWP_NOSIZE
);
UpdateWindow(logoWindow);
// AVI
g_bIntroFinished = TRUE;
g_sLaunchOnExit_app[0] = NULL;
g_sLaunchOnExit_params[0] = NULL;
LPCSTR fsgame_ltx_name = "-fsltx ";
string_path fsgame = "";
//MessageBox(0, lpCmdLine, "my cmd string", MB_OK);
if (strstr(lpCmdLine, fsgame_ltx_name))
{
int sz = xr_strlen(fsgame_ltx_name);
sscanf(strstr(lpCmdLine, fsgame_ltx_name) + sz, "%[^ ] ", fsgame);
//MessageBox(0, fsgame, "using fsltx", MB_OK);
}
// g_temporary_stuff = &trivial_encryptor::decode;
compute_build_id();
Core._initialize("xray", NULL, TRUE, fsgame[0] ? fsgame : NULL);
InitSettings();
// Adjust player & computer name for Asian
if (pSettings->line_exist("string_table", "no_native_input"))
{
xr_strcpy(Core.UserName, sizeof(Core.UserName), "Player");
xr_strcpy(Core.CompName, sizeof(Core.CompName), "Computer");
}
#ifndef DEDICATED_SERVER
{
damn_keys_filter filter;
(void)filter;
#endif // DEDICATED_SERVER
FPU::m24r();
InitEngine();
InitInput();
InitConsole();
Engine.External.CreateRendererList();
LPCSTR benchName = "-batch_benchmark ";
if (strstr(lpCmdLine, benchName))
{
int sz = xr_strlen(benchName);
string64 b_name;
sscanf(strstr(Core.Params, benchName) + sz, "%[^ ] ", b_name);
doBenchmark(b_name);
return 0;
}
Msg("command line %s", lpCmdLine);
LPCSTR sashName = "-openautomate ";
if (strstr(lpCmdLine, sashName))
{
int sz = xr_strlen(sashName);
string512 sash_arg;
sscanf(strstr(Core.Params, sashName) + sz, "%[^ ] ", sash_arg);
//doBenchmark (sash_arg);
g_SASH.Init(sash_arg);
g_SASH.MainLoop();
return 0;
}
if (strstr(lpCmdLine, "-launcher"))
{
int l_res = doLauncher();
if (l_res != 0)
return 0;
};
#ifndef DEDICATED_SERVER
if (strstr(Core.Params, "-r2a"))
Console->Execute("renderer renderer_r2a");
else if (strstr(Core.Params, "-r2"))
Console->Execute("renderer renderer_r2");
else
{
CCC_LoadCFG_custom* pTmp = xr_new<CCC_LoadCFG_custom>("renderer ");
pTmp->Execute(Console->ConfigFile);
xr_delete(pTmp);
}
#else
Console->Execute("renderer renderer_r1");
#endif
//. InitInput ( );
Engine.External.Initialize();
Console->Execute("stat_memory");
Startup();
Core._destroy();
// check for need to execute something external
if (/*xr_strlen(g_sLaunchOnExit_params) && */xr_strlen(g_sLaunchOnExit_app))
{
//CreateProcess need to return results to next two structures
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
//We use CreateProcess to setup working folder
char const* temp_wf = (xr_strlen(g_sLaunchWorkingFolder) > 0) ? g_sLaunchWorkingFolder : NULL;
CreateProcess(g_sLaunchOnExit_app, g_sLaunchOnExit_params, NULL, NULL, FALSE, 0, NULL,
temp_wf, &si, &pi);
}
#ifndef DEDICATED_SERVER
#ifdef NO_MULTI_INSTANCES
// Delete application presence mutex
CloseHandle(hCheckPresenceMutex);
#endif
}
// here damn_keys_filter class instanse will be destroyed
#endif // DEDICATED_SERVER
return 0;
}
int stack_overflow_exception_filter(int exception_code)
{
if (exception_code == EXCEPTION_STACK_OVERFLOW)
{
// Do not call _resetstkoflw here, because
// at this point, the stack is not yet unwound.
// Instead, signal that the handler (the __except block)
// is to be executed.
return EXCEPTION_EXECUTE_HANDLER;
}
else
return EXCEPTION_CONTINUE_SEARCH;
}
#include <boost/crc.hpp>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
char* lpCmdLine,
int nCmdShow)
{
//FILE* file = 0;
//fopen_s ( &file, "z:\\development\\call_of_prypiat\\resources\\gamedata\\shaders\\r3\\objects\\r4\\accum_sun_near_msaa_minmax.ps\\2048__1___________4_11141_", "rb" );
//u32 const file_size = 29544;
//char* buffer = (char*)malloc(file_size);
//fread ( buffer, file_size, 1, file );
//fclose ( file );
//u32 const& crc = *(u32*)buffer;
//boost::crc_32_type processor;
//processor.process_block ( buffer + 4, buffer + file_size );
//u32 const new_crc = processor.checksum( );
//VERIFY ( new_crc == crc );
//free (buffer);
__try
{
WinMain_impl(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
__except (stack_overflow_exception_filter(GetExceptionCode()))
{
_resetstkoflw();
FATAL("stack overflow");
}
return (0);
}
LPCSTR _GetFontTexName(LPCSTR section)
{
static char* tex_names[] = {"texture800", "texture", "texture1600"};
int def_idx = 1;//default 1024x768
int idx = def_idx;
#if 0
u32 w = Device.dwWidth;
if (w <= 800) idx = 0;
else if (w <= 1280)idx = 1;
else idx = 2;
#else
u32 h = Device.dwHeight;
if (h <= 600) idx = 0;
else if (h < 1024) idx = 1;
else idx = 2;
#endif
while (idx >= 0)
{
if (pSettings->line_exist(section, tex_names[idx]))
return pSettings->r_string(section, tex_names[idx]);
--idx;
}
return pSettings->r_string(section, tex_names[def_idx]);
}
void _InitializeFont(CGameFont*& F, LPCSTR section, u32 flags)
{
LPCSTR font_tex_name = _GetFontTexName(section);
R_ASSERT(font_tex_name);
LPCSTR sh_name = pSettings->r_string(section, "shader");
if (!F)
{
F = xr_new<CGameFont>(sh_name, font_tex_name, flags);
}
else
F->Initialize(sh_name, font_tex_name);
if (pSettings->line_exist(section, "size"))
{
float sz = pSettings->r_float(section, "size");
if (flags&CGameFont::fsDeviceIndependent) F->SetHeightI(sz);
else F->SetHeight(sz);
}
if (pSettings->line_exist(section, "interval"))
F->SetInterval(pSettings->r_fvector2(section, "interval"));
}
CApplication::CApplication()
{
ll_dwReference = 0;
max_load_stage = 0;
// events
eQuit = Engine.Event.Handler_Attach("KERNEL:quit", this);
eStart = Engine.Event.Handler_Attach("KERNEL:start", this);
eStartLoad = Engine.Event.Handler_Attach("KERNEL:load", this);
eDisconnect = Engine.Event.Handler_Attach("KERNEL:disconnect", this);
eConsole = Engine.Event.Handler_Attach("KERNEL:console", this);
eStartMPDemo = Engine.Event.Handler_Attach("KERNEL:start_mp_demo", this);
// levels
Level_Current = u32(-1);
Level_Scan();
// Font
pFontSystem = NULL;
// Register us
Device.seqFrame.Add(this, REG_PRIORITY_HIGH + 1000);
if (psDeviceFlags.test(mtSound)) Device.seqFrameMT.Add(&SoundProcessor);
else Device.seqFrame.Add(&SoundProcessor);
Console->Show();
// App Title
// app_title[ 0 ] = '\0';
ls_header[0] = '\0';
ls_tip_number[0] = '\0';
ls_tip[0] = '\0';
}
CApplication::~CApplication()
{
Console->Hide();
// font
xr_delete(pFontSystem);
Device.seqFrameMT.Remove(&SoundProcessor);
Device.seqFrame.Remove(&SoundProcessor);
Device.seqFrame.Remove(this);
// events
Engine.Event.Handler_Detach(eConsole, this);
Engine.Event.Handler_Detach(eDisconnect, this);
Engine.Event.Handler_Detach(eStartLoad, this);
Engine.Event.Handler_Detach(eStart, this);
Engine.Event.Handler_Detach(eQuit, this);
Engine.Event.Handler_Detach(eStartMPDemo, this);
}
extern CRenderDevice Device;
void CApplication::OnEvent(EVENT E, u64 P1, u64 P2)
{
if (E == eQuit)
{
g_SASH.EndBenchmark();
PostQuitMessage(0);
for (u32 i = 0; i < Levels.size(); i++)
{
xr_free(Levels[i].folder);
xr_free(Levels[i].name);
}
}
else if (E == eStart)
{
LPSTR op_server = LPSTR(P1);
LPSTR op_client = LPSTR(P2);
Level_Current = u32(-1);
R_ASSERT(0 == g_pGameLevel);
R_ASSERT(0 != g_pGamePersistent);
#ifdef NO_SINGLE
Console->Execute("main_menu on");
if ((op_server == NULL) ||
(!xr_strlen(op_server)) ||
(
(strstr(op_server, "/dm") || strstr(op_server, "/deathmatch") ||
strstr(op_server, "/tdm") || strstr(op_server, "/teamdeathmatch") ||
strstr(op_server, "/ah") || strstr(op_server, "/artefacthunt") ||
strstr(op_server, "/cta") || strstr(op_server, "/capturetheartefact")
) &&
!strstr(op_server, "/alife")
)
)
#endif // #ifdef NO_SINGLE
{
Console->Execute("main_menu off");
Console->Hide();
//! this line is commented by Dima
//! because I don't see any reason to reset device here
//! Device.Reset (false);
//-----------------------------------------------------------
g_pGamePersistent->PreStart(op_server);
//-----------------------------------------------------------
g_pGameLevel = (IGame_Level*)NEW_INSTANCE(CLSID_GAME_LEVEL);
pApp->LoadBegin();
g_pGamePersistent->Start(op_server);
g_pGameLevel->net_Start(op_server, op_client);
pApp->LoadEnd();
}
xr_free(op_server);
xr_free(op_client);
}
else if (E == eDisconnect)
{
ls_header[0] = '\0';
ls_tip_number[0] = '\0';
ls_tip[0] = '\0';
if (g_pGameLevel)
{
Console->Hide();
g_pGameLevel->net_Stop();
DEL_INSTANCE(g_pGameLevel);
Console->Show();
if ((FALSE == Engine.Event.Peek("KERNEL:quit")) && (FALSE == Engine.Event.Peek("KERNEL:start")))
{
Console->Execute("main_menu off");
Console->Execute("main_menu on");
}
}
R_ASSERT(0 != g_pGamePersistent);
g_pGamePersistent->Disconnect();
}
else if (E == eConsole)
{
LPSTR command = (LPSTR)P1;
Console->ExecuteCommand(command, false);
xr_free(command);
}
else if (E == eStartMPDemo)
{
LPSTR demo_file = LPSTR(P1);
R_ASSERT(0 == g_pGameLevel);
R_ASSERT(0 != g_pGamePersistent);
Console->Execute("main_menu off");
Console->Hide();
Device.Reset(false);
g_pGameLevel = (IGame_Level*)NEW_INSTANCE(CLSID_GAME_LEVEL);
shared_str server_options = g_pGameLevel->OpenDemoFile(demo_file);
//-----------------------------------------------------------
g_pGamePersistent->PreStart(server_options.c_str());
//-----------------------------------------------------------
pApp->LoadBegin();
g_pGamePersistent->Start("");//server_options.c_str()); - no prefetch !
g_pGameLevel->net_StartPlayDemo();
pApp->LoadEnd();
xr_free(demo_file);
}
}
static CTimer phase_timer;
extern ENGINE_API BOOL g_appLoaded = FALSE;
void CApplication::LoadBegin()
{
ll_dwReference++;
if (1 == ll_dwReference)
{
g_appLoaded = FALSE;
#ifndef DEDICATED_SERVER
_InitializeFont(pFontSystem, "ui_font_letterica18_russian", 0);
m_pRender->LoadBegin();
#endif
if (Core.ParamFlags.test(Core.verboselog))
phase_timer.Start();
load_stage = 0;
}
}
void CApplication::LoadEnd()
{
ll_dwReference--;
if (0 == ll_dwReference)
{
if (Core.ParamFlags.test(Core.verboselog))
{
Msg("* phase time: %d ms", phase_timer.GetElapsed_ms());
Msg("* phase cmem: %d K", Memory.mem_usage() / 1024);
Console->Execute("stat_memory");
}
g_appLoaded = TRUE;
// DUMP_PHASE;
}
}
void CApplication::destroy_loading_shaders()
{
m_pRender->destroy_loading_shaders();
//hLevelLogo.destroy ();
//sh_progress.destroy ();
//. ::Sound->mute (false);
}
//u32 calc_progress_color(u32, u32, int, int);
PROTECT_API void CApplication::LoadDraw()
{
if (g_appLoaded) return;
Device.dwFrame += 1;
if (!Device.Begin()) return;
if (g_dedicated_server)
Console->OnRender();
else
load_draw_internal();
Device.End();
}
void CApplication::LoadTitleInt(LPCSTR str1, LPCSTR str2, LPCSTR str3)
{
xr_strcpy(ls_header, str1);
xr_strcpy(ls_tip_number, str2);
xr_strcpy(ls_tip, str3);
// LoadDraw ();
}
void CApplication::LoadStage()
{
load_stage++;
VERIFY(ll_dwReference);
if (Core.ParamFlags.test(Core.verboselog))
{
Msg("* phase time: %d ms", phase_timer.GetElapsed_ms());
phase_timer.Start();
Msg("* phase cmem: %d K", Memory.mem_usage() / 1024);
}
if (g_pGamePersistent->GameType() == 1)
max_load_stage = 17;
else
max_load_stage = 14;
LoadDraw();
}
void CApplication::LoadSwitch()
{
}
// Sequential
void CApplication::OnFrame()
{
Engine.Event.OnFrame();
g_SpatialSpace->update();
g_SpatialSpacePhysic->update();
if (g_pGameLevel)
g_pGameLevel->SoundEvent_Dispatch();
}
void CApplication::Level_Append(LPCSTR folder)
{
string_path N1, N2, N3, N4;
strconcat(sizeof(N1), N1, folder, "level");
strconcat(sizeof(N2), N2, folder, "level.ltx");
strconcat(sizeof(N3), N3, folder, "level.geom");
strconcat(sizeof(N4), N4, folder, "level.cform");
if (
FS.exist("$game_levels$", N1) &&
FS.exist("$game_levels$", N2) &&
FS.exist("$game_levels$", N3) &&
FS.exist("$game_levels$", N4)
)
{
sLevelInfo LI;
LI.folder = xr_strdup(folder);
LI.name = 0;
Levels.push_back(LI);
}
}
void CApplication::Level_Scan()
{
//SECUROM_MARKER_PERFORMANCE_ON(8)
for (u32 i = 0; i < Levels.size(); i++)
{
xr_free(Levels[i].folder);
xr_free(Levels[i].name);
}
Levels.clear();
xr_vector<char*>* folder = FS.file_list_open("$game_levels$", FS_ListFolders | FS_RootOnly);
//. R_ASSERT (folder&&folder->size());
for (u32 i = 0; i < folder->size(); ++i)
Level_Append((*folder)[i]);
FS.file_list_close(folder);
//SECUROM_MARKER_PERFORMANCE_OFF(8)
}
void gen_logo_name(string_path& dest, LPCSTR level_name, int num)
{
strconcat(sizeof(dest), dest, "intro\\intro_", level_name);
u32 len = xr_strlen(dest);
if (dest[len - 1] == '\\')
dest[len - 1] = 0;
string16 buff;
xr_strcat(dest, sizeof(dest), "_");
xr_strcat(dest, sizeof(dest), itoa(num + 1, buff, 10));
}
void CApplication::Level_Set(u32 L)
{
//SECUROM_MARKER_PERFORMANCE_ON(9)
if (L >= Levels.size()) return;
FS.get_path("$level$")->_set(Levels[L].folder);
static string_path path;
if (Level_Current != L)
{
path[0] = 0;
Level_Current = L;
int count = 0;
while (true)
{
string_path temp2;
gen_logo_name(path, Levels[L].folder, count);
if (FS.exist(temp2, "$game_textures$", path, ".dds") || FS.exist(temp2, "$level$", path, ".dds"))
count++;
else
break;
}
if (count)
{
int num = ::Random.randI(count);
gen_logo_name(path, Levels[L].folder, num);
}
}
if (path[0])
m_pRender->setLevelLogo(path);
//SECUROM_MARKER_PERFORMANCE_OFF(9)
}
int CApplication::Level_ID(LPCSTR name, LPCSTR ver, bool bSet)
{
int result = -1;
////SECUROM_MARKER_SECURITY_ON(7)
CLocatorAPI::archives_it it = FS.m_archives.begin();
CLocatorAPI::archives_it it_e = FS.m_archives.end();
bool arch_res = false;
for (; it != it_e; ++it)
{
CLocatorAPI::archive& A = *it;
if (A.hSrcFile == NULL)
{
LPCSTR ln = A.header->r_string("header", "level_name");
LPCSTR lv = A.header->r_string("header", "level_ver");
if (0 == stricmp(ln, name) && 0 == stricmp(lv, ver))
{
FS.LoadArchive(A);
arch_res = true;
}
}
}
if (arch_res)
Level_Scan();
string256 buffer;
strconcat(sizeof(buffer), buffer, name, "\\");
for (u32 I = 0; I < Levels.size(); ++I)
{
if (0 == stricmp(buffer, Levels[I].folder))
{
result = int(I);
break;
}
}
if (bSet && result != -1)
Level_Set(result);
if (arch_res)
g_pGamePersistent->OnAssetsChanged();
////SECUROM_MARKER_SECURITY_OFF(7)
return result;
}
CInifile* CApplication::GetArchiveHeader(LPCSTR name, LPCSTR ver)
{
CLocatorAPI::archives_it it = FS.m_archives.begin();
CLocatorAPI::archives_it it_e = FS.m_archives.end();
for (; it != it_e; ++it)
{
CLocatorAPI::archive& A = *it;
LPCSTR ln = A.header->r_string("header", "level_name");
LPCSTR lv = A.header->r_string("header", "level_ver");
if (0 == stricmp(ln, name) && 0 == stricmp(lv, ver))
{
return A.header;
}
}
return NULL;
}
void CApplication::LoadAllArchives()
{
if (FS.load_all_unloaded_archives())
{
Level_Scan();
g_pGamePersistent->OnAssetsChanged();
}
}
//launcher stuff----------------------------
extern "C" {
typedef int __cdecl LauncherFunc(int);
}
HMODULE hLauncher = NULL;
LauncherFunc* pLauncher = NULL;
void InitLauncher()
{
if (hLauncher)
return;
hLauncher = LoadLibrary("xrLauncher.dll");
if (0 == hLauncher) R_CHK(GetLastError());
R_ASSERT2(hLauncher, "xrLauncher DLL raised exception during loading or there is no xrLauncher.dll at all");
pLauncher = (LauncherFunc*)GetProcAddress(hLauncher, "RunXRLauncher");
R_ASSERT2(pLauncher, "Cannot obtain RunXRLauncher function from xrLauncher.dll");
};
void FreeLauncher()
{
if (hLauncher)
{
FreeLibrary(hLauncher);
hLauncher = NULL;
pLauncher = NULL;
};
}
int doLauncher()
{
/*
execUserScript();
InitLauncher();
int res = pLauncher(0);
FreeLauncher();
if(res == 1) // do benchmark
g_bBenchmark = true;
if(g_bBenchmark){ //perform benchmark cycle
doBenchmark();
// InitLauncher ();
// pLauncher (2); //show results
// FreeLauncher ();
Core._destroy ();
return (1);
};
if(res==8){//Quit
Core._destroy ();
return (1);
}
*/
return 0;
}
void doBenchmark(LPCSTR name)
{
g_bBenchmark = true;
string_path in_file;
FS.update_path(in_file, "$app_data_root$", name);
CInifile ini(in_file);
int test_count = ini.line_count("benchmark");
LPCSTR test_name, t;
shared_str test_command;
for (int i = 0; i < test_count; ++i)
{
ini.r_line("benchmark", i, &test_name, &t);
xr_strcpy(g_sBenchmarkName, test_name);
test_command = ini.r_string_wb("benchmark", test_name);
u32 cmdSize = test_command.size() + 1;
Core.Params = (char*)xr_realloc(Core.Params, cmdSize);
xr_strcpy(Core.Params, cmdSize, test_command.c_str());
xr_strlwr(Core.Params);
InitInput();
if (i)
{
//ZeroMemory(&HW,sizeof(CHW));
// TODO: KILL HW here!
// pApp->m_pRender->KillHW();
InitEngine();
}
Engine.External.Initialize();
xr_strcpy(Console->ConfigFile, "user.ltx");
if (strstr(Core.Params, "-ltx "))
{
string64 c_name;
sscanf(strstr(Core.Params, "-ltx ") + 5, "%[^ ] ", c_name);
xr_strcpy(Console->ConfigFile, c_name);
}
Startup();
}
}
#pragma optimize("g", off)
void CApplication::load_draw_internal()
{
m_pRender->load_draw_internal(*this);
/*
if(!sh_progress){
CHK_DX (HW.pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_ARGB(0,0,0,0),1,0));
return;
}
// Draw logo
u32 Offset;
u32 C = 0xffffffff;
u32 _w = Device.dwWidth;
u32 _h = Device.dwHeight;
FVF::TL* pv = NULL;
//progress
float bw = 1024.0f;
float bh = 768.0f;
Fvector2 k; k.set(float(_w)/bw, float(_h)/bh);
RCache.set_Shader (sh_progress);
CTexture* T = RCache.get_ActiveTexture(0);
Fvector2 tsz;
tsz.set ((float)T->get_Width(),(float)T->get_Height());
Frect back_text_coords;
Frect back_coords;
Fvector2 back_size;
//progress background
static float offs = -0.5f;
back_size.set (1024,768);
back_text_coords.lt.set (0,0);back_text_coords.rb.add(back_text_coords.lt,back_size);
back_coords.lt.set (offs, offs); back_coords.rb.add(back_coords.lt,back_size);
back_coords.lt.mul (k);back_coords.rb.mul(k);
back_text_coords.lt.x/=tsz.x; back_text_coords.lt.y/=tsz.y; back_text_coords.rb.x/=tsz.x; back_text_coords.rb.y/=tsz.y;
pv = (FVF::TL*) RCache.Vertex.Lock(4,ll_hGeom.stride(),Offset);
pv->set (back_coords.lt.x, back_coords.rb.y, C,back_text_coords.lt.x, back_text_coords.rb.y); pv++;
pv->set (back_coords.lt.x, back_coords.lt.y, C,back_text_coords.lt.x, back_text_coords.lt.y); pv++;
pv->set (back_coords.rb.x, back_coords.rb.y, C,back_text_coords.rb.x, back_text_coords.rb.y); pv++;
pv->set (back_coords.rb.x, back_coords.lt.y, C,back_text_coords.rb.x, back_text_coords.lt.y); pv++;
RCache.Vertex.Unlock (4,ll_hGeom.stride());
RCache.set_Geometry (ll_hGeom);
RCache.Render (D3DPT_TRIANGLELIST,Offset,0,4,0,2);
//progress bar
back_size.set (268,37);
back_text_coords.lt.set (0,768);back_text_coords.rb.add(back_text_coords.lt,back_size);
back_coords.lt.set (379 ,726);back_coords.rb.add(back_coords.lt,back_size);
back_coords.lt.mul (k);back_coords.rb.mul(k);
back_text_coords.lt.x/=tsz.x; back_text_coords.lt.y/=tsz.y; back_text_coords.rb.x/=tsz.x; back_text_coords.rb.y/=tsz.y;
u32 v_cnt = 40;
pv = (FVF::TL*)RCache.Vertex.Lock (2*(v_cnt+1),ll_hGeom2.stride(),Offset);
FVF::TL* _pv = pv;
float pos_delta = back_coords.width()/v_cnt;
float tc_delta = back_text_coords.width()/v_cnt;
u32 clr = C;
for(u32 idx=0; idx<v_cnt+1; ++idx){
clr = calc_progress_color(idx,v_cnt,load_stage,max_load_stage);
pv->set (back_coords.lt.x+pos_delta*idx+offs, back_coords.rb.y+offs, 0+EPS_S, 1, clr, back_text_coords.lt.x+tc_delta*idx, back_text_coords.rb.y); pv++;
pv->set (back_coords.lt.x+pos_delta*idx+offs, back_coords.lt.y+offs, 0+EPS_S, 1, clr, back_text_coords.lt.x+tc_delta*idx, back_text_coords.lt.y); pv++;
}
VERIFY (u32(pv-_pv)==2*(v_cnt+1));
RCache.Vertex.Unlock (2*(v_cnt+1),ll_hGeom2.stride());
RCache.set_Geometry (ll_hGeom2);
RCache.Render (D3DPT_TRIANGLESTRIP, Offset, 2*v_cnt);
// Draw title
VERIFY (pFontSystem);
pFontSystem->Clear ();
pFontSystem->SetColor (color_rgba(157,140,120,255));
pFontSystem->SetAligment (CGameFont::alCenter);
pFontSystem->OutI (0.f,0.815f,app_title);
pFontSystem->OnRender ();
//draw level-specific screenshot
if(hLevelLogo){
Frect r;
r.lt.set (257,369);
r.lt.x += offs;
r.lt.y += offs;
r.rb.add (r.lt,Fvector2().set(512,256));
r.lt.mul (k);
r.rb.mul (k);
pv = (FVF::TL*) RCache.Vertex.Lock(4,ll_hGeom.stride(),Offset);
pv->set (r.lt.x, r.rb.y, C, 0, 1); pv++;
pv->set (r.lt.x, r.lt.y, C, 0, 0); pv++;
pv->set (r.rb.x, r.rb.y, C, 1, 1); pv++;
pv->set (r.rb.x, r.lt.y, C, 1, 0); pv++;
RCache.Vertex.Unlock (4,ll_hGeom.stride());
RCache.set_Shader (hLevelLogo);
RCache.set_Geometry (ll_hGeom);
RCache.Render (D3DPT_TRIANGLELIST,Offset,0,4,0,2);
}
*/
}
/*
u32 calc_progress_color(u32 idx, u32 total, int stage, int max_stage)
{
if(idx>(total/2))
idx = total-idx;
float kk = (float(stage+1)/float(max_stage))*(total/2.0f);
float f = 1/(exp((float(idx)-kk)*0.5f)+1.0f);
return color_argb_f (f,1.0f,1.0f,1.0f);
}
*/ | 0 | 0.988225 | 1 | 0.988225 | game-dev | MEDIA | 0.870492 | game-dev | 0.868311 | 1 | 0.868311 |
Sandern/lambdawars | 4,782 | src/game/server/fogvolume.cpp | //--------------------------------------------------------------------------------------------------------
// Copyright (c) 2007 Turtle Rock Studios, Inc. - All Rights Reserved
#include "cbase.h"
#include "fogvolume.h"
#include "collisionutils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
CUtlVector< CFogVolume * > TheFogVolumes;
ConVar fog_volume_debug( "fog_volume_debug", "0", 0, "If enabled, prints diagnostic information about the current fog volume" );
//--------------------------------------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS(fog_volume, CFogVolume);
BEGIN_DATADESC( CFogVolume )
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
DEFINE_KEYFIELD( m_fogName, FIELD_STRING, "FogName" ),
DEFINE_KEYFIELD( m_postProcessName, FIELD_STRING, "PostProcessName" ),
DEFINE_KEYFIELD( m_colorCorrectionName, FIELD_STRING, "ColorCorrectionName" ),
DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_FIELD( m_hFogController, FIELD_EHANDLE ),
DEFINE_FIELD( m_hPostProcessController, FIELD_EHANDLE ),
DEFINE_FIELD( m_hColorCorrectionController, FIELD_EHANDLE ),
END_DATADESC()
//--------------------------------------------------------------------------------------------------------
CFogVolume *CFogVolume::FindFogVolumeForPosition( const Vector &position )
{
CFogVolume *fogVolume = NULL;
for ( int i=0; i<TheFogVolumes.Count(); ++i )
{
fogVolume = TheFogVolumes[i];
Vector vecRelativeCenter;
fogVolume->CollisionProp()->WorldToCollisionSpace( position, &vecRelativeCenter );
if ( IsBoxIntersectingSphere( fogVolume->CollisionProp()->OBBMins(), fogVolume->CollisionProp()->OBBMaxs(), vecRelativeCenter, 1.0f ) )
{
break;
}
fogVolume = NULL;
}
// This doesn't work well if there are multiple players or multiple fog volume queries per frame; might want to relocate this if that's the case
if ( fog_volume_debug.GetBool() )
{
if ( fogVolume )
{
char fogVolumeName[256];
fogVolume->GetKeyValue( "targetname", fogVolumeName, 256 );
engine->Con_NPrintf( 0, "Fog Volume ""%s"" found at position (%f %f %f)", fogVolumeName, position.x, position.y, position.z );
engine->Con_NPrintf( 1, "Fog: %s, post process: %s, color correct: %s", fogVolume->m_fogName, fogVolume->m_postProcessName, fogVolume->m_colorCorrectionName );
}
else
{
engine->Con_NPrintf( 0, "No Fog Volume found at given position (%f %f %f)", position.x, position.y, position.z );
}
}
return fogVolume;
}
//--------------------------------------------------------------------------------------------------------
CFogVolume::CFogVolume() :
BaseClass(),
m_bDisabled( false ),
m_bInFogVolumesList( false )
{
}
//--------------------------------------------------------------------------------------------------------
CFogVolume::~CFogVolume()
{
RemoveFromGlobalList();
}
//--------------------------------------------------------------------------------------------------------
void CFogVolume::Spawn( void )
{
BaseClass::Spawn();
SetSolid( SOLID_BSP );
SetSolidFlags( FSOLID_NOT_SOLID );
SetModel( STRING( GetModelName() ) );
}
//--------------------------------------------------------------------------------------------------------
void CFogVolume::AddToGlobalList()
{
if ( !m_bInFogVolumesList )
{
TheFogVolumes.AddToTail( this );
m_bInFogVolumesList = true;
}
}
//--------------------------------------------------------------------------------------------------------
void CFogVolume::RemoveFromGlobalList()
{
if ( m_bInFogVolumesList )
{
TheFogVolumes.FindAndRemove( this );
m_bInFogVolumesList = false;
}
}
//----------------------------------------------------------------------------
void CFogVolume::InputEnable( inputdata_t &data )
{
m_bDisabled = false;
AddToGlobalList();
}
//----------------------------------------------------------------------------
void CFogVolume::InputDisable( inputdata_t &data )
{
m_bDisabled = true;
RemoveFromGlobalList();
}
//----------------------------------------------------------------------------
// Called when the level loads or is restored
//----------------------------------------------------------------------------
void CFogVolume::Activate()
{
BaseClass::Activate();
m_hFogController = dynamic_cast< CFogController* >( gEntList.FindEntityByName( NULL, m_fogName ) );
m_hPostProcessController = dynamic_cast< CPostProcessController* >( gEntList.FindEntityByName( NULL, m_postProcessName ) );
m_hColorCorrectionController = dynamic_cast< CColorCorrection* >( gEntList.FindEntityByName( NULL, m_colorCorrectionName ) );
if ( !m_bDisabled )
{
AddToGlobalList();
}
}
| 0 | 0.838661 | 1 | 0.838661 | game-dev | MEDIA | 0.770481 | game-dev | 0.866122 | 1 | 0.866122 |
KitsuneX07/Dataset_Maker_for_Galgames | 26,361 | [KEY]青空_AIR/seens/SEEN0504.ke | {-# cp utf8 #- Disassembled with Kprl 1.41 -}
#file 'SEEN0504.TXT'
#resource 'SEEN0504.utf'
#kidoku_type 2
#entrypoint 000
intF[3] = 4
intF[4] = 1
title (#res<0000>)
msgHide
intF[1107] = 1
grpMulti ('DAY_000', 0, copy('DAY_804', 0))
farcall (9070, 0)
wavStop
wavLoop ('KAZE', 0)
msgHide
intF[1107] = 1
recOpenBg ('SIRO', 0, 0, 640, 480, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 255, 0)
#res<0001>
pause
#res<0002>
pause
#res<0003>
pause
#res<0004>
pause
#res<0005>
pause
#res<0006>
pause
msgHide
intF[1107] = 1
grpOpenBg ('FGKA19A', 56)
#res<0007>
pause
#res<0008>
pause
#res<0009>
pause
#res<0010>
pause
#res<0011>
pause
#res<0012>
pause
#res<0013>
pause
#res<0014>
pause
#res<0015>
pause
msgHide
intF[1107] = 1
grpOpenBg ('SIRO', 56)
#res<0016>
pause
#res<0017>
pause
wavStopAll
bgmLoop ('BGM16')
intF[1107] = 1
strS[1000] = 'BG016Y'
goto_unless (intF[1107] == 1) @1
intF[1107] = 0
msgHide
@1
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @5
goto_unless (!intF[4]) @2
strS[1003] = 'SDT07'
goto @3
@2
goto_unless (intF[4] == 1) @3
strS[1003] = 'SDT08'
@3
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @4
objBgMove (83, 16, 16)
goto @5
@4
goto_unless (intB[2] == 1) @5
objBgMove (83, 16, 66)
@5
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @6
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@6
bgrMulti (strS[1000], 0)
#res<0018>
pause
#res<0019>
pause
#res<0020>
pause
#res<0021>
pause
#res<0022>
pause
#res<0023>
pause
#res<0024>
pause
#res<0025>
pause
#res<0026>
pause
koePlay (1111435)
#res<0027>
pause
#res<0028>
pause
#res<0029>
pause
#res<0030>
pause
#res<0031>
pause
#res<0032>
pause
#res<0033>
pause
#res<0034>
pause
#res<0035>
pause
#res<0036>
pause
koePlay (1111436)
#res<0037>
pause
goto_unless (intF[1107] == 1) @7
intF[1107] = 0
msgHide
@7
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @11
goto_unless (!intF[4]) @8
strS[1003] = 'SDT07'
goto @9
@8
goto_unless (intF[4] == 1) @9
strS[1003] = 'SDT08'
@9
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @10
objBgMove (83, 16, 16)
goto @11
@10
goto_unless (intB[2] == 1) @11
objBgMove (83, 16, 66)
@11
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @12
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@12
bgrMulti (strS[1000], 60, copy('CGHI11', 61))
koePlay (1111437)
#res<0038>
pause
koePlay (1111438)
#res<0039>
pause
#res<0040>
pause
#res<0041>
pause
#res<0042>
pause
goto_unless (intF[1107] == 1) @13
intF[1107] = 0
msgHide
@13
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @17
goto_unless (!intF[4]) @14
strS[1003] = 'SDT07'
goto @15
@14
goto_unless (intF[4] == 1) @15
strS[1003] = 'SDT08'
@15
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @16
objBgMove (83, 16, 16)
goto @17
@16
goto_unless (intB[2] == 1) @17
objBgMove (83, 16, 66)
@17
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @18
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@18
bgrMulti (strS[1000], 60, copy('CGHI10', 61))
koePlay (1111439)
#res<0043>
pause
koePlay (1111440)
#res<0044>
pause
koePlay (1111441)
#res<0045>
pause
koePlay (1111442)
#res<0046>
pause
koePlay (1111443)
#res<0047>
pause
koePlay (1111444)
#res<0048>
pause
#res<0049>
pause
#res<0050>
pause
goto_unless (intF[1107] == 1) @19
intF[1107] = 0
msgHide
@19
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @23
goto_unless (!intF[4]) @20
strS[1003] = 'SDT07'
goto @21
@20
goto_unless (intF[4] == 1) @21
strS[1003] = 'SDT08'
@21
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @22
objBgMove (83, 16, 16)
goto @23
@22
goto_unless (intB[2] == 1) @23
objBgMove (83, 16, 66)
@23
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @24
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@24
bgrMulti (strS[1000], 60, copy('CGHI13', 61))
koePlay (1111445)
#res<0051>
pause
koePlay (1111446)
#res<0052>
pause
koePlay (1111447)
#res<0053>
pause
koePlay (1111448)
#res<0054>
pause
koePlay (1111449)
#res<0055>
pause
#res<0056>
pause
goto_unless (intF[1107] == 1) @25
intF[1107] = 0
msgHide
@25
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @29
goto_unless (!intF[4]) @26
strS[1003] = 'SDT07'
goto @27
@26
goto_unless (intF[4] == 1) @27
strS[1003] = 'SDT08'
@27
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @28
objBgMove (83, 16, 16)
goto @29
@28
goto_unless (intB[2] == 1) @29
objBgMove (83, 16, 66)
@29
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @30
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@30
bgrMulti (strS[1000], 0)
#res<0057>
pause
#res<0058>
pause
#res<0059>
pause
goto_unless (intF[1107] == 1) @31
intF[1107] = 0
msgHide
@31
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @35
goto_unless (!intF[4]) @32
strS[1003] = 'SDT07'
goto @33
@32
goto_unless (intF[4] == 1) @33
strS[1003] = 'SDT08'
@33
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @34
objBgMove (83, 16, 16)
goto @35
@34
goto_unless (intB[2] == 1) @35
objBgMove (83, 16, 66)
@35
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @36
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@36
bgrMulti (strS[1000], 60, copy('CGHI13', 61))
koePlay (1111450)
#res<0060>
pause
koePlay (1111451)
#res<0061>
pause
koePlay (1111452)
#res<0062>
pause
koePlay (1111453)
#res<0063>
pause
koePlay (1111454)
#res<0064>
pause
goto_unless (intF[1107] == 1) @37
intF[1107] = 0
msgHide
@37
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @41
goto_unless (!intF[4]) @38
strS[1003] = 'SDT07'
goto @39
@38
goto_unless (intF[4] == 1) @39
strS[1003] = 'SDT08'
@39
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @40
objBgMove (83, 16, 16)
goto @41
@40
goto_unless (intB[2] == 1) @41
objBgMove (83, 16, 66)
@41
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @42
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@42
bgrMulti (strS[1000], 0)
#res<0065>
pause
#res<0066>
pause
#res<0067>
pause
#res<0068>
pause
#res<0069>
pause
#res<0070>
pause
#res<0071>
pause
#res<0072>
pause
#res<0073>
pause
#res<0074>
pause
goto_unless (intF[1107] == 1) @43
intF[1107] = 0
msgHide
@43
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @47
goto_unless (!intF[4]) @44
strS[1003] = 'SDT07'
goto @45
@44
goto_unless (intF[4] == 1) @45
strS[1003] = 'SDT08'
@45
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @46
objBgMove (83, 16, 16)
goto @47
@46
goto_unless (intB[2] == 1) @47
objBgMove (83, 16, 66)
@47
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @48
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@48
bgrMulti (strS[1000], 60, copy('CGHI21', 61))
koePlay (1111455)
#res<0075>
pause
#res<0076>
pause
koePlay (1111456)
#res<0077>
pause
koePlay (1111457)
#res<0078>
pause
goto_unless (intF[1107] == 1) @49
intF[1107] = 0
msgHide
@49
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @53
goto_unless (!intF[4]) @50
strS[1003] = 'SDT07'
goto @51
@50
goto_unless (intF[4] == 1) @51
strS[1003] = 'SDT08'
@51
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @52
objBgMove (83, 16, 16)
goto @53
@52
goto_unless (intB[2] == 1) @53
objBgMove (83, 16, 66)
@53
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @54
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@54
bgrMulti (strS[1000], 60, copy('CGHI22', 61))
koePlay (1111458)
#res<0079>
pause
#res<0080>
pause
#res<0081>
pause
goto_unless (intF[1107] == 1) @55
intF[1107] = 0
msgHide
@55
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @59
goto_unless (!intF[4]) @56
strS[1003] = 'SDT07'
goto @57
@56
goto_unless (intF[4] == 1) @57
strS[1003] = 'SDT08'
@57
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @58
objBgMove (83, 16, 16)
goto @59
@58
goto_unless (intB[2] == 1) @59
objBgMove (83, 16, 66)
@59
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @60
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@60
bgrMulti (strS[1000], 0)
#res<0082>
pause
#res<0083>
pause
#res<0084>
pause
#res<0085>
pause
#res<0086>
pause
#res<0087>
pause
#res<0088>
pause
#res<0089>
pause
#res<0090>
pause
#res<0091>
pause
koePlay (1111459)
#res<0092>
pause
#res<0093>
pause
#res<0094>
pause
koePlay (1111460)
#res<0095>
pause
goto_unless (intF[1107] == 1) @61
intF[1107] = 0
msgHide
@61
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @65
goto_unless (!intF[4]) @62
strS[1003] = 'SDT07'
goto @63
@62
goto_unless (intF[4] == 1) @63
strS[1003] = 'SDT08'
@63
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @64
objBgMove (83, 16, 16)
goto @65
@64
goto_unless (intB[2] == 1) @65
objBgMove (83, 16, 66)
@65
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @66
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@66
bgrMulti (strS[1000], 60, copy('CGHI11', 61))
koePlay (1111461)
#res<0096>
pause
koePlay (1111462)
#res<0097>
pause
koePlay (1111463)
#res<0098>
pause
koePlay (1111464)
#res<0099>
pause
koePlay (1111465)
#res<0100>
pause
bgmFadeOut (1200)
msgHide
intF[1107] = 1
grpOpenBg ('KURO', 48)
intF[1107] = 1
strS[1000] = 'BG014Y'
goto_unless (intF[1107] == 1) @67
intF[1107] = 0
msgHide
@67
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @71
goto_unless (!intF[4]) @68
strS[1003] = 'SDT07'
goto @69
@68
goto_unless (intF[4] == 1) @69
strS[1003] = 'SDT08'
@69
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @70
objBgMove (83, 16, 16)
goto @71
@70
goto_unless (intB[2] == 1) @71
objBgMove (83, 16, 66)
@71
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @72
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@72
bgrMulti (strS[1000], 48)
bgmLoop ('BGM19')
#res<0101>
pause
koePlay (1111466)
#res<0102>
pause
#res<0103>
pause
#res<0104>
pause
#res<0105>
pause
#res<0106>
pause
#res<0107>
pause
#res<0108>
pause
#res<0109>
pause
#res<0110>
pause
goto_unless (intF[1107] == 1) @73
intF[1107] = 0
msgHide
@73
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @77
goto_unless (!intF[4]) @74
strS[1003] = 'SDT07'
goto @75
@74
goto_unless (intF[4] == 1) @75
strS[1003] = 'SDT08'
@75
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @76
objBgMove (83, 16, 16)
goto @77
@76
goto_unless (intB[2] == 1) @77
objBgMove (83, 16, 66)
@77
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @78
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@78
bgrMulti (strS[1000], 60, copy('CGHI11', 61))
koePlay (1111467)
#res<0111>
pause
koePlay (1111468)
#res<0112>
pause
goto_unless (intF[1107] == 1) @79
intF[1107] = 0
msgHide
@79
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @83
goto_unless (!intF[4]) @80
strS[1003] = 'SDT07'
goto @81
@80
goto_unless (intF[4] == 1) @81
strS[1003] = 'SDT08'
@81
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @82
objBgMove (83, 16, 16)
goto @83
@82
goto_unless (intB[2] == 1) @83
objBgMove (83, 16, 66)
@83
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @84
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@84
bgrMulti (strS[1000], 60, copy('CGHI10', 61))
koePlay (1111469)
#res<0113>
pause
koePlay (1111470)
#res<0114>
pause
#res<0115>
pause
goto_unless (intF[1107] == 1) @85
intF[1107] = 0
msgHide
@85
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @89
goto_unless (!intF[4]) @86
strS[1003] = 'SDT07'
goto @87
@86
goto_unless (intF[4] == 1) @87
strS[1003] = 'SDT08'
@87
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @88
objBgMove (83, 16, 16)
goto @89
@88
goto_unless (intB[2] == 1) @89
objBgMove (83, 16, 66)
@89
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @90
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@90
bgrMulti (strS[1000], 60, copy('CGHI12', 61))
koePlay (1111471)
#res<0116>
pause
koePlay (1111472)
#res<0117>
pause
koePlay (1111473)
#res<0118>
pause
goto_unless (intF[1107] == 1) @91
intF[1107] = 0
msgHide
@91
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @95
goto_unless (!intF[4]) @92
strS[1003] = 'SDT07'
goto @93
@92
goto_unless (intF[4] == 1) @93
strS[1003] = 'SDT08'
@93
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @94
objBgMove (83, 16, 16)
goto @95
@94
goto_unless (intB[2] == 1) @95
objBgMove (83, 16, 66)
@95
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @96
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@96
bgrMulti (strS[1000], 60, copy('CGHI22', 61))
koePlay (1111474)
#res<0119>
pause
goto_unless (intF[1107] == 1) @97
intF[1107] = 0
msgHide
@97
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @101
goto_unless (!intF[4]) @98
strS[1003] = 'SDT07'
goto @99
@98
goto_unless (intF[4] == 1) @99
strS[1003] = 'SDT08'
@99
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @100
objBgMove (83, 16, 16)
goto @101
@100
goto_unless (intB[2] == 1) @101
objBgMove (83, 16, 66)
@101
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @102
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@102
bgrMulti (strS[1000], 0)
#res<0120>
pause
goto_unless (intF[1107] == 1) @103
intF[1107] = 0
msgHide
@103
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @107
goto_unless (!intF[4]) @104
strS[1003] = 'SDT07'
goto @105
@104
goto_unless (intF[4] == 1) @105
strS[1003] = 'SDT08'
@105
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @106
objBgMove (83, 16, 16)
goto @107
@106
goto_unless (intB[2] == 1) @107
objBgMove (83, 16, 66)
@107
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @108
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@108
bgrMulti (strS[1000], 60, copy('CGHI23', 61))
koePlay (1111475)
#res<0121>
pause
koePlay (1111476)
#res<0122>
pause
goto_unless (intF[1107] == 1) @109
intF[1107] = 0
msgHide
@109
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @113
goto_unless (!intF[4]) @110
strS[1003] = 'SDT07'
goto @111
@110
goto_unless (intF[4] == 1) @111
strS[1003] = 'SDT08'
@111
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @112
objBgMove (83, 16, 16)
goto @113
@112
goto_unless (intB[2] == 1) @113
objBgMove (83, 16, 66)
@113
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @114
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@114
bgrMulti (strS[1000], 60, copy('CGPO20T', 62), copy('CGHI23', 63))
koePlay (1111477)
#res<0123>
pause
koePlay (1111478)
#res<0124>
pause
koePlay (1111479)
#res<0125>
pause
bgmFadeOut (1200)
intF[1107] = 1
strS[1000] = 'BG013N'
goto_unless (intF[1107] == 1) @115
intF[1107] = 0
msgHide
@115
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @119
goto_unless (!intF[4]) @116
strS[1003] = 'SDT07'
goto @117
@116
goto_unless (intF[4] == 1) @117
strS[1003] = 'SDT08'
@117
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @118
objBgMove (83, 16, 16)
goto @119
@118
goto_unless (intB[2] == 1) @119
objBgMove (83, 16, 66)
@119
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @120
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@120
bgrMulti (strS[1000], 48)
wavStop
wavLoop ('MUSHI', 0)
#res<0126>
pause
#res<0127>
pause
#res<0128>
pause
#res<0129>
pause
intF[1107] = 1
strS[1000] = 'BG012N'
goto_unless (intF[1107] == 1) @121
intF[1107] = 0
msgHide
@121
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @125
goto_unless (!intF[4]) @122
strS[1003] = 'SDT07'
goto @123
@122
goto_unless (intF[4] == 1) @123
strS[1003] = 'SDT08'
@123
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @124
objBgMove (83, 16, 16)
goto @125
@124
goto_unless (intB[2] == 1) @125
objBgMove (83, 16, 66)
@125
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @126
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@126
bgrMulti (strS[1000], 48)
koePlay (1111480)
#res<0130>
pause
#res<0131>
pause
#res<0132>
pause
#res<0133>
pause
#res<0134>
pause
#res<0135>
pause
#res<0136>
pause
goto_unless (intF[1107] == 1) @127
intF[1107] = 0
msgHide
@127
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @131
goto_unless (!intF[4]) @128
strS[1003] = 'SDT07'
goto @129
@128
goto_unless (intF[4] == 1) @129
strS[1003] = 'SDT08'
@129
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @130
objBgMove (83, 16, 16)
goto @131
@130
goto_unless (intB[2] == 1) @131
objBgMove (83, 16, 66)
@131
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @132
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@132
bgrMulti (strS[1000], 60, copy('CGHI11N', 61))
koePlay (1111481)
#res<0137>
pause
#res<0138>
pause
#res<0139>
pause
goto_unless (intF[1107] == 1) @133
intF[1107] = 0
msgHide
@133
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @137
goto_unless (!intF[4]) @134
strS[1003] = 'SDT07'
goto @135
@134
goto_unless (intF[4] == 1) @135
strS[1003] = 'SDT08'
@135
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @136
objBgMove (83, 16, 16)
goto @137
@136
goto_unless (intB[2] == 1) @137
objBgMove (83, 16, 66)
@137
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @138
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@138
bgrMulti (strS[1000], 60, copy('CGHI14N', 61))
koePlay (1111482)
#res<0140>
pause
#res<0141>
pause
#res<0142>
pause
#res<0143>
pause
#res<0144>
pause
goto_unless (intF[1107] == 1) @139
intF[1107] = 0
msgHide
@139
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @143
goto_unless (!intF[4]) @140
strS[1003] = 'SDT07'
goto @141
@140
goto_unless (intF[4] == 1) @141
strS[1003] = 'SDT08'
@141
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @142
objBgMove (83, 16, 16)
goto @143
@142
goto_unless (intB[2] == 1) @143
objBgMove (83, 16, 66)
@143
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @144
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@144
bgrMulti (strS[1000], 60, copy('CGHI21N', 61))
#res<0145>
pause
goto_unless (intF[1107] == 1) @145
intF[1107] = 0
msgHide
@145
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @149
goto_unless (!intF[4]) @146
strS[1003] = 'SDT07'
goto @147
@146
goto_unless (intF[4] == 1) @147
strS[1003] = 'SDT08'
@147
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @148
objBgMove (83, 16, 16)
goto @149
@148
goto_unless (intB[2] == 1) @149
objBgMove (83, 16, 66)
@149
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @150
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@150
bgrMulti (strS[1000], 60, copy('CGHI14N', 61))
koePlay (1111483)
#res<0146>
pause
#res<0147>
pause
goto_unless (intF[1107] == 1) @151
intF[1107] = 0
msgHide
@151
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @155
goto_unless (!intF[4]) @152
strS[1003] = 'SDT07'
goto @153
@152
goto_unless (intF[4] == 1) @153
strS[1003] = 'SDT08'
@153
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @154
objBgMove (83, 16, 16)
goto @155
@154
goto_unless (intB[2] == 1) @155
objBgMove (83, 16, 66)
@155
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @156
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@156
bgrMulti (strS[1000], 0)
#res<0148>
pause
#res<0149>
pause
#res<0150>
pause
#res<0151>
pause
goto_unless (intF[1107] == 1) @157
intF[1107] = 0
msgHide
@157
stackClear
objBgClear (83)
op<1:060:00001, 0> (83)
goto_unless (intF[2] == 1) @161
goto_unless (!intF[4]) @158
strS[1003] = 'SDT07'
goto @159
@158
goto_unless (intF[4] == 1) @159
strS[1003] = 'SDT08'
@159
strS[0] = itoa (intF[3], 2)
strS[1003] += strS[0]
objBgOfFile (83, strS[1003], 1)
goto_unless (!intB[2]) @160
objBgMove (83, 16, 16)
goto @161
@160
goto_unless (intB[2] == 1) @161
objBgMove (83, 16, 66)
@161
objBgClear (81)
objBgClear (82)
op<1:060:00001, 0> (81)
op<1:060:00001, 0> (82)
goto_unless (intB[2] == 1) @162
objBgOfRect (81, 0, 0, 640, 50, 1)
objBgOfRect (82, 0, 430, 640, 50, 1)
objBgColour (81, 0, 0, 0, 255)
objBgColour (82, 0, 0, 0, 255)
@162
bgrMulti (strS[1000], 60, copy('CGHI14N', 61))
koePlay (1111484)
#res<0152>
pause
#res<0153>
pause
#res<0154>
pause
#res<0155>
pause
#res<0156>
pause
msgHide
intF[1107] = 1
recOpenBg ('KURO', 0, 0, 640, 480, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 255, 0)
wavStopAll
bgmLoop ('BGM11')
#res<0157>
pause
#res<0158>
pause
#res<0159>
pause
#res<0160>
pause
koePlay (1111485)
#res<0161>
pause
#res<0162>
pause
koePlay (1111486)
#res<0163>
pause
#res<0164>
pause
#res<0165>
pause
#res<0166>
pause
#res<0167>
pause
#res<0168>
pause
#res<0169>
pause
#res<0170>
pause
koePlay (1111487)
#res<0171>
pause
#res<0172>
pause
#res<0173>
pause
koePlay (1111488)
#res<0174>
pause
#res<0175>
pause
koePlay (1111489)
#res<0176>
pause
#res<0177>
pause
#res<0178>
pause
#res<0179>
pause
#res<0180>
pause
#res<0181>
pause
#res<0182>
pause
#res<0183>
pause
#res<0184>
pause
koePlay (1111490)
#res<0185>
pause
#res<0186>
pause
#res<0187>
pause
#res<0188>
pause
#res<0189>
pause
#res<0190>
pause
#res<0191>
pause
#res<0192>
pause
#res<0193>
pause
#res<0194>
pause
#res<0195>
pause
#res<0196>
pause
#res<0197>
pause
#res<0198>
pause
#res<0199>
pause
#res<0200>
pause
bgmFadeOut (1200)
msgHide
intF[1107] = 1
grpOpenBg ('SIRO', 26)
wait (1000)
#res<0201>
pause
bgmStop
jump (505)
eof
| 0 | 0.562288 | 1 | 0.562288 | game-dev | MEDIA | 0.688734 | game-dev | 0.704316 | 1 | 0.704316 |
ChaoticOnyx/OnyxBay | 6,007 | code/modules/virus2/helpers.dm | #define VIRUS_THRESHOLD 10
//Returns 1 if mob can be infected, 0 otherwise.
/proc/infection_chance(mob/living/carbon/M, vector = "Airborne")
if(!istype(M))
return 0
var/mob/living/carbon/human/H = M
if(istype(H) && H.species.get_virus_immune(H))
return 0
var/protection = M.get_flat_armor(null, "bio") //gets the full body bio armour value, weighted by body part coverage.
var/score = round(0.06*protection) //scales 100% protection to 6.
switch(vector)
if("Airborne")
if(M.internal) //not breathing infected air helps greatly
return 0
var/obj/item/I = M.wear_mask
//masks provide a small bonus and can replace overall bio protection
if(I)
score = max(score, round(0.06*I.armor["bio"]))
if (istype(I, /obj/item/clothing/mask))
score += 1 //this should be added after
if("Contact")
if(istype(H))
//gloves provide a larger bonus
if (istype(H.gloves, /obj/item/clothing/gloves))
score += 2
switch(score)
if (6 to INFINITY)
return 0
if (5)
return 1
if (4)
return 5
if (3)
return 25
if (2)
return 45
if (1)
return 65
else
return 100
//Similar to infection check, but used for when M is spreading the virus.
/proc/infection_spreading_check(mob/living/carbon/M, vector = "Airborne")
ASSERT(istype(M))
var/protection = M.get_flat_armor(null, "bio") //gets the full body bio armour value, weighted by body part coverage.
if(vector == "Airborne") //for airborne infections face-covering items give non-weighted protection value.
if(M.internal)
return 1
protection = max(protection, M.get_flat_armor(FACE, "bio"))
return prob(protection + 15*M.chem_effects[CE_ANTIVIRAL])
/proc/airborne_can_reach(turf/simulated/source, turf/simulated/target)
//Can't ariborne without air
if(is_below_sound_pressure(source) || is_below_sound_pressure(target))
return FALSE
//no infecting from other side of the hallway
if(get_dist(source,target) > 5)
return FALSE
if(istype(source) && istype(target))
return source.zone == target.zone
//Attemptes to infect mob M with virus. Set forced to 1 to ignore protective clothnig
/proc/infect_virus2(mob/living/carbon/M,datum/disease2/disease/disease,forced = 0)
if(!istype(disease))
return
if(!istype(M))
return
if((M.status_flags & GODMODE) || (isundead(M)))
return
if("[disease.uniqueID]" in M.virus2)
return
if(length(M.virus2) > VIRUS_THRESHOLD)
return
// if one of the antibodies in the mob's body matches one of the disease's antigens, don't infect
var/list/antibodies_in_common = M.antibodies & disease.antigen
if(antibodies_in_common.len)
return
if(prob(100 * M.reagents.get_reagent_amount(/datum/reagent/spaceacillin) / (REAGENTS_OVERDOSE/2)))
return
if(!disease.affected_species.len)
return
if (!(M.species?.name in disease.affected_species))
if (forced)
disease.affected_species[1] = M.species.name
else
return //not compatible with this species
var/mob_infection_prob = infection_chance(M, disease.spreadtype) * M.immunity_weakness()
if(forced || (prob(disease.infectionchance) && prob(mob_infection_prob)))
var/datum/disease2/disease/D = disease.getcopy()
D.minormutate()
D.update_disease()
D.infected = M
M.virus2["[D.uniqueID]"] = D
BITSET(M.hud_updateflag, STATUS_HUD)
//Infects mob M with random lesser disease, if he doesn't have one
/proc/infect_mob_random_lesser(mob/living/carbon/M)
var/datum/disease2/disease/D = new /datum/disease2/disease
D.makerandom(VIRUS_MILD)
infect_virus2(M, D, 1)
//Infects mob M with random greated disease, if he doesn't have one
/proc/infect_mob_random_greater(mob/living/carbon/M)
var/datum/disease2/disease/D = new /datum/disease2/disease
D.makerandom(VIRUS_COMMON)
infect_virus2(M, D, 1)
//Fancy prob() function.
/proc/dprob(p)
return(prob(sqrt(p)) && prob(sqrt(p)))
//Checks if the equipment that covers the mouth has bioprotection
/mob/living/carbon/human/proc/can_spread_disease()
for(var/obj/item/clothing/gear in list(head, wear_mask))
if(istype(gear) && (gear.body_parts_covered & FACE))
if(gear.armor["bio"] > 0)
return FALSE
return TRUE
/mob/living/carbon/proc/spread_disease_to(mob/living/carbon/victim, vector = "Airborne")
if (src == victim)
return "retardation"
if (virus2.len > 0)
for (var/ID in virus2)
var/datum/disease2/disease/V = virus2[ID]
if(V.spreadtype != vector)
continue
//It's hard to get other people sick if you're in an airtight suit.
if(infection_spreading_check(src, V.spreadtype))
continue
if (vector == "Airborne")
if(airborne_can_reach(get_turf(src), get_turf(victim)))
infect_virus2(victim,V)
if (vector == "Contact")
if (Adjacent(victim))
infect_virus2(victim,V)
//contact goes both ways
if (victim.virus2.len > 0 && vector == "Contact" && Adjacent(victim))
var/nudity = 1
if (ishuman(victim))
var/mob/living/carbon/human/H = victim
//Allow for small chance of touching other zones.
//This is proc is also used for passive spreading so just because they are targeting
//that zone doesn't mean that's necessarily where they will touch.
var/touch_zone = zone_sel ? zone_sel.selecting : "chest"
touch_zone = ran_zone(touch_zone, 80)
var/obj/item/organ/external/select_area = H.get_organ(touch_zone)
if(!select_area)
//give it one more chance, since this is also called for passive spreading
select_area = H.get_organ(ran_zone())
if(!select_area)
nudity = 0 //cant contact a missing body part
else
var/list/clothes = list(H.head, H.wear_mask, H.wear_suit, H.w_uniform, H.gloves, H.shoes)
for(var/obj/item/clothing/C in clothes)
if(C && istype(C))
if(C.body_parts_covered & select_area.body_part)
nudity = 0
if (nudity)
for (var/ID in victim.virus2)
var/datum/disease2/disease/V = victim.virus2[ID]
if(V && V.spreadtype != vector) continue
if(infection_spreading_check(victim, V.spreadtype)) continue
infect_virus2(src,V)
#undef VIRUS_THRESHOLD
| 0 | 0.853941 | 1 | 0.853941 | game-dev | MEDIA | 0.94139 | game-dev | 0.837225 | 1 | 0.837225 |
hagish/love-native-android | 3,367 | jni/physfs-2.0.2/extras/physfsrwops.h | /*
* This code provides a glue layer between PhysicsFS and Simple Directmedia
* Layer's (SDL) RWops i/o abstraction.
*
* License: this code is public domain. I make no warranty that it is useful,
* correct, harmless, or environmentally safe.
*
* This particular file may be used however you like, including copying it
* verbatim into a closed-source project, exploiting it commercially, and
* removing any trace of my name from the source (although I hope you won't
* do that). I welcome enhancements and corrections to this file, but I do
* not require you to send me patches if you make changes. This code has
* NO WARRANTY.
*
* Unless otherwise stated, the rest of PhysicsFS falls under the zlib license.
* Please see LICENSE.txt in the root of the source tree.
*
* SDL falls under the LGPL license. You can get SDL at http://www.libsdl.org/
*
* This file was written by Ryan C. Gordon. (icculus@icculus.org).
*/
#ifndef _INCLUDE_PHYSFSRWOPS_H_
#define _INCLUDE_PHYSFSRWOPS_H_
#include "physfs.h"
#include "SDL.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Open a platform-independent filename for reading, and make it accessible
* via an SDL_RWops structure. The file will be closed in PhysicsFS when the
* RWops is closed. PhysicsFS should be configured to your liking before
* opening files through this method.
*
* @param filename File to open in platform-independent notation.
* @return A valid SDL_RWops structure on success, NULL on error. Specifics
* of the error can be gleaned from PHYSFS_getLastError().
*/
__EXPORT__ SDL_RWops *PHYSFSRWOPS_openRead(const char *fname);
/**
* Open a platform-independent filename for writing, and make it accessible
* via an SDL_RWops structure. The file will be closed in PhysicsFS when the
* RWops is closed. PhysicsFS should be configured to your liking before
* opening files through this method.
*
* @param filename File to open in platform-independent notation.
* @return A valid SDL_RWops structure on success, NULL on error. Specifics
* of the error can be gleaned from PHYSFS_getLastError().
*/
__EXPORT__ SDL_RWops *PHYSFSRWOPS_openWrite(const char *fname);
/**
* Open a platform-independent filename for appending, and make it accessible
* via an SDL_RWops structure. The file will be closed in PhysicsFS when the
* RWops is closed. PhysicsFS should be configured to your liking before
* opening files through this method.
*
* @param filename File to open in platform-independent notation.
* @return A valid SDL_RWops structure on success, NULL on error. Specifics
* of the error can be gleaned from PHYSFS_getLastError().
*/
__EXPORT__ SDL_RWops *PHYSFSRWOPS_openAppend(const char *fname);
/**
* Make a SDL_RWops from an existing PhysicsFS file handle. You should
* dispose of any references to the handle after successful creation of
* the RWops. The actual PhysicsFS handle will be destroyed when the
* RWops is closed.
*
* @param handle a valid PhysicsFS file handle.
* @return A valid SDL_RWops structure on success, NULL on error. Specifics
* of the error can be gleaned from PHYSFS_getLastError().
*/
__EXPORT__ SDL_RWops *PHYSFSRWOPS_makeRWops(PHYSFS_File *handle);
#ifdef __cplusplus
}
#endif
#endif /* include-once blocker */
/* end of physfsrwops.h ... */
| 0 | 0.68427 | 1 | 0.68427 | game-dev | MEDIA | 0.77583 | game-dev | 0.538852 | 1 | 0.538852 |
Redux-Team/Legacy_SM63Redux | 4,211 | classes/entity/entity.gd | class_name Entity
extends CharacterBody2D
# Root class for entities that move in any way.
# Entities have the Entity collision layer bit enabled, so they can influence weights.
# They have water collision built-in.
# Constants for movement. These should not need to be changed.
# In situations where these are variable (e.g. Space), it could be best to use a multiplier.
const GRAVITY = 0.17
const TERM_VEL_AIR = 6
const TERM_VEL_WATER = 2
@export var disabled = false: set = set_disabled
var vel = Vector2.ZERO
var _water_bodies: int = 0
# Entities may or may not have certain functionality nodes.
# The WaterCheck node, for example, is used to determine if the entity is in water or not.
# However, this may not always be necessary. If an entity is unaffected by water, this node is obsolete.
# As such, we want an implementation in which nodes are optional, and the code handles this.
# For that, we use a private exported node path, that can be assigned in the scene editor.
# This is then loaded into the main variable on ready.
# If this returns null, we assume the node does not exist, and as such functionality is disabled.
@export var _water_check_path: NodePath = "WaterCheck"
@onready var water_check = get_node_or_null(_water_check_path)
# Virtual methods such as _ready(), _process() and _physics_process() behave unusually when inherited.
# This (I think) is because Godot manages these with notifications, unlike other methods.
# As such, overriding them doesn't actually disable the original functionality.
# For this reason, we wrap the code in a separate function, which can be overridden properly.
# See _ready_override().
func _ready():
_ready_override()
func _ready_override():
_connect_signals()
# Connect WaterCheck signals through code.
# Since this is in a parent class, this cannot be done in the scene editor.
func _connect_signals():
_preempt_all_node_readies()
_connect_node_signal_if_exists(water_check, "area_entered", self, "_on_WaterCheck_area_entered")
_connect_node_signal_if_exists(water_check, "area_exited", self, "_on_WaterCheck_area_exited")
func _preempt_all_node_readies():
water_check = _preempt_node_ready(water_check, _water_check_path)
func _process(delta):
_process_override(delta)
func _physics_process(_delta):
if !disabled:
_physics_step()
func _process_override(_delta):
pass
# The default entity physics step.
func _physics_step():
if _water_bodies > 0:
vel.y = min(vel.y + GRAVITY, TERM_VEL_WATER)
else:
vel.y = min(vel.y + GRAVITY, TERM_VEL_AIR)
if is_on_floor():
vel.y = min(vel.y, GRAVITY)
var snap
if is_on_floor() and vel.y >= 0:
snap = 4
else:
snap = 0
# warning-ignore:RETURN_VALUE_DISCARDED
set_velocity(vel * 60)
floor_snap_length = snap
set_up_direction(Vector2.UP)
set_floor_stop_on_slope_enabled(true)
move_and_slide()
# WaterCheck signal methods.
func _on_WaterCheck_area_entered(_area):
_water_bodies += 1
func _on_WaterCheck_area_exited(_area):
_water_bodies -= 1
# Setget for the "disabled" property
# Can be overridden in child classes
func set_disabled(val):
disabled = val
_preempt_all_node_readies()
set_collision_layer_value(3, 0 if val else 1)
# The following functions deal with child nodes that may or may not exist.
# This is useful for having optional functionality.
# Almost functionally identical to simply running get_node_or_null(path).
# However, this function is used due to its semantic significance.
# It is also marginally more secure, as it will not destroy the reference if the node is reparented.
# This is used during the ready cycle, when a node may not be assigned to its variable properly.
func _preempt_node_ready(node, path: NodePath) -> Node:
return get_node_or_null(path) if node == null else node
# Set a node's property if the node exists.
func _set_node_property_if_exists(node: Node, property: String, val) -> void:
if node != null:
node.set(property, val)
# Connect a node to a signal if the node exists.
func _connect_node_signal_if_exists(node, signame: String, target, method: String, deferred : bool = false) -> void:
if node != null:
node.connect(signame, Callable(target, method), CONNECT_DEFERRED if deferred else 0)
| 0 | 0.923295 | 1 | 0.923295 | game-dev | MEDIA | 0.843318 | game-dev | 0.700723 | 1 | 0.700723 |
LostArtefacts/TRX | 1,634 | src/tr1/game/objects/general/scion3.c | // The Great Pyramid shootable Scion.
#include "game/effects.h"
#include <libtrx/game/camera.h>
#include <libtrx/game/objects.h>
#include <libtrx/game/random.h>
#include <libtrx/game/rooms.h>
#include <libtrx/game/sound.h>
static void M_Control(const int16_t item_num)
{
static int32_t counter = 0;
ITEM *const item = Item_Get(item_num);
if (item->hit_points > 0) {
counter = 0;
Item_Animate(item);
return;
}
if (counter == 0) {
item->status = IS_INVISIBLE;
item->hit_points = DONT_TARGET;
Room_TestTriggers(item);
Item_RemoveDrawn(item_num);
}
if (counter % 10 == 0) {
int16_t effect_num = Effect_Create(item->room_num);
if (effect_num != NO_EFFECT) {
EFFECT *effect = Effect_Get(effect_num);
effect->pos.x = item->pos.x + (Random_GetControl() - 0x4000) / 32;
effect->pos.y =
item->pos.y + (Random_GetControl() - 0x4000) / 256 - 500;
effect->pos.z = item->pos.z + (Random_GetControl() - 0x4000) / 32;
effect->speed = 0;
effect->frame_num = 0;
effect->object_id = O_EXPLOSION_1;
effect->counter = 0;
Sound_Effect(SFX_EXPLOSION_1, &effect->pos, SPM_NORMAL);
g_Camera.bounce = -200;
}
}
counter++;
if (counter >= LOGIC_FPS * 3) {
Item_Kill(item_num);
}
}
static void M_Setup(OBJECT *const obj)
{
obj->control_func = M_Control;
obj->hit_points = 5;
obj->save_flags = true;
obj->save_hitpoints = true;
}
REGISTER_OBJECT(O_SCION_ITEM_3, M_Setup)
| 0 | 0.867588 | 1 | 0.867588 | game-dev | MEDIA | 0.912787 | game-dev | 0.658208 | 1 | 0.658208 |
stephengold/Libbulletjme | 35,022 | src/main/native/bullet3/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btMultiBodyDynamicsWorld.h"
#include "btMultiBodyConstraintSolver.h"
#include "btMultiBody.h"
#include "btMultiBodyLinkCollider.h"
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
#include "LinearMath/btQuickprof.h"
#include "btMultiBodyConstraint.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btSerializer.h"
void btMultiBodyDynamicsWorld::addMultiBody(btMultiBody* body, int group, int mask)
{
m_multiBodies.push_back(body);
}
void btMultiBodyDynamicsWorld::removeMultiBody(btMultiBody* body)
{
m_multiBodies.remove(body);
}
void btMultiBodyDynamicsWorld::predictUnconstraintMotion(btScalar timeStep)
{
btDiscreteDynamicsWorld::predictUnconstraintMotion(timeStep);
predictMultiBodyTransforms(timeStep);
}
void btMultiBodyDynamicsWorld::calculateSimulationIslands()
{
BT_PROFILE("calculateSimulationIslands");
getSimulationIslandManager()->updateActivationState(getCollisionWorld(), getCollisionWorld()->getDispatcher());
{
//merge islands based on speculative contact manifolds too
for (int i = 0; i < this->m_predictiveManifolds.size(); i++)
{
btPersistentManifold* manifold = m_predictiveManifolds[i];
const btCollisionObject* colObj0 = manifold->getBody0();
const btCollisionObject* colObj1 = manifold->getBody1();
if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
{
getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(), (colObj1)->getIslandTag());
}
}
}
{
int i;
int numConstraints = int(m_constraints.size());
for (i = 0; i < numConstraints; i++)
{
btTypedConstraint* constraint = m_constraints[i];
if (constraint->isEnabled())
{
const btRigidBody* colObj0 = &constraint->getRigidBodyA();
const btRigidBody* colObj1 = &constraint->getRigidBodyB();
if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) &&
((colObj1) && (!(colObj1)->isStaticOrKinematicObject())))
{
getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(), (colObj1)->getIslandTag());
}
}
}
}
//merge islands linked by Featherstone link colliders
for (int i = 0; i < m_multiBodies.size(); i++)
{
btMultiBody* body = m_multiBodies[i];
{
btMultiBodyLinkCollider* prev = body->getBaseCollider();
for (int b = 0; b < body->getNumLinks(); b++)
{
btMultiBodyLinkCollider* cur = body->getLink(b).m_collider;
if (((cur) && (!(cur)->isStaticOrKinematicObject())) &&
((prev) && (!(prev)->isStaticOrKinematicObject())))
{
int tagPrev = prev->getIslandTag();
int tagCur = cur->getIslandTag();
getSimulationIslandManager()->getUnionFind().unite(tagPrev, tagCur);
}
if (cur && !cur->isStaticOrKinematicObject())
prev = cur;
}
}
}
//merge islands linked by multibody constraints
{
for (int i = 0; i < this->m_multiBodyConstraints.size(); i++)
{
btMultiBodyConstraint* c = m_multiBodyConstraints[i];
int tagA = c->getIslandIdA();
int tagB = c->getIslandIdB();
if (tagA >= 0 && tagB >= 0)
getSimulationIslandManager()->getUnionFind().unite(tagA, tagB);
}
}
//Store the island id in each body
getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld());
}
void btMultiBodyDynamicsWorld::updateActivationState(btScalar timeStep)
{
BT_PROFILE("btMultiBodyDynamicsWorld::updateActivationState");
for (int i = 0; i < m_multiBodies.size(); i++)
{
btMultiBody* body = m_multiBodies[i];
if (body)
{
body->checkMotionAndSleepIfRequired(timeStep);
if (!body->isAwake())
{
btMultiBodyLinkCollider* col = body->getBaseCollider();
if (col && col->getActivationState() == ACTIVE_TAG)
{
if (body->hasFixedBase())
{
col->setActivationState(FIXED_BASE_MULTI_BODY);
} else
{
col->setActivationState(WANTS_DEACTIVATION);
}
col->setDeactivationTime(0.f);
}
for (int b = 0; b < body->getNumLinks(); b++)
{
btMultiBodyLinkCollider* col = body->getLink(b).m_collider;
if (col && col->getActivationState() == ACTIVE_TAG)
{
col->setActivationState(WANTS_DEACTIVATION);
col->setDeactivationTime(0.f);
}
}
}
else
{
btMultiBodyLinkCollider* col = body->getBaseCollider();
if (col && col->getActivationState() != DISABLE_DEACTIVATION)
col->setActivationState(ACTIVE_TAG);
for (int b = 0; b < body->getNumLinks(); b++)
{
btMultiBodyLinkCollider* col = body->getLink(b).m_collider;
if (col && col->getActivationState() != DISABLE_DEACTIVATION)
col->setActivationState(ACTIVE_TAG);
}
}
}
}
btDiscreteDynamicsWorld::updateActivationState(timeStep);
}
void btMultiBodyDynamicsWorld::getAnalyticsData(btAlignedObjectArray<btSolverAnalyticsData>& islandAnalyticsData) const
{
islandAnalyticsData = m_solverMultiBodyIslandCallback->m_islandAnalyticsData;
}
btMultiBodyDynamicsWorld::btMultiBodyDynamicsWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btMultiBodyConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration)
: btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration),
m_multiBodyConstraintSolver(constraintSolver)
{
//split impulse is not yet supported for Featherstone hierarchies
// getSolverInfo().m_splitImpulse = false;
getSolverInfo().m_solverMode |= SOLVER_USE_2_FRICTION_DIRECTIONS;
m_solverMultiBodyIslandCallback = new MultiBodyInplaceSolverIslandCallback(constraintSolver, dispatcher);
}
btMultiBodyDynamicsWorld::~btMultiBodyDynamicsWorld()
{
delete m_solverMultiBodyIslandCallback;
}
void btMultiBodyDynamicsWorld::setMultiBodyConstraintSolver(btMultiBodyConstraintSolver* solver)
{
m_multiBodyConstraintSolver = solver;
m_solverMultiBodyIslandCallback->setMultiBodyConstraintSolver(solver);
btDiscreteDynamicsWorld::setConstraintSolver(solver);
}
void btMultiBodyDynamicsWorld::setConstraintSolver(btConstraintSolver* solver)
{
if (solver->getSolverType() == BT_MULTIBODY_SOLVER)
{
m_multiBodyConstraintSolver = (btMultiBodyConstraintSolver*)solver;
}
btDiscreteDynamicsWorld::setConstraintSolver(solver);
}
void btMultiBodyDynamicsWorld::forwardKinematics()
{
for (int b = 0; b < m_multiBodies.size(); b++)
{
btMultiBody* bod = m_multiBodies[b];
bod->forwardKinematics(m_scratch_world_to_local, m_scratch_local_origin);
}
}
void btMultiBodyDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo)
{
solveExternalForces(solverInfo);
buildIslands();
solveInternalConstraints(solverInfo);
}
void btMultiBodyDynamicsWorld::buildIslands()
{
m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(), getCollisionWorld(), m_solverMultiBodyIslandCallback);
}
void btMultiBodyDynamicsWorld::solveInternalConstraints(btContactSolverInfo& solverInfo)
{
/// solve all the constraints for this island
m_solverMultiBodyIslandCallback->processConstraints();
m_constraintSolver->allSolved(solverInfo, m_debugDrawer);
{
BT_PROFILE("btMultiBody stepVelocities");
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
//useless? they get resized in stepVelocities once again (AND DIFFERENTLY)
m_scratch_r.resize(bod->getNumLinks() + 1); //multidof? ("Y"s use it and it is used to store qdd)
m_scratch_v.resize(bod->getNumLinks() + 1);
m_scratch_m.resize(bod->getNumLinks() + 1);
if (bod->internalNeedsJointFeedback())
{
if (!bod->isUsingRK4Integration())
{
if (bod->internalNeedsJointFeedback())
{
bool isConstraintPass = true;
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(solverInfo.m_timeStep, m_scratch_r, m_scratch_v, m_scratch_m, isConstraintPass,
getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
}
}
}
}
}
}
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bod->processDeltaVeeMultiDof2();
}
}
void btMultiBodyDynamicsWorld::solveExternalForces(btContactSolverInfo& solverInfo)
{
forwardKinematics();
BT_PROFILE("solveConstraints");
clearMultiBodyConstraintForces();
m_sortedConstraints.resize(m_constraints.size());
int i;
for (i = 0; i < getNumConstraints(); i++)
{
m_sortedConstraints[i] = m_constraints[i];
}
m_sortedConstraints.quickSort(btSortConstraintOnIslandPredicate2());
btTypedConstraint** constraintsPtr = getNumConstraints() ? &m_sortedConstraints[0] : 0;
m_sortedMultiBodyConstraints.resize(m_multiBodyConstraints.size());
for (i = 0; i < m_multiBodyConstraints.size(); i++)
{
m_sortedMultiBodyConstraints[i] = m_multiBodyConstraints[i];
}
m_sortedMultiBodyConstraints.quickSort(btSortMultiBodyConstraintOnIslandPredicate());
btMultiBodyConstraint** sortedMultiBodyConstraints = m_sortedMultiBodyConstraints.size() ? &m_sortedMultiBodyConstraints[0] : 0;
m_solverMultiBodyIslandCallback->setup(&solverInfo, constraintsPtr, m_sortedConstraints.size(), sortedMultiBodyConstraints, m_sortedMultiBodyConstraints.size(), getDebugDrawer());
m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds());
#ifndef BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
{
BT_PROFILE("btMultiBody addForce");
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
//useless? they get resized in stepVelocities once again (AND DIFFERENTLY)
m_scratch_r.resize(bod->getNumLinks() + 1); //multidof? ("Y"s use it and it is used to store qdd)
m_scratch_v.resize(bod->getNumLinks() + 1);
m_scratch_m.resize(bod->getNumLinks() + 1);
bod->addBaseForce(m_gravity * bod->getBaseMass());
for (int j = 0; j < bod->getNumLinks(); ++j)
{
bod->addLinkForce(j, m_gravity * bod->getLinkMass(j));
}
} //if (!isSleeping)
}
}
#endif //BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
{
BT_PROFILE("btMultiBody stepVelocities");
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
//useless? they get resized in stepVelocities once again (AND DIFFERENTLY)
m_scratch_r.resize(bod->getNumLinks() + 1); //multidof? ("Y"s use it and it is used to store qdd)
m_scratch_v.resize(bod->getNumLinks() + 1);
m_scratch_m.resize(bod->getNumLinks() + 1);
bool doNotUpdatePos = false;
bool isConstraintPass = false;
{
if (!bod->isUsingRK4Integration())
{
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(solverInfo.m_timeStep,
m_scratch_r, m_scratch_v, m_scratch_m,isConstraintPass,
getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
}
else
{
//
int numDofs = bod->getNumDofs() + 6;
int numPosVars = bod->getNumPosVars() + 7;
btAlignedObjectArray<btScalar> scratch_r2;
scratch_r2.resize(2 * numPosVars + 8 * numDofs);
//convenience
btScalar* pMem = &scratch_r2[0];
btScalar* scratch_q0 = pMem;
pMem += numPosVars;
btScalar* scratch_qx = pMem;
pMem += numPosVars;
btScalar* scratch_qd0 = pMem;
pMem += numDofs;
btScalar* scratch_qd1 = pMem;
pMem += numDofs;
btScalar* scratch_qd2 = pMem;
pMem += numDofs;
btScalar* scratch_qd3 = pMem;
pMem += numDofs;
btScalar* scratch_qdd0 = pMem;
pMem += numDofs;
btScalar* scratch_qdd1 = pMem;
pMem += numDofs;
btScalar* scratch_qdd2 = pMem;
pMem += numDofs;
btScalar* scratch_qdd3 = pMem;
pMem += numDofs;
btAssert((pMem - (2 * numPosVars + 8 * numDofs)) == &scratch_r2[0]);
/////
//copy q0 to scratch_q0 and qd0 to scratch_qd0
scratch_q0[0] = bod->getWorldToBaseRot().x();
scratch_q0[1] = bod->getWorldToBaseRot().y();
scratch_q0[2] = bod->getWorldToBaseRot().z();
scratch_q0[3] = bod->getWorldToBaseRot().w();
scratch_q0[4] = bod->getBasePos().x();
scratch_q0[5] = bod->getBasePos().y();
scratch_q0[6] = bod->getBasePos().z();
//
for (int link = 0; link < bod->getNumLinks(); ++link)
{
for (int dof = 0; dof < bod->getLink(link).m_posVarCount; ++dof)
scratch_q0[7 + bod->getLink(link).m_cfgOffset + dof] = bod->getLink(link).m_jointPos[dof];
}
//
for (int dof = 0; dof < numDofs; ++dof)
scratch_qd0[dof] = bod->getVelocityVector()[dof];
////
struct
{
btMultiBody* bod;
btScalar *scratch_qx, *scratch_q0;
void operator()()
{
for (int dof = 0; dof < bod->getNumPosVars() + 7; ++dof)
scratch_qx[dof] = scratch_q0[dof];
}
} pResetQx = {bod, scratch_qx, scratch_q0};
//
struct
{
void operator()(btScalar dt, const btScalar* pDer, const btScalar* pCurVal, btScalar* pVal, int size)
{
for (int i = 0; i < size; ++i)
pVal[i] = pCurVal[i] + dt * pDer[i];
}
} pEulerIntegrate;
//
struct
{
void operator()(btMultiBody* pBody, const btScalar* pData)
{
btScalar* pVel = const_cast<btScalar*>(pBody->getVelocityVector());
for (int i = 0; i < pBody->getNumDofs() + 6; ++i)
pVel[i] = pData[i];
}
} pCopyToVelocityVector;
//
struct
{
void operator()(const btScalar* pSrc, btScalar* pDst, int start, int size)
{
for (int i = 0; i < size; ++i)
pDst[i] = pSrc[start + i];
}
} pCopy;
//
btScalar h = solverInfo.m_timeStep;
#define output &m_scratch_r[bod->getNumDofs()]
//calc qdd0 from: q0 & qd0
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(0., m_scratch_r, m_scratch_v, m_scratch_m,
isConstraintPass,getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
pCopy(output, scratch_qdd0, 0, numDofs);
//calc q1 = q0 + h/2 * qd0
pResetQx();
bod->stepPositionsMultiDof(btScalar(.5) * h, scratch_qx, scratch_qd0);
//calc qd1 = qd0 + h/2 * qdd0
pEulerIntegrate(btScalar(.5) * h, scratch_qdd0, scratch_qd0, scratch_qd1, numDofs);
//
//calc qdd1 from: q1 & qd1
pCopyToVelocityVector(bod, scratch_qd1);
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(0., m_scratch_r, m_scratch_v, m_scratch_m,
isConstraintPass,getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
pCopy(output, scratch_qdd1, 0, numDofs);
//calc q2 = q0 + h/2 * qd1
pResetQx();
bod->stepPositionsMultiDof(btScalar(.5) * h, scratch_qx, scratch_qd1);
//calc qd2 = qd0 + h/2 * qdd1
pEulerIntegrate(btScalar(.5) * h, scratch_qdd1, scratch_qd0, scratch_qd2, numDofs);
//
//calc qdd2 from: q2 & qd2
pCopyToVelocityVector(bod, scratch_qd2);
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(0., m_scratch_r, m_scratch_v, m_scratch_m,
isConstraintPass,getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
pCopy(output, scratch_qdd2, 0, numDofs);
//calc q3 = q0 + h * qd2
pResetQx();
bod->stepPositionsMultiDof(h, scratch_qx, scratch_qd2);
//calc qd3 = qd0 + h * qdd2
pEulerIntegrate(h, scratch_qdd2, scratch_qd0, scratch_qd3, numDofs);
//
//calc qdd3 from: q3 & qd3
pCopyToVelocityVector(bod, scratch_qd3);
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(0., m_scratch_r, m_scratch_v, m_scratch_m,
isConstraintPass,getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
pCopy(output, scratch_qdd3, 0, numDofs);
//
//calc q = q0 + h/6(qd0 + 2*(qd1 + qd2) + qd3)
//calc qd = qd0 + h/6(qdd0 + 2*(qdd1 + qdd2) + qdd3)
btAlignedObjectArray<btScalar> delta_q;
delta_q.resize(numDofs);
btAlignedObjectArray<btScalar> delta_qd;
delta_qd.resize(numDofs);
for (int i = 0; i < numDofs; ++i)
{
delta_q[i] = h / btScalar(6.) * (scratch_qd0[i] + 2 * scratch_qd1[i] + 2 * scratch_qd2[i] + scratch_qd3[i]);
delta_qd[i] = h / btScalar(6.) * (scratch_qdd0[i] + 2 * scratch_qdd1[i] + 2 * scratch_qdd2[i] + scratch_qdd3[i]);
//delta_q[i] = h*scratch_qd0[i];
//delta_qd[i] = h*scratch_qdd0[i];
}
//
pCopyToVelocityVector(bod, scratch_qd0);
bod->applyDeltaVeeMultiDof(&delta_qd[0], 1);
//
if (!doNotUpdatePos)
{
btScalar* pRealBuf = const_cast<btScalar*>(bod->getVelocityVector());
pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs() * bod->getNumDofs();
for (int i = 0; i < numDofs; ++i)
pRealBuf[i] = delta_q[i];
//bod->stepPositionsMultiDof(1, 0, &delta_q[0]);
bod->setPosUpdated(true);
}
//ugly hack which resets the cached data to t0 (needed for constraint solver)
{
for (int link = 0; link < bod->getNumLinks(); ++link)
bod->getLink(link).updateCacheMultiDof();
bod->computeAccelerationsArticulatedBodyAlgorithmMultiDof(0, m_scratch_r, m_scratch_v, m_scratch_m,
isConstraintPass,getSolverInfo().m_jointFeedbackInWorldSpace,
getSolverInfo().m_jointFeedbackInJointFrame);
}
}
}
#ifndef BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
bod->clearForcesAndTorques();
#endif //BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
} //if (!isSleeping)
}
}
}
void btMultiBodyDynamicsWorld::integrateTransforms(btScalar timeStep)
{
btDiscreteDynamicsWorld::integrateTransforms(timeStep);
integrateMultiBodyTransforms(timeStep);
}
void btMultiBodyDynamicsWorld::integrateMultiBodyTransforms(btScalar timeStep)
{
BT_PROFILE("btMultiBody stepPositions");
//integrate and update the Featherstone hierarchies
for (int b = 0; b < m_multiBodies.size(); b++)
{
btMultiBody* bod = m_multiBodies[b];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
bod->addSplitV();
int nLinks = bod->getNumLinks();
///base + num m_links
if (!bod->isPosUpdated())
bod->stepPositionsMultiDof(timeStep);
else
{
btScalar* pRealBuf = const_cast<btScalar*>(bod->getVelocityVector());
pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs() * bod->getNumDofs();
bod->stepPositionsMultiDof(1, 0, pRealBuf);
bod->setPosUpdated(false);
}
m_scratch_world_to_local.resize(nLinks + 1);
m_scratch_local_origin.resize(nLinks + 1);
bod->updateCollisionObjectWorldTransforms(m_scratch_world_to_local, m_scratch_local_origin);
bod->substractSplitV();
}
else
{
bod->clearVelocities();
}
}
}
void btMultiBodyDynamicsWorld::predictMultiBodyTransforms(btScalar timeStep)
{
BT_PROFILE("btMultiBody stepPositions");
//integrate and update the Featherstone hierarchies
for (int b = 0; b < m_multiBodies.size(); b++)
{
btMultiBody* bod = m_multiBodies[b];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
int nLinks = bod->getNumLinks();
bod->predictPositionsMultiDof(timeStep);
m_scratch_world_to_local.resize(nLinks + 1);
m_scratch_local_origin.resize(nLinks + 1);
bod->updateCollisionObjectInterpolationWorldTransforms(m_scratch_world_to_local, m_scratch_local_origin);
}
else
{
bod->clearVelocities();
}
}
}
void btMultiBodyDynamicsWorld::addMultiBodyConstraint(btMultiBodyConstraint* constraint)
{
m_multiBodyConstraints.push_back(constraint);
}
void btMultiBodyDynamicsWorld::removeMultiBodyConstraint(btMultiBodyConstraint* constraint)
{
m_multiBodyConstraints.remove(constraint);
}
void btMultiBodyDynamicsWorld::debugDrawMultiBodyConstraint(btMultiBodyConstraint* constraint)
{
constraint->debugDraw(getDebugDrawer());
}
void btMultiBodyDynamicsWorld::debugDrawWorld()
{
BT_PROFILE("btMultiBodyDynamicsWorld debugDrawWorld");
btDiscreteDynamicsWorld::debugDrawWorld();
bool drawConstraints = false;
if (getDebugDrawer())
{
int mode = getDebugDrawer()->getDebugMode();
if (mode & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits))
{
drawConstraints = true;
}
if (drawConstraints)
{
BT_PROFILE("btMultiBody debugDrawWorld");
for (int c = 0; c < m_multiBodyConstraints.size(); c++)
{
btMultiBodyConstraint* constraint = m_multiBodyConstraints[c];
debugDrawMultiBodyConstraint(constraint);
}
for (int b = 0; b < m_multiBodies.size(); b++)
{
btMultiBody* bod = m_multiBodies[b];
bod->forwardKinematics(m_scratch_world_to_local1, m_scratch_local_origin1);
if (mode & btIDebugDraw::DBG_DrawFrames)
{
getDebugDrawer()->drawTransform(bod->getBaseWorldTransform(), 0.1);
}
for (int m = 0; m < bod->getNumLinks(); m++)
{
const btTransform& tr = bod->getLink(m).m_cachedWorldTransform;
if (mode & btIDebugDraw::DBG_DrawFrames)
{
getDebugDrawer()->drawTransform(tr, 0.1);
}
//draw the joint axis
if (bod->getLink(m).m_jointType == btMultibodyLink::eRevolute)
{
btVector3 vec = quatRotate(tr.getRotation(), bod->getLink(m).m_axes[0].m_topVec) * 0.1;
btVector4 color(0, 0, 0, 1); //1,1,1);
btVector3 from = vec + tr.getOrigin() - quatRotate(tr.getRotation(), bod->getLink(m).m_dVector);
btVector3 to = tr.getOrigin() - quatRotate(tr.getRotation(), bod->getLink(m).m_dVector);
getDebugDrawer()->drawLine(from, to, color);
}
if (bod->getLink(m).m_jointType == btMultibodyLink::eFixed)
{
btVector3 vec = quatRotate(tr.getRotation(), bod->getLink(m).m_axes[0].m_bottomVec) * 0.1;
btVector4 color(0, 0, 0, 1); //1,1,1);
btVector3 from = vec + tr.getOrigin() - quatRotate(tr.getRotation(), bod->getLink(m).m_dVector);
btVector3 to = tr.getOrigin() - quatRotate(tr.getRotation(), bod->getLink(m).m_dVector);
getDebugDrawer()->drawLine(from, to, color);
}
if (bod->getLink(m).m_jointType == btMultibodyLink::ePrismatic)
{
btVector3 vec = quatRotate(tr.getRotation(), bod->getLink(m).m_axes[0].m_bottomVec) * 0.1;
btVector4 color(0, 0, 0, 1); //1,1,1);
btVector3 from = vec + tr.getOrigin() - quatRotate(tr.getRotation(), bod->getLink(m).m_dVector);
btVector3 to = tr.getOrigin() - quatRotate(tr.getRotation(), bod->getLink(m).m_dVector);
getDebugDrawer()->drawLine(from, to, color);
}
}
}
}
}
}
void btMultiBodyDynamicsWorld::applyGravity()
{
btDiscreteDynamicsWorld::applyGravity();
#ifdef BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
BT_PROFILE("btMultiBody addGravity");
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
bod->addBaseForce(m_gravity * bod->getBaseMass());
for (int j = 0; j < bod->getNumLinks(); ++j)
{
bod->addLinkForce(j, m_gravity * bod->getLinkMass(j));
}
} //if (!isSleeping)
}
#endif //BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
}
void btMultiBodyDynamicsWorld::clearMultiBodyConstraintForces()
{
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bod->clearConstraintForces();
}
}
void btMultiBodyDynamicsWorld::clearMultiBodyForces()
{
{
// BT_PROFILE("clearMultiBodyForces");
for (int i = 0; i < this->m_multiBodies.size(); i++)
{
btMultiBody* bod = m_multiBodies[i];
bool isSleeping = false;
if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING)
{
isSleeping = true;
}
for (int b = 0; b < bod->getNumLinks(); b++)
{
if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState() == ISLAND_SLEEPING)
isSleeping = true;
}
if (!isSleeping)
{
btMultiBody* bod = m_multiBodies[i];
bod->clearForcesAndTorques();
}
}
}
}
void btMultiBodyDynamicsWorld::clearForces()
{
btDiscreteDynamicsWorld::clearForces();
#ifdef BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
clearMultiBodyForces();
#endif
}
void btMultiBodyDynamicsWorld::serialize(btSerializer* serializer)
{
serializer->startSerialization();
serializeDynamicsWorldInfo(serializer);
serializeMultiBodies(serializer);
serializeRigidBodies(serializer);
serializeCollisionObjects(serializer);
serializeContactManifolds(serializer);
serializer->finishSerialization();
}
void btMultiBodyDynamicsWorld::serializeMultiBodies(btSerializer* serializer)
{
int i;
//serialize all collision objects
for (i = 0; i < m_multiBodies.size(); i++)
{
btMultiBody* mb = m_multiBodies[i];
{
int len = mb->calculateSerializeBufferSize();
btChunk* chunk = serializer->allocate(len, 1);
const char* structType = mb->serialize(chunk->m_oldPtr, serializer);
serializer->finalizeChunk(chunk, structType, BT_MULTIBODY_CODE, mb);
}
}
//serialize all multibody links (collision objects)
for (i = 0; i < m_collisionObjects.size(); i++)
{
btCollisionObject* colObj = m_collisionObjects[i];
if (colObj->getInternalType() == btCollisionObject::CO_FEATHERSTONE_LINK)
{
int len = colObj->calculateSerializeBufferSize();
btChunk* chunk = serializer->allocate(len, 1);
const char* structType = colObj->serialize(chunk->m_oldPtr, serializer);
serializer->finalizeChunk(chunk, structType, BT_MB_LINKCOLLIDER_CODE, colObj);
}
}
}
void btMultiBodyDynamicsWorld::saveKinematicState(btScalar timeStep)
{
btDiscreteDynamicsWorld::saveKinematicState(timeStep);
for(int i = 0; i < m_multiBodies.size(); i++)
{
btMultiBody* body = m_multiBodies[i];
if(body->isBaseKinematic())
body->saveKinematicState(timeStep);
}
}
//
//void btMultiBodyDynamicsWorld::setSplitIslands(bool split)
//{
// m_islandManager->setSplitIslands(split);
//}
| 0 | 0.966777 | 1 | 0.966777 | game-dev | MEDIA | 0.916407 | game-dev | 0.987149 | 1 | 0.987149 |
5tratz/qbcore-framework | 11,228 | qb-drugs/server/deliveries.lua | QBCore = exports['qb-core']:GetCoreObject()
-- Functions
exports('GetDealers', function()
return Config.Dealers
end)
-- Callbacks
QBCore.Functions.CreateCallback('qb-drugs:server:RequestConfig', function(_, cb)
cb(Config.Dealers)
end)
-- Events
RegisterNetEvent('qb-drugs:server:updateDealerItems', function(itemData, amount, dealer)
local src = source
local Player = QBCore.Functions.GetPlayer(src)
if not Player then return end
if Config.Dealers[dealer]["products"][itemData.slot].amount - 1 >= 0 then
Config.Dealers[dealer]["products"][itemData.slot].amount -= amount
TriggerClientEvent('qb-drugs:client:setDealerItems', -1, itemData, amount, dealer)
else
Player.Functions.RemoveItem(itemData.name, amount)
Player.Functions.AddMoney('cash', amount * Config.Dealers[dealer]["products"][itemData.slot].price)
TriggerClientEvent("QBCore:Notify", src, Lang:t("error.item_unavailable"), "error")
end
end)
RegisterNetEvent('qb-drugs:server:giveDeliveryItems', function(deliveryData)
local src = source
local Player = QBCore.Functions.GetPlayer(src)
if not Player then return end
local item = Config.DeliveryItems[deliveryData.item].item
if not item then return end
Player.Functions.AddItem(item, deliveryData.amount)
TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[item], "add")
end)
RegisterNetEvent('qb-drugs:server:successDelivery', function(deliveryData, inTime)
local src = source
local Player = QBCore.Functions.GetPlayer(src)
if not Player then return end
local item = Config.DeliveryItems[deliveryData.item].item
local itemAmount = deliveryData.amount
local payout = deliveryData.itemData.payout * itemAmount
local copsOnline = QBCore.Functions.GetDutyCount('police')
local curRep = Player.PlayerData.metadata["dealerrep"]
local invItem = Player.Functions.GetItemByName(item)
if inTime then
if invItem and invItem.amount >= itemAmount then -- on time correct amount
Player.Functions.RemoveItem(item, itemAmount)
if copsOnline > 0 then
local copModifier = copsOnline * Config.PoliceDeliveryModifier
if Config.UseMarkedBills then
local info = {worth = math.floor(payout * copModifier)}
Player.Functions.AddItem('markedbills', 1, false, info)
else
Player.Functions.AddMoney('cash', math.floor(payout * copModifier), 'drug-delivery')
end
else
if Config.UseMarkedBills then
local info = {worth = payout}
Player.Functions.AddItem('markedbills', 1, false, info)
else
Player.Functions.AddMoney('cash', payout, 'drug-delivery')
end
end
TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[item], "remove")
TriggerClientEvent('QBCore:Notify', src, Lang:t("success.order_delivered"), 'success')
SetTimeout(math.random(5000, 10000), function()
TriggerClientEvent('qb-drugs:client:sendDeliveryMail', src, 'perfect', deliveryData)
Player.Functions.SetMetaData('dealerrep', (curRep + Config.DeliveryRepGain))
end)
else
TriggerClientEvent('QBCore:Notify', src, Lang:t("error.order_not_right"), 'error')-- on time incorrect amount
if invItem then
local newItemAmount = invItem.amount
local modifiedPayout = deliveryData.itemData.payout * newItemAmount
Player.Functions.RemoveItem(item, newItemAmount)
TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[item], "remove")
Player.Functions.AddMoney('cash', math.floor(modifiedPayout / Config.WrongAmountFee))
end
SetTimeout(math.random(5000, 10000), function()
TriggerClientEvent('qb-drugs:client:sendDeliveryMail', src, 'bad', deliveryData)
if curRep - 1 > 0 then
Player.Functions.SetMetaData('dealerrep', (curRep - Config.DeliveryRepLoss))
else
Player.Functions.SetMetaData('dealerrep', 0)
end
end)
end
else
if invItem and invItem.amount >= itemAmount then -- late correct amount
TriggerClientEvent('QBCore:Notify', src, Lang:t("error.too_late"), 'error')
Player.Functions.RemoveItem(item, itemAmount)
Player.Functions.AddMoney('cash', math.floor(payout / Config.OverdueDeliveryFee), "delivery-drugs-too-late")
TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[item], "remove")
SetTimeout(math.random(5000, 10000), function()
TriggerClientEvent('qb-drugs:client:sendDeliveryMail', src, 'late', deliveryData)
if curRep - 1 > 0 then
Player.Functions.SetMetaData('dealerrep', (curRep - Config.DeliveryRepLoss))
else
Player.Functions.SetMetaData('dealerrep', 0)
end
end)
else
if invItem then -- late incorrect amount
local newItemAmount = invItem.amount
local modifiedPayout = deliveryData.itemData.payout * newItemAmount
TriggerClientEvent('QBCore:Notify', src, Lang:t("error.too_late"), 'error')
Player.Functions.RemoveItem(item, itemAmount)
Player.Functions.AddMoney('cash', math.floor(modifiedPayout / Config.OverdueDeliveryFee), "delivery-drugs-too-late")
TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[item], "remove")
SetTimeout(math.random(5000, 10000), function()
TriggerClientEvent('qb-drugs:client:sendDeliveryMail', src, 'late', deliveryData)
if curRep - 1 > 0 then
Player.Functions.SetMetaData('dealerrep', (curRep - Config.DeliveryRepLoss))
else
Player.Functions.SetMetaData('dealerrep', 0)
end
end)
end
end
end
end)
-- Commands
QBCore.Commands.Add("newdealer", Lang:t("info.newdealer_command_desc"), {{
name = Lang:t("info.newdealer_command_help1_name"),
help = Lang:t("info.newdealer_command_help1_help")
}, {
name = Lang:t("info.newdealer_command_help2_name"),
help = Lang:t("info.newdealer_command_help2_help")
}, {
name = Lang:t("info.newdealer_command_help3_name"),
help = Lang:t("info.newdealer_command_help3_help")
}}, true, function(source, args)
local ped = GetPlayerPed(source)
local coords = GetEntityCoords(ped)
local Player = QBCore.Functions.GetPlayer(source)
if not Player then return end
local dealerName = args[1]
local minTime = tonumber(args[2])
local maxTime = tonumber(args[3])
local time = json.encode({min = minTime, max = maxTime})
local pos = json.encode({x = coords.x, y = coords.y, z = coords.z})
local result = MySQL.scalar.await('SELECT name FROM dealers WHERE name = ?', {dealerName})
if result then return TriggerClientEvent('QBCore:Notify', source, Lang:t("error.dealer_already_exists"), "error") end
MySQL.insert('INSERT INTO dealers (name, coords, time, createdby) VALUES (?, ?, ?, ?)', {dealerName, pos, time, Player.PlayerData.citizenid}, function()
Config.Dealers[dealerName] = {
["name"] = dealerName,
["coords"] = {
["x"] = coords.x,
["y"] = coords.y,
["z"] = coords.z
},
["time"] = {
["min"] = minTime,
["max"] = maxTime
},
["products"] = Config.Products
}
TriggerClientEvent('qb-drugs:client:RefreshDealers', -1, Config.Dealers)
end)
end, "admin")
QBCore.Commands.Add("deletedealer", Lang:t("info.deletedealer_command_desc"), {{
name = Lang:t("info.deletedealer_command_help1_name"),
help = Lang:t("info.deletedealer_command_help1_help")
}}, true, function(source, args)
local dealerName = args[1]
local result = MySQL.scalar.await('SELECT * FROM dealers WHERE name = ?', {dealerName})
if result then
MySQL.query('DELETE FROM dealers WHERE name = ?', {dealerName})
Config.Dealers[dealerName] = nil
TriggerClientEvent('qb-drugs:client:RefreshDealers', -1, Config.Dealers)
TriggerClientEvent('QBCore:Notify', source, Lang:t("success.dealer_deleted", {dealerName = dealerName}), "success")
else
TriggerClientEvent('QBCore:Notify', source, Lang:t("error.dealer_not_exists_command", {dealerName = dealerName}), "error")
end
end, "admin")
QBCore.Commands.Add("dealers", Lang:t("info.dealers_command_desc"), {}, false, function(source, _)
local DealersText = ""
if Config.Dealers ~= nil and next(Config.Dealers) ~= nil then
for _, v in pairs(Config.Dealers) do
DealersText = DealersText .. Lang:t("info.list_dealers_name_prefix") .. v["name"] .. "<br>"
end
TriggerClientEvent('chat:addMessage', source, {
template = '<div class="chat-message advert"><div class="chat-message-body"><strong>' .. Lang:t("info.list_dealers_title") .. '</strong><br><br> ' .. DealersText .. '</div></div>',
args = {}
})
else
TriggerClientEvent('QBCore:Notify', source, Lang:t("error.no_dealers"), 'error')
end
end, "admin")
QBCore.Commands.Add("dealergoto", Lang:t("info.dealergoto_command_desc"), {{
name = Lang:t("info.dealergoto_command_help1_name"),
help = Lang:t("info.dealergoto_command_help1_help")
}}, true, function(source, args)
local DealerName = tostring(args[1])
if Config.Dealers[DealerName] then
local ped = GetPlayerPed(source)
SetEntityCoords(ped, Config.Dealers[DealerName]['coords']['x'], Config.Dealers[DealerName]['coords']['y'], Config.Dealers[DealerName]['coords']['z'])
TriggerClientEvent('QBCore:Notify', source, Lang:t("success.teleported_to_dealer", {dealerName = DealerName}), 'success')
else
TriggerClientEvent('QBCore:Notify', source, Lang:t("error.dealer_not_exists"), 'error')
end
end, "admin")
CreateThread(function()
Wait(500)
local dealers = MySQL.query.await('SELECT * FROM dealers', {})
if dealers[1] then
for _, v in pairs(dealers) do
local coords = json.decode(v.coords)
local time = json.decode(v.time)
Config.Dealers[v.name] = {
["name"] = v.name,
["coords"] = {
["x"] = coords.x,
["y"] = coords.y,
["z"] = coords.z
},
["time"] = {
["min"] = time.min,
["max"] = time.max
},
["products"] = Config.Products
}
end
end
TriggerClientEvent('qb-drugs:client:RefreshDealers', -1, Config.Dealers)
end)
| 0 | 0.910693 | 1 | 0.910693 | game-dev | MEDIA | 0.541567 | game-dev,testing-qa | 0.951477 | 1 | 0.951477 |
jesseduffield/lazygit | 4,608 | pkg/snake/snake.go | package snake
import (
"math/rand"
"time"
"github.com/samber/lo"
)
type Game struct {
// width/height of the board
width int
height int
// function for rendering the game. If alive is false, the cells are expected
// to be ignored.
render func(cells [][]CellType, alive bool)
// closed when the game is exited
exit chan (struct{})
// channel for specifying the direction the player wants the snake to go in
setNewDir chan (Direction)
// allows logging for debugging
logger func(string)
// putting this on the struct for deterministic testing
randIntFn func(int) int
}
type State struct {
// first element is the head, final element is the tail
snakePositions []Position
foodPosition Position
// direction of the snake
direction Direction
// direction as of the end of the last tick. We hold onto this so that
// the snake can't do a 180 turn inbetween ticks
lastTickDirection Direction
}
type Position struct {
x int
y int
}
type Direction int
const (
Up Direction = iota
Down
Left
Right
)
type CellType int
const (
None CellType = iota
Snake
Food
)
func NewGame(width, height int, render func(cells [][]CellType, alive bool), logger func(string)) *Game {
return &Game{
width: width,
height: height,
render: render,
randIntFn: rand.Intn,
exit: make(chan struct{}),
logger: logger,
setNewDir: make(chan Direction),
}
}
func (self *Game) Start() {
go self.gameLoop()
}
func (self *Game) Exit() {
close(self.exit)
}
func (self *Game) SetDirection(direction Direction) {
self.setNewDir <- direction
}
func (self *Game) gameLoop() {
state := self.initializeState()
var alive bool
self.render(self.getCells(state), true)
ticker := time.NewTicker(time.Duration(75) * time.Millisecond)
for {
select {
case <-self.exit:
return
case dir := <-self.setNewDir:
state.direction = self.newDirection(state, dir)
case <-ticker.C:
state, alive = self.tick(state)
self.render(self.getCells(state), alive)
if !alive {
return
}
}
}
}
func (self *Game) initializeState() State {
centerOfScreen := Position{self.width / 2, self.height / 2}
snakePositions := []Position{centerOfScreen}
state := State{
snakePositions: snakePositions,
direction: Right,
foodPosition: self.newFoodPos(snakePositions),
}
return state
}
func (self *Game) newFoodPos(snakePositions []Position) Position {
// arbitrarily setting a limit of attempts to place food
attemptLimit := 1000
for range attemptLimit {
newFoodPos := Position{self.randIntFn(self.width), self.randIntFn(self.height)}
if !lo.Contains(snakePositions, newFoodPos) {
return newFoodPos
}
}
panic("SORRY, BUT I WAS TOO LAZY TO MAKE THE SNAKE GAME SMART ENOUGH TO PUT THE FOOD SOMEWHERE SENSIBLE NO MATTER WHAT, AND I ALSO WAS TOO LAZY TO ADD A WIN CONDITION")
}
// returns whether the snake is alive
func (self *Game) tick(currentState State) (State, bool) {
nextState := currentState // copy by value
newHeadPos := nextState.snakePositions[0]
nextState.lastTickDirection = nextState.direction
switch nextState.direction {
case Up:
newHeadPos.y--
case Down:
newHeadPos.y++
case Left:
newHeadPos.x--
case Right:
newHeadPos.x++
}
outOfBounds := newHeadPos.x < 0 || newHeadPos.x >= self.width || newHeadPos.y < 0 || newHeadPos.y >= self.height
eatingOwnTail := lo.Contains(nextState.snakePositions, newHeadPos)
if outOfBounds || eatingOwnTail {
return State{}, false
}
nextState.snakePositions = append([]Position{newHeadPos}, nextState.snakePositions...)
if newHeadPos == nextState.foodPosition {
nextState.foodPosition = self.newFoodPos(nextState.snakePositions)
} else {
nextState.snakePositions = nextState.snakePositions[:len(nextState.snakePositions)-1]
}
return nextState, true
}
func (self *Game) getCells(state State) [][]CellType {
cells := make([][]CellType, self.height)
setCell := func(pos Position, value CellType) {
cells[pos.y][pos.x] = value
}
for i := range self.height {
cells[i] = make([]CellType, self.width)
}
for _, pos := range state.snakePositions {
setCell(pos, Snake)
}
setCell(state.foodPosition, Food)
return cells
}
func (self *Game) newDirection(state State, direction Direction) Direction {
// don't allow the snake to turn 180 degrees
if (state.lastTickDirection == Up && direction == Down) ||
(state.lastTickDirection == Down && direction == Up) ||
(state.lastTickDirection == Left && direction == Right) ||
(state.lastTickDirection == Right && direction == Left) {
return state.direction
}
return direction
}
| 0 | 0.867442 | 1 | 0.867442 | game-dev | MEDIA | 0.863553 | game-dev | 0.973316 | 1 | 0.973316 |
EpicSentry/P2ASW | 4,978 | src/game/shared/swarm/asw_fx_shared.cpp | #include "cbase.h"
#include "mathlib/mathlib.h"
#include "util_shared.h"
//#include "model_types.h"
#include "convar.h"
#include "IEffects.h"
//#include "vphysics/object_hash.h"
//#include "IceKey.H"
//#include "checksum_crc.h"
#include "asw_fx_shared.h"
#include "particle_parse.h"
#ifdef CLIENT_DLL
#include "c_te_effect_dispatch.h"
#else
#include "te_effect_dispatch.h"
#include "Sprite.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef GAME_DLL
// link clientside sprite to CSprite - can remove this if we fixup all the maps to not have _clientside ones (do when we're sure we don't need clientside sprites)
LINK_ENTITY_TO_CLASS( env_sprite_clientside, CSprite );
#endif
void UTIL_ASW_EggGibs( const Vector &pos, int iFlags, int iEntIndex )
{
#ifdef GAME_DLL
Vector vecOrigin = pos;
CPASFilter filter( vecOrigin );
UserMessageBegin( filter, "ASWEggEffects" );
WRITE_FLOAT( vecOrigin.x );
WRITE_FLOAT( vecOrigin.y );
WRITE_FLOAT( vecOrigin.z );
WRITE_SHORT( iFlags );
WRITE_SHORT( iEntIndex );
MessageEnd();
#endif
}
void UTIL_ASW_BuzzerDeath( const Vector &pos )
{
#ifdef GAME_DLL
Vector vecExplosionPos = pos;
CPASFilter filter( vecExplosionPos );
UserMessageBegin( filter, "ASWBuzzerDeath" );
WRITE_FLOAT( vecExplosionPos.x );
WRITE_FLOAT( vecExplosionPos.y );
WRITE_FLOAT( vecExplosionPos.z );
MessageEnd();
#endif
}
void UTIL_ASW_DroneBleed( const Vector &pos, const Vector &dir, int amount )
{
CEffectData data;
data.m_vOrigin = pos;
data.m_vNormal = dir;
//data.m_flScale = (float)amount;
// todo: use filter?
QAngle vecAngles;
VectorAngles( data.m_vNormal, vecAngles );
DispatchParticleEffect( "drone_shot", data.m_vOrigin, vecAngles );
//DispatchEffect( "DroneBleed", data );
}
void UTIL_ASW_BloodImpact( const Vector &pos, const Vector &dir, int color, int amount )
{
CEffectData data;
data.m_vOrigin = pos;
data.m_vNormal = dir;
data.m_flScale = (float)amount;
data.m_nColor = (unsigned char)color;
DispatchEffect( "ASWBloodImpact", data );
}
void UTIL_ASW_BloodDrips( const Vector &origin, const Vector &direction, int color, int amount )
{
if ( !UTIL_ShouldShowBlood( color ) )
return;
if ( color == DONT_BLEED || amount == 0 )
return;
if ( g_Language.GetInt() == LANGUAGE_GERMAN && color == BLOOD_COLOR_RED )
color = 0;
if ( amount > 255 )
amount = 255;
if (color == BLOOD_COLOR_MECH)
{
g_pEffects->Sparks(origin);
if (random->RandomFloat(0, 2) >= 1)
{
UTIL_Smoke(origin, random->RandomInt(10, 15), 10);
}
}
else
{
// Normal blood impact
//UTIL_ASW_BloodImpact( origin, direction, color, amount );
QAngle vecAngles;
VectorAngles( direction, vecAngles );
if ( amount < 4 )
DispatchParticleEffect( "marine_bloodsplat_light", origin, vecAngles );
else
DispatchParticleEffect( "marine_bloodsplat_heavy", origin, vecAngles );
}
}
void UTIL_ASW_MarineTakeDamage( const Vector &origin, const Vector &direction, int color, int amount, CASW_Marine *pMarine, bool bFriendly )
{
if ( !UTIL_ShouldShowBlood( color ) )
return;
if ( color == DONT_BLEED || amount == 0 )
return;
if ( g_Language.GetInt() == LANGUAGE_GERMAN && color == BLOOD_COLOR_RED )
color = 0;
if ( amount > 255 )
amount = 255;
// TODO: use amount to determine large versus small attacks taken?
QAngle vecAngles;
VectorAngles( -direction, vecAngles );
Vector vecForward, vecRight, vecUp;
AngleVectors( vecAngles, &vecForward, &vecRight, &vecUp );
#ifdef CLIENT_DLL
const char *pchEffectName = NULL;
if ( bFriendly )
pchEffectName = "marine_hit_blood_ff";
else
pchEffectName = "marine_hit_blood";
CUtlReference< CNewParticleEffect > pEffect;
pEffect = pMarine->ParticleProp()->Create( pchEffectName, PATTACH_CUSTOMORIGIN );
if ( pEffect )
{
pMarine->ParticleProp()->AddControlPoint( pEffect, 2, pMarine, PATTACH_ABSORIGIN_FOLLOW );
pEffect->SetControlPoint( 0, origin );//origin - pMarine->GetAbsOrigin()
pEffect->SetControlPointOrientation( 0, vecForward, vecRight, vecUp );
}
else
{
Warning( "Could not create effect for marine hurt: %s", pchEffectName );
}
#endif
}
void UTIL_ASW_GrenadeExplosion( const Vector &vecPos, float flRadius )
{
#ifdef GAME_DLL
Vector vecExplosionPos = vecPos;
CPASFilter filter( vecExplosionPos );
UserMessageBegin( filter, "ASWGrenadeExplosion" );
WRITE_FLOAT( vecExplosionPos.x );
WRITE_FLOAT( vecExplosionPos.y );
WRITE_FLOAT( vecExplosionPos.z );
WRITE_FLOAT( flRadius );
MessageEnd();
#endif
}
void UTIL_ASW_EnvExplosionFX( const Vector &vecPos, float flRadius, bool bOnGround )
{
#ifdef GAME_DLL
Vector vecExplosionPos = vecPos;
CPASFilter filter( vecExplosionPos );
UserMessageBegin( filter, "ASWEnvExplosionFX" );
WRITE_FLOAT( vecExplosionPos.x );
WRITE_FLOAT( vecExplosionPos.y );
WRITE_FLOAT( vecExplosionPos.z );
WRITE_FLOAT( flRadius );
WRITE_BOOL( bOnGround );
//damage.bFriendlyFire = msg.ReadOneBit() ? true : false;
MessageEnd();
#endif
} | 0 | 0.923785 | 1 | 0.923785 | game-dev | MEDIA | 0.915 | game-dev | 0.844255 | 1 | 0.844255 |
jaseowns/uo_outlands_razor_scripts | 4,132 | outlands.uorazorscripts.com/script/0b591428-7149-4144-9e36-a82ee3c343c5 | # This is an automated backup - check out https://outlands.uorazorscripts.com/script/0b591428-7149-4144-9e36-a82ee3c343c5 for latest
# Automation by Jaseowns
## Script: TemporalShift
## Created by: temporalshift.#0
#############################################
@setvar! hidelogsInRedPouch 1
if not varexist jase_lumber_runebook
overhead "Select your escape runebook" 88
setvar jase_lumber_runebook
endif
if not listexists "jase_lumber_actions"
createlist "jase_lumber_actions"
endif
if inlist "jase_lumber_actions" "red_alert"
overhead "Red Alert!" 34
if skill "Magery" >= 40
overhead 'Recalling...'
while not targetexists
cast "Recall"
wait 200
endwhile
target jase_lumber_runebook
elseif skill "Hiding" >= 40
useskill "Hiding"
endif
poplist "jase_lumber_actions" "red_alert"
overhead "Stopping script..." 34
stop
# replay
endif
clearsysmsg
if diffweight <= 30
organizer 1
while queued
overhead 'Moving items...'
wait 500
endwhile
if diffweight <= 30
overhead "Too heavy still.. check organizer agent 1" 34
replay
endif
endif
if hideLogsInRedPouch = 1 and findtype "pouch" backpack 38 as jouch
while findtype 7133 backpack as jingots
if find jingots jouch
// do nothing
else
lift jingots 60000
drop jouch -1 -1 -1
endif
@ignore jingots
endwhile
endif
@clearignore
endif
if not timerexists 'DH'
createtimer 'DH'
settimer 'DH' 0
endif
if timer 'DH' > 11000
useskill 'DetectingHidden'
wft 250
target self
settimer 'DH' 0
pause 500
endif
if lhandempty ?? 0
if findtype "hatchet" backpack
dclicktype 'hatchet' backpack
wait 200
endif
endif
if lhandempty ?? 0
overhead "No more hatchets!" 34
replay
endif
wait 500
overhead 'Lumberjacking' 0
hotkey 'Use item in hand'
wft 1000
hotkey 'Target Self'
for 75
wait 100
if insysmsg 'world is saving'
for 30
overhead 'Waiting for world save...'
wait 1000
if insysmsg 'save complete'
overhead 'Save complete - continue on!' 88
clearsysmsg
wait 250
replay
elseif insysmsg "now tracking"
pushlist "jase_lumber_actions" "red_alert"
clearsysmsg
wait 250
replay
endif
endfor
elseif insysmsg "now tracking"
pushlist "jase_lumber_actions" "red_alert"
replay
elseif lhandempty ?? 0
overhead "Broke axe" 34
replay
elseif insysmsg 'You do not see any' or insysmsg 'You cannot produce any wood'
overhead 'Move to next spot' 88
wait 250
replay
elseif insysmsg "travel"
overhead 'Waiting for travel...'
wait 1000
replay
else
if insysmsg "any harvestable" or insysmsg "jase_lumber_actions"
// No Ore
overhead 'Move to next spot' 88
replay
elseif insysmsg "skillgain" or insysmsg "harvesting is not allowed"
// Gained skill
replay
elseif insysmsg "world is saving" or insysmsg 'World save complete'
// World Save
replay
elseif insysmsg "You hack"
// Failed
replay
elseif insysmsg "You chop"
// Success
replay
elseif insysmsg "You must wait"
// Wait message
overhead 'You must wait..' 34
wait 500
replay
endif
endif
endfor
if insysmsg "You must wait"
// Wait message
overhead 'You must wait..' 34
wait 500
replay
endif
overhead 'Captcha break!' 34
for 20
overhead 'Awaiting Captcha...' 34
wait 1000
if insysmsg 'Captcha successful'
overhead 'Success - continue on!' 88
wait 1000
replay
endif
endfor
overhead 'Stopping script' 34 | 0 | 0.752196 | 1 | 0.752196 | game-dev | MEDIA | 0.85758 | game-dev | 0.800669 | 1 | 0.800669 |
doughtmw/ArUcoDetectionHoloLens-Unity | 2,569 | ArUcoDetectionHoloLensUnity/Assets/MRTK/SDK/Features/UX/Scripts/VisualThemes/ThemeEngines/InteractableAnimatorTheme.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.UI
{
/// <summary>
/// ThemeEngine that controls Animator state based on state changes
/// Targets first Animator component returned on initialized GameObject
/// </summary>
public class InteractableAnimatorTheme : InteractableThemeBase
{
private int lastIndex = -1;
private Animator controller;
public InteractableAnimatorTheme()
{
Types = new Type[] { typeof(Transform) };
Name = "AnimatorTheme";
}
/// <inheritdoc />
public override ThemeDefinition GetDefaultThemeDefinition()
{
return new ThemeDefinition()
{
ThemeType = GetType(),
StateProperties = new List<ThemeStateProperty>()
{
new ThemeStateProperty()
{
Name = "Animator Trigger",
Type = ThemePropertyTypes.AnimatorTrigger,
Values = new List<ThemePropertyValue>(),
Default = new ThemePropertyValue() { String = "Default" }
},
},
CustomProperties = new List<ThemeProperty>(),
};
}
/// <inheritdoc />
public override void Init(GameObject host, ThemeDefinition settings)
{
controller = host.GetComponent<Animator>();
base.Init(host, settings);
}
/// <inheritdoc />
public override ThemePropertyValue GetProperty(ThemeStateProperty property)
{
ThemePropertyValue start = new ThemePropertyValue();
start.String = lastIndex != -1 ? property.Values[lastIndex].String : string.Empty;
return start;
}
/// <inheritdoc />
public override void SetValue(ThemeStateProperty property, int index, float percentage)
{
if (lastIndex != index)
{
SetValue(property, property.Values[index]);
lastIndex = index;
}
}
/// <inheritdoc />
protected override void SetValue(ThemeStateProperty property, ThemePropertyValue value)
{
if (controller != null && !string.IsNullOrEmpty(value.String))
{
controller.SetTrigger(value.String);
}
}
}
}
| 0 | 0.817596 | 1 | 0.817596 | game-dev | MEDIA | 0.945242 | game-dev | 0.924653 | 1 | 0.924653 |
surparallel/luacluster_unity3d_demo | 23,428 | Assets/core/LoadManager.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Video;
namespace grpania_unity3d_demo
{
public class LoadManager : MonoBehaviour
{
private static LoadManager instance;
private Dictionary<string, AssetBundleManifest> _manifest;
private Dictionary<string, AssetBundle> _abs;
private Dictionary<string, Dictionary<string, object>> _res;
private List<string> _del;
//private Queue<LoadABItem> que = new Queue<LoadABItem>();
//private bool isQue = false;
public static string TXT = "text";
public static string AC = "audio";
public static string VC = "video";
public static string MAT = "mat";
public static string SP = "sprite";
public static string OBJ = "object";
public static string SHA = "shader";
public static string SCENE = "scene";
public static string FGUI = "fgui";
public LoadManager()
{
_manifest = new Dictionary<string, AssetBundleManifest>();
_abs = new Dictionary<string, AssetBundle>();
_res = new Dictionary<string, Dictionary<string, object>>();
_del = new List<string>();
}
public static LoadManager inst
{
get
{
if (instance == null)
{
instance = new GameObject("ab").AddComponent<LoadManager>();
instance.gameObject.name = "ab";
instance.gameObject.transform.parent = GameObject.Find("main").transform;
GameObject.DontDestroyOnLoad(instance.gameObject);
}
//instance = new LoadManager();
return instance;
}
}
public void Log()
{
Tool.Err("_manifest.len = " + _manifest.Keys.Count);
Tool.Err("_abs.len = " + _abs.Keys.Count);
Tool.Err("_res.len = " + _res.Keys.Count);
foreach(string i in _res.Keys)
Tool.Err("_res name="+i);
Tool.Err("_del.len = " + _del.Count);
}
public void Update()
{
lock (_del)
{
int len = _del.Count;
while (len > 0)
{
string ab = _del[0];
_del.RemoveAt(0);
this.RemoveRes(ab);
_abs[ab].Unload(true);
_abs.Remove(ab);
len--;
//Tools.LogError("remove ab - " + ri.b);
}
}
}
public void ClearGame(string game)
{
// Tools.LogError("ClearGame _del.abs.count = "+_abs.Keys.Count + " " + game);
// Tools.LogError("ClearGame game = " + game + " abs.len =" + _abs.Keys.Count);
string[] msg;
string ab;
foreach (string g in _abs.Keys)
{
msg = g.Replace(Config.fileExt, "").Split('_');
// ab = msg[msg.Length - 1];
ab = msg[0];
// Tools.LogError("ClearGame msg[0] = " + ab);
if (ab == game)
{
Tool.Err("ClearGame _del.add = "+g);
_del.Add(g);
}
}
}
public void RemoveRes(string ab)
{
// ab = game + "_" + ab.ToLower() + Config.fileExt;
// Tools.LogError("RemoveRes ab = " + ab);
if (_res.ContainsKey(ab))
{
Dictionary<string, object> res = _res[ab];
foreach (UnityEngine.Object o in res.Values)
GameObject.DestroyImmediate(o,true);
_res.Remove(ab);
// Tools.LogError("remove res - " + ab);
}
}
public void AddAB(string ab, AssetBundle abs,LoadABItem item = null)
{
// Tools.LogError("AddAB ab = " + ab);
if (!_abs.ContainsKey(ab))
{
_abs.Add(ab, abs);
if (item != null)
{
UnityEngine.Object[] objs = abs.LoadAllAssets();
foreach (UnityEngine.Object o in objs)
{
// Tools.LogError("AddRes name = " + o.name);
this.AddRes(item.sb, o.name, o, item.game);
}
}
}
else
{
Tool.Err("error add ab=" + ab);
}
}
public void RemoveAB(string ab, string game)
{
ab = game + "_" + ab.ToLower() + Config.fileExt;
if (_abs.ContainsKey(ab))
{
this.RemoveRes(ab);
_abs[ab].Unload(true);
_abs.Remove(ab);
}
}
public bool IsExistsAB(string ab)
{
return _abs.ContainsKey(ab);
}
public void AddRes(string ab, string name, object obj, string game)
{
ab = game + "_" + ab.ToLower() + Config.fileExt;
// Tools.LogError("AddRes ab = "+ab + " name = " + obj.name);
if (_res.ContainsKey(ab))
{
_res[ab][name] = obj;
}
else
{
_res[ab] = new Dictionary<string, object>();
_res[ab][name] = obj;
}
}
public object GetRes(string ab, string name, string game)
{
ab = game + "_" + ab.ToLower() + Config.fileExt;
if (_res.ContainsKey(ab) && _res[ab].ContainsKey(name))
{
return _res[ab][name];
}
return null;
}
public void ChangeSceneAsync(string ab, string name, Action fun, string game = "base")
{
#if G
this.LoadAsync(SCENE, ab, name, (x) =>
{
this.StartCoroutine(LoadSceneAsync(name, fun));
}, game);
#else
this.StartCoroutine(LoadSceneAsync(name, fun));
#endif
}
public void ChangeSceneSync(string ab, string name, string game = "base")
{
#if G
this.Load(SCENE, ab, name, game);
#else
#endif
SceneManager.LoadScene(name);
}
private IEnumerator LoadSceneAsync(string name, Action fun)
{
AsyncOperation ao = SceneManager.LoadSceneAsync(name);
ao.allowSceneActivation = false;
while (!ao.isDone)
{
if (ao.progress >= 0.9f)
{
ao.allowSceneActivation = true;
if (fun != null)
fun();
yield break;
}
yield return null;
}
//yield return ao;
//if (ao.isDone)
//{
// if (fun != null)
// fun();
//}
}
public void AddManifest(string name)
{
#if G
//Debug.Log(Config.path + game + "/" + game);
AssetBundle ab = AssetBundle.LoadFromFile(Config.path + name + "/" + name);
// AssetBundle ab = AssetBundle.LoadFromFile(Config.path + name);
if (ab != null)
{
AssetBundleManifest manifest = ab.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
ab.Unload(false);
if (!_manifest.ContainsKey(name))
_manifest.Add(name, manifest);
}
#endif
}
public void ClearManifest()
{
#if G
_manifest = new Dictionary<string, AssetBundleManifest>();
#endif
}
private string[] GetBundleDependencies(string ab, string game = "base")
{
//Tools.LogError("GetBundleDependencies - ab=" + ab + " game=" + game);
// game = "ab";
if (!_manifest.ContainsKey(game))
{
Tool.Err("GetBundleDependencies not contain game=" + game);
return new string[] { };
}
AssetBundleManifest manifest = _manifest[game];
string[] array = manifest.GetAllDependencies(ab);
List<string> dependnces = new List<string>();
if (array != null && array.Length > 0)
{
foreach (string item in array)
{
if (!dependnces.Contains(item) && !this.IsExistsAB(item))
{
dependnces.Add(item);
//string[] arr = this.GetBundleDependencies(item, game);
//if (arr != null && arr.Length > 0)
//{
// foreach (string t in arr)
// {
// if (!dependnces.Contains(t) && !this.IsExistsAB(item))
// dependnces.Add(t);
// }
//}
}
}
}
if (dependnces.Count > 0)
return dependnces.ToArray();
return null;
}
private string GetGameByBundle(string name)
{
string[] names = name.Split('_');
return names[0];
}
//private void CheckQueue()
//{
// if(que.Count > 0)
// {
// LoadABItem item = que.Dequeue();
// if(item.type == 0)
// {
// }
// else
// {
// //this.isQue = false;
// this._LoadAsyncEx(item);
// }
// }
// else
// {
// this.isQue = false;
// }
//}
public void _LoadAsync(string ab, Action<AssetBundle> fun = null, string game = "base",bool isAll = false)
{
#if G
string sb = ab;
ab = ab.ToLower();
ab = game + "_" + ab.ToLower() + Config.fileExt;
if (_abs.ContainsKey(ab))
{
if(fun != null)
fun(_abs[ab]);
return;
}
LoadABItem item = new LoadABItem();
item.sb = sb;
item.ab = ab;
item.game = game;
item.type = 1;
item.fun = fun;
//if (this.isQue)
//{
// que.Enqueue(item);
//}
//else
//{
// this.isQue = true;
this._LoadAsyncEx(item,isAll);
//}
#else
if(fun != null)
fun(null);
#endif
}
private void _LoadAsyncEx(LoadABItem item,bool isAll = false)
{
string ab = item.ab;
Action<AssetBundle> fun = item.fun;
string game = item.game;
string[] deps = this.GetBundleDependencies(ab, game);
string path = "";
List<LoadItem> list = new List<LoadItem>();
if (deps != null)
{
foreach (string bundle in deps)
{
if (this.IsExistsAB(bundle) || bundle == ab)
continue;
path = Config.path + this.GetGameByBundle(bundle) + "/" + bundle;
LoadItem li = new LoadItem();
li.path = path;
li.ab = bundle;
li.game = game;
li.fun = fun;
list.Add(li);
}
}
if (!this.IsExistsAB(ab))
{
path = Config.path + this.GetGameByBundle(ab) + "/" + ab;
LoadItem lx = new LoadItem();
lx.path = path;
lx.ab = ab;
lx.game = game;
lx.fun = fun;
list.Add(lx);
}
foreach (LoadItem ll in list)
{
Tool.Err("_LoadAsync ab=" + ll.path);
}
if (list.Count > 0)
{
//Tools.LogError("list LoadItemList.inst.Load - " + list.Count.ToString());
LoadItemList.inst.Load(list, (x) =>
{
//Tools.LogError("x LoadItemList.inst.Load - " + x.Count.ToString());
foreach (LoadCom ax in x)
{
if (ax.ab != null)
{
if (isAll)
this.AddAB(ax.name, ax.ab, item);
else
this.AddAB(ax.name, ax.ab);
}
}
if (fun != null)
{
fun(_abs[ab]);
//this.CheckQueue();
}
});
}
}
public AssetBundle _LoadSync(string ab, string game = "base",bool isAll = false)
{
#if G
string sb = ab;
ab = ab.ToLower();
ab = game + "_" + ab + Config.fileExt;
//Tools.LogError("_LoadSync ab=" + ab + " game=" + game);
if (_abs.ContainsKey(ab))
{
return _abs[ab];
}
LoadABItem item = new LoadABItem();
item.sb = sb;
item.ab = ab;
item.game = game;
item.type = 0;
item.fun = null;
//if (que.Count > 0)
//{
// que.Enqueue(item);
//}
//else
//{
return this._LoadSyncEx(item,isAll);
//}
#else
return null;
#endif
}
private AssetBundle _LoadSyncEx(LoadABItem item,bool isAll = false)
{
string ab = item.ab;
string game = item.game;
string[] deps = this.GetBundleDependencies(ab, game);
string path = Config.path + game + "/" + ab;
AssetBundle asset = null;
if (deps != null)
{
foreach (string bundle in deps)
{
if (this.IsExistsAB(bundle) || bundle == ab)
continue;
path = Config.path + this.GetGameByBundle(bundle) + "/" + bundle;
asset = AssetBundle.LoadFromFile(path);
if (asset != null)
{
if (isAll)
this.AddAB(bundle, asset, item);
else
this.AddAB(bundle, asset);
}
}
}
if (!this.IsExistsAB(ab))
{
path = Config.path + this.GetGameByBundle(ab) + "/" + ab;
Tool.Err("_LoadSync ab=" + path);
asset = AssetBundle.LoadFromFile(path);
if (asset != null)
{
if (isAll)
this.AddAB(ab, asset, item);
else
this.AddAB(ab, asset);
}
}
return asset;
}
private object LoadEditor(string type, string ab, string name, Action<object> fun, string game = "base")
{
#if UNITY_EDITOR
string path = "";
if (type == SP)
{
path = this.GetLocalPath(@"/image/" + ab + "/", name, "*.png", game);
UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(path);
Sprite sp = null;
if (obj != null && obj.GetType() == typeof(Texture2D))
{
Texture2D texture = obj as Texture2D;
sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
}
else
{
sp = obj as Sprite;
}
this.AddRes(ab, name, sp, game);
if (fun != null)
fun(sp);
else
return sp;
}
else if (type == AC)
{
path = this.GetLocalPath(@"/audio/" + ab + "/", name, "*.mp3", game);
AudioClip ac = AssetDatabase.LoadMainAssetAtPath(path) as AudioClip;
this.AddRes(ab, name, ac, game);
if (fun != null)
fun(ac);
else
return ac;
}
else if (type == VC)
{
path = this.GetLocalPath(@"/video/" + ab + "/", name, "*.ogv", game);
VideoClip vc = AssetDatabase.LoadMainAssetAtPath(path) as VideoClip;
this.AddRes(ab, name, vc, game);
if (fun != null)
fun(vc);
else
return vc;
}
else if (type == MAT)
{
path = this.GetLocalPath(@"/mat/" + ab + "/", name, "*.mat", game);
Material mat = AssetDatabase.LoadMainAssetAtPath(path) as Material;
this.AddRes(ab, name, mat, game);
if (fun != null)
fun(mat);
else
return mat;
}
else if (type == OBJ)
{
path = this.GetLocalPath(@"/ui/" + ab + "/", name, "*.prefab", game);
UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(path) as UnityEngine.Object;
this.AddRes(ab, name, obj, game);
if (fun != null)
fun(obj);
else
return obj;
}
else if (type == SHA)
{
path = this.GetLocalPath(@"/shader/" + ab + "/", name, "*.shader", game);
UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(path) as UnityEngine.Object;
this.AddRes(ab, name, obj, game);
if (fun != null)
fun(obj);
else
return obj;
}
else if (type == TXT)
{
path = this.GetLocalPath(@"/data/" + ab + "/", name, "*.json", game);
UnityEngine.TextAsset obj = AssetDatabase.LoadMainAssetAtPath(path) as UnityEngine.TextAsset;
this.AddRes(ab, name, obj.text, game);
if (fun != null)
fun(obj.text);
else
return obj.text;
}
else if (type == SCENE)
{
path = this.GetLocalPath(@"/scene/" + ab + "/", name, "*.unity", game);
UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(path);
if (fun != null)
fun(obj);
else
return obj;
}
#endif
return null;
}
private string GetLocalPath(string ab, string assetName, string assetType, string game = "base")
{
string fullPath = "Res/ab/" + game + ab;
//Debug.Log("GetLocalPath = " + fullPath);
string[] files = Directory.GetFiles(Application.dataPath + "/" + fullPath, "*.*", SearchOption.AllDirectories);
assetType = assetType.Replace("*", string.Empty);
string path = null;
foreach (string item in files)
{
//Debug.Log("path - " + item + "|" + Path.GetFileName(item) + "-" + assetName + assetType);
if (Path.GetExtension(item) == ".meta")
continue;
if (Path.GetFileName(item).ToLower() == (assetName + assetType).ToLower())
{
path = item;
break;
}
if (assetType == ".mp3" && Path.GetFileName(item) == assetName + ".wav")
{
path = item;
break;
}
if (assetType == ".mp3" && Path.GetFileName(item) == assetName + ".ogg")
{
path = item;
break;
}
if (assetType == ".png" && Path.GetFileName(item) == assetName + ".jpg")
{
path = item;
break;
}
}
if (path != null)
path = "Assets/" + path.Replace(Application.dataPath + @"/", string.Empty);
//Tools.Log("GetLoadAssetPath - " + fullPath + " path-" + path);
return path;
}
}
public class LoadItemList : MonoBehaviour
{
private static LoadItemList instance;
private List<LoadItem> list;
private List<LoadCom> abs;
private Action<List<LoadCom>> abFun;
public LoadItemList()
{
abs = new List<LoadCom>();
}
public static LoadItemList inst
{
get
{
instance = new GameObject("load_item").AddComponent<LoadItemList>();
instance.gameObject.name = "ab_" + Tool.GetRandom();
GameObject.DontDestroyOnLoad(instance.gameObject);
return instance;
}
}
public void Load(List<LoadItem> list, Action<List<LoadCom>> fun)
{
this.list = list;
this.abFun = fun;
this.StartCoroutine(LoadItem());
}
private System.Collections.IEnumerator LoadItem()
{
while (list.Count > 0)
{
LoadItem li = list[0];
list.RemoveAt(0);
//Tools.LogError("async - ab=" + li.ab + " path=" + li.path);
if (!LoadManager.inst.IsExistsAB(li.ab))
{
AssetBundleCreateRequest abcr = AssetBundle.LoadFromFileAsync(li.path);
yield return abcr;
//Tools.LogError("async add ab - " + li.ab);
LoadCom lc = new LoadCom();
lc.name = li.ab;
lc.ab = abcr.assetBundle;
this.abs.Add(lc);
}
}
yield return null;
this.abFun(this.abs);
GameObject.Destroy(this.gameObject);
}
}
public class LoadCom
{
public string name;
public AssetBundle ab;
}
public class LoadItem
{
public string path;
public string ab;
public string game;
public Action<AssetBundle> fun;
}
public class RemoveItem
{
public string ab;
public string k;
public RemoveItem(string ab, string k)
{
this.ab = ab;
this.k = k;
}
}
public class LoadABItem
{
public string sb;
public string ab;
public string game;
public Action<AssetBundle> fun;
public int type = 0;//0同步 1异步
}
}
| 0 | 0.839568 | 1 | 0.839568 | game-dev | MEDIA | 0.66778 | game-dev | 0.938424 | 1 | 0.938424 |
PotRooms/AzurPromiliaData | 3,966 | Lua/config/chs/weapon_type.lua | local weapon_type = {
[1] = {
[-1] = -1,
[-2] = {
[-3] = -2,
[-4] = -3
}
},
[2] = {
[-1] = -4,
[-2] = {
[-3] = -2,
[-4] = -5
}
},
[3] = {
[-1] = -6,
[-2] = {
[-3] = -2,
[-4] = -7
}
},
[4] = {
[-1] = -8,
[-2] = {
[-3] = -2,
[-4] = -9
}
},
[5] = {
[-1] = -10,
[-2] = {
[-3] = -2,
[-4] = -11
}
},
[6] = {
[-1] = -12,
[-2] = {
[-3] = -2,
[-4] = -13
}
},
[7] = {
[-1] = -14,
[-2] = {
[-3] = -2,
[-4] = -15
}
},
[8] = {
[-1] = -16,
[-2] = {
[-3] = -2,
[-4] = -17
}
},
[9] = {
[-1] = -18,
[-2] = {
[-3] = -2,
[-4] = -19
}
},
[10] = {
[-1] = -20,
[-2] = {
[-3] = -2,
[-4] = -21
}
},
[11] = {
[-1] = -22,
[-2] = {
[-3] = -2,
[-4] = -23
}
},
[12] = {
[-1] = -24,
[-2] = {
[-3] = -2,
[-4] = -25
}
},
[13] = {
[-1] = -26,
[-2] = {
[-3] = -2,
[-4] = -27
}
},
[14] = {
[-1] = -28,
[-2] = {
[-3] = -2,
[-4] = -29
}
},
[15] = {
[-1] = -30,
[-2] = {
[-3] = -2,
[-4] = -31
}
},
[16] = {
[-1] = -32,
[-2] = {
[-3] = -2,
[-4] = -33
}
}
}
local key_to_index_map = {
id = -1,
typeName = -2,
group = -3,
langKey = -4
}
local index_to_key_map = {}
for k, v in pairs(key_to_index_map) do
index_to_key_map[v] = k
end
local value_to_index_map = {
[1] = -1,
lang_weapon_type = -2,
["1_1_0"] = -3,
[2] = -4,
["2_1_0"] = -5,
[3] = -6,
["3_1_0"] = -7,
[4] = -8,
["4_1_0"] = -9,
[5] = -10,
["5_1_0"] = -11,
[6] = -12,
["6_1_0"] = -13,
[7] = -14,
["7_1_0"] = -15,
[8] = -16,
["8_1_0"] = -17,
[9] = -18,
["9_1_0"] = -19,
[10] = -20,
["10_1_0"] = -21,
[11] = -22,
["11_1_0"] = -23,
[12] = -24,
["12_1_0"] = -25,
[13] = -26,
["13_1_0"] = -27,
[14] = -28,
["14_1_0"] = -29,
[15] = -30,
["15_1_0"] = -31,
[16] = -32,
["16_1_0"] = -33
}
local index_to_value_map = {}
for k, v in pairs(value_to_index_map) do
index_to_value_map[v] = k
end
local function SetReadonlyTable(t)
for k, v in pairs(t) do
if type(v) == "table" then
t[k] = SetReadonlyTable(v)
end
end
local mt = {
__data = t,
__index_to_key_map = index_to_key_map,
__key_to_index_map = key_to_index_map,
__index_to_value_map = index_to_value_map,
__index = function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local value_index
if tmt.__key_to_index_map[k] ~= nil then
value_index = data[tmt.__key_to_index_map[k]]
else
value_index = data[k]
end
if type(value_index) == "table" then
return value_index
else
return tmt.__index_to_value_map[value_index]
end
end,
__newindex = function(t, k, v)
errorf("attempt to modify a read-only talbe!", 2)
end,
__pairs = function(t, k)
return function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local nk, nv
if tmt.__key_to_index_map[k] ~= nil then
local iter_key = tmt.__key_to_index_map[k]
nk, nv = next(data, iter_key)
else
nk, nv = next(data, k)
end
local key, value
if tmt.__index_to_key_map[nk] ~= nil then
key = tmt.__index_to_key_map[nk]
else
key = nk
end
if type(nv) == "table" then
value = nv
else
value = tmt.__index_to_value_map[nv]
end
return key, value
end, t, nil
end,
__len = function(t)
local tmt = getmetatable(t)
local data = tmt.__data
return #data
end
}
t = setmetatable({}, mt)
return t
end
weapon_type = SetReadonlyTable(weapon_type)
return weapon_type
| 0 | 0.600271 | 1 | 0.600271 | game-dev | MEDIA | 0.904382 | game-dev | 0.642632 | 1 | 0.642632 |
dengzibiao/moba | 16,001 | Assets/LoadingProgressBar.cs | using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class LoadingProgressBar : MonoBehaviour {
UISlider mProcess;
float mNextTime = 0;
static float mCurrentNum = 0f;
float mMaxNum = 0.01f;
float mCurrentDownSize;
float mMaxSize;
static string backImg;
static string showText;
UISprite m_backImg;
UISprite m_roleRunImg;
UISprite[] m_SpriteList;
int m_RoleRunIndexer = 0;
UILabel m_showText;
UILabel m_proNumText0;
UILabel m_proNumText1;
UILabel m_proNumText2;
public static bool m_LoginScene = true;
public static bool m_DecompressRes = false;
public static bool isFirst = true;
//GameObject selfOb;
public static LoadingProgressBar single;
public static LoadingProgressBar GetSingle()
{
if (single)
return single;
else
return null;
}
bool m_isLoaded = false;
bool m_isGetNextScene = false;
bool m_isWaiting = false;
float startGetServerTime;
public void SetLoaded()
{
m_isLoaded = true;
}
// public int baseTexture;
void Awake()
{
}
public void Start()
{
//if (m_LoginScene)
//{
// mProcess = transform.FindChild("up").GetComponent<UISlider>();
//}
//else
//{
Transform mytra = transform;
mProcess = mytra.FindChild("ProgressBar_liner/up").GetComponent<UISlider>();
m_backImg = mytra.FindChild("BG").GetComponent<UISprite>();
//m_roleRunImg = mytra.FindChild("UI_jiazaiObjAnchor/UI_jiazai/Control - Colored Slider/LoadRoleAnimations/LoadRoleAnimation").GetComponent<UISprite>();
//m_roleRunImg.gameObject.SetActive(roleShow);
//m_showText = mytra.FindChild("UI_jiazaiObjAnchor/UI_jiazai/Label").GetComponent<UILabel>();
//m_SpriteList = new UISprite[4];
//m_SpriteList[0] = m_backImg;
//m_SpriteList[1] = m_roleRunImg;
//m_SpriteList[2] = mytra.FindChild("UI_jiazaiObjAnchor/UI_jiazai/Control - Colored Slider").GetComponent<UISprite>();
//m_SpriteList[3] = mytra.FindChild("UI_jiazaiObjAnchor/UI_jiazai/Control - Colored Slider/Foreground").GetComponent<UISprite>();
//single = this;
if (!m_isLoaded)
{
//selfOb = gameObject;
//if (SwitchingScence.GetScence().dengBool)
//{
// Application.LoadLevel("DengLu");
//}
//else
{
//DontDestroyOnLoad(selfOb.transform.parent);
//Debug.Log(Time.time);
//StartCoroutine(LoadScence());
//mCurrentNum = 0f;
}
RandomBaseTexture();
startGetServerTime = Time.time + 10f;
}
//backImg = FSDataNodeTable<LoadingUINode>.GetSingleton().DataNodeList[baseTexture].UI_type;
//m_backImg.spriteName = backImg;
// m_showText.text = showText;
if (GameLibrary.LastScene == GameLibrary.UI_Major)
{
//Debug.Log("<color=#10DF11>scripId</color>" + playerData.GetInstance().guideData.scripId + "<color=#10DF11>typeId</color>" + playerData.GetInstance().guideData.typeId
// + "<color=#10DF11>stepId</color>" + playerData.GetInstance().guideData.stepId + "<color=#10DF11>uId</color>" + playerData.GetInstance().guideData.uId);
playerData.GetInstance().guideData.scripId = 0;
playerData.GetInstance().guideData.typeId = 0;
playerData.GetInstance().guideData.stepId = 0;
playerData.GetInstance().guideData.uId = 0;
ClientSendDataMgr.GetSingle().GetGuideSend().SendGuidStep(99);
//Debug.Log("<color=#10DF11>scripId</color>" + playerData.GetInstance().guideData.scripId + "<color=#10DF11>typeId</color>" + playerData.GetInstance().guideData.typeId
// + "<color=#10DF11>stepId</color>" + playerData.GetInstance().guideData.stepId + "<color=#10DF11>uId</color>" + playerData.GetInstance().guideData.uId);
}
UI_Loading.LoadScene(Globe.LoadScenceName, Globe.LoadTime, Globe.callBack, Globe.completed);
//}
}
public void RandomBaseTexture()
{
if (isFirst)
{
int baseTexture = Random.Range(1, 7);
//backImg = FSDataNodeTable<LoadingUINode>.GetSingleton().DataNodeList[baseTexture].UI_type;
Debug.Log("randomCount: " + baseTexture);
int showLable = Random.Range(1, 3);
isFirst = false;
}
//showText = FSDataNodeTable<LanguageNode>.GetSingleton().DataNodeList[showLable].content;
}
// Update is called once per frame
void Update()
{
if (m_roleRunImg && Time.frameCount % 3 == 0)
{
m_roleRunImg.spriteName = "UI_loading_pao_" + m_RoleRunIndexer.ToString();
m_RoleRunIndexer++;
if (m_RoleRunIndexer > 6)
{
m_RoleRunIndexer = 0;
}
}
if (mIsDes)
{
if (Time.time - desTime > 0.5f)
{
DestroyObject(gameObject);
//if (SwitchingScence.sceneType != 6)
//{
// //if (SwitchingScence.GetScence().scenceNode.scenceType < 6)
// // CameMoveByPlayer.GetCamera().IsCanMove = true;
// CameMoveByPlayer.GetCamera().SetShowRamera();
// if (FriendManager.Get().GetFriendCount() > 0 && SwitchingScence.sceneType == 2 || SwitchingScence.sceneType == 7)//zcs f
// {
// for (int i = 0; i < FriendManager.Get().GetFriendCount(); i++)
// {
// if (FriendManager.Get().GetIndexFightFriend(i))
// {
// FriendManager.Get().GetIndexFightFriend(i).SetShowActionNmae("Cchang");
// }
// // FightFriend.Get().SetShowActionNmae("Cchang");
// }
// }
//}
//else
//{
// CameMoveByPlayer.GetCamera().selfSetPos = true;
//}
}
else
{
foreach (UISprite child in m_SpriteList)
{
child.color = new Color(1f, 1f, 1f, 1f - (Time.time - desTime) * 2f * 1f);
}
//m_backImg.color = new Color(1f, 1f, 1f, 1f - (Time.time - desTime)*2f * 1f);
//m_roleRunImg.color = new Color(1f, 1f, 1f, 1f - (Time.time - desTime) * 2f * 1f);
}
}
else
{
//Application.LoadLevelAsync(2);
if (m_LoginScene)
{
if (!m_DecompressRes)
{
mCurrentNum += Time.deltaTime * 0.2f;
if (mCurrentNum > mMaxNum)
{
mCurrentNum = mMaxNum;
if (!m_isWaiting)
{
m_isWaiting = true;
startGetServerTime = Time.time;
}
}
if (mProcess)
{
mProcess.value = mCurrentNum;
}
}
}
else
{
if (!m_isGetNextScene)
{
//if (SwitchingScence.GetScence().m_isSetNextScene)
//{
// if (transform.FindChild("UI_Promort/UI_Prompt/0") && transform.FindChild("UI_Promort/UI_Prompt/0").gameObject.activeSelf)
// transform.FindChild("UI_Promort/UI_Prompt/0").gameObject.SetActive(false);
// StartCoroutine(LoadScence());
// mCurrentNum = 0f;
// m_isGetNextScene = true;
// SwitchingScence.GetScence().m_isSetNextScene = false;
//}
//else
//{
// if (Time.time - startGetServerTime > 7f)
// {//超过5秒还是没有获取到服务器发送来的消息
// // if (transform.FindChild("UI_Promort/UI_Prompt/0"))
// // transform.FindChild("UI_Promort/UI_Prompt/0").gameObject.SetActive(true);
// ClientNetMgr.GetSingle().Update();
// }
// else
// {
// ClientNetMgr.GetSingle().Update();
// }
//}
}
//float tempAddNum = Mathf.Max(2f, (mMaxNum - mCurrentNum) * 0.2f);
mCurrentNum += Time.deltaTime * 0.5f;
if (mCurrentNum > mMaxNum)
{
mCurrentNum = mMaxNum;
if (!m_isWaiting)
{
m_isWaiting = true;
startGetServerTime = Time.time;
}
}
if (mProcess)
{
mProcess.value = mCurrentNum;
}
}
}
}
public static int loadedRoleIndex = 0;
//public void ReConnect()
//{
// transform.FindChild("UI_Promort/UI_Prompt/0").gameObject.SetActive(false);
// //ClientSendDataMgr.GetSingle().GetLoginSend().SendEnterScen(AccountMng.getsingleton().mRoleDataArr[loadedRoleIndex].roleid);
// //startGetServerTime = Time.time;
// SwitchingScence.GetScence().dengBool = true;
// Application.LoadLevel("DengLu");
//}
public void SetMaxNum(float num)
{
//if (m_roleRunImg && !m_roleRunImg.gameObject.activeSelf)
// m_roleRunImg.gameObject.SetActive(true);
mMaxNum = num;
//Debug.Log(Time.time + " " + num);
}
bool roleShow = false;
public void SetRoleRun()
{
roleShow = true;
if (m_roleRunImg)
m_roleRunImg.gameObject.SetActive(true);
}
public void SetProNumText1Decompress(float size)
{
m_proNumText1.text = "正在解压资源:";
mCurrentDownSize += size;
m_proNumText0.text = mCurrentDownSize.ToString() + "mb/" + mMaxSize.ToString() + "mb";
}
public void SetStartProNumText(int maxNum, float maxSize)
{
SetTextInfo();
m_proNumText1.text = "正在下载资源:";
m_proNumText2.text = "(1/" + maxNum + ")";
mMaxSize = maxSize;
m_proNumText0.text = mCurrentDownSize.ToString() + "mb/" + mMaxSize.ToString() + "mb";
}
public void SetTextInfo()
{
//m_proNumText0 = transform.FindChild("Control - Colored Slider/Label").GetComponent<UILabel>();
m_proNumText1 = transform.FindChild("ProgressBar_liner/Label1").GetComponent<UILabel>();
//m_proNumText2 = transform.FindChild("Control - Colored Slider/Label2").GetComponent<UILabel>();
}
public void SetCurrentNum(int num, int maxNum)
{
mCurrentNum = 0;
mProcess.value = 0;
//mProcess.value = (float)num / maxNum;
m_proNumText1.text = "正在下载资源:";
m_proNumText2.text = "(" + (num + 1).ToString() + "/" + maxNum.ToString() + ")";
}
public void SetCurrentNumCompress(int index, int total)
{
if (mProcess)
{
mProcess.value = (float)index / total;
m_proNumText1.text = "正在解压资源:";
m_proNumText2.text = "(" + index.ToString() + "/" + total.ToString() + ")";
}
}
public float GetCurrentNum()
{
return mProcess.value;
}
public void SetShowtext(string str)
{
//m_showText.text = str;
}
public void SetPos(Vector3 pos)
{
transform.parent.position = pos;
}
//public void ChangePar(Transform parent)
//{
// Transform desTra = transform.parent;
// transform.parent = parent;
// transform.localPosition = new Vector3(0,0,0);
// DestroyObject(desTra.gameObject);
//}
bool mIsDes = false;
float desTime;
//public void DesPar()
//{
// mIsDes = true;
// desTime = Time.time;
// if (SwitchingScence.sceneType == 4)
// {
// MainRoleScence.GetSingle().GetMainUIRootTra().FindChild("UI_Gongneng_A/UI_Gongneng_P/UI_Gongneng/UI_RoleGongNeng").gameObject.SetActive(false);
// MainRoleScence.GetSingle().GetMainUIRootTra().FindChild("UI_Gongneng_A/UI_Gongneng_P/UI_Gongneng/UI_RoleGongNeng_NQ").gameObject.SetActive(false);
// MainRoleScence.GetSingle().GetMainUIRootTra().FindChild("UI_Gongneng_A/UI_Gongneng_P/UI_Gongneng/UI_OtherGongNeng").gameObject.SetActive(false);
// }
// if (SwitchingScence.scenceID == 15)
// {
// MonsterModeNode monsterModel = FSDataNodeTable<MonsterModeNode>.GetSingleton().DataNodeList[510];
// GameObject NPCOb;
// ResLoad.LoadAndInstanResource("Role/NPC/", monsterModel.monsterModeName, monsterModel.monsterResourceName, out NPCOb,
// SelfPlayer.GetSelfPlayer().m_myTraPa.position + Vector3.one * 2.5f,
// SelfPlayer.GetSelfPlayer().m_myTraPa.rotation.eulerAngles, false);
// //}
// NPCOb.transform.parent = Scene_RoleManage.GetSingle().GetNPCCollection();
// NPCOb.name = "";
// //NPCOb.transform.position = new Vector3(tempNPC.NPCPositionX, tempNPC.NPCPositionY, tempNPC.NPCPositionZ);
// //NPCOb.transform.localScale = new Vector3(tempNPC.NPCSize, tempNPC.NPCSize, tempNPC.NPCSize);
// NPCOb.tag = "NPC";
// //NPCOb.transform.eulerAngles = new Vector3(tempNPC.NPCRositionX, tempNPC.NPCRositionY, tempNPC.NPCRositionZ);
// //}
// NPC npcInfo = null;
// //if (npcObj.GetGameOb() != null)
// {
// npcInfo = NPCOb.transform.GetChild(0).gameObject.AddComponent<NPC>();
// //npcInfo.modleID = npcObj.GetModeID();
// //npcInfo.m_scaling = tempNPC.NPCSize;
// npcInfo.MyInfo = new CMyObject(1);
// npcInfo.MyInfo.SetRoleID(1);
// //npcInfo.Animator.Play("Idle");
// //npcInfo.SetRoleName(tempNPC.NPCName);
// //npcInfo.SetRolePoint(tempNPC.NpcHead);
// //NPCList.AddFirst(npcInfo);
// npcInfo.mType = NPC.NPCType.FollowNpc;
// }
// NPCOb.GetComponent<NavMeshAgent>().enabled = true;
// NPCOb.GetComponent<NavMeshAgent>().avoidancePriority = 40;
// NPCOb.GetComponent<NavMeshAgent>().speed = 6f;
// //if (sceneBlockInfo.sceneBlock_type == 2)
// // NPCOb.SetActive(false);
// }
//}
static AssetBundle bundle;
// IEnumerator LoadScence()
// {
// // MobileInput();
//#if UNITY_IPHONE || UNITY_ANDROID
// // if(Handheld)
// Handheld.ClearShaderCache();//清理显卡
//#endif
// //Resources.UnloadUnusedAssets();
// //System.GC.Collect();//清理内存
// if (bundle)
// bundle.Unload(false);
// //bundle = AssetBundle.LoadFromFile(ResLoad.LOCAL_RES_PATH + SwitchingScence.GetScence().GetSceneInfo().scenceLevelResource + ".unity3d");
// //Debug.Log(SwitchingScence.GetScence().GetSceneInfo().scenceLevelResource + " " + SwitchingScence.GetScence().scenceName);
// ////Object scene = bundle.mainAsset;
// //AsyncOperation async = Application.LoadLevelAsync(SwitchingScence.GetScence().scenceName);
// //yield return async;
// //bundle.Unload(false);
// }
}
| 0 | 0.821942 | 1 | 0.821942 | game-dev | MEDIA | 0.933719 | game-dev | 0.985274 | 1 | 0.985274 |
Kyushik/Unity_ML_Agent | 2,702 | UnitySDK/Assets/ML-Agents/Scripts/HeuristicBrain.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace MLAgents
{
/// <summary>
/// The Heuristic Brain type allows you to hand code an Agent's decision making process.
/// A Heuristic Brain requires an implementation of the Decision interface to which it
/// delegates the decision making process.
/// When yusing a Heuristic Brain, you must give it a Monoscript of a Decision implementation.
/// </summary>
[CreateAssetMenu(fileName = "NewHeuristicBrain", menuName = "ML-Agents/Heuristic Brain")]
public class HeuristicBrain : Brain
{
[SerializeField]
[HideInInspector]
public Decision decision;
#if UNITY_EDITOR
[HideInInspector]
public MonoScript decisionScript;
#endif
[SerializeField]
[HideInInspector]
public string c_decision;
public void OnValidate()
{
#if UNITY_EDITOR
if (decisionScript != null)
{
c_decision = decisionScript.GetClass().Name;
}
else
{
c_decision = "";
}
#endif
}
/// <inheritdoc/>
protected override void Initialize()
{
if ((c_decision != null) && decision == null)
{
decision = CreateInstance(c_decision) as Decision;
decision.brainParameters = brainParameters;
}
}
///Uses the Decision Component to decide that action to take
protected override void DecideAction()
{
if (decision == null)
{
throw new UnityAgentsException(
"The Brain is set to Heuristic, but no decision script attached to it");
}
foreach (Agent agent in agentInfos.Keys)
{
agent.UpdateVectorAction(decision.Decide(
agentInfos[agent].stackedVectorObservation,
agentInfos[agent].visualObservations,
agentInfos[agent].reward,
agentInfos[agent].done,
agentInfos[agent].memories));
}
foreach (Agent agent in agentInfos.Keys)
{
agent.UpdateMemoriesAction(decision.MakeMemory(
agentInfos[agent].stackedVectorObservation,
agentInfos[agent].visualObservations,
agentInfos[agent].reward,
agentInfos[agent].done,
agentInfos[agent].memories));
}
agentInfos.Clear();
}
}
}
| 0 | 0.761832 | 1 | 0.761832 | game-dev | MEDIA | 0.30747 | game-dev | 0.867736 | 1 | 0.867736 |
rust-tw/advent-of-code | 2,481 | 2022/17/i-am-closer/src/lib.rs | mod rock;
mod tower;
use rock::Rock;
use std::collections::HashMap;
use tower::Tower;
pub fn challenge_17(lines: Vec<&str>) -> (usize, usize) {
let part1 = action(2022, lines[0]);
let part2 = action(1_000_000_000_000, lines[0]);
(part1, part2)
}
#[derive(Debug, Hash, PartialEq, Eq)]
struct Snapshot {
rock_type: usize,
dir_index: usize,
top_levels: [u8; 8],
}
fn action(total_rocks: usize, ops: &str) -> usize {
let mut tower = Tower::new();
let mut dir = ops.chars().enumerate().cycle();
let mut rock_count = 0;
let mut database = HashMap::new();
let mut heights = Vec::new();
loop {
if rock_count >= total_rocks {
break tower.get_height();
}
heights.push(tower.get_height());
let mut rock = Rock::new(rock_count % 5, tower.get_height() as i64 + 3);
rock_count += 1;
let dir_index = loop {
let index = match dir.next() {
Some((idx, '>')) => {
rock.move_right(&tower);
idx
}
Some((idx, '<')) => {
rock.move_left(&tower);
idx
}
_ => panic!("Noooo!!!"),
};
if !rock.move_down(&mut tower) {
break index;
}
};
if tower.get_height() > 8 {
let top_levels: [u8; 8] = ((tower.get_height() - 8)..tower.get_height())
.map(|y| tower.get_level(y))
.collect::<Vec<_>>()
.try_into()
.unwrap();
let snapshot = Snapshot {
rock_type: rock_count % 5,
dir_index,
top_levels,
};
match database.get(&snapshot) {
Some(&old_rock_index) => {
let cycle_count = (total_rocks - rock_count) / (rock_count - old_rock_index);
let extra_count = (total_rocks - rock_count) % (rock_count - old_rock_index);
let h = tower.get_height()
+ cycle_count * (tower.get_height() - heights[old_rock_index])
+ heights[old_rock_index + extra_count]
- heights[old_rock_index];
break h;
}
None => {
database.insert(snapshot, rock_count);
}
}
}
}
}
| 0 | 0.790717 | 1 | 0.790717 | game-dev | MEDIA | 0.767149 | game-dev | 0.926831 | 1 | 0.926831 |
chris81605/DOL-BJXExtende_for_ML_Project | 3,845 | DATA/原版 0.4.5.3/DoLModExportData_20240117_021134/passage/Pirate Deck.twee | :: Pirate Deck []
<<location "seapirates">><<set $outside to 1>><<effects>><<getTarget true>>
你在海盗船的甲板上。
<<if Time.dayState is "night">>
<<if isBloodmoon()>>
红色的月光反射在波浪上,整片海看起来就像酒红色。
<</if>>
<<if $weather is "rain" or $weather is "snow">>
寒冷的雨夹雪打在你的脸上。
<<elseif $weather is "clear">>
在月光下你能看得很清楚。
<<else>>
风有把你刮走的危险。
<</if>>
<<elseif Time.dayState is "dawn">>
<<if $weather is "rain" or $weather is "snow">>
汹涌的海浪在黎明的阳光下闪烁。
<<elseif $weather is "clear">>
黎明照亮了地平线。
<<else>>
海浪在黎明的阳光下闪闪发光。
<</if>>
<<elseif Time.dayState is "dusk">>
<<if $weather is "rain" or $weather is "snow">>
夕阳映出四面八方的暴雨。
<<elseif $weather is "clear">>
太阳在地平线上下落。
<<else>>
太阳落在地平线上,黑暗威胁着吞噬世界。
<</if>>
<<else>>
<<if $weather is "rain" or $weather is "snow">>
大雨倾盆。
<<elseif $weather is "clear">>
太阳下山了。
<<else>>
风吹得你眯着眼。
<</if>>
<</if>>
<<if $exposed gte 1>>
你躲到一些木箱后面,掩盖着你未着寸缕的狀態。
<</if>>
<br><br>
<<if $stress gte $stressmax and !$possessed>>
<<passoutpirates>>
<<elseif (Time.dayState is "dawn" or Time.dayState is "day") and $pirate_journey lte 1>>
<<npc "Zephyr">><<person1>>
“是陆地!”桅上瞭望台上有一个声音大喊。泽菲尔到甲板的一侧举起<<his>>的望远镜。你不需要望远镜就能看到海岸线,海滩的斜坡通向一片树林。很近。你不知为何直到现在才有人发现它的存在。
<br><br>
在泽菲尔的命令下,船员们匆匆忙忙地开始行动中。“那里,”泽菲尔大喊着,大步走到舵手面前。“绕着那边走。他们有可供停泊的地方,你应该明白的。”
<br><br>
<<if $exposed gte 1>>
“然后给这个荡妇衣服!”
<br><br>
<</if>>
<<link [[继续|Pirate End]]>><<towelup>><<unset $pirate_journey>><</link>>
<br>
<<else>>
<<set $danger to random(1, 10000)>><<set $dangerevent to 0>>
<<if $pirate_rank gte 1>>
<<set _allure to ($allure / 2)>>
<<else>>
<<set _allure to $allure>>
<</if>>
<<if ($danger gte (9900 - _allure) or $eventforced) and $eventskip is 0>>
<<events_pirate_deck>>
<<elseif $pirate_rank is 0 and $pirate_status gte 90>>
<<generateRole 0 0 "pirate">><<person1>>
你听到一声令人担忧的爆裂声。你并不是唯一一个注意到的人。很多双眼睛一同望向了一个坐在桅杆瞭望台上的<<person>>。
<br><br>
又是一声脆响,桅杆瞭望台崩塌成了木头碎片。<<person>>从高空坠落,<<he>>抓住了桅杆,但桅杆也跟着断裂了。<<He>>一头栽入了海中。
<br><br>
<<link [[跳水救人|Pirate Rank Dive]]>><</link>>
<br>
<<link [[让泽菲尔来|Pirate Rank Get]]>><</link>>
<br>
<<elseif Time.hour gte 12 and Time.hour lte 18 and $pirate_attack is undefined>>
“所有人!”泽菲尔大吼着,收起<<nnpc_his "Zephyr">>的望远镜。“进入备战状态!”
<br><br>
海盗们从船舱中冲出,迅速投入行动。
<br><br>
<<link [[继续|Pirate Attack]]>><<set $pirate_attack to 1>><</link>>
<br>
<<elseif random(1, 4) is 4 and $exposed lte 0 and $eventskip is 0>>
<<pirate_mate_work deck>>
<<else>>
<<if $nextPassageCheck is "Wraith Snatched Pirate Railing">>
<span class="nextLink"><<link [[栏杆。|Wraith Snatched Pirate Railing]]>><</link>></span>
<<elseif $pirate_rank lte 0>>
<<link [[靠在栏杆上|Pirate Railing]]>><</link>>
<br>
<</if>>
<<if Time.dayState is "dawn">>
<<link [[观赏日出 (1:00)|Pirate Dawn]]>><<pass 60>><<stress -6>><</link>><<lstress>>
<br><br>
<<elseif Time.dayState is "dusk">>
<<link [[观赏日落 (1:00)|Pirate Dusk]]>><<pass 60>><<stress -6>><</link>><<lstress>>
<br><br>
<</if>>
<<if $possessed>>
<<elseif Time.dayState isnot "night">>
泽菲尔船长透过望远镜观察。
<br>
<<if $exposed gte 1>>
<<link [[向泽菲尔请求衣物|Pirate Clothes]]>><</link>><<difficulty 67>>
<br>
<<else>>
<<link [[走近|Pirate Zephyr]]>><</link>>
<br>
<</if>>
<<else>>
泽菲尔船长安坐在<<nnpc_his "Zephyr">>的房间裡。
<br>
<<if $exposed gte 1>>
<<link [[向泽菲尔请求衣物|Pirate Clothes]]>><</link>><<difficulty 67>>
<br>
<</if>>
<</if>>
<br>
<<link [[船舱 (0:01)|Pirate Cabin]]>><<pass 1>><</link>>
<br>
<</if>>
<</if>>
/*A girl in a white sundress swabs the deck with a skip, her long brown hair jumping with each movement. "Oops," she says when she sees you. "You're not supposed to be here yet. Let me help. Whoosh!" She bonks your head with the broom. The world spins.
<br><br>
<<link [[Next|Beach]]>><<set $eventskip to 1>><<endevent>><</link>>
<br>*/
<<set $eventskip to 0>> | 0 | 0.761643 | 1 | 0.761643 | game-dev | MEDIA | 0.902725 | game-dev | 0.794036 | 1 | 0.794036 |
kbrawley95/VSCode-OpenGL-Game-Engine | 3,852 | Dependencies/include/BulletCollision/CollisionDispatch/btHashedSimplePairCache.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_HASHED_SIMPLE_PAIR_CACHE_H
#define BT_HASHED_SIMPLE_PAIR_CACHE_H
#include "LinearMath/btAlignedObjectArray.h"
const int BT_SIMPLE_NULL_PAIR=0xffffffff;
struct btSimplePair
{
btSimplePair(int indexA,int indexB)
:m_indexA(indexA),
m_indexB(indexB),
m_userPointer(0)
{
}
int m_indexA;
int m_indexB;
union
{
void* m_userPointer;
int m_userValue;
};
};
typedef btAlignedObjectArray<btSimplePair> btSimplePairArray;
extern int gOverlappingSimplePairs;
extern int gRemoveSimplePairs;
extern int gAddedSimplePairs;
extern int gFindSimplePairs;
class btHashedSimplePairCache
{
btSimplePairArray m_overlappingPairArray;
bool m_blockedForChanges;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
public:
btHashedSimplePairCache();
virtual ~btHashedSimplePairCache();
void removeAllPairs();
virtual void* removeOverlappingPair(int indexA,int indexB);
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btSimplePair* addOverlappingPair(int indexA,int indexB)
{
gAddedSimplePairs++;
return internalAddPair(indexA,indexB);
}
virtual btSimplePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btSimplePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btSimplePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btSimplePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btSimplePair* findPair(int indexA,int indexB);
int GetCount() const { return m_overlappingPairArray.size(); }
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btSimplePair* internalAddPair(int indexA, int indexB);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btSimplePair& pair, int indexA, int indexB)
{
return pair.m_indexA == indexA && pair.m_indexB == indexB;
}
SIMD_FORCE_INLINE unsigned int getHash(unsigned int indexA, unsigned int indexB)
{
int key = static_cast<int>(((unsigned int)indexA) | (((unsigned int)indexB) <<16));
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return static_cast<unsigned int>(key);
}
SIMD_FORCE_INLINE btSimplePair* internalFindPair(int proxyIdA , int proxyIdB, int hash)
{
int index = m_hashTable[hash];
while( index != BT_SIMPLE_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyIdA, proxyIdB) == false)
{
index = m_next[index];
}
if ( index == BT_SIMPLE_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
};
#endif //BT_HASHED_SIMPLE_PAIR_CACHE_H
| 0 | 0.886249 | 1 | 0.886249 | game-dev | MEDIA | 0.608504 | game-dev | 0.943129 | 1 | 0.943129 |
bloodmc/GriefDefender | 91,076 | bukkit/src/main/java/com/griefdefender/permission/GDPermissionManager.java | /*
* This file is part of GriefDefender, licensed under the MIT License (MIT).
*
* Copyright (c) bloodmc
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.griefdefender.permission;
import com.google.common.collect.ImmutableMap;
import com.google.common.reflect.TypeToken;
import com.griefdefender.GDPlayerData;
import com.griefdefender.GriefDefenderPlugin;
import com.griefdefender.api.GriefDefender;
import com.griefdefender.api.Subject;
import com.griefdefender.api.Tristate;
import com.griefdefender.api.claim.Claim;
import com.griefdefender.api.claim.ClaimContexts;
import com.griefdefender.api.claim.ClaimType;
import com.griefdefender.api.claim.TrustType;
import com.griefdefender.api.permission.Context;
import com.griefdefender.api.permission.ContextKeys;
import com.griefdefender.api.permission.PermissionManager;
import com.griefdefender.api.permission.PermissionResult;
import com.griefdefender.api.permission.ResultTypes;
import com.griefdefender.api.permission.flag.Flag;
import com.griefdefender.api.permission.flag.FlagDefinition;
import com.griefdefender.api.permission.flag.Flags;
import com.griefdefender.api.permission.option.Option;
import com.griefdefender.api.permission.option.Options;
import com.griefdefender.api.permission.option.type.CreateModeType;
import com.griefdefender.api.permission.option.type.CreateModeTypes;
import com.griefdefender.api.permission.option.type.GameModeType;
import com.griefdefender.api.permission.option.type.GameModeTypes;
import com.griefdefender.api.permission.option.type.WeatherType;
import com.griefdefender.api.permission.option.type.WeatherTypes;
import com.griefdefender.cache.EventResultCache;
import com.griefdefender.cache.MessageCache;
import com.griefdefender.cache.PermissionHolderCache;
import com.griefdefender.claim.GDClaim;
import com.griefdefender.claim.GDClaimManager;
import com.griefdefender.command.CommandHelper;
import com.griefdefender.configuration.MessageStorage;
import com.griefdefender.configuration.category.BanCategory;
import com.griefdefender.event.GDCauseStackManager;
import com.griefdefender.event.GDFlagPermissionEvent;
import com.griefdefender.internal.registry.BlockTypeRegistryModule;
import com.griefdefender.internal.registry.EntityTypeRegistryModule;
import com.griefdefender.internal.registry.GDEntityType;
import com.griefdefender.internal.registry.GDTileType;
import com.griefdefender.internal.registry.ItemTypeRegistryModule;
import com.griefdefender.internal.registry.TileEntityTypeRegistryModule;
import com.griefdefender.internal.tracking.chunk.GDChunk;
import com.griefdefender.internal.util.NMSUtil;
import com.griefdefender.permission.option.GDOptions;
import com.griefdefender.provider.PermissionProvider.PermissionDataType;
import com.griefdefender.registry.FlagRegistryModule;
import com.griefdefender.util.EconomyUtil;
import com.griefdefender.util.PermissionUtil;
import com.griefdefender.util.PlayerUtil;
import net.kyori.text.Component;
import net.kyori.text.TextComponent;
import net.kyori.text.adapter.bukkit.TextAdapter;
import net.kyori.text.format.TextColor;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.Event;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerBucketEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GDPermissionManager implements PermissionManager {
private static final Pattern BLOCKSTATE_PATTERN = Pattern.compile("(?:\\w+=\\w+,)*\\w+=\\w+", Pattern.MULTILINE);
private static GDPermissionManager instance;
public boolean blacklistCheck = false;
private Event currentEvent;
private Location eventLocation;
private GDPermissionHolder eventSubject;
private GDPlayerData eventPlayerData;
private String eventSourceId = "none";
private String eventTargetId = "none";
private Set<Context> eventContexts = new HashSet<>();
private Component eventMessage;
private static final Pattern PATTERN_META = Pattern.compile("\\.[\\d+]*$");
private enum BanType {
BLOCK,
ENTITY,
ITEM
}
public GDPermissionHolder getDefaultHolder() {
return GriefDefenderPlugin.DEFAULT_HOLDER;
}
@Override
public Tristate getActiveFlagPermissionValue(Claim claim, Subject subject, Flag flag, Object source, Object target, Set<Context> contexts, TrustType type, boolean checkOverride) {
return getFinalPermission(null, null, contexts, claim, flag, source, target, (GDPermissionHolder) subject, type, checkOverride);
}
public Tristate getFinalPermission(Event event, Location location, Claim claim, Flag flag, Object source, Object target, GDPermissionHolder permissionHolder) {
return getFinalPermission(event, location, claim, flag, source, target, permissionHolder, null, false);
}
public Tristate getFinalPermission(Event event, Location location, Claim claim, Flag flag, Object source, Object target, Player player) {
final GDPermissionHolder permissionHolder = PermissionHolderCache.getInstance().getOrCreateUser(player);
return getFinalPermission(event, location, claim, flag, source, target, permissionHolder, null, false);
}
public Tristate getFinalPermission(Event event, Location location, Claim claim, Flag flag, Object source, Object target, Player player, boolean checkOverride) {
final GDPermissionHolder permissionHolder = PermissionHolderCache.getInstance().getOrCreateUser(player);
return getFinalPermission(event, location, claim, flag, source, target, permissionHolder, null, checkOverride);
}
public Tristate getFinalPermission(Event event, Location location, Claim claim, Flag flag, Object source, Object target, GDPermissionHolder permissionHolder, boolean checkOverride) {
return getFinalPermission(event, location, claim, flag, source, target, permissionHolder, null, checkOverride);
}
public Tristate getFinalPermission(Event event, Location location, Claim claim, Flag flag, Object source, Object target, Player player, TrustType type, boolean checkOverride) {
final GDPermissionHolder permissionHolder = PermissionHolderCache.getInstance().getOrCreateUser(player);
return getFinalPermission(event, location, claim, flag, source, target, permissionHolder, type, checkOverride);
}
public Tristate getFinalPermission(Event event, Location location, Claim claim, Flag flag, Object source, Object target, GDPermissionHolder permissionHolder, TrustType type, boolean checkOverride) {
return getFinalPermission(event, location, new HashSet<>(), claim, flag, source, target, permissionHolder, type, checkOverride);
}
public Tristate getFinalPermission(Event event, Location location, Set<Context> contexts, Claim claim, Flag flag, Object source, Object target, GDPermissionHolder permissionHolder, TrustType type, boolean checkOverride) {
if (claim == null) {
return Tristate.TRUE;
}
GDPlayerData playerData = null;
final GDPermissionUser user = permissionHolder instanceof GDPermissionUser ? (GDPermissionUser) permissionHolder : null;
this.eventSubject = user;
this.eventMessage = null;
this.eventSourceId = "none";
this.eventTargetId = "none";
if (permissionHolder != null) {
if (user != null) {
playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(claim.getWorldUniqueId(), user.getUniqueId());
}
}
this.currentEvent = event;
this.eventLocation = location;
// refresh contexts
this.eventContexts = new HashSet<>();
if (source instanceof Player && flag != Flags.COLLIDE_BLOCK && flag != Flags.COLLIDE_ENTITY) {
this.addPlayerContexts((Player) source, contexts, flag);
}
if (!(source instanceof Player) && user != null && user.getOnlinePlayer() != null) {
boolean addPlayerContext = false;
if (!(target instanceof Player)) {
addPlayerContext = true;
} else if (!user.getUniqueId().equals(((Player) target).getUniqueId())) {
addPlayerContext = true;
}
if (addPlayerContext) {
// add source player context
// this allows users to block all pvp actions when direct source isn't a player
contexts.add(new Context(ContextKeys.SOURCE, this.getPermissionIdentifier(user.getOnlinePlayer())));
}
}
if (source instanceof Block && event instanceof EntityChangeBlockEvent && flag == Flags.BLOCK_MODIFY) {
final EntityChangeBlockEvent entityChangeBlockEvent = (EntityChangeBlockEvent) event;
contexts.add(new Context(ContextKeys.SOURCE, this.getPermissionIdentifier(entityChangeBlockEvent.getEntity())));
}
final Set<Context> sourceContexts = this.getPermissionContexts((GDClaim) claim, source, true);
if (sourceContexts == null) {
return Tristate.FALSE;
}
final Set<Context> targetContexts = this.getPermissionContexts((GDClaim) claim, target, false);
if (targetContexts == null) {
return Tristate.FALSE;
}
contexts.addAll(sourceContexts);
contexts.addAll(targetContexts);
contexts.add(((GDClaim) claim).getWorldContext());
this.eventContexts = contexts;
this.eventPlayerData = playerData;
final String targetPermission = flag.getPermission();
if (flag == Flags.ENTITY_SPAWN && GDOptions.SPAWN_LIMIT && target instanceof LivingEntity) {
// Check spawn limit
final GDClaim gdClaim = (GDClaim) claim;
final int spawnLimit = gdClaim.getSpawnLimit(contexts);
if (spawnLimit > -1) {
final Entity entity = (Entity) target;
final int currentEntityCount = gdClaim.countEntities(entity);
if (currentEntityCount >= spawnLimit) {
if (user != null && user.getOnlinePlayer() != null && (source == SpawnReason.ENDER_PEARL || source == SpawnReason.SPAWNER_EGG || source == SpawnReason.SPAWNER)) {
final String name = entity.getType().getName() == null ? entity.getType().name().toLowerCase() : entity.getType().getName();
final GDEntityType entityType = EntityTypeRegistryModule.getInstance().getById(name).orElse(null);
final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.OPTION_APPLY_SPAWN_LIMIT,
ImmutableMap.of(
"type", entityType.getId(),
"limit", spawnLimit));
GriefDefenderPlugin.sendMessage(user.getOnlinePlayer(), message);
}
return this.processResult(claim, flag.getPermission(), "spawn-limit", Tristate.FALSE, this.eventSubject);
}
}
}
if (user != null && playerData != null && !playerData.debugClaimPermissions && playerData.canIgnoreClaim(claim)) {
return processResult(claim, targetPermission, "ignore", Tristate.TRUE, user);
}
if (checkOverride) {
// First check for claim flag overrides
final Tristate override = getFlagOverride(claim, permissionHolder == null ? GriefDefenderPlugin.DEFAULT_HOLDER : permissionHolder, playerData, targetPermission);
if (override != Tristate.UNDEFINED) {
return processResult(claim, targetPermission, type == null ? "none" : type.getName().toLowerCase(), override, user);
}
}
if (playerData != null && user != null) {
if (playerData.debugClaimPermissions) {
if (type != null && claim.isUserTrusted(user.getUniqueId(), type)) {
return processResult(claim, targetPermission, type.getName().toLowerCase(), Tristate.TRUE, user);
}
return getClaimFlagPermission(claim, targetPermission);
}
// Check for ignoreclaims after override and debug checks
if (playerData.canIgnoreClaim(claim)) {
return processResult(claim, targetPermission, "ignore", Tristate.TRUE, user);
}
}
if (user != null) {
// check if rented
if (claim.getEconomyData() != null && claim.getEconomyData().isRented() &&
flag != Flags.COMMAND_EXECUTE &&
flag != Flags.COMMAND_EXECUTE_PVP &&
flag != Flags.ENTER_CLAIM &&
flag != Flags.EXIT_CLAIM &&
flag != Flags.ENTITY_TELEPORT_FROM &&
flag != Flags.ENTITY_TELEPORT_TO &&
flag != Flags.INTERACT_INVENTORY_CLICK) {
if (claim.getOwnerUniqueId() != null && user != null && claim.getOwnerUniqueId().equals(user.getUniqueId())) {
return processResult(claim, targetPermission, "rent-owner-deny", Tristate.FALSE, user);
}
if (EconomyUtil.getInstance().isRenter(claim, user) && (targetPermission.contains("interact") || targetPermission.contains("block"))) {
if ((targetPermission.contains("interact") || targetPermission.contains("block-place"))) {
final boolean hasInventory = NMSUtil.getInstance().isTileInventory(location) || location.getBlock().getType() == Material.ENDER_CHEST;
if (!hasInventory || flag == Flags.BLOCK_PLACE) {
return processResult(claim, targetPermission, "renter-interact", Tristate.TRUE, user);
}
// check entity interactions
if (targetPermission.contains("interact-entity") && target instanceof LivingEntity) {
// Allow interaction with all living entities
return processResult(claim, targetPermission, "renter-interact", Tristate.TRUE, user);
}
}
// Allow renters to break/change their own blocks
final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(location.getWorld().getUID());
final GDChunk gdChunk = claimWorldManager.getChunk(location.getBlock().getChunk());
final GDPermissionUser owner = gdChunk.getBlockOwner(location);
if (owner != null && owner.getUniqueId().equals(user.getUniqueId())) {
// allow
return processResult(claim, targetPermission, "renter-owned", Tristate.TRUE, user);
}
}
}
if (type != null) {
if (((GDClaim) claim).isUserTrusted(user, type)) {
// check persisted flags
if (!claim.isWilderness()) {
if ((claim.isAdminClaim() && !user.getInternalPlayerData().canManageAdminClaims) || !user.getUniqueId().equals(claim.getOwnerUniqueId())) {
final Tristate result = getUserPermission(user, claim, targetPermission, PermissionDataType.USER_PERSISTENT);
if (result != Tristate.UNDEFINED) {
return processResult(claim, targetPermission, result, user);
}
}
}
return processResult(claim, targetPermission, type.getName().toLowerCase(), Tristate.TRUE, permissionHolder);
}
}
return getUserPermission(user, claim, targetPermission, PermissionDataType.PERSISTENT);
}
return getClaimFlagPermission(claim, targetPermission);
}
private Tristate getUserPermission(GDPermissionHolder holder, Claim claim, String permission, PermissionDataType dataType) {
final List<Claim> inheritParents = claim.getInheritedParents();
final Set<Context> contexts = new HashSet<>();
contexts.addAll(this.eventContexts);
for (Claim parentClaim : inheritParents) {
GDClaim parent = (GDClaim) parentClaim;
// check parent context
contexts.add(parent.getContext());
Tristate value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, holder, permission, contexts, dataType);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, holder);
}
contexts.remove(parent.getContext());
}
// Check claim context
contexts.add(claim.getContext());
Tristate value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, holder, permission, contexts, dataType);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, holder);
}
if (dataType == PermissionDataType.USER_PERSISTENT) {
// don't log, just return result
return value;
}
// Group MUST inherit default group or above will return undefined if no permission set on non-default group/user.
contexts.remove(claim.getContext());
return getFlagDefaultPermission(claim, permission, contexts);
}
private Tristate getClaimFlagPermission(Claim claim, String permission) {
return this.getClaimFlagPermission(claim, permission, new HashSet<>(), null);
}
private Tristate getClaimFlagPermission(Claim claim, String permission, Set<Context> contexts, List<Claim> inheritParents) {
if (contexts.isEmpty()) {
if (inheritParents == null) {
inheritParents = claim.getInheritedParents();
}
contexts.addAll(this.eventContexts);
for (Claim parentClaim : inheritParents) {
GDClaim parent = (GDClaim) parentClaim;
// check parent context
contexts.add(parent.getContext());
Tristate value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, GriefDefenderPlugin.DEFAULT_HOLDER, permission, contexts, PermissionDataType.PERSISTENT);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, GriefDefenderPlugin.DEFAULT_HOLDER);
}
contexts.remove(parent.getContext());
}
contexts.add(claim.getContext());
}
Tristate value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, GriefDefenderPlugin.DEFAULT_HOLDER, permission, contexts, PermissionDataType.PERSISTENT);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, GriefDefenderPlugin.DEFAULT_HOLDER);
}
return getFlagDefaultPermission(claim, permission, contexts);
}
// Only uses world and claim type contexts
private Tristate getFlagDefaultPermission(Claim claim, String permission, Set<Context> contexts) {
contexts.add(claim.getDefaultTypeContext());
Tristate value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, GriefDefenderPlugin.DEFAULT_HOLDER, permission, contexts, PermissionDataType.PERSISTENT);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, GriefDefenderPlugin.DEFAULT_HOLDER);
}
contexts.remove(claim.getDefaultTypeContext());
if (!claim.isWilderness()) {
contexts.add(ClaimContexts.GLOBAL_DEFAULT_CONTEXT);
contexts.add(ClaimContexts.USER_DEFAULT_CONTEXT);
value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, GriefDefenderPlugin.DEFAULT_HOLDER, permission, contexts, PermissionDataType.PERSISTENT);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, GriefDefenderPlugin.DEFAULT_HOLDER);
}
contexts.remove(ClaimContexts.USER_DEFAULT_CONTEXT);
} else {
contexts.add(ClaimContexts.GLOBAL_DEFAULT_CONTEXT);
value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, GriefDefenderPlugin.DEFAULT_HOLDER, permission, contexts, PermissionDataType.PERSISTENT);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, GriefDefenderPlugin.DEFAULT_HOLDER);
}
}
contexts.remove(ClaimContexts.GLOBAL_DEFAULT_CONTEXT);
contexts.add(ClaimContexts.USER_DEFAULT_CONTEXT);
contexts.add(claim.getDefaultTypeContext());
value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, GriefDefenderPlugin.GD_DEFAULT_HOLDER, permission, contexts, PermissionDataType.TRANSIENT);
if (value != Tristate.UNDEFINED) {
return processResult(claim, permission, value, GriefDefenderPlugin.GD_DEFAULT_HOLDER);
}
return processResult(claim, permission, Tristate.UNDEFINED, GriefDefenderPlugin.DEFAULT_HOLDER);
}
private Tristate getFlagOverride(Claim claim, GDPermissionHolder permissionHolder, GDPlayerData playerData, String flagPermission) {
if (!((GDClaim) claim).getInternalClaimData().allowFlagOverrides()) {
return Tristate.UNDEFINED;
}
Player player = null;
Set<Context> contexts = new HashSet<>();
if (claim.isAdminClaim()) {
contexts.add(ClaimContexts.ADMIN_OVERRIDE_CONTEXT);
} else if (claim.isTown()) {
contexts.add(ClaimContexts.TOWN_OVERRIDE_CONTEXT);
} else if (claim.isBasicClaim()) {
contexts.add(ClaimContexts.BASIC_OVERRIDE_CONTEXT);
} else if (claim.isWilderness()) {
contexts.add(ClaimContexts.WILDERNESS_OVERRIDE_CONTEXT);
player = permissionHolder instanceof GDPermissionUser ? ((GDPermissionUser) permissionHolder).getOnlinePlayer() : null;
}
if (!claim.isWilderness()) {
contexts.add(ClaimContexts.USER_OVERRIDE_CONTEXT);
}
contexts.add(((GDClaim) claim).getWorldContext());
contexts.add(ClaimContexts.GLOBAL_OVERRIDE_CONTEXT);
contexts.addAll(this.eventContexts);
Tristate value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, permissionHolder, flagPermission, contexts, PermissionDataType.PERSISTENT);
if (value == Tristate.UNDEFINED) {
// check claim owner parent override
/*final List<Claim> inheritParents = claim.getInheritedParents();
contexts = new HashSet<>();
contexts.add(((GDClaim) claim).getWorldContext());
contexts.addAll(this.eventContexts);
for (Claim parentClaim : inheritParents) {
GDClaim parent = (GDClaim) parentClaim;
// check parent override claim context
contexts.add(parent.getOverrideClaimContext());
value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, permissionHolder, flagPermission, contexts);
if (value != Tristate.UNDEFINED) {
if (value == Tristate.FALSE) {
this.eventMessage = MessageCache.getInstance().PERMISSION_OVERRIDE_DENY;
}
return processResult(claim, flagPermission, value, permissionHolder);
}
contexts.remove(parent.getOverrideClaimContext());
}*/
// check claim owner override
contexts = new HashSet<>();
contexts.add(((GDClaim) claim).getWorldContext());
contexts.addAll(this.eventContexts);
contexts.add(claim.getOverrideClaimContext());
value = PermissionUtil.getInstance().getPermissionValue((GDClaim) claim, permissionHolder, flagPermission, contexts, PermissionDataType.PERSISTENT);
}
if (value != Tristate.UNDEFINED) {
if (value == Tristate.FALSE) {
this.eventMessage = MessageCache.getInstance().PERMISSION_OVERRIDE_DENY;
}
return processResult(claim, flagPermission, value, permissionHolder);
}
return Tristate.UNDEFINED;
}
public Tristate processResult(Claim claim, String permission, Tristate permissionValue, GDPermissionHolder permissionHolder) {
return processResult(claim, permission, null, permissionValue, permissionHolder);
}
public Tristate processResult(Claim claim, String permission, String trust, Tristate permissionValue, GDPermissionHolder permissionHolder) {
if (GriefDefenderPlugin.debugActive && this.currentEvent != null) {
// Use the event subject always if available
// This prevents debug showing 'default' for users
if (eventSubject != null) {
permissionHolder = eventSubject;
} else if (permissionHolder == null) {
final Object source = GDCauseStackManager.getInstance().getCurrentCause().root();
if (source instanceof GDPermissionUser) {
permissionHolder = (GDPermissionUser) source;
} else {
permissionHolder = GriefDefenderPlugin.DEFAULT_HOLDER;
}
}
if (this.currentEvent instanceof BlockPhysicsEvent) {
if (((GDClaim) claim).getWorld().getTime() % 100 != 0L) {
return permissionValue;
}
}
GriefDefenderPlugin.addEventLogEntry(this.currentEvent, claim, this.eventLocation, this.eventSourceId, this.eventTargetId, this.eventSubject == null ? permissionHolder : this.eventSubject, permission, trust, permissionValue, this.eventContexts);
}
if (eventPlayerData != null && eventPlayerData.eventResultCache != null) {
final Flag flag = FlagRegistryModule.getInstance().getById(permission).orElse(null);
if (flag != null) {
eventPlayerData.eventResultCache = new EventResultCache((GDClaim) claim, flag.getName().toLowerCase(), permissionValue);
}
}
return permissionValue;
}
public void processEventLog(Event event, Location location, Claim claim, String permission, Object source, Object target, GDPermissionHolder user, String trust, Tristate value) {
final String sourceId = this.getPermissionIdentifier(source, true);
final String targetId = this.getPermissionIdentifier(target);
final Set<Context> sourceContexts = this.getPermissionContexts((GDClaim) claim, source, true);
if (sourceContexts == null) {
return;
}
final Set<Context> targetContexts = this.getPermissionContexts((GDClaim) claim, target, false);
if (targetContexts == null) {
return;
}
final Set<Context> contexts = new HashSet<>();
if (!(source instanceof Player) && target instanceof Player && user instanceof GDPermissionUser && ((GDPermissionUser) user).getOnlinePlayer() != null && !((GDPermissionUser) user).getUniqueId().equals(((Player) target).getUniqueId())) {
// add source player context
// this allows users to block all pvp actions when direct source isn't a player
contexts.add(new Context(ContextKeys.SOURCE, this.getPermissionIdentifier(((GDPermissionUser) user).getOnlinePlayer())));
}
contexts.addAll(sourceContexts);
contexts.addAll(targetContexts);
contexts.add(((GDClaim) claim).getWorldContext());
if (GriefDefenderPlugin.debugActive) {
if (user == null) {
final Object root = GDCauseStackManager.getInstance().getCurrentCause().root();
if (source instanceof GDPermissionUser) {
user = (GDPermissionUser) root;
} else {
user = GriefDefenderPlugin.DEFAULT_HOLDER;
}
}
GriefDefenderPlugin.addEventLogEntry(event, claim, location, sourceId, targetId, user, permission, trust.toLowerCase(), value, contexts);
}
}
public String getPermissionIdentifier(Object obj) {
return getPermissionIdentifier(obj, false);
}
public String getPermissionIdentifier(Object obj, boolean isSource) {
if (obj != null) {
if (obj instanceof Entity) {
Entity targetEntity = (Entity) obj;
if (targetEntity instanceof Item) {
return getPermissionIdentifier(((Item) targetEntity).getItemStack(), isSource);
}
if (targetEntity.getType() == null) {
// Plugin sending fake player and violating API contract so just ignore...
return "unknown";
}
final String name = targetEntity.getType().getName() == null ? targetEntity.getType().name().toLowerCase() : targetEntity.getType().getName();
final GDEntityType type = EntityTypeRegistryModule.getInstance().getByBukkitType(targetEntity);
if (type == null) {
// Should never happen
return name;
}
String id = type.getId();
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof Block) {
final Block block = (Block) obj;
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String customItemId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeBlockId(block);
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTarget(customItemId, isSource);
}
}
final String id = BlockTypeRegistryModule.getInstance().getNMSKey(block);
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof BlockState) {
final BlockState blockstate = (BlockState) obj;
if (blockstate.getBlock().getType() != blockstate.getType()) {
return populateEventSourceTarget(blockstate.getType().name().toLowerCase(), isSource);
}
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String customItemId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeBlockId(blockstate.getBlock());
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTarget(customItemId, isSource);
}
}
final String id = BlockTypeRegistryModule.getInstance().getNMSKey(blockstate);
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof Material) {
final String id = ((Material) obj).name().toLowerCase();
return populateEventSourceTarget(id, isSource);
} /*else if (obj instanceof TileEntity) {
TileEntity tileEntity = (TileEntity) obj;
final String id = tileEntity.getMinecraftKeyString();
return populateEventSourceTarget(id, isSource);
}*/ else if (obj instanceof Inventory) {
final String id = ((Inventory) obj).getType().name().toLowerCase();
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof InventoryType) {
final String id = ((InventoryType) obj).name().toLowerCase();
populateEventSourceTarget(id, isSource);
return id;
} else if (obj instanceof Item) {
} else if (obj instanceof ItemStack) {
final ItemStack itemstack = (ItemStack) obj;
if (GriefDefenderPlugin.getInstance().isCustomItemsInstalled) {
final String customItemId = NMSUtil.getInstance().getItemStackNBTString(itemstack, "com.jojodmo.customitems.itemID");
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTarget("customitems:" + customItemId, isSource);
}
}
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String customItemId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeItemId(itemstack);
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTarget(customItemId, isSource);
}
}
String id = ItemTypeRegistryModule.getInstance().getNMSKey(itemstack);
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof DamageCause) {
final DamageCause damageCause = (DamageCause) obj;
String id = damageCause.name().toLowerCase();
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof TeleportCause) {
final TeleportCause teleportCause = (TeleportCause) obj;
String id = teleportCause.name().toLowerCase();
return populateEventSourceTarget(id, isSource);
} else if (obj instanceof SpawnReason) {
return populateEventSourceTarget("spawnreason:" + ((SpawnReason) obj).name().toLowerCase(), isSource);
} else if (obj instanceof CreatureSpawner) {
final CreatureSpawner spawner = (CreatureSpawner) obj;
return this.getPermissionIdentifier(spawner.getBlock());
} else if (obj instanceof String) {
final String id = obj.toString().toLowerCase();
return populateEventSourceTarget(id, isSource);
}
}
populateEventSourceTarget("none", isSource);
return "";
}
public Set<Context> getPermissionContexts(GDClaim claim, Object obj, boolean isSource) {
final Set<Context> contexts = new HashSet<>();
if (obj == null) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_ANY);
} else {
contexts.add(ContextGroups.TARGET_ANY);
}
return contexts;
}
if (obj instanceof Entity) {
Entity targetEntity = (Entity) obj;
if (targetEntity instanceof Item) {
return getPermissionContexts(claim, ((Item) targetEntity).getItemStack(), isSource);
}
if (targetEntity.getType() == null) {
// Plugin sending fake player and violating API contract so just ignore...
return contexts;
}
final GDEntityType type = EntityTypeRegistryModule.getInstance().getByBukkitType(targetEntity);
String id = type.getId();
if (!(targetEntity instanceof Player)) {
addCustomEntityTypeContexts(targetEntity, id, contexts, type, isSource);
} else {
final Player player = (Player) targetEntity;
if (PlayerUtil.getInstance().isFakePlayer(player)) {
final String modId = EntityTypeRegistryModule.getInstance().findModIdFromBukkit(targetEntity);
id = modId + ":fakeplayer_" + EntityTypeRegistryModule.getInstance().getFriendlyName(targetEntity.getName());
}
}
if (this.isObjectIdBanned(claim, id, BanType.ENTITY)) {
return null;
}
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof Block) {
final Block block = (Block) obj;
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String customItemId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeBlockId(block, contexts);
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTargetContext(contexts, customItemId, isSource);
}
}
String id = BlockTypeRegistryModule.getInstance().getNMSKey(block);
if (GriefDefenderPlugin.getGlobalConfig().getConfig().mod.convertBlockId(id)) {
final GDTileType tileType = TileEntityTypeRegistryModule.getInstance().getByBlock(block.getLocation());
if (tileType != null) {
id = tileType.getId();
}
}
this.addBlockContexts(contexts, block, isSource);
if (this.isObjectIdBanned(claim, id, BanType.BLOCK)) {
return null;
}
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof BlockState) {
final BlockState blockstate = (BlockState) obj;
final Block block = blockstate.getBlock();
if (block.getType() != blockstate.getType()) {
return populateEventSourceTargetContext(contexts, blockstate.getType().name().toLowerCase(), isSource);
}
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String customItemId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeBlockId(block, contexts);
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTargetContext(contexts, customItemId, isSource);
}
}
String id = BlockTypeRegistryModule.getInstance().getNMSKey(blockstate);
if (GriefDefenderPlugin.getGlobalConfig().getConfig().mod.convertBlockId(id)) {
final GDTileType tileType = TileEntityTypeRegistryModule.getInstance().getByBlock(block.getLocation());
if (tileType != null) {
id = tileType.getId();
}
}
this.addBlockContexts(contexts, block, isSource);
if (this.isObjectIdBanned(claim, id, BanType.BLOCK)) {
return null;
}
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof Material) {
final String id = BlockTypeRegistryModule.getInstance().getNMSKey((Material) obj);
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof Inventory) {
final String id = ((Inventory) obj).getType().name().toLowerCase();
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof InventoryType) {
final String id = ((InventoryType) obj).name().toLowerCase();
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof ItemStack) {
final ItemStack itemstack = (ItemStack) obj;
if (GriefDefenderPlugin.getInstance().isCustomItemsInstalled) {
final String customItemId = NMSUtil.getInstance().getItemStackNBTString(itemstack, "com.jojodmo.customitems.itemID");
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTargetContext(contexts, "customitems:" + customItemId, isSource);
}
}
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String customItemId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeItemId(itemstack, contexts);
if (customItemId != null && !customItemId.isEmpty()) {
return populateEventSourceTargetContext(contexts, customItemId, isSource);
}
}
if (NMSUtil.getInstance().isItemFood(itemstack)) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_FOOD);
} else {
contexts.add(ContextGroups.TARGET_FOOD);
}
}
if (NMSUtil.getInstance().isItemHanging(itemstack)) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_HANGING);
} else {
contexts.add(ContextGroups.TARGET_HANGING);
}
}
if (NMSUtil.getInstance().isItemBoat(itemstack) || NMSUtil.getInstance().isItemMinecart(itemstack)) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_VEHICLE);
} else {
contexts.add(ContextGroups.TARGET_VEHICLE);
}
}
if (NMSUtil.getInstance().isItemPotion(itemstack)) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_POTION);
} else {
contexts.add(ContextGroups.TARGET_POTION);
}
if (GriefDefenderPlugin.getGlobalConfig().getConfig().context.potionEffects) {
final List<String> effects = NMSUtil.getInstance().getPotionEffects(itemstack);
for (String effect : effects) {
contexts.add(new Context("potion_effect", effect.toLowerCase()));
}
if (!effects.isEmpty()) {
contexts.add(new Context("potion_effect", ContextGroupKeys.ANY));
}
}
}
if (GriefDefenderPlugin.getGlobalConfig().getConfig().context.enchantments) {
// add enchantment contexts
final List<String> enchantments = NMSUtil.getInstance().getEnchantments(itemstack);
for (String enchantment : enchantments) {
final String[] parts = enchantment.split(",");
for (String part : parts) {
if (part.startsWith("id:")) {
part = part.replace("id:", "");
part = part.replace("\"", "");
part = part.substring(0, part.length() - 1);
if (Character.isDigit(part.charAt(0))) {
part = part.replaceAll("[^0-9]", "");
part = NMSUtil.getInstance().getEnchantmentId(Integer.valueOf(part));
}
contexts.add(new Context("enchant", part));
}
}
enchantment = enchantment.replace("\"", "");
enchantment = enchantment.substring(1, enchantment.length() - 1);
contexts.add(new Context("enchant_data", enchantment));
}
if (!enchantments.isEmpty()) {
contexts.add(new Context("enchant", ContextGroupKeys.ANY));
}
}
String id = ItemTypeRegistryModule.getInstance().getNMSKey(itemstack);
if (GriefDefenderPlugin.getGlobalConfig().getConfig().mod.convertBlockId(id)) {
final String itemName = NMSUtil.getInstance().getItemName(itemstack, id);
if (itemName != null) {
if (!itemName.contains(":")) {
final int index = id.indexOf(":");
final String modId = id.substring(0, index);
id = modId + ":" + itemName;
} else {
id = itemName;
}
}
}
if (this.isObjectIdBanned(claim, id, BanType.ITEM)) {
return null;
}
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof DamageCause) {
final DamageCause damageCause = (DamageCause) obj;
String id = damageCause.name().toLowerCase();
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof TeleportCause) {
final TeleportCause teleportCause = (TeleportCause) obj;
String id = teleportCause.name().toLowerCase();
return populateEventSourceTargetContext(contexts, id, isSource);
} else if (obj instanceof SpawnReason) {
return populateEventSourceTargetContext(contexts, "spawnreason:" + ((SpawnReason) obj).name().toLowerCase(), isSource);
} else if (obj instanceof CreatureSpawner) {
final CreatureSpawner spawner = (CreatureSpawner) obj;
return this.getPermissionContexts(claim, spawner.getBlock(), isSource);
} else if (obj instanceof String) {
final String id = obj.toString().toLowerCase();
return populateEventSourceTargetContext(contexts, id, isSource);
}
return contexts;
}
public boolean isObjectIdBanned(GDClaim claim, String id, BanType type) {
if (id.equalsIgnoreCase("player")) {
return false;
}
GDPermissionUser user = null;
if (this.eventSubject != null && this.eventSubject instanceof GDPermissionUser) {
user = (GDPermissionUser) this.eventSubject;
if (user.getInternalPlayerData() != null && user.getInternalPlayerData().canIgnoreClaim(claim)) {
return false;
}
}
final String permission = StringUtils.replace(id, ":", ".");
Component banReason = null;
final BanCategory banCategory = GriefDefenderPlugin.getGlobalConfig().getConfig().bans;
if (type == BanType.BLOCK) {
for (Entry<String, Component> banId : banCategory.getBlockMap().entrySet()) {
if (FilenameUtils.wildcardMatch(id, banId.getKey())) {
banReason = GriefDefenderPlugin.getGlobalConfig().getConfig().bans.getBlockBanReason(banId.getKey());
if (banReason != null && banReason.equals(TextComponent.empty())) {
banReason = MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.PERMISSION_BAN_BLOCK,
ImmutableMap.of("id", TextComponent.of(id, TextColor.GOLD)));
}
break;
}
}
} else if (type == BanType.ITEM) {
for (Entry<String, Component> banId : banCategory.getItemMap().entrySet()) {
if (FilenameUtils.wildcardMatch(id, banId.getKey())) {
banReason = GriefDefenderPlugin.getGlobalConfig().getConfig().bans.getItemBanReason(banId.getKey());
if (banReason != null && banReason.equals(TextComponent.empty())) {
banReason = MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.PERMISSION_BAN_ITEM,
ImmutableMap.of("id", TextComponent.of(id, TextColor.GOLD)));
}
}
}
} else if (type == BanType.ENTITY) {
for (Entry<String, Component> banId : banCategory.getEntityMap().entrySet()) {
if (FilenameUtils.wildcardMatch(id, banId.getKey())) {
banReason = GriefDefenderPlugin.getGlobalConfig().getConfig().bans.getEntityBanReason(banId.getKey());
if (banReason != null && banReason.equals(TextComponent.empty())) {
banReason = MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.PERMISSION_BAN_ENTITY,
ImmutableMap.of("id", TextComponent.of(id, TextColor.GOLD)));
}
}
}
}
if (banReason != null && user != null) {
final Player player = user.getOnlinePlayer();
if (player != null) {
if (banReason.equals(TextComponent.empty())) {
banReason = MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.PERMISSION_BAN_BLOCK,
ImmutableMap.of("id", id));
}
TextAdapter.sendComponent(player, banReason);
this.processResult(claim, permission, "banned", Tristate.FALSE, user);
return true;
}
}
if (banReason != null) {
// Detected ban
this.processResult(claim, permission, "banned", Tristate.FALSE, this.eventSubject);
return true;
}
return false;
}
public void addCustomEntityTypeContexts(Entity targetEntity, String id, Set<Context> contexts, GDEntityType type, boolean isSource) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_ANY);
contexts.add(new Context(ContextKeys.SOURCE, "#" + type.getModId().toLowerCase() + ":any"));
} else {
contexts.add(ContextGroups.TARGET_ANY);
contexts.add(new Context(ContextKeys.TARGET, "#" + type.getModId().toLowerCase() + ":any"));
}
// check vehicle
if (targetEntity instanceof Vehicle) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_VEHICLE);
} else {
contexts.add(ContextGroups.TARGET_VEHICLE);
}
}
// pixelmon
if (targetEntity.getType() != null && targetEntity.getType().name().equalsIgnoreCase("pixelmon_pixelmon") || targetEntity.getType().name().equalsIgnoreCase("pixelmon")) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_PIXELMON);
} else {
contexts.add(ContextGroups.TARGET_PIXELMON);
}
}
// potion
if (targetEntity instanceof ThrownPotion && GriefDefenderPlugin.getGlobalConfig().getConfig().context.potionEffects) {
final ThrownPotion potion = (ThrownPotion) targetEntity;
for (PotionEffect effect : potion.getEffects()) {
contexts.add(new Context("potion_effect", effect.getType().getName().toLowerCase()));
}
if (!potion.getEffects().isEmpty()) {
contexts.add(new Context("potion_effect", ContextGroupKeys.ANY));
}
}
final String creatureType = type.getEnumCreatureTypeId();
if (creatureType == null) {
return;
}
final String modId = type.getModId().toLowerCase();
if (creatureType.contains("animal")) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_ANIMAL);
contexts.add(new Context(ContextKeys.SOURCE, "#" + modId + ":animal"));
} else {
contexts.add(ContextGroups.TARGET_ANIMAL);
contexts.add(new Context(ContextKeys.TARGET, "#" + modId + ":animal"));
}
this.checkPetContext(targetEntity, modId, contexts, isSource);
} else if (creatureType.contains("aquatic")) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_AQUATIC);
contexts.add(new Context(ContextKeys.SOURCE, "#" + modId + ":aquatic"));
} else {
contexts.add(ContextGroups.TARGET_AQUATIC);
contexts.add(new Context(ContextKeys.TARGET, "#" + modId + ":aquatic"));
}
this.checkPetContext(targetEntity, modId, contexts, isSource);
} else if (creatureType.contains("monster")) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_MONSTER);
contexts.add(new Context(ContextKeys.SOURCE, "#" + modId + ":monster"));
} else {
contexts.add(ContextGroups.TARGET_MONSTER);
contexts.add(new Context(ContextKeys.TARGET, "#" + modId + ":monster"));
}
} else if (creatureType.contains("ambient")) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_AMBIENT);
contexts.add(new Context(ContextKeys.SOURCE, "#" + modId + ":ambient"));
} else {
contexts.add(ContextGroups.TARGET_AMBIENT);
contexts.add(new Context(ContextKeys.TARGET, "#" + modId + ":ambient"));
}
this.checkPetContext(targetEntity, modId, contexts, isSource);
} else {
if (isSource) {
contexts.add(ContextGroups.SOURCE_MISC);
contexts.add(new Context(ContextKeys.SOURCE, "#" + modId + ":misc"));
} else {
contexts.add(ContextGroups.TARGET_MISC);
contexts.add(new Context(ContextKeys.TARGET, "#" + modId + ":misc"));
}
}
}
private void checkPetContext(Entity targetEntity, String modId, Set<Context> contexts, boolean isSource) {
if (this.eventSubject != null && this.eventSubject instanceof GDPermissionUser) {
final GDPermissionUser user = (GDPermissionUser) this.eventSubject;
final UUID uuid = NMSUtil.getInstance().getTameableOwnerUUID(targetEntity);
if (uuid != null && uuid.equals(user.getUniqueId())) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_PET);
if (modId != null && !modId.isEmpty()) {
contexts.add(new Context(ContextKeys.SOURCE, "#" + modId + ":pet"));
}
} else {
contexts.add(ContextGroups.TARGET_PET);
if (modId != null && !modId.isEmpty()) {
contexts.add(new Context(ContextKeys.TARGET, "#" + modId + ":pet"));
}
}
}
}
}
private void addPlayerContexts(Player player, Set<Context> contexts, Flag flag) {
Context usedItemContext = null;
for (Context context : contexts) {
if (context.getKey().equals(ContextKeys.USED_ITEM)) {
usedItemContext = context;
break;
}
}
if(usedItemContext == null) {
// special case
if (this.currentEvent instanceof PlayerBucketEvent) {
final PlayerBucketEvent bucketEvent = (PlayerBucketEvent) this.currentEvent;
contexts.add(new Context(ContextKeys.USED_ITEM, "minecraft:" + bucketEvent.getBucket().name().toLowerCase()));
} else {
final ItemStack stack = NMSUtil.getInstance().getActiveItem(player, this.currentEvent);
if (stack != null && stack.getType() != Material.AIR) {
final String stackId = getPermissionIdentifier(stack);
contexts.add(new Context(ContextKeys.USED_ITEM, stackId));
if (stack.getItemMeta() != null && stack.getItemMeta().getDisplayName() != null) {
String itemName = stack.getItemMeta().getDisplayName().replaceAll("[^A-Za-z0-9]", "").toLowerCase();
if (GriefDefenderPlugin.getInstance().getSlimefunProvider() != null) {
final String slimefunId = GriefDefenderPlugin.getInstance().getSlimefunProvider().getSlimeItemDisplayName(stack);
if (slimefunId != null && !slimefunId.isEmpty()) {
itemName = slimefunId;
}
}
if (itemName != null && !itemName.isEmpty()) {
if (!itemName.contains(":")) {
itemName = "minecraft:" + itemName;
}
contexts.add(new Context("item_name", itemName));
}
}
// populate item tag
if (GriefDefenderPlugin.getInstance().getTagProvider() != null) {
final Set<Context> tagContexts = GriefDefenderPlugin.getInstance().getTagProvider().getTagMap().get(stackId);
if (tagContexts != null) {
for (Context context : tagContexts) {
contexts.add(new Context(ContextKeys.USED_ITEM, "#" + context.getKey() + ":" + context.getValue()));
if (context.getKey().equalsIgnoreCase("minecraft")) {
contexts.add(new Context(ContextKeys.USED_ITEM, "#" + context.getValue()));
}
}
}
}
}
}
} else {
// populate item tag
if (GriefDefenderPlugin.getInstance().getTagProvider() != null) {
final Set<Context> tagContexts = GriefDefenderPlugin.getInstance().getTagProvider().getTagMap().get(usedItemContext.getValue());
if (tagContexts != null) {
for (Context context : tagContexts) {
contexts.add(new Context(ContextKeys.USED_ITEM, "#" + context.getKey() + ":" + context.getValue()));
if (context.getKey().equalsIgnoreCase("minecraft")) {
contexts.add(new Context(ContextKeys.USED_ITEM, "#" + context.getValue()));
}
}
}
}
}
if (GriefDefenderPlugin.getGlobalConfig().getConfig().context.playerEquipment) {
final ItemStack helmet = player.getInventory().getHelmet();
final ItemStack chestplate = player.getInventory().getChestplate();
final ItemStack leggings = player.getInventory().getLeggings();
final ItemStack boots = player.getInventory().getBoots();
if (helmet != null) {
contexts.add(new Context("helmet", getPermissionIdentifier(helmet)));
}
if (chestplate != null) {
contexts.add(new Context("chestplate", getPermissionIdentifier(chestplate)));
}
if (leggings != null) {
contexts.add(new Context("leggings", getPermissionIdentifier(leggings)));
}
if (boots != null) {
contexts.add(new Context("boots", getPermissionIdentifier(boots)));
}
}
if (GriefDefenderPlugin.getGlobalConfig().getConfig().context.enchantments) {
// add player item enchantment contexts
final List<String> enchantments = NMSUtil.getInstance().getEnchantmentsItemMainHand(player);
for (String enchantment : enchantments) {
final String[] parts = enchantment.split(",");
for (String part : parts) {
if (part.startsWith("id:")) {
part = part.replace("id:", "");
part = part.replace("\"", "");
part = part.substring(0, part.length() - 1);
if (Character.isDigit(part.charAt(0))) {
part = part.replaceAll("[^0-9]", "");
part = NMSUtil.getInstance().getEnchantmentId(Integer.valueOf(part));
}
contexts.add(new Context("mainhand_enchant", part));
contexts.add(new Context("mainhand_enchant", ContextGroupKeys.ANY));
}
}
enchantment = enchantment.replace("\"", "");
enchantment = enchantment.substring(1, enchantment.length() - 1);
contexts.add(new Context("mainhand_enchant_data", enchantment));
}
if (!enchantments.isEmpty()) {
contexts.add(new Context("mainhand_enchant", ContextGroupKeys.ANY));
}
final List<String> offEnchantments = NMSUtil.getInstance().getEnchantmentsItemOffHand(player);
for (String enchantment : offEnchantments) {
final String[] parts = enchantment.split(",");
for (String part : parts) {
if (part.startsWith("id:")) {
part = part.replace("id:", "");
part = part.replace("\"", "");
part = part.substring(0, part.length() - 1);
if (Character.isDigit(part.charAt(0))) {
part = part.replaceAll("[^0-9]", "");
part = NMSUtil.getInstance().getEnchantmentId(Integer.valueOf(part));
}
contexts.add(new Context("offhand_enchant", part));
}
}
enchantment = enchantment.replace("\"", "");
enchantment = enchantment.substring(1, enchantment.length() - 1);
contexts.add(new Context("offhand_enchant_data", enchantment));
}
if (!offEnchantments.isEmpty()) {
contexts.add(new Context("offhand_enchant", ContextGroupKeys.ANY));
}
}
}
private Set<Context> addBlockContexts(Set<Context> contexts, Block block, boolean isSource) {
Matcher matcher = BLOCKSTATE_PATTERN.matcher(NMSUtil.getInstance().getBlockDataString((Block) block));
if (matcher.find()) {
final String properties[] = matcher.group(0).split(",");
for (String property : properties) {
String prop = property.replace("=", ":");
if (prop.equals("type:invalid")) {
// ignore
continue;
}
contexts.add(new Context(ContextKeys.STATE, prop));
}
}
if (NMSUtil.getInstance().isBlockCrops(block)) {
if (isSource) {
contexts.add(ContextGroups.SOURCE_CROPS);
} else {
contexts.add(ContextGroups.TARGET_CROPS);
}
} else if (NMSUtil.getInstance().isBlockPlant(block)){
if (isSource) {
contexts.add(ContextGroups.SOURCE_PLANTS);
} else {
contexts.add(ContextGroups.TARGET_PLANTS);
}
}
return contexts;
}
public String getIdentifierWithoutMeta(String targetId) {
Matcher m = PATTERN_META.matcher(targetId);
String targetMeta = "";
if (m.find()) {
targetMeta = m.group(0);
targetId = StringUtils.replace(targetId, targetMeta, "");
}
return targetId;
}
private Set<Context> populateEventSourceTargetContext(Set<Context> contexts, String id, boolean isSource) {
if (!id.contains(":")) {
id = "minecraft:" + id;
}
contexts = this.populateTagContextsForId(contexts, id, isSource);
// always add source/target any contexts
contexts.add(ContextGroups.SOURCE_ANY);
contexts.add(ContextGroups.TARGET_ANY);
final String[] parts = id.split(":");
final String modId = parts[0];
if (isSource) {
this.eventSourceId = id.toLowerCase();
contexts.add(new Context("source", this.eventSourceId));
contexts.add(new Context("source", modId + ":any"));
} else {
this.eventTargetId = id.toLowerCase();
contexts.add(new Context("target", this.eventTargetId));
contexts.add(new Context("target", modId + ":any"));
}
return contexts;
}
public Set<Context> populateTagContextsForId(Set<Context> contexts, String id, boolean isSource) {
if (GriefDefenderPlugin.getInstance().getTagProvider() == null) {
return contexts;
}
final Set<Context> tagContexts = GriefDefenderPlugin.getInstance().getTagProvider().getTagMap().get(id);
if (tagContexts == null) {
return contexts;
}
for (Context context : tagContexts) {
if (isSource) {
contexts.add(new Context(ContextKeys.SOURCE, "#" + context.getKey() + ":" + context.getValue()));
if (context.getKey().equalsIgnoreCase("minecraft")) {
contexts.add(new Context(ContextKeys.SOURCE, "#" + context.getValue()));
}
} else {
contexts.add(new Context(ContextKeys.TARGET, "#" + context.getKey() + ":" + context.getValue()));
if (context.getKey().equalsIgnoreCase("minecraft")) {
contexts.add(new Context(ContextKeys.TARGET, "#" + context.getValue()));
}
}
}
return contexts;
}
private String populateEventSourceTarget(String id, boolean isSource) {
if (this.blacklistCheck) {
return id;
}
if (!id.contains(":")) {
id = "minecraft:" + id;
}
String[] parts = id.split(":");
if (parts != null && parts.length == 3) {
if (parts[0].equals(parts[1])) {
id = parts[1] + ":" + parts[2];
}
}
if (isSource) {
this.eventSourceId = id.toLowerCase();
} else {
this.eventTargetId = id.toLowerCase();
}
return id;
}
@Override
public CompletableFuture<PermissionResult> clearAllFlagPermissions(Subject subject) {
CompletableFuture<PermissionResult> result = new CompletableFuture<>();
if (subject == null) {
result.complete(new GDPermissionResult(ResultTypes.SUBJECT_DOES_NOT_EXIST));
return result;
}
GDFlagPermissionEvent.ClearAll event = new GDFlagPermissionEvent.ClearAll(subject);
GriefDefender.getEventManager().post(event);
if (event.cancelled()) {
result.complete(new GDPermissionResult(ResultTypes.EVENT_CANCELLED, event.getMessage().orElse(null)));
return result;
}
for (Map.Entry<Set<Context>, Map<String, Boolean>> mapEntry : PermissionUtil.getInstance().getPermanentPermissions((GDPermissionHolder) subject).entrySet()) {
final Set<Context> contextSet = mapEntry.getKey();
for (Context context : contextSet) {
if (context.getValue().equals(subject.getIdentifier())) {
PermissionUtil.getInstance().clearPermissions((GDPermissionHolder) subject, context);
}
}
}
result.complete(new GDPermissionResult(ResultTypes.SUCCESS));
return result;
}
@Override
public CompletableFuture<PermissionResult> clearFlagPermissions(Set<Context> contexts) {
return clearFlagPermissions(GriefDefenderPlugin.DEFAULT_HOLDER, contexts);
}
@Override
public CompletableFuture<PermissionResult> clearFlagPermissions(Subject subject, Set<Context> contexts) {
CompletableFuture<PermissionResult> result = new CompletableFuture<>();
if (subject == null) {
result.complete(new GDPermissionResult(ResultTypes.SUBJECT_DOES_NOT_EXIST));
}
GDFlagPermissionEvent.Clear event = new GDFlagPermissionEvent.Clear(subject, contexts);
GriefDefender.getEventManager().post(event);
if (event.cancelled()) {
result.complete(new GDPermissionResult(ResultTypes.EVENT_CANCELLED, event.getMessage().orElse(null)));
return result;
}
PermissionUtil.getInstance().clearPermissions((GDPermissionHolder) subject, contexts);
result.complete(new GDPermissionResult(ResultTypes.SUCCESS));
return result;
}
@Override
public CompletableFuture<PermissionResult> setFlagPermission(Flag flag, Tristate value, Set<Context> contexts) {
return setPermission(GriefDefenderPlugin.DEFAULT_HOLDER, flag, value, contexts);
}
public CompletableFuture<PermissionResult> setPermission(Subject subject, Flag flag, Tristate value, Set<Context> contexts) {
CompletableFuture<PermissionResult> result = new CompletableFuture<>();
GDFlagPermissionEvent.Set event = new GDFlagPermissionEvent.Set(subject, flag, value, contexts);
GriefDefender.getEventManager().post(event);
if (event.cancelled()) {
result.complete(new GDPermissionResult(ResultTypes.EVENT_CANCELLED, event.getMessage().orElse(null)));
return result;
}
return PermissionUtil.getInstance().setPermissionValue((GDPermissionHolder) subject, flag, value, contexts);
}
// internal
public CompletableFuture<PermissionResult> setPermission(Claim claim, GDPermissionHolder subject, Flag flag, String target, Tristate value, Set<Context> contexts) {
if (target.equalsIgnoreCase("any:any")) {
target = "any";
}
CompletableFuture<PermissionResult> result = new CompletableFuture<>();
if (flag != Flags.COMMAND_EXECUTE && flag != Flags.COMMAND_EXECUTE_PVP) {
String[] parts = target.split(":");
if (!target.startsWith("#") && parts.length > 1 && parts[0].equalsIgnoreCase("minecraft")) {
target = parts[1];
}
if (target != null && !GriefDefenderPlugin.ID_MAP.contains(target)) {
result.complete(new GDPermissionResult(ResultTypes.TARGET_NOT_VALID));
return result;
}
}
contexts.add(new Context(ContextKeys.TARGET, target));
GDFlagPermissionEvent.Set event = new GDFlagPermissionEvent.Set(subject, flag, value, contexts);
GriefDefender.getEventManager().post(event);
if (event.cancelled()) {
result.complete(new GDPermissionResult(ResultTypes.EVENT_CANCELLED, event.getMessage().orElse(null)));
return result;
}
final GDPermissionUser user = GDCauseStackManager.getInstance().getCurrentCause().first(GDPermissionUser.class).orElse(null);
CommandSender commandSource = user != null && user.getOnlinePlayer() != null ? user.getOnlinePlayer() : Bukkit.getConsoleSender();
result.complete(CommandHelper.addFlagPermission(commandSource, subject, claim, flag, target, value, contexts));
return result;
}
@Override
public Tristate getFlagPermissionValue(Flag flag, Set<Context> contexts) {
return getPermissionValue(GriefDefenderPlugin.DEFAULT_HOLDER, flag, contexts);
}
public Tristate getPermissionValue(GDPermissionHolder subject, Flag flag, Set<Context> contexts) {
return PermissionUtil.getInstance().getPermissionValue(subject, flag.getPermission(), contexts);
}
@Override
public Map<String, Boolean> getFlagPermissions(Set<Context> contexts) {
return getFlagPermissions(GriefDefenderPlugin.DEFAULT_HOLDER, contexts);
}
@Override
public Map<String, Boolean> getFlagPermissions(Subject subject, Set<Context> contexts) {
if (subject == null) {
return new HashMap<>();
}
return PermissionUtil.getInstance().getPermissions((GDPermissionHolder) subject, contexts);
}
public static GDPermissionManager getInstance() {
return instance;
}
static {
instance = new GDPermissionManager();
}
@Override
public Optional<String> getOptionValue(Option option, Set<Context> contexts) {
return Optional.empty();
}
@Override
public Optional<String> getOptionValue(Subject subject, Option option, Set<Context> contexts) {
return Optional.empty();
}
public <T> T getInternalOptionValue(TypeToken<T> type, OfflinePlayer player, Option<T> option) {
return getInternalOptionValue(type, player, option, (ClaimType) null);
}
public <T> T getInternalOptionValue(TypeToken<T> type, OfflinePlayer player, Option<T> option, Claim claim) {
final GDPermissionHolder holder = PermissionHolderCache.getInstance().getOrCreateHolder(player.getUniqueId().toString());
if (claim != null) {
return this.getInternalOptionValue(type, holder, option, claim, claim.getType(), new HashSet<>());
}
return this.getInternalOptionValue(type, holder, option, (ClaimType) null);
}
public <T> T getInternalOptionValue(TypeToken<T> type, OfflinePlayer player, Option<T> option, ClaimType claimType) {
final GDPermissionHolder holder = PermissionHolderCache.getInstance().getOrCreateHolder(player.getUniqueId().toString());
return this.getInternalOptionValue(type, holder, option, null, claimType, new HashSet<>());
}
public <T> T getInternalOptionValue(TypeToken<T> type, GDPermissionHolder holder, Option<T> option) {
return this.getInternalOptionValue(type, holder, option, (ClaimType) null);
}
public <T> T getInternalOptionValue(TypeToken<T> type, GDPermissionHolder holder, Option<T> option, Claim claim) {
if (claim != null) {
return this.getInternalOptionValue(type, holder, option, claim, claim.getType(), new HashSet<>());
}
return this.getInternalOptionValue(type, holder, option, (ClaimType) null);
}
public <T> T getInternalOptionValue(TypeToken<T> type, GDPermissionHolder holder, Option<T> option, Set<Context> contexts) {
return getInternalOptionValue(type, holder, option, null, null, contexts);
}
public <T> T getInternalOptionValue(TypeToken<T> type, GDPermissionHolder holder, Option<T> option, Claim claim, Set<Context> contexts) {
return getInternalOptionValue(type, holder, option, claim, null, contexts);
}
public <T> T getInternalOptionValue(TypeToken<T> type, GDPermissionHolder holder, Option<T> option, ClaimType claimType) {
return this.getInternalOptionValue(type, holder, option, null, claimType, new HashSet<>());
}
public <T> T getInternalOptionValue(TypeToken<T> type, GDPermissionHolder holder, Option<T> option, Claim claim, ClaimType claimType, Set<Context> contexts) {
if (holder != GriefDefenderPlugin.DEFAULT_HOLDER && holder instanceof GDPermissionUser) {
final GDPermissionUser user = (GDPermissionUser) holder;
final GDPlayerData playerData = (GDPlayerData) user.getPlayerData();
// Prevent world contexts being added when checking for accrued blocks in global mode
if (option != Options.ACCRUED_BLOCKS || GriefDefenderPlugin.getGlobalConfig().getConfig().playerdata.useWorldPlayerData()) {
PermissionUtil.getInstance().addActiveContexts(contexts, holder, playerData, claim);
}
}
Set<Context> optionContexts = new HashSet<>(contexts);
if (!option.isGlobal() && (claim != null || claimType != null)) {
// check claim
if (claim != null) {
// check override
if (claim.isAdminClaim()) {
optionContexts.add(ClaimContexts.ADMIN_OVERRIDE_CONTEXT);
} else if (claim.isTown()) {
optionContexts.add(ClaimContexts.TOWN_OVERRIDE_CONTEXT);
} else if (claim.isBasicClaim()) {
optionContexts.add(ClaimContexts.BASIC_OVERRIDE_CONTEXT);
} else if (claim.isWilderness()) {
optionContexts.add(ClaimContexts.WILDERNESS_OVERRIDE_CONTEXT);
}
if (!claim.isWilderness()) {
optionContexts.add(ClaimContexts.USER_OVERRIDE_CONTEXT);
}
optionContexts.add(((GDClaim) claim).getWorldContext());
optionContexts.add(ClaimContexts.GLOBAL_OVERRIDE_CONTEXT);
T value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
// check claim owner override
optionContexts = new HashSet<>(contexts);
optionContexts.add(((GDClaim) claim).getWorldContext());
optionContexts.add(claim.getOverrideClaimContext());
value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
optionContexts = new HashSet<>(contexts);
optionContexts.add(claim.getContext());
value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
}
// check claim type
if (claimType != null) {
optionContexts = new HashSet<>(contexts);
optionContexts.add(claimType.getContext());
final T value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
}
}
optionContexts = new HashSet<>(contexts);
// Check only active contexts
T value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
if (claim != null) {
optionContexts.add(claim.getDefaultTypeContext());
value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
optionContexts.remove(claim.getDefaultTypeContext());
}
optionContexts.add(ClaimContexts.GLOBAL_DEFAULT_CONTEXT);
if (claim != null && !claim.isWilderness()) {
optionContexts.add(ClaimContexts.USER_DEFAULT_CONTEXT);
}
value = this.getOptionActualValue(type, holder, option, optionContexts);
if (value != null) {
return value;
}
// Check default holder
if (holder != GriefDefenderPlugin.DEFAULT_HOLDER) {
return getInternalOptionValue(type, GriefDefenderPlugin.DEFAULT_HOLDER, option, claim, claimType, contexts);
}
return option.getDefaultValue();
}
private <T> T getOptionActualValue(TypeToken<T> type, GDPermissionHolder holder, Option option, Set<Context> contexts) {
if (option.multiValued()) {
List<String> values = PermissionUtil.getInstance().getOptionValueList(holder, option, contexts);
if (values != null && !values.isEmpty()) {
return (T) values;
}
}
String value = PermissionUtil.getInstance().getOptionValue(holder, option, contexts);
if (value != null) {
return this.getOptionTypeValue(type, value);
}
return null;
}
private <T> T getOptionTypeValue(TypeToken<T> type, String value) {
if (type.getRawType().isAssignableFrom(Double.class)) {
return (T) Double.valueOf(value);
}
if (type.getRawType().isAssignableFrom(Integer.class)) {
if (value.equalsIgnoreCase("undefined")) {
return (T) Integer.valueOf(-1);
}
Integer val = null;
try {
val = Integer.valueOf(value);
} catch (NumberFormatException e) {
return (T) Integer.valueOf(-1);
}
return (T) Integer.valueOf(value);
}
if (type.getRawType().isAssignableFrom(String.class)) {
return (T) value;
}
if (type.getRawType().isAssignableFrom(Tristate.class)) {
if (value.equalsIgnoreCase("true")) {
return (T) Tristate.TRUE;
}
if (value.equalsIgnoreCase("false")) {
return (T) Tristate.FALSE;
}
int permValue = 0;
try {
permValue = Integer.parseInt(value);
} catch (NumberFormatException e) {
}
if (permValue == 0) {
return (T) Tristate.UNDEFINED;
}
return (T) (permValue == 1 ? Tristate.TRUE : Tristate.FALSE);
}
if (type.getRawType().isAssignableFrom(CreateModeType.class)) {
if (value.equalsIgnoreCase("undefined")) {
return (T) CreateModeTypes.AREA;
}
if (value.equalsIgnoreCase("volume")) {
return (T) CreateModeTypes.VOLUME;
}
if (value.equalsIgnoreCase("area")) {
return (T) CreateModeTypes.AREA;
}
int permValue = 0;
try {
permValue = Integer.parseInt(value);
} catch (NumberFormatException e) {
}
if (permValue == 0) {
return (T) CreateModeTypes.AREA;
}
return (T) (permValue == 1 ? CreateModeTypes.VOLUME : CreateModeTypes.AREA);
}
if (type.getRawType().isAssignableFrom(WeatherType.class)) {
if (value.equalsIgnoreCase("downfall")) {
return (T) WeatherTypes.DOWNFALL;
}
if (value.equalsIgnoreCase("clear")) {
return (T) WeatherTypes.CLEAR;
}
return (T) WeatherTypes.UNDEFINED;
}
if (type.getRawType().isAssignableFrom(GameModeType.class)) {
if (value.equalsIgnoreCase("adventure")) {
return (T) GameModeTypes.ADVENTURE;
}
if (value.equalsIgnoreCase("creative")) {
return (T) GameModeTypes.CREATIVE;
}
if (value.equalsIgnoreCase("spectator")) {
return (T) GameModeTypes.SPECTATOR;
}
if (value.equalsIgnoreCase("survival")) {
return (T) GameModeTypes.SURVIVAL;
}
return (T) GameModeTypes.UNDEFINED;
}
if (type.getRawType().isAssignableFrom(Boolean.class)) {
return (T) Boolean.valueOf(Boolean.parseBoolean(value));
}
return (T) value;
}
// Uses passed contexts and only adds active contexts
public Double getActualOptionValue(GDPermissionHolder holder, Option option, Claim claim, GDPlayerData playerData, Set<Context> contexts) {
if (holder != GriefDefenderPlugin.DEFAULT_HOLDER) {
if (playerData != null) {
playerData.ignoreActiveContexts = true;
}
PermissionUtil.getInstance().addActiveContexts(contexts, holder, playerData, claim);
}
final String value = PermissionUtil.getInstance().getOptionValue(holder, option, contexts);
if (value != null) {
return this.getDoubleValue(value);
}
return Double.valueOf(option.getDefaultValue().toString());
}
private Double getDoubleValue(String option) {
if (option == null) {
return null;
}
double optionValue = 0.0;
try {
optionValue = Double.parseDouble(option);
} catch (NumberFormatException e) {
}
return optionValue;
}
public Optional<Flag> getFlag(String value) {
if (value == null) {
return Optional.empty();
}
value = value.replace("griefdefender.flag.", "");
String[] parts = value.split("\\.");
if (parts.length > 0) {
value = parts[0];
}
return FlagRegistryModule.getInstance().getById(value);
}
public Optional<Option> getOption(String value) {
if (value == null) {
return Optional.empty();
}
value = value.replace("griefdefender.", "");
String[] parts = value.split("\\.");
if (parts.length > 0) {
value = parts[0];
}
return GriefDefender.getRegistry().getType(Option.class, value);
}
public Component getEventMessage() {
return this.eventMessage;
}
@Override
public CompletableFuture<PermissionResult> clearOptions() {
// TODO Auto-generated method stub
return null;
}
@Override
public CompletableFuture<PermissionResult> clearOptions(Set<Context> contexts) {
// TODO Auto-generated method stub
return null;
}
@Override
public Tristate getFlagPermissionValue(Flag flag, Subject subject, Set<Context> contexts) {
// TODO Auto-generated method stub
return null;
}
@Override
public CompletableFuture<PermissionResult> setFlagPermission(Flag flag, Subject subject, Tristate value,
Set<Context> contexts) {
// TODO Auto-generated method stub
return null;
}
@Override
public CompletableFuture<PermissionResult> setOption(Option option, String value, Set<Context> contexts) {
return PermissionUtil.getInstance().setOptionValue(GriefDefenderPlugin.DEFAULT_HOLDER, option.getPermission(), value, contexts);
}
@Override
public CompletableFuture<PermissionResult> setOption(Option option, Subject subject, String value, Set<Context> contexts) {
return PermissionUtil.getInstance().setOptionValue((GDPermissionHolder) subject, option.getPermission(), value, contexts);
}
@Override
public <T> Optional<T> getOptionValue(TypeToken<T> type, Option<T> option, Set<Context> contexts) {
String value = PermissionUtil.getInstance().getOptionValue(GriefDefenderPlugin.DEFAULT_HOLDER, option, contexts);
if (value != null) {
return Optional.of(this.getOptionTypeValue(type, value));
}
return Optional.empty();
}
@Override
public <T> Optional<T> getOptionValue(TypeToken<T> type, Subject subject, Option<T> option, Set<Context> contexts) {
String value = PermissionUtil.getInstance().getOptionValue((GDPermissionHolder) subject, option, contexts);
if (value != null) {
return Optional.of(this.getOptionTypeValue(type, value));
}
return Optional.empty();
}
@Override
public <T> T getActiveOptionValue(TypeToken<T> type, Option<T> option, Subject subject, Claim claim,
Set<Context> contexts) {
return this.getInternalOptionValue(type, (GDPermissionHolder) subject, option, claim, claim.getType(), contexts);
}
@Override
public CompletableFuture<PermissionResult> setFlagDefinition(Subject subject, FlagDefinition flagDefinition, Tristate value) {
Set<Context> contexts = new HashSet<>(flagDefinition.getContexts());
Set<Context> defaultContexts = new HashSet<>();
Set<Context> overrideContexts = new HashSet<>();
String groupStr = null;
final Iterator<Context> iterator = contexts.iterator();
while (iterator.hasNext()) {
final Context context = iterator.next();
if (context.getKey().equalsIgnoreCase("gd_claim_default")) {
defaultContexts.add(context);
} else if (context.getKey().equalsIgnoreCase("gd_claim_override")) {
if (context.getValue().equalsIgnoreCase("claim")) {
iterator.remove();
continue;
}
overrideContexts.add(context);
} else if (context.getKey().equalsIgnoreCase("group")) {
groupStr = context.getValue();
}
}
GDPermissionHolder holder = GriefDefenderPlugin.DEFAULT_HOLDER;
if (groupStr != null) {
if (PermissionUtil.getInstance().hasGroupSubject(groupStr)) {
holder = PermissionHolderCache.getInstance().getOrCreateGroup(groupStr);
if (holder == null) {
holder = GriefDefenderPlugin.DEFAULT_HOLDER;
}
}
}
CompletableFuture<PermissionResult> result = new CompletableFuture<>();
if (!defaultContexts.isEmpty()) {
result = PermissionUtil.getInstance().setFlagDefinition(holder, flagDefinition, flagDefinition.getDefaultValue(), defaultContexts, true);
}
if (!overrideContexts.isEmpty()) {
result = PermissionUtil.getInstance().setFlagDefinition(holder, flagDefinition, flagDefinition.getDefaultValue(), overrideContexts, false);
}
PermissionUtil.getInstance().save(holder);
return result;
}
}
| 0 | 0.976698 | 1 | 0.976698 | game-dev | MEDIA | 0.826486 | game-dev | 0.841688 | 1 | 0.841688 |
corail-research/seahorse | 3,963 | src/seahorse/game/game_layout/board.py | from __future__ import annotations
import json
from typing import TYPE_CHECKING
from seahorse.game.representation import Representation
from seahorse.utils.serializer import Serializable
if TYPE_CHECKING:
from seahorse.player.player import Player
class Piece(Serializable):
"""
A class representing a piece in the game.
Attributes:
piece_type (str): The type of the piece.
owner_id (int): The ID of the player who possesses the piece.
"""
def __init__(self, piece_type: str, owner: Player | None = None, owner_id: int=-1) -> None:
"""
Initializes a new instance of the Piece class.
Args:
piece_type (str): The type of the piece.
owner (Player): The player who possesses the piece.
"""
self.piece_type = piece_type
if owner is None:
self.owner_id = owner_id
else:
self.owner_id = owner.get_id()
def get_type(self) -> str:
"""
Gets the type of the piece.
Returns:
str: The type of the piece.
"""
return self.piece_type
def get_owner_id(self) -> int:
"""
Gets the ID of the owner of the piece.
Returns:
int: The ID of the owner.
"""
return self.owner_id
def copy(self) -> Piece:
"""
Creates a copy of the piece.
Returns:
Piece: A copy of the piece.
"""
return Piece(self.piece_type, None)
def __hash__(self) -> int:
return hash((hash(self.get_type()), hash(self.owner_id)))
def __eq__(self, __value: object) -> bool:
return hash(self) == hash(__value)
#def __str__(self) -> str:
# return self.get_type()
def to_json(self) -> str:
return self.__dict__
@classmethod
def from_json(cls,data) -> str:
return cls(**json.loads(data))
class Board(Representation):
"""
A class representing the game board.
Attributes:
env (dict[Tuple[int], Piece]): The environment dictionary composed of pieces.
dimensions (list[int]): The dimensions of the board.
"""
def __init__(self, env: dict[tuple[int], Piece], dim: list[int]) -> None:
"""
Initializes a new instance of the Board class.
Args:
env (dict[Tuple[int], Piece]): The environment dictionary composed of pieces.
dim (list[int]): The dimensions of the board.
"""
super().__init__(env)
self.dimensions = dim
def get_dimensions(self) -> list[int]:
"""
Gets the dimensions of the board.
Returns:
list[int]: The list of dimensions.
"""
return self.dimensions
def get_pieces_player(self, owner: Player) -> tuple[int, list[Piece]]:
"""
Gets the pieces owned by a specific player.
Args:
owner (Player): The player specified.
Returns:
Tuple[int, list[Piece]]: The number of pieces owned by the player and the list of their pieces.
"""
pieces_list = []
number = 0
for key in self.env.keys():
if self.env[key].get_owner_id() == owner.get_id():
number += 1
pieces_list.append(key)
return number, pieces_list
def __hash__(self):
return hash(frozenset([(hash(pos), hash(piece)) for pos, piece in self.env.items()]))
def __eq__(self, __value: object) -> bool:
return hash(self) == hash(__value)
def __str__(self) -> str:
dim = self.get_dimensions()
to_print = ""
for i in range(dim[0]):
for j in range(dim[1]):
if self.get_env().get((i, j), -1) != -1:
to_print += str(self.get_env().get((i, j)).get_type()) + " "
else:
to_print += "_ "
to_print += "\n"
return to_print
| 0 | 0.869756 | 1 | 0.869756 | game-dev | MEDIA | 0.444912 | game-dev | 0.966038 | 1 | 0.966038 |
KAMKEEL/CustomNPC-Plus | 23,685 | src/main/java/kamkeel/npcs/util/AttributeItemUtil.java | package kamkeel.npcs.util;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.CustomAttributes;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.AttributeDefinition;
import kamkeel.npcs.controllers.data.attribute.AttributeValueType;
import kamkeel.npcs.controllers.data.attribute.requirement.IRequirementChecker;
import kamkeel.npcs.controllers.data.attribute.requirement.RequirementCheckerRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.ClientProxy;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.Magic;
import org.lwjgl.input.Keyboard;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Provides helper functions to write/read item attributes to/from NBT.
* All data is now stored under a hierarchical structure:
* <p>
* "RPGCore"
* ├─ "Attributes"
* ├─ "Magic"
* └─ "Requirements"
*/
public class AttributeItemUtil {
// New hierarchical keys.
public static final String TAG_RPGCORE = "RPGCore";
public static final String TAG_ATTRIBUTES = "Attributes";
public static final String TAG_MAGIC = "Magic";
public static final String TAG_REQUIREMENTS = "Requirements";
/**
* Applies a non–magic attribute to an item.
*/
public static void applyAttribute(ItemStack item, String attributeKey, float value) {
if (item == null) return;
if (item.stackTagCompound == null) {
item.stackTagCompound = new NBTTagCompound();
}
NBTTagCompound root = item.stackTagCompound;
// Get (or create) the RPGCore compound.
NBTTagCompound rpgCore = root.hasKey(TAG_RPGCORE) ? root.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound();
// Get (or create) the Attributes compound.
NBTTagCompound attrTag = rpgCore.hasKey(TAG_ATTRIBUTES) ? rpgCore.getCompoundTag(TAG_ATTRIBUTES) : new NBTTagCompound();
attrTag.setFloat(attributeKey, value);
rpgCore.setTag(TAG_ATTRIBUTES, attrTag);
root.setTag(TAG_RPGCORE, rpgCore);
}
public static void applyAttribute(ItemStack item, AttributeDefinition definition, float value) {
applyAttribute(item, definition.getKey(), value);
}
/**
* Removes a non–magic attribute from an item.
*/
public static void removeAttribute(ItemStack item, String attributeKey) {
if (item == null || item.stackTagCompound == null) return;
NBTTagCompound root = item.stackTagCompound;
if (root.hasKey(TAG_RPGCORE)) {
NBTTagCompound rpgCore = root.getCompoundTag(TAG_RPGCORE);
if (rpgCore.hasKey(TAG_ATTRIBUTES)) {
NBTTagCompound attrTag = rpgCore.getCompoundTag(TAG_ATTRIBUTES);
attrTag.removeTag(attributeKey);
if (attrTag.func_150296_c().isEmpty()) {
rpgCore.removeTag(TAG_ATTRIBUTES);
} else {
rpgCore.setTag(TAG_ATTRIBUTES, attrTag);
}
root.setTag(TAG_RPGCORE, rpgCore);
}
}
}
/**
* Reads non–magic attributes from an item.
*/
public static Map<String, Float> readAttributes(ItemStack item) {
Map<String, Float> map = new HashMap<>();
if (item == null || item.stackTagCompound == null) return map;
NBTTagCompound root = item.stackTagCompound;
if (root.hasKey(TAG_RPGCORE)) {
NBTTagCompound rpgCore = root.getCompoundTag(TAG_RPGCORE);
if (rpgCore.hasKey(TAG_ATTRIBUTES)) {
NBTTagCompound attrTag = rpgCore.getCompoundTag(TAG_ATTRIBUTES);
Set<String> keys = attrTag.func_150296_c();
for (String key : keys) {
map.put(key, attrTag.getFloat(key));
}
}
}
return map;
}
/**
* Reads a magic attribute map from an item.
* The given attributeTag is the key under which the compound is stored (e.g., MAGIC_DAMAGE_KEY).
*/
public static Map<Integer, Float> readMagicAttributeMap(ItemStack item, String attributeTag) {
Map<Integer, Float> map = new HashMap<>();
if (item == null || item.stackTagCompound == null) return map;
NBTTagCompound root = item.stackTagCompound;
if (root.hasKey(TAG_RPGCORE)) {
NBTTagCompound rpgCore = root.getCompoundTag(TAG_RPGCORE);
if (rpgCore.hasKey(TAG_MAGIC)) {
NBTTagCompound magicCompound = rpgCore.getCompoundTag(TAG_MAGIC);
if (magicCompound.hasKey(attributeTag)) {
NBTTagCompound magicMap = magicCompound.getCompoundTag(attributeTag);
Set<String> keys = magicMap.func_150296_c();
for (String key : keys) {
try {
int magicId = Integer.parseInt(key);
map.put(magicId, magicMap.getFloat(key));
} catch (NumberFormatException e) {
// Skip invalid key.
}
}
}
}
}
return map;
}
/**
* Applies (writes) a magic attribute to an item.
*/
public static void applyMagicAttribute(ItemStack item, String attributeTag, int magicId, float value) {
writeMagicAttribute(item, attributeTag, magicId, value);
}
/**
* Writes a magic attribute value to the given attributeTag.
*/
public static void writeMagicAttribute(ItemStack item, String attributeTag, int magicId, float value) {
if (item == null) return;
if (item.stackTagCompound == null)
item.stackTagCompound = new NBTTagCompound();
NBTTagCompound root = item.stackTagCompound;
// Get or create RPGCore compound.
NBTTagCompound rpgCore = root.hasKey(TAG_RPGCORE) ? root.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound();
// Get or create Magic compound.
NBTTagCompound magicCompound = rpgCore.hasKey(TAG_MAGIC) ? rpgCore.getCompoundTag(TAG_MAGIC) : new NBTTagCompound();
// Get or create the specific magic map.
NBTTagCompound magicMap = magicCompound.hasKey(attributeTag) ? magicCompound.getCompoundTag(attributeTag) : new NBTTagCompound();
magicMap.setFloat(String.valueOf(magicId), value);
magicCompound.setTag(attributeTag, magicMap);
rpgCore.setTag(TAG_MAGIC, magicCompound);
root.setTag(TAG_RPGCORE, rpgCore);
}
/**
* Removes a magic attribute value from the given attributeTag.
*/
public static void removeMagicAttribute(ItemStack item, String attributeTag, int magicId) {
if (item == null || item.stackTagCompound == null)
return;
NBTTagCompound root = item.stackTagCompound;
if (root.hasKey(TAG_RPGCORE)) {
NBTTagCompound rpgCore = root.getCompoundTag(TAG_RPGCORE);
if (rpgCore.hasKey(TAG_MAGIC)) {
NBTTagCompound magicCompound = rpgCore.getCompoundTag(TAG_MAGIC);
if (magicCompound.hasKey(attributeTag)) {
NBTTagCompound magicMap = magicCompound.getCompoundTag(attributeTag);
magicMap.removeTag(String.valueOf(magicId));
if (magicMap.func_150296_c().isEmpty())
magicCompound.removeTag(attributeTag);
else
magicCompound.setTag(attributeTag, magicMap);
rpgCore.setTag(TAG_MAGIC, magicCompound);
root.setTag(TAG_RPGCORE, rpgCore);
}
}
}
}
public static void applyRequirement(ItemStack item, String reqKey, Object value) {
if (item == null) return;
if (item.stackTagCompound == null)
item.stackTagCompound = new NBTTagCompound();
NBTTagCompound root = item.stackTagCompound;
// Get (or create) the RPGCore compound.
NBTTagCompound rpgCore = root.hasKey(TAG_RPGCORE) ? root.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound();
// Get (or create) the Requirements compound.
NBTTagCompound reqTag = rpgCore.hasKey(TAG_REQUIREMENTS) ? rpgCore.getCompoundTag(TAG_REQUIREMENTS) : new NBTTagCompound();
// Retrieve the checker from the registry.
IRequirementChecker checker = RequirementCheckerRegistry.getChecker(reqKey);
if (checker != null) {
checker.apply(reqTag, value);
}
rpgCore.setTag(TAG_REQUIREMENTS, reqTag);
root.setTag(TAG_RPGCORE, rpgCore);
}
public static void removeRequirement(ItemStack item, String reqKey) {
if (item == null || item.stackTagCompound == null) return;
NBTTagCompound root = item.stackTagCompound;
if (root.hasKey(TAG_RPGCORE)) {
NBTTagCompound rpgCore = root.getCompoundTag(TAG_RPGCORE);
if (rpgCore.hasKey(TAG_REQUIREMENTS)) {
NBTTagCompound reqTag = rpgCore.getCompoundTag(TAG_REQUIREMENTS);
reqTag.removeTag(reqKey);
if (reqTag.func_150296_c().isEmpty()) {
rpgCore.removeTag(TAG_REQUIREMENTS);
} else {
rpgCore.setTag(TAG_REQUIREMENTS, reqTag);
}
root.setTag(TAG_RPGCORE, rpgCore);
}
}
}
// ----------------- Tooltip Generation with Custom Sorting -------------------
/**
* Returns the item tooltip.
*/
@SideOnly(Side.CLIENT)
public static List<String> getToolTip(List<String> original, NBTTagCompound compound) {
List<String> tooltip = new ArrayList<>(original);
// Get the RPGCore compound and then the Attributes compound.
NBTTagCompound rpgCore = compound.hasKey(TAG_RPGCORE) ? compound.getCompoundTag(TAG_RPGCORE) : new NBTTagCompound();
NBTTagCompound attrTag = rpgCore.hasKey(TAG_ATTRIBUTES) ? rpgCore.getCompoundTag(TAG_ATTRIBUTES) : new NBTTagCompound();
if (Keyboard.isKeyDown(ClientProxy.NPCButton.getKeyCode())) {
List<String> newTooltips = new ArrayList<>();
if (!tooltip.isEmpty()) {
newTooltips.add(tooltip.get(0));
}
// Instead of storing plain strings, we wrap each line in a TooltipEntry
List<TooltipEntry> baseList = new ArrayList<>();
List<TooltipEntry> modifierList = new ArrayList<>();
List<TooltipEntry> statsList = new ArrayList<>();
List<TooltipEntry> infoList = new ArrayList<>();
List<TooltipEntry> extraList = new ArrayList<>();
// Process non–magic attributes.
Set<String> keys = attrTag.func_150296_c();
for (String key : keys) {
// For non–magic we include everything.
Float value = attrTag.getFloat(key);
AttributeDefinition def = AttributeController.getAttribute(key);
if (def == null)
continue;
AttributeDefinition.AttributeSection section = def != null ? def.getSection() : AttributeDefinition.AttributeSection.EXTRA;
String plainName = getTranslatedAttributeName(key, def); // unformatted name
String formattedLine = formatAttributeLine(def, section, value, plainName);
TooltipEntry entry = new TooltipEntry(plainName, formattedLine);
switch (section) {
case BASE:
baseList.add(entry);
break;
case MODIFIER:
modifierList.add(entry);
break;
case STATS:
statsList.add(entry);
break;
case INFO:
infoList.add(entry);
break;
default:
extraList.add(entry);
break;
}
}
// Process magic attributes.
processMagicAttributes(compound, baseList, modifierList, infoList, extraList);
// Define custom order maps for Base and Modifier sections.
// For Base: Health, Main Attack Damage, Neutral Damage come first.
Map<String, Integer> baseOrder = new HashMap<>();
baseOrder.put("Health", 1);
baseOrder.put("Main Attack Damage", 2);
baseOrder.put("Neutral Damage", 3);
// For Modifier: Main Attack Damage then Neutral Damage.
Map<String, Integer> modOrder = new HashMap<>();
modOrder.put("Health Boost", 1);
modOrder.put("Main Attack Damage", 2);
modOrder.put("Neutral Damage", 3);
modOrder.put("Movement Speed", 4);
modOrder.put("Knockback Resistance", 5);
// Build sections using our custom sorting.
newTooltips.addAll(buildSection(baseList, baseOrder));
newTooltips.addAll(buildSection(modifierList, modOrder));
newTooltips.addAll(buildSection(statsList)); // alphabetical
newTooltips.addAll(buildSection(infoList)); // alphabetical
newTooltips.addAll(buildSection(extraList)); // alphabetical
if (rpgCore.hasKey(TAG_REQUIREMENTS)) {
NBTTagCompound reqTag = rpgCore.getCompoundTag(TAG_REQUIREMENTS);
List<TooltipEntry> reqEntries = new ArrayList<>();
Minecraft mc = Minecraft.getMinecraft();
EntityPlayer clientPlayer = mc.thePlayer;
Set<String> requirements = reqTag.func_150296_c();
for (String reqKey : requirements) {
IRequirementChecker checker = RequirementCheckerRegistry.getChecker(reqKey);
if (checker != null) {
boolean met = clientPlayer != null && checker.check(clientPlayer, reqTag);
String tooltipValue = checker.getTooltipValue(reqTag);
String color = met ? EnumChatFormatting.GRAY.toString() : EnumChatFormatting.RED.toString();
String line = EnumChatFormatting.GRAY + StatCollector.translateToLocal(checker.getTranslation()) + ": " + color + tooltipValue;
reqEntries.add(new TooltipEntry(stripFormatting(StatCollector.translateToLocal(checker.getTranslation())), line));
}
}
newTooltips.addAll(buildSection(reqEntries));
}
tooltip = newTooltips;
} else {
String keyName = Keyboard.getKeyName(ClientProxy.NPCButton.getKeyCode());
tooltip.add(EnumChatFormatting.YELLOW + "" + EnumChatFormatting.ITALIC +
StatCollector.translateToLocal("rpgcore:tooltip").replace("%key%", keyName));
}
return tooltip;
}
/**
* Processes magic attributes from the compound.
* For each magic key, it retrieves the stored magic attributes from the "Magic" compound,
* formats each line and adds it to the proper section list.
*/
private static void processMagicAttributes(NBTTagCompound compound, List<TooltipEntry> baseList, List<TooltipEntry> modifierList,
List<TooltipEntry> infoList, List<TooltipEntry> extraList) {
if (!compound.hasKey(TAG_RPGCORE)) return;
NBTTagCompound rpgCore = compound.getCompoundTag(TAG_RPGCORE);
if (!rpgCore.hasKey(TAG_MAGIC)) return;
NBTTagCompound magicCompound = rpgCore.getCompoundTag(TAG_MAGIC);
String[] magicKeys = {
CustomAttributes.MAGIC_DAMAGE_KEY,
CustomAttributes.MAGIC_BOOST_KEY,
CustomAttributes.MAGIC_DEFENSE_KEY,
CustomAttributes.MAGIC_RESISTANCE_KEY
};
for (String magicKey : magicKeys) {
if (magicCompound.hasKey(magicKey)) {
NBTTagCompound magicTag = magicCompound.getCompoundTag(magicKey);
AttributeDefinition def = AttributeController.getAttribute(magicKey);
AttributeDefinition.AttributeSection section = def != null ? def.getSection() : AttributeDefinition.AttributeSection.EXTRA;
Set<String> keys = magicTag.func_150296_c();
for (String key : keys) {
try {
int magicId = Integer.parseInt(key);
Float value = magicTag.getFloat(key);
Magic magic = MagicController.getInstance().getMagic(magicId);
if (magic != null) {
// Build the magic display name without formatting for sorting.
String rawMagicName = magic.getDisplayName().replace("&", "\u00A7") + " \u00A77" + getMagicAppendix(magicKey);
String plainName = stripFormatting(rawMagicName);
String formattedLine = formatAttributeLine(def, section, value, rawMagicName);
TooltipEntry entry = new TooltipEntry(plainName, formattedLine);
switch (section) {
case BASE:
baseList.add(entry);
break;
case MODIFIER:
modifierList.add(entry);
break;
case INFO:
infoList.add(entry);
break;
default:
extraList.add(entry);
break;
}
}
} catch (NumberFormatException e) {
// Skip invalid key.
}
}
}
}
}
@SideOnly(Side.CLIENT)
private static String getMagicAppendix(String type) {
switch (type) {
case CustomAttributes.MAGIC_DEFENSE_KEY:
return StatCollector.translateToLocal("rpgcore:attribute.defense");
case CustomAttributes.MAGIC_RESISTANCE_KEY:
return StatCollector.translateToLocal("rpgcore:attribute.resistance");
default:
return StatCollector.translateToLocal("rpgcore:attribute.damage");
}
}
@SideOnly(Side.CLIENT)
private static String getTranslatedAttributeName(String key, AttributeDefinition def) {
key = def != null ? def.getTranslationKey() : key;
String translation = null;
if (StatCollector.canTranslate(key))
translation = StatCollector.translateToLocal(key);
if (translation == null && def != null)
translation = def.getDisplayName();
else if (translation == null)
translation = key;
return translation;
}
private static String formatAttributeLine(AttributeDefinition def, AttributeDefinition.AttributeSection section,
Float value, String displayName) {
String formattedValue = formatFloat(value);
if (section == AttributeDefinition.AttributeSection.STATS) {
String sign = value >= 0 ? "+" : "";
String color = value >= 0 ? EnumChatFormatting.GREEN.toString() : EnumChatFormatting.RED.toString();
String valueString = color + sign + formattedValue;
if (def != null && def.getValueType() == AttributeValueType.PERCENT)
valueString += "%";
valueString += EnumChatFormatting.GRAY;
if (def != null)
displayName = "\u00A7" + def.getColorCode() + displayName;
else
displayName = EnumChatFormatting.AQUA + displayName;
return valueString + " " + displayName;
} else if (section == AttributeDefinition.AttributeSection.MODIFIER || section == AttributeDefinition.AttributeSection.INFO) {
String sign = value >= 0 ? "+" : "";
String color = value >= 0 ? EnumChatFormatting.GREEN.toString() : EnumChatFormatting.RED.toString();
String valueString = color + sign + formattedValue;
if (def != null && (def.getValueType() == AttributeValueType.PERCENT || def.getValueType() == AttributeValueType.MAGIC))
valueString += "%";
valueString += EnumChatFormatting.GRAY;
return valueString + " " + displayName;
} else {
if (def != null)
displayName = "\u00A7" + def.getColorCode() + displayName;
else
displayName = EnumChatFormatting.AQUA + displayName;
String sign = value >= 0 ? "+" : "";
String color = value >= 0 ? EnumChatFormatting.GREEN.toString() : EnumChatFormatting.RED.toString();
String valueString = color + sign + formattedValue;
return displayName + "\u00A77: " + valueString;
}
}
private static String formatFloat(Float value) {
return new java.math.BigDecimal(Float.toString(value)).stripTrailingZeros().toPlainString();
}
// ---------------- Helper Methods for Sorting Tooltip Entries ----------------
// A small container to hold a tooltip line and its plain sort key.
private static class TooltipEntry {
public String sortKey;
public String line;
public TooltipEntry(String sortKey, String line) {
this.sortKey = sortKey;
this.line = line;
}
}
// Removes formatting codes (e.g., '§') from a string.
private static String stripFormatting(String input) {
return input == null ? "" : Pattern.compile("(?i)§[0-9A-FK-OR]").matcher(input).replaceAll("");
}
// Build a section with default alphabetical order.
private static List<String> buildSection(List<TooltipEntry> entries) {
Collections.sort(entries, (a, b) -> a.sortKey.compareToIgnoreCase(b.sortKey));
List<String> section = new ArrayList<>();
if (!entries.isEmpty()) {
section.add("");
for (TooltipEntry entry : entries) {
section.add(entry.line);
}
}
return section;
}
// Build a section using a custom order map.
private static List<String> buildSection(List<TooltipEntry> entries, Map<String, Integer> orderMap) {
Collections.sort(entries, (a, b) -> {
int pa = orderMap.containsKey(a.sortKey) ? orderMap.get(a.sortKey) : Integer.MAX_VALUE;
int pb = orderMap.containsKey(b.sortKey) ? orderMap.get(b.sortKey) : Integer.MAX_VALUE;
if (pa != pb) return Integer.compare(pa, pb);
return a.sortKey.compareToIgnoreCase(b.sortKey);
});
List<String> section = new ArrayList<>();
if (!entries.isEmpty()) {
section.add("");
for (TooltipEntry entry : entries) {
section.add(entry.line);
}
}
return section;
}
}
| 0 | 0.886192 | 1 | 0.886192 | game-dev | MEDIA | 0.992158 | game-dev | 0.969121 | 1 | 0.969121 |
getsentry/sentry-lua | 2,592 | examples/roblox/README.md | # Roblox Sentry Integration
Example Sentry integration for Roblox games.
## 🚀 Quick Start
**Use the all-in-one file:**
1. **Copy** `sentry-all-in-one.lua`
2. **Paste** into ServerScriptService as a Script
3. **Update DSN** on line 18
4. **Enable HTTP**: Game Settings → Security → "Allow HTTP Requests"
5. **Run** the game (F5)
## 📁 Available Files
- **`sentry-all-in-one.lua`** ⭐ **Complete single-file solution**
- **`sentry-roblox-sdk.lua`** - Reusable SDK module
- **`clean-example.lua`** - Example using the SDK module
## 🧪 Testing
Use the standard Sentry API (same as other platforms):
```lua
-- Capture events
sentry.capture_message("Hello Sentry!", "info")
sentry.capture_exception({type = "TestError", message = "Something failed"})
-- Set context
sentry.set_user({id = "123", username = "Player1"})
sentry.set_tag("level", "5")
sentry.add_breadcrumb({message = "Player moved", category = "navigation"})
```
## ✅ Success Indicators
Your integration is working when you see:
1. **Console Output**:
```
✅ Event sent successfully!
📊 Response: {"id":"..."}
```
2. **Sentry Dashboard**: Events appear within 30 seconds
3. **Manual Commands Work**: `sentry.capture_message("test")` executes without errors
## 🛠️ Customization
```lua
-- Required: Update your DSN
local SENTRY_DSN = "https://your-key@your-org.ingest.sentry.io/your-project-id"
-- Optional: Customize environment and release
sentry.init({
dsn = SENTRY_DSN,
environment = "production", -- or "staging", "development"
release = "1.2.0" -- your game version
})
-- Add user context
sentry.set_user({
id = tostring(player.UserId),
username = player.Name
})
-- Add custom tags and breadcrumbs
sentry.set_tag("game_mode", "survival")
sentry.add_breadcrumb({
message = "Player entered dungeon",
category = "game_event"
})
```
## 🐛 Troubleshooting
**"HTTP requests not enabled"**
→ Game Settings → Security → ✅ "Allow HTTP Requests"
**No events in Sentry dashboard**
→ Wait 10-30 seconds, check correct project, verify DSN
**"attempt to index nil with 'capture_message'"**
→ Make sure sentry.init() was called successfully first
## 🔨 Validation
To validate the Roblox integration is ready:
```bash
make roblox-all-in-one
# or directly:
./scripts/generate-roblox-all-in-one.sh
```
This checks that the `sentry-all-in-one.lua` file contains all required components and uses the standard SDK API.
## 🎉 Ready to Go!
Use `sentry-all-in-one.lua` to get started immediately. Copy, paste, update DSN, and test!
**Happy debugging with Sentry! 🐛→✅** | 0 | 0.841567 | 1 | 0.841567 | game-dev | MEDIA | 0.309247 | game-dev | 0.811364 | 1 | 0.811364 |
ReikaKalseki/ChromatiCraft | 4,893 | Block/Dimension/Structure/GOL/BlockGOLController.java | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.ChromatiCraft.Block.Dimension.Structure.GOL;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import Reika.ChromatiCraft.Base.BlockDimensionStructureTile;
import Reika.ChromatiCraft.Base.DimensionStructureGenerator.DimensionStructureType;
import Reika.ChromatiCraft.Base.TileEntity.StructureBlockTile;
import Reika.ChromatiCraft.Block.Dimension.Structure.GOL.BlockGOLTile.GOLTile;
import Reika.ChromatiCraft.Registry.ChromaBlocks;
import Reika.ChromatiCraft.World.Dimension.Structure.GOLGenerator;
public class BlockGOLController extends BlockDimensionStructureTile {
private final IIcon[] icons = new IIcon[3];
public BlockGOLController(Material mat) {
super(mat);
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
return new GOLController();
}
@Override
public void onBlockClicked(World world, int x, int y, int z, EntityPlayer ep) {
if (!world.isRemote)
this.activate(world, x, y, z);
}
@Override
public boolean onRightClicked(World world, int x, int y, int z, EntityPlayer ep, int s, float a, float b, float c) {
if (!world.isRemote)
this.activate(world, x, y, z);
return true;
}
private void activate(World world, int x, int y, int z) {
GOLController te = (GOLController)world.getTileEntity(x, y, z);
if (te.isActive)
te.reset();
else
te.activate();
}
@Override
public void registerBlockIcons(IIconRegister ico) {
icons[0] = ico.registerIcon("chromaticraft:dimstruct/gol_control_play");
icons[1] = ico.registerIcon("chromaticraft:dimstruct/gol_control_stop");
icons[2] = ico.registerIcon("chromaticraft:dimstruct/gol_control_end");
}
@Override
public IIcon getIcon(int s, int meta) {
return s <= 1 ? icons[2] : icons[0];
}
@Override
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int s) {
if (s <= 1)
return icons[2];
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof GOLController && ((GOLController)te).isActive) {
return icons[1];
}
return super.getIcon(world, x, y, z, s);
}
public static class GOLController extends StructureBlockTile<GOLGenerator> {
private int minX;
private int maxX;
private int minZ;
private int maxZ;
private int floorY;
private boolean isActive;
@Override
public boolean canUpdate() {
return false;
}
public void initialize(int x1, int x2, int z1, int z2, int y) {
minX = x1;
maxX = x2;
minZ = z1;
maxZ = z2;
floorY = y;
}
private void activate() {
isActive = true;
//ReikaJavaLibrary.pConsole("activate");
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
Block b = worldObj.getBlock(x, floorY, z);
if (b == ChromaBlocks.GOL.getBlockInstance()) {
GOLTile te = (GOLTile)worldObj.getTileEntity(x, floorY, z);
te.activate();
}
}
}
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
private void reset() {
//ReikaJavaLibrary.pConsole("reset");
this.getGenerator().checkConditions(worldObj);
isActive = false;
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
Block b = worldObj.getBlock(x, floorY, z);
if (b == ChromaBlocks.GOL.getBlockInstance()) {
GOLTile te = (GOLTile)worldObj.getTileEntity(x, floorY, z);
te.reset();
worldObj.setBlockMetadataWithNotify(x, floorY+GOLGenerator.ROOM_HEIGHT, z, 2, 3);
}
}
}
this.getGenerator().clearTiles();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
@Override
public void writeToNBT(NBTTagCompound NBT) {
super.writeToNBT(NBT);
NBT.setInteger("minx", minX);
NBT.setInteger("maxx", maxX);
NBT.setInteger("minz", minZ);
NBT.setInteger("maxz", maxZ);
NBT.setInteger("posy", floorY);
NBT.setBoolean("active", isActive);
}
@Override
public void readFromNBT(NBTTagCompound NBT) {
super.readFromNBT(NBT);
minX = NBT.getInteger("minx");
maxX = NBT.getInteger("maxx");
minZ = NBT.getInteger("minz");
maxZ = NBT.getInteger("maxz");
floorY = NBT.getInteger("posy");
isActive = NBT.getBoolean("active");
}
@Override
public DimensionStructureType getType() {
return DimensionStructureType.GOL;
}
}
}
| 0 | 0.828397 | 1 | 0.828397 | game-dev | MEDIA | 0.992707 | game-dev | 0.910003 | 1 | 0.910003 |
ggnkua/Atari_ST_Sources | 3,898 | ASM/VMAX/ATOMIC/ATOMIC.3_3/DEPACK.S | ;decrunch source code of ATOMIK by ALTAIR ;je tiens a preciser
;A0=packed code ;que j'ai entierement
;call it by bsr ;ecris ce compacteur
;environnement compris.
DEC_MARGE: equ $10 ;min=0 , max=126 (pair!)
RESTORE_M: equ 1 ;argh j'ai plant pendant
;10 jours sur TOTAL RECALL
;a cause de ca!!!!!
PIC_ALGO: equ 1 ;PIC_ALGO=1,RESTORE_M=0 ; lenght=$18e
depack: movem.l d0-a6,-(a7) ;PIC_ALGO=0,RESTORE_M=0 ; lenght=$146
cmp.l #"ATOM",(a0)+ ;RESTORE_M=1 ; lenght=lenght+
bne no_crunched ;DEC_MARGE+$32
move.l (a0)+,d0
move.l d0,-(a7)
lea DEC_MARGE(a0,d0.l),a5
ifne RESTORE_M
move.l a5,a4
lea buff_marg(pc),a3
moveq #DEC_MARGE+9,d0
.save_m: move.b -(a4),(a3)+
dbf d0,.save_m
movem.l a3-a4,-(a7)
endc
ifne PIC_ALGO
pea (a5)
endc
move.l (a0)+,d0
lea 0(a0,d0.l),a6
move.b -(a6),d7
bra make_jnk
tablus: lea tablus_table(pc),a4
moveq #1,d6
bsr.s get_bit2
bra.s tablus2
decrunch: moveq #6,d6
take_lenght: add.b d7,d7
beq.s .empty1
.cont_copy: dbcc d6,take_lenght
bcs.s .next_cod
moveq #6,d5
sub d6,d5
bra.s .do_copy
.next_cod: moveq #3,d6
bsr.s get_bit2
beq.s .next_cod1
addq #6,d5
bra.s .do_copy
.next_cod1: moveq #7,d6
bsr.s get_bit2
beq.s .next_cod2
add #15+6,d5
bra.s .do_copy
.empty1: move.b -(a6),d7
addx.b d7,d7
bra.s .cont_copy
.next_cod2: moveq #13,d6
bsr.s get_bit2
add #255+15+6,d5
.do_copy: move d5,-(a7)
bne.s bigger
lea decrun_table2(pc),a4
moveq #2,d6
bsr.s get_bit2
cmp #5,d5
blt.s contus
addq #2,a7
subq #6,d5
bgt.s tablus
move.l a5,a4
blt.s .first4
addq #4,a4
.first4: moveq #1,d6
bsr.s get_bit2
tablus2: move.b 0(a4,d5.w),-(a5)
bra.s make_jnk
get_bit2: clr d5
.get_bits: add.b d7,d7
beq.s .empty
.cont: addx d5,d5
dbf d6,.get_bits
tst d5
rts
.empty: move.b -(a6),d7
addx.b d7,d7
bra.s .cont
bigger: lea decrun_table(pc),a4
cont: moveq #2,d6
bsr.s get_bit2
contus: move d5,d4
move.b 14(a4,d4.w),d6
ext d6
bsr.s get_bit2
add d4,d4
beq.s .first
add -2(a4,d4.w),d5
.first: lea 1(a5,d5.w),a4
move (a7)+,d5
move.b -(a4),-(a5)
.copy_same: move.b -(a4),-(a5)
dbf d5,.copy_same
make_jnk: moveq #11,d6
moveq #11,d5
take_jnk: add.b d7,d7
beq.s empty
cont_jnk: dbcc d6,take_jnk
bcs.s next_cod
sub d6,d5
bra.s copy_jnk1
next_cod: moveq #7,d6
bsr.s get_bit2
beq.s .next_cod1
addq #8,d5
addq #3,d5
bra.s copy_jnk1
.next_cod1: moveq #2,d6
bsr.s get_bit2
swap d5
moveq #15,d6
bsr.s get_bit2
addq.l #8,d5
addq.l #3,d5
copy_jnk1: subq #1,d5
bmi.s .end_word
moveq #1,d6
swap d6
.copy_jnk: move.b -(a6),-(a5)
dbf d5,.copy_jnk
sub.l d6,d5
bpl.s .copy_jnk
.end_word: cmp.l a6,a0
.decrunch: bne decrunch
cmp.b #$80,d7
bne.s .decrunch
ifne PIC_ALGO
move.l (a7)+,a0
bsr decod_picture
endc
ifne RESTORE_M
movem.l (a7)+,a3-a4
endc
move.l (a7)+,d0
bsr copy_decrun
ifne RESTORE_M
moveq #DEC_MARGE+9,d0
.restore_m: move.b -(a3),(a4)+
dbf d0,.restore_m
endc
no_crunched: movem.l (a7)+,d0-a6
rts
empty: move.b -(a6),d7
addx.b d7,d7
bra.s cont_jnk
decrun_table: dc.w 32,32+64,32+64+256,32+64+256+512,32+64+256+512+1024
dc.w 32+64+256+512+1024+2048,32+64+256+512+1024+2048+4096
dc.b 4,5,7,8,9,10,11,12
decrun_table2: dc.w 32,32+64,32+64+128,32+64+128+256
dc.w 32+64+128+256+512,32+64+128+256+512*2
dc.w 32+64+128+256+512*3
dc.b 4,5,6,7,8,8
tablus_table: dc.b $60,$20,$10,$8
ifne PIC_ALGO
decod_picture: move -(a0),d7
clr (a0)
.next_picture: dbf d7,.decod_algo
rts
.decod_algo: move.l -(a0),d0
clr.l (a0)
lea 0(a5,d0.l),a1
lea $7d00(a1),a2
.next_planes: moveq #3,d6
.next_word: move (a1)+,d0
moveq #3,d5
.next_bits: add d0,d0
addx d1,d1
add d0,d0
addx d2,d2
add d0,d0
addx d3,d3
add d0,d0
addx d4,d4
dbf d5,.next_bits
dbf d6,.next_word
movem d1-d4,-8(a1)
cmp.l a1,a2
bne.s .next_planes
bra.s .next_picture
endc
copy_decrun: lsr.l #4,d0
lea -12(a6),a6
.copy_decrun: rept 4
move.l (a5)+,(a6)+
endr
dbf d0,.copy_decrun
rts
ifne RESTORE_M
buff_marg: dcb.b DEC_MARGE+10,0
endc | 0 | 0.954446 | 1 | 0.954446 | game-dev | MEDIA | 0.577014 | game-dev | 0.978254 | 1 | 0.978254 |
twhl-community/halflife-updated | 6,255 | game_shared/filesystem_utils.h | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#pragma once
/**
* @file
*
* Functions, types and globals to load and use the GoldSource engine filesystem interface to read and write files.
* See the VDC for information on which search paths exist to be used as path IDs:
* https://developer.valvesoftware.com/wiki/GoldSource_SteamPipe_Directories
*/
#include <cstddef>
#include <ctime>
#include <string>
#include <vector>
#include "Platform.h"
#include "FileSystem.h"
#ifdef WIN32
constexpr char DefaultPathSeparatorChar = '\\';
constexpr char AlternatePathSeparatorChar = '/';
#else
constexpr char DefaultPathSeparatorChar = '/';
constexpr char AlternatePathSeparatorChar = '\\';
#endif
inline IFileSystem* g_pFileSystem = nullptr;
bool FileSystem_LoadFileSystem();
void FileSystem_FreeFileSystem();
/**
* @brief Returns the mod directory name. Only valid to call after calling FileSystem_LoadFileSystem.
*/
const std::string& FileSystem_GetModDirectoryName();
/**
* @brief Replaces occurrences of ::AlternatePathSeparatorChar with ::DefaultPathSeparatorChar.
*/
void FileSystem_FixSlashes(std::string& fileName);
/**
* @brief Returns the last modification time of the given file.
* Filenames are relative to the game directory.
*/
time_t FileSystem_GetFileTime(const char* fileName);
/**
* @brief Compares the file time of the given files located in the mod directory.
* @details Needed because IFileSystem::GetFileTime() does not provide a path ID parameter.
* @param filename1 First file to compare.
* @param filename2 Second file to compare.
* @param[out] iCompare Stores the result of the comparison.
* -@c 0 if equal
* -@c -1 if @p filename2 is newer than @p filename1
* -@c 1 if @p filename1 is newer than @p filename2
* @return @c true if filetimes were retrieved, false otherwise.
*/
bool FileSystem_CompareFileTime(const char* filename1, const char* filename2, int* iCompare);
enum class FileContentFormat
{
Binary = 0,
Text = 1
};
/**
* @brief Loads a file from disk into a buffer.
*
* @details If the returned buffer contains text data and @p format is @c FileContentFormat::Text it is safe to cast the data pointer to char*:
* @code{.cpp}
* auto text = reinterpret_cast<char*>(buffer.data());
* @endcode
*
* @param fileName Name of the file to load.
* @param format If @c FileContentFormat::Text, a null terminator will be appended.
* @param pathID If not null, only looks for the file in this search path.
* @return If the file was successfully loaded the contents of the buffer,
* with a zero byte (null terminator) appended to it if @p format is @c FileContentFormat::Text.
* If the file could not be loaded an empty buffer is returned.
*/
std::vector<std::byte> FileSystem_LoadFileIntoBuffer(const char* fileName, FileContentFormat format, const char* pathID = nullptr);
/**
* @brief Writes a text file to disk.
* @param fileName Name of the file to write to.
* @param text Null-terminated text to write. The null terminator is not written to disk.
* @param pathID If not null, writes to a writable location assigned to the given search path.
* Otherwise the first writable location will be used (in practice this will be the mod directory).
* If no writable location exists no file will be written to.
* @return True if the file was written, false if an error occurred.
*/
bool FileSystem_WriteTextToFile(const char* fileName, const char* text, const char* pathID = nullptr);
/**
* @brief Returns @c true if the current game directory is that of a Valve game.
* Any directory whose name starts with that of a Valve game's directory name is considered to be one, matching Steam's behavior.
*/
bool UTIL_IsValveGameDirectory();
/**
* @brief Helper class to automatically close the file handle associated with a file.
*/
class FSFile
{
public:
FSFile() noexcept = default;
FSFile(const char* fileName, const char* options, const char* pathID = nullptr);
FSFile(FSFile&& other) noexcept
: _handle(other._handle)
{
other._handle = FILESYSTEM_INVALID_HANDLE;
}
FSFile& operator=(FSFile&& other) noexcept
{
if (this != &other)
{
Close();
_handle = other._handle;
other._handle = FILESYSTEM_INVALID_HANDLE;
}
return *this;
}
FSFile(const FSFile&) = delete;
FSFile& operator=(const FSFile&) = delete;
~FSFile();
constexpr bool IsOpen() const { return _handle != FILESYSTEM_INVALID_HANDLE; }
std::size_t Size() const { return static_cast<std::size_t>(g_pFileSystem->Size(_handle)); }
bool Open(const char* filename, const char* options, const char* pathID = nullptr);
void Close();
void Seek(int pos, FileSystemSeek_t seekType);
int Read(void* dest, int size);
int Write(const void* input, int size);
template <typename... Args>
int Printf(const char* format, Args&&... args)
{
return g_pFileSystem->FPrintf(_handle, format, std::forward<Args>(args)...);
}
constexpr operator bool() const { return IsOpen(); }
private:
FileHandle_t _handle = FILESYSTEM_INVALID_HANDLE;
};
inline FSFile::FSFile(const char* filename, const char* options, const char* pathID)
{
Open(filename, options, pathID);
}
inline FSFile::~FSFile()
{
Close();
}
inline bool FSFile::Open(const char* filename, const char* options, const char* pathID)
{
Close();
_handle = g_pFileSystem->Open(filename, options, pathID);
return IsOpen();
}
inline void FSFile::Close()
{
if (IsOpen())
{
g_pFileSystem->Close(_handle);
_handle = FILESYSTEM_INVALID_HANDLE;
}
}
inline void FSFile::Seek(int pos, FileSystemSeek_t seekType)
{
if (IsOpen())
{
g_pFileSystem->Seek(_handle, pos, seekType);
}
}
inline int FSFile::Read(void* dest, int size)
{
return g_pFileSystem->Read(dest, size, _handle);
}
inline int FSFile::Write(const void* input, int size)
{
return g_pFileSystem->Write(input, size, _handle);
}
| 0 | 0.946451 | 1 | 0.946451 | game-dev | MEDIA | 0.294068 | game-dev | 0.60037 | 1 | 0.60037 |
tulustul/ants-sandbox | 7,516 | src/ui/colonies/ColonyForm.vue | <script setup lang="ts">
import { inject, ref, watch } from "vue";
import { useIntervalFn } from "@vueuse/core";
import { AntType, getAntMaxEnergy } from "@/simulation";
import { state } from "@/ui/state";
import { FieldGroup, Slider } from "@/ui/forms";
import { vExplode } from "@/ui/widgets";
import type { Simulation } from "@/ui/simulation";
import { Tooltip } from "@/ui/widgets";
const simulation = inject<Simulation>("simulation")!;
let colony = getTrackedColony()!;
const stats = ref(colony.stats);
const warCoef = ref(colony.warCoef);
const aggresiveness = ref(colony.aggresiveness);
const antsMeanEnergy = ref(colony.antsMeanEnergy);
const freedom = ref(colony.freedom);
watch(state, () => {
if (!state.trackedColony) {
return;
}
colony = getTrackedColony()!;
aggresiveness.value = colony.aggresiveness;
antsMeanEnergy.value = colony.antsMeanEnergy;
freedom.value = colony.freedom;
});
watch(aggresiveness, () => (colony.aggresiveness = aggresiveness.value));
watch(antsMeanEnergy, () => {
colony.antsMeanEnergy = antsMeanEnergy.value;
for (const ant of colony.ants) {
ant.maxEnergy = getAntMaxEnergy(colony);
ant.energy = Math.min(ant.energy, ant.maxEnergy);
ant.energyReturnThreshold = ant.maxEnergy / 2;
}
});
watch(freedom, () => (colony.freedom = freedom.value));
useIntervalFn(() => {
stats.value = { ...colony.stats };
warCoef.value = colony.warCoef;
}, 200);
function getTrackedColony() {
return simulation.garden.colonies.find(
(colony) => colony.id === state.trackedColony
);
}
function destroyColony() {
colony.destroy();
state.trackedColony = null;
}
function addFood() {
colony.addFood(1000);
}
function removeFood() {
colony.removeFood(1000);
}
function addWorkers() {
(colony as any).addAnts(AntType.worker, 100);
}
function removeWorkers() {
colony.killAnts(AntType.worker, 100);
}
function addSoldiers() {
colony.addAnts(AntType.soldier, 25);
}
function removeSoldiers() {
colony.killAnts(AntType.soldier, 25);
}
function move() {
state.movingColony = !state.movingColony;
}
</script>
<template>
<div class="column">
<div class="row">
<button class="btn grow" :onclick="move">
<span v-if="state.movingColony">Click on the map...</span>
<span v-else>Move</span>
</button>
<button class="btn btn-danger grow" :onclick="destroyColony">
Destroy
</button>
</div>
<FieldGroup label="Food">
<div class="row space-between">
<div class="row">
<Tooltip>
Food currently stored in the nest.<br />
Food is used to feed ants when they visit the nest. When enough food
is accumulated, a new ant is being born. When the ants cannot be
fed, they eventually die of hunger.
</Tooltip>
<span
>Stored <strong>{{ stats.food.toFixed(0) }}</strong></span
>
</div>
<div class="row">
<span
>Total <strong>{{ stats.totalFood.toFixed(0) }}</strong></span
>
<Tooltip> Total amount of food ever produced by the colony. </Tooltip>
</div>
</div>
<div class="row">
<button class="btn btn-primary grow" v-explode :onclick="addFood">
Add 1000 food
</button>
<button class="btn btn-danger grow" v-explode :onclick="removeFood">
Remove 1000 food
</button>
</div>
</FieldGroup>
<FieldGroup label="Ants">
<div class="row space-between">
<div class="row">
<Tooltip>
Workers seek for food, collect it and bring it to the nest. They
cannot fight with other ants. When they see the enemy they flee to
the nest.
</Tooltip>
<span
>Workers <strong>{{ stats.workers }}</strong></span
>
</div>
<div class="row">
<span
>Soldiers <strong>{{ stats.soldiers }}</strong></span
>
<Tooltip>
The rate of soldiers birth depends on war coefficient. They follow
"to enemy" pheromone and seek for enemies. Only soldiers can fight
other ants.
</Tooltip>
</div>
</div>
<div class="row">
<div class="column grow">
<button class="btn btn-primary grow" v-explode :onclick="addWorkers">
Add 100 workers
</button>
<button
class="btn btn-danger grow"
v-explode
:onclick="removeWorkers"
>
Kill 100 workers
</button>
</div>
<div class="column grow">
<button class="btn btn-primary grow" v-explode :onclick="addSoldiers">
Add 25 soldiers
</button>
<button
class="btn btn-danger grow"
v-explode
:onclick="removeSoldiers"
>
Kill 25 soldiers
</button>
</div>
</div>
</FieldGroup>
<FieldGroup label="Parameters">
<Slider
label="Aggresiveness"
v-model="aggresiveness"
:min="0"
:max="1"
:step="0.01"
tooltip="The higher the value the faster war coefficient increases and the slower it decays."
/>
<Slider
label="Mean ant energy"
v-model="antsMeanEnergy"
:min="0.1"
:max="10"
:step="0.1"
tooltip="Determines how much time the ants can spend without revisiting the nest. The ants die out of starvation if their energy falls to zero. Higher values are required for solving complex mazes or bigger maps."
/>
<Slider
label="Freedom"
v-model="freedom"
:min="0.001"
:max="0.1"
:step="0.001"
:default="0.003"
tooltip="The lower, the more chance the ant will choose the best possible path. Better don't touch it but might have to be adjusted for some scenarios."
/>
</FieldGroup>
<FieldGroup label="Stats">
<div class="row space-between">
<div class="row">
<Tooltip>
Total number of ants in the colony that every lived.
</Tooltip>
<span
>Total ants <strong>{{ stats.totalAnts }}</strong></span
>
</div>
<div class="row">
<span
>Starved ants <strong>{{ stats.starvedAnts }}</strong></span
>
<Tooltip> Number of ants that died because of starvation. </Tooltip>
</div>
</div>
<div class="row space-between">
<div class="row">
<Tooltip>
Number of ants in this colony that were killed by other ants.
</Tooltip>
<span
>Killed <strong>{{ stats.killedAnts }}</strong></span
>
</div>
<div class="row">
<span
>Kills <strong>{{ stats.killedEnemyAnts }}</strong></span
>
<Tooltip> Number of enemy ants killed by this colony. </Tooltip>
</div>
</div>
<div class="row">
<Tooltip>
Increases when the ant that saw an enemy visits the nest. Higher
values increase the chance of a soldier being born instead of a normal
worker. Takes values between 0 and 1.
</Tooltip>
<span
>War coefficient <strong>{{ warCoef.toFixed(3) }}</strong></span
>
</div>
</FieldGroup>
</div>
</template>
<style></style>
| 0 | 0.786267 | 1 | 0.786267 | game-dev | MEDIA | 0.604158 | game-dev | 0.772348 | 1 | 0.772348 |
olliem5/ferox | 1,209 | src/main/java/com/olliem5/ferox/impl/modules/exploit/Portals.java | package com.olliem5.ferox.impl.modules.exploit;
import com.olliem5.ferox.api.module.Category;
import com.olliem5.ferox.api.module.FeroxModule;
import com.olliem5.ferox.api.module.Module;
import com.olliem5.ferox.api.setting.Setting;
import com.olliem5.ferox.impl.events.PacketEvent;
import com.olliem5.pace.annotation.PaceHandler;
import net.minecraft.network.play.client.CPacketConfirmTeleport;
/**
* @author olliem5
*/
@FeroxModule(name = "Portals", description = "Allows you to tweak how portals work", category = Category.Exploit)
public final class Portals extends Module {
public static final Setting<Boolean> godmode = new Setting<>("Godmode", "Gives you godmode when you go through a portal", false);
public static final Setting<Boolean> useGUIS = new Setting<>("Use GUI's", "Allows you to use GUI's in portals", true);
public Portals() {
this.addSettings(
godmode,
useGUIS
);
}
@PaceHandler
public void onPacketSend(PacketEvent.Send event) {
if (nullCheck()) return;
if (event.getPacket() instanceof CPacketConfirmTeleport && godmode.getValue()) {
event.setCancelled(true);
}
}
}
| 0 | 0.938351 | 1 | 0.938351 | game-dev | MEDIA | 0.832941 | game-dev | 0.896137 | 1 | 0.896137 |
oriches/Simple.Wpf.DataGrid | 2,747 | Simple.Wpf.DataGrid/Extensions/MemoryExtensions.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Simple.Wpf.DataGrid.Models;
namespace Simple.Wpf.DataGrid.Extensions
{
public static class MemoryExtensions
{
private static readonly IDictionary<MemoryUnits, string> UnitsAsString = new Dictionary<MemoryUnits, string>();
private static readonly IDictionary<MemoryUnits, decimal> UnitsMultiplier =
new Dictionary<MemoryUnits, decimal>();
private static readonly Type MemoryUnitsType = typeof(MemoryUnits);
public static string WorkingSetPrivateAsString(this Memory memory)
{
var valueAsString = decimal.Round(memory.WorkingSetPrivate * GetMultiplier(MemoryUnits.Mega), 2)
.ToString(CultureInfo.InvariantCulture);
return valueAsString + " " + GetUnitString(MemoryUnits.Mega);
}
public static string ManagedAsString(this Memory memory)
{
var valueAsString = decimal.Round(memory.Managed * GetMultiplier(MemoryUnits.Mega), 2)
.ToString(CultureInfo.InvariantCulture);
return valueAsString + " " + GetUnitString(MemoryUnits.Mega);
}
private static decimal GetMultiplier(MemoryUnits units)
{
if (UnitsMultiplier.TryGetValue(units, out var unitsMultiplier)) return unitsMultiplier;
unitsMultiplier = 1 / Convert.ToDecimal((int) units);
UnitsMultiplier.Add(units, unitsMultiplier);
return unitsMultiplier;
}
private static string GetUnitString(MemoryUnits units)
{
if (UnitsAsString.TryGetValue(units, out var unitsString)) return unitsString;
string unitAsString;
switch (units)
{
case MemoryUnits.Bytes:
unitAsString = "Bytes";
break;
case MemoryUnits.Kilo:
unitAsString = "Kilo";
break;
case MemoryUnits.Mega:
unitAsString = "Mega";
break;
case MemoryUnits.Giga:
unitAsString = "Giga";
break;
default:
throw new ArgumentOutOfRangeException(nameof(units), @"Unknown units of memory!");
}
var memInfo = MemoryUnitsType.GetMember(unitAsString);
var attributes = memInfo[0]
.GetCustomAttributes(typeof(DescriptionAttribute), false);
unitsString = ((DescriptionAttribute) attributes[0]).Description;
UnitsAsString.Add(units, unitsString);
return unitsString;
}
}
} | 0 | 0.814477 | 1 | 0.814477 | game-dev | MEDIA | 0.213838 | game-dev | 0.634043 | 1 | 0.634043 |
binary-husky/unreal-map | 15,779 | Source/JsonxUtilities/Public/JsonxObjectConverter.h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Class.h"
#include "Serialization/JsonxTypes.h"
#include "Dom/JsonxObject.h"
#include "Serialization/JsonxReader.h"
#include "Serialization/JsonxSerializer.h"
#include "JsonxObjectWrapper.h"
/** Class that handles converting Jsonx objects to and from UStructs */
class JSONXUTILITIES_API FJsonxObjectConverter
{
public:
/** FName case insensitivity can make the casing of UPROPERTIES unpredictable. Attempt to standardize output. */
static FString StandardizeCase(const FString &StringIn);
/** Parse an FText from a json object (assumed to be of the form where keys are culture codes and values are strings) */
static bool GetTextFromObject(const TSharedRef<FJsonxObject>& Obj, FText& TextOut);
/** Convert a Jsonx value to text (takes some hints from the value name) */
static bool GetTextFromField(const FString& FieldName, const TSharedPtr<FJsonxValue>& FieldValue, FText& TextOut);
public: // UStruct -> JSONX
/**
* Optional callback that will be run when exporting a single property to Jsonx.
* If this returns a valid value it will be inserted into the export chain.
* If this returns nullptr or is not bound, it will try generic type-specific export behavior before falling back to outputting ExportText as a string.
*/
DECLARE_DELEGATE_RetVal_TwoParams(TSharedPtr<FJsonxValue>, CustomExportCallback, FProperty* /* Property */, const void* /* Value */);
/**
* Utility Export Callback for having object properties expanded to full Jsonx.
*/
UE_DEPRECATED(4.25, "ObjectJsonxCallback has been deprecated - please remove the usage of it from your project")
static TSharedPtr<FJsonxValue> ObjectJsonxCallback(FProperty* Property , const void* Value);
/**
* Templated version of UStructToJsonxObject to try and make most of the params. Also serves as an example use case
*
* @param InStruct The UStruct instance to read from
* @param ExportCb Optional callback to override export behavior, if this returns null it will fallback to the default
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @return FJsonxObject pointer. Invalid if an error occurred.
*/
template<typename InStructType>
static TSharedPtr<FJsonxObject> UStructToJsonxObject(const InStructType& InStruct, int64 CheckFlags = 0, int64 SkipFlags = 0, const CustomExportCallback* ExportCb = nullptr)
{
TSharedRef<FJsonxObject> JsonxObject = MakeShared<FJsonxObject>();
if (UStructToJsonxObject(InStructType::StaticStruct(), &InStruct, JsonxObject, CheckFlags, SkipFlags, ExportCb))
{
return JsonxObject;
}
return TSharedPtr<FJsonxObject>(); // something went wrong
}
/**
* Converts from a UStruct to a Jsonx Object, using exportText
*
* @param StructDefinition UStruct definition that is looked over for properties
* @param Struct The UStruct instance to copy out of
* @param JsonxObject Jsonx Object to be filled in with data from the ustruct
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param ExportCb Optional callback to override export behavior, if this returns null it will fallback to the default
*
* @return False if any properties failed to write
*/
static bool UStructToJsonxObject(const UStruct* StructDefinition, const void* Struct, TSharedRef<FJsonxObject> OutJsonxObject, int64 CheckFlags = 0, int64 SkipFlags = 0, const CustomExportCallback* ExportCb = nullptr);
/**
* Converts from a UStruct to a json string containing an object, using exportText
*
* @param StructDefinition UStruct definition that is looked over for properties
* @param Struct The UStruct instance to copy out of
* @param JsonxObject Jsonx Object to be filled in with data from the ustruct
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param Indent How many tabs to add to the json serializer
* @param ExportCb Optional callback to override export behavior, if this returns null it will fallback to the default
* @param bPrettyPrint Option to use pretty print (e.g., adds line endings) or condensed print
*
* @return False if any properties failed to write
*/
static bool UStructToJsonxObjectString(const UStruct* StructDefinition, const void* Struct, FString& OutJsonxString, int64 CheckFlags = 0, int64 SkipFlags = 0, int32 Indent = 0, const CustomExportCallback* ExportCb = nullptr, bool bPrettyPrint = true);
/**
* Templated version; Converts from a UStruct to a json string containing an object, using exportText
*
* @param Struct The UStruct instance to copy out of
* @param JsonxObject Jsonx Object to be filled in with data from the ustruct
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param Indent How many tabs to add to the json serializer
* @param ExportCb Optional callback to override export behavior, if this returns null it will fallback to the default
* @param bPrettyPrint Option to use pretty print (e.g., adds line endings) or condensed print
*
* @return False if any properties failed to write
*/
template<typename InStructType>
static bool UStructToJsonxObjectString(const InStructType& InStruct, FString& OutJsonxString, int64 CheckFlags = 0, int64 SkipFlags = 0, int32 Indent = 0, const CustomExportCallback* ExportCb = nullptr, bool bPrettyPrint = true)
{
return UStructToJsonxObjectString(InStructType::StaticStruct(), &InStruct, OutJsonxString, CheckFlags, SkipFlags, Indent, ExportCb, bPrettyPrint);
}
/**
* Wrapper to UStructToJsonxObjectString that allows a print policy to be specified.
*/
template<typename CharType, template<typename> class PrintPolicy>
static bool UStructToFormattedJsonxObjectString(const UStruct* StructDefinition, const void* Struct, FString& OutJsonxString, int64 CheckFlags = 0, int64 SkipFlags = 0, int32 Indent = 0, const CustomExportCallback* ExportCb = nullptr)
{
TSharedRef<FJsonxObject> JsonxObject = MakeShareable(new FJsonxObject());
if (UStructToJsonxObject(StructDefinition, Struct, JsonxObject, CheckFlags, SkipFlags, ExportCb))
{
TSharedRef<TJsonxWriter<CharType, PrintPolicy<CharType>>> JsonxWriter = TJsonxWriterFactory<CharType, PrintPolicy<CharType>>::Create(&OutJsonxString, Indent);
if (FJsonxSerializer::Serialize(JsonxObject, JsonxWriter))
{
JsonxWriter->Close();
return true;
}
else
{
UE_LOG(LogJsonx, Warning, TEXT("UStructToFormattedObjectString - Unable to write out json"));
JsonxWriter->Close();
}
}
return false;
}
/**
* Converts from a UStruct to a set of json attributes (possibly from within a JsonxObject)
*
* @param StructDefinition UStruct definition that is looked over for properties
* @param Struct The UStruct instance to copy out of
* @param JsonxAttributes Map of attributes to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param ExportCb Optional callback to override export behavior, if this returns null it will fallback to the default
*
* @return False if any properties failed to write
*/
static bool UStructToJsonxAttributes(const UStruct* StructDefinition, const void* Struct, TMap< FString, TSharedPtr<FJsonxValue> >& OutJsonxAttributes, int64 CheckFlags = 0, int64 SkipFlags = 0, const CustomExportCallback* ExportCb = nullptr);
/* * Converts from a FProperty to a Jsonx Value using exportText
*
* @param Property The property to export
* @param Value Pointer to the value of the property
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
* @param ExportCb Optional callback to override export behavior, if this returns null it will fallback to the default
* @param OuterProperty If applicable, the Array/Set/Map Property that contains this property
*
* @return The constructed JsonxValue from the property
*/
static TSharedPtr<FJsonxValue> UPropertyToJsonxValue(FProperty* Property, const void* Value, int64 CheckFlags = 0, int64 SkipFlags = 0, const CustomExportCallback* ExportCb = nullptr, FProperty* OuterProperty = nullptr);
public: // JSONX -> UStruct
/**
* Converts from a Jsonx Object to a UStruct, using importText
*
* @param JsonxObject Jsonx Object to copy data out of
* @param StructDefinition UStruct definition that is looked over for properties
* @param Struct The UStruct instance to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
*
* @return False if any properties matched but failed to deserialize
*/
static bool JsonxObjectToUStruct(const TSharedRef<FJsonxObject>& JsonxObject, const UStruct* StructDefinition, void* OutStruct, int64 CheckFlags = 0, int64 SkipFlags = 0);
/**
* Templated version of JsonxObjectToUStruct
*
* @param JsonxObject Jsonx Object to copy data out of
* @param OutStruct The UStruct instance to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
*
* @return False if any properties matched but failed to deserialize
*/
template<typename OutStructType>
static bool JsonxObjectToUStruct(const TSharedRef<FJsonxObject>& JsonxObject, OutStructType* OutStruct, int64 CheckFlags = 0, int64 SkipFlags = 0)
{
return JsonxObjectToUStruct(JsonxObject, OutStructType::StaticStruct(), OutStruct, CheckFlags, SkipFlags);
}
/**
* Converts a set of json attributes (possibly from within a JsonxObject) to a UStruct, using importText
*
* @param JsonxAttributes Jsonx Object to copy data out of
* @param StructDefinition UStruct definition that is looked over for properties
* @param OutStruct The UStruct instance to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
*
* @return False if any properties matched but failed to deserialize
*/
static bool JsonxAttributesToUStruct(const TMap< FString, TSharedPtr<FJsonxValue> >& JsonxAttributes, const UStruct* StructDefinition, void* OutStruct, int64 CheckFlags = 0, int64 SkipFlags = 0);
/**
* Converts a single JsonxValue to the corresponding FProperty (this may recurse if the property is a UStruct for instance).
*
* @param JsonxValue The value to assign to this property
* @param Property The FProperty definition of the property we're setting.
* @param OutValue Pointer to the property instance to be modified.
* @param CheckFlags Only convert sub-properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip sub-properties that match any of these flags
*
* @return False if the property failed to serialize
*/
static bool JsonxValueToUProperty(const TSharedPtr<FJsonxValue>& JsonxValue, FProperty* Property, void* OutValue, int64 CheckFlags = 0, int64 SkipFlags = 0);
/**
* Converts from a json string containing an object to a UStruct
*
* @param JsonxString String containing JSONX formatted data.
* @param OutStruct The UStruct instance to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags
*
* @return False if any properties matched but failed to deserialize
*/
template<typename OutStructType>
static bool JsonxObjectStringToUStruct(const FString& JsonxString, OutStructType* OutStruct, int64 CheckFlags = 0, int64 SkipFlags = 0)
{
TSharedPtr<FJsonxObject> JsonxObject;
TSharedRef<TJsonxReader<> > JsonxReader = TJsonxReaderFactory<>::Create(JsonxString);
if (!FJsonxSerializer::Deserialize(JsonxReader, JsonxObject) || !JsonxObject.IsValid())
{
UE_LOG(LogJsonx, Warning, TEXT("JsonxObjectStringToUStruct - Unable to parse json=[%s]"), *JsonxString);
return false;
}
if (!FJsonxObjectConverter::JsonxObjectToUStruct(JsonxObject.ToSharedRef(), OutStruct, CheckFlags, SkipFlags))
{
UE_LOG(LogJsonx, Warning, TEXT("JsonxObjectStringToUStruct - Unable to deserialize. json=[%s]"), *JsonxString);
return false;
}
return true;
}
/**
* Converts from a json string containing an array to an array of UStructs
*
* @param JsonxString String containing JSONX formatted data.
* @param OutStructArray The UStruct array to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags.
*
* @return False if any properties matched but failed to deserialize.
*/
template<typename OutStructType>
static bool JsonxArrayStringToUStruct(const FString& JsonxString, TArray<OutStructType>* OutStructArray, int64 CheckFlags = 0, int64 SkipFlags = 0)
{
TArray<TSharedPtr<FJsonxValue> > JsonxArray;
TSharedRef<TJsonxReader<> > JsonxReader = TJsonxReaderFactory<>::Create(JsonxString);
if (!FJsonxSerializer::Deserialize(JsonxReader, JsonxArray))
{
UE_LOG(LogJsonx, Warning, TEXT("JsonxArrayStringToUStruct - Unable to parse. json=[%s]"), *JsonxString);
return false;
}
if (!JsonxArrayToUStruct(JsonxArray, OutStructArray, CheckFlags, SkipFlags))
{
UE_LOG(LogJsonx, Warning, TEXT("JsonxArrayStringToUStruct - Error parsing one of the elements. json=[%s]"), *JsonxString);
return false;
}
return true;
}
/**
* Converts from an array of json values to an array of UStructs.
*
* @param JsonxArray Array containing json values to convert.
* @param OutStructArray The UStruct array to copy in to
* @param CheckFlags Only convert properties that match at least one of these flags. If 0 check all properties.
* @param SkipFlags Skip properties that match any of these flags.
*
* @return False if any of the matching elements are not an object, or if one of the matching elements could not be converted to the specified UStruct type.
*/
template<typename OutStructType>
static bool JsonxArrayToUStruct(const TArray<TSharedPtr<FJsonxValue>>& JsonxArray, TArray<OutStructType>* OutStructArray, int64 CheckFlags = 0, int64 SkipFlags = 0)
{
OutStructArray->SetNum(JsonxArray.Num());
for (int32 i = 0; i < JsonxArray.Num(); ++i)
{
const auto& Value = JsonxArray[i];
if (Value->Type != EJsonx::Object)
{
UE_LOG(LogJsonx, Warning, TEXT("JsonxArrayToUStruct - Array element [%i] was not an object."), i);
return false;
}
if (!FJsonxObjectConverter::JsonxObjectToUStruct(Value->AsObject().ToSharedRef(), OutStructType::StaticStruct(), &(*OutStructArray)[i], CheckFlags, SkipFlags))
{
UE_LOG(LogJsonx, Warning, TEXT("JsonxArrayToUStruct - Unable to convert element [%i]."), i);
return false;
}
}
return true;
}
/*
* Parses text arguments from Jsonx into a map
* @param JsonxObject Object to parse arguments from
*/
static FFormatNamedArguments ParseTextArgumentsFromJsonx(const TSharedPtr<const FJsonxObject>& JsonxObject);
};
| 0 | 0.745975 | 1 | 0.745975 | game-dev | MEDIA | 0.294299 | game-dev | 0.680444 | 1 | 0.680444 |
spartanoah/acrimony-client | 2,128 | net/minecraft/world/chunk/storage/RegionFileCache.java | /*
* Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty).
*/
package net.minecraft.world.chunk.storage;
import com.google.common.collect.Maps;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import net.minecraft.world.chunk.storage.RegionFile;
public class RegionFileCache {
private static final Map<File, RegionFile> regionsByFilename = Maps.newHashMap();
public static synchronized RegionFile createOrLoadRegionFile(File worldDir, int chunkX, int chunkZ) {
File file1 = new File(worldDir, "region");
File file2 = new File(file1, "r." + (chunkX >> 5) + "." + (chunkZ >> 5) + ".mca");
RegionFile regionfile = regionsByFilename.get(file2);
if (regionfile != null) {
return regionfile;
}
if (!file1.exists()) {
file1.mkdirs();
}
if (regionsByFilename.size() >= 256) {
RegionFileCache.clearRegionFileReferences();
}
RegionFile regionfile1 = new RegionFile(file2);
regionsByFilename.put(file2, regionfile1);
return regionfile1;
}
public static synchronized void clearRegionFileReferences() {
for (RegionFile regionfile : regionsByFilename.values()) {
try {
if (regionfile == null) continue;
regionfile.close();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
regionsByFilename.clear();
}
public static DataInputStream getChunkInputStream(File worldDir, int chunkX, int chunkZ) {
RegionFile regionfile = RegionFileCache.createOrLoadRegionFile(worldDir, chunkX, chunkZ);
return regionfile.getChunkDataInputStream(chunkX & 0x1F, chunkZ & 0x1F);
}
public static DataOutputStream getChunkOutputStream(File worldDir, int chunkX, int chunkZ) {
RegionFile regionfile = RegionFileCache.createOrLoadRegionFile(worldDir, chunkX, chunkZ);
return regionfile.getChunkDataOutputStream(chunkX & 0x1F, chunkZ & 0x1F);
}
}
| 0 | 0.705365 | 1 | 0.705365 | game-dev | MEDIA | 0.902524 | game-dev | 0.771643 | 1 | 0.771643 |
GaijinEntertainment/DagorEngine | 9,819 | samples/dngSceneViewer/prog/scripts/das/input/charctrl_input.das | require app
require ecs
require math.base
require das.input.input_events
require DagorInput
require DagorSystem
require DagorMath
require DagorMathUtils
require das.character_controller.charctrl_state
let VIEW_HT_STAND = 1.75f
let VIEW_HT_SPRINT = VIEW_HT_STAND - 0.2f
let VIEW_HT_CROUCH = VIEW_HT_STAND * 0.55f
let VIEW_HT_CRAWL = VIEW_HT_STAND
let CAP_OFS_Y_STAND = 0.5f
let CAP_OFS_Y_SPRINT = 0.55f
let CAP_OFS_Y_CROUCH = 0.3f
let CAP_OFS_Y_CRAWL = 0.50f
let MOVE_VEL_STAND = 13.f / 3.6f
let MOVE_VEL_SPRINT = MOVE_VEL_STAND * 2.0f
let MOVE_VEL_CROUCH = MOVE_VEL_STAND * 0.4f
let MOVE_VEL_CRAWL = MOVE_VEL_STAND * 0.2f
let JUMP_HT_STAND = 0.7f
let JUMP_HT_SPRINT = 0.5f
let JUMP_HT_CROUCH = 0.3f
def vel0_for_jump_ht(ht : float)
return sqrt(2.f * 9.81f * ht)
def init(var move : uint16&;
var look : uint16&;
var jump : uint16&;
var sprint : uint16&;
var crouch : uint16&;
var crawl : uint16&)
move = get_action_handle("CharCtrl.Move", TYPEGRP_STICK)
look = get_action_handle("CharCtrl.Look", TYPEGRP_STICK)
jump = get_action_handle("CharCtrl.Jump", TYPEGRP_DIGITAL)
sprint = get_action_handle("CharCtrl.Sprint", TYPEGRP_DIGITAL)
crouch = get_action_handle("CharCtrl.Crouch", TYPEGRP_DIGITAL)
crawl = get_action_handle("CharCtrl.Crawl", TYPEGRP_DIGITAL)
let charctrlSetHandle = get_action_set_handle("CharCtrl")
if charctrlSetHandle != BAD_ACTION_SET_HANDLE
activate_action_set(charctrlSetHandle, true)
def reset(var move : uint16&;
var look : uint16&;
var jump : uint16&;
var sprint : uint16&;
var crouch : uint16&;
var crawl : uint16&)
move = BAD_ACTION_HANDLE
look = BAD_ACTION_HANDLE
jump = BAD_ACTION_HANDLE
sprint = BAD_ACTION_HANDLE
crouch = BAD_ACTION_HANDLE
crawl = BAD_ACTION_HANDLE
let charctrlSetHandle = get_action_set_handle("CharCtrl")
if charctrlSetHandle != BAD_ACTION_SET_HANDLE
activate_action_set(charctrlSetHandle, false)
[es(tag=input, on_appear, REQUIRE=charctrl_input)]
def charctrl_input_appear_es(evt : Event; eid : EntityId;
transform : float3x4 const?;
var charctrl__look_ang : float2&;
var charctrl_input__aMove : uint16&;
var charctrl_input__aLook : uint16&;
var charctrl_input__aJump : uint16&;
var charctrl_input__aSprint : uint16&;
var charctrl_input__aCrouch : uint16&;
var charctrl_input__aCrawl : uint16&)
let thisEid = eid
let found = ecs::find_query() <| $ [es(REQUIRE=charctrl_input, REQUIRE_NOT=deadEntity)] (eid : EntityId)
return eid != thisEid
if found
logerr("Attempt to create > 1 charctrl_input component")
charctrl__look_ang = float2(euler_from_quat(float4(math::quat(transform ?? IDENT_TM))).xz)
print("quat={float4(math::quat(transform ?? IDENT_TM))} charctrl__look_ang={charctrl__look_ang}")
init(charctrl_input__aMove, charctrl_input__aLook, charctrl_input__aJump,
charctrl_input__aSprint, charctrl_input__aCrouch, charctrl_input__aCrawl)
[es(tag=input, on_disappear, REQUIRE=charctrl_input)]
def charctrl_input_destroyed_es(evt : Event;
var charctrl_input__aMove : uint16&;
var charctrl_input__aLook : uint16&;
var charctrl_input__aJump : uint16&;
var charctrl_input__aSprint : uint16&;
var charctrl_input__aCrouch : uint16&;
var charctrl_input__aCrawl : uint16&)
reset(charctrl_input__aMove, charctrl_input__aLook, charctrl_input__aJump,
charctrl_input__aSprint, charctrl_input__aCrouch, charctrl_input__aCrawl)
[es(tag=input, REQUIRE=charctrl_input)]
def charctrl_input_init_es(evt : EventDaInputInit; input__enabled : bool;
var charctrl_input__aMove : uint16&;
var charctrl_input__aLook : uint16&;
var charctrl_input__aJump : uint16&;
var charctrl_input__aSprint : uint16&;
var charctrl_input__aCrouch : uint16&;
var charctrl_input__aCrawl : uint16&)
if !input__enabled
return
if evt.init
init(charctrl_input__aMove, charctrl_input__aLook, charctrl_input__aJump,
charctrl_input__aSprint, charctrl_input__aCrouch, charctrl_input__aCrawl)
else
reset(charctrl_input__aMove, charctrl_input__aLook, charctrl_input__aJump,
charctrl_input__aSprint, charctrl_input__aCrouch, charctrl_input__aCrawl)
[es(tag=input, REQUIRE=charctrl_input)]
def charctrl_input_es(info : UpdateStageUpdateInput; input__enabled : bool;
charctrl_input__aMove : uint16;
charctrl_input__aLook : uint16;
charctrl_input__aJump : uint16;
charctrl_input__aSprint : uint16;
charctrl_input__aCrouch : uint16;
charctrl_input__aCrawl : uint16;
var charctrl__state : int3&; // CCStandType, CCMoveType, CCStateFlag
var charctrl__move_vel : float2&;
var charctrl__look_ang : float2&;
var charctrl__jump_vel : float&;
var charctrl__capsule_dir : float3&;
var charctrl__capsule_ofs : float2&;
var charctrl__view_ht : float&)
let morph_viscosity = 0.17f
let move_viscosity = 0.08f
let dt = info.dt
if !input__enabled
charctrl__move_vel.x = approach(charctrl__move_vel.x, 0.f, dt, move_viscosity)
charctrl__move_vel.y = approach(charctrl__move_vel.y, 0.f, dt, move_viscosity)
charctrl__state.xy = int2(int(CCStandType.ESS_STAND), int(CCMoveType.EMS_STAND))
return
let aLook = get_analog_stick_action_state(charctrl_input__aLook)
if aLook.bActive
charctrl__look_ang.x = charctrl__look_ang.x + aLook.x
charctrl__look_ang.y = clamp(norm_s_ang(charctrl__look_ang.y + aLook.y), -70.f * PI / 180.f, +70.f * PI / 180.f)
let aSprint = get_digital_action_state(charctrl_input__aSprint)
let aCrouch = get_digital_action_state(charctrl_input__aCrouch)
let aCrawl = get_digital_action_state(charctrl_input__aCrawl)
let aJump = get_digital_action_state(charctrl_input__aJump)
var move_vel : float = MOVE_VEL_STAND
if aSprint.bActive && aSprint.bState
move_vel = MOVE_VEL_SPRINT
charctrl__view_ht = approach(charctrl__view_ht, VIEW_HT_SPRINT, dt, morph_viscosity)
charctrl__capsule_dir = normalize(approach(charctrl__capsule_dir, normalize(float3(0.f, 1.f, 0.1f)), dt, morph_viscosity))
charctrl__capsule_ofs = approach(charctrl__capsule_ofs, float2(0.f, CAP_OFS_Y_SPRINT), dt, morph_viscosity)
charctrl__jump_vel = aJump.bActive && aJump.bState && !(aCrawl.bActive && aCrawl.bState) ? vel0_for_jump_ht(JUMP_HT_SPRINT) : 0.f
charctrl__state.x = int(CCStandType.ESS_STAND)
charctrl__state.y = int(CCMoveType.EMS_SPRINT)
elif aCrouch.bActive && aCrouch.bState
move_vel = MOVE_VEL_CROUCH
charctrl__view_ht = approach(charctrl__view_ht, VIEW_HT_CROUCH, dt, morph_viscosity)
charctrl__capsule_dir = normalize(approach(charctrl__capsule_dir, float3(0.f, 1.f, 0.f), dt, morph_viscosity))
charctrl__capsule_ofs = approach(charctrl__capsule_ofs, float2(0.f, CAP_OFS_Y_CROUCH), dt, morph_viscosity)
charctrl__jump_vel = aJump.bActive && aJump.bState && !(aCrawl.bActive && aCrawl.bState) ? vel0_for_jump_ht(JUMP_HT_CROUCH) : 0.f
charctrl__state.x = int(CCStandType.ESS_CROUCH)
charctrl__state.y = int(CCMoveType.EMS_WALK)
elif aCrawl.bActive && aCrawl.bState
move_vel = MOVE_VEL_CRAWL
charctrl__view_ht = approach(charctrl__view_ht, VIEW_HT_CRAWL, dt, morph_viscosity)
charctrl__capsule_dir = normalize(approach(charctrl__capsule_dir, float3(0.f, 0.f, 1.f), dt, morph_viscosity))
charctrl__capsule_ofs = approach(charctrl__capsule_ofs, float2(0.5f, CAP_OFS_Y_CRAWL), dt, morph_viscosity)
charctrl__jump_vel = 0.f
charctrl__state.x = int(CCStandType.ESS_CRAWL)
charctrl__state.y = int(CCMoveType.EMS_WALK)
else
charctrl__view_ht = approach(charctrl__view_ht, VIEW_HT_STAND, dt, morph_viscosity)
charctrl__capsule_dir = normalize(approach(charctrl__capsule_dir, float3(0.f, 1.f, 0.f), dt, morph_viscosity))
charctrl__capsule_ofs = approach(charctrl__capsule_ofs, float2(0.f, CAP_OFS_Y_STAND), dt, morph_viscosity)
charctrl__jump_vel = aJump.bActive && aJump.bState && !(aCrawl.bActive && aCrawl.bState) ? vel0_for_jump_ht(JUMP_HT_STAND) : 0.f
charctrl__state.x = int(CCStandType.ESS_STAND)
charctrl__state.y = int(CCMoveType.EMS_RUN)
let aMove = get_analog_stick_action_state(charctrl_input__aMove)
if aMove.bActive
charctrl__move_vel.x = approach(charctrl__move_vel.x, move_vel * aMove.x, dt, move_viscosity)
charctrl__move_vel.y = approach(charctrl__move_vel.y, move_vel * aMove.y, dt, move_viscosity)
else
charctrl__move_vel.x = approach(charctrl__move_vel.x, 0.f, dt, move_viscosity)
charctrl__move_vel.y = approach(charctrl__move_vel.y, 0.f, dt, move_viscosity)
if charctrl__state.y != int(CCMoveType.EMS_STAND) && length(charctrl__move_vel) < 0.01
charctrl__state.y = int(CCMoveType.EMS_STAND)
if charctrl__state.y == int(CCStandType.ESS_CRAWL)
charctrl__state.z |= int(CCStateFlag.ST_CRAWL)
else
charctrl__state.z &= ~int(CCStateFlag.ST_CRAWL)
if charctrl__state.y == int(CCStandType.ESS_CROUCH)
charctrl__state.z |= int(CCStateFlag.ST_CROUCH)
else
charctrl__state.z &= ~int(CCStateFlag.ST_CROUCH)
| 0 | 0.875777 | 1 | 0.875777 | game-dev | MEDIA | 0.620944 | game-dev | 0.969489 | 1 | 0.969489 |
VPDPersonal/Aspid.MVVM | 2,780 | Assets/_Assets/TextMesh Pro/Examples & Extras/Scripts/TextMeshSpawner.cs | using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TextMeshSpawner : MonoBehaviour
{
public int SpawnType = 0;
public int NumberOfNPC = 12;
public Font TheFont;
private TextMeshProFloatingText floatingText_Script;
void Awake()
{
}
void Start()
{
for (int i = 0; i < NumberOfNPC; i++)
{
if (SpawnType == 0)
{
// TextMesh Pro Implementation
//go.transform.localScale = new Vector3(2, 2, 2);
GameObject go = new GameObject(); //"NPC " + i);
go.transform.position = new Vector3(Random.Range(-95f, 95f), 0.5f, Random.Range(-95f, 95f));
//go.transform.position = new Vector3(0, 1.01f, 0);
//go.renderer.castShadows = false;
//go.renderer.receiveShadows = false;
//go.transform.rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
TextMeshPro textMeshPro = go.AddComponent<TextMeshPro>();
//textMeshPro.FontAsset = Resources.Load("Fonts & Materials/LiberationSans SDF", typeof(TextMeshProFont)) as TextMeshProFont;
//textMeshPro.anchor = AnchorPositions.Bottom;
textMeshPro.fontSize = 96;
textMeshPro.text = "!";
textMeshPro.color = new Color32(255, 255, 0, 255);
//textMeshPro.Text = "!";
// Spawn Floating Text
floatingText_Script = go.AddComponent<TextMeshProFloatingText>();
floatingText_Script.SpawnType = 0;
}
else
{
// TextMesh Implementation
GameObject go = new GameObject(); //"NPC " + i);
go.transform.position = new Vector3(Random.Range(-95f, 95f), 0.5f, Random.Range(-95f, 95f));
//go.transform.position = new Vector3(0, 1.01f, 0);
TextMesh textMesh = go.AddComponent<TextMesh>();
textMesh.GetComponent<Renderer>().sharedMaterial = TheFont.material;
textMesh.font = TheFont;
textMesh.anchor = TextAnchor.LowerCenter;
textMesh.fontSize = 96;
textMesh.color = new Color32(255, 255, 0, 255);
textMesh.text = "!";
// Spawn Floating Text
floatingText_Script = go.AddComponent<TextMeshProFloatingText>();
floatingText_Script.SpawnType = 1;
}
}
}
}
}
| 0 | 0.631416 | 1 | 0.631416 | game-dev | MEDIA | 0.980734 | game-dev | 0.633001 | 1 | 0.633001 |
MemoriesOfTime/Nukkit-MOT | 4,231 | src/main/java/cn/nukkit/entity/passive/EntityMooshroom.java | package cn.nukkit.entity.passive;
import cn.nukkit.Player;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.data.IntEntityData;
import cn.nukkit.item.Item;
import cn.nukkit.level.Sound;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.particle.ItemBreakParticle;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.network.protocol.LevelSoundEventPacket;
import cn.nukkit.utils.Utils;
import java.util.ArrayList;
import java.util.List;
public class EntityMooshroom extends EntityWalkingAnimal {
public static final int NETWORK_ID = 16;
public EntityMooshroom(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
public int getNetworkId() {
return NETWORK_ID;
}
@Override
public float getWidth() {
if (this.isBaby()) {
return 0.45f;
}
return 0.9f;
}
@Override
public float getHeight() {
if (this.isBaby()) {
return 0.7f;
}
return 1.4f;
}
@Override
public void initEntity() {
this.setMaxHealth(10);
super.initEntity();
if (this.namedTag.contains("Variant")) {
this.setBrown(this.namedTag.getInt("Variant") == 1);
}
}
@Override
public boolean isFeedItem(Item item) {
return item.getId() == Item.WHEAT;
}
@Override
public Item[] getDrops() {
List<Item> drops = new ArrayList<>();
if (!this.isBaby()) {
drops.add(Item.get(Item.LEATHER, 0, Utils.rand(0, 2)));
drops.add(Item.get(this.isOnFire() ? Item.STEAK : Item.RAW_BEEF, 0, Utils.rand(1, 3)));
}
return drops.toArray(Item.EMPTY_ARRAY);
}
@Override
public int getKillExperience() {
return this.isBaby() ? 0 : Utils.rand(1, 3);
}
@Override
public boolean onInteract(Player player, Item item, Vector3 clickedPos) {
if (item.getId() == Item.BOWL) {
if (!player.isCreative()) {
player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex());
}
player.getInventory().addItem(Item.get(Item.MUSHROOM_STEW, 0, 1));
this.level.addSoundToViewers(this, Sound.MOB_MOOSHROOM_SUSPICIOUS_MILK);
return false;
} else if (item.getId() == Item.BUCKET) {
if (!player.isCreative()) {
player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex());
}
Item newBucket = Item.get(Item.BUCKET, 1, 1);
if (player.getInventory().getItemFast(player.getInventory().getHeldItemIndex()).count > 0) {
if (player.getInventory().canAddItem(newBucket)) {
player.getInventory().addItem(newBucket);
} else {
player.dropItem(newBucket);
}
} else {
player.getInventory().setItemInHand(newBucket);
}
this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_MILK);
return false;
} else if (item.getId() == Item.WHEAT && !this.isBaby() && !this.isInLoveCooldown()) {
if (!player.isCreative()) {
player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex());
}
this.level.addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_EAT);
this.level.addParticle(new ItemBreakParticle(this.add(0, this.getMountedYOffset(), 0), Item.get(Item.WHEAT)));
this.setInLove();
return false;
}
return super.onInteract(player, item, clickedPos);
}
@Override
public void saveNBT() {
super.saveNBT();
this.namedTag.putInt("Variant", this.isBrown() ? 1 : 0);
}
@Override
public void onStruckByLightning(Entity entity) {
this.setBrown(!this.isBrown());
super.onStruckByLightning(entity);
}
public boolean isBrown() {
return this.getDataPropertyInt(DATA_VARIANT) == 1;
}
public void setBrown(boolean brown) {
this.setDataProperty(new IntEntityData(DATA_VARIANT, brown ? 1 : 0));
}
}
| 0 | 0.917515 | 1 | 0.917515 | game-dev | MEDIA | 0.981192 | game-dev | 0.968707 | 1 | 0.968707 |
MengeCrowdSim/Menge | 18,587 | src/Menge/MengeVis/Runtime/AgentContext/ORCATypeAgentContext.h | /*
Menge Crowd Simulation Framework
Copyright and trademark 2012-17 University of North Carolina at Chapel Hill
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
or
LICENSE.txt in the root of the Menge repository.
Any questions or comments should be sent to the authors menge@cs.unc.edu
<http://gamma.cs.unc.edu/Menge/>
*/
/*!
@file ORCATypeAgentContext.h
@brief A basic context for interacting with and displaying ORCA-type agent parameters.
ORCA-type agents are those that solve w.r.t. a set of linear constraints this context gives some
basic functionality for displaying those constraints.
*/
#ifndef __ORCA_TYPE_AGENT_CONTEXT_H__
#define __ORCA_TYPE_AGENT_CONTEXT_H__
#include <iomanip>
#include <sstream>
#include "MengeVis/Runtime/AgentContext/BaseAgentContext.h"
#include "MengeVis/Runtime/VisAgent/VisAgent.h"
#include "MengeVis/SceneGraph/shapes.h"
namespace MengeVis {
namespace Runtime {
/*!
@brief Context class for displaying various aspects of the ORCA-type agent computation.
*/
template <class Agent>
class ORCATypeAgentContext : public BaseAgentContext {
public:
/*!
@brief Default constructor.
*/
ORCATypeAgentContext();
/*!
@brief Sets the agent for this context.
This method works in conjunction with the VisElementDatabase. When this visualization element is
triggered, the database will supply the triggering element.
@param agent The agent to interact with.
*/
virtual void setElement(VisAgent* agent);
/*!
@brief Returns the name of the context for display.
@returns The name of this context.
*/
virtual std::string contextName() const { return "UNDEFINED ORCA TYPE"; }
/*!
@brief The value used to store this element in the visual element database.
This string value should correspond to the getStringId method of the corresponding simulation
element.
*/
virtual std::string getElementName() const { return "undefined_orca"; }
/*!
@brief Give the context the opportunity to respond to a keyboard event.
@param e The SDL event with the keyboard event data.
@returns A ContextResult instance reporting if the event was handled and if redrawing is
necessary.
*/
virtual SceneGraph::ContextResult handleKeyboard(SDL_Event& e);
/*!
@brief Allow the context to update any time-dependent state it might have to the given global
time.
*/
virtual void update();
protected:
/*!
@brief Draw context elements into the 3D world.
@param select Defines if the drawing is being done for selection purposes (true) or
visualization (false).
*/
virtual void draw3DGL(bool select = false);
/*!
@brief Helper function for drawing a halfplane
@param line The line object which defines the half plane.
@param pos The relative position to draw the plane. Typically the position of the agent on
which the half-plane is applied.
@param r The red component of the half plane color.
@param g The green component of the half plane color.
@param b The blue component of the half plane color.
@param h Value, on the verical-axis (in world coordinates), of the plane on which to draw
the half plane.
*/
void drawHalfPlane(const Menge::Math::Line& line, const Menge::Math::Vector2& pos, float r,
float g, float b, float h) const;
/*!
@brief Draws the given ORCA line for the given agent
@param agent A pointer to the agent to whom this line applies.
@param line The actual line.
@param isAgent A boolean reporting if the orca line comes from an agent. true --> agent,
false --> obstacle.
*/
void drawORCALine(const Agent* agent, const Menge::Math::Line& line, bool isAgent) const;
/*!
@brief Draw the optimized velocity for the current set of orca lines
@param agent A pointer to the agent for which the velocity is drawn computeNewVelocity() will
be called on the agent.
*/
void drawOptVelocity(Agent* agent) const;
/*!
@brief Creates a formatted string to be printed in the context for a particular agent.
@param agent A pointer to the agent for which the information is displayed.
@returns A formatted string for display in the context's 2D gui.
*/
virtual std::string agentText(const Menge::Agents::BaseAgent* agent) const;
/*!
@brief Determines if the ORCA lines are drawn.
*/
bool _showOrcaLines;
/*!
@brief Function for drawing the ORCA lines acting on `agt`.
@param agt A pointer to the agent whose ORCA lines will be drawn.
*/
void drawORCALines(const Agent* agt) const;
/*!
@brief Determines if the ORCA line construction is visualized.
*/
bool _visualizeORCA;
/*!
@brief The agent to visualize.
*/
size_t _visNbrID;
/*!
@brief The function that draws the visualization of the orca construction.
@param agt A pointer to the agent for whom the *computation* of a single ORCA line is
illustrated.
*/
void visORCA(const Agent* agt) const;
};
template <class Agent>
ORCATypeAgentContext<Agent>::ORCATypeAgentContext()
: _showOrcaLines(false), _visualizeORCA(false), _visNbrID(0) {}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::setElement(VisAgent* agent) {
// TODO: Make this NVI
BaseAgentContext::setElement(agent);
_visNbrID = 0;
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::update() {
if (this->_selected && _visNbrID) {
const Agent* agt = dynamic_cast<const Agent*>(this->_selected->getAgent());
if (_visNbrID > 0) {
size_t NBR_COUNT = agt->_nearAgents.size();
if (_visNbrID > NBR_COUNT) {
_visNbrID = NBR_COUNT;
}
}
}
}
////////////////////////////////////////////////////////////////
template <class Agent>
SceneGraph::ContextResult ORCATypeAgentContext<Agent>::handleKeyboard(SDL_Event& e) {
SceneGraph::ContextResult result = BaseAgentContext::handleKeyboard(e);
if (!result.isHandled()) {
SDL_Keymod mods = SDL_GetModState();
bool hasCtrl = (mods & KMOD_CTRL) > 0;
bool hasAlt = (mods & KMOD_ALT) > 0;
bool hasShift = (mods & KMOD_SHIFT) > 0;
bool noMods = !(hasCtrl || hasAlt || hasShift);
if (e.type == SDL_KEYDOWN) {
if (noMods) {
if (e.key.keysym.sym == SDLK_c) {
_showOrcaLines = !_showOrcaLines;
result.set(true, true);
} else if (e.key.keysym.sym == SDLK_z) {
_visualizeORCA = !_visualizeORCA;
_visNbrID = 0;
result.set(true, true);
} else if (e.key.keysym.sym == SDLK_UP) {
if (_visualizeORCA && this->_selected) {
const Agent* agt = dynamic_cast<const Agent*>(this->_selected->getAgent());
++_visNbrID;
if (_visNbrID >= agt->_nearAgents.size()) _visNbrID = 0;
result.set(true, true);
}
} else if (e.key.keysym.sym == SDLK_DOWN) {
if (_visualizeORCA && this->_selected) {
const Agent* agt = dynamic_cast<const Agent*>(this->_selected->getAgent());
if (_visNbrID == 0)
_visNbrID = agt->_nearAgents.size() - 1;
else
--_visNbrID;
result.set(true, true);
}
}
}
}
}
return result;
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::draw3DGL(bool select) {
BaseAgentContext::draw3DGL(select);
if (!select && this->_selected) {
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_LINE_BIT |
GL_POLYGON_BIT);
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
const Agent* agt = dynamic_cast<const Agent*>(this->_selected->getAgent());
drawORCALines(agt);
visORCA(agt);
glPopAttrib();
}
}
////////////////////////////////////////////////////////////////
template <class Agent>
std::string ORCATypeAgentContext<Agent>::agentText(const Menge::Agents::BaseAgent* agt) const {
const Agent* agent = dynamic_cast<const Agent*>(agt);
std::string m = BaseAgentContext::agentText(agent);
std::stringstream ss;
ss << std::setiosflags(std::ios::fixed) << std::setprecision(2);
ss << "\n_________________________";
ss << "\nDraw OR(C)A lines";
if (_showOrcaLines) {
const size_t LINE_COUNT = agent->_orcaLines.size();
const size_t AGT_COUNT = agent->_nearAgents.size();
const size_t OBST_COUNT = LINE_COUNT - AGT_COUNT;
ss << "\n " << OBST_COUNT << " obstacle lines";
ss << "\n " << AGT_COUNT << " agent lines";
}
ss << "\nVisuali(z)e ORCA";
if (_visualizeORCA) {
if (agent->_nearAgents.size() == 0) {
ss << "\n No nearby agents.";
} else {
size_t id = (agent->_nearAgents[_visNbrID].agent)->_id;
ss << "\n Showing agent: " << id << " (up/down arrow to change)";
}
}
return m + ss.str();
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::drawHalfPlane(const Menge::Math::Line& line,
const Menge::Math::Vector2& pos, float r, float g,
float b, float h) const {
const float DIST = 35.f;
Menge::Math::Vector2 norm(-line._direction.y(), line._direction.x());
Menge::Math::Vector2 p0 = line._point + line._direction * DIST + pos;
Menge::Math::Vector2 p1 = p0 - norm * DIST;
Menge::Math::Vector2 p2 = p1 - line._direction * (2 * DIST);
Menge::Math::Vector2 p3 = p2 + norm * DIST;
glColor4f(r, g, b, 0.1f);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_BLEND);
glBegin(GL_QUADS);
glVertex3f(p0.x(), p0.y(), h);
glVertex3f(p1.x(), p1.y(), h);
glVertex3f(p2.x(), p2.y(), h);
glVertex3f(p3.x(), p3.y(), h);
glEnd();
glDisable(GL_BLEND);
glBegin(GL_LINES);
glVertex3f(p0.x(), p0.y(), h);
glVertex3f(p3.x(), p3.y(), h);
glEnd();
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::drawORCALines(const Agent* agent) const {
if (_showOrcaLines && this->_selected) {
Agent* agt = const_cast<Agent*>(agent);
agt->computeORCALines();
const size_t LINE_COUNT = agt->_orcaLines.size();
const size_t FIRST_AGENT = LINE_COUNT - agt->_nearAgents.size();
const float DIST = 35.f;
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_BLEND);
// Obstacle color
glColor4f(0.75f, 0.75f, 0.75f, 0.1f);
glBegin(GL_QUADS);
for (size_t i = 0; i < LINE_COUNT; ++i) {
// Agent color
if (i == FIRST_AGENT) {
glColor4f(1.f, 0.f, 0.f, 0.1f);
}
const Menge::Math::Line& line = agt->_orcaLines[i];
// Find the nearest point on the orca line to the agent -- use that as the center
Menge::Math::Vector2 norm(-line._direction.y(), line._direction.x());
float t = line._direction * (-line._point);
Menge::Math::Vector2 nearPt = line._point + t * line._direction;
Menge::Math::Vector2 p0 = nearPt + line._direction * DIST + agt->_pos;
Menge::Math::Vector2 p1 = p0 - norm * DIST;
Menge::Math::Vector2 p2 = p1 - line._direction * (2 * DIST);
Menge::Math::Vector2 p3 = p2 + norm * DIST;
glVertex3f(p0.x(), p0.y(), this->H);
glVertex3f(p1.x(), p1.y(), this->H);
glVertex3f(p2.x(), p2.y(), this->H);
glVertex3f(p3.x(), p3.y(), this->H);
}
glEnd();
glDisable(GL_BLEND);
glColor4f(0.75f, 0.75f, 0.75f, 0.1f);
glBegin(GL_LINES);
for (size_t i = 0; i < LINE_COUNT; ++i) {
if (i == FIRST_AGENT) {
glColor4f(1.f, 0.f, 0.f, 0.1f);
}
const Menge::Math::Line& line = agt->_orcaLines[i];
float t = line._direction * (-line._point);
Menge::Math::Vector2 nearPt = line._point + t * line._direction;
Menge::Math::Vector2 p0 = nearPt + line._direction * DIST + agt->_pos;
Menge::Math::Vector2 p1 = nearPt - line._direction * DIST + agt->_pos;
glVertex3f(p0.x(), p0.y(), this->H);
glVertex3f(p1.x(), p1.y(), this->H);
}
glEnd();
// Label the orca lines from agents
glColor4f(1.f, 0.f, 0.f, 1.f);
for (size_t i = FIRST_AGENT; i < LINE_COUNT; ++i) {
std::stringstream ss;
const Menge::Agents::BaseAgent* nbr = agent->_nearAgents[i - FIRST_AGENT].agent;
ss << nbr->_id;
Menge::Math::Vector2 d = agent->_orcaLines[i].nearestPt(Menge::Math::Vector2(0.f, 0.f));
Menge::Math::Vector2 p = d + agent->_pos;
this->writeTextRadially(ss.str(), p, d, true);
this->writeAlignedText(ss.str(), nbr->_pos, SceneGraph::TextWriter::CENTERED, true);
}
}
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::visORCA(const Agent* agt) const {
if (_visualizeORCA && this->_selected) {
if (agt->_nearAgents.size() > 0) {
Menge::Math::Vector2 velPref = agt->_velPref.getPreferredVel();
const float RAD_TO_DEG = 180.f * 3.1415927f;
glColor3f(0.1f, 1.f, 0.1f);
Agent* agent = const_cast<Agent*>(agt);
agent->computeORCALines();
const Agent* nbr = static_cast<const Agent*>(agent->_nearAgents[_visNbrID].agent);
float R = agent->_radius + nbr->_radius;
Menge::Math::Vector2 disp = nbr->_pos - agent->_pos;
float dist = abs(disp);
Menge::Math::Vector2 dir = disp / dist;
Menge::Math::Vector2 perp(-dir.y(), dir.x());
// Compute the tangent portions of the minkowski sum
float cosPhi = R / dist;
float sinPhi = sqrtf(1 - cosPhi * cosPhi);
float cx = cosPhi * -dir.x();
float sx = sinPhi * -dir.x();
float cy = cosPhi * -dir.y();
float sy = sinPhi * -dir.y();
Menge::Math::Vector2 r0 = disp + R * Menge::Math::Vector2(cx - sy, sx + cy);
Menge::Math::Vector2 l0 = disp + R * Menge::Math::Vector2(cx + sy, -sx + cy);
// modify the positions of r0 and l0 so that they project onto the center
//
float l = dist / (r0 * dir);
r0 *= l;
l0 *= l;
r0 += agent->_pos;
l0 += agent->_pos;
// What's the closest circle?
const float TAU = agent->_timeHorizon;
float minVel = dist / TAU;
float Rmin = R / TAU;
Menge::Math::Vector2 center(agent->_pos + dir * minVel);
// First, draw leading circle
glPushMatrix();
glTranslatef(center.x(), center.y(), this->H);
SceneGraph::Circle::drawCircle(Rmin, 0.1f, 1.f, 0.1f, 0.75f, GL_LINE);
glPopMatrix();
Menge::Math::Vector2 r1 = center + Rmin * Menge::Math::Vector2(cx - sy, sx + cy);
Menge::Math::Vector2 l1 = center + Rmin * Menge::Math::Vector2(cx + sy, -sx + cy);
glBegin(GL_LINES);
glVertex3f(r0.x(), r0.y(), this->H);
glVertex3f(r1.x(), r1.y(), this->H);
glVertex3f(l0.x(), l0.y(), this->H);
glVertex3f(l1.x(), l1.y(), this->H);
glEnd();
// Use right of way to compute velocities
float row = agent->_priority - nbr->_priority;
Menge::Math::Vector2 agtVel = agent->_vel;
Menge::Math::Vector2 nbrVel = nbr->_vel;
Menge::Math::Vector2 nbrVelPref = nbr->_velPref.getPreferredVel();
if (row > 0.f) {
// agent's advantage
row = row > 1.f ? 1.f : row;
if (dir * velPref > dir * agent->_vel) {
agtVel = velPref * row + (1.f - row) * agent->_vel;
}
} else if (row < 0.f) {
// nbr's advantage
row = row < -1.f ? 1.f : -row;
if (dir * nbrVelPref < dir * nbr->_vel) {
nbrVel = nbrVelPref * row + (1.f - row) * nbr->_vel;
}
}
// Other guy's velocity
glColor3f(0.1f, 0.1f, 0.8f);
glBegin(GL_LINES);
glVertex3f(nbr->_pos.x(), nbr->_pos.y(), this->H);
glVertex3f(nbr->_pos.x() + nbrVel.x(), nbr->_pos.y() + nbrVel.y(), this->H);
glEnd();
this->writeTextRadially("v_j", nbr->_pos + nbrVel, nbrVel, true);
// My velocity
glColor3f(0.1f, 0.8f, 0.1f);
glBegin(GL_LINES);
glVertex3f(agent->_pos.x(), agent->_pos.y(), this->H);
glVertex3f(agent->_pos.x() + agtVel.x(), agent->_pos.y() + agtVel.y(), this->H);
glEnd();
this->writeTextRadially("v_i", agent->_pos + agtVel, agtVel, true);
// Relative velocity
glColor3f(0.1f, 0.8f, 0.8f);
glBegin(GL_LINES);
Menge::Math::Vector2 rel = agtVel - nbrVel;
glVertex3f(agent->_pos.x(), agent->_pos.y(), this->H);
glVertex3f(agent->_pos.x() + rel.x(), agent->_pos.y() + rel.y(), this->H);
glEnd();
this->writeTextRadially("v_ij", agent->_pos + rel, rel, true);
// Draw the ORCA line
// Determine which line it is
size_t NBR_COUNT = agent->_nearAgents.size();
size_t FIRST_NBR = agent->_orcaLines.size() - NBR_COUNT;
drawORCALine(agent, agent->_orcaLines[FIRST_NBR + _visNbrID], true);
// optimized velocity in transformed space
drawOptVelocity(agent);
}
}
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::drawORCALine(const Agent* agent, const Menge::Math::Line& line,
bool isAgent) const {
if (isAgent) {
drawHalfPlane(line, agent->_pos, 1.f, 0.f, 0.f, this->H);
} else {
drawHalfPlane(line, agent->_pos, 0.75f, 0.75f, 0.75f, this->H);
}
}
////////////////////////////////////////////////////////////////
template <class Agent>
void ORCATypeAgentContext<Agent>::drawOptVelocity(Agent* agent) const {
// Draw the optimized velocity (transformed and untransformed
agent->computeNewVelocity();
// NORMAL space
glPushAttrib(GL_POINT_BIT);
glPointSize(3.f);
glColor3f(0.2f, 0.2f, 1.f);
glBegin(GL_POINTS);
glVertex3f(agent->_pos.x() + agent->_velNew.x(), agent->_pos.y() + agent->_velNew.y(), this->H);
glEnd();
this->writeTextRadially(" v_new ", agent->_pos + agent->_velNew, agent->_velNew, true);
}
} // namespace Runtime
} // namespace MengeVis
#endif // __ORCA_TYPE_AGENT_CONTEXT_H__
| 0 | 0.926414 | 1 | 0.926414 | game-dev | MEDIA | 0.368185 | game-dev | 0.960992 | 1 | 0.960992 |
hippich/Bitcoin-Poker-Room | 2,198 | lib/ppn/pokernetwork/pokergameclient.py | # -*- py-indent-offset: 4; coding: iso-8859-1; mode: python -*-
#
# Copyright (C) 2007, 2008, 2009 Loic Dachary <loic@dachary.org>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) as published by the Free
# Software Foundation (FSF), either version 3 of the License, or (at your
# option) any later version of the AGPL published by the FSF.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3". If not, see <http://www.gnu.org/licenses/>.
#
from pokerengine.pokergame import PokerGameClient
class PokerNetworkGameClient(PokerGameClient):
SERIAL_IN_POSITION = 0
POSITION_OBSOLETE = 1
def __init__(self, url, dirs):
PokerGameClient.__init__(self, url, dirs)
self.level_skin = ""
self.currency_serial = 0
self.history_index = 0
self.position_info = [ 0, 0 ]
def reset(self):
PokerGameClient.reset(self)
self.resetStaticPlayerList()
def cancelState(self):
self.resetStaticPlayerList()
return PokerGameClient.cancelState(self)
def endState(self):
self.resetStaticPlayerList()
return PokerGameClient.endState(self)
def resetStaticPlayerList(self):
self.static_player_list = None
def setStaticPlayerList(self, player_list):
self.static_player_list = player_list[:]
def getStaticPlayerList(self):
return self.static_player_list
def buildPlayerList(self, with_wait_for):
self.player_list = self.getStaticPlayerList()
if self.verbose >= 3:
self.message("buildPlayerList " + str(self.player_list))
assert self.player_list == filter(lambda x: self.serial2player[x].isSit(), self.player_list)
return True
| 0 | 0.712859 | 1 | 0.712859 | game-dev | MEDIA | 0.361045 | game-dev | 0.683551 | 1 | 0.683551 |
Brotcrunsher/BrotBoxEngine | 3,849 | Third-Party/box2d-master/testbed/tests/bullet_test.cpp | // MIT License
// Copyright (c) 2019 Erin Catto
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "test.h"
class BulletTest : public Test
{
public:
BulletTest()
{
{
b2BodyDef bd;
bd.position.Set(0.0f, 0.0f);
b2Body* body = m_world->CreateBody(&bd);
b2EdgeShape edge;
edge.SetTwoSided(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f));
body->CreateFixture(&edge, 0.0f);
b2PolygonShape shape;
shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f);
body->CreateFixture(&shape, 0.0f);
}
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 4.0f);
b2PolygonShape box;
box.SetAsBox(2.0f, 0.1f);
m_body = m_world->CreateBody(&bd);
m_body->CreateFixture(&box, 1.0f);
box.SetAsBox(0.25f, 0.25f);
//m_x = RandomFloat(-1.0f, 1.0f);
m_x = 0.20352793f;
bd.position.Set(m_x, 10.0f);
bd.bullet = true;
m_bullet = m_world->CreateBody(&bd);
m_bullet->CreateFixture(&box, 100.0f);
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
}
}
void Launch()
{
m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f);
m_body->SetLinearVelocity(b2Vec2_zero);
m_body->SetAngularVelocity(0.0f);
m_x = RandomFloat(-1.0f, 1.0f);
m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f);
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
m_bullet->SetAngularVelocity(0.0f);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters;
b2_gjkCalls = 0;
b2_gjkIters = 0;
b2_gjkMaxIters = 0;
b2_toiCalls = 0;
b2_toiIters = 0;
b2_toiMaxIters = 0;
b2_toiRootIters = 0;
b2_toiMaxRootIters = 0;
}
void Step(Settings& settings) override
{
Test::Step(settings);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
extern int32 b2_toiCalls, b2_toiIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters;
if (b2_gjkCalls > 0)
{
g_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d",
b2_gjkCalls, b2_gjkIters / float(b2_gjkCalls), b2_gjkMaxIters);
m_textLine += m_textIncrement;
}
if (b2_toiCalls > 0)
{
g_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d",
b2_toiCalls, b2_toiIters / float(b2_toiCalls), b2_toiMaxRootIters);
m_textLine += m_textIncrement;
g_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d",
b2_toiRootIters / float(b2_toiCalls), b2_toiMaxRootIters);
m_textLine += m_textIncrement;
}
if (m_stepCount % 60 == 0)
{
Launch();
}
}
static Test* Create()
{
return new BulletTest;
}
b2Body* m_body;
b2Body* m_bullet;
float m_x;
};
static int testIndex = RegisterTest("Continuous", "Bullet Test", BulletTest::Create);
| 0 | 0.897634 | 1 | 0.897634 | game-dev | MEDIA | 0.937591 | game-dev,testing-qa | 0.860333 | 1 | 0.860333 |
mightycow/uberdemotools | 26,165 | UDT_DLL/src/analysis_captures.cpp | #include "analysis_captures.hpp"
#include "utils.hpp"
#include "scoped_stack_allocator.hpp"
#include <stdlib.h>
/*
Sound indices for EV_GLOBAL_TEAM_SOUND in CPMA:
0 blue captures (flag team: red)
1 red captures (flag team: blue)
4 red taken (flag team: red)
5 blue taken (flag team: blue)
*/
#define MAX_ALLOWED_TIME_DELTA_QL_MS 1500
static bool ParseDuration(s32& durationMs, const udtString& duration)
{
u32 colonIndex = 0;
if(!udtString::FindFirstCharacterMatch(colonIndex, duration, ':'))
{
return false;
}
u32 dotIndex = 0;
const bool hasDot = udtString::FindFirstCharacterMatch(dotIndex, duration, '.', colonIndex + 2);
int minutes = 0;
if(sscanf(duration.GetPtr(), "%d", &minutes) != 1)
{
return false;
}
int seconds = 0;
if(sscanf(duration.GetPtr() + colonIndex + 1, "%d", &seconds) != 1)
{
return false;
}
s32 result = s32((minutes * 60 + seconds) * 1000);
if(hasDot)
{
int subSeconds = 0;
if(sscanf(duration.GetPtr() + dotIndex + 1, "%d", &subSeconds) != 1)
{
return false;
}
static const u32 multipliers[4] = { 1, 100, 10, 1 };
const u32 digitCount = duration.GetLength() - dotIndex - 1;
if(digitCount == 0 || digitCount > 3)
{
return false;
}
result += (s32)subSeconds * multipliers[digitCount];
}
durationMs = result;
return true;
}
udtCapturesAnalyzer::udtCapturesAnalyzer()
{
_tempAllocator = NULL;
}
udtCapturesAnalyzer::~udtCapturesAnalyzer()
{
}
void udtCapturesAnalyzer::Init(u32, udtVMLinearAllocator* tempAllocator)
{
_tempAllocator = tempAllocator;
}
void udtCapturesAnalyzer::StartDemoAnalysis()
{
_mapName = udtString::NewNull();
_gameStateIndex = -1;
_demoTakerIndex = -1;
_firstSnapshot = true;
_processGamestate = &udtCapturesAnalyzer::ProcessGamestateMessageDummy;
_processCommand = &udtCapturesAnalyzer::ProcessCommandMessageDummy;
_processSnapshot = &udtCapturesAnalyzer::ProcessSnapshotMessageDummy;
_playerNameAllocator.Clear();
for(u32 i = 0; i < 64; ++i)
{
_playerNames[i] = udtString::NewNull();
_playerClanNames[i] = udtString::NewNull();
}
}
void udtCapturesAnalyzer::FinishDemoAnalysis()
{
}
void udtCapturesAnalyzer::ProcessGamestateMessage(const udtGamestateCallbackArg& arg, udtBaseParser& parser)
{
++_gameStateIndex;
_firstSnapshot = true;
_demoTakerIndex = arg.ClientNum;
udtVMScopedStackAllocator allocScope(*_tempAllocator);
const udtProtocol::Id protocol = parser._inProtocol;
if(AreAllProtocolFlagsSet(protocol, udtProtocolFlags::QuakeLive))
{
_processGamestate = &udtCapturesAnalyzer::ProcessGamestateMessageQLorOSP;
_processCommand = &udtCapturesAnalyzer::ProcessCommandMessageQLorOSP;
_processSnapshot = &udtCapturesAnalyzer::ProcessSnapshotMessageQLorOSP;
}
// @NOTE: EF_AWARD_CAP doesn't exist in dm3.
else if(AreAllProtocolFlagsSet(protocol, udtProtocolFlags::Quake3) &&
protocol != udtProtocol::Dm3)
{
udtString gameName;
if(ParseConfigStringValueString(gameName, *_tempAllocator, "gamename", parser.GetConfigString(CS_SERVERINFO).GetPtr()))
{
if(udtString::Equals(gameName, "cpma"))
{
_processGamestate = &udtCapturesAnalyzer::ProcessGamestateMessageCPMA;
_processCommand = &udtCapturesAnalyzer::ProcessCommandMessageCPMA;
_processSnapshot = &udtCapturesAnalyzer::ProcessSnapshotMessageCPMA;
}
else if(udtString::Equals(gameName, "osp"))
{
_processGamestate = &udtCapturesAnalyzer::ProcessGamestateMessageQLorOSP;
_processCommand = &udtCapturesAnalyzer::ProcessCommandMessageQLorOSP;
_processSnapshot = &udtCapturesAnalyzer::ProcessSnapshotMessageQLorOSP;
}
}
}
else
{
_processGamestate = &udtCapturesAnalyzer::ProcessGamestateMessageDummy;
_processCommand = &udtCapturesAnalyzer::ProcessCommandMessageDummy;
_processSnapshot = &udtCapturesAnalyzer::ProcessSnapshotMessageDummy;
}
udtString mapName;
if(ParseConfigStringValueString(mapName, *_tempAllocator, "mapname", parser.GetConfigString(CS_SERVERINFO).GetPtr()))
{
_mapName = udtString::NewCloneFromRef(StringAllocator, mapName);
}
else
{
_mapName = udtString::NewNull();
}
(this->*_processGamestate)(arg, parser);
}
void udtCapturesAnalyzer::ProcessCommandMessage(const udtCommandCallbackArg& arg, udtBaseParser& parser)
{
(this->*_processCommand)(arg, parser);
}
void udtCapturesAnalyzer::ProcessSnapshotMessage(const udtSnapshotCallbackArg& arg, udtBaseParser& parser)
{
(this->*_processSnapshot)(arg, parser);
_firstSnapshot = false;
}
void udtCapturesAnalyzer::ProcessGamestateMessageQLorOSP(const udtGamestateCallbackArg& arg, udtBaseParser& parser)
{
ProcessGamestateMessageClearStates(arg, parser);
_lastCaptureQL.Clear();
_playerStateQL.Clear();
const s32 firstPlayerCsIdx = GetIdNumber(udtMagicNumberType::ConfigStringIndex, udtConfigStringIndex::FirstPlayer, parser._inProtocol);
for(s32 i = 0; i < 64; ++i)
{
const udtString cs = parser.GetConfigString(firstPlayerCsIdx + i);
if(!udtString::IsNullOrEmpty(cs))
{
ProcessPlayerConfigStringQLorOSP(cs.GetPtr(), parser, i);
}
}
}
void udtCapturesAnalyzer::ProcessCommandMessageQLorOSP(const udtCommandCallbackArg& arg, udtBaseParser& parser)
{
if(arg.IsConfigString)
{
if(arg.ConfigStringIndex == GetIdNumber(udtMagicNumberType::ConfigStringIndex, udtConfigStringIndex::FlagStatus, parser._inProtocol))
{
ProcessFlagStatusCommandQLorOSP(arg, parser);
return;
}
const s32 firstPlayerCsIdx = GetIdNumber(udtMagicNumberType::ConfigStringIndex, udtConfigStringIndex::FirstPlayer, parser._inProtocol);
if(arg.ConfigStringIndex >= firstPlayerCsIdx &&
arg.ConfigStringIndex < firstPlayerCsIdx + 64)
{
const s32 playerIndex = arg.ConfigStringIndex - firstPlayerCsIdx;
ProcessPlayerConfigStringQLorOSP(parser.GetTokenizer().GetArgString(2), parser, playerIndex);
return;
}
}
else
{
idTokenizer& tokenizer = parser._context->Tokenizer;
tokenizer.Tokenize(arg.String);
if(tokenizer.GetArgCount() == 2 &&
udtString::EqualsNoCase(tokenizer.GetArg(0), "print"))
{
ProcessPrintCommandQLorOSP(arg, parser);
return;
}
}
}
void udtCapturesAnalyzer::ProcessSnapshotMessageQLorOSP(const udtSnapshotCallbackArg& arg, udtBaseParser& parser)
{
idPlayerStateBase* const ps = GetPlayerState(arg.Snapshot, parser._inProtocol);
//
// Step 1: update Defined, PrevDefined, Position
//
if(ps->clientNum >= 0 && ps->clientNum < 64)
{
PlayerInfo& player = _players[ps->clientNum];
player.PrevDefined = player.Defined;
player.Defined = true;
Float3::Copy(player.Position, ps->origin);
}
for(u32 i = 0; i < 64; ++i)
{
if((s32)i == ps->clientNum)
{
continue;
}
PlayerInfo& player = _players[i];
player.PrevDefined = player.Defined;
player.Defined = false;
}
const s32 entityTypePlayerId = GetIdNumber(udtMagicNumberType::EntityType, udtEntityType::Player, parser._inProtocol);
for(u32 i = 0, count = arg.ChangedEntityCount; i < count; ++i)
{
idEntityStateBase* const es = arg.ChangedEntities[i].Entity;
if(arg.ChangedEntities[i].IsNewEvent ||
es == NULL ||
es->eType != entityTypePlayerId ||
es->clientNum < 0 ||
es->clientNum >= 64)
{
continue;
}
PlayerInfo& player = _players[es->clientNum];
player.Defined = true;
Float3::Copy(player.Position, es->pos.trBase);
}
//
// Step 2: handle pick-up and capture events
//
if(ps->clientNum >= 0 && ps->clientNum < 64)
{
const s32 redFlagIdx = GetIdNumber(udtMagicNumberType::PowerUpIndex, udtPowerUpIndex::RedFlag, parser._inProtocol);
const s32 blueFlagIdx = GetIdNumber(udtMagicNumberType::PowerUpIndex, udtPowerUpIndex::BlueFlag, parser._inProtocol);
const s32 captureCountPersIdx = GetIdNumber(udtMagicNumberType::PersStatsIndex, udtPersStatsIndex::FlagCaptures, parser._inProtocol);
PlayerInfo& player = _players[ps->clientNum];
const bool hasFlag = ps->powerups[redFlagIdx] != 0 || ps->powerups[blueFlagIdx] != 0;
const bool prevHasFlag = _firstSnapshot ? hasFlag : _playerStateQL.HasFlag;
_playerStateQL.HasFlag = hasFlag;
_playerStateQL.PrevHasFlag = prevHasFlag;
const s32 captureCount = ps->persistant[captureCountPersIdx];
const s32 prevCaptureCount = _firstSnapshot ? captureCount : _playerStateQL.CaptureCount;
_playerStateQL.CaptureCount = captureCount;
_playerStateQL.PrevCaptureCount = prevCaptureCount;
if(!prevHasFlag && hasFlag)
{
Float3::Copy(player.PickupPosition, ps->origin);
}
else if(captureCount > prevCaptureCount)
{
const u32 storedCaptureCount = Captures.GetSize();
if(!hasFlag && prevHasFlag && storedCaptureCount > 0)
{
udtParseDataCapture& capture = Captures[storedCaptureCount - 1];
if(abs((int)(capture.CaptureTimeMs - parser._inServerTime)) < (int)MAX_ALLOWED_TIME_DELTA_QL_MS)
{
const f32 distance = Float3::Dist(player.PickupPosition, player.Position);
capture.Distance = distance;
capture.Flags |= (u32)udtParseDataCaptureMask::DistanceValid;
capture.Flags |= (u32)udtParseDataCaptureMask::FirstPersonPlayer;
if(ps->clientNum == _demoTakerIndex)
{
capture.Flags |= (u32)udtParseDataCaptureMask::DemoTaker;
}
}
}
_lastCaptureQL.Clear();
}
}
const s32 entityTypeEventId = GetIdNumber(udtMagicNumberType::EntityType, udtEntityType::Event, parser._inProtocol);
const s32 globalTeamSoundId = GetIdNumber(udtMagicNumberType::EntityEvent, udtEntityEvent::GlobalTeamSound, parser._inProtocol);
for(u32 i = 0, count = arg.ChangedEntityCount; i < count; ++i)
{
idEntityStateBase* const es = arg.ChangedEntities[i].Entity;
if(!arg.ChangedEntities[i].IsNewEvent ||
es == NULL ||
es->eType <= entityTypeEventId)
{
continue;
}
const s32 event = (es->eType - entityTypeEventId) & (~ID_ES_EVENT_BITS);
if(event == globalTeamSoundId)
{
const s32 soundIndex = es->eventParm;
if(soundIndex == 0 || soundIndex == 1)
{
TeamInfo& team = _teams[soundIndex];
const s32 playerIndex = team.PlayerIndex;
if(playerIndex < 0 || playerIndex >= 64)
{
continue;
}
PlayerInfo& player = _players[playerIndex];
if(player.PickupPositionValid &&
(player.Defined || player.PrevDefined))
{
const f32 distance = Float3::Dist(player.PickupPosition, player.Position);
const u32 captureCount = Captures.GetSize();
if(captureCount > 0)
{
udtParseDataCapture& cap = Captures[captureCount - 1];
if(abs((int)(cap.CaptureTimeMs - parser._inServerTime)) < (int)MAX_ALLOWED_TIME_DELTA_QL_MS)
{
_lastCaptureQL.Time = parser._inServerTime;
_lastCaptureQL.Distance = distance;
}
else
{
_lastCaptureQL.Clear();
}
}
else
{
_lastCaptureQL.Clear();
}
}
}
else if(soundIndex == 4 || soundIndex == 5)
{
const s32 playerIndex = es->otherEntityNum;
if(playerIndex < 0 || playerIndex >= 64)
{
continue;
}
PlayerInfo& player = _players[playerIndex];
if(player.Defined && player.PrevDefined)
{
Float3::Copy(player.PickupPosition, player.Position);
player.PickupPositionValid = true;
}
else
{
player.PickupPositionValid = false;
}
const u32 teamIndex = (u32)soundIndex - 4;
TeamInfo& team = _teams[teamIndex];
team.PlayerIndex = playerIndex;
}
}
}
}
void udtCapturesAnalyzer::ProcessGamestateMessageCPMA(const udtGamestateCallbackArg& arg, udtBaseParser& parser)
{
ProcessGamestateMessageClearStates(arg, parser);
_flagStatusCPMA[0].Clear();
_flagStatusCPMA[1].Clear();
}
void udtCapturesAnalyzer::ProcessCommandMessageCPMA(const udtCommandCallbackArg& arg, udtBaseParser& parser)
{
if(arg.IsConfigString && arg.ConfigStringIndex == GetIdNumber(udtMagicNumberType::ConfigStringIndex, udtConfigStringIndex::FlagStatus, parser._inProtocol))
{
const udtString cs = parser.GetTokenizer().GetArg(2);
if(cs.GetLength() >= 2)
{
_teams[0].PrevFlagState = _teams[0].FlagState;
_teams[1].PrevFlagState = _teams[1].FlagState;
const char* const csString = cs.GetPtr();
_teams[0].FlagState = (u8)(csString[0] - '0');
_teams[1].FlagState = (u8)(csString[1] - '0');
const s32 time = parser._inServerTime;
for(u32 i = 0; i < 2; ++i)
{
FlagStatusCPMA& flagStatus = _flagStatusCPMA[i];
const TeamInfo& team = _teams[i];
const s32 prevTime = flagStatus.ChangeTime;
const bool returned = team.PrevFlagState == (u8)idFlagStatus::Carried && team.FlagState == (u8)idFlagStatus::InBase;
if(time == prevTime && returned)
{
flagStatus.InstantCapture = true;
}
if(team.FlagState != team.PrevFlagState)
{
flagStatus.ChangeTime = time;
}
}
}
}
}
void udtCapturesAnalyzer::ProcessSnapshotMessageCPMA(const udtSnapshotCallbackArg& arg, udtBaseParser& parser)
{
idPlayerStateBase* const ps = GetPlayerState(arg.Snapshot, parser._inProtocol);
//
// Step 1: update Defined, PrevDefined, Position
//
if(ps->clientNum >= 0 && ps->clientNum < 64)
{
PlayerInfo& player = _players[ps->clientNum];
player.PrevDefined = player.Defined;
player.Defined = true;
Float3::Copy(player.Position, ps->origin);
}
for(u32 i = 0; i < 64; ++i)
{
if((s32)i == ps->clientNum)
{
continue;
}
PlayerInfo& player = _players[i];
player.PrevDefined = player.Defined;
player.Defined = false;
}
const s32 entityTypePlayerId = GetIdNumber(udtMagicNumberType::EntityType, udtEntityType::Player, parser._inProtocol);
for(u32 i = 0, count = arg.ChangedEntityCount; i < count; ++i)
{
idEntityStateBase* const es = arg.ChangedEntities[i].Entity;
if(arg.ChangedEntities[i].IsNewEvent ||
es == NULL ||
es->eType != entityTypePlayerId ||
es->clientNum < 0 ||
es->clientNum >= 64)
{
continue;
}
PlayerInfo& player = _players[es->clientNum];
player.Defined = true;
Float3::Copy(player.Position, es->pos.trBase);
}
//
// Step 2: handle pick-up and capture events
//
const s32 entityTypeEventId = GetIdNumber(udtMagicNumberType::EntityType, udtEntityType::Event, parser._inProtocol);
const s32 globalTeamSoundId = GetIdNumber(udtMagicNumberType::EntityEvent, udtEntityEvent::GlobalTeamSound, parser._inProtocol);
for(u32 i = 0, count = arg.ChangedEntityCount; i < count; ++i)
{
idEntityStateBase* const es = arg.ChangedEntities[i].Entity;
if(!arg.ChangedEntities[i].IsNewEvent ||
es == NULL ||
es->eType <= entityTypeEventId)
{
continue;
}
const s32 event = (es->eType - entityTypeEventId) & (~ID_ES_EVENT_BITS);
if(event == globalTeamSoundId)
{
const s32 soundIndex = es->eventParm;
if(soundIndex == 0 || soundIndex == 1)
{
const s32 playerIndex = es->generic1;
if(playerIndex < 0 || playerIndex >= 64)
{
continue;
}
const s32 captureTimeMs = parser._inServerTime;
const s32 durationMs = es->time;
const s32 pickupTimeMs = captureTimeMs - durationMs;
TeamInfo& team = _teams[soundIndex];
const s32 udtPlayerIndex = team.PlayerIndex;
udtParseDataCapture capture;
capture.GameStateIndex = _gameStateIndex;
capture.PickUpTimeMs = pickupTimeMs;
capture.CaptureTimeMs = captureTimeMs;
capture.PlayerIndex = playerIndex;
WriteStringToApiStruct(capture.MapName, _mapName);
capture.Flags = 0;
capture.Flags |= (u32)udtParseDataCaptureMask::PlayerIndexValid;
capture.Flags |= (u32)udtParseDataCaptureMask::PlayerNameValid;
if(playerIndex == _demoTakerIndex)
{
capture.Flags |= (u32)udtParseDataCaptureMask::DemoTaker;
}
else if(playerIndex == ps->clientNum)
{
capture.Flags |= (u32)udtParseDataCaptureMask::FirstPersonPlayer;
}
WriteStringToApiStruct(capture.PlayerName, GetPlayerName(playerIndex, parser));
FlagStatusCPMA& flagStatus = _flagStatusCPMA[soundIndex];
if(udtPlayerIndex == playerIndex)
{
capture.Flags |= (u32)udtParseDataCaptureMask::DistanceValid;
PlayerInfo& player = _players[playerIndex];
capture.Distance = Float3::Dist(player.PickupPosition, player.Position);
if(team.BasePickup && !flagStatus.InstantCapture)
{
capture.Flags |= (u32)udtParseDataCaptureMask::BaseToBase;
}
player.PickupPositionValid = false;
team.BasePickup = false;
team.PlayerIndex = -1;
}
else
{
// The last player for which we got a pick-up sound event
// is not the one the server says.
capture.Distance = -1.0f;
}
Captures.Add(capture);
flagStatus.InstantCapture = false;
}
else if(soundIndex == 4 || soundIndex == 5)
{
const s32 playerIndex = es->generic1;
if(playerIndex < 0 || playerIndex >= 64)
{
continue;
}
PlayerInfo& player = _players[playerIndex];
if(player.Defined && player.PrevDefined)
{
Float3::Copy(player.PickupPosition, player.Position);
player.PickupPositionValid = true;
}
else
{
player.PickupPositionValid = false;
}
const u32 teamIndex = (u32)soundIndex - 4;
TeamInfo& team = _teams[teamIndex];
team.BasePickup = WasFlagPickedUpInBase(teamIndex);
team.PlayerIndex = playerIndex;
}
}
}
}
void udtCapturesAnalyzer::ProcessGamestateMessageDummy(const udtGamestateCallbackArg&, udtBaseParser&)
{
}
void udtCapturesAnalyzer::ProcessCommandMessageDummy(const udtCommandCallbackArg&, udtBaseParser&)
{
}
void udtCapturesAnalyzer::ProcessSnapshotMessageDummy(const udtSnapshotCallbackArg&, udtBaseParser&)
{
}
void udtCapturesAnalyzer::ProcessGamestateMessageClearStates(const udtGamestateCallbackArg&, udtBaseParser& parser)
{
memset(_players, 0, sizeof(_players));
for(u32 i = 0; i < 64; ++i)
{
PlayerInfo& player = _players[i];
player.PickupTime = UDT_S32_MIN;
player.Defined = false;
player.PrevDefined = false;
player.PickupPositionValid = false;
Float3::Zero(player.PickupPosition);
Float3::Zero(player.Position);
}
memset(_teams, 0, sizeof(_teams));
for(u32 i = 0; i < 2; ++i)
{
TeamInfo& team = _teams[i];
team.PlayerIndex = -1;
team.FlagState = (u8)idFlagStatus::InBase;
team.PrevFlagState = (u8)idFlagStatus::InBase;
team.BasePickup = false;
}
const s32 flagStatusIdx = GetIdNumber(udtMagicNumberType::ConfigStringIndex, udtConfigStringIndex::FlagStatus, parser._inProtocol);
if(flagStatusIdx >= 0)
{
const udtString cs = parser.GetConfigString(flagStatusIdx);
if(cs.GetLength() >= 2)
{
const char* const csString = cs.GetPtr();
_teams[0].FlagState = (u8)(csString[0] - '0');
_teams[1].FlagState = (u8)(csString[1] - '0');
_teams[0].PrevFlagState = _teams[0].FlagState;
_teams[1].PrevFlagState = _teams[1].FlagState;
}
}
}
udtString udtCapturesAnalyzer::GetPlayerName(s32 playerIndex, udtBaseParser& parser)
{
if(playerIndex < 0 || playerIndex >= 64)
{
return udtString::NewNull();
}
udtVMScopedStackAllocator allocScope(*_tempAllocator);
const s32 csIndex = GetIdNumber(udtMagicNumberType::ConfigStringIndex, udtConfigStringIndex::FirstPlayer, parser._inProtocol) + playerIndex;
udtString playerName;
if(!ParseConfigStringValueString(playerName, *_tempAllocator, "n", parser.GetConfigString(csIndex).GetPtr()))
{
return udtString::NewNull();
}
return udtString::NewCleanCloneFromRef(StringAllocator, parser._inProtocol, playerName);
}
bool udtCapturesAnalyzer::WasFlagPickedUpInBase(u32 teamIndex)
{
if(teamIndex > 1)
{
return false;
}
const TeamInfo& team = _teams[teamIndex];
const u8 prevFlagStatus = team.PrevFlagState;
const u8 currFlagStatus = team.FlagState;
const u8 flagStatus = currFlagStatus == (u8)idFlagStatus::Carried ? prevFlagStatus : currFlagStatus;
const bool inBase = flagStatus == (u8)idFlagStatus::InBase;
return inBase;
}
void udtCapturesAnalyzer::ProcessPlayerConfigStringQLorOSP(const char* configString, udtBaseParser& parser, s32 playerIndex)
{
udtVMScopedStackAllocator tempAllocScope(*_tempAllocator);
udtString name;
if(ParseConfigStringValueString(name, *_tempAllocator, "n", configString))
{
_playerNames[playerIndex] = udtString::NewCloneFromRef(_playerNameAllocator, name);
}
else
{
_playerNames[playerIndex] = udtString::NewNull();
}
if(AreAllProtocolFlagsSet(parser._inProtocol, udtProtocolFlagsEx::QL_ClanName))
{
udtString clan;
if(ParseConfigStringValueString(clan, *_tempAllocator, "cn", configString))
{
_playerClanNames[playerIndex] = udtString::NewCloneFromRef(_playerNameAllocator, clan);
}
else
{
_playerClanNames[playerIndex] = udtString::NewNull();
}
}
}
void udtCapturesAnalyzer::ProcessFlagStatusCommandQLorOSP(const udtCommandCallbackArg&, udtBaseParser& parser)
{
const udtString cs = parser.GetTokenizer().GetArg(2);
if(cs.GetLength() >= 2)
{
_teams[0].PrevFlagState = _teams[0].FlagState;
_teams[1].PrevFlagState = _teams[1].FlagState;
const char* const csString = cs.GetPtr();
_teams[0].FlagState = (u8)(csString[0] - '0');
_teams[1].FlagState = (u8)(csString[1] - '0');
}
}
void udtCapturesAnalyzer::ProcessPrintCommandQLorOSP(const udtCommandCallbackArg&, udtBaseParser& parser)
{
// QL : "^4BLUE TEAM^3 CAPTURED the flag!^7 (^4BREAK ^7whaz captured in 0:12.490)\n"
// OSP: "^xFF00FF^6Raistlin^2 captured the BLUE flag! (held for 0:42.70)\n"
idTokenizer& tokenizer = parser._context->Tokenizer;
const udtString message = tokenizer.GetArg(1);
const bool qlMode = udtString::ContainsNoCase(message, "CAPTURED the flag!");
if(!qlMode &&
!udtString::ContainsNoCase(message, "captured the RED flag!") &&
!udtString::ContainsNoCase(message, "captured the BLUE flag!"))
{
return;
}
const udtString capturedIn = udtString::NewConstRef("captured in");
const udtString heldFor = udtString::NewConstRef("held for");
u32 capturedInIdx = 0;
u32 heldForIdx = 0;
const bool capturedInFound = udtString::ContainsNoCase(capturedInIdx, message, "captured in");
const bool heldForFound = udtString::ContainsNoCase(heldForIdx, message, "held for");
if(!capturedInFound && !heldForFound)
{
return;
}
u32 leftParenIdx = 0;
if(!udtString::FindFirstCharacterMatch(leftParenIdx, message, '('))
{
return;
}
u32 rightParenIdx = 0;
if(!udtString::FindFirstCharacterMatch(rightParenIdx, message, ')', leftParenIdx + 1))
{
return;
}
const u32 parenTextIdx = capturedInFound ? capturedInIdx : heldForIdx;
if(parenTextIdx < leftParenIdx || parenTextIdx > rightParenIdx)
{
return;
}
udtVMScopedStackAllocator tempAllocatorScope(*_tempAllocator);
udtString playerName;
if(qlMode)
{
playerName = udtString::NewSubstringClone(*_tempAllocator, message, leftParenIdx + 1, parenTextIdx - leftParenIdx - 2);
}
else
{
u32 capturedTheIdx = 0;
if(!udtString::ContainsNoCase(capturedTheIdx, message, " captured the "))
{
return;
}
playerName = udtString::NewSubstringClone(*_tempAllocator, message, 0, capturedTheIdx);
}
const udtString cleanPlayerName = udtString::NewCleanCloneFromRef(StringAllocator, parser._inProtocol, playerName);
const udtString parenText = capturedInFound ? capturedIn : heldFor;
const u32 durationIdx = parenTextIdx + parenText.GetLength() + 1;
if(durationIdx > rightParenIdx)
{
return;
}
const udtString duration = udtString::NewSubstringClone(*_tempAllocator, message, durationIdx, rightParenIdx - durationIdx);
s32 captureDuration = 0;
if(!ParseDuration(captureDuration, duration))
{
return;
}
const s32 time = parser._inServerTime;
u32 flags = 0;
if(capturedInFound)
{
flags |= (u32)udtParseDataCaptureMask::BaseToBase;
}
flags |= (u32)udtParseDataCaptureMask::PlayerNameValid;
f32 distance = -1.0f;
if(_lastCaptureQL.IsValid())
{
distance = _lastCaptureQL.Distance;
flags |= (u32)udtParseDataCaptureMask::DistanceValid;
_lastCaptureQL.Clear();
}
s32 playerIndex = -1;
if(ExtractPlayerIndexFromCaptureMessageQLorOSP(playerIndex, playerName, parser._inProtocol))
{
flags |= (u32)udtParseDataCaptureMask::PlayerIndexValid;
}
udtParseDataCapture capture;
capture.CaptureTimeMs = time;
capture.Distance = distance;
capture.Flags = flags;
capture.GameStateIndex = _gameStateIndex;
WriteStringToApiStruct(capture.MapName, _mapName);
capture.PickUpTimeMs = time - captureDuration;
capture.PlayerIndex = -1;
WriteStringToApiStruct(capture.PlayerName, cleanPlayerName);
Captures.Add(capture);
}
bool udtCapturesAnalyzer::ExtractPlayerIndexFromCaptureMessageQLorOSP(s32& playerIndex, const udtString& playerName, udtProtocol::Id protocol)
{
// dm_73: sprintf(name, "%s %s", cn, n) OR sprintf(name, "%s^7 %s", cn, n)
// dm_90: sprintf(name, "%s %s", cn, n) OR sprintf(name, "%s^7 %s", cn, n)
// dm_91: sprintf(name, "%s", n)
if(!AreAllProtocolFlagsSet(protocol, udtProtocolFlagsEx::QL_ClanName))
{
for(s32 i = 0; i < 64; ++i)
{
if(!_playerNames[i].IsValid())
{
continue;
}
if(udtString::Equals(_playerNames[i], playerName))
{
playerIndex = i;
return true;
}
}
return false;
}
for(s32 i = 0; i < 64; ++i)
{
if(!_playerNames[i].IsValid() ||
!_playerClanNames[i].IsValid())
{
continue;
}
if(udtString::IsEmpty(_playerClanNames[i]) &&
udtString::Equals(_playerNames[i], playerName))
{
playerIndex = i;
return true;
}
const udtString space = udtString::NewConstRef(" ");
const udtString* formattedNameParts[] =
{
&_playerClanNames[i],
&space,
&_playerNames[i]
};
udtVMScopedStackAllocator tempAllocScope(*_tempAllocator);
const udtString formattedName = udtString::NewFromConcatenatingMultiple(*_tempAllocator, formattedNameParts, UDT_COUNT_OF(formattedNameParts));
if(udtString::Equals(formattedName, playerName))
{
playerIndex = i;
return true;
}
const udtString spaceColor = udtString::NewConstRef("^7 ");
const udtString* formattedNamePartsColor[] =
{
&_playerClanNames[i],
&spaceColor,
&_playerNames[i]
};
const udtString formattedNameColor = udtString::NewFromConcatenatingMultiple(*_tempAllocator, formattedNamePartsColor, UDT_COUNT_OF(formattedNamePartsColor));
if(udtString::Equals(formattedNameColor, playerName))
{
playerIndex = i;
return true;
}
}
return false;
}
void udtCapturesAnalyzer::Clear()
{
_playerNameAllocator.Clear();
StringAllocator.Clear();
Captures.Clear();
}
| 0 | 0.861314 | 1 | 0.861314 | game-dev | MEDIA | 0.810732 | game-dev | 0.980444 | 1 | 0.980444 |
ezEngine/ezEngine | 1,413 | Code/Engine/Core/ResourceManager/Implementation/WorkerTasks.h | #pragma once
#include <Core/ResourceManager/Implementation/Declarations.h>
#include <Core/ResourceManager/ResourceTypeLoader.h>
#include <Foundation/Threading/TaskSystem.h>
#include <Foundation/Types/UniquePtr.h>
/// \brief [internal] Worker task for loading resources (typically from disk).
class EZ_CORE_DLL ezResourceManagerWorkerDataLoad final : public ezTask
{
public:
~ezResourceManagerWorkerDataLoad();
private:
friend class ezResourceManager;
friend class ezResourceManagerState;
ezResourceManagerWorkerDataLoad();
virtual void Execute() override;
};
/// \brief [internal] Worker task for uploading resource data.
/// Depending on the resource type, this may get scheduled to run on the main thread or on any thread.
class EZ_CORE_DLL ezResourceManagerWorkerUpdateContent final : public ezTask
{
public:
~ezResourceManagerWorkerUpdateContent();
ezResourceLoadData m_LoaderData;
ezResource* m_pResourceToLoad = nullptr;
ezResourceTypeLoader* m_pLoader = nullptr;
// this is only used to clean up a custom loader at the right time, if one is used
// m_pLoader is always set, no need to go through m_pCustomLoader
ezUniquePtr<ezResourceTypeLoader> m_pCustomLoader;
private:
friend class ezResourceManager;
friend class ezResourceManagerState;
friend class ezResourceManagerWorkerDataLoad;
ezResourceManagerWorkerUpdateContent();
virtual void Execute() override;
};
| 0 | 0.866047 | 1 | 0.866047 | game-dev | MEDIA | 0.847742 | game-dev | 0.737038 | 1 | 0.737038 |
MIA-Development-Team/Made-In-Abyss | 1,552 | src/main/java/com/altnoir/mia/worldgen/noise_setting/densityfunction/AbyssBrinkBigHole.java | package com.altnoir.mia.worldgen.noise_setting.densityfunction;
import com.mojang.serialization.MapCodec;
import net.minecraft.util.KeyDispatchDataCodec;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.levelgen.DensityFunction;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
public class AbyssBrinkBigHole implements DensityFunction.SimpleFunction {
public static final KeyDispatchDataCodec<AbyssBrinkBigHole> CODEC = KeyDispatchDataCodec.of(
MapCodec.unit(new AbyssBrinkBigHole(0L))
);
public AbyssBrinkBigHole(long seed) {
RandomSource randomsource = new LegacyRandomSource(seed);
randomsource.consumeCount(17292);
}
private static final Float AbyssBrinkBigRadius = 128.0F;
private static float getHeightValue(int x, int z) {
float d = Mth.sqrt((float) (x * x + z * z));
// 400 = √400 = 20区块.
float f = (AbyssBrinkHole.getAbyssRadius() + AbyssBrinkBigRadius) - d * 8.0F; // 深渊半径
f = Mth.clamp(f, -100.0F, 80.0F);
return f;
}
@Override
public double compute(DensityFunction.FunctionContext context) {
return (8.0 - (double) getHeightValue(context.blockX() / 8, context.blockZ() / 8)) / 16;
}
@Override
public double minValue() {
return -0.5625;
}
@Override
public double maxValue() {
return 0.84375;
}
@Override
public KeyDispatchDataCodec<? extends DensityFunction> codec() {
return CODEC;
}
} | 0 | 0.836707 | 1 | 0.836707 | game-dev | MEDIA | 0.894386 | game-dev | 0.883633 | 1 | 0.883633 |
PacktPublishing/Mastering-ROS-for-Robotics-Programming-Second-Edition | 1,984 | Chapter12/seven_dof_arm_test/src/add_collision_object.cpp | #include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit_msgs/AttachedCollisionObject.h>
#include <moveit_msgs/CollisionObject.h>
int main(int argc, char **argv)
{
// Initialize ROS, create the node handle and an async spinner
ros::init(argc, argv, "add_collision_objct");
ros::NodeHandle nh;
ros::AsyncSpinner spin(1);
spin.start();
// We obtain the current planning scene and wait until everything is up
// and running, otherwise the request won't succeed
moveit::planning_interface::PlanningSceneInterface current_scene;
sleep(5.0);
// We create a box with certain dimensions and orientation, we also
// give it a name which can later be used to remove it from the scene
// The dimensions of the box (and also the object type which in this case
// is box) is defined by a SolidPrimitive message, the pose of the box by a
// pose message
moveit_msgs::CollisionObject cylinder;
cylinder.id = "seven_dof_arm_cylinder";
shape_msgs::SolidPrimitive primitive;
primitive.type = primitive.CYLINDER;
primitive.dimensions.resize(3);
primitive.dimensions[0] = 0.6;
primitive.dimensions[1] = 0.2;
primitive.dimensions[2] = 0.2;
geometry_msgs::Pose pose;
pose.orientation.w = 1.0;
pose.position.x = 0.0;
pose.position.y = -0.4;
pose.position.z = 0.4;
cylinder.primitives.push_back(primitive);
cylinder.primitive_poses.push_back(pose);
cylinder.operation = cylinder.ADD;
cylinder.header.frame_id = "base_link";
std::vector<moveit_msgs::CollisionObject> collision_objects;
collision_objects.push_back(cylinder);
// Once all of the objects (in this case just one) have been added to the
// vector, we tell the planning scene to add our new box
current_scene.addCollisionObjects(collision_objects);
sleep(2);
ros::shutdown();
return 0;
}
| 0 | 0.727943 | 1 | 0.727943 | game-dev | MEDIA | 0.649575 | game-dev | 0.604178 | 1 | 0.604178 |
Rockbox/rockbox | 27,989 | apps/plugins/sdl/progs/duke3d/Game/src/config.c | //-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment
This file is part of Duke Nukem 3D version 1.5 - Atomic Edition
Duke Nukem 3D 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
aint32_t with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include "duke3d.h"
#include "scriplib.h"
#include "../../Engine/src/build.h"
// we load this in to get default button and key assignments
// as well as setting up function mappings
#include "_functio.h"
//
// Sound variables
//
int32_t FXDevice;
int32_t MusicDevice;
int32_t FXVolume;
int32_t MusicVolume;
int32_t SoundToggle;
int32_t MusicToggle;
int32_t VoiceToggle;
int32_t AmbienceToggle;
int32_t OpponentSoundToggle; // xduke to toggle opponent's sounds on/off in DM (duke 1.3d scheme)
fx_blaster_config BlasterConfig;
int32_t NumVoices;
int32_t NumChannels;
int32_t NumBits;
int32_t MixRate;
int32_t MidiPort;
int32_t ReverseStereo;
int32_t ControllerType;
int32_t MouseAiming = 0;
int32_t BFullScreen = 0;
//
// Screen variables
//
int32 ScreenMode=2;
int32 ScreenWidth = LCD_WIDTH;
int32 ScreenHeight = LCD_HEIGHT;
//
// Mouse variables
//
int32 mouseSensitivity_X;
int32 mouseSensitivity_Y;
static char setupfilename[512] = "/.rockbox/duke3d/duke3d.cfg";
static int32 scripthandle;
static int32 setupread=0;
/*
===================
=
= CONFIG_GetSetupFilename
=
===================
*/
#define MAXSETUPFILES 20
void CONFIG_GetSetupFilename( void )
{
int32 i;
setupfilename[0] = '\0';
// Are we trying to load a mod?
#if 0
if(getGameDir()[0] != '\0'){
FILE *fp = NULL;
//Yes
sprintf(setupfilename, "%s/%s", getGameDir(), SETUPFILENAME);
// let's make sure it's actually there
fp = fopen(setupfilename, "r");
if(fp)
fclose(fp);
else{
// It doesn't exist, so revert to the main one.
printf("Config file: %s does not exist, using main config.\n", setupfilename);
sprintf(setupfilename, "%s", SETUPFILENAME);
}
}else{
#endif
//No
sprintf(setupfilename, "%s/%s", getGameDir(), SETUPFILENAME);
//}
printf("Using Setup file: '%s'\n",setupfilename);
// i=clock()+(3*CLOCKS_PER_SEC/4);
// while (clock()<i){
// ;
// }
}
/*
===================
=
= CONFIG_FunctionNameToNum
=
===================
*/
int32 CONFIG_FunctionNameToNum( char * func )
{
int32 i;
for (i=0;i<NUMGAMEFUNCTIONS;i++)
{
if (!stricmp(func,gamefunctions[i]))
{
return i;
}
}
return -1;
}
/*
===================
=
= CONFIG_FunctionNumToName
=
===================
*/
char * CONFIG_FunctionNumToName( int32 func )
{
if (-1 < func && func < NUMGAMEFUNCTIONS)
{
return gamefunctions[func];
}
else
{
return NULL;
}
}
/*
===================
=
= CONFIG_AnalogNameToNum
=
===================
*/
int32 CONFIG_AnalogNameToNum( char * func )
{
if (!stricmp(func,"analog_turning"))
{
return analog_turning;
}
if (!stricmp(func,"analog_strafing"))
{
return analog_strafing;
}
if (!stricmp(func,"analog_moving"))
{
return analog_moving;
}
if (!stricmp(func,"analog_lookingupanddown"))
{
return analog_lookingupanddown;
}
return -1;
}
/*
===================
=
= CONFIG_SetDefaults
=
===================
*/
void CONFIG_SetDefaults( void )
{
// sound
SoundToggle = 1;
MusicToggle = 1;
VoiceToggle = 1;
AmbienceToggle = 1;
OpponentSoundToggle = 1;
FXVolume = 220;
MusicVolume = 200;
FXDevice = SoundScape;
MusicDevice = -1;
ReverseStereo = 0;
// mouse
mouseSensitivity_X = 16;
mouseSensitivity_Y = mouseSensitivity_X;
// game
ps[0].aim_mode = 0;
ud.screen_size = 8;
ud.extended_screen_size = 0;
ud.screen_tilting = 1;
ud.brightness = 16;
ud.auto_run = 1;
ud.showweapons = 0;
ud.tickrate = 0;
ud.scrollmode = 0;
ud.shadows = 1;
ud.detail = 1;
ud.lockout = 0;
ud.pwlockout[0] = '\0';
ud.crosshair = 1;
ud.m_marker = 1; // for multiplayer
ud.m_ffire = 1;
ud.showcinematics = 1;
ud.weaponautoswitch = 0;
ud.hideweapon = 0;
ud.auto_aim = 2; // full by default
ud.gitdat_mdk = 0;
ud.playing_demo_rev = 0;
// com
strcpy(ud.rtsname,"DUKE.RTS");
strcpy(ud.ridecule[0],"An inspiration for birth control.");
strcpy(ud.ridecule[1],"You're gonna die for that!");
strcpy(ud.ridecule[2],"It hurts to be you.");
strcpy(ud.ridecule[3],"Lucky Son of a Bitch.");
strcpy(ud.ridecule[4],"Hmmm....Payback time.");
strcpy(ud.ridecule[5],"You bottom dwelling scum sucker.");
strcpy(ud.ridecule[6],"Damn, you're ugly.");
strcpy(ud.ridecule[7],"Ha ha ha...Wasted!");
strcpy(ud.ridecule[8],"You suck!");
strcpy(ud.ridecule[9],"AARRRGHHHHH!!!");
// Controller
ControllerType = controltype_keyboardandmouse;
}
/*
===================
=
= CONFIG_ReadKeys
=
===================
*/
void CONFIG_ReadKeys( void )
{
printf("CONFIG_ReadKeys\n");
int32 i;
int32 numkeyentries;
int32 function;
char keyname1[80];
char keyname2[80];
kb_scancode key1,key2;
// set default keys in case duke3d.cfg was not found
// FIX_00011: duke3d.cfg not needed anymore to start the game. Will create a default one
// if not found and use default keys.
for(i=0; i<NUMKEYENTRIES; i++){
function = CONFIG_FunctionNameToNum(keydefaults[i].entryKey);
key1 = (byte) KB_StringToScanCode( keydefaults[i].keyname1 );
key2 = (byte) KB_StringToScanCode( keydefaults[i].keyname2 );
CONTROL_MapKey( function, key1, key2 );
}
numkeyentries = SCRIPT_NumberEntries( scripthandle, "KeyDefinitions" );
for (i=0;i<numkeyentries;i++) // i = number in which the functions appear in duke3d.cfg
{
function = CONFIG_FunctionNameToNum(SCRIPT_Entry( scripthandle, "KeyDefinitions", i ));
if (function != -1) // ensure it is in the list gamefunctions[function]
{
memset(keyname1,0,sizeof(keyname1));
memset(keyname2,0,sizeof(keyname2));
SCRIPT_GetDoubleString
(
scripthandle,
"KeyDefinitions",
SCRIPT_Entry( scripthandle,"KeyDefinitions", i ),
keyname1,
keyname2
);
key1 = 0;
key2 = 0;
if (keyname1[0])
{
key1 = (byte) KB_StringToScanCode( keyname1 );
}
if (keyname2[0])
{
key2 = (byte) KB_StringToScanCode( keyname2 );
}
CONTROL_MapKey( function, key1, key2 );
}
}
}
/*
===================
=
= CONFIG_SetupMouse
=
===================
*/
void CONFIG_SetupMouse( int32 scripthandle )
{
int32 i;
char str[80];
char temp[80];
int32 function, scale;
for (i=0;i<MAXMOUSEBUTTONS;i++)
{
sprintf(str,"MouseButton%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
CONTROL_MapButton( function, i, false );
sprintf(str,"MouseButtonClicked%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
CONTROL_MapButton( function, i, true );
}
// map over the axes
for (i=0;i<MAXMOUSEAXES;i++)
{
sprintf(str,"MouseAnalogAxes%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_AnalogNameToNum(temp);
if (function != -1)
{
//TODO Fix the Analog mouse axis issue. Just make a new function for registering them.
//CONTROL_MapAnalogAxis(i,function);
}
sprintf(str,"MouseDigitalAxes%d_0",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
CONTROL_MapDigitalAxis( i, function, 0 );
sprintf(str,"MouseDigitalAxes%d_1",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
CONTROL_MapDigitalAxis( i, function, 1 );
sprintf(str,"MouseAnalogScale%d",i);
SCRIPT_GetNumber(scripthandle, "Controls", str,&scale);
//TODO: Fix the Analog mouse scale issue. Just make a new function for registering them.
//CONTROL_SetAnalogAxisScale( i, scale );
}
SCRIPT_GetNumber( scripthandle, "Controls","MouseSensitivity_X_Rancid",&mouseSensitivity_X);
if(mouseSensitivity_X>63 || mouseSensitivity_X < 0)
mouseSensitivity_X = 15;
// FIX_00014: Added Y cursor setup for mouse sensitivity in the menus
// Copy Sensitivity_X into Sensitivity_Y in case it is not set.
mouseSensitivity_Y = mouseSensitivity_X;
SCRIPT_GetNumber( scripthandle, "Controls","MouseSensitivity_Y_Rancid",&mouseSensitivity_Y);
if(mouseSensitivity_Y>63 || mouseSensitivity_Y < 0)
mouseSensitivity_Y = 15;
}
/*
===================
=
= CONFIG_SetupGamePad
=
===================
*/
void CONFIG_SetupGamePad( int32 scripthandle )
{
int32 i;
char str[80];
char temp[80];
int32 function;
for (i=0;i<MAXJOYBUTTONS;i++)
{
sprintf(str,"JoystickButton%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapButton( function, i, false );
sprintf(str,"JoystickButtonClicked%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapButton( function, i, true );
}
// map over the axes
for (i=0;i<MAXGAMEPADAXES;i++)
{
sprintf(str,"GamePadDigitalAxes%d_0",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapDigitalAxis( i, function, 0 );
sprintf(str,"GamePadDigitalAxes%d_1",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapDigitalAxis( i, function, 1 );
}
SCRIPT_GetNumber( scripthandle, "Controls","JoystickPort",&function);
CONTROL_JoystickPort = function;
}
/*
===================
=
= CONFIG_SetupJoystick
=
===================
*/
void CONFIG_SetupJoystick( int32 scripthandle )
{
int32 i, j;
char str[80];
char temp[80];
int32 function, deadzone;
float scale;
for (i=0;i<MAXJOYBUTTONS;i++)
{
sprintf(str,"JoystickButton%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapJoyButton( function, i, false );
sprintf(str,"JoystickButtonClicked%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapJoyButton( function, i, true );
}
// map over the axes
for (i=0;i<MAXJOYAXES;i++)
{
sprintf(str,"JoystickAnalogAxes%d",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_AnalogNameToNum(temp);
//if (function != -1)
//{
CONTROL_MapAnalogAxis(i,function);
//}
sprintf(str,"JoystickDigitalAxes%d_0",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapDigitalAxis( i, function, 0 );
sprintf(str,"JoystickDigitalAxes%d_1",i);
memset(temp,0,sizeof(temp));
SCRIPT_GetString(scripthandle, "Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
CONTROL_MapDigitalAxis( i, function, 1 );
sprintf(str,"JoystickAnalogScale%d",i);
SCRIPT_GetFloat(scripthandle, "Controls", str,&scale);
CONTROL_SetAnalogAxisScale( i, scale );
deadzone = 0;
sprintf(str,"JoystickAnalogDeadzone%d",i);
SCRIPT_GetNumber(scripthandle, "Controls", str, &deadzone);
CONTROL_SetAnalogAxisDeadzone( i, deadzone);
}
// map over the "top hats"
for (i=0; i < MAXJOYHATS; i++)
{
for(j=0; j < 8; j++) // 8? because hats can have 8 different values
{
sprintf(str,"JoystickHat%d_%d",i, j);
memset(temp,0,sizeof(temp));
SCRIPT_GetString( scripthandle,"Controls", str,temp);
function = CONFIG_FunctionNameToNum(temp);
if (function != -1)
{
CONTROL_MapJoyHat( function, i, j);
}
}
}
// read in JoystickPort
SCRIPT_GetNumber( scripthandle, "Controls","JoystickPort",&function);
CONTROL_JoystickPort = function;
// read in rudder state
SCRIPT_GetNumber( scripthandle, "Controls","EnableRudder",(int32_t*)&CONTROL_RudderEnabled);
}
void readsavenames(void)
{
int32_t dummy;
short i;
uint8_t fn[] = "game_.sav";
FILE *fil;
char fullpathsavefilename[256];
for (i=0;i<10;i++)
{
fn[4] = i+'0';
// Are we loading a TC?
if(getGameDir()[0] != '\0')
{
// Yes
sprintf(fullpathsavefilename, "%s/%s", getGameDir(), fn);
}
else
{
// No
sprintf(fullpathsavefilename, "%s", fn);
}
if ((fil = fopen(fullpathsavefilename,"rb")) == NULL ) continue;
dfread(&dummy,4,1,fil);
// FIX_00015: Backward compliance with older demos (down to demos v27, 28, 116 and 117 only)
if( dummy != BYTEVERSION &&
dummy != BYTEVERSION_27 &&
dummy != BYTEVERSION_28 &&
dummy != BYTEVERSION_116 &&
dummy != BYTEVERSION_117) continue;
// FIX_00092: corrupted saved files making the following saved files invisible (Bryzian)
dfread(&dummy,4,1,fil);
dfread(&ud.savegame[i][0],19,1,fil);
fclose(fil);
}
}
/*
===================
=
= CONFIG_ReadSetup
=
===================
*/
//int32 dukever13;
void CONFIG_ReadSetup( void )
{
int32 dummy;
char commmacro[] = COMMMACRO;
FILE* setup_file_hdl;
printf("CONFIG_ReadSetup...\n");
if (!SafeFileExists(setupfilename))
{
// FIX_00011: duke3d.cfg not needed anymore to start the game. Will create a default one
// if not found and use default keys.
printf("%s does not exist. Don't forget to set it up!\n" ,setupfilename);
setup_file_hdl = fopen (setupfilename, "w"); // create it...
if(setup_file_hdl)
fclose(setup_file_hdl);
}
CONFIG_SetDefaults();
scripthandle = SCRIPT_Load( setupfilename );
for(dummy = 0;dummy < 10;dummy++)
{
commmacro[13] = dummy+'0';
SCRIPT_GetString( scripthandle, "Comm Setup",commmacro,ud.ridecule[dummy]);
}
SCRIPT_GetString( scripthandle, "Comm Setup","PlayerName",&myname[0]);
dummy = CheckParm("NAME");
if( dummy ) strcpy(myname,_argv[dummy+1]);
dummy = CheckParm("MAP");
if( dummy )
{
if (!VOLUMEONE)
{
//boardfilename might be set from commandline only zero if we are replacing
boardfilename[0] = 0;
strcpy(boardfilename,_argv[dummy+1]);
if( strchr(boardfilename,'.') == 0)
strcat(boardfilename,".map");
printf("Using level: '%s'.\n",boardfilename);
}
else
{
Error(EXIT_SUCCESS, "The -map option does not work with the Shareware version of duke3d.grp\n"
"Change your duke3d.grp file to the 1.3d version or 1.5 Atomic version\n");
}
}
SCRIPT_GetString( scripthandle, "Comm Setup","RTSName",&ud.rtsname[0]);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "Shadows",&ud.shadows);
SCRIPT_GetString( scripthandle, "Screen Setup","Password",&ud.pwlockout[0]);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "Detail",&ud.detail);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "Tilt",&ud.screen_tilting);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "Messages",&ud.fta_on);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenWidth",&ScreenWidth);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenHeight",&ScreenHeight);
// SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenMode",&ScreenMode);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenGamma",&ud.brightness);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenSize",&ud.screen_size);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "ExtScreenSize",&ud.extended_screen_size);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "Out",&ud.lockout);
SCRIPT_GetNumber( scripthandle, "Screen Setup", "ShowFPS",&ud.tickrate);
ud.tickrate &= 1;
SCRIPT_GetNumber( scripthandle, "Misc", "Executions",&ud.executions);
ud.executions++;
SCRIPT_GetNumber( scripthandle, "Misc", "RunMode",&ud.auto_run);
SCRIPT_GetNumber( scripthandle, "Misc", "Crosshairs",&ud.crosshair);
SCRIPT_GetNumber( scripthandle, "Misc", "ShowCinematics",&ud.showcinematics);
SCRIPT_GetNumber( scripthandle, "Misc", "WeaponAutoSwitch",&ud.weaponautoswitch);
SCRIPT_GetNumber( scripthandle, "Misc", "HideWeapon",&ud.hideweapon);
SCRIPT_GetNumber( scripthandle, "Misc", "ShowWeapon",&ud.showweapons);
SCRIPT_GetNumber( scripthandle, "Misc", "AutoAim",&ud.auto_aim);
if(ud.auto_aim!=1 && ud.auto_aim != 2)
ud.auto_aim = 2; // avoid people missing with the cfg to go in a deadlock
SCRIPT_GetNumber( scripthandle, "Misc", "GitDatMdk",&ud.gitdat_mdk);
if(ud.mywchoice[0] == 0 && ud.mywchoice[1] == 0)
{
ud.mywchoice[0] = 3;
ud.mywchoice[1] = 4;
ud.mywchoice[2] = 5;
ud.mywchoice[3] = 7;
ud.mywchoice[4] = 8;
ud.mywchoice[5] = 6;
ud.mywchoice[6] = 0;
ud.mywchoice[7] = 2;
ud.mywchoice[8] = 9;
ud.mywchoice[9] = 1;
for(dummy=0;dummy<10;dummy++)
{
sprintf(buf,"WeaponChoice%d",dummy);
SCRIPT_GetNumber( scripthandle, "Misc", buf, &ud.mywchoice[dummy]);
}
}
SCRIPT_GetNumber( scripthandle, "Sound Setup", "FXDevice",&FXDevice);
if (FXDevice != NumSoundCards)
FXDevice = SoundScape;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "MusicDevice",&MusicDevice);
// FIX_00015: Forced NumVoices=8, NumChannels=2, NumBits=16, MixRate=44100, ScreenMode = x(
// (ScreenMode has no meaning anymore)
SCRIPT_GetNumber( scripthandle, "Sound Setup", "FXVolume",&FXVolume);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "MusicVolume",&MusicVolume);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "SoundToggle",&SoundToggle);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "MusicToggle",&MusicToggle);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "VoiceToggle",&VoiceToggle);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "AmbienceToggle",&AmbienceToggle);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "OpponentSoundToggle",&OpponentSoundToggle);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "NumVoices",&NumVoices);
NumVoices = 32;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "NumChannels",&NumChannels);
NumChannels = 2;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "NumBits",&NumBits);
NumBits = 16;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "MixRate",&MixRate);
MixRate = RB_SAMPR;
printf("MixRate = %d Hz", MixRate);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "MidiPort",&MidiPort);
SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterAddress",&dummy);
BlasterConfig.Address = dummy;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterType",&dummy);
BlasterConfig.Type = dummy;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterInterrupt",&dummy);
BlasterConfig.Interrupt = dummy;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterDma8",&dummy);
BlasterConfig.Dma8 = dummy;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterDma16",&dummy);
BlasterConfig.Dma16 = dummy;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterEmu",&dummy);
BlasterConfig.Emu = dummy;
SCRIPT_GetNumber( scripthandle, "Sound Setup", "ReverseStereo",&ReverseStereo);
SCRIPT_GetNumber( scripthandle, "Controls","ControllerType",&ControllerType);
SCRIPT_GetNumber( scripthandle, "Controls","MouseAimingFlipped",&ud.mouseflip);
SCRIPT_GetNumber( scripthandle, "Controls","MouseAiming",&MouseAiming);
SCRIPT_GetNumber( scripthandle, "Controls","GameMouseAiming",(int32 *)&ps[0].aim_mode);
SCRIPT_GetNumber( scripthandle, "Controls","AimingFlag",(int32 *)&myaimmode);
CONTROL_ClearAssignments();
CONFIG_ReadKeys();
switch (ControllerType)
{
case controltype_keyboardandmouse:
{
CONFIG_SetupMouse(scripthandle);
}
break;
case controltype_keyboardandjoystick:
case controltype_keyboardandflightstick:
case controltype_keyboardandthrustmaster:
{
CONTROL_JoystickEnabled = 1;
CONFIG_SetupJoystick(scripthandle);
}
break;
case controltype_keyboardandgamepad:
{
CONFIG_SetupGamePad(scripthandle);
}
break;
case controltype_joystickandmouse:
{
CONTROL_JoystickEnabled = 1;
CONFIG_SetupJoystick(scripthandle);
CONFIG_SetupMouse(scripthandle);
}
break;
default:
{
CONFIG_SetupMouse(scripthandle);
}
}
setupread = 1;
}
/*
===================
=
= CONFIG_WriteSetup
=
===================
*/
void CONFIG_WriteSetup( void )
{
int32 dummy, i;
char commmacro[] = COMMMACRO;
if (!setupread) return;
printf("CONFIG_WriteSetup...\n");
SCRIPT_PutNumber( scripthandle, "Screen Setup", "Shadows",ud.shadows,false,false);
SCRIPT_PutString( scripthandle, "Screen Setup", "Password",ud.pwlockout);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "Detail",ud.detail,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "Tilt",ud.screen_tilting,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "Messages",ud.fta_on,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "Out",ud.lockout,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "ShowFPS",ud.tickrate&1,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "ScreenWidth",xdim,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "ScreenHeight",ydim,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "Fullscreen",BFullScreen,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "FXVolume",FXVolume,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "MusicVolume",MusicVolume,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "FXDevice",FXDevice,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "MusicDevice",MusicDevice,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "SoundToggle",SoundToggle,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "VoiceToggle",VoiceToggle,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "AmbienceToggle",AmbienceToggle,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "OpponentSoundToggle",OpponentSoundToggle,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "MusicToggle",MusicToggle,false,false);
SCRIPT_PutNumber( scripthandle, "Sound Setup", "ReverseStereo",ReverseStereo,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "ScreenSize",ud.screen_size,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "ExtScreenSize",ud.extended_screen_size,false,false);
SCRIPT_PutNumber( scripthandle, "Screen Setup", "ScreenGamma",ud.brightness,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "Executions",ud.executions,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "RunMode",ud.auto_run,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "Crosshairs",ud.crosshair,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "ShowCinematics",ud.showcinematics,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "HideWeapon",ud.hideweapon,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "ShowWeapon",ud.showweapons,false,false);
SCRIPT_PutNumber( scripthandle, "Misc", "WeaponAutoSwitch",ud.weaponautoswitch,false,false);
if( nHostForceDisableAutoaim == 0) // do not save Host request to have AutoAim Off.
SCRIPT_PutNumber( scripthandle, "Misc", "AutoAim",ud.auto_aim,false,false);
SCRIPT_PutNumber( scripthandle, "Controls", "MouseAimingFlipped",ud.mouseflip,false,false);
SCRIPT_PutNumber( scripthandle, "Controls","MouseAiming",MouseAiming,false,false);
SCRIPT_PutNumber( scripthandle, "Controls","GameMouseAiming",(int32) ps[myconnectindex].aim_mode,false,false);
SCRIPT_PutNumber( scripthandle, "Controls","AimingFlag",(int32_t) myaimmode,false,false);
// FIX_00016: Build in Keyboard/mouse setup. Mouse now faster.
for(i=0; i<MAXMOUSEBUTTONS; i++)
{
sprintf((char *)tempbuf, "MouseButton%d", i);
SCRIPT_PutString(scripthandle, "Controls", (char *)tempbuf,
(MouseMapping[i]!=-1)?CONFIG_FunctionNumToName(MouseMapping[i]):"");
}
for (i=0;i<MAXMOUSEAXES*2;i++)
{
sprintf((char *)tempbuf, "MouseDigitalAxes%d_%d", i>>1, i&1);
SCRIPT_PutString(scripthandle, "Controls", (char *)tempbuf,
(MouseDigitalAxeMapping[i>>1][i&1]!=-1)?CONFIG_FunctionNumToName(MouseDigitalAxeMapping[i>>1][i&1]):"");
}
for(i=0; i<NUMGAMEFUNCTIONS; i++) // write keys
{
SCRIPT_PutDoubleString(
scripthandle,
"KeyDefinitions",
gamefunctions[i],
KB_ScanCodeToString( KeyMapping[i].key1 )?KB_ScanCodeToString( KeyMapping[i].key1 ):"",
KB_ScanCodeToString( KeyMapping[i].key2 )?KB_ScanCodeToString( KeyMapping[i].key2 ):"");
}
for(dummy=0;dummy<10;dummy++)
{
sprintf(buf,"WeaponChoice%d",dummy);
SCRIPT_PutNumber( scripthandle, "Misc",buf,ud.mywchoice[dummy],false,false);
}
dummy = CONTROL_GetMouseSensitivity_X();
SCRIPT_PutNumber( scripthandle, "Controls","MouseSensitivity_X_Rancid",dummy,false,false);
dummy = CONTROL_GetMouseSensitivity_Y();
SCRIPT_PutNumber( scripthandle, "Controls","MouseSensitivity_Y_Rancid",dummy,false,false);
SCRIPT_PutNumber( scripthandle, "Controls","ControllerType",ControllerType,false,false);
SCRIPT_PutString( scripthandle, "Comm Setup","PlayerName",myname);
SCRIPT_PutString( scripthandle, "Comm Setup","RTSName",ud.rtsname);
for(dummy = 0;dummy < 10;dummy++)
{
commmacro[13] = dummy+'0';
SCRIPT_PutString( scripthandle, "Comm Setup",commmacro,ud.ridecule[dummy]);
}
SCRIPT_Save (scripthandle, setupfilename);
SCRIPT_Free (scripthandle);
}
| 0 | 0.650877 | 1 | 0.650877 | game-dev | MEDIA | 0.742182 | game-dev | 0.901079 | 1 | 0.901079 |
CraftJarvis/ROCKET-1 | 3,208 | rocket/stark_tech/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/RewardForDistanceTraveledToCompassTargetImplementation.java | package com.microsoft.Malmo.MissionHandlers;
import com.microsoft.Malmo.Schemas.MissionInit;
import com.microsoft.Malmo.Schemas.RewardForDistanceTraveledToCompassTarget;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
public class RewardForDistanceTraveledToCompassTargetImplementation extends RewardBase
{
RewardForDistanceTraveledToCompassTarget params;
double previousDistance;
float totalReward;
boolean positionInitialized;
BlockPos prevSpawn;
@Override
public boolean parseParameters(Object params)
{
super.parseParameters(params);
if (params == null || !(params instanceof RewardForDistanceTraveledToCompassTarget))
return false;
this.params = (RewardForDistanceTraveledToCompassTarget)params;
EntityPlayerSP player = Minecraft.getMinecraft().player;
if( player != null && player.world != null){
prevSpawn = player.world.getSpawnPoint();
}
else{
prevSpawn = new BlockPos(0,0,0);
}
this.previousDistance = 0;
this.totalReward = 0;
this.positionInitialized = false;
return true;
}
@Override
public void getReward(MissionInit missionInit, MultidimensionalReward reward)
{
boolean sendReward = false;
EntityPlayerSP player = Minecraft.getMinecraft().player;
BlockPos spawn = player.world.getSpawnPoint();
Vec3d playerLoc = player.getPositionVector();
Vec3d spawnPos = new Vec3d(spawn.getX(), spawn.getY(), spawn.getZ());
double currentDistance = playerLoc.distanceTo(spawnPos);
float delta = !positionInitialized ? 0.0f : (float)(this.previousDistance - currentDistance);
switch (this.params.getDensity()) {
case MISSION_END:
this.totalReward += this.params.getRewardPerBlock().floatValue() * delta;
sendReward = reward.isFinalReward();
break;
case PER_TICK:
this.totalReward = this.params.getRewardPerBlock().floatValue() * delta;
sendReward = true;
break;
case PER_TICK_ACCUMULATED:
this.totalReward += this.params.getRewardPerBlock().floatValue() * delta;
sendReward = true;
break;
default:
break;
}
// Avoid sending large rewards as the result of an initial teleport event
if (this.prevSpawn.getX() != spawn.getX() ||
this.prevSpawn.getY() != spawn.getY() ||
this.prevSpawn.getZ() != spawn.getZ()) {
this.totalReward = 0;
} else{
this.positionInitialized = true;
}
this.previousDistance = currentDistance;
this.prevSpawn = spawn;
super.getReward(missionInit, reward);
if (sendReward)
{
float adjusted_reward = adjustAndDistributeReward(this.totalReward, this.params.getDimension(), this.params.getRewardDistribution());
reward.add(this.params.getDimension(), adjusted_reward);
}
}
}
| 0 | 0.902938 | 1 | 0.902938 | game-dev | MEDIA | 0.972791 | game-dev | 0.898889 | 1 | 0.898889 |
OpenRA/OpenRA | 1,952 | OpenRA.Mods.Common/Widgets/Logic/Ingame/Hotkeys/EditorQuickSaveHotkeyLogic.cs | #region Copyright & License Information
/*
* Copyright (c) The OpenRA Developers and Contributors
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileSystem;
using OpenRA.Mods.Common.Lint;
using OpenRA.Mods.Common.Traits;
using OpenRA.Widgets;
namespace OpenRA.Mods.Common.Widgets.Logic.Ingame
{
[ChromeLogicArgsHotkeys("EditorQuickSaveKey")]
public class EditorQuickSaveHotkeyLogic : SingleHotkeyBaseLogic
{
readonly World world;
readonly ModData modData;
[ObjectCreator.UseCtor]
public EditorQuickSaveHotkeyLogic(Widget widget, ModData modData, World world, Dictionary<string, MiniYaml> logicArgs)
: base(widget, modData, "QuickSaveKey", "GLOBAL_KEYHANDLER", logicArgs)
{
this.world = world;
this.modData = modData;
}
protected override bool OnHotkeyActivated(KeyInput keyInput)
{
var actionManager = world.WorldActor.TraitOrDefault<EditorActionManager>();
if (actionManager != null && (!actionManager.Modified || actionManager.SaveFailed))
return false;
var map = world.Map;
void SaveMap(string combinedPath)
{
var editorActorLayer = world.WorldActor.Trait<EditorActorLayer>();
var actorDefinitions = editorActorLayer.Save();
if (actorDefinitions != null)
map.ActorDefinitions = actorDefinitions;
var playerDefinitions = editorActorLayer.Players.ToMiniYaml();
if (playerDefinitions != null)
map.PlayerDefinitions = playerDefinitions;
var package = (IReadWritePackage)map.Package;
SaveMapLogic.SaveMapInner(map, package, world, modData);
}
SaveMapLogic.SaveMap(modData, world, map, map.Package?.Name, SaveMap);
return true;
}
}
}
| 0 | 0.719991 | 1 | 0.719991 | game-dev | MEDIA | 0.5443 | game-dev | 0.651102 | 1 | 0.651102 |
jaredballou/insurgency-sourcemod | 3,308 | scripting/entcontrol/NPCs/antlion.sp | /*
------------------------------------------------------------------------------------------
EntControl::AntLion
by Raffael 'LeGone' Holz
------------------------------------------------------------------------------------------
*/
public InitAntlion()
{
PrecacheModel("models/antlion.mdl");
PrecacheSound("npc/antlion/attack_double3.wav");
PrecacheSound("npc/antlion/idle3.wav");
PrecacheSound("npc/antlion/distract1.wav");
}
/*
------------------------------------------------------------------------------------------
Command_AntLion
------------------------------------------------------------------------------------------
*/
public Action:Command_AntLion(client, args)
{
if (!CanUseCMD(client, gAdminFlagNPC)) return (Plugin_Handled);
decl Float:vPosition[3];
if(GetPlayerEye(client, vPosition))
AntLion_Spawn(vPosition);
else
PrintHintText(client, "%t", "Wrong entity");
return (Plugin_Handled);
}
/*
------------------------------------------------------------------------------------------
AntLion_Spawn
------------------------------------------------------------------------------------------
*/
public AntLion_Spawn(Float:vPosition[3])
{
// Spawn
new monster = BaseNPC_Spawn(vPosition, "models/antlion.mdl", AntLion_SeekThink, "npc_antlion");
SDKHook(monster, SDKHook_OnTakeDamage, AntLion_DamageHook);
}
/*
------------------------------------------------------------------------------------------
AntLion_SeekThink
------------------------------------------------------------------------------------------
*/
public Action:AntLion_SeekThink(Handle:timer, any:monsterRef)
{
new monster = EntRefToEntIndex(monsterRef);
if (monster != INVALID_ENT_REFERENCE && BaseNPC_IsAlive(monster))
{
new target = BaseNPC_GetTarget(monster);
if (target > 0)
{
new Float:vClientPosition[3], Float:vEntPosition[3];
GetClientEyePosition(target, vClientPosition);
GetEntPropVector(monster, Prop_Send, "m_vecOrigin", vEntPosition);
if ((GetVectorDistance(vClientPosition, vEntPosition, false) < 120.0) && BaseNPC_CanSeeEachOther(monster, target))
{
BaseNPC_HurtPlayer(monster, target, 57);
BaseNPC_PlaySound(monster, "npc/antlion/attack_double3.wav");
BaseNPC_SetAnimation(monster, "attack2", 1.7);
/*
new Float:vReturn[3];
MakeVectorFromPoints(vEntPosition, vClientPosition, vReturn);
GetVectorAngles(vReturn, vReturn);
NormalizeVector(vReturn, vReturn);
ScaleVector(vReturn, 3000.0);
TeleportEntity(target, NULL_VECTOR, NULL_VECTOR, vReturn);
*/
}
else
{
BaseNPC_SetAnimation(monster, "walk_all");
}
}
else
{
BaseNPC_PlaySound(monster, "npc/antlion/idle3.wav");
BaseNPC_SetAnimation(monster, "idle");
}
return (Plugin_Continue);
}
else
return (Plugin_Stop);
}
/*
------------------------------------------------------------------------------------------
AntLion_DamageHook
------------------------------------------------------------------------------------------
*/
public Action:AntLion_DamageHook(monster, &attacker, &inflictor, &Float:damage, &damagetype)
{
if (BaseNPC_Hurt(monster, attacker, RoundToZero(damage), "npc/antlion/attack_double3.wav"))
SDKUnhook(monster, SDKHook_OnTakeDamage, AntLion_DamageHook);
return (Plugin_Handled);
} | 0 | 0.948882 | 1 | 0.948882 | game-dev | MEDIA | 0.983909 | game-dev | 0.932042 | 1 | 0.932042 |
TrashboxBobylev/Summoning-Pixel-Dungeon | 7,838 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/Goo.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2022 Evan Debenham
*
* Summoning Pixel Dungeon
* Copyright (C) 2019-2022 TrashboxBobylev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.actors.mobs;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Badges;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.LockedFloor;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Ooze;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.DriedRose;
import com.shatteredpixel.shatteredpixeldungeon.items.keys.SkeletonKey;
import com.shatteredpixel.shatteredpixeldungeon.items.quest.GooBlob;
import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.CharSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.GooSprite;
import com.shatteredpixel.shatteredpixeldungeon.ui.BossHealthBar;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.Camera;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.Bundle;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
public class Goo extends Mob {
{
HP = HT = 100;
EXP = 0;//see loot
defenseSkill = 8;
spriteClass = GooSprite.class;
properties.add(Property.BOSS);
properties.add(Property.DEMONIC);
properties.add(Property.ACIDIC);
if (Dungeon.mode == Dungeon.GameMode.DIFFICULT){
flying = true;
}
}
private int pumpedUp = 0;
@Override
public int damageRoll() {
int min = 1;
int max = (HP*2 <= HT) ? 12 : 8;
if (pumpedUp > 0) {
pumpedUp = 0;
Sample.INSTANCE.play( Assets.Sounds.BURNING );
return Random.NormalIntRange( min*3, max*3 );
} else {
return Random.NormalIntRange( min, max );
}
}
@Override
public int attackSkill( Char target ) {
int attack = 10;
if (HP*2 <= HT) attack = 15;
if (pumpedUp > 0) attack *= 2;
return attack;
}
@Override
public int defenseSkill(Char enemy) {
return (int)(super.defenseSkill(enemy) * ((HP*2 <= HT)? 1.5 : 1));
}
@Override
public int defenseValue() {
return 3;
}
@Override
public boolean act() {
if (Dungeon.level.water[pos] && HP < HT) {
sprite.emitter().burst( Speck.factory( Speck.HEALING ), 1 );
if (HP*2 == HT) {
BossHealthBar.bleed(false);
((GooSprite)sprite).spray(false);
}
HP++;
}
if (state != SLEEPING){
Dungeon.level.seal();
}
return super.act();
}
@Override
protected boolean canAttack( Char enemy ) {
if (pumpedUp > 0){
//we check both from and to in this case as projectile logic isn't always symmetrical.
//this helps trim out BS edge-cases
return Dungeon.level.distance(enemy.pos, pos) <= (Dungeon.mode == Dungeon.GameMode.DIFFICULT ? 3 : 2)
&& new Ballistica( pos, enemy.pos, Ballistica.PROJECTILE).collisionPos == enemy.pos
&& new Ballistica( enemy.pos, pos, Ballistica.PROJECTILE).collisionPos == pos;
} else {
return super.canAttack(enemy);
}
}
@Override
public int attackProc( Char enemy, int damage ) {
damage = super.attackProc( enemy, damage );
if (Random.Int( 3 ) == 0) {
Buff.affect( enemy, Ooze.class ).set( Ooze.DURATION );
enemy.sprite.burst( 0x000000, 5 );
}
if (pumpedUp > 0) {
Camera.main.shake( 3, 0.2f );
}
return damage;
}
@Override
public void updateSpriteState() {
super.updateSpriteState();
if (pumpedUp > 0){
((GooSprite)sprite).pumpUp( pumpedUp );
}
}
@Override
protected boolean doAttack( Char enemy ) {
if (pumpedUp == 1) {
((GooSprite)sprite).pumpUp( 2 );
pumpedUp++;
Sample.INSTANCE.play( Assets.Sounds.CHARGEUP );
spend( attackDelay() );
return true;
} else if (pumpedUp >= 2 || Random.Int( (HP*2 <= HT) ? 2 : 5 ) > 0) {
boolean visible = Dungeon.level.heroFOV[pos];
if (visible) {
if (pumpedUp >= 2) {
((GooSprite) sprite).pumpAttack();
} else {
sprite.attack(enemy.pos);
}
} else {
attack( enemy );
}
spend( attackDelay() );
return !visible;
} else {
pumpedUp++;
((GooSprite)sprite).pumpUp( 1 );
if (Dungeon.level.heroFOV[pos]) {
sprite.showStatus( CharSprite.NEGATIVE, Messages.get(this, "!!!") );
GLog.negative( Messages.get(this, "pumpup") );
Sample.INSTANCE.play( Assets.Sounds.CHARGEUP, 1f, 0.8f );
}
spend( attackDelay() );
return true;
}
}
@Override
public boolean attack( Char enemy ) {
boolean result = super.attack( enemy );
pumpedUp = 0;
return result;
}
@Override
protected boolean getCloser( int target ) {
pumpedUp = 0;
sprite.idle();
return super.getCloser( target );
}
@Override
public int damage(int dmg, Object src) {
if (!BossHealthBar.isAssigned()){
BossHealthBar.assignBoss( this );
}
boolean bleeding = (HP*2 <= HT);
int damage = super.damage(dmg, src);
if ((HP*2 <= HT) && !bleeding){
BossHealthBar.bleed(true);
sprite.showStatus(CharSprite.NEGATIVE, Messages.get(this, "enraged"));
((GooSprite)sprite).spray(true);
yell(Messages.get(this, "gluuurp"));
}
LockedFloor lock = Dungeon.hero.buff(LockedFloor.class);
if (lock != null) lock.addTime(dmg*2);
return damage;
}
@Override
public void die( Object cause ) {
super.die( cause );
Dungeon.level.unseal();
GameScene.bossSlain();
Dungeon.level.drop( new SkeletonKey( Dungeon.depth ), pos ).sprite.drop();
Dungeon.hero.earnExp( Dungeon.hero.maxExp(), getClass() );
//60% chance of 2 blobs, 30% chance of 3, 10% chance for 4. Average of 2.5
int blobs = Random.chances(new float[]{0, 0, 6, 3, 1});
for (int i = 0; i < blobs; i++){
int ofs;
do {
ofs = PathFinder.NEIGHBOURS8[Random.Int(8)];
} while (!Dungeon.level.passable[pos + ofs]);
Dungeon.level.drop( new GooBlob(), pos + ofs ).sprite.drop( pos );
}
Badges.validateBossSlain();
yell( Messages.get(this, "defeated") );
}
@Override
public void notice() {
super.notice();
if (!BossHealthBar.isAssigned()) {
BossHealthBar.assignBoss(this);
yell(Messages.get(this, "notice"));
for (Char ch : Actor.chars()){
if (ch instanceof DriedRose.GhostHero){
GLog.negative("\n");
((DriedRose.GhostHero) ch).sayBoss();
}
}
}
}
private final String PUMPEDUP = "pumpedup";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( PUMPEDUP , pumpedUp );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
pumpedUp = bundle.getInt( PUMPEDUP );
if (state != SLEEPING) BossHealthBar.assignBoss(this);
if ((HP*2 <= HT)) BossHealthBar.bleed(true);
}
}
| 0 | 0.966102 | 1 | 0.966102 | game-dev | MEDIA | 0.994802 | game-dev | 0.990934 | 1 | 0.990934 |
DanWBR/dwsim3 | 3,690 | RandomOps/Multi.cs | /// ------------------------------------------------------
/// RandomOps - (Pseudo) Random Number Generator For C#
/// Copyright (C) 2003-2010 Magnus Erik Hvass Pedersen.
/// Please see the file license.txt for license details.
/// RandomOps on the internet: http://www.Hvass-Labs.org/
/// ------------------------------------------------------
namespace RandomOps
{
/// <summary>
/// Abstract class for using multiple RNGs that can be switched
/// between. Example implementation is the Switcher-class which
/// does the RNG-switching randomly. Thread-safe if supplied RNGs
/// are thread-safe, and if SelectRand() is made thread-safe.
/// </summary>
/// <remarks>
/// If you are using RNGs that have custom methods for generating
/// random numbers then you need to extend this class in a fashion
/// similar to that of the Uniform()-method.
/// </remarks>
public abstract partial class Multi : Random
{
#region Constructor.
/// <summary>
/// Constructs the RNG-object from different RNG's.
/// </summary>
/// <param name="rands">The RNGs that will be switched between.</param>
public Multi(Random[] rands)
: base()
{
Rands = rands;
}
#endregion
#region Override these methods.
/// <summary>
/// Select the RNG to use.
/// </summary>
/// <returns>Index into the Rands-array.</returns>
protected abstract int SelectRand();
#endregion
#region Internal variables.
/// <summary>
/// The array of RNGs to switch between.
/// </summary>
protected Random[] Rands
{
get;
private set;
}
/// <summary>
/// The currently selected RNG.
/// </summary>
Random Rand;
#endregion
#region RNG Implementation.
/// <summary>
/// Switch the RNG currently being used. This is to be
/// called before every RNG-method call.
/// </summary>
void Switch()
{
int selected = SelectRand();
Rand = Rands[selected];
}
#endregion
#region Base-class overrides.
/// <summary>
/// Name of the RNG.
/// </summary>
public override string Name
{
get
{
string s = "Multi(";
foreach (Random rand in Rands)
{
s += rand.Name + ", ";
}
s += ")";
return s;
}
}
/// <summary>
/// Draw a uniform random number in the exclusive range (0,1)
/// </summary>
public sealed override double Uniform()
{
Switch();
return Rand.Uniform();
}
/// <summary>
/// Draw a random boolean with equal probability of drawing true or false.
/// </summary>
public sealed override bool Bool()
{
Switch();
return Rand.Bool();
}
/// <summary>
/// Draw a random and uniform byte.
/// </summary>
public sealed override byte Byte()
{
Switch();
return Rand.Byte();
}
/// <summary>
/// Draw an array of random and uniform bytes.
/// </summary>
/// <param name="length">The array length requested.</param>
public sealed override byte[] Bytes(int length)
{
Switch();
return Rand.Bytes(length);
}
#endregion
}
}
| 0 | 0.91628 | 1 | 0.91628 | game-dev | MEDIA | 0.191844 | game-dev | 0.891816 | 1 | 0.891816 |
PetteriM1/NukkitPetteriM1Edition | 4,288 | src/main/java/cn/nukkit/entity/item/EntityPotion.java | package cn.nukkit.entity.item;
import cn.nukkit.Player;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.data.IntEntityData;
import cn.nukkit.entity.projectile.EntityProjectile;
import cn.nukkit.event.potion.PotionCollideEvent;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.particle.Particle;
import cn.nukkit.level.particle.SpellParticle;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.network.protocol.LevelSoundEventPacket;
import cn.nukkit.potion.Effect;
import cn.nukkit.potion.Potion;
/**
* @author xtypr
*/
public class EntityPotion extends EntityProjectile {
public static final int NETWORK_ID = 86;
public int potionId;
public EntityPotion(FullChunk chunk, CompoundTag nbt) {
this(chunk, nbt, null);
}
public EntityPotion(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) {
super(chunk, nbt, shootingEntity);
}
@Override
protected void initEntity() {
super.initEntity();
potionId = this.namedTag.getShort("PotionId");
this.dataProperties.putShort(DATA_POTION_AUX_VALUE, this.potionId);
Effect effect = Potion.getEffect(potionId, true);
if (effect != null) {
int count = 0;
int[] c = effect.getColor();
count += effect.getAmplifier() + 1;
int r = ((c[0] * (effect.getAmplifier() + 1)) / count) & 0xff;
int g = ((c[1] * (effect.getAmplifier() + 1)) / count) & 0xff;
int b = ((c[2] * (effect.getAmplifier() + 1)) / count) & 0xff;
this.setDataProperty(new IntEntityData(Entity.DATA_POTION_COLOR, (r << 16) + (g << 8) + b));
}
}
@Override
public int getNetworkId() {
return NETWORK_ID;
}
@Override
public float getWidth() {
return 0.25f;
}
@Override
public float getLength() {
return 0.25f;
}
@Override
public float getHeight() {
return 0.25f;
}
@Override
protected float getGravity() {
return 0.05f;
}
@Override
protected float getDrag() {
return 0.01f;
}
protected void splash(Entity collidedWith) {
Potion potion = Potion.getPotion(this.potionId);
PotionCollideEvent event = new PotionCollideEvent(potion, this);
this.server.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
this.close();
potion = event.getPotion();
if (potion == null) {
return;
}
potion.setSplash(true);
Particle particle;
int r;
int g;
int b;
Effect effect = Potion.getEffect(potion.getId(), true);
if (effect == null) {
r = 40;
g = 40;
b = 255;
} else {
int[] colors = effect.getColor();
r = colors[0];
g = colors[1];
b = colors[2];
}
particle = new SpellParticle(this, r, g, b);
this.getLevel().addParticle(particle);
this.getLevel().addLevelSoundEvent(this, LevelSoundEventPacket.SOUND_GLASS);
Entity[] entities = this.getLevel().getNearbyEntities(this.getBoundingBox().grow(4.125, 2.125, 4.125), this);
for (Entity anEntity : entities) {
if (anEntity == null || anEntity.closed || !anEntity.isAlive() || anEntity instanceof Player && ((Player) anEntity).isSpectator()) {
continue;
}
double distance = anEntity.distanceSquared(this);
if (distance < 16) {
double d = anEntity.equals(collidedWith) ? 1 : 1 - Math.sqrt(distance) / 4;
potion.applyPotion(anEntity, d);
}
}
}
@Override
public void onCollideWithEntity(Entity entity) {
this.splash(entity);
this.close();
}
@Override
public boolean onUpdate(int currentTick) {
boolean update = super.onUpdate(currentTick);
if (this.closed) {
return false;
}
if (this.isCollided) {
this.splash(null);
}
if (this.age > 1200 || this.isCollided) {
this.close();
return false;
}
return update;
}
}
| 0 | 0.842194 | 1 | 0.842194 | game-dev | MEDIA | 0.991264 | game-dev | 0.97319 | 1 | 0.97319 |
LangYa466/MCPLite-all-source | 2,813 | src/main/java/net/minecraft/command/server/CommandBanPlayer.java | /*
* Decompiled with CFR 0.151.
*/
package net.minecraft.command.server;
import com.mojang.authlib.GameProfile;
import java.util.Date;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.UserListBansEntry;
import net.minecraft.util.BlockPos;
public class CommandBanPlayer
extends CommandBase {
@Override
public String getCommandName() {
return "ban";
}
@Override
public int getRequiredPermissionLevel() {
return 3;
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "commands.ban.usage";
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender sender) {
return MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().isLanServer() && super.canCommandSenderUseCommand(sender);
}
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length >= 1 && args[0].length() > 0) {
MinecraftServer minecraftserver = MinecraftServer.getServer();
GameProfile gameprofile = minecraftserver.getPlayerProfileCache().getGameProfileForUsername(args[0]);
if (gameprofile == null) {
throw new CommandException("commands.ban.failed", args[0]);
}
String s = null;
if (args.length >= 2) {
s = CommandBanPlayer.getChatComponentFromNthArg(sender, args, 1).getUnformattedText();
}
UserListBansEntry userlistbansentry = new UserListBansEntry(gameprofile, (Date)null, sender.getName(), (Date)null, s);
minecraftserver.getConfigurationManager().getBannedPlayers().addEntry(userlistbansentry);
EntityPlayerMP entityplayermp = minecraftserver.getConfigurationManager().getPlayerByUsername(args[0]);
if (entityplayermp != null) {
entityplayermp.playerNetServerHandler.kickPlayerFromServer("You are banned from this server.");
}
} else {
throw new WrongUsageException("commands.ban.usage", new Object[0]);
}
CommandBanPlayer.notifyOperators(sender, (ICommand)this, "commands.ban.success", args[0]);
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) {
return args.length >= 1 ? CommandBanPlayer.getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()) : null;
}
}
| 0 | 0.797359 | 1 | 0.797359 | game-dev | MEDIA | 0.93616 | game-dev | 0.862756 | 1 | 0.862756 |
fulpstation/fulpstation | 7,420 | code/game/objects/effects/step_triggers.dm | /* Simple object type, calls a proc when "stepped" on by something */
/obj/effect/step_trigger
var/affect_ghosts = 0
var/stopper = 1 // stops throwers
var/mobs_only = FALSE
invisibility = INVISIBILITY_ABSTRACT // nope cant see this shit
anchored = TRUE
/obj/effect/step_trigger/Initialize(mapload)
. = ..()
var/static/list/loc_connections = list(
COMSIG_ATOM_ENTERED = PROC_REF(on_entered),
)
AddElement(/datum/element/connect_loc, loc_connections)
/obj/effect/step_trigger/proc/Trigger(atom/movable/A)
return 0
/obj/effect/step_trigger/proc/on_entered(datum/source, atom/movable/entering)
SIGNAL_HANDLER
if(!entering || entering == src || entering.invisibility >= INVISIBILITY_ABSTRACT || istype(entering, /atom/movable/mirage_holder)) //dont teleport ourselves, abstract objects, and mirage holders due to init shenanigans
return
if(isobserver(entering) && !affect_ghosts)
return
if(!ismob(entering) && mobs_only)
return
INVOKE_ASYNC(src, PROC_REF(Trigger), entering)
/obj/effect/step_trigger/singularity_act()
return
/obj/effect/step_trigger/singularity_pull(atom/singularity, current_size)
return
/* Sends a message to mob when triggered*/
/obj/effect/step_trigger/message
var/message //the message to give to the mob
var/once = 1
mobs_only = TRUE
/obj/effect/step_trigger/message/Trigger(mob/M)
if(M.client)
to_chat(M, span_info("[message]"))
if(once)
qdel(src)
/* Tosses things in a certain direction */
/obj/effect/step_trigger/thrower
var/direction = SOUTH // the direction of throw
var/tiles = 3 // if 0: forever until atom hits a stopper
var/immobilize = 1 // if nonzero: prevents mobs from moving while they're being flung
var/speed = 1 // delay of movement
var/facedir = 0 // if 1: atom faces the direction of movement
var/nostop = 0 // if 1: will only be stopped by teleporters
///List of moving atoms mapped to their inital direction
var/list/affecting = list()
/obj/effect/step_trigger/thrower/Trigger(atom/A)
if(!A || !ismovable(A))
return
var/atom/movable/AM = A
for(var/obj/effect/step_trigger/thrower/T in orange(2, src))
if(AM in T.affecting)
return
if(immobilize)
ADD_TRAIT(AM, TRAIT_IMMOBILIZED, REF(src))
affecting[AM] = AM.dir
var/datum/move_loop/loop = GLOB.move_manager.move(AM, direction, speed, tiles ? tiles * speed : INFINITY)
RegisterSignal(loop, COMSIG_MOVELOOP_PREPROCESS_CHECK, PROC_REF(pre_move))
RegisterSignal(loop, COMSIG_MOVELOOP_POSTPROCESS, PROC_REF(post_move))
RegisterSignal(loop, COMSIG_QDELETING, PROC_REF(set_to_normal))
/obj/effect/step_trigger/thrower/proc/pre_move(datum/move_loop/source)
SIGNAL_HANDLER
var/atom/movable/being_moved = source.moving
affecting[being_moved] = being_moved.dir
/obj/effect/step_trigger/thrower/proc/post_move(datum/move_loop/source)
SIGNAL_HANDLER
var/atom/movable/being_moved = source.moving
if(!facedir)
being_moved.setDir(affecting[being_moved])
if(being_moved.z != z)
qdel(source)
return
if(!nostop)
for(var/obj/effect/step_trigger/T in get_turf(being_moved))
if(T.stopper && T != src)
qdel(source)
return
else
for(var/obj/effect/step_trigger/teleporter/T in get_turf(being_moved))
if(T.stopper)
qdel(source)
return
/obj/effect/step_trigger/thrower/proc/set_to_normal(datum/move_loop/source)
SIGNAL_HANDLER
var/atom/movable/being_moved = source.moving
affecting -= being_moved
REMOVE_TRAIT(being_moved, TRAIT_IMMOBILIZED, REF(src))
/* Stops things thrown by a thrower, doesn't do anything */
/obj/effect/step_trigger/stopper
/* Instant teleporter */
/obj/effect/step_trigger/teleporter
var/teleport_x = 0 // teleportation coordinates (if one is null, then no teleport!)
var/teleport_y = 0
var/teleport_z = 0
/obj/effect/step_trigger/teleporter/Trigger(atom/movable/A)
if(teleport_x && teleport_y && teleport_z)
var/turf/T = locate(teleport_x, teleport_y, teleport_z)
A.forceMove(T)
/* Random teleporter, teleports atoms to locations ranging from teleport_x - teleport_x_offset, etc */
/obj/effect/step_trigger/teleporter/random
var/teleport_x_offset = 0
var/teleport_y_offset = 0
var/teleport_z_offset = 0
/obj/effect/step_trigger/teleporter/random/Trigger(atom/movable/A)
if(teleport_x && teleport_y && teleport_z)
if(teleport_x_offset && teleport_y_offset && teleport_z_offset)
var/turf/T = locate(rand(teleport_x, teleport_x_offset), rand(teleport_y, teleport_y_offset), rand(teleport_z, teleport_z_offset))
if (T)
A.forceMove(T)
/* Teleports atoms directly to an offset, no randomness, looping hallways! */
/obj/effect/step_trigger/teleporter/offset
var/teleport_x_offset = 0
var/teleport_y_offset = 0
/obj/effect/step_trigger/teleporter/offset/on_entered(datum/source, atom/movable/entered, atom/old_loc)
if(!old_loc?.Adjacent(loc)) // prevents looping, if we were teleported into this then the old loc is usually not adjacent
return
return ..()
/obj/effect/step_trigger/teleporter/offset/Trigger(atom/movable/poor_soul)
var/turf/destination = locate(x + teleport_x_offset, y + teleport_y_offset, z)
if(!destination)
return
poor_soul.forceMove(destination)
var/mob/living/living_soul = poor_soul
if(istype(living_soul) && living_soul.client)
living_soul.client.move_delay = 0
/* Fancy teleporter, creates sparks and smokes when used */
/obj/effect/step_trigger/teleport_fancy
var/locationx
var/locationy
var/uses = 1 //0 for infinite uses
var/entersparks = 0
var/exitsparks = 0
var/entersmoke = 0
var/exitsmoke = 0
/obj/effect/step_trigger/teleport_fancy/Trigger(mob/M)
var/dest = locate(locationx, locationy, z)
M.Move(dest)
if(entersparks)
var/datum/effect_system/spark_spread/s = new
s.set_up(4, 1, src)
s.start()
if(exitsparks)
var/datum/effect_system/spark_spread/s = new
s.set_up(4, 1, dest)
s.start()
if(entersmoke)
var/datum/effect_system/fluid_spread/smoke/s = new
s.set_up(4, holder = src, location = src)
s.start()
if(exitsmoke)
var/datum/effect_system/fluid_spread/smoke/s = new
s.set_up(4, holder = src, location = dest)
s.start()
uses--
if(uses == 0)
qdel(src)
/* Simple sound player, Mapper friendly! */
/obj/effect/step_trigger/sound_effect
var/sound //eg. path to the sound, inside '' eg: 'growl.ogg'
var/volume = 100
var/freq_vary = 1 //Should the frequency of the sound vary?
var/extra_range = 0 // eg World.view = 7, extra_range = 1, 7+1 = 8, 8 turfs radius
var/happens_once = FALSE
var/triggerer_only = 0 //Whether the triggerer is the only person who hears this
/obj/effect/step_trigger/sound_effect/Trigger(atom/movable/A)
var/turf/T = get_turf(A)
if(!T)
return
if(triggerer_only && ismob(A))
var/mob/B = A
B.playsound_local(T, sound, volume, freq_vary)
else
playsound(T, sound, volume, freq_vary, extra_range)
if(happens_once)
qdel(src)
/obj/effect/step_trigger/sound_effect/lavaland_cult_altar
happens_once = TRUE
name = "a grave mistake";
sound = 'sound/effects/hallucinations/i_see_you1.ogg'
triggerer_only = 1
/// Forces a given outfit onto any carbon which crosses it, for event maps
/obj/effect/step_trigger/outfitter
mobs_only = TRUE
///outfit to equip
var/datum/outfit/outfit_to_equip
var/happens_once = FALSE
/obj/effect/step_trigger/outfitter/Trigger(atom/movable/A)
if(!ishuman(A))
return
var/mob/living/carbon/human/fellow = A
fellow.delete_equipment()
fellow.equipOutfit(outfit_to_equip,FALSE)
if(happens_once)
qdel(src)
| 0 | 0.978707 | 1 | 0.978707 | game-dev | MEDIA | 0.983903 | game-dev | 0.995304 | 1 | 0.995304 |
metroidret/mzm | 7,136 | src/cutscenes/samus_in_blue_ship.c | #include "cutscenes/samus_in_blue_ship.h"
#include "cutscenes/cutscene_utils.h"
#include "dma.h"
#include "data/shortcut_pointers.h"
#include "data/cutscenes/samus_in_blue_ship_data.h"
#include "constants/audio.h"
#include "constants/cutscene.h"
#include "structs/cutscene.h"
#include "structs/display.h"
static void SamusInBlueShipShakeScreen(struct CutsceneGraphicsData* pGraphics);
static void SamusInBlueShipUpdateControlPanel(struct CutsceneOamData* pOam);
static void SamusInBlueShipProcessOAM(void);
/**
* @brief 67d8c | f8 | Handles the sip powering up part (entire cutscene)
*
* @return u8 FALSE
*/
static u8 SamusInBlueShipPoweringUp(void)
{
switch (CUTSCENE_DATA.timeInfo.subStage)
{
case 0:
if (CutsceneTransferAndUpdateFade())
{
CUTSCENE_DATA.timeInfo.timer = 0;
CUTSCENE_DATA.timeInfo.subStage++;
}
break;
case 1:
if (CUTSCENE_DATA.timeInfo.timer > CONVERT_SECONDS(.5f))
{
CUTSCENE_DATA.oam[0].actions = 1;
CUTSCENE_DATA.timeInfo.timer = 0;
CUTSCENE_DATA.timeInfo.subStage++;
}
break;
case 2:
if (CUTSCENE_DATA.oam[0].actions == 4)
{
CUTSCENE_DATA.timeInfo.timer = 0;
CUTSCENE_DATA.timeInfo.subStage++;
}
break;
case 3:
if (CUTSCENE_DATA.timeInfo.timer > CONVERT_SECONDS(.5f))
{
SoundPlay(SOUND_BLUE_SHIP_POWERING_UP);
CUTSCENE_DATA.graphicsData[0].active = TRUE;
CUTSCENE_DATA.graphicsData[0].timer = 0;
CUTSCENE_DATA.timeInfo.timer = 0;
CUTSCENE_DATA.timeInfo.subStage++;
}
break;
case 4:
if (CUTSCENE_DATA.timeInfo.timer > CONVERT_SECONDS(1.5f))
{
CUTSCENE_DATA.timeInfo.timer = 0;
CUTSCENE_DATA.timeInfo.subStage++;
}
break;
case 5:
CutsceneFadeScreenToBlack();
CUTSCENE_DATA.timeInfo.stage++;
MACRO_CUTSCENE_NEXT_STAGE();
break;
}
SamusInBlueShipShakeScreen(&CUTSCENE_DATA.graphicsData[0]);
SamusInBlueShipUpdateControlPanel(&CUTSCENE_DATA.oam[0]);
#if DEBUG
CutsceneCheckSkipStage(1);
#endif // DEBUG
return FALSE;
}
/**
* @brief 67e84 | 4c | Handles the screen shake movement
*
* @param pGraphics Cutscene graphics data pointer
*/
static void SamusInBlueShipShakeScreen(struct CutsceneGraphicsData* pGraphics)
{
if (!pGraphics->active)
return;
APPLY_DELTA_TIME_INC(pGraphics->timer);
if (MOD_AND(pGraphics->timer, 2))
return;
if (MOD_BLOCK_AND(pGraphics->timer, 2))
*CutsceneGetBgHorizontalPointer(sSamusInBlueShipPageData[0].bg) += PIXEL_SIZE;
else
*CutsceneGetBgHorizontalPointer(sSamusInBlueShipPageData[0].bg) -= PIXEL_SIZE;
}
static u8 sSamusInBlueShipPanelTransparency[4] = {
16, 15, 14, 15
};
/**
* @brief 67ed0 | c0 | Updates the control panel object
*
* @param pOam Cutscene OAM data pointer
*/
static void SamusInBlueShipUpdateControlPanel(struct CutsceneOamData* pOam)
{
switch (pOam->actions)
{
case 0:
break;
case 1:
UpdateCutsceneOamDataID(pOam, 2);
SoundPlay(SOUND_BLUE_SHIP_TURNING_ON);
gWrittenToBldalpha_L = BLDALPHA_MAX_VALUE;
gWrittenToBldalpha_H = 0;
pOam->actions++;
break;
case 2:
if (pOam->ended)
{
pOam->timer = 0;
pOam->actions++;
}
break;
case 3:
pOam->unk_1A = 0;
pOam->unk_1E = 2;
pOam->timer = 0;
pOam->actions++;
break;
case 4:
if (pOam->unk_1A == 0)
{
pOam->unk_1A = pOam->unk_1E;
APPLY_DELTA_TIME_INC(pOam->timer);
if (pOam->timer >= ARRAY_SIZE(sSamusInBlueShipPanelTransparency))
pOam->timer = 0;
gWrittenToBldalpha_L = sSamusInBlueShipPanelTransparency[pOam->timer];
gWrittenToBldalpha_H = BLDALPHA_MAX_VALUE - gWrittenToBldalpha_L;
}
else
pOam->unk_1A--;
break;
}
}
/**
* @brief 67f90 | 12c | Initializes the samus in blue ship cutscene
*
* @return u8 FALSE
*/
static u8 SamusInBlueShipInit(void)
{
CutsceneFadeScreenToBlack();
DmaTransfer(3, sSamusInBlueShipPal, PALRAM_OBJ, sizeof(sSamusInBlueShipPal), 16);
DmaTransfer(3, sSamusInBlueShipPal, PALRAM_BASE, sizeof(sSamusInBlueShipPal), 16);
SET_BACKDROP_COLOR(COLOR_BLACK);
CallLZ77UncompVram(sSamusInBlueShipSamusGfx, BGCNT_TO_VRAM_CHAR_BASE(sSamusInBlueShipPageData[0].graphicsPage));
CallLZ77UncompVram(sSamusInBlueShipSamusTileTable, BGCNT_TO_VRAM_TILE_BASE(sSamusInBlueShipPageData[0].tiletablePage));
CallLZ77UncompVram(sSamusInBlueShipControlsGfx, BGCNT_TO_VRAM_CHAR_BASE(4));
CutsceneSetBgcntPageData(sSamusInBlueShipPageData[0]);
CutsceneReset();
CUTSCENE_DATA.bldcnt = BLDCNT_OBJ_FIRST_TARGET_PIXEL | BLDCNT_ALPHA_BLENDING_EFFECT | BLDCNT_SCREEN_SECOND_TARGET;
gWrittenToBldalpha_L = BLDALPHA_MAX_VALUE;
gWrittenToBldalpha_H = 0;
CutsceneSetBackgroundPosition(CUTSCENE_BG_EDIT_HOFS | CUTSCENE_BG_EDIT_VOFS, sSamusInBlueShipPageData[0].bg, NON_GAMEPLAY_START_BG_POS);
UpdateCutsceneOamDataID(&CUTSCENE_DATA.oam[0], 1);
CUTSCENE_DATA.oam[0].xPosition = NON_GAMEPLAY_START_BG_POS + BLOCK_SIZE * 7 + HALF_BLOCK_SIZE;
CUTSCENE_DATA.oam[0].yPosition = NON_GAMEPLAY_START_BG_POS + BLOCK_SIZE * 5 - PIXEL_SIZE;
CUTSCENE_DATA.oam[0].priority = 0;
CUTSCENE_DATA.oam[0].boundBackground = 3;
CutsceneStartBackgroundFading(2);
CUTSCENE_DATA.dispcnt = DCNT_OBJ | sSamusInBlueShipPageData[0].bg;
CUTSCENE_DATA.timeInfo.stage++;
CUTSCENE_DATA.timeInfo.timer = 0;
CUTSCENE_DATA.timeInfo.subStage = 0;
return FALSE;
}
static struct CutsceneSubroutineData sSamusInBlueShipSubroutineData[3] = {
[0] = {
.pFunction = SamusInBlueShipInit,
.oamLength = 1
},
[1] = {
.pFunction = SamusInBlueShipPoweringUp,
.oamLength = 1
},
[2] = {
.pFunction = CutsceneEndFunction,
.oamLength = 1
}
};
/**
* @brief 680bc | 34 | Subroutine for the samus in blue ship cutscene
*
* @return u8 bool, ended
*/
u8 SamusInBlueShipSubroutine(void)
{
u8 ended;
ended = sSamusInBlueShipSubroutineData[CUTSCENE_DATA.timeInfo.stage].pFunction();
CutsceneUpdateBackgroundsPosition(TRUE);
SamusInBlueShipProcessOAM();
return ended;
}
/**
* @brief 680f0 | 38 | Processes the OAM
*
*/
static void SamusInBlueShipProcessOAM(void)
{
gNextOamSlot = 0;
ProcessCutsceneOam(sSamusInBlueShipSubroutineData[CUTSCENE_DATA.timeInfo.stage].oamLength, CUTSCENE_DATA.oam, sSamusInBlueShipOam);
ResetFreeOam();
}
| 0 | 0.963499 | 1 | 0.963499 | game-dev | MEDIA | 0.896182 | game-dev | 0.981143 | 1 | 0.981143 |
quicklyslow/cocos2d-bgfx | 46,265 | cocos/scripting/js-bindings/manual/jsb_node.cpp | //
// jsb_node.cpp
// cocos2d_js_bindings
//
// Created by James Chen on 4/26/17.
//
//
#include "jsb_node.hpp"
#include "jsb_global.h"
#include "jsb_conversions.hpp"
#include "ScriptingCore.h"
#include "cocos2d.h"
using namespace cocos2d;
#define STANDALONE_TEST 0
extern se::Object* __jsb_cocos2d_Node_proto;
extern se::Class* __jsb_cocos2d__Node_class;
extern se::Object* __jsb_cocos2d_Scheduler_proto;
se::Object* __jsb_Node_proto = nullptr;
se::Class* __jsb_Node_class = nullptr;
static bool Node_finalized(se::State& s)
{
if (s.nativeThisObject())
{
Node* thiz = (Node*) s.nativeThisObject();
SE_LOGD("Node_finalized %p ...\n", thiz->getUserData());
CC_SAFE_RELEASE(thiz);
}
return true;
}
SE_BIND_FINALIZE_FUNC(Node_finalized)
static bool Node_constructor(se::State& s)
{
SE_LOGD("Node_constructor ...\n");
Node* obj = new Node();
s.thisObject()->setPrivateData(obj);
return true;
}
SE_BIND_CTOR(Node_constructor, __jsb_Node_class, Node_finalized)
static bool Node_ctor(se::State& s)
{
SE_LOGD("Node_ctor ...\n");
Node* obj = new Node();
s.thisObject()->setPrivateData(obj);
return true;
}
SE_BIND_SUB_CLS_CTOR(Node_ctor, __jsb_Node_class, Node_finalized)
static bool Node_create(se::State& s)
{
Node* node = Node::create();
node->retain();
auto obj = se::Object::createObjectWithClass(__jsb_Node_class);
obj->setPrivateData(node);
s.rval().setObject(obj);
return true;
}
SE_BIND_FUNC(Node_create)
static bool Node_onEnter(se::State& s)
{
ScriptingCore::getInstance()->setCalledFromScript(true);
Node* thiz = (Node*)s.nativeThisObject();
thiz->onEnter();
return true;
}
SE_BIND_FUNC(Node_onEnter)
static bool Node_onExit(se::State& s)
{
ScriptingCore::getInstance()->setCalledFromScript(true);
Node* thiz = (Node*)s.nativeThisObject();
thiz->onExit();
return true;
}
SE_BIND_FUNC(Node_onExit)
static bool Node_onEnterTransitionDidFinish(se::State& s)
{
ScriptingCore::getInstance()->setCalledFromScript(true);
Node* thiz = (Node*)s.nativeThisObject();
thiz->onEnterTransitionDidFinish();
return true;
}
SE_BIND_FUNC(Node_onEnterTransitionDidFinish)
static bool Node_onExitTransitionDidStart(se::State& s)
{
ScriptingCore::getInstance()->setCalledFromScript(true);
Node* thiz = (Node*)s.nativeThisObject();
thiz->onExitTransitionDidStart();
return true;
}
SE_BIND_FUNC(Node_onExitTransitionDidStart)
static bool Node_cleanup(se::State& s)
{
ScriptingCore::getInstance()->setCalledFromScript(true);
Node* thiz = (Node*)s.nativeThisObject();
thiz->cleanup();
return true;
}
SE_BIND_FUNC(Node_cleanup)
static bool Node_addChild(se::State& s)
{
const auto& args = s.args();
Node* thiz = (Node*)s.nativeThisObject();
Node* child = (Node*)args[0].toObject()->getPrivateData();
thiz->addChild(child);
return true;
}
SE_BIND_FUNC(Node_addChild)
class ScheduleElement
{
public:
ScheduleElement(se::Object* target, se::Object* func, const std::string& key, uint32_t targetId, uint32_t funcId)
: _target(target)
, _func(func)
, _key(key)
, _targetId(targetId)
, _funcId(funcId)
{}
ScheduleElement(ScheduleElement&& o)
{
*this = std::move(o);
}
ScheduleElement* operator=(ScheduleElement&& o)
{
if (this != &o)
{
_target = o._target;
_func = o._func;
_key = std::move(o._key);
_targetId = o._targetId;
_funcId = o._funcId;
}
return this;
}
inline se::Object* getTarget() const { return _target; }
inline se::Object* getFunc() const { return _func; }
inline const std::string& getKey() const { return _key; }
inline uint32_t getTargetId() const { return _targetId; }
inline uint32_t getFuncId() const { return _funcId; }
private:
ScheduleElement(const ScheduleElement& o) { assert(false); }
ScheduleElement* operator=(const ScheduleElement& o) { assert(false); return this; }
se::Object* _target;
se::Object* _func;
std::string _key;
uint32_t _targetId;
uint32_t _funcId;
};
static uint32_t __scheduleTargetIdCounter = 0;
static uint32_t __scheduleFuncIdCounter = 0;
static const char* SCHEDULE_TARGET_ID_KEY = "__seScheTargetId";
static const char* SCHEDULE_FUNC_ID_KEY = "__seScheFuncId";
static std::unordered_map<uint32_t/*targetId*/, std::unordered_map<uint32_t/*funcId*/, ScheduleElement>> __js_target_schedulekey_map;
static std::unordered_map<uint32_t/*targetId*/, std::pair<int/*priority*/, se::Object*>> __js_target_schedule_update_map;
static bool isScheduleExist(uint32_t jsFuncId, uint32_t jsTargetId, const ScheduleElement** outElement)
{
bool found = false;
for (const auto& e : __js_target_schedulekey_map)
{
if (e.first == jsTargetId)
{
for (const auto& e2 : e.second)
{
if (e2.first == jsFuncId)
{
*outElement = &e2.second;
found = true;
break;
}
}
}
if (found)
{
break;
}
}
if (!found)
{
*outElement = nullptr;
}
return found;
}
static bool isScheduleExist(const std::string& key, uint32_t jsTargetId, const ScheduleElement** outElement)
{
bool found = false;
for (const auto& e : __js_target_schedulekey_map)
{
if (e.first == jsTargetId)
{
for (const auto& e2 : e.second)
{
if (e2.second.getKey() == key)
{
*outElement = &e2.second;
found = true;
break;
}
}
}
if (found)
break;
}
if (!found)
{
*outElement = nullptr;
}
return found;
}
static void removeSchedule(uint32_t jsFuncId, uint32_t jsTargetId, bool needDetachChild)
{
auto funcObjKeyMapIter = __js_target_schedulekey_map.find(jsTargetId);
if (funcObjKeyMapIter != __js_target_schedulekey_map.end())
{
auto& funcMap = funcObjKeyMapIter->second;
auto iter = funcMap.find(jsFuncId);
if (iter != funcMap.end())
{
se::Object* target = iter->second.getTarget();
se::Object* func = iter->second.getFunc();
if (needDetachChild)
{
target->detachObject(func);
}
func->decRef();
target->decRef();
funcMap.erase(iter);
}
if (funcMap.empty())
{
__js_target_schedulekey_map.erase(funcObjKeyMapIter);
}
}
}
static void removeScheduleForThis(uint32_t jsTargetId, bool needDetachChild)
{
auto funcObjKeyMapIter = __js_target_schedulekey_map.find(jsTargetId);
if (funcObjKeyMapIter != __js_target_schedulekey_map.end())
{
auto& funcMap = funcObjKeyMapIter->second;
se::Object* target = nullptr;
se::Object* func = nullptr;
for (auto& e : funcMap)
{
target = e.second.getTarget();
func = e.second.getFunc();
if (needDetachChild)
{
target->detachObject(func);
}
func->decRef(); // Release jsFunc
target->decRef(); // Release jsThis
}
funcMap.clear();
__js_target_schedulekey_map.erase(funcObjKeyMapIter);
}
}
static void removeAllSchedules(bool needDetachChild)
{
CCLOG("Begin unschedule all callbacks");
for (auto& e1 :__js_target_schedulekey_map)
{
auto& funcMap = e1.second;
CCLOG(">> Found funcMap: %d", (int)funcMap.size());
se::Object* target = nullptr;
se::Object* func = nullptr;
for (auto& e : funcMap)
{
target = e.second.getTarget();
func = e.second.getFunc();
if (needDetachChild)
{
CCLOG("detachObject: owner: %p, target: %p", target, func);
target->detachObject(func);
}
target->decRef(); // Release jsThis
func->decRef(); // Release jsFunc
}
funcMap.clear();
}
__js_target_schedulekey_map.clear();
}
static void removeAllScheduleUpdates()
{
for (auto& e2 : __js_target_schedule_update_map)
{
e2.second.second->decRef();
}
__js_target_schedule_update_map.clear();
}
static void removeAllScheduleAndUpdate(bool needDetachChild)
{
removeAllSchedules(needDetachChild);
removeAllScheduleUpdates();
}
static bool isScheduleUpdateExist(uint32_t targetId)
{
for (const auto& e : __js_target_schedule_update_map)
{
if (e.first == targetId)
{
return true;
}
}
return false;
}
static void removeScheduleUpdate(uint32_t targetId)
{
auto iter = __js_target_schedule_update_map.find(targetId);
if (iter != __js_target_schedule_update_map.end())
{
iter->second.second->decRef();
__js_target_schedule_update_map.erase(iter);
}
}
static void removeScheduleUpdatesForMinPriority(int minPriority)
{
int foundPriority = 0;
auto iter = __js_target_schedule_update_map.begin();
while (iter != __js_target_schedule_update_map.end())
{
foundPriority = iter->second.first;
if (foundPriority >= minPriority)
{
iter->second.second->decRef();
iter = __js_target_schedule_update_map.erase(iter);
}
else
{
++iter;
}
}
}
static void insertScheduleUpdate(uint32_t targetId, int priority, se::Object* targetObj)
{
assert(__js_target_schedule_update_map.find(targetId) == __js_target_schedule_update_map.end());
__js_target_schedule_update_map[targetId] = std::make_pair(priority, targetObj);
targetObj->incRef();
}
static void insertSchedule(uint32_t funcId, uint32_t targetId, ScheduleElement&& element)
{
auto& funcKeyMap = __js_target_schedulekey_map[targetId];
assert(funcKeyMap.find(funcId) == funcKeyMap.end());
element.getTarget()->incRef();
element.getFunc()->incRef();
funcKeyMap.emplace(funcId, std::move(element));
}
static bool isTargetExistInScheduler(uint32_t targetId)
{
assert(targetId != 0);
// Iterating the schedule func map
for (const auto& e : __js_target_schedulekey_map)
{
if (e.first == targetId)
{
return true;
}
}
// Iterating the schedule update map
for (const auto& e : __js_target_schedule_update_map)
{
if (e.first == targetId)
{
return true;
}
}
return false;
}
class UnscheduleNotifier
{
public:
UnscheduleNotifier(uint32_t funcId, uint32_t targetId)
: _funcId(funcId)
, _targetId(targetId)
{
}
~UnscheduleNotifier()
{
// SE_LOGD("~UnscheduleNotifier, targetId: %u, funcId: %u\n", _targetId, _funcId);
se::ScriptEngine::getInstance()->clearException();
se::AutoHandleScope hs;
//removeSchedule(_funcId, _targetId, false);
}
private:
uint32_t _funcId;
uint32_t _targetId;
};
static uint32_t __idx = 0;
static bool Scheduler_scheduleCommon(Scheduler* scheduler, const se::Value& jsThis, const se::Value& jsFunc, float interval, unsigned int repeat, float delay, bool isPaused, bool toRootTarget, const std::string& callFromDebug)
{
assert(jsThis.isObject());
assert(jsFunc.isObject());
assert(jsFunc.toObject()->isFunction());
jsThis.toObject()->attachObject(jsFunc.toObject());
std::string key;
se::Value targetIdVal;
se::Value funcIdVal;
uint32_t targetId = 0;
uint32_t funcId = 0;
if (jsThis.toObject()->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) && targetIdVal.isNumber())
{
targetId = targetIdVal.toUint32();
}
if (jsFunc.toObject()->getProperty(SCHEDULE_FUNC_ID_KEY, &funcIdVal) && funcIdVal.isNumber())
{
funcId = funcIdVal.toUint32();
}
if (targetIdVal.isNumber() && funcIdVal.isNumber())
{
const ScheduleElement* scheduleElem = nullptr;
bool found = isScheduleExist(funcId, targetId, &scheduleElem);
if (found)
key = scheduleElem->getKey();
if (found && !key.empty())
{
removeSchedule(funcId, targetId, true);
scheduler->unschedule(key, reinterpret_cast<void*>(targetId));
}
}
else
{
if (targetId == 0)
{
targetId = ++__scheduleTargetIdCounter;
// counter is probably overfollow, it maybe 0 which is invalid id. Increase 1.
if (targetId == 0)
{
targetId = ++__scheduleTargetIdCounter;
}
jsThis.toObject()->setProperty(SCHEDULE_TARGET_ID_KEY, se::Value(targetId));
}
if (funcId == 0)
{
funcId = ++__scheduleFuncIdCounter;
// counter is probably overfollow, it maybe 0 which is invalid id. Increase 1.
if (funcId == 0)
{
funcId = ++__scheduleFuncIdCounter;
}
jsFunc.toObject()->setProperty(SCHEDULE_FUNC_ID_KEY, se::Value(funcId));
}
}
key = StringUtils::format("__node_schedule_key:%u", __idx++);
se::Object* target = jsThis.toObject();
insertSchedule(funcId, targetId, ScheduleElement(target, jsFunc.toObject(), key, targetId, funcId));
std::shared_ptr<UnscheduleNotifier> unscheduleNotifier = std::make_shared<UnscheduleNotifier>(funcId, targetId);
if (toRootTarget)
{
target->root();
}
scheduler->schedule([jsThis, jsFunc, unscheduleNotifier, callFromDebug](float dt){
se::ScriptEngine::getInstance()->clearException();
se::AutoHandleScope hs;
se::Object* thisObj = jsThis.toObject();
se::Object* funcObj = jsFunc.toObject();
se::ValueArray args;
args.push_back(se::Value((double)dt));
bool ok = funcObj->call(args, thisObj);
if (!ok)
{
CCLOGERROR("Invoking schedule callback failed, where: %s", callFromDebug.c_str());
}
}, reinterpret_cast<void*>(targetId), interval, repeat, delay, isPaused, key);
return true;
}
static bool Node_schedule(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
#if 0//COCOS2D_DEBUG > 0
SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size());
int totalCount = 0;
for (const auto& e1 : __js_target_schedulekey_map)
{
SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size());
totalCount += (int)e1.second.size();
}
SE_LOGD("total: %d-------------------------- \n", totalCount);
#endif
if (argc >= 1)
{
Node* thiz = (Node*)s.nativeThisObject();
se::Value jsThis(s.thisObject());
se::Value jsFunc(args[0]);
float interval = 0.0f;
unsigned int repeat = CC_REPEAT_FOREVER;
float delay = 0.0f;
bool ok = false;
if (argc >= 2)
{
ok = seval_to_float(args[1], &interval);
SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed");
}
if (argc >= 3)
{
ok = seval_to_uint32(args[2], &repeat);
SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed");
}
if (argc >= 4)
{
ok = seval_to_float(args[3], &delay);
SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed");
}
return Scheduler_scheduleCommon(thiz->getScheduler(), jsThis, jsFunc, interval, repeat, delay, !thiz->isRunning(), false, "cc.Node.schedule");
}
SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=1");
return false;
}
SE_BIND_FUNC(Node_schedule)
static bool Node_scheduleOnce(se::State& s)
{
const auto& args = s.args();
size_t argc = args.size();
#if 0//COCOS2D_DEBUG > 0
SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size());
for (const auto& e1 : __js_target_schedulekey_map)
{
SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size());
}
SE_LOGD("-------------------------- \n");
#endif
Node* thiz = (Node*)s.nativeThisObject();
se::Value jsThis(s.thisObject());
se::Value jsFunc(args[0]);
float delay = 0.0f;
bool ok = false;
if (argc >= 2)
{
ok = seval_to_float(args[1], &delay);
SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed");
}
return Scheduler_scheduleCommon(thiz->getScheduler(), jsThis, jsFunc, 0.0f, 0, delay, !thiz->isRunning(), false, "cc.Node.scheduleOnce");
}
SE_BIND_FUNC(Node_scheduleOnce)
class UnscheduleUpdateNotifier
{
public:
UnscheduleUpdateNotifier(uint32_t targetId)
: _targetId(targetId)
{
}
~UnscheduleUpdateNotifier()
{
// SE_LOGD("~UnscheduleUpdateNotifier: %p\n", _target);
removeScheduleUpdate(_targetId);
}
private:
uint32_t _targetId;
};
static bool Scheduler_unscheduleUpdateCommon(Scheduler* scheduler, se::Object* jsTarget, uint32_t* foundTargetId = nullptr)
{
assert(jsTarget != nullptr);
se::Value targetIdVal;
if (!jsTarget->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) || !targetIdVal.isNumber())
{
if (foundTargetId != nullptr)
*foundTargetId = 0;
return false;
}
uint32_t targetId = targetIdVal.toUint32();
if (foundTargetId != nullptr)
*foundTargetId = targetId;
bool found = isScheduleUpdateExist(targetId);
if (found)
{
removeScheduleUpdate(targetId);
scheduler->unscheduleUpdate(reinterpret_cast<void*>(targetId));
}
return found;
}
static bool Scheduler_scheduleUpdateCommon(Scheduler* scheduler, const se::Value& jsThis, int priority, bool isPaused)
{
se::Object* jsTargetObj = jsThis.toObject();
uint32_t targetId = 0;
Scheduler_unscheduleUpdateCommon(scheduler, jsTargetObj, &targetId);
if (targetId == 0)
{
targetId = ++__scheduleTargetIdCounter;
// counter is probably overfollow, it maybe 0 which is invalid id. Increase 1.
if (targetId == 0)
{
targetId = ++__scheduleTargetIdCounter;
}
jsTargetObj->setProperty(SCHEDULE_TARGET_ID_KEY, se::Value(targetId));
}
insertScheduleUpdate(targetId, priority, jsTargetObj);
std::shared_ptr<UnscheduleUpdateNotifier> scheduleUpdateWrapper = std::make_shared<UnscheduleUpdateNotifier>(targetId);
se::Value thisVal = jsThis;
scheduler->schedulePerFrame([thisVal, scheduleUpdateWrapper](float dt){
se::ScriptEngine::getInstance()->clearException();
se::AutoHandleScope hs;
se::Value funcVal;
if (thisVal.toObject()->getProperty("update", &funcVal) && funcVal.isObject() && funcVal.toObject()->isFunction())
{
se::ValueArray args;
args.reserve(1);
args.push_back(se::Value(dt));
funcVal.toObject()->call(args, thisVal.toObject());
}
}, reinterpret_cast<void*>(targetId), priority, isPaused);
return true;
}
static bool Node_scheduleUpdate(se::State& s)
{
#if COCOS2D_DEBUG > 1
SE_LOGD("--------------------------\nscheduleUpdate target count: %d\n", (int)__js_target_schedule_update_map.size());
for (const auto& e1 : __js_target_schedule_update_map)
{
SE_LOGD("target: %u, updated: priority: %d\n", e1.first, e1.second.first);
}
SE_LOGD("-------------------------- \n");
#endif
Node* thiz = (Node*)s.nativeThisObject();
se::Value jsThis(s.thisObject());
return Scheduler_scheduleUpdateCommon(thiz->getScheduler(), jsThis, 0, !thiz->isRunning());
}
SE_BIND_FUNC(Node_scheduleUpdate)
static bool Node_scheduleUpdateWithPriority(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
#if COCOS2D_DEBUG > 1
SE_LOGD("--------------------------\nscheduleUpdate target count: %d\n", (int)__js_target_schedule_update_map.size());
for (const auto& e1 : __js_target_schedule_update_map)
{
SE_LOGD("target: %u, updated: priority: %d\n", e1.first, e1.second.first);
}
SE_LOGD("-------------------------- \n");
#endif
Node* thiz = (Node*)s.nativeThisObject();
se::Value jsThis(s.thisObject());
int priority = 0;
if (argc == 1)
{
bool ok = seval_to_int32(args[0], &priority);
SE_PRECONDITION2(ok, false, "Converting priority failed!");
return Scheduler_scheduleUpdateCommon(thiz->getScheduler(), jsThis, priority, !thiz->isRunning());
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(Node_scheduleUpdateWithPriority)
static bool Node_unscheduleUpdate(se::State& s)
{
int argc = (int)s.args().size();
if (argc == 0)
{
Node* node = (Node*)s.nativeThisObject();
Scheduler_unscheduleUpdateCommon(node->getScheduler(), s.thisObject());
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
SE_BIND_FUNC(Node_unscheduleUpdate)
static bool Scheduler_unscheduleCommon(Scheduler* scheduler, const se::Value& jsThis, const se::Value& jsFuncOrKey)
{
std::string key;
bool found = false;
se::Value targetIdVal;
se::Value funcIdVal;
jsThis.toObject()->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal);
if (!targetIdVal.isNumber())
return true;
uint32_t targetId = targetIdVal.toUint32();
uint32_t funcId = 0;
if (jsFuncOrKey.isString() || jsFuncOrKey.isNumber())
{
key = jsFuncOrKey.toStringForce();
const ScheduleElement* scheduleElem = nullptr;
found = isScheduleExist(key, targetId, &scheduleElem);
if (found)
funcId = scheduleElem->getFuncId();
}
else if (jsFuncOrKey.isObject())
{
if (jsFuncOrKey.toObject()->getProperty(SCHEDULE_FUNC_ID_KEY, &funcIdVal) && funcIdVal.isNumber())
{
funcId = funcIdVal.toUint32();
const ScheduleElement* scheduleElem = nullptr;
found = isScheduleExist(funcId, targetId, &scheduleElem);
if (found)
key = scheduleElem->getKey();
}
}
else
{
assert(false);
}
if (!targetIdVal.isNumber() || !funcIdVal.isNumber())
{
return true;
}
if (found && !key.empty())
{
removeSchedule(funcId, targetId, true);
scheduler->unschedule(key, reinterpret_cast<void*>(targetId));
}
else
{
SE_LOGD("WARNING: %s not found\n", __FUNCTION__);
}
return true;
}
static bool Node_unschedule(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
Node* thiz = (Node*)s.nativeThisObject();
se::Value jsThis(s.thisObject());
se::Value jsFunc(args[0]);
return Scheduler_unscheduleCommon(thiz->getScheduler(), jsThis, jsFunc);
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(Node_unschedule)
static bool Scheduler_isScheduled(Scheduler* scheduler, const se::Value& jsThis, const se::Value& jsFuncOrKey)
{
se::Value targetIdVal;
if (!jsThis.toObject()->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) || !targetIdVal.isNumber())
return false;
uint32_t targetId = targetIdVal.toUint32();
if (isTargetExistInScheduler(targetId))
{
if (jsFuncOrKey.isString() || jsFuncOrKey.isNumber())
{
return scheduler->isScheduled(jsFuncOrKey.toStringForce(), reinterpret_cast<void*>(targetId));
}
else if (jsFuncOrKey.isObject())
{
std::string key;
se::Value funcIdVal;
if (jsFuncOrKey.toObject()->getProperty(SCHEDULE_FUNC_ID_KEY, &funcIdVal) && funcIdVal.isNumber())
{
uint32_t funcId = funcIdVal.toUint32();
const ScheduleElement* scheduleElem = nullptr;
if (isScheduleExist(funcId, targetId, &scheduleElem))
{
key = scheduleElem->getKey();
if (!key.empty())
{
return scheduler->isScheduled(key, reinterpret_cast<void*>(targetId));
}
}
}
}
else
{
assert(false);
}
}
return false;
}
static bool Node_isScheduled(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
Node* thiz = (Node*)s.nativeThisObject();
se::Value jsThis(s.thisObject());
se::Value jsFuncOrKey(args[0]);
bool isScheduled = Scheduler_isScheduled(thiz->getScheduler(), jsThis, jsFuncOrKey);
s.rval().setBoolean(isScheduled);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(Node_isScheduled)
static bool Scheduler_unscheduleAllCallbacksCommon(Scheduler* scheduler, se::Object* jsThis, bool needDetachChild)
{
se::Value targetIdVal;
if (!jsThis->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) || !targetIdVal.isNumber())
return true;
uint32_t targetId = targetIdVal.toUint32();
if (isTargetExistInScheduler(targetId))
{
removeScheduleForThis(targetId, needDetachChild);
removeScheduleUpdate(targetId);
}
scheduler->unscheduleAllForTarget(reinterpret_cast<void*>(targetId));
return true;
}
static bool Node_unscheduleAllCallbacks(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
Node* thiz = (Node*)s.nativeThisObject();
if (argc == 0)
{
return Scheduler_unscheduleAllCallbacksCommon(thiz->getScheduler(), s.thisObject(), true);
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
SE_BIND_FUNC(Node_unscheduleAllCallbacks)
static bool Node_getChildren(se::State& s)
{
Node* thiz = (Node*)s.nativeThisObject();
const auto& children = thiz->getChildren();
bool ok = Vector_to_seval(children, &s.rval());
return ok;
}
SE_BIND_FUNC(Node_getChildren)
static bool Node_foo(se::State& s)
{
s.rval().setString("hello world");
return true;
}
SE_BIND_FUNC(Node_foo)
static bool Node_set_x(se::State& s)
{
const auto& args = s.args();
Node* thiz = (Node*)s.nativeThisObject();
float x = args[0].toNumber();
SE_LOGD("cc.Node set_x (%f) native obj: %p\n", x, thiz);
thiz->setPositionX(x);
return true;
}
SE_BIND_PROP_SET(Node_set_x)
static bool Node_get_x(se::State& s)
{
Node* thiz = (Node*)s.nativeThisObject();
s.rval().setFloat(thiz->getPositionX());
return true;
}
SE_BIND_PROP_GET(Node_get_x)
static bool Node_set_y(se::State& s)
{
const auto& args = s.args();
Node* thiz = (Node*)s.nativeThisObject();
float y = args[0].toNumber();
SE_LOGD("cc.Node set_y (%f) native obj: %p\n", y, thiz);
thiz->setPositionY(y);
return true;
}
SE_BIND_PROP_SET(Node_set_y)
static bool Node_get_y(se::State& s)
{
Node* thiz = (Node*)s.nativeThisObject();
s.rval().setFloat(thiz->getPositionY());
return true;
}
SE_BIND_PROP_GET(Node_get_y)
static bool Node_setContentSize(se::State& s)
{
const auto& args = s.args();
size_t argc = args.size();
Node* cobj = (Node*)s.nativeThisObject();
bool ok = true;
if (argc == 1)
{
cocos2d::Size arg0;
ok &= seval_to_Size(args[0], &arg0);
SE_PRECONDITION2(ok, false, "Error processing arguments");
cobj->setContentSize(arg0);
return true;
}
else if (argc == 2)
{
float width = 0.0f;
float height = 0.0f;
ok &= seval_to_float(args[0], &width);
ok &= seval_to_float(args[1], &height);
cobj->setContentSize(cocos2d::Size(width, height));
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
return false;
}
SE_BIND_FUNC(Node_setContentSize)
static bool Node_setAnchorPoint(se::State& s)
{
const auto& args = s.args();
size_t argc = args.size();
Node* cobj = (Node*)s.nativeThisObject();
bool ok = true;
if (argc == 1)
{
cocos2d::Vec2 arg0;
ok &= seval_to_Vec2(args[0], &arg0);
SE_PRECONDITION2(ok, false, "Error processing arguments");
cobj->setAnchorPoint(arg0);
return true;
}
else if (argc == 2)
{
float x = 0.0f;
float y = 0.0f;
ok &= seval_to_float(args[0], &x);
ok &= seval_to_float(args[1], &y);
cobj->setAnchorPoint(cocos2d::Vec2(x, y));
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
return false;
}
SE_BIND_FUNC(Node_setAnchorPoint)
static bool Node_setPosition(se::State& s)
{
const auto& args = s.args();
size_t argc = args.size();
Node* cobj = (Node*)s.nativeThisObject();
bool ok = true;
if (argc == 1)
{
cocos2d::Vec2 arg0;
ok &= seval_to_Vec2(args[0], &arg0);
SE_PRECONDITION2(ok, false, "Error processing arguments");
cobj->setPosition(arg0);
return true;
}
else if (argc == 2)
{
float x = 0.0f;
float y = 0.0f;
ok &= seval_to_float(args[0], &x);
ok &= seval_to_float(args[1], &y);
cobj->setPosition(x, y);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
return false;
}
SE_BIND_FUNC(Node_setPosition)
// Scheduler
static bool js_cocos2dx_Scheduler_scheduleUpdateForTarget(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc >= 1)
{
bool ok = true;
se::Value jsTarget = args[0];
int priority = 0;
bool isPaused = false;
if (argc >= 2)
{
ok = seval_to_int32(args[1], &priority);
SE_PRECONDITION2(ok, false, "Error processing arguments");
}
if (argc >= 3)
{
ok = seval_to_boolean(args[2], &isPaused);
SE_PRECONDITION2(ok, false, "Error processing arguments");
}
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
Scheduler_scheduleUpdateCommon(cobj, jsTarget, priority, isPaused);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=1");
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_scheduleUpdateForTarget)
static bool js_cocos2dx_Scheduler_unscheduleUpdate(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc >= 1)
{
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
se::Value jsTarget = args[0];
Scheduler_unscheduleUpdateCommon(cobj, jsTarget.toObject());
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, "1");
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_unscheduleUpdate)
static bool js_cocos2dx_Scheduler_schedule(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
#if 0//COCOS2D_DEBUG > 0
SE_LOGD("--------------------------\nschedule target count: %d\n", (int)__js_target_schedulekey_map.size());
for (const auto& e1 : __js_target_schedulekey_map)
{
SE_LOGD("schedule target: %p, functions: %d\n", e1.first, (int)e1.second.size());
}
SE_LOGD("-------------------------- \n");
#endif
//
if (argc >= 3)
{
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
se::Value jsFunc;
se::Value jsThis;
if (args[0].isObject() && args[0].toObject()->isFunction())
{
jsFunc = args[0];
jsThis = args[1];
}
else
{
jsFunc = args[1];
jsThis = args[0];
}
bool isBindedObject = jsThis.toObject()->getPrivateData() != nullptr;
// SE_LOGD("%s, is binded object: %s\n", __FUNCTION__, isBindedObject ? "true" : "false");
assert(jsThis.isObject());
assert(!jsThis.toObject()->isFunction());
bool ok = false;
float interval = 0.0f;
unsigned int repeat = CC_REPEAT_FOREVER;
float delay = 0.0f;
bool isPaused = false;
ok = seval_to_float(args[2], &interval);
SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed");
if (argc == 4)
{
// callback, target, interval, paused
ok = seval_to_boolean(args[3], &isPaused);
SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed");
}
else if (argc >= 6)
{
// callback, target, interval, repeat, delay, paused
// repeat
ok = seval_to_uint32(args[3], &repeat);
SE_PRECONDITION2(ok, false, "Converting 'interval' argument failed");
// delay
ok = seval_to_float(args[4], &delay);
SE_PRECONDITION2(ok, false, "Converting 'delay' argument failed");
// isPaused
ok = seval_to_boolean(args[5], &isPaused);
SE_PRECONDITION2(ok, false, "Converting 'isPaused' argument failed");
}
return Scheduler_scheduleCommon(cobj, jsThis, jsFunc, interval, repeat, delay, isPaused, !isBindedObject, "cc.Scheduler.schedule");
}
SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=3");
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_schedule)
static bool js_cocos2dx_Scheduler_unschedule(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc >= 2)
{
se::Value jsFuncOrKey;
se::Value jsTarget;
if (args[0].isString() || (args[0].isObject() && args[0].toObject()->isFunction()))
{
jsFuncOrKey = args[0];
jsTarget = args[1];
}
else
{
jsFuncOrKey = args[1];
jsTarget = args[0];
}
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
return Scheduler_unscheduleCommon(cobj, jsTarget, jsFuncOrKey);
}
SE_REPORT_ERROR("wrong number of arguments: %d, expected: %s", argc, ">=2");
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_unschedule)
static bool js_cocos2dx_Scheduler_unscheduleAllForTarget(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
if (argc == 1)
{
se::Value target = args[0];
return Scheduler_unscheduleAllCallbacksCommon(cobj, target.toObject(), true);
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_unscheduleAllForTarget)
static bool js_cocos2dx_Scheduler_unscheduleAllCallbacks(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 0)
{
removeAllScheduleAndUpdate(true);
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
cobj->unscheduleAll();
CCLOG("After unschedule all callbacks");
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_unscheduleAllCallbacks)
static bool js_cocos2dx_Scheduler_unscheduleAllCallbacksWithMinPriority(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
int minPriority = 0;
bool ok = false;
ok = seval_to_int32(args[0], &minPriority);
SE_PRECONDITION2(ok, false, "Converting minPriority failed!");
removeAllSchedules(true);
removeScheduleUpdatesForMinPriority(minPriority);
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
cobj->unscheduleAllWithMinPriority(minPriority);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_unscheduleAllCallbacksWithMinPriority)
static bool js_cocos2dx_Scheduler_isScheduled(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 2)
{
Scheduler* thiz = (Scheduler*)s.nativeThisObject();
se::Value jsFuncOrKey(args[0]);
se::Value jsThis(args[1]);
bool isScheduled = Scheduler_isScheduled(thiz, jsThis, jsFuncOrKey);
s.rval().setBoolean(isScheduled);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_isScheduled)
static bool js_cocos2dx_Scheduler_pauseTarget(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
se::Value targetIdVal;
if (args[0].toObject()->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) && targetIdVal.isNumber())
{
uint32_t targetId = targetIdVal.toUint32();
if (isTargetExistInScheduler(targetId))
{
cobj->pauseTarget(reinterpret_cast<void*>(targetId));
}
}
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_pauseTarget)
static bool js_cocos2dx_Scheduler_resumeTarget(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
se::Value targetIdVal;
if (args[0].toObject()->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) && targetIdVal.isNumber())
{
uint32_t targetId = targetIdVal.toUint32();
if (isTargetExistInScheduler(targetId))
{
cobj->resumeTarget(reinterpret_cast<void*>(targetId));
}
}
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_resumeTarget)
static bool js_cocos2dx_Scheduler_isTargetPaused(se::State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
Scheduler* cobj = (Scheduler*)s.nativeThisObject();
se::Value targetIdVal;
if (args[0].toObject()->getProperty(SCHEDULE_TARGET_ID_KEY, &targetIdVal) && targetIdVal.isNumber())
{
uint32_t targetId = targetIdVal.toUint32();
if (isTargetExistInScheduler(targetId))
{
bool isPaused = cobj->isTargetPaused(reinterpret_cast<void*>(targetId));
s.rval().setBoolean(isPaused);
return true;
}
}
s.rval().setBoolean(false);
return true;
}
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
SE_BIND_FUNC(js_cocos2dx_Scheduler_isTargetPaused)
static void resumeAllSchedulesForTarget(Node* node, se::Object* jsThis)
{
node->getScheduler()->resumeTarget(jsThis);
}
static void pauseAllSchedulesForTarget(Node* node, se::Object* jsThis)
{
node->getScheduler()->pauseTarget(jsThis);
}
static void cleanupAllSchedulesForTarget(Node* node, se::Object* jsThis)
{
//FIXME: ?? Do we need this since we have already had a 'UnscheduleNotifier' and 'UnscheduleUpdateWrapper'.
node->getScheduler()->unscheduleAllForTarget(jsThis);
}
static bool onReceiveNodeEvent(void* node, ScriptingCore::NodeEventType type)
{
auto iter = se::NativePtrToObjectMap::find(node);
if (iter == se::NativePtrToObjectMap::end())
return false;
se::ScriptEngine::getInstance()->clearException();
se::AutoHandleScope hs;
se::Object* target = iter->second;
const char* funcName = nullptr;
bool ret = false;
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
JSNative func = nullptr;
#endif
if (type == ScriptingCore::NodeEventType::ENTER)
{
funcName = "onEnter";
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
func = _SE(Node_onEnter);
#endif
}
else if (type == ScriptingCore::NodeEventType::EXIT)
{
funcName = "onExit";
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
func = _SE(Node_onExit);
#endif
}
else if (type == ScriptingCore::NodeEventType::ENTER_TRANSITION_DID_FINISH)
{
funcName = "onEnterTransitionDidFinish";
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
func = _SE(Node_onEnterTransitionDidFinish);
#endif
}
else if (type == ScriptingCore::NodeEventType::EXIT_TRANSITION_DID_START)
{
funcName = "onExitTransitionDidStart";
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
func = _SE(Node_onExitTransitionDidStart);
#endif
}
else if (type == ScriptingCore::NodeEventType::CLEANUP)
{
funcName = "cleanup";
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
func = _SE(Node_cleanup);
#endif
}
else
{
assert(false);
}
se::Value funcVal;
bool ok = target->getProperty(funcName, &funcVal);
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
bool isNativeFunc = funcVal.toObject()->_isNativeFunction(func);
#else
bool isNativeFunc = funcVal.toObject()->_isNativeFunction();
#endif
if (ok && !isNativeFunc)
{
ret = funcVal.toObject()->call(se::EmptyValueArray, target);
}
// Handle schedule stuff
if (type == ScriptingCore::NodeEventType::ENTER)
{
resumeAllSchedulesForTarget((Node*)node, target);
}
else if (type == ScriptingCore::NodeEventType::EXIT)
{
pauseAllSchedulesForTarget((Node*)node, target);
}
else if (type == ScriptingCore::NodeEventType::CLEANUP)
{
cleanupAllSchedulesForTarget((Node*)node, target);
}
return ret;
}
bool jsb_register_Node_manual(se::Object* global)
{
#if STANDALONE_TEST
auto cls = se::Class::create("Node", __ccObj, nullptr, _SE(Node_constructor));
cls->defineStaticFunction("create", _SE(Node_create));
cls->defineProperty("x", _SE(Node_get_x), _SE(Node_set_x));
cls->defineProperty("y", _SE(Node_get_y), _SE(Node_set_y));
cls->defineFunction("ctor", _SE(Node_ctor));
#else
auto cls = __jsb_cocos2d_Node_proto;
#endif
cls->defineFunction("onEnter", _SE(Node_onEnter));
cls->defineFunction("onExit", _SE(Node_onExit));
cls->defineFunction("onEnterTransitionDidFinish", _SE(Node_onEnterTransitionDidFinish));
cls->defineFunction("onExitTransitionDidStart", _SE(Node_onExitTransitionDidStart));
cls->defineFunction("cleanup", _SE(Node_cleanup));
cls->defineFunction("schedule", _SE(Node_schedule));
cls->defineFunction("scheduleOnce", _SE(Node_scheduleOnce));
cls->defineFunction("scheduleUpdateWithPriority", _SE(Node_scheduleUpdateWithPriority));
cls->defineFunction("scheduleUpdate", _SE(Node_scheduleUpdate));
cls->defineFunction("unscheduleUpdate", _SE(Node_unscheduleUpdate));
cls->defineFunction("unschedule", _SE(Node_unschedule));
cls->defineFunction("unscheduleAllCallbacks", _SE(Node_unscheduleAllCallbacks));
cls->defineFunction("isScheduled", _SE(Node_isScheduled));
cls->defineFunction("setContentSize", _SE(Node_setContentSize));
cls->defineFunction("setAnchorPoint", _SE(Node_setAnchorPoint));
cls->defineFunction("setPosition", _SE(Node_setPosition));
auto schedulerProto = __jsb_cocos2d_Scheduler_proto;
schedulerProto->defineFunction("scheduleUpdateForTarget", _SE(js_cocos2dx_Scheduler_scheduleUpdateForTarget));
schedulerProto->defineFunction("scheduleUpdate", _SE(js_cocos2dx_Scheduler_scheduleUpdateForTarget));
schedulerProto->defineFunction("unscheduleUpdate", _SE(js_cocos2dx_Scheduler_unscheduleUpdate));
schedulerProto->defineFunction("schedule", _SE(js_cocos2dx_Scheduler_schedule));
schedulerProto->defineFunction("scheduleCallbackForTarget", _SE(js_cocos2dx_Scheduler_schedule));
schedulerProto->defineFunction("unschedule", _SE(js_cocos2dx_Scheduler_unschedule));
schedulerProto->defineFunction("unscheduleCallbackForTarget", _SE(js_cocos2dx_Scheduler_unschedule));
schedulerProto->defineFunction("unscheduleAllForTarget", _SE(js_cocos2dx_Scheduler_unscheduleAllForTarget));
schedulerProto->defineFunction("unscheduleAllCallbacks", _SE(js_cocos2dx_Scheduler_unscheduleAllCallbacks));
schedulerProto->defineFunction("unscheduleAllCallbacksWithMinPriority", _SE(js_cocos2dx_Scheduler_unscheduleAllCallbacksWithMinPriority));
schedulerProto->defineFunction("isScheduled", _SE(js_cocos2dx_Scheduler_isScheduled));
schedulerProto->defineFunction("pauseTarget", _SE(js_cocos2dx_Scheduler_pauseTarget));
schedulerProto->defineFunction("resumeTarget", _SE(js_cocos2dx_Scheduler_resumeTarget));
schedulerProto->defineFunction("isTargetPaused", _SE(js_cocos2dx_Scheduler_isTargetPaused));
#if STANDALONE_TEST
cls->defineFunction("addChild", _SE(Node_addChild));
cls->defineFunction("getChildren", _SE(Node_getChildren));
cls->defineFinalizeFunction(_SE(Node_finalized));
cls->install();
__jsb_Node_proto = cls->getProto();
__jsb_Node_class = cls;
__jsb_Node_proto->defineFunction("foo", _SE(Node_foo));
__jsb_Node_proto->setProperty("var1", se::Value("I'm var1"));
__jsb_Node_proto->setProperty("var2", se::Value(10000.323));
#endif
ScriptingCore::getInstance()->setNodeEventListener(onReceiveNodeEvent);
se::ScriptEngine::getInstance()->clearException();
return true;
}
| 0 | 0.943278 | 1 | 0.943278 | game-dev | MEDIA | 0.763933 | game-dev | 0.901124 | 1 | 0.901124 |
ReactVision/virocore | 12,449 | macos/Libraries/bullet/include/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_OVERLAPPING_PAIR_CACHE_H
#define BT_OVERLAPPING_PAIR_CACHE_H
#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"
#include "LinearMath/btAlignedObjectArray.h"
class btDispatcher;
typedef btAlignedObjectArray<btBroadphasePair> btBroadphasePairArray;
struct btOverlapCallback
{
virtual ~btOverlapCallback()
{}
//return true for deletion of the pair
virtual bool processOverlap(btBroadphasePair& pair) = 0;
};
struct btOverlapFilterCallback
{
virtual ~btOverlapFilterCallback()
{}
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const = 0;
};
extern int gRemovePairs;
extern int gAddedPairs;
extern int gFindPairs;
const int BT_NULL_PAIR=0xffffffff;
///The btOverlappingPairCache provides an interface for overlapping pair management (add, remove, storage), used by the btBroadphaseInterface broadphases.
///The btHashedOverlappingPairCache and btSortedOverlappingPairCache classes are two implementations.
class btOverlappingPairCache : public btOverlappingPairCallback
{
public:
virtual ~btOverlappingPairCache() {} // this is needed so we can get to the derived class destructor
virtual btBroadphasePair* getOverlappingPairArrayPtr() = 0;
virtual const btBroadphasePair* getOverlappingPairArrayPtr() const = 0;
virtual btBroadphasePairArray& getOverlappingPairArray() = 0;
virtual void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher) = 0;
virtual int getNumOverlappingPairs() const = 0;
virtual void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher) = 0;
virtual void setOverlapFilterCallback(btOverlapFilterCallback* callback) = 0;
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher) = 0;
virtual btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) = 0;
virtual bool hasDeferredRemoval() = 0;
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)=0;
virtual void sortOverlappingPairs(btDispatcher* dispatcher) = 0;
};
/// Hash-space based Pair Cache, thanks to Erin Catto, Box2D, http://www.box2d.org, and Pierre Terdiman, Codercorner, http://codercorner.com
ATTRIBUTE_ALIGNED16(class) btHashedOverlappingPairCache : public btOverlappingPairCache
{
btBroadphasePairArray m_overlappingPairArray;
btOverlapFilterCallback* m_overlapFilterCallback;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
btOverlappingPairCallback* m_ghostPairCallback;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btHashedOverlappingPairCache();
virtual ~btHashedOverlappingPairCache();
void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher);
SIMD_FORCE_INLINE bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
{
if (m_overlapFilterCallback)
return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)
{
gAddedPairs++;
if (!needsBroadphaseCollision(proxy0,proxy1))
return 0;
return internalAddPair(proxy0,proxy1);
}
void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher);
virtual btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btBroadphasePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher);
btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1);
int GetCount() const { return m_overlappingPairArray.size(); }
// btBroadphasePair* GetPairs() { return m_pairs; }
btOverlapFilterCallback* getOverlapFilterCallback()
{
return m_overlapFilterCallback;
}
void setOverlapFilterCallback(btOverlapFilterCallback* callback)
{
m_overlapFilterCallback = callback;
}
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btBroadphasePair* internalAddPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btBroadphasePair& pair, int proxyId1, int proxyId2)
{
return pair.m_pProxy0->getUid() == proxyId1 && pair.m_pProxy1->getUid() == proxyId2;
}
/*
// Thomas Wang's hash, see: http://www.concentric.net/~Ttwang/tech/inthash.htm
// This assumes proxyId1 and proxyId2 are 16-bit.
SIMD_FORCE_INLINE int getHash(int proxyId1, int proxyId2)
{
int key = (proxyId2 << 16) | proxyId1;
key = ~key + (key << 15);
key = key ^ (key >> 12);
key = key + (key << 2);
key = key ^ (key >> 4);
key = key * 2057;
key = key ^ (key >> 16);
return key;
}
*/
SIMD_FORCE_INLINE unsigned int getHash(unsigned int proxyId1, unsigned int proxyId2)
{
unsigned int key = proxyId1 | (proxyId2 << 16);
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
SIMD_FORCE_INLINE btBroadphasePair* internalFindPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, int hash)
{
int proxyId1 = proxy0->getUid();
int proxyId2 = proxy1->getUid();
#if 0 // wrong, 'equalsPair' use unsorted uids, copy-past devil striked again. Nat.
if (proxyId1 > proxyId2)
btSwap(proxyId1, proxyId2);
#endif
int index = m_hashTable[hash];
while( index != BT_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyId1, proxyId2) == false)
{
index = m_next[index];
}
if ( index == BT_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
virtual bool hasDeferredRemoval()
{
return false;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)
{
m_ghostPairCallback = ghostPairCallback;
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};
///btSortedOverlappingPairCache maintains the objects with overlapping AABB
///Typically managed by the Broadphase, Axis3Sweep or btSimpleBroadphase
class btSortedOverlappingPairCache : public btOverlappingPairCache
{
protected:
//avoid brute-force finding all the time
btBroadphasePairArray m_overlappingPairArray;
//during the dispatch, check that user doesn't destroy/create proxy
bool m_blockedForChanges;
///by default, do the removal during the pair traversal
bool m_hasDeferredRemoval;
//if set, use the callback instead of the built in filter in needBroadphaseCollision
btOverlapFilterCallback* m_overlapFilterCallback;
btOverlappingPairCallback* m_ghostPairCallback;
public:
btSortedOverlappingPairCache();
virtual ~btSortedOverlappingPairCache();
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher);
void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher);
void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher);
btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
btBroadphasePair* findPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
inline bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
{
if (m_overlapFilterCallback)
return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btBroadphasePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
btOverlapFilterCallback* getOverlapFilterCallback()
{
return m_overlapFilterCallback;
}
void setOverlapFilterCallback(btOverlapFilterCallback* callback)
{
m_overlapFilterCallback = callback;
}
virtual bool hasDeferredRemoval()
{
return m_hasDeferredRemoval;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)
{
m_ghostPairCallback = ghostPairCallback;
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};
///btNullPairCache skips add/removal of overlapping pairs. Userful for benchmarking and unit testing.
class btNullPairCache : public btOverlappingPairCache
{
btBroadphasePairArray m_overlappingPairArray;
public:
virtual btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
virtual void cleanOverlappingPair(btBroadphasePair& /*pair*/,btDispatcher* /*dispatcher*/)
{
}
virtual int getNumOverlappingPairs() const
{
return 0;
}
virtual void cleanProxyFromPairs(btBroadphaseProxy* /*proxy*/,btDispatcher* /*dispatcher*/)
{
}
virtual void setOverlapFilterCallback(btOverlapFilterCallback* /*callback*/)
{
}
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* /*dispatcher*/)
{
}
virtual btBroadphasePair* findPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/)
{
return 0;
}
virtual bool hasDeferredRemoval()
{
return true;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* /* ghostPairCallback */)
{
}
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/)
{
return 0;
}
virtual void* removeOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/,btDispatcher* /*dispatcher*/)
{
return 0;
}
virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/,btDispatcher* /*dispatcher*/)
{
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher)
{
(void) dispatcher;
}
};
#endif //BT_OVERLAPPING_PAIR_CACHE_H
| 0 | 0.91222 | 1 | 0.91222 | game-dev | MEDIA | 0.741091 | game-dev,networking | 0.931686 | 1 | 0.931686 |
projectPiki/pikmin | 6,520 | src/plugPikiNishimura/genBoss.cpp | #include "Age.h"
#include "Boss.h"
#include "DebugLog.h"
#include "Generator.h"
#include "Pellet.h"
#include "sysNew.h"
/*
* --INFO--
* Address: ........
* Size: 00009C
*/
DEFINE_ERROR(__LINE__) // Never used in the DLL
/*
* --INFO--
* Address: ........
* Size: 0000F0
*/
DEFINE_PRINT("genBoss");
/*
* --INFO--
* Address: 8014D2D0
* Size: 00008C
*/
static GenObject* makeObjectBoss()
{
return new GenObjectBoss();
}
/*
* --INFO--
* Address: 8014D35C
* Size: 000088
*/
void GenObjectBoss::initialise()
{
GenObjectFactory::factory->registerMember('boss', &makeObjectBoss, "ボスを発生", 2);
}
/*
* --INFO--
* Address: 8014D3E4
* Size: 0000EC
*/
void GenObjectBoss::doRead(RandomAccessStream& input)
{
if (mVersion == 'v0.0') {
mBossID = input.readInt();
return;
}
if (mVersion < 2) {
mBossID = input.readInt();
mItemIndex = input.readInt();
mItemColour = input.readInt();
mItemCount = input.readInt();
ID32 id;
id.read(input);
return;
}
readParameters(input);
}
/*
* --INFO--
* Address: 8014D4D0
* Size: 000020
*/
void GenObjectBoss::doWrite(RandomAccessStream& output)
{
writeParameters(output);
}
/*
* --INFO--
* Address: 8014D4F0
* Size: 000020
*/
void GenObjectBoss::ramLoadParameters(RandomAccessStream& input)
{
readParameters(input);
}
/*
* --INFO--
* Address: 8014D510
* Size: 000020
*/
void GenObjectBoss::ramSaveParameters(RandomAccessStream& output)
{
writeParameters(output);
}
/*
* --INFO--
* Address: 8014D530
* Size: 000080
*/
void GenObjectBoss::readParameters(RandomAccessStream& input)
{
// this is too much compression, just read them as words goddamn it!
union GenFlags {
u32 w;
struct {
u32 m0 : 20;
u32 m1 : 4;
u32 m2 : 2;
u32 m3 : 2;
u32 m4 : 4;
} b;
} flags;
flags.w = input.readInt();
mBossID = flags.b.m4;
mItemIndex = flags.b.m3;
mItemColour = flags.b.m2;
mItemCount = flags.b.m1;
mPelletConfigIdx = flags.b.m0 - 1;
}
/*
* --INFO--
* Address: 8014D5B0
* Size: 000090
*/
void GenObjectBoss::writeParameters(RandomAccessStream& output)
{
// this is too much compression, just write them as words goddamn it!
union GenFlags {
u32 w;
struct {
u32 m0 : 20;
u32 m1 : 4;
u32 m2 : 2;
u32 m3 : 2;
u32 m4 : 4;
} b;
} flags;
flags.w = 0;
flags.b.m4 = mBossID;
flags.b.m3 = mItemIndex;
flags.b.m2 = mItemColour;
flags.b.m1 = mItemCount;
flags.b.m0 = mPelletConfigIdx + 1;
output.writeInt(flags.w);
}
/*
* --INFO--
* Address: 8014D640
* Size: 000150
*/
void GenObjectBoss::updateUseList(Generator*, int count)
{
if (mBossID == GENBOSS_Spider) {
bossMgr->addUseCount(BOSS_Spider, 1);
return;
}
if (mBossID == GENBOSS_Snake) {
bossMgr->addUseCount(BOSS_Snake, 1);
return;
}
if (mBossID == GENBOSS_Slime) {
bossMgr->addUseCount(BOSS_Slime, 1);
bossMgr->addUseCount(BOSS_Nucleus, 1);
bossMgr->addUseCount(BOSS_CoreNucleus, 1);
return;
}
if (mBossID == GENBOSS_King) {
bossMgr->addUseCount(BOSS_King, 1);
return;
}
if (mBossID == GENBOSS_Kogane) {
bossMgr->addUseCount(BOSS_Kogane, count);
return;
}
if (mBossID == GENBOSS_Pom) {
bossMgr->addUseCount(BOSS_Pom, 1);
return;
}
if (mBossID == GENBOSS_KingBack) {
bossMgr->addUseCount(BOSS_KingBack, 1);
return;
}
if (mBossID == GENBOSS_BoxSnake) {
bossMgr->addUseCount(BOSS_BoxSnake, 1);
return;
}
if (mBossID == GENBOSS_Mizu) {
bossMgr->addUseCount(BOSS_Mizu, 1);
return;
}
if (mBossID == GENBOSS_Geyzer) {
bossMgr->addUseCount(BOSS_Geyzer, 1);
return;
}
}
/*
* --INFO--
* Address: 8014D790
* Size: 00013C
*/
Creature* GenObjectBoss::birth(BirthInfo& info)
{
Creature* boss = nullptr;
PRINT("\n");
PRINT("************ BOSS BIRTH START : kind = %d ************\n", mBossID);
if (mBossID == GENBOSS_Spider) {
boss = bossMgr->create(GENBOSS_Spider, info, this);
} else if (mBossID == GENBOSS_Snake) {
boss = bossMgr->create(GENBOSS_Snake, info, this);
} else if (mBossID == GENBOSS_Slime) {
boss = bossMgr->create(GENBOSS_Slime, info, this);
} else if (mBossID == GENBOSS_King) {
boss = bossMgr->create(GENBOSS_King, info, this);
} else if (mBossID == GENBOSS_Kogane) {
boss = bossMgr->create(GENBOSS_Kogane, info, this);
} else if (mBossID == GENBOSS_Pom) {
boss = bossMgr->create(GENBOSS_Pom, info, this);
} else if (mBossID == GENBOSS_KingBack) {
boss = bossMgr->create(GENBOSS_KingBack, info, this);
} else if (mBossID == GENBOSS_BoxSnake) {
boss = bossMgr->create(GENBOSS_BoxSnake, info, this);
} else if (mBossID == GENBOSS_Mizu) {
boss = bossMgr->create(GENBOSS_Mizu, info, this);
} else if (mBossID == GENBOSS_Geyzer) {
boss = bossMgr->create(GENBOSS_Geyzer, info, this);
}
if (!boss) {
PRINT("************ BOSS BIRTH END : FAILURE ************\n");
} else {
PRINT(" VVVVVVVVV \n");
PRINT(" ww ww \n");
PRINT("<-○--__ | \n");
PRINT(" | Λ -○->\n");
PRINT(" \ ё / \n");
PRINT("************ BOSS BIRTH END : SUCCESS ************\n");
}
PRINT("\n");
return boss;
}
#ifdef WIN32
void GenObjectBoss::doGenAge(AgeServer& server)
{
server.StartOptionBox("ボスの種類", &mBossID, 252); // boss type
server.NewOption("ダマグモ", 0);
server.NewOption("ヘビガラス1", 1);
server.NewOption("ヘビガラス2", 7);
server.NewOption("スライム", 2);
server.NewOption("キングチャッピー", 3);
server.NewOption("コガネ", 4);
server.NewOption("ポンガシ草", 5);
server.NewOption("キングの背中", 6);
server.NewOption("間欠泉1", 8);
server.NewOption("間欠泉2", 9);
server.EndOptionBox();
server.StartOptionBox("ペレットの種類", &mItemIndex, 252);
server.NewOption("1ペレット", 0);
server.NewOption("5ペレット", 1);
server.NewOption("10ペレット", 2);
server.NewOption("20ペレット", 3);
server.EndOptionBox();
server.StartOptionBox("ペレットの色", &mItemColour, 252);
server.NewOption("青ペレット", 0);
server.NewOption("赤ペレット", 1);
server.NewOption("黄ペレット", 2);
server.NewOption("ランダム", 3);
server.EndOptionBox();
server.StartOptionBox("ペレットの数", &mItemCount, 252);
for (int i = 0; i < 16; i++) {
char id[4];
if (i / 10 < 1) {
id[0] = i % 10 + '0';
id[1] = 0;
} else {
id[0] = i / 10 + '0';
id[1] = i % 10 + '0';
id[2] = 0;
}
server.NewOption(id, i);
}
server.EndOptionBox();
server.StartOptionBox("UFOパーツ", &mPelletConfigIdx, 252);
server.NewOption("none", -1);
for (int i = 0; i < pelletMgr->getNumConfigs(); i++) {
PelletConfig* config = pelletMgr->getConfigFromIdx(i);
server.NewOption(config->mPelletName().mString, config->mPelletId.mId);
}
server.EndOptionBox();
}
#endif
| 0 | 0.87244 | 1 | 0.87244 | game-dev | MEDIA | 0.32861 | game-dev | 0.59748 | 1 | 0.59748 |
Tencent/behaviac | 5,058 | integration/demo_running/behaviac/BehaviorTree/Nodes/Decorators/DecoratorIterator.cs | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System.Collections;
using System.Collections.Generic;
namespace behaviac
{
public class DecoratorIterator : DecoratorNode
{
#if BEHAVIAC_USE_HTN
public override bool decompose(BehaviorNode node, PlannerTaskComplex seqTask, int depth, Planner planner)
{
DecoratorIterator pForEach = (DecoratorIterator)node;
bool bOk = false;
int childCount = pForEach.GetChildrenCount();
Debug.Check(childCount == 1);
BehaviorNode childNode = pForEach.GetChild(0);
bool bGoOn = true;
int count = 0;
int index = 0;
while (bGoOn)
{
int depth2 = planner.GetAgent().Variables.Depth;
using(AgentState currentState = planner.GetAgent().Variables.Push(false))
{
bGoOn = pForEach.IterateIt(planner.GetAgent(), index, ref count);
if (bGoOn)
{
planner.LogPlanForEachBegin(planner.GetAgent(), pForEach, index, count);
PlannerTask childTask = planner.decomposeNode(childNode, depth);
planner.LogPlanForEachEnd(planner.GetAgent(), pForEach, index, count, childTask != null ? "success" : "failure");
if (childTask != null)
{
Debug.Check(seqTask is PlannerTaskIterator);
PlannerTaskIterator pForEachTask = seqTask as PlannerTaskIterator;
pForEachTask.Index = index;
seqTask.AddChild(childTask);
bOk = true;
break;
}
index++;
}
}
Debug.Check(planner.GetAgent().Variables.Depth == depth2);
}
return bOk;
}
#endif//
protected override void load(int version, string agentType, List<property_t> properties)
{
base.load(version, agentType, properties);
for (int i = 0; i < properties.Count; ++i)
{
property_t p = properties[i];
if (p.name == "Opl")
{
int pParenthesis = p.value.IndexOf('(');
if (pParenthesis == -1)
{
this.m_opl = AgentMeta.ParseProperty(p.value);
}
else
{
Debug.Check(false);
}
}
else if (p.name == "Opr")
{
int pParenthesis = p.value.IndexOf('(');
if (pParenthesis == -1)
{
this.m_opr = AgentMeta.ParseProperty(p.value);
}
else
{
this.m_opr = AgentMeta.ParseMethod(p.value);
}
}
}
}
public override bool IsValid(Agent pAgent, BehaviorTask pTask)
{
if (!(pTask.GetNode() is DecoratorIterator))
{
return false;
}
return base.IsValid(pAgent, pTask);
}
public bool IterateIt(Agent pAgent, int index, ref int count)
{
if (this.m_opl != null && this.m_opr != null)
{
count = this.m_opr.GetCount(pAgent);
if (index >= 0 && index < count)
{
this.m_opl.SetValue(pAgent, this.m_opr, index);
return true;
}
}
else
{
Debug.Check(false);
}
return false;
}
protected override BehaviorTask createTask()
{
Debug.Check(false);
return null;
}
protected IInstanceMember m_opl;
protected IInstanceMember m_opr;
}
}
| 0 | 0.94676 | 1 | 0.94676 | game-dev | MEDIA | 0.882469 | game-dev | 0.985342 | 1 | 0.985342 |
chai3d/chai3d | 3,583 | modules/Bullet/externals/bullet/src/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_MULTIBODY_DYNAMICS_WORLD_H
#define BT_MULTIBODY_DYNAMICS_WORLD_H
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"
#define BT_USE_VIRTUAL_CLEARFORCES_AND_GRAVITY
class btMultiBody;
class btMultiBodyConstraint;
class btMultiBodyConstraintSolver;
struct MultiBodyInplaceSolverIslandCallback;
///The btMultiBodyDynamicsWorld adds Featherstone multi body dynamics to Bullet
///This implementation is still preliminary/experimental.
class btMultiBodyDynamicsWorld : public btDiscreteDynamicsWorld
{
protected:
btAlignedObjectArray<btMultiBody*> m_multiBodies;
btAlignedObjectArray<btMultiBodyConstraint*> m_multiBodyConstraints;
btAlignedObjectArray<btMultiBodyConstraint*> m_sortedMultiBodyConstraints;
btMultiBodyConstraintSolver* m_multiBodyConstraintSolver;
MultiBodyInplaceSolverIslandCallback* m_solverMultiBodyIslandCallback;
virtual void calculateSimulationIslands();
virtual void updateActivationState(btScalar timeStep);
virtual void solveConstraints(btContactSolverInfo& solverInfo);
virtual void serializeMultiBodies(btSerializer* serializer);
public:
btMultiBodyDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btMultiBodyConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration);
virtual ~btMultiBodyDynamicsWorld ();
virtual void addMultiBody(btMultiBody* body, short group= btBroadphaseProxy::DefaultFilter, short mask=btBroadphaseProxy::AllFilter);
virtual void removeMultiBody(btMultiBody* body);
virtual int getNumMultibodies() const
{
return m_multiBodies.size();
}
btMultiBody* getMultiBody(int mbIndex)
{
return m_multiBodies[mbIndex];
}
virtual void addMultiBodyConstraint( btMultiBodyConstraint* constraint);
virtual int getNumMultiBodyConstraints() const
{
return m_multiBodyConstraints.size();
}
virtual btMultiBodyConstraint* getMultiBodyConstraint( int constraintIndex)
{
return m_multiBodyConstraints[constraintIndex];
}
virtual const btMultiBodyConstraint* getMultiBodyConstraint( int constraintIndex) const
{
return m_multiBodyConstraints[constraintIndex];
}
virtual void removeMultiBodyConstraint( btMultiBodyConstraint* constraint);
virtual void integrateTransforms(btScalar timeStep);
virtual void debugDrawWorld();
virtual void debugDrawMultiBodyConstraint(btMultiBodyConstraint* constraint);
void forwardKinematics();
virtual void clearForces();
virtual void clearMultiBodyConstraintForces();
virtual void clearMultiBodyForces();
virtual void applyGravity();
virtual void serialize(btSerializer* serializer);
};
#endif //BT_MULTIBODY_DYNAMICS_WORLD_H
| 0 | 0.686435 | 1 | 0.686435 | game-dev | MEDIA | 0.918227 | game-dev | 0.741329 | 1 | 0.741329 |
ComputationalBiomechanicsLab/opensim-creator | 47,152 | third_party/SDL/src/video/emscripten/SDL_emscriptenevents.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#ifdef SDL_VIDEO_DRIVER_EMSCRIPTEN
#include <emscripten/html5.h>
#include <emscripten/dom_pk_codes.h>
#include "../../events/SDL_dropevents_c.h"
#include "../../events/SDL_events_c.h"
#include "../../events/SDL_keyboard_c.h"
#include "../../events/SDL_touch_c.h"
#include "SDL_emscriptenevents.h"
#include "SDL_emscriptenvideo.h"
/*
Emscripten PK code to scancode
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code
*/
static const SDL_Scancode emscripten_scancode_table[] = {
/* 0x00 "Unidentified" */ SDL_SCANCODE_UNKNOWN,
/* 0x01 "Escape" */ SDL_SCANCODE_ESCAPE,
/* 0x02 "Digit0" */ SDL_SCANCODE_0,
/* 0x03 "Digit1" */ SDL_SCANCODE_1,
/* 0x04 "Digit2" */ SDL_SCANCODE_2,
/* 0x05 "Digit3" */ SDL_SCANCODE_3,
/* 0x06 "Digit4" */ SDL_SCANCODE_4,
/* 0x07 "Digit5" */ SDL_SCANCODE_5,
/* 0x08 "Digit6" */ SDL_SCANCODE_6,
/* 0x09 "Digit7" */ SDL_SCANCODE_7,
/* 0x0A "Digit8" */ SDL_SCANCODE_8,
/* 0x0B "Digit9" */ SDL_SCANCODE_9,
/* 0x0C "Minus" */ SDL_SCANCODE_MINUS,
/* 0x0D "Equal" */ SDL_SCANCODE_EQUALS,
/* 0x0E "Backspace" */ SDL_SCANCODE_BACKSPACE,
/* 0x0F "Tab" */ SDL_SCANCODE_TAB,
/* 0x10 "KeyQ" */ SDL_SCANCODE_Q,
/* 0x11 "KeyW" */ SDL_SCANCODE_W,
/* 0x12 "KeyE" */ SDL_SCANCODE_E,
/* 0x13 "KeyR" */ SDL_SCANCODE_R,
/* 0x14 "KeyT" */ SDL_SCANCODE_T,
/* 0x15 "KeyY" */ SDL_SCANCODE_Y,
/* 0x16 "KeyU" */ SDL_SCANCODE_U,
/* 0x17 "KeyI" */ SDL_SCANCODE_I,
/* 0x18 "KeyO" */ SDL_SCANCODE_O,
/* 0x19 "KeyP" */ SDL_SCANCODE_P,
/* 0x1A "BracketLeft" */ SDL_SCANCODE_LEFTBRACKET,
/* 0x1B "BracketRight" */ SDL_SCANCODE_RIGHTBRACKET,
/* 0x1C "Enter" */ SDL_SCANCODE_RETURN,
/* 0x1D "ControlLeft" */ SDL_SCANCODE_LCTRL,
/* 0x1E "KeyA" */ SDL_SCANCODE_A,
/* 0x1F "KeyS" */ SDL_SCANCODE_S,
/* 0x20 "KeyD" */ SDL_SCANCODE_D,
/* 0x21 "KeyF" */ SDL_SCANCODE_F,
/* 0x22 "KeyG" */ SDL_SCANCODE_G,
/* 0x23 "KeyH" */ SDL_SCANCODE_H,
/* 0x24 "KeyJ" */ SDL_SCANCODE_J,
/* 0x25 "KeyK" */ SDL_SCANCODE_K,
/* 0x26 "KeyL" */ SDL_SCANCODE_L,
/* 0x27 "Semicolon" */ SDL_SCANCODE_SEMICOLON,
/* 0x28 "Quote" */ SDL_SCANCODE_APOSTROPHE,
/* 0x29 "Backquote" */ SDL_SCANCODE_GRAVE,
/* 0x2A "ShiftLeft" */ SDL_SCANCODE_LSHIFT,
/* 0x2B "Backslash" */ SDL_SCANCODE_BACKSLASH,
/* 0x2C "KeyZ" */ SDL_SCANCODE_Z,
/* 0x2D "KeyX" */ SDL_SCANCODE_X,
/* 0x2E "KeyC" */ SDL_SCANCODE_C,
/* 0x2F "KeyV" */ SDL_SCANCODE_V,
/* 0x30 "KeyB" */ SDL_SCANCODE_B,
/* 0x31 "KeyN" */ SDL_SCANCODE_N,
/* 0x32 "KeyM" */ SDL_SCANCODE_M,
/* 0x33 "Comma" */ SDL_SCANCODE_COMMA,
/* 0x34 "Period" */ SDL_SCANCODE_PERIOD,
/* 0x35 "Slash" */ SDL_SCANCODE_SLASH,
/* 0x36 "ShiftRight" */ SDL_SCANCODE_RSHIFT,
/* 0x37 "NumpadMultiply" */ SDL_SCANCODE_KP_MULTIPLY,
/* 0x38 "AltLeft" */ SDL_SCANCODE_LALT,
/* 0x39 "Space" */ SDL_SCANCODE_SPACE,
/* 0x3A "CapsLock" */ SDL_SCANCODE_CAPSLOCK,
/* 0x3B "F1" */ SDL_SCANCODE_F1,
/* 0x3C "F2" */ SDL_SCANCODE_F2,
/* 0x3D "F3" */ SDL_SCANCODE_F3,
/* 0x3E "F4" */ SDL_SCANCODE_F4,
/* 0x3F "F5" */ SDL_SCANCODE_F5,
/* 0x40 "F6" */ SDL_SCANCODE_F6,
/* 0x41 "F7" */ SDL_SCANCODE_F7,
/* 0x42 "F8" */ SDL_SCANCODE_F8,
/* 0x43 "F9" */ SDL_SCANCODE_F9,
/* 0x44 "F10" */ SDL_SCANCODE_F10,
/* 0x45 "Pause" */ SDL_SCANCODE_PAUSE,
/* 0x46 "ScrollLock" */ SDL_SCANCODE_SCROLLLOCK,
/* 0x47 "Numpad7" */ SDL_SCANCODE_KP_7,
/* 0x48 "Numpad8" */ SDL_SCANCODE_KP_8,
/* 0x49 "Numpad9" */ SDL_SCANCODE_KP_9,
/* 0x4A "NumpadSubtract" */ SDL_SCANCODE_KP_MINUS,
/* 0x4B "Numpad4" */ SDL_SCANCODE_KP_4,
/* 0x4C "Numpad5" */ SDL_SCANCODE_KP_5,
/* 0x4D "Numpad6" */ SDL_SCANCODE_KP_6,
/* 0x4E "NumpadAdd" */ SDL_SCANCODE_KP_PLUS,
/* 0x4F "Numpad1" */ SDL_SCANCODE_KP_1,
/* 0x50 "Numpad2" */ SDL_SCANCODE_KP_2,
/* 0x51 "Numpad3" */ SDL_SCANCODE_KP_3,
/* 0x52 "Numpad0" */ SDL_SCANCODE_KP_0,
/* 0x53 "NumpadDecimal" */ SDL_SCANCODE_KP_PERIOD,
/* 0x54 "PrintScreen" */ SDL_SCANCODE_PRINTSCREEN,
/* 0x55 */ SDL_SCANCODE_UNKNOWN,
/* 0x56 "IntlBackslash" */ SDL_SCANCODE_NONUSBACKSLASH,
/* 0x57 "F11" */ SDL_SCANCODE_F11,
/* 0x58 "F12" */ SDL_SCANCODE_F12,
/* 0x59 "NumpadEqual" */ SDL_SCANCODE_KP_EQUALS,
/* 0x5A */ SDL_SCANCODE_UNKNOWN,
/* 0x5B */ SDL_SCANCODE_UNKNOWN,
/* 0x5C */ SDL_SCANCODE_UNKNOWN,
/* 0x5D */ SDL_SCANCODE_UNKNOWN,
/* 0x5E */ SDL_SCANCODE_UNKNOWN,
/* 0x5F */ SDL_SCANCODE_UNKNOWN,
/* 0x60 */ SDL_SCANCODE_UNKNOWN,
/* 0x61 */ SDL_SCANCODE_UNKNOWN,
/* 0x62 */ SDL_SCANCODE_UNKNOWN,
/* 0x63 */ SDL_SCANCODE_UNKNOWN,
/* 0x64 "F13" */ SDL_SCANCODE_F13,
/* 0x65 "F14" */ SDL_SCANCODE_F14,
/* 0x66 "F15" */ SDL_SCANCODE_F15,
/* 0x67 "F16" */ SDL_SCANCODE_F16,
/* 0x68 "F17" */ SDL_SCANCODE_F17,
/* 0x69 "F18" */ SDL_SCANCODE_F18,
/* 0x6A "F19" */ SDL_SCANCODE_F19,
/* 0x6B "F20" */ SDL_SCANCODE_F20,
/* 0x6C "F21" */ SDL_SCANCODE_F21,
/* 0x6D "F22" */ SDL_SCANCODE_F22,
/* 0x6E "F23" */ SDL_SCANCODE_F23,
/* 0x6F */ SDL_SCANCODE_UNKNOWN,
/* 0x70 "KanaMode" */ SDL_SCANCODE_INTERNATIONAL2,
/* 0x71 "Lang2" */ SDL_SCANCODE_LANG2,
/* 0x72 "Lang1" */ SDL_SCANCODE_LANG1,
/* 0x73 "IntlRo" */ SDL_SCANCODE_INTERNATIONAL1,
/* 0x74 */ SDL_SCANCODE_UNKNOWN,
/* 0x75 */ SDL_SCANCODE_UNKNOWN,
/* 0x76 "F24" */ SDL_SCANCODE_F24,
/* 0x77 */ SDL_SCANCODE_UNKNOWN,
/* 0x78 */ SDL_SCANCODE_UNKNOWN,
/* 0x79 "Convert" */ SDL_SCANCODE_INTERNATIONAL4,
/* 0x7A */ SDL_SCANCODE_UNKNOWN,
/* 0x7B "NonConvert" */ SDL_SCANCODE_INTERNATIONAL5,
/* 0x7C */ SDL_SCANCODE_UNKNOWN,
/* 0x7D "IntlYen" */ SDL_SCANCODE_INTERNATIONAL3,
/* 0x7E "NumpadComma" */ SDL_SCANCODE_KP_COMMA
};
static SDL_Scancode Emscripten_MapScanCode(const char *code)
{
const DOM_PK_CODE_TYPE pk_code = emscripten_compute_dom_pk_code(code);
if (pk_code < SDL_arraysize(emscripten_scancode_table)) {
return emscripten_scancode_table[pk_code];
}
switch (pk_code) {
case DOM_PK_PASTE:
return SDL_SCANCODE_PASTE;
case DOM_PK_MEDIA_TRACK_PREVIOUS:
return SDL_SCANCODE_MEDIA_PREVIOUS_TRACK;
case DOM_PK_CUT:
return SDL_SCANCODE_CUT;
case DOM_PK_COPY:
return SDL_SCANCODE_COPY;
case DOM_PK_MEDIA_TRACK_NEXT:
return SDL_SCANCODE_MEDIA_NEXT_TRACK;
case DOM_PK_NUMPAD_ENTER:
return SDL_SCANCODE_KP_ENTER;
case DOM_PK_CONTROL_RIGHT:
return SDL_SCANCODE_RCTRL;
case DOM_PK_AUDIO_VOLUME_MUTE:
return SDL_SCANCODE_MUTE;
case DOM_PK_MEDIA_PLAY_PAUSE:
return SDL_SCANCODE_MEDIA_PLAY_PAUSE;
case DOM_PK_MEDIA_STOP:
return SDL_SCANCODE_MEDIA_STOP;
case DOM_PK_EJECT:
return SDL_SCANCODE_MEDIA_EJECT;
case DOM_PK_AUDIO_VOLUME_DOWN:
return SDL_SCANCODE_VOLUMEDOWN;
case DOM_PK_AUDIO_VOLUME_UP:
return SDL_SCANCODE_VOLUMEUP;
case DOM_PK_BROWSER_HOME:
return SDL_SCANCODE_AC_HOME;
case DOM_PK_NUMPAD_DIVIDE:
return SDL_SCANCODE_KP_DIVIDE;
case DOM_PK_ALT_RIGHT:
return SDL_SCANCODE_RALT;
case DOM_PK_HELP:
return SDL_SCANCODE_HELP;
case DOM_PK_NUM_LOCK:
return SDL_SCANCODE_NUMLOCKCLEAR;
case DOM_PK_HOME:
return SDL_SCANCODE_HOME;
case DOM_PK_ARROW_UP:
return SDL_SCANCODE_UP;
case DOM_PK_PAGE_UP:
return SDL_SCANCODE_PAGEUP;
case DOM_PK_ARROW_LEFT:
return SDL_SCANCODE_LEFT;
case DOM_PK_ARROW_RIGHT:
return SDL_SCANCODE_RIGHT;
case DOM_PK_END:
return SDL_SCANCODE_END;
case DOM_PK_ARROW_DOWN:
return SDL_SCANCODE_DOWN;
case DOM_PK_PAGE_DOWN:
return SDL_SCANCODE_PAGEDOWN;
case DOM_PK_INSERT:
return SDL_SCANCODE_INSERT;
case DOM_PK_DELETE:
return SDL_SCANCODE_DELETE;
case DOM_PK_META_LEFT:
return SDL_SCANCODE_LGUI;
case DOM_PK_META_RIGHT:
return SDL_SCANCODE_RGUI;
case DOM_PK_CONTEXT_MENU:
return SDL_SCANCODE_APPLICATION;
case DOM_PK_POWER:
return SDL_SCANCODE_POWER;
case DOM_PK_BROWSER_SEARCH:
return SDL_SCANCODE_AC_SEARCH;
case DOM_PK_BROWSER_FAVORITES:
return SDL_SCANCODE_AC_BOOKMARKS;
case DOM_PK_BROWSER_REFRESH:
return SDL_SCANCODE_AC_REFRESH;
case DOM_PK_BROWSER_STOP:
return SDL_SCANCODE_AC_STOP;
case DOM_PK_BROWSER_FORWARD:
return SDL_SCANCODE_AC_FORWARD;
case DOM_PK_BROWSER_BACK:
return SDL_SCANCODE_AC_BACK;
case DOM_PK_MEDIA_SELECT:
return SDL_SCANCODE_MEDIA_SELECT;
}
return SDL_SCANCODE_UNKNOWN;
}
static EM_BOOL Emscripten_HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent *changeEvent, void *userData)
{
SDL_WindowData *window_data = (SDL_WindowData *)userData;
// keep track of lock losses, so we can regrab if/when appropriate.
window_data->has_pointer_lock = changeEvent->isActive;
return 0;
}
static EM_BOOL Emscripten_HandleMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
{
SDL_WindowData *window_data = userData;
const bool isPointerLocked = window_data->has_pointer_lock;
float mx, my;
// rescale (in case canvas is being scaled)
double client_w, client_h, xscale, yscale;
emscripten_get_element_css_size(window_data->canvas_id, &client_w, &client_h);
xscale = window_data->window->w / client_w;
yscale = window_data->window->h / client_h;
if (isPointerLocked) {
mx = (float)(mouseEvent->movementX * xscale);
my = (float)(mouseEvent->movementY * yscale);
} else {
mx = (float)(mouseEvent->targetX * xscale);
my = (float)(mouseEvent->targetY * yscale);
}
SDL_SendMouseMotion(0, window_data->window, SDL_DEFAULT_MOUSE_ID, isPointerLocked, mx, my);
return 0;
}
static EM_BOOL Emscripten_HandleMouseButton(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
{
SDL_WindowData *window_data = userData;
Uint8 sdl_button;
bool sdl_button_state;
double css_w, css_h;
bool prevent_default = false; // needed for iframe implementation in Chrome-based browsers.
switch (mouseEvent->button) {
case 0:
sdl_button = SDL_BUTTON_LEFT;
break;
case 1:
sdl_button = SDL_BUTTON_MIDDLE;
break;
case 2:
sdl_button = SDL_BUTTON_RIGHT;
break;
default:
return 0;
}
const SDL_Mouse *mouse = SDL_GetMouse();
SDL_assert(mouse != NULL);
if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) {
if (mouse->relative_mode && !window_data->has_pointer_lock) {
emscripten_request_pointerlock(window_data->canvas_id, 0); // try to regrab lost pointer lock.
}
sdl_button_state = true;
} else {
sdl_button_state = false;
prevent_default = SDL_EventEnabled(SDL_EVENT_MOUSE_BUTTON_UP);
}
SDL_SendMouseButton(0, window_data->window, SDL_DEFAULT_MOUSE_ID, sdl_button, sdl_button_state);
// We have an imaginary mouse capture, because we need SDL to not drop our imaginary mouse focus when we leave the canvas.
if (mouse->auto_capture) {
if (SDL_GetMouseState(NULL, NULL) != 0) {
window_data->window->flags |= SDL_WINDOW_MOUSE_CAPTURE;
} else {
window_data->window->flags &= ~SDL_WINDOW_MOUSE_CAPTURE;
}
}
if ((eventType == EMSCRIPTEN_EVENT_MOUSEUP) && window_data->mouse_focus_loss_pending) {
window_data->mouse_focus_loss_pending = (window_data->window->flags & SDL_WINDOW_MOUSE_CAPTURE) != 0;
if (!window_data->mouse_focus_loss_pending) {
SDL_SetMouseFocus(NULL);
}
} else {
// Do not consume the event if the mouse is outside of the canvas.
emscripten_get_element_css_size(window_data->canvas_id, &css_w, &css_h);
if (mouseEvent->targetX < 0 || mouseEvent->targetX >= css_w ||
mouseEvent->targetY < 0 || mouseEvent->targetY >= css_h) {
return 0;
}
}
return prevent_default;
}
static EM_BOOL Emscripten_HandleMouseFocus(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
{
SDL_WindowData *window_data = userData;
const bool isPointerLocked = window_data->has_pointer_lock;
if (!isPointerLocked) {
// rescale (in case canvas is being scaled)
float mx, my;
double client_w, client_h;
emscripten_get_element_css_size(window_data->canvas_id, &client_w, &client_h);
mx = (float)(mouseEvent->targetX * (window_data->window->w / client_w));
my = (float)(mouseEvent->targetY * (window_data->window->h / client_h));
SDL_SendMouseMotion(0, window_data->window, SDL_GLOBAL_MOUSE_ID, isPointerLocked, mx, my);
}
const bool isenter = (eventType == EMSCRIPTEN_EVENT_MOUSEENTER);
if (isenter && window_data->mouse_focus_loss_pending) {
window_data->mouse_focus_loss_pending = false; // just drop the state, but don't send the enter event.
} else if (!isenter && (window_data->window->flags & SDL_WINDOW_MOUSE_CAPTURE)) {
window_data->mouse_focus_loss_pending = true; // waiting on a mouse button to let go before we send the mouse focus update.
} else {
SDL_SetMouseFocus(isenter ? window_data->window : NULL);
}
return SDL_EventEnabled(SDL_EVENT_MOUSE_MOTION); // !!! FIXME: should this be MOUSE_MOTION or something else?
}
static EM_BOOL Emscripten_HandleWheel(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData)
{
SDL_WindowData *window_data = userData;
float deltaY = wheelEvent->deltaY;
float deltaX = wheelEvent->deltaX;
switch (wheelEvent->deltaMode) {
case DOM_DELTA_PIXEL:
deltaX /= 100; // 100 pixels make up a step
deltaY /= 100; // 100 pixels make up a step
break;
case DOM_DELTA_LINE:
deltaX /= 3; // 3 lines make up a step
deltaY /= 3; // 3 lines make up a step
break;
case DOM_DELTA_PAGE:
deltaX *= 80; // A page makes up 80 steps
deltaY *= 80; // A page makes up 80 steps
break;
}
SDL_SendMouseWheel(0, window_data->window, SDL_DEFAULT_MOUSE_ID, deltaX, -deltaY, SDL_MOUSEWHEEL_NORMAL);
return SDL_EventEnabled(SDL_EVENT_MOUSE_WHEEL);
}
static EM_BOOL Emscripten_HandleFocus(int eventType, const EmscriptenFocusEvent *wheelEvent, void *userData)
{
SDL_WindowData *window_data = userData;
SDL_EventType sdl_event_type;
/* If the user switches away while keys are pressed (such as
* via Alt+Tab), key release events won't be received. */
if (eventType == EMSCRIPTEN_EVENT_BLUR) {
SDL_ResetKeyboard();
}
sdl_event_type = (eventType == EMSCRIPTEN_EVENT_FOCUS) ? SDL_EVENT_WINDOW_FOCUS_GAINED : SDL_EVENT_WINDOW_FOCUS_LOST;
SDL_SetKeyboardFocus(sdl_event_type == SDL_EVENT_WINDOW_FOCUS_GAINED ? window_data->window : NULL);
return SDL_EventEnabled(sdl_event_type);
}
static EM_BOOL Emscripten_HandleTouch(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData)
{
SDL_WindowData *window_data = (SDL_WindowData *)userData;
int i;
double client_w, client_h;
int preventDefault = 0;
const SDL_TouchID deviceId = 1;
if (SDL_AddTouch(deviceId, SDL_TOUCH_DEVICE_DIRECT, "") < 0) {
return 0;
}
emscripten_get_element_css_size(window_data->canvas_id, &client_w, &client_h);
for (i = 0; i < touchEvent->numTouches; i++) {
SDL_FingerID id;
float x, y;
if (!touchEvent->touches[i].isChanged) {
continue;
}
id = touchEvent->touches[i].identifier + 1;
if (client_w <= 1) {
x = 0.5f;
} else {
x = touchEvent->touches[i].targetX / (client_w - 1);
}
if (client_h <= 1) {
y = 0.5f;
} else {
y = touchEvent->touches[i].targetY / (client_h - 1);
}
if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) {
SDL_SendTouch(0, deviceId, id, window_data->window, SDL_EVENT_FINGER_DOWN, x, y, 1.0f);
// disable browser scrolling/pinch-to-zoom if app handles touch events
if (!preventDefault && SDL_EventEnabled(SDL_EVENT_FINGER_DOWN)) {
preventDefault = 1;
}
} else if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) {
SDL_SendTouchMotion(0, deviceId, id, window_data->window, x, y, 1.0f);
} else if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) {
SDL_SendTouch(0, deviceId, id, window_data->window, SDL_EVENT_FINGER_UP, x, y, 1.0f);
// block browser's simulated mousedown/mouseup on touchscreen devices
preventDefault = 1;
} else if (eventType == EMSCRIPTEN_EVENT_TOUCHCANCEL) {
SDL_SendTouch(0, deviceId, id, window_data->window, SDL_EVENT_FINGER_CANCELED, x, y, 1.0f);
}
}
return preventDefault;
}
static bool IsFunctionKey(SDL_Scancode scancode)
{
if (scancode >= SDL_SCANCODE_F1 && scancode <= SDL_SCANCODE_F12) {
return true;
}
if (scancode >= SDL_SCANCODE_F13 && scancode <= SDL_SCANCODE_F24) {
return true;
}
return false;
}
/* This is a great tool to see web keyboard events live:
* https://w3c.github.io/uievents/tools/key-event-viewer.html
*/
static EM_BOOL Emscripten_HandleKey(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData)
{
SDL_WindowData *window_data = (SDL_WindowData *)userData;
SDL_Scancode scancode = Emscripten_MapScanCode(keyEvent->code);
SDL_Keycode keycode = SDLK_UNKNOWN;
bool prevent_default = false;
bool is_nav_key = false;
if (scancode == SDL_SCANCODE_UNKNOWN) {
if (SDL_strcmp(keyEvent->key, "Sleep") == 0) {
scancode = SDL_SCANCODE_SLEEP;
} else if (SDL_strcmp(keyEvent->key, "ChannelUp") == 0) {
scancode = SDL_SCANCODE_CHANNEL_INCREMENT;
} else if (SDL_strcmp(keyEvent->key, "ChannelDown") == 0) {
scancode = SDL_SCANCODE_CHANNEL_DECREMENT;
} else if (SDL_strcmp(keyEvent->key, "MediaPlay") == 0) {
scancode = SDL_SCANCODE_MEDIA_PLAY;
} else if (SDL_strcmp(keyEvent->key, "MediaPause") == 0) {
scancode = SDL_SCANCODE_MEDIA_PAUSE;
} else if (SDL_strcmp(keyEvent->key, "MediaRecord") == 0) {
scancode = SDL_SCANCODE_MEDIA_RECORD;
} else if (SDL_strcmp(keyEvent->key, "MediaFastForward") == 0) {
scancode = SDL_SCANCODE_MEDIA_FAST_FORWARD;
} else if (SDL_strcmp(keyEvent->key, "MediaRewind") == 0) {
scancode = SDL_SCANCODE_MEDIA_REWIND;
} else if (SDL_strcmp(keyEvent->key, "Close") == 0) {
scancode = SDL_SCANCODE_AC_CLOSE;
} else if (SDL_strcmp(keyEvent->key, "New") == 0) {
scancode = SDL_SCANCODE_AC_NEW;
} else if (SDL_strcmp(keyEvent->key, "Open") == 0) {
scancode = SDL_SCANCODE_AC_OPEN;
} else if (SDL_strcmp(keyEvent->key, "Print") == 0) {
scancode = SDL_SCANCODE_AC_PRINT;
} else if (SDL_strcmp(keyEvent->key, "Save") == 0) {
scancode = SDL_SCANCODE_AC_SAVE;
} else if (SDL_strcmp(keyEvent->key, "Props") == 0) {
scancode = SDL_SCANCODE_AC_PROPERTIES;
}
}
if (scancode == SDL_SCANCODE_UNKNOWN) {
// KaiOS Left Soft Key and Right Soft Key, they act as OK/Next/Menu and Cancel/Back/Clear
if (SDL_strcmp(keyEvent->key, "SoftLeft") == 0) {
scancode = SDL_SCANCODE_AC_FORWARD;
} else if (SDL_strcmp(keyEvent->key, "SoftRight") == 0) {
scancode = SDL_SCANCODE_AC_BACK;
}
}
if (keyEvent->location == 0 && SDL_utf8strlen(keyEvent->key) == 1) {
const char *key = keyEvent->key;
keycode = SDL_StepUTF8(&key, NULL);
if (keycode == SDL_INVALID_UNICODE_CODEPOINT) {
keycode = SDLK_UNKNOWN;
}
}
if (keycode != SDLK_UNKNOWN) {
prevent_default = SDL_SendKeyboardKeyAndKeycode(0, SDL_DEFAULT_KEYBOARD_ID, 0, scancode, keycode, (eventType == EMSCRIPTEN_EVENT_KEYDOWN));
} else {
prevent_default = SDL_SendKeyboardKey(0, SDL_DEFAULT_KEYBOARD_ID, 0, scancode, (eventType == EMSCRIPTEN_EVENT_KEYDOWN));
}
/* if TEXTINPUT events are enabled we can't prevent keydown or we won't get keypress
* we need to ALWAYS prevent backspace and tab otherwise chrome takes action and does bad navigation UX
*/
if ((scancode == SDL_SCANCODE_BACKSPACE) ||
(scancode == SDL_SCANCODE_TAB) ||
(scancode == SDL_SCANCODE_LEFT) ||
(scancode == SDL_SCANCODE_UP) ||
(scancode == SDL_SCANCODE_RIGHT) ||
(scancode == SDL_SCANCODE_DOWN) ||
IsFunctionKey(scancode) ||
keyEvent->ctrlKey) {
is_nav_key = true;
}
if ((eventType == EMSCRIPTEN_EVENT_KEYDOWN) && SDL_TextInputActive(window_data->window) && !is_nav_key) {
prevent_default = false;
}
return prevent_default;
}
static EM_BOOL Emscripten_HandleKeyPress(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData)
{
SDL_WindowData *window_data = (SDL_WindowData *)userData;
if (SDL_TextInputActive(window_data->window)) {
char text[5];
char *end = SDL_UCS4ToUTF8(keyEvent->charCode, text);
*end = '\0';
SDL_SendKeyboardText(text);
return EM_TRUE;
}
return EM_FALSE;
}
static EM_BOOL Emscripten_HandleFullscreenChange(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData)
{
SDL_WindowData *window_data = userData;
if (fullscreenChangeEvent->isFullscreen) {
SDL_SendWindowEvent(window_data->window, SDL_EVENT_WINDOW_ENTER_FULLSCREEN, 0, 0);
window_data->fullscreen_mode_flags = 0;
} else {
SDL_SendWindowEvent(window_data->window, SDL_EVENT_WINDOW_LEAVE_FULLSCREEN, 0, 0);
}
SDL_UpdateFullscreenMode(window_data->window, fullscreenChangeEvent->isFullscreen, false);
return 0;
}
static EM_BOOL Emscripten_HandleResize(int eventType, const EmscriptenUiEvent *uiEvent, void *userData)
{
SDL_WindowData *window_data = userData;
bool force = false;
// update pixel ratio
if (window_data->window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) {
if (window_data->pixel_ratio != emscripten_get_device_pixel_ratio()) {
window_data->pixel_ratio = emscripten_get_device_pixel_ratio();
force = true;
}
}
if (!(window_data->window->flags & SDL_WINDOW_FULLSCREEN)) {
// this will only work if the canvas size is set through css
if (window_data->window->flags & SDL_WINDOW_RESIZABLE) {
double w = window_data->window->w;
double h = window_data->window->h;
if (window_data->external_size) {
emscripten_get_element_css_size(window_data->canvas_id, &w, &h);
}
emscripten_set_canvas_element_size(window_data->canvas_id, SDL_lroundf(w * window_data->pixel_ratio), SDL_lroundf(h * window_data->pixel_ratio));
// set_canvas_size unsets this
if (!window_data->external_size && window_data->pixel_ratio != 1.0f) {
emscripten_set_element_css_size(window_data->canvas_id, w, h);
}
if (force) {
// force the event to trigger, so pixel ratio changes can be handled
window_data->window->w = 0;
window_data->window->h = 0;
}
SDL_SendWindowEvent(window_data->window, SDL_EVENT_WINDOW_RESIZED, SDL_lroundf(w), SDL_lroundf(h));
}
}
return 0;
}
EM_BOOL
Emscripten_HandleCanvasResize(int eventType, const void *reserved, void *userData)
{
// this is used during fullscreen changes
SDL_WindowData *window_data = userData;
if (window_data->fullscreen_resize) {
double css_w, css_h;
emscripten_get_element_css_size(window_data->canvas_id, &css_w, &css_h);
SDL_SendWindowEvent(window_data->window, SDL_EVENT_WINDOW_RESIZED, SDL_lroundf(css_w), SDL_lroundf(css_h));
}
return 0;
}
static EM_BOOL Emscripten_HandleVisibilityChange(int eventType, const EmscriptenVisibilityChangeEvent *visEvent, void *userData)
{
SDL_WindowData *window_data = userData;
SDL_SendWindowEvent(window_data->window, visEvent->hidden ? SDL_EVENT_WINDOW_HIDDEN : SDL_EVENT_WINDOW_SHOWN, 0, 0);
return 0;
}
static const char *Emscripten_HandleBeforeUnload(int eventType, const void *reserved, void *userData)
{
/* This event will need to be handled synchronously, e.g. using
SDL_AddEventWatch, as the page is being closed *now*. */
// No need to send a SDL_EVENT_QUIT, the app won't get control again.
SDL_SendAppEvent(SDL_EVENT_TERMINATING);
return ""; // don't trigger confirmation dialog
}
static EM_BOOL Emscripten_HandleOrientationChange(int eventType, const EmscriptenOrientationChangeEvent *orientationChangeEvent, void *userData)
{
SDL_DisplayOrientation orientation;
switch (orientationChangeEvent->orientationIndex) {
#define CHECK_ORIENTATION(emsdk, sdl) case EMSCRIPTEN_ORIENTATION_##emsdk: orientation = SDL_ORIENTATION_##sdl; break
CHECK_ORIENTATION(LANDSCAPE_PRIMARY, LANDSCAPE);
CHECK_ORIENTATION(LANDSCAPE_SECONDARY, LANDSCAPE_FLIPPED);
CHECK_ORIENTATION(PORTRAIT_PRIMARY, PORTRAIT);
CHECK_ORIENTATION(PORTRAIT_SECONDARY, PORTRAIT_FLIPPED);
#undef CHECK_ORIENTATION
default: orientation = SDL_ORIENTATION_UNKNOWN; break;
}
SDL_WindowData *window_data = (SDL_WindowData *) userData;
SDL_SendDisplayEvent(SDL_GetVideoDisplayForWindow(window_data->window), SDL_EVENT_DISPLAY_ORIENTATION, orientation, 0);
return 0;
}
// IF YOU CHANGE THIS STRUCTURE, YOU NEED TO UPDATE THE JAVASCRIPT THAT FILLS IT IN: makePointerEventCStruct, below.
typedef struct Emscripten_PointerEvent
{
int pointerid;
int button;
int buttons;
float movementX;
float movementY;
float targetX;
float targetY;
float pressure;
float tangential_pressure;
float tiltx;
float tilty;
float rotation;
} Emscripten_PointerEvent;
static void Emscripten_UpdatePointerFromEvent(SDL_WindowData *window_data, const Emscripten_PointerEvent *event)
{
const SDL_PenID pen = SDL_FindPenByHandle((void *) (size_t) event->pointerid);
if (pen) {
// rescale (in case canvas is being scaled)
double client_w, client_h;
emscripten_get_element_css_size(window_data->canvas_id, &client_w, &client_h);
const double xscale = window_data->window->w / client_w;
const double yscale = window_data->window->h / client_h;
const bool isPointerLocked = window_data->has_pointer_lock;
float mx, my;
if (isPointerLocked) {
mx = (float)(event->movementX * xscale);
my = (float)(event->movementY * yscale);
} else {
mx = (float)(event->targetX * xscale);
my = (float)(event->targetY * yscale);
}
SDL_SendPenMotion(0, pen, window_data->window, mx, my);
if (event->button == 0) { // pen touch
bool down = ((event->buttons & 1) != 0);
SDL_SendPenTouch(0, pen, window_data->window, false, down);
} else if (event->button == 5) { // eraser touch...? Not sure if this is right...
bool down = ((event->buttons & 32) != 0);
SDL_SendPenTouch(0, pen, window_data->window, true, down);
} else if (event->button == 1) {
bool down = ((event->buttons & 4) != 0);
SDL_SendPenButton(0, pen, window_data->window, 2, down);
} else if (event->button == 2) {
bool down = ((event->buttons & 2) != 0);
SDL_SendPenButton(0, pen, window_data->window, 1, down);
}
SDL_SendPenAxis(0, pen, window_data->window, SDL_PEN_AXIS_PRESSURE, event->pressure);
SDL_SendPenAxis(0, pen, window_data->window, SDL_PEN_AXIS_TANGENTIAL_PRESSURE, event->tangential_pressure);
SDL_SendPenAxis(0, pen, window_data->window, SDL_PEN_AXIS_XTILT, event->tiltx);
SDL_SendPenAxis(0, pen, window_data->window, SDL_PEN_AXIS_YTILT, event->tilty);
SDL_SendPenAxis(0, pen, window_data->window, SDL_PEN_AXIS_ROTATION, event->rotation);
}
}
EMSCRIPTEN_KEEPALIVE void Emscripten_HandlePointerEnter(SDL_WindowData *window_data, const Emscripten_PointerEvent *event)
{
// Web browsers offer almost none of this information as specifics, but can without warning offer any of these specific things.
SDL_PenInfo peninfo;
SDL_zero(peninfo);
peninfo.capabilities = SDL_PEN_CAPABILITY_PRESSURE | SDL_PEN_CAPABILITY_ROTATION | SDL_PEN_CAPABILITY_XTILT | SDL_PEN_CAPABILITY_YTILT | SDL_PEN_CAPABILITY_TANGENTIAL_PRESSURE | SDL_PEN_CAPABILITY_ERASER;
peninfo.max_tilt = 90.0f;
peninfo.num_buttons = 2;
peninfo.subtype = SDL_PEN_TYPE_PEN;
SDL_AddPenDevice(0, NULL, &peninfo, (void *) (size_t) event->pointerid);
Emscripten_UpdatePointerFromEvent(window_data, event);
}
EMSCRIPTEN_KEEPALIVE void Emscripten_HandlePointerLeave(SDL_WindowData *window_data, const Emscripten_PointerEvent *event)
{
const SDL_PenID pen = SDL_FindPenByHandle((void *) (size_t) event->pointerid);
if (pen) {
Emscripten_UpdatePointerFromEvent(window_data, event); // last data updates?
SDL_RemovePenDevice(0, pen);
}
}
EMSCRIPTEN_KEEPALIVE void Emscripten_HandlePointerGeneric(SDL_WindowData *window_data, const Emscripten_PointerEvent *event)
{
Emscripten_UpdatePointerFromEvent(window_data, event);
}
static void Emscripten_set_pointer_event_callbacks(SDL_WindowData *data)
{
MAIN_THREAD_EM_ASM({
var target = document.querySelector(UTF8ToString($1));
if (target) {
var data = $0;
if (typeof(Module['SDL3']) === 'undefined') {
Module['SDL3'] = {};
}
var SDL3 = Module['SDL3'];
var makePointerEventCStruct = function(event) {
var ptr = 0;
if (event.pointerType == "pen") {
ptr = _SDL_malloc($2);
if (ptr != 0) {
var rect = target.getBoundingClientRect();
var idx = ptr >> 2;
HEAP32[idx++] = event.pointerId;
HEAP32[idx++] = (typeof(event.button) !== "undefined") ? event.button : -1;
HEAP32[idx++] = event.buttons;
HEAPF32[idx++] = event.movementX;
HEAPF32[idx++] = event.movementY;
HEAPF32[idx++] = event.clientX - rect.left;
HEAPF32[idx++] = event.clientY - rect.top;
HEAPF32[idx++] = event.pressure;
HEAPF32[idx++] = event.tangentialPressure;
HEAPF32[idx++] = event.tiltX;
HEAPF32[idx++] = event.tiltY;
HEAPF32[idx++] = event.twist;
}
}
return ptr;
};
SDL3.eventHandlerPointerEnter = function(event) {
var d = makePointerEventCStruct(event); if (d != 0) { _Emscripten_HandlePointerEnter(data, d); _SDL_free(d); }
};
target.addEventListener("pointerenter", SDL3.eventHandlerPointerEnter);
SDL3.eventHandlerPointerLeave = function(event) {
var d = makePointerEventCStruct(event); if (d != 0) { _Emscripten_HandlePointerLeave(data, d); _SDL_free(d); }
};
target.addEventListener("pointerleave", SDL3.eventHandlerPointerLeave);
target.addEventListener("pointercancel", SDL3.eventHandlerPointerLeave); // catch this, just in case.
SDL3.eventHandlerPointerGeneric = function(event) {
var d = makePointerEventCStruct(event); if (d != 0) { _Emscripten_HandlePointerGeneric(data, d); _SDL_free(d); }
};
target.addEventListener("pointerdown", SDL3.eventHandlerPointerGeneric);
target.addEventListener("pointerup", SDL3.eventHandlerPointerGeneric);
target.addEventListener("pointermove", SDL3.eventHandlerPointerGeneric);
}
}, data, data->canvas_id, sizeof (Emscripten_PointerEvent));
}
static void Emscripten_unset_pointer_event_callbacks(SDL_WindowData *data)
{
MAIN_THREAD_EM_ASM({
var target = document.querySelector(UTF8ToString($0));
if (target) {
var SDL3 = Module['SDL3'];
target.removeEventListener("pointerenter", SDL3.eventHandlerPointerEnter);
target.removeEventListener("pointerleave", SDL3.eventHandlerPointerLeave);
target.removeEventListener("pointercancel", SDL3.eventHandlerPointerLeave);
target.removeEventListener("pointerdown", SDL3.eventHandlerPointerGeneric);
target.removeEventListener("pointerup", SDL3.eventHandlerPointerGeneric);
target.removeEventListener("pointermove", SDL3.eventHandlerPointerGeneric);
SDL3.eventHandlerPointerEnter = undefined;
SDL3.eventHandlerPointerLeave = undefined;
SDL3.eventHandlerPointerGeneric = undefined;
}
}, data->canvas_id);
}
// IF YOU CHANGE THIS STRUCTURE, YOU NEED TO UPDATE THE JAVASCRIPT THAT FILLS IT IN: makeDropEventCStruct, below.
typedef struct Emscripten_DropEvent
{
int x;
int y;
} Emscripten_DropEvent;
EMSCRIPTEN_KEEPALIVE void Emscripten_SendDragEvent(SDL_WindowData *window_data, const Emscripten_DropEvent *event)
{
SDL_SendDropPosition(window_data->window, event->x, event->y);
}
EMSCRIPTEN_KEEPALIVE void Emscripten_SendDragCompleteEvent(SDL_WindowData *window_data)
{
SDL_SendDropComplete(window_data->window);
}
EMSCRIPTEN_KEEPALIVE void Emscripten_SendDragTextEvent(SDL_WindowData *window_data, char *text)
{
SDL_SendDropText(window_data->window, text);
}
EMSCRIPTEN_KEEPALIVE void Emscripten_SendDragFileEvent(SDL_WindowData *window_data, char *filename)
{
SDL_SendDropFile(window_data->window, NULL, filename);
}
EM_JS_DEPS(dragndrop, "$writeArrayToMemory");
static void Emscripten_set_drag_event_callbacks(SDL_WindowData *data)
{
MAIN_THREAD_EM_ASM({
var target = document.querySelector(UTF8ToString($1));
if (target) {
var data = $0;
if (typeof(Module['SDL3']) === 'undefined') {
Module['SDL3'] = {};
}
var SDL3 = Module['SDL3'];
var makeDropEventCStruct = function(event) {
var ptr = 0;
ptr = _SDL_malloc($2);
if (ptr != 0) {
var idx = ptr >> 2;
var rect = target.getBoundingClientRect();
HEAP32[idx++] = event.clientX - rect.left;
HEAP32[idx++] = event.clientY - rect.top;
}
return ptr;
};
SDL3.eventHandlerDropDragover = function(event) {
event.preventDefault();
var d = makeDropEventCStruct(event); if (d != 0) { _Emscripten_SendDragEvent(data, d); _SDL_free(d); }
};
target.addEventListener("dragover", SDL3.eventHandlerDropDragover);
SDL3.drop_count = 0;
FS.mkdir("/tmp/filedrop");
SDL3.eventHandlerDropDrop = function(event) {
event.preventDefault();
if (event.dataTransfer.types.includes("text/plain")) {
let plain_text = stringToNewUTF8(event.dataTransfer.getData("text/plain"));
_Emscripten_SendDragTextEvent(data, plain_text);
_free(plain_text);
} else if (event.dataTransfer.types.includes("Files")) {
for (let i = 0; i < event.dataTransfer.files.length; i++) {
const file = event.dataTransfer.files.item(i);
const file_reader = new FileReader();
file_reader.readAsArrayBuffer(file);
file_reader.onload = function(event) {
const fs_dropdir = `/tmp/filedrop/${SDL3.drop_count}`;
SDL3.drop_count += 1;
const fs_filepath = `${fs_dropdir}/${file.name}`;
const c_fs_filepath = stringToNewUTF8(fs_filepath);
const contents_array8 = new Uint8Array(event.target.result);
FS.mkdir(fs_dropdir);
var stream = FS.open(fs_filepath, "w");
FS.write(stream, contents_array8, 0, contents_array8.length, 0);
FS.close(stream);
_Emscripten_SendDragFileEvent(data, c_fs_filepath);
_free(c_fs_filepath);
_Emscripten_SendDragCompleteEvent(data);
};
}
}
_Emscripten_SendDragCompleteEvent(data);
};
target.addEventListener("drop", SDL3.eventHandlerDropDrop);
SDL3.eventHandlerDropDragend = function(event) {
event.preventDefault();
_Emscripten_SendDragCompleteEvent(data);
};
target.addEventListener("dragend", SDL3.eventHandlerDropDragend);
target.addEventListener("dragleave", SDL3.eventHandlerDropDragend);
}
}, data, data->canvas_id, sizeof (Emscripten_DropEvent));
}
static void Emscripten_unset_drag_event_callbacks(SDL_WindowData *data)
{
MAIN_THREAD_EM_ASM({
var target = document.querySelector(UTF8ToString($0));
if (target) {
var SDL3 = Module['SDL3'];
target.removeEventListener("dragleave", SDL3.eventHandlerDropDragend);
target.removeEventListener("dragend", SDL3.eventHandlerDropDragend);
target.removeEventListener("drop", SDL3.eventHandlerDropDrop);
SDL3.drop_count = undefined;
function recursive_remove(dirpath) {
FS.readdir(dirpath).forEach((filename) => {
const p = `${dirpath}/${filename}`;
const p_s = FS.stat(p);
if (FS.isFile(p_s.mode)) {
FS.unlink(p);
} else if (FS.isDir(p)) {
recursive_remove(p);
}
});
FS.rmdir(dirpath);
}("/tmp/filedrop");
FS.rmdir("/tmp/filedrop");
target.removeEventListener("dragover", SDL3.eventHandlerDropDragover);
SDL3.eventHandlerDropDragover = undefined;
SDL3.eventHandlerDropDrop = undefined;
SDL3.eventHandlerDropDragend = undefined;
}
}, data->canvas_id);
}
static const char *Emscripten_GetKeyboardTargetElement()
{
const char *target = SDL_GetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT);
if (!target || !*target) {
return EMSCRIPTEN_EVENT_TARGET_WINDOW;
}
if (SDL_strcmp(target, "#none") == 0) {
return NULL;
} else if (SDL_strcmp(target, "#window") == 0) {
return EMSCRIPTEN_EVENT_TARGET_WINDOW;
} else if (SDL_strcmp(target, "#document") == 0) {
return EMSCRIPTEN_EVENT_TARGET_DOCUMENT;
} else if (SDL_strcmp(target, "#screen") == 0) {
return EMSCRIPTEN_EVENT_TARGET_SCREEN;
}
return target;
}
void Emscripten_RegisterEventHandlers(SDL_WindowData *data)
{
const char *keyElement;
// There is only one window and that window is the canvas
emscripten_set_mousemove_callback(data->canvas_id, data, 0, Emscripten_HandleMouseMove);
emscripten_set_mousedown_callback(data->canvas_id, data, 0, Emscripten_HandleMouseButton);
emscripten_set_mouseup_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, data, 0, Emscripten_HandleMouseButton);
emscripten_set_mouseenter_callback(data->canvas_id, data, 0, Emscripten_HandleMouseFocus);
emscripten_set_mouseleave_callback(data->canvas_id, data, 0, Emscripten_HandleMouseFocus);
emscripten_set_wheel_callback(data->canvas_id, data, 0, Emscripten_HandleWheel);
emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, data, 0, Emscripten_HandleFocus);
emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, data, 0, Emscripten_HandleFocus);
emscripten_set_orientationchange_callback(data, 0, Emscripten_HandleOrientationChange);
emscripten_set_touchstart_callback(data->canvas_id, data, 0, Emscripten_HandleTouch);
emscripten_set_touchend_callback(data->canvas_id, data, 0, Emscripten_HandleTouch);
emscripten_set_touchmove_callback(data->canvas_id, data, 0, Emscripten_HandleTouch);
emscripten_set_touchcancel_callback(data->canvas_id, data, 0, Emscripten_HandleTouch);
emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, data, 0, Emscripten_HandlePointerLockChange);
// Keyboard events are awkward
keyElement = Emscripten_GetKeyboardTargetElement();
if (keyElement) {
emscripten_set_keydown_callback(keyElement, data, 0, Emscripten_HandleKey);
emscripten_set_keyup_callback(keyElement, data, 0, Emscripten_HandleKey);
emscripten_set_keypress_callback(keyElement, data, 0, Emscripten_HandleKeyPress);
}
emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, data, 0, Emscripten_HandleFullscreenChange);
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, data, 0, Emscripten_HandleResize);
emscripten_set_visibilitychange_callback(data, 0, Emscripten_HandleVisibilityChange);
emscripten_set_beforeunload_callback(data, Emscripten_HandleBeforeUnload);
// !!! FIXME: currently Emscripten doesn't have a Pointer Events functions like emscripten_set_*_callback, but we should use those when they do:
// !!! FIXME: https://github.com/emscripten-core/emscripten/issues/7278#issuecomment-2280024621
Emscripten_set_pointer_event_callbacks(data);
// !!! FIXME: currently Emscripten doesn't have a Drop Events functions like emscripten_set_*_callback, but we should use those when they do:
Emscripten_set_drag_event_callbacks(data);
}
void Emscripten_UnregisterEventHandlers(SDL_WindowData *data)
{
const char *target;
// !!! FIXME: currently Emscripten doesn't have a Drop Events functions like emscripten_set_*_callback, but we should use those when they do:
Emscripten_unset_drag_event_callbacks(data);
// !!! FIXME: currently Emscripten doesn't have a Pointer Events functions like emscripten_set_*_callback, but we should use those when they do:
// !!! FIXME: https://github.com/emscripten-core/emscripten/issues/7278#issuecomment-2280024621
Emscripten_unset_pointer_event_callbacks(data);
// only works due to having one window
emscripten_set_mousemove_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_mousedown_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_mouseup_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, 0, NULL);
emscripten_set_mouseenter_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_mouseleave_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_wheel_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL);
emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL);
emscripten_set_orientationchange_callback(NULL, 0, NULL);
emscripten_set_touchstart_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_touchend_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_touchmove_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_touchcancel_callback(data->canvas_id, NULL, 0, NULL);
emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, 0, NULL);
target = Emscripten_GetKeyboardTargetElement();
if (target) {
emscripten_set_keydown_callback(target, NULL, 0, NULL);
emscripten_set_keyup_callback(target, NULL, 0, NULL);
emscripten_set_keypress_callback(target, NULL, 0, NULL);
}
emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, NULL, 0, NULL);
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL);
emscripten_set_visibilitychange_callback(NULL, 0, NULL);
emscripten_set_beforeunload_callback(NULL, NULL);
}
#endif // SDL_VIDEO_DRIVER_EMSCRIPTEN
| 0 | 0.914657 | 1 | 0.914657 | game-dev | MEDIA | 0.545356 | game-dev | 0.718703 | 1 | 0.718703 |
redeclipse/base | 6,932 | config/ui/tool/toolphysics.cfg | # ui_tool_phys_deathplane = [
result [
uivlist 0 [
ui_tool_numinput deathplane#1 arg1 0 0 0.1 [
p_label = [#1(? $arg1 "" "Height")]
p_label_size = $ui_tool_text_size_xs
p_interval = $ui_tool_env_param_interval
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Death plane height" "position")
uistyle clampx
uipropchild [uialign 1]
uistyle righttop
]
]
]
ui_tool_phys_param_outside_table_group = [
uihlist 0 [
uistyle clampx
uipad $ui_tool_elem_space_m $ui_tool_elem_space_xl $ui_tool_elem_space_m 0 [
uitext $arg1 $ui_tool_text_size_s [
uitextrotate 3
]
uialign -1
]
@arg2
]
@ui_tool_divider
]
// 1:<text> 2:<contents>
ui_tool_phys_param_group = [
uitablerow [
uistyle clampxy
uipad $ui_tool_elem_space_m $ui_tool_elem_space_xl $ui_tool_elem_space_m 0 [
uitext $arg1 $ui_tool_text_size_s [
uitextrotate 3
]
uialign -1
]
@arg2
]
uitablerow [] [
@@ui_tool_divider
]
]
// 1:<ui> 2:<label>
ui_tool_phys_variant_params = [
result [
ui_tool_phys_param_group [@@arg2] [
@@($arg1)
@@($arg1 alt)
]
]
]
# ui_tool_phys_table = [
result [
ui_tool_vscrollarea [
uitable $ui_tool_elem_space_l $ui_tool_elem_space_l [
uistyle clampx
uitableheader [
uifill
uicolourtext (at $MPV_NAMES 1) (? (<= $forcemapvariant 1) $ui_tool_accent_colour $ui_tool_dark_accent_colour) $ui_tool_text_size_s
uicolourtext (at $MPV_NAMES 2) (? (= $forcemapvariant 2) $ui_tool_accent_colour $ui_tool_dark_accent_colour) $ui_tool_text_size_s
]
uiline $ui_tool_dark_accent_colour 0 0 [ uistyle clampx ]
#1 arg1
]
] [
p_height = 0.6
p_id = #(tool_get_id)
]
]
]
# ui_tool_phys = [
uivlist $ui_toolpanel_elem_space [
uistyle clampxy
ui_tool_phys_param_outside_table_group "Movement" [
uivlist 0 [
uistyle clampx
ui_tool_numinput gravity 0 0 10 [
p_label = "Gravity"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Gravity" "")
uifill 0 $ui_tool_elem_space_s
ui_tool_numinput floorcoast 0 0 1 [
p_label = "Floor coast"
p_tip_simple = "Inverse of friction"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Floor coast" "friction drag")
ui_tool_numinput slidecoast 0 0 1 [
p_label = "Slide coast"
p_tip_simple = "Inverse of friction during slides"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Slide coast" "friction drag")
ui_tool_numinput aircoast 0 0 1 [
p_label = "Air coast"
p_tip_simple = "Inverse of drag"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Air coast" "friction drag")
#ui_tool_divider
ui_tool_collapsegroup tool_phys_adv [
ui_tool_numinput stairheight 0 0 0.1 [
p_label = "Stair smoothing height"
p_tip_simple = "Maximum height of stair steps, used for smooth descending/ascending."
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Stair smoothing height" "" 1)
ui_tool_numinput stepspeed 0 0 0.1 [
p_label = "Stair smoothing speed"
p_tip_simple = "Speed of stair descent/ascent smoothing"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Stair smoothing speed" "" 1)
uifill 0 $ui_tool_elem_space_s
ui_tool_numinput floorz 0 0 0.001 [
p_label = "Floor threshold"
p_tip_simple = "Floor collision height threshold"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Floor threshold" "" 1)
ui_tool_numinput slopez 0 0 0.001 [
p_label = "Slope threshold"
p_tip_simple = "Slope collision height threshold"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Slope threshold" "" 1)
ui_tool_numinput wallz 0 0 0.001 [
p_label = "Wall threshold"
p_tip_simple = "Wall collision height threshold"
p_val_format = f
p_immediate = 0
p_label_size = $ui_tool_text_size_xs
p_id = #(tool_get_id)
]
#(tool_phys_register_control "Wall threshold" "" 1)
] [
p_label = "Advanced"
]
]
]
@@(ui_tool_phys_table [
@(ui_tool_phys_variant_params ui_tool_phys_deathplane "Deathplane")
])
]
]
| 0 | 0.883464 | 1 | 0.883464 | game-dev | MEDIA | 0.594069 | game-dev,desktop-app | 0.544947 | 1 | 0.544947 |
db0/godot-card-game-framework | 6,164 | tests/integration/test_board_use.gd | extends "res://tests/UTcommon.gd"
class TestCardBoardDrop:
extends "res://tests/Basic_common.gd"
func test_card_table_drop_location_and_rotation_use_rectangle():
cfc.game_settings.hand_use_oval_shape = false
for c in cfc.NMAP.hand.get_all_cards():
c.reorganize_self()
yield(yield_for(0.5), YIELD) # Wait to allow dragging to start
# Reminder that card should not have trigger script definitions, to avoid
# messing with the tests
var card = cards[1]
yield(drag_card(card, Vector2(300,300)), 'completed')
yield(move_mouse(Vector2(500,200)), 'completed')
drop_card(card,board._UT_mouse_position)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_almost_eq(Vector2(500, 200),card.global_position,Vector2(2,2),
"Card dragged in correct global position")
card.card_rotation = 90
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_almost_eq(90.0,card.get_node("Control").rect_rotation,2.0,
"Card rotates 90")
card.card_rotation = 180
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_almost_eq(180.0,card.get_node("Control").rect_rotation,2.0,
"Card rotates 180")
card.set_card_rotation(180,false)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_almost_eq(180.0,card.get_node("Control").rect_rotation,2.0,
"Card rotation doesn't revert without toggle")
card.set_card_rotation(180,true)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_almost_eq(0.0,card.get_node("Control").rect_rotation,2.0,
"Card rotation toggle works to reset to 0")
assert_eq(2,card.set_card_rotation(111),
"Setting rotation to an invalid value fails")
assert_eq(2,cards[0].set_card_rotation(180),
"Changing rotation to a card outside table fails")
yield(move_mouse(card.global_position), 'completed')
assert_eq(1,card.set_card_rotation(270),
"Rotation remained when card is focused")
yield(drag_card(card, Vector2(1000,100)), 'completed')
assert_eq(270,card.card_rotation,
"Rotation remains while card is being dragged")
yield(move_mouse(cfc.NMAP.discard.position), 'completed')
drop_card(card,board._UT_mouse_position)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_eq(0.0,card.get_node("Control").rect_rotation,
"Rotation reset to 0 while card is moving to hand")
cfc.game_settings.hand_use_oval_shape = true
func test_card_table_drop_location_use_oval():
cfc.game_settings.hand_use_oval_shape = true
# Reminder that card should not have trigger script definitions, to avoid
# messing with the tests
var card = cards[1]
yield(table_move(card, Vector2(100,200)), "completed")
card.card_rotation = 180
yield(drag_drop(card, Vector2(400,600)), 'completed')
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_almost_eq(12.461,card.get_node("Control").rect_rotation,2.0,
"Rotation reset to a hand angle when card moved back to hand")
cfc.game_settings.hand_use_oval_shape = true
func test_fast_card_table_drop():
# This catches a bug where the card keeps following the mouse after being dropped
var card = cards[0]
yield(drag_drop(card, Vector2(700,300)), 'completed')
yield(move_mouse(Vector2(400,200)), 'completed')
yield(move_mouse(Vector2(1000,500)), 'completed')
assert_almost_eq(Vector2(700, 300),cards[0].global_position,Vector2(2,2),
"Card not dragged with mouse after dropping on table")
class TestDropRecovery:
extends "res://tests/Basic_common.gd"
func test_card_hand_drop_recovery():
var card = cards[1]
yield(drag_card(card, Vector2(100,100)), 'completed')
yield(move_mouse(Vector2(200,620)), 'completed')
drop_card(card,board._UT_mouse_position)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
yield(yield_to(card._tween, "tween_all_completed", 0.5), YIELD)
assert_eq(hand.get_card_count(),5,
"Card dragged back in hand remains in hand")
class TestBoardBorderBlock:
extends "res://tests/Basic_common.gd"
func test_card_drag_block_by_board_borders():
var card = cards[4]
yield(drag_card(card, Vector2(-100,100)), 'completed')
assert_almost_eq(Vector2(-5, 95),card.global_position,Vector2(2,2),
"Dragged outside left viewport borders stays inside viewport")
yield(move_mouse(Vector2(1300,300)), 'completed')
assert_almost_eq(Vector2(1215, 295),card.global_position,Vector2(2,2),
"Dragged outside right viewport borders stays inside viewport")
yield(move_mouse(Vector2(800,-100)), 'completed')
assert_almost_eq(Vector2(795, -5),card.global_position,Vector2(2,2),
"Dragged outside top viewport borders stays inside viewport")
yield(move_mouse(Vector2(500,800)), 'completed')
assert_almost_eq(Vector2(495, 619),card.global_position,Vector2(2,2),
"Dragged outside bottom viewport borders stays inside viewport")
class TestBoardToBoardMove:
extends "res://tests/Basic_common.gd"
func test_board_to_board_move():
var card: Card
card = cards[0]
yield(table_move(card, Vector2(100,200)), "completed")
card.card_rotation = 90
yield(drag_drop(card, Vector2(800,200)), 'completed')
assert_eq(90.0,card.get_node("Control").rect_rotation,
"Card should stay in the same rotation when moved around the board")
class TestBoardPause:
extends "res://tests/Basic_common.gd"
func test_pause():
var card: Card
card = cards[0]
yield(table_move(card, Vector2(100,200)), "completed")
yield(move_mouse(Vector2(0,0)), 'completed')
cfc.game_paused = true
yield(drag_drop(card, Vector2(700,300)), 'completed')
assert_almost_eq(Vector2(100, 200),card.global_position,Vector2(2,2),
"Card not moved while game paused")
yield(move_mouse(deck.position + Vector2(10,10)), 'completed')
for button in deck.get_all_manipulation_buttons():
assert_eq(button.modulate[3],0.0)
cfc.game_paused = false
yield(drag_drop(card, Vector2(700,300)), 'completed')
assert_almost_eq(Vector2(700, 300),card.global_position,Vector2(5,5),
"Game unpaused correctly")
| 0 | 0.647682 | 1 | 0.647682 | game-dev | MEDIA | 0.687341 | game-dev,testing-qa | 0.847284 | 1 | 0.847284 |
Crustaly/audemywebsite | 3,159 | src/pages/GameZone/GameZoneList/BusStopBrainstorm.vue | <template>
<GameLayout
:bgColor="gameConfig.bgColor"
:isTablet="isTablet"
:isMobile="isMobile"
:currentAudios="currentAudios"
:handleSthNotWorkingButtonClick="handleSthNotWorkingButtonClick"
:goBack="goBack"
>
<div class="flex flex-col justify-center items-center mb-8">
<GameHeader
:iconSrc="gameConfig.iconSrc"
:title="gameConfig.title"
:description="gameConfig.description"
:isMobile="isMobile"
:showCaptions="
playButton &&
!isIntroPlaying &&
numOfAudiosPlayed > 0 &&
numOfAudiosPlayed < 5
"
:currentQuestionIndex="currentQuestionIndex"
:currentQuestion="currentQuestion"
:isAnswerPlaying="isAnswerPlaying"
:isCorrect="isCorrect"
:firstMatchingAnswer="firstMatchingAnswer"
/>
<PlayButton v-if="playButton === false" @play-click="playButton = true" />
<div
v-else-if="numOfAudiosPlayed < 5 && playButton === true"
class="flex flex-col p-4 justify-center"
id="content"
>
<StartQuestionsButton
v-show="numOfAudiosPlayed === 0"
:isIntroPlaying="isIntroPlaying"
@start-click="startFirstQuestion"
/>
<GameControls
v-show="!isIntroPlaying && numOfAudiosPlayed > 0"
:isTablet="isTablet"
:isMobile="isMobile"
:isRecording="isRecording"
:isFinalResult="isFinalResult"
:isIntroPlaying="isIntroPlaying"
:isButtonCooldown="isButtonCooldown"
:transcription="transcription"
:numOfAudiosPlayed="numOfAudiosPlayed"
:recordButtonText="recordButtonText"
:recordButtonClasses="recordButtonClasses"
:recordButtonTitle="recordButtonTitle"
:isButtonDisabled="isButtonDisabled"
@record-click="toggleRecording"
@repeat-click="repeatQuestion"
/>
</div>
<GameOver v-else :score="score" />
</div>
</GameLayout>
</template>
<script setup>
import GameLayout from '../../../components/Game/GameLayout.vue';
import GameControls from '../../../components/Game/GameControls.vue';
import GameHeader from '../../../components/Game/GameHeader.vue';
import PlayButton from '../../../components/Game/PlayButton.vue';
import StartQuestionsButton from '../../../components/Game/StartQuestionsButton.vue';
import GameOver from '../../../components/Game/GameOver.vue';
import { useGameCore } from '../../../composables/useGameCore';
import { gameConfigs } from '../../../config/gameConfigs';
const gameConfig = gameConfigs.busStopBrainstorm;
const {
numOfAudiosPlayed,
currentQuestionIndex,
score,
isRecording,
isFinalResult,
transcription,
playButton,
isIntroPlaying,
isButtonCooldown,
isAnswerPlaying,
isCorrect,
firstMatchingAnswer,
isTablet,
isMobile,
currentAudios,
currentQuestion,
isButtonDisabled,
recordButtonClasses,
recordButtonTitle,
recordButtonText,
toggleRecording,
goBack,
repeatQuestion,
startFirstQuestion,
handleSthNotWorkingButtonClick,
} = useGameCore(gameConfig);
</script>
| 0 | 0.774159 | 1 | 0.774159 | game-dev | MEDIA | 0.568639 | game-dev,audio-video-media | 0.759183 | 1 | 0.759183 |
v3921358/MapleRoot | 14,219 | DLLSource-main/ijl15/MapleHook.cpp | #pragma once
#include "Global.h"
#include "SkillEdits/ActiveSkill.h"
#include "shavitstuff/aquila.h"
#include "shavitstuff/IWzResMan.h"
#include "rulaxStuff.h"
#include "SkillEdits/CharacterDataEx.h"
// do active hooks
void Hook_DoActiveSkill(bool bEnable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
(bEnable ? DetourAttach : DetourDetach)(&(PVOID&)pDoActiveSkill, &CUserLocal__DoActiveSkill_t);
DetourTransactionCommit();
}
void Hook_Jump(bool bEnable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
(bEnable ? DetourAttach : DetourDetach)(&(PVOID&)pDoJump, &CUserLocal_Jump);
DetourTransactionCommit();
}
bool HookPcCreateObject_IWzResMan(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_PcCreateObject_IWzResMan), _PcCreateObject_IWzResMan_Hook);
}
bool HookPcCreateObject_IWzNameSpace(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_PcCreateObject_IWzNameSpace), _PcCreateObject_IWzNameSpace_Hook);
}
bool HookPcCreateObject_IWzFileSystem(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_PcCreateObject_IWzFileSystem), _PcCreateObject_IWzFileSystem_Hook);
}
bool HookCWvsApp__Dir_BackSlashToSlash(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_CWvsApp__Dir_BackSlashToSlash), _CWvsApp__Dir_BackSlashToSlash_Hook);
}
bool HookCWvsApp__Dir_upDir(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_CWvsApp__Dir_upDir), _CWvsApp__Dir_upDir_Hook);
}
bool Hookbstr_ctor(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_bstr_ctor), _bstr_ctor_Hook);
}
bool HookIWzFileSystem__Init(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_IWzFileSystem__Init), _IWzFileSystem__Init_Hook);
}
bool HookIWzNameSpace__Mount(bool bEnable)
{
return SetHook(bEnable, reinterpret_cast<void**>(&_IWzNameSpace__Mount), _IWzNameSpace__Mount_Hook);
}
//void Hook_Strings(bool bEnable)
//{
// DetourTransactionBegin();
// DetourUpdateThread(GetCurrentThread());
// (bEnable ? DetourAttach : DetourDetach)(&(PVOID&)GetString, &tGetString);
// DetourTransactionCommit();
//}
//void Hook_SMP(bool bEnable)
//{
// DetourTransactionBegin();
// DetourUpdateThread(GetCurrentThread());
// (bEnable ? DetourAttach : DetourDetach)(&(PVOID&)SetMovePathAttribute, &tSetMovePathAttribute);
// DetourTransactionCommit();
//}
void Hook_GetSkillLevel(bool bEnable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
(bEnable ? DetourAttach : DetourDetach)(&(PVOID&)pGetSkillLevel, &GetSkillLevel);
DetourTransactionCommit();
}
void Hook_Combo(bool bEnable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
(bEnable ? DetourAttach : DetourDetach)(&(PVOID&)comboCalc_hook, &comboCalc);
DetourTransactionCommit();
}
void Hook_Layers(bool bEnable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
(bEnable ? DetourAttach : DetourDetach)(&(PVOID&)animation_hook, &LoadLayer);
DetourTransactionCommit();
}
void Hook_Layers2(bool bEnable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
(bEnable ? DetourAttach : DetourDetach)(&(PVOID&)animation_hook2, &LoadLayer2);
DetourTransactionCommit();
}
//old stuff
//void asmStuff()
//{
// ui_hacks();
// misc_hacks();
// skillhacks();
// clientHacks();
//}
//void Hook_Crit(bool bEnable)
//{
// DetourTransactionBegin();
// DetourUpdateThread(GetCurrentThread());
// (bEnable ? DetourAttach : DetourDetach)(&(PVOID&)getcrit, &get_critical_skill_level);
// DetourTransactionCommit();
//}
bool Hook_CUserLocal__CanUseBareHand(bool enable) {
typedef bool(__fastcall* CUserLocal__CanUseBareHand_t)(LPVOID lpvClassPtr, LPVOID lpvEdx);
static auto CUserLocal__CanUseBareHand = reinterpret_cast<CUserLocal__CanUseBareHand_t>(0x0095F8CF);
CUserLocal__CanUseBareHand_t Hook = [](void* ecx, void* edx) -> bool
{
/*Log("barehandaddy %p", _ReturnAddress());*/
return true;
};
return SetHook(enable, reinterpret_cast<void**>(&CUserLocal__CanUseBareHand), Hook);
}
bool Hook_get_novice_skill_point(bool enable) {
typedef int(__fastcall* get_novice_skill_point_t)(LPVOID lpvClassPtr, LPVOID lpvEdx);
static auto get_novice_skill_point = reinterpret_cast<get_novice_skill_point_t>(0x765E9E);
get_novice_skill_point_t Hook = [](void* ecx, void* edx) -> int
{
return 0;
};
return SetHook(enable, reinterpret_cast<void**>(&get_novice_skill_point), Hook);
}
bool Hook_monster_book_open(bool enable) {
typedef int(__fastcall* monster_book_open_t)(LPVOID lpvClassPtr, LPVOID lpvEdx, unsigned int a1);
static auto monster_book_open = reinterpret_cast<monster_book_open_t>(0x861B12);
monster_book_open_t Hook = [](void* ecx, void* edx, unsigned int a1) -> int
{
return 0;
};
return SetHook(enable, reinterpret_cast<void**>(&monster_book_open), Hook);
}
bool Hook_monster_book_open_mob(bool enable) {
typedef int(__fastcall* Hook_monster_book_open_mob_t)(LPVOID lpvClassPtr, LPVOID lpvEdx, char a2, signed int* a3);
static auto Hook_monster_book_open_mob = reinterpret_cast<Hook_monster_book_open_mob_t>(0x86793F);
Hook_monster_book_open_mob_t Hook = [](void* ecx, void* edx, char a2, signed int* a3) -> int
{
return 0;
};
return SetHook(enable, reinterpret_cast<void**>(&Hook_monster_book_open_mob), Hook);
}
bool HookCWvsApp__InitializeResMan(bool bEnable) //resman hook that does nothing, kept for analysis and referrence //not skilled enough to rewrite to load custom wz files
{
static _CWvsApp__InitializeResMan_t _CWvsApp__InitializeResMan_Hook = [](void* pThis, void* edx) {
////-> void {_CWvsApp__InitializeResMan(pThis, edx);
//_CWvsApp__InitializeResMan(pThis, edx); //comment this out and uncomment below if testing, supposed to load from .img files in folders but i never got to test it
void* pData = nullptr;
void* pFileSystem = nullptr;
void* pUnkOuter = 0;
void* nPriority = 0;
void* sPath;
// Resman
_PcCreateObject_IWzResMan(L"ResMan", g_rm, pUnkOuter); //?(void*) //?&g
void* pIWzResMan_Instance = *g_rm; //?&g
auto IWzResMan__SetResManParam = *(void(__fastcall**)(void*, void*, void*, int, int, int))((*(int*)pIWzResMan_Instance) + 20); // Hard Coded
IWzResMan__SetResManParam(nullptr, nullptr, pIWzResMan_Instance, RC_AUTO_REPARSE | RC_AUTO_SERIALIZE, 60000, -1);
// NameSpace
_PcCreateObject_IWzNameSpace(L"NameSpace", g_root, pUnkOuter);
void* pIWzNameSpace_Instance = g_root;
auto PcSetRootNameSpace = *(void(__cdecl*)(void*, int)) * (int*)pNameSpace; // Hard Coded
PcSetRootNameSpace(pIWzNameSpace_Instance, 1);
// Game FileSystem
_PcCreateObject_IWzFileSystem(L"NameSpace#FileSystem", &pFileSystem, pUnkOuter);
char sStartPath[MAX_PATH];
GetModuleFileNameA(NULL, sStartPath, MAX_PATH);
_CWvsApp__Dir_BackSlashToSlash(sStartPath);
_CWvsApp__Dir_upDir(sStartPath);
_bstr_ctor(&sPath, pData, sStartPath);
auto iGameFS = _IWzFileSystem__Init(pFileSystem, pData, sPath);
_bstr_ctor(&sPath, pData, "/");
auto mGameFS = _IWzNameSpace__Mount(*g_root, pData, sPath, pFileSystem, (int)nPriority);
// Data FileSystem
_PcCreateObject_IWzFileSystem(L"NameSpace#FileSystem", &pFileSystem, pUnkOuter);
_bstr_ctor(&sPath, pData, "./Data");
auto iDataFS = _IWzFileSystem__Init(pFileSystem, pData, sPath);
_bstr_ctor(&sPath, pData, "/");
auto mDataFS = _IWzNameSpace__Mount(*g_root, pData, sPath, pFileSystem, (int)nPriority);
};
return SetHook(bEnable, reinterpret_cast<void**>(&_CWvsApp__InitializeResMan), _CWvsApp__InitializeResMan_Hook);
}
//void flushcache() {
// constexpr const uint32_t SWEEPCACHE_DELAY_1 = 0x00411BE2;
// write_to_mem<int>(SWEEPCACHE_DELAY_1 + 2, 10000);
//
// constexpr const uint32_t SWEEPCACHE_DELAY_2[] = { 0x00411D70, 0x00411E13, 0x00411EC5, 0x00411F68, 0x0041625F, 0x0041201A, 0x004120BD, 0x00412282, 0x00412303, 0x00412388 };
//
// for (auto n : SWEEPCACHE_DELAY_2)
// {
// write_to_mem<int>(n + 2, 10000);
// }
//
// // flush in CField::Init
// constexpr const uint32_t CFIELD_FLUSH = 0x00529320;
// write_to_mem<int>(CFIELD_FLUSH + 1, 0);
//}
BOOL HaxMaple() {
doini();
UpdateResolution();
WriteValue(0x0078F60A + 2, 0xAFE858); // 1h axe/bw = 0xAFE858
WriteValue(0x0078f6B0 + 2, 0xAFE858);
WriteValue(0x0078F1A4 + 2, 0xAFE858); // 2H axe/bw = 4.6
WriteValue(0x0078F24A + 2, 0xAFE858);
WriteValue(0x0078F3FB + 2, 0xAFE858); // Polearm/Spear = 5.0
WriteValue(0x0078F4A8 + 2, 0xAFE858);
WriteValue(0x0078FE3E + 2, 0xAFE858);
WriteValue(0x0078FABD + 2, 0xAFE858);
WriteValue(0x0078F555 + 2, 0xAFE858); //2h sword
WriteValue(0x0078FD81 + 2, 0xAFE858);
WriteValue(0x0078F4A8 + 2, 0xAFE858);
WriteValue(0x0078FCD4 + 2, 0xAFE858);
WriteValue(0x0078FB6B + 2, 0xAFE858);
WriteValue(0x0078F1A4 + 2, 0xAFE858);
WriteValue(0x0078F24A + 2, 0xAFE858);
WriteValue(0x0078FC2E + 2, 0xAFE858);
WriteValue(0x0078F042 + 2, 0xAFE858);
WriteValue(0x0078F0EF + 2, 0xAFE858);
WriteValue(0X0078EB28 + 2, 0xAFE858);
WriteValue(0x0078EBD5 + 2, 0xAFE858);
WriteValue(0x0078F1A4 + 2, 0xAFE858);
//DRAW UI
WriteValue(0x008C2CE3 + 2, 0xAFE858);
WriteValue(0x008C2DFD + 2, 0xAFE858);
WriteValue(0x008C2E46 + 2, 0xAFE858);
WriteValue(0x008C2C56 + 2, 0xAFE858);
WriteValue(0x008C2C9F + 2, 0xAFE858);
WriteValue(0x008C2D2C + 2, 0xAFE858);
WriteValue(0x008C2AEC + 2, 0xAFE858);
WriteValue(0x008C2B35 + 2, 0xAFE858);
WriteValue(0x008C320C + 2, 0xAFE858);
WriteValue(0x008C3255 + 2, 0xAFE858);
WriteValue(0x008C3299 + 2, 0xAFE858);
WriteValue(0x008C2BC9 + 2, 0xAFE858);
WriteValue(0x008C2EE0 + 2, 0xAFE858);
WriteValue(0x008C2C12 + 2, 0xAFE858);
WriteValue(0x008C309D + 2, 0xAFE858);
WriteValue(0x008C32E2 + 2, 0xAFE858);
WriteValue(0x008C2D70 + 2, 0xAFE858);
WriteValue(0x008C2DB9 + 2, 0xAFE858);
WriteValue(0x008C31C8 + 2, 0xAFE858);
WriteValue(0x008C317F + 2, 0xAFE858);
WriteValue(0x00792509 + 2, 0xAFE860); // SUMMON DEX * 5
PatchNop(0x00668DDF, 27); //show mob for snipe/hh/etc
//damage calcs for tempesthh etc
WriteValue(0x0078E4D6 + 1, 3222222); //snipe calc skip
WriteValue(0x0078E5CE + 1, 3222222); // Tempest
WriteValue(0x0078E699 + 2, 202200202); //HH
WriteByte(0x0078E4B0, 0xEB);
WriteByte(0x0078E4DB, 0xEB);
WriteByte(0x0078E55C, 0xEB);
WriteByte(0x0078E5D3, 0xEB);
WriteByte(0x0078E934, 0xEB);
WriteByte(0x007669B7 + 1, 0xA); // COMBO SMASH 10
WriteByte(0x007669B3 + 1, 0x1E);
WriteByte(0x004F2D9B + 2, 0x07);//Super Beginner Wears anything
WriteValue(0x0075BF65 + 3, 0x00B3D108); //chain lightning to 1.25 bonus per mob
HookPcCreateObject_IWzResMan(true);
HookPcCreateObject_IWzNameSpace(true);
HookPcCreateObject_IWzFileSystem(true);
HookCWvsApp__Dir_BackSlashToSlash(true);
Hook_Combo(true);
Hook_Layers(true);
Hook_Layers2(true);
HookCWvsApp__Dir_upDir(true);
Hookbstr_ctor(true);
HookIWzFileSystem__Init(true);
HookIWzNameSpace__Mount(true);
Hook_GetSkillLevel(true);
HookCWvsApp__InitializeResMan(true); //experimental //ty to all the contributors of the ragezone release: Client load .img instead of .wz v62~v92
SetHook(TRUE, reinterpret_cast<PVOID*>(&_is_attack_area_set_by_data), is_attack_area_set_by_data);
SetHook(true, reinterpret_cast<void**>(&g_real_CUser__IsDarkSight), Horizons_CUser__IsDarkSight);
SetHook(true, reinterpret_cast<void**>(<rbshoothook), ltrb);
SetHook(true, reinterpret_cast<void**>(&pDoActiveSkill), CUserLocal__DoActiveSkill_t);
SetHook(true, reinterpret_cast<void**>(&skillDelayHook), summondelay);
SetHook(true, reinterpret_cast<void**>(&octHook), octopus);
SetHook(true, reinterpret_cast<void**>(&pGetAttackSpeedDegree), GetAttackSpeedDegree);
SetHook(true, reinterpret_cast<void**>(&get_cool_time), get_cool_time_t);
SetHook(true, reinterpret_cast<void**>(&remove_bullet_skill_hook), remove_bullets);
SetHook(true, reinterpret_cast<void**>(&ztlSecureFuse_check), ztlfuse);
//SetHook(true, reinterpret_cast<void**>(&ztlSecureFuse_UI), ztlfuse_UI);
//SetHook(true, reinterpret_cast<void**>(&getFindHitMobInRect), FindHitMobInRect);
SetHook(true, reinterpret_cast<void**>(&hook_bstr_t), bstrt);
SetHook(true, reinterpret_cast<void**>(&getPAD_hook), getPAD);
SetHook(true, reinterpret_cast<void**>(&hook_message), messageStuff);
SetHook(true, reinterpret_cast<void**>(&CUserRemote__OnAttack), CUserOnAttackPacket);
SetHook(true, reinterpret_cast<void**>(&CUserRemote__OnPrepare), CUserPreparePacket);
SetHook(true, reinterpret_cast<void**>(&CUserRemote__OnPrepareCancel), CUserPrepareCancelPacket);
SetHook(true, reinterpret_cast<void**>(&mastery_Calcs_Hook), mCalc);
SetHook(true, reinterpret_cast<void**>(&chainLightning_Hook), drop_off_damage_skills);
SetHook(true, reinterpret_cast<void**>(&calcpdamage_hook), CalcDamage__PDamage);
//SetHook(true, reinterpret_cast<void**>(&setObjVisible_Hook), setObjVisible);
//hacky magnus ballshit
//PatchNop(0x00678539, 2);
//WriteByte(0x00678552, 0xEB);
//WriteByte(0x00678552 + 1, 0x48);
//PatchNop(0x00678552 + 2, 4);
// ui stuff
WriteByte(0x008C35C9 + 1, 0x2C); // weapon def
WriteByte(0x008C374A + 1, 0x1A); // weapon def
WriteByte(0x008C39E9 + 1, 0x62); // weapon def
WriteByte(0x008C3B9C + 1, 0x50); // weapon def
WriteByte(0x008C3D4F + 1, 0x3E); // weapon def
WriteByte(0x008C3F8E + 1, 0x74); // weapon def
PatchNop(0x00668C04, 5);
//CodeCave(DamCalc, madcalcjmpout, 1);
WriteByte(0x00620F2B + 1, 0x1F); // bypass checks for spam to login
InitExpOverride();
CodeCave(please, 0x00791C41, 4);
CodeCave((void*)critAllClasses, 0x0076514E, 0);
CodeCave((void*)NW_Multi, nwthrow, 0);
WriteByte(0x0078EDB1 + 1, 0x84);
CodeCave((void*)Claw_5, 0x0078EDB1, 1);
CodeCave((void*)dCrits, 0x007650AF, 5);
PatchNop(0x007650F9, 6);
WriteByte(0x0076511E, 0xEB);
RulaxEdits();
WriteByte(0x008ECB02, 0xEB);//draw weapons speed
GooseExpansion();
DarnellEdits();
Hook_DoActiveSkill(true);
Hook_Jump(true);
//DiscordRichPresence::hook();
SetHook(TRUE, reinterpret_cast<PVOID*>(&_is_attack_area_set_by_data), is_attack_area_set_by_data);
//Avenger + other ranged skills patch to evaluate inside TryDoingShootAttack
CodeCave(LtRb_Eval, 0x00953E2C, 6);
//Hook_CAvatar__PrepareActionLayer(true);
//Hook_CUser__SetActivePortableChair(true);
//Hook_CUser__Update(true);
init();
return TRUE;
} | 0 | 0.931333 | 1 | 0.931333 | game-dev | MEDIA | 0.354014 | game-dev | 0.970858 | 1 | 0.970858 |
decentraland/unity-renderer | 2,143 | unity-renderer/Assets/Scripts/MainScripts/DCL/AssetsEmbedment/Editor/EditorAssetBundlesDownloader.cs | using Cysharp.Threading.Tasks;
using DCL;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.Networking;
namespace MainScripts.DCL.AssetsEmbedment.Editor
{
public static class EditorAssetBundlesDownloader
{
public static async UniTask<bool> DownloadAssetBundleWithDependenciesAsync(string baseUrl, string hash, Dictionary<string, byte[]> loadedData)
{
if (loadedData.ContainsKey(hash))
return true;
var url = $"{baseUrl}{hash}";
try
{
// Passing no extra arguments will bypass caching and crc checks
var wr = await UnityWebRequest.Get(url).SendWebRequest();
if (wr.WebRequestSucceded())
{
var data = wr.downloadHandler.data;
var assetBundle = await AssetBundle.LoadFromMemoryAsync(data);
try
{
var dependencies = await assetBundle.GetDependenciesAsync(baseUrl, hash, CancellationToken.None);
var result = await UniTask.WhenAll(dependencies.Select(d => DownloadAssetBundleWithDependenciesAsync(baseUrl, d, loadedData)));
if (result.All(r => r))
{
loadedData.Add(hash, data);
return true;
}
}
finally
{
if (assetBundle)
{
assetBundle.Unload(true);
Object.DestroyImmediate(assetBundle);
}
}
return false;
}
Debug.LogError(wr.error);
}
catch (UnityWebRequestException)
{
Debug.LogError($"Failed to download AB: {hash}. Url: {url}");
// ignore for now
return true;
}
return false;
}
}
}
| 0 | 0.85733 | 1 | 0.85733 | game-dev | MEDIA | 0.802105 | game-dev | 0.975128 | 1 | 0.975128 |
mkernel/DXFLib | 1,908 | DXFLib/DXFEntity.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DXFLib
{
public class DXFEntity
{
public string EntityType { get; set; }
public string Handle { get; set; }
private List<string> classhierarchy = new List<string>();
public List<string> ClassHierarchy { get { return classhierarchy; } }
public bool IsInPaperSpace { get; set; }
public string LayerName { get; set; }
public string LineType { get; set; }
public int ColorNumber { get; set; }
public double LineTypeScale { get; set; }
public bool IsInvisible { get; set; }
public virtual bool HasChildren { get { return false; } }
private List<DXFEntity> children = new List<DXFEntity>();
public List<DXFEntity> Children { get { return children; } }
public virtual void ParseGroupCode(int groupcode, string value)
{
switch (groupcode)
{
case 0:
EntityType = value;
break;
case 5:
Handle = value;
break;
case 100:
ClassHierarchy.Add(value);
break;
case 67:
IsInPaperSpace = int.Parse(value) == 1;
break;
case 8:
LayerName = value;
break;
case 6:
LineType = value;
break;
case 62:
ColorNumber = int.Parse(value);
break;
case 48:
LineTypeScale = double.Parse(value);
break;
case 60:
IsInvisible = int.Parse(value) == 1;
break;
}
}
}
}
| 0 | 0.814252 | 1 | 0.814252 | game-dev | MEDIA | 0.342585 | game-dev | 0.946207 | 1 | 0.946207 |
HerculesWS/Hercules | 6,328 | src/map/duel.c | /**
* This file is part of Hercules.
* http://herc.ws - http://github.com/HerculesWS/Hercules
*
* Copyright (C) 2012-2025 Hercules Dev Team
* Copyright (C) Athena Dev Teams
*
* Hercules 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/>.
*/
#define HERCULES_CORE
#include "duel.h"
#include "map/atcommand.h" // msg_txt
#include "map/clif.h"
#include "map/pc.h"
#include "common/cbasetypes.h"
#include "common/msgtable.h"
#include "common/nullpo.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static struct duel_interface duel_s;
struct duel_interface *duel;
/*==========================================
* Duel organizing functions [LuzZza]
*------------------------------------------*/
static void duel_savetime(struct map_session_data *sd)
{
pc_setglobalreg(sd, script->add_variable("PC_LAST_DUEL_TIME"), (int)time(NULL));
}
static int64 duel_difftime(struct map_session_data *sd)
{
return (pc_readglobalreg(sd, script->add_variable("PC_LAST_DUEL_TIME")) + battle_config.duel_time_interval - (int)time(NULL));
}
static int duel_showinfo_sub(struct map_session_data *sd, va_list va)
{
struct map_session_data *ssd = va_arg(va, struct map_session_data*);
int *p = va_arg(va, int*);
char output[256];
nullpo_retr(1, sd);
nullpo_retr(1, ssd);
if (sd->duel_group != ssd->duel_group) return 0;
sprintf(output, " %d. %s", ++(*p), sd->status.name);
clif_disp_onlyself(ssd, output);
return 1;
}
static void duel_showinfo(const unsigned int did, struct map_session_data *sd)
{
int p=0;
char output[256];
if(duel->list[did].max_players_limit > 0)
sprintf(output, msg_sd(sd, MSGTBL_DUEL_INFO_LIMIT), //" -- Duels: %d/%d, Members: %d/%d, Max players: %d --"
did, duel->count,
duel->list[did].members_count,
duel->list[did].members_count + duel->list[did].invites_count,
duel->list[did].max_players_limit);
else
sprintf(output, msg_sd(sd, MSGTBL_DUEL_INFO_NO_LIMIT), //" -- Duels: %d/%d, Members: %d/%d --"
did, duel->count,
duel->list[did].members_count,
duel->list[did].members_count + duel->list[did].invites_count);
clif_disp_onlyself(sd, output);
map->foreachpc(duel_showinfo_sub, sd, &p);
}
static int duel_create(struct map_session_data *sd, const unsigned int maxpl)
{
int i=1;
char output[256];
nullpo_ret(sd);
while(i < MAX_DUEL && duel->list[i].members_count > 0) i++;
if(i == MAX_DUEL) return 0;
duel->count++;
sd->duel_group = i;
duel->list[i].members_count++;
duel->list[i].invites_count = 0;
duel->list[i].max_players_limit = maxpl;
safestrncpy(output, msg_sd(sd, MSGTBL_DUEL_CREATED), sizeof(output)); // " -- Duel has been created (@invite/@leave) --"
clif_disp_onlyself(sd, output);
clif->map_property(sd, MAPPROPERTY_FREEPVPZONE);
clif->maptypeproperty2(&sd->bl,SELF);
return i;
}
static void duel_invite(const unsigned int did, struct map_session_data *sd, struct map_session_data *target_sd)
{
char output[256];
nullpo_retv(sd);
nullpo_retv(target_sd);
// " -- Player %s invites %s to duel --"
sprintf(output, msg_sd(sd, MSGTBL_DUEL_INVITE_INFO), sd->status.name, target_sd->status.name);
clif->disp_message(&sd->bl, output, DUEL_WOS);
target_sd->duel_invite = did;
duel->list[did].invites_count++;
// "Blue -- Player %s invites you to PVP duel (@accept/@reject) --"
sprintf(output, msg_sd(target_sd, MSGTBL_DUEL_INVITE_MESSAGE), sd->status.name);
clif->broadcast(&target_sd->bl, output, (int)strlen(output)+1, BC_BLUE, SELF);
}
static int duel_leave_sub(struct map_session_data *sd, va_list va)
{
int did = va_arg(va, int);
nullpo_ret(sd);
if (sd->duel_invite == did)
sd->duel_invite = 0;
return 0;
}
static void duel_leave(const unsigned int did, struct map_session_data *sd)
{
char output[256];
nullpo_retv(sd);
// " <- Player %s has left duel --"
sprintf(output, msg_sd(sd, MSGTBL_DUEL_PLAYER_LEFT), sd->status.name);
clif->disp_message(&sd->bl, output, DUEL_WOS);
duel->list[did].members_count--;
if(duel->list[did].members_count == 0) {
map->foreachpc(duel_leave_sub, did);
duel->count--;
}
sd->duel_group = 0;
duel_savetime(sd);
clif->map_property(sd, MAPPROPERTY_NOTHING);
clif->maptypeproperty2(&sd->bl,SELF);
}
static void duel_accept(const unsigned int did, struct map_session_data *sd)
{
char output[256];
nullpo_retv(sd);
duel->list[did].members_count++;
sd->duel_group = sd->duel_invite;
duel->list[did].invites_count--;
sd->duel_invite = 0;
// " -> Player %s has accepted duel --"
sprintf(output, msg_sd(sd, MSGTBL_DUEL_PLAYER_ACCEPTED), sd->status.name);
clif->disp_message(&sd->bl, output, DUEL_WOS);
clif->map_property(sd, MAPPROPERTY_FREEPVPZONE);
clif->maptypeproperty2(&sd->bl,SELF);
}
static void duel_reject(const unsigned int did, struct map_session_data *sd)
{
char output[256];
nullpo_retv(sd);
// " -- Player %s has rejected duel --"
sprintf(output, msg_sd(sd, MSGTBL_DUEL_PLAYER_REJECTED), sd->status.name);
clif->disp_message(&sd->bl, output, DUEL_WOS);
duel->list[did].invites_count--;
sd->duel_invite = 0;
}
static void do_final_duel(void)
{
}
static void do_init_duel(bool minimal)
{
if (minimal)
return;
memset(&duel->list[0], 0, sizeof(duel->list));
}
/*=====================================
* Default Functions : duel.h
* Generated by HerculesInterfaceMaker
* created by Susu
*-------------------------------------*/
void duel_defaults(void)
{
duel = &duel_s;
/* vars */
duel->count = 0;
/* funcs */
//Duel functions // [LuzZza]
duel->create = duel_create;
duel->invite = duel_invite;
duel->accept = duel_accept;
duel->reject = duel_reject;
duel->leave = duel_leave;
duel->showinfo = duel_showinfo;
duel->difftime = duel_difftime;
duel->init = do_init_duel;
duel->final = do_final_duel;
}
| 0 | 0.813179 | 1 | 0.813179 | game-dev | MEDIA | 0.835313 | game-dev | 0.850225 | 1 | 0.850225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.